blob: a446bbeb28cdb5ec005781e42555b0caf05d4135 [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?)
Eric Andersen25f27032001-04-26 23:22:31 +000040 * $_
41 * ! negation operator for pipes
42 * &> and >& redirection of stdout+stderr
43 * Brace Expansion
44 * Tilde Expansion
45 * fancy forms of Parameter Expansion
Eric Andersen78a7c992001-05-15 16:30:25 +000046 * aliases
Eric Andersen25f27032001-04-26 23:22:31 +000047 * Arithmetic Expansion
48 * <(list) and >(list) Process Substitution
Eric Andersen83a2ae22001-05-07 17:59:25 +000049 * reserved words: case, esac, select, function
Eric Andersen25f27032001-04-26 23:22:31 +000050 * Here Documents ( << word )
51 * Functions
52 * Major bugs:
Denis Vlasenkob81b3df2007-04-28 16:48:04 +000053 * job handling woefully incomplete and buggy (improved --vda)
Eric Andersen25f27032001-04-26 23:22:31 +000054 * reserved word execution woefully incomplete and buggy
Eric Andersen25f27032001-04-26 23:22:31 +000055 * to-do:
Eric Andersen83a2ae22001-05-07 17:59:25 +000056 * port selected bugfixes from post-0.49 busybox lash - done?
57 * finish implementing reserved words: for, while, until, do, done
58 * change { and } from special chars to reserved words
59 * builtins: break, continue, eval, return, set, trap, ulimit
60 * test magic exec
Eric Andersen25f27032001-04-26 23:22:31 +000061 * handle children going into background
62 * clean up recognition of null pipes
Eric Andersen25f27032001-04-26 23:22:31 +000063 * check setting of global_argc and global_argv
64 * control-C handling, probably with longjmp
Eric Andersen25f27032001-04-26 23:22:31 +000065 * follow IFS rules more precisely, including update semantics
Eric Andersen25f27032001-04-26 23:22:31 +000066 * figure out what to do with backslash-newline
67 * explain why we use signal instead of sigaction
68 * propagate syntax errors, die on resource errors?
69 * continuation lines, both explicit and implicit - done?
70 * memory leak finding and plugging - done?
71 * more testing, especially quoting rules and redirection
Eric Andersen78a7c992001-05-15 16:30:25 +000072 * document how quoting rules not precisely followed for variable assignments
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +000073 * maybe change charmap[] to use 2-bit entries
Eric Andersen25f27032001-04-26 23:22:31 +000074 * (eventually) remove all the printf's
Eric Andersen25f27032001-04-26 23:22:31 +000075 *
Bernhard Reutner-Fischer86f5c992006-01-22 22:55:11 +000076 * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
Eric Andersen25f27032001-04-26 23:22:31 +000077 */
Bernhard Reutner-Fischere15d7572006-06-02 20:56:16 +000078
Denis Vlasenkob6adbf12007-05-26 19:00:18 +000079
Eric Andersen25f27032001-04-26 23:22:31 +000080#include <glob.h> /* glob, of course */
Eric Andersen25f27032001-04-26 23:22:31 +000081#include <getopt.h> /* should be pretty obvious */
Eric Andersen25f27032001-04-26 23:22:31 +000082/* #include <dmalloc.h> */
Denis Vlasenkob6adbf12007-05-26 19:00:18 +000083
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
Denis Vlasenkob6adbf12007-05-26 19:00:18 +000086#include "busybox.h" /* for struct bb_applet */
87
Denis Vlasenkod01ff132007-05-02 21:40:23 +000088
89/* If you comment out one of these below, it will be #defined later
90 * to perform debug printfs to stderr: */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +000091#define debug_printf(...) do {} while (0)
Denis Vlasenko400c5b62007-05-04 13:07:27 +000092/* Finer-grained debug switches */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +000093#define debug_printf_parse(...) do {} while (0)
94#define debug_print_tree(a, b) do {} while (0)
95#define debug_printf_exec(...) do {} while (0)
96#define debug_printf_jobs(...) do {} while (0)
97#define debug_printf_expand(...) do {} while (0)
98#define debug_printf_clean(...) do {} while (0)
Denis Vlasenkod01ff132007-05-02 21:40:23 +000099
100#ifndef debug_printf
101#define debug_printf(...) fprintf(stderr, __VA_ARGS__)
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000102#endif
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000103
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +0000104#ifndef debug_printf_parse
105#define debug_printf_parse(...) fprintf(stderr, __VA_ARGS__)
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000106#endif
107
108#ifndef debug_printf_exec
109#define debug_printf_exec(...) fprintf(stderr, __VA_ARGS__)
110#endif
111
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +0000112#ifndef debug_printf_jobs
113#define debug_printf_jobs(...) fprintf(stderr, __VA_ARGS__)
114#define DEBUG_SHELL_JOBS 1
115#endif
116
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000117#ifndef debug_printf_expand
118#define debug_printf_expand(...) fprintf(stderr, __VA_ARGS__)
119#define DEBUG_EXPAND 1
120#endif
121
Denis Vlasenko170435c2007-05-23 13:01:10 +0000122/* Keep unconditionally on for now */
123#define ENABLE_HUSH_DEBUG 1
124
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +0000125#ifndef debug_printf_clean
126/* broken, of course, but OK for testing */
127static const char *indenter(int i)
128{
129 static const char blanks[] = " ";
130 return &blanks[sizeof(blanks) - i - 1];
131}
132#define debug_printf_clean(...) fprintf(stderr, __VA_ARGS__)
Denis Vlasenkoc666f712007-05-16 22:18:54 +0000133#define DEBUG_CLEAN 1
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +0000134#endif
135
Eric Andersen25f27032001-04-26 23:22:31 +0000136
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000137#if !ENABLE_HUSH_INTERACTIVE
138#undef ENABLE_FEATURE_EDITING
139#define ENABLE_FEATURE_EDITING 0
140#undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
141#define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
142#endif
"Robert P. J. Day"f3501602006-07-01 12:19:39 +0000143
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +0000144#define SPECIAL_VAR_SYMBOL 3
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000145
146#define PARSEFLAG_EXIT_FROM_LOOP 1
147#define PARSEFLAG_SEMICOLON (1 << 1) /* symbol ';' is special for parser */
148#define PARSEFLAG_REPARSING (1 << 2) /* >= 2nd pass */
Eric Andersen25f27032001-04-26 23:22:31 +0000149
150typedef enum {
151 REDIRECT_INPUT = 1,
152 REDIRECT_OVERWRITE = 2,
153 REDIRECT_APPEND = 3,
154 REDIRECT_HEREIS = 4,
155 REDIRECT_IO = 5
156} redir_type;
157
158/* The descrip member of this structure is only used to make debugging
159 * output pretty */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +0000160static const struct {
161 int mode;
Denis Vlasenkoef36ead2007-05-02 15:34:47 +0000162 signed char default_fd;
163 char descrip[3];
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +0000164} redir_table[] = {
Eric Andersen25f27032001-04-26 23:22:31 +0000165 { 0, 0, "()" },
166 { O_RDONLY, 0, "<" },
167 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
168 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
169 { O_RDONLY, -1, "<<" },
170 { O_RDWR, 1, "<>" }
171};
172
173typedef enum {
174 PIPE_SEQ = 1,
175 PIPE_AND = 2,
176 PIPE_OR = 3,
177 PIPE_BG = 4,
178} pipe_style;
179
180/* might eventually control execution */
181typedef enum {
182 RES_NONE = 0,
Denis Vlasenko06810332007-05-21 23:30:54 +0000183#if ENABLE_HUSH_IF
Eric Andersen25f27032001-04-26 23:22:31 +0000184 RES_IF = 1,
185 RES_THEN = 2,
186 RES_ELIF = 3,
187 RES_ELSE = 4,
188 RES_FI = 5,
Denis Vlasenko06810332007-05-21 23:30:54 +0000189#endif
190#if ENABLE_HUSH_LOOPS
Eric Andersen25f27032001-04-26 23:22:31 +0000191 RES_FOR = 6,
192 RES_WHILE = 7,
193 RES_UNTIL = 8,
194 RES_DO = 9,
195 RES_DONE = 10,
Denis Vlasenko06810332007-05-21 23:30:54 +0000196 RES_IN = 11,
197#endif
198 RES_XXXX = 12,
Eric Andersen4c9b68f2002-04-13 12:33:41 +0000199 RES_SNTX = 13
Eric Andersen25f27032001-04-26 23:22:31 +0000200} reserved_style;
Denis Vlasenko5f786c22007-04-20 08:35:45 +0000201enum {
202 FLAG_END = (1 << RES_NONE ),
Denis Vlasenko06810332007-05-21 23:30:54 +0000203#if ENABLE_HUSH_IF
Denis Vlasenko5f786c22007-04-20 08:35:45 +0000204 FLAG_IF = (1 << RES_IF ),
205 FLAG_THEN = (1 << RES_THEN ),
206 FLAG_ELIF = (1 << RES_ELIF ),
207 FLAG_ELSE = (1 << RES_ELSE ),
208 FLAG_FI = (1 << RES_FI ),
Denis Vlasenko06810332007-05-21 23:30:54 +0000209#endif
210#if ENABLE_HUSH_LOOPS
Denis Vlasenko5f786c22007-04-20 08:35:45 +0000211 FLAG_FOR = (1 << RES_FOR ),
212 FLAG_WHILE = (1 << RES_WHILE),
213 FLAG_UNTIL = (1 << RES_UNTIL),
214 FLAG_DO = (1 << RES_DO ),
215 FLAG_DONE = (1 << RES_DONE ),
216 FLAG_IN = (1 << RES_IN ),
Denis Vlasenko06810332007-05-21 23:30:54 +0000217#endif
Denis Vlasenko5f786c22007-04-20 08:35:45 +0000218 FLAG_START = (1 << RES_XXXX ),
219};
Eric Andersen25f27032001-04-26 23:22:31 +0000220
221/* This holds pointers to the various results of parsing */
222struct p_context {
223 struct child_prog *child;
224 struct pipe *list_head;
225 struct pipe *pipe;
226 struct redir_struct *pending_redirect;
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000227 smallint res_w;
228 smallint parse_type; /* bitmask of PARSEFLAG_xxx, defines type of parser : ";$" common or special symbol */
229 int old_flag; /* bitmask of FLAG_xxx, for figuring out valid reserved words */
Eric Andersen25f27032001-04-26 23:22:31 +0000230 struct p_context *stack;
231 /* How about quoting status? */
232};
233
234struct redir_struct {
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000235 struct redir_struct *next; /* pointer to the next redirect in the list */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000236 redir_type type; /* type of redirection */
237 int fd; /* file descriptor being redirected */
238 int dup; /* -1, or file descriptor being duplicated */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000239 glob_t word; /* *word.gl_pathv is the filename */
Eric Andersen25f27032001-04-26 23:22:31 +0000240};
241
242struct child_prog {
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000243 pid_t pid; /* 0 if exited */
244 char **argv; /* program name and arguments */
245 struct pipe *group; /* if non-NULL, first in group or subshell */
Denis Vlasenko262d7652007-05-20 21:52:49 +0000246 smallint subshell; /* flag, non-zero if group must be forked */
247 smallint is_stopped; /* is the program currently running? */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000248 struct redir_struct *redirects; /* I/O redirections */
249 glob_t glob_result; /* result of parameter globbing */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000250 struct pipe *family; /* pointer back to the child's parent pipe */
Denis Vlasenkoc666f712007-05-16 22:18:54 +0000251 //sp counting seems to be broken... so commented out, grep for '//sp:'
252 //sp: int sp; /* number of SPECIAL_VAR_SYMBOL */
Denis Vlasenko262d7652007-05-20 21:52:49 +0000253 //seems to be unused, grep for '//pt:'
254 //pt: int parse_type;
Eric Andersen25f27032001-04-26 23:22:31 +0000255};
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000256/* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
257 * and on execution these are substituted with their values.
258 * Substitution can make _several_ words out of one argv[n]!
259 * Example: argv[0]=='.^C*^C.' here: echo .$*.
260 */
Eric Andersen25f27032001-04-26 23:22:31 +0000261
262struct pipe {
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000263 struct pipe *next;
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000264 int num_progs; /* total number of programs in job */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000265 int running_progs; /* number of programs running (not exited) */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000266 int stopped_progs; /* number of programs alive, but stopped */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000267#if ENABLE_HUSH_JOB
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000268 int jobid; /* job number */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000269 pid_t pgrp; /* process group ID for the job */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000270 char *cmdtext; /* name of job */
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000271#endif
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000272 char *cmdbuf; /* buffer various argv's point into */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000273 struct child_prog *progs; /* array of commands in pipe */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000274 int job_context; /* bitmask defining current context */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000275 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
276 smallint res_word; /* needed for if, for, while, until... */
Eric Andersen25f27032001-04-26 23:22:31 +0000277};
278
Eric Andersen25f27032001-04-26 23:22:31 +0000279struct close_me {
Eric Andersen25f27032001-04-26 23:22:31 +0000280 struct close_me *next;
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000281 int fd;
Eric Andersen25f27032001-04-26 23:22:31 +0000282};
283
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000284/* On program start, environ points to initial environment.
285 * putenv adds new pointers into it, unsetenv removes them.
286 * Neither of these (de)allocates the strings.
287 * setenv allocates new strings in malloc space and does putenv,
288 * and thus setenv is unusable (leaky) for shell's purposes */
289#define setenv(...) setenv_is_leaky_dont_use()
290struct variable {
291 struct variable *next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +0000292 char *varstr; /* points to "name=" portion */
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000293 int max_len; /* if > 0, name is part of initial env; else name is malloced */
294 smallint flg_export; /* putenv should be done on this var */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000295 smallint flg_read_only;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000296};
297
Eric Andersen25f27032001-04-26 23:22:31 +0000298typedef struct {
299 char *data;
300 int length;
301 int maxlen;
302 int quote;
303 int nonnull;
304} o_string;
305#define NULL_O_STRING {NULL,0,0,0,0}
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000306/* used for initialization: o_string foo = NULL_O_STRING; */
Eric Andersen25f27032001-04-26 23:22:31 +0000307
308/* I can almost use ordinary FILE *. Is open_memstream() universally
309 * available? Where is it documented? */
310struct in_str {
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +0000311 const char *p;
312 /* eof_flag=1: last char in ->p is really an EOF */
313 char eof_flag; /* meaningless if ->p == NULL */
314 char peek_buf[2];
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000315#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko5a1437d2007-05-24 13:22:47 +0000316 smallint promptme;
317 smallint promptmode; /* 0: PS1, 1: PS2 */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000318#endif
Eric Andersen25f27032001-04-26 23:22:31 +0000319 FILE *file;
320 int (*get) (struct in_str *);
321 int (*peek) (struct in_str *);
322};
323#define b_getch(input) ((input)->get(input))
324#define b_peek(input) ((input)->peek(input))
325
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000326enum {
327 CHAR_ORDINARY = 0,
328 CHAR_ORDINARY_IF_QUOTED = 1, /* example: *, # */
329 CHAR_IFS = 2, /* treated as ordinary if quoted */
330 CHAR_SPECIAL = 3, /* example: $ */
Eric Andersen25f27032001-04-26 23:22:31 +0000331};
332
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000333#define HUSH_VER_STR "0.02"
334
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000335/* "Globals" within this file */
336
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000337/* Sorted roughly by size (smaller offsets == smaller code) */
338struct globals {
339#if ENABLE_HUSH_INTERACTIVE
340 /* 'interactive_fd' is a fd# open to ctty, if we have one
341 * _AND_ if we decided to act interactively */
342 int interactive_fd;
343 const char *PS1;
344 const char *PS2;
345#endif
346#if ENABLE_FEATURE_EDITING
347 line_input_t *line_input_state;
348#endif
349#if ENABLE_HUSH_JOB
350 int run_list_level;
351 pid_t saved_task_pgrp;
352 pid_t saved_tty_pgrp;
353 int last_jobid;
354 struct pipe *job_list;
355 struct pipe *toplevel_list;
356 smallint ctrl_z_flag;
357#endif
358 smallint fake_mode;
359 /* these three support $?, $#, and $1 */
360 char **global_argv;
361 int global_argc;
362 int last_return_code;
363 const char *ifs;
364 struct close_me *close_me_head;
365 const char *cwd;
366 unsigned last_bg_pid;
Denis Vlasenko0a83fc32007-05-25 11:12:32 +0000367 struct variable *top_var; /* = &shell_ver (set in main()) */
368 struct variable shell_ver;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000369#if ENABLE_FEATURE_SH_STANDALONE
370 struct nofork_save_area nofork_save;
371#endif
372#if ENABLE_HUSH_JOB
373 sigjmp_buf toplevel_jb;
374#endif
375 unsigned char charmap[256];
376 char user_input_buf[ENABLE_FEATURE_EDITING ? BUFSIZ : 2];
377};
378
379#define G (*ptr_to_globals)
380
381#if !ENABLE_HUSH_INTERACTIVE
382enum { interactive_fd = 0 };
383#endif
384#if !ENABLE_HUSH_JOB
385enum { run_list_level = 0 };
386#endif
387
388#if ENABLE_HUSH_INTERACTIVE
389#define interactive_fd (G.interactive_fd )
390#define PS1 (G.PS1 )
391#define PS2 (G.PS2 )
392#endif
393#if ENABLE_FEATURE_EDITING
394#define line_input_state (G.line_input_state)
395#endif
396#if ENABLE_HUSH_JOB
397#define run_list_level (G.run_list_level )
398#define saved_task_pgrp (G.saved_task_pgrp )
399#define saved_tty_pgrp (G.saved_tty_pgrp )
400#define last_jobid (G.last_jobid )
401#define job_list (G.job_list )
402#define toplevel_list (G.toplevel_list )
403#define toplevel_jb (G.toplevel_jb )
404#define ctrl_z_flag (G.ctrl_z_flag )
405#endif /* JOB */
406#define global_argv (G.global_argv )
407#define global_argc (G.global_argc )
408#define last_return_code (G.last_return_code)
409#define ifs (G.ifs )
410#define fake_mode (G.fake_mode )
411#define close_me_head (G.close_me_head )
412#define cwd (G.cwd )
413#define last_bg_pid (G.last_bg_pid )
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000414#define top_var (G.top_var )
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000415#define shell_ver (G.shell_ver )
416#if ENABLE_FEATURE_SH_STANDALONE
417#define nofork_save (G.nofork_save )
Denis Vlasenko4b924f32007-05-30 00:29:55 +0000418#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000419#if ENABLE_HUSH_JOB
420#define toplevel_jb (G.toplevel_jb )
421#endif
422#define charmap (G.charmap )
423#define user_input_buf (G.user_input_buf )
424
425
426#define B_CHUNK 100
427#define B_NOSPAC 1
428#define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
429
Denis Vlasenko90e485c2007-05-23 15:22:50 +0000430#if 1
431/* Normal */
432static void syntax(const char *msg)
433{
Denis Vlasenko5a1437d2007-05-24 13:22:47 +0000434 /* Was using fancy stuff:
435 * (interactive_fd ? bb_error_msg : bb_error_msg_and_die)(...params...)
436 * but it SEGVs. ?! Oh well... explicit temp ptr works around that */
437 void (*fp)(const char *s, ...);
438
439 fp = (interactive_fd ? bb_error_msg : bb_error_msg_and_die);
440 fp(msg ? "%s: %s" : "syntax error", "syntax error", msg);
Denis Vlasenko90e485c2007-05-23 15:22:50 +0000441}
Denis Vlasenko5a1437d2007-05-24 13:22:47 +0000442
Denis Vlasenko90e485c2007-05-23 15:22:50 +0000443#else
444/* Debug */
445static void syntax_lineno(int line)
Denis Vlasenkob6aae0f2007-01-29 22:51:25 +0000446{
Denis Vlasenko5a1437d2007-05-24 13:22:47 +0000447 void (*fp)(const char *s, ...);
448
449 fp = (interactive_fd ? bb_error_msg : bb_error_msg_and_die);
450 fp("syntax error hush.c:%d", line);
Eric Andersen25f27032001-04-26 23:22:31 +0000451}
Denis Vlasenko90e485c2007-05-23 15:22:50 +0000452#define syntax(str) syntax_lineno(__LINE__)
453#endif
Eric Andersen25f27032001-04-26 23:22:31 +0000454
455/* Index of subroutines: */
456/* function prototypes for builtins */
Denis Vlasenko1359da62007-04-21 23:27:30 +0000457static int builtin_cd(char **argv);
Denis Vlasenko1359da62007-04-21 23:27:30 +0000458static int builtin_eval(char **argv);
459static int builtin_exec(char **argv);
460static int builtin_exit(char **argv);
461static int builtin_export(char **argv);
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000462#if ENABLE_HUSH_JOB
Denis Vlasenko1359da62007-04-21 23:27:30 +0000463static int builtin_fg_bg(char **argv);
Denis Vlasenko1359da62007-04-21 23:27:30 +0000464static int builtin_jobs(char **argv);
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000465#endif
Denis Vlasenko06810332007-05-21 23:30:54 +0000466#if ENABLE_HUSH_HELP
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000467static int builtin_help(char **argv);
Denis Vlasenko06810332007-05-21 23:30:54 +0000468#endif
Denis Vlasenko1359da62007-04-21 23:27:30 +0000469static int builtin_pwd(char **argv);
470static int builtin_read(char **argv);
471static int builtin_set(char **argv);
472static int builtin_shift(char **argv);
473static int builtin_source(char **argv);
474static int builtin_umask(char **argv);
475static int builtin_unset(char **argv);
Denis Vlasenko06810332007-05-21 23:30:54 +0000476//static int builtin_not_written(char **argv);
Eric Andersen25f27032001-04-26 23:22:31 +0000477/* o_string manipulation: */
478static int b_check_space(o_string *o, int len);
479static int b_addchr(o_string *o, int ch);
480static void b_reset(o_string *o);
481static int b_addqchr(o_string *o, int ch, int quote);
Eric Andersen25f27032001-04-26 23:22:31 +0000482/* in_str manipulations: */
483static int static_get(struct in_str *i);
484static int static_peek(struct in_str *i);
485static int file_get(struct in_str *i);
486static int file_peek(struct in_str *i);
487static void setup_file_in_str(struct in_str *i, FILE *f);
488static void setup_string_in_str(struct in_str *i, const char *s);
489/* close_me manipulations: */
490static void mark_open(int fd);
491static void mark_closed(int fd);
Eric Anderseneaecbf32001-10-31 10:41:31 +0000492static void close_all(void);
Eric Andersen25f27032001-04-26 23:22:31 +0000493/* "run" the final data structures: */
Denis Vlasenkoc666f712007-05-16 22:18:54 +0000494#if !defined(DEBUG_CLEAN)
495#define free_pipe_list(head, indent) free_pipe_list(head)
496#define free_pipe(pi, indent) free_pipe(pi)
497#endif
Eric Andersenbf7df042001-05-23 22:18:35 +0000498static int free_pipe_list(struct pipe *head, int indent);
499static int free_pipe(struct pipe *pi, int indent);
Eric Andersen25f27032001-04-26 23:22:31 +0000500/* really run the final data structures: */
501static int setup_redirects(struct child_prog *prog, int squirrel[]);
Eric Andersen25f27032001-04-26 23:22:31 +0000502static int run_list_real(struct pipe *pi);
Denis Vlasenko1359da62007-04-21 23:27:30 +0000503static void pseudo_exec_argv(char **argv) ATTRIBUTE_NORETURN;
Bernhard Reutner-Fischer86f5c992006-01-22 22:55:11 +0000504static void pseudo_exec(struct child_prog *child) ATTRIBUTE_NORETURN;
Eric Andersen25f27032001-04-26 23:22:31 +0000505static int run_pipe_real(struct pipe *pi);
506/* extended glob support: */
507static int globhack(const char *src, int flags, glob_t *pglob);
508static int glob_needed(const char *s);
509static int xglob(o_string *dest, int flags, glob_t *pglob);
Eric Andersen78a7c992001-05-15 16:30:25 +0000510/* variable assignment: */
Eric Andersen78a7c992001-05-15 16:30:25 +0000511static int is_assignment(const char *s);
Eric Andersen25f27032001-04-26 23:22:31 +0000512/* data structure manipulation: */
513static int setup_redirect(struct p_context *ctx, int fd, redir_type style, struct in_str *input);
514static void initialize_context(struct p_context *ctx);
515static int done_word(o_string *dest, struct p_context *ctx);
516static int done_command(struct p_context *ctx);
517static int done_pipe(struct p_context *ctx, pipe_style type);
518/* primary string parsing: */
519static int redirect_dup_num(struct in_str *input);
520static int redirect_opt_num(o_string *o);
Denis Vlasenko14b5dd92007-05-20 21:51:38 +0000521#if ENABLE_HUSH_TICK
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +0000522static 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 +0000523#endif
Eric Andersen25f27032001-04-26 23:22:31 +0000524static int parse_group(o_string *dest, struct p_context *ctx, struct in_str *input, int ch);
Denis Vlasenko15d78fb2007-01-30 22:28:21 +0000525static const char *lookup_param(const char *src);
Eric Andersen25f27032001-04-26 23:22:31 +0000526static int handle_dollar(o_string *dest, struct p_context *ctx, struct in_str *input);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +0000527static 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 +0000528/* setup: */
Denis Vlasenko170435c2007-05-23 13:01:10 +0000529static int parse_and_run_stream(struct in_str *inp, int parse_flag);
530static int parse_and_run_string(const char *s, int parse_flag);
531static int parse_and_run_file(FILE *f);
Eric Andersenbafd94f2001-05-02 16:11:59 +0000532/* job management: */
Eric Andersenc798b072001-06-22 06:23:03 +0000533static int checkjobs(struct pipe* fg_pipe);
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000534#if ENABLE_HUSH_JOB
Denis Vlasenko52881e92007-04-21 13:42:52 +0000535static int checkjobs_and_fg_shell(struct pipe* fg_pipe);
Eric Andersenbafd94f2001-05-02 16:11:59 +0000536static void insert_bg_job(struct pipe *pi);
537static void remove_bg_job(struct pipe *pi);
Denis Vlasenko1359da62007-04-21 23:27:30 +0000538static void delete_finished_bg_job(struct pipe *pi);
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000539#else
540int checkjobs_and_fg_shell(struct pipe* fg_pipe); /* never called */
541#endif
Eric Andersenf72f5622001-05-15 23:21:41 +0000542/* local variable support */
Denis Vlasenko170435c2007-05-23 13:01:10 +0000543static char **expand_strvec_to_strvec(char **argv);
544/* used for eval */
545static char *expand_strvec_to_string(char **argv);
Denis Vlasenkob6a741f2007-05-17 14:38:17 +0000546/* used for expansion of right hand of assignments */
Denis Vlasenko170435c2007-05-23 13:01:10 +0000547static char *expand_string_to_string(const char *str);
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +0000548static struct variable *get_local_var(const char *name);
549static int set_local_var(char *str, int flg_export);
Denis Vlasenko87cb2db2007-04-21 10:00:01 +0000550static void unset_local_var(const char *name);
Eric Andersen25f27032001-04-26 23:22:31 +0000551
552/* Table of built-in functions. They can be forked or not, depending on
553 * context: within pipes, they fork. As simple commands, they do not.
554 * When used in non-forking context, they can change global variables
Denis Vlasenkoe1a0d482006-10-20 13:28:22 +0000555 * in the parent shell process. If forked, of course they cannot.
Eric Andersen25f27032001-04-26 23:22:31 +0000556 * For example, 'unset foo | whatever' will parse and run, but foo will
557 * still be set at the end. */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000558struct built_in_command {
559 const char *cmd; /* name */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000560 int (*function) (char **argv); /* function ptr */
Denis Vlasenko06810332007-05-21 23:30:54 +0000561#if ENABLE_HUSH_HELP
562 const char *descr; /* description */
563#define BLTIN(cmd, func, help) { cmd, func, help }
564#else
565#define BLTIN(cmd, func, help) { cmd, func }
566#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000567};
568
"Vladimir N. Oleynik"485d7cb2005-10-17 09:48:57 +0000569static const struct built_in_command bltins[] = {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000570#if ENABLE_HUSH_JOB
Denis Vlasenko06810332007-05-21 23:30:54 +0000571 BLTIN("bg" , builtin_fg_bg, "Resume a job in the background"),
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000572#endif
Denis Vlasenko06810332007-05-21 23:30:54 +0000573// BLTIN("break" , builtin_not_written, "Exit for, while or until loop"),
574 BLTIN("cd" , builtin_cd, "Change working directory"),
575// BLTIN("continue", builtin_not_written, "Continue for, while or until loop"),
576 BLTIN("eval" , builtin_eval, "Construct and run shell command"),
577 BLTIN("exec" , builtin_exec, "Exec command, replacing this shell with the exec'd process"),
578 BLTIN("exit" , builtin_exit, "Exit from shell"),
579 BLTIN("export", builtin_export, "Set environment variable"),
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000580#if ENABLE_HUSH_JOB
Denis Vlasenko06810332007-05-21 23:30:54 +0000581 BLTIN("fg" , builtin_fg_bg, "Bring job into the foreground"),
582 BLTIN("jobs" , builtin_jobs, "Lists the active jobs"),
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000583#endif
Denis Vlasenko06810332007-05-21 23:30:54 +0000584// TODO: remove pwd? we have it as an applet...
585 BLTIN("pwd" , builtin_pwd, "Print current directory"),
586 BLTIN("read" , builtin_read, "Input environment variable"),
587// BLTIN("return", builtin_not_written, "Return from a function"),
588 BLTIN("set" , builtin_set, "Set/unset shell local variables"),
589 BLTIN("shift" , builtin_shift, "Shift positional parameters"),
590// BLTIN("trap" , builtin_not_written, "Trap signals"),
591// BLTIN("ulimit", builtin_not_written, "Controls resource limits"),
592 BLTIN("umask" , builtin_umask, "Sets file creation mask"),
593 BLTIN("unset" , builtin_unset, "Unset environment variable"),
594 BLTIN("." , builtin_source, "Source-in and run commands in a file"),
595#if ENABLE_HUSH_HELP
596 BLTIN("help" , builtin_help, "List shell built-in commands"),
597#endif
598 BLTIN(NULL, NULL, NULL)
Eric Andersen25f27032001-04-26 23:22:31 +0000599};
600
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000601#if ENABLE_HUSH_JOB
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000602
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000603/* move to libbb? */
604static void signal_SA_RESTART(int sig, void (*handler)(int))
605{
606 struct sigaction sa;
607 sa.sa_handler = handler;
608 sa.sa_flags = SA_RESTART;
609 sigemptyset(&sa.sa_mask);
610 sigaction(sig, &sa, NULL);
611}
612
Denis Vlasenko3ac0e002007-04-28 16:45:22 +0000613/* Signals are grouped, we handle them in batches */
614static void set_fatal_sighandler(void (*handler)(int))
615{
616 signal(SIGILL , handler);
617 signal(SIGTRAP, handler);
618 signal(SIGABRT, handler);
619 signal(SIGFPE , handler);
620 signal(SIGBUS , handler);
621 signal(SIGSEGV, handler);
622 /* bash 3.2 seems to handle these just like 'fatal' ones */
623 signal(SIGHUP , handler);
624 signal(SIGPIPE, handler);
625 signal(SIGALRM, handler);
626}
627static void set_jobctrl_sighandler(void (*handler)(int))
628{
629 signal(SIGTSTP, handler);
630 signal(SIGTTIN, handler);
631 signal(SIGTTOU, handler);
632}
633static void set_misc_sighandler(void (*handler)(int))
634{
635 signal(SIGINT , handler);
636 signal(SIGQUIT, handler);
637 signal(SIGTERM, handler);
638}
639/* SIGCHLD is special and handled separately */
640
641static void set_every_sighandler(void (*handler)(int))
642{
643 set_fatal_sighandler(handler);
644 set_jobctrl_sighandler(handler);
645 set_misc_sighandler(handler);
646 signal(SIGCHLD, handler);
647}
648
Denis Vlasenkob5eaabb2007-04-28 16:45:59 +0000649static void handler_ctrl_c(int sig)
650{
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000651 debug_printf_jobs("got sig %d\n", sig);
Denis Vlasenkob5eaabb2007-04-28 16:45:59 +0000652// as usual we can have all kinds of nasty problems with leaked malloc data here
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +0000653 siglongjmp(toplevel_jb, 1);
Denis Vlasenkob5eaabb2007-04-28 16:45:59 +0000654}
655
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000656static void handler_ctrl_z(int sig)
657{
658 pid_t pid;
659
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +0000660 debug_printf_jobs("got tty sig %d in pid %d\n", sig, getpid());
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000661 pid = fork();
Denis Vlasenkoc2990322007-05-16 12:57:12 +0000662 if (pid < 0) /* can't fork. Pretend there was no ctrl-Z */
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000663 return;
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +0000664 ctrl_z_flag = 1;
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000665 if (!pid) { /* child */
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000666 setpgrp();
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +0000667 debug_printf_jobs("set pgrp for child %d ok\n", getpid());
Denis Vlasenko3ac0e002007-04-28 16:45:22 +0000668 set_every_sighandler(SIG_DFL);
Denis Vlasenko18e19f22007-04-28 16:43:18 +0000669 raise(SIGTSTP); /* resend TSTP so that child will be stopped */
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +0000670 debug_printf_jobs("returning in child\n");
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000671 /* return to nofork, it will eventually exit now,
672 * not return back to shell */
673 return;
674 }
675 /* parent */
676 /* finish filling up pipe info */
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +0000677 toplevel_list->pgrp = pid; /* child is in its own pgrp */
678 toplevel_list->progs[0].pid = pid;
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000679 /* parent needs to longjmp out of running nofork.
680 * we will "return" exitcode 0, with child put in background */
681// as usual we can have all kinds of nasty problems with leaked malloc data here
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +0000682 debug_printf_jobs("siglongjmp in parent\n");
683 siglongjmp(toplevel_jb, 1);
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000684}
685
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000686/* Restores tty foreground process group, and exits.
687 * May be called as signal handler for fatal signal
688 * (will faithfully resend signal to itself, producing correct exit state)
689 * or called directly with -EXITCODE.
690 * We also call it if xfunc is exiting. */
691static void sigexit(int sig) ATTRIBUTE_NORETURN;
692static void sigexit(int sig)
693{
694 sigset_t block_all;
695
696 /* Disable all signals: job control, SIGPIPE, etc. */
697 sigfillset(&block_all);
698 sigprocmask(SIG_SETMASK, &block_all, NULL);
699
Denis Vlasenko87cb2db2007-04-21 10:00:01 +0000700 if (interactive_fd)
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000701 tcsetpgrp(interactive_fd, saved_tty_pgrp);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000702
703 /* Not a signal, just exit */
704 if (sig <= 0)
705 _exit(- sig);
706
707 /* Enable only this sig and kill ourself with it */
708 signal(sig, SIG_DFL);
709 sigdelset(&block_all, sig);
710 sigprocmask(SIG_SETMASK, &block_all, NULL);
711 raise(sig);
712 _exit(1); /* Should not reach it */
713}
714
715/* Restores tty foreground process group, and exits. */
716static void hush_exit(int exitcode) ATTRIBUTE_NORETURN;
717static void hush_exit(int exitcode)
718{
719 fflush(NULL); /* flush all streams */
720 sigexit(- (exitcode & 0xff));
721}
722
Denis Vlasenkoef36ead2007-05-02 15:34:47 +0000723#else /* !JOB */
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000724
725#define set_fatal_sighandler(handler) ((void)0)
726#define set_jobctrl_sighandler(handler) ((void)0)
727#define set_misc_sighandler(handler) ((void)0)
Denis Vlasenkoef36ead2007-05-02 15:34:47 +0000728#define hush_exit(e) exit(e)
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000729
Denis Vlasenkoef36ead2007-05-02 15:34:47 +0000730#endif /* JOB */
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000731
732
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000733static const char *set_cwd(void)
734{
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000735 if (cwd == bb_msg_unknown)
Denis Vlasenko7cced6e2007-04-12 17:08:53 +0000736 cwd = NULL; /* xrealloc_getcwd_or_warn(arg) calls free(arg)! */
Denis Vlasenko6ca04442007-02-11 16:19:28 +0000737 cwd = xrealloc_getcwd_or_warn((char *)cwd);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000738 if (!cwd)
Manuel Novoa III cad53642003-03-19 09:13:01 +0000739 cwd = bb_msg_unknown;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000740 return cwd;
741}
742
Eric Andersen4c9b68f2002-04-13 12:33:41 +0000743/* built-in 'eval' handler */
Denis Vlasenko1359da62007-04-21 23:27:30 +0000744static int builtin_eval(char **argv)
Eric Andersen4c9b68f2002-04-13 12:33:41 +0000745{
Eric Andersen4c9b68f2002-04-13 12:33:41 +0000746 int rcode = EXIT_SUCCESS;
Eric Andersenc7bda1c2004-03-15 08:29:22 +0000747
Denis Vlasenko1359da62007-04-21 23:27:30 +0000748 if (argv[1]) {
Denis Vlasenko170435c2007-05-23 13:01:10 +0000749 char *str = expand_strvec_to_string(argv + 1);
750 parse_and_run_string(str, PARSEFLAG_EXIT_FROM_LOOP |
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000751 PARSEFLAG_SEMICOLON);
Eric Andersen4c9b68f2002-04-13 12:33:41 +0000752 free(str);
753 rcode = last_return_code;
754 }
755 return rcode;
756}
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000757
Eric Andersen25f27032001-04-26 23:22:31 +0000758/* built-in 'cd <path>' handler */
Denis Vlasenko1359da62007-04-21 23:27:30 +0000759static int builtin_cd(char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +0000760{
Denis Vlasenko170435c2007-05-23 13:01:10 +0000761 const char *newdir;
Denis Vlasenko1359da62007-04-21 23:27:30 +0000762 if (argv[1] == NULL)
Denis Vlasenko170435c2007-05-23 13:01:10 +0000763 newdir = getenv("HOME") ? : "/";
Eric Andersen25f27032001-04-26 23:22:31 +0000764 else
Denis Vlasenko1359da62007-04-21 23:27:30 +0000765 newdir = argv[1];
Eric Andersen25f27032001-04-26 23:22:31 +0000766 if (chdir(newdir)) {
767 printf("cd: %s: %s\n", newdir, strerror(errno));
768 return EXIT_FAILURE;
769 }
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000770 set_cwd();
Eric Andersen25f27032001-04-26 23:22:31 +0000771 return EXIT_SUCCESS;
772}
773
Eric Andersen25f27032001-04-26 23:22:31 +0000774/* built-in 'exec' handler */
Denis Vlasenko1359da62007-04-21 23:27:30 +0000775static int builtin_exec(char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +0000776{
Denis Vlasenko1359da62007-04-21 23:27:30 +0000777 if (argv[1] == NULL)
Eric Andersen25f27032001-04-26 23:22:31 +0000778 return EXIT_SUCCESS; /* Really? */
Denis Vlasenko1359da62007-04-21 23:27:30 +0000779 pseudo_exec_argv(argv + 1);
Eric Andersen25f27032001-04-26 23:22:31 +0000780 /* never returns */
781}
782
783/* built-in 'exit' handler */
Denis Vlasenko1359da62007-04-21 23:27:30 +0000784static int builtin_exit(char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +0000785{
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000786// TODO: bash does it ONLY on top-level sh exit (+interacive only?)
787 //puts("exit"); /* bash does it */
Denis Vlasenkof2fffd02007-05-02 23:39:04 +0000788// TODO: warn if we have background jobs: "There are stopped jobs"
789// On second consecutive 'exit', exit anyway.
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000790
Denis Vlasenko1359da62007-04-21 23:27:30 +0000791 if (argv[1] == NULL)
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000792 hush_exit(last_return_code);
Denis Vlasenko5f786c22007-04-20 08:35:45 +0000793 /* mimic bash: exit 123abc == exit 255 + error msg */
794 xfunc_error_retval = 255;
795 /* bash: exit -2 == exit 254, no error msg */
Denis Vlasenkof2fffd02007-05-02 23:39:04 +0000796 hush_exit(xatoi(argv[1]) & 0xff);
Eric Andersen25f27032001-04-26 23:22:31 +0000797}
798
799/* built-in 'export VAR=value' handler */
Denis Vlasenko1359da62007-04-21 23:27:30 +0000800static int builtin_export(char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +0000801{
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000802 const char *value;
Denis Vlasenko1359da62007-04-21 23:27:30 +0000803 char *name = argv[1];
Eric Andersen25f27032001-04-26 23:22:31 +0000804
Eric Andersenf72f5622001-05-15 23:21:41 +0000805 if (name == NULL) {
Denis Vlasenkof2fffd02007-05-02 23:39:04 +0000806 // TODO:
807 // ash emits: export VAR='VAL'
808 // bash: declare -x VAR="VAL"
809 // (both also escape as needed (quotes, $, etc))
810 char **e = environ;
811 if (e)
812 while (*e)
813 puts(*e++);
814 return EXIT_SUCCESS;
Eric Andersen25f27032001-04-26 23:22:31 +0000815 }
Eric Andersenf72f5622001-05-15 23:21:41 +0000816
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000817 value = strchr(name, '=');
818 if (!value) {
819 /* They are exporting something without a =VALUE */
820 struct variable *var;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000821
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000822 var = get_local_var(name);
823 if (var) {
824 var->flg_export = 1;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +0000825 putenv(var->varstr);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000826 }
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000827 /* bash does not return an error when trying to export
828 * an undefined variable. Do likewise. */
829 return EXIT_SUCCESS;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000830 }
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000831
832 set_local_var(xstrdup(name), 1);
833 return EXIT_SUCCESS;
Eric Andersen25f27032001-04-26 23:22:31 +0000834}
835
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000836#if ENABLE_HUSH_JOB
Eric Andersen25f27032001-04-26 23:22:31 +0000837/* built-in 'fg' and 'bg' handler */
Denis Vlasenko1359da62007-04-21 23:27:30 +0000838static int builtin_fg_bg(char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +0000839{
Eric Andersen0fcd4472001-05-02 20:12:03 +0000840 int i, jobnum;
Denis Vlasenko8a28e622007-04-14 11:16:29 +0000841 struct pipe *pi;
Eric Andersen25f27032001-04-26 23:22:31 +0000842
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000843 if (!interactive_fd)
Eric Andersenc798b072001-06-22 06:23:03 +0000844 return EXIT_FAILURE;
Eric Andersen0fcd4472001-05-02 20:12:03 +0000845 /* If they gave us no args, assume they want the last backgrounded task */
Denis Vlasenko1359da62007-04-21 23:27:30 +0000846 if (!argv[1]) {
Eric Andersenc798b072001-06-22 06:23:03 +0000847 for (pi = job_list; pi; pi = pi->next) {
848 if (pi->jobid == last_jobid) {
Denis Vlasenko8a28e622007-04-14 11:16:29 +0000849 goto found;
Eric Andersen0fcd4472001-05-02 20:12:03 +0000850 }
851 }
Denis Vlasenko1359da62007-04-21 23:27:30 +0000852 bb_error_msg("%s: no current job", argv[0]);
Denis Vlasenko8a28e622007-04-14 11:16:29 +0000853 return EXIT_FAILURE;
854 }
Denis Vlasenko1359da62007-04-21 23:27:30 +0000855 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
856 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
Denis Vlasenko8a28e622007-04-14 11:16:29 +0000857 return EXIT_FAILURE;
858 }
859 for (pi = job_list; pi; pi = pi->next) {
860 if (pi->jobid == jobnum) {
861 goto found;
Eric Andersen25f27032001-04-26 23:22:31 +0000862 }
863 }
Denis Vlasenko1359da62007-04-21 23:27:30 +0000864 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
Denis Vlasenko8a28e622007-04-14 11:16:29 +0000865 return EXIT_FAILURE;
866 found:
Denis Vlasenko52881e92007-04-21 13:42:52 +0000867 // TODO: bash prints a string representation
868 // of job being foregrounded (like "sleep 1 | cat")
Denis Vlasenko1359da62007-04-21 23:27:30 +0000869 if (*argv[0] == 'f') {
Eric Andersen028b65b2001-06-28 01:10:11 +0000870 /* Put the job into the foreground. */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000871 tcsetpgrp(interactive_fd, pi->pgrp);
Eric Andersen25f27032001-04-26 23:22:31 +0000872 }
873
874 /* Restart the processes in the job */
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000875 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_progs, pi->pgrp);
Denis Vlasenko1359da62007-04-21 23:27:30 +0000876 for (i = 0; i < pi->num_progs; i++) {
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000877 debug_printf_jobs("reviving pid %d\n", pi->progs[i].pid);
Eric Andersen0fcd4472001-05-02 20:12:03 +0000878 pi->progs[i].is_stopped = 0;
Denis Vlasenko1359da62007-04-21 23:27:30 +0000879 }
880 pi->stopped_progs = 0;
Eric Andersen25f27032001-04-26 23:22:31 +0000881
Denis Vlasenkobb81c582007-01-30 22:32:09 +0000882 i = kill(- pi->pgrp, SIGCONT);
883 if (i < 0) {
Denis Vlasenko8a28e622007-04-14 11:16:29 +0000884 if (errno == ESRCH) {
Denis Vlasenko1359da62007-04-21 23:27:30 +0000885 delete_finished_bg_job(pi);
Denis Vlasenko3ac0e002007-04-28 16:45:22 +0000886 return EXIT_SUCCESS;
Eric Andersen028b65b2001-06-28 01:10:11 +0000887 } else {
Manuel Novoa III cad53642003-03-19 09:13:01 +0000888 bb_perror_msg("kill (SIGCONT)");
Eric Andersen028b65b2001-06-28 01:10:11 +0000889 }
890 }
Eric Andersen25f27032001-04-26 23:22:31 +0000891
Denis Vlasenko1359da62007-04-21 23:27:30 +0000892 if (*argv[0] == 'f') {
893 remove_bg_job(pi);
Denis Vlasenko52881e92007-04-21 13:42:52 +0000894 return checkjobs_and_fg_shell(pi);
Denis Vlasenko1359da62007-04-21 23:27:30 +0000895 }
Eric Andersen25f27032001-04-26 23:22:31 +0000896 return EXIT_SUCCESS;
897}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000898#endif
Eric Andersen25f27032001-04-26 23:22:31 +0000899
900/* built-in 'help' handler */
Denis Vlasenko06810332007-05-21 23:30:54 +0000901#if ENABLE_HUSH_HELP
Denis Vlasenko1359da62007-04-21 23:27:30 +0000902static int builtin_help(char **argv ATTRIBUTE_UNUSED)
Eric Andersen25f27032001-04-26 23:22:31 +0000903{
"Vladimir N. Oleynik"485d7cb2005-10-17 09:48:57 +0000904 const struct built_in_command *x;
Eric Andersen25f27032001-04-26 23:22:31 +0000905
906 printf("\nBuilt-in commands:\n");
907 printf("-------------------\n");
908 for (x = bltins; x->cmd; x++) {
Eric Andersen25f27032001-04-26 23:22:31 +0000909 printf("%s\t%s\n", x->cmd, x->descr);
910 }
911 printf("\n\n");
912 return EXIT_SUCCESS;
913}
Denis Vlasenko06810332007-05-21 23:30:54 +0000914#endif
Eric Andersen25f27032001-04-26 23:22:31 +0000915
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000916#if ENABLE_HUSH_JOB
Eric Andersen25f27032001-04-26 23:22:31 +0000917/* built-in 'jobs' handler */
Denis Vlasenko1359da62007-04-21 23:27:30 +0000918static int builtin_jobs(char **argv ATTRIBUTE_UNUSED)
Eric Andersen25f27032001-04-26 23:22:31 +0000919{
920 struct pipe *job;
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000921 const char *status_string;
Eric Andersen25f27032001-04-26 23:22:31 +0000922
Eric Andersenc798b072001-06-22 06:23:03 +0000923 for (job = job_list; job; job = job->next) {
Eric Andersen25f27032001-04-26 23:22:31 +0000924 if (job->running_progs == job->stopped_progs)
925 status_string = "Stopped";
926 else
927 status_string = "Running";
Eric Andersen52a97ca2001-06-22 06:49:26 +0000928
Denis Vlasenko3ac0e002007-04-28 16:45:22 +0000929 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
Eric Andersen25f27032001-04-26 23:22:31 +0000930 }
931 return EXIT_SUCCESS;
932}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000933#endif
Eric Andersen25f27032001-04-26 23:22:31 +0000934
Eric Andersen25f27032001-04-26 23:22:31 +0000935/* built-in 'pwd' handler */
Denis Vlasenko1359da62007-04-21 23:27:30 +0000936static int builtin_pwd(char **argv ATTRIBUTE_UNUSED)
Eric Andersen25f27032001-04-26 23:22:31 +0000937{
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000938 puts(set_cwd());
Eric Andersen25f27032001-04-26 23:22:31 +0000939 return EXIT_SUCCESS;
940}
941
942/* built-in 'read VAR' handler */
Denis Vlasenko1359da62007-04-21 23:27:30 +0000943static int builtin_read(char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +0000944{
Denis Vlasenkod67cef22007-06-13 06:47:47 +0000945 char *string;
Denis Vlasenko3e7b0e62007-05-16 12:52:15 +0000946 const char *name = argv[1] ? argv[1] : "REPLY";
Eric Andersen25f27032001-04-26 23:22:31 +0000947
Denis Vlasenkod67cef22007-06-13 06:47:47 +0000948 string = xmalloc_reads(STDIN_FILENO, xasprintf("%s=", name));
949 return set_local_var(string, 0);
Eric Andersen25f27032001-04-26 23:22:31 +0000950}
951
Denis Vlasenko3e7b0e62007-05-16 12:52:15 +0000952/* built-in 'set [VAR=value]' handler */
Denis Vlasenko1359da62007-04-21 23:27:30 +0000953static int builtin_set(char **argv)
Eric Andersenf72f5622001-05-15 23:21:41 +0000954{
Denis Vlasenko1359da62007-04-21 23:27:30 +0000955 char *temp = argv[1];
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000956 struct variable *e;
Eric Andersenf72f5622001-05-15 23:21:41 +0000957
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000958 if (temp == NULL)
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000959 for (e = top_var; e; e = e->next)
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +0000960 puts(e->varstr);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000961 else
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000962 set_local_var(xstrdup(temp), 0);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000963
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000964 return EXIT_SUCCESS;
Eric Andersenf72f5622001-05-15 23:21:41 +0000965}
966
967
Eric Andersen25f27032001-04-26 23:22:31 +0000968/* Built-in 'shift' handler */
Denis Vlasenko1359da62007-04-21 23:27:30 +0000969static int builtin_shift(char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +0000970{
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000971 int n = 1;
Denis Vlasenko1359da62007-04-21 23:27:30 +0000972 if (argv[1]) {
973 n = atoi(argv[1]);
Eric Andersen25f27032001-04-26 23:22:31 +0000974 }
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000975 if (n >= 0 && n < global_argc) {
Denis Vlasenko004baba2007-05-20 22:22:18 +0000976 global_argv[n] = global_argv[0];
Eric Andersen25f27032001-04-26 23:22:31 +0000977 global_argc -= n;
978 global_argv += n;
979 return EXIT_SUCCESS;
Eric Andersen25f27032001-04-26 23:22:31 +0000980 }
Denis Vlasenkof03dbed2007-04-13 19:55:50 +0000981 return EXIT_FAILURE;
Eric Andersen25f27032001-04-26 23:22:31 +0000982}
983
984/* Built-in '.' handler (read-in and execute commands from file) */
Denis Vlasenko1359da62007-04-21 23:27:30 +0000985static int builtin_source(char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +0000986{
987 FILE *input;
988 int status;
989
Denis Vlasenko1359da62007-04-21 23:27:30 +0000990 if (argv[1] == NULL)
Eric Andersen25f27032001-04-26 23:22:31 +0000991 return EXIT_FAILURE;
992
993 /* XXX search through $PATH is missing */
Denis Vlasenko1359da62007-04-21 23:27:30 +0000994 input = fopen(argv[1], "r");
Eric Andersen25f27032001-04-26 23:22:31 +0000995 if (!input) {
Denis Vlasenko1359da62007-04-21 23:27:30 +0000996 bb_error_msg("cannot open '%s'", argv[1]);
Eric Andersen25f27032001-04-26 23:22:31 +0000997 return EXIT_FAILURE;
998 }
999
1000 /* Now run the file */
1001 /* XXX argv and argc are broken; need to save old global_argv
1002 * (pointer only is OK!) on this stack frame,
Denis Vlasenko1359da62007-04-21 23:27:30 +00001003 * set global_argv=argv+1, recurse, and restore. */
Eric Andersen25f27032001-04-26 23:22:31 +00001004 mark_open(fileno(input));
Denis Vlasenko170435c2007-05-23 13:01:10 +00001005 status = parse_and_run_file(input);
Eric Andersen25f27032001-04-26 23:22:31 +00001006 mark_closed(fileno(input));
1007 fclose(input);
Denis Vlasenkod9e15f22006-11-27 16:49:55 +00001008 return status;
Eric Andersen25f27032001-04-26 23:22:31 +00001009}
1010
Denis Vlasenko1359da62007-04-21 23:27:30 +00001011static int builtin_umask(char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00001012{
Eric Andersen83a2ae22001-05-07 17:59:25 +00001013 mode_t new_umask;
Denis Vlasenko1359da62007-04-21 23:27:30 +00001014 const char *arg = argv[1];
Eric Andersen83a2ae22001-05-07 17:59:25 +00001015 char *end;
1016 if (arg) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001017 new_umask = strtoul(arg, &end, 8);
1018 if (*end != '\0' || end == arg) {
Eric Andersen83a2ae22001-05-07 17:59:25 +00001019 return EXIT_FAILURE;
1020 }
1021 } else {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001022 new_umask = umask(0);
1023 printf("%.3o\n", (unsigned) new_umask);
Eric Andersen83a2ae22001-05-07 17:59:25 +00001024 }
1025 umask(new_umask);
1026 return EXIT_SUCCESS;
Eric Andersen25f27032001-04-26 23:22:31 +00001027}
1028
1029/* built-in 'unset VAR' handler */
Denis Vlasenko1359da62007-04-21 23:27:30 +00001030static int builtin_unset(char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00001031{
Denis Vlasenko3e7b0e62007-05-16 12:52:15 +00001032 /* bash always returns true */
Denis Vlasenko1359da62007-04-21 23:27:30 +00001033 unset_local_var(argv[1]);
Eric Andersen25f27032001-04-26 23:22:31 +00001034 return EXIT_SUCCESS;
1035}
1036
Denis Vlasenko06810332007-05-21 23:30:54 +00001037//static int builtin_not_written(char **argv)
1038//{
1039// printf("builtin_%s not written\n", argv[0]);
1040// return EXIT_FAILURE;
1041//}
Eric Andersen83a2ae22001-05-07 17:59:25 +00001042
Eric Andersen25f27032001-04-26 23:22:31 +00001043static int b_check_space(o_string *o, int len)
1044{
1045 /* It would be easy to drop a more restrictive policy
1046 * in here, such as setting a maximum string length */
1047 if (o->length + len > o->maxlen) {
Denis Vlasenkof5294e12007-04-14 10:09:57 +00001048 /* assert(data == NULL || o->maxlen != 0); */
Denis Vlasenkoef36ead2007-05-02 15:34:47 +00001049 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001050 o->data = xrealloc(o->data, 1 + o->maxlen);
Eric Andersen25f27032001-04-26 23:22:31 +00001051 }
1052 return o->data == NULL;
1053}
1054
1055static int b_addchr(o_string *o, int ch)
1056{
Denis Vlasenko831dcc42007-05-16 15:05:36 +00001057 debug_printf("b_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001058 if (b_check_space(o, 1))
1059 return B_NOSPAC;
Eric Andersen25f27032001-04-26 23:22:31 +00001060 o->data[o->length] = ch;
1061 o->length++;
1062 o->data[o->length] = '\0';
1063 return 0;
1064}
1065
1066static void b_reset(o_string *o)
1067{
1068 o->length = 0;
1069 o->nonnull = 0;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001070 if (o->data != NULL)
1071 *o->data = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00001072}
1073
1074static void b_free(o_string *o)
1075{
1076 b_reset(o);
Aaron Lehmanna170e1c2002-11-28 11:27:31 +00001077 free(o->data);
Eric Andersen25f27032001-04-26 23:22:31 +00001078 o->data = NULL;
1079 o->maxlen = 0;
1080}
1081
1082/* My analysis of quoting semantics tells me that state information
1083 * is associated with a destination, not a source.
1084 */
1085static int b_addqchr(o_string *o, int ch, int quote)
1086{
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00001087 if (quote && strchr("*?[\\", ch)) {
Eric Andersen25f27032001-04-26 23:22:31 +00001088 int rc;
1089 rc = b_addchr(o, '\\');
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001090 if (rc)
1091 return rc;
Eric Andersen25f27032001-04-26 23:22:31 +00001092 }
1093 return b_addchr(o, ch);
1094}
1095
Eric Andersen25f27032001-04-26 23:22:31 +00001096static int static_get(struct in_str *i)
1097{
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001098 int ch = *i->p++;
1099 if (ch == '\0') return EOF;
Eric Andersen25f27032001-04-26 23:22:31 +00001100 return ch;
1101}
1102
1103static int static_peek(struct in_str *i)
1104{
1105 return *i->p;
1106}
1107
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001108#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001109#if ENABLE_FEATURE_EDITING
Rob Landley88621d72006-08-29 19:41:06 +00001110static void cmdedit_set_initial_prompt(void)
Eric Andersen25f27032001-04-26 23:22:31 +00001111{
Denis Vlasenko38f63192007-01-22 09:03:07 +00001112#if !ENABLE_FEATURE_EDITING_FANCY_PROMPT
Eric Andersen25f27032001-04-26 23:22:31 +00001113 PS1 = NULL;
1114#else
1115 PS1 = getenv("PS1");
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001116 if (PS1 == NULL)
Eric Andersen25f27032001-04-26 23:22:31 +00001117 PS1 = "\\w \\$ ";
Eric Andersenc7bda1c2004-03-15 08:29:22 +00001118#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001119}
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001120#endif /* EDITING */
Eric Andersen25f27032001-04-26 23:22:31 +00001121
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00001122static const char* setup_prompt_string(int promptmode)
Eric Andersen25f27032001-04-26 23:22:31 +00001123{
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00001124 const char *prompt_str;
1125 debug_printf("setup_prompt_string %d ", promptmode);
Denis Vlasenko38f63192007-01-22 09:03:07 +00001126#if !ENABLE_FEATURE_EDITING_FANCY_PROMPT
Eric Andersen25f27032001-04-26 23:22:31 +00001127 /* Set up the prompt */
Denis Vlasenko5a1437d2007-05-24 13:22:47 +00001128 if (promptmode == 0) { /* PS1 */
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00001129 free((char*)PS1);
Denis Vlasenko5a1437d2007-05-24 13:22:47 +00001130 PS1 = xasprintf("%s %c ", cwd, (geteuid() != 0) ? '$' : '#');
1131 prompt_str = PS1;
Eric Andersen25f27032001-04-26 23:22:31 +00001132 } else {
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00001133 prompt_str = PS2;
Eric Andersen25f27032001-04-26 23:22:31 +00001134 }
1135#else
Denis Vlasenko5a1437d2007-05-24 13:22:47 +00001136 prompt_str = (promptmode == 0) ? PS1 : PS2;
Eric Andersenaf44a0e2001-04-27 07:26:12 +00001137#endif
Denis Vlasenko5a1437d2007-05-24 13:22:47 +00001138 debug_printf("result '%s'\n", prompt_str);
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00001139 return prompt_str;
Eric Andersen25f27032001-04-26 23:22:31 +00001140}
1141
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001142static void get_user_input(struct in_str *i)
Eric Andersen25f27032001-04-26 23:22:31 +00001143{
Denis Vlasenko0937be52007-04-28 16:47:08 +00001144 int r;
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00001145 const char *prompt_str;
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001146
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00001147 prompt_str = setup_prompt_string(i->promptmode);
Denis Vlasenko38f63192007-01-22 09:03:07 +00001148#if ENABLE_FEATURE_EDITING
Denis Vlasenko170435c2007-05-23 13:01:10 +00001149 /* Enable command line editing only while a command line
1150 * is actually being read; otherwise, we'll end up bequeathing
1151 * atexit() handlers and other unwanted stuff to our
1152 * child processes (rob@sysgo.de) */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001153 r = read_line_input(prompt_str, user_input_buf, BUFSIZ-1, line_input_state);
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001154 i->eof_flag = (r < 0);
1155 if (i->eof_flag) { /* EOF/error detected */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001156 user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
1157 user_input_buf[1] = '\0';
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001158 }
Eric Andersen25f27032001-04-26 23:22:31 +00001159#else
1160 fputs(prompt_str, stdout);
1161 fflush(stdout);
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001162 user_input_buf[0] = r = fgetc(i->file);
1163 /*user_input_buf[1] = '\0'; - already is and never changed */
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001164 i->eof_flag = (r == EOF);
Eric Andersen25f27032001-04-26 23:22:31 +00001165#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001166 i->p = user_input_buf;
Eric Andersen25f27032001-04-26 23:22:31 +00001167}
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001168#endif /* INTERACTIVE */
Eric Andersen25f27032001-04-26 23:22:31 +00001169
Eric Andersenc7bda1c2004-03-15 08:29:22 +00001170/* This is the magic location that prints prompts
Eric Andersen25f27032001-04-26 23:22:31 +00001171 * and gets data back from the user */
1172static int file_get(struct in_str *i)
1173{
1174 int ch;
1175
Eric Andersen25f27032001-04-26 23:22:31 +00001176 /* If there is data waiting, eat it up */
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001177 if (i->p && *i->p) {
Denis Vlasenko96f67dc2007-05-17 13:02:41 +00001178#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001179 take_cached:
Denis Vlasenko96f67dc2007-05-17 13:02:41 +00001180#endif
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001181 ch = *i->p++;
1182 if (i->eof_flag && !*i->p)
1183 ch = EOF;
Eric Andersen25f27032001-04-26 23:22:31 +00001184 } else {
1185 /* need to double check i->file because we might be doing something
1186 * more complicated by now, like sourcing or substituting. */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001187#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko5a1437d2007-05-24 13:22:47 +00001188 if (interactive_fd && i->promptme && i->file == stdin) {
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001189 do {
1190 get_user_input(i);
1191 } while (!*i->p); /* need non-empty line */
Denis Vlasenko5a1437d2007-05-24 13:22:47 +00001192 i->promptmode = 1; /* PS2 */
1193 i->promptme = 0;
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001194 goto take_cached;
Eric Andersen25f27032001-04-26 23:22:31 +00001195 }
Denis Vlasenko96f67dc2007-05-17 13:02:41 +00001196#endif
1197 ch = fgetc(i->file);
Eric Andersen25f27032001-04-26 23:22:31 +00001198 }
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001199 debug_printf("file_get: got a '%c' %d\n", ch, ch);
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001200#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001201 if (ch == '\n')
Denis Vlasenko5a1437d2007-05-24 13:22:47 +00001202 i->promptme = 1;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001203#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001204 return ch;
1205}
1206
1207/* All the callers guarantee this routine will never be
1208 * used right after a newline, so prompting is not needed.
1209 */
1210static int file_peek(struct in_str *i)
1211{
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00001212 int ch;
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001213 if (i->p && *i->p) {
1214 if (i->eof_flag && !i->p[1])
1215 return EOF;
1216 return *i->p;
Eric Andersen25f27032001-04-26 23:22:31 +00001217 }
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00001218 ch = fgetc(i->file);
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001219 i->eof_flag = (ch == EOF);
1220 i->peek_buf[0] = ch;
1221 i->peek_buf[1] = '\0';
1222 i->p = i->peek_buf;
1223 debug_printf("file_peek: got a '%c' %d\n", *i->p, *i->p);
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00001224 return ch;
Eric Andersen25f27032001-04-26 23:22:31 +00001225}
1226
1227static void setup_file_in_str(struct in_str *i, FILE *f)
1228{
1229 i->peek = file_peek;
1230 i->get = file_get;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001231#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko5a1437d2007-05-24 13:22:47 +00001232 i->promptme = 1;
1233 i->promptmode = 0; /* PS1 */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001234#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001235 i->file = f;
1236 i->p = NULL;
1237}
1238
1239static void setup_string_in_str(struct in_str *i, const char *s)
1240{
1241 i->peek = static_peek;
1242 i->get = static_get;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001243#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko5a1437d2007-05-24 13:22:47 +00001244 i->promptme = 1;
1245 i->promptmode = 0; /* PS1 */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001246#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001247 i->p = s;
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001248 i->eof_flag = 0;
Eric Andersen25f27032001-04-26 23:22:31 +00001249}
1250
1251static void mark_open(int fd)
1252{
1253 struct close_me *new = xmalloc(sizeof(struct close_me));
1254 new->fd = fd;
1255 new->next = close_me_head;
1256 close_me_head = new;
1257}
1258
1259static void mark_closed(int fd)
1260{
1261 struct close_me *tmp;
1262 if (close_me_head == NULL || close_me_head->fd != fd)
Manuel Novoa III cad53642003-03-19 09:13:01 +00001263 bb_error_msg_and_die("corrupt close_me");
Eric Andersen25f27032001-04-26 23:22:31 +00001264 tmp = close_me_head;
1265 close_me_head = close_me_head->next;
1266 free(tmp);
1267}
1268
Eric Anderseneaecbf32001-10-31 10:41:31 +00001269static void close_all(void)
Eric Andersen25f27032001-04-26 23:22:31 +00001270{
1271 struct close_me *c;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001272 for (c = close_me_head; c; c = c->next) {
Eric Andersen25f27032001-04-26 23:22:31 +00001273 close(c->fd);
1274 }
1275 close_me_head = NULL;
1276}
1277
1278/* squirrel != NULL means we squirrel away copies of stdin, stdout,
1279 * and stderr if they are redirected. */
1280static int setup_redirects(struct child_prog *prog, int squirrel[])
1281{
1282 int openfd, mode;
1283 struct redir_struct *redir;
1284
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001285 for (redir = prog->redirects; redir; redir = redir->next) {
Eric Andersen817e73c2001-06-06 17:56:09 +00001286 if (redir->dup == -1 && redir->word.gl_pathv == NULL) {
1287 /* something went wrong in the parse. Pretend it didn't happen */
1288 continue;
1289 }
Eric Andersen25f27032001-04-26 23:22:31 +00001290 if (redir->dup == -1) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001291 mode = redir_table[redir->type].mode;
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00001292 openfd = open_or_warn(redir->word.gl_pathv[0], mode);
Eric Andersen25f27032001-04-26 23:22:31 +00001293 if (openfd < 0) {
1294 /* this could get lost if stderr has been redirected, but
1295 bash and ash both lose it as well (though zsh doesn't!) */
Eric Andersen25f27032001-04-26 23:22:31 +00001296 return 1;
1297 }
1298 } else {
1299 openfd = redir->dup;
1300 }
1301
1302 if (openfd != redir->fd) {
1303 if (squirrel && redir->fd < 3) {
1304 squirrel[redir->fd] = dup(redir->fd);
1305 }
Eric Andersen83a2ae22001-05-07 17:59:25 +00001306 if (openfd == -3) {
1307 close(openfd);
1308 } else {
1309 dup2(openfd, redir->fd);
Matt Kraaic616e532001-06-05 16:50:08 +00001310 if (redir->dup == -1)
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00001311 close(openfd);
Eric Andersen83a2ae22001-05-07 17:59:25 +00001312 }
Eric Andersen25f27032001-04-26 23:22:31 +00001313 }
1314 }
1315 return 0;
1316}
1317
1318static void restore_redirects(int squirrel[])
1319{
1320 int i, fd;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001321 for (i = 0; i < 3; i++) {
Eric Andersen25f27032001-04-26 23:22:31 +00001322 fd = squirrel[i];
1323 if (fd != -1) {
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00001324 /* We simply die on error */
1325 xmove_fd(fd, i);
Eric Andersen25f27032001-04-26 23:22:31 +00001326 }
1327 }
1328}
1329
Eric Andersenada18ff2001-05-21 16:18:22 +00001330/* never returns */
Eric Andersen94ac2442001-05-22 19:05:18 +00001331/* XXX no exit() here. If you don't exec, use _exit instead.
1332 * The at_exit handlers apparently confuse the calling process,
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00001333 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
Denis Vlasenko1359da62007-04-21 23:27:30 +00001334static void pseudo_exec_argv(char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00001335{
Eric Andersen78a7c992001-05-15 16:30:25 +00001336 int i, rcode;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00001337 char *p;
"Vladimir N. Oleynik"485d7cb2005-10-17 09:48:57 +00001338 const struct built_in_command *x;
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00001339
Denis Vlasenko1359da62007-04-21 23:27:30 +00001340 for (i = 0; is_assignment(argv[i]); i++) {
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001341 debug_printf_exec("pid %d environment modification: %s\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00001342 getpid(), argv[i]);
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001343// FIXME: vfork case??
Denis Vlasenko170435c2007-05-23 13:01:10 +00001344 p = expand_string_to_string(argv[i]);
1345 putenv(p);
Denis Vlasenko1359da62007-04-21 23:27:30 +00001346 }
1347 argv += i;
1348 /* If a variable is assigned in a forest, and nobody listens,
1349 * was it ever really set?
1350 */
1351 if (argv[0] == NULL) {
1352 _exit(EXIT_SUCCESS);
1353 }
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00001354
Denis Vlasenko170435c2007-05-23 13:01:10 +00001355 argv = expand_strvec_to_strvec(argv);
Denis Vlasenko764d59d2007-05-14 16:23:23 +00001356
Denis Vlasenko1359da62007-04-21 23:27:30 +00001357 /*
1358 * Check if the command matches any of the builtins.
1359 * Depending on context, this might be redundant. But it's
1360 * easier to waste a few CPU cycles than it is to figure out
1361 * if this is one of those cases.
1362 */
1363 for (x = bltins; x->cmd; x++) {
1364 if (strcmp(argv[0], x->cmd) == 0) {
Denis Vlasenko764d59d2007-05-14 16:23:23 +00001365 debug_printf_exec("running builtin '%s'\n", argv[0]);
Denis Vlasenko1359da62007-04-21 23:27:30 +00001366 rcode = x->function(argv);
1367 fflush(stdout);
1368 _exit(rcode);
Eric Andersen94ac2442001-05-22 19:05:18 +00001369 }
Denis Vlasenko1359da62007-04-21 23:27:30 +00001370 }
Eric Andersen78a7c992001-05-15 16:30:25 +00001371
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001372 /* Check if the command matches any busybox applets */
Denis Vlasenko80d14be2007-04-10 23:03:30 +00001373#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001374 if (strchr(argv[0], '/') == NULL) {
1375 const struct bb_applet *a = find_applet_by_name(argv[0]);
1376 if (a) {
1377 if (a->noexec) {
1378 current_applet = a;
1379 debug_printf_exec("running applet '%s'\n", argv[0]);
1380// is it ok that run_current_applet_and_exit() does exit(), not _exit()?
1381 run_current_applet_and_exit(argv);
1382 }
1383 /* re-exec ourselves with the new arguments */
1384 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
Denis Vlasenkobdbbb7e2007-06-08 15:02:55 +00001385 execvp(bb_busybox_exec_path, argv);
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001386 /* If they called chroot or otherwise made the binary no longer
1387 * executable, fall through */
1388 }
1389 }
Eric Andersenaac75e52001-04-30 18:18:45 +00001390#endif
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001391
1392 debug_printf_exec("execing '%s'\n", argv[0]);
Denis Vlasenko1359da62007-04-21 23:27:30 +00001393 execvp(argv[0], argv);
1394 bb_perror_msg("cannot exec '%s'", argv[0]);
1395 _exit(1);
1396}
1397
1398static void pseudo_exec(struct child_prog *child)
1399{
Denis Vlasenkof2fffd02007-05-02 23:39:04 +00001400// FIXME: buggy wrt NOMMU! Must not modify any global data
1401// until it does exec/_exit, but currently it does.
Denis Vlasenko1359da62007-04-21 23:27:30 +00001402 int rcode;
1403
1404 if (child->argv) {
1405 pseudo_exec_argv(child->argv);
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00001406 }
1407
1408 if (child->group) {
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00001409 // FIXME: do not modify globals! Think vfork!
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001410#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001411 debug_printf_exec("pseudo_exec: setting interactive_fd=0\n");
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001412 interactive_fd = 0; /* crucial!!!! */
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001413#endif
Denis Vlasenkod01ff132007-05-02 21:40:23 +00001414 debug_printf_exec("pseudo_exec: run_list_real\n");
Eric Andersen25f27032001-04-26 23:22:31 +00001415 rcode = run_list_real(child->group);
Eric Andersenbf7df042001-05-23 22:18:35 +00001416 /* OK to leak memory by not calling free_pipe_list,
Eric Andersen25f27032001-04-26 23:22:31 +00001417 * since this process is about to exit */
Eric Andersen94ac2442001-05-22 19:05:18 +00001418 _exit(rcode);
Eric Andersen25f27032001-04-26 23:22:31 +00001419 }
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00001420
1421 /* Can happen. See what bash does with ">foo" by itself. */
1422 debug_printf("trying to pseudo_exec null command\n");
1423 _exit(EXIT_SUCCESS);
Eric Andersen25f27032001-04-26 23:22:31 +00001424}
1425
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001426#if ENABLE_HUSH_JOB
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00001427static const char *get_cmdtext(struct pipe *pi)
1428{
1429 char **argv;
1430 char *p;
1431 int len;
1432
1433 /* This is subtle. ->cmdtext is created only on first backgrounding.
1434 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001435 * On subsequent bg argv is trashed, but we won't use it */
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00001436 if (pi->cmdtext)
1437 return pi->cmdtext;
1438 argv = pi->progs[0].argv;
1439 if (!argv || !argv[0])
1440 return (pi->cmdtext = xzalloc(1));
1441
1442 len = 0;
1443 do len += strlen(*argv) + 1; while (*++argv);
1444 pi->cmdtext = p = xmalloc(len);
1445 argv = pi->progs[0].argv;
1446 do {
1447 len = strlen(*argv);
1448 memcpy(p, *argv, len);
1449 p += len;
1450 *p++ = ' ';
1451 } while (*++argv);
1452 p[-1] = '\0';
1453 return pi->cmdtext;
1454}
1455
Eric Andersenbafd94f2001-05-02 16:11:59 +00001456static void insert_bg_job(struct pipe *pi)
1457{
1458 struct pipe *thejob;
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001459 int i;
Eric Andersenbafd94f2001-05-02 16:11:59 +00001460
1461 /* Linear search for the ID of the job to use */
1462 pi->jobid = 1;
Eric Andersenc798b072001-06-22 06:23:03 +00001463 for (thejob = job_list; thejob; thejob = thejob->next)
Eric Andersenbafd94f2001-05-02 16:11:59 +00001464 if (thejob->jobid >= pi->jobid)
1465 pi->jobid = thejob->jobid + 1;
1466
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001467 /* Add thejob to the list of running jobs */
Eric Andersenc798b072001-06-22 06:23:03 +00001468 if (!job_list) {
Eric Andersen52a97ca2001-06-22 06:49:26 +00001469 thejob = job_list = xmalloc(sizeof(*thejob));
Eric Andersenbafd94f2001-05-02 16:11:59 +00001470 } else {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001471 for (thejob = job_list; thejob->next; thejob = thejob->next)
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00001472 continue;
Eric Andersenbafd94f2001-05-02 16:11:59 +00001473 thejob->next = xmalloc(sizeof(*thejob));
1474 thejob = thejob->next;
1475 }
1476
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001477 /* Physically copy the struct job */
Eric Andersen0fcd4472001-05-02 20:12:03 +00001478 memcpy(thejob, pi, sizeof(struct pipe));
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001479 thejob->progs = xzalloc(sizeof(pi->progs[0]) * pi->num_progs);
1480 /* We cannot copy entire pi->progs[] vector! Double free()s will happen */
1481 for (i = 0; i < pi->num_progs; i++) {
1482// TODO: do we really need to have so many fields which are just dead weight
1483// at execution stage?
1484 thejob->progs[i].pid = pi->progs[i].pid;
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001485 /* all other fields are not used and stay zero */
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001486 }
Eric Andersenbafd94f2001-05-02 16:11:59 +00001487 thejob->next = NULL;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00001488 thejob->cmdtext = xstrdup(get_cmdtext(pi));
Eric Andersenbafd94f2001-05-02 16:11:59 +00001489
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001490 /* We don't wait for background thejobs to return -- append it
Eric Andersenbafd94f2001-05-02 16:11:59 +00001491 to the list of backgrounded thejobs and leave it alone */
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00001492 printf("[%d] %d %s\n", thejob->jobid, thejob->progs[0].pid, thejob->cmdtext);
Eric Andersen1a6d39b2001-05-08 05:11:54 +00001493 last_bg_pid = thejob->progs[0].pid;
Eric Andersenc798b072001-06-22 06:23:03 +00001494 last_jobid = thejob->jobid;
Eric Andersenbafd94f2001-05-02 16:11:59 +00001495}
1496
Eric Andersenbafd94f2001-05-02 16:11:59 +00001497static void remove_bg_job(struct pipe *pi)
1498{
1499 struct pipe *prev_pipe;
1500
Eric Andersenc798b072001-06-22 06:23:03 +00001501 if (pi == job_list) {
Eric Andersen52a97ca2001-06-22 06:49:26 +00001502 job_list = pi->next;
Eric Andersenbafd94f2001-05-02 16:11:59 +00001503 } else {
Eric Andersenc798b072001-06-22 06:23:03 +00001504 prev_pipe = job_list;
Eric Andersenbafd94f2001-05-02 16:11:59 +00001505 while (prev_pipe->next != pi)
1506 prev_pipe = prev_pipe->next;
1507 prev_pipe->next = pi->next;
1508 }
Eric Andersen028b65b2001-06-28 01:10:11 +00001509 if (job_list)
1510 last_jobid = job_list->jobid;
1511 else
1512 last_jobid = 0;
Denis Vlasenko1359da62007-04-21 23:27:30 +00001513}
Eric Andersen028b65b2001-06-28 01:10:11 +00001514
Denis Vlasenko1359da62007-04-21 23:27:30 +00001515/* remove a backgrounded job */
1516static void delete_finished_bg_job(struct pipe *pi)
1517{
1518 remove_bg_job(pi);
Eric Andersen52a97ca2001-06-22 06:49:26 +00001519 pi->stopped_progs = 0;
Eric Andersenbf7df042001-05-23 22:18:35 +00001520 free_pipe(pi, 0);
Eric Andersenbafd94f2001-05-02 16:11:59 +00001521 free(pi);
1522}
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001523#endif /* JOB */
Eric Andersenbafd94f2001-05-02 16:11:59 +00001524
Eric Andersenc7bda1c2004-03-15 08:29:22 +00001525/* Checks to see if any processes have exited -- if they
Eric Andersenbafd94f2001-05-02 16:11:59 +00001526 have, figure out why and see if a job has completed */
Eric Andersenc798b072001-06-22 06:23:03 +00001527static int checkjobs(struct pipe* fg_pipe)
Eric Andersenbafd94f2001-05-02 16:11:59 +00001528{
Eric Andersenc798b072001-06-22 06:23:03 +00001529 int attributes;
1530 int status;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001531#if ENABLE_HUSH_JOB
Eric Andersenbafd94f2001-05-02 16:11:59 +00001532 int prognum = 0;
1533 struct pipe *pi;
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001534#endif
Eric Andersenbafd94f2001-05-02 16:11:59 +00001535 pid_t childpid;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001536 int rcode = 0;
Eric Andersenbafd94f2001-05-02 16:11:59 +00001537
Eric Andersenc798b072001-06-22 06:23:03 +00001538 attributes = WUNTRACED;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001539 if (fg_pipe == NULL) {
Eric Andersenc798b072001-06-22 06:23:03 +00001540 attributes |= WNOHANG;
1541 }
1542
Denis Vlasenko1359da62007-04-21 23:27:30 +00001543/* Do we do this right?
1544 * bash-3.00# sleep 20 | false
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001545 * <ctrl-Z pressed>
Denis Vlasenko1359da62007-04-21 23:27:30 +00001546 * [3]+ Stopped sleep 20 | false
1547 * bash-3.00# echo $?
1548 * 1 <========== bg pipe is not fully done, but exitcode is already known!
1549 */
1550
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001551//FIXME: non-interactive bash does not continue even if all processes in fg pipe
1552//are stopped. Testcase: "cat | cat" in a script (not on command line)
1553// + killall -STOP cat
1554
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001555 wait_more:
Eric Andersenc798b072001-06-22 06:23:03 +00001556 while ((childpid = waitpid(-1, &status, attributes)) > 0) {
Denis Vlasenko1359da62007-04-21 23:27:30 +00001557 const int dead = WIFEXITED(status) || WIFSIGNALED(status);
1558
1559#ifdef DEBUG_SHELL_JOBS
1560 if (WIFSTOPPED(status))
Denis Vlasenkod01ff132007-05-02 21:40:23 +00001561 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00001562 childpid, WSTOPSIG(status), WEXITSTATUS(status));
1563 if (WIFSIGNALED(status))
Denis Vlasenkod01ff132007-05-02 21:40:23 +00001564 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00001565 childpid, WTERMSIG(status), WEXITSTATUS(status));
1566 if (WIFEXITED(status))
Denis Vlasenkod01ff132007-05-02 21:40:23 +00001567 debug_printf_jobs("pid %d exited, exitcode %d\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00001568 childpid, WEXITSTATUS(status));
1569#endif
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001570 /* Were we asked to wait for fg pipe? */
Eric Andersenc798b072001-06-22 06:23:03 +00001571 if (fg_pipe) {
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001572 int i;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001573 for (i = 0; i < fg_pipe->num_progs; i++) {
Denis Vlasenkod01ff132007-05-02 21:40:23 +00001574 debug_printf_jobs("check pid %d\n", fg_pipe->progs[i].pid);
Eric Andersenc798b072001-06-22 06:23:03 +00001575 if (fg_pipe->progs[i].pid == childpid) {
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001576 /* printf("process %d exit %d\n", i, WEXITSTATUS(status)); */
Denis Vlasenko1359da62007-04-21 23:27:30 +00001577 if (dead) {
1578 fg_pipe->progs[i].pid = 0;
1579 fg_pipe->running_progs--;
1580 if (i == fg_pipe->num_progs-1)
1581 /* last process gives overall exitstatus */
1582 rcode = WEXITSTATUS(status);
1583 } else {
1584 fg_pipe->progs[i].is_stopped = 1;
1585 fg_pipe->stopped_progs++;
1586 }
Denis Vlasenkod01ff132007-05-02 21:40:23 +00001587 debug_printf_jobs("fg_pipe: running_progs %d stopped_progs %d\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00001588 fg_pipe->running_progs, fg_pipe->stopped_progs);
1589 if (fg_pipe->running_progs - fg_pipe->stopped_progs <= 0) {
1590 /* All processes in fg pipe have exited/stopped */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001591#if ENABLE_HUSH_JOB
Denis Vlasenko1359da62007-04-21 23:27:30 +00001592 if (fg_pipe->running_progs)
1593 insert_bg_job(fg_pipe);
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001594#endif
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001595 return rcode;
Denis Vlasenko1359da62007-04-21 23:27:30 +00001596 }
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001597 /* There are still running processes in the fg pipe */
1598 goto wait_more;
Eric Andersenc798b072001-06-22 06:23:03 +00001599 }
1600 }
Denis Vlasenko1359da62007-04-21 23:27:30 +00001601 /* fall through to searching process in bg pipes */
Eric Andersenc798b072001-06-22 06:23:03 +00001602 }
1603
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001604#if ENABLE_HUSH_JOB
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001605 /* We asked to wait for bg or orphaned children */
1606 /* No need to remember exitcode in this case */
Eric Andersenc798b072001-06-22 06:23:03 +00001607 for (pi = job_list; pi; pi = pi->next) {
Eric Andersenbafd94f2001-05-02 16:11:59 +00001608 prognum = 0;
Denis Vlasenko5f786c22007-04-20 08:35:45 +00001609 while (prognum < pi->num_progs) {
1610 if (pi->progs[prognum].pid == childpid)
1611 goto found_pi_and_prognum;
Eric Andersen52a97ca2001-06-22 06:49:26 +00001612 prognum++;
1613 }
Eric Andersenbafd94f2001-05-02 16:11:59 +00001614 }
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001615#endif
Eric Andersenbafd94f2001-05-02 16:11:59 +00001616
Denis Vlasenko5f786c22007-04-20 08:35:45 +00001617 /* Happens when shell is used as init process (init=/bin/sh) */
1618 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
Denis Vlasenko1359da62007-04-21 23:27:30 +00001619 goto wait_more;
Eric Andersenaeb44c42001-05-22 20:29:00 +00001620
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001621#if ENABLE_HUSH_JOB
Denis Vlasenko5f786c22007-04-20 08:35:45 +00001622 found_pi_and_prognum:
Denis Vlasenko1359da62007-04-21 23:27:30 +00001623 if (dead) {
Eric Andersenbafd94f2001-05-02 16:11:59 +00001624 /* child exited */
Eric Andersenbafd94f2001-05-02 16:11:59 +00001625 pi->progs[prognum].pid = 0;
Denis Vlasenko1359da62007-04-21 23:27:30 +00001626 pi->running_progs--;
Eric Andersenbafd94f2001-05-02 16:11:59 +00001627 if (!pi->running_progs) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001628 printf(JOB_STATUS_FORMAT, pi->jobid,
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00001629 "Done", pi->cmdtext);
Denis Vlasenko1359da62007-04-21 23:27:30 +00001630 delete_finished_bg_job(pi);
Eric Andersenbafd94f2001-05-02 16:11:59 +00001631 }
1632 } else {
1633 /* child stopped */
1634 pi->stopped_progs++;
1635 pi->progs[prognum].is_stopped = 1;
Eric Andersenbafd94f2001-05-02 16:11:59 +00001636 }
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001637#endif
Eric Andersenbafd94f2001-05-02 16:11:59 +00001638 }
1639
Denis Vlasenko1359da62007-04-21 23:27:30 +00001640 /* wait found no children or failed */
1641
1642 if (childpid && errno != ECHILD)
Manuel Novoa III cad53642003-03-19 09:13:01 +00001643 bb_perror_msg("waitpid");
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001644 return rcode;
Eric Andersenada18ff2001-05-21 16:18:22 +00001645}
1646
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001647#if ENABLE_HUSH_JOB
Denis Vlasenko52881e92007-04-21 13:42:52 +00001648static int checkjobs_and_fg_shell(struct pipe* fg_pipe)
1649{
1650 pid_t p;
1651 int rcode = checkjobs(fg_pipe);
1652 /* Job finished, move the shell to the foreground */
Denis Vlasenko170435c2007-05-23 13:01:10 +00001653 p = getpgid(0); /* pgid of our process */
1654 debug_printf_jobs("fg'ing ourself: getpgid(0)=%d\n", (int)p);
Denis Vlasenko52881e92007-04-21 13:42:52 +00001655 if (tcsetpgrp(interactive_fd, p) && errno != ENOTTY)
1656 bb_perror_msg("tcsetpgrp-4a");
1657 return rcode;
1658}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001659#endif
Denis Vlasenko52881e92007-04-21 13:42:52 +00001660
Eric Andersen25f27032001-04-26 23:22:31 +00001661/* run_pipe_real() starts all the jobs, but doesn't wait for anything
Eric Andersenc798b072001-06-22 06:23:03 +00001662 * to finish. See checkjobs().
Eric Andersen25f27032001-04-26 23:22:31 +00001663 *
1664 * return code is normally -1, when the caller has to wait for children
1665 * to finish to determine the exit status of the pipe. If the pipe
1666 * is a simple builtin command, however, the action is done by the
1667 * time run_pipe_real returns, and the exit code is provided as the
1668 * return value.
1669 *
1670 * The input of the pipe is always stdin, the output is always
1671 * stdout. The outpipe[] mechanism in BusyBox-0.48 lash is bogus,
1672 * because it tries to avoid running the command substitution in
1673 * subshell, when that is in fact necessary. The subshell process
1674 * now has its stdout directed to the input of the appropriate pipe,
1675 * so this routine is noticeably simpler.
Denis Vlasenko170435c2007-05-23 13:01:10 +00001676 *
1677 * Returns -1 only if started some children. IOW: we have to
1678 * mask out retvals of builtins etc with 0xff!
Eric Andersen25f27032001-04-26 23:22:31 +00001679 */
1680static int run_pipe_real(struct pipe *pi)
1681{
1682 int i;
1683 int nextin, nextout;
1684 int pipefds[2]; /* pipefds[0] is for reading */
Rob Landley53702e52006-07-19 21:43:53 +00001685 struct child_prog *child;
"Vladimir N. Oleynik"485d7cb2005-10-17 09:48:57 +00001686 const struct built_in_command *x;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00001687 char *p;
Denis Vlasenkof5294e12007-04-14 10:09:57 +00001688 /* it is not always needed, but we aim to smaller code */
1689 int squirrel[] = { -1, -1, -1 };
1690 int rcode;
Denis Vlasenko52881e92007-04-21 13:42:52 +00001691 const int single_fg = (pi->num_progs == 1 && pi->followup != PIPE_BG);
Eric Andersen25f27032001-04-26 23:22:31 +00001692
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001693 debug_printf_exec("run_pipe_real start: single_fg=%d\n", single_fg);
Denis Vlasenko4ac530c2007-05-02 15:35:45 +00001694
Eric Andersen25f27032001-04-26 23:22:31 +00001695 nextin = 0;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001696#if ENABLE_HUSH_JOB
Eric Andersenada18ff2001-05-21 16:18:22 +00001697 pi->pgrp = -1;
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001698#endif
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001699 pi->running_progs = 1;
Denis Vlasenko1359da62007-04-21 23:27:30 +00001700 pi->stopped_progs = 0;
Eric Andersen25f27032001-04-26 23:22:31 +00001701
1702 /* Check if this is a simple builtin (not part of a pipe).
1703 * Builtins within pipes have to fork anyway, and are handled in
1704 * pseudo_exec. "echo foo | read bar" doesn't work on bash, either.
1705 */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001706 child = &(pi->progs[0]);
Denis Vlasenko52881e92007-04-21 13:42:52 +00001707 if (single_fg && child->group && child->subshell == 0) {
Eric Andersen04407e52001-06-07 16:42:05 +00001708 debug_printf("non-subshell grouping\n");
1709 setup_redirects(child, squirrel);
Denis Vlasenkod01ff132007-05-02 21:40:23 +00001710 debug_printf_exec(": run_list_real\n");
Eric Andersen04407e52001-06-07 16:42:05 +00001711 rcode = run_list_real(child->group);
1712 restore_redirects(squirrel);
Denis Vlasenkod01ff132007-05-02 21:40:23 +00001713 debug_printf_exec("run_pipe_real return %d\n", rcode);
Denis Vlasenko170435c2007-05-23 13:01:10 +00001714 return rcode; // do we need to add '... & 0xff' ?
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00001715 }
1716
Denis Vlasenko1359da62007-04-21 23:27:30 +00001717 if (single_fg && child->argv != NULL) {
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001718 char **argv_expanded;
Denis Vlasenko1359da62007-04-21 23:27:30 +00001719 char **argv = child->argv;
1720
1721 for (i = 0; is_assignment(argv[i]); i++)
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00001722 continue;
Denis Vlasenko1359da62007-04-21 23:27:30 +00001723 if (i != 0 && argv[i] == NULL) {
Eric Andersen78a7c992001-05-15 16:30:25 +00001724 /* assignments, but no command: set the local environment */
Denis Vlasenko1359da62007-04-21 23:27:30 +00001725 for (i = 0; argv[i] != NULL; i++) {
Denis Vlasenkod76c0492007-05-25 02:16:25 +00001726 debug_printf("local environment set: %s\n", argv[i]);
Denis Vlasenko170435c2007-05-23 13:01:10 +00001727 p = expand_string_to_string(argv[i]);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00001728 set_local_var(p, 0);
Eric Andersen78a7c992001-05-15 16:30:25 +00001729 }
1730 return EXIT_SUCCESS; /* don't worry about errors in set_local_var() yet */
1731 }
Denis Vlasenko1359da62007-04-21 23:27:30 +00001732 for (i = 0; is_assignment(argv[i]); i++) {
Denis Vlasenko170435c2007-05-23 13:01:10 +00001733 p = expand_string_to_string(argv[i]);
1734 //sp: child->sp--;
1735 putenv(p);
Eric Andersen4c9b68f2002-04-13 12:33:41 +00001736 }
Eric Andersen25f27032001-04-26 23:22:31 +00001737 for (x = bltins; x->cmd; x++) {
Denis Vlasenko1359da62007-04-21 23:27:30 +00001738 if (strcmp(argv[i], x->cmd) == 0) {
1739 if (x->function == builtin_exec && argv[i+1] == NULL) {
Eric Andersen83a2ae22001-05-07 17:59:25 +00001740 debug_printf("magic exec\n");
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00001741 setup_redirects(child, NULL);
Eric Andersen83a2ae22001-05-07 17:59:25 +00001742 return EXIT_SUCCESS;
1743 }
Denis Vlasenko1359da62007-04-21 23:27:30 +00001744 debug_printf("builtin inline %s\n", argv[0]);
Eric Andersen25f27032001-04-26 23:22:31 +00001745 /* XXX setup_redirects acts on file descriptors, not FILEs.
1746 * This is perfect for work that comes after exec().
1747 * Is it really safe for inline use? Experimentally,
1748 * things seem to work with glibc. */
1749 setup_redirects(child, squirrel);
Denis Vlasenkod01ff132007-05-02 21:40:23 +00001750 debug_printf_exec(": builtin '%s' '%s'...\n", x->cmd, argv[i+1]);
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001751 //sp: if (child->sp) /* btw we can do it unconditionally... */
Denis Vlasenko170435c2007-05-23 13:01:10 +00001752 argv_expanded = expand_strvec_to_strvec(argv + i);
1753 rcode = x->function(argv_expanded) & 0xff;
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001754 free(argv_expanded);
Eric Andersen25f27032001-04-26 23:22:31 +00001755 restore_redirects(squirrel);
Denis Vlasenkod01ff132007-05-02 21:40:23 +00001756 debug_printf_exec("run_pipe_real return %d\n", rcode);
Eric Andersen25f27032001-04-26 23:22:31 +00001757 return rcode;
1758 }
1759 }
Denis Vlasenkof5294e12007-04-14 10:09:57 +00001760#if ENABLE_FEATURE_SH_STANDALONE
1761 {
Denis Vlasenko1359da62007-04-21 23:27:30 +00001762 const struct bb_applet *a = find_applet_by_name(argv[i]);
Denis Vlasenkof5294e12007-04-14 10:09:57 +00001763 if (a && a->nofork) {
1764 setup_redirects(child, squirrel);
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001765 save_nofork_data(&nofork_save);
Denis Vlasenko764d59d2007-05-14 16:23:23 +00001766 argv_expanded = argv + i;
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001767 //sp: if (child->sp)
Denis Vlasenko170435c2007-05-23 13:01:10 +00001768 argv_expanded = expand_strvec_to_strvec(argv + i);
Denis Vlasenko764d59d2007-05-14 16:23:23 +00001769 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n", argv_expanded[0], argv_expanded[1]);
Denis Vlasenko170435c2007-05-23 13:01:10 +00001770 rcode = run_nofork_applet_prime(&nofork_save, a, argv_expanded) & 0xff;
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001771 free(argv_expanded);
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00001772 restore_redirects(squirrel);
Denis Vlasenkod01ff132007-05-02 21:40:23 +00001773 debug_printf_exec("run_pipe_real return %d\n", rcode);
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00001774 return rcode;
Denis Vlasenkof5294e12007-04-14 10:09:57 +00001775 }
1776 }
1777#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001778 }
1779
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00001780 /* Going to fork a child per each pipe member */
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001781 pi->running_progs = 0;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00001782
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001783 /* Disable job control signals for shell (parent) and
1784 * for initial child code after fork */
1785 set_jobctrl_sighandler(SIG_IGN);
1786
Eric Andersen25f27032001-04-26 23:22:31 +00001787 for (i = 0; i < pi->num_progs; i++) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001788 child = &(pi->progs[i]);
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001789 if (child->argv)
1790 debug_printf_exec(": pipe member '%s' '%s'...\n", child->argv[0], child->argv[1]);
1791 else
1792 debug_printf_exec(": pipe member with no argv\n");
Eric Andersen25f27032001-04-26 23:22:31 +00001793
1794 /* pipes are inserted between pairs of commands */
1795 if ((i + 1) < pi->num_progs) {
Denis Vlasenko5a6aedd2007-05-26 16:44:20 +00001796 pipe(pipefds);
Eric Andersen25f27032001-04-26 23:22:31 +00001797 nextout = pipefds[1];
1798 } else {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001799 nextout = 1;
Eric Andersen25f27032001-04-26 23:22:31 +00001800 pipefds[0] = -1;
1801 }
1802
1803 /* XXX test for failed fork()? */
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00001804#if BB_MMU
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001805 child->pid = fork();
Eric Andersen72f9a422001-10-28 05:12:20 +00001806#else
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001807 child->pid = vfork();
Eric Andersen72f9a422001-10-28 05:12:20 +00001808#endif
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001809 if (!child->pid) { /* child */
1810 /* Every child adds itself to new process group
1811 * with pgid == pid of first child in pipe */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001812#if ENABLE_HUSH_JOB
Denis Vlasenko170435c2007-05-23 13:01:10 +00001813 if (run_list_level == 1 && interactive_fd) {
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00001814 /* Don't do pgrp restore anymore on fatal signals */
1815 set_fatal_sighandler(SIG_DFL);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001816 if (pi->pgrp < 0) /* true for 1st process only */
1817 pi->pgrp = getpid();
1818 if (setpgid(0, pi->pgrp) == 0 && pi->followup != PIPE_BG) {
1819 /* We do it in *every* child, not just first,
1820 * to avoid races */
1821 tcsetpgrp(interactive_fd, pi->pgrp);
1822 }
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001823 }
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001824#endif
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001825 /* in non-interactive case fatal sigs are already SIG_DFL */
Eric Andersen25f27032001-04-26 23:22:31 +00001826 close_all();
Eric Andersen25f27032001-04-26 23:22:31 +00001827 if (nextin != 0) {
1828 dup2(nextin, 0);
1829 close(nextin);
1830 }
1831 if (nextout != 1) {
1832 dup2(nextout, 1);
1833 close(nextout);
1834 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00001835 if (pipefds[0] != -1) {
Eric Andersen25f27032001-04-26 23:22:31 +00001836 close(pipefds[0]); /* opposite end of our output pipe */
1837 }
Eric Andersen25f27032001-04-26 23:22:31 +00001838 /* Like bash, explicit redirects override pipes,
1839 * and the pipe fd is available for dup'ing. */
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00001840 setup_redirects(child, NULL);
Eric Andersen52a97ca2001-06-22 06:49:26 +00001841
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001842 /* Restore default handlers just prior to exec */
1843 set_jobctrl_sighandler(SIG_DFL);
1844 set_misc_sighandler(SIG_DFL);
1845 signal(SIGCHLD, SIG_DFL);
Eric Andersen25f27032001-04-26 23:22:31 +00001846 pseudo_exec(child);
1847 }
Eric Andersenc7bda1c2004-03-15 08:29:22 +00001848
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001849 pi->running_progs++;
1850
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001851#if ENABLE_HUSH_JOB
Denis Vlasenko2f1bb362007-04-21 10:01:14 +00001852 /* Second and next children need to know pid of first one */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001853 if (pi->pgrp < 0)
Eric Andersen0fcd4472001-05-02 20:12:03 +00001854 pi->pgrp = child->pid;
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001855#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001856 if (nextin != 0)
1857 close(nextin);
1858 if (nextout != 1)
1859 close(nextout);
1860
Eric Andersenc7bda1c2004-03-15 08:29:22 +00001861 /* If there isn't another process, nextin is garbage
Eric Andersen25f27032001-04-26 23:22:31 +00001862 but it doesn't matter */
1863 nextin = pipefds[0];
1864 }
Denis Vlasenkod01ff132007-05-02 21:40:23 +00001865 debug_printf_exec("run_pipe_real return -1\n");
Eric Andersen25f27032001-04-26 23:22:31 +00001866 return -1;
1867}
1868
Denis Vlasenko4b924f32007-05-30 00:29:55 +00001869#ifndef debug_print_tree
Denis Vlasenko400c5b62007-05-04 13:07:27 +00001870static void debug_print_tree(struct pipe *pi, int lvl)
1871{
1872 static const char *PIPE[] = {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001873 [PIPE_SEQ] = "SEQ",
1874 [PIPE_AND] = "AND",
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001875 [PIPE_OR ] = "OR" ,
1876 [PIPE_BG ] = "BG" ,
Denis Vlasenko400c5b62007-05-04 13:07:27 +00001877 };
1878 static const char *RES[] = {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001879 [RES_NONE ] = "NONE" ,
Denis Vlasenko06810332007-05-21 23:30:54 +00001880#if ENABLE_HUSH_IF
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001881 [RES_IF ] = "IF" ,
1882 [RES_THEN ] = "THEN" ,
1883 [RES_ELIF ] = "ELIF" ,
1884 [RES_ELSE ] = "ELSE" ,
1885 [RES_FI ] = "FI" ,
Denis Vlasenko06810332007-05-21 23:30:54 +00001886#endif
1887#if ENABLE_HUSH_LOOPS
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001888 [RES_FOR ] = "FOR" ,
1889 [RES_WHILE] = "WHILE",
1890 [RES_UNTIL] = "UNTIL",
1891 [RES_DO ] = "DO" ,
1892 [RES_DONE ] = "DONE" ,
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001893 [RES_IN ] = "IN" ,
Denis Vlasenko06810332007-05-21 23:30:54 +00001894#endif
1895 [RES_XXXX ] = "XXXX" ,
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001896 [RES_SNTX ] = "SNTX" ,
Denis Vlasenko400c5b62007-05-04 13:07:27 +00001897 };
1898
1899 int pin, prn;
Denis Vlasenko219e88d2007-05-21 10:18:23 +00001900
Denis Vlasenko400c5b62007-05-04 13:07:27 +00001901 pin = 0;
1902 while (pi) {
Denis Vlasenko219e88d2007-05-21 10:18:23 +00001903 fprintf(stderr, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
1904 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
Denis Vlasenko400c5b62007-05-04 13:07:27 +00001905 prn = 0;
1906 while (prn < pi->num_progs) {
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00001907 struct child_prog *child = &pi->progs[prn];
1908 char **argv = child->argv;
1909
Denis Vlasenko400c5b62007-05-04 13:07:27 +00001910 fprintf(stderr, "%*s prog %d", lvl*2, "", prn);
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00001911 if (child->group) {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001912 fprintf(stderr, " group %s: (argv=%p)\n",
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00001913 (child->subshell ? "()" : "{}"),
1914 argv);
1915 debug_print_tree(child->group, lvl+1);
Denis Vlasenko400c5b62007-05-04 13:07:27 +00001916 prn++;
1917 continue;
1918 }
Denis Vlasenko400c5b62007-05-04 13:07:27 +00001919 if (argv) while (*argv) {
1920 fprintf(stderr, " '%s'", *argv);
1921 argv++;
Denis Vlasenko4b924f32007-05-30 00:29:55 +00001922 }
Denis Vlasenko400c5b62007-05-04 13:07:27 +00001923 fprintf(stderr, "\n");
1924 prn++;
1925 }
1926 pi = pi->next;
1927 pin++;
1928 }
1929}
1930#endif
1931
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001932/* NB: called by pseudo_exec, and therefore must not modify any
1933 * global data until exec/_exit (we can be a child after vfork!) */
Eric Andersen25f27032001-04-26 23:22:31 +00001934static int run_list_real(struct pipe *pi)
1935{
Denis Vlasenko06810332007-05-21 23:30:54 +00001936 struct pipe *rpipe;
1937#if ENABLE_HUSH_LOOPS
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00001938 char *for_varname = NULL;
1939 char **for_lcur = NULL;
1940 char **for_list = NULL;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00001941 int flag_rep = 0;
Denis Vlasenko06810332007-05-21 23:30:54 +00001942#endif
Eric Andersen4c9b68f2002-04-13 12:33:41 +00001943 int save_num_progs;
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001944 int flag_skip = 1;
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00001945 int rcode = 0; /* probably for gcc only */
Eric Andersen4c9b68f2002-04-13 12:33:41 +00001946 int flag_restore = 0;
Denis Vlasenko06810332007-05-21 23:30:54 +00001947#if ENABLE_HUSH_IF
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001948 int if_code = 0, next_if_code = 0; /* need double-buffer to handle elif */
Denis Vlasenko06810332007-05-21 23:30:54 +00001949#else
1950 enum { if_code = 0, next_if_code = 0 };
1951#endif
Denis Vlasenko219e88d2007-05-21 10:18:23 +00001952 reserved_style rword;
1953 reserved_style skip_more_for_this_rword = RES_XXXX;
Denis Vlasenko4ac530c2007-05-02 15:35:45 +00001954
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001955 debug_printf_exec("run_list_real start lvl %d\n", run_list_level + 1);
Denis Vlasenko4ac530c2007-05-02 15:35:45 +00001956
Denis Vlasenko06810332007-05-21 23:30:54 +00001957#if ENABLE_HUSH_LOOPS
Eric Andersen4c9b68f2002-04-13 12:33:41 +00001958 /* check syntax for "for" */
1959 for (rpipe = pi; rpipe; rpipe = rpipe->next) {
Denis Vlasenko219e88d2007-05-21 10:18:23 +00001960 if ((rpipe->res_word == RES_IN || rpipe->res_word == RES_FOR)
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001961 && (rpipe->next == NULL)
1962 ) {
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001963 syntax("malformed for"); /* no IN or no commands after IN */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001964 debug_printf_exec("run_list_real lvl %d return 1\n", run_list_level);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001965 return 1;
Eric Andersenc7bda1c2004-03-15 08:29:22 +00001966 }
Denis Vlasenko219e88d2007-05-21 10:18:23 +00001967 if ((rpipe->res_word == RES_IN && rpipe->next->res_word == RES_IN && rpipe->next->progs[0].argv != NULL)
1968 || (rpipe->res_word == RES_FOR && rpipe->next->res_word != RES_IN)
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001969 ) {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001970 /* TODO: what is tested in the first condition? */
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001971 syntax("malformed for"); /* 2nd condition: not followed by IN */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001972 debug_printf_exec("run_list_real lvl %d return 1\n", run_list_level);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001973 return 1;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00001974 }
1975 }
Denis Vlasenko06810332007-05-21 23:30:54 +00001976#else
1977 rpipe = NULL;
1978#endif
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001979
1980#if ENABLE_HUSH_JOB
1981 /* Example of nested list: "while true; do { sleep 1 | exit 2; } done".
1982 * We are saving state before entering outermost list ("while...done")
1983 * so that ctrl-Z will correctly background _entire_ outermost list,
1984 * not just a part of it (like "sleep 1 | exit 2") */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001985 if (++run_list_level == 1 && interactive_fd) {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001986 if (sigsetjmp(toplevel_jb, 1)) {
1987 /* ctrl-Z forked and we are parent; or ctrl-C.
1988 * Sighandler has longjmped us here */
1989 signal(SIGINT, SIG_IGN);
1990 signal(SIGTSTP, SIG_IGN);
1991 /* Restore level (we can be coming from deep inside
1992 * nested levels) */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001993 run_list_level = 1;
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001994#if ENABLE_FEATURE_SH_STANDALONE
1995 if (nofork_save.saved) { /* if save area is valid */
1996 debug_printf_jobs("exiting nofork early\n");
1997 restore_nofork_data(&nofork_save);
1998 }
1999#endif
2000 if (ctrl_z_flag) {
2001 /* ctrl-Z has forked and stored pid of the child in pi->pid.
2002 * Remember this child as background job */
2003 insert_bg_job(pi);
2004 } else {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002005 /* ctrl-C. We just stop doing whatever we were doing */
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002006 putchar('\n');
2007 }
2008 rcode = 0;
2009 goto ret;
2010 }
2011 /* ctrl-Z handler will store pid etc in pi */
2012 toplevel_list = pi;
2013 ctrl_z_flag = 0;
2014#if ENABLE_FEATURE_SH_STANDALONE
2015 nofork_save.saved = 0; /* in case we will run a nofork later */
2016#endif
2017 signal_SA_RESTART(SIGTSTP, handler_ctrl_z);
2018 signal(SIGINT, handler_ctrl_c);
2019 }
2020#endif
2021
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002022 for (; pi; pi = flag_restore ? rpipe : pi->next) {
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002023 rword = pi->res_word;
Denis Vlasenko06810332007-05-21 23:30:54 +00002024#if ENABLE_HUSH_LOOPS
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002025 if (rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002026 flag_restore = 0;
2027 if (!rpipe) {
2028 flag_rep = 0;
2029 rpipe = pi;
2030 }
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002031 }
Denis Vlasenko06810332007-05-21 23:30:54 +00002032#endif
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002033 debug_printf_exec(": rword=%d if_code=%d next_if_code=%d skip_more=%d\n",
2034 rword, if_code, next_if_code, skip_more_for_this_rword);
2035 if (rword == skip_more_for_this_rword && flag_skip) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002036 if (pi->followup == PIPE_SEQ)
2037 flag_skip = 0;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002038 continue;
2039 }
2040 flag_skip = 1;
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002041 skip_more_for_this_rword = RES_XXXX;
Denis Vlasenko06810332007-05-21 23:30:54 +00002042#if ENABLE_HUSH_IF
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002043 if (rword == RES_THEN || rword == RES_ELSE)
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002044 if_code = next_if_code;
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002045 if (rword == RES_THEN && if_code)
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002046 continue;
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002047 if (rword == RES_ELSE && !if_code)
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002048 continue;
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002049 if (rword == RES_ELIF && !if_code)
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002050 break;
Denis Vlasenko06810332007-05-21 23:30:54 +00002051#endif
2052#if ENABLE_HUSH_LOOPS
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002053 if (rword == RES_FOR && pi->num_progs) {
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002054 if (!for_lcur) {
Eric Andersenc7bda1c2004-03-15 08:29:22 +00002055 /* if no variable values after "in" we skip "for" */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002056 if (!pi->next->progs->argv)
2057 continue;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002058 /* create list of variable values */
Denis Vlasenko170435c2007-05-23 13:01:10 +00002059 for_list = expand_strvec_to_strvec(pi->next->progs->argv);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002060 for_lcur = for_list;
2061 for_varname = pi->progs->argv[0];
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002062 pi->progs->argv[0] = NULL;
2063 flag_rep = 1;
Eric Andersenc7bda1c2004-03-15 08:29:22 +00002064 }
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002065 free(pi->progs->argv[0]);
2066 if (!*for_lcur) {
2067 free(for_list);
2068 for_lcur = NULL;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002069 flag_rep = 0;
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002070 pi->progs->argv[0] = for_varname;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002071 pi->progs->glob_result.gl_pathv[0] = pi->progs->argv[0];
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002072 continue;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002073 }
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002074 /* insert next value from for_lcur */
Denis Vlasenko764d59d2007-05-14 16:23:23 +00002075 /* vda: does it need escaping? */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002076 pi->progs->argv[0] = xasprintf("%s=%s", for_varname, *for_lcur++);
Denis Vlasenko5f786c22007-04-20 08:35:45 +00002077 pi->progs->glob_result.gl_pathv[0] = pi->progs->argv[0];
Eric Andersenc7bda1c2004-03-15 08:29:22 +00002078 }
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002079 if (rword == RES_IN)
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002080 continue;
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002081 if (rword == RES_DO) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002082 if (!flag_rep)
2083 continue;
Tim Rikerc1ef7bd2006-01-25 00:08:53 +00002084 }
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002085 if (rword == RES_DONE) {
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002086 if (flag_rep) {
2087 flag_restore = 1;
2088 } else {
2089 rpipe = NULL;
2090 }
Eric Andersenc7bda1c2004-03-15 08:29:22 +00002091 }
Denis Vlasenko06810332007-05-21 23:30:54 +00002092#endif
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002093 if (pi->num_progs == 0)
2094 continue;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002095 save_num_progs = pi->num_progs; /* save number of programs */
Denis Vlasenkod01ff132007-05-02 21:40:23 +00002096 debug_printf_exec(": run_pipe_real with %d members\n", pi->num_progs);
Eric Andersen25f27032001-04-26 23:22:31 +00002097 rcode = run_pipe_real(pi);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002098 if (rcode != -1) {
Eric Andersen25f27032001-04-26 23:22:31 +00002099 /* We only ran a builtin: rcode was set by the return value
2100 * of run_pipe_real(), and we don't need to wait for anything. */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002101 } else if (pi->followup == PIPE_BG) {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002102 /* What does bash do with attempts to background builtins? */
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002103 /* Even bash 3.2 doesn't do that well with nested bg:
2104 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
Denis Vlasenko170435c2007-05-23 13:01:10 +00002105 * I'm NOT treating inner &'s as jobs */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00002106#if ENABLE_HUSH_JOB
Denis Vlasenko4b924f32007-05-30 00:29:55 +00002107 if (run_list_level == 1)
Denis Vlasenko170435c2007-05-23 13:01:10 +00002108 insert_bg_job(pi);
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00002109#endif
Eric Andersen25f27032001-04-26 23:22:31 +00002110 rcode = EXIT_SUCCESS;
2111 } else {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00002112#if ENABLE_HUSH_JOB
Denis Vlasenko170435c2007-05-23 13:01:10 +00002113 /* Paranoia, just "interactive_fd" should be enough? */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00002114 if (run_list_level == 1 && interactive_fd) {
Denis Vlasenko170435c2007-05-23 13:01:10 +00002115 /* waits for completion, then fg's main shell */
Denis Vlasenko52881e92007-04-21 13:42:52 +00002116 rcode = checkjobs_and_fg_shell(pi);
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00002117 } else
2118#endif
2119 {
Denis Vlasenko170435c2007-05-23 13:01:10 +00002120 /* this one just waits for completion */
Eric Andersenc798b072001-06-22 06:23:03 +00002121 rcode = checkjobs(pi);
Eric Andersen25f27032001-04-26 23:22:31 +00002122 }
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002123 debug_printf_exec(": checkjobs returned %d\n", rcode);
Eric Andersen25f27032001-04-26 23:22:31 +00002124 }
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002125 debug_printf_exec(": setting last_return_code=%d\n", rcode);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002126 last_return_code = rcode;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002127 pi->num_progs = save_num_progs; /* restore number of programs */
Denis Vlasenko06810332007-05-21 23:30:54 +00002128#if ENABLE_HUSH_IF
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002129 if (rword == RES_IF || rword == RES_ELIF)
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002130 next_if_code = rcode; /* can be overwritten a number of times */
Denis Vlasenko06810332007-05-21 23:30:54 +00002131#endif
2132#if ENABLE_HUSH_LOOPS
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002133 if (rword == RES_WHILE)
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002134 flag_rep = !last_return_code;
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002135 if (rword == RES_UNTIL)
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002136 flag_rep = last_return_code;
Denis Vlasenko06810332007-05-21 23:30:54 +00002137#endif
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002138 if ((rcode == EXIT_SUCCESS && pi->followup == PIPE_OR)
2139 || (rcode != EXIT_SUCCESS && pi->followup == PIPE_AND)
2140 ) {
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002141 skip_more_for_this_rword = rword;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002142 }
Eric Andersen028b65b2001-06-28 01:10:11 +00002143 checkjobs(NULL);
Eric Andersen25f27032001-04-26 23:22:31 +00002144 }
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002145
2146#if ENABLE_HUSH_JOB
2147 if (ctrl_z_flag) {
2148 /* ctrl-Z forked somewhere in the past, we are the child,
2149 * and now we completed running the list. Exit. */
2150 exit(rcode);
2151 }
2152 ret:
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00002153 if (!--run_list_level && interactive_fd) {
2154 signal(SIGTSTP, SIG_IGN);
2155 signal(SIGINT, SIG_IGN);
2156 }
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002157#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00002158 debug_printf_exec("run_list_real lvl %d return %d\n", run_list_level + 1, rcode);
Eric Andersen25f27032001-04-26 23:22:31 +00002159 return rcode;
2160}
2161
Eric Andersen25f27032001-04-26 23:22:31 +00002162/* return code is the exit status of the pipe */
Eric Andersenbf7df042001-05-23 22:18:35 +00002163static int free_pipe(struct pipe *pi, int indent)
Eric Andersen25f27032001-04-26 23:22:31 +00002164{
2165 char **p;
2166 struct child_prog *child;
2167 struct redir_struct *r, *rnext;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002168 int a, i, ret_code = 0;
Eric Andersen52a97ca2001-06-22 06:49:26 +00002169
2170 if (pi->stopped_progs > 0)
2171 return ret_code;
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002172 debug_printf_clean("%s run pipe: (pid %d)\n", indenter(indent), getpid());
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002173 for (i = 0; i < pi->num_progs; i++) {
Eric Andersen25f27032001-04-26 23:22:31 +00002174 child = &pi->progs[i];
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002175 debug_printf_clean("%s command %d:\n", indenter(indent), i);
Eric Andersen25f27032001-04-26 23:22:31 +00002176 if (child->argv) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002177 for (a = 0, p = child->argv; *p; a++, p++) {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002178 debug_printf_clean("%s argv[%d] = %s\n", indenter(indent), a, *p);
Eric Andersen25f27032001-04-26 23:22:31 +00002179 }
2180 globfree(&child->glob_result);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002181 child->argv = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00002182 } else if (child->group) {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002183 debug_printf_clean("%s begin group (subshell:%d)\n", indenter(indent), child->subshell);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002184 ret_code = free_pipe_list(child->group, indent+3);
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002185 debug_printf_clean("%s end group\n", indenter(indent));
Eric Andersen25f27032001-04-26 23:22:31 +00002186 } else {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002187 debug_printf_clean("%s (nil)\n", indenter(indent));
Eric Andersen25f27032001-04-26 23:22:31 +00002188 }
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002189 for (r = child->redirects; r; r = rnext) {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002190 debug_printf_clean("%s redirect %d%s", indenter(indent), r->fd, redir_table[r->type].descrip);
Eric Andersen25f27032001-04-26 23:22:31 +00002191 if (r->dup == -1) {
Eric Andersen817e73c2001-06-06 17:56:09 +00002192 /* guard against the case >$FOO, where foo is unset or blank */
2193 if (r->word.gl_pathv) {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002194 debug_printf_clean(" %s\n", *r->word.gl_pathv);
Eric Andersen817e73c2001-06-06 17:56:09 +00002195 globfree(&r->word);
2196 }
Eric Andersen25f27032001-04-26 23:22:31 +00002197 } else {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002198 debug_printf_clean("&%d\n", r->dup);
Eric Andersen25f27032001-04-26 23:22:31 +00002199 }
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002200 rnext = r->next;
Eric Andersen25f27032001-04-26 23:22:31 +00002201 free(r);
2202 }
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002203 child->redirects = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00002204 }
2205 free(pi->progs); /* children are an array, they get freed all at once */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002206 pi->progs = NULL;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00002207#if ENABLE_HUSH_JOB
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00002208 free(pi->cmdtext);
2209 pi->cmdtext = NULL;
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00002210#endif
Eric Andersen25f27032001-04-26 23:22:31 +00002211 return ret_code;
2212}
2213
Eric Andersenbf7df042001-05-23 22:18:35 +00002214static int free_pipe_list(struct pipe *head, int indent)
Eric Andersen25f27032001-04-26 23:22:31 +00002215{
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002216 int rcode = 0; /* if list has no members */
Eric Andersen25f27032001-04-26 23:22:31 +00002217 struct pipe *pi, *next;
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002218
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002219 for (pi = head; pi; pi = next) {
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002220 debug_printf_clean("%s pipe reserved mode %d\n", indenter(indent), pi->res_word);
Eric Andersenbf7df042001-05-23 22:18:35 +00002221 rcode = free_pipe(pi, indent);
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002222 debug_printf_clean("%s pipe followup code %d\n", indenter(indent), pi->followup);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002223 next = pi->next;
Denis Vlasenko5f786c22007-04-20 08:35:45 +00002224 /*pi->next = NULL;*/
Eric Andersen25f27032001-04-26 23:22:31 +00002225 free(pi);
2226 }
Eric Andersenc7bda1c2004-03-15 08:29:22 +00002227 return rcode;
Eric Andersen25f27032001-04-26 23:22:31 +00002228}
2229
2230/* Select which version we will use */
2231static int run_list(struct pipe *pi)
2232{
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002233 int rcode = 0;
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002234 debug_printf_exec("run_list entered\n");
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002235 if (fake_mode == 0) {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002236 debug_printf_exec(": run_list_real with %d members\n", pi->num_progs);
Eric Andersen25f27032001-04-26 23:22:31 +00002237 rcode = run_list_real(pi);
Eric Andersenc7bda1c2004-03-15 08:29:22 +00002238 }
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002239 /* free_pipe_list has the side effect of clearing memory.
Eric Andersen25f27032001-04-26 23:22:31 +00002240 * In the long run that function can be merged with run_list_real,
2241 * but doing that now would hobble the debugging effort. */
Denis Vlasenko400c5b62007-05-04 13:07:27 +00002242 free_pipe_list(pi, 0);
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002243 debug_printf_exec("run_list return %d\n", rcode);
Eric Andersen25f27032001-04-26 23:22:31 +00002244 return rcode;
2245}
2246
2247/* The API for glob is arguably broken. This routine pushes a non-matching
2248 * string into the output structure, removing non-backslashed backslashes.
2249 * If someone can prove me wrong, by performing this function within the
2250 * original glob(3) api, feel free to rewrite this routine into oblivion.
2251 * Return code (0 vs. GLOB_NOSPACE) matches glob(3).
2252 * XXX broken if the last character is '\\', check that before calling.
2253 */
2254static int globhack(const char *src, int flags, glob_t *pglob)
2255{
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002256 int cnt = 0, pathc;
Eric Andersen25f27032001-04-26 23:22:31 +00002257 const char *s;
2258 char *dest;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002259 for (cnt = 1, s = src; s && *s; s++) {
Eric Andersen25f27032001-04-26 23:22:31 +00002260 if (*s == '\\') s++;
2261 cnt++;
2262 }
Denis Vlasenkoc666f712007-05-16 22:18:54 +00002263 dest = xmalloc(cnt);
Eric Andersen25f27032001-04-26 23:22:31 +00002264 if (!(flags & GLOB_APPEND)) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002265 pglob->gl_pathv = NULL;
2266 pglob->gl_pathc = 0;
2267 pglob->gl_offs = 0;
2268 pglob->gl_offs = 0;
Eric Andersen25f27032001-04-26 23:22:31 +00002269 }
2270 pathc = ++pglob->gl_pathc;
Denis Vlasenkoc666f712007-05-16 22:18:54 +00002271 pglob->gl_pathv = xrealloc(pglob->gl_pathv, (pathc+1) * sizeof(*pglob->gl_pathv));
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002272 pglob->gl_pathv[pathc-1] = dest;
2273 pglob->gl_pathv[pathc] = NULL;
2274 for (s = src; s && *s; s++, dest++) {
Eric Andersen25f27032001-04-26 23:22:31 +00002275 if (*s == '\\') s++;
2276 *dest = *s;
2277 }
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002278 *dest = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00002279 return 0;
2280}
2281
2282/* XXX broken if the last character is '\\', check that before calling */
2283static int glob_needed(const char *s)
2284{
2285 for (; *s; s++) {
2286 if (*s == '\\') s++;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002287 if (strchr("*[?", *s)) return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00002288 }
2289 return 0;
2290}
2291
Eric Andersen25f27032001-04-26 23:22:31 +00002292static int xglob(o_string *dest, int flags, glob_t *pglob)
2293{
2294 int gr;
2295
Tim Rikerc1ef7bd2006-01-25 00:08:53 +00002296 /* short-circuit for null word */
Eric Andersen25f27032001-04-26 23:22:31 +00002297 /* we can code this better when the debug_printf's are gone */
Tim Rikerc1ef7bd2006-01-25 00:08:53 +00002298 if (dest->length == 0) {
2299 if (dest->nonnull) {
2300 /* bash man page calls this an "explicit" null */
2301 gr = globhack(dest->data, flags, pglob);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002302 debug_printf("globhack returned %d\n", gr);
Tim Rikerc1ef7bd2006-01-25 00:08:53 +00002303 } else {
Eric Andersen25f27032001-04-26 23:22:31 +00002304 return 0;
2305 }
Tim Rikerc1ef7bd2006-01-25 00:08:53 +00002306 } else if (glob_needed(dest->data)) {
Eric Andersen25f27032001-04-26 23:22:31 +00002307 gr = glob(dest->data, flags, NULL, pglob);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002308 debug_printf("glob returned %d\n", gr);
Eric Andersen25f27032001-04-26 23:22:31 +00002309 if (gr == GLOB_NOMATCH) {
2310 /* quote removal, or more accurately, backslash removal */
2311 gr = globhack(dest->data, flags, pglob);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002312 debug_printf("globhack returned %d\n", gr);
Eric Andersen25f27032001-04-26 23:22:31 +00002313 }
2314 } else {
2315 gr = globhack(dest->data, flags, pglob);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002316 debug_printf("globhack returned %d\n", gr);
Eric Andersen25f27032001-04-26 23:22:31 +00002317 }
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002318 if (gr == GLOB_NOSPACE)
Manuel Novoa III cad53642003-03-19 09:13:01 +00002319 bb_error_msg_and_die("out of memory during glob");
Eric Andersen25f27032001-04-26 23:22:31 +00002320 if (gr != 0) { /* GLOB_ABORTED ? */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002321 bb_error_msg("glob(3) error %d", gr);
Eric Andersen25f27032001-04-26 23:22:31 +00002322 }
2323 /* globprint(glob_target); */
2324 return gr;
2325}
2326
Denis Vlasenko170435c2007-05-23 13:01:10 +00002327/* expand_strvec_to_strvec() takes a list of strings, expands
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002328 * all variable references within and returns a pointer to
2329 * a list of expanded strings, possibly with larger number
2330 * of strings. (Think VAR="a b"; echo $VAR).
2331 * This new list is allocated as a single malloc block.
2332 * NULL-terminated list of char* pointers is at the beginning of it,
2333 * followed by strings themself.
2334 * Caller can deallocate entire list by single free(list). */
2335
2336/* Helpers first:
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00002337 * count_XXX estimates size of the block we need. It's okay
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002338 * to over-estimate sizes a bit, if it makes code simpler */
2339static int count_ifs(const char *str)
2340{
2341 int cnt = 0;
2342 debug_printf_expand("count_ifs('%s') ifs='%s'", str, ifs);
2343 while (1) {
2344 str += strcspn(str, ifs);
2345 if (!*str) break;
Denis Vlasenkoc666f712007-05-16 22:18:54 +00002346 str++; /* str += strspn(str, ifs); */
2347 cnt++; /* cnt += strspn(str, ifs); - but this code is larger */
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00002348 }
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002349 debug_printf_expand(" return %d\n", cnt);
2350 return cnt;
2351}
2352
2353static void count_var_expansion_space(int *countp, int *lenp, char *arg)
2354{
2355 char first_ch;
2356 int i;
2357 int len = *lenp;
2358 int count = *countp;
2359 const char *val;
2360 char *p;
2361
2362 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL))) {
2363 len += p - arg;
2364 arg = ++p;
2365 p = strchr(p, SPECIAL_VAR_SYMBOL);
2366 first_ch = arg[0];
2367
2368 switch (first_ch & 0x7f) {
2369 /* high bit in 1st_ch indicates that var is double-quoted */
2370 case '$': /* pid */
2371 case '!': /* bg pid */
2372 case '?': /* exitcode */
2373 case '#': /* argc */
2374 len += sizeof(int)*3 + 1; /* enough for int */
2375 break;
2376 case '*':
2377 case '@':
2378 for (i = 1; i < global_argc; i++) {
2379 len += strlen(global_argv[i]) + 1;
2380 count++;
2381 if (!(first_ch & 0x80))
2382 count += count_ifs(global_argv[i]);
2383 }
2384 break;
2385 default:
2386 *p = '\0';
2387 arg[0] = first_ch & 0x7f;
Denis Vlasenko764d59d2007-05-14 16:23:23 +00002388 if (isdigit(arg[0])) {
2389 i = xatoi_u(arg);
2390 val = NULL;
2391 if (i < global_argc)
2392 val = global_argv[i];
2393 } else
2394 val = lookup_param(arg);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002395 arg[0] = first_ch;
2396 *p = SPECIAL_VAR_SYMBOL;
2397
2398 if (val) {
2399 len += strlen(val) + 1;
2400 if (!(first_ch & 0x80))
2401 count += count_ifs(val);
2402 }
2403 }
2404 arg = ++p;
2405 }
2406
2407 len += strlen(arg) + 1;
2408 count++;
2409 *lenp = len;
2410 *countp = count;
2411}
2412
2413/* Store given string, finalizing the word and starting new one whenever
2414 * we encounter ifs char(s). This is used for expanding variable values.
Denis Vlasenko764d59d2007-05-14 16:23:23 +00002415 * End-of-string does NOT finalize word: think about 'echo -$VAR-' */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002416static int expand_on_ifs(char **list, int n, char **posp, const char *str)
2417{
2418 char *pos = *posp;
2419 while (1) {
2420 int word_len = strcspn(str, ifs);
2421 if (word_len) {
2422 memcpy(pos, str, word_len); /* store non-ifs chars */
2423 pos += word_len;
2424 str += word_len;
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002425 }
Denis Vlasenko764d59d2007-05-14 16:23:23 +00002426 if (!*str) /* EOL - do not finalize word */
2427 break;
2428 *pos++ = '\0';
2429 if (n) debug_printf_expand("expand_on_ifs finalized list[%d]=%p '%s' "
2430 "strlen=%d next=%p pos=%p\n", n-1, list[n-1], list[n-1],
2431 strlen(list[n-1]), list[n-1] + strlen(list[n-1]) + 1, pos);
2432 list[n++] = pos;
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002433 str += strspn(str, ifs); /* skip ifs chars */
2434 }
2435 *posp = pos;
2436 return n;
2437}
2438
2439/* Expand all variable references in given string, adding words to list[]
2440 * at n, n+1,... positions. Return updated n (so that list[n] is next one
2441 * to be filled). This routine is extremely tricky: has to deal with
2442 * variables/parameters with whitespace, $* and $@, and constructs like
2443 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002444/* NB: another bug is that we cannot detect empty strings yet:
2445 * "" or $empty"" expands to zero words, has to expand to empty word */
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002446static int expand_vars_to_list(char **list, int n, char **posp, char *arg, char or_mask)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002447{
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002448 /* or_mask is either 0 (normal case) or 0x80
2449 * (expansion of right-hand side of assignment == 1-element expand) */
2450
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002451 char first_ch, ored_ch;
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00002452 int i;
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002453 const char *val;
2454 char *p;
2455 char *pos = *posp;
2456
2457 ored_ch = 0;
2458
2459 if (n) debug_printf_expand("expand_vars_to_list finalized list[%d]=%p '%s' "
2460 "strlen=%d next=%p pos=%p\n", n-1, list[n-1], list[n-1],
2461 strlen(list[n-1]), list[n-1] + strlen(list[n-1]) + 1, pos);
2462 list[n++] = pos;
2463
2464 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL))) {
2465 memcpy(pos, arg, p - arg);
2466 pos += (p - arg);
2467 arg = ++p;
2468 p = strchr(p, SPECIAL_VAR_SYMBOL);
2469
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002470 first_ch = arg[0] | or_mask; /* forced to "quoted" if or_mask = 0x80 */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002471 ored_ch |= first_ch;
2472 val = NULL;
2473 switch (first_ch & 0x7f) {
2474 /* Highest bit in first_ch indicates that var is double-quoted */
2475 case '$': /* pid */
2476 /* FIXME: (echo $$) should still print pid of main shell */
2477 val = utoa(getpid());
2478 break;
2479 case '!': /* bg pid */
2480 val = last_bg_pid ? utoa(last_bg_pid) : (char*)"";
2481 break;
2482 case '?': /* exitcode */
2483 val = utoa(last_return_code);
2484 break;
2485 case '#': /* argc */
2486 val = utoa(global_argc ? global_argc-1 : 0);
2487 break;
2488 case '*':
2489 case '@':
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00002490 i = 1;
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002491 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002492 while (i < global_argc) {
2493 n = expand_on_ifs(list, n, &pos, global_argv[i]);
2494 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, global_argc-1);
2495 if (global_argv[i++][0] && i < global_argc) {
2496 /* this argv[] is not empty and not last:
2497 * put terminating NUL, start new word */
2498 *pos++ = '\0';
2499 if (n) debug_printf_expand("expand_vars_to_list 2 finalized list[%d]=%p '%s' "
2500 "strlen=%d next=%p pos=%p\n", n-1, list[n-1], list[n-1],
2501 strlen(list[n-1]), list[n-1] + strlen(list[n-1]) + 1, pos);
2502 list[n++] = pos;
2503 }
2504 }
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002505 } else
2506 /* If or_mask is nonzero, we handle assignment 'a=....$@.....'
2507 * and in this case should theat it like '$*' */
2508 if (first_ch == ('@'|0x80) && !or_mask) { /* quoted $@ */
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00002509 while (1) {
2510 strcpy(pos, global_argv[i]);
2511 pos += strlen(global_argv[i]);
2512 if (++i >= global_argc)
2513 break;
2514 *pos++ = '\0';
2515 if (n) debug_printf_expand("expand_vars_to_list 3 finalized list[%d]=%p '%s' "
2516 "strlen=%d next=%p pos=%p\n", n-1, list[n-1], list[n-1],
2517 strlen(list[n-1]), list[n-1] + strlen(list[n-1]) + 1, pos);
2518 list[n++] = pos;
2519 }
2520 } else { /* quoted $*: add as one word */
2521 while (1) {
2522 strcpy(pos, global_argv[i]);
2523 pos += strlen(global_argv[i]);
2524 if (++i >= global_argc)
2525 break;
2526 if (ifs[0])
2527 *pos++ = ifs[0];
2528 }
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002529 }
2530 break;
2531 default:
2532 *p = '\0';
2533 arg[0] = first_ch & 0x7f;
Denis Vlasenko764d59d2007-05-14 16:23:23 +00002534 if (isdigit(arg[0])) {
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00002535 i = xatoi_u(arg);
Denis Vlasenko764d59d2007-05-14 16:23:23 +00002536 val = NULL;
2537 if (i < global_argc)
2538 val = global_argv[i];
2539 } else
2540 val = lookup_param(arg);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002541 arg[0] = first_ch;
2542 *p = SPECIAL_VAR_SYMBOL;
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00002543 if (!(first_ch & 0x80)) { /* unquoted $VAR */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002544 if (val) {
2545 n = expand_on_ifs(list, n, &pos, val);
2546 val = NULL;
2547 }
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00002548 } /* else: quoted $VAR, val will be appended at pos */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002549 }
2550 if (val) {
2551 strcpy(pos, val);
2552 pos += strlen(val);
2553 }
2554 arg = ++p;
2555 }
2556 debug_printf_expand("expand_vars_to_list adding tail '%s' at %p\n", arg, pos);
2557 strcpy(pos, arg);
2558 pos += strlen(arg) + 1;
2559 if (pos == list[n-1] + 1) { /* expansion is empty */
2560 if (!(ored_ch & 0x80)) { /* all vars were not quoted... */
2561 debug_printf_expand("expand_vars_to_list list[%d] empty, going back\n", n);
2562 pos--;
2563 n--;
2564 }
2565 }
2566
2567 *posp = pos;
2568 return n;
2569}
2570
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002571static char **expand_variables(char **argv, char or_mask)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002572{
2573 int n;
2574 int count = 1;
2575 int len = 0;
2576 char *pos, **v, **list;
2577
2578 v = argv;
2579 if (!*v) debug_printf_expand("count_var_expansion_space: "
2580 "argv[0]=NULL count=%d len=%d alloc_space=%d\n",
2581 count, len, sizeof(char*) * count + len);
2582 while (*v) {
2583 count_var_expansion_space(&count, &len, *v);
2584 debug_printf_expand("count_var_expansion_space: "
2585 "'%s' count=%d len=%d alloc_space=%d\n",
2586 *v, count, len, sizeof(char*) * count + len);
2587 v++;
2588 }
2589 len += sizeof(char*) * count; /* total to alloc */
2590 list = xmalloc(len);
2591 pos = (char*)(list + count);
2592 debug_printf_expand("list=%p, list[0] should be %p\n", list, pos);
2593 n = 0;
2594 v = argv;
2595 while (*v)
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002596 n = expand_vars_to_list(list, n, &pos, *v++, or_mask);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002597
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002598 if (n) debug_printf_expand("finalized list[%d]=%p '%s' "
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002599 "strlen=%d next=%p pos=%p\n", n-1, list[n-1], list[n-1],
2600 strlen(list[n-1]), list[n-1] + strlen(list[n-1]) + 1, pos);
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00002601 list[n] = NULL;
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002602
2603#ifdef DEBUG_EXPAND
2604 {
2605 int m = 0;
2606 while (m <= n) {
2607 debug_printf_expand("list[%d]=%p '%s'\n", m, list[m], list[m]);
2608 m++;
2609 }
2610 debug_printf_expand("used_space=%d\n", pos - (char*)list);
2611 }
2612#endif
Denis Vlasenko170435c2007-05-23 13:01:10 +00002613 if (ENABLE_HUSH_DEBUG)
2614 if (pos - (char*)list > len)
2615 bb_error_msg_and_die("BUG in varexp");
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00002616 return list;
2617}
2618
Denis Vlasenko170435c2007-05-23 13:01:10 +00002619static char **expand_strvec_to_strvec(char **argv)
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00002620{
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002621 return expand_variables(argv, 0);
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00002622}
2623
Denis Vlasenko170435c2007-05-23 13:01:10 +00002624static char *expand_string_to_string(const char *str)
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002625{
2626 char *argv[2], **list;
2627
2628 argv[0] = (char*)str;
2629 argv[1] = NULL;
2630 list = expand_variables(argv, 0x80); /* 0x80: make one-element expansion */
Denis Vlasenko170435c2007-05-23 13:01:10 +00002631 if (ENABLE_HUSH_DEBUG)
2632 if (!list[0] || list[1])
2633 bb_error_msg_and_die("BUG in varexp2");
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002634 /* actually, just move string 2*sizeof(char*) bytes back */
2635 strcpy((char*)list, list[0]);
Denis Vlasenko170435c2007-05-23 13:01:10 +00002636 debug_printf_expand("string_to_string='%s'\n", (char*)list);
2637 return (char*)list;
2638}
2639
2640static char* expand_strvec_to_string(char **argv)
2641{
2642 char **list;
2643
2644 list = expand_variables(argv, 0x80);
2645 /* Convert all NULs to spaces */
2646 if (list[0]) {
2647 int n = 1;
2648 while (list[n]) {
2649 if (ENABLE_HUSH_DEBUG)
2650 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
2651 bb_error_msg_and_die("BUG in varexp3");
2652 list[n][-1] = ' '; /* TODO: or to ifs[0]? */
2653 n++;
2654 }
2655 }
2656 strcpy((char*)list, list[0]);
2657 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002658 return (char*)list;
2659}
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002660
Eric Andersenf72f5622001-05-15 23:21:41 +00002661/* This is used to get/check local shell variables */
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002662static struct variable *get_local_var(const char *name)
Eric Andersenf72f5622001-05-15 23:21:41 +00002663{
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002664 struct variable *cur;
2665 int len;
Eric Andersenf72f5622001-05-15 23:21:41 +00002666
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002667 if (!name)
Eric Andersenf72f5622001-05-15 23:21:41 +00002668 return NULL;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002669 len = strlen(name);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002670 for (cur = top_var; cur; cur = cur->next) {
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002671 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002672 return cur;
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00002673 }
Eric Andersenf72f5622001-05-15 23:21:41 +00002674 return NULL;
2675}
2676
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002677/* str holds "NAME=VAL" and is expected to be malloced.
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002678 * We take ownership of it. */
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002679static int set_local_var(char *str, int flg_export)
Eric Andersen78a7c992001-05-15 16:30:25 +00002680{
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002681 struct variable *cur;
2682 char *value;
2683 int name_len;
Eric Andersen20a69a72001-05-15 17:24:44 +00002684
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002685 value = strchr(str, '=');
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002686 if (!value) { /* not expected to ever happen? */
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002687 free(str);
Eric Andersen99785762001-05-22 21:37:48 +00002688 return -1;
2689 }
Eric Andersen20a69a72001-05-15 17:24:44 +00002690
Denis Vlasenko201c72a2007-05-25 10:00:36 +00002691 name_len = value - str + 1; /* including '=' */
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002692 cur = top_var; /* cannot be NULL (we have HUSH_VERSION and it's RO) */
2693 while (1) {
Denis Vlasenko201c72a2007-05-25 10:00:36 +00002694 if (strncmp(cur->varstr, str, name_len) != 0) {
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002695 if (!cur->next) {
Denis Vlasenko201c72a2007-05-25 10:00:36 +00002696 /* Bail out. Note that now cur points
2697 * to last var in linked list */
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002698 break;
Eric Andersen20a69a72001-05-15 17:24:44 +00002699 }
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002700 cur = cur->next;
2701 continue;
Eric Andersen20a69a72001-05-15 17:24:44 +00002702 }
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002703 /* We found an existing var with this name */
2704 *value = '\0';
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002705 if (cur->flg_read_only) {
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002706 bb_error_msg("%s: readonly variable", str);
2707 free(str);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002708 return -1;
2709 }
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002710 unsetenv(str); /* just in case */
2711 *value = '=';
2712 if (strcmp(cur->varstr, str) == 0) {
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002713 free_and_exp:
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002714 free(str);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002715 goto exp;
2716 }
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002717 if (cur->max_len >= strlen(str)) {
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002718 /* This one is from startup env, reuse space */
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002719 strcpy(cur->varstr, str);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002720 goto free_and_exp;
2721 }
2722 /* max_len == 0 signifies "malloced" var, which we can
2723 * (and has to) free */
2724 if (!cur->max_len)
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002725 free(cur->varstr);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002726 cur->max_len = 0;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002727 goto set_str_and_exp;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002728 }
Eric Andersen20a69a72001-05-15 17:24:44 +00002729
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002730 /* Not found - create next variable struct */
2731 cur->next = xzalloc(sizeof(*cur));
2732 cur = cur->next;
2733
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002734 set_str_and_exp:
2735 cur->varstr = str;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002736 exp:
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002737 if (flg_export)
2738 cur->flg_export = 1;
2739 if (cur->flg_export)
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002740 return putenv(cur->varstr);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002741 return 0;
Eric Andersen20a69a72001-05-15 17:24:44 +00002742}
2743
Eric Andersenf72f5622001-05-15 23:21:41 +00002744static void unset_local_var(const char *name)
Eric Andersen20a69a72001-05-15 17:24:44 +00002745{
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002746 struct variable *cur;
2747 struct variable *prev = prev; /* for gcc */
2748 int name_len;
Eric Andersen20a69a72001-05-15 17:24:44 +00002749
Denis Vlasenko5f786c22007-04-20 08:35:45 +00002750 if (!name)
2751 return;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002752 name_len = strlen(name);
2753 cur = top_var;
2754 while (cur) {
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002755 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002756 if (cur->flg_read_only) {
Manuel Novoa III cad53642003-03-19 09:13:01 +00002757 bb_error_msg("%s: readonly variable", name);
Eric Andersen94ac2442001-05-22 19:05:18 +00002758 return;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002759 }
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002760 /* prev is ok to use here because 1st variable, HUSH_VERSION,
2761 * is ro, and we cannot reach this code on the 1st pass */
2762 prev->next = cur->next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002763 unsetenv(cur->varstr);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002764 if (!cur->max_len)
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002765 free(cur->varstr);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002766 free(cur);
Denis Vlasenko5f786c22007-04-20 08:35:45 +00002767 return;
Eric Andersenf72f5622001-05-15 23:21:41 +00002768 }
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002769 prev = cur;
2770 cur = cur->next;
Eric Andersen20a69a72001-05-15 17:24:44 +00002771 }
Eric Andersen78a7c992001-05-15 16:30:25 +00002772}
2773
2774static int is_assignment(const char *s)
2775{
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002776 if (!s || !isalpha(*s))
2777 return 0;
2778 s++;
2779 while (isalnum(*s) || *s == '_')
2780 s++;
2781 return *s == '=';
Eric Andersen78a7c992001-05-15 16:30:25 +00002782}
2783
Eric Andersen25f27032001-04-26 23:22:31 +00002784/* the src parameter allows us to peek forward to a possible &n syntax
2785 * for file descriptor duplication, e.g., "2>&1".
2786 * Return code is 0 normally, 1 if a syntax error is detected in src.
2787 * Resource errors (in xmalloc) cause the process to exit */
2788static int setup_redirect(struct p_context *ctx, int fd, redir_type style,
2789 struct in_str *input)
2790{
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002791 struct child_prog *child = ctx->child;
Eric Andersen25f27032001-04-26 23:22:31 +00002792 struct redir_struct *redir = child->redirects;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002793 struct redir_struct *last_redir = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00002794
2795 /* Create a new redir_struct and drop it onto the end of the linked list */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002796 while (redir) {
2797 last_redir = redir;
2798 redir = redir->next;
Eric Andersen25f27032001-04-26 23:22:31 +00002799 }
2800 redir = xmalloc(sizeof(struct redir_struct));
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002801 redir->next = NULL;
2802 redir->word.gl_pathv = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00002803 if (last_redir) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002804 last_redir->next = redir;
Eric Andersen25f27032001-04-26 23:22:31 +00002805 } else {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002806 child->redirects = redir;
Eric Andersen25f27032001-04-26 23:22:31 +00002807 }
2808
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002809 redir->type = style;
2810 redir->fd = (fd == -1) ? redir_table[style].default_fd : fd;
Eric Andersen25f27032001-04-26 23:22:31 +00002811
2812 debug_printf("Redirect type %d%s\n", redir->fd, redir_table[style].descrip);
2813
Eric Andersenc7bda1c2004-03-15 08:29:22 +00002814 /* Check for a '2>&1' type redirect */
Eric Andersen25f27032001-04-26 23:22:31 +00002815 redir->dup = redirect_dup_num(input);
2816 if (redir->dup == -2) return 1; /* syntax error */
2817 if (redir->dup != -1) {
2818 /* Erik had a check here that the file descriptor in question
Eric Andersen83a2ae22001-05-07 17:59:25 +00002819 * is legit; I postpone that to "run time"
2820 * A "-" representation of "close me" shows up as a -3 here */
Eric Andersen25f27032001-04-26 23:22:31 +00002821 debug_printf("Duplicating redirect '%d>&%d'\n", redir->fd, redir->dup);
2822 } else {
2823 /* We do _not_ try to open the file that src points to,
2824 * since we need to return and let src be expanded first.
2825 * Set ctx->pending_redirect, so we know what to do at the
Denis Vlasenko201c72a2007-05-25 10:00:36 +00002826 * end of the next parsed word. */
Eric Andersen25f27032001-04-26 23:22:31 +00002827 ctx->pending_redirect = redir;
2828 }
2829 return 0;
2830}
2831
Denis Vlasenkoac678ec2007-04-16 22:32:04 +00002832static struct pipe *new_pipe(void)
2833{
Eric Andersen25f27032001-04-26 23:22:31 +00002834 struct pipe *pi;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00002835 pi = xzalloc(sizeof(struct pipe));
2836 /*pi->num_progs = 0;*/
2837 /*pi->progs = NULL;*/
2838 /*pi->next = NULL;*/
2839 /*pi->followup = 0; invalid */
2840 if (RES_NONE)
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002841 pi->res_word = RES_NONE;
Eric Andersen25f27032001-04-26 23:22:31 +00002842 return pi;
2843}
2844
2845static void initialize_context(struct p_context *ctx)
2846{
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002847 ctx->child = NULL;
Denis Vlasenko1a735862007-05-23 00:32:25 +00002848 ctx->pipe = ctx->list_head = new_pipe();
2849 ctx->pending_redirect = NULL;
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002850 ctx->res_w = RES_NONE;
Denis Vlasenko1a735862007-05-23 00:32:25 +00002851 //only ctx->parse_type is not touched... is this intentional?
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002852 ctx->old_flag = 0;
Denis Vlasenko1a735862007-05-23 00:32:25 +00002853 ctx->stack = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00002854 done_command(ctx); /* creates the memory for working child */
2855}
2856
2857/* normal return is 0
2858 * if a reserved word is found, and processed, return 1
2859 * should handle if, then, elif, else, fi, for, while, until, do, done.
2860 * case, function, and select are obnoxious, save those for later.
2861 */
Denis Vlasenko06810332007-05-21 23:30:54 +00002862#if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS
"Vladimir N. Oleynik"19c37012005-09-22 14:33:15 +00002863static int reserved_word(o_string *dest, struct p_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00002864{
2865 struct reserved_combo {
Denis Vlasenko5f786c22007-04-20 08:35:45 +00002866 char literal[7];
2867 unsigned char code;
2868 int flag;
Eric Andersen25f27032001-04-26 23:22:31 +00002869 };
2870 /* Mostly a list of accepted follow-up reserved words.
2871 * FLAG_END means we are done with the sequence, and are ready
2872 * to turn the compound list into a command.
2873 * FLAG_START means the word must start a new compound list.
2874 */
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00002875 static const struct reserved_combo reserved_list[] = {
Denis Vlasenko06810332007-05-21 23:30:54 +00002876#if ENABLE_HUSH_IF
Eric Andersen25f27032001-04-26 23:22:31 +00002877 { "if", RES_IF, FLAG_THEN | FLAG_START },
2878 { "then", RES_THEN, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
2879 { "elif", RES_ELIF, FLAG_THEN },
2880 { "else", RES_ELSE, FLAG_FI },
2881 { "fi", RES_FI, FLAG_END },
Denis Vlasenko06810332007-05-21 23:30:54 +00002882#endif
2883#if ENABLE_HUSH_LOOPS
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002884 { "for", RES_FOR, FLAG_IN | FLAG_START },
Eric Andersen25f27032001-04-26 23:22:31 +00002885 { "while", RES_WHILE, FLAG_DO | FLAG_START },
2886 { "until", RES_UNTIL, FLAG_DO | FLAG_START },
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002887 { "in", RES_IN, FLAG_DO },
Eric Andersen25f27032001-04-26 23:22:31 +00002888 { "do", RES_DO, FLAG_DONE },
2889 { "done", RES_DONE, FLAG_END }
Denis Vlasenko06810332007-05-21 23:30:54 +00002890#endif
Eric Andersen25f27032001-04-26 23:22:31 +00002891 };
Denis Vlasenko7d4c44e2007-04-16 22:34:39 +00002892 enum { NRES = sizeof(reserved_list)/sizeof(reserved_list[0]) };
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00002893 const struct reserved_combo *r;
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00002894
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002895 for (r = reserved_list; r < reserved_list + NRES; r++) {
Denis Vlasenko1a735862007-05-23 00:32:25 +00002896 if (strcmp(dest->data, r->literal) != 0)
2897 continue;
2898 debug_printf("found reserved word %s, code %d\n", r->literal, r->code);
2899 if (r->flag & FLAG_START) {
2900 struct p_context *new;
2901 debug_printf("push stack\n");
Denis Vlasenko06810332007-05-21 23:30:54 +00002902#if ENABLE_HUSH_LOOPS
Denis Vlasenko1a735862007-05-23 00:32:25 +00002903 if (ctx->res_w == RES_IN || ctx->res_w == RES_FOR) {
Denis Vlasenko90e485c2007-05-23 15:22:50 +00002904 syntax("malformed for"); /* example: 'for if' */
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002905 ctx->res_w = RES_SNTX;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002906 b_reset(dest);
Eric Andersenaf44a0e2001-04-27 07:26:12 +00002907 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00002908 }
Denis Vlasenko1a735862007-05-23 00:32:25 +00002909#endif
2910 new = xmalloc(sizeof(*new));
2911 *new = *ctx; /* physical copy */
2912 initialize_context(ctx);
2913 ctx->stack = new;
2914 } else if (ctx->res_w == RES_NONE || !(ctx->old_flag & (1 << r->code))) {
Denis Vlasenko90e485c2007-05-23 15:22:50 +00002915 syntax(NULL);
Denis Vlasenko1a735862007-05-23 00:32:25 +00002916 ctx->res_w = RES_SNTX;
Denis Vlasenkoff131b92007-04-10 15:42:06 +00002917 b_reset(dest);
Eric Andersen25f27032001-04-26 23:22:31 +00002918 return 1;
2919 }
Denis Vlasenko1a735862007-05-23 00:32:25 +00002920 ctx->res_w = r->code;
2921 ctx->old_flag = r->flag;
2922 if (ctx->old_flag & FLAG_END) {
2923 struct p_context *old;
2924 debug_printf("pop stack\n");
2925 done_pipe(ctx, PIPE_SEQ);
2926 old = ctx->stack;
2927 old->child->group = ctx->list_head;
2928 old->child->subshell = 0;
2929 *ctx = *old; /* physical copy */
2930 free(old);
2931 }
2932 b_reset(dest);
2933 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00002934 }
2935 return 0;
2936}
Denis Vlasenko06810332007-05-21 23:30:54 +00002937#else
2938#define reserved_word(dest, ctx) ((int)0)
2939#endif
Eric Andersen25f27032001-04-26 23:22:31 +00002940
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00002941/* Normal return is 0.
Eric Andersen25f27032001-04-26 23:22:31 +00002942 * Syntax or xglob errors return 1. */
2943static int done_word(o_string *dest, struct p_context *ctx)
2944{
Denis Vlasenkobb81c582007-01-30 22:32:09 +00002945 struct child_prog *child = ctx->child;
Eric Andersen25f27032001-04-26 23:22:31 +00002946 glob_t *glob_target;
2947 int gr, flags = 0;
2948
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002949 debug_printf_parse("done_word entered: '%s' %p\n", dest->data, child);
Eric Andersen25f27032001-04-26 23:22:31 +00002950 if (dest->length == 0 && !dest->nonnull) {
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00002951 debug_printf_parse("done_word return 0: true null, ignored\n");
Eric Andersen25f27032001-04-26 23:22:31 +00002952 return 0;
2953 }
2954 if (ctx->pending_redirect) {
2955 glob_target = &ctx->pending_redirect->word;
2956 } else {
2957 if (child->group) {
Denis Vlasenko90e485c2007-05-23 15:22:50 +00002958 syntax(NULL);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00002959 debug_printf_parse("done_word return 1: syntax error, groups and arglists don't mix\n");
2960 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00002961 }
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002962 if (!child->argv && (ctx->parse_type & PARSEFLAG_SEMICOLON)) {
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002963 debug_printf_parse(": checking '%s' for reserved-ness\n", dest->data);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00002964 if (reserved_word(dest, ctx)) {
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002965 debug_printf_parse("done_word return %d\n", (ctx->res_w == RES_SNTX));
2966 return (ctx->res_w == RES_SNTX);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00002967 }
Eric Andersen25f27032001-04-26 23:22:31 +00002968 }
2969 glob_target = &child->glob_result;
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002970 if (child->argv)
2971 flags |= GLOB_APPEND;
Eric Andersen25f27032001-04-26 23:22:31 +00002972 }
2973 gr = xglob(dest, flags, glob_target);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00002974 if (gr != 0) {
2975 debug_printf_parse("done_word return 1: xglob returned %d\n", gr);
2976 return 1;
2977 }
Eric Andersen25f27032001-04-26 23:22:31 +00002978
2979 b_reset(dest);
2980 if (ctx->pending_redirect) {
Denis Vlasenkobb81c582007-01-30 22:32:09 +00002981 ctx->pending_redirect = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00002982 if (glob_target->gl_pathc != 1) {
Manuel Novoa III cad53642003-03-19 09:13:01 +00002983 bb_error_msg("ambiguous redirect");
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00002984 debug_printf_parse("done_word return 1: ambiguous redirect\n");
Eric Andersen25f27032001-04-26 23:22:31 +00002985 return 1;
2986 }
2987 } else {
2988 child->argv = glob_target->gl_pathv;
2989 }
Denis Vlasenko06810332007-05-21 23:30:54 +00002990#if ENABLE_HUSH_LOOPS
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002991 if (ctx->res_w == RES_FOR) {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00002992 done_word(dest, ctx);
2993 done_pipe(ctx, PIPE_SEQ);
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002994 }
Denis Vlasenko06810332007-05-21 23:30:54 +00002995#endif
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00002996 debug_printf_parse("done_word return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00002997 return 0;
2998}
2999
3000/* The only possible error here is out of memory, in which case
3001 * xmalloc exits. */
3002static int done_command(struct p_context *ctx)
3003{
3004 /* The child is really already in the pipe structure, so
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003005 * advance the pipe counter and make a new, null child. */
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003006 struct pipe *pi = ctx->pipe;
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003007 struct child_prog *child = ctx->child;
Eric Andersen25f27032001-04-26 23:22:31 +00003008
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003009 if (child) {
3010 if (child->group == NULL
3011 && child->argv == NULL
3012 && child->redirects == NULL
3013 ) {
Denis Vlasenkodd4cb2b2007-05-05 15:11:40 +00003014 debug_printf_parse("done_command: skipping null cmd, num_progs=%d\n", pi->num_progs);
3015 return pi->num_progs;
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003016 }
Eric Andersen25f27032001-04-26 23:22:31 +00003017 pi->num_progs++;
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003018 debug_printf_parse("done_command: ++num_progs=%d\n", pi->num_progs);
Eric Andersen25f27032001-04-26 23:22:31 +00003019 } else {
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003020 debug_printf_parse("done_command: initializing, num_progs=%d\n", pi->num_progs);
Eric Andersen25f27032001-04-26 23:22:31 +00003021 }
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003022
3023 /* Only real trickiness here is that the uncommitted
3024 * child structure is not counted in pi->num_progs. */
Eric Andersen25f27032001-04-26 23:22:31 +00003025 pi->progs = xrealloc(pi->progs, sizeof(*pi->progs) * (pi->num_progs+1));
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003026 child = &pi->progs[pi->num_progs];
Eric Andersen25f27032001-04-26 23:22:31 +00003027
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003028 memset(child, 0, sizeof(*child));
3029 /*child->redirects = NULL;*/
3030 /*child->argv = NULL;*/
3031 /*child->is_stopped = 0;*/
3032 /*child->group = NULL;*/
3033 /*child->glob_result.gl_pathv = NULL;*/
3034 child->family = pi;
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003035 //sp: /*child->sp = 0;*/
Denis Vlasenko262d7652007-05-20 21:52:49 +00003036 //pt: child->parse_type = ctx->parse_type;
Eric Andersen25f27032001-04-26 23:22:31 +00003037
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003038 ctx->child = child;
Eric Andersen25f27032001-04-26 23:22:31 +00003039 /* but ctx->pipe and ctx->list_head remain unchanged */
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003040
Denis Vlasenkodd4cb2b2007-05-05 15:11:40 +00003041 return pi->num_progs; /* used only for 0/nonzero check */
Eric Andersen25f27032001-04-26 23:22:31 +00003042}
3043
3044static int done_pipe(struct p_context *ctx, pipe_style type)
3045{
3046 struct pipe *new_p;
Denis Vlasenkodd4cb2b2007-05-05 15:11:40 +00003047 int not_null;
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003048
3049 debug_printf_parse("done_pipe entered, followup %d\n", type);
Denis Vlasenkodd4cb2b2007-05-05 15:11:40 +00003050 not_null = done_command(ctx); /* implicit closure of previous command */
Eric Andersen25f27032001-04-26 23:22:31 +00003051 ctx->pipe->followup = type;
Denis Vlasenko219e88d2007-05-21 10:18:23 +00003052 ctx->pipe->res_word = ctx->res_w;
Denis Vlasenkodd4cb2b2007-05-05 15:11:40 +00003053 /* Without this check, even just <enter> on command line generates
3054 * tree of three NOPs (!). Which is harmless but annoying.
3055 * IOW: it is safe to do it unconditionally. */
3056 if (not_null) {
3057 new_p = new_pipe();
3058 ctx->pipe->next = new_p;
3059 ctx->pipe = new_p;
3060 ctx->child = NULL;
3061 done_command(ctx); /* set up new pipe to accept commands */
3062 }
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003063 debug_printf_parse("done_pipe return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003064 return 0;
3065}
3066
3067/* peek ahead in the in_str to find out if we have a "&n" construct,
3068 * as in "2>&1", that represents duplicating a file descriptor.
3069 * returns either -2 (syntax error), -1 (no &), or the number found.
3070 */
3071static int redirect_dup_num(struct in_str *input)
3072{
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003073 int ch, d = 0, ok = 0;
Eric Andersen25f27032001-04-26 23:22:31 +00003074 ch = b_peek(input);
3075 if (ch != '&') return -1;
3076
3077 b_getch(input); /* get the & */
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003078 ch = b_peek(input);
Eric Andersen83a2ae22001-05-07 17:59:25 +00003079 if (ch == '-') {
3080 b_getch(input);
3081 return -3; /* "-" represents "close me" */
3082 }
3083 while (isdigit(ch)) {
Denis Vlasenko7d4c44e2007-04-16 22:34:39 +00003084 d = d*10 + (ch-'0');
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003085 ok = 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003086 b_getch(input);
Eric Andersen83a2ae22001-05-07 17:59:25 +00003087 ch = b_peek(input);
Eric Andersen25f27032001-04-26 23:22:31 +00003088 }
3089 if (ok) return d;
3090
Manuel Novoa III cad53642003-03-19 09:13:01 +00003091 bb_error_msg("ambiguous redirect");
Eric Andersen25f27032001-04-26 23:22:31 +00003092 return -2;
3093}
3094
3095/* If a redirect is immediately preceded by a number, that number is
3096 * supposed to tell which file descriptor to redirect. This routine
3097 * looks for such preceding numbers. In an ideal world this routine
3098 * needs to handle all the following classes of redirects...
3099 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
3100 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
3101 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
3102 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
3103 * A -1 output from this program means no valid number was found, so the
3104 * caller should use the appropriate default for this redirection.
3105 */
3106static int redirect_opt_num(o_string *o)
3107{
3108 int num;
3109
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003110 if (o->length == 0)
3111 return -1;
3112 for (num = 0; num < o->length; num++) {
3113 if (!isdigit(*(o->data + num))) {
Eric Andersen25f27032001-04-26 23:22:31 +00003114 return -1;
3115 }
3116 }
3117 /* reuse num (and save an int) */
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003118 num = atoi(o->data);
Eric Andersen25f27032001-04-26 23:22:31 +00003119 b_reset(o);
3120 return num;
3121}
3122
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003123#if ENABLE_HUSH_TICK
"Vladimir N. Oleynik"19c37012005-09-22 14:33:15 +00003124static FILE *generate_stream_from_list(struct pipe *head)
Eric Andersen25f27032001-04-26 23:22:31 +00003125{
3126 FILE *pf;
Eric Andersen25f27032001-04-26 23:22:31 +00003127 int pid, channel[2];
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00003128
Denis Vlasenko5a6aedd2007-05-26 16:44:20 +00003129 xpipe(channel);
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00003130#if BB_MMU
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003131 pid = fork();
Eric Andersen72f9a422001-10-28 05:12:20 +00003132#else
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003133 pid = vfork();
Eric Andersen72f9a422001-10-28 05:12:20 +00003134#endif
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003135 if (pid < 0) {
Manuel Novoa III cad53642003-03-19 09:13:01 +00003136 bb_perror_msg_and_die("fork");
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003137 } else if (pid == 0) {
Eric Andersen25f27032001-04-26 23:22:31 +00003138 close(channel[0]);
3139 if (channel[1] != 1) {
Denis Vlasenko7d4c44e2007-04-16 22:34:39 +00003140 dup2(channel[1], 1);
Eric Andersen25f27032001-04-26 23:22:31 +00003141 close(channel[1]);
3142 }
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00003143 /* Prevent it from trying to handle ctrl-z etc */
Denis Vlasenko27f79ff2007-05-30 00:55:52 +00003144#if ENABLE_HUSH_JOB
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00003145 run_list_level = 1;
Denis Vlasenko27f79ff2007-05-30 00:55:52 +00003146#endif
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00003147 /* Process substitution is not considered to be usual
3148 * 'command execution'.
3149 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not. */
3150 /* Not needed, we are relying on it being disabled
3151 * everywhere outside actual command execution. */
3152 /*set_jobctrl_sighandler(SIG_IGN);*/
3153 set_misc_sighandler(SIG_DFL);
Eric Andersen94ac2442001-05-22 19:05:18 +00003154 _exit(run_list_real(head)); /* leaks memory */
Eric Andersen25f27032001-04-26 23:22:31 +00003155 }
Eric Andersen25f27032001-04-26 23:22:31 +00003156 close(channel[1]);
Denis Vlasenko5f786c22007-04-20 08:35:45 +00003157 pf = fdopen(channel[0], "r");
Eric Andersen25f27032001-04-26 23:22:31 +00003158 return pf;
3159}
3160
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003161/* Return code is exit status of the process that is run. */
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003162static int process_command_subs(o_string *dest, struct p_context *ctx,
3163 struct in_str *input, const char *subst_end)
Eric Andersen25f27032001-04-26 23:22:31 +00003164{
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00003165 int retcode, ch, eol_cnt;
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003166 o_string result = NULL_O_STRING;
Eric Andersen25f27032001-04-26 23:22:31 +00003167 struct p_context inner;
3168 FILE *p;
3169 struct in_str pipe_str;
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00003170
Eric Andersen25f27032001-04-26 23:22:31 +00003171 initialize_context(&inner);
3172
3173 /* recursion to generate command */
3174 retcode = parse_stream(&result, &inner, input, subst_end);
Denis Vlasenko1a735862007-05-23 00:32:25 +00003175 if (retcode != 0)
3176 return retcode; /* syntax error or EOF */
Eric Andersen25f27032001-04-26 23:22:31 +00003177 done_word(&result, &inner);
3178 done_pipe(&inner, PIPE_SEQ);
3179 b_free(&result);
3180
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003181 p = generate_stream_from_list(inner.list_head);
3182 if (p == NULL) return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003183 mark_open(fileno(p));
3184 setup_file_in_str(&pipe_str, p);
3185
3186 /* now send results of command back into original context */
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00003187 eol_cnt = 0;
3188 while ((ch = b_getch(&pipe_str)) != EOF) {
3189 if (ch == '\n') {
3190 eol_cnt++;
3191 continue;
3192 }
3193 while (eol_cnt) {
3194 b_addqchr(dest, '\n', dest->quote);
3195 eol_cnt--;
3196 }
3197 b_addqchr(dest, ch, dest->quote);
Eric Andersen25f27032001-04-26 23:22:31 +00003198 }
3199
3200 debug_printf("done reading from pipe, pclose()ing\n");
3201 /* This is the step that wait()s for the child. Should be pretty
3202 * safe, since we just read an EOF from its stdout. We could try
Denis Vlasenko262d7652007-05-20 21:52:49 +00003203 * to do better, by using wait(), and keeping track of background jobs
Eric Andersen25f27032001-04-26 23:22:31 +00003204 * at the same time. That would be a lot of work, and contrary
3205 * to the KISS philosophy of this program. */
3206 mark_closed(fileno(p));
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00003207 retcode = fclose(p);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003208 free_pipe_list(inner.list_head, 0);
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00003209 debug_printf("closed FILE from child, retcode=%d\n", retcode);
Eric Andersen25f27032001-04-26 23:22:31 +00003210 return retcode;
3211}
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003212#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003213
3214static int parse_group(o_string *dest, struct p_context *ctx,
3215 struct in_str *input, int ch)
3216{
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003217 int rcode;
3218 const char *endch = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00003219 struct p_context sub;
3220 struct child_prog *child = ctx->child;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003221
3222 debug_printf_parse("parse_group entered\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003223 if (child->argv) {
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003224 syntax(NULL);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003225 debug_printf_parse("parse_group return 1: syntax error, groups and arglists don't mix\n");
3226 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003227 }
3228 initialize_context(&sub);
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003229 endch = "}";
3230 if (ch == '(') {
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003231 endch = ")";
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003232 child->subshell = 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003233 }
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003234 rcode = parse_stream(dest, &sub, input, endch);
Denis Vlasenko5a1437d2007-05-24 13:22:47 +00003235//vda: err chk?
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003236 done_word(dest, &sub); /* finish off the final word in the subcontext */
Eric Andersen25f27032001-04-26 23:22:31 +00003237 done_pipe(&sub, PIPE_SEQ); /* and the final command there, too */
3238 child->group = sub.list_head;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003239
3240 debug_printf_parse("parse_group return %d\n", rcode);
Eric Andersen25f27032001-04-26 23:22:31 +00003241 return rcode;
3242 /* child remains "open", available for possible redirects */
3243}
3244
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003245/* Basically useful version until someone wants to get fancier,
Eric Andersen25f27032001-04-26 23:22:31 +00003246 * see the bash man page under "Parameter Expansion" */
Denis Vlasenko15d78fb2007-01-30 22:28:21 +00003247static const char *lookup_param(const char *src)
Eric Andersen25f27032001-04-26 23:22:31 +00003248{
Denis Vlasenkod76c0492007-05-25 02:16:25 +00003249 struct variable *var = get_local_var(src);
3250 if (var)
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00003251 return strchr(var->varstr, '=') + 1;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00003252 return NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00003253}
3254
3255/* return code: 0 for OK, 1 for syntax error */
3256static int handle_dollar(o_string *dest, struct p_context *ctx, struct in_str *input)
3257{
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003258 int ch = b_peek(input); /* first character after the $ */
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00003259 unsigned char quote_mask = dest->quote ? 0x80 : 0;
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003260
3261 debug_printf_parse("handle_dollar entered: ch='%c'\n", ch);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00003262 if (isalpha(ch)) {
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003263 b_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003264 //sp: ctx->child->sp++;
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003265 while (1) {
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003266 debug_printf_parse(": '%c'\n", ch);
Eric Andersen25f27032001-04-26 23:22:31 +00003267 b_getch(input);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00003268 b_addchr(dest, ch | quote_mask);
3269 quote_mask = 0;
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003270 ch = b_peek(input);
3271 if (!isalnum(ch) && ch != '_')
3272 break;
Eric Andersen25f27032001-04-26 23:22:31 +00003273 }
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003274 b_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00003275 } else if (isdigit(ch)) {
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003276 make_one_char_var:
3277 b_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003278 //sp: ctx->child->sp++;
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003279 debug_printf_parse(": '%c'\n", ch);
3280 b_getch(input);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00003281 b_addchr(dest, ch | quote_mask);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003282 b_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00003283 } else switch (ch) {
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003284 case '$': /* pid */
3285 case '!': /* last bg pid */
3286 case '?': /* last exit code */
3287 case '#': /* number of args */
3288 case '*': /* args */
3289 case '@': /* args */
3290 goto make_one_char_var;
Eric Andersen25f27032001-04-26 23:22:31 +00003291 case '{':
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003292 b_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003293 //sp: ctx->child->sp++;
Eric Andersen25f27032001-04-26 23:22:31 +00003294 b_getch(input);
3295 /* XXX maybe someone will try to escape the '}' */
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003296 while (1) {
3297 ch = b_getch(input);
Denis Vlasenkob0550012007-05-24 12:18:16 +00003298 if (ch == '}')
3299 break;
3300 if (!isalnum(ch) && ch != '_') {
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003301 syntax("unterminated ${name}");
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003302 debug_printf_parse("handle_dollar return 1: unterminated ${name}\n");
3303 return 1;
3304 }
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003305 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00003306 b_addchr(dest, ch | quote_mask);
3307 quote_mask = 0;
Eric Andersen25f27032001-04-26 23:22:31 +00003308 }
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003309 b_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00003310 break;
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003311#if ENABLE_HUSH_TICK
Eric Andersen25f27032001-04-26 23:22:31 +00003312 case '(':
Matt Kraai9f8caf12001-05-02 16:26:12 +00003313 b_getch(input);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003314 process_command_subs(dest, ctx, input, ")");
Eric Andersen25f27032001-04-26 23:22:31 +00003315 break;
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003316#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003317 case '-':
3318 case '_':
3319 /* still unhandled, but should be eventually */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003320 bb_error_msg("unhandled syntax: $%c", ch);
Eric Andersen25f27032001-04-26 23:22:31 +00003321 return 1;
3322 break;
3323 default:
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003324 b_addqchr(dest, '$', dest->quote);
Eric Andersen25f27032001-04-26 23:22:31 +00003325 }
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003326 debug_printf_parse("handle_dollar return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003327 return 0;
3328}
3329
Eric Andersen25f27032001-04-26 23:22:31 +00003330/* return code is 0 for normal exit, 1 for syntax error */
Denis Vlasenko5f786c22007-04-20 08:35:45 +00003331static int parse_stream(o_string *dest, struct p_context *ctx,
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003332 struct in_str *input, const char *end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00003333{
"Vladimir N. Oleynik"4ccd2b42006-01-31 09:27:48 +00003334 int ch, m;
Eric Andersen25f27032001-04-26 23:22:31 +00003335 int redir_fd;
3336 redir_type redir_style;
3337 int next;
3338
3339 /* Only double-quote state is handled in the state variable dest->quote.
3340 * A single-quote triggers a bypass of the main loop until its mate is
3341 * found. When recursing, quote state is passed in via dest->quote. */
3342
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003343 debug_printf_parse("parse_stream entered, end_trigger='%s'\n", end_trigger);
3344
Denis Vlasenko1a735862007-05-23 00:32:25 +00003345 while (1) {
Denis Vlasenko1a735862007-05-23 00:32:25 +00003346 m = CHAR_IFS;
3347 next = '\0';
Denis Vlasenko170435c2007-05-23 13:01:10 +00003348 ch = b_getch(input);
Denis Vlasenko1a735862007-05-23 00:32:25 +00003349 if (ch != EOF) {
3350 m = charmap[ch];
3351 if (ch != '\n')
3352 next = b_peek(input);
3353 }
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003354 debug_printf_parse(": ch=%c (%d) m=%d quote=%d\n",
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003355 ch, ch, m, dest->quote);
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003356 if (m == CHAR_ORDINARY
3357 || (m != CHAR_SPECIAL && dest->quote)
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003358 ) {
Denis Vlasenko170435c2007-05-23 13:01:10 +00003359 if (ch == EOF) {
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003360 syntax("unterminated \"");
Denis Vlasenko170435c2007-05-23 13:01:10 +00003361 debug_printf_parse("parse_stream return 1: unterminated \"\n");
3362 return 1;
3363 }
Eric Andersen25f27032001-04-26 23:22:31 +00003364 b_addqchr(dest, ch, dest->quote);
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003365 continue;
3366 }
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003367 if (m == CHAR_IFS) {
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003368 if (done_word(dest, ctx)) {
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003369 debug_printf_parse("parse_stream return 1: done_word!=0\n");
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003370 return 1;
Eric Andersenaac75e52001-04-30 18:18:45 +00003371 }
Denis Vlasenko1a735862007-05-23 00:32:25 +00003372 if (ch == EOF)
3373 break;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003374 /* If we aren't performing a substitution, treat
3375 * a newline as a command separator.
3376 * [why we don't handle it exactly like ';'? --vda] */
3377 if (end_trigger && ch == '\n') {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003378 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003379 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003380 }
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003381 if ((end_trigger && strchr(end_trigger, ch))
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003382 && !dest->quote && ctx->res_w == RES_NONE
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003383 ) {
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003384 debug_printf_parse("parse_stream return 0: end_trigger char found\n");
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003385 return 0;
3386 }
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003387 if (m == CHAR_IFS)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003388 continue;
3389 switch (ch) {
Eric Andersen25f27032001-04-26 23:22:31 +00003390 case '#':
3391 if (dest->length == 0 && !dest->quote) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003392 while (1) {
3393 ch = b_peek(input);
3394 if (ch == EOF || ch == '\n')
3395 break;
3396 b_getch(input);
3397 }
Eric Andersen25f27032001-04-26 23:22:31 +00003398 } else {
3399 b_addqchr(dest, ch, dest->quote);
3400 }
3401 break;
3402 case '\\':
3403 if (next == EOF) {
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003404 syntax("\\<eof>");
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003405 debug_printf_parse("parse_stream return 1: \\<eof>\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003406 return 1;
3407 }
3408 b_addqchr(dest, '\\', dest->quote);
3409 b_addqchr(dest, b_getch(input), dest->quote);
3410 break;
3411 case '$':
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003412 if (handle_dollar(dest, ctx, input) != 0) {
3413 debug_printf_parse("parse_stream return 1: handle_dollar returned non-0\n");
3414 return 1;
3415 }
Eric Andersen25f27032001-04-26 23:22:31 +00003416 break;
3417 case '\'':
3418 dest->nonnull = 1;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003419 while (1) {
3420 ch = b_getch(input);
3421 if (ch == EOF || ch == '\'')
3422 break;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003423 b_addchr(dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00003424 }
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003425 if (ch == EOF) {
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003426 syntax("unterminated '");
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003427 debug_printf_parse("parse_stream return 1: unterminated '\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003428 return 1;
3429 }
3430 break;
3431 case '"':
3432 dest->nonnull = 1;
3433 dest->quote = !dest->quote;
3434 break;
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003435#if ENABLE_HUSH_TICK
Eric Andersen25f27032001-04-26 23:22:31 +00003436 case '`':
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003437 process_command_subs(dest, ctx, input, "`");
Eric Andersen25f27032001-04-26 23:22:31 +00003438 break;
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003439#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003440 case '>':
3441 redir_fd = redirect_opt_num(dest);
3442 done_word(dest, ctx);
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003443 redir_style = REDIRECT_OVERWRITE;
Eric Andersen25f27032001-04-26 23:22:31 +00003444 if (next == '>') {
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003445 redir_style = REDIRECT_APPEND;
Eric Andersen25f27032001-04-26 23:22:31 +00003446 b_getch(input);
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003447 }
3448#if 0
3449 else if (next == '(') {
3450 syntax(">(process) not supported");
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003451 debug_printf_parse("parse_stream return 1: >(process) not supported\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003452 return 1;
3453 }
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003454#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003455 setup_redirect(ctx, redir_fd, redir_style, input);
3456 break;
3457 case '<':
3458 redir_fd = redirect_opt_num(dest);
3459 done_word(dest, ctx);
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003460 redir_style = REDIRECT_INPUT;
Eric Andersen25f27032001-04-26 23:22:31 +00003461 if (next == '<') {
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003462 redir_style = REDIRECT_HEREIS;
Eric Andersen25f27032001-04-26 23:22:31 +00003463 b_getch(input);
3464 } else if (next == '>') {
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003465 redir_style = REDIRECT_IO;
Eric Andersen25f27032001-04-26 23:22:31 +00003466 b_getch(input);
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003467 }
3468#if 0
3469 else if (next == '(') {
3470 syntax("<(process) not supported");
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003471 debug_printf_parse("parse_stream return 1: <(process) not supported\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003472 return 1;
3473 }
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003474#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003475 setup_redirect(ctx, redir_fd, redir_style, input);
3476 break;
3477 case ';':
3478 done_word(dest, ctx);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003479 done_pipe(ctx, PIPE_SEQ);
Eric Andersen25f27032001-04-26 23:22:31 +00003480 break;
3481 case '&':
3482 done_word(dest, ctx);
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003483 if (next == '&') {
Eric Andersen25f27032001-04-26 23:22:31 +00003484 b_getch(input);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003485 done_pipe(ctx, PIPE_AND);
Eric Andersen25f27032001-04-26 23:22:31 +00003486 } else {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003487 done_pipe(ctx, PIPE_BG);
Eric Andersen25f27032001-04-26 23:22:31 +00003488 }
3489 break;
3490 case '|':
3491 done_word(dest, ctx);
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003492 if (next == '|') {
Eric Andersen25f27032001-04-26 23:22:31 +00003493 b_getch(input);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003494 done_pipe(ctx, PIPE_OR);
Eric Andersen25f27032001-04-26 23:22:31 +00003495 } else {
3496 /* we could pick up a file descriptor choice here
3497 * with redirect_opt_num(), but bash doesn't do it.
3498 * "echo foo 2| cat" yields "foo 2". */
3499 done_command(ctx);
3500 }
3501 break;
3502 case '(':
3503 case '{':
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003504 if (parse_group(dest, ctx, input, ch) != 0) {
3505 debug_printf_parse("parse_stream return 1: parse_group returned non-0\n");
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003506 return 1;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003507 }
Eric Andersen25f27032001-04-26 23:22:31 +00003508 break;
3509 case ')':
3510 case '}':
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003511 syntax("unexpected }"); /* Proper use of this character is caught by end_trigger */
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003512 debug_printf_parse("parse_stream return 1: unexpected '}'\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003513 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003514 default:
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003515 if (ENABLE_HUSH_DEBUG)
3516 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
Eric Andersen25f27032001-04-26 23:22:31 +00003517 }
3518 }
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003519 /* Complain if quote? No, maybe we just finished a command substitution
Eric Andersen25f27032001-04-26 23:22:31 +00003520 * that was quoted. Example:
Eric Andersenc7bda1c2004-03-15 08:29:22 +00003521 * $ echo "`cat foo` plus more"
Eric Andersen25f27032001-04-26 23:22:31 +00003522 * and we just got the EOF generated by the subshell that ran "cat foo"
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003523 * The only real complaint is if we got an EOF when end_trigger != NULL,
Eric Andersen25f27032001-04-26 23:22:31 +00003524 * that is, we were really supposed to get end_trigger, and never got
3525 * one before the EOF. Can't use the standard "syntax error" return code,
3526 * so that parse_stream_outer can distinguish the EOF and exit smoothly. */
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003527 debug_printf_parse("parse_stream return %d\n", -(end_trigger != NULL));
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003528 if (end_trigger)
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00003529 return -1;
Eric Andersen25f27032001-04-26 23:22:31 +00003530 return 0;
3531}
3532
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003533static void set_in_charmap(const char *set, int code)
Eric Andersen25f27032001-04-26 23:22:31 +00003534{
Denis Vlasenkof5294e12007-04-14 10:09:57 +00003535 while (*set)
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003536 charmap[(unsigned char)*set++] = code;
Eric Andersen25f27032001-04-26 23:22:31 +00003537}
3538
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003539static void update_charmap(void)
Eric Andersen25f27032001-04-26 23:22:31 +00003540{
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003541 /* char *ifs and char charmap[256] are both globals. */
Eric Andersen25f27032001-04-26 23:22:31 +00003542 ifs = getenv("IFS");
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003543 if (ifs == NULL)
3544 ifs = " \t\n";
Eric Andersen25f27032001-04-26 23:22:31 +00003545 /* Precompute a list of 'flow through' behavior so it can be treated
3546 * quickly up front. Computation is necessary because of IFS.
3547 * Special case handling of IFS == " \t\n" is not implemented.
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003548 * The charmap[] array only really needs two bits each,
3549 * and on most machines that would be faster (reduced L1 cache use).
Eric Andersen25f27032001-04-26 23:22:31 +00003550 */
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003551 memset(charmap, CHAR_ORDINARY, sizeof(charmap));
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003552#if ENABLE_HUSH_TICK
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003553 set_in_charmap("\\$\"`", CHAR_SPECIAL);
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003554#else
3555 set_in_charmap("\\$\"", CHAR_SPECIAL);
3556#endif
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003557 set_in_charmap("<>;&|(){}#'", CHAR_ORDINARY_IF_QUOTED);
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003558 set_in_charmap(ifs, CHAR_IFS); /* are ordinary if quoted */
Eric Andersen25f27032001-04-26 23:22:31 +00003559}
3560
Eric Andersenaff114c2004-04-14 17:51:38 +00003561/* most recursion does not come through here, the exception is
Denis Vlasenko170435c2007-05-23 13:01:10 +00003562 * from builtin_source() and builtin_eval() */
3563static int parse_and_run_stream(struct in_str *inp, int parse_flag)
Eric Andersen25f27032001-04-26 23:22:31 +00003564{
Eric Andersen25f27032001-04-26 23:22:31 +00003565 struct p_context ctx;
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003566 o_string temp = NULL_O_STRING;
Eric Andersen25f27032001-04-26 23:22:31 +00003567 int rcode;
3568 do {
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003569 ctx.parse_type = parse_flag;
Eric Andersen25f27032001-04-26 23:22:31 +00003570 initialize_context(&ctx);
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003571 update_charmap();
Denis Vlasenko219e88d2007-05-21 10:18:23 +00003572 if (!(parse_flag & PARSEFLAG_SEMICOLON) || (parse_flag & PARSEFLAG_REPARSING))
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003573 set_in_charmap(";$&|", CHAR_ORDINARY);
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003574#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko5a1437d2007-05-24 13:22:47 +00003575 inp->promptmode = 0; /* PS1 */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003576#endif
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003577 /* We will stop & execute after each ';' or '\n'.
3578 * Example: "sleep 9999; echo TEST" + ctrl-C:
3579 * TEST should be printed */
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003580 rcode = parse_stream(&temp, &ctx, inp, ";\n");
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003581 if (rcode != 1 && ctx.old_flag != 0) {
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003582 syntax(NULL);
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003583 }
3584 if (rcode != 1 && ctx.old_flag == 0) {
3585 done_word(&temp, &ctx);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003586 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko400c5b62007-05-04 13:07:27 +00003587 debug_print_tree(ctx.list_head, 0);
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003588 debug_printf_exec("parse_stream_outer: run_list\n");
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003589 run_list(ctx.list_head);
3590 } else {
3591 if (ctx.old_flag != 0) {
3592 free(ctx.stack);
3593 b_reset(&temp);
Eric Andersenc7bda1c2004-03-15 08:29:22 +00003594 }
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003595 temp.nonnull = 0;
3596 temp.quote = 0;
3597 inp->p = NULL;
Denis Vlasenko2f1bb362007-04-21 10:01:14 +00003598 free_pipe_list(ctx.list_head, 0);
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003599 }
Eric Andersena813afc2001-05-24 16:19:36 +00003600 b_free(&temp);
Denis Vlasenko219e88d2007-05-21 10:18:23 +00003601 } while (rcode != -1 && !(parse_flag & PARSEFLAG_EXIT_FROM_LOOP)); /* loop on syntax errors, return on EOF */
Eric Andersen25f27032001-04-26 23:22:31 +00003602 return 0;
3603}
3604
Denis Vlasenko170435c2007-05-23 13:01:10 +00003605static int parse_and_run_string(const char *s, int parse_flag)
Eric Andersen25f27032001-04-26 23:22:31 +00003606{
3607 struct in_str input;
3608 setup_string_in_str(&input, s);
Denis Vlasenko170435c2007-05-23 13:01:10 +00003609 return parse_and_run_stream(&input, parse_flag);
Eric Andersen25f27032001-04-26 23:22:31 +00003610}
3611
Denis Vlasenko170435c2007-05-23 13:01:10 +00003612static int parse_and_run_file(FILE *f)
Eric Andersen25f27032001-04-26 23:22:31 +00003613{
3614 int rcode;
3615 struct in_str input;
3616 setup_file_in_str(&input, f);
Denis Vlasenko170435c2007-05-23 13:01:10 +00003617 rcode = parse_and_run_stream(&input, PARSEFLAG_SEMICOLON);
Eric Andersen25f27032001-04-26 23:22:31 +00003618 return rcode;
3619}
3620
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003621#if ENABLE_HUSH_JOB
Eric Andersen6c947d22001-06-25 22:24:38 +00003622/* Make sure we have a controlling tty. If we get started under a job
3623 * aware app (like bash for example), make sure we are now in charge so
3624 * we don't fight over who gets the foreground */
Eric Anderseneaecbf32001-10-31 10:41:31 +00003625static void setup_job_control(void)
Eric Andersen52a97ca2001-06-22 06:49:26 +00003626{
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003627 pid_t shell_pgrp;
3628
Denis Vlasenkoa6a17852007-04-28 16:42:11 +00003629 saved_task_pgrp = shell_pgrp = getpgrp();
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003630 debug_printf_jobs("saved_task_pgrp=%d\n", saved_task_pgrp);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003631 fcntl(interactive_fd, F_SETFD, FD_CLOEXEC);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003632
Denis Vlasenkoa6a17852007-04-28 16:42:11 +00003633 /* If we were ran as 'hush &',
3634 * sleep until we are in the foreground. */
3635 while (tcgetpgrp(interactive_fd) != shell_pgrp) {
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00003636 /* Send TTIN to ourself (should stop us) */
Denis Vlasenkoff131b92007-04-10 15:42:06 +00003637 kill(- shell_pgrp, SIGTTIN);
Denis Vlasenkoa6a17852007-04-28 16:42:11 +00003638 shell_pgrp = getpgrp();
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003639 }
Eric Andersen52a97ca2001-06-22 06:49:26 +00003640
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003641 /* Ignore job-control and misc signals. */
3642 set_jobctrl_sighandler(SIG_IGN);
3643 set_misc_sighandler(SIG_IGN);
3644//huh? signal(SIGCHLD, SIG_IGN);
3645
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003646 /* We _must_ restore tty pgrp on fatal signals */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003647 set_fatal_sighandler(sigexit);
Eric Andersen6c947d22001-06-25 22:24:38 +00003648
3649 /* Put ourselves in our own process group. */
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00003650 setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
Eric Andersen6c947d22001-06-25 22:24:38 +00003651 /* Grab control of the terminal. */
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00003652 tcsetpgrp(interactive_fd, getpid());
Eric Andersen6c947d22001-06-25 22:24:38 +00003653}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00003654#endif
Eric Andersenada18ff2001-05-21 16:18:22 +00003655
Denis Vlasenko06af2162007-02-03 17:28:39 +00003656int hush_main(int argc, char **argv);
Matt Kraai2d91deb2001-08-01 17:21:35 +00003657int hush_main(int argc, char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00003658{
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00003659 static const char version_str[] = "HUSH_VERSION="HUSH_VER_STR;
3660 static const struct variable const_shell_ver = {
3661 .next = NULL,
3662 .varstr = (char*)version_str,
3663 .max_len = 1, /* 0 can provoke free(name) */
3664 .flg_export = 1,
3665 .flg_read_only = 1,
3666 };
3667
Eric Andersen25f27032001-04-26 23:22:31 +00003668 int opt;
3669 FILE *input;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003670 char **e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00003671 struct variable *cur_var;
Eric Andersenbc604a22001-05-16 05:24:03 +00003672
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00003673 PTR_TO_GLOBALS = xzalloc(sizeof(G));
Denis Vlasenkod76c0492007-05-25 02:16:25 +00003674
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00003675 /* Deal with HUSH_VERSION */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00003676 shell_ver = const_shell_ver; /* copying struct here */
Denis Vlasenkod76c0492007-05-25 02:16:25 +00003677 top_var = &shell_ver;
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00003678 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
3679 /* Initialize our shell local variables with the values
Denis Vlasenkod76c0492007-05-25 02:16:25 +00003680 * currently living in the environment */
Denis Vlasenkod76c0492007-05-25 02:16:25 +00003681 cur_var = top_var;
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00003682 e = environ;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00003683 if (e) while (*e) {
3684 char *value = strchr(*e, '=');
3685 if (value) { /* paranoia */
3686 cur_var->next = xzalloc(sizeof(*cur_var));
3687 cur_var = cur_var->next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00003688 cur_var->varstr = *e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00003689 cur_var->max_len = strlen(*e);
3690 cur_var->flg_export = 1;
3691 }
3692 e++;
3693 }
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00003694 putenv((char *)version_str); /* reinstate HUSH_VERSION */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00003695
Denis Vlasenko38f63192007-01-22 09:03:07 +00003696#if ENABLE_FEATURE_EDITING
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00003697 line_input_state = new_line_input_t(FOR_SHELL);
3698#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003699 /* XXX what should these be while sourcing /etc/profile? */
3700 global_argc = argc;
3701 global_argv = argv;
Eric Andersen94ac2442001-05-22 19:05:18 +00003702 /* Initialize some more globals to non-zero values */
3703 set_cwd();
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003704#if ENABLE_HUSH_INTERACTIVE
3705#if ENABLE_FEATURE_EDITING
3706 cmdedit_set_initial_prompt();
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003707#endif
Eric Andersen94ac2442001-05-22 19:05:18 +00003708 PS2 = "> ";
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003709#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00003710
Denis Vlasenkod76c0492007-05-25 02:16:25 +00003711 if (EXIT_SUCCESS) /* otherwise is already done */
3712 last_return_code = EXIT_SUCCESS;
Eric Andersen25f27032001-04-26 23:22:31 +00003713
3714 if (argv[0] && argv[0][0] == '-') {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003715 debug_printf("sourcing /etc/profile\n");
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00003716 input = fopen("/etc/profile", "r");
3717 if (input != NULL) {
Eric Andersena90f20b2001-06-26 23:00:21 +00003718 mark_open(fileno(input));
Denis Vlasenko170435c2007-05-23 13:01:10 +00003719 parse_and_run_file(input);
Eric Andersena90f20b2001-06-26 23:00:21 +00003720 mark_closed(fileno(input));
3721 fclose(input);
3722 }
Eric Andersen25f27032001-04-26 23:22:31 +00003723 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003724 input = stdin;
Eric Andersenc7bda1c2004-03-15 08:29:22 +00003725
Eric Andersen25f27032001-04-26 23:22:31 +00003726 while ((opt = getopt(argc, argv, "c:xif")) > 0) {
3727 switch (opt) {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003728 case 'c':
Denis Vlasenko5f786c22007-04-20 08:35:45 +00003729 global_argv = argv + optind;
3730 global_argc = argc - optind;
Denis Vlasenko170435c2007-05-23 13:01:10 +00003731 opt = parse_and_run_string(optarg, PARSEFLAG_SEMICOLON);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003732 goto final_return;
3733 case 'i':
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003734 /* Well, we cannot just declare interactiveness,
3735 * we have to have some stuff (ctty, etc) */
3736 /* interactive_fd++; */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003737 break;
3738 case 'f':
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00003739 fake_mode = 1;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003740 break;
3741 default:
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00003742#ifndef BB_VER
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003743 fprintf(stderr, "Usage: sh [FILE]...\n"
3744 " or: sh -c command [args]...\n\n");
3745 exit(EXIT_FAILURE);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00003746#else
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003747 bb_show_usage();
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00003748#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003749 }
3750 }
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003751#if ENABLE_HUSH_JOB
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003752 /* A shell is interactive if the '-i' flag was given, or if all of
Eric Andersen25f27032001-04-26 23:22:31 +00003753 * the following conditions are met:
Denis Vlasenko55b2de72007-04-18 17:21:28 +00003754 * no -c command
Eric Andersen25f27032001-04-26 23:22:31 +00003755 * no arguments remaining or the -s flag given
3756 * standard input is a terminal
3757 * standard output is a terminal
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003758 * Refer to Posix.2, the description of the 'sh' utility. */
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003759 if (argv[optind] == NULL && input == stdin
3760 && isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)
3761 ) {
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003762 saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
3763 debug_printf("saved_tty_pgrp=%d\n", saved_tty_pgrp);
3764 if (saved_tty_pgrp >= 0) {
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003765 /* try to dup to high fd#, >= 255 */
3766 interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
3767 if (interactive_fd < 0) {
3768 /* try to dup to any fd */
3769 interactive_fd = dup(STDIN_FILENO);
3770 if (interactive_fd < 0)
3771 /* give up */
3772 interactive_fd = 0;
3773 }
Denis Vlasenko2f1bb362007-04-21 10:01:14 +00003774 // TODO: track & disallow any attempts of user
3775 // to (inadvertently) close/redirect it
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003776 }
Eric Andersen25f27032001-04-26 23:22:31 +00003777 }
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003778 debug_printf("interactive_fd=%d\n", interactive_fd);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003779 if (interactive_fd) {
Eric Andersen25f27032001-04-26 23:22:31 +00003780 /* Looks like they want an interactive shell */
Eric Andersen52a97ca2001-06-22 06:49:26 +00003781 setup_job_control();
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003782 /* Make xfuncs do cleanup on exit */
3783 die_sleep = -1; /* flag */
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003784// FIXME: should we reset die_sleep = 0 whereever we fork?
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003785 if (setjmp(die_jmp)) {
3786 /* xfunc has failed! die die die */
3787 hush_exit(xfunc_error_retval);
3788 }
Denis Vlasenko2f1bb362007-04-21 10:01:14 +00003789#if !ENABLE_FEATURE_SH_EXTRA_QUIET
Denis Vlasenkoca525b42007-06-13 12:27:17 +00003790 printf("\n\n%s hush - the humble shell v"HUSH_VER_STR"\n", bb_banner);
Denis Vlasenko2f1bb362007-04-21 10:01:14 +00003791 printf("Enter 'help' for a list of built-in commands.\n\n");
3792#endif
Eric Andersenada18ff2001-05-21 16:18:22 +00003793 }
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003794#elif ENABLE_HUSH_INTERACTIVE
3795/* no job control compiled, only prompt/line editing */
3796 if (argv[optind] == NULL && input == stdin
3797 && isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)
3798 ) {
3799 interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
3800 if (interactive_fd < 0) {
3801 /* try to dup to any fd */
3802 interactive_fd = dup(STDIN_FILENO);
3803 if (interactive_fd < 0)
3804 /* give up */
3805 interactive_fd = 0;
3806 }
3807 }
3808
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00003809#endif
Eric Andersenc7bda1c2004-03-15 08:29:22 +00003810
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003811 if (argv[optind] == NULL) {
Denis Vlasenko170435c2007-05-23 13:01:10 +00003812 opt = parse_and_run_file(stdin);
Eric Andersene67c3ce2001-05-02 02:09:36 +00003813 goto final_return;
Eric Andersen25f27032001-04-26 23:22:31 +00003814 }
Eric Andersen25f27032001-04-26 23:22:31 +00003815
3816 debug_printf("\nrunning script '%s'\n", argv[optind]);
Denis Vlasenko4c978632007-02-03 03:31:13 +00003817 global_argv = argv + optind;
3818 global_argc = argc - optind;
Rob Landleyd921b2e2006-08-03 15:41:12 +00003819 input = xfopen(argv[optind], "r");
Denis Vlasenko170435c2007-05-23 13:01:10 +00003820 opt = parse_and_run_file(input);
Eric Andersen25f27032001-04-26 23:22:31 +00003821
Denis Vlasenkod76c0492007-05-25 02:16:25 +00003822 final_return:
3823
Denis Vlasenko38f63192007-01-22 09:03:07 +00003824#if ENABLE_FEATURE_CLEAN_UP
Eric Andersenaeb44c42001-05-22 20:29:00 +00003825 fclose(input);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003826 if (cwd != bb_msg_unknown)
Eric Andersenaeb44c42001-05-22 20:29:00 +00003827 free((char*)cwd);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00003828 cur_var = top_var->next;
3829 while (cur_var) {
3830 struct variable *tmp = cur_var;
3831 if (!cur_var->max_len)
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00003832 free(cur_var->varstr);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00003833 cur_var = cur_var->next;
3834 free(tmp);
Eric Andersenaeb44c42001-05-22 20:29:00 +00003835 }
Eric Andersen25f27032001-04-26 23:22:31 +00003836#endif
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003837 hush_exit(opt ? opt : last_return_code);
Eric Andersen25f27032001-04-26 23:22:31 +00003838}