blob: a7b55415f5001763c3d27e3ba37f8a463861b164 [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
79#include "busybox.h"
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 Vlasenkoc8be5ee2007-05-17 15:38:46 +000083extern char **environ; /* This is in <unistd.h>, but protected with __USE_GNU */
Denis Vlasenkod01ff132007-05-02 21:40:23 +000084
85
86/* If you comment out one of these below, it will be #defined later
87 * to perform debug printfs to stderr: */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +000088#define debug_printf(...) do {} while (0)
Denis Vlasenko400c5b62007-05-04 13:07:27 +000089/* Finer-grained debug switches */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +000090#define debug_printf_parse(...) do {} while (0)
91#define debug_print_tree(a, b) do {} while (0)
92#define debug_printf_exec(...) do {} while (0)
93#define debug_printf_jobs(...) do {} while (0)
94#define debug_printf_expand(...) do {} while (0)
95#define debug_printf_clean(...) do {} while (0)
Denis Vlasenkod01ff132007-05-02 21:40:23 +000096
97#ifndef debug_printf
98#define debug_printf(...) fprintf(stderr, __VA_ARGS__)
Denis Vlasenkod01ff132007-05-02 21:40:23 +000099#endif
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000100
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +0000101#ifndef debug_printf_parse
102#define debug_printf_parse(...) fprintf(stderr, __VA_ARGS__)
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000103#endif
104
105#ifndef debug_printf_exec
106#define debug_printf_exec(...) fprintf(stderr, __VA_ARGS__)
107#endif
108
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +0000109#ifndef debug_printf_jobs
110#define debug_printf_jobs(...) fprintf(stderr, __VA_ARGS__)
111#define DEBUG_SHELL_JOBS 1
112#endif
113
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000114#ifndef debug_printf_expand
115#define debug_printf_expand(...) fprintf(stderr, __VA_ARGS__)
116#define DEBUG_EXPAND 1
117#endif
118
Denis Vlasenko170435c2007-05-23 13:01:10 +0000119/* Keep unconditionally on for now */
120#define ENABLE_HUSH_DEBUG 1
121
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +0000122#ifndef debug_printf_clean
123/* broken, of course, but OK for testing */
124static const char *indenter(int i)
125{
126 static const char blanks[] = " ";
127 return &blanks[sizeof(blanks) - i - 1];
128}
129#define debug_printf_clean(...) fprintf(stderr, __VA_ARGS__)
Denis Vlasenkoc666f712007-05-16 22:18:54 +0000130#define DEBUG_CLEAN 1
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +0000131#endif
132
Eric Andersen25f27032001-04-26 23:22:31 +0000133
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000134#if !ENABLE_HUSH_INTERACTIVE
135#undef ENABLE_FEATURE_EDITING
136#define ENABLE_FEATURE_EDITING 0
137#undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
138#define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
139#endif
"Robert P. J. Day"f3501602006-07-01 12:19:39 +0000140
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +0000141#define SPECIAL_VAR_SYMBOL 3
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000142
143#define PARSEFLAG_EXIT_FROM_LOOP 1
144#define PARSEFLAG_SEMICOLON (1 << 1) /* symbol ';' is special for parser */
145#define PARSEFLAG_REPARSING (1 << 2) /* >= 2nd pass */
Eric Andersen25f27032001-04-26 23:22:31 +0000146
147typedef enum {
148 REDIRECT_INPUT = 1,
149 REDIRECT_OVERWRITE = 2,
150 REDIRECT_APPEND = 3,
151 REDIRECT_HEREIS = 4,
152 REDIRECT_IO = 5
153} redir_type;
154
155/* The descrip member of this structure is only used to make debugging
156 * output pretty */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +0000157static const struct {
158 int mode;
Denis Vlasenkoef36ead2007-05-02 15:34:47 +0000159 signed char default_fd;
160 char descrip[3];
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +0000161} redir_table[] = {
Eric Andersen25f27032001-04-26 23:22:31 +0000162 { 0, 0, "()" },
163 { O_RDONLY, 0, "<" },
164 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
165 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
166 { O_RDONLY, -1, "<<" },
167 { O_RDWR, 1, "<>" }
168};
169
170typedef enum {
171 PIPE_SEQ = 1,
172 PIPE_AND = 2,
173 PIPE_OR = 3,
174 PIPE_BG = 4,
175} pipe_style;
176
177/* might eventually control execution */
178typedef enum {
179 RES_NONE = 0,
Denis Vlasenko06810332007-05-21 23:30:54 +0000180#if ENABLE_HUSH_IF
Eric Andersen25f27032001-04-26 23:22:31 +0000181 RES_IF = 1,
182 RES_THEN = 2,
183 RES_ELIF = 3,
184 RES_ELSE = 4,
185 RES_FI = 5,
Denis Vlasenko06810332007-05-21 23:30:54 +0000186#endif
187#if ENABLE_HUSH_LOOPS
Eric Andersen25f27032001-04-26 23:22:31 +0000188 RES_FOR = 6,
189 RES_WHILE = 7,
190 RES_UNTIL = 8,
191 RES_DO = 9,
192 RES_DONE = 10,
Denis Vlasenko06810332007-05-21 23:30:54 +0000193 RES_IN = 11,
194#endif
195 RES_XXXX = 12,
Eric Andersen4c9b68f2002-04-13 12:33:41 +0000196 RES_SNTX = 13
Eric Andersen25f27032001-04-26 23:22:31 +0000197} reserved_style;
Denis Vlasenko5f786c22007-04-20 08:35:45 +0000198enum {
199 FLAG_END = (1 << RES_NONE ),
Denis Vlasenko06810332007-05-21 23:30:54 +0000200#if ENABLE_HUSH_IF
Denis Vlasenko5f786c22007-04-20 08:35:45 +0000201 FLAG_IF = (1 << RES_IF ),
202 FLAG_THEN = (1 << RES_THEN ),
203 FLAG_ELIF = (1 << RES_ELIF ),
204 FLAG_ELSE = (1 << RES_ELSE ),
205 FLAG_FI = (1 << RES_FI ),
Denis Vlasenko06810332007-05-21 23:30:54 +0000206#endif
207#if ENABLE_HUSH_LOOPS
Denis Vlasenko5f786c22007-04-20 08:35:45 +0000208 FLAG_FOR = (1 << RES_FOR ),
209 FLAG_WHILE = (1 << RES_WHILE),
210 FLAG_UNTIL = (1 << RES_UNTIL),
211 FLAG_DO = (1 << RES_DO ),
212 FLAG_DONE = (1 << RES_DONE ),
213 FLAG_IN = (1 << RES_IN ),
Denis Vlasenko06810332007-05-21 23:30:54 +0000214#endif
Denis Vlasenko5f786c22007-04-20 08:35:45 +0000215 FLAG_START = (1 << RES_XXXX ),
216};
Eric Andersen25f27032001-04-26 23:22:31 +0000217
218/* This holds pointers to the various results of parsing */
219struct p_context {
220 struct child_prog *child;
221 struct pipe *list_head;
222 struct pipe *pipe;
223 struct redir_struct *pending_redirect;
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000224 smallint res_w;
225 smallint parse_type; /* bitmask of PARSEFLAG_xxx, defines type of parser : ";$" common or special symbol */
226 int old_flag; /* bitmask of FLAG_xxx, for figuring out valid reserved words */
Eric Andersen25f27032001-04-26 23:22:31 +0000227 struct p_context *stack;
228 /* How about quoting status? */
229};
230
231struct redir_struct {
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000232 struct redir_struct *next; /* pointer to the next redirect in the list */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000233 redir_type type; /* type of redirection */
234 int fd; /* file descriptor being redirected */
235 int dup; /* -1, or file descriptor being duplicated */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000236 glob_t word; /* *word.gl_pathv is the filename */
Eric Andersen25f27032001-04-26 23:22:31 +0000237};
238
239struct child_prog {
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000240 pid_t pid; /* 0 if exited */
241 char **argv; /* program name and arguments */
242 struct pipe *group; /* if non-NULL, first in group or subshell */
Denis Vlasenko262d7652007-05-20 21:52:49 +0000243 smallint subshell; /* flag, non-zero if group must be forked */
244 smallint is_stopped; /* is the program currently running? */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000245 struct redir_struct *redirects; /* I/O redirections */
246 glob_t glob_result; /* result of parameter globbing */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000247 struct pipe *family; /* pointer back to the child's parent pipe */
Denis Vlasenkoc666f712007-05-16 22:18:54 +0000248 //sp counting seems to be broken... so commented out, grep for '//sp:'
249 //sp: int sp; /* number of SPECIAL_VAR_SYMBOL */
Denis Vlasenko262d7652007-05-20 21:52:49 +0000250 //seems to be unused, grep for '//pt:'
251 //pt: int parse_type;
Eric Andersen25f27032001-04-26 23:22:31 +0000252};
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000253/* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
254 * and on execution these are substituted with their values.
255 * Substitution can make _several_ words out of one argv[n]!
256 * Example: argv[0]=='.^C*^C.' here: echo .$*.
257 */
Eric Andersen25f27032001-04-26 23:22:31 +0000258
259struct pipe {
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000260 struct pipe *next;
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000261 int num_progs; /* total number of programs in job */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000262 int running_progs; /* number of programs running (not exited) */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000263 int stopped_progs; /* number of programs alive, but stopped */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000264#if ENABLE_HUSH_JOB
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000265 int jobid; /* job number */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000266 pid_t pgrp; /* process group ID for the job */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000267 char *cmdtext; /* name of job */
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000268#endif
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000269 char *cmdbuf; /* buffer various argv's point into */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000270 struct child_prog *progs; /* array of commands in pipe */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000271 int job_context; /* bitmask defining current context */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000272 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
273 smallint res_word; /* needed for if, for, while, until... */
Eric Andersen25f27032001-04-26 23:22:31 +0000274};
275
Eric Andersen25f27032001-04-26 23:22:31 +0000276struct close_me {
Eric Andersen25f27032001-04-26 23:22:31 +0000277 struct close_me *next;
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000278 int fd;
Eric Andersen25f27032001-04-26 23:22:31 +0000279};
280
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000281/* On program start, environ points to initial environment.
282 * putenv adds new pointers into it, unsetenv removes them.
283 * Neither of these (de)allocates the strings.
284 * setenv allocates new strings in malloc space and does putenv,
285 * and thus setenv is unusable (leaky) for shell's purposes */
286#define setenv(...) setenv_is_leaky_dont_use()
287struct variable {
288 struct variable *next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +0000289 char *varstr; /* points to "name=" portion */
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000290 int max_len; /* if > 0, name is part of initial env; else name is malloced */
291 smallint flg_export; /* putenv should be done on this var */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000292 smallint flg_read_only;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000293};
294
Eric Andersen25f27032001-04-26 23:22:31 +0000295typedef struct {
296 char *data;
297 int length;
298 int maxlen;
299 int quote;
300 int nonnull;
301} o_string;
302#define NULL_O_STRING {NULL,0,0,0,0}
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000303/* used for initialization: o_string foo = NULL_O_STRING; */
Eric Andersen25f27032001-04-26 23:22:31 +0000304
305/* I can almost use ordinary FILE *. Is open_memstream() universally
306 * available? Where is it documented? */
307struct in_str {
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +0000308 const char *p;
309 /* eof_flag=1: last char in ->p is really an EOF */
310 char eof_flag; /* meaningless if ->p == NULL */
311 char peek_buf[2];
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000312#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko5a1437d2007-05-24 13:22:47 +0000313 smallint promptme;
314 smallint promptmode; /* 0: PS1, 1: PS2 */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000315#endif
Eric Andersen25f27032001-04-26 23:22:31 +0000316 FILE *file;
317 int (*get) (struct in_str *);
318 int (*peek) (struct in_str *);
319};
320#define b_getch(input) ((input)->get(input))
321#define b_peek(input) ((input)->peek(input))
322
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000323enum {
324 CHAR_ORDINARY = 0,
325 CHAR_ORDINARY_IF_QUOTED = 1, /* example: *, # */
326 CHAR_IFS = 2, /* treated as ordinary if quoted */
327 CHAR_SPECIAL = 3, /* example: $ */
Eric Andersen25f27032001-04-26 23:22:31 +0000328};
329
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000330#define HUSH_VER_STR "0.02"
331
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000332/* "Globals" within this file */
333
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000334/* Sorted roughly by size (smaller offsets == smaller code) */
335struct globals {
336#if ENABLE_HUSH_INTERACTIVE
337 /* 'interactive_fd' is a fd# open to ctty, if we have one
338 * _AND_ if we decided to act interactively */
339 int interactive_fd;
340 const char *PS1;
341 const char *PS2;
342#endif
343#if ENABLE_FEATURE_EDITING
344 line_input_t *line_input_state;
345#endif
346#if ENABLE_HUSH_JOB
347 int run_list_level;
348 pid_t saved_task_pgrp;
349 pid_t saved_tty_pgrp;
350 int last_jobid;
351 struct pipe *job_list;
352 struct pipe *toplevel_list;
353 smallint ctrl_z_flag;
354#endif
355 smallint fake_mode;
356 /* these three support $?, $#, and $1 */
357 char **global_argv;
358 int global_argc;
359 int last_return_code;
360 const char *ifs;
361 struct close_me *close_me_head;
362 const char *cwd;
363 unsigned last_bg_pid;
Denis Vlasenko0a83fc32007-05-25 11:12:32 +0000364 struct variable *top_var; /* = &shell_ver (set in main()) */
365 struct variable shell_ver;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000366#if ENABLE_FEATURE_SH_STANDALONE
367 struct nofork_save_area nofork_save;
368#endif
369#if ENABLE_HUSH_JOB
370 sigjmp_buf toplevel_jb;
371#endif
372 unsigned char charmap[256];
373 char user_input_buf[ENABLE_FEATURE_EDITING ? BUFSIZ : 2];
374};
375
376#define G (*ptr_to_globals)
377
378#if !ENABLE_HUSH_INTERACTIVE
379enum { interactive_fd = 0 };
380#endif
381#if !ENABLE_HUSH_JOB
382enum { run_list_level = 0 };
383#endif
384
385#if ENABLE_HUSH_INTERACTIVE
386#define interactive_fd (G.interactive_fd )
387#define PS1 (G.PS1 )
388#define PS2 (G.PS2 )
389#endif
390#if ENABLE_FEATURE_EDITING
391#define line_input_state (G.line_input_state)
392#endif
393#if ENABLE_HUSH_JOB
394#define run_list_level (G.run_list_level )
395#define saved_task_pgrp (G.saved_task_pgrp )
396#define saved_tty_pgrp (G.saved_tty_pgrp )
397#define last_jobid (G.last_jobid )
398#define job_list (G.job_list )
399#define toplevel_list (G.toplevel_list )
400#define toplevel_jb (G.toplevel_jb )
401#define ctrl_z_flag (G.ctrl_z_flag )
402#endif /* JOB */
403#define global_argv (G.global_argv )
404#define global_argc (G.global_argc )
405#define last_return_code (G.last_return_code)
406#define ifs (G.ifs )
407#define fake_mode (G.fake_mode )
408#define close_me_head (G.close_me_head )
409#define cwd (G.cwd )
410#define last_bg_pid (G.last_bg_pid )
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000411#define top_var (G.top_var )
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000412#define shell_ver (G.shell_ver )
413#if ENABLE_FEATURE_SH_STANDALONE
414#define nofork_save (G.nofork_save )
415#endif
416#if ENABLE_HUSH_JOB
417#define toplevel_jb (G.toplevel_jb )
418#endif
419#define charmap (G.charmap )
420#define user_input_buf (G.user_input_buf )
421
422
423#define B_CHUNK 100
424#define B_NOSPAC 1
425#define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
426
Denis Vlasenko90e485c2007-05-23 15:22:50 +0000427#if 1
428/* Normal */
429static void syntax(const char *msg)
430{
Denis Vlasenko5a1437d2007-05-24 13:22:47 +0000431 /* Was using fancy stuff:
432 * (interactive_fd ? bb_error_msg : bb_error_msg_and_die)(...params...)
433 * but it SEGVs. ?! Oh well... explicit temp ptr works around that */
434 void (*fp)(const char *s, ...);
435
436 fp = (interactive_fd ? bb_error_msg : bb_error_msg_and_die);
437 fp(msg ? "%s: %s" : "syntax error", "syntax error", msg);
Denis Vlasenko90e485c2007-05-23 15:22:50 +0000438}
Denis Vlasenko5a1437d2007-05-24 13:22:47 +0000439
Denis Vlasenko90e485c2007-05-23 15:22:50 +0000440#else
441/* Debug */
442static void syntax_lineno(int line)
Denis Vlasenkob6aae0f2007-01-29 22:51:25 +0000443{
Denis Vlasenko5a1437d2007-05-24 13:22:47 +0000444 void (*fp)(const char *s, ...);
445
446 fp = (interactive_fd ? bb_error_msg : bb_error_msg_and_die);
447 fp("syntax error hush.c:%d", line);
Eric Andersen25f27032001-04-26 23:22:31 +0000448}
Denis Vlasenko90e485c2007-05-23 15:22:50 +0000449#define syntax(str) syntax_lineno(__LINE__)
450#endif
Eric Andersen25f27032001-04-26 23:22:31 +0000451
452/* Index of subroutines: */
453/* function prototypes for builtins */
Denis Vlasenko1359da62007-04-21 23:27:30 +0000454static int builtin_cd(char **argv);
Denis Vlasenko1359da62007-04-21 23:27:30 +0000455static int builtin_eval(char **argv);
456static int builtin_exec(char **argv);
457static int builtin_exit(char **argv);
458static int builtin_export(char **argv);
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000459#if ENABLE_HUSH_JOB
Denis Vlasenko1359da62007-04-21 23:27:30 +0000460static int builtin_fg_bg(char **argv);
Denis Vlasenko1359da62007-04-21 23:27:30 +0000461static int builtin_jobs(char **argv);
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000462#endif
Denis Vlasenko06810332007-05-21 23:30:54 +0000463#if ENABLE_HUSH_HELP
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000464static int builtin_help(char **argv);
Denis Vlasenko06810332007-05-21 23:30:54 +0000465#endif
Denis Vlasenko1359da62007-04-21 23:27:30 +0000466static int builtin_pwd(char **argv);
467static int builtin_read(char **argv);
468static int builtin_set(char **argv);
469static int builtin_shift(char **argv);
470static int builtin_source(char **argv);
471static int builtin_umask(char **argv);
472static int builtin_unset(char **argv);
Denis Vlasenko06810332007-05-21 23:30:54 +0000473//static int builtin_not_written(char **argv);
Eric Andersen25f27032001-04-26 23:22:31 +0000474/* o_string manipulation: */
475static int b_check_space(o_string *o, int len);
476static int b_addchr(o_string *o, int ch);
477static void b_reset(o_string *o);
478static int b_addqchr(o_string *o, int ch, int quote);
Eric Andersen25f27032001-04-26 23:22:31 +0000479/* in_str manipulations: */
480static int static_get(struct in_str *i);
481static int static_peek(struct in_str *i);
482static int file_get(struct in_str *i);
483static int file_peek(struct in_str *i);
484static void setup_file_in_str(struct in_str *i, FILE *f);
485static void setup_string_in_str(struct in_str *i, const char *s);
486/* close_me manipulations: */
487static void mark_open(int fd);
488static void mark_closed(int fd);
Eric Anderseneaecbf32001-10-31 10:41:31 +0000489static void close_all(void);
Eric Andersen25f27032001-04-26 23:22:31 +0000490/* "run" the final data structures: */
Denis Vlasenkoc666f712007-05-16 22:18:54 +0000491#if !defined(DEBUG_CLEAN)
492#define free_pipe_list(head, indent) free_pipe_list(head)
493#define free_pipe(pi, indent) free_pipe(pi)
494#endif
Eric Andersenbf7df042001-05-23 22:18:35 +0000495static int free_pipe_list(struct pipe *head, int indent);
496static int free_pipe(struct pipe *pi, int indent);
Eric Andersen25f27032001-04-26 23:22:31 +0000497/* really run the final data structures: */
498static int setup_redirects(struct child_prog *prog, int squirrel[]);
Eric Andersen25f27032001-04-26 23:22:31 +0000499static int run_list_real(struct pipe *pi);
Denis Vlasenko1359da62007-04-21 23:27:30 +0000500static void pseudo_exec_argv(char **argv) ATTRIBUTE_NORETURN;
Bernhard Reutner-Fischer86f5c992006-01-22 22:55:11 +0000501static void pseudo_exec(struct child_prog *child) ATTRIBUTE_NORETURN;
Eric Andersen25f27032001-04-26 23:22:31 +0000502static int run_pipe_real(struct pipe *pi);
503/* extended glob support: */
504static int globhack(const char *src, int flags, glob_t *pglob);
505static int glob_needed(const char *s);
506static int xglob(o_string *dest, int flags, glob_t *pglob);
Eric Andersen78a7c992001-05-15 16:30:25 +0000507/* variable assignment: */
Eric Andersen78a7c992001-05-15 16:30:25 +0000508static int is_assignment(const char *s);
Eric Andersen25f27032001-04-26 23:22:31 +0000509/* data structure manipulation: */
510static int setup_redirect(struct p_context *ctx, int fd, redir_type style, struct in_str *input);
511static void initialize_context(struct p_context *ctx);
512static int done_word(o_string *dest, struct p_context *ctx);
513static int done_command(struct p_context *ctx);
514static int done_pipe(struct p_context *ctx, pipe_style type);
515/* primary string parsing: */
516static int redirect_dup_num(struct in_str *input);
517static int redirect_opt_num(o_string *o);
Denis Vlasenko14b5dd92007-05-20 21:51:38 +0000518#if ENABLE_HUSH_TICK
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +0000519static 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 +0000520#endif
Eric Andersen25f27032001-04-26 23:22:31 +0000521static int parse_group(o_string *dest, struct p_context *ctx, struct in_str *input, int ch);
Denis Vlasenko15d78fb2007-01-30 22:28:21 +0000522static const char *lookup_param(const char *src);
Eric Andersen25f27032001-04-26 23:22:31 +0000523static int handle_dollar(o_string *dest, struct p_context *ctx, struct in_str *input);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +0000524static 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 +0000525/* setup: */
Denis Vlasenko170435c2007-05-23 13:01:10 +0000526static int parse_and_run_stream(struct in_str *inp, int parse_flag);
527static int parse_and_run_string(const char *s, int parse_flag);
528static int parse_and_run_file(FILE *f);
Eric Andersenbafd94f2001-05-02 16:11:59 +0000529/* job management: */
Eric Andersenc798b072001-06-22 06:23:03 +0000530static int checkjobs(struct pipe* fg_pipe);
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000531#if ENABLE_HUSH_JOB
Denis Vlasenko52881e92007-04-21 13:42:52 +0000532static int checkjobs_and_fg_shell(struct pipe* fg_pipe);
Eric Andersenbafd94f2001-05-02 16:11:59 +0000533static void insert_bg_job(struct pipe *pi);
534static void remove_bg_job(struct pipe *pi);
Denis Vlasenko1359da62007-04-21 23:27:30 +0000535static void delete_finished_bg_job(struct pipe *pi);
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000536#else
537int checkjobs_and_fg_shell(struct pipe* fg_pipe); /* never called */
538#endif
Eric Andersenf72f5622001-05-15 23:21:41 +0000539/* local variable support */
Denis Vlasenko170435c2007-05-23 13:01:10 +0000540static char **expand_strvec_to_strvec(char **argv);
541/* used for eval */
542static char *expand_strvec_to_string(char **argv);
Denis Vlasenkob6a741f2007-05-17 14:38:17 +0000543/* used for expansion of right hand of assignments */
Denis Vlasenko170435c2007-05-23 13:01:10 +0000544static char *expand_string_to_string(const char *str);
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +0000545static struct variable *get_local_var(const char *name);
546static int set_local_var(char *str, int flg_export);
Denis Vlasenko87cb2db2007-04-21 10:00:01 +0000547static void unset_local_var(const char *name);
Eric Andersen25f27032001-04-26 23:22:31 +0000548
549/* Table of built-in functions. They can be forked or not, depending on
550 * context: within pipes, they fork. As simple commands, they do not.
551 * When used in non-forking context, they can change global variables
Denis Vlasenkoe1a0d482006-10-20 13:28:22 +0000552 * in the parent shell process. If forked, of course they cannot.
Eric Andersen25f27032001-04-26 23:22:31 +0000553 * For example, 'unset foo | whatever' will parse and run, but foo will
554 * still be set at the end. */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000555struct built_in_command {
556 const char *cmd; /* name */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000557 int (*function) (char **argv); /* function ptr */
Denis Vlasenko06810332007-05-21 23:30:54 +0000558#if ENABLE_HUSH_HELP
559 const char *descr; /* description */
560#define BLTIN(cmd, func, help) { cmd, func, help }
561#else
562#define BLTIN(cmd, func, help) { cmd, func }
563#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000564};
565
"Vladimir N. Oleynik"485d7cb2005-10-17 09:48:57 +0000566static const struct built_in_command bltins[] = {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000567#if ENABLE_HUSH_JOB
Denis Vlasenko06810332007-05-21 23:30:54 +0000568 BLTIN("bg" , builtin_fg_bg, "Resume a job in the background"),
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000569#endif
Denis Vlasenko06810332007-05-21 23:30:54 +0000570// BLTIN("break" , builtin_not_written, "Exit for, while or until loop"),
571 BLTIN("cd" , builtin_cd, "Change working directory"),
572// BLTIN("continue", builtin_not_written, "Continue for, while or until loop"),
573 BLTIN("eval" , builtin_eval, "Construct and run shell command"),
574 BLTIN("exec" , builtin_exec, "Exec command, replacing this shell with the exec'd process"),
575 BLTIN("exit" , builtin_exit, "Exit from shell"),
576 BLTIN("export", builtin_export, "Set environment variable"),
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000577#if ENABLE_HUSH_JOB
Denis Vlasenko06810332007-05-21 23:30:54 +0000578 BLTIN("fg" , builtin_fg_bg, "Bring job into the foreground"),
579 BLTIN("jobs" , builtin_jobs, "Lists the active jobs"),
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000580#endif
Denis Vlasenko06810332007-05-21 23:30:54 +0000581// TODO: remove pwd? we have it as an applet...
582 BLTIN("pwd" , builtin_pwd, "Print current directory"),
583 BLTIN("read" , builtin_read, "Input environment variable"),
584// BLTIN("return", builtin_not_written, "Return from a function"),
585 BLTIN("set" , builtin_set, "Set/unset shell local variables"),
586 BLTIN("shift" , builtin_shift, "Shift positional parameters"),
587// BLTIN("trap" , builtin_not_written, "Trap signals"),
588// BLTIN("ulimit", builtin_not_written, "Controls resource limits"),
589 BLTIN("umask" , builtin_umask, "Sets file creation mask"),
590 BLTIN("unset" , builtin_unset, "Unset environment variable"),
591 BLTIN("." , builtin_source, "Source-in and run commands in a file"),
592#if ENABLE_HUSH_HELP
593 BLTIN("help" , builtin_help, "List shell built-in commands"),
594#endif
595 BLTIN(NULL, NULL, NULL)
Eric Andersen25f27032001-04-26 23:22:31 +0000596};
597
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000598#if ENABLE_HUSH_JOB
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000599
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000600/* move to libbb? */
601static void signal_SA_RESTART(int sig, void (*handler)(int))
602{
603 struct sigaction sa;
604 sa.sa_handler = handler;
605 sa.sa_flags = SA_RESTART;
606 sigemptyset(&sa.sa_mask);
607 sigaction(sig, &sa, NULL);
608}
609
Denis Vlasenko3ac0e002007-04-28 16:45:22 +0000610/* Signals are grouped, we handle them in batches */
611static void set_fatal_sighandler(void (*handler)(int))
612{
613 signal(SIGILL , handler);
614 signal(SIGTRAP, handler);
615 signal(SIGABRT, handler);
616 signal(SIGFPE , handler);
617 signal(SIGBUS , handler);
618 signal(SIGSEGV, handler);
619 /* bash 3.2 seems to handle these just like 'fatal' ones */
620 signal(SIGHUP , handler);
621 signal(SIGPIPE, handler);
622 signal(SIGALRM, handler);
623}
624static void set_jobctrl_sighandler(void (*handler)(int))
625{
626 signal(SIGTSTP, handler);
627 signal(SIGTTIN, handler);
628 signal(SIGTTOU, handler);
629}
630static void set_misc_sighandler(void (*handler)(int))
631{
632 signal(SIGINT , handler);
633 signal(SIGQUIT, handler);
634 signal(SIGTERM, handler);
635}
636/* SIGCHLD is special and handled separately */
637
638static void set_every_sighandler(void (*handler)(int))
639{
640 set_fatal_sighandler(handler);
641 set_jobctrl_sighandler(handler);
642 set_misc_sighandler(handler);
643 signal(SIGCHLD, handler);
644}
645
Denis Vlasenkob5eaabb2007-04-28 16:45:59 +0000646static void handler_ctrl_c(int sig)
647{
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000648 debug_printf_jobs("got sig %d\n", sig);
Denis Vlasenkob5eaabb2007-04-28 16:45:59 +0000649// as usual we can have all kinds of nasty problems with leaked malloc data here
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +0000650 siglongjmp(toplevel_jb, 1);
Denis Vlasenkob5eaabb2007-04-28 16:45:59 +0000651}
652
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000653static void handler_ctrl_z(int sig)
654{
655 pid_t pid;
656
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +0000657 debug_printf_jobs("got tty sig %d in pid %d\n", sig, getpid());
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000658 pid = fork();
Denis Vlasenkoc2990322007-05-16 12:57:12 +0000659 if (pid < 0) /* can't fork. Pretend there was no ctrl-Z */
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000660 return;
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +0000661 ctrl_z_flag = 1;
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000662 if (!pid) { /* child */
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000663 setpgrp();
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +0000664 debug_printf_jobs("set pgrp for child %d ok\n", getpid());
Denis Vlasenko3ac0e002007-04-28 16:45:22 +0000665 set_every_sighandler(SIG_DFL);
Denis Vlasenko18e19f22007-04-28 16:43:18 +0000666 raise(SIGTSTP); /* resend TSTP so that child will be stopped */
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +0000667 debug_printf_jobs("returning in child\n");
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000668 /* return to nofork, it will eventually exit now,
669 * not return back to shell */
670 return;
671 }
672 /* parent */
673 /* finish filling up pipe info */
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +0000674 toplevel_list->pgrp = pid; /* child is in its own pgrp */
675 toplevel_list->progs[0].pid = pid;
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000676 /* parent needs to longjmp out of running nofork.
677 * we will "return" exitcode 0, with child put in background */
678// as usual we can have all kinds of nasty problems with leaked malloc data here
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +0000679 debug_printf_jobs("siglongjmp in parent\n");
680 siglongjmp(toplevel_jb, 1);
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000681}
682
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000683/* Restores tty foreground process group, and exits.
684 * May be called as signal handler for fatal signal
685 * (will faithfully resend signal to itself, producing correct exit state)
686 * or called directly with -EXITCODE.
687 * We also call it if xfunc is exiting. */
688static void sigexit(int sig) ATTRIBUTE_NORETURN;
689static void sigexit(int sig)
690{
691 sigset_t block_all;
692
693 /* Disable all signals: job control, SIGPIPE, etc. */
694 sigfillset(&block_all);
695 sigprocmask(SIG_SETMASK, &block_all, NULL);
696
Denis Vlasenko87cb2db2007-04-21 10:00:01 +0000697 if (interactive_fd)
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000698 tcsetpgrp(interactive_fd, saved_tty_pgrp);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000699
700 /* Not a signal, just exit */
701 if (sig <= 0)
702 _exit(- sig);
703
704 /* Enable only this sig and kill ourself with it */
705 signal(sig, SIG_DFL);
706 sigdelset(&block_all, sig);
707 sigprocmask(SIG_SETMASK, &block_all, NULL);
708 raise(sig);
709 _exit(1); /* Should not reach it */
710}
711
712/* Restores tty foreground process group, and exits. */
713static void hush_exit(int exitcode) ATTRIBUTE_NORETURN;
714static void hush_exit(int exitcode)
715{
716 fflush(NULL); /* flush all streams */
717 sigexit(- (exitcode & 0xff));
718}
719
Denis Vlasenkoef36ead2007-05-02 15:34:47 +0000720#else /* !JOB */
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000721
722#define set_fatal_sighandler(handler) ((void)0)
723#define set_jobctrl_sighandler(handler) ((void)0)
724#define set_misc_sighandler(handler) ((void)0)
Denis Vlasenkoef36ead2007-05-02 15:34:47 +0000725#define hush_exit(e) exit(e)
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000726
Denis Vlasenkoef36ead2007-05-02 15:34:47 +0000727#endif /* JOB */
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000728
729
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000730static const char *set_cwd(void)
731{
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000732 if (cwd == bb_msg_unknown)
Denis Vlasenko7cced6e2007-04-12 17:08:53 +0000733 cwd = NULL; /* xrealloc_getcwd_or_warn(arg) calls free(arg)! */
Denis Vlasenko6ca04442007-02-11 16:19:28 +0000734 cwd = xrealloc_getcwd_or_warn((char *)cwd);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000735 if (!cwd)
Manuel Novoa III cad53642003-03-19 09:13:01 +0000736 cwd = bb_msg_unknown;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000737 return cwd;
738}
739
Eric Andersen4c9b68f2002-04-13 12:33:41 +0000740/* built-in 'eval' handler */
Denis Vlasenko1359da62007-04-21 23:27:30 +0000741static int builtin_eval(char **argv)
Eric Andersen4c9b68f2002-04-13 12:33:41 +0000742{
Eric Andersen4c9b68f2002-04-13 12:33:41 +0000743 int rcode = EXIT_SUCCESS;
Eric Andersenc7bda1c2004-03-15 08:29:22 +0000744
Denis Vlasenko1359da62007-04-21 23:27:30 +0000745 if (argv[1]) {
Denis Vlasenko170435c2007-05-23 13:01:10 +0000746 char *str = expand_strvec_to_string(argv + 1);
747 parse_and_run_string(str, PARSEFLAG_EXIT_FROM_LOOP |
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000748 PARSEFLAG_SEMICOLON);
Eric Andersen4c9b68f2002-04-13 12:33:41 +0000749 free(str);
750 rcode = last_return_code;
751 }
752 return rcode;
753}
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000754
Eric Andersen25f27032001-04-26 23:22:31 +0000755/* built-in 'cd <path>' handler */
Denis Vlasenko1359da62007-04-21 23:27:30 +0000756static int builtin_cd(char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +0000757{
Denis Vlasenko170435c2007-05-23 13:01:10 +0000758 const char *newdir;
Denis Vlasenko1359da62007-04-21 23:27:30 +0000759 if (argv[1] == NULL)
Denis Vlasenko170435c2007-05-23 13:01:10 +0000760 newdir = getenv("HOME") ? : "/";
Eric Andersen25f27032001-04-26 23:22:31 +0000761 else
Denis Vlasenko1359da62007-04-21 23:27:30 +0000762 newdir = argv[1];
Eric Andersen25f27032001-04-26 23:22:31 +0000763 if (chdir(newdir)) {
764 printf("cd: %s: %s\n", newdir, strerror(errno));
765 return EXIT_FAILURE;
766 }
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000767 set_cwd();
Eric Andersen25f27032001-04-26 23:22:31 +0000768 return EXIT_SUCCESS;
769}
770
Eric Andersen25f27032001-04-26 23:22:31 +0000771/* built-in 'exec' handler */
Denis Vlasenko1359da62007-04-21 23:27:30 +0000772static int builtin_exec(char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +0000773{
Denis Vlasenko1359da62007-04-21 23:27:30 +0000774 if (argv[1] == NULL)
Eric Andersen25f27032001-04-26 23:22:31 +0000775 return EXIT_SUCCESS; /* Really? */
Denis Vlasenko1359da62007-04-21 23:27:30 +0000776 pseudo_exec_argv(argv + 1);
Eric Andersen25f27032001-04-26 23:22:31 +0000777 /* never returns */
778}
779
780/* built-in 'exit' handler */
Denis Vlasenko1359da62007-04-21 23:27:30 +0000781static int builtin_exit(char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +0000782{
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000783// TODO: bash does it ONLY on top-level sh exit (+interacive only?)
784 //puts("exit"); /* bash does it */
Denis Vlasenkof2fffd02007-05-02 23:39:04 +0000785// TODO: warn if we have background jobs: "There are stopped jobs"
786// On second consecutive 'exit', exit anyway.
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000787
Denis Vlasenko1359da62007-04-21 23:27:30 +0000788 if (argv[1] == NULL)
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000789 hush_exit(last_return_code);
Denis Vlasenko5f786c22007-04-20 08:35:45 +0000790 /* mimic bash: exit 123abc == exit 255 + error msg */
791 xfunc_error_retval = 255;
792 /* bash: exit -2 == exit 254, no error msg */
Denis Vlasenkof2fffd02007-05-02 23:39:04 +0000793 hush_exit(xatoi(argv[1]) & 0xff);
Eric Andersen25f27032001-04-26 23:22:31 +0000794}
795
796/* built-in 'export VAR=value' handler */
Denis Vlasenko1359da62007-04-21 23:27:30 +0000797static int builtin_export(char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +0000798{
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000799 const char *value;
Denis Vlasenko1359da62007-04-21 23:27:30 +0000800 char *name = argv[1];
Eric Andersen25f27032001-04-26 23:22:31 +0000801
Eric Andersenf72f5622001-05-15 23:21:41 +0000802 if (name == NULL) {
Denis Vlasenkof2fffd02007-05-02 23:39:04 +0000803 // TODO:
804 // ash emits: export VAR='VAL'
805 // bash: declare -x VAR="VAL"
806 // (both also escape as needed (quotes, $, etc))
807 char **e = environ;
808 if (e)
809 while (*e)
810 puts(*e++);
811 return EXIT_SUCCESS;
Eric Andersen25f27032001-04-26 23:22:31 +0000812 }
Eric Andersenf72f5622001-05-15 23:21:41 +0000813
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000814 value = strchr(name, '=');
815 if (!value) {
816 /* They are exporting something without a =VALUE */
817 struct variable *var;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000818
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000819 var = get_local_var(name);
820 if (var) {
821 var->flg_export = 1;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +0000822 putenv(var->varstr);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000823 }
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000824 /* bash does not return an error when trying to export
825 * an undefined variable. Do likewise. */
826 return EXIT_SUCCESS;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000827 }
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000828
829 set_local_var(xstrdup(name), 1);
830 return EXIT_SUCCESS;
Eric Andersen25f27032001-04-26 23:22:31 +0000831}
832
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000833#if ENABLE_HUSH_JOB
Eric Andersen25f27032001-04-26 23:22:31 +0000834/* built-in 'fg' and 'bg' handler */
Denis Vlasenko1359da62007-04-21 23:27:30 +0000835static int builtin_fg_bg(char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +0000836{
Eric Andersen0fcd4472001-05-02 20:12:03 +0000837 int i, jobnum;
Denis Vlasenko8a28e622007-04-14 11:16:29 +0000838 struct pipe *pi;
Eric Andersen25f27032001-04-26 23:22:31 +0000839
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000840 if (!interactive_fd)
Eric Andersenc798b072001-06-22 06:23:03 +0000841 return EXIT_FAILURE;
Eric Andersen0fcd4472001-05-02 20:12:03 +0000842 /* If they gave us no args, assume they want the last backgrounded task */
Denis Vlasenko1359da62007-04-21 23:27:30 +0000843 if (!argv[1]) {
Eric Andersenc798b072001-06-22 06:23:03 +0000844 for (pi = job_list; pi; pi = pi->next) {
845 if (pi->jobid == last_jobid) {
Denis Vlasenko8a28e622007-04-14 11:16:29 +0000846 goto found;
Eric Andersen0fcd4472001-05-02 20:12:03 +0000847 }
848 }
Denis Vlasenko1359da62007-04-21 23:27:30 +0000849 bb_error_msg("%s: no current job", argv[0]);
Denis Vlasenko8a28e622007-04-14 11:16:29 +0000850 return EXIT_FAILURE;
851 }
Denis Vlasenko1359da62007-04-21 23:27:30 +0000852 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
853 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
Denis Vlasenko8a28e622007-04-14 11:16:29 +0000854 return EXIT_FAILURE;
855 }
856 for (pi = job_list; pi; pi = pi->next) {
857 if (pi->jobid == jobnum) {
858 goto found;
Eric Andersen25f27032001-04-26 23:22:31 +0000859 }
860 }
Denis Vlasenko1359da62007-04-21 23:27:30 +0000861 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
Denis Vlasenko8a28e622007-04-14 11:16:29 +0000862 return EXIT_FAILURE;
863 found:
Denis Vlasenko52881e92007-04-21 13:42:52 +0000864 // TODO: bash prints a string representation
865 // of job being foregrounded (like "sleep 1 | cat")
Denis Vlasenko1359da62007-04-21 23:27:30 +0000866 if (*argv[0] == 'f') {
Eric Andersen028b65b2001-06-28 01:10:11 +0000867 /* Put the job into the foreground. */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000868 tcsetpgrp(interactive_fd, pi->pgrp);
Eric Andersen25f27032001-04-26 23:22:31 +0000869 }
870
871 /* Restart the processes in the job */
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000872 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_progs, pi->pgrp);
Denis Vlasenko1359da62007-04-21 23:27:30 +0000873 for (i = 0; i < pi->num_progs; i++) {
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000874 debug_printf_jobs("reviving pid %d\n", pi->progs[i].pid);
Eric Andersen0fcd4472001-05-02 20:12:03 +0000875 pi->progs[i].is_stopped = 0;
Denis Vlasenko1359da62007-04-21 23:27:30 +0000876 }
877 pi->stopped_progs = 0;
Eric Andersen25f27032001-04-26 23:22:31 +0000878
Denis Vlasenkobb81c582007-01-30 22:32:09 +0000879 i = kill(- pi->pgrp, SIGCONT);
880 if (i < 0) {
Denis Vlasenko8a28e622007-04-14 11:16:29 +0000881 if (errno == ESRCH) {
Denis Vlasenko1359da62007-04-21 23:27:30 +0000882 delete_finished_bg_job(pi);
Denis Vlasenko3ac0e002007-04-28 16:45:22 +0000883 return EXIT_SUCCESS;
Eric Andersen028b65b2001-06-28 01:10:11 +0000884 } else {
Manuel Novoa III cad53642003-03-19 09:13:01 +0000885 bb_perror_msg("kill (SIGCONT)");
Eric Andersen028b65b2001-06-28 01:10:11 +0000886 }
887 }
Eric Andersen25f27032001-04-26 23:22:31 +0000888
Denis Vlasenko1359da62007-04-21 23:27:30 +0000889 if (*argv[0] == 'f') {
890 remove_bg_job(pi);
Denis Vlasenko52881e92007-04-21 13:42:52 +0000891 return checkjobs_and_fg_shell(pi);
Denis Vlasenko1359da62007-04-21 23:27:30 +0000892 }
Eric Andersen25f27032001-04-26 23:22:31 +0000893 return EXIT_SUCCESS;
894}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000895#endif
Eric Andersen25f27032001-04-26 23:22:31 +0000896
897/* built-in 'help' handler */
Denis Vlasenko06810332007-05-21 23:30:54 +0000898#if ENABLE_HUSH_HELP
Denis Vlasenko1359da62007-04-21 23:27:30 +0000899static int builtin_help(char **argv ATTRIBUTE_UNUSED)
Eric Andersen25f27032001-04-26 23:22:31 +0000900{
"Vladimir N. Oleynik"485d7cb2005-10-17 09:48:57 +0000901 const struct built_in_command *x;
Eric Andersen25f27032001-04-26 23:22:31 +0000902
903 printf("\nBuilt-in commands:\n");
904 printf("-------------------\n");
905 for (x = bltins; x->cmd; x++) {
Eric Andersen25f27032001-04-26 23:22:31 +0000906 printf("%s\t%s\n", x->cmd, x->descr);
907 }
908 printf("\n\n");
909 return EXIT_SUCCESS;
910}
Denis Vlasenko06810332007-05-21 23:30:54 +0000911#endif
Eric Andersen25f27032001-04-26 23:22:31 +0000912
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000913#if ENABLE_HUSH_JOB
Eric Andersen25f27032001-04-26 23:22:31 +0000914/* built-in 'jobs' handler */
Denis Vlasenko1359da62007-04-21 23:27:30 +0000915static int builtin_jobs(char **argv ATTRIBUTE_UNUSED)
Eric Andersen25f27032001-04-26 23:22:31 +0000916{
917 struct pipe *job;
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000918 const char *status_string;
Eric Andersen25f27032001-04-26 23:22:31 +0000919
Eric Andersenc798b072001-06-22 06:23:03 +0000920 for (job = job_list; job; job = job->next) {
Eric Andersen25f27032001-04-26 23:22:31 +0000921 if (job->running_progs == job->stopped_progs)
922 status_string = "Stopped";
923 else
924 status_string = "Running";
Eric Andersen52a97ca2001-06-22 06:49:26 +0000925
Denis Vlasenko3ac0e002007-04-28 16:45:22 +0000926 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
Eric Andersen25f27032001-04-26 23:22:31 +0000927 }
928 return EXIT_SUCCESS;
929}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000930#endif
Eric Andersen25f27032001-04-26 23:22:31 +0000931
Eric Andersen25f27032001-04-26 23:22:31 +0000932/* built-in 'pwd' handler */
Denis Vlasenko1359da62007-04-21 23:27:30 +0000933static int builtin_pwd(char **argv ATTRIBUTE_UNUSED)
Eric Andersen25f27032001-04-26 23:22:31 +0000934{
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000935 puts(set_cwd());
Eric Andersen25f27032001-04-26 23:22:31 +0000936 return EXIT_SUCCESS;
937}
938
939/* built-in 'read VAR' handler */
Denis Vlasenko1359da62007-04-21 23:27:30 +0000940static int builtin_read(char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +0000941{
Denis Vlasenko3e7b0e62007-05-16 12:52:15 +0000942 char string[BUFSIZ];
943 char *p;
944 const char *name = argv[1] ? argv[1] : "REPLY";
945 int name_len = strlen(name);
Eric Andersen25f27032001-04-26 23:22:31 +0000946
Denis Vlasenko3e7b0e62007-05-16 12:52:15 +0000947 if (name_len >= sizeof(string) - 2)
948 return EXIT_FAILURE;
949 strcpy(string, name);
950 p = string + name_len;
951 *p++ = '=';
952 *p = '\0'; /* In case stdin has only EOF */
953 /* read string. name_len+1 chars are already used by 'name=' */
954 fgets(p, sizeof(string) - 1 - name_len, stdin);
955 chomp(p);
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000956 return set_local_var(xstrdup(string), 0);
Eric Andersen25f27032001-04-26 23:22:31 +0000957}
958
Denis Vlasenko3e7b0e62007-05-16 12:52:15 +0000959/* built-in 'set [VAR=value]' handler */
Denis Vlasenko1359da62007-04-21 23:27:30 +0000960static int builtin_set(char **argv)
Eric Andersenf72f5622001-05-15 23:21:41 +0000961{
Denis Vlasenko1359da62007-04-21 23:27:30 +0000962 char *temp = argv[1];
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000963 struct variable *e;
Eric Andersenf72f5622001-05-15 23:21:41 +0000964
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000965 if (temp == NULL)
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000966 for (e = top_var; e; e = e->next)
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +0000967 puts(e->varstr);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000968 else
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000969 set_local_var(xstrdup(temp), 0);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000970
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000971 return EXIT_SUCCESS;
Eric Andersenf72f5622001-05-15 23:21:41 +0000972}
973
974
Eric Andersen25f27032001-04-26 23:22:31 +0000975/* Built-in 'shift' handler */
Denis Vlasenko1359da62007-04-21 23:27:30 +0000976static int builtin_shift(char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +0000977{
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000978 int n = 1;
Denis Vlasenko1359da62007-04-21 23:27:30 +0000979 if (argv[1]) {
980 n = atoi(argv[1]);
Eric Andersen25f27032001-04-26 23:22:31 +0000981 }
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000982 if (n >= 0 && n < global_argc) {
Denis Vlasenko004baba2007-05-20 22:22:18 +0000983 global_argv[n] = global_argv[0];
Eric Andersen25f27032001-04-26 23:22:31 +0000984 global_argc -= n;
985 global_argv += n;
986 return EXIT_SUCCESS;
Eric Andersen25f27032001-04-26 23:22:31 +0000987 }
Denis Vlasenkof03dbed2007-04-13 19:55:50 +0000988 return EXIT_FAILURE;
Eric Andersen25f27032001-04-26 23:22:31 +0000989}
990
991/* Built-in '.' handler (read-in and execute commands from file) */
Denis Vlasenko1359da62007-04-21 23:27:30 +0000992static int builtin_source(char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +0000993{
994 FILE *input;
995 int status;
996
Denis Vlasenko1359da62007-04-21 23:27:30 +0000997 if (argv[1] == NULL)
Eric Andersen25f27032001-04-26 23:22:31 +0000998 return EXIT_FAILURE;
999
1000 /* XXX search through $PATH is missing */
Denis Vlasenko1359da62007-04-21 23:27:30 +00001001 input = fopen(argv[1], "r");
Eric Andersen25f27032001-04-26 23:22:31 +00001002 if (!input) {
Denis Vlasenko1359da62007-04-21 23:27:30 +00001003 bb_error_msg("cannot open '%s'", argv[1]);
Eric Andersen25f27032001-04-26 23:22:31 +00001004 return EXIT_FAILURE;
1005 }
1006
1007 /* Now run the file */
1008 /* XXX argv and argc are broken; need to save old global_argv
1009 * (pointer only is OK!) on this stack frame,
Denis Vlasenko1359da62007-04-21 23:27:30 +00001010 * set global_argv=argv+1, recurse, and restore. */
Eric Andersen25f27032001-04-26 23:22:31 +00001011 mark_open(fileno(input));
Denis Vlasenko170435c2007-05-23 13:01:10 +00001012 status = parse_and_run_file(input);
Eric Andersen25f27032001-04-26 23:22:31 +00001013 mark_closed(fileno(input));
1014 fclose(input);
Denis Vlasenkod9e15f22006-11-27 16:49:55 +00001015 return status;
Eric Andersen25f27032001-04-26 23:22:31 +00001016}
1017
Denis Vlasenko1359da62007-04-21 23:27:30 +00001018static int builtin_umask(char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00001019{
Eric Andersen83a2ae22001-05-07 17:59:25 +00001020 mode_t new_umask;
Denis Vlasenko1359da62007-04-21 23:27:30 +00001021 const char *arg = argv[1];
Eric Andersen83a2ae22001-05-07 17:59:25 +00001022 char *end;
1023 if (arg) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001024 new_umask = strtoul(arg, &end, 8);
1025 if (*end != '\0' || end == arg) {
Eric Andersen83a2ae22001-05-07 17:59:25 +00001026 return EXIT_FAILURE;
1027 }
1028 } else {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001029 new_umask = umask(0);
1030 printf("%.3o\n", (unsigned) new_umask);
Eric Andersen83a2ae22001-05-07 17:59:25 +00001031 }
1032 umask(new_umask);
1033 return EXIT_SUCCESS;
Eric Andersen25f27032001-04-26 23:22:31 +00001034}
1035
1036/* built-in 'unset VAR' handler */
Denis Vlasenko1359da62007-04-21 23:27:30 +00001037static int builtin_unset(char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00001038{
Denis Vlasenko3e7b0e62007-05-16 12:52:15 +00001039 /* bash always returns true */
Denis Vlasenko1359da62007-04-21 23:27:30 +00001040 unset_local_var(argv[1]);
Eric Andersen25f27032001-04-26 23:22:31 +00001041 return EXIT_SUCCESS;
1042}
1043
Denis Vlasenko06810332007-05-21 23:30:54 +00001044//static int builtin_not_written(char **argv)
1045//{
1046// printf("builtin_%s not written\n", argv[0]);
1047// return EXIT_FAILURE;
1048//}
Eric Andersen83a2ae22001-05-07 17:59:25 +00001049
Eric Andersen25f27032001-04-26 23:22:31 +00001050static int b_check_space(o_string *o, int len)
1051{
1052 /* It would be easy to drop a more restrictive policy
1053 * in here, such as setting a maximum string length */
1054 if (o->length + len > o->maxlen) {
Denis Vlasenkof5294e12007-04-14 10:09:57 +00001055 /* assert(data == NULL || o->maxlen != 0); */
Denis Vlasenkoef36ead2007-05-02 15:34:47 +00001056 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001057 o->data = xrealloc(o->data, 1 + o->maxlen);
Eric Andersen25f27032001-04-26 23:22:31 +00001058 }
1059 return o->data == NULL;
1060}
1061
1062static int b_addchr(o_string *o, int ch)
1063{
Denis Vlasenko831dcc42007-05-16 15:05:36 +00001064 debug_printf("b_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001065 if (b_check_space(o, 1))
1066 return B_NOSPAC;
Eric Andersen25f27032001-04-26 23:22:31 +00001067 o->data[o->length] = ch;
1068 o->length++;
1069 o->data[o->length] = '\0';
1070 return 0;
1071}
1072
1073static void b_reset(o_string *o)
1074{
1075 o->length = 0;
1076 o->nonnull = 0;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001077 if (o->data != NULL)
1078 *o->data = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00001079}
1080
1081static void b_free(o_string *o)
1082{
1083 b_reset(o);
Aaron Lehmanna170e1c2002-11-28 11:27:31 +00001084 free(o->data);
Eric Andersen25f27032001-04-26 23:22:31 +00001085 o->data = NULL;
1086 o->maxlen = 0;
1087}
1088
1089/* My analysis of quoting semantics tells me that state information
1090 * is associated with a destination, not a source.
1091 */
1092static int b_addqchr(o_string *o, int ch, int quote)
1093{
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00001094 if (quote && strchr("*?[\\", ch)) {
Eric Andersen25f27032001-04-26 23:22:31 +00001095 int rc;
1096 rc = b_addchr(o, '\\');
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001097 if (rc)
1098 return rc;
Eric Andersen25f27032001-04-26 23:22:31 +00001099 }
1100 return b_addchr(o, ch);
1101}
1102
Eric Andersen25f27032001-04-26 23:22:31 +00001103static int static_get(struct in_str *i)
1104{
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001105 int ch = *i->p++;
1106 if (ch == '\0') return EOF;
Eric Andersen25f27032001-04-26 23:22:31 +00001107 return ch;
1108}
1109
1110static int static_peek(struct in_str *i)
1111{
1112 return *i->p;
1113}
1114
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001115#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001116#if ENABLE_FEATURE_EDITING
Rob Landley88621d72006-08-29 19:41:06 +00001117static void cmdedit_set_initial_prompt(void)
Eric Andersen25f27032001-04-26 23:22:31 +00001118{
Denis Vlasenko38f63192007-01-22 09:03:07 +00001119#if !ENABLE_FEATURE_EDITING_FANCY_PROMPT
Eric Andersen25f27032001-04-26 23:22:31 +00001120 PS1 = NULL;
1121#else
1122 PS1 = getenv("PS1");
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001123 if (PS1 == NULL)
Eric Andersen25f27032001-04-26 23:22:31 +00001124 PS1 = "\\w \\$ ";
Eric Andersenc7bda1c2004-03-15 08:29:22 +00001125#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001126}
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001127#endif /* EDITING */
Eric Andersen25f27032001-04-26 23:22:31 +00001128
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00001129static const char* setup_prompt_string(int promptmode)
Eric Andersen25f27032001-04-26 23:22:31 +00001130{
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00001131 const char *prompt_str;
1132 debug_printf("setup_prompt_string %d ", promptmode);
Denis Vlasenko38f63192007-01-22 09:03:07 +00001133#if !ENABLE_FEATURE_EDITING_FANCY_PROMPT
Eric Andersen25f27032001-04-26 23:22:31 +00001134 /* Set up the prompt */
Denis Vlasenko5a1437d2007-05-24 13:22:47 +00001135 if (promptmode == 0) { /* PS1 */
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00001136 free((char*)PS1);
Denis Vlasenko5a1437d2007-05-24 13:22:47 +00001137 PS1 = xasprintf("%s %c ", cwd, (geteuid() != 0) ? '$' : '#');
1138 prompt_str = PS1;
Eric Andersen25f27032001-04-26 23:22:31 +00001139 } else {
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00001140 prompt_str = PS2;
Eric Andersen25f27032001-04-26 23:22:31 +00001141 }
1142#else
Denis Vlasenko5a1437d2007-05-24 13:22:47 +00001143 prompt_str = (promptmode == 0) ? PS1 : PS2;
Eric Andersenaf44a0e2001-04-27 07:26:12 +00001144#endif
Denis Vlasenko5a1437d2007-05-24 13:22:47 +00001145 debug_printf("result '%s'\n", prompt_str);
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00001146 return prompt_str;
Eric Andersen25f27032001-04-26 23:22:31 +00001147}
1148
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001149static void get_user_input(struct in_str *i)
Eric Andersen25f27032001-04-26 23:22:31 +00001150{
Denis Vlasenko0937be52007-04-28 16:47:08 +00001151 int r;
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00001152 const char *prompt_str;
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001153
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00001154 prompt_str = setup_prompt_string(i->promptmode);
Denis Vlasenko38f63192007-01-22 09:03:07 +00001155#if ENABLE_FEATURE_EDITING
Denis Vlasenko170435c2007-05-23 13:01:10 +00001156 /* Enable command line editing only while a command line
1157 * is actually being read; otherwise, we'll end up bequeathing
1158 * atexit() handlers and other unwanted stuff to our
1159 * child processes (rob@sysgo.de) */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001160 r = read_line_input(prompt_str, user_input_buf, BUFSIZ-1, line_input_state);
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001161 i->eof_flag = (r < 0);
1162 if (i->eof_flag) { /* EOF/error detected */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001163 user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
1164 user_input_buf[1] = '\0';
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001165 }
Eric Andersen25f27032001-04-26 23:22:31 +00001166#else
1167 fputs(prompt_str, stdout);
1168 fflush(stdout);
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001169 user_input_buf[0] = r = fgetc(i->file);
1170 /*user_input_buf[1] = '\0'; - already is and never changed */
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001171 i->eof_flag = (r == EOF);
Eric Andersen25f27032001-04-26 23:22:31 +00001172#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001173 i->p = user_input_buf;
Eric Andersen25f27032001-04-26 23:22:31 +00001174}
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001175#endif /* INTERACTIVE */
Eric Andersen25f27032001-04-26 23:22:31 +00001176
Eric Andersenc7bda1c2004-03-15 08:29:22 +00001177/* This is the magic location that prints prompts
Eric Andersen25f27032001-04-26 23:22:31 +00001178 * and gets data back from the user */
1179static int file_get(struct in_str *i)
1180{
1181 int ch;
1182
Eric Andersen25f27032001-04-26 23:22:31 +00001183 /* If there is data waiting, eat it up */
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001184 if (i->p && *i->p) {
Denis Vlasenko96f67dc2007-05-17 13:02:41 +00001185#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001186 take_cached:
Denis Vlasenko96f67dc2007-05-17 13:02:41 +00001187#endif
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001188 ch = *i->p++;
1189 if (i->eof_flag && !*i->p)
1190 ch = EOF;
Eric Andersen25f27032001-04-26 23:22:31 +00001191 } else {
1192 /* need to double check i->file because we might be doing something
1193 * more complicated by now, like sourcing or substituting. */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001194#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko5a1437d2007-05-24 13:22:47 +00001195 if (interactive_fd && i->promptme && i->file == stdin) {
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001196 do {
1197 get_user_input(i);
1198 } while (!*i->p); /* need non-empty line */
Denis Vlasenko5a1437d2007-05-24 13:22:47 +00001199 i->promptmode = 1; /* PS2 */
1200 i->promptme = 0;
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001201 goto take_cached;
Eric Andersen25f27032001-04-26 23:22:31 +00001202 }
Denis Vlasenko96f67dc2007-05-17 13:02:41 +00001203#endif
1204 ch = fgetc(i->file);
Eric Andersen25f27032001-04-26 23:22:31 +00001205 }
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001206 debug_printf("file_get: got a '%c' %d\n", ch, ch);
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001207#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001208 if (ch == '\n')
Denis Vlasenko5a1437d2007-05-24 13:22:47 +00001209 i->promptme = 1;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001210#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001211 return ch;
1212}
1213
1214/* All the callers guarantee this routine will never be
1215 * used right after a newline, so prompting is not needed.
1216 */
1217static int file_peek(struct in_str *i)
1218{
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00001219 int ch;
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001220 if (i->p && *i->p) {
1221 if (i->eof_flag && !i->p[1])
1222 return EOF;
1223 return *i->p;
Eric Andersen25f27032001-04-26 23:22:31 +00001224 }
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00001225 ch = fgetc(i->file);
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001226 i->eof_flag = (ch == EOF);
1227 i->peek_buf[0] = ch;
1228 i->peek_buf[1] = '\0';
1229 i->p = i->peek_buf;
1230 debug_printf("file_peek: got a '%c' %d\n", *i->p, *i->p);
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00001231 return ch;
Eric Andersen25f27032001-04-26 23:22:31 +00001232}
1233
1234static void setup_file_in_str(struct in_str *i, FILE *f)
1235{
1236 i->peek = file_peek;
1237 i->get = file_get;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001238#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko5a1437d2007-05-24 13:22:47 +00001239 i->promptme = 1;
1240 i->promptmode = 0; /* PS1 */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001241#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001242 i->file = f;
1243 i->p = NULL;
1244}
1245
1246static void setup_string_in_str(struct in_str *i, const char *s)
1247{
1248 i->peek = static_peek;
1249 i->get = static_get;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001250#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko5a1437d2007-05-24 13:22:47 +00001251 i->promptme = 1;
1252 i->promptmode = 0; /* PS1 */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001253#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001254 i->p = s;
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001255 i->eof_flag = 0;
Eric Andersen25f27032001-04-26 23:22:31 +00001256}
1257
1258static void mark_open(int fd)
1259{
1260 struct close_me *new = xmalloc(sizeof(struct close_me));
1261 new->fd = fd;
1262 new->next = close_me_head;
1263 close_me_head = new;
1264}
1265
1266static void mark_closed(int fd)
1267{
1268 struct close_me *tmp;
1269 if (close_me_head == NULL || close_me_head->fd != fd)
Manuel Novoa III cad53642003-03-19 09:13:01 +00001270 bb_error_msg_and_die("corrupt close_me");
Eric Andersen25f27032001-04-26 23:22:31 +00001271 tmp = close_me_head;
1272 close_me_head = close_me_head->next;
1273 free(tmp);
1274}
1275
Eric Anderseneaecbf32001-10-31 10:41:31 +00001276static void close_all(void)
Eric Andersen25f27032001-04-26 23:22:31 +00001277{
1278 struct close_me *c;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001279 for (c = close_me_head; c; c = c->next) {
Eric Andersen25f27032001-04-26 23:22:31 +00001280 close(c->fd);
1281 }
1282 close_me_head = NULL;
1283}
1284
1285/* squirrel != NULL means we squirrel away copies of stdin, stdout,
1286 * and stderr if they are redirected. */
1287static int setup_redirects(struct child_prog *prog, int squirrel[])
1288{
1289 int openfd, mode;
1290 struct redir_struct *redir;
1291
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001292 for (redir = prog->redirects; redir; redir = redir->next) {
Eric Andersen817e73c2001-06-06 17:56:09 +00001293 if (redir->dup == -1 && redir->word.gl_pathv == NULL) {
1294 /* something went wrong in the parse. Pretend it didn't happen */
1295 continue;
1296 }
Eric Andersen25f27032001-04-26 23:22:31 +00001297 if (redir->dup == -1) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001298 mode = redir_table[redir->type].mode;
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00001299 openfd = open_or_warn(redir->word.gl_pathv[0], mode);
Eric Andersen25f27032001-04-26 23:22:31 +00001300 if (openfd < 0) {
1301 /* this could get lost if stderr has been redirected, but
1302 bash and ash both lose it as well (though zsh doesn't!) */
Eric Andersen25f27032001-04-26 23:22:31 +00001303 return 1;
1304 }
1305 } else {
1306 openfd = redir->dup;
1307 }
1308
1309 if (openfd != redir->fd) {
1310 if (squirrel && redir->fd < 3) {
1311 squirrel[redir->fd] = dup(redir->fd);
1312 }
Eric Andersen83a2ae22001-05-07 17:59:25 +00001313 if (openfd == -3) {
1314 close(openfd);
1315 } else {
1316 dup2(openfd, redir->fd);
Matt Kraaic616e532001-06-05 16:50:08 +00001317 if (redir->dup == -1)
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00001318 close(openfd);
Eric Andersen83a2ae22001-05-07 17:59:25 +00001319 }
Eric Andersen25f27032001-04-26 23:22:31 +00001320 }
1321 }
1322 return 0;
1323}
1324
1325static void restore_redirects(int squirrel[])
1326{
1327 int i, fd;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001328 for (i = 0; i < 3; i++) {
Eric Andersen25f27032001-04-26 23:22:31 +00001329 fd = squirrel[i];
1330 if (fd != -1) {
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00001331 /* We simply die on error */
1332 xmove_fd(fd, i);
Eric Andersen25f27032001-04-26 23:22:31 +00001333 }
1334 }
1335}
1336
Eric Andersenada18ff2001-05-21 16:18:22 +00001337/* never returns */
Eric Andersen94ac2442001-05-22 19:05:18 +00001338/* XXX no exit() here. If you don't exec, use _exit instead.
1339 * The at_exit handlers apparently confuse the calling process,
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00001340 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
Denis Vlasenko1359da62007-04-21 23:27:30 +00001341static void pseudo_exec_argv(char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00001342{
Eric Andersen78a7c992001-05-15 16:30:25 +00001343 int i, rcode;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00001344 char *p;
"Vladimir N. Oleynik"485d7cb2005-10-17 09:48:57 +00001345 const struct built_in_command *x;
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00001346
Denis Vlasenko1359da62007-04-21 23:27:30 +00001347 for (i = 0; is_assignment(argv[i]); i++) {
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001348 debug_printf_exec("pid %d environment modification: %s\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00001349 getpid(), argv[i]);
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001350// FIXME: vfork case??
Denis Vlasenko170435c2007-05-23 13:01:10 +00001351 p = expand_string_to_string(argv[i]);
1352 putenv(p);
Denis Vlasenko1359da62007-04-21 23:27:30 +00001353 }
1354 argv += i;
1355 /* If a variable is assigned in a forest, and nobody listens,
1356 * was it ever really set?
1357 */
1358 if (argv[0] == NULL) {
1359 _exit(EXIT_SUCCESS);
1360 }
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00001361
Denis Vlasenko170435c2007-05-23 13:01:10 +00001362 argv = expand_strvec_to_strvec(argv);
Denis Vlasenko764d59d2007-05-14 16:23:23 +00001363
Denis Vlasenko1359da62007-04-21 23:27:30 +00001364 /*
1365 * Check if the command matches any of the builtins.
1366 * Depending on context, this might be redundant. But it's
1367 * easier to waste a few CPU cycles than it is to figure out
1368 * if this is one of those cases.
1369 */
1370 for (x = bltins; x->cmd; x++) {
1371 if (strcmp(argv[0], x->cmd) == 0) {
Denis Vlasenko764d59d2007-05-14 16:23:23 +00001372 debug_printf_exec("running builtin '%s'\n", argv[0]);
Denis Vlasenko1359da62007-04-21 23:27:30 +00001373 rcode = x->function(argv);
1374 fflush(stdout);
1375 _exit(rcode);
Eric Andersen94ac2442001-05-22 19:05:18 +00001376 }
Denis Vlasenko1359da62007-04-21 23:27:30 +00001377 }
Eric Andersen78a7c992001-05-15 16:30:25 +00001378
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001379 /* Check if the command matches any busybox applets */
Denis Vlasenko80d14be2007-04-10 23:03:30 +00001380#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001381 if (strchr(argv[0], '/') == NULL) {
1382 const struct bb_applet *a = find_applet_by_name(argv[0]);
1383 if (a) {
1384 if (a->noexec) {
1385 current_applet = a;
1386 debug_printf_exec("running applet '%s'\n", argv[0]);
1387// is it ok that run_current_applet_and_exit() does exit(), not _exit()?
1388 run_current_applet_and_exit(argv);
1389 }
1390 /* re-exec ourselves with the new arguments */
1391 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
1392 execvp(CONFIG_BUSYBOX_EXEC_PATH, argv);
1393 /* If they called chroot or otherwise made the binary no longer
1394 * executable, fall through */
1395 }
1396 }
Eric Andersenaac75e52001-04-30 18:18:45 +00001397#endif
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001398
1399 debug_printf_exec("execing '%s'\n", argv[0]);
Denis Vlasenko1359da62007-04-21 23:27:30 +00001400 execvp(argv[0], argv);
1401 bb_perror_msg("cannot exec '%s'", argv[0]);
1402 _exit(1);
1403}
1404
1405static void pseudo_exec(struct child_prog *child)
1406{
Denis Vlasenkof2fffd02007-05-02 23:39:04 +00001407// FIXME: buggy wrt NOMMU! Must not modify any global data
1408// until it does exec/_exit, but currently it does.
Denis Vlasenko1359da62007-04-21 23:27:30 +00001409 int rcode;
1410
1411 if (child->argv) {
1412 pseudo_exec_argv(child->argv);
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00001413 }
1414
1415 if (child->group) {
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00001416 // FIXME: do not modify globals! Think vfork!
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001417#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001418 debug_printf_exec("pseudo_exec: setting interactive_fd=0\n");
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001419 interactive_fd = 0; /* crucial!!!! */
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001420#endif
Denis Vlasenkod01ff132007-05-02 21:40:23 +00001421 debug_printf_exec("pseudo_exec: run_list_real\n");
Eric Andersen25f27032001-04-26 23:22:31 +00001422 rcode = run_list_real(child->group);
Eric Andersenbf7df042001-05-23 22:18:35 +00001423 /* OK to leak memory by not calling free_pipe_list,
Eric Andersen25f27032001-04-26 23:22:31 +00001424 * since this process is about to exit */
Eric Andersen94ac2442001-05-22 19:05:18 +00001425 _exit(rcode);
Eric Andersen25f27032001-04-26 23:22:31 +00001426 }
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00001427
1428 /* Can happen. See what bash does with ">foo" by itself. */
1429 debug_printf("trying to pseudo_exec null command\n");
1430 _exit(EXIT_SUCCESS);
Eric Andersen25f27032001-04-26 23:22:31 +00001431}
1432
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001433#if ENABLE_HUSH_JOB
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00001434static const char *get_cmdtext(struct pipe *pi)
1435{
1436 char **argv;
1437 char *p;
1438 int len;
1439
1440 /* This is subtle. ->cmdtext is created only on first backgrounding.
1441 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001442 * On subsequent bg argv is trashed, but we won't use it */
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00001443 if (pi->cmdtext)
1444 return pi->cmdtext;
1445 argv = pi->progs[0].argv;
1446 if (!argv || !argv[0])
1447 return (pi->cmdtext = xzalloc(1));
1448
1449 len = 0;
1450 do len += strlen(*argv) + 1; while (*++argv);
1451 pi->cmdtext = p = xmalloc(len);
1452 argv = pi->progs[0].argv;
1453 do {
1454 len = strlen(*argv);
1455 memcpy(p, *argv, len);
1456 p += len;
1457 *p++ = ' ';
1458 } while (*++argv);
1459 p[-1] = '\0';
1460 return pi->cmdtext;
1461}
1462
Eric Andersenbafd94f2001-05-02 16:11:59 +00001463static void insert_bg_job(struct pipe *pi)
1464{
1465 struct pipe *thejob;
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001466 int i;
Eric Andersenbafd94f2001-05-02 16:11:59 +00001467
1468 /* Linear search for the ID of the job to use */
1469 pi->jobid = 1;
Eric Andersenc798b072001-06-22 06:23:03 +00001470 for (thejob = job_list; thejob; thejob = thejob->next)
Eric Andersenbafd94f2001-05-02 16:11:59 +00001471 if (thejob->jobid >= pi->jobid)
1472 pi->jobid = thejob->jobid + 1;
1473
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001474 /* Add thejob to the list of running jobs */
Eric Andersenc798b072001-06-22 06:23:03 +00001475 if (!job_list) {
Eric Andersen52a97ca2001-06-22 06:49:26 +00001476 thejob = job_list = xmalloc(sizeof(*thejob));
Eric Andersenbafd94f2001-05-02 16:11:59 +00001477 } else {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001478 for (thejob = job_list; thejob->next; thejob = thejob->next)
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00001479 continue;
Eric Andersenbafd94f2001-05-02 16:11:59 +00001480 thejob->next = xmalloc(sizeof(*thejob));
1481 thejob = thejob->next;
1482 }
1483
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001484 /* Physically copy the struct job */
Eric Andersen0fcd4472001-05-02 20:12:03 +00001485 memcpy(thejob, pi, sizeof(struct pipe));
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001486 thejob->progs = xzalloc(sizeof(pi->progs[0]) * pi->num_progs);
1487 /* We cannot copy entire pi->progs[] vector! Double free()s will happen */
1488 for (i = 0; i < pi->num_progs; i++) {
1489// TODO: do we really need to have so many fields which are just dead weight
1490// at execution stage?
1491 thejob->progs[i].pid = pi->progs[i].pid;
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001492 /* all other fields are not used and stay zero */
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001493 }
Eric Andersenbafd94f2001-05-02 16:11:59 +00001494 thejob->next = NULL;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00001495 thejob->cmdtext = xstrdup(get_cmdtext(pi));
Eric Andersenbafd94f2001-05-02 16:11:59 +00001496
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001497 /* We don't wait for background thejobs to return -- append it
Eric Andersenbafd94f2001-05-02 16:11:59 +00001498 to the list of backgrounded thejobs and leave it alone */
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00001499 printf("[%d] %d %s\n", thejob->jobid, thejob->progs[0].pid, thejob->cmdtext);
Eric Andersen1a6d39b2001-05-08 05:11:54 +00001500 last_bg_pid = thejob->progs[0].pid;
Eric Andersenc798b072001-06-22 06:23:03 +00001501 last_jobid = thejob->jobid;
Eric Andersenbafd94f2001-05-02 16:11:59 +00001502}
1503
Eric Andersenbafd94f2001-05-02 16:11:59 +00001504static void remove_bg_job(struct pipe *pi)
1505{
1506 struct pipe *prev_pipe;
1507
Eric Andersenc798b072001-06-22 06:23:03 +00001508 if (pi == job_list) {
Eric Andersen52a97ca2001-06-22 06:49:26 +00001509 job_list = pi->next;
Eric Andersenbafd94f2001-05-02 16:11:59 +00001510 } else {
Eric Andersenc798b072001-06-22 06:23:03 +00001511 prev_pipe = job_list;
Eric Andersenbafd94f2001-05-02 16:11:59 +00001512 while (prev_pipe->next != pi)
1513 prev_pipe = prev_pipe->next;
1514 prev_pipe->next = pi->next;
1515 }
Eric Andersen028b65b2001-06-28 01:10:11 +00001516 if (job_list)
1517 last_jobid = job_list->jobid;
1518 else
1519 last_jobid = 0;
Denis Vlasenko1359da62007-04-21 23:27:30 +00001520}
Eric Andersen028b65b2001-06-28 01:10:11 +00001521
Denis Vlasenko1359da62007-04-21 23:27:30 +00001522/* remove a backgrounded job */
1523static void delete_finished_bg_job(struct pipe *pi)
1524{
1525 remove_bg_job(pi);
Eric Andersen52a97ca2001-06-22 06:49:26 +00001526 pi->stopped_progs = 0;
Eric Andersenbf7df042001-05-23 22:18:35 +00001527 free_pipe(pi, 0);
Eric Andersenbafd94f2001-05-02 16:11:59 +00001528 free(pi);
1529}
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001530#endif /* JOB */
Eric Andersenbafd94f2001-05-02 16:11:59 +00001531
Eric Andersenc7bda1c2004-03-15 08:29:22 +00001532/* Checks to see if any processes have exited -- if they
Eric Andersenbafd94f2001-05-02 16:11:59 +00001533 have, figure out why and see if a job has completed */
Eric Andersenc798b072001-06-22 06:23:03 +00001534static int checkjobs(struct pipe* fg_pipe)
Eric Andersenbafd94f2001-05-02 16:11:59 +00001535{
Eric Andersenc798b072001-06-22 06:23:03 +00001536 int attributes;
1537 int status;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001538#if ENABLE_HUSH_JOB
Eric Andersenbafd94f2001-05-02 16:11:59 +00001539 int prognum = 0;
1540 struct pipe *pi;
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001541#endif
Eric Andersenbafd94f2001-05-02 16:11:59 +00001542 pid_t childpid;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001543 int rcode = 0;
Eric Andersenbafd94f2001-05-02 16:11:59 +00001544
Eric Andersenc798b072001-06-22 06:23:03 +00001545 attributes = WUNTRACED;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001546 if (fg_pipe == NULL) {
Eric Andersenc798b072001-06-22 06:23:03 +00001547 attributes |= WNOHANG;
1548 }
1549
Denis Vlasenko1359da62007-04-21 23:27:30 +00001550/* Do we do this right?
1551 * bash-3.00# sleep 20 | false
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001552 * <ctrl-Z pressed>
Denis Vlasenko1359da62007-04-21 23:27:30 +00001553 * [3]+ Stopped sleep 20 | false
1554 * bash-3.00# echo $?
1555 * 1 <========== bg pipe is not fully done, but exitcode is already known!
1556 */
1557
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001558//FIXME: non-interactive bash does not continue even if all processes in fg pipe
1559//are stopped. Testcase: "cat | cat" in a script (not on command line)
1560// + killall -STOP cat
1561
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001562 wait_more:
Eric Andersenc798b072001-06-22 06:23:03 +00001563 while ((childpid = waitpid(-1, &status, attributes)) > 0) {
Denis Vlasenko1359da62007-04-21 23:27:30 +00001564 const int dead = WIFEXITED(status) || WIFSIGNALED(status);
1565
1566#ifdef DEBUG_SHELL_JOBS
1567 if (WIFSTOPPED(status))
Denis Vlasenkod01ff132007-05-02 21:40:23 +00001568 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00001569 childpid, WSTOPSIG(status), WEXITSTATUS(status));
1570 if (WIFSIGNALED(status))
Denis Vlasenkod01ff132007-05-02 21:40:23 +00001571 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00001572 childpid, WTERMSIG(status), WEXITSTATUS(status));
1573 if (WIFEXITED(status))
Denis Vlasenkod01ff132007-05-02 21:40:23 +00001574 debug_printf_jobs("pid %d exited, exitcode %d\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00001575 childpid, WEXITSTATUS(status));
1576#endif
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001577 /* Were we asked to wait for fg pipe? */
Eric Andersenc798b072001-06-22 06:23:03 +00001578 if (fg_pipe) {
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001579 int i;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001580 for (i = 0; i < fg_pipe->num_progs; i++) {
Denis Vlasenkod01ff132007-05-02 21:40:23 +00001581 debug_printf_jobs("check pid %d\n", fg_pipe->progs[i].pid);
Eric Andersenc798b072001-06-22 06:23:03 +00001582 if (fg_pipe->progs[i].pid == childpid) {
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001583 /* printf("process %d exit %d\n", i, WEXITSTATUS(status)); */
Denis Vlasenko1359da62007-04-21 23:27:30 +00001584 if (dead) {
1585 fg_pipe->progs[i].pid = 0;
1586 fg_pipe->running_progs--;
1587 if (i == fg_pipe->num_progs-1)
1588 /* last process gives overall exitstatus */
1589 rcode = WEXITSTATUS(status);
1590 } else {
1591 fg_pipe->progs[i].is_stopped = 1;
1592 fg_pipe->stopped_progs++;
1593 }
Denis Vlasenkod01ff132007-05-02 21:40:23 +00001594 debug_printf_jobs("fg_pipe: running_progs %d stopped_progs %d\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00001595 fg_pipe->running_progs, fg_pipe->stopped_progs);
1596 if (fg_pipe->running_progs - fg_pipe->stopped_progs <= 0) {
1597 /* All processes in fg pipe have exited/stopped */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001598#if ENABLE_HUSH_JOB
Denis Vlasenko1359da62007-04-21 23:27:30 +00001599 if (fg_pipe->running_progs)
1600 insert_bg_job(fg_pipe);
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001601#endif
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001602 return rcode;
Denis Vlasenko1359da62007-04-21 23:27:30 +00001603 }
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001604 /* There are still running processes in the fg pipe */
1605 goto wait_more;
Eric Andersenc798b072001-06-22 06:23:03 +00001606 }
1607 }
Denis Vlasenko1359da62007-04-21 23:27:30 +00001608 /* fall through to searching process in bg pipes */
Eric Andersenc798b072001-06-22 06:23:03 +00001609 }
1610
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001611#if ENABLE_HUSH_JOB
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001612 /* We asked to wait for bg or orphaned children */
1613 /* No need to remember exitcode in this case */
Eric Andersenc798b072001-06-22 06:23:03 +00001614 for (pi = job_list; pi; pi = pi->next) {
Eric Andersenbafd94f2001-05-02 16:11:59 +00001615 prognum = 0;
Denis Vlasenko5f786c22007-04-20 08:35:45 +00001616 while (prognum < pi->num_progs) {
1617 if (pi->progs[prognum].pid == childpid)
1618 goto found_pi_and_prognum;
Eric Andersen52a97ca2001-06-22 06:49:26 +00001619 prognum++;
1620 }
Eric Andersenbafd94f2001-05-02 16:11:59 +00001621 }
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001622#endif
Eric Andersenbafd94f2001-05-02 16:11:59 +00001623
Denis Vlasenko5f786c22007-04-20 08:35:45 +00001624 /* Happens when shell is used as init process (init=/bin/sh) */
1625 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
Denis Vlasenko1359da62007-04-21 23:27:30 +00001626 goto wait_more;
Eric Andersenaeb44c42001-05-22 20:29:00 +00001627
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001628#if ENABLE_HUSH_JOB
Denis Vlasenko5f786c22007-04-20 08:35:45 +00001629 found_pi_and_prognum:
Denis Vlasenko1359da62007-04-21 23:27:30 +00001630 if (dead) {
Eric Andersenbafd94f2001-05-02 16:11:59 +00001631 /* child exited */
Eric Andersenbafd94f2001-05-02 16:11:59 +00001632 pi->progs[prognum].pid = 0;
Denis Vlasenko1359da62007-04-21 23:27:30 +00001633 pi->running_progs--;
Eric Andersenbafd94f2001-05-02 16:11:59 +00001634 if (!pi->running_progs) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001635 printf(JOB_STATUS_FORMAT, pi->jobid,
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00001636 "Done", pi->cmdtext);
Denis Vlasenko1359da62007-04-21 23:27:30 +00001637 delete_finished_bg_job(pi);
Eric Andersenbafd94f2001-05-02 16:11:59 +00001638 }
1639 } else {
1640 /* child stopped */
1641 pi->stopped_progs++;
1642 pi->progs[prognum].is_stopped = 1;
Eric Andersenbafd94f2001-05-02 16:11:59 +00001643 }
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001644#endif
Eric Andersenbafd94f2001-05-02 16:11:59 +00001645 }
1646
Denis Vlasenko1359da62007-04-21 23:27:30 +00001647 /* wait found no children or failed */
1648
1649 if (childpid && errno != ECHILD)
Manuel Novoa III cad53642003-03-19 09:13:01 +00001650 bb_perror_msg("waitpid");
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001651 return rcode;
Eric Andersenada18ff2001-05-21 16:18:22 +00001652}
1653
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001654#if ENABLE_HUSH_JOB
Denis Vlasenko52881e92007-04-21 13:42:52 +00001655static int checkjobs_and_fg_shell(struct pipe* fg_pipe)
1656{
1657 pid_t p;
1658 int rcode = checkjobs(fg_pipe);
1659 /* Job finished, move the shell to the foreground */
Denis Vlasenko170435c2007-05-23 13:01:10 +00001660 p = getpgid(0); /* pgid of our process */
1661 debug_printf_jobs("fg'ing ourself: getpgid(0)=%d\n", (int)p);
Denis Vlasenko52881e92007-04-21 13:42:52 +00001662 if (tcsetpgrp(interactive_fd, p) && errno != ENOTTY)
1663 bb_perror_msg("tcsetpgrp-4a");
1664 return rcode;
1665}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001666#endif
Denis Vlasenko52881e92007-04-21 13:42:52 +00001667
Eric Andersen25f27032001-04-26 23:22:31 +00001668/* run_pipe_real() starts all the jobs, but doesn't wait for anything
Eric Andersenc798b072001-06-22 06:23:03 +00001669 * to finish. See checkjobs().
Eric Andersen25f27032001-04-26 23:22:31 +00001670 *
1671 * return code is normally -1, when the caller has to wait for children
1672 * to finish to determine the exit status of the pipe. If the pipe
1673 * is a simple builtin command, however, the action is done by the
1674 * time run_pipe_real returns, and the exit code is provided as the
1675 * return value.
1676 *
1677 * The input of the pipe is always stdin, the output is always
1678 * stdout. The outpipe[] mechanism in BusyBox-0.48 lash is bogus,
1679 * because it tries to avoid running the command substitution in
1680 * subshell, when that is in fact necessary. The subshell process
1681 * now has its stdout directed to the input of the appropriate pipe,
1682 * so this routine is noticeably simpler.
Denis Vlasenko170435c2007-05-23 13:01:10 +00001683 *
1684 * Returns -1 only if started some children. IOW: we have to
1685 * mask out retvals of builtins etc with 0xff!
Eric Andersen25f27032001-04-26 23:22:31 +00001686 */
1687static int run_pipe_real(struct pipe *pi)
1688{
1689 int i;
1690 int nextin, nextout;
1691 int pipefds[2]; /* pipefds[0] is for reading */
Rob Landley53702e52006-07-19 21:43:53 +00001692 struct child_prog *child;
"Vladimir N. Oleynik"485d7cb2005-10-17 09:48:57 +00001693 const struct built_in_command *x;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00001694 char *p;
Denis Vlasenkof5294e12007-04-14 10:09:57 +00001695 /* it is not always needed, but we aim to smaller code */
1696 int squirrel[] = { -1, -1, -1 };
1697 int rcode;
Denis Vlasenko52881e92007-04-21 13:42:52 +00001698 const int single_fg = (pi->num_progs == 1 && pi->followup != PIPE_BG);
Eric Andersen25f27032001-04-26 23:22:31 +00001699
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001700 debug_printf_exec("run_pipe_real start: single_fg=%d\n", single_fg);
Denis Vlasenko4ac530c2007-05-02 15:35:45 +00001701
Eric Andersen25f27032001-04-26 23:22:31 +00001702 nextin = 0;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001703#if ENABLE_HUSH_JOB
Eric Andersenada18ff2001-05-21 16:18:22 +00001704 pi->pgrp = -1;
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001705#endif
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001706 pi->running_progs = 1;
Denis Vlasenko1359da62007-04-21 23:27:30 +00001707 pi->stopped_progs = 0;
Eric Andersen25f27032001-04-26 23:22:31 +00001708
1709 /* Check if this is a simple builtin (not part of a pipe).
1710 * Builtins within pipes have to fork anyway, and are handled in
1711 * pseudo_exec. "echo foo | read bar" doesn't work on bash, either.
1712 */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001713 child = &(pi->progs[0]);
Denis Vlasenko52881e92007-04-21 13:42:52 +00001714 if (single_fg && child->group && child->subshell == 0) {
Eric Andersen04407e52001-06-07 16:42:05 +00001715 debug_printf("non-subshell grouping\n");
1716 setup_redirects(child, squirrel);
Denis Vlasenkod01ff132007-05-02 21:40:23 +00001717 debug_printf_exec(": run_list_real\n");
Eric Andersen04407e52001-06-07 16:42:05 +00001718 rcode = run_list_real(child->group);
1719 restore_redirects(squirrel);
Denis Vlasenkod01ff132007-05-02 21:40:23 +00001720 debug_printf_exec("run_pipe_real return %d\n", rcode);
Denis Vlasenko170435c2007-05-23 13:01:10 +00001721 return rcode; // do we need to add '... & 0xff' ?
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00001722 }
1723
Denis Vlasenko1359da62007-04-21 23:27:30 +00001724 if (single_fg && child->argv != NULL) {
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001725 char **argv_expanded;
Denis Vlasenko1359da62007-04-21 23:27:30 +00001726 char **argv = child->argv;
1727
1728 for (i = 0; is_assignment(argv[i]); i++)
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00001729 continue;
Denis Vlasenko1359da62007-04-21 23:27:30 +00001730 if (i != 0 && argv[i] == NULL) {
Eric Andersen78a7c992001-05-15 16:30:25 +00001731 /* assignments, but no command: set the local environment */
Denis Vlasenko1359da62007-04-21 23:27:30 +00001732 for (i = 0; argv[i] != NULL; i++) {
Denis Vlasenkod76c0492007-05-25 02:16:25 +00001733 debug_printf("local environment set: %s\n", argv[i]);
Denis Vlasenko170435c2007-05-23 13:01:10 +00001734 p = expand_string_to_string(argv[i]);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00001735 set_local_var(p, 0);
Eric Andersen78a7c992001-05-15 16:30:25 +00001736 }
1737 return EXIT_SUCCESS; /* don't worry about errors in set_local_var() yet */
1738 }
Denis Vlasenko1359da62007-04-21 23:27:30 +00001739 for (i = 0; is_assignment(argv[i]); i++) {
Denis Vlasenko170435c2007-05-23 13:01:10 +00001740 p = expand_string_to_string(argv[i]);
1741 //sp: child->sp--;
1742 putenv(p);
Eric Andersen4c9b68f2002-04-13 12:33:41 +00001743 }
Eric Andersen25f27032001-04-26 23:22:31 +00001744 for (x = bltins; x->cmd; x++) {
Denis Vlasenko1359da62007-04-21 23:27:30 +00001745 if (strcmp(argv[i], x->cmd) == 0) {
1746 if (x->function == builtin_exec && argv[i+1] == NULL) {
Eric Andersen83a2ae22001-05-07 17:59:25 +00001747 debug_printf("magic exec\n");
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00001748 setup_redirects(child, NULL);
Eric Andersen83a2ae22001-05-07 17:59:25 +00001749 return EXIT_SUCCESS;
1750 }
Denis Vlasenko1359da62007-04-21 23:27:30 +00001751 debug_printf("builtin inline %s\n", argv[0]);
Eric Andersen25f27032001-04-26 23:22:31 +00001752 /* XXX setup_redirects acts on file descriptors, not FILEs.
1753 * This is perfect for work that comes after exec().
1754 * Is it really safe for inline use? Experimentally,
1755 * things seem to work with glibc. */
1756 setup_redirects(child, squirrel);
Denis Vlasenkod01ff132007-05-02 21:40:23 +00001757 debug_printf_exec(": builtin '%s' '%s'...\n", x->cmd, argv[i+1]);
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001758 //sp: if (child->sp) /* btw we can do it unconditionally... */
Denis Vlasenko170435c2007-05-23 13:01:10 +00001759 argv_expanded = expand_strvec_to_strvec(argv + i);
1760 rcode = x->function(argv_expanded) & 0xff;
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001761 free(argv_expanded);
Eric Andersen25f27032001-04-26 23:22:31 +00001762 restore_redirects(squirrel);
Denis Vlasenkod01ff132007-05-02 21:40:23 +00001763 debug_printf_exec("run_pipe_real return %d\n", rcode);
Eric Andersen25f27032001-04-26 23:22:31 +00001764 return rcode;
1765 }
1766 }
Denis Vlasenkof5294e12007-04-14 10:09:57 +00001767#if ENABLE_FEATURE_SH_STANDALONE
1768 {
Denis Vlasenko1359da62007-04-21 23:27:30 +00001769 const struct bb_applet *a = find_applet_by_name(argv[i]);
Denis Vlasenkof5294e12007-04-14 10:09:57 +00001770 if (a && a->nofork) {
1771 setup_redirects(child, squirrel);
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001772 save_nofork_data(&nofork_save);
Denis Vlasenko764d59d2007-05-14 16:23:23 +00001773 argv_expanded = argv + i;
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001774 //sp: if (child->sp)
Denis Vlasenko170435c2007-05-23 13:01:10 +00001775 argv_expanded = expand_strvec_to_strvec(argv + i);
Denis Vlasenko764d59d2007-05-14 16:23:23 +00001776 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n", argv_expanded[0], argv_expanded[1]);
Denis Vlasenko170435c2007-05-23 13:01:10 +00001777 rcode = run_nofork_applet_prime(&nofork_save, a, argv_expanded) & 0xff;
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001778 free(argv_expanded);
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00001779 restore_redirects(squirrel);
Denis Vlasenkod01ff132007-05-02 21:40:23 +00001780 debug_printf_exec("run_pipe_real return %d\n", rcode);
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00001781 return rcode;
Denis Vlasenkof5294e12007-04-14 10:09:57 +00001782 }
1783 }
1784#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001785 }
1786
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00001787 /* Going to fork a child per each pipe member */
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001788 pi->running_progs = 0;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00001789
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001790 /* Disable job control signals for shell (parent) and
1791 * for initial child code after fork */
1792 set_jobctrl_sighandler(SIG_IGN);
1793
Eric Andersen25f27032001-04-26 23:22:31 +00001794 for (i = 0; i < pi->num_progs; i++) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001795 child = &(pi->progs[i]);
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001796 if (child->argv)
1797 debug_printf_exec(": pipe member '%s' '%s'...\n", child->argv[0], child->argv[1]);
1798 else
1799 debug_printf_exec(": pipe member with no argv\n");
Eric Andersen25f27032001-04-26 23:22:31 +00001800
1801 /* pipes are inserted between pairs of commands */
1802 if ((i + 1) < pi->num_progs) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001803 if (pipe(pipefds) < 0)
1804 bb_perror_msg_and_die("pipe");
Eric Andersen25f27032001-04-26 23:22:31 +00001805 nextout = pipefds[1];
1806 } else {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001807 nextout = 1;
Eric Andersen25f27032001-04-26 23:22:31 +00001808 pipefds[0] = -1;
1809 }
1810
1811 /* XXX test for failed fork()? */
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00001812#if BB_MMU
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001813 child->pid = fork();
Eric Andersen72f9a422001-10-28 05:12:20 +00001814#else
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001815 child->pid = vfork();
Eric Andersen72f9a422001-10-28 05:12:20 +00001816#endif
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001817 if (!child->pid) { /* child */
1818 /* Every child adds itself to new process group
1819 * with pgid == pid of first child in pipe */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001820#if ENABLE_HUSH_JOB
Denis Vlasenko170435c2007-05-23 13:01:10 +00001821 if (run_list_level == 1 && interactive_fd) {
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00001822 /* Don't do pgrp restore anymore on fatal signals */
1823 set_fatal_sighandler(SIG_DFL);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001824 if (pi->pgrp < 0) /* true for 1st process only */
1825 pi->pgrp = getpid();
1826 if (setpgid(0, pi->pgrp) == 0 && pi->followup != PIPE_BG) {
1827 /* We do it in *every* child, not just first,
1828 * to avoid races */
1829 tcsetpgrp(interactive_fd, pi->pgrp);
1830 }
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001831 }
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001832#endif
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001833 /* in non-interactive case fatal sigs are already SIG_DFL */
Eric Andersen25f27032001-04-26 23:22:31 +00001834 close_all();
Eric Andersen25f27032001-04-26 23:22:31 +00001835 if (nextin != 0) {
1836 dup2(nextin, 0);
1837 close(nextin);
1838 }
1839 if (nextout != 1) {
1840 dup2(nextout, 1);
1841 close(nextout);
1842 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00001843 if (pipefds[0] != -1) {
Eric Andersen25f27032001-04-26 23:22:31 +00001844 close(pipefds[0]); /* opposite end of our output pipe */
1845 }
Eric Andersen25f27032001-04-26 23:22:31 +00001846 /* Like bash, explicit redirects override pipes,
1847 * and the pipe fd is available for dup'ing. */
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00001848 setup_redirects(child, NULL);
Eric Andersen52a97ca2001-06-22 06:49:26 +00001849
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001850 /* Restore default handlers just prior to exec */
1851 set_jobctrl_sighandler(SIG_DFL);
1852 set_misc_sighandler(SIG_DFL);
1853 signal(SIGCHLD, SIG_DFL);
Eric Andersen25f27032001-04-26 23:22:31 +00001854 pseudo_exec(child);
1855 }
Eric Andersenc7bda1c2004-03-15 08:29:22 +00001856
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001857 pi->running_progs++;
1858
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001859#if ENABLE_HUSH_JOB
Denis Vlasenko2f1bb362007-04-21 10:01:14 +00001860 /* Second and next children need to know pid of first one */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001861 if (pi->pgrp < 0)
Eric Andersen0fcd4472001-05-02 20:12:03 +00001862 pi->pgrp = child->pid;
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001863#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001864 if (nextin != 0)
1865 close(nextin);
1866 if (nextout != 1)
1867 close(nextout);
1868
Eric Andersenc7bda1c2004-03-15 08:29:22 +00001869 /* If there isn't another process, nextin is garbage
Eric Andersen25f27032001-04-26 23:22:31 +00001870 but it doesn't matter */
1871 nextin = pipefds[0];
1872 }
Denis Vlasenkod01ff132007-05-02 21:40:23 +00001873 debug_printf_exec("run_pipe_real return -1\n");
Eric Andersen25f27032001-04-26 23:22:31 +00001874 return -1;
1875}
1876
Denis Vlasenko400c5b62007-05-04 13:07:27 +00001877#ifndef debug_print_tree
1878static void debug_print_tree(struct pipe *pi, int lvl)
1879{
1880 static const char *PIPE[] = {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001881 [PIPE_SEQ] = "SEQ",
1882 [PIPE_AND] = "AND",
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001883 [PIPE_OR ] = "OR" ,
1884 [PIPE_BG ] = "BG" ,
Denis Vlasenko400c5b62007-05-04 13:07:27 +00001885 };
1886 static const char *RES[] = {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001887 [RES_NONE ] = "NONE" ,
Denis Vlasenko06810332007-05-21 23:30:54 +00001888#if ENABLE_HUSH_IF
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001889 [RES_IF ] = "IF" ,
1890 [RES_THEN ] = "THEN" ,
1891 [RES_ELIF ] = "ELIF" ,
1892 [RES_ELSE ] = "ELSE" ,
1893 [RES_FI ] = "FI" ,
Denis Vlasenko06810332007-05-21 23:30:54 +00001894#endif
1895#if ENABLE_HUSH_LOOPS
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001896 [RES_FOR ] = "FOR" ,
1897 [RES_WHILE] = "WHILE",
1898 [RES_UNTIL] = "UNTIL",
1899 [RES_DO ] = "DO" ,
1900 [RES_DONE ] = "DONE" ,
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001901 [RES_IN ] = "IN" ,
Denis Vlasenko06810332007-05-21 23:30:54 +00001902#endif
1903 [RES_XXXX ] = "XXXX" ,
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001904 [RES_SNTX ] = "SNTX" ,
Denis Vlasenko400c5b62007-05-04 13:07:27 +00001905 };
1906
1907 int pin, prn;
Denis Vlasenko219e88d2007-05-21 10:18:23 +00001908
Denis Vlasenko400c5b62007-05-04 13:07:27 +00001909 pin = 0;
1910 while (pi) {
Denis Vlasenko219e88d2007-05-21 10:18:23 +00001911 fprintf(stderr, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
1912 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
Denis Vlasenko400c5b62007-05-04 13:07:27 +00001913 prn = 0;
1914 while (prn < pi->num_progs) {
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00001915 struct child_prog *child = &pi->progs[prn];
1916 char **argv = child->argv;
1917
Denis Vlasenko400c5b62007-05-04 13:07:27 +00001918 fprintf(stderr, "%*s prog %d", lvl*2, "", prn);
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00001919 if (child->group) {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001920 fprintf(stderr, " group %s: (argv=%p)\n",
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00001921 (child->subshell ? "()" : "{}"),
1922 argv);
1923 debug_print_tree(child->group, lvl+1);
Denis Vlasenko400c5b62007-05-04 13:07:27 +00001924 prn++;
1925 continue;
1926 }
Denis Vlasenko400c5b62007-05-04 13:07:27 +00001927 if (argv) while (*argv) {
1928 fprintf(stderr, " '%s'", *argv);
1929 argv++;
1930 }
1931 fprintf(stderr, "\n");
1932 prn++;
1933 }
1934 pi = pi->next;
1935 pin++;
1936 }
1937}
1938#endif
1939
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001940/* NB: called by pseudo_exec, and therefore must not modify any
1941 * global data until exec/_exit (we can be a child after vfork!) */
Eric Andersen25f27032001-04-26 23:22:31 +00001942static int run_list_real(struct pipe *pi)
1943{
Denis Vlasenko06810332007-05-21 23:30:54 +00001944 struct pipe *rpipe;
1945#if ENABLE_HUSH_LOOPS
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00001946 char *for_varname = NULL;
1947 char **for_lcur = NULL;
1948 char **for_list = NULL;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00001949 int flag_rep = 0;
Denis Vlasenko06810332007-05-21 23:30:54 +00001950#endif
Eric Andersen4c9b68f2002-04-13 12:33:41 +00001951 int save_num_progs;
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001952 int flag_skip = 1;
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00001953 int rcode = 0; /* probably for gcc only */
Eric Andersen4c9b68f2002-04-13 12:33:41 +00001954 int flag_restore = 0;
Denis Vlasenko06810332007-05-21 23:30:54 +00001955#if ENABLE_HUSH_IF
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001956 int if_code = 0, next_if_code = 0; /* need double-buffer to handle elif */
Denis Vlasenko06810332007-05-21 23:30:54 +00001957#else
1958 enum { if_code = 0, next_if_code = 0 };
1959#endif
Denis Vlasenko219e88d2007-05-21 10:18:23 +00001960 reserved_style rword;
1961 reserved_style skip_more_for_this_rword = RES_XXXX;
Denis Vlasenko4ac530c2007-05-02 15:35:45 +00001962
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001963 debug_printf_exec("run_list_real start lvl %d\n", run_list_level + 1);
Denis Vlasenko4ac530c2007-05-02 15:35:45 +00001964
Denis Vlasenko06810332007-05-21 23:30:54 +00001965#if ENABLE_HUSH_LOOPS
Eric Andersen4c9b68f2002-04-13 12:33:41 +00001966 /* check syntax for "for" */
1967 for (rpipe = pi; rpipe; rpipe = rpipe->next) {
Denis Vlasenko219e88d2007-05-21 10:18:23 +00001968 if ((rpipe->res_word == RES_IN || rpipe->res_word == RES_FOR)
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001969 && (rpipe->next == NULL)
1970 ) {
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001971 syntax("malformed for"); /* no IN or no commands after 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 Andersenc7bda1c2004-03-15 08:29:22 +00001974 }
Denis Vlasenko219e88d2007-05-21 10:18:23 +00001975 if ((rpipe->res_word == RES_IN && rpipe->next->res_word == RES_IN && rpipe->next->progs[0].argv != NULL)
1976 || (rpipe->res_word == RES_FOR && rpipe->next->res_word != RES_IN)
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001977 ) {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001978 /* TODO: what is tested in the first condition? */
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001979 syntax("malformed for"); /* 2nd condition: not followed by IN */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001980 debug_printf_exec("run_list_real lvl %d return 1\n", run_list_level);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001981 return 1;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00001982 }
1983 }
Denis Vlasenko06810332007-05-21 23:30:54 +00001984#else
1985 rpipe = NULL;
1986#endif
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001987
1988#if ENABLE_HUSH_JOB
1989 /* Example of nested list: "while true; do { sleep 1 | exit 2; } done".
1990 * We are saving state before entering outermost list ("while...done")
1991 * so that ctrl-Z will correctly background _entire_ outermost list,
1992 * not just a part of it (like "sleep 1 | exit 2") */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001993 if (++run_list_level == 1 && interactive_fd) {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001994 if (sigsetjmp(toplevel_jb, 1)) {
1995 /* ctrl-Z forked and we are parent; or ctrl-C.
1996 * Sighandler has longjmped us here */
1997 signal(SIGINT, SIG_IGN);
1998 signal(SIGTSTP, SIG_IGN);
1999 /* Restore level (we can be coming from deep inside
2000 * nested levels) */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00002001 run_list_level = 1;
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002002#if ENABLE_FEATURE_SH_STANDALONE
2003 if (nofork_save.saved) { /* if save area is valid */
2004 debug_printf_jobs("exiting nofork early\n");
2005 restore_nofork_data(&nofork_save);
2006 }
2007#endif
2008 if (ctrl_z_flag) {
2009 /* ctrl-Z has forked and stored pid of the child in pi->pid.
2010 * Remember this child as background job */
2011 insert_bg_job(pi);
2012 } else {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002013 /* ctrl-C. We just stop doing whatever we were doing */
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002014 putchar('\n');
2015 }
2016 rcode = 0;
2017 goto ret;
2018 }
2019 /* ctrl-Z handler will store pid etc in pi */
2020 toplevel_list = pi;
2021 ctrl_z_flag = 0;
2022#if ENABLE_FEATURE_SH_STANDALONE
2023 nofork_save.saved = 0; /* in case we will run a nofork later */
2024#endif
2025 signal_SA_RESTART(SIGTSTP, handler_ctrl_z);
2026 signal(SIGINT, handler_ctrl_c);
2027 }
2028#endif
2029
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002030 for (; pi; pi = flag_restore ? rpipe : pi->next) {
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002031 rword = pi->res_word;
Denis Vlasenko06810332007-05-21 23:30:54 +00002032#if ENABLE_HUSH_LOOPS
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002033 if (rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002034 flag_restore = 0;
2035 if (!rpipe) {
2036 flag_rep = 0;
2037 rpipe = pi;
2038 }
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002039 }
Denis Vlasenko06810332007-05-21 23:30:54 +00002040#endif
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002041 debug_printf_exec(": rword=%d if_code=%d next_if_code=%d skip_more=%d\n",
2042 rword, if_code, next_if_code, skip_more_for_this_rword);
2043 if (rword == skip_more_for_this_rword && flag_skip) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002044 if (pi->followup == PIPE_SEQ)
2045 flag_skip = 0;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002046 continue;
2047 }
2048 flag_skip = 1;
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002049 skip_more_for_this_rword = RES_XXXX;
Denis Vlasenko06810332007-05-21 23:30:54 +00002050#if ENABLE_HUSH_IF
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002051 if (rword == RES_THEN || rword == RES_ELSE)
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002052 if_code = next_if_code;
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002053 if (rword == RES_THEN && if_code)
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002054 continue;
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002055 if (rword == RES_ELSE && !if_code)
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002056 continue;
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002057 if (rword == RES_ELIF && !if_code)
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002058 break;
Denis Vlasenko06810332007-05-21 23:30:54 +00002059#endif
2060#if ENABLE_HUSH_LOOPS
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002061 if (rword == RES_FOR && pi->num_progs) {
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002062 if (!for_lcur) {
Eric Andersenc7bda1c2004-03-15 08:29:22 +00002063 /* if no variable values after "in" we skip "for" */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002064 if (!pi->next->progs->argv)
2065 continue;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002066 /* create list of variable values */
Denis Vlasenko170435c2007-05-23 13:01:10 +00002067 for_list = expand_strvec_to_strvec(pi->next->progs->argv);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002068 for_lcur = for_list;
2069 for_varname = pi->progs->argv[0];
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002070 pi->progs->argv[0] = NULL;
2071 flag_rep = 1;
Eric Andersenc7bda1c2004-03-15 08:29:22 +00002072 }
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002073 free(pi->progs->argv[0]);
2074 if (!*for_lcur) {
2075 free(for_list);
2076 for_lcur = NULL;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002077 flag_rep = 0;
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002078 pi->progs->argv[0] = for_varname;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002079 pi->progs->glob_result.gl_pathv[0] = pi->progs->argv[0];
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002080 continue;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002081 }
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002082 /* insert next value from for_lcur */
Denis Vlasenko764d59d2007-05-14 16:23:23 +00002083 /* vda: does it need escaping? */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002084 pi->progs->argv[0] = xasprintf("%s=%s", for_varname, *for_lcur++);
Denis Vlasenko5f786c22007-04-20 08:35:45 +00002085 pi->progs->glob_result.gl_pathv[0] = pi->progs->argv[0];
Eric Andersenc7bda1c2004-03-15 08:29:22 +00002086 }
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002087 if (rword == RES_IN)
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002088 continue;
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002089 if (rword == RES_DO) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002090 if (!flag_rep)
2091 continue;
Tim Rikerc1ef7bd2006-01-25 00:08:53 +00002092 }
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002093 if (rword == RES_DONE) {
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002094 if (flag_rep) {
2095 flag_restore = 1;
2096 } else {
2097 rpipe = NULL;
2098 }
Eric Andersenc7bda1c2004-03-15 08:29:22 +00002099 }
Denis Vlasenko06810332007-05-21 23:30:54 +00002100#endif
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002101 if (pi->num_progs == 0)
2102 continue;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002103 save_num_progs = pi->num_progs; /* save number of programs */
Denis Vlasenkod01ff132007-05-02 21:40:23 +00002104 debug_printf_exec(": run_pipe_real with %d members\n", pi->num_progs);
Eric Andersen25f27032001-04-26 23:22:31 +00002105 rcode = run_pipe_real(pi);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002106 if (rcode != -1) {
Eric Andersen25f27032001-04-26 23:22:31 +00002107 /* We only ran a builtin: rcode was set by the return value
2108 * of run_pipe_real(), and we don't need to wait for anything. */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002109 } else if (pi->followup == PIPE_BG) {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002110 /* What does bash do with attempts to background builtins? */
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002111 /* Even bash 3.2 doesn't do that well with nested bg:
2112 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
Denis Vlasenko170435c2007-05-23 13:01:10 +00002113 * I'm NOT treating inner &'s as jobs */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00002114#if ENABLE_HUSH_JOB
Denis Vlasenko170435c2007-05-23 13:01:10 +00002115 if (run_list_level == 1)
2116 insert_bg_job(pi);
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00002117#endif
Eric Andersen25f27032001-04-26 23:22:31 +00002118 rcode = EXIT_SUCCESS;
2119 } else {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00002120#if ENABLE_HUSH_JOB
Denis Vlasenko170435c2007-05-23 13:01:10 +00002121 /* Paranoia, just "interactive_fd" should be enough? */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00002122 if (run_list_level == 1 && interactive_fd) {
Denis Vlasenko170435c2007-05-23 13:01:10 +00002123 /* waits for completion, then fg's main shell */
Denis Vlasenko52881e92007-04-21 13:42:52 +00002124 rcode = checkjobs_and_fg_shell(pi);
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00002125 } else
2126#endif
2127 {
Denis Vlasenko170435c2007-05-23 13:01:10 +00002128 /* this one just waits for completion */
Eric Andersenc798b072001-06-22 06:23:03 +00002129 rcode = checkjobs(pi);
Eric Andersen25f27032001-04-26 23:22:31 +00002130 }
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002131 debug_printf_exec(": checkjobs returned %d\n", rcode);
Eric Andersen25f27032001-04-26 23:22:31 +00002132 }
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002133 debug_printf_exec(": setting last_return_code=%d\n", rcode);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002134 last_return_code = rcode;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002135 pi->num_progs = save_num_progs; /* restore number of programs */
Denis Vlasenko06810332007-05-21 23:30:54 +00002136#if ENABLE_HUSH_IF
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002137 if (rword == RES_IF || rword == RES_ELIF)
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002138 next_if_code = rcode; /* can be overwritten a number of times */
Denis Vlasenko06810332007-05-21 23:30:54 +00002139#endif
2140#if ENABLE_HUSH_LOOPS
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002141 if (rword == RES_WHILE)
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002142 flag_rep = !last_return_code;
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002143 if (rword == RES_UNTIL)
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002144 flag_rep = last_return_code;
Denis Vlasenko06810332007-05-21 23:30:54 +00002145#endif
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002146 if ((rcode == EXIT_SUCCESS && pi->followup == PIPE_OR)
2147 || (rcode != EXIT_SUCCESS && pi->followup == PIPE_AND)
2148 ) {
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002149 skip_more_for_this_rword = rword;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002150 }
Eric Andersen028b65b2001-06-28 01:10:11 +00002151 checkjobs(NULL);
Eric Andersen25f27032001-04-26 23:22:31 +00002152 }
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002153
2154#if ENABLE_HUSH_JOB
2155 if (ctrl_z_flag) {
2156 /* ctrl-Z forked somewhere in the past, we are the child,
2157 * and now we completed running the list. Exit. */
2158 exit(rcode);
2159 }
2160 ret:
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00002161 run_list_level--;
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002162#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00002163 debug_printf_exec("run_list_real lvl %d return %d\n", run_list_level + 1, rcode);
Eric Andersen25f27032001-04-26 23:22:31 +00002164 return rcode;
2165}
2166
Eric Andersen25f27032001-04-26 23:22:31 +00002167/* return code is the exit status of the pipe */
Eric Andersenbf7df042001-05-23 22:18:35 +00002168static int free_pipe(struct pipe *pi, int indent)
Eric Andersen25f27032001-04-26 23:22:31 +00002169{
2170 char **p;
2171 struct child_prog *child;
2172 struct redir_struct *r, *rnext;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002173 int a, i, ret_code = 0;
Eric Andersen52a97ca2001-06-22 06:49:26 +00002174
2175 if (pi->stopped_progs > 0)
2176 return ret_code;
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002177 debug_printf_clean("%s run pipe: (pid %d)\n", indenter(indent), getpid());
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002178 for (i = 0; i < pi->num_progs; i++) {
Eric Andersen25f27032001-04-26 23:22:31 +00002179 child = &pi->progs[i];
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002180 debug_printf_clean("%s command %d:\n", indenter(indent), i);
Eric Andersen25f27032001-04-26 23:22:31 +00002181 if (child->argv) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002182 for (a = 0, p = child->argv; *p; a++, p++) {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002183 debug_printf_clean("%s argv[%d] = %s\n", indenter(indent), a, *p);
Eric Andersen25f27032001-04-26 23:22:31 +00002184 }
2185 globfree(&child->glob_result);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002186 child->argv = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00002187 } else if (child->group) {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002188 debug_printf_clean("%s begin group (subshell:%d)\n", indenter(indent), child->subshell);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002189 ret_code = free_pipe_list(child->group, indent+3);
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002190 debug_printf_clean("%s end group\n", indenter(indent));
Eric Andersen25f27032001-04-26 23:22:31 +00002191 } else {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002192 debug_printf_clean("%s (nil)\n", indenter(indent));
Eric Andersen25f27032001-04-26 23:22:31 +00002193 }
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002194 for (r = child->redirects; r; r = rnext) {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002195 debug_printf_clean("%s redirect %d%s", indenter(indent), r->fd, redir_table[r->type].descrip);
Eric Andersen25f27032001-04-26 23:22:31 +00002196 if (r->dup == -1) {
Eric Andersen817e73c2001-06-06 17:56:09 +00002197 /* guard against the case >$FOO, where foo is unset or blank */
2198 if (r->word.gl_pathv) {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002199 debug_printf_clean(" %s\n", *r->word.gl_pathv);
Eric Andersen817e73c2001-06-06 17:56:09 +00002200 globfree(&r->word);
2201 }
Eric Andersen25f27032001-04-26 23:22:31 +00002202 } else {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002203 debug_printf_clean("&%d\n", r->dup);
Eric Andersen25f27032001-04-26 23:22:31 +00002204 }
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002205 rnext = r->next;
Eric Andersen25f27032001-04-26 23:22:31 +00002206 free(r);
2207 }
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002208 child->redirects = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00002209 }
2210 free(pi->progs); /* children are an array, they get freed all at once */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002211 pi->progs = NULL;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00002212#if ENABLE_HUSH_JOB
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00002213 free(pi->cmdtext);
2214 pi->cmdtext = NULL;
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00002215#endif
Eric Andersen25f27032001-04-26 23:22:31 +00002216 return ret_code;
2217}
2218
Eric Andersenbf7df042001-05-23 22:18:35 +00002219static int free_pipe_list(struct pipe *head, int indent)
Eric Andersen25f27032001-04-26 23:22:31 +00002220{
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002221 int rcode = 0; /* if list has no members */
Eric Andersen25f27032001-04-26 23:22:31 +00002222 struct pipe *pi, *next;
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002223
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002224 for (pi = head; pi; pi = next) {
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002225 debug_printf_clean("%s pipe reserved mode %d\n", indenter(indent), pi->res_word);
Eric Andersenbf7df042001-05-23 22:18:35 +00002226 rcode = free_pipe(pi, indent);
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002227 debug_printf_clean("%s pipe followup code %d\n", indenter(indent), pi->followup);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002228 next = pi->next;
Denis Vlasenko5f786c22007-04-20 08:35:45 +00002229 /*pi->next = NULL;*/
Eric Andersen25f27032001-04-26 23:22:31 +00002230 free(pi);
2231 }
Eric Andersenc7bda1c2004-03-15 08:29:22 +00002232 return rcode;
Eric Andersen25f27032001-04-26 23:22:31 +00002233}
2234
2235/* Select which version we will use */
2236static int run_list(struct pipe *pi)
2237{
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002238 int rcode = 0;
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002239 debug_printf_exec("run_list entered\n");
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002240 if (fake_mode == 0) {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002241 debug_printf_exec(": run_list_real with %d members\n", pi->num_progs);
Eric Andersen25f27032001-04-26 23:22:31 +00002242 rcode = run_list_real(pi);
Eric Andersenc7bda1c2004-03-15 08:29:22 +00002243 }
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002244 /* free_pipe_list has the side effect of clearing memory.
Eric Andersen25f27032001-04-26 23:22:31 +00002245 * In the long run that function can be merged with run_list_real,
2246 * but doing that now would hobble the debugging effort. */
Denis Vlasenko400c5b62007-05-04 13:07:27 +00002247 free_pipe_list(pi, 0);
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002248 debug_printf_exec("run_list return %d\n", rcode);
Eric Andersen25f27032001-04-26 23:22:31 +00002249 return rcode;
2250}
2251
2252/* The API for glob is arguably broken. This routine pushes a non-matching
2253 * string into the output structure, removing non-backslashed backslashes.
2254 * If someone can prove me wrong, by performing this function within the
2255 * original glob(3) api, feel free to rewrite this routine into oblivion.
2256 * Return code (0 vs. GLOB_NOSPACE) matches glob(3).
2257 * XXX broken if the last character is '\\', check that before calling.
2258 */
2259static int globhack(const char *src, int flags, glob_t *pglob)
2260{
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002261 int cnt = 0, pathc;
Eric Andersen25f27032001-04-26 23:22:31 +00002262 const char *s;
2263 char *dest;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002264 for (cnt = 1, s = src; s && *s; s++) {
Eric Andersen25f27032001-04-26 23:22:31 +00002265 if (*s == '\\') s++;
2266 cnt++;
2267 }
Denis Vlasenkoc666f712007-05-16 22:18:54 +00002268 dest = xmalloc(cnt);
Eric Andersen25f27032001-04-26 23:22:31 +00002269 if (!(flags & GLOB_APPEND)) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002270 pglob->gl_pathv = NULL;
2271 pglob->gl_pathc = 0;
2272 pglob->gl_offs = 0;
2273 pglob->gl_offs = 0;
Eric Andersen25f27032001-04-26 23:22:31 +00002274 }
2275 pathc = ++pglob->gl_pathc;
Denis Vlasenkoc666f712007-05-16 22:18:54 +00002276 pglob->gl_pathv = xrealloc(pglob->gl_pathv, (pathc+1) * sizeof(*pglob->gl_pathv));
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002277 pglob->gl_pathv[pathc-1] = dest;
2278 pglob->gl_pathv[pathc] = NULL;
2279 for (s = src; s && *s; s++, dest++) {
Eric Andersen25f27032001-04-26 23:22:31 +00002280 if (*s == '\\') s++;
2281 *dest = *s;
2282 }
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002283 *dest = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00002284 return 0;
2285}
2286
2287/* XXX broken if the last character is '\\', check that before calling */
2288static int glob_needed(const char *s)
2289{
2290 for (; *s; s++) {
2291 if (*s == '\\') s++;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002292 if (strchr("*[?", *s)) return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00002293 }
2294 return 0;
2295}
2296
Eric Andersen25f27032001-04-26 23:22:31 +00002297static int xglob(o_string *dest, int flags, glob_t *pglob)
2298{
2299 int gr;
2300
Tim Rikerc1ef7bd2006-01-25 00:08:53 +00002301 /* short-circuit for null word */
Eric Andersen25f27032001-04-26 23:22:31 +00002302 /* we can code this better when the debug_printf's are gone */
Tim Rikerc1ef7bd2006-01-25 00:08:53 +00002303 if (dest->length == 0) {
2304 if (dest->nonnull) {
2305 /* bash man page calls this an "explicit" null */
2306 gr = globhack(dest->data, flags, pglob);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002307 debug_printf("globhack returned %d\n", gr);
Tim Rikerc1ef7bd2006-01-25 00:08:53 +00002308 } else {
Eric Andersen25f27032001-04-26 23:22:31 +00002309 return 0;
2310 }
Tim Rikerc1ef7bd2006-01-25 00:08:53 +00002311 } else if (glob_needed(dest->data)) {
Eric Andersen25f27032001-04-26 23:22:31 +00002312 gr = glob(dest->data, flags, NULL, pglob);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002313 debug_printf("glob returned %d\n", gr);
Eric Andersen25f27032001-04-26 23:22:31 +00002314 if (gr == GLOB_NOMATCH) {
2315 /* quote removal, or more accurately, backslash removal */
2316 gr = globhack(dest->data, flags, pglob);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002317 debug_printf("globhack returned %d\n", gr);
Eric Andersen25f27032001-04-26 23:22:31 +00002318 }
2319 } else {
2320 gr = globhack(dest->data, flags, pglob);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002321 debug_printf("globhack returned %d\n", gr);
Eric Andersen25f27032001-04-26 23:22:31 +00002322 }
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002323 if (gr == GLOB_NOSPACE)
Manuel Novoa III cad53642003-03-19 09:13:01 +00002324 bb_error_msg_and_die("out of memory during glob");
Eric Andersen25f27032001-04-26 23:22:31 +00002325 if (gr != 0) { /* GLOB_ABORTED ? */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002326 bb_error_msg("glob(3) error %d", gr);
Eric Andersen25f27032001-04-26 23:22:31 +00002327 }
2328 /* globprint(glob_target); */
2329 return gr;
2330}
2331
Denis Vlasenko170435c2007-05-23 13:01:10 +00002332/* expand_strvec_to_strvec() takes a list of strings, expands
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002333 * all variable references within and returns a pointer to
2334 * a list of expanded strings, possibly with larger number
2335 * of strings. (Think VAR="a b"; echo $VAR).
2336 * This new list is allocated as a single malloc block.
2337 * NULL-terminated list of char* pointers is at the beginning of it,
2338 * followed by strings themself.
2339 * Caller can deallocate entire list by single free(list). */
2340
2341/* Helpers first:
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00002342 * count_XXX estimates size of the block we need. It's okay
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002343 * to over-estimate sizes a bit, if it makes code simpler */
2344static int count_ifs(const char *str)
2345{
2346 int cnt = 0;
2347 debug_printf_expand("count_ifs('%s') ifs='%s'", str, ifs);
2348 while (1) {
2349 str += strcspn(str, ifs);
2350 if (!*str) break;
Denis Vlasenkoc666f712007-05-16 22:18:54 +00002351 str++; /* str += strspn(str, ifs); */
2352 cnt++; /* cnt += strspn(str, ifs); - but this code is larger */
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00002353 }
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002354 debug_printf_expand(" return %d\n", cnt);
2355 return cnt;
2356}
2357
2358static void count_var_expansion_space(int *countp, int *lenp, char *arg)
2359{
2360 char first_ch;
2361 int i;
2362 int len = *lenp;
2363 int count = *countp;
2364 const char *val;
2365 char *p;
2366
2367 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL))) {
2368 len += p - arg;
2369 arg = ++p;
2370 p = strchr(p, SPECIAL_VAR_SYMBOL);
2371 first_ch = arg[0];
2372
2373 switch (first_ch & 0x7f) {
2374 /* high bit in 1st_ch indicates that var is double-quoted */
2375 case '$': /* pid */
2376 case '!': /* bg pid */
2377 case '?': /* exitcode */
2378 case '#': /* argc */
2379 len += sizeof(int)*3 + 1; /* enough for int */
2380 break;
2381 case '*':
2382 case '@':
2383 for (i = 1; i < global_argc; i++) {
2384 len += strlen(global_argv[i]) + 1;
2385 count++;
2386 if (!(first_ch & 0x80))
2387 count += count_ifs(global_argv[i]);
2388 }
2389 break;
2390 default:
2391 *p = '\0';
2392 arg[0] = first_ch & 0x7f;
Denis Vlasenko764d59d2007-05-14 16:23:23 +00002393 if (isdigit(arg[0])) {
2394 i = xatoi_u(arg);
2395 val = NULL;
2396 if (i < global_argc)
2397 val = global_argv[i];
2398 } else
2399 val = lookup_param(arg);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002400 arg[0] = first_ch;
2401 *p = SPECIAL_VAR_SYMBOL;
2402
2403 if (val) {
2404 len += strlen(val) + 1;
2405 if (!(first_ch & 0x80))
2406 count += count_ifs(val);
2407 }
2408 }
2409 arg = ++p;
2410 }
2411
2412 len += strlen(arg) + 1;
2413 count++;
2414 *lenp = len;
2415 *countp = count;
2416}
2417
2418/* Store given string, finalizing the word and starting new one whenever
2419 * we encounter ifs char(s). This is used for expanding variable values.
Denis Vlasenko764d59d2007-05-14 16:23:23 +00002420 * End-of-string does NOT finalize word: think about 'echo -$VAR-' */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002421static int expand_on_ifs(char **list, int n, char **posp, const char *str)
2422{
2423 char *pos = *posp;
2424 while (1) {
2425 int word_len = strcspn(str, ifs);
2426 if (word_len) {
2427 memcpy(pos, str, word_len); /* store non-ifs chars */
2428 pos += word_len;
2429 str += word_len;
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002430 }
Denis Vlasenko764d59d2007-05-14 16:23:23 +00002431 if (!*str) /* EOL - do not finalize word */
2432 break;
2433 *pos++ = '\0';
2434 if (n) debug_printf_expand("expand_on_ifs finalized list[%d]=%p '%s' "
2435 "strlen=%d next=%p pos=%p\n", n-1, list[n-1], list[n-1],
2436 strlen(list[n-1]), list[n-1] + strlen(list[n-1]) + 1, pos);
2437 list[n++] = pos;
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002438 str += strspn(str, ifs); /* skip ifs chars */
2439 }
2440 *posp = pos;
2441 return n;
2442}
2443
2444/* Expand all variable references in given string, adding words to list[]
2445 * at n, n+1,... positions. Return updated n (so that list[n] is next one
2446 * to be filled). This routine is extremely tricky: has to deal with
2447 * variables/parameters with whitespace, $* and $@, and constructs like
2448 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002449/* NB: another bug is that we cannot detect empty strings yet:
2450 * "" or $empty"" expands to zero words, has to expand to empty word */
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002451static int expand_vars_to_list(char **list, int n, char **posp, char *arg, char or_mask)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002452{
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002453 /* or_mask is either 0 (normal case) or 0x80
2454 * (expansion of right-hand side of assignment == 1-element expand) */
2455
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002456 char first_ch, ored_ch;
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00002457 int i;
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002458 const char *val;
2459 char *p;
2460 char *pos = *posp;
2461
2462 ored_ch = 0;
2463
2464 if (n) debug_printf_expand("expand_vars_to_list finalized list[%d]=%p '%s' "
2465 "strlen=%d next=%p pos=%p\n", n-1, list[n-1], list[n-1],
2466 strlen(list[n-1]), list[n-1] + strlen(list[n-1]) + 1, pos);
2467 list[n++] = pos;
2468
2469 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL))) {
2470 memcpy(pos, arg, p - arg);
2471 pos += (p - arg);
2472 arg = ++p;
2473 p = strchr(p, SPECIAL_VAR_SYMBOL);
2474
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002475 first_ch = arg[0] | or_mask; /* forced to "quoted" if or_mask = 0x80 */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002476 ored_ch |= first_ch;
2477 val = NULL;
2478 switch (first_ch & 0x7f) {
2479 /* Highest bit in first_ch indicates that var is double-quoted */
2480 case '$': /* pid */
2481 /* FIXME: (echo $$) should still print pid of main shell */
2482 val = utoa(getpid());
2483 break;
2484 case '!': /* bg pid */
2485 val = last_bg_pid ? utoa(last_bg_pid) : (char*)"";
2486 break;
2487 case '?': /* exitcode */
2488 val = utoa(last_return_code);
2489 break;
2490 case '#': /* argc */
2491 val = utoa(global_argc ? global_argc-1 : 0);
2492 break;
2493 case '*':
2494 case '@':
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00002495 i = 1;
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002496 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002497 while (i < global_argc) {
2498 n = expand_on_ifs(list, n, &pos, global_argv[i]);
2499 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, global_argc-1);
2500 if (global_argv[i++][0] && i < global_argc) {
2501 /* this argv[] is not empty and not last:
2502 * put terminating NUL, start new word */
2503 *pos++ = '\0';
2504 if (n) debug_printf_expand("expand_vars_to_list 2 finalized list[%d]=%p '%s' "
2505 "strlen=%d next=%p pos=%p\n", n-1, list[n-1], list[n-1],
2506 strlen(list[n-1]), list[n-1] + strlen(list[n-1]) + 1, pos);
2507 list[n++] = pos;
2508 }
2509 }
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002510 } else
2511 /* If or_mask is nonzero, we handle assignment 'a=....$@.....'
2512 * and in this case should theat it like '$*' */
2513 if (first_ch == ('@'|0x80) && !or_mask) { /* quoted $@ */
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00002514 while (1) {
2515 strcpy(pos, global_argv[i]);
2516 pos += strlen(global_argv[i]);
2517 if (++i >= global_argc)
2518 break;
2519 *pos++ = '\0';
2520 if (n) debug_printf_expand("expand_vars_to_list 3 finalized list[%d]=%p '%s' "
2521 "strlen=%d next=%p pos=%p\n", n-1, list[n-1], list[n-1],
2522 strlen(list[n-1]), list[n-1] + strlen(list[n-1]) + 1, pos);
2523 list[n++] = pos;
2524 }
2525 } else { /* quoted $*: add as one word */
2526 while (1) {
2527 strcpy(pos, global_argv[i]);
2528 pos += strlen(global_argv[i]);
2529 if (++i >= global_argc)
2530 break;
2531 if (ifs[0])
2532 *pos++ = ifs[0];
2533 }
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002534 }
2535 break;
2536 default:
2537 *p = '\0';
2538 arg[0] = first_ch & 0x7f;
Denis Vlasenko764d59d2007-05-14 16:23:23 +00002539 if (isdigit(arg[0])) {
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00002540 i = xatoi_u(arg);
Denis Vlasenko764d59d2007-05-14 16:23:23 +00002541 val = NULL;
2542 if (i < global_argc)
2543 val = global_argv[i];
2544 } else
2545 val = lookup_param(arg);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002546 arg[0] = first_ch;
2547 *p = SPECIAL_VAR_SYMBOL;
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00002548 if (!(first_ch & 0x80)) { /* unquoted $VAR */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002549 if (val) {
2550 n = expand_on_ifs(list, n, &pos, val);
2551 val = NULL;
2552 }
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00002553 } /* else: quoted $VAR, val will be appended at pos */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002554 }
2555 if (val) {
2556 strcpy(pos, val);
2557 pos += strlen(val);
2558 }
2559 arg = ++p;
2560 }
2561 debug_printf_expand("expand_vars_to_list adding tail '%s' at %p\n", arg, pos);
2562 strcpy(pos, arg);
2563 pos += strlen(arg) + 1;
2564 if (pos == list[n-1] + 1) { /* expansion is empty */
2565 if (!(ored_ch & 0x80)) { /* all vars were not quoted... */
2566 debug_printf_expand("expand_vars_to_list list[%d] empty, going back\n", n);
2567 pos--;
2568 n--;
2569 }
2570 }
2571
2572 *posp = pos;
2573 return n;
2574}
2575
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002576static char **expand_variables(char **argv, char or_mask)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002577{
2578 int n;
2579 int count = 1;
2580 int len = 0;
2581 char *pos, **v, **list;
2582
2583 v = argv;
2584 if (!*v) debug_printf_expand("count_var_expansion_space: "
2585 "argv[0]=NULL count=%d len=%d alloc_space=%d\n",
2586 count, len, sizeof(char*) * count + len);
2587 while (*v) {
2588 count_var_expansion_space(&count, &len, *v);
2589 debug_printf_expand("count_var_expansion_space: "
2590 "'%s' count=%d len=%d alloc_space=%d\n",
2591 *v, count, len, sizeof(char*) * count + len);
2592 v++;
2593 }
2594 len += sizeof(char*) * count; /* total to alloc */
2595 list = xmalloc(len);
2596 pos = (char*)(list + count);
2597 debug_printf_expand("list=%p, list[0] should be %p\n", list, pos);
2598 n = 0;
2599 v = argv;
2600 while (*v)
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002601 n = expand_vars_to_list(list, n, &pos, *v++, or_mask);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002602
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002603 if (n) debug_printf_expand("finalized list[%d]=%p '%s' "
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002604 "strlen=%d next=%p pos=%p\n", n-1, list[n-1], list[n-1],
2605 strlen(list[n-1]), list[n-1] + strlen(list[n-1]) + 1, pos);
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00002606 list[n] = NULL;
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002607
2608#ifdef DEBUG_EXPAND
2609 {
2610 int m = 0;
2611 while (m <= n) {
2612 debug_printf_expand("list[%d]=%p '%s'\n", m, list[m], list[m]);
2613 m++;
2614 }
2615 debug_printf_expand("used_space=%d\n", pos - (char*)list);
2616 }
2617#endif
Denis Vlasenko170435c2007-05-23 13:01:10 +00002618 if (ENABLE_HUSH_DEBUG)
2619 if (pos - (char*)list > len)
2620 bb_error_msg_and_die("BUG in varexp");
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00002621 return list;
2622}
2623
Denis Vlasenko170435c2007-05-23 13:01:10 +00002624static char **expand_strvec_to_strvec(char **argv)
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00002625{
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002626 return expand_variables(argv, 0);
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00002627}
2628
Denis Vlasenko170435c2007-05-23 13:01:10 +00002629static char *expand_string_to_string(const char *str)
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002630{
2631 char *argv[2], **list;
2632
2633 argv[0] = (char*)str;
2634 argv[1] = NULL;
2635 list = expand_variables(argv, 0x80); /* 0x80: make one-element expansion */
Denis Vlasenko170435c2007-05-23 13:01:10 +00002636 if (ENABLE_HUSH_DEBUG)
2637 if (!list[0] || list[1])
2638 bb_error_msg_and_die("BUG in varexp2");
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002639 /* actually, just move string 2*sizeof(char*) bytes back */
2640 strcpy((char*)list, list[0]);
Denis Vlasenko170435c2007-05-23 13:01:10 +00002641 debug_printf_expand("string_to_string='%s'\n", (char*)list);
2642 return (char*)list;
2643}
2644
2645static char* expand_strvec_to_string(char **argv)
2646{
2647 char **list;
2648
2649 list = expand_variables(argv, 0x80);
2650 /* Convert all NULs to spaces */
2651 if (list[0]) {
2652 int n = 1;
2653 while (list[n]) {
2654 if (ENABLE_HUSH_DEBUG)
2655 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
2656 bb_error_msg_and_die("BUG in varexp3");
2657 list[n][-1] = ' '; /* TODO: or to ifs[0]? */
2658 n++;
2659 }
2660 }
2661 strcpy((char*)list, list[0]);
2662 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002663 return (char*)list;
2664}
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002665
Eric Andersenf72f5622001-05-15 23:21:41 +00002666/* This is used to get/check local shell variables */
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002667static struct variable *get_local_var(const char *name)
Eric Andersenf72f5622001-05-15 23:21:41 +00002668{
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002669 struct variable *cur;
2670 int len;
Eric Andersenf72f5622001-05-15 23:21:41 +00002671
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002672 if (!name)
Eric Andersenf72f5622001-05-15 23:21:41 +00002673 return NULL;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002674 len = strlen(name);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002675 for (cur = top_var; cur; cur = cur->next) {
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002676 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002677 return cur;
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00002678 }
Eric Andersenf72f5622001-05-15 23:21:41 +00002679 return NULL;
2680}
2681
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002682/* str holds "NAME=VAL" and is expected to be malloced.
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002683 * We take ownership of it. */
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002684static int set_local_var(char *str, int flg_export)
Eric Andersen78a7c992001-05-15 16:30:25 +00002685{
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002686 struct variable *cur;
2687 char *value;
2688 int name_len;
Eric Andersen20a69a72001-05-15 17:24:44 +00002689
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002690 value = strchr(str, '=');
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002691 if (!value) { /* not expected to ever happen? */
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002692 free(str);
Eric Andersen99785762001-05-22 21:37:48 +00002693 return -1;
2694 }
Eric Andersen20a69a72001-05-15 17:24:44 +00002695
Denis Vlasenko201c72a2007-05-25 10:00:36 +00002696 name_len = value - str + 1; /* including '=' */
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002697 cur = top_var; /* cannot be NULL (we have HUSH_VERSION and it's RO) */
2698 while (1) {
Denis Vlasenko201c72a2007-05-25 10:00:36 +00002699 if (strncmp(cur->varstr, str, name_len) != 0) {
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002700 if (!cur->next) {
Denis Vlasenko201c72a2007-05-25 10:00:36 +00002701 /* Bail out. Note that now cur points
2702 * to last var in linked list */
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002703 break;
Eric Andersen20a69a72001-05-15 17:24:44 +00002704 }
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002705 cur = cur->next;
2706 continue;
Eric Andersen20a69a72001-05-15 17:24:44 +00002707 }
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002708 /* We found an existing var with this name */
2709 *value = '\0';
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002710 if (cur->flg_read_only) {
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002711 bb_error_msg("%s: readonly variable", str);
2712 free(str);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002713 return -1;
2714 }
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002715 unsetenv(str); /* just in case */
2716 *value = '=';
2717 if (strcmp(cur->varstr, str) == 0) {
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002718 free_and_exp:
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002719 free(str);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002720 goto exp;
2721 }
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002722 if (cur->max_len >= strlen(str)) {
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002723 /* This one is from startup env, reuse space */
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002724 strcpy(cur->varstr, str);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002725 goto free_and_exp;
2726 }
2727 /* max_len == 0 signifies "malloced" var, which we can
2728 * (and has to) free */
2729 if (!cur->max_len)
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002730 free(cur->varstr);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002731 cur->max_len = 0;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002732 goto set_str_and_exp;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002733 }
Eric Andersen20a69a72001-05-15 17:24:44 +00002734
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002735 /* Not found - create next variable struct */
2736 cur->next = xzalloc(sizeof(*cur));
2737 cur = cur->next;
2738
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002739 set_str_and_exp:
2740 cur->varstr = str;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002741 exp:
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002742 if (flg_export)
2743 cur->flg_export = 1;
2744 if (cur->flg_export)
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002745 return putenv(cur->varstr);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002746 return 0;
Eric Andersen20a69a72001-05-15 17:24:44 +00002747}
2748
Eric Andersenf72f5622001-05-15 23:21:41 +00002749static void unset_local_var(const char *name)
Eric Andersen20a69a72001-05-15 17:24:44 +00002750{
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002751 struct variable *cur;
2752 struct variable *prev = prev; /* for gcc */
2753 int name_len;
Eric Andersen20a69a72001-05-15 17:24:44 +00002754
Denis Vlasenko5f786c22007-04-20 08:35:45 +00002755 if (!name)
2756 return;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002757 name_len = strlen(name);
2758 cur = top_var;
2759 while (cur) {
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002760 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002761 if (cur->flg_read_only) {
Manuel Novoa III cad53642003-03-19 09:13:01 +00002762 bb_error_msg("%s: readonly variable", name);
Eric Andersen94ac2442001-05-22 19:05:18 +00002763 return;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002764 }
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002765 /* prev is ok to use here because 1st variable, HUSH_VERSION,
2766 * is ro, and we cannot reach this code on the 1st pass */
2767 prev->next = cur->next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002768 unsetenv(cur->varstr);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002769 if (!cur->max_len)
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002770 free(cur->varstr);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002771 free(cur);
Denis Vlasenko5f786c22007-04-20 08:35:45 +00002772 return;
Eric Andersenf72f5622001-05-15 23:21:41 +00002773 }
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002774 prev = cur;
2775 cur = cur->next;
Eric Andersen20a69a72001-05-15 17:24:44 +00002776 }
Eric Andersen78a7c992001-05-15 16:30:25 +00002777}
2778
2779static int is_assignment(const char *s)
2780{
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002781 if (!s || !isalpha(*s))
2782 return 0;
2783 s++;
2784 while (isalnum(*s) || *s == '_')
2785 s++;
2786 return *s == '=';
Eric Andersen78a7c992001-05-15 16:30:25 +00002787}
2788
Eric Andersen25f27032001-04-26 23:22:31 +00002789/* the src parameter allows us to peek forward to a possible &n syntax
2790 * for file descriptor duplication, e.g., "2>&1".
2791 * Return code is 0 normally, 1 if a syntax error is detected in src.
2792 * Resource errors (in xmalloc) cause the process to exit */
2793static int setup_redirect(struct p_context *ctx, int fd, redir_type style,
2794 struct in_str *input)
2795{
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002796 struct child_prog *child = ctx->child;
Eric Andersen25f27032001-04-26 23:22:31 +00002797 struct redir_struct *redir = child->redirects;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002798 struct redir_struct *last_redir = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00002799
2800 /* Create a new redir_struct and drop it onto the end of the linked list */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002801 while (redir) {
2802 last_redir = redir;
2803 redir = redir->next;
Eric Andersen25f27032001-04-26 23:22:31 +00002804 }
2805 redir = xmalloc(sizeof(struct redir_struct));
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002806 redir->next = NULL;
2807 redir->word.gl_pathv = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00002808 if (last_redir) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002809 last_redir->next = redir;
Eric Andersen25f27032001-04-26 23:22:31 +00002810 } else {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002811 child->redirects = redir;
Eric Andersen25f27032001-04-26 23:22:31 +00002812 }
2813
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002814 redir->type = style;
2815 redir->fd = (fd == -1) ? redir_table[style].default_fd : fd;
Eric Andersen25f27032001-04-26 23:22:31 +00002816
2817 debug_printf("Redirect type %d%s\n", redir->fd, redir_table[style].descrip);
2818
Eric Andersenc7bda1c2004-03-15 08:29:22 +00002819 /* Check for a '2>&1' type redirect */
Eric Andersen25f27032001-04-26 23:22:31 +00002820 redir->dup = redirect_dup_num(input);
2821 if (redir->dup == -2) return 1; /* syntax error */
2822 if (redir->dup != -1) {
2823 /* Erik had a check here that the file descriptor in question
Eric Andersen83a2ae22001-05-07 17:59:25 +00002824 * is legit; I postpone that to "run time"
2825 * A "-" representation of "close me" shows up as a -3 here */
Eric Andersen25f27032001-04-26 23:22:31 +00002826 debug_printf("Duplicating redirect '%d>&%d'\n", redir->fd, redir->dup);
2827 } else {
2828 /* We do _not_ try to open the file that src points to,
2829 * since we need to return and let src be expanded first.
2830 * Set ctx->pending_redirect, so we know what to do at the
Denis Vlasenko201c72a2007-05-25 10:00:36 +00002831 * end of the next parsed word. */
Eric Andersen25f27032001-04-26 23:22:31 +00002832 ctx->pending_redirect = redir;
2833 }
2834 return 0;
2835}
2836
Denis Vlasenkoac678ec2007-04-16 22:32:04 +00002837static struct pipe *new_pipe(void)
2838{
Eric Andersen25f27032001-04-26 23:22:31 +00002839 struct pipe *pi;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00002840 pi = xzalloc(sizeof(struct pipe));
2841 /*pi->num_progs = 0;*/
2842 /*pi->progs = NULL;*/
2843 /*pi->next = NULL;*/
2844 /*pi->followup = 0; invalid */
2845 if (RES_NONE)
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002846 pi->res_word = RES_NONE;
Eric Andersen25f27032001-04-26 23:22:31 +00002847 return pi;
2848}
2849
2850static void initialize_context(struct p_context *ctx)
2851{
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002852 ctx->child = NULL;
Denis Vlasenko1a735862007-05-23 00:32:25 +00002853 ctx->pipe = ctx->list_head = new_pipe();
2854 ctx->pending_redirect = NULL;
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002855 ctx->res_w = RES_NONE;
Denis Vlasenko1a735862007-05-23 00:32:25 +00002856 //only ctx->parse_type is not touched... is this intentional?
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002857 ctx->old_flag = 0;
Denis Vlasenko1a735862007-05-23 00:32:25 +00002858 ctx->stack = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00002859 done_command(ctx); /* creates the memory for working child */
2860}
2861
2862/* normal return is 0
2863 * if a reserved word is found, and processed, return 1
2864 * should handle if, then, elif, else, fi, for, while, until, do, done.
2865 * case, function, and select are obnoxious, save those for later.
2866 */
Denis Vlasenko06810332007-05-21 23:30:54 +00002867#if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS
"Vladimir N. Oleynik"19c37012005-09-22 14:33:15 +00002868static int reserved_word(o_string *dest, struct p_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00002869{
2870 struct reserved_combo {
Denis Vlasenko5f786c22007-04-20 08:35:45 +00002871 char literal[7];
2872 unsigned char code;
2873 int flag;
Eric Andersen25f27032001-04-26 23:22:31 +00002874 };
2875 /* Mostly a list of accepted follow-up reserved words.
2876 * FLAG_END means we are done with the sequence, and are ready
2877 * to turn the compound list into a command.
2878 * FLAG_START means the word must start a new compound list.
2879 */
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00002880 static const struct reserved_combo reserved_list[] = {
Denis Vlasenko06810332007-05-21 23:30:54 +00002881#if ENABLE_HUSH_IF
Eric Andersen25f27032001-04-26 23:22:31 +00002882 { "if", RES_IF, FLAG_THEN | FLAG_START },
2883 { "then", RES_THEN, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
2884 { "elif", RES_ELIF, FLAG_THEN },
2885 { "else", RES_ELSE, FLAG_FI },
2886 { "fi", RES_FI, FLAG_END },
Denis Vlasenko06810332007-05-21 23:30:54 +00002887#endif
2888#if ENABLE_HUSH_LOOPS
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002889 { "for", RES_FOR, FLAG_IN | FLAG_START },
Eric Andersen25f27032001-04-26 23:22:31 +00002890 { "while", RES_WHILE, FLAG_DO | FLAG_START },
2891 { "until", RES_UNTIL, FLAG_DO | FLAG_START },
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002892 { "in", RES_IN, FLAG_DO },
Eric Andersen25f27032001-04-26 23:22:31 +00002893 { "do", RES_DO, FLAG_DONE },
2894 { "done", RES_DONE, FLAG_END }
Denis Vlasenko06810332007-05-21 23:30:54 +00002895#endif
Eric Andersen25f27032001-04-26 23:22:31 +00002896 };
Denis Vlasenko7d4c44e2007-04-16 22:34:39 +00002897 enum { NRES = sizeof(reserved_list)/sizeof(reserved_list[0]) };
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00002898 const struct reserved_combo *r;
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00002899
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002900 for (r = reserved_list; r < reserved_list + NRES; r++) {
Denis Vlasenko1a735862007-05-23 00:32:25 +00002901 if (strcmp(dest->data, r->literal) != 0)
2902 continue;
2903 debug_printf("found reserved word %s, code %d\n", r->literal, r->code);
2904 if (r->flag & FLAG_START) {
2905 struct p_context *new;
2906 debug_printf("push stack\n");
Denis Vlasenko06810332007-05-21 23:30:54 +00002907#if ENABLE_HUSH_LOOPS
Denis Vlasenko1a735862007-05-23 00:32:25 +00002908 if (ctx->res_w == RES_IN || ctx->res_w == RES_FOR) {
Denis Vlasenko90e485c2007-05-23 15:22:50 +00002909 syntax("malformed for"); /* example: 'for if' */
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002910 ctx->res_w = RES_SNTX;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002911 b_reset(dest);
Eric Andersenaf44a0e2001-04-27 07:26:12 +00002912 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00002913 }
Denis Vlasenko1a735862007-05-23 00:32:25 +00002914#endif
2915 new = xmalloc(sizeof(*new));
2916 *new = *ctx; /* physical copy */
2917 initialize_context(ctx);
2918 ctx->stack = new;
2919 } else if (ctx->res_w == RES_NONE || !(ctx->old_flag & (1 << r->code))) {
Denis Vlasenko90e485c2007-05-23 15:22:50 +00002920 syntax(NULL);
Denis Vlasenko1a735862007-05-23 00:32:25 +00002921 ctx->res_w = RES_SNTX;
Denis Vlasenkoff131b92007-04-10 15:42:06 +00002922 b_reset(dest);
Eric Andersen25f27032001-04-26 23:22:31 +00002923 return 1;
2924 }
Denis Vlasenko1a735862007-05-23 00:32:25 +00002925 ctx->res_w = r->code;
2926 ctx->old_flag = r->flag;
2927 if (ctx->old_flag & FLAG_END) {
2928 struct p_context *old;
2929 debug_printf("pop stack\n");
2930 done_pipe(ctx, PIPE_SEQ);
2931 old = ctx->stack;
2932 old->child->group = ctx->list_head;
2933 old->child->subshell = 0;
2934 *ctx = *old; /* physical copy */
2935 free(old);
2936 }
2937 b_reset(dest);
2938 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00002939 }
2940 return 0;
2941}
Denis Vlasenko06810332007-05-21 23:30:54 +00002942#else
2943#define reserved_word(dest, ctx) ((int)0)
2944#endif
Eric Andersen25f27032001-04-26 23:22:31 +00002945
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00002946/* Normal return is 0.
Eric Andersen25f27032001-04-26 23:22:31 +00002947 * Syntax or xglob errors return 1. */
2948static int done_word(o_string *dest, struct p_context *ctx)
2949{
Denis Vlasenkobb81c582007-01-30 22:32:09 +00002950 struct child_prog *child = ctx->child;
Eric Andersen25f27032001-04-26 23:22:31 +00002951 glob_t *glob_target;
2952 int gr, flags = 0;
2953
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002954 debug_printf_parse("done_word entered: '%s' %p\n", dest->data, child);
Eric Andersen25f27032001-04-26 23:22:31 +00002955 if (dest->length == 0 && !dest->nonnull) {
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00002956 debug_printf_parse("done_word return 0: true null, ignored\n");
Eric Andersen25f27032001-04-26 23:22:31 +00002957 return 0;
2958 }
2959 if (ctx->pending_redirect) {
2960 glob_target = &ctx->pending_redirect->word;
2961 } else {
2962 if (child->group) {
Denis Vlasenko90e485c2007-05-23 15:22:50 +00002963 syntax(NULL);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00002964 debug_printf_parse("done_word return 1: syntax error, groups and arglists don't mix\n");
2965 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00002966 }
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002967 if (!child->argv && (ctx->parse_type & PARSEFLAG_SEMICOLON)) {
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002968 debug_printf_parse(": checking '%s' for reserved-ness\n", dest->data);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00002969 if (reserved_word(dest, ctx)) {
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002970 debug_printf_parse("done_word return %d\n", (ctx->res_w == RES_SNTX));
2971 return (ctx->res_w == RES_SNTX);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00002972 }
Eric Andersen25f27032001-04-26 23:22:31 +00002973 }
2974 glob_target = &child->glob_result;
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002975 if (child->argv)
2976 flags |= GLOB_APPEND;
Eric Andersen25f27032001-04-26 23:22:31 +00002977 }
2978 gr = xglob(dest, flags, glob_target);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00002979 if (gr != 0) {
2980 debug_printf_parse("done_word return 1: xglob returned %d\n", gr);
2981 return 1;
2982 }
Eric Andersen25f27032001-04-26 23:22:31 +00002983
2984 b_reset(dest);
2985 if (ctx->pending_redirect) {
Denis Vlasenkobb81c582007-01-30 22:32:09 +00002986 ctx->pending_redirect = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00002987 if (glob_target->gl_pathc != 1) {
Manuel Novoa III cad53642003-03-19 09:13:01 +00002988 bb_error_msg("ambiguous redirect");
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00002989 debug_printf_parse("done_word return 1: ambiguous redirect\n");
Eric Andersen25f27032001-04-26 23:22:31 +00002990 return 1;
2991 }
2992 } else {
2993 child->argv = glob_target->gl_pathv;
2994 }
Denis Vlasenko06810332007-05-21 23:30:54 +00002995#if ENABLE_HUSH_LOOPS
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002996 if (ctx->res_w == RES_FOR) {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00002997 done_word(dest, ctx);
2998 done_pipe(ctx, PIPE_SEQ);
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002999 }
Denis Vlasenko06810332007-05-21 23:30:54 +00003000#endif
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003001 debug_printf_parse("done_word return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003002 return 0;
3003}
3004
3005/* The only possible error here is out of memory, in which case
3006 * xmalloc exits. */
3007static int done_command(struct p_context *ctx)
3008{
3009 /* The child is really already in the pipe structure, so
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003010 * advance the pipe counter and make a new, null child. */
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003011 struct pipe *pi = ctx->pipe;
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003012 struct child_prog *child = ctx->child;
Eric Andersen25f27032001-04-26 23:22:31 +00003013
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003014 if (child) {
3015 if (child->group == NULL
3016 && child->argv == NULL
3017 && child->redirects == NULL
3018 ) {
Denis Vlasenkodd4cb2b2007-05-05 15:11:40 +00003019 debug_printf_parse("done_command: skipping null cmd, num_progs=%d\n", pi->num_progs);
3020 return pi->num_progs;
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003021 }
Eric Andersen25f27032001-04-26 23:22:31 +00003022 pi->num_progs++;
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003023 debug_printf_parse("done_command: ++num_progs=%d\n", pi->num_progs);
Eric Andersen25f27032001-04-26 23:22:31 +00003024 } else {
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003025 debug_printf_parse("done_command: initializing, num_progs=%d\n", pi->num_progs);
Eric Andersen25f27032001-04-26 23:22:31 +00003026 }
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003027
3028 /* Only real trickiness here is that the uncommitted
3029 * child structure is not counted in pi->num_progs. */
Eric Andersen25f27032001-04-26 23:22:31 +00003030 pi->progs = xrealloc(pi->progs, sizeof(*pi->progs) * (pi->num_progs+1));
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003031 child = &pi->progs[pi->num_progs];
Eric Andersen25f27032001-04-26 23:22:31 +00003032
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003033 memset(child, 0, sizeof(*child));
3034 /*child->redirects = NULL;*/
3035 /*child->argv = NULL;*/
3036 /*child->is_stopped = 0;*/
3037 /*child->group = NULL;*/
3038 /*child->glob_result.gl_pathv = NULL;*/
3039 child->family = pi;
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003040 //sp: /*child->sp = 0;*/
Denis Vlasenko262d7652007-05-20 21:52:49 +00003041 //pt: child->parse_type = ctx->parse_type;
Eric Andersen25f27032001-04-26 23:22:31 +00003042
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003043 ctx->child = child;
Eric Andersen25f27032001-04-26 23:22:31 +00003044 /* but ctx->pipe and ctx->list_head remain unchanged */
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003045
Denis Vlasenkodd4cb2b2007-05-05 15:11:40 +00003046 return pi->num_progs; /* used only for 0/nonzero check */
Eric Andersen25f27032001-04-26 23:22:31 +00003047}
3048
3049static int done_pipe(struct p_context *ctx, pipe_style type)
3050{
3051 struct pipe *new_p;
Denis Vlasenkodd4cb2b2007-05-05 15:11:40 +00003052 int not_null;
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003053
3054 debug_printf_parse("done_pipe entered, followup %d\n", type);
Denis Vlasenkodd4cb2b2007-05-05 15:11:40 +00003055 not_null = done_command(ctx); /* implicit closure of previous command */
Eric Andersen25f27032001-04-26 23:22:31 +00003056 ctx->pipe->followup = type;
Denis Vlasenko219e88d2007-05-21 10:18:23 +00003057 ctx->pipe->res_word = ctx->res_w;
Denis Vlasenkodd4cb2b2007-05-05 15:11:40 +00003058 /* Without this check, even just <enter> on command line generates
3059 * tree of three NOPs (!). Which is harmless but annoying.
3060 * IOW: it is safe to do it unconditionally. */
3061 if (not_null) {
3062 new_p = new_pipe();
3063 ctx->pipe->next = new_p;
3064 ctx->pipe = new_p;
3065 ctx->child = NULL;
3066 done_command(ctx); /* set up new pipe to accept commands */
3067 }
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003068 debug_printf_parse("done_pipe return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003069 return 0;
3070}
3071
3072/* peek ahead in the in_str to find out if we have a "&n" construct,
3073 * as in "2>&1", that represents duplicating a file descriptor.
3074 * returns either -2 (syntax error), -1 (no &), or the number found.
3075 */
3076static int redirect_dup_num(struct in_str *input)
3077{
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003078 int ch, d = 0, ok = 0;
Eric Andersen25f27032001-04-26 23:22:31 +00003079 ch = b_peek(input);
3080 if (ch != '&') return -1;
3081
3082 b_getch(input); /* get the & */
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003083 ch = b_peek(input);
Eric Andersen83a2ae22001-05-07 17:59:25 +00003084 if (ch == '-') {
3085 b_getch(input);
3086 return -3; /* "-" represents "close me" */
3087 }
3088 while (isdigit(ch)) {
Denis Vlasenko7d4c44e2007-04-16 22:34:39 +00003089 d = d*10 + (ch-'0');
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003090 ok = 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003091 b_getch(input);
Eric Andersen83a2ae22001-05-07 17:59:25 +00003092 ch = b_peek(input);
Eric Andersen25f27032001-04-26 23:22:31 +00003093 }
3094 if (ok) return d;
3095
Manuel Novoa III cad53642003-03-19 09:13:01 +00003096 bb_error_msg("ambiguous redirect");
Eric Andersen25f27032001-04-26 23:22:31 +00003097 return -2;
3098}
3099
3100/* If a redirect is immediately preceded by a number, that number is
3101 * supposed to tell which file descriptor to redirect. This routine
3102 * looks for such preceding numbers. In an ideal world this routine
3103 * needs to handle all the following classes of redirects...
3104 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
3105 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
3106 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
3107 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
3108 * A -1 output from this program means no valid number was found, so the
3109 * caller should use the appropriate default for this redirection.
3110 */
3111static int redirect_opt_num(o_string *o)
3112{
3113 int num;
3114
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003115 if (o->length == 0)
3116 return -1;
3117 for (num = 0; num < o->length; num++) {
3118 if (!isdigit(*(o->data + num))) {
Eric Andersen25f27032001-04-26 23:22:31 +00003119 return -1;
3120 }
3121 }
3122 /* reuse num (and save an int) */
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003123 num = atoi(o->data);
Eric Andersen25f27032001-04-26 23:22:31 +00003124 b_reset(o);
3125 return num;
3126}
3127
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003128#if ENABLE_HUSH_TICK
"Vladimir N. Oleynik"19c37012005-09-22 14:33:15 +00003129static FILE *generate_stream_from_list(struct pipe *head)
Eric Andersen25f27032001-04-26 23:22:31 +00003130{
3131 FILE *pf;
Eric Andersen25f27032001-04-26 23:22:31 +00003132 int pid, channel[2];
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003133 if (pipe(channel) < 0) bb_perror_msg_and_die("pipe");
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00003134#if BB_MMU
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003135 pid = fork();
Eric Andersen72f9a422001-10-28 05:12:20 +00003136#else
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003137 pid = vfork();
Eric Andersen72f9a422001-10-28 05:12:20 +00003138#endif
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003139 if (pid < 0) {
Manuel Novoa III cad53642003-03-19 09:13:01 +00003140 bb_perror_msg_and_die("fork");
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003141 } else if (pid == 0) {
Eric Andersen25f27032001-04-26 23:22:31 +00003142 close(channel[0]);
3143 if (channel[1] != 1) {
Denis Vlasenko7d4c44e2007-04-16 22:34:39 +00003144 dup2(channel[1], 1);
Eric Andersen25f27032001-04-26 23:22:31 +00003145 close(channel[1]);
3146 }
Eric Andersen94ac2442001-05-22 19:05:18 +00003147 _exit(run_list_real(head)); /* leaks memory */
Eric Andersen25f27032001-04-26 23:22:31 +00003148 }
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003149 debug_printf("forked child %d\n", pid);
Eric Andersen25f27032001-04-26 23:22:31 +00003150 close(channel[1]);
Denis Vlasenko5f786c22007-04-20 08:35:45 +00003151 pf = fdopen(channel[0], "r");
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003152 debug_printf("pipe on FILE *%p\n", pf);
Eric Andersen25f27032001-04-26 23:22:31 +00003153 return pf;
3154}
3155
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003156/* Return code is exit status of the process that is run. */
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003157static int process_command_subs(o_string *dest, struct p_context *ctx,
3158 struct in_str *input, const char *subst_end)
Eric Andersen25f27032001-04-26 23:22:31 +00003159{
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00003160 int retcode, ch, eol_cnt;
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003161 o_string result = NULL_O_STRING;
Eric Andersen25f27032001-04-26 23:22:31 +00003162 struct p_context inner;
3163 FILE *p;
3164 struct in_str pipe_str;
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00003165
Eric Andersen25f27032001-04-26 23:22:31 +00003166 initialize_context(&inner);
3167
3168 /* recursion to generate command */
3169 retcode = parse_stream(&result, &inner, input, subst_end);
Denis Vlasenko1a735862007-05-23 00:32:25 +00003170 if (retcode != 0)
3171 return retcode; /* syntax error or EOF */
Eric Andersen25f27032001-04-26 23:22:31 +00003172 done_word(&result, &inner);
3173 done_pipe(&inner, PIPE_SEQ);
3174 b_free(&result);
3175
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003176 p = generate_stream_from_list(inner.list_head);
3177 if (p == NULL) return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003178 mark_open(fileno(p));
3179 setup_file_in_str(&pipe_str, p);
3180
3181 /* now send results of command back into original context */
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00003182 eol_cnt = 0;
3183 while ((ch = b_getch(&pipe_str)) != EOF) {
3184 if (ch == '\n') {
3185 eol_cnt++;
3186 continue;
3187 }
3188 while (eol_cnt) {
3189 b_addqchr(dest, '\n', dest->quote);
3190 eol_cnt--;
3191 }
3192 b_addqchr(dest, ch, dest->quote);
Eric Andersen25f27032001-04-26 23:22:31 +00003193 }
3194
3195 debug_printf("done reading from pipe, pclose()ing\n");
3196 /* This is the step that wait()s for the child. Should be pretty
3197 * safe, since we just read an EOF from its stdout. We could try
Denis Vlasenko262d7652007-05-20 21:52:49 +00003198 * to do better, by using wait(), and keeping track of background jobs
Eric Andersen25f27032001-04-26 23:22:31 +00003199 * at the same time. That would be a lot of work, and contrary
3200 * to the KISS philosophy of this program. */
3201 mark_closed(fileno(p));
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003202 retcode = pclose(p);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003203 free_pipe_list(inner.list_head, 0);
3204 debug_printf("pclosed, retcode=%d\n", retcode);
Eric Andersen25f27032001-04-26 23:22:31 +00003205 return retcode;
3206}
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003207#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003208
3209static int parse_group(o_string *dest, struct p_context *ctx,
3210 struct in_str *input, int ch)
3211{
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003212 int rcode;
3213 const char *endch = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00003214 struct p_context sub;
3215 struct child_prog *child = ctx->child;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003216
3217 debug_printf_parse("parse_group entered\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003218 if (child->argv) {
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003219 syntax(NULL);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003220 debug_printf_parse("parse_group return 1: syntax error, groups and arglists don't mix\n");
3221 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003222 }
3223 initialize_context(&sub);
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003224 endch = "}";
3225 if (ch == '(') {
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003226 endch = ")";
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003227 child->subshell = 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003228 }
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003229 rcode = parse_stream(dest, &sub, input, endch);
Denis Vlasenko5a1437d2007-05-24 13:22:47 +00003230//vda: err chk?
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003231 done_word(dest, &sub); /* finish off the final word in the subcontext */
Eric Andersen25f27032001-04-26 23:22:31 +00003232 done_pipe(&sub, PIPE_SEQ); /* and the final command there, too */
3233 child->group = sub.list_head;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003234
3235 debug_printf_parse("parse_group return %d\n", rcode);
Eric Andersen25f27032001-04-26 23:22:31 +00003236 return rcode;
3237 /* child remains "open", available for possible redirects */
3238}
3239
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003240/* Basically useful version until someone wants to get fancier,
Eric Andersen25f27032001-04-26 23:22:31 +00003241 * see the bash man page under "Parameter Expansion" */
Denis Vlasenko15d78fb2007-01-30 22:28:21 +00003242static const char *lookup_param(const char *src)
Eric Andersen25f27032001-04-26 23:22:31 +00003243{
Denis Vlasenkod76c0492007-05-25 02:16:25 +00003244 struct variable *var = get_local_var(src);
3245 if (var)
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00003246 return strchr(var->varstr, '=') + 1;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00003247 return NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00003248}
3249
3250/* return code: 0 for OK, 1 for syntax error */
3251static int handle_dollar(o_string *dest, struct p_context *ctx, struct in_str *input)
3252{
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003253 int ch = b_peek(input); /* first character after the $ */
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00003254 unsigned char quote_mask = dest->quote ? 0x80 : 0;
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003255
3256 debug_printf_parse("handle_dollar entered: ch='%c'\n", ch);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00003257 if (isalpha(ch)) {
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003258 b_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003259 //sp: ctx->child->sp++;
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003260 while (1) {
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003261 debug_printf_parse(": '%c'\n", ch);
Eric Andersen25f27032001-04-26 23:22:31 +00003262 b_getch(input);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00003263 b_addchr(dest, ch | quote_mask);
3264 quote_mask = 0;
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003265 ch = b_peek(input);
3266 if (!isalnum(ch) && ch != '_')
3267 break;
Eric Andersen25f27032001-04-26 23:22:31 +00003268 }
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003269 b_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00003270 } else if (isdigit(ch)) {
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003271 make_one_char_var:
3272 b_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003273 //sp: ctx->child->sp++;
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003274 debug_printf_parse(": '%c'\n", ch);
3275 b_getch(input);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00003276 b_addchr(dest, ch | quote_mask);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003277 b_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00003278 } else switch (ch) {
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003279 case '$': /* pid */
3280 case '!': /* last bg pid */
3281 case '?': /* last exit code */
3282 case '#': /* number of args */
3283 case '*': /* args */
3284 case '@': /* args */
3285 goto make_one_char_var;
Eric Andersen25f27032001-04-26 23:22:31 +00003286 case '{':
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003287 b_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003288 //sp: ctx->child->sp++;
Eric Andersen25f27032001-04-26 23:22:31 +00003289 b_getch(input);
3290 /* XXX maybe someone will try to escape the '}' */
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003291 while (1) {
3292 ch = b_getch(input);
Denis Vlasenkob0550012007-05-24 12:18:16 +00003293 if (ch == '}')
3294 break;
3295 if (!isalnum(ch) && ch != '_') {
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003296 syntax("unterminated ${name}");
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003297 debug_printf_parse("handle_dollar return 1: unterminated ${name}\n");
3298 return 1;
3299 }
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003300 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00003301 b_addchr(dest, ch | quote_mask);
3302 quote_mask = 0;
Eric Andersen25f27032001-04-26 23:22:31 +00003303 }
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003304 b_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00003305 break;
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003306#if ENABLE_HUSH_TICK
Eric Andersen25f27032001-04-26 23:22:31 +00003307 case '(':
Matt Kraai9f8caf12001-05-02 16:26:12 +00003308 b_getch(input);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003309 process_command_subs(dest, ctx, input, ")");
Eric Andersen25f27032001-04-26 23:22:31 +00003310 break;
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003311#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003312 case '-':
3313 case '_':
3314 /* still unhandled, but should be eventually */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003315 bb_error_msg("unhandled syntax: $%c", ch);
Eric Andersen25f27032001-04-26 23:22:31 +00003316 return 1;
3317 break;
3318 default:
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003319 b_addqchr(dest, '$', dest->quote);
Eric Andersen25f27032001-04-26 23:22:31 +00003320 }
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003321 debug_printf_parse("handle_dollar return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003322 return 0;
3323}
3324
Eric Andersen25f27032001-04-26 23:22:31 +00003325/* return code is 0 for normal exit, 1 for syntax error */
Denis Vlasenko5f786c22007-04-20 08:35:45 +00003326static int parse_stream(o_string *dest, struct p_context *ctx,
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003327 struct in_str *input, const char *end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00003328{
"Vladimir N. Oleynik"4ccd2b42006-01-31 09:27:48 +00003329 int ch, m;
Eric Andersen25f27032001-04-26 23:22:31 +00003330 int redir_fd;
3331 redir_type redir_style;
3332 int next;
3333
3334 /* Only double-quote state is handled in the state variable dest->quote.
3335 * A single-quote triggers a bypass of the main loop until its mate is
3336 * found. When recursing, quote state is passed in via dest->quote. */
3337
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003338 debug_printf_parse("parse_stream entered, end_trigger='%s'\n", end_trigger);
3339
Denis Vlasenko1a735862007-05-23 00:32:25 +00003340 while (1) {
Denis Vlasenko1a735862007-05-23 00:32:25 +00003341 m = CHAR_IFS;
3342 next = '\0';
Denis Vlasenko170435c2007-05-23 13:01:10 +00003343 ch = b_getch(input);
Denis Vlasenko1a735862007-05-23 00:32:25 +00003344 if (ch != EOF) {
3345 m = charmap[ch];
3346 if (ch != '\n')
3347 next = b_peek(input);
3348 }
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003349 debug_printf_parse(": ch=%c (%d) m=%d quote=%d\n",
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003350 ch, ch, m, dest->quote);
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003351 if (m == CHAR_ORDINARY
3352 || (m != CHAR_SPECIAL && dest->quote)
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003353 ) {
Denis Vlasenko170435c2007-05-23 13:01:10 +00003354 if (ch == EOF) {
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003355 syntax("unterminated \"");
Denis Vlasenko170435c2007-05-23 13:01:10 +00003356 debug_printf_parse("parse_stream return 1: unterminated \"\n");
3357 return 1;
3358 }
Eric Andersen25f27032001-04-26 23:22:31 +00003359 b_addqchr(dest, ch, dest->quote);
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003360 continue;
3361 }
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003362 if (m == CHAR_IFS) {
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003363 if (done_word(dest, ctx)) {
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003364 debug_printf_parse("parse_stream return 1: done_word!=0\n");
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003365 return 1;
Eric Andersenaac75e52001-04-30 18:18:45 +00003366 }
Denis Vlasenko1a735862007-05-23 00:32:25 +00003367 if (ch == EOF)
3368 break;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003369 /* If we aren't performing a substitution, treat
3370 * a newline as a command separator.
3371 * [why we don't handle it exactly like ';'? --vda] */
3372 if (end_trigger && ch == '\n') {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003373 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003374 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003375 }
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003376 if ((end_trigger && strchr(end_trigger, ch))
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003377 && !dest->quote && ctx->res_w == RES_NONE
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003378 ) {
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003379 debug_printf_parse("parse_stream return 0: end_trigger char found\n");
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003380 return 0;
3381 }
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003382 if (m == CHAR_IFS)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003383 continue;
3384 switch (ch) {
Eric Andersen25f27032001-04-26 23:22:31 +00003385 case '#':
3386 if (dest->length == 0 && !dest->quote) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003387 while (1) {
3388 ch = b_peek(input);
3389 if (ch == EOF || ch == '\n')
3390 break;
3391 b_getch(input);
3392 }
Eric Andersen25f27032001-04-26 23:22:31 +00003393 } else {
3394 b_addqchr(dest, ch, dest->quote);
3395 }
3396 break;
3397 case '\\':
3398 if (next == EOF) {
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003399 syntax("\\<eof>");
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003400 debug_printf_parse("parse_stream return 1: \\<eof>\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003401 return 1;
3402 }
3403 b_addqchr(dest, '\\', dest->quote);
3404 b_addqchr(dest, b_getch(input), dest->quote);
3405 break;
3406 case '$':
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003407 if (handle_dollar(dest, ctx, input) != 0) {
3408 debug_printf_parse("parse_stream return 1: handle_dollar returned non-0\n");
3409 return 1;
3410 }
Eric Andersen25f27032001-04-26 23:22:31 +00003411 break;
3412 case '\'':
3413 dest->nonnull = 1;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003414 while (1) {
3415 ch = b_getch(input);
3416 if (ch == EOF || ch == '\'')
3417 break;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003418 b_addchr(dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00003419 }
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003420 if (ch == EOF) {
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003421 syntax("unterminated '");
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003422 debug_printf_parse("parse_stream return 1: unterminated '\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003423 return 1;
3424 }
3425 break;
3426 case '"':
3427 dest->nonnull = 1;
3428 dest->quote = !dest->quote;
3429 break;
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003430#if ENABLE_HUSH_TICK
Eric Andersen25f27032001-04-26 23:22:31 +00003431 case '`':
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003432 process_command_subs(dest, ctx, input, "`");
Eric Andersen25f27032001-04-26 23:22:31 +00003433 break;
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003434#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003435 case '>':
3436 redir_fd = redirect_opt_num(dest);
3437 done_word(dest, ctx);
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003438 redir_style = REDIRECT_OVERWRITE;
Eric Andersen25f27032001-04-26 23:22:31 +00003439 if (next == '>') {
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003440 redir_style = REDIRECT_APPEND;
Eric Andersen25f27032001-04-26 23:22:31 +00003441 b_getch(input);
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003442 }
3443#if 0
3444 else if (next == '(') {
3445 syntax(">(process) not supported");
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003446 debug_printf_parse("parse_stream return 1: >(process) not supported\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003447 return 1;
3448 }
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003449#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003450 setup_redirect(ctx, redir_fd, redir_style, input);
3451 break;
3452 case '<':
3453 redir_fd = redirect_opt_num(dest);
3454 done_word(dest, ctx);
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003455 redir_style = REDIRECT_INPUT;
Eric Andersen25f27032001-04-26 23:22:31 +00003456 if (next == '<') {
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003457 redir_style = REDIRECT_HEREIS;
Eric Andersen25f27032001-04-26 23:22:31 +00003458 b_getch(input);
3459 } else if (next == '>') {
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003460 redir_style = REDIRECT_IO;
Eric Andersen25f27032001-04-26 23:22:31 +00003461 b_getch(input);
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003462 }
3463#if 0
3464 else if (next == '(') {
3465 syntax("<(process) not supported");
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003466 debug_printf_parse("parse_stream return 1: <(process) not supported\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003467 return 1;
3468 }
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003469#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003470 setup_redirect(ctx, redir_fd, redir_style, input);
3471 break;
3472 case ';':
3473 done_word(dest, ctx);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003474 done_pipe(ctx, PIPE_SEQ);
Eric Andersen25f27032001-04-26 23:22:31 +00003475 break;
3476 case '&':
3477 done_word(dest, ctx);
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003478 if (next == '&') {
Eric Andersen25f27032001-04-26 23:22:31 +00003479 b_getch(input);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003480 done_pipe(ctx, PIPE_AND);
Eric Andersen25f27032001-04-26 23:22:31 +00003481 } else {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003482 done_pipe(ctx, PIPE_BG);
Eric Andersen25f27032001-04-26 23:22:31 +00003483 }
3484 break;
3485 case '|':
3486 done_word(dest, ctx);
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003487 if (next == '|') {
Eric Andersen25f27032001-04-26 23:22:31 +00003488 b_getch(input);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003489 done_pipe(ctx, PIPE_OR);
Eric Andersen25f27032001-04-26 23:22:31 +00003490 } else {
3491 /* we could pick up a file descriptor choice here
3492 * with redirect_opt_num(), but bash doesn't do it.
3493 * "echo foo 2| cat" yields "foo 2". */
3494 done_command(ctx);
3495 }
3496 break;
3497 case '(':
3498 case '{':
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003499 if (parse_group(dest, ctx, input, ch) != 0) {
3500 debug_printf_parse("parse_stream return 1: parse_group returned non-0\n");
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003501 return 1;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003502 }
Eric Andersen25f27032001-04-26 23:22:31 +00003503 break;
3504 case ')':
3505 case '}':
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003506 syntax("unexpected }"); /* Proper use of this character is caught by end_trigger */
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003507 debug_printf_parse("parse_stream return 1: unexpected '}'\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003508 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003509 default:
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003510 if (ENABLE_HUSH_DEBUG)
3511 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
Eric Andersen25f27032001-04-26 23:22:31 +00003512 }
3513 }
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003514 /* Complain if quote? No, maybe we just finished a command substitution
Eric Andersen25f27032001-04-26 23:22:31 +00003515 * that was quoted. Example:
Eric Andersenc7bda1c2004-03-15 08:29:22 +00003516 * $ echo "`cat foo` plus more"
Eric Andersen25f27032001-04-26 23:22:31 +00003517 * and we just got the EOF generated by the subshell that ran "cat foo"
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003518 * The only real complaint is if we got an EOF when end_trigger != NULL,
Eric Andersen25f27032001-04-26 23:22:31 +00003519 * that is, we were really supposed to get end_trigger, and never got
3520 * one before the EOF. Can't use the standard "syntax error" return code,
3521 * so that parse_stream_outer can distinguish the EOF and exit smoothly. */
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003522 debug_printf_parse("parse_stream return %d\n", -(end_trigger != NULL));
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003523 if (end_trigger)
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00003524 return -1;
Eric Andersen25f27032001-04-26 23:22:31 +00003525 return 0;
3526}
3527
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003528static void set_in_charmap(const char *set, int code)
Eric Andersen25f27032001-04-26 23:22:31 +00003529{
Denis Vlasenkof5294e12007-04-14 10:09:57 +00003530 while (*set)
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003531 charmap[(unsigned char)*set++] = code;
Eric Andersen25f27032001-04-26 23:22:31 +00003532}
3533
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003534static void update_charmap(void)
Eric Andersen25f27032001-04-26 23:22:31 +00003535{
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003536 /* char *ifs and char charmap[256] are both globals. */
Eric Andersen25f27032001-04-26 23:22:31 +00003537 ifs = getenv("IFS");
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003538 if (ifs == NULL)
3539 ifs = " \t\n";
Eric Andersen25f27032001-04-26 23:22:31 +00003540 /* Precompute a list of 'flow through' behavior so it can be treated
3541 * quickly up front. Computation is necessary because of IFS.
3542 * Special case handling of IFS == " \t\n" is not implemented.
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003543 * The charmap[] array only really needs two bits each,
3544 * and on most machines that would be faster (reduced L1 cache use).
Eric Andersen25f27032001-04-26 23:22:31 +00003545 */
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003546 memset(charmap, CHAR_ORDINARY, sizeof(charmap));
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003547#if ENABLE_HUSH_TICK
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003548 set_in_charmap("\\$\"`", CHAR_SPECIAL);
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003549#else
3550 set_in_charmap("\\$\"", CHAR_SPECIAL);
3551#endif
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003552 set_in_charmap("<>;&|(){}#'", CHAR_ORDINARY_IF_QUOTED);
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003553 set_in_charmap(ifs, CHAR_IFS); /* are ordinary if quoted */
Eric Andersen25f27032001-04-26 23:22:31 +00003554}
3555
Eric Andersenaff114c2004-04-14 17:51:38 +00003556/* most recursion does not come through here, the exception is
Denis Vlasenko170435c2007-05-23 13:01:10 +00003557 * from builtin_source() and builtin_eval() */
3558static int parse_and_run_stream(struct in_str *inp, int parse_flag)
Eric Andersen25f27032001-04-26 23:22:31 +00003559{
Eric Andersen25f27032001-04-26 23:22:31 +00003560 struct p_context ctx;
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003561 o_string temp = NULL_O_STRING;
Eric Andersen25f27032001-04-26 23:22:31 +00003562 int rcode;
3563 do {
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003564 ctx.parse_type = parse_flag;
Eric Andersen25f27032001-04-26 23:22:31 +00003565 initialize_context(&ctx);
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003566 update_charmap();
Denis Vlasenko219e88d2007-05-21 10:18:23 +00003567 if (!(parse_flag & PARSEFLAG_SEMICOLON) || (parse_flag & PARSEFLAG_REPARSING))
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003568 set_in_charmap(";$&|", CHAR_ORDINARY);
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003569#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko5a1437d2007-05-24 13:22:47 +00003570 inp->promptmode = 0; /* PS1 */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003571#endif
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003572 /* We will stop & execute after each ';' or '\n'.
3573 * Example: "sleep 9999; echo TEST" + ctrl-C:
3574 * TEST should be printed */
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003575 rcode = parse_stream(&temp, &ctx, inp, ";\n");
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003576 if (rcode != 1 && ctx.old_flag != 0) {
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003577 syntax(NULL);
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003578 }
3579 if (rcode != 1 && ctx.old_flag == 0) {
3580 done_word(&temp, &ctx);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003581 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko400c5b62007-05-04 13:07:27 +00003582 debug_print_tree(ctx.list_head, 0);
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003583 debug_printf_exec("parse_stream_outer: run_list\n");
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003584 run_list(ctx.list_head);
3585 } else {
3586 if (ctx.old_flag != 0) {
3587 free(ctx.stack);
3588 b_reset(&temp);
Eric Andersenc7bda1c2004-03-15 08:29:22 +00003589 }
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003590 temp.nonnull = 0;
3591 temp.quote = 0;
3592 inp->p = NULL;
Denis Vlasenko2f1bb362007-04-21 10:01:14 +00003593 free_pipe_list(ctx.list_head, 0);
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003594 }
Eric Andersena813afc2001-05-24 16:19:36 +00003595 b_free(&temp);
Denis Vlasenko219e88d2007-05-21 10:18:23 +00003596 } while (rcode != -1 && !(parse_flag & PARSEFLAG_EXIT_FROM_LOOP)); /* loop on syntax errors, return on EOF */
Eric Andersen25f27032001-04-26 23:22:31 +00003597 return 0;
3598}
3599
Denis Vlasenko170435c2007-05-23 13:01:10 +00003600static int parse_and_run_string(const char *s, int parse_flag)
Eric Andersen25f27032001-04-26 23:22:31 +00003601{
3602 struct in_str input;
3603 setup_string_in_str(&input, s);
Denis Vlasenko170435c2007-05-23 13:01:10 +00003604 return parse_and_run_stream(&input, parse_flag);
Eric Andersen25f27032001-04-26 23:22:31 +00003605}
3606
Denis Vlasenko170435c2007-05-23 13:01:10 +00003607static int parse_and_run_file(FILE *f)
Eric Andersen25f27032001-04-26 23:22:31 +00003608{
3609 int rcode;
3610 struct in_str input;
3611 setup_file_in_str(&input, f);
Denis Vlasenko170435c2007-05-23 13:01:10 +00003612 rcode = parse_and_run_stream(&input, PARSEFLAG_SEMICOLON);
Eric Andersen25f27032001-04-26 23:22:31 +00003613 return rcode;
3614}
3615
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003616#if ENABLE_HUSH_JOB
Eric Andersen6c947d22001-06-25 22:24:38 +00003617/* Make sure we have a controlling tty. If we get started under a job
3618 * aware app (like bash for example), make sure we are now in charge so
3619 * we don't fight over who gets the foreground */
Eric Anderseneaecbf32001-10-31 10:41:31 +00003620static void setup_job_control(void)
Eric Andersen52a97ca2001-06-22 06:49:26 +00003621{
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003622 pid_t shell_pgrp;
3623
Denis Vlasenkoa6a17852007-04-28 16:42:11 +00003624 saved_task_pgrp = shell_pgrp = getpgrp();
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003625 debug_printf_jobs("saved_task_pgrp=%d\n", saved_task_pgrp);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003626 fcntl(interactive_fd, F_SETFD, FD_CLOEXEC);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003627
Denis Vlasenkoa6a17852007-04-28 16:42:11 +00003628 /* If we were ran as 'hush &',
3629 * sleep until we are in the foreground. */
3630 while (tcgetpgrp(interactive_fd) != shell_pgrp) {
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00003631 /* Send TTIN to ourself (should stop us) */
Denis Vlasenkoff131b92007-04-10 15:42:06 +00003632 kill(- shell_pgrp, SIGTTIN);
Denis Vlasenkoa6a17852007-04-28 16:42:11 +00003633 shell_pgrp = getpgrp();
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003634 }
Eric Andersen52a97ca2001-06-22 06:49:26 +00003635
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003636 /* Ignore job-control and misc signals. */
3637 set_jobctrl_sighandler(SIG_IGN);
3638 set_misc_sighandler(SIG_IGN);
3639//huh? signal(SIGCHLD, SIG_IGN);
3640
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003641 /* We _must_ restore tty pgrp on fatal signals */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003642 set_fatal_sighandler(sigexit);
Eric Andersen6c947d22001-06-25 22:24:38 +00003643
3644 /* Put ourselves in our own process group. */
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00003645 setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
Eric Andersen6c947d22001-06-25 22:24:38 +00003646 /* Grab control of the terminal. */
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00003647 tcsetpgrp(interactive_fd, getpid());
Eric Andersen6c947d22001-06-25 22:24:38 +00003648}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00003649#endif
Eric Andersenada18ff2001-05-21 16:18:22 +00003650
Denis Vlasenko06af2162007-02-03 17:28:39 +00003651int hush_main(int argc, char **argv);
Matt Kraai2d91deb2001-08-01 17:21:35 +00003652int hush_main(int argc, char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00003653{
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00003654 static const char version_str[] = "HUSH_VERSION="HUSH_VER_STR;
3655 static const struct variable const_shell_ver = {
3656 .next = NULL,
3657 .varstr = (char*)version_str,
3658 .max_len = 1, /* 0 can provoke free(name) */
3659 .flg_export = 1,
3660 .flg_read_only = 1,
3661 };
3662
Eric Andersen25f27032001-04-26 23:22:31 +00003663 int opt;
3664 FILE *input;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003665 char **e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00003666 struct variable *cur_var;
Eric Andersenbc604a22001-05-16 05:24:03 +00003667
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00003668 PTR_TO_GLOBALS = xzalloc(sizeof(G));
Denis Vlasenkod76c0492007-05-25 02:16:25 +00003669
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00003670 /* Deal with HUSH_VERSION */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00003671 shell_ver = const_shell_ver; /* copying struct here */
Denis Vlasenkod76c0492007-05-25 02:16:25 +00003672 top_var = &shell_ver;
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00003673 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
3674 /* Initialize our shell local variables with the values
Denis Vlasenkod76c0492007-05-25 02:16:25 +00003675 * currently living in the environment */
Denis Vlasenkod76c0492007-05-25 02:16:25 +00003676 cur_var = top_var;
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00003677 e = environ;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00003678 if (e) while (*e) {
3679 char *value = strchr(*e, '=');
3680 if (value) { /* paranoia */
3681 cur_var->next = xzalloc(sizeof(*cur_var));
3682 cur_var = cur_var->next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00003683 cur_var->varstr = *e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00003684 cur_var->max_len = strlen(*e);
3685 cur_var->flg_export = 1;
3686 }
3687 e++;
3688 }
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00003689 putenv((char *)version_str); /* reinstate HUSH_VERSION */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00003690
Denis Vlasenko38f63192007-01-22 09:03:07 +00003691#if ENABLE_FEATURE_EDITING
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00003692 line_input_state = new_line_input_t(FOR_SHELL);
3693#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003694 /* XXX what should these be while sourcing /etc/profile? */
3695 global_argc = argc;
3696 global_argv = argv;
Eric Andersen94ac2442001-05-22 19:05:18 +00003697 /* Initialize some more globals to non-zero values */
3698 set_cwd();
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003699#if ENABLE_HUSH_INTERACTIVE
3700#if ENABLE_FEATURE_EDITING
3701 cmdedit_set_initial_prompt();
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003702#endif
Eric Andersen94ac2442001-05-22 19:05:18 +00003703 PS2 = "> ";
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003704#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00003705
Denis Vlasenkod76c0492007-05-25 02:16:25 +00003706 if (EXIT_SUCCESS) /* otherwise is already done */
3707 last_return_code = EXIT_SUCCESS;
Eric Andersen25f27032001-04-26 23:22:31 +00003708
3709 if (argv[0] && argv[0][0] == '-') {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003710 debug_printf("sourcing /etc/profile\n");
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00003711 input = fopen("/etc/profile", "r");
3712 if (input != NULL) {
Eric Andersena90f20b2001-06-26 23:00:21 +00003713 mark_open(fileno(input));
Denis Vlasenko170435c2007-05-23 13:01:10 +00003714 parse_and_run_file(input);
Eric Andersena90f20b2001-06-26 23:00:21 +00003715 mark_closed(fileno(input));
3716 fclose(input);
3717 }
Eric Andersen25f27032001-04-26 23:22:31 +00003718 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003719 input = stdin;
Eric Andersenc7bda1c2004-03-15 08:29:22 +00003720
Eric Andersen25f27032001-04-26 23:22:31 +00003721 while ((opt = getopt(argc, argv, "c:xif")) > 0) {
3722 switch (opt) {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003723 case 'c':
Denis Vlasenko5f786c22007-04-20 08:35:45 +00003724 global_argv = argv + optind;
3725 global_argc = argc - optind;
Denis Vlasenko170435c2007-05-23 13:01:10 +00003726 opt = parse_and_run_string(optarg, PARSEFLAG_SEMICOLON);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003727 goto final_return;
3728 case 'i':
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003729 /* Well, we cannot just declare interactiveness,
3730 * we have to have some stuff (ctty, etc) */
3731 /* interactive_fd++; */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003732 break;
3733 case 'f':
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00003734 fake_mode = 1;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003735 break;
3736 default:
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00003737#ifndef BB_VER
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003738 fprintf(stderr, "Usage: sh [FILE]...\n"
3739 " or: sh -c command [args]...\n\n");
3740 exit(EXIT_FAILURE);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00003741#else
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003742 bb_show_usage();
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00003743#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003744 }
3745 }
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003746#if ENABLE_HUSH_JOB
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003747 /* A shell is interactive if the '-i' flag was given, or if all of
Eric Andersen25f27032001-04-26 23:22:31 +00003748 * the following conditions are met:
Denis Vlasenko55b2de72007-04-18 17:21:28 +00003749 * no -c command
Eric Andersen25f27032001-04-26 23:22:31 +00003750 * no arguments remaining or the -s flag given
3751 * standard input is a terminal
3752 * standard output is a terminal
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003753 * Refer to Posix.2, the description of the 'sh' utility. */
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003754 if (argv[optind] == NULL && input == stdin
3755 && isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)
3756 ) {
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003757 saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
3758 debug_printf("saved_tty_pgrp=%d\n", saved_tty_pgrp);
3759 if (saved_tty_pgrp >= 0) {
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003760 /* try to dup to high fd#, >= 255 */
3761 interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
3762 if (interactive_fd < 0) {
3763 /* try to dup to any fd */
3764 interactive_fd = dup(STDIN_FILENO);
3765 if (interactive_fd < 0)
3766 /* give up */
3767 interactive_fd = 0;
3768 }
Denis Vlasenko2f1bb362007-04-21 10:01:14 +00003769 // TODO: track & disallow any attempts of user
3770 // to (inadvertently) close/redirect it
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003771 }
Eric Andersen25f27032001-04-26 23:22:31 +00003772 }
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003773 debug_printf("interactive_fd=%d\n", interactive_fd);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003774 if (interactive_fd) {
Eric Andersen25f27032001-04-26 23:22:31 +00003775 /* Looks like they want an interactive shell */
Eric Andersen52a97ca2001-06-22 06:49:26 +00003776 setup_job_control();
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003777 /* Make xfuncs do cleanup on exit */
3778 die_sleep = -1; /* flag */
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003779// FIXME: should we reset die_sleep = 0 whereever we fork?
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003780 if (setjmp(die_jmp)) {
3781 /* xfunc has failed! die die die */
3782 hush_exit(xfunc_error_retval);
3783 }
Denis Vlasenko2f1bb362007-04-21 10:01:14 +00003784#if !ENABLE_FEATURE_SH_EXTRA_QUIET
Denis Vlasenkoef36ead2007-05-02 15:34:47 +00003785 printf("\n\n%s hush - the humble shell v"HUSH_VER_STR"\n", BB_BANNER);
Denis Vlasenko2f1bb362007-04-21 10:01:14 +00003786 printf("Enter 'help' for a list of built-in commands.\n\n");
3787#endif
Eric Andersenada18ff2001-05-21 16:18:22 +00003788 }
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003789#elif ENABLE_HUSH_INTERACTIVE
3790/* no job control compiled, only prompt/line editing */
3791 if (argv[optind] == NULL && input == stdin
3792 && isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)
3793 ) {
3794 interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
3795 if (interactive_fd < 0) {
3796 /* try to dup to any fd */
3797 interactive_fd = dup(STDIN_FILENO);
3798 if (interactive_fd < 0)
3799 /* give up */
3800 interactive_fd = 0;
3801 }
3802 }
3803
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00003804#endif
Eric Andersenc7bda1c2004-03-15 08:29:22 +00003805
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003806 if (argv[optind] == NULL) {
Denis Vlasenko170435c2007-05-23 13:01:10 +00003807 opt = parse_and_run_file(stdin);
Eric Andersene67c3ce2001-05-02 02:09:36 +00003808 goto final_return;
Eric Andersen25f27032001-04-26 23:22:31 +00003809 }
Eric Andersen25f27032001-04-26 23:22:31 +00003810
3811 debug_printf("\nrunning script '%s'\n", argv[optind]);
Denis Vlasenko4c978632007-02-03 03:31:13 +00003812 global_argv = argv + optind;
3813 global_argc = argc - optind;
Rob Landleyd921b2e2006-08-03 15:41:12 +00003814 input = xfopen(argv[optind], "r");
Denis Vlasenko170435c2007-05-23 13:01:10 +00003815 opt = parse_and_run_file(input);
Eric Andersen25f27032001-04-26 23:22:31 +00003816
Denis Vlasenkod76c0492007-05-25 02:16:25 +00003817 final_return:
3818
Denis Vlasenko38f63192007-01-22 09:03:07 +00003819#if ENABLE_FEATURE_CLEAN_UP
Eric Andersenaeb44c42001-05-22 20:29:00 +00003820 fclose(input);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003821 if (cwd != bb_msg_unknown)
Eric Andersenaeb44c42001-05-22 20:29:00 +00003822 free((char*)cwd);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00003823 cur_var = top_var->next;
3824 while (cur_var) {
3825 struct variable *tmp = cur_var;
3826 if (!cur_var->max_len)
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00003827 free(cur_var->varstr);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00003828 cur_var = cur_var->next;
3829 free(tmp);
Eric Andersenaeb44c42001-05-22 20:29:00 +00003830 }
Eric Andersen25f27032001-04-26 23:22:31 +00003831#endif
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003832 hush_exit(opt ? opt : last_return_code);
Eric Andersen25f27032001-04-26 23:22:31 +00003833}