blob: 107b821f83338324a54d9751c15f25d7f8035183 [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:
Eric Andersen25f27032001-04-26 23:22:31 +000023 * b_addchr() derived from similar w_addchar function in glibc-2.2
24 * 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
Eric Andersen25f27032001-04-26 23:22:31 +000026 * miscellaneous bugfixes from Matt Kraai
27 *
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?)
40 * $@ (those sure look like weird quoting rules)
41 * $_
42 * ! negation operator for pipes
43 * &> and >& redirection of stdout+stderr
44 * Brace Expansion
45 * Tilde Expansion
46 * fancy forms of Parameter Expansion
Eric Andersen78a7c992001-05-15 16:30:25 +000047 * aliases
Eric Andersen25f27032001-04-26 23:22:31 +000048 * Arithmetic Expansion
49 * <(list) and >(list) Process Substitution
Eric Andersen83a2ae22001-05-07 17:59:25 +000050 * reserved words: case, esac, select, function
Eric Andersen25f27032001-04-26 23:22:31 +000051 * Here Documents ( << word )
52 * Functions
53 * Major bugs:
Denis Vlasenkob81b3df2007-04-28 16:48:04 +000054 * job handling woefully incomplete and buggy (improved --vda)
Eric Andersen25f27032001-04-26 23:22:31 +000055 * reserved word execution woefully incomplete and buggy
Eric Andersen25f27032001-04-26 23:22:31 +000056 * to-do:
Eric Andersen83a2ae22001-05-07 17:59:25 +000057 * port selected bugfixes from post-0.49 busybox lash - done?
58 * finish implementing reserved words: for, while, until, do, done
59 * change { and } from special chars to reserved words
60 * builtins: break, continue, eval, return, set, trap, ulimit
61 * test magic exec
Eric Andersen25f27032001-04-26 23:22:31 +000062 * handle children going into background
63 * clean up recognition of null pipes
Eric Andersen25f27032001-04-26 23:22:31 +000064 * check setting of global_argc and global_argv
65 * control-C handling, probably with longjmp
Eric Andersen25f27032001-04-26 23:22:31 +000066 * follow IFS rules more precisely, including update semantics
Eric Andersen25f27032001-04-26 23:22:31 +000067 * figure out what to do with backslash-newline
68 * explain why we use signal instead of sigaction
69 * propagate syntax errors, die on resource errors?
70 * continuation lines, both explicit and implicit - done?
71 * memory leak finding and plugging - done?
72 * more testing, especially quoting rules and redirection
Eric Andersen78a7c992001-05-15 16:30:25 +000073 * document how quoting rules not precisely followed for variable assignments
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +000074 * maybe change charmap[] to use 2-bit entries
Eric Andersen25f27032001-04-26 23:22:31 +000075 * (eventually) remove all the printf's
Eric Andersen25f27032001-04-26 23:22:31 +000076 *
Bernhard Reutner-Fischer86f5c992006-01-22 22:55:11 +000077 * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
Eric Andersen25f27032001-04-26 23:22:31 +000078 */
Bernhard Reutner-Fischere15d7572006-06-02 20:56:16 +000079
80#include "busybox.h"
Eric Andersen25f27032001-04-26 23:22:31 +000081#include <glob.h> /* glob, of course */
Eric Andersen25f27032001-04-26 23:22:31 +000082#include <getopt.h> /* should be pretty obvious */
Eric Andersen25f27032001-04-26 23:22:31 +000083/* #include <dmalloc.h> */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +000084extern char **environ; /* This is in <unistd.h>, but protected with __USE_GNU */
Denis Vlasenkod01ff132007-05-02 21:40:23 +000085
86
87/* If you comment out one of these below, it will be #defined later
88 * to perform debug printfs to stderr: */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +000089#define debug_printf(...) do {} while (0)
Denis Vlasenko400c5b62007-05-04 13:07:27 +000090/* Finer-grained debug switches */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +000091#define debug_printf_parse(...) do {} while (0)
92#define debug_print_tree(a, b) do {} while (0)
93#define debug_printf_exec(...) do {} while (0)
94#define debug_printf_jobs(...) do {} while (0)
95#define debug_printf_expand(...) do {} while (0)
96#define debug_printf_clean(...) do {} while (0)
Denis Vlasenkod01ff132007-05-02 21:40:23 +000097
98#ifndef debug_printf
99#define debug_printf(...) fprintf(stderr, __VA_ARGS__)
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000100#endif
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000101
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +0000102#ifndef debug_printf_parse
103#define debug_printf_parse(...) fprintf(stderr, __VA_ARGS__)
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000104#endif
105
106#ifndef debug_printf_exec
107#define debug_printf_exec(...) fprintf(stderr, __VA_ARGS__)
108#endif
109
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +0000110#ifndef debug_printf_jobs
111#define debug_printf_jobs(...) fprintf(stderr, __VA_ARGS__)
112#define DEBUG_SHELL_JOBS 1
113#endif
114
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000115#ifndef debug_printf_expand
116#define debug_printf_expand(...) fprintf(stderr, __VA_ARGS__)
117#define DEBUG_EXPAND 1
118#endif
119
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +0000120#ifndef debug_printf_clean
121/* broken, of course, but OK for testing */
122static const char *indenter(int i)
123{
124 static const char blanks[] = " ";
125 return &blanks[sizeof(blanks) - i - 1];
126}
127#define debug_printf_clean(...) fprintf(stderr, __VA_ARGS__)
Denis Vlasenkoc666f712007-05-16 22:18:54 +0000128#define DEBUG_CLEAN 1
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +0000129#endif
130
Eric Andersen25f27032001-04-26 23:22:31 +0000131
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000132#if !ENABLE_HUSH_INTERACTIVE
133#undef ENABLE_FEATURE_EDITING
134#define ENABLE_FEATURE_EDITING 0
135#undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
136#define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
137#endif
"Robert P. J. Day"f3501602006-07-01 12:19:39 +0000138
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +0000139#define SPECIAL_VAR_SYMBOL 3
140#define FLAG_EXIT_FROM_LOOP 1
Eric Andersen4c9b68f2002-04-13 12:33:41 +0000141#define FLAG_PARSE_SEMICOLON (1 << 1) /* symbol ';' is special for parser */
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +0000142#define FLAG_REPARSING (1 << 2) /* >= 2nd pass */
Eric Andersen25f27032001-04-26 23:22:31 +0000143
144typedef enum {
145 REDIRECT_INPUT = 1,
146 REDIRECT_OVERWRITE = 2,
147 REDIRECT_APPEND = 3,
148 REDIRECT_HEREIS = 4,
149 REDIRECT_IO = 5
150} redir_type;
151
152/* The descrip member of this structure is only used to make debugging
153 * output pretty */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +0000154static const struct {
155 int mode;
Denis Vlasenkoef36ead2007-05-02 15:34:47 +0000156 signed char default_fd;
157 char descrip[3];
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +0000158} redir_table[] = {
Eric Andersen25f27032001-04-26 23:22:31 +0000159 { 0, 0, "()" },
160 { O_RDONLY, 0, "<" },
161 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
162 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
163 { O_RDONLY, -1, "<<" },
164 { O_RDWR, 1, "<>" }
165};
166
167typedef enum {
168 PIPE_SEQ = 1,
169 PIPE_AND = 2,
170 PIPE_OR = 3,
171 PIPE_BG = 4,
172} pipe_style;
173
174/* might eventually control execution */
175typedef enum {
176 RES_NONE = 0,
177 RES_IF = 1,
178 RES_THEN = 2,
179 RES_ELIF = 3,
180 RES_ELSE = 4,
181 RES_FI = 5,
182 RES_FOR = 6,
183 RES_WHILE = 7,
184 RES_UNTIL = 8,
185 RES_DO = 9,
186 RES_DONE = 10,
Eric Andersenaf44a0e2001-04-27 07:26:12 +0000187 RES_XXXX = 11,
Eric Andersen4c9b68f2002-04-13 12:33:41 +0000188 RES_IN = 12,
189 RES_SNTX = 13
Eric Andersen25f27032001-04-26 23:22:31 +0000190} reserved_style;
Denis Vlasenko5f786c22007-04-20 08:35:45 +0000191enum {
192 FLAG_END = (1 << RES_NONE ),
193 FLAG_IF = (1 << RES_IF ),
194 FLAG_THEN = (1 << RES_THEN ),
195 FLAG_ELIF = (1 << RES_ELIF ),
196 FLAG_ELSE = (1 << RES_ELSE ),
197 FLAG_FI = (1 << RES_FI ),
198 FLAG_FOR = (1 << RES_FOR ),
199 FLAG_WHILE = (1 << RES_WHILE),
200 FLAG_UNTIL = (1 << RES_UNTIL),
201 FLAG_DO = (1 << RES_DO ),
202 FLAG_DONE = (1 << RES_DONE ),
203 FLAG_IN = (1 << RES_IN ),
204 FLAG_START = (1 << RES_XXXX ),
205};
Eric Andersen25f27032001-04-26 23:22:31 +0000206
207/* This holds pointers to the various results of parsing */
208struct p_context {
209 struct child_prog *child;
210 struct pipe *list_head;
211 struct pipe *pipe;
212 struct redir_struct *pending_redirect;
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +0000213 reserved_style res_w;
214 int old_flag; /* for figuring out valid reserved words */
Eric Andersen25f27032001-04-26 23:22:31 +0000215 struct p_context *stack;
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +0000216 int parse_type; /* define type of parser : ";$" common or special symbol */
Eric Andersen25f27032001-04-26 23:22:31 +0000217 /* How about quoting status? */
218};
219
220struct redir_struct {
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000221 struct redir_struct *next; /* pointer to the next redirect in the list */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000222 redir_type type; /* type of redirection */
223 int fd; /* file descriptor being redirected */
224 int dup; /* -1, or file descriptor being duplicated */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000225 glob_t word; /* *word.gl_pathv is the filename */
Eric Andersen25f27032001-04-26 23:22:31 +0000226};
227
228struct child_prog {
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000229 pid_t pid; /* 0 if exited */
230 char **argv; /* program name and arguments */
231 struct pipe *group; /* if non-NULL, first in group or subshell */
Denis Vlasenko262d7652007-05-20 21:52:49 +0000232 smallint subshell; /* flag, non-zero if group must be forked */
233 smallint is_stopped; /* is the program currently running? */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000234 struct redir_struct *redirects; /* I/O redirections */
235 glob_t glob_result; /* result of parameter globbing */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000236 struct pipe *family; /* pointer back to the child's parent pipe */
Denis Vlasenkoc666f712007-05-16 22:18:54 +0000237 //sp counting seems to be broken... so commented out, grep for '//sp:'
238 //sp: int sp; /* number of SPECIAL_VAR_SYMBOL */
Denis Vlasenko262d7652007-05-20 21:52:49 +0000239 //seems to be unused, grep for '//pt:'
240 //pt: int parse_type;
Eric Andersen25f27032001-04-26 23:22:31 +0000241};
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000242/* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
243 * and on execution these are substituted with their values.
244 * Substitution can make _several_ words out of one argv[n]!
245 * Example: argv[0]=='.^C*^C.' here: echo .$*.
246 */
Eric Andersen25f27032001-04-26 23:22:31 +0000247
248struct pipe {
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000249 struct pipe *next;
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000250 int num_progs; /* total number of programs in job */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000251 int running_progs; /* number of programs running (not exited) */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000252 char *cmdbuf; /* buffer various argv's point into */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000253#if ENABLE_HUSH_JOB
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000254 int jobid; /* job number */
255 char *cmdtext; /* name of job */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000256 pid_t pgrp; /* process group ID for the job */
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000257#endif
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000258 struct child_prog *progs; /* array of commands in pipe */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000259 int stopped_progs; /* number of programs alive, but stopped */
260 int job_context; /* bitmask defining current context */
261 pipe_style followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
262 reserved_style r_mode; /* supports if, for, while, until */
Eric Andersen25f27032001-04-26 23:22:31 +0000263};
264
Eric Andersen25f27032001-04-26 23:22:31 +0000265struct close_me {
Eric Andersen25f27032001-04-26 23:22:31 +0000266 struct close_me *next;
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000267 int fd;
Eric Andersen25f27032001-04-26 23:22:31 +0000268};
269
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000270struct variables {
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000271 struct variables *next;
Denis Vlasenko15d78fb2007-01-30 22:28:21 +0000272 const char *name;
273 const char *value;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000274 int flg_export;
275 int flg_read_only;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000276};
277
Eric Andersen25f27032001-04-26 23:22:31 +0000278typedef struct {
279 char *data;
280 int length;
281 int maxlen;
282 int quote;
283 int nonnull;
284} o_string;
285#define NULL_O_STRING {NULL,0,0,0,0}
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000286/* used for initialization: o_string foo = NULL_O_STRING; */
Eric Andersen25f27032001-04-26 23:22:31 +0000287
288/* I can almost use ordinary FILE *. Is open_memstream() universally
289 * available? Where is it documented? */
290struct in_str {
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +0000291 const char *p;
292 /* eof_flag=1: last char in ->p is really an EOF */
293 char eof_flag; /* meaningless if ->p == NULL */
294 char peek_buf[2];
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000295#if ENABLE_HUSH_INTERACTIVE
Eric Andersen25f27032001-04-26 23:22:31 +0000296 int __promptme;
297 int promptmode;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000298#endif
Eric Andersen25f27032001-04-26 23:22:31 +0000299 FILE *file;
300 int (*get) (struct in_str *);
301 int (*peek) (struct in_str *);
302};
303#define b_getch(input) ((input)->get(input))
304#define b_peek(input) ((input)->peek(input))
305
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000306enum {
307 CHAR_ORDINARY = 0,
308 CHAR_ORDINARY_IF_QUOTED = 1, /* example: *, # */
309 CHAR_IFS = 2, /* treated as ordinary if quoted */
310 CHAR_SPECIAL = 3, /* example: $ */
Eric Andersen25f27032001-04-26 23:22:31 +0000311};
312
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000313
314/* "Globals" within this file */
315
316#define HUSH_VER_STR "0.02"
317static const struct variables const_shell_ver = {
318 NULL, "HUSH_VERSION", HUSH_VER_STR, 1, 1
319};
320
321/* Sorted roughly by size (smaller offsets == smaller code) */
322struct globals {
323#if ENABLE_HUSH_INTERACTIVE
324 /* 'interactive_fd' is a fd# open to ctty, if we have one
325 * _AND_ if we decided to act interactively */
326 int interactive_fd;
327 const char *PS1;
328 const char *PS2;
329#endif
330#if ENABLE_FEATURE_EDITING
331 line_input_t *line_input_state;
332#endif
333#if ENABLE_HUSH_JOB
334 int run_list_level;
335 pid_t saved_task_pgrp;
336 pid_t saved_tty_pgrp;
337 int last_jobid;
338 struct pipe *job_list;
339 struct pipe *toplevel_list;
340 smallint ctrl_z_flag;
341#endif
342 smallint fake_mode;
343 /* these three support $?, $#, and $1 */
344 char **global_argv;
345 int global_argc;
346 int last_return_code;
347 const char *ifs;
348 struct close_me *close_me_head;
349 const char *cwd;
350 unsigned last_bg_pid;
351 struct variables *top_vars; /* = &shell_ver (both are set in main()) */
352 struct variables shell_ver; /* = const_shell_ver */
353#if ENABLE_FEATURE_SH_STANDALONE
354 struct nofork_save_area nofork_save;
355#endif
356#if ENABLE_HUSH_JOB
357 sigjmp_buf toplevel_jb;
358#endif
359 unsigned char charmap[256];
360 char user_input_buf[ENABLE_FEATURE_EDITING ? BUFSIZ : 2];
361};
362
363#define G (*ptr_to_globals)
364
365#if !ENABLE_HUSH_INTERACTIVE
366enum { interactive_fd = 0 };
367#endif
368#if !ENABLE_HUSH_JOB
369enum { run_list_level = 0 };
370#endif
371
372#if ENABLE_HUSH_INTERACTIVE
373#define interactive_fd (G.interactive_fd )
374#define PS1 (G.PS1 )
375#define PS2 (G.PS2 )
376#endif
377#if ENABLE_FEATURE_EDITING
378#define line_input_state (G.line_input_state)
379#endif
380#if ENABLE_HUSH_JOB
381#define run_list_level (G.run_list_level )
382#define saved_task_pgrp (G.saved_task_pgrp )
383#define saved_tty_pgrp (G.saved_tty_pgrp )
384#define last_jobid (G.last_jobid )
385#define job_list (G.job_list )
386#define toplevel_list (G.toplevel_list )
387#define toplevel_jb (G.toplevel_jb )
388#define ctrl_z_flag (G.ctrl_z_flag )
389#endif /* JOB */
390#define global_argv (G.global_argv )
391#define global_argc (G.global_argc )
392#define last_return_code (G.last_return_code)
393#define ifs (G.ifs )
394#define fake_mode (G.fake_mode )
395#define close_me_head (G.close_me_head )
396#define cwd (G.cwd )
397#define last_bg_pid (G.last_bg_pid )
398#define top_vars (G.top_vars )
399#define shell_ver (G.shell_ver )
400#if ENABLE_FEATURE_SH_STANDALONE
401#define nofork_save (G.nofork_save )
402#endif
403#if ENABLE_HUSH_JOB
404#define toplevel_jb (G.toplevel_jb )
405#endif
406#define charmap (G.charmap )
407#define user_input_buf (G.user_input_buf )
408
409
410#define B_CHUNK 100
411#define B_NOSPAC 1
412#define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
413
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000414static void __syntax(int line)
Denis Vlasenkob6aae0f2007-01-29 22:51:25 +0000415{
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000416 bb_error_msg("syntax error hush.c:%d", line);
Eric Andersen25f27032001-04-26 23:22:31 +0000417}
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000418#define syntax() __syntax(__LINE__)
Eric Andersen25f27032001-04-26 23:22:31 +0000419
420/* Index of subroutines: */
421/* function prototypes for builtins */
Denis Vlasenko1359da62007-04-21 23:27:30 +0000422static int builtin_cd(char **argv);
Denis Vlasenko1359da62007-04-21 23:27:30 +0000423static int builtin_eval(char **argv);
424static int builtin_exec(char **argv);
425static int builtin_exit(char **argv);
426static int builtin_export(char **argv);
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000427#if ENABLE_HUSH_JOB
Denis Vlasenko1359da62007-04-21 23:27:30 +0000428static int builtin_fg_bg(char **argv);
Denis Vlasenko1359da62007-04-21 23:27:30 +0000429static int builtin_jobs(char **argv);
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000430#endif
431static int builtin_help(char **argv);
Denis Vlasenko1359da62007-04-21 23:27:30 +0000432static int builtin_pwd(char **argv);
433static int builtin_read(char **argv);
434static int builtin_set(char **argv);
435static int builtin_shift(char **argv);
436static int builtin_source(char **argv);
437static int builtin_umask(char **argv);
438static int builtin_unset(char **argv);
439static int builtin_not_written(char **argv);
Eric Andersen25f27032001-04-26 23:22:31 +0000440/* o_string manipulation: */
441static int b_check_space(o_string *o, int len);
442static int b_addchr(o_string *o, int ch);
443static void b_reset(o_string *o);
444static int b_addqchr(o_string *o, int ch, int quote);
Eric Andersen25f27032001-04-26 23:22:31 +0000445/* in_str manipulations: */
446static int static_get(struct in_str *i);
447static int static_peek(struct in_str *i);
448static int file_get(struct in_str *i);
449static int file_peek(struct in_str *i);
450static void setup_file_in_str(struct in_str *i, FILE *f);
451static void setup_string_in_str(struct in_str *i, const char *s);
452/* close_me manipulations: */
453static void mark_open(int fd);
454static void mark_closed(int fd);
Eric Anderseneaecbf32001-10-31 10:41:31 +0000455static void close_all(void);
Eric Andersen25f27032001-04-26 23:22:31 +0000456/* "run" the final data structures: */
Denis Vlasenkoc666f712007-05-16 22:18:54 +0000457#if !defined(DEBUG_CLEAN)
458#define free_pipe_list(head, indent) free_pipe_list(head)
459#define free_pipe(pi, indent) free_pipe(pi)
460#endif
Eric Andersenbf7df042001-05-23 22:18:35 +0000461static int free_pipe_list(struct pipe *head, int indent);
462static int free_pipe(struct pipe *pi, int indent);
Eric Andersen25f27032001-04-26 23:22:31 +0000463/* really run the final data structures: */
464static int setup_redirects(struct child_prog *prog, int squirrel[]);
Eric Andersen25f27032001-04-26 23:22:31 +0000465static int run_list_real(struct pipe *pi);
Denis Vlasenko1359da62007-04-21 23:27:30 +0000466static void pseudo_exec_argv(char **argv) ATTRIBUTE_NORETURN;
Bernhard Reutner-Fischer86f5c992006-01-22 22:55:11 +0000467static void pseudo_exec(struct child_prog *child) ATTRIBUTE_NORETURN;
Eric Andersen25f27032001-04-26 23:22:31 +0000468static int run_pipe_real(struct pipe *pi);
469/* extended glob support: */
470static int globhack(const char *src, int flags, glob_t *pglob);
471static int glob_needed(const char *s);
472static int xglob(o_string *dest, int flags, glob_t *pglob);
Eric Andersen78a7c992001-05-15 16:30:25 +0000473/* variable assignment: */
Eric Andersen78a7c992001-05-15 16:30:25 +0000474static int is_assignment(const char *s);
Eric Andersen25f27032001-04-26 23:22:31 +0000475/* data structure manipulation: */
476static int setup_redirect(struct p_context *ctx, int fd, redir_type style, struct in_str *input);
477static void initialize_context(struct p_context *ctx);
478static int done_word(o_string *dest, struct p_context *ctx);
479static int done_command(struct p_context *ctx);
480static int done_pipe(struct p_context *ctx, pipe_style type);
481/* primary string parsing: */
482static int redirect_dup_num(struct in_str *input);
483static int redirect_opt_num(o_string *o);
Denis Vlasenko14b5dd92007-05-20 21:51:38 +0000484#if ENABLE_HUSH_TICK
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +0000485static int process_command_subs(o_string *dest, struct p_context *ctx, struct in_str *input, const char *subst_end);
Denis Vlasenko14b5dd92007-05-20 21:51:38 +0000486#endif
Eric Andersen25f27032001-04-26 23:22:31 +0000487static int parse_group(o_string *dest, struct p_context *ctx, struct in_str *input, int ch);
Denis Vlasenko15d78fb2007-01-30 22:28:21 +0000488static const char *lookup_param(const char *src);
Eric Andersen4c9b68f2002-04-13 12:33:41 +0000489static char *make_string(char **inp);
Eric Andersen25f27032001-04-26 23:22:31 +0000490static int handle_dollar(o_string *dest, struct p_context *ctx, struct in_str *input);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +0000491static 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 +0000492/* setup: */
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +0000493static int parse_stream_outer(struct in_str *inp, int parse_flag);
494static int parse_string_outer(const char *s, int parse_flag);
Eric Andersen25f27032001-04-26 23:22:31 +0000495static int parse_file_outer(FILE *f);
Eric Andersenbafd94f2001-05-02 16:11:59 +0000496/* job management: */
Eric Andersenc798b072001-06-22 06:23:03 +0000497static int checkjobs(struct pipe* fg_pipe);
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000498#if ENABLE_HUSH_JOB
Denis Vlasenko52881e92007-04-21 13:42:52 +0000499static int checkjobs_and_fg_shell(struct pipe* fg_pipe);
Eric Andersenbafd94f2001-05-02 16:11:59 +0000500static void insert_bg_job(struct pipe *pi);
501static void remove_bg_job(struct pipe *pi);
Denis Vlasenko1359da62007-04-21 23:27:30 +0000502static void delete_finished_bg_job(struct pipe *pi);
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000503#else
504int checkjobs_and_fg_shell(struct pipe* fg_pipe); /* never called */
505#endif
Eric Andersenf72f5622001-05-15 23:21:41 +0000506/* local variable support */
Denis Vlasenkob6a741f2007-05-17 14:38:17 +0000507static char **expand_variables_to_list(char **argv);
508/* used for expansion of right hand of assignments */
509static char *expand_variables_to_string(const char *str);
Denis Vlasenko15d78fb2007-01-30 22:28:21 +0000510static const char *get_local_var(const char *var);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000511static int set_local_var(const char *s, int flg_export);
Denis Vlasenko87cb2db2007-04-21 10:00:01 +0000512static void unset_local_var(const char *name);
Eric Andersen25f27032001-04-26 23:22:31 +0000513
514/* Table of built-in functions. They can be forked or not, depending on
515 * context: within pipes, they fork. As simple commands, they do not.
516 * When used in non-forking context, they can change global variables
Denis Vlasenkoe1a0d482006-10-20 13:28:22 +0000517 * in the parent shell process. If forked, of course they cannot.
Eric Andersen25f27032001-04-26 23:22:31 +0000518 * For example, 'unset foo | whatever' will parse and run, but foo will
519 * still be set at the end. */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000520struct built_in_command {
521 const char *cmd; /* name */
522 const char *descr; /* description */
523 int (*function) (char **argv); /* function ptr */
524};
525
"Vladimir N. Oleynik"485d7cb2005-10-17 09:48:57 +0000526static const struct built_in_command bltins[] = {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000527#if ENABLE_HUSH_JOB
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000528 { "bg", "Resume a job in the background", builtin_fg_bg },
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000529#endif
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000530 { "break", "Exit for, while or until loop", builtin_not_written },
531 { "cd", "Change working directory", builtin_cd },
532 { "continue", "Continue for, while or until loop", builtin_not_written },
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000533 { "eval", "Construct and run shell command", builtin_eval },
534 { "exec", "Exec command, replacing this shell with the exec'd process",
535 builtin_exec },
536 { "exit", "Exit from shell()", builtin_exit },
537 { "export", "Set environment variable", builtin_export },
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000538#if ENABLE_HUSH_JOB
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000539 { "fg", "Bring job into the foreground", builtin_fg_bg },
540 { "jobs", "Lists the active jobs", builtin_jobs },
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000541#endif
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000542 { "pwd", "Print current directory", builtin_pwd },
543 { "read", "Input environment variable", builtin_read },
544 { "return", "Return from a function", builtin_not_written },
545 { "set", "Set/unset shell local variables", builtin_set },
546 { "shift", "Shift positional parameters", builtin_shift },
547 { "trap", "Trap signals", builtin_not_written },
548 { "ulimit","Controls resource limits", builtin_not_written },
549 { "umask","Sets file creation mask", builtin_umask },
550 { "unset", "Unset environment variable", builtin_unset },
551 { ".", "Source-in and run commands in a file", builtin_source },
552 { "help", "List shell built-in commands", builtin_help },
553 { NULL, NULL, NULL }
Eric Andersen25f27032001-04-26 23:22:31 +0000554};
555
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000556#if ENABLE_HUSH_JOB
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000557
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000558/* move to libbb? */
559static void signal_SA_RESTART(int sig, void (*handler)(int))
560{
561 struct sigaction sa;
562 sa.sa_handler = handler;
563 sa.sa_flags = SA_RESTART;
564 sigemptyset(&sa.sa_mask);
565 sigaction(sig, &sa, NULL);
566}
567
Denis Vlasenko3ac0e002007-04-28 16:45:22 +0000568/* Signals are grouped, we handle them in batches */
569static void set_fatal_sighandler(void (*handler)(int))
570{
571 signal(SIGILL , handler);
572 signal(SIGTRAP, handler);
573 signal(SIGABRT, handler);
574 signal(SIGFPE , handler);
575 signal(SIGBUS , handler);
576 signal(SIGSEGV, handler);
577 /* bash 3.2 seems to handle these just like 'fatal' ones */
578 signal(SIGHUP , handler);
579 signal(SIGPIPE, handler);
580 signal(SIGALRM, handler);
581}
582static void set_jobctrl_sighandler(void (*handler)(int))
583{
584 signal(SIGTSTP, handler);
585 signal(SIGTTIN, handler);
586 signal(SIGTTOU, handler);
587}
588static void set_misc_sighandler(void (*handler)(int))
589{
590 signal(SIGINT , handler);
591 signal(SIGQUIT, handler);
592 signal(SIGTERM, handler);
593}
594/* SIGCHLD is special and handled separately */
595
596static void set_every_sighandler(void (*handler)(int))
597{
598 set_fatal_sighandler(handler);
599 set_jobctrl_sighandler(handler);
600 set_misc_sighandler(handler);
601 signal(SIGCHLD, handler);
602}
603
Denis Vlasenkob5eaabb2007-04-28 16:45:59 +0000604static void handler_ctrl_c(int sig)
605{
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000606 debug_printf_jobs("got sig %d\n", sig);
Denis Vlasenkob5eaabb2007-04-28 16:45:59 +0000607// as usual we can have all kinds of nasty problems with leaked malloc data here
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +0000608 siglongjmp(toplevel_jb, 1);
Denis Vlasenkob5eaabb2007-04-28 16:45:59 +0000609}
610
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000611static void handler_ctrl_z(int sig)
612{
613 pid_t pid;
614
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +0000615 debug_printf_jobs("got tty sig %d in pid %d\n", sig, getpid());
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000616 pid = fork();
Denis Vlasenkoc2990322007-05-16 12:57:12 +0000617 if (pid < 0) /* can't fork. Pretend there was no ctrl-Z */
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000618 return;
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +0000619 ctrl_z_flag = 1;
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000620 if (!pid) { /* child */
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000621 setpgrp();
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +0000622 debug_printf_jobs("set pgrp for child %d ok\n", getpid());
Denis Vlasenko3ac0e002007-04-28 16:45:22 +0000623 set_every_sighandler(SIG_DFL);
Denis Vlasenko18e19f22007-04-28 16:43:18 +0000624 raise(SIGTSTP); /* resend TSTP so that child will be stopped */
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +0000625 debug_printf_jobs("returning in child\n");
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000626 /* return to nofork, it will eventually exit now,
627 * not return back to shell */
628 return;
629 }
630 /* parent */
631 /* finish filling up pipe info */
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +0000632 toplevel_list->pgrp = pid; /* child is in its own pgrp */
633 toplevel_list->progs[0].pid = pid;
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000634 /* parent needs to longjmp out of running nofork.
635 * we will "return" exitcode 0, with child put in background */
636// as usual we can have all kinds of nasty problems with leaked malloc data here
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +0000637 debug_printf_jobs("siglongjmp in parent\n");
638 siglongjmp(toplevel_jb, 1);
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000639}
640
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000641/* Restores tty foreground process group, and exits.
642 * May be called as signal handler for fatal signal
643 * (will faithfully resend signal to itself, producing correct exit state)
644 * or called directly with -EXITCODE.
645 * We also call it if xfunc is exiting. */
646static void sigexit(int sig) ATTRIBUTE_NORETURN;
647static void sigexit(int sig)
648{
649 sigset_t block_all;
650
651 /* Disable all signals: job control, SIGPIPE, etc. */
652 sigfillset(&block_all);
653 sigprocmask(SIG_SETMASK, &block_all, NULL);
654
Denis Vlasenko87cb2db2007-04-21 10:00:01 +0000655 if (interactive_fd)
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000656 tcsetpgrp(interactive_fd, saved_tty_pgrp);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000657
658 /* Not a signal, just exit */
659 if (sig <= 0)
660 _exit(- sig);
661
662 /* Enable only this sig and kill ourself with it */
663 signal(sig, SIG_DFL);
664 sigdelset(&block_all, sig);
665 sigprocmask(SIG_SETMASK, &block_all, NULL);
666 raise(sig);
667 _exit(1); /* Should not reach it */
668}
669
670/* Restores tty foreground process group, and exits. */
671static void hush_exit(int exitcode) ATTRIBUTE_NORETURN;
672static void hush_exit(int exitcode)
673{
674 fflush(NULL); /* flush all streams */
675 sigexit(- (exitcode & 0xff));
676}
677
Denis Vlasenkoef36ead2007-05-02 15:34:47 +0000678#else /* !JOB */
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000679
680#define set_fatal_sighandler(handler) ((void)0)
681#define set_jobctrl_sighandler(handler) ((void)0)
682#define set_misc_sighandler(handler) ((void)0)
Denis Vlasenkoef36ead2007-05-02 15:34:47 +0000683#define hush_exit(e) exit(e)
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000684
Denis Vlasenkoef36ead2007-05-02 15:34:47 +0000685#endif /* JOB */
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000686
687
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000688static const char *set_cwd(void)
689{
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000690 if (cwd == bb_msg_unknown)
Denis Vlasenko7cced6e2007-04-12 17:08:53 +0000691 cwd = NULL; /* xrealloc_getcwd_or_warn(arg) calls free(arg)! */
Denis Vlasenko6ca04442007-02-11 16:19:28 +0000692 cwd = xrealloc_getcwd_or_warn((char *)cwd);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000693 if (!cwd)
Manuel Novoa III cad53642003-03-19 09:13:01 +0000694 cwd = bb_msg_unknown;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000695 return cwd;
696}
697
Eric Andersen4c9b68f2002-04-13 12:33:41 +0000698/* built-in 'eval' handler */
Denis Vlasenko1359da62007-04-21 23:27:30 +0000699static int builtin_eval(char **argv)
Eric Andersen4c9b68f2002-04-13 12:33:41 +0000700{
701 char *str = NULL;
702 int rcode = EXIT_SUCCESS;
Eric Andersenc7bda1c2004-03-15 08:29:22 +0000703
Denis Vlasenko1359da62007-04-21 23:27:30 +0000704 if (argv[1]) {
705 str = make_string(argv + 1);
Eric Andersenc7bda1c2004-03-15 08:29:22 +0000706 parse_string_outer(str, FLAG_EXIT_FROM_LOOP |
Eric Andersen4c9b68f2002-04-13 12:33:41 +0000707 FLAG_PARSE_SEMICOLON);
708 free(str);
709 rcode = last_return_code;
710 }
711 return rcode;
712}
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000713
Eric Andersen25f27032001-04-26 23:22:31 +0000714/* built-in 'cd <path>' handler */
Denis Vlasenko1359da62007-04-21 23:27:30 +0000715static int builtin_cd(char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +0000716{
717 char *newdir;
Denis Vlasenko1359da62007-04-21 23:27:30 +0000718 if (argv[1] == NULL)
Eric Andersen25f27032001-04-26 23:22:31 +0000719 newdir = getenv("HOME");
720 else
Denis Vlasenko1359da62007-04-21 23:27:30 +0000721 newdir = argv[1];
Eric Andersen25f27032001-04-26 23:22:31 +0000722 if (chdir(newdir)) {
723 printf("cd: %s: %s\n", newdir, strerror(errno));
724 return EXIT_FAILURE;
725 }
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000726 set_cwd();
Eric Andersen25f27032001-04-26 23:22:31 +0000727 return EXIT_SUCCESS;
728}
729
Eric Andersen25f27032001-04-26 23:22:31 +0000730/* built-in 'exec' handler */
Denis Vlasenko1359da62007-04-21 23:27:30 +0000731static int builtin_exec(char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +0000732{
Denis Vlasenko1359da62007-04-21 23:27:30 +0000733 if (argv[1] == NULL)
Eric Andersen25f27032001-04-26 23:22:31 +0000734 return EXIT_SUCCESS; /* Really? */
Denis Vlasenko1359da62007-04-21 23:27:30 +0000735 pseudo_exec_argv(argv + 1);
Eric Andersen25f27032001-04-26 23:22:31 +0000736 /* never returns */
737}
738
739/* built-in 'exit' handler */
Denis Vlasenko1359da62007-04-21 23:27:30 +0000740static int builtin_exit(char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +0000741{
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000742// TODO: bash does it ONLY on top-level sh exit (+interacive only?)
743 //puts("exit"); /* bash does it */
Denis Vlasenkof2fffd02007-05-02 23:39:04 +0000744// TODO: warn if we have background jobs: "There are stopped jobs"
745// On second consecutive 'exit', exit anyway.
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000746
Denis Vlasenko1359da62007-04-21 23:27:30 +0000747 if (argv[1] == NULL)
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000748 hush_exit(last_return_code);
Denis Vlasenko5f786c22007-04-20 08:35:45 +0000749 /* mimic bash: exit 123abc == exit 255 + error msg */
750 xfunc_error_retval = 255;
751 /* bash: exit -2 == exit 254, no error msg */
Denis Vlasenkof2fffd02007-05-02 23:39:04 +0000752 hush_exit(xatoi(argv[1]) & 0xff);
Eric Andersen25f27032001-04-26 23:22:31 +0000753}
754
755/* built-in 'export VAR=value' handler */
Denis Vlasenko1359da62007-04-21 23:27:30 +0000756static int builtin_export(char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +0000757{
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000758 int res = 0;
Denis Vlasenko1359da62007-04-21 23:27:30 +0000759 char *name = argv[1];
Eric Andersen25f27032001-04-26 23:22:31 +0000760
Eric Andersenf72f5622001-05-15 23:21:41 +0000761 if (name == NULL) {
Denis Vlasenkof2fffd02007-05-02 23:39:04 +0000762 // TODO:
763 // ash emits: export VAR='VAL'
764 // bash: declare -x VAR="VAL"
765 // (both also escape as needed (quotes, $, etc))
766 char **e = environ;
767 if (e)
768 while (*e)
769 puts(*e++);
770 return EXIT_SUCCESS;
Eric Andersen25f27032001-04-26 23:22:31 +0000771 }
Eric Andersenf72f5622001-05-15 23:21:41 +0000772
Denis Vlasenkoc666f712007-05-16 22:18:54 +0000773 name = xstrdup(name);
774 {
Denis Vlasenko15d78fb2007-01-30 22:28:21 +0000775 const char *value = strchr(name, '=');
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000776
Eric Andersen94ac2442001-05-22 19:05:18 +0000777 if (!value) {
778 char *tmp;
779 /* They are exporting something without an =VALUE */
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000780
Eric Andersen94ac2442001-05-22 19:05:18 +0000781 value = get_local_var(name);
782 if (value) {
783 size_t ln = strlen(name);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000784
Denis Vlasenkoc666f712007-05-16 22:18:54 +0000785 tmp = xrealloc(name, ln+strlen(value)+2);
786 sprintf(tmp+ln, "=%s", value);
787 name = tmp;
Eric Andersen94ac2442001-05-22 19:05:18 +0000788 } else {
789 /* bash does not return an error when trying to export
790 * an undefined variable. Do likewise. */
791 res = 1;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000792 }
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000793 }
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000794 }
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000795 if (res < 0)
Manuel Novoa III cad53642003-03-19 09:13:01 +0000796 bb_perror_msg("export");
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000797 else if (res == 0)
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000798 res = set_local_var(name, 1);
799 else
800 res = 0;
801 free(name);
802 return res;
Eric Andersen25f27032001-04-26 23:22:31 +0000803}
804
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000805#if ENABLE_HUSH_JOB
Eric Andersen25f27032001-04-26 23:22:31 +0000806/* built-in 'fg' and 'bg' handler */
Denis Vlasenko1359da62007-04-21 23:27:30 +0000807static int builtin_fg_bg(char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +0000808{
Eric Andersen0fcd4472001-05-02 20:12:03 +0000809 int i, jobnum;
Denis Vlasenko8a28e622007-04-14 11:16:29 +0000810 struct pipe *pi;
Eric Andersen25f27032001-04-26 23:22:31 +0000811
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000812 if (!interactive_fd)
Eric Andersenc798b072001-06-22 06:23:03 +0000813 return EXIT_FAILURE;
Eric Andersen0fcd4472001-05-02 20:12:03 +0000814 /* If they gave us no args, assume they want the last backgrounded task */
Denis Vlasenko1359da62007-04-21 23:27:30 +0000815 if (!argv[1]) {
Eric Andersenc798b072001-06-22 06:23:03 +0000816 for (pi = job_list; pi; pi = pi->next) {
817 if (pi->jobid == last_jobid) {
Denis Vlasenko8a28e622007-04-14 11:16:29 +0000818 goto found;
Eric Andersen0fcd4472001-05-02 20:12:03 +0000819 }
820 }
Denis Vlasenko1359da62007-04-21 23:27:30 +0000821 bb_error_msg("%s: no current job", argv[0]);
Denis Vlasenko8a28e622007-04-14 11:16:29 +0000822 return EXIT_FAILURE;
823 }
Denis Vlasenko1359da62007-04-21 23:27:30 +0000824 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
825 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
Denis Vlasenko8a28e622007-04-14 11:16:29 +0000826 return EXIT_FAILURE;
827 }
828 for (pi = job_list; pi; pi = pi->next) {
829 if (pi->jobid == jobnum) {
830 goto found;
Eric Andersen25f27032001-04-26 23:22:31 +0000831 }
832 }
Denis Vlasenko1359da62007-04-21 23:27:30 +0000833 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
Denis Vlasenko8a28e622007-04-14 11:16:29 +0000834 return EXIT_FAILURE;
835 found:
Denis Vlasenko52881e92007-04-21 13:42:52 +0000836 // TODO: bash prints a string representation
837 // of job being foregrounded (like "sleep 1 | cat")
Denis Vlasenko1359da62007-04-21 23:27:30 +0000838 if (*argv[0] == 'f') {
Eric Andersen028b65b2001-06-28 01:10:11 +0000839 /* Put the job into the foreground. */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000840 tcsetpgrp(interactive_fd, pi->pgrp);
Eric Andersen25f27032001-04-26 23:22:31 +0000841 }
842
843 /* Restart the processes in the job */
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000844 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_progs, pi->pgrp);
Denis Vlasenko1359da62007-04-21 23:27:30 +0000845 for (i = 0; i < pi->num_progs; i++) {
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000846 debug_printf_jobs("reviving pid %d\n", pi->progs[i].pid);
Eric Andersen0fcd4472001-05-02 20:12:03 +0000847 pi->progs[i].is_stopped = 0;
Denis Vlasenko1359da62007-04-21 23:27:30 +0000848 }
849 pi->stopped_progs = 0;
Eric Andersen25f27032001-04-26 23:22:31 +0000850
Denis Vlasenkobb81c582007-01-30 22:32:09 +0000851 i = kill(- pi->pgrp, SIGCONT);
852 if (i < 0) {
Denis Vlasenko8a28e622007-04-14 11:16:29 +0000853 if (errno == ESRCH) {
Denis Vlasenko1359da62007-04-21 23:27:30 +0000854 delete_finished_bg_job(pi);
Denis Vlasenko3ac0e002007-04-28 16:45:22 +0000855 return EXIT_SUCCESS;
Eric Andersen028b65b2001-06-28 01:10:11 +0000856 } else {
Manuel Novoa III cad53642003-03-19 09:13:01 +0000857 bb_perror_msg("kill (SIGCONT)");
Eric Andersen028b65b2001-06-28 01:10:11 +0000858 }
859 }
Eric Andersen25f27032001-04-26 23:22:31 +0000860
Denis Vlasenko1359da62007-04-21 23:27:30 +0000861 if (*argv[0] == 'f') {
862 remove_bg_job(pi);
Denis Vlasenko52881e92007-04-21 13:42:52 +0000863 return checkjobs_and_fg_shell(pi);
Denis Vlasenko1359da62007-04-21 23:27:30 +0000864 }
Eric Andersen25f27032001-04-26 23:22:31 +0000865 return EXIT_SUCCESS;
866}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000867#endif
Eric Andersen25f27032001-04-26 23:22:31 +0000868
869/* built-in 'help' handler */
Denis Vlasenko1359da62007-04-21 23:27:30 +0000870static int builtin_help(char **argv ATTRIBUTE_UNUSED)
Eric Andersen25f27032001-04-26 23:22:31 +0000871{
"Vladimir N. Oleynik"485d7cb2005-10-17 09:48:57 +0000872 const struct built_in_command *x;
Eric Andersen25f27032001-04-26 23:22:31 +0000873
874 printf("\nBuilt-in commands:\n");
875 printf("-------------------\n");
876 for (x = bltins; x->cmd; x++) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000877 if (x->descr == NULL)
Eric Andersen25f27032001-04-26 23:22:31 +0000878 continue;
879 printf("%s\t%s\n", x->cmd, x->descr);
880 }
881 printf("\n\n");
882 return EXIT_SUCCESS;
883}
884
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000885#if ENABLE_HUSH_JOB
Eric Andersen25f27032001-04-26 23:22:31 +0000886/* built-in 'jobs' handler */
Denis Vlasenko1359da62007-04-21 23:27:30 +0000887static int builtin_jobs(char **argv ATTRIBUTE_UNUSED)
Eric Andersen25f27032001-04-26 23:22:31 +0000888{
889 struct pipe *job;
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000890 const char *status_string;
Eric Andersen25f27032001-04-26 23:22:31 +0000891
Eric Andersenc798b072001-06-22 06:23:03 +0000892 for (job = job_list; job; job = job->next) {
Eric Andersen25f27032001-04-26 23:22:31 +0000893 if (job->running_progs == job->stopped_progs)
894 status_string = "Stopped";
895 else
896 status_string = "Running";
Eric Andersen52a97ca2001-06-22 06:49:26 +0000897
Denis Vlasenko3ac0e002007-04-28 16:45:22 +0000898 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
Eric Andersen25f27032001-04-26 23:22:31 +0000899 }
900 return EXIT_SUCCESS;
901}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000902#endif
Eric Andersen25f27032001-04-26 23:22:31 +0000903
Eric Andersen25f27032001-04-26 23:22:31 +0000904/* built-in 'pwd' handler */
Denis Vlasenko1359da62007-04-21 23:27:30 +0000905static int builtin_pwd(char **argv ATTRIBUTE_UNUSED)
Eric Andersen25f27032001-04-26 23:22:31 +0000906{
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000907 puts(set_cwd());
Eric Andersen25f27032001-04-26 23:22:31 +0000908 return EXIT_SUCCESS;
909}
910
911/* built-in 'read VAR' handler */
Denis Vlasenko1359da62007-04-21 23:27:30 +0000912static int builtin_read(char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +0000913{
Denis Vlasenko3e7b0e62007-05-16 12:52:15 +0000914 char string[BUFSIZ];
915 char *p;
916 const char *name = argv[1] ? argv[1] : "REPLY";
917 int name_len = strlen(name);
Eric Andersen25f27032001-04-26 23:22:31 +0000918
Denis Vlasenko3e7b0e62007-05-16 12:52:15 +0000919 if (name_len >= sizeof(string) - 2)
920 return EXIT_FAILURE;
921 strcpy(string, name);
922 p = string + name_len;
923 *p++ = '=';
924 *p = '\0'; /* In case stdin has only EOF */
925 /* read string. name_len+1 chars are already used by 'name=' */
926 fgets(p, sizeof(string) - 1 - name_len, stdin);
927 chomp(p);
928 return set_local_var(string, 0);
Eric Andersen25f27032001-04-26 23:22:31 +0000929}
930
Denis Vlasenko3e7b0e62007-05-16 12:52:15 +0000931/* built-in 'set [VAR=value]' handler */
Denis Vlasenko1359da62007-04-21 23:27:30 +0000932static int builtin_set(char **argv)
Eric Andersenf72f5622001-05-15 23:21:41 +0000933{
Denis Vlasenko1359da62007-04-21 23:27:30 +0000934 char *temp = argv[1];
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000935 struct variables *e;
Eric Andersenf72f5622001-05-15 23:21:41 +0000936
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000937 if (temp == NULL)
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000938 for (e = top_vars; e; e = e->next)
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000939 printf("%s=%s\n", e->name, e->value);
940 else
941 set_local_var(temp, 0);
942
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000943 return EXIT_SUCCESS;
Eric Andersenf72f5622001-05-15 23:21:41 +0000944}
945
946
Eric Andersen25f27032001-04-26 23:22:31 +0000947/* Built-in 'shift' handler */
Denis Vlasenko1359da62007-04-21 23:27:30 +0000948static int builtin_shift(char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +0000949{
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000950 int n = 1;
Denis Vlasenko1359da62007-04-21 23:27:30 +0000951 if (argv[1]) {
952 n = atoi(argv[1]);
Eric Andersen25f27032001-04-26 23:22:31 +0000953 }
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000954 if (n >= 0 && n < global_argc) {
Denis Vlasenko004baba2007-05-20 22:22:18 +0000955 global_argv[n] = global_argv[0];
Eric Andersen25f27032001-04-26 23:22:31 +0000956 global_argc -= n;
957 global_argv += n;
958 return EXIT_SUCCESS;
Eric Andersen25f27032001-04-26 23:22:31 +0000959 }
Denis Vlasenkof03dbed2007-04-13 19:55:50 +0000960 return EXIT_FAILURE;
Eric Andersen25f27032001-04-26 23:22:31 +0000961}
962
963/* Built-in '.' handler (read-in and execute commands from file) */
Denis Vlasenko1359da62007-04-21 23:27:30 +0000964static int builtin_source(char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +0000965{
966 FILE *input;
967 int status;
968
Denis Vlasenko1359da62007-04-21 23:27:30 +0000969 if (argv[1] == NULL)
Eric Andersen25f27032001-04-26 23:22:31 +0000970 return EXIT_FAILURE;
971
972 /* XXX search through $PATH is missing */
Denis Vlasenko1359da62007-04-21 23:27:30 +0000973 input = fopen(argv[1], "r");
Eric Andersen25f27032001-04-26 23:22:31 +0000974 if (!input) {
Denis Vlasenko1359da62007-04-21 23:27:30 +0000975 bb_error_msg("cannot open '%s'", argv[1]);
Eric Andersen25f27032001-04-26 23:22:31 +0000976 return EXIT_FAILURE;
977 }
978
979 /* Now run the file */
980 /* XXX argv and argc are broken; need to save old global_argv
981 * (pointer only is OK!) on this stack frame,
Denis Vlasenko1359da62007-04-21 23:27:30 +0000982 * set global_argv=argv+1, recurse, and restore. */
Eric Andersen25f27032001-04-26 23:22:31 +0000983 mark_open(fileno(input));
984 status = parse_file_outer(input);
985 mark_closed(fileno(input));
986 fclose(input);
Denis Vlasenkod9e15f22006-11-27 16:49:55 +0000987 return status;
Eric Andersen25f27032001-04-26 23:22:31 +0000988}
989
Denis Vlasenko1359da62007-04-21 23:27:30 +0000990static int builtin_umask(char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +0000991{
Eric Andersen83a2ae22001-05-07 17:59:25 +0000992 mode_t new_umask;
Denis Vlasenko1359da62007-04-21 23:27:30 +0000993 const char *arg = argv[1];
Eric Andersen83a2ae22001-05-07 17:59:25 +0000994 char *end;
995 if (arg) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000996 new_umask = strtoul(arg, &end, 8);
997 if (*end != '\0' || end == arg) {
Eric Andersen83a2ae22001-05-07 17:59:25 +0000998 return EXIT_FAILURE;
999 }
1000 } else {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001001 new_umask = umask(0);
1002 printf("%.3o\n", (unsigned) new_umask);
Eric Andersen83a2ae22001-05-07 17:59:25 +00001003 }
1004 umask(new_umask);
1005 return EXIT_SUCCESS;
Eric Andersen25f27032001-04-26 23:22:31 +00001006}
1007
1008/* built-in 'unset VAR' handler */
Denis Vlasenko1359da62007-04-21 23:27:30 +00001009static int builtin_unset(char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00001010{
Denis Vlasenko3e7b0e62007-05-16 12:52:15 +00001011 /* bash always returns true */
Denis Vlasenko1359da62007-04-21 23:27:30 +00001012 unset_local_var(argv[1]);
Eric Andersen25f27032001-04-26 23:22:31 +00001013 return EXIT_SUCCESS;
1014}
1015
Denis Vlasenko1359da62007-04-21 23:27:30 +00001016static int builtin_not_written(char **argv)
Eric Andersen83a2ae22001-05-07 17:59:25 +00001017{
Denis Vlasenko1359da62007-04-21 23:27:30 +00001018 printf("builtin_%s not written\n", argv[0]);
Eric Andersen83a2ae22001-05-07 17:59:25 +00001019 return EXIT_FAILURE;
1020}
1021
Eric Andersen25f27032001-04-26 23:22:31 +00001022static int b_check_space(o_string *o, int len)
1023{
1024 /* It would be easy to drop a more restrictive policy
1025 * in here, such as setting a maximum string length */
1026 if (o->length + len > o->maxlen) {
Denis Vlasenkof5294e12007-04-14 10:09:57 +00001027 /* assert(data == NULL || o->maxlen != 0); */
Denis Vlasenkoef36ead2007-05-02 15:34:47 +00001028 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001029 o->data = xrealloc(o->data, 1 + o->maxlen);
Eric Andersen25f27032001-04-26 23:22:31 +00001030 }
1031 return o->data == NULL;
1032}
1033
1034static int b_addchr(o_string *o, int ch)
1035{
Denis Vlasenko831dcc42007-05-16 15:05:36 +00001036 debug_printf("b_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001037 if (b_check_space(o, 1))
1038 return B_NOSPAC;
Eric Andersen25f27032001-04-26 23:22:31 +00001039 o->data[o->length] = ch;
1040 o->length++;
1041 o->data[o->length] = '\0';
1042 return 0;
1043}
1044
1045static void b_reset(o_string *o)
1046{
1047 o->length = 0;
1048 o->nonnull = 0;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001049 if (o->data != NULL)
1050 *o->data = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00001051}
1052
1053static void b_free(o_string *o)
1054{
1055 b_reset(o);
Aaron Lehmanna170e1c2002-11-28 11:27:31 +00001056 free(o->data);
Eric Andersen25f27032001-04-26 23:22:31 +00001057 o->data = NULL;
1058 o->maxlen = 0;
1059}
1060
1061/* My analysis of quoting semantics tells me that state information
1062 * is associated with a destination, not a source.
1063 */
1064static int b_addqchr(o_string *o, int ch, int quote)
1065{
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00001066 if (quote && strchr("*?[\\", ch)) {
Eric Andersen25f27032001-04-26 23:22:31 +00001067 int rc;
1068 rc = b_addchr(o, '\\');
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001069 if (rc)
1070 return rc;
Eric Andersen25f27032001-04-26 23:22:31 +00001071 }
1072 return b_addchr(o, ch);
1073}
1074
Eric Andersen25f27032001-04-26 23:22:31 +00001075static int static_get(struct in_str *i)
1076{
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001077 int ch = *i->p++;
1078 if (ch == '\0') return EOF;
Eric Andersen25f27032001-04-26 23:22:31 +00001079 return ch;
1080}
1081
1082static int static_peek(struct in_str *i)
1083{
1084 return *i->p;
1085}
1086
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001087#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001088#if ENABLE_FEATURE_EDITING
Rob Landley88621d72006-08-29 19:41:06 +00001089static void cmdedit_set_initial_prompt(void)
Eric Andersen25f27032001-04-26 23:22:31 +00001090{
Denis Vlasenko38f63192007-01-22 09:03:07 +00001091#if !ENABLE_FEATURE_EDITING_FANCY_PROMPT
Eric Andersen25f27032001-04-26 23:22:31 +00001092 PS1 = NULL;
1093#else
1094 PS1 = getenv("PS1");
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001095 if (PS1 == NULL)
Eric Andersen25f27032001-04-26 23:22:31 +00001096 PS1 = "\\w \\$ ";
Eric Andersenc7bda1c2004-03-15 08:29:22 +00001097#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001098}
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001099#endif /* EDITING */
Eric Andersen25f27032001-04-26 23:22:31 +00001100
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00001101static const char* setup_prompt_string(int promptmode)
Eric Andersen25f27032001-04-26 23:22:31 +00001102{
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00001103 const char *prompt_str;
1104 debug_printf("setup_prompt_string %d ", promptmode);
Denis Vlasenko38f63192007-01-22 09:03:07 +00001105#if !ENABLE_FEATURE_EDITING_FANCY_PROMPT
Eric Andersen25f27032001-04-26 23:22:31 +00001106 /* Set up the prompt */
1107 if (promptmode == 1) {
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00001108 char *ns;
1109 free((char*)PS1);
1110 ns = xmalloc(strlen(cwd)+4);
1111 sprintf(ns, "%s %s", cwd, (geteuid() != 0) ? "$ " : "# ");
1112 prompt_str = ns;
1113 PS1 = ns;
Eric Andersen25f27032001-04-26 23:22:31 +00001114 } else {
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00001115 prompt_str = PS2;
Eric Andersen25f27032001-04-26 23:22:31 +00001116 }
1117#else
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00001118 prompt_str = (promptmode == 1) ? PS1 : PS2;
Eric Andersenaf44a0e2001-04-27 07:26:12 +00001119#endif
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00001120 debug_printf("result %s\n", prompt_str);
1121 return prompt_str;
Eric Andersen25f27032001-04-26 23:22:31 +00001122}
1123
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001124static void get_user_input(struct in_str *i)
Eric Andersen25f27032001-04-26 23:22:31 +00001125{
Denis Vlasenko0937be52007-04-28 16:47:08 +00001126 int r;
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00001127 const char *prompt_str;
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001128
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00001129 prompt_str = setup_prompt_string(i->promptmode);
Denis Vlasenko38f63192007-01-22 09:03:07 +00001130#if ENABLE_FEATURE_EDITING
Eric Andersen25f27032001-04-26 23:22:31 +00001131 /*
1132 ** enable command line editing only while a command line
1133 ** is actually being read; otherwise, we'll end up bequeathing
1134 ** atexit() handlers and other unwanted stuff to our
1135 ** child processes (rob@sysgo.de)
1136 */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001137 r = read_line_input(prompt_str, user_input_buf, BUFSIZ-1, line_input_state);
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001138 i->eof_flag = (r < 0);
1139 if (i->eof_flag) { /* EOF/error detected */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001140 user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
1141 user_input_buf[1] = '\0';
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001142 }
Eric Andersen25f27032001-04-26 23:22:31 +00001143#else
1144 fputs(prompt_str, stdout);
1145 fflush(stdout);
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001146 user_input_buf[0] = r = fgetc(i->file);
1147 /*user_input_buf[1] = '\0'; - already is and never changed */
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001148 i->eof_flag = (r == EOF);
Eric Andersen25f27032001-04-26 23:22:31 +00001149#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001150 i->p = user_input_buf;
Eric Andersen25f27032001-04-26 23:22:31 +00001151}
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001152#endif /* INTERACTIVE */
Eric Andersen25f27032001-04-26 23:22:31 +00001153
Eric Andersenc7bda1c2004-03-15 08:29:22 +00001154/* This is the magic location that prints prompts
Eric Andersen25f27032001-04-26 23:22:31 +00001155 * and gets data back from the user */
1156static int file_get(struct in_str *i)
1157{
1158 int ch;
1159
Eric Andersen25f27032001-04-26 23:22:31 +00001160 /* If there is data waiting, eat it up */
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001161 if (i->p && *i->p) {
Denis Vlasenko96f67dc2007-05-17 13:02:41 +00001162#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001163 take_cached:
Denis Vlasenko96f67dc2007-05-17 13:02:41 +00001164#endif
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001165 ch = *i->p++;
1166 if (i->eof_flag && !*i->p)
1167 ch = EOF;
Eric Andersen25f27032001-04-26 23:22:31 +00001168 } else {
1169 /* need to double check i->file because we might be doing something
1170 * more complicated by now, like sourcing or substituting. */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001171#if ENABLE_HUSH_INTERACTIVE
1172 if (interactive_fd && i->__promptme && i->file == stdin) {
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001173 do {
1174 get_user_input(i);
1175 } while (!*i->p); /* need non-empty line */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001176 i->promptmode = 2;
Eric Andersene67c3ce2001-05-02 02:09:36 +00001177 i->__promptme = 0;
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001178 goto take_cached;
Eric Andersen25f27032001-04-26 23:22:31 +00001179 }
Denis Vlasenko96f67dc2007-05-17 13:02:41 +00001180#endif
1181 ch = fgetc(i->file);
Eric Andersen25f27032001-04-26 23:22:31 +00001182 }
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001183 debug_printf("file_get: got a '%c' %d\n", ch, ch);
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001184#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001185 if (ch == '\n')
1186 i->__promptme = 1;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001187#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001188 return ch;
1189}
1190
1191/* All the callers guarantee this routine will never be
1192 * used right after a newline, so prompting is not needed.
1193 */
1194static int file_peek(struct in_str *i)
1195{
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00001196 int ch;
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001197 if (i->p && *i->p) {
1198 if (i->eof_flag && !i->p[1])
1199 return EOF;
1200 return *i->p;
Eric Andersen25f27032001-04-26 23:22:31 +00001201 }
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00001202 ch = fgetc(i->file);
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001203 i->eof_flag = (ch == EOF);
1204 i->peek_buf[0] = ch;
1205 i->peek_buf[1] = '\0';
1206 i->p = i->peek_buf;
1207 debug_printf("file_peek: got a '%c' %d\n", *i->p, *i->p);
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00001208 return ch;
Eric Andersen25f27032001-04-26 23:22:31 +00001209}
1210
1211static void setup_file_in_str(struct in_str *i, FILE *f)
1212{
1213 i->peek = file_peek;
1214 i->get = file_get;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001215#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001216 i->__promptme = 1;
1217 i->promptmode = 1;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001218#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001219 i->file = f;
1220 i->p = NULL;
1221}
1222
1223static void setup_string_in_str(struct in_str *i, const char *s)
1224{
1225 i->peek = static_peek;
1226 i->get = static_get;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001227#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenkobb81c582007-01-30 22:32:09 +00001228 i->__promptme = 1;
1229 i->promptmode = 1;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001230#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001231 i->p = s;
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001232 i->eof_flag = 0;
Eric Andersen25f27032001-04-26 23:22:31 +00001233}
1234
1235static void mark_open(int fd)
1236{
1237 struct close_me *new = xmalloc(sizeof(struct close_me));
1238 new->fd = fd;
1239 new->next = close_me_head;
1240 close_me_head = new;
1241}
1242
1243static void mark_closed(int fd)
1244{
1245 struct close_me *tmp;
1246 if (close_me_head == NULL || close_me_head->fd != fd)
Manuel Novoa III cad53642003-03-19 09:13:01 +00001247 bb_error_msg_and_die("corrupt close_me");
Eric Andersen25f27032001-04-26 23:22:31 +00001248 tmp = close_me_head;
1249 close_me_head = close_me_head->next;
1250 free(tmp);
1251}
1252
Eric Anderseneaecbf32001-10-31 10:41:31 +00001253static void close_all(void)
Eric Andersen25f27032001-04-26 23:22:31 +00001254{
1255 struct close_me *c;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001256 for (c = close_me_head; c; c = c->next) {
Eric Andersen25f27032001-04-26 23:22:31 +00001257 close(c->fd);
1258 }
1259 close_me_head = NULL;
1260}
1261
1262/* squirrel != NULL means we squirrel away copies of stdin, stdout,
1263 * and stderr if they are redirected. */
1264static int setup_redirects(struct child_prog *prog, int squirrel[])
1265{
1266 int openfd, mode;
1267 struct redir_struct *redir;
1268
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001269 for (redir = prog->redirects; redir; redir = redir->next) {
Eric Andersen817e73c2001-06-06 17:56:09 +00001270 if (redir->dup == -1 && redir->word.gl_pathv == NULL) {
1271 /* something went wrong in the parse. Pretend it didn't happen */
1272 continue;
1273 }
Eric Andersen25f27032001-04-26 23:22:31 +00001274 if (redir->dup == -1) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001275 mode = redir_table[redir->type].mode;
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00001276 openfd = open_or_warn(redir->word.gl_pathv[0], mode);
Eric Andersen25f27032001-04-26 23:22:31 +00001277 if (openfd < 0) {
1278 /* this could get lost if stderr has been redirected, but
1279 bash and ash both lose it as well (though zsh doesn't!) */
Eric Andersen25f27032001-04-26 23:22:31 +00001280 return 1;
1281 }
1282 } else {
1283 openfd = redir->dup;
1284 }
1285
1286 if (openfd != redir->fd) {
1287 if (squirrel && redir->fd < 3) {
1288 squirrel[redir->fd] = dup(redir->fd);
1289 }
Eric Andersen83a2ae22001-05-07 17:59:25 +00001290 if (openfd == -3) {
1291 close(openfd);
1292 } else {
1293 dup2(openfd, redir->fd);
Matt Kraaic616e532001-06-05 16:50:08 +00001294 if (redir->dup == -1)
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00001295 close(openfd);
Eric Andersen83a2ae22001-05-07 17:59:25 +00001296 }
Eric Andersen25f27032001-04-26 23:22:31 +00001297 }
1298 }
1299 return 0;
1300}
1301
1302static void restore_redirects(int squirrel[])
1303{
1304 int i, fd;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001305 for (i = 0; i < 3; i++) {
Eric Andersen25f27032001-04-26 23:22:31 +00001306 fd = squirrel[i];
1307 if (fd != -1) {
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00001308 /* We simply die on error */
1309 xmove_fd(fd, i);
Eric Andersen25f27032001-04-26 23:22:31 +00001310 }
1311 }
1312}
1313
Eric Andersenada18ff2001-05-21 16:18:22 +00001314/* never returns */
Eric Andersen94ac2442001-05-22 19:05:18 +00001315/* XXX no exit() here. If you don't exec, use _exit instead.
1316 * The at_exit handlers apparently confuse the calling process,
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00001317 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
Denis Vlasenko1359da62007-04-21 23:27:30 +00001318static void pseudo_exec_argv(char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00001319{
Eric Andersen78a7c992001-05-15 16:30:25 +00001320 int i, rcode;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00001321 char *p;
"Vladimir N. Oleynik"485d7cb2005-10-17 09:48:57 +00001322 const struct built_in_command *x;
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00001323
Denis Vlasenko1359da62007-04-21 23:27:30 +00001324 for (i = 0; is_assignment(argv[i]); i++) {
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001325 debug_printf_exec("pid %d environment modification: %s\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00001326 getpid(), argv[i]);
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001327// FIXME: vfork case??
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00001328 p = expand_variables_to_string(argv[i]);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00001329 putenv(p == argv[i] ? xstrdup(p) : p);
Denis Vlasenko1359da62007-04-21 23:27:30 +00001330 }
1331 argv += i;
1332 /* If a variable is assigned in a forest, and nobody listens,
1333 * was it ever really set?
1334 */
1335 if (argv[0] == NULL) {
1336 _exit(EXIT_SUCCESS);
1337 }
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00001338
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00001339 argv = expand_variables_to_list(argv);
Denis Vlasenko764d59d2007-05-14 16:23:23 +00001340
Denis Vlasenko1359da62007-04-21 23:27:30 +00001341 /*
1342 * Check if the command matches any of the builtins.
1343 * Depending on context, this might be redundant. But it's
1344 * easier to waste a few CPU cycles than it is to figure out
1345 * if this is one of those cases.
1346 */
1347 for (x = bltins; x->cmd; x++) {
1348 if (strcmp(argv[0], x->cmd) == 0) {
Denis Vlasenko764d59d2007-05-14 16:23:23 +00001349 debug_printf_exec("running builtin '%s'\n", argv[0]);
Denis Vlasenko1359da62007-04-21 23:27:30 +00001350 rcode = x->function(argv);
1351 fflush(stdout);
1352 _exit(rcode);
Eric Andersen94ac2442001-05-22 19:05:18 +00001353 }
Denis Vlasenko1359da62007-04-21 23:27:30 +00001354 }
Eric Andersen78a7c992001-05-15 16:30:25 +00001355
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001356 /* Check if the command matches any busybox applets */
Denis Vlasenko80d14be2007-04-10 23:03:30 +00001357#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001358 if (strchr(argv[0], '/') == NULL) {
1359 const struct bb_applet *a = find_applet_by_name(argv[0]);
1360 if (a) {
1361 if (a->noexec) {
1362 current_applet = a;
1363 debug_printf_exec("running applet '%s'\n", argv[0]);
1364// is it ok that run_current_applet_and_exit() does exit(), not _exit()?
1365 run_current_applet_and_exit(argv);
1366 }
1367 /* re-exec ourselves with the new arguments */
1368 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
1369 execvp(CONFIG_BUSYBOX_EXEC_PATH, argv);
1370 /* If they called chroot or otherwise made the binary no longer
1371 * executable, fall through */
1372 }
1373 }
Eric Andersenaac75e52001-04-30 18:18:45 +00001374#endif
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001375
1376 debug_printf_exec("execing '%s'\n", argv[0]);
Denis Vlasenko1359da62007-04-21 23:27:30 +00001377 execvp(argv[0], argv);
1378 bb_perror_msg("cannot exec '%s'", argv[0]);
1379 _exit(1);
1380}
1381
1382static void pseudo_exec(struct child_prog *child)
1383{
Denis Vlasenkof2fffd02007-05-02 23:39:04 +00001384// FIXME: buggy wrt NOMMU! Must not modify any global data
1385// until it does exec/_exit, but currently it does.
Denis Vlasenko1359da62007-04-21 23:27:30 +00001386 int rcode;
1387
1388 if (child->argv) {
1389 pseudo_exec_argv(child->argv);
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00001390 }
1391
1392 if (child->group) {
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00001393 // FIXME: do not modify globals! Think vfork!
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001394#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001395 debug_printf_exec("pseudo_exec: setting interactive_fd=0\n");
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001396 interactive_fd = 0; /* crucial!!!! */
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001397#endif
Denis Vlasenkod01ff132007-05-02 21:40:23 +00001398 debug_printf_exec("pseudo_exec: run_list_real\n");
Eric Andersen25f27032001-04-26 23:22:31 +00001399 rcode = run_list_real(child->group);
Eric Andersenbf7df042001-05-23 22:18:35 +00001400 /* OK to leak memory by not calling free_pipe_list,
Eric Andersen25f27032001-04-26 23:22:31 +00001401 * since this process is about to exit */
Eric Andersen94ac2442001-05-22 19:05:18 +00001402 _exit(rcode);
Eric Andersen25f27032001-04-26 23:22:31 +00001403 }
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00001404
1405 /* Can happen. See what bash does with ">foo" by itself. */
1406 debug_printf("trying to pseudo_exec null command\n");
1407 _exit(EXIT_SUCCESS);
Eric Andersen25f27032001-04-26 23:22:31 +00001408}
1409
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001410#if ENABLE_HUSH_JOB
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00001411static const char *get_cmdtext(struct pipe *pi)
1412{
1413 char **argv;
1414 char *p;
1415 int len;
1416
1417 /* This is subtle. ->cmdtext is created only on first backgrounding.
1418 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001419 * On subsequent bg argv is trashed, but we won't use it */
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00001420 if (pi->cmdtext)
1421 return pi->cmdtext;
1422 argv = pi->progs[0].argv;
1423 if (!argv || !argv[0])
1424 return (pi->cmdtext = xzalloc(1));
1425
1426 len = 0;
1427 do len += strlen(*argv) + 1; while (*++argv);
1428 pi->cmdtext = p = xmalloc(len);
1429 argv = pi->progs[0].argv;
1430 do {
1431 len = strlen(*argv);
1432 memcpy(p, *argv, len);
1433 p += len;
1434 *p++ = ' ';
1435 } while (*++argv);
1436 p[-1] = '\0';
1437 return pi->cmdtext;
1438}
1439
Eric Andersenbafd94f2001-05-02 16:11:59 +00001440static void insert_bg_job(struct pipe *pi)
1441{
1442 struct pipe *thejob;
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001443 int i;
Eric Andersenbafd94f2001-05-02 16:11:59 +00001444
1445 /* Linear search for the ID of the job to use */
1446 pi->jobid = 1;
Eric Andersenc798b072001-06-22 06:23:03 +00001447 for (thejob = job_list; thejob; thejob = thejob->next)
Eric Andersenbafd94f2001-05-02 16:11:59 +00001448 if (thejob->jobid >= pi->jobid)
1449 pi->jobid = thejob->jobid + 1;
1450
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001451 /* Add thejob to the list of running jobs */
Eric Andersenc798b072001-06-22 06:23:03 +00001452 if (!job_list) {
Eric Andersen52a97ca2001-06-22 06:49:26 +00001453 thejob = job_list = xmalloc(sizeof(*thejob));
Eric Andersenbafd94f2001-05-02 16:11:59 +00001454 } else {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001455 for (thejob = job_list; thejob->next; thejob = thejob->next)
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00001456 continue;
Eric Andersenbafd94f2001-05-02 16:11:59 +00001457 thejob->next = xmalloc(sizeof(*thejob));
1458 thejob = thejob->next;
1459 }
1460
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001461 /* Physically copy the struct job */
Eric Andersen0fcd4472001-05-02 20:12:03 +00001462 memcpy(thejob, pi, sizeof(struct pipe));
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001463 thejob->progs = xzalloc(sizeof(pi->progs[0]) * pi->num_progs);
1464 /* We cannot copy entire pi->progs[] vector! Double free()s will happen */
1465 for (i = 0; i < pi->num_progs; i++) {
1466// TODO: do we really need to have so many fields which are just dead weight
1467// at execution stage?
1468 thejob->progs[i].pid = pi->progs[i].pid;
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001469 /* all other fields are not used and stay zero */
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001470 }
Eric Andersenbafd94f2001-05-02 16:11:59 +00001471 thejob->next = NULL;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00001472 thejob->cmdtext = xstrdup(get_cmdtext(pi));
Eric Andersenbafd94f2001-05-02 16:11:59 +00001473
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001474 /* We don't wait for background thejobs to return -- append it
Eric Andersenbafd94f2001-05-02 16:11:59 +00001475 to the list of backgrounded thejobs and leave it alone */
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00001476 printf("[%d] %d %s\n", thejob->jobid, thejob->progs[0].pid, thejob->cmdtext);
Eric Andersen1a6d39b2001-05-08 05:11:54 +00001477 last_bg_pid = thejob->progs[0].pid;
Eric Andersenc798b072001-06-22 06:23:03 +00001478 last_jobid = thejob->jobid;
Eric Andersenbafd94f2001-05-02 16:11:59 +00001479}
1480
Eric Andersenbafd94f2001-05-02 16:11:59 +00001481static void remove_bg_job(struct pipe *pi)
1482{
1483 struct pipe *prev_pipe;
1484
Eric Andersenc798b072001-06-22 06:23:03 +00001485 if (pi == job_list) {
Eric Andersen52a97ca2001-06-22 06:49:26 +00001486 job_list = pi->next;
Eric Andersenbafd94f2001-05-02 16:11:59 +00001487 } else {
Eric Andersenc798b072001-06-22 06:23:03 +00001488 prev_pipe = job_list;
Eric Andersenbafd94f2001-05-02 16:11:59 +00001489 while (prev_pipe->next != pi)
1490 prev_pipe = prev_pipe->next;
1491 prev_pipe->next = pi->next;
1492 }
Eric Andersen028b65b2001-06-28 01:10:11 +00001493 if (job_list)
1494 last_jobid = job_list->jobid;
1495 else
1496 last_jobid = 0;
Denis Vlasenko1359da62007-04-21 23:27:30 +00001497}
Eric Andersen028b65b2001-06-28 01:10:11 +00001498
Denis Vlasenko1359da62007-04-21 23:27:30 +00001499/* remove a backgrounded job */
1500static void delete_finished_bg_job(struct pipe *pi)
1501{
1502 remove_bg_job(pi);
Eric Andersen52a97ca2001-06-22 06:49:26 +00001503 pi->stopped_progs = 0;
Eric Andersenbf7df042001-05-23 22:18:35 +00001504 free_pipe(pi, 0);
Eric Andersenbafd94f2001-05-02 16:11:59 +00001505 free(pi);
1506}
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001507#endif /* JOB */
Eric Andersenbafd94f2001-05-02 16:11:59 +00001508
Eric Andersenc7bda1c2004-03-15 08:29:22 +00001509/* Checks to see if any processes have exited -- if they
Eric Andersenbafd94f2001-05-02 16:11:59 +00001510 have, figure out why and see if a job has completed */
Eric Andersenc798b072001-06-22 06:23:03 +00001511static int checkjobs(struct pipe* fg_pipe)
Eric Andersenbafd94f2001-05-02 16:11:59 +00001512{
Eric Andersenc798b072001-06-22 06:23:03 +00001513 int attributes;
1514 int status;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001515#if ENABLE_HUSH_JOB
Eric Andersenbafd94f2001-05-02 16:11:59 +00001516 int prognum = 0;
1517 struct pipe *pi;
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001518#endif
Eric Andersenbafd94f2001-05-02 16:11:59 +00001519 pid_t childpid;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001520 int rcode = 0;
Eric Andersenbafd94f2001-05-02 16:11:59 +00001521
Eric Andersenc798b072001-06-22 06:23:03 +00001522 attributes = WUNTRACED;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001523 if (fg_pipe == NULL) {
Eric Andersenc798b072001-06-22 06:23:03 +00001524 attributes |= WNOHANG;
1525 }
1526
Denis Vlasenko1359da62007-04-21 23:27:30 +00001527/* Do we do this right?
1528 * bash-3.00# sleep 20 | false
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001529 * <ctrl-Z pressed>
Denis Vlasenko1359da62007-04-21 23:27:30 +00001530 * [3]+ Stopped sleep 20 | false
1531 * bash-3.00# echo $?
1532 * 1 <========== bg pipe is not fully done, but exitcode is already known!
1533 */
1534
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001535//FIXME: non-interactive bash does not continue even if all processes in fg pipe
1536//are stopped. Testcase: "cat | cat" in a script (not on command line)
1537// + killall -STOP cat
1538
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001539 wait_more:
Eric Andersenc798b072001-06-22 06:23:03 +00001540 while ((childpid = waitpid(-1, &status, attributes)) > 0) {
Denis Vlasenko1359da62007-04-21 23:27:30 +00001541 const int dead = WIFEXITED(status) || WIFSIGNALED(status);
1542
1543#ifdef DEBUG_SHELL_JOBS
1544 if (WIFSTOPPED(status))
Denis Vlasenkod01ff132007-05-02 21:40:23 +00001545 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00001546 childpid, WSTOPSIG(status), WEXITSTATUS(status));
1547 if (WIFSIGNALED(status))
Denis Vlasenkod01ff132007-05-02 21:40:23 +00001548 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00001549 childpid, WTERMSIG(status), WEXITSTATUS(status));
1550 if (WIFEXITED(status))
Denis Vlasenkod01ff132007-05-02 21:40:23 +00001551 debug_printf_jobs("pid %d exited, exitcode %d\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00001552 childpid, WEXITSTATUS(status));
1553#endif
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001554 /* Were we asked to wait for fg pipe? */
Eric Andersenc798b072001-06-22 06:23:03 +00001555 if (fg_pipe) {
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001556 int i;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001557 for (i = 0; i < fg_pipe->num_progs; i++) {
Denis Vlasenkod01ff132007-05-02 21:40:23 +00001558 debug_printf_jobs("check pid %d\n", fg_pipe->progs[i].pid);
Eric Andersenc798b072001-06-22 06:23:03 +00001559 if (fg_pipe->progs[i].pid == childpid) {
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001560 /* printf("process %d exit %d\n", i, WEXITSTATUS(status)); */
Denis Vlasenko1359da62007-04-21 23:27:30 +00001561 if (dead) {
1562 fg_pipe->progs[i].pid = 0;
1563 fg_pipe->running_progs--;
1564 if (i == fg_pipe->num_progs-1)
1565 /* last process gives overall exitstatus */
1566 rcode = WEXITSTATUS(status);
1567 } else {
1568 fg_pipe->progs[i].is_stopped = 1;
1569 fg_pipe->stopped_progs++;
1570 }
Denis Vlasenkod01ff132007-05-02 21:40:23 +00001571 debug_printf_jobs("fg_pipe: running_progs %d stopped_progs %d\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00001572 fg_pipe->running_progs, fg_pipe->stopped_progs);
1573 if (fg_pipe->running_progs - fg_pipe->stopped_progs <= 0) {
1574 /* All processes in fg pipe have exited/stopped */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001575#if ENABLE_HUSH_JOB
Denis Vlasenko1359da62007-04-21 23:27:30 +00001576 if (fg_pipe->running_progs)
1577 insert_bg_job(fg_pipe);
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001578#endif
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001579 return rcode;
Denis Vlasenko1359da62007-04-21 23:27:30 +00001580 }
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001581 /* There are still running processes in the fg pipe */
1582 goto wait_more;
Eric Andersenc798b072001-06-22 06:23:03 +00001583 }
1584 }
Denis Vlasenko1359da62007-04-21 23:27:30 +00001585 /* fall through to searching process in bg pipes */
Eric Andersenc798b072001-06-22 06:23:03 +00001586 }
1587
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001588#if ENABLE_HUSH_JOB
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001589 /* We asked to wait for bg or orphaned children */
1590 /* No need to remember exitcode in this case */
Eric Andersenc798b072001-06-22 06:23:03 +00001591 for (pi = job_list; pi; pi = pi->next) {
Eric Andersenbafd94f2001-05-02 16:11:59 +00001592 prognum = 0;
Denis Vlasenko5f786c22007-04-20 08:35:45 +00001593 while (prognum < pi->num_progs) {
1594 if (pi->progs[prognum].pid == childpid)
1595 goto found_pi_and_prognum;
Eric Andersen52a97ca2001-06-22 06:49:26 +00001596 prognum++;
1597 }
Eric Andersenbafd94f2001-05-02 16:11:59 +00001598 }
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001599#endif
Eric Andersenbafd94f2001-05-02 16:11:59 +00001600
Denis Vlasenko5f786c22007-04-20 08:35:45 +00001601 /* Happens when shell is used as init process (init=/bin/sh) */
1602 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
Denis Vlasenko1359da62007-04-21 23:27:30 +00001603 goto wait_more;
Eric Andersenaeb44c42001-05-22 20:29:00 +00001604
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001605#if ENABLE_HUSH_JOB
Denis Vlasenko5f786c22007-04-20 08:35:45 +00001606 found_pi_and_prognum:
Denis Vlasenko1359da62007-04-21 23:27:30 +00001607 if (dead) {
Eric Andersenbafd94f2001-05-02 16:11:59 +00001608 /* child exited */
Eric Andersenbafd94f2001-05-02 16:11:59 +00001609 pi->progs[prognum].pid = 0;
Denis Vlasenko1359da62007-04-21 23:27:30 +00001610 pi->running_progs--;
Eric Andersenbafd94f2001-05-02 16:11:59 +00001611 if (!pi->running_progs) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001612 printf(JOB_STATUS_FORMAT, pi->jobid,
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00001613 "Done", pi->cmdtext);
Denis Vlasenko1359da62007-04-21 23:27:30 +00001614 delete_finished_bg_job(pi);
Eric Andersenbafd94f2001-05-02 16:11:59 +00001615 }
1616 } else {
1617 /* child stopped */
1618 pi->stopped_progs++;
1619 pi->progs[prognum].is_stopped = 1;
Eric Andersenbafd94f2001-05-02 16:11:59 +00001620 }
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001621#endif
Eric Andersenbafd94f2001-05-02 16:11:59 +00001622 }
1623
Denis Vlasenko1359da62007-04-21 23:27:30 +00001624 /* wait found no children or failed */
1625
1626 if (childpid && errno != ECHILD)
Manuel Novoa III cad53642003-03-19 09:13:01 +00001627 bb_perror_msg("waitpid");
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001628 return rcode;
Eric Andersenada18ff2001-05-21 16:18:22 +00001629}
1630
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001631#if ENABLE_HUSH_JOB
Denis Vlasenko52881e92007-04-21 13:42:52 +00001632static int checkjobs_and_fg_shell(struct pipe* fg_pipe)
1633{
1634 pid_t p;
1635 int rcode = checkjobs(fg_pipe);
1636 /* Job finished, move the shell to the foreground */
1637 p = getpgid(0);
1638 debug_printf("fg'ing ourself: getpgid(0)=%d\n", (int)p);
1639 if (tcsetpgrp(interactive_fd, p) && errno != ENOTTY)
1640 bb_perror_msg("tcsetpgrp-4a");
1641 return rcode;
1642}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001643#endif
Denis Vlasenko52881e92007-04-21 13:42:52 +00001644
Eric Andersen25f27032001-04-26 23:22:31 +00001645/* run_pipe_real() starts all the jobs, but doesn't wait for anything
Eric Andersenc798b072001-06-22 06:23:03 +00001646 * to finish. See checkjobs().
Eric Andersen25f27032001-04-26 23:22:31 +00001647 *
1648 * return code is normally -1, when the caller has to wait for children
1649 * to finish to determine the exit status of the pipe. If the pipe
1650 * is a simple builtin command, however, the action is done by the
1651 * time run_pipe_real returns, and the exit code is provided as the
1652 * return value.
1653 *
1654 * The input of the pipe is always stdin, the output is always
1655 * stdout. The outpipe[] mechanism in BusyBox-0.48 lash is bogus,
1656 * because it tries to avoid running the command substitution in
1657 * subshell, when that is in fact necessary. The subshell process
1658 * now has its stdout directed to the input of the appropriate pipe,
1659 * so this routine is noticeably simpler.
1660 */
1661static int run_pipe_real(struct pipe *pi)
1662{
1663 int i;
1664 int nextin, nextout;
1665 int pipefds[2]; /* pipefds[0] is for reading */
Rob Landley53702e52006-07-19 21:43:53 +00001666 struct child_prog *child;
"Vladimir N. Oleynik"485d7cb2005-10-17 09:48:57 +00001667 const struct built_in_command *x;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00001668 char *p;
Denis Vlasenkof5294e12007-04-14 10:09:57 +00001669 /* it is not always needed, but we aim to smaller code */
1670 int squirrel[] = { -1, -1, -1 };
1671 int rcode;
Denis Vlasenko52881e92007-04-21 13:42:52 +00001672 const int single_fg = (pi->num_progs == 1 && pi->followup != PIPE_BG);
Eric Andersen25f27032001-04-26 23:22:31 +00001673
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001674 debug_printf_exec("run_pipe_real start: single_fg=%d\n", single_fg);
Denis Vlasenko4ac530c2007-05-02 15:35:45 +00001675
Eric Andersen25f27032001-04-26 23:22:31 +00001676 nextin = 0;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001677#if ENABLE_HUSH_JOB
Eric Andersenada18ff2001-05-21 16:18:22 +00001678 pi->pgrp = -1;
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001679#endif
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001680 pi->running_progs = 1;
Denis Vlasenko1359da62007-04-21 23:27:30 +00001681 pi->stopped_progs = 0;
Eric Andersen25f27032001-04-26 23:22:31 +00001682
1683 /* Check if this is a simple builtin (not part of a pipe).
1684 * Builtins within pipes have to fork anyway, and are handled in
1685 * pseudo_exec. "echo foo | read bar" doesn't work on bash, either.
1686 */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001687 child = &(pi->progs[0]);
Denis Vlasenko52881e92007-04-21 13:42:52 +00001688 if (single_fg && child->group && child->subshell == 0) {
Eric Andersen04407e52001-06-07 16:42:05 +00001689 debug_printf("non-subshell grouping\n");
1690 setup_redirects(child, squirrel);
Denis Vlasenkod01ff132007-05-02 21:40:23 +00001691 debug_printf_exec(": run_list_real\n");
Eric Andersen04407e52001-06-07 16:42:05 +00001692 rcode = run_list_real(child->group);
1693 restore_redirects(squirrel);
Denis Vlasenkod01ff132007-05-02 21:40:23 +00001694 debug_printf_exec("run_pipe_real return %d\n", rcode);
Eric Andersen04407e52001-06-07 16:42:05 +00001695 return rcode;
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00001696 }
1697
Denis Vlasenko1359da62007-04-21 23:27:30 +00001698 if (single_fg && child->argv != NULL) {
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001699 char **argv_expanded;
Denis Vlasenko1359da62007-04-21 23:27:30 +00001700 char **argv = child->argv;
1701
1702 for (i = 0; is_assignment(argv[i]); i++)
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00001703 continue;
Denis Vlasenko1359da62007-04-21 23:27:30 +00001704 if (i != 0 && argv[i] == NULL) {
Eric Andersen78a7c992001-05-15 16:30:25 +00001705 /* assignments, but no command: set the local environment */
Denis Vlasenko1359da62007-04-21 23:27:30 +00001706 for (i = 0; argv[i] != NULL; i++) {
Eric Andersen99785762001-05-22 21:37:48 +00001707 /* Ok, this case is tricky. We have to decide if this is a
1708 * local variable, or an already exported variable. If it is
1709 * already exported, we have to export the new value. If it is
Eric Andersenc7bda1c2004-03-15 08:29:22 +00001710 * not exported, we need only set this as a local variable.
Eric Andersen99785762001-05-22 21:37:48 +00001711 * This junk is all to decide whether or not to export this
1712 * variable. */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001713 int export_me = 0;
Eric Andersen99785762001-05-22 21:37:48 +00001714 char *name, *value;
Denis Vlasenko1359da62007-04-21 23:27:30 +00001715 name = xstrdup(argv[i]);
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00001716 debug_printf("local environment set: %s\n", name);
Eric Andersen99785762001-05-22 21:37:48 +00001717 value = strchr(name, '=');
1718 if (value)
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00001719 *value = '\0';
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001720 if (get_local_var(name)) {
1721 export_me = 1;
Eric Andersen99785762001-05-22 21:37:48 +00001722 }
1723 free(name);
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00001724 p = expand_variables_to_string(argv[i]);
Eric Andersen4c9b68f2002-04-13 12:33:41 +00001725 set_local_var(p, export_me);
Denis Vlasenko1359da62007-04-21 23:27:30 +00001726 if (p != argv[i])
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001727 free(p);
Eric Andersen78a7c992001-05-15 16:30:25 +00001728 }
1729 return EXIT_SUCCESS; /* don't worry about errors in set_local_var() yet */
1730 }
Denis Vlasenko1359da62007-04-21 23:27:30 +00001731 for (i = 0; is_assignment(argv[i]); i++) {
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00001732 p = expand_variables_to_string(argv[i]);
Denis Vlasenko1359da62007-04-21 23:27:30 +00001733 if (p != argv[i]) {
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001734 //sp: child->sp--;
Denis Vlasenko602d13c2007-05-13 18:34:53 +00001735 putenv(p);
1736 } else {
1737 putenv(xstrdup(p));
Eric Andersen4c9b68f2002-04-13 12:33:41 +00001738 }
1739 }
Eric Andersen25f27032001-04-26 23:22:31 +00001740 for (x = bltins; x->cmd; x++) {
Denis Vlasenko1359da62007-04-21 23:27:30 +00001741 if (strcmp(argv[i], x->cmd) == 0) {
1742 if (x->function == builtin_exec && argv[i+1] == NULL) {
Eric Andersen83a2ae22001-05-07 17:59:25 +00001743 debug_printf("magic exec\n");
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00001744 setup_redirects(child, NULL);
Eric Andersen83a2ae22001-05-07 17:59:25 +00001745 return EXIT_SUCCESS;
1746 }
Denis Vlasenko1359da62007-04-21 23:27:30 +00001747 debug_printf("builtin inline %s\n", argv[0]);
Eric Andersen25f27032001-04-26 23:22:31 +00001748 /* XXX setup_redirects acts on file descriptors, not FILEs.
1749 * This is perfect for work that comes after exec().
1750 * Is it really safe for inline use? Experimentally,
1751 * things seem to work with glibc. */
1752 setup_redirects(child, squirrel);
Denis Vlasenkod01ff132007-05-02 21:40:23 +00001753 debug_printf_exec(": builtin '%s' '%s'...\n", x->cmd, argv[i+1]);
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001754 //sp: if (child->sp) /* btw we can do it unconditionally... */
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00001755 argv_expanded = expand_variables_to_list(argv + i);
Denis Vlasenko764d59d2007-05-14 16:23:23 +00001756 rcode = x->function(argv_expanded);
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001757 free(argv_expanded);
Eric Andersen25f27032001-04-26 23:22:31 +00001758 restore_redirects(squirrel);
Denis Vlasenkod01ff132007-05-02 21:40:23 +00001759 debug_printf_exec("run_pipe_real return %d\n", rcode);
Eric Andersen25f27032001-04-26 23:22:31 +00001760 return rcode;
1761 }
1762 }
Denis Vlasenkof5294e12007-04-14 10:09:57 +00001763#if ENABLE_FEATURE_SH_STANDALONE
1764 {
Denis Vlasenko1359da62007-04-21 23:27:30 +00001765 const struct bb_applet *a = find_applet_by_name(argv[i]);
Denis Vlasenkof5294e12007-04-14 10:09:57 +00001766 if (a && a->nofork) {
1767 setup_redirects(child, squirrel);
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001768 save_nofork_data(&nofork_save);
Denis Vlasenko764d59d2007-05-14 16:23:23 +00001769 argv_expanded = argv + i;
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001770 //sp: if (child->sp)
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00001771 argv_expanded = expand_variables_to_list(argv + i);
Denis Vlasenko764d59d2007-05-14 16:23:23 +00001772 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n", argv_expanded[0], argv_expanded[1]);
1773 rcode = run_nofork_applet_prime(&nofork_save, a, argv_expanded);
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001774 free(argv_expanded);
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00001775 restore_redirects(squirrel);
Denis Vlasenkod01ff132007-05-02 21:40:23 +00001776 debug_printf_exec("run_pipe_real return %d\n", rcode);
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00001777 return rcode;
Denis Vlasenkof5294e12007-04-14 10:09:57 +00001778 }
1779 }
1780#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001781 }
1782
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00001783 /* Going to fork a child per each pipe member */
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001784 pi->running_progs = 0;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00001785
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001786 /* Disable job control signals for shell (parent) and
1787 * for initial child code after fork */
1788 set_jobctrl_sighandler(SIG_IGN);
1789
Eric Andersen25f27032001-04-26 23:22:31 +00001790 for (i = 0; i < pi->num_progs; i++) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001791 child = &(pi->progs[i]);
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001792 if (child->argv)
1793 debug_printf_exec(": pipe member '%s' '%s'...\n", child->argv[0], child->argv[1]);
1794 else
1795 debug_printf_exec(": pipe member with no argv\n");
Eric Andersen25f27032001-04-26 23:22:31 +00001796
1797 /* pipes are inserted between pairs of commands */
1798 if ((i + 1) < pi->num_progs) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001799 if (pipe(pipefds) < 0)
1800 bb_perror_msg_and_die("pipe");
Eric Andersen25f27032001-04-26 23:22:31 +00001801 nextout = pipefds[1];
1802 } else {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001803 nextout = 1;
Eric Andersen25f27032001-04-26 23:22:31 +00001804 pipefds[0] = -1;
1805 }
1806
1807 /* XXX test for failed fork()? */
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00001808#if BB_MMU
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001809 child->pid = fork();
Eric Andersen72f9a422001-10-28 05:12:20 +00001810#else
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001811 child->pid = vfork();
Eric Andersen72f9a422001-10-28 05:12:20 +00001812#endif
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001813 if (!child->pid) { /* child */
1814 /* Every child adds itself to new process group
1815 * with pgid == pid of first child in pipe */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001816#if ENABLE_HUSH_JOB
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001817 if (interactive_fd) {
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00001818 /* Don't do pgrp restore anymore on fatal signals */
1819 set_fatal_sighandler(SIG_DFL);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001820 if (pi->pgrp < 0) /* true for 1st process only */
1821 pi->pgrp = getpid();
1822 if (setpgid(0, pi->pgrp) == 0 && pi->followup != PIPE_BG) {
1823 /* We do it in *every* child, not just first,
1824 * to avoid races */
1825 tcsetpgrp(interactive_fd, pi->pgrp);
1826 }
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001827 }
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001828#endif
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001829 /* in non-interactive case fatal sigs are already SIG_DFL */
Eric Andersen25f27032001-04-26 23:22:31 +00001830 close_all();
Eric Andersen25f27032001-04-26 23:22:31 +00001831 if (nextin != 0) {
1832 dup2(nextin, 0);
1833 close(nextin);
1834 }
1835 if (nextout != 1) {
1836 dup2(nextout, 1);
1837 close(nextout);
1838 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00001839 if (pipefds[0] != -1) {
Eric Andersen25f27032001-04-26 23:22:31 +00001840 close(pipefds[0]); /* opposite end of our output pipe */
1841 }
Eric Andersen25f27032001-04-26 23:22:31 +00001842 /* Like bash, explicit redirects override pipes,
1843 * and the pipe fd is available for dup'ing. */
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00001844 setup_redirects(child, NULL);
Eric Andersen52a97ca2001-06-22 06:49:26 +00001845
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001846 /* Restore default handlers just prior to exec */
1847 set_jobctrl_sighandler(SIG_DFL);
1848 set_misc_sighandler(SIG_DFL);
1849 signal(SIGCHLD, SIG_DFL);
Eric Andersen25f27032001-04-26 23:22:31 +00001850 pseudo_exec(child);
1851 }
Eric Andersenc7bda1c2004-03-15 08:29:22 +00001852
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001853 pi->running_progs++;
1854
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001855#if ENABLE_HUSH_JOB
Denis Vlasenko2f1bb362007-04-21 10:01:14 +00001856 /* Second and next children need to know pid of first one */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001857 if (pi->pgrp < 0)
Eric Andersen0fcd4472001-05-02 20:12:03 +00001858 pi->pgrp = child->pid;
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001859#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001860 if (nextin != 0)
1861 close(nextin);
1862 if (nextout != 1)
1863 close(nextout);
1864
Eric Andersenc7bda1c2004-03-15 08:29:22 +00001865 /* If there isn't another process, nextin is garbage
Eric Andersen25f27032001-04-26 23:22:31 +00001866 but it doesn't matter */
1867 nextin = pipefds[0];
1868 }
Denis Vlasenkod01ff132007-05-02 21:40:23 +00001869 debug_printf_exec("run_pipe_real return -1\n");
Eric Andersen25f27032001-04-26 23:22:31 +00001870 return -1;
1871}
1872
Denis Vlasenko400c5b62007-05-04 13:07:27 +00001873#ifndef debug_print_tree
1874static void debug_print_tree(struct pipe *pi, int lvl)
1875{
1876 static const char *PIPE[] = {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001877 [PIPE_SEQ] = "SEQ",
1878 [PIPE_AND] = "AND",
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001879 [PIPE_OR ] = "OR" ,
1880 [PIPE_BG ] = "BG" ,
Denis Vlasenko400c5b62007-05-04 13:07:27 +00001881 };
1882 static const char *RES[] = {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001883 [RES_NONE ] = "NONE" ,
1884 [RES_IF ] = "IF" ,
1885 [RES_THEN ] = "THEN" ,
1886 [RES_ELIF ] = "ELIF" ,
1887 [RES_ELSE ] = "ELSE" ,
1888 [RES_FI ] = "FI" ,
1889 [RES_FOR ] = "FOR" ,
1890 [RES_WHILE] = "WHILE",
1891 [RES_UNTIL] = "UNTIL",
1892 [RES_DO ] = "DO" ,
1893 [RES_DONE ] = "DONE" ,
1894 [RES_XXXX ] = "XXXX" ,
1895 [RES_IN ] = "IN" ,
1896 [RES_SNTX ] = "SNTX" ,
Denis Vlasenko400c5b62007-05-04 13:07:27 +00001897 };
1898
1899 int pin, prn;
Denis Vlasenko400c5b62007-05-04 13:07:27 +00001900 pin = 0;
1901 while (pi) {
1902 fprintf(stderr, "%*spipe %d r_mode=%s followup=%d %s\n", lvl*2, "",
1903 pin, RES[pi->r_mode], pi->followup, PIPE[pi->followup]);
1904 prn = 0;
1905 while (prn < pi->num_progs) {
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00001906 struct child_prog *child = &pi->progs[prn];
1907 char **argv = child->argv;
1908
Denis Vlasenko400c5b62007-05-04 13:07:27 +00001909 fprintf(stderr, "%*s prog %d", lvl*2, "", prn);
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00001910 if (child->group) {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001911 fprintf(stderr, " group %s: (argv=%p)\n",
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00001912 (child->subshell ? "()" : "{}"),
1913 argv);
1914 debug_print_tree(child->group, lvl+1);
Denis Vlasenko400c5b62007-05-04 13:07:27 +00001915 prn++;
1916 continue;
1917 }
Denis Vlasenko400c5b62007-05-04 13:07:27 +00001918 if (argv) while (*argv) {
1919 fprintf(stderr, " '%s'", *argv);
1920 argv++;
1921 }
1922 fprintf(stderr, "\n");
1923 prn++;
1924 }
1925 pi = pi->next;
1926 pin++;
1927 }
1928}
1929#endif
1930
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001931/* NB: called by pseudo_exec, and therefore must not modify any
1932 * global data until exec/_exit (we can be a child after vfork!) */
Eric Andersen25f27032001-04-26 23:22:31 +00001933static int run_list_real(struct pipe *pi)
1934{
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00001935 char *for_varname = NULL;
1936 char **for_lcur = NULL;
1937 char **for_list = NULL;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00001938 struct pipe *rpipe;
1939 int flag_rep = 0;
1940 int save_num_progs;
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001941 int flag_skip = 1;
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00001942 int rcode = 0; /* probably for gcc only */
Eric Andersen4c9b68f2002-04-13 12:33:41 +00001943 int flag_restore = 0;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001944 int if_code = 0, next_if_code = 0; /* need double-buffer to handle elif */
1945 reserved_style rmode, skip_more_in_this_rmode = RES_XXXX;
Denis Vlasenko4ac530c2007-05-02 15:35:45 +00001946
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001947 debug_printf_exec("run_list_real start lvl %d\n", run_list_level + 1);
Denis Vlasenko4ac530c2007-05-02 15:35:45 +00001948
Eric Andersen4c9b68f2002-04-13 12:33:41 +00001949 /* check syntax for "for" */
1950 for (rpipe = pi; rpipe; rpipe = rpipe->next) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001951 if ((rpipe->r_mode == RES_IN || rpipe->r_mode == RES_FOR)
1952 && (rpipe->next == NULL)
1953 ) {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001954 syntax(); /* unterminated FOR (no IN or no commands after IN) */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001955 debug_printf_exec("run_list_real lvl %d return 1\n", run_list_level);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001956 return 1;
Eric Andersenc7bda1c2004-03-15 08:29:22 +00001957 }
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001958 if ((rpipe->r_mode == RES_IN && rpipe->next->r_mode == RES_IN && rpipe->next->progs[0].argv != NULL)
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001959 || (rpipe->r_mode == RES_FOR && rpipe->next->r_mode != RES_IN)
1960 ) {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001961 /* TODO: what is tested in the first condition? */
1962 syntax(); /* 2nd: malformed FOR (not followed by IN) */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001963 debug_printf_exec("run_list_real lvl %d return 1\n", run_list_level);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001964 return 1;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00001965 }
1966 }
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001967
1968#if ENABLE_HUSH_JOB
1969 /* Example of nested list: "while true; do { sleep 1 | exit 2; } done".
1970 * We are saving state before entering outermost list ("while...done")
1971 * so that ctrl-Z will correctly background _entire_ outermost list,
1972 * not just a part of it (like "sleep 1 | exit 2") */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001973 if (++run_list_level == 1 && interactive_fd) {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001974 if (sigsetjmp(toplevel_jb, 1)) {
1975 /* ctrl-Z forked and we are parent; or ctrl-C.
1976 * Sighandler has longjmped us here */
1977 signal(SIGINT, SIG_IGN);
1978 signal(SIGTSTP, SIG_IGN);
1979 /* Restore level (we can be coming from deep inside
1980 * nested levels) */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001981 run_list_level = 1;
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001982#if ENABLE_FEATURE_SH_STANDALONE
1983 if (nofork_save.saved) { /* if save area is valid */
1984 debug_printf_jobs("exiting nofork early\n");
1985 restore_nofork_data(&nofork_save);
1986 }
1987#endif
1988 if (ctrl_z_flag) {
1989 /* ctrl-Z has forked and stored pid of the child in pi->pid.
1990 * Remember this child as background job */
1991 insert_bg_job(pi);
1992 } else {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001993 /* ctrl-C. We just stop doing whatever we were doing */
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001994 putchar('\n');
1995 }
1996 rcode = 0;
1997 goto ret;
1998 }
1999 /* ctrl-Z handler will store pid etc in pi */
2000 toplevel_list = pi;
2001 ctrl_z_flag = 0;
2002#if ENABLE_FEATURE_SH_STANDALONE
2003 nofork_save.saved = 0; /* in case we will run a nofork later */
2004#endif
2005 signal_SA_RESTART(SIGTSTP, handler_ctrl_z);
2006 signal(SIGINT, handler_ctrl_c);
2007 }
2008#endif
2009
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002010 for (; pi; pi = flag_restore ? rpipe : pi->next) {
2011 rmode = pi->r_mode;
2012 if (rmode == RES_WHILE || rmode == RES_UNTIL || rmode == RES_FOR) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002013 flag_restore = 0;
2014 if (!rpipe) {
2015 flag_rep = 0;
2016 rpipe = pi;
2017 }
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002018 }
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002019 debug_printf_exec(": rmode=%d if_code=%d next_if_code=%d skip_more=%d\n",
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002020 rmode, if_code, next_if_code, skip_more_in_this_rmode);
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002021 if (rmode == skip_more_in_this_rmode && flag_skip) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002022 if (pi->followup == PIPE_SEQ)
2023 flag_skip = 0;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002024 continue;
2025 }
2026 flag_skip = 1;
Eric Andersen4ed5e372001-05-01 01:49:50 +00002027 skip_more_in_this_rmode = RES_XXXX;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002028 if (rmode == RES_THEN || rmode == RES_ELSE)
2029 if_code = next_if_code;
Denis Vlasenko2f1bb362007-04-21 10:01:14 +00002030 if (rmode == RES_THEN && if_code)
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002031 continue;
2032 if (rmode == RES_ELSE && !if_code)
2033 continue;
2034 if (rmode == RES_ELIF && !if_code)
2035 break;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002036 if (rmode == RES_FOR && pi->num_progs) {
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002037 if (!for_lcur) {
Eric Andersenc7bda1c2004-03-15 08:29:22 +00002038 /* if no variable values after "in" we skip "for" */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002039 if (!pi->next->progs->argv)
2040 continue;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002041 /* create list of variable values */
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002042 for_list = expand_variables_to_list(pi->next->progs->argv);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002043 for_lcur = for_list;
2044 for_varname = pi->progs->argv[0];
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002045 pi->progs->argv[0] = NULL;
2046 flag_rep = 1;
Eric Andersenc7bda1c2004-03-15 08:29:22 +00002047 }
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002048 free(pi->progs->argv[0]);
2049 if (!*for_lcur) {
2050 free(for_list);
2051 for_lcur = NULL;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002052 flag_rep = 0;
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002053 pi->progs->argv[0] = for_varname;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002054 pi->progs->glob_result.gl_pathv[0] = pi->progs->argv[0];
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002055 continue;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002056 }
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002057 /* insert next value from for_lcur */
Denis Vlasenko764d59d2007-05-14 16:23:23 +00002058 /* vda: does it need escaping? */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002059 pi->progs->argv[0] = xasprintf("%s=%s", for_varname, *for_lcur++);
Denis Vlasenko5f786c22007-04-20 08:35:45 +00002060 pi->progs->glob_result.gl_pathv[0] = pi->progs->argv[0];
Eric Andersenc7bda1c2004-03-15 08:29:22 +00002061 }
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002062 if (rmode == RES_IN)
2063 continue;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002064 if (rmode == RES_DO) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002065 if (!flag_rep)
2066 continue;
Tim Rikerc1ef7bd2006-01-25 00:08:53 +00002067 }
Denis Vlasenko5f786c22007-04-20 08:35:45 +00002068 if (rmode == RES_DONE) {
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002069 if (flag_rep) {
2070 flag_restore = 1;
2071 } else {
2072 rpipe = NULL;
2073 }
Eric Andersenc7bda1c2004-03-15 08:29:22 +00002074 }
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002075 if (pi->num_progs == 0)
2076 continue;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002077 save_num_progs = pi->num_progs; /* save number of programs */
Denis Vlasenkod01ff132007-05-02 21:40:23 +00002078 debug_printf_exec(": run_pipe_real with %d members\n", pi->num_progs);
Eric Andersen25f27032001-04-26 23:22:31 +00002079 rcode = run_pipe_real(pi);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002080 if (rcode != -1) {
Eric Andersen25f27032001-04-26 23:22:31 +00002081 /* We only ran a builtin: rcode was set by the return value
2082 * of run_pipe_real(), and we don't need to wait for anything. */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002083 } else if (pi->followup == PIPE_BG) {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002084 /* What does bash do with attempts to background builtins? */
2085
2086 /* Even bash 3.2 doesn't do that well with nested bg:
2087 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
2088 * I'm considering NOT treating inner bgs as jobs -
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00002089 * thus maybe "if (run_list_level == 1 && pi->followup == PIPE_BG)"
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002090 * above? */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00002091#if ENABLE_HUSH_JOB
Eric Andersenbafd94f2001-05-02 16:11:59 +00002092 insert_bg_job(pi);
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00002093#endif
Eric Andersen25f27032001-04-26 23:22:31 +00002094 rcode = EXIT_SUCCESS;
2095 } else {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00002096#if ENABLE_HUSH_JOB
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002097 /* Paranoia, just "interactive_fd" should be enough */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00002098 if (run_list_level == 1 && interactive_fd) {
Denis Vlasenko52881e92007-04-21 13:42:52 +00002099 rcode = checkjobs_and_fg_shell(pi);
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00002100 } else
2101#endif
2102 {
Eric Andersenc798b072001-06-22 06:23:03 +00002103 rcode = checkjobs(pi);
Eric Andersen25f27032001-04-26 23:22:31 +00002104 }
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002105 debug_printf_exec(": checkjobs returned %d\n", rcode);
Eric Andersen25f27032001-04-26 23:22:31 +00002106 }
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002107 debug_printf_exec(": setting last_return_code=%d\n", rcode);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002108 last_return_code = rcode;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002109 pi->num_progs = save_num_progs; /* restore number of programs */
Denis Vlasenko5f786c22007-04-20 08:35:45 +00002110 if (rmode == RES_IF || rmode == RES_ELIF)
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002111 next_if_code = rcode; /* can be overwritten a number of times */
Eric Andersenc7bda1c2004-03-15 08:29:22 +00002112 if (rmode == RES_WHILE)
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002113 flag_rep = !last_return_code;
Eric Andersenc7bda1c2004-03-15 08:29:22 +00002114 if (rmode == RES_UNTIL)
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002115 flag_rep = last_return_code;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002116 if ((rcode == EXIT_SUCCESS && pi->followup == PIPE_OR)
2117 || (rcode != EXIT_SUCCESS && pi->followup == PIPE_AND)
2118 ) {
2119 skip_more_in_this_rmode = rmode;
2120 }
Eric Andersen028b65b2001-06-28 01:10:11 +00002121 checkjobs(NULL);
Eric Andersen25f27032001-04-26 23:22:31 +00002122 }
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002123
2124#if ENABLE_HUSH_JOB
2125 if (ctrl_z_flag) {
2126 /* ctrl-Z forked somewhere in the past, we are the child,
2127 * and now we completed running the list. Exit. */
2128 exit(rcode);
2129 }
2130 ret:
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00002131 run_list_level--;
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002132#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00002133 debug_printf_exec("run_list_real lvl %d return %d\n", run_list_level + 1, rcode);
Eric Andersen25f27032001-04-26 23:22:31 +00002134 return rcode;
2135}
2136
Eric Andersen25f27032001-04-26 23:22:31 +00002137/* return code is the exit status of the pipe */
Eric Andersenbf7df042001-05-23 22:18:35 +00002138static int free_pipe(struct pipe *pi, int indent)
Eric Andersen25f27032001-04-26 23:22:31 +00002139{
2140 char **p;
2141 struct child_prog *child;
2142 struct redir_struct *r, *rnext;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002143 int a, i, ret_code = 0;
Eric Andersen52a97ca2001-06-22 06:49:26 +00002144
2145 if (pi->stopped_progs > 0)
2146 return ret_code;
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002147 debug_printf_clean("%s run pipe: (pid %d)\n", indenter(indent), getpid());
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002148 for (i = 0; i < pi->num_progs; i++) {
Eric Andersen25f27032001-04-26 23:22:31 +00002149 child = &pi->progs[i];
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002150 debug_printf_clean("%s command %d:\n", indenter(indent), i);
Eric Andersen25f27032001-04-26 23:22:31 +00002151 if (child->argv) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002152 for (a = 0, p = child->argv; *p; a++, p++) {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002153 debug_printf_clean("%s argv[%d] = %s\n", indenter(indent), a, *p);
Eric Andersen25f27032001-04-26 23:22:31 +00002154 }
2155 globfree(&child->glob_result);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002156 child->argv = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00002157 } else if (child->group) {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002158 debug_printf_clean("%s begin group (subshell:%d)\n", indenter(indent), child->subshell);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002159 ret_code = free_pipe_list(child->group, indent+3);
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002160 debug_printf_clean("%s end group\n", indenter(indent));
Eric Andersen25f27032001-04-26 23:22:31 +00002161 } else {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002162 debug_printf_clean("%s (nil)\n", indenter(indent));
Eric Andersen25f27032001-04-26 23:22:31 +00002163 }
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002164 for (r = child->redirects; r; r = rnext) {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002165 debug_printf_clean("%s redirect %d%s", indenter(indent), r->fd, redir_table[r->type].descrip);
Eric Andersen25f27032001-04-26 23:22:31 +00002166 if (r->dup == -1) {
Eric Andersen817e73c2001-06-06 17:56:09 +00002167 /* guard against the case >$FOO, where foo is unset or blank */
2168 if (r->word.gl_pathv) {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002169 debug_printf_clean(" %s\n", *r->word.gl_pathv);
Eric Andersen817e73c2001-06-06 17:56:09 +00002170 globfree(&r->word);
2171 }
Eric Andersen25f27032001-04-26 23:22:31 +00002172 } else {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002173 debug_printf_clean("&%d\n", r->dup);
Eric Andersen25f27032001-04-26 23:22:31 +00002174 }
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002175 rnext = r->next;
Eric Andersen25f27032001-04-26 23:22:31 +00002176 free(r);
2177 }
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002178 child->redirects = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00002179 }
2180 free(pi->progs); /* children are an array, they get freed all at once */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002181 pi->progs = NULL;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00002182#if ENABLE_HUSH_JOB
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00002183 free(pi->cmdtext);
2184 pi->cmdtext = NULL;
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00002185#endif
Eric Andersen25f27032001-04-26 23:22:31 +00002186 return ret_code;
2187}
2188
Eric Andersenbf7df042001-05-23 22:18:35 +00002189static int free_pipe_list(struct pipe *head, int indent)
Eric Andersen25f27032001-04-26 23:22:31 +00002190{
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002191 int rcode = 0; /* if list has no members */
Eric Andersen25f27032001-04-26 23:22:31 +00002192 struct pipe *pi, *next;
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002193
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002194 for (pi = head; pi; pi = next) {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002195 debug_printf_clean("%s pipe reserved mode %d\n", indenter(indent), pi->r_mode);
Eric Andersenbf7df042001-05-23 22:18:35 +00002196 rcode = free_pipe(pi, indent);
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002197 debug_printf_clean("%s pipe followup code %d\n", indenter(indent), pi->followup);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002198 next = pi->next;
Denis Vlasenko5f786c22007-04-20 08:35:45 +00002199 /*pi->next = NULL;*/
Eric Andersen25f27032001-04-26 23:22:31 +00002200 free(pi);
2201 }
Eric Andersenc7bda1c2004-03-15 08:29:22 +00002202 return rcode;
Eric Andersen25f27032001-04-26 23:22:31 +00002203}
2204
2205/* Select which version we will use */
2206static int run_list(struct pipe *pi)
2207{
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002208 int rcode = 0;
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002209 debug_printf_exec("run_list entered\n");
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002210 if (fake_mode == 0) {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002211 debug_printf_exec(": run_list_real with %d members\n", pi->num_progs);
Eric Andersen25f27032001-04-26 23:22:31 +00002212 rcode = run_list_real(pi);
Eric Andersenc7bda1c2004-03-15 08:29:22 +00002213 }
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002214 /* free_pipe_list has the side effect of clearing memory.
Eric Andersen25f27032001-04-26 23:22:31 +00002215 * In the long run that function can be merged with run_list_real,
2216 * but doing that now would hobble the debugging effort. */
Denis Vlasenko400c5b62007-05-04 13:07:27 +00002217 free_pipe_list(pi, 0);
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002218 debug_printf_exec("run_list return %d\n", rcode);
Eric Andersen25f27032001-04-26 23:22:31 +00002219 return rcode;
2220}
2221
2222/* The API for glob is arguably broken. This routine pushes a non-matching
2223 * string into the output structure, removing non-backslashed backslashes.
2224 * If someone can prove me wrong, by performing this function within the
2225 * original glob(3) api, feel free to rewrite this routine into oblivion.
2226 * Return code (0 vs. GLOB_NOSPACE) matches glob(3).
2227 * XXX broken if the last character is '\\', check that before calling.
2228 */
2229static int globhack(const char *src, int flags, glob_t *pglob)
2230{
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002231 int cnt = 0, pathc;
Eric Andersen25f27032001-04-26 23:22:31 +00002232 const char *s;
2233 char *dest;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002234 for (cnt = 1, s = src; s && *s; s++) {
Eric Andersen25f27032001-04-26 23:22:31 +00002235 if (*s == '\\') s++;
2236 cnt++;
2237 }
Denis Vlasenkoc666f712007-05-16 22:18:54 +00002238 dest = xmalloc(cnt);
Eric Andersen25f27032001-04-26 23:22:31 +00002239 if (!(flags & GLOB_APPEND)) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002240 pglob->gl_pathv = NULL;
2241 pglob->gl_pathc = 0;
2242 pglob->gl_offs = 0;
2243 pglob->gl_offs = 0;
Eric Andersen25f27032001-04-26 23:22:31 +00002244 }
2245 pathc = ++pglob->gl_pathc;
Denis Vlasenkoc666f712007-05-16 22:18:54 +00002246 pglob->gl_pathv = xrealloc(pglob->gl_pathv, (pathc+1) * sizeof(*pglob->gl_pathv));
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002247 pglob->gl_pathv[pathc-1] = dest;
2248 pglob->gl_pathv[pathc] = NULL;
2249 for (s = src; s && *s; s++, dest++) {
Eric Andersen25f27032001-04-26 23:22:31 +00002250 if (*s == '\\') s++;
2251 *dest = *s;
2252 }
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002253 *dest = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00002254 return 0;
2255}
2256
2257/* XXX broken if the last character is '\\', check that before calling */
2258static int glob_needed(const char *s)
2259{
2260 for (; *s; s++) {
2261 if (*s == '\\') s++;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002262 if (strchr("*[?", *s)) return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00002263 }
2264 return 0;
2265}
2266
Eric Andersen25f27032001-04-26 23:22:31 +00002267static int xglob(o_string *dest, int flags, glob_t *pglob)
2268{
2269 int gr;
2270
Tim Rikerc1ef7bd2006-01-25 00:08:53 +00002271 /* short-circuit for null word */
Eric Andersen25f27032001-04-26 23:22:31 +00002272 /* we can code this better when the debug_printf's are gone */
Tim Rikerc1ef7bd2006-01-25 00:08:53 +00002273 if (dest->length == 0) {
2274 if (dest->nonnull) {
2275 /* bash man page calls this an "explicit" null */
2276 gr = globhack(dest->data, flags, pglob);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002277 debug_printf("globhack returned %d\n", gr);
Tim Rikerc1ef7bd2006-01-25 00:08:53 +00002278 } else {
Eric Andersen25f27032001-04-26 23:22:31 +00002279 return 0;
2280 }
Tim Rikerc1ef7bd2006-01-25 00:08:53 +00002281 } else if (glob_needed(dest->data)) {
Eric Andersen25f27032001-04-26 23:22:31 +00002282 gr = glob(dest->data, flags, NULL, pglob);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002283 debug_printf("glob returned %d\n", gr);
Eric Andersen25f27032001-04-26 23:22:31 +00002284 if (gr == GLOB_NOMATCH) {
2285 /* quote removal, or more accurately, backslash removal */
2286 gr = globhack(dest->data, flags, pglob);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002287 debug_printf("globhack returned %d\n", gr);
Eric Andersen25f27032001-04-26 23:22:31 +00002288 }
2289 } else {
2290 gr = globhack(dest->data, flags, pglob);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002291 debug_printf("globhack returned %d\n", gr);
Eric Andersen25f27032001-04-26 23:22:31 +00002292 }
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002293 if (gr == GLOB_NOSPACE)
Manuel Novoa III cad53642003-03-19 09:13:01 +00002294 bb_error_msg_and_die("out of memory during glob");
Eric Andersen25f27032001-04-26 23:22:31 +00002295 if (gr != 0) { /* GLOB_ABORTED ? */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002296 bb_error_msg("glob(3) error %d", gr);
Eric Andersen25f27032001-04-26 23:22:31 +00002297 }
2298 /* globprint(glob_target); */
2299 return gr;
2300}
2301
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002302/* expand_variables_to_list() takes a list of strings, expands
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002303 * all variable references within and returns a pointer to
2304 * a list of expanded strings, possibly with larger number
2305 * of strings. (Think VAR="a b"; echo $VAR).
2306 * This new list is allocated as a single malloc block.
2307 * NULL-terminated list of char* pointers is at the beginning of it,
2308 * followed by strings themself.
2309 * Caller can deallocate entire list by single free(list). */
2310
2311/* Helpers first:
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00002312 * count_XXX estimates size of the block we need. It's okay
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002313 * to over-estimate sizes a bit, if it makes code simpler */
2314static int count_ifs(const char *str)
2315{
2316 int cnt = 0;
2317 debug_printf_expand("count_ifs('%s') ifs='%s'", str, ifs);
2318 while (1) {
2319 str += strcspn(str, ifs);
2320 if (!*str) break;
Denis Vlasenkoc666f712007-05-16 22:18:54 +00002321 str++; /* str += strspn(str, ifs); */
2322 cnt++; /* cnt += strspn(str, ifs); - but this code is larger */
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00002323 }
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002324 debug_printf_expand(" return %d\n", cnt);
2325 return cnt;
2326}
2327
2328static void count_var_expansion_space(int *countp, int *lenp, char *arg)
2329{
2330 char first_ch;
2331 int i;
2332 int len = *lenp;
2333 int count = *countp;
2334 const char *val;
2335 char *p;
2336
2337 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL))) {
2338 len += p - arg;
2339 arg = ++p;
2340 p = strchr(p, SPECIAL_VAR_SYMBOL);
2341 first_ch = arg[0];
2342
2343 switch (first_ch & 0x7f) {
2344 /* high bit in 1st_ch indicates that var is double-quoted */
2345 case '$': /* pid */
2346 case '!': /* bg pid */
2347 case '?': /* exitcode */
2348 case '#': /* argc */
2349 len += sizeof(int)*3 + 1; /* enough for int */
2350 break;
2351 case '*':
2352 case '@':
2353 for (i = 1; i < global_argc; i++) {
2354 len += strlen(global_argv[i]) + 1;
2355 count++;
2356 if (!(first_ch & 0x80))
2357 count += count_ifs(global_argv[i]);
2358 }
2359 break;
2360 default:
2361 *p = '\0';
2362 arg[0] = first_ch & 0x7f;
Denis Vlasenko764d59d2007-05-14 16:23:23 +00002363 if (isdigit(arg[0])) {
2364 i = xatoi_u(arg);
2365 val = NULL;
2366 if (i < global_argc)
2367 val = global_argv[i];
2368 } else
2369 val = lookup_param(arg);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002370 arg[0] = first_ch;
2371 *p = SPECIAL_VAR_SYMBOL;
2372
2373 if (val) {
2374 len += strlen(val) + 1;
2375 if (!(first_ch & 0x80))
2376 count += count_ifs(val);
2377 }
2378 }
2379 arg = ++p;
2380 }
2381
2382 len += strlen(arg) + 1;
2383 count++;
2384 *lenp = len;
2385 *countp = count;
2386}
2387
2388/* Store given string, finalizing the word and starting new one whenever
2389 * we encounter ifs char(s). This is used for expanding variable values.
Denis Vlasenko764d59d2007-05-14 16:23:23 +00002390 * End-of-string does NOT finalize word: think about 'echo -$VAR-' */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002391static int expand_on_ifs(char **list, int n, char **posp, const char *str)
2392{
2393 char *pos = *posp;
2394 while (1) {
2395 int word_len = strcspn(str, ifs);
2396 if (word_len) {
2397 memcpy(pos, str, word_len); /* store non-ifs chars */
2398 pos += word_len;
2399 str += word_len;
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002400 }
Denis Vlasenko764d59d2007-05-14 16:23:23 +00002401 if (!*str) /* EOL - do not finalize word */
2402 break;
2403 *pos++ = '\0';
2404 if (n) debug_printf_expand("expand_on_ifs finalized list[%d]=%p '%s' "
2405 "strlen=%d next=%p pos=%p\n", n-1, list[n-1], list[n-1],
2406 strlen(list[n-1]), list[n-1] + strlen(list[n-1]) + 1, pos);
2407 list[n++] = pos;
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002408 str += strspn(str, ifs); /* skip ifs chars */
2409 }
2410 *posp = pos;
2411 return n;
2412}
2413
2414/* Expand all variable references in given string, adding words to list[]
2415 * at n, n+1,... positions. Return updated n (so that list[n] is next one
2416 * to be filled). This routine is extremely tricky: has to deal with
2417 * variables/parameters with whitespace, $* and $@, and constructs like
2418 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002419/* NB: another bug is that we cannot detect empty strings yet:
2420 * "" or $empty"" expands to zero words, has to expand to empty word */
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002421static int expand_vars_to_list(char **list, int n, char **posp, char *arg, char or_mask)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002422{
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002423 /* or_mask is either 0 (normal case) or 0x80
2424 * (expansion of right-hand side of assignment == 1-element expand) */
2425
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002426 char first_ch, ored_ch;
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00002427 int i;
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002428 const char *val;
2429 char *p;
2430 char *pos = *posp;
2431
2432 ored_ch = 0;
2433
2434 if (n) debug_printf_expand("expand_vars_to_list finalized list[%d]=%p '%s' "
2435 "strlen=%d next=%p pos=%p\n", n-1, list[n-1], list[n-1],
2436 strlen(list[n-1]), list[n-1] + strlen(list[n-1]) + 1, pos);
2437 list[n++] = pos;
2438
2439 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL))) {
2440 memcpy(pos, arg, p - arg);
2441 pos += (p - arg);
2442 arg = ++p;
2443 p = strchr(p, SPECIAL_VAR_SYMBOL);
2444
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002445 first_ch = arg[0] | or_mask; /* forced to "quoted" if or_mask = 0x80 */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002446 ored_ch |= first_ch;
2447 val = NULL;
2448 switch (first_ch & 0x7f) {
2449 /* Highest bit in first_ch indicates that var is double-quoted */
2450 case '$': /* pid */
2451 /* FIXME: (echo $$) should still print pid of main shell */
2452 val = utoa(getpid());
2453 break;
2454 case '!': /* bg pid */
2455 val = last_bg_pid ? utoa(last_bg_pid) : (char*)"";
2456 break;
2457 case '?': /* exitcode */
2458 val = utoa(last_return_code);
2459 break;
2460 case '#': /* argc */
2461 val = utoa(global_argc ? global_argc-1 : 0);
2462 break;
2463 case '*':
2464 case '@':
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00002465 i = 1;
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002466 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002467 while (i < global_argc) {
2468 n = expand_on_ifs(list, n, &pos, global_argv[i]);
2469 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, global_argc-1);
2470 if (global_argv[i++][0] && i < global_argc) {
2471 /* this argv[] is not empty and not last:
2472 * put terminating NUL, start new word */
2473 *pos++ = '\0';
2474 if (n) debug_printf_expand("expand_vars_to_list 2 finalized list[%d]=%p '%s' "
2475 "strlen=%d next=%p pos=%p\n", n-1, list[n-1], list[n-1],
2476 strlen(list[n-1]), list[n-1] + strlen(list[n-1]) + 1, pos);
2477 list[n++] = pos;
2478 }
2479 }
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002480 } else
2481 /* If or_mask is nonzero, we handle assignment 'a=....$@.....'
2482 * and in this case should theat it like '$*' */
2483 if (first_ch == ('@'|0x80) && !or_mask) { /* quoted $@ */
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00002484 while (1) {
2485 strcpy(pos, global_argv[i]);
2486 pos += strlen(global_argv[i]);
2487 if (++i >= global_argc)
2488 break;
2489 *pos++ = '\0';
2490 if (n) debug_printf_expand("expand_vars_to_list 3 finalized list[%d]=%p '%s' "
2491 "strlen=%d next=%p pos=%p\n", n-1, list[n-1], list[n-1],
2492 strlen(list[n-1]), list[n-1] + strlen(list[n-1]) + 1, pos);
2493 list[n++] = pos;
2494 }
2495 } else { /* quoted $*: add as one word */
2496 while (1) {
2497 strcpy(pos, global_argv[i]);
2498 pos += strlen(global_argv[i]);
2499 if (++i >= global_argc)
2500 break;
2501 if (ifs[0])
2502 *pos++ = ifs[0];
2503 }
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002504 }
2505 break;
2506 default:
2507 *p = '\0';
2508 arg[0] = first_ch & 0x7f;
Denis Vlasenko764d59d2007-05-14 16:23:23 +00002509 if (isdigit(arg[0])) {
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00002510 i = xatoi_u(arg);
Denis Vlasenko764d59d2007-05-14 16:23:23 +00002511 val = NULL;
2512 if (i < global_argc)
2513 val = global_argv[i];
2514 } else
2515 val = lookup_param(arg);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002516 arg[0] = first_ch;
2517 *p = SPECIAL_VAR_SYMBOL;
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00002518 if (!(first_ch & 0x80)) { /* unquoted $VAR */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002519 if (val) {
2520 n = expand_on_ifs(list, n, &pos, val);
2521 val = NULL;
2522 }
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00002523 } /* else: quoted $VAR, val will be appended at pos */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002524 }
2525 if (val) {
2526 strcpy(pos, val);
2527 pos += strlen(val);
2528 }
2529 arg = ++p;
2530 }
2531 debug_printf_expand("expand_vars_to_list adding tail '%s' at %p\n", arg, pos);
2532 strcpy(pos, arg);
2533 pos += strlen(arg) + 1;
2534 if (pos == list[n-1] + 1) { /* expansion is empty */
2535 if (!(ored_ch & 0x80)) { /* all vars were not quoted... */
2536 debug_printf_expand("expand_vars_to_list list[%d] empty, going back\n", n);
2537 pos--;
2538 n--;
2539 }
2540 }
2541
2542 *posp = pos;
2543 return n;
2544}
2545
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002546static char **expand_variables(char **argv, char or_mask)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002547{
2548 int n;
2549 int count = 1;
2550 int len = 0;
2551 char *pos, **v, **list;
2552
2553 v = argv;
2554 if (!*v) debug_printf_expand("count_var_expansion_space: "
2555 "argv[0]=NULL count=%d len=%d alloc_space=%d\n",
2556 count, len, sizeof(char*) * count + len);
2557 while (*v) {
2558 count_var_expansion_space(&count, &len, *v);
2559 debug_printf_expand("count_var_expansion_space: "
2560 "'%s' count=%d len=%d alloc_space=%d\n",
2561 *v, count, len, sizeof(char*) * count + len);
2562 v++;
2563 }
2564 len += sizeof(char*) * count; /* total to alloc */
2565 list = xmalloc(len);
2566 pos = (char*)(list + count);
2567 debug_printf_expand("list=%p, list[0] should be %p\n", list, pos);
2568 n = 0;
2569 v = argv;
2570 while (*v)
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002571 n = expand_vars_to_list(list, n, &pos, *v++, or_mask);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002572
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002573 if (n) debug_printf_expand("finalized list[%d]=%p '%s' "
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002574 "strlen=%d next=%p pos=%p\n", n-1, list[n-1], list[n-1],
2575 strlen(list[n-1]), list[n-1] + strlen(list[n-1]) + 1, pos);
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00002576 list[n] = NULL;
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002577
2578#ifdef DEBUG_EXPAND
2579 {
2580 int m = 0;
2581 while (m <= n) {
2582 debug_printf_expand("list[%d]=%p '%s'\n", m, list[m], list[m]);
2583 m++;
2584 }
2585 debug_printf_expand("used_space=%d\n", pos - (char*)list);
2586 }
2587#endif
2588 /* To be removed / made conditional later. */
2589 if (pos - (char*)list > len)
2590 bb_error_msg_and_die("BUG in varexp");
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00002591 return list;
2592}
2593
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002594static char **expand_variables_to_list(char **argv)
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00002595{
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002596 return expand_variables(argv, 0);
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00002597}
2598
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002599static char *expand_variables_to_string(const char *str)
2600{
2601 char *argv[2], **list;
2602
2603 argv[0] = (char*)str;
2604 argv[1] = NULL;
2605 list = expand_variables(argv, 0x80); /* 0x80: make one-element expansion */
2606 /* To be removed / made conditional later. */
2607 if (!list[0] || list[1])
2608 bb_error_msg_and_die("BUG in varexp");
2609 /* actually, just move string 2*sizeof(char*) bytes back */
2610 strcpy((char*)list, list[0]);
2611 return (char*)list;
2612}
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002613
Eric Andersenf72f5622001-05-15 23:21:41 +00002614/* This is used to get/check local shell variables */
Denis Vlasenko15d78fb2007-01-30 22:28:21 +00002615static const char *get_local_var(const char *s)
Eric Andersenf72f5622001-05-15 23:21:41 +00002616{
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002617 struct variables *cur;
Eric Andersenf72f5622001-05-15 23:21:41 +00002618
2619 if (!s)
2620 return NULL;
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00002621 for (cur = top_vars; cur; cur = cur->next) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002622 if (strcmp(cur->name, s) == 0)
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002623 return cur->value;
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00002624 }
Eric Andersenf72f5622001-05-15 23:21:41 +00002625 return NULL;
2626}
2627
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002628/* This is used to set local shell variables
Denis Vlasenkobb81c582007-01-30 22:32:09 +00002629 flg_export == 0 if only local (not exporting) variable
2630 flg_export == 1 if "new" exporting environ
2631 flg_export > 1 if current startup environ (not call putenv()) */
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002632static int set_local_var(const char *s, int flg_export)
Eric Andersen78a7c992001-05-15 16:30:25 +00002633{
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002634 char *name, *value;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002635 int result = 0;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002636 struct variables *cur;
Eric Andersen20a69a72001-05-15 17:24:44 +00002637
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00002638 name = xstrdup(s);
Eric Andersen20a69a72001-05-15 17:24:44 +00002639
2640 /* Assume when we enter this function that we are already in
2641 * NAME=VALUE format. So the first order of business is to
Eric Andersenc7bda1c2004-03-15 08:29:22 +00002642 * split 's' on the '=' into 'name' and 'value' */
Eric Andersen20a69a72001-05-15 17:24:44 +00002643 value = strchr(name, '=');
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00002644 /*if (value == 0 && ++value == 0) ??? -vda */
2645 if (value == NULL || value[1] == '\0') {
Eric Andersen99785762001-05-22 21:37:48 +00002646 free(name);
2647 return -1;
2648 }
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00002649 *value++ = '\0';
Eric Andersen20a69a72001-05-15 17:24:44 +00002650
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002651 for (cur = top_vars; cur; cur = cur->next) {
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00002652 if (strcmp(cur->name, name) == 0) {
2653 if (strcmp(cur->value, value) == 0) {
Denis Vlasenko3e7b0e62007-05-16 12:52:15 +00002654 if (flg_export && !cur->flg_export)
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00002655 cur->flg_export = flg_export;
2656 else
2657 result++;
2658 } else if (cur->flg_read_only) {
2659 bb_error_msg("%s: readonly variable", name);
Eric Andersen99785762001-05-22 21:37:48 +00002660 result = -1;
2661 } else {
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00002662 if (flg_export > 0 || cur->flg_export > 1)
2663 cur->flg_export = 1;
2664 free((char*)cur->value);
Denis Vlasenkoc666f712007-05-16 22:18:54 +00002665 cur->value = xstrdup(value);
Eric Andersen20a69a72001-05-15 17:24:44 +00002666 }
Denis Vlasenko3e7b0e62007-05-16 12:52:15 +00002667 goto skip;
Eric Andersen20a69a72001-05-15 17:24:44 +00002668 }
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002669 }
Eric Andersen20a69a72001-05-15 17:24:44 +00002670
Denis Vlasenkoc666f712007-05-16 22:18:54 +00002671 cur = xzalloc(sizeof(*cur));
2672 cur->name = xstrdup(name);
2673 cur->value = xstrdup(value);
2674 /*cur->next = 0;*/
2675 cur->flg_export = flg_export;
2676 /*cur->flg_read_only = 0;*/
2677 {
2678 struct variables *bottom = top_vars;
2679 while (bottom->next)
2680 bottom = bottom->next;
2681 bottom->next = cur;
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00002682 }
2683 skip:
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002684 if (result == 0 && cur->flg_export == 1) {
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002685 *(value-1) = '=';
2686 result = putenv(name);
2687 } else {
Eric Andersen94ac2442001-05-22 19:05:18 +00002688 free(name);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002689 if (result > 0) /* equivalent to previous set */
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002690 result = 0;
2691 }
Eric Andersen20a69a72001-05-15 17:24:44 +00002692 return result;
2693}
2694
Eric Andersenf72f5622001-05-15 23:21:41 +00002695static void unset_local_var(const char *name)
Eric Andersen20a69a72001-05-15 17:24:44 +00002696{
Denis Vlasenko5f786c22007-04-20 08:35:45 +00002697 struct variables *cur, *next;
Eric Andersen20a69a72001-05-15 17:24:44 +00002698
Denis Vlasenko5f786c22007-04-20 08:35:45 +00002699 if (!name)
2700 return;
2701 for (cur = top_vars; cur; cur = cur->next) {
2702 if (strcmp(cur->name, name) == 0) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002703 if (cur->flg_read_only) {
Manuel Novoa III cad53642003-03-19 09:13:01 +00002704 bb_error_msg("%s: readonly variable", name);
Eric Andersen94ac2442001-05-22 19:05:18 +00002705 return;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002706 }
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002707 if (cur->flg_export)
2708 unsetenv(cur->name);
2709 free((char*)cur->name);
2710 free((char*)cur->value);
Denis Vlasenko5f786c22007-04-20 08:35:45 +00002711 next = top_vars;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002712 while (next->next != cur)
2713 next = next->next;
2714 next->next = cur->next;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002715 free(cur);
Denis Vlasenko5f786c22007-04-20 08:35:45 +00002716 return;
Eric Andersenf72f5622001-05-15 23:21:41 +00002717 }
Eric Andersen20a69a72001-05-15 17:24:44 +00002718 }
Eric Andersen78a7c992001-05-15 16:30:25 +00002719}
2720
2721static int is_assignment(const char *s)
2722{
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002723 if (!s || !isalpha(*s))
2724 return 0;
2725 s++;
2726 while (isalnum(*s) || *s == '_')
2727 s++;
2728 return *s == '=';
Eric Andersen78a7c992001-05-15 16:30:25 +00002729}
2730
Eric Andersen25f27032001-04-26 23:22:31 +00002731/* the src parameter allows us to peek forward to a possible &n syntax
2732 * for file descriptor duplication, e.g., "2>&1".
2733 * Return code is 0 normally, 1 if a syntax error is detected in src.
2734 * Resource errors (in xmalloc) cause the process to exit */
2735static int setup_redirect(struct p_context *ctx, int fd, redir_type style,
2736 struct in_str *input)
2737{
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002738 struct child_prog *child = ctx->child;
Eric Andersen25f27032001-04-26 23:22:31 +00002739 struct redir_struct *redir = child->redirects;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002740 struct redir_struct *last_redir = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00002741
2742 /* Create a new redir_struct and drop it onto the end of the linked list */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002743 while (redir) {
2744 last_redir = redir;
2745 redir = redir->next;
Eric Andersen25f27032001-04-26 23:22:31 +00002746 }
2747 redir = xmalloc(sizeof(struct redir_struct));
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002748 redir->next = NULL;
2749 redir->word.gl_pathv = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00002750 if (last_redir) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002751 last_redir->next = redir;
Eric Andersen25f27032001-04-26 23:22:31 +00002752 } else {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002753 child->redirects = redir;
Eric Andersen25f27032001-04-26 23:22:31 +00002754 }
2755
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002756 redir->type = style;
2757 redir->fd = (fd == -1) ? redir_table[style].default_fd : fd;
Eric Andersen25f27032001-04-26 23:22:31 +00002758
2759 debug_printf("Redirect type %d%s\n", redir->fd, redir_table[style].descrip);
2760
Eric Andersenc7bda1c2004-03-15 08:29:22 +00002761 /* Check for a '2>&1' type redirect */
Eric Andersen25f27032001-04-26 23:22:31 +00002762 redir->dup = redirect_dup_num(input);
2763 if (redir->dup == -2) return 1; /* syntax error */
2764 if (redir->dup != -1) {
2765 /* Erik had a check here that the file descriptor in question
Eric Andersen83a2ae22001-05-07 17:59:25 +00002766 * is legit; I postpone that to "run time"
2767 * A "-" representation of "close me" shows up as a -3 here */
Eric Andersen25f27032001-04-26 23:22:31 +00002768 debug_printf("Duplicating redirect '%d>&%d'\n", redir->fd, redir->dup);
2769 } else {
2770 /* We do _not_ try to open the file that src points to,
2771 * since we need to return and let src be expanded first.
2772 * Set ctx->pending_redirect, so we know what to do at the
2773 * end of the next parsed word.
2774 */
2775 ctx->pending_redirect = redir;
2776 }
2777 return 0;
2778}
2779
Denis Vlasenkoac678ec2007-04-16 22:32:04 +00002780static struct pipe *new_pipe(void)
2781{
Eric Andersen25f27032001-04-26 23:22:31 +00002782 struct pipe *pi;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00002783 pi = xzalloc(sizeof(struct pipe));
2784 /*pi->num_progs = 0;*/
2785 /*pi->progs = NULL;*/
2786 /*pi->next = NULL;*/
2787 /*pi->followup = 0; invalid */
2788 if (RES_NONE)
2789 pi->r_mode = RES_NONE;
Eric Andersen25f27032001-04-26 23:22:31 +00002790 return pi;
2791}
2792
2793static void initialize_context(struct p_context *ctx)
2794{
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002795 ctx->pipe = NULL;
2796 ctx->pending_redirect = NULL;
2797 ctx->child = NULL;
2798 ctx->list_head = new_pipe();
2799 ctx->pipe = ctx->list_head;
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002800 ctx->res_w = RES_NONE;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002801 ctx->stack = NULL;
2802 ctx->old_flag = 0;
Eric Andersen25f27032001-04-26 23:22:31 +00002803 done_command(ctx); /* creates the memory for working child */
2804}
2805
2806/* normal return is 0
2807 * if a reserved word is found, and processed, return 1
2808 * should handle if, then, elif, else, fi, for, while, until, do, done.
2809 * case, function, and select are obnoxious, save those for later.
2810 */
"Vladimir N. Oleynik"19c37012005-09-22 14:33:15 +00002811static int reserved_word(o_string *dest, struct p_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00002812{
2813 struct reserved_combo {
Denis Vlasenko5f786c22007-04-20 08:35:45 +00002814 char literal[7];
2815 unsigned char code;
2816 int flag;
Eric Andersen25f27032001-04-26 23:22:31 +00002817 };
2818 /* Mostly a list of accepted follow-up reserved words.
2819 * FLAG_END means we are done with the sequence, and are ready
2820 * to turn the compound list into a command.
2821 * FLAG_START means the word must start a new compound list.
2822 */
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00002823 static const struct reserved_combo reserved_list[] = {
Eric Andersen25f27032001-04-26 23:22:31 +00002824 { "if", RES_IF, FLAG_THEN | FLAG_START },
2825 { "then", RES_THEN, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
2826 { "elif", RES_ELIF, FLAG_THEN },
2827 { "else", RES_ELSE, FLAG_FI },
2828 { "fi", RES_FI, FLAG_END },
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002829 { "for", RES_FOR, FLAG_IN | FLAG_START },
Eric Andersen25f27032001-04-26 23:22:31 +00002830 { "while", RES_WHILE, FLAG_DO | FLAG_START },
2831 { "until", RES_UNTIL, FLAG_DO | FLAG_START },
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002832 { "in", RES_IN, FLAG_DO },
Eric Andersen25f27032001-04-26 23:22:31 +00002833 { "do", RES_DO, FLAG_DONE },
2834 { "done", RES_DONE, FLAG_END }
2835 };
Denis Vlasenko7d4c44e2007-04-16 22:34:39 +00002836 enum { NRES = sizeof(reserved_list)/sizeof(reserved_list[0]) };
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00002837 const struct reserved_combo *r;
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00002838
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002839 for (r = reserved_list; r < reserved_list + NRES; r++) {
Eric Andersen25f27032001-04-26 23:22:31 +00002840 if (strcmp(dest->data, r->literal) == 0) {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00002841 debug_printf("found reserved word %s, code %d\n", r->literal, r->code);
Eric Andersen25f27032001-04-26 23:22:31 +00002842 if (r->flag & FLAG_START) {
2843 struct p_context *new = xmalloc(sizeof(struct p_context));
2844 debug_printf("push stack\n");
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002845 if (ctx->res_w == RES_IN || ctx->res_w == RES_FOR) {
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002846 syntax();
2847 free(new);
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002848 ctx->res_w = RES_SNTX;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002849 b_reset(dest);
2850 return 1;
2851 }
Eric Andersen25f27032001-04-26 23:22:31 +00002852 *new = *ctx; /* physical copy */
2853 initialize_context(ctx);
Denis Vlasenkobb81c582007-01-30 22:32:09 +00002854 ctx->stack = new;
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002855 } else if (ctx->res_w == RES_NONE || !(ctx->old_flag & (1 << r->code))) {
Eric Andersenaf44a0e2001-04-27 07:26:12 +00002856 syntax();
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002857 ctx->res_w = RES_SNTX;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002858 b_reset(dest);
Eric Andersenaf44a0e2001-04-27 07:26:12 +00002859 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00002860 }
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002861 ctx->res_w = r->code;
Eric Andersen25f27032001-04-26 23:22:31 +00002862 ctx->old_flag = r->flag;
2863 if (ctx->old_flag & FLAG_END) {
2864 struct p_context *old;
2865 debug_printf("pop stack\n");
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00002866 done_pipe(ctx, PIPE_SEQ);
Eric Andersen25f27032001-04-26 23:22:31 +00002867 old = ctx->stack;
2868 old->child->group = ctx->list_head;
Eric Andersen04407e52001-06-07 16:42:05 +00002869 old->child->subshell = 0;
Eric Andersen25f27032001-04-26 23:22:31 +00002870 *ctx = *old; /* physical copy */
2871 free(old);
Eric Andersen25f27032001-04-26 23:22:31 +00002872 }
Denis Vlasenkoff131b92007-04-10 15:42:06 +00002873 b_reset(dest);
Eric Andersen25f27032001-04-26 23:22:31 +00002874 return 1;
2875 }
2876 }
2877 return 0;
2878}
2879
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00002880/* Normal return is 0.
Eric Andersen25f27032001-04-26 23:22:31 +00002881 * Syntax or xglob errors return 1. */
2882static int done_word(o_string *dest, struct p_context *ctx)
2883{
Denis Vlasenkobb81c582007-01-30 22:32:09 +00002884 struct child_prog *child = ctx->child;
Eric Andersen25f27032001-04-26 23:22:31 +00002885 glob_t *glob_target;
2886 int gr, flags = 0;
2887
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002888 debug_printf_parse("done_word entered: '%s' %p\n", dest->data, child);
Eric Andersen25f27032001-04-26 23:22:31 +00002889 if (dest->length == 0 && !dest->nonnull) {
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00002890 debug_printf_parse("done_word return 0: true null, ignored\n");
Eric Andersen25f27032001-04-26 23:22:31 +00002891 return 0;
2892 }
2893 if (ctx->pending_redirect) {
2894 glob_target = &ctx->pending_redirect->word;
2895 } else {
2896 if (child->group) {
2897 syntax();
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00002898 debug_printf_parse("done_word return 1: syntax error, groups and arglists don't mix\n");
2899 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00002900 }
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002901 if (!child->argv && (ctx->parse_type & FLAG_PARSE_SEMICOLON)) {
2902 debug_printf_parse(": checking '%s' for reserved-ness\n", dest->data);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00002903 if (reserved_word(dest, ctx)) {
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002904 debug_printf_parse("done_word return %d\n", (ctx->res_w == RES_SNTX));
2905 return (ctx->res_w == RES_SNTX);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00002906 }
Eric Andersen25f27032001-04-26 23:22:31 +00002907 }
2908 glob_target = &child->glob_result;
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002909 if (child->argv)
2910 flags |= GLOB_APPEND;
Eric Andersen25f27032001-04-26 23:22:31 +00002911 }
2912 gr = xglob(dest, flags, glob_target);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00002913 if (gr != 0) {
2914 debug_printf_parse("done_word return 1: xglob returned %d\n", gr);
2915 return 1;
2916 }
Eric Andersen25f27032001-04-26 23:22:31 +00002917
2918 b_reset(dest);
2919 if (ctx->pending_redirect) {
Denis Vlasenkobb81c582007-01-30 22:32:09 +00002920 ctx->pending_redirect = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00002921 if (glob_target->gl_pathc != 1) {
Manuel Novoa III cad53642003-03-19 09:13:01 +00002922 bb_error_msg("ambiguous redirect");
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00002923 debug_printf_parse("done_word return 1: ambiguous redirect\n");
Eric Andersen25f27032001-04-26 23:22:31 +00002924 return 1;
2925 }
2926 } else {
2927 child->argv = glob_target->gl_pathv;
2928 }
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002929 if (ctx->res_w == RES_FOR) {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00002930 done_word(dest, ctx);
2931 done_pipe(ctx, PIPE_SEQ);
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002932 }
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00002933 debug_printf_parse("done_word return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00002934 return 0;
2935}
2936
2937/* The only possible error here is out of memory, in which case
2938 * xmalloc exits. */
2939static int done_command(struct p_context *ctx)
2940{
2941 /* The child is really already in the pipe structure, so
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002942 * advance the pipe counter and make a new, null child. */
Denis Vlasenkobb81c582007-01-30 22:32:09 +00002943 struct pipe *pi = ctx->pipe;
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002944 struct child_prog *child = ctx->child;
Eric Andersen25f27032001-04-26 23:22:31 +00002945
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002946 if (child) {
2947 if (child->group == NULL
2948 && child->argv == NULL
2949 && child->redirects == NULL
2950 ) {
Denis Vlasenkodd4cb2b2007-05-05 15:11:40 +00002951 debug_printf_parse("done_command: skipping null cmd, num_progs=%d\n", pi->num_progs);
2952 return pi->num_progs;
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002953 }
Eric Andersen25f27032001-04-26 23:22:31 +00002954 pi->num_progs++;
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002955 debug_printf_parse("done_command: ++num_progs=%d\n", pi->num_progs);
Eric Andersen25f27032001-04-26 23:22:31 +00002956 } else {
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002957 debug_printf_parse("done_command: initializing, num_progs=%d\n", pi->num_progs);
Eric Andersen25f27032001-04-26 23:22:31 +00002958 }
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002959
2960 /* Only real trickiness here is that the uncommitted
2961 * child structure is not counted in pi->num_progs. */
Eric Andersen25f27032001-04-26 23:22:31 +00002962 pi->progs = xrealloc(pi->progs, sizeof(*pi->progs) * (pi->num_progs+1));
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002963 child = &pi->progs[pi->num_progs];
Eric Andersen25f27032001-04-26 23:22:31 +00002964
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002965 memset(child, 0, sizeof(*child));
2966 /*child->redirects = NULL;*/
2967 /*child->argv = NULL;*/
2968 /*child->is_stopped = 0;*/
2969 /*child->group = NULL;*/
2970 /*child->glob_result.gl_pathv = NULL;*/
2971 child->family = pi;
Denis Vlasenkoc666f712007-05-16 22:18:54 +00002972 //sp: /*child->sp = 0;*/
Denis Vlasenko262d7652007-05-20 21:52:49 +00002973 //pt: child->parse_type = ctx->parse_type;
Eric Andersen25f27032001-04-26 23:22:31 +00002974
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002975 ctx->child = child;
Eric Andersen25f27032001-04-26 23:22:31 +00002976 /* but ctx->pipe and ctx->list_head remain unchanged */
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002977
Denis Vlasenkodd4cb2b2007-05-05 15:11:40 +00002978 return pi->num_progs; /* used only for 0/nonzero check */
Eric Andersen25f27032001-04-26 23:22:31 +00002979}
2980
2981static int done_pipe(struct p_context *ctx, pipe_style type)
2982{
2983 struct pipe *new_p;
Denis Vlasenkodd4cb2b2007-05-05 15:11:40 +00002984 int not_null;
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002985
2986 debug_printf_parse("done_pipe entered, followup %d\n", type);
Denis Vlasenkodd4cb2b2007-05-05 15:11:40 +00002987 not_null = done_command(ctx); /* implicit closure of previous command */
Eric Andersen25f27032001-04-26 23:22:31 +00002988 ctx->pipe->followup = type;
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002989 ctx->pipe->r_mode = ctx->res_w;
Denis Vlasenkodd4cb2b2007-05-05 15:11:40 +00002990 /* Without this check, even just <enter> on command line generates
2991 * tree of three NOPs (!). Which is harmless but annoying.
2992 * IOW: it is safe to do it unconditionally. */
2993 if (not_null) {
2994 new_p = new_pipe();
2995 ctx->pipe->next = new_p;
2996 ctx->pipe = new_p;
2997 ctx->child = NULL;
2998 done_command(ctx); /* set up new pipe to accept commands */
2999 }
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003000 debug_printf_parse("done_pipe return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003001 return 0;
3002}
3003
3004/* peek ahead in the in_str to find out if we have a "&n" construct,
3005 * as in "2>&1", that represents duplicating a file descriptor.
3006 * returns either -2 (syntax error), -1 (no &), or the number found.
3007 */
3008static int redirect_dup_num(struct in_str *input)
3009{
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003010 int ch, d = 0, ok = 0;
Eric Andersen25f27032001-04-26 23:22:31 +00003011 ch = b_peek(input);
3012 if (ch != '&') return -1;
3013
3014 b_getch(input); /* get the & */
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003015 ch = b_peek(input);
Eric Andersen83a2ae22001-05-07 17:59:25 +00003016 if (ch == '-') {
3017 b_getch(input);
3018 return -3; /* "-" represents "close me" */
3019 }
3020 while (isdigit(ch)) {
Denis Vlasenko7d4c44e2007-04-16 22:34:39 +00003021 d = d*10 + (ch-'0');
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003022 ok = 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003023 b_getch(input);
Eric Andersen83a2ae22001-05-07 17:59:25 +00003024 ch = b_peek(input);
Eric Andersen25f27032001-04-26 23:22:31 +00003025 }
3026 if (ok) return d;
3027
Manuel Novoa III cad53642003-03-19 09:13:01 +00003028 bb_error_msg("ambiguous redirect");
Eric Andersen25f27032001-04-26 23:22:31 +00003029 return -2;
3030}
3031
3032/* If a redirect is immediately preceded by a number, that number is
3033 * supposed to tell which file descriptor to redirect. This routine
3034 * looks for such preceding numbers. In an ideal world this routine
3035 * needs to handle all the following classes of redirects...
3036 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
3037 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
3038 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
3039 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
3040 * A -1 output from this program means no valid number was found, so the
3041 * caller should use the appropriate default for this redirection.
3042 */
3043static int redirect_opt_num(o_string *o)
3044{
3045 int num;
3046
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003047 if (o->length == 0)
3048 return -1;
3049 for (num = 0; num < o->length; num++) {
3050 if (!isdigit(*(o->data + num))) {
Eric Andersen25f27032001-04-26 23:22:31 +00003051 return -1;
3052 }
3053 }
3054 /* reuse num (and save an int) */
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003055 num = atoi(o->data);
Eric Andersen25f27032001-04-26 23:22:31 +00003056 b_reset(o);
3057 return num;
3058}
3059
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003060#if ENABLE_HUSH_TICK
"Vladimir N. Oleynik"19c37012005-09-22 14:33:15 +00003061static FILE *generate_stream_from_list(struct pipe *head)
Eric Andersen25f27032001-04-26 23:22:31 +00003062{
3063 FILE *pf;
Eric Andersen25f27032001-04-26 23:22:31 +00003064 int pid, channel[2];
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003065 if (pipe(channel) < 0) bb_perror_msg_and_die("pipe");
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00003066#if BB_MMU
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003067 pid = fork();
Eric Andersen72f9a422001-10-28 05:12:20 +00003068#else
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003069 pid = vfork();
Eric Andersen72f9a422001-10-28 05:12:20 +00003070#endif
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003071 if (pid < 0) {
Manuel Novoa III cad53642003-03-19 09:13:01 +00003072 bb_perror_msg_and_die("fork");
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003073 } else if (pid == 0) {
Eric Andersen25f27032001-04-26 23:22:31 +00003074 close(channel[0]);
3075 if (channel[1] != 1) {
Denis Vlasenko7d4c44e2007-04-16 22:34:39 +00003076 dup2(channel[1], 1);
Eric Andersen25f27032001-04-26 23:22:31 +00003077 close(channel[1]);
3078 }
Eric Andersen94ac2442001-05-22 19:05:18 +00003079 _exit(run_list_real(head)); /* leaks memory */
Eric Andersen25f27032001-04-26 23:22:31 +00003080 }
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003081 debug_printf("forked child %d\n", pid);
Eric Andersen25f27032001-04-26 23:22:31 +00003082 close(channel[1]);
Denis Vlasenko5f786c22007-04-20 08:35:45 +00003083 pf = fdopen(channel[0], "r");
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003084 debug_printf("pipe on FILE *%p\n", pf);
Eric Andersen25f27032001-04-26 23:22:31 +00003085 return pf;
3086}
3087
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003088/* Return code is exit status of the process that is run. */
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003089static int process_command_subs(o_string *dest, struct p_context *ctx,
3090 struct in_str *input, const char *subst_end)
Eric Andersen25f27032001-04-26 23:22:31 +00003091{
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00003092 int retcode, ch, eol_cnt;
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003093 o_string result = NULL_O_STRING;
Eric Andersen25f27032001-04-26 23:22:31 +00003094 struct p_context inner;
3095 FILE *p;
3096 struct in_str pipe_str;
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00003097
Eric Andersen25f27032001-04-26 23:22:31 +00003098 initialize_context(&inner);
3099
3100 /* recursion to generate command */
3101 retcode = parse_stream(&result, &inner, input, subst_end);
3102 if (retcode != 0) return retcode; /* syntax error or EOF */
3103 done_word(&result, &inner);
3104 done_pipe(&inner, PIPE_SEQ);
3105 b_free(&result);
3106
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003107 p = generate_stream_from_list(inner.list_head);
3108 if (p == NULL) return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003109 mark_open(fileno(p));
3110 setup_file_in_str(&pipe_str, p);
3111
3112 /* now send results of command back into original context */
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00003113 eol_cnt = 0;
3114 while ((ch = b_getch(&pipe_str)) != EOF) {
3115 if (ch == '\n') {
3116 eol_cnt++;
3117 continue;
3118 }
3119 while (eol_cnt) {
3120 b_addqchr(dest, '\n', dest->quote);
3121 eol_cnt--;
3122 }
3123 b_addqchr(dest, ch, dest->quote);
Eric Andersen25f27032001-04-26 23:22:31 +00003124 }
3125
3126 debug_printf("done reading from pipe, pclose()ing\n");
3127 /* This is the step that wait()s for the child. Should be pretty
3128 * safe, since we just read an EOF from its stdout. We could try
Denis Vlasenko262d7652007-05-20 21:52:49 +00003129 * to do better, by using wait(), and keeping track of background jobs
Eric Andersen25f27032001-04-26 23:22:31 +00003130 * at the same time. That would be a lot of work, and contrary
3131 * to the KISS philosophy of this program. */
3132 mark_closed(fileno(p));
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003133 retcode = pclose(p);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003134 free_pipe_list(inner.list_head, 0);
3135 debug_printf("pclosed, retcode=%d\n", retcode);
Eric Andersen25f27032001-04-26 23:22:31 +00003136 return retcode;
3137}
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003138#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003139
3140static int parse_group(o_string *dest, struct p_context *ctx,
3141 struct in_str *input, int ch)
3142{
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003143 int rcode;
3144 const char *endch = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00003145 struct p_context sub;
3146 struct child_prog *child = ctx->child;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003147
3148 debug_printf_parse("parse_group entered\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003149 if (child->argv) {
3150 syntax();
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003151 debug_printf_parse("parse_group return 1: syntax error, groups and arglists don't mix\n");
3152 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003153 }
3154 initialize_context(&sub);
Denis Vlasenkobf0a2012006-12-26 10:42:51 +00003155 switch (ch) {
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003156 case '(':
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003157 endch = ")";
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003158 child->subshell = 1;
3159 break;
3160 case '{':
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003161 endch = "}";
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003162 break;
3163 default:
3164 syntax(); /* really logic error */
Eric Andersen25f27032001-04-26 23:22:31 +00003165 }
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003166 rcode = parse_stream(dest, &sub, input, endch);
3167 done_word(dest, &sub); /* finish off the final word in the subcontext */
Eric Andersen25f27032001-04-26 23:22:31 +00003168 done_pipe(&sub, PIPE_SEQ); /* and the final command there, too */
3169 child->group = sub.list_head;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003170
3171 debug_printf_parse("parse_group return %d\n", rcode);
Eric Andersen25f27032001-04-26 23:22:31 +00003172 return rcode;
3173 /* child remains "open", available for possible redirects */
3174}
3175
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003176/* Basically useful version until someone wants to get fancier,
Eric Andersen25f27032001-04-26 23:22:31 +00003177 * see the bash man page under "Parameter Expansion" */
Denis Vlasenko15d78fb2007-01-30 22:28:21 +00003178static const char *lookup_param(const char *src)
Eric Andersen25f27032001-04-26 23:22:31 +00003179{
Denis Vlasenko15d78fb2007-01-30 22:28:21 +00003180 const char *p = NULL;
Eric Andersenc7bda1c2004-03-15 08:29:22 +00003181 if (src) {
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003182 p = getenv(src);
Eric Andersenc7bda1c2004-03-15 08:29:22 +00003183 if (!p)
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003184 p = get_local_var(src);
Eric Andersen20a69a72001-05-15 17:24:44 +00003185 }
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003186 return p;
Eric Andersen25f27032001-04-26 23:22:31 +00003187}
3188
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00003189/* Make new string for parser */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00003190static char* make_string(char **inp)
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00003191{
3192 char *p;
3193 char *str = NULL;
3194 int n;
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003195 int val_len;
3196 int len = 0;
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00003197
3198 for (n = 0; inp[n]; n++) {
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00003199 p = expand_variables_to_string(inp[n]);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003200 val_len = strlen(p);
3201 str = xrealloc(str, len + val_len + 3); /* +3: space, '\n', <nul>*/
3202 str[len++] = ' ';
3203 strcpy(str + len, p);
3204 len += val_len;
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00003205 if (p != inp[n]) free(p);
3206 }
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003207 /* We do not check for case where loop had no iterations at all
3208 * - cannot happen? */
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00003209 str[len] = '\n';
3210 str[len+1] = '\0';
3211 return str;
3212}
3213
Eric Andersen25f27032001-04-26 23:22:31 +00003214/* return code: 0 for OK, 1 for syntax error */
3215static int handle_dollar(o_string *dest, struct p_context *ctx, struct in_str *input)
3216{
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003217 int ch = b_peek(input); /* first character after the $ */
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00003218 unsigned char quote_mask = dest->quote ? 0x80 : 0;
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003219
3220 debug_printf_parse("handle_dollar entered: ch='%c'\n", ch);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00003221 if (isalpha(ch)) {
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003222 b_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003223 //sp: ctx->child->sp++;
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003224 while (1) {
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003225 debug_printf_parse(": '%c'\n", ch);
Eric Andersen25f27032001-04-26 23:22:31 +00003226 b_getch(input);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00003227 b_addchr(dest, ch | quote_mask);
3228 quote_mask = 0;
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003229 ch = b_peek(input);
3230 if (!isalnum(ch) && ch != '_')
3231 break;
Eric Andersen25f27032001-04-26 23:22:31 +00003232 }
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003233 b_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00003234 } else if (isdigit(ch)) {
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003235 make_one_char_var:
3236 b_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003237 //sp: ctx->child->sp++;
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003238 debug_printf_parse(": '%c'\n", ch);
3239 b_getch(input);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00003240 b_addchr(dest, ch | quote_mask);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003241 b_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00003242 } else switch (ch) {
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003243 case '$': /* pid */
3244 case '!': /* last bg pid */
3245 case '?': /* last exit code */
3246 case '#': /* number of args */
3247 case '*': /* args */
3248 case '@': /* args */
3249 goto make_one_char_var;
Eric Andersen25f27032001-04-26 23:22:31 +00003250 case '{':
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003251 b_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003252 //sp: ctx->child->sp++;
Eric Andersen25f27032001-04-26 23:22:31 +00003253 b_getch(input);
3254 /* XXX maybe someone will try to escape the '}' */
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003255 while (1) {
3256 ch = b_getch(input);
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003257 if (ch == EOF) {
3258 syntax();
3259 debug_printf_parse("handle_dollar return 1: unterminated ${name}\n");
3260 return 1;
3261 }
3262 if (ch == '}')
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003263 break;
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003264 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00003265 b_addchr(dest, ch | quote_mask);
3266 quote_mask = 0;
Eric Andersen25f27032001-04-26 23:22:31 +00003267 }
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003268 b_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00003269 break;
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003270#if ENABLE_HUSH_TICK
Eric Andersen25f27032001-04-26 23:22:31 +00003271 case '(':
Matt Kraai9f8caf12001-05-02 16:26:12 +00003272 b_getch(input);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003273 process_command_subs(dest, ctx, input, ")");
Eric Andersen25f27032001-04-26 23:22:31 +00003274 break;
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003275#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003276 case '-':
3277 case '_':
3278 /* still unhandled, but should be eventually */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003279 bb_error_msg("unhandled syntax: $%c", ch);
Eric Andersen25f27032001-04-26 23:22:31 +00003280 return 1;
3281 break;
3282 default:
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003283 b_addqchr(dest, '$', dest->quote);
Eric Andersen25f27032001-04-26 23:22:31 +00003284 }
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003285 debug_printf_parse("handle_dollar return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003286 return 0;
3287}
3288
Eric Andersen25f27032001-04-26 23:22:31 +00003289/* return code is 0 for normal exit, 1 for syntax error */
Denis Vlasenko5f786c22007-04-20 08:35:45 +00003290static int parse_stream(o_string *dest, struct p_context *ctx,
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003291 struct in_str *input, const char *end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00003292{
"Vladimir N. Oleynik"4ccd2b42006-01-31 09:27:48 +00003293 int ch, m;
Eric Andersen25f27032001-04-26 23:22:31 +00003294 int redir_fd;
3295 redir_type redir_style;
3296 int next;
3297
3298 /* Only double-quote state is handled in the state variable dest->quote.
3299 * A single-quote triggers a bypass of the main loop until its mate is
3300 * found. When recursing, quote state is passed in via dest->quote. */
3301
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003302 debug_printf_parse("parse_stream entered, end_trigger='%s'\n", end_trigger);
3303
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003304 while ((ch = b_getch(input)) != EOF) {
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003305 m = charmap[ch];
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003306 next = (ch == '\n') ? '\0' : b_peek(input);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003307 debug_printf_parse(": ch=%c (%d) m=%d quote=%d\n",
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003308 ch, ch, m, dest->quote);
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003309 if (m == CHAR_ORDINARY
3310 || (m != CHAR_SPECIAL && dest->quote)
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003311 ) {
Eric Andersen25f27032001-04-26 23:22:31 +00003312 b_addqchr(dest, ch, dest->quote);
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003313 continue;
3314 }
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003315 if (m == CHAR_IFS) {
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003316 if (done_word(dest, ctx)) {
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003317 debug_printf_parse("parse_stream return 1: done_word!=0\n");
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003318 return 1;
Eric Andersenaac75e52001-04-30 18:18:45 +00003319 }
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003320 /* If we aren't performing a substitution, treat
3321 * a newline as a command separator.
3322 * [why we don't handle it exactly like ';'? --vda] */
3323 if (end_trigger && ch == '\n') {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003324 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003325 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003326 }
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003327 if ((end_trigger && strchr(end_trigger, ch))
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003328 && !dest->quote && ctx->res_w == RES_NONE
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003329 ) {
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003330 debug_printf_parse("parse_stream return 0: end_trigger char found\n");
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003331 return 0;
3332 }
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003333 if (m == CHAR_IFS)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003334 continue;
3335 switch (ch) {
Eric Andersen25f27032001-04-26 23:22:31 +00003336 case '#':
3337 if (dest->length == 0 && !dest->quote) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003338 while (1) {
3339 ch = b_peek(input);
3340 if (ch == EOF || ch == '\n')
3341 break;
3342 b_getch(input);
3343 }
Eric Andersen25f27032001-04-26 23:22:31 +00003344 } else {
3345 b_addqchr(dest, ch, dest->quote);
3346 }
3347 break;
3348 case '\\':
3349 if (next == EOF) {
3350 syntax();
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003351 debug_printf_parse("parse_stream return 1: \\<eof>\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003352 return 1;
3353 }
3354 b_addqchr(dest, '\\', dest->quote);
3355 b_addqchr(dest, b_getch(input), dest->quote);
3356 break;
3357 case '$':
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003358 if (handle_dollar(dest, ctx, input) != 0) {
3359 debug_printf_parse("parse_stream return 1: handle_dollar returned non-0\n");
3360 return 1;
3361 }
Eric Andersen25f27032001-04-26 23:22:31 +00003362 break;
3363 case '\'':
3364 dest->nonnull = 1;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003365 while (1) {
3366 ch = b_getch(input);
3367 if (ch == EOF || ch == '\'')
3368 break;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003369 b_addchr(dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00003370 }
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003371 if (ch == EOF) {
Eric Andersen25f27032001-04-26 23:22:31 +00003372 syntax();
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003373 debug_printf_parse("parse_stream return 1: unterminated '\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003374 return 1;
3375 }
3376 break;
3377 case '"':
3378 dest->nonnull = 1;
3379 dest->quote = !dest->quote;
3380 break;
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003381#if ENABLE_HUSH_TICK
Eric Andersen25f27032001-04-26 23:22:31 +00003382 case '`':
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003383 process_command_subs(dest, ctx, input, "`");
Eric Andersen25f27032001-04-26 23:22:31 +00003384 break;
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003385#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003386 case '>':
3387 redir_fd = redirect_opt_num(dest);
3388 done_word(dest, ctx);
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003389 redir_style = REDIRECT_OVERWRITE;
Eric Andersen25f27032001-04-26 23:22:31 +00003390 if (next == '>') {
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003391 redir_style = REDIRECT_APPEND;
Eric Andersen25f27032001-04-26 23:22:31 +00003392 b_getch(input);
3393 } else if (next == '(') {
3394 syntax(); /* until we support >(list) Process Substitution */
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003395 debug_printf_parse("parse_stream return 1: >(process) not supported\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003396 return 1;
3397 }
3398 setup_redirect(ctx, redir_fd, redir_style, input);
3399 break;
3400 case '<':
3401 redir_fd = redirect_opt_num(dest);
3402 done_word(dest, ctx);
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003403 redir_style = REDIRECT_INPUT;
Eric Andersen25f27032001-04-26 23:22:31 +00003404 if (next == '<') {
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003405 redir_style = REDIRECT_HEREIS;
Eric Andersen25f27032001-04-26 23:22:31 +00003406 b_getch(input);
3407 } else if (next == '>') {
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003408 redir_style = REDIRECT_IO;
Eric Andersen25f27032001-04-26 23:22:31 +00003409 b_getch(input);
3410 } else if (next == '(') {
3411 syntax(); /* until we support <(list) Process Substitution */
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003412 debug_printf_parse("parse_stream return 1: <(process) not supported\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003413 return 1;
3414 }
3415 setup_redirect(ctx, redir_fd, redir_style, input);
3416 break;
3417 case ';':
3418 done_word(dest, ctx);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003419 done_pipe(ctx, PIPE_SEQ);
Eric Andersen25f27032001-04-26 23:22:31 +00003420 break;
3421 case '&':
3422 done_word(dest, ctx);
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003423 if (next == '&') {
Eric Andersen25f27032001-04-26 23:22:31 +00003424 b_getch(input);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003425 done_pipe(ctx, PIPE_AND);
Eric Andersen25f27032001-04-26 23:22:31 +00003426 } else {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003427 done_pipe(ctx, PIPE_BG);
Eric Andersen25f27032001-04-26 23:22:31 +00003428 }
3429 break;
3430 case '|':
3431 done_word(dest, ctx);
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003432 if (next == '|') {
Eric Andersen25f27032001-04-26 23:22:31 +00003433 b_getch(input);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003434 done_pipe(ctx, PIPE_OR);
Eric Andersen25f27032001-04-26 23:22:31 +00003435 } else {
3436 /* we could pick up a file descriptor choice here
3437 * with redirect_opt_num(), but bash doesn't do it.
3438 * "echo foo 2| cat" yields "foo 2". */
3439 done_command(ctx);
3440 }
3441 break;
3442 case '(':
3443 case '{':
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003444 if (parse_group(dest, ctx, input, ch) != 0) {
3445 debug_printf_parse("parse_stream return 1: parse_group returned non-0\n");
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003446 return 1;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003447 }
Eric Andersen25f27032001-04-26 23:22:31 +00003448 break;
3449 case ')':
3450 case '}':
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003451 syntax(); /* Proper use of this character is caught by end_trigger */
3452 debug_printf_parse("parse_stream return 1: unexpected '}'\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003453 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003454 default:
3455 syntax(); /* this is really an internal logic error */
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003456 debug_printf_parse("parse_stream return 1: internal logic error\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003457 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003458 }
3459 }
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003460 /* Complain if quote? No, maybe we just finished a command substitution
Eric Andersen25f27032001-04-26 23:22:31 +00003461 * that was quoted. Example:
Eric Andersenc7bda1c2004-03-15 08:29:22 +00003462 * $ echo "`cat foo` plus more"
Eric Andersen25f27032001-04-26 23:22:31 +00003463 * and we just got the EOF generated by the subshell that ran "cat foo"
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003464 * The only real complaint is if we got an EOF when end_trigger != NULL,
Eric Andersen25f27032001-04-26 23:22:31 +00003465 * that is, we were really supposed to get end_trigger, and never got
3466 * one before the EOF. Can't use the standard "syntax error" return code,
3467 * so that parse_stream_outer can distinguish the EOF and exit smoothly. */
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003468 debug_printf_parse("parse_stream return %d\n", -(end_trigger != NULL));
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003469 if (end_trigger)
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00003470 return -1;
Eric Andersen25f27032001-04-26 23:22:31 +00003471 return 0;
3472}
3473
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003474static void set_in_charmap(const char *set, int code)
Eric Andersen25f27032001-04-26 23:22:31 +00003475{
Denis Vlasenkof5294e12007-04-14 10:09:57 +00003476 while (*set)
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003477 charmap[(unsigned char)*set++] = code;
Eric Andersen25f27032001-04-26 23:22:31 +00003478}
3479
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003480static void update_charmap(void)
Eric Andersen25f27032001-04-26 23:22:31 +00003481{
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003482 /* char *ifs and char charmap[256] are both globals. */
Eric Andersen25f27032001-04-26 23:22:31 +00003483 ifs = getenv("IFS");
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003484 if (ifs == NULL)
3485 ifs = " \t\n";
Eric Andersen25f27032001-04-26 23:22:31 +00003486 /* Precompute a list of 'flow through' behavior so it can be treated
3487 * quickly up front. Computation is necessary because of IFS.
3488 * Special case handling of IFS == " \t\n" is not implemented.
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003489 * The charmap[] array only really needs two bits each,
3490 * and on most machines that would be faster (reduced L1 cache use).
Eric Andersen25f27032001-04-26 23:22:31 +00003491 */
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003492 memset(charmap, CHAR_ORDINARY, sizeof(charmap));
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003493#if ENABLE_HUSH_TICK
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003494 set_in_charmap("\\$\"`", CHAR_SPECIAL);
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003495#else
3496 set_in_charmap("\\$\"", CHAR_SPECIAL);
3497#endif
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003498 set_in_charmap("<>;&|(){}#'", CHAR_ORDINARY_IF_QUOTED);
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003499 set_in_charmap(ifs, CHAR_IFS); /* are ordinary if quoted */
Eric Andersen25f27032001-04-26 23:22:31 +00003500}
3501
Eric Andersenaff114c2004-04-14 17:51:38 +00003502/* most recursion does not come through here, the exception is
Eric Andersen25f27032001-04-26 23:22:31 +00003503 * from builtin_source() */
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003504static int parse_stream_outer(struct in_str *inp, int parse_flag)
Eric Andersen25f27032001-04-26 23:22:31 +00003505{
Eric Andersen25f27032001-04-26 23:22:31 +00003506 struct p_context ctx;
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003507 o_string temp = NULL_O_STRING;
Eric Andersen25f27032001-04-26 23:22:31 +00003508 int rcode;
3509 do {
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003510 ctx.parse_type = parse_flag;
Eric Andersen25f27032001-04-26 23:22:31 +00003511 initialize_context(&ctx);
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003512 update_charmap();
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003513 if (!(parse_flag & FLAG_PARSE_SEMICOLON) || (parse_flag & FLAG_REPARSING))
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003514 set_in_charmap(";$&|", CHAR_ORDINARY);
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003515#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003516 inp->promptmode = 1;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003517#endif
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003518 /* We will stop & execute after each ';' or '\n'.
3519 * Example: "sleep 9999; echo TEST" + ctrl-C:
3520 * TEST should be printed */
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003521 rcode = parse_stream(&temp, &ctx, inp, ";\n");
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003522 if (rcode != 1 && ctx.old_flag != 0) {
3523 syntax();
3524 }
3525 if (rcode != 1 && ctx.old_flag == 0) {
3526 done_word(&temp, &ctx);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003527 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko400c5b62007-05-04 13:07:27 +00003528 debug_print_tree(ctx.list_head, 0);
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003529 debug_printf_exec("parse_stream_outer: run_list\n");
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003530 run_list(ctx.list_head);
3531 } else {
3532 if (ctx.old_flag != 0) {
3533 free(ctx.stack);
3534 b_reset(&temp);
Eric Andersenc7bda1c2004-03-15 08:29:22 +00003535 }
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003536 temp.nonnull = 0;
3537 temp.quote = 0;
3538 inp->p = NULL;
Denis Vlasenko2f1bb362007-04-21 10:01:14 +00003539 free_pipe_list(ctx.list_head, 0);
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003540 }
Eric Andersena813afc2001-05-24 16:19:36 +00003541 b_free(&temp);
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003542 } while (rcode != -1 && !(parse_flag & FLAG_EXIT_FROM_LOOP)); /* loop on syntax errors, return on EOF */
Eric Andersen25f27032001-04-26 23:22:31 +00003543 return 0;
3544}
3545
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003546static int parse_string_outer(const char *s, int parse_flag)
Eric Andersen25f27032001-04-26 23:22:31 +00003547{
3548 struct in_str input;
3549 setup_string_in_str(&input, s);
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003550 return parse_stream_outer(&input, parse_flag);
Eric Andersen25f27032001-04-26 23:22:31 +00003551}
3552
3553static int parse_file_outer(FILE *f)
3554{
3555 int rcode;
3556 struct in_str input;
3557 setup_file_in_str(&input, f);
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003558 rcode = parse_stream_outer(&input, FLAG_PARSE_SEMICOLON);
Eric Andersen25f27032001-04-26 23:22:31 +00003559 return rcode;
3560}
3561
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003562#if ENABLE_HUSH_JOB
Eric Andersen6c947d22001-06-25 22:24:38 +00003563/* Make sure we have a controlling tty. If we get started under a job
3564 * aware app (like bash for example), make sure we are now in charge so
3565 * we don't fight over who gets the foreground */
Eric Anderseneaecbf32001-10-31 10:41:31 +00003566static void setup_job_control(void)
Eric Andersen52a97ca2001-06-22 06:49:26 +00003567{
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003568 pid_t shell_pgrp;
3569
Denis Vlasenkoa6a17852007-04-28 16:42:11 +00003570 saved_task_pgrp = shell_pgrp = getpgrp();
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003571 debug_printf_jobs("saved_task_pgrp=%d\n", saved_task_pgrp);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003572 fcntl(interactive_fd, F_SETFD, FD_CLOEXEC);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003573
Denis Vlasenkoa6a17852007-04-28 16:42:11 +00003574 /* If we were ran as 'hush &',
3575 * sleep until we are in the foreground. */
3576 while (tcgetpgrp(interactive_fd) != shell_pgrp) {
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00003577 /* Send TTIN to ourself (should stop us) */
Denis Vlasenkoff131b92007-04-10 15:42:06 +00003578 kill(- shell_pgrp, SIGTTIN);
Denis Vlasenkoa6a17852007-04-28 16:42:11 +00003579 shell_pgrp = getpgrp();
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003580 }
Eric Andersen52a97ca2001-06-22 06:49:26 +00003581
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003582 /* Ignore job-control and misc signals. */
3583 set_jobctrl_sighandler(SIG_IGN);
3584 set_misc_sighandler(SIG_IGN);
3585//huh? signal(SIGCHLD, SIG_IGN);
3586
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003587 /* We _must_ restore tty pgrp on fatal signals */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003588 set_fatal_sighandler(sigexit);
Eric Andersen6c947d22001-06-25 22:24:38 +00003589
3590 /* Put ourselves in our own process group. */
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00003591 setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
Eric Andersen6c947d22001-06-25 22:24:38 +00003592 /* Grab control of the terminal. */
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00003593 tcsetpgrp(interactive_fd, getpid());
Eric Andersen6c947d22001-06-25 22:24:38 +00003594}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00003595#endif
Eric Andersenada18ff2001-05-21 16:18:22 +00003596
Denis Vlasenko06af2162007-02-03 17:28:39 +00003597int hush_main(int argc, char **argv);
Matt Kraai2d91deb2001-08-01 17:21:35 +00003598int hush_main(int argc, char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00003599{
3600 int opt;
3601 FILE *input;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003602 char **e;
Eric Andersenbc604a22001-05-16 05:24:03 +00003603
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00003604 PTR_TO_GLOBALS = xzalloc(sizeof(G));
3605 top_vars = &shell_ver;
3606 shell_ver = const_shell_ver; /* copying struct here */
3607
Denis Vlasenko38f63192007-01-22 09:03:07 +00003608#if ENABLE_FEATURE_EDITING
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00003609 line_input_state = new_line_input_t(FOR_SHELL);
3610#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003611 /* XXX what should these be while sourcing /etc/profile? */
3612 global_argc = argc;
3613 global_argv = argv;
Eric Andersen94ac2442001-05-22 19:05:18 +00003614 /* Initialize some more globals to non-zero values */
3615 set_cwd();
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003616#if ENABLE_HUSH_INTERACTIVE
3617#if ENABLE_FEATURE_EDITING
3618 cmdedit_set_initial_prompt();
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003619#endif
Eric Andersen94ac2442001-05-22 19:05:18 +00003620 PS2 = "> ";
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003621#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00003622
Eric Andersenc7bda1c2004-03-15 08:29:22 +00003623 /* initialize our shell local variables with the values
Eric Andersen94ac2442001-05-22 19:05:18 +00003624 * currently living in the environment */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003625 e = environ;
3626 if (e)
3627 while (*e)
3628 set_local_var(*e++, 2); /* without call putenv() */
Eric Andersen94ac2442001-05-22 19:05:18 +00003629
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003630 last_return_code = EXIT_SUCCESS;
Eric Andersen25f27032001-04-26 23:22:31 +00003631
3632 if (argv[0] && argv[0][0] == '-') {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003633 debug_printf("sourcing /etc/profile\n");
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00003634 input = fopen("/etc/profile", "r");
3635 if (input != NULL) {
Eric Andersena90f20b2001-06-26 23:00:21 +00003636 mark_open(fileno(input));
3637 parse_file_outer(input);
3638 mark_closed(fileno(input));
3639 fclose(input);
3640 }
Eric Andersen25f27032001-04-26 23:22:31 +00003641 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003642 input = stdin;
Eric Andersenc7bda1c2004-03-15 08:29:22 +00003643
Eric Andersen25f27032001-04-26 23:22:31 +00003644 while ((opt = getopt(argc, argv, "c:xif")) > 0) {
3645 switch (opt) {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003646 case 'c':
Denis Vlasenko5f786c22007-04-20 08:35:45 +00003647 global_argv = argv + optind;
3648 global_argc = argc - optind;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003649 opt = parse_string_outer(optarg, FLAG_PARSE_SEMICOLON);
3650 goto final_return;
3651 case 'i':
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003652 /* Well, we cannot just declare interactiveness,
3653 * we have to have some stuff (ctty, etc) */
3654 /* interactive_fd++; */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003655 break;
3656 case 'f':
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00003657 fake_mode = 1;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003658 break;
3659 default:
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00003660#ifndef BB_VER
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003661 fprintf(stderr, "Usage: sh [FILE]...\n"
3662 " or: sh -c command [args]...\n\n");
3663 exit(EXIT_FAILURE);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00003664#else
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003665 bb_show_usage();
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00003666#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003667 }
3668 }
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003669#if ENABLE_HUSH_JOB
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003670 /* A shell is interactive if the '-i' flag was given, or if all of
Eric Andersen25f27032001-04-26 23:22:31 +00003671 * the following conditions are met:
Denis Vlasenko55b2de72007-04-18 17:21:28 +00003672 * no -c command
Eric Andersen25f27032001-04-26 23:22:31 +00003673 * no arguments remaining or the -s flag given
3674 * standard input is a terminal
3675 * standard output is a terminal
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003676 * Refer to Posix.2, the description of the 'sh' utility. */
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003677 if (argv[optind] == NULL && input == stdin
3678 && isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)
3679 ) {
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003680 saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
3681 debug_printf("saved_tty_pgrp=%d\n", saved_tty_pgrp);
3682 if (saved_tty_pgrp >= 0) {
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003683 /* try to dup to high fd#, >= 255 */
3684 interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
3685 if (interactive_fd < 0) {
3686 /* try to dup to any fd */
3687 interactive_fd = dup(STDIN_FILENO);
3688 if (interactive_fd < 0)
3689 /* give up */
3690 interactive_fd = 0;
3691 }
Denis Vlasenko2f1bb362007-04-21 10:01:14 +00003692 // TODO: track & disallow any attempts of user
3693 // to (inadvertently) close/redirect it
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003694 }
Eric Andersen25f27032001-04-26 23:22:31 +00003695 }
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003696 debug_printf("interactive_fd=%d\n", interactive_fd);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003697 if (interactive_fd) {
Eric Andersen25f27032001-04-26 23:22:31 +00003698 /* Looks like they want an interactive shell */
Eric Andersen52a97ca2001-06-22 06:49:26 +00003699 setup_job_control();
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003700 /* Make xfuncs do cleanup on exit */
3701 die_sleep = -1; /* flag */
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003702// FIXME: should we reset die_sleep = 0 whereever we fork?
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003703 if (setjmp(die_jmp)) {
3704 /* xfunc has failed! die die die */
3705 hush_exit(xfunc_error_retval);
3706 }
Denis Vlasenko2f1bb362007-04-21 10:01:14 +00003707#if !ENABLE_FEATURE_SH_EXTRA_QUIET
Denis Vlasenkoef36ead2007-05-02 15:34:47 +00003708 printf("\n\n%s hush - the humble shell v"HUSH_VER_STR"\n", BB_BANNER);
Denis Vlasenko2f1bb362007-04-21 10:01:14 +00003709 printf("Enter 'help' for a list of built-in commands.\n\n");
3710#endif
Eric Andersenada18ff2001-05-21 16:18:22 +00003711 }
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003712#elif ENABLE_HUSH_INTERACTIVE
3713/* no job control compiled, only prompt/line editing */
3714 if (argv[optind] == NULL && input == stdin
3715 && isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)
3716 ) {
3717 interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
3718 if (interactive_fd < 0) {
3719 /* try to dup to any fd */
3720 interactive_fd = dup(STDIN_FILENO);
3721 if (interactive_fd < 0)
3722 /* give up */
3723 interactive_fd = 0;
3724 }
3725 }
3726
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00003727#endif
Eric Andersenc7bda1c2004-03-15 08:29:22 +00003728
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003729 if (argv[optind] == NULL) {
3730 opt = parse_file_outer(stdin);
Eric Andersene67c3ce2001-05-02 02:09:36 +00003731 goto final_return;
Eric Andersen25f27032001-04-26 23:22:31 +00003732 }
Eric Andersen25f27032001-04-26 23:22:31 +00003733
3734 debug_printf("\nrunning script '%s'\n", argv[optind]);
Denis Vlasenko4c978632007-02-03 03:31:13 +00003735 global_argv = argv + optind;
3736 global_argc = argc - optind;
Rob Landleyd921b2e2006-08-03 15:41:12 +00003737 input = xfopen(argv[optind], "r");
Eric Andersen25f27032001-04-26 23:22:31 +00003738 opt = parse_file_outer(input);
3739
Denis Vlasenko38f63192007-01-22 09:03:07 +00003740#if ENABLE_FEATURE_CLEAN_UP
Eric Andersenaeb44c42001-05-22 20:29:00 +00003741 fclose(input);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003742 if (cwd != bb_msg_unknown)
Eric Andersenaeb44c42001-05-22 20:29:00 +00003743 free((char*)cwd);
3744 {
3745 struct variables *cur, *tmp;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003746 for (cur = top_vars; cur; cur = tmp) {
Eric Andersenaeb44c42001-05-22 20:29:00 +00003747 tmp = cur->next;
3748 if (!cur->flg_read_only) {
Denis Vlasenko4c978632007-02-03 03:31:13 +00003749 free((char*)cur->name);
3750 free((char*)cur->value);
Eric Andersenaeb44c42001-05-22 20:29:00 +00003751 free(cur);
3752 }
3753 }
3754 }
Eric Andersen25f27032001-04-26 23:22:31 +00003755#endif
3756
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00003757 final_return:
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003758 hush_exit(opt ? opt : last_return_code);
Eric Andersen25f27032001-04-26 23:22:31 +00003759}