blob: a76327721a51eb1542d53643c5c0b85b3fdf9cd9 [file] [log] [blame]
Eric Andersen25f27032001-04-26 23:22:31 +00001/* vi: set sw=4 ts=4: */
2/*
3 * sh.c -- a prototype Bourne shell grammar parser
4 * Intended to follow the original Thompson and Ritchie
5 * "small and simple is beautiful" philosophy, which
6 * incidentally is a good match to today's BusyBox.
7 *
8 * Copyright (C) 2000,2001 Larry Doolittle <larry@doolittle.boa.org>
9 *
10 * Credits:
11 * The parser routines proper are all original material, first
Eric Andersencb81e642003-07-14 21:21:08 +000012 * written Dec 2000 and Jan 2001 by Larry Doolittle. The
13 * execution engine, the builtins, and much of the underlying
14 * support has been adapted from busybox-0.49pre's lash, which is
Eric Andersenc7bda1c2004-03-15 08:29:22 +000015 * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
Eric Andersencb81e642003-07-14 21:21:08 +000016 * written by Erik Andersen <andersen@codepoet.org>. That, in turn,
17 * is based in part on ladsh.c, by Michael K. Johnson and Erik W.
18 * Troan, which they placed in the public domain. I don't know
19 * how much of the Johnson/Troan code has survived the repeated
20 * rewrites.
21 *
Eric Andersen25f27032001-04-26 23:22:31 +000022 * Other credits:
Eric Andersen25f27032001-04-26 23:22:31 +000023 * b_addchr() derived from similar w_addchar function in glibc-2.2
24 * setup_redirect(), redirect_opt_num(), and big chunks of main()
Denis Vlasenko55b2de72007-04-18 17:21:28 +000025 * and many builtins derived from contributions by Erik Andersen
Eric Andersen25f27032001-04-26 23:22:31 +000026 * miscellaneous bugfixes from Matt Kraai
27 *
28 * There are two big (and related) architecture differences between
29 * this parser and the lash parser. One is that this version is
30 * actually designed from the ground up to understand nearly all
31 * of the Bourne grammar. The second, consequential change is that
32 * the parser and input reader have been turned inside out. Now,
33 * the parser is in control, and asks for input as needed. The old
34 * way had the input reader in control, and it asked for parsing to
35 * take place as needed. The new way makes it much easier to properly
36 * handle the recursion implicit in the various substitutions, especially
37 * across continuation lines.
38 *
39 * Bash grammar not implemented: (how many of these were in original sh?)
Eric Andersen25f27032001-04-26 23:22:31 +000040 * $_
41 * ! negation operator for pipes
42 * &> and >& redirection of stdout+stderr
43 * Brace Expansion
44 * Tilde Expansion
45 * fancy forms of Parameter Expansion
Eric Andersen78a7c992001-05-15 16:30:25 +000046 * aliases
Eric Andersen25f27032001-04-26 23:22:31 +000047 * Arithmetic Expansion
48 * <(list) and >(list) Process Substitution
Eric Andersen83a2ae22001-05-07 17:59:25 +000049 * reserved words: case, esac, select, function
Eric Andersen25f27032001-04-26 23:22:31 +000050 * Here Documents ( << word )
51 * Functions
52 * Major bugs:
Denis Vlasenkob81b3df2007-04-28 16:48:04 +000053 * job handling woefully incomplete and buggy (improved --vda)
Eric Andersen25f27032001-04-26 23:22:31 +000054 * reserved word execution woefully incomplete and buggy
Eric Andersen25f27032001-04-26 23:22:31 +000055 * to-do:
Eric Andersen83a2ae22001-05-07 17:59:25 +000056 * port selected bugfixes from post-0.49 busybox lash - done?
57 * finish implementing reserved words: for, while, until, do, done
58 * change { and } from special chars to reserved words
59 * builtins: break, continue, eval, return, set, trap, ulimit
60 * test magic exec
Eric Andersen25f27032001-04-26 23:22:31 +000061 * handle children going into background
62 * clean up recognition of null pipes
Eric Andersen25f27032001-04-26 23:22:31 +000063 * check setting of global_argc and global_argv
64 * control-C handling, probably with longjmp
Eric Andersen25f27032001-04-26 23:22:31 +000065 * follow IFS rules more precisely, including update semantics
Eric Andersen25f27032001-04-26 23:22:31 +000066 * figure out what to do with backslash-newline
67 * explain why we use signal instead of sigaction
68 * propagate syntax errors, die on resource errors?
69 * continuation lines, both explicit and implicit - done?
70 * memory leak finding and plugging - done?
71 * more testing, especially quoting rules and redirection
Eric Andersen78a7c992001-05-15 16:30:25 +000072 * document how quoting rules not precisely followed for variable assignments
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +000073 * maybe change charmap[] to use 2-bit entries
Eric Andersen25f27032001-04-26 23:22:31 +000074 * (eventually) remove all the printf's
Eric Andersen25f27032001-04-26 23:22:31 +000075 *
Bernhard Reutner-Fischer86f5c992006-01-22 22:55:11 +000076 * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
Eric Andersen25f27032001-04-26 23:22:31 +000077 */
Bernhard Reutner-Fischere15d7572006-06-02 20:56:16 +000078
Denis Vlasenkob6adbf12007-05-26 19:00:18 +000079
Eric Andersen25f27032001-04-26 23:22:31 +000080#include <glob.h> /* glob, of course */
Eric Andersen25f27032001-04-26 23:22:31 +000081#include <getopt.h> /* should be pretty obvious */
Eric Andersen25f27032001-04-26 23:22:31 +000082/* #include <dmalloc.h> */
Denis Vlasenkob6adbf12007-05-26 19:00:18 +000083
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +000084extern char **environ; /* This is in <unistd.h>, but protected with __USE_GNU */
Denis Vlasenkod01ff132007-05-02 21:40:23 +000085
Denis Vlasenkob6adbf12007-05-26 19:00:18 +000086#include "busybox.h" /* for struct bb_applet */
87
Denis Vlasenkod01ff132007-05-02 21:40:23 +000088
Denis Vlasenko8412d792007-10-01 09:59:47 +000089#if !BB_MMU
90/* A bit drastic. Can allow some simpler commands
91 * by analysing command in generate_stream_from_list()
92 */
93#undef ENABLE_HUSH_TICK
94#define ENABLE_HUSH_TICK 0
95#endif
96
97
Denis Vlasenkod01ff132007-05-02 21:40:23 +000098/* If you comment out one of these below, it will be #defined later
99 * to perform debug printfs to stderr: */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000100#define debug_printf(...) do {} while (0)
Denis Vlasenko400c5b62007-05-04 13:07:27 +0000101/* Finer-grained debug switches */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000102#define debug_printf_parse(...) do {} while (0)
103#define debug_print_tree(a, b) do {} while (0)
104#define debug_printf_exec(...) do {} while (0)
105#define debug_printf_jobs(...) do {} while (0)
106#define debug_printf_expand(...) do {} while (0)
107#define debug_printf_clean(...) do {} while (0)
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000108
109#ifndef debug_printf
110#define debug_printf(...) fprintf(stderr, __VA_ARGS__)
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000111#endif
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000112
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +0000113#ifndef debug_printf_parse
114#define debug_printf_parse(...) fprintf(stderr, __VA_ARGS__)
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000115#endif
116
117#ifndef debug_printf_exec
118#define debug_printf_exec(...) fprintf(stderr, __VA_ARGS__)
119#endif
120
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +0000121#ifndef debug_printf_jobs
122#define debug_printf_jobs(...) fprintf(stderr, __VA_ARGS__)
123#define DEBUG_SHELL_JOBS 1
124#endif
125
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000126#ifndef debug_printf_expand
127#define debug_printf_expand(...) fprintf(stderr, __VA_ARGS__)
128#define DEBUG_EXPAND 1
129#endif
130
Denis Vlasenko170435c2007-05-23 13:01:10 +0000131/* Keep unconditionally on for now */
132#define ENABLE_HUSH_DEBUG 1
133
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +0000134#ifndef debug_printf_clean
135/* broken, of course, but OK for testing */
136static const char *indenter(int i)
137{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +0000138 static const char blanks[] ALIGN1 =
139 " ";
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +0000140 return &blanks[sizeof(blanks) - i - 1];
141}
142#define debug_printf_clean(...) fprintf(stderr, __VA_ARGS__)
Denis Vlasenkoc666f712007-05-16 22:18:54 +0000143#define DEBUG_CLEAN 1
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +0000144#endif
145
Eric Andersen25f27032001-04-26 23:22:31 +0000146
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000147#if !ENABLE_HUSH_INTERACTIVE
148#undef ENABLE_FEATURE_EDITING
149#define ENABLE_FEATURE_EDITING 0
150#undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
151#define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
152#endif
"Robert P. J. Day"f3501602006-07-01 12:19:39 +0000153
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +0000154#define SPECIAL_VAR_SYMBOL 3
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000155
156#define PARSEFLAG_EXIT_FROM_LOOP 1
157#define PARSEFLAG_SEMICOLON (1 << 1) /* symbol ';' is special for parser */
158#define PARSEFLAG_REPARSING (1 << 2) /* >= 2nd pass */
Eric Andersen25f27032001-04-26 23:22:31 +0000159
160typedef enum {
161 REDIRECT_INPUT = 1,
162 REDIRECT_OVERWRITE = 2,
163 REDIRECT_APPEND = 3,
164 REDIRECT_HEREIS = 4,
165 REDIRECT_IO = 5
166} redir_type;
167
168/* The descrip member of this structure is only used to make debugging
169 * output pretty */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +0000170static const struct {
171 int mode;
Denis Vlasenkoef36ead2007-05-02 15:34:47 +0000172 signed char default_fd;
173 char descrip[3];
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +0000174} redir_table[] = {
Eric Andersen25f27032001-04-26 23:22:31 +0000175 { 0, 0, "()" },
176 { O_RDONLY, 0, "<" },
177 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
178 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
179 { O_RDONLY, -1, "<<" },
180 { O_RDWR, 1, "<>" }
181};
182
183typedef enum {
184 PIPE_SEQ = 1,
185 PIPE_AND = 2,
186 PIPE_OR = 3,
187 PIPE_BG = 4,
188} pipe_style;
189
190/* might eventually control execution */
191typedef enum {
192 RES_NONE = 0,
Denis Vlasenko06810332007-05-21 23:30:54 +0000193#if ENABLE_HUSH_IF
Eric Andersen25f27032001-04-26 23:22:31 +0000194 RES_IF = 1,
195 RES_THEN = 2,
196 RES_ELIF = 3,
197 RES_ELSE = 4,
198 RES_FI = 5,
Denis Vlasenko06810332007-05-21 23:30:54 +0000199#endif
200#if ENABLE_HUSH_LOOPS
Eric Andersen25f27032001-04-26 23:22:31 +0000201 RES_FOR = 6,
202 RES_WHILE = 7,
203 RES_UNTIL = 8,
204 RES_DO = 9,
205 RES_DONE = 10,
Denis Vlasenko06810332007-05-21 23:30:54 +0000206 RES_IN = 11,
207#endif
208 RES_XXXX = 12,
Eric Andersen4c9b68f2002-04-13 12:33:41 +0000209 RES_SNTX = 13
Eric Andersen25f27032001-04-26 23:22:31 +0000210} reserved_style;
Denis Vlasenko5f786c22007-04-20 08:35:45 +0000211enum {
212 FLAG_END = (1 << RES_NONE ),
Denis Vlasenko06810332007-05-21 23:30:54 +0000213#if ENABLE_HUSH_IF
Denis Vlasenko5f786c22007-04-20 08:35:45 +0000214 FLAG_IF = (1 << RES_IF ),
215 FLAG_THEN = (1 << RES_THEN ),
216 FLAG_ELIF = (1 << RES_ELIF ),
217 FLAG_ELSE = (1 << RES_ELSE ),
218 FLAG_FI = (1 << RES_FI ),
Denis Vlasenko06810332007-05-21 23:30:54 +0000219#endif
220#if ENABLE_HUSH_LOOPS
Denis Vlasenko5f786c22007-04-20 08:35:45 +0000221 FLAG_FOR = (1 << RES_FOR ),
222 FLAG_WHILE = (1 << RES_WHILE),
223 FLAG_UNTIL = (1 << RES_UNTIL),
224 FLAG_DO = (1 << RES_DO ),
225 FLAG_DONE = (1 << RES_DONE ),
226 FLAG_IN = (1 << RES_IN ),
Denis Vlasenko06810332007-05-21 23:30:54 +0000227#endif
Denis Vlasenko5f786c22007-04-20 08:35:45 +0000228 FLAG_START = (1 << RES_XXXX ),
229};
Eric Andersen25f27032001-04-26 23:22:31 +0000230
231/* This holds pointers to the various results of parsing */
232struct p_context {
233 struct child_prog *child;
234 struct pipe *list_head;
235 struct pipe *pipe;
236 struct redir_struct *pending_redirect;
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000237 smallint res_w;
238 smallint parse_type; /* bitmask of PARSEFLAG_xxx, defines type of parser : ";$" common or special symbol */
239 int old_flag; /* bitmask of FLAG_xxx, for figuring out valid reserved words */
Eric Andersen25f27032001-04-26 23:22:31 +0000240 struct p_context *stack;
241 /* How about quoting status? */
242};
243
244struct redir_struct {
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000245 struct redir_struct *next; /* pointer to the next redirect in the list */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000246 redir_type type; /* type of redirection */
247 int fd; /* file descriptor being redirected */
248 int dup; /* -1, or file descriptor being duplicated */
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000249 char **glob_word; /* *word.gl_pathv is the filename */
Eric Andersen25f27032001-04-26 23:22:31 +0000250};
251
252struct child_prog {
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000253 pid_t pid; /* 0 if exited */
254 char **argv; /* program name and arguments */
255 struct pipe *group; /* if non-NULL, first in group or subshell */
Denis Vlasenko262d7652007-05-20 21:52:49 +0000256 smallint subshell; /* flag, non-zero if group must be forked */
257 smallint is_stopped; /* is the program currently running? */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000258 struct redir_struct *redirects; /* I/O redirections */
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000259 char **glob_result; /* result of parameter globbing */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000260 struct pipe *family; /* pointer back to the child's parent pipe */
Denis Vlasenkoc666f712007-05-16 22:18:54 +0000261 //sp counting seems to be broken... so commented out, grep for '//sp:'
262 //sp: int sp; /* number of SPECIAL_VAR_SYMBOL */
Denis Vlasenko262d7652007-05-20 21:52:49 +0000263 //seems to be unused, grep for '//pt:'
264 //pt: int parse_type;
Eric Andersen25f27032001-04-26 23:22:31 +0000265};
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000266/* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
267 * and on execution these are substituted with their values.
268 * Substitution can make _several_ words out of one argv[n]!
269 * Example: argv[0]=='.^C*^C.' here: echo .$*.
270 */
Eric Andersen25f27032001-04-26 23:22:31 +0000271
272struct pipe {
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000273 struct pipe *next;
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000274 int num_progs; /* total number of programs in job */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000275 int running_progs; /* number of programs running (not exited) */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000276 int stopped_progs; /* number of programs alive, but stopped */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000277#if ENABLE_HUSH_JOB
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000278 int jobid; /* job number */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000279 pid_t pgrp; /* process group ID for the job */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000280 char *cmdtext; /* name of job */
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000281#endif
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000282 char *cmdbuf; /* buffer various argv's point into */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000283 struct child_prog *progs; /* array of commands in pipe */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000284 int job_context; /* bitmask defining current context */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000285 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
286 smallint res_word; /* needed for if, for, while, until... */
Eric Andersen25f27032001-04-26 23:22:31 +0000287};
288
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000289/* On program start, environ points to initial environment.
290 * putenv adds new pointers into it, unsetenv removes them.
291 * Neither of these (de)allocates the strings.
292 * setenv allocates new strings in malloc space and does putenv,
293 * and thus setenv is unusable (leaky) for shell's purposes */
294#define setenv(...) setenv_is_leaky_dont_use()
295struct variable {
296 struct variable *next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +0000297 char *varstr; /* points to "name=" portion */
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000298 int max_len; /* if > 0, name is part of initial env; else name is malloced */
299 smallint flg_export; /* putenv should be done on this var */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000300 smallint flg_read_only;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000301};
302
Eric Andersen25f27032001-04-26 23:22:31 +0000303typedef struct {
304 char *data;
305 int length;
306 int maxlen;
Denis Vlasenkoff097622007-10-01 10:00:45 +0000307 smallint o_quote;
308 smallint nonnull;
Eric Andersen25f27032001-04-26 23:22:31 +0000309} o_string;
310#define NULL_O_STRING {NULL,0,0,0,0}
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000311/* used for initialization: o_string foo = NULL_O_STRING; */
Eric Andersen25f27032001-04-26 23:22:31 +0000312
313/* I can almost use ordinary FILE *. Is open_memstream() universally
314 * available? Where is it documented? */
315struct in_str {
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +0000316 const char *p;
317 /* eof_flag=1: last char in ->p is really an EOF */
318 char eof_flag; /* meaningless if ->p == NULL */
319 char peek_buf[2];
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000320#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko5a1437d2007-05-24 13:22:47 +0000321 smallint promptme;
322 smallint promptmode; /* 0: PS1, 1: PS2 */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000323#endif
Eric Andersen25f27032001-04-26 23:22:31 +0000324 FILE *file;
325 int (*get) (struct in_str *);
326 int (*peek) (struct in_str *);
327};
328#define b_getch(input) ((input)->get(input))
329#define b_peek(input) ((input)->peek(input))
330
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000331enum {
332 CHAR_ORDINARY = 0,
333 CHAR_ORDINARY_IF_QUOTED = 1, /* example: *, # */
334 CHAR_IFS = 2, /* treated as ordinary if quoted */
335 CHAR_SPECIAL = 3, /* example: $ */
Eric Andersen25f27032001-04-26 23:22:31 +0000336};
337
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000338#define HUSH_VER_STR "0.02"
339
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000340/* "Globals" within this file */
341
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000342/* Sorted roughly by size (smaller offsets == smaller code) */
343struct globals {
344#if ENABLE_HUSH_INTERACTIVE
345 /* 'interactive_fd' is a fd# open to ctty, if we have one
346 * _AND_ if we decided to act interactively */
347 int interactive_fd;
348 const char *PS1;
349 const char *PS2;
350#endif
351#if ENABLE_FEATURE_EDITING
352 line_input_t *line_input_state;
353#endif
354#if ENABLE_HUSH_JOB
355 int run_list_level;
356 pid_t saved_task_pgrp;
357 pid_t saved_tty_pgrp;
358 int last_jobid;
359 struct pipe *job_list;
360 struct pipe *toplevel_list;
361 smallint ctrl_z_flag;
362#endif
363 smallint fake_mode;
364 /* these three support $?, $#, and $1 */
365 char **global_argv;
366 int global_argc;
367 int last_return_code;
368 const char *ifs;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000369 const char *cwd;
370 unsigned last_bg_pid;
Denis Vlasenko0a83fc32007-05-25 11:12:32 +0000371 struct variable *top_var; /* = &shell_ver (set in main()) */
372 struct variable shell_ver;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000373#if ENABLE_FEATURE_SH_STANDALONE
374 struct nofork_save_area nofork_save;
375#endif
376#if ENABLE_HUSH_JOB
377 sigjmp_buf toplevel_jb;
378#endif
379 unsigned char charmap[256];
380 char user_input_buf[ENABLE_FEATURE_EDITING ? BUFSIZ : 2];
381};
382
383#define G (*ptr_to_globals)
384
385#if !ENABLE_HUSH_INTERACTIVE
386enum { interactive_fd = 0 };
387#endif
388#if !ENABLE_HUSH_JOB
389enum { run_list_level = 0 };
390#endif
391
392#if ENABLE_HUSH_INTERACTIVE
393#define interactive_fd (G.interactive_fd )
394#define PS1 (G.PS1 )
395#define PS2 (G.PS2 )
396#endif
397#if ENABLE_FEATURE_EDITING
398#define line_input_state (G.line_input_state)
399#endif
400#if ENABLE_HUSH_JOB
401#define run_list_level (G.run_list_level )
402#define saved_task_pgrp (G.saved_task_pgrp )
403#define saved_tty_pgrp (G.saved_tty_pgrp )
404#define last_jobid (G.last_jobid )
405#define job_list (G.job_list )
406#define toplevel_list (G.toplevel_list )
407#define toplevel_jb (G.toplevel_jb )
408#define ctrl_z_flag (G.ctrl_z_flag )
409#endif /* JOB */
410#define global_argv (G.global_argv )
411#define global_argc (G.global_argc )
412#define last_return_code (G.last_return_code)
413#define ifs (G.ifs )
414#define fake_mode (G.fake_mode )
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000415#define cwd (G.cwd )
416#define last_bg_pid (G.last_bg_pid )
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000417#define top_var (G.top_var )
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000418#define shell_ver (G.shell_ver )
419#if ENABLE_FEATURE_SH_STANDALONE
420#define nofork_save (G.nofork_save )
Denis Vlasenko4b924f32007-05-30 00:29:55 +0000421#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000422#if ENABLE_HUSH_JOB
423#define toplevel_jb (G.toplevel_jb )
424#endif
425#define charmap (G.charmap )
426#define user_input_buf (G.user_input_buf )
427
428
429#define B_CHUNK 100
430#define B_NOSPAC 1
431#define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
432
Denis Vlasenko90e485c2007-05-23 15:22:50 +0000433#if 1
434/* Normal */
435static void syntax(const char *msg)
436{
Denis Vlasenko5a1437d2007-05-24 13:22:47 +0000437 /* Was using fancy stuff:
438 * (interactive_fd ? bb_error_msg : bb_error_msg_and_die)(...params...)
439 * but it SEGVs. ?! Oh well... explicit temp ptr works around that */
440 void (*fp)(const char *s, ...);
441
442 fp = (interactive_fd ? bb_error_msg : bb_error_msg_and_die);
443 fp(msg ? "%s: %s" : "syntax error", "syntax error", msg);
Denis Vlasenko90e485c2007-05-23 15:22:50 +0000444}
Denis Vlasenko5a1437d2007-05-24 13:22:47 +0000445
Denis Vlasenko90e485c2007-05-23 15:22:50 +0000446#else
447/* Debug */
448static void syntax_lineno(int line)
Denis Vlasenkob6aae0f2007-01-29 22:51:25 +0000449{
Denis Vlasenko5a1437d2007-05-24 13:22:47 +0000450 void (*fp)(const char *s, ...);
451
452 fp = (interactive_fd ? bb_error_msg : bb_error_msg_and_die);
453 fp("syntax error hush.c:%d", line);
Eric Andersen25f27032001-04-26 23:22:31 +0000454}
Denis Vlasenko90e485c2007-05-23 15:22:50 +0000455#define syntax(str) syntax_lineno(__LINE__)
456#endif
Eric Andersen25f27032001-04-26 23:22:31 +0000457
458/* Index of subroutines: */
459/* function prototypes for builtins */
Denis Vlasenko1359da62007-04-21 23:27:30 +0000460static int builtin_cd(char **argv);
Denis Vlasenko1359da62007-04-21 23:27:30 +0000461static int builtin_eval(char **argv);
462static int builtin_exec(char **argv);
463static int builtin_exit(char **argv);
464static int builtin_export(char **argv);
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000465#if ENABLE_HUSH_JOB
Denis Vlasenko1359da62007-04-21 23:27:30 +0000466static int builtin_fg_bg(char **argv);
Denis Vlasenko1359da62007-04-21 23:27:30 +0000467static int builtin_jobs(char **argv);
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000468#endif
Denis Vlasenko06810332007-05-21 23:30:54 +0000469#if ENABLE_HUSH_HELP
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000470static int builtin_help(char **argv);
Denis Vlasenko06810332007-05-21 23:30:54 +0000471#endif
Denis Vlasenko1359da62007-04-21 23:27:30 +0000472static int builtin_pwd(char **argv);
473static int builtin_read(char **argv);
474static int builtin_set(char **argv);
475static int builtin_shift(char **argv);
476static int builtin_source(char **argv);
477static int builtin_umask(char **argv);
478static int builtin_unset(char **argv);
Denis Vlasenko06810332007-05-21 23:30:54 +0000479//static int builtin_not_written(char **argv);
Eric Andersen25f27032001-04-26 23:22:31 +0000480/* o_string manipulation: */
481static int b_check_space(o_string *o, int len);
482static int b_addchr(o_string *o, int ch);
483static void b_reset(o_string *o);
484static int b_addqchr(o_string *o, int ch, int quote);
Eric Andersen25f27032001-04-26 23:22:31 +0000485/* in_str manipulations: */
486static int static_get(struct in_str *i);
487static int static_peek(struct in_str *i);
488static int file_get(struct in_str *i);
489static int file_peek(struct in_str *i);
490static void setup_file_in_str(struct in_str *i, FILE *f);
491static void setup_string_in_str(struct in_str *i, const char *s);
Eric Andersen25f27032001-04-26 23:22:31 +0000492/* "run" the final data structures: */
Denis Vlasenkoc666f712007-05-16 22:18:54 +0000493#if !defined(DEBUG_CLEAN)
494#define free_pipe_list(head, indent) free_pipe_list(head)
495#define free_pipe(pi, indent) free_pipe(pi)
496#endif
Eric Andersenbf7df042001-05-23 22:18:35 +0000497static int free_pipe_list(struct pipe *head, int indent);
498static int free_pipe(struct pipe *pi, int indent);
Eric Andersen25f27032001-04-26 23:22:31 +0000499/* really run the final data structures: */
500static int setup_redirects(struct child_prog *prog, int squirrel[]);
Eric Andersen25f27032001-04-26 23:22:31 +0000501static int run_list_real(struct pipe *pi);
Denis Vlasenko1359da62007-04-21 23:27:30 +0000502static void pseudo_exec_argv(char **argv) ATTRIBUTE_NORETURN;
Bernhard Reutner-Fischer86f5c992006-01-22 22:55:11 +0000503static void pseudo_exec(struct child_prog *child) ATTRIBUTE_NORETURN;
Eric Andersen25f27032001-04-26 23:22:31 +0000504static int run_pipe_real(struct pipe *pi);
505/* extended glob support: */
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000506static char **globhack(const char *src, char **strings);
Eric Andersen25f27032001-04-26 23:22:31 +0000507static int glob_needed(const char *s);
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000508static int xglob(o_string *dest, char ***pglob);
Eric Andersen78a7c992001-05-15 16:30:25 +0000509/* variable assignment: */
Eric Andersen78a7c992001-05-15 16:30:25 +0000510static int is_assignment(const char *s);
Eric Andersen25f27032001-04-26 23:22:31 +0000511/* data structure manipulation: */
512static int setup_redirect(struct p_context *ctx, int fd, redir_type style, struct in_str *input);
513static void initialize_context(struct p_context *ctx);
514static int done_word(o_string *dest, struct p_context *ctx);
515static int done_command(struct p_context *ctx);
516static int done_pipe(struct p_context *ctx, pipe_style type);
517/* primary string parsing: */
518static int redirect_dup_num(struct in_str *input);
519static int redirect_opt_num(o_string *o);
Denis Vlasenko14b5dd92007-05-20 21:51:38 +0000520#if ENABLE_HUSH_TICK
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +0000521static 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 +0000522#endif
Eric Andersen25f27032001-04-26 23:22:31 +0000523static int parse_group(o_string *dest, struct p_context *ctx, struct in_str *input, int ch);
Denis Vlasenko15d78fb2007-01-30 22:28:21 +0000524static const char *lookup_param(const char *src);
Eric Andersen25f27032001-04-26 23:22:31 +0000525static int handle_dollar(o_string *dest, struct p_context *ctx, struct in_str *input);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +0000526static 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 +0000527/* setup: */
Denis Vlasenko170435c2007-05-23 13:01:10 +0000528static int parse_and_run_stream(struct in_str *inp, int parse_flag);
529static int parse_and_run_string(const char *s, int parse_flag);
530static int parse_and_run_file(FILE *f);
Eric Andersenbafd94f2001-05-02 16:11:59 +0000531/* job management: */
Eric Andersenc798b072001-06-22 06:23:03 +0000532static int checkjobs(struct pipe* fg_pipe);
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000533#if ENABLE_HUSH_JOB
Denis Vlasenko52881e92007-04-21 13:42:52 +0000534static int checkjobs_and_fg_shell(struct pipe* fg_pipe);
Eric Andersenbafd94f2001-05-02 16:11:59 +0000535static void insert_bg_job(struct pipe *pi);
536static void remove_bg_job(struct pipe *pi);
Denis Vlasenko1359da62007-04-21 23:27:30 +0000537static void delete_finished_bg_job(struct pipe *pi);
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000538#else
539int checkjobs_and_fg_shell(struct pipe* fg_pipe); /* never called */
540#endif
Eric Andersenf72f5622001-05-15 23:21:41 +0000541/* local variable support */
Denis Vlasenko170435c2007-05-23 13:01:10 +0000542static char **expand_strvec_to_strvec(char **argv);
543/* used for eval */
544static char *expand_strvec_to_string(char **argv);
Denis Vlasenkob6a741f2007-05-17 14:38:17 +0000545/* used for expansion of right hand of assignments */
Denis Vlasenko170435c2007-05-23 13:01:10 +0000546static char *expand_string_to_string(const char *str);
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +0000547static struct variable *get_local_var(const char *name);
548static int set_local_var(char *str, int flg_export);
Denis Vlasenko87cb2db2007-04-21 10:00:01 +0000549static void unset_local_var(const char *name);
Eric Andersen25f27032001-04-26 23:22:31 +0000550
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000551
552static char **add_strings_to_strings(int need_xstrdup, char **strings, char **add)
553{
554 int i;
555 unsigned count1;
556 unsigned count2;
557 char **v;
558
559 v = strings;
560 count1 = 0;
561 if (v) {
562 while (*v) {
563 count1++;
564 v++;
565 }
566 }
567 count2 = 0;
568 v = add;
569 while (*v) {
570 count2++;
571 v++;
572 }
573 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
574 v[count1 + count2] = NULL;
575 i = count2;
576 while (--i >= 0)
577 v[count1 + i] = need_xstrdup ? xstrdup(add[i]) : add[i];
578 return v;
579}
580
581/* 'add' should be a malloced pointer */
582static char **add_string_to_strings(char **strings, char *add)
583{
584 char *v[2];
585
586 v[0] = add;
587 v[1] = NULL;
588
589 return add_strings_to_strings(0, strings, v);
590}
591
592static void free_strings(char **strings)
593{
594 if (strings) {
595 char **v = strings;
596 while (*v)
597 free(*v++);
598 free(strings);
599 }
600}
601
602
Eric Andersen25f27032001-04-26 23:22:31 +0000603/* Table of built-in functions. They can be forked or not, depending on
604 * context: within pipes, they fork. As simple commands, they do not.
605 * When used in non-forking context, they can change global variables
Denis Vlasenkoe1a0d482006-10-20 13:28:22 +0000606 * in the parent shell process. If forked, of course they cannot.
Eric Andersen25f27032001-04-26 23:22:31 +0000607 * For example, 'unset foo | whatever' will parse and run, but foo will
608 * still be set at the end. */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000609struct built_in_command {
610 const char *cmd; /* name */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000611 int (*function) (char **argv); /* function ptr */
Denis Vlasenko06810332007-05-21 23:30:54 +0000612#if ENABLE_HUSH_HELP
613 const char *descr; /* description */
614#define BLTIN(cmd, func, help) { cmd, func, help }
615#else
616#define BLTIN(cmd, func, help) { cmd, func }
617#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000618};
619
"Vladimir N. Oleynik"485d7cb2005-10-17 09:48:57 +0000620static const struct built_in_command bltins[] = {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000621#if ENABLE_HUSH_JOB
Denis Vlasenko06810332007-05-21 23:30:54 +0000622 BLTIN("bg" , builtin_fg_bg, "Resume a job in the background"),
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000623#endif
Denis Vlasenko06810332007-05-21 23:30:54 +0000624// BLTIN("break" , builtin_not_written, "Exit for, while or until loop"),
625 BLTIN("cd" , builtin_cd, "Change working directory"),
626// BLTIN("continue", builtin_not_written, "Continue for, while or until loop"),
627 BLTIN("eval" , builtin_eval, "Construct and run shell command"),
628 BLTIN("exec" , builtin_exec, "Exec command, replacing this shell with the exec'd process"),
629 BLTIN("exit" , builtin_exit, "Exit from shell"),
630 BLTIN("export", builtin_export, "Set environment variable"),
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000631#if ENABLE_HUSH_JOB
Denis Vlasenko06810332007-05-21 23:30:54 +0000632 BLTIN("fg" , builtin_fg_bg, "Bring job into the foreground"),
633 BLTIN("jobs" , builtin_jobs, "Lists the active jobs"),
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000634#endif
Denis Vlasenko06810332007-05-21 23:30:54 +0000635// TODO: remove pwd? we have it as an applet...
636 BLTIN("pwd" , builtin_pwd, "Print current directory"),
637 BLTIN("read" , builtin_read, "Input environment variable"),
638// BLTIN("return", builtin_not_written, "Return from a function"),
639 BLTIN("set" , builtin_set, "Set/unset shell local variables"),
640 BLTIN("shift" , builtin_shift, "Shift positional parameters"),
641// BLTIN("trap" , builtin_not_written, "Trap signals"),
642// BLTIN("ulimit", builtin_not_written, "Controls resource limits"),
643 BLTIN("umask" , builtin_umask, "Sets file creation mask"),
644 BLTIN("unset" , builtin_unset, "Unset environment variable"),
645 BLTIN("." , builtin_source, "Source-in and run commands in a file"),
646#if ENABLE_HUSH_HELP
647 BLTIN("help" , builtin_help, "List shell built-in commands"),
648#endif
649 BLTIN(NULL, NULL, NULL)
Eric Andersen25f27032001-04-26 23:22:31 +0000650};
651
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000652#if ENABLE_HUSH_JOB
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000653
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000654/* move to libbb? */
655static void signal_SA_RESTART(int sig, void (*handler)(int))
656{
657 struct sigaction sa;
658 sa.sa_handler = handler;
659 sa.sa_flags = SA_RESTART;
660 sigemptyset(&sa.sa_mask);
661 sigaction(sig, &sa, NULL);
662}
663
Denis Vlasenko3ac0e002007-04-28 16:45:22 +0000664/* Signals are grouped, we handle them in batches */
665static void set_fatal_sighandler(void (*handler)(int))
666{
667 signal(SIGILL , handler);
668 signal(SIGTRAP, handler);
669 signal(SIGABRT, handler);
670 signal(SIGFPE , handler);
671 signal(SIGBUS , handler);
672 signal(SIGSEGV, handler);
673 /* bash 3.2 seems to handle these just like 'fatal' ones */
674 signal(SIGHUP , handler);
675 signal(SIGPIPE, handler);
676 signal(SIGALRM, handler);
677}
678static void set_jobctrl_sighandler(void (*handler)(int))
679{
680 signal(SIGTSTP, handler);
681 signal(SIGTTIN, handler);
682 signal(SIGTTOU, handler);
683}
684static void set_misc_sighandler(void (*handler)(int))
685{
686 signal(SIGINT , handler);
687 signal(SIGQUIT, handler);
688 signal(SIGTERM, handler);
689}
690/* SIGCHLD is special and handled separately */
691
692static void set_every_sighandler(void (*handler)(int))
693{
694 set_fatal_sighandler(handler);
695 set_jobctrl_sighandler(handler);
696 set_misc_sighandler(handler);
697 signal(SIGCHLD, handler);
698}
699
Denis Vlasenkob5eaabb2007-04-28 16:45:59 +0000700static void handler_ctrl_c(int sig)
701{
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000702 debug_printf_jobs("got sig %d\n", sig);
Denis Vlasenkob5eaabb2007-04-28 16:45:59 +0000703// as usual we can have all kinds of nasty problems with leaked malloc data here
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +0000704 siglongjmp(toplevel_jb, 1);
Denis Vlasenkob5eaabb2007-04-28 16:45:59 +0000705}
706
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000707static void handler_ctrl_z(int sig)
708{
709 pid_t pid;
710
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +0000711 debug_printf_jobs("got tty sig %d in pid %d\n", sig, getpid());
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000712 pid = fork();
Denis Vlasenkoc2990322007-05-16 12:57:12 +0000713 if (pid < 0) /* can't fork. Pretend there was no ctrl-Z */
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000714 return;
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +0000715 ctrl_z_flag = 1;
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000716 if (!pid) { /* child */
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000717 setpgrp();
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +0000718 debug_printf_jobs("set pgrp for child %d ok\n", getpid());
Denis Vlasenko3ac0e002007-04-28 16:45:22 +0000719 set_every_sighandler(SIG_DFL);
Denis Vlasenko18e19f22007-04-28 16:43:18 +0000720 raise(SIGTSTP); /* resend TSTP so that child will be stopped */
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +0000721 debug_printf_jobs("returning in child\n");
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000722 /* return to nofork, it will eventually exit now,
723 * not return back to shell */
724 return;
725 }
726 /* parent */
727 /* finish filling up pipe info */
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +0000728 toplevel_list->pgrp = pid; /* child is in its own pgrp */
729 toplevel_list->progs[0].pid = pid;
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000730 /* parent needs to longjmp out of running nofork.
731 * we will "return" exitcode 0, with child put in background */
732// as usual we can have all kinds of nasty problems with leaked malloc data here
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +0000733 debug_printf_jobs("siglongjmp in parent\n");
734 siglongjmp(toplevel_jb, 1);
Denis Vlasenkoa6a17852007-04-28 16:42:11 +0000735}
736
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000737/* Restores tty foreground process group, and exits.
738 * May be called as signal handler for fatal signal
739 * (will faithfully resend signal to itself, producing correct exit state)
740 * or called directly with -EXITCODE.
741 * We also call it if xfunc is exiting. */
742static void sigexit(int sig) ATTRIBUTE_NORETURN;
743static void sigexit(int sig)
744{
745 sigset_t block_all;
746
747 /* Disable all signals: job control, SIGPIPE, etc. */
748 sigfillset(&block_all);
749 sigprocmask(SIG_SETMASK, &block_all, NULL);
750
Denis Vlasenko87cb2db2007-04-21 10:00:01 +0000751 if (interactive_fd)
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000752 tcsetpgrp(interactive_fd, saved_tty_pgrp);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000753
754 /* Not a signal, just exit */
755 if (sig <= 0)
756 _exit(- sig);
757
758 /* Enable only this sig and kill ourself with it */
759 signal(sig, SIG_DFL);
760 sigdelset(&block_all, sig);
761 sigprocmask(SIG_SETMASK, &block_all, NULL);
762 raise(sig);
763 _exit(1); /* Should not reach it */
764}
765
766/* Restores tty foreground process group, and exits. */
767static void hush_exit(int exitcode) ATTRIBUTE_NORETURN;
768static void hush_exit(int exitcode)
769{
770 fflush(NULL); /* flush all streams */
771 sigexit(- (exitcode & 0xff));
772}
773
Denis Vlasenkoef36ead2007-05-02 15:34:47 +0000774#else /* !JOB */
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000775
776#define set_fatal_sighandler(handler) ((void)0)
777#define set_jobctrl_sighandler(handler) ((void)0)
778#define set_misc_sighandler(handler) ((void)0)
Denis Vlasenkoef36ead2007-05-02 15:34:47 +0000779#define hush_exit(e) exit(e)
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000780
Denis Vlasenkoef36ead2007-05-02 15:34:47 +0000781#endif /* JOB */
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000782
783
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000784static const char *set_cwd(void)
785{
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000786 if (cwd == bb_msg_unknown)
Denis Vlasenko7cced6e2007-04-12 17:08:53 +0000787 cwd = NULL; /* xrealloc_getcwd_or_warn(arg) calls free(arg)! */
Denis Vlasenko6ca04442007-02-11 16:19:28 +0000788 cwd = xrealloc_getcwd_or_warn((char *)cwd);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000789 if (!cwd)
Manuel Novoa III cad53642003-03-19 09:13:01 +0000790 cwd = bb_msg_unknown;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000791 return cwd;
792}
793
Eric Andersen4c9b68f2002-04-13 12:33:41 +0000794/* built-in 'eval' handler */
Denis Vlasenko1359da62007-04-21 23:27:30 +0000795static int builtin_eval(char **argv)
Eric Andersen4c9b68f2002-04-13 12:33:41 +0000796{
Eric Andersen4c9b68f2002-04-13 12:33:41 +0000797 int rcode = EXIT_SUCCESS;
Eric Andersenc7bda1c2004-03-15 08:29:22 +0000798
Denis Vlasenko1359da62007-04-21 23:27:30 +0000799 if (argv[1]) {
Denis Vlasenko170435c2007-05-23 13:01:10 +0000800 char *str = expand_strvec_to_string(argv + 1);
801 parse_and_run_string(str, PARSEFLAG_EXIT_FROM_LOOP |
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000802 PARSEFLAG_SEMICOLON);
Eric Andersen4c9b68f2002-04-13 12:33:41 +0000803 free(str);
804 rcode = last_return_code;
805 }
806 return rcode;
807}
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000808
Eric Andersen25f27032001-04-26 23:22:31 +0000809/* built-in 'cd <path>' handler */
Denis Vlasenko1359da62007-04-21 23:27:30 +0000810static int builtin_cd(char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +0000811{
Denis Vlasenko170435c2007-05-23 13:01:10 +0000812 const char *newdir;
Denis Vlasenko96e1b382007-09-30 23:50:48 +0000813 if (argv[1] == NULL) {
814 // bash does nothing (exitcode 0) if HOME is ""; if it's unset,
815 // bash says "bash: cd: HOME not set" and does nothing (exitcode 1)
Denis Vlasenko170435c2007-05-23 13:01:10 +0000816 newdir = getenv("HOME") ? : "/";
Denis Vlasenko96e1b382007-09-30 23:50:48 +0000817 } else
Denis Vlasenko1359da62007-04-21 23:27:30 +0000818 newdir = argv[1];
Eric Andersen25f27032001-04-26 23:22:31 +0000819 if (chdir(newdir)) {
820 printf("cd: %s: %s\n", newdir, strerror(errno));
821 return EXIT_FAILURE;
822 }
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000823 set_cwd();
Eric Andersen25f27032001-04-26 23:22:31 +0000824 return EXIT_SUCCESS;
825}
826
Eric Andersen25f27032001-04-26 23:22:31 +0000827/* built-in 'exec' handler */
Denis Vlasenko1359da62007-04-21 23:27:30 +0000828static int builtin_exec(char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +0000829{
Denis Vlasenko1359da62007-04-21 23:27:30 +0000830 if (argv[1] == NULL)
Eric Andersen25f27032001-04-26 23:22:31 +0000831 return EXIT_SUCCESS; /* Really? */
Denis Vlasenko1359da62007-04-21 23:27:30 +0000832 pseudo_exec_argv(argv + 1);
Eric Andersen25f27032001-04-26 23:22:31 +0000833 /* never returns */
834}
835
836/* built-in 'exit' handler */
Denis Vlasenko1359da62007-04-21 23:27:30 +0000837static int builtin_exit(char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +0000838{
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000839// TODO: bash does it ONLY on top-level sh exit (+interacive only?)
840 //puts("exit"); /* bash does it */
Denis Vlasenkof2fffd02007-05-02 23:39:04 +0000841// TODO: warn if we have background jobs: "There are stopped jobs"
842// On second consecutive 'exit', exit anyway.
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000843
Denis Vlasenko1359da62007-04-21 23:27:30 +0000844 if (argv[1] == NULL)
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000845 hush_exit(last_return_code);
Denis Vlasenko5f786c22007-04-20 08:35:45 +0000846 /* mimic bash: exit 123abc == exit 255 + error msg */
847 xfunc_error_retval = 255;
848 /* bash: exit -2 == exit 254, no error msg */
Denis Vlasenkof2fffd02007-05-02 23:39:04 +0000849 hush_exit(xatoi(argv[1]) & 0xff);
Eric Andersen25f27032001-04-26 23:22:31 +0000850}
851
852/* built-in 'export VAR=value' handler */
Denis Vlasenko1359da62007-04-21 23:27:30 +0000853static int builtin_export(char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +0000854{
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000855 const char *value;
Denis Vlasenko1359da62007-04-21 23:27:30 +0000856 char *name = argv[1];
Eric Andersen25f27032001-04-26 23:22:31 +0000857
Eric Andersenf72f5622001-05-15 23:21:41 +0000858 if (name == NULL) {
Denis Vlasenkof2fffd02007-05-02 23:39:04 +0000859 // TODO:
860 // ash emits: export VAR='VAL'
861 // bash: declare -x VAR="VAL"
862 // (both also escape as needed (quotes, $, etc))
863 char **e = environ;
864 if (e)
865 while (*e)
866 puts(*e++);
867 return EXIT_SUCCESS;
Eric Andersen25f27032001-04-26 23:22:31 +0000868 }
Eric Andersenf72f5622001-05-15 23:21:41 +0000869
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000870 value = strchr(name, '=');
871 if (!value) {
872 /* They are exporting something without a =VALUE */
873 struct variable *var;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000874
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000875 var = get_local_var(name);
876 if (var) {
877 var->flg_export = 1;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +0000878 putenv(var->varstr);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000879 }
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000880 /* bash does not return an error when trying to export
881 * an undefined variable. Do likewise. */
882 return EXIT_SUCCESS;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000883 }
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000884
885 set_local_var(xstrdup(name), 1);
886 return EXIT_SUCCESS;
Eric Andersen25f27032001-04-26 23:22:31 +0000887}
888
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000889#if ENABLE_HUSH_JOB
Eric Andersen25f27032001-04-26 23:22:31 +0000890/* built-in 'fg' and 'bg' handler */
Denis Vlasenko1359da62007-04-21 23:27:30 +0000891static int builtin_fg_bg(char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +0000892{
Eric Andersen0fcd4472001-05-02 20:12:03 +0000893 int i, jobnum;
Denis Vlasenko8a28e622007-04-14 11:16:29 +0000894 struct pipe *pi;
Eric Andersen25f27032001-04-26 23:22:31 +0000895
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000896 if (!interactive_fd)
Eric Andersenc798b072001-06-22 06:23:03 +0000897 return EXIT_FAILURE;
Eric Andersen0fcd4472001-05-02 20:12:03 +0000898 /* If they gave us no args, assume they want the last backgrounded task */
Denis Vlasenko1359da62007-04-21 23:27:30 +0000899 if (!argv[1]) {
Eric Andersenc798b072001-06-22 06:23:03 +0000900 for (pi = job_list; pi; pi = pi->next) {
901 if (pi->jobid == last_jobid) {
Denis Vlasenko8a28e622007-04-14 11:16:29 +0000902 goto found;
Eric Andersen0fcd4472001-05-02 20:12:03 +0000903 }
904 }
Denis Vlasenko1359da62007-04-21 23:27:30 +0000905 bb_error_msg("%s: no current job", argv[0]);
Denis Vlasenko8a28e622007-04-14 11:16:29 +0000906 return EXIT_FAILURE;
907 }
Denis Vlasenko1359da62007-04-21 23:27:30 +0000908 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
909 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
Denis Vlasenko8a28e622007-04-14 11:16:29 +0000910 return EXIT_FAILURE;
911 }
912 for (pi = job_list; pi; pi = pi->next) {
913 if (pi->jobid == jobnum) {
914 goto found;
Eric Andersen25f27032001-04-26 23:22:31 +0000915 }
916 }
Denis Vlasenko1359da62007-04-21 23:27:30 +0000917 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
Denis Vlasenko8a28e622007-04-14 11:16:29 +0000918 return EXIT_FAILURE;
919 found:
Denis Vlasenko52881e92007-04-21 13:42:52 +0000920 // TODO: bash prints a string representation
921 // of job being foregrounded (like "sleep 1 | cat")
Denis Vlasenko1359da62007-04-21 23:27:30 +0000922 if (*argv[0] == 'f') {
Eric Andersen028b65b2001-06-28 01:10:11 +0000923 /* Put the job into the foreground. */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +0000924 tcsetpgrp(interactive_fd, pi->pgrp);
Eric Andersen25f27032001-04-26 23:22:31 +0000925 }
926
927 /* Restart the processes in the job */
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000928 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_progs, pi->pgrp);
Denis Vlasenko1359da62007-04-21 23:27:30 +0000929 for (i = 0; i < pi->num_progs; i++) {
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000930 debug_printf_jobs("reviving pid %d\n", pi->progs[i].pid);
Eric Andersen0fcd4472001-05-02 20:12:03 +0000931 pi->progs[i].is_stopped = 0;
Denis Vlasenko1359da62007-04-21 23:27:30 +0000932 }
933 pi->stopped_progs = 0;
Eric Andersen25f27032001-04-26 23:22:31 +0000934
Denis Vlasenkobb81c582007-01-30 22:32:09 +0000935 i = kill(- pi->pgrp, SIGCONT);
936 if (i < 0) {
Denis Vlasenko8a28e622007-04-14 11:16:29 +0000937 if (errno == ESRCH) {
Denis Vlasenko1359da62007-04-21 23:27:30 +0000938 delete_finished_bg_job(pi);
Denis Vlasenko3ac0e002007-04-28 16:45:22 +0000939 return EXIT_SUCCESS;
Eric Andersen028b65b2001-06-28 01:10:11 +0000940 } else {
Manuel Novoa III cad53642003-03-19 09:13:01 +0000941 bb_perror_msg("kill (SIGCONT)");
Eric Andersen028b65b2001-06-28 01:10:11 +0000942 }
943 }
Eric Andersen25f27032001-04-26 23:22:31 +0000944
Denis Vlasenko1359da62007-04-21 23:27:30 +0000945 if (*argv[0] == 'f') {
946 remove_bg_job(pi);
Denis Vlasenko52881e92007-04-21 13:42:52 +0000947 return checkjobs_and_fg_shell(pi);
Denis Vlasenko1359da62007-04-21 23:27:30 +0000948 }
Eric Andersen25f27032001-04-26 23:22:31 +0000949 return EXIT_SUCCESS;
950}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000951#endif
Eric Andersen25f27032001-04-26 23:22:31 +0000952
953/* built-in 'help' handler */
Denis Vlasenko06810332007-05-21 23:30:54 +0000954#if ENABLE_HUSH_HELP
Denis Vlasenko1359da62007-04-21 23:27:30 +0000955static int builtin_help(char **argv ATTRIBUTE_UNUSED)
Eric Andersen25f27032001-04-26 23:22:31 +0000956{
"Vladimir N. Oleynik"485d7cb2005-10-17 09:48:57 +0000957 const struct built_in_command *x;
Eric Andersen25f27032001-04-26 23:22:31 +0000958
959 printf("\nBuilt-in commands:\n");
960 printf("-------------------\n");
961 for (x = bltins; x->cmd; x++) {
Eric Andersen25f27032001-04-26 23:22:31 +0000962 printf("%s\t%s\n", x->cmd, x->descr);
963 }
964 printf("\n\n");
965 return EXIT_SUCCESS;
966}
Denis Vlasenko06810332007-05-21 23:30:54 +0000967#endif
Eric Andersen25f27032001-04-26 23:22:31 +0000968
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000969#if ENABLE_HUSH_JOB
Eric Andersen25f27032001-04-26 23:22:31 +0000970/* built-in 'jobs' handler */
Denis Vlasenko1359da62007-04-21 23:27:30 +0000971static int builtin_jobs(char **argv ATTRIBUTE_UNUSED)
Eric Andersen25f27032001-04-26 23:22:31 +0000972{
973 struct pipe *job;
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000974 const char *status_string;
Eric Andersen25f27032001-04-26 23:22:31 +0000975
Eric Andersenc798b072001-06-22 06:23:03 +0000976 for (job = job_list; job; job = job->next) {
Eric Andersen25f27032001-04-26 23:22:31 +0000977 if (job->running_progs == job->stopped_progs)
978 status_string = "Stopped";
979 else
980 status_string = "Running";
Eric Andersen52a97ca2001-06-22 06:49:26 +0000981
Denis Vlasenko3ac0e002007-04-28 16:45:22 +0000982 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
Eric Andersen25f27032001-04-26 23:22:31 +0000983 }
984 return EXIT_SUCCESS;
985}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000986#endif
Eric Andersen25f27032001-04-26 23:22:31 +0000987
Eric Andersen25f27032001-04-26 23:22:31 +0000988/* built-in 'pwd' handler */
Denis Vlasenko1359da62007-04-21 23:27:30 +0000989static int builtin_pwd(char **argv ATTRIBUTE_UNUSED)
Eric Andersen25f27032001-04-26 23:22:31 +0000990{
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000991 puts(set_cwd());
Eric Andersen25f27032001-04-26 23:22:31 +0000992 return EXIT_SUCCESS;
993}
994
995/* built-in 'read VAR' handler */
Denis Vlasenko1359da62007-04-21 23:27:30 +0000996static int builtin_read(char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +0000997{
Denis Vlasenkod67cef22007-06-13 06:47:47 +0000998 char *string;
Denis Vlasenko3e7b0e62007-05-16 12:52:15 +0000999 const char *name = argv[1] ? argv[1] : "REPLY";
Eric Andersen25f27032001-04-26 23:22:31 +00001000
Denis Vlasenkod67cef22007-06-13 06:47:47 +00001001 string = xmalloc_reads(STDIN_FILENO, xasprintf("%s=", name));
1002 return set_local_var(string, 0);
Eric Andersen25f27032001-04-26 23:22:31 +00001003}
1004
Denis Vlasenko3e7b0e62007-05-16 12:52:15 +00001005/* built-in 'set [VAR=value]' handler */
Denis Vlasenko1359da62007-04-21 23:27:30 +00001006static int builtin_set(char **argv)
Eric Andersenf72f5622001-05-15 23:21:41 +00001007{
Denis Vlasenko1359da62007-04-21 23:27:30 +00001008 char *temp = argv[1];
Denis Vlasenkod76c0492007-05-25 02:16:25 +00001009 struct variable *e;
Eric Andersenf72f5622001-05-15 23:21:41 +00001010
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00001011 if (temp == NULL)
Denis Vlasenkod76c0492007-05-25 02:16:25 +00001012 for (e = top_var; e; e = e->next)
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00001013 puts(e->varstr);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00001014 else
Denis Vlasenkod76c0492007-05-25 02:16:25 +00001015 set_local_var(xstrdup(temp), 0);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00001016
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001017 return EXIT_SUCCESS;
Eric Andersenf72f5622001-05-15 23:21:41 +00001018}
1019
1020
Eric Andersen25f27032001-04-26 23:22:31 +00001021/* Built-in 'shift' handler */
Denis Vlasenko1359da62007-04-21 23:27:30 +00001022static int builtin_shift(char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00001023{
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001024 int n = 1;
Denis Vlasenko1359da62007-04-21 23:27:30 +00001025 if (argv[1]) {
1026 n = atoi(argv[1]);
Eric Andersen25f27032001-04-26 23:22:31 +00001027 }
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001028 if (n >= 0 && n < global_argc) {
Denis Vlasenko004baba2007-05-20 22:22:18 +00001029 global_argv[n] = global_argv[0];
Eric Andersen25f27032001-04-26 23:22:31 +00001030 global_argc -= n;
1031 global_argv += n;
1032 return EXIT_SUCCESS;
Eric Andersen25f27032001-04-26 23:22:31 +00001033 }
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00001034 return EXIT_FAILURE;
Eric Andersen25f27032001-04-26 23:22:31 +00001035}
1036
1037/* Built-in '.' handler (read-in and execute commands from file) */
Denis Vlasenko1359da62007-04-21 23:27:30 +00001038static int builtin_source(char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00001039{
1040 FILE *input;
1041 int status;
1042
Denis Vlasenko1359da62007-04-21 23:27:30 +00001043 if (argv[1] == NULL)
Eric Andersen25f27032001-04-26 23:22:31 +00001044 return EXIT_FAILURE;
1045
1046 /* XXX search through $PATH is missing */
Denis Vlasenko1359da62007-04-21 23:27:30 +00001047 input = fopen(argv[1], "r");
Eric Andersen25f27032001-04-26 23:22:31 +00001048 if (!input) {
Denis Vlasenko1359da62007-04-21 23:27:30 +00001049 bb_error_msg("cannot open '%s'", argv[1]);
Eric Andersen25f27032001-04-26 23:22:31 +00001050 return EXIT_FAILURE;
1051 }
Denis Vlasenkoa0898172007-10-01 09:59:01 +00001052 close_on_exec_on(fileno(input));
Eric Andersen25f27032001-04-26 23:22:31 +00001053
1054 /* Now run the file */
1055 /* XXX argv and argc are broken; need to save old global_argv
1056 * (pointer only is OK!) on this stack frame,
Denis Vlasenko1359da62007-04-21 23:27:30 +00001057 * set global_argv=argv+1, recurse, and restore. */
Denis Vlasenko170435c2007-05-23 13:01:10 +00001058 status = parse_and_run_file(input);
Eric Andersen25f27032001-04-26 23:22:31 +00001059 fclose(input);
Denis Vlasenkod9e15f22006-11-27 16:49:55 +00001060 return status;
Eric Andersen25f27032001-04-26 23:22:31 +00001061}
1062
Denis Vlasenko1359da62007-04-21 23:27:30 +00001063static int builtin_umask(char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00001064{
Eric Andersen83a2ae22001-05-07 17:59:25 +00001065 mode_t new_umask;
Denis Vlasenko1359da62007-04-21 23:27:30 +00001066 const char *arg = argv[1];
Eric Andersen83a2ae22001-05-07 17:59:25 +00001067 char *end;
1068 if (arg) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001069 new_umask = strtoul(arg, &end, 8);
1070 if (*end != '\0' || end == arg) {
Eric Andersen83a2ae22001-05-07 17:59:25 +00001071 return EXIT_FAILURE;
1072 }
1073 } else {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001074 new_umask = umask(0);
1075 printf("%.3o\n", (unsigned) new_umask);
Eric Andersen83a2ae22001-05-07 17:59:25 +00001076 }
1077 umask(new_umask);
1078 return EXIT_SUCCESS;
Eric Andersen25f27032001-04-26 23:22:31 +00001079}
1080
1081/* built-in 'unset VAR' handler */
Denis Vlasenko1359da62007-04-21 23:27:30 +00001082static int builtin_unset(char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00001083{
Denis Vlasenko3e7b0e62007-05-16 12:52:15 +00001084 /* bash always returns true */
Denis Vlasenko1359da62007-04-21 23:27:30 +00001085 unset_local_var(argv[1]);
Eric Andersen25f27032001-04-26 23:22:31 +00001086 return EXIT_SUCCESS;
1087}
1088
Denis Vlasenko06810332007-05-21 23:30:54 +00001089//static int builtin_not_written(char **argv)
1090//{
1091// printf("builtin_%s not written\n", argv[0]);
1092// return EXIT_FAILURE;
1093//}
Eric Andersen83a2ae22001-05-07 17:59:25 +00001094
Eric Andersen25f27032001-04-26 23:22:31 +00001095static int b_check_space(o_string *o, int len)
1096{
1097 /* It would be easy to drop a more restrictive policy
1098 * in here, such as setting a maximum string length */
1099 if (o->length + len > o->maxlen) {
Denis Vlasenkof5294e12007-04-14 10:09:57 +00001100 /* assert(data == NULL || o->maxlen != 0); */
Denis Vlasenkoef36ead2007-05-02 15:34:47 +00001101 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001102 o->data = xrealloc(o->data, 1 + o->maxlen);
Eric Andersen25f27032001-04-26 23:22:31 +00001103 }
1104 return o->data == NULL;
1105}
1106
1107static int b_addchr(o_string *o, int ch)
1108{
Denis Vlasenko831dcc42007-05-16 15:05:36 +00001109 debug_printf("b_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001110 if (b_check_space(o, 1))
1111 return B_NOSPAC;
Eric Andersen25f27032001-04-26 23:22:31 +00001112 o->data[o->length] = ch;
1113 o->length++;
1114 o->data[o->length] = '\0';
1115 return 0;
1116}
1117
1118static void b_reset(o_string *o)
1119{
1120 o->length = 0;
1121 o->nonnull = 0;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001122 if (o->data)
1123 o->data[0] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00001124}
1125
1126static void b_free(o_string *o)
1127{
Aaron Lehmanna170e1c2002-11-28 11:27:31 +00001128 free(o->data);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001129 memset(o, 0, sizeof(*o));
Eric Andersen25f27032001-04-26 23:22:31 +00001130}
1131
1132/* My analysis of quoting semantics tells me that state information
1133 * is associated with a destination, not a source.
1134 */
1135static int b_addqchr(o_string *o, int ch, int quote)
1136{
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00001137 if (quote && strchr("*?[\\", ch)) {
Eric Andersen25f27032001-04-26 23:22:31 +00001138 int rc;
1139 rc = b_addchr(o, '\\');
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001140 if (rc)
1141 return rc;
Eric Andersen25f27032001-04-26 23:22:31 +00001142 }
1143 return b_addchr(o, ch);
1144}
1145
Eric Andersen25f27032001-04-26 23:22:31 +00001146static int static_get(struct in_str *i)
1147{
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001148 int ch = *i->p++;
1149 if (ch == '\0') return EOF;
Eric Andersen25f27032001-04-26 23:22:31 +00001150 return ch;
1151}
1152
1153static int static_peek(struct in_str *i)
1154{
1155 return *i->p;
1156}
1157
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001158#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001159#if ENABLE_FEATURE_EDITING
Rob Landley88621d72006-08-29 19:41:06 +00001160static void cmdedit_set_initial_prompt(void)
Eric Andersen25f27032001-04-26 23:22:31 +00001161{
Denis Vlasenko38f63192007-01-22 09:03:07 +00001162#if !ENABLE_FEATURE_EDITING_FANCY_PROMPT
Eric Andersen25f27032001-04-26 23:22:31 +00001163 PS1 = NULL;
1164#else
1165 PS1 = getenv("PS1");
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001166 if (PS1 == NULL)
Eric Andersen25f27032001-04-26 23:22:31 +00001167 PS1 = "\\w \\$ ";
Eric Andersenc7bda1c2004-03-15 08:29:22 +00001168#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001169}
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001170#endif /* EDITING */
Eric Andersen25f27032001-04-26 23:22:31 +00001171
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00001172static const char* setup_prompt_string(int promptmode)
Eric Andersen25f27032001-04-26 23:22:31 +00001173{
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00001174 const char *prompt_str;
1175 debug_printf("setup_prompt_string %d ", promptmode);
Denis Vlasenko38f63192007-01-22 09:03:07 +00001176#if !ENABLE_FEATURE_EDITING_FANCY_PROMPT
Eric Andersen25f27032001-04-26 23:22:31 +00001177 /* Set up the prompt */
Denis Vlasenko5a1437d2007-05-24 13:22:47 +00001178 if (promptmode == 0) { /* PS1 */
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00001179 free((char*)PS1);
Denis Vlasenko5a1437d2007-05-24 13:22:47 +00001180 PS1 = xasprintf("%s %c ", cwd, (geteuid() != 0) ? '$' : '#');
1181 prompt_str = PS1;
Eric Andersen25f27032001-04-26 23:22:31 +00001182 } else {
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00001183 prompt_str = PS2;
Eric Andersen25f27032001-04-26 23:22:31 +00001184 }
1185#else
Denis Vlasenko5a1437d2007-05-24 13:22:47 +00001186 prompt_str = (promptmode == 0) ? PS1 : PS2;
Eric Andersenaf44a0e2001-04-27 07:26:12 +00001187#endif
Denis Vlasenko5a1437d2007-05-24 13:22:47 +00001188 debug_printf("result '%s'\n", prompt_str);
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00001189 return prompt_str;
Eric Andersen25f27032001-04-26 23:22:31 +00001190}
1191
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001192static void get_user_input(struct in_str *i)
Eric Andersen25f27032001-04-26 23:22:31 +00001193{
Denis Vlasenko0937be52007-04-28 16:47:08 +00001194 int r;
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00001195 const char *prompt_str;
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001196
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00001197 prompt_str = setup_prompt_string(i->promptmode);
Denis Vlasenko38f63192007-01-22 09:03:07 +00001198#if ENABLE_FEATURE_EDITING
Denis Vlasenko170435c2007-05-23 13:01:10 +00001199 /* Enable command line editing only while a command line
1200 * is actually being read; otherwise, we'll end up bequeathing
1201 * atexit() handlers and other unwanted stuff to our
1202 * child processes (rob@sysgo.de) */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001203 r = read_line_input(prompt_str, user_input_buf, BUFSIZ-1, line_input_state);
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001204 i->eof_flag = (r < 0);
1205 if (i->eof_flag) { /* EOF/error detected */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001206 user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
1207 user_input_buf[1] = '\0';
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001208 }
Eric Andersen25f27032001-04-26 23:22:31 +00001209#else
1210 fputs(prompt_str, stdout);
1211 fflush(stdout);
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001212 user_input_buf[0] = r = fgetc(i->file);
1213 /*user_input_buf[1] = '\0'; - already is and never changed */
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001214 i->eof_flag = (r == EOF);
Eric Andersen25f27032001-04-26 23:22:31 +00001215#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001216 i->p = user_input_buf;
Eric Andersen25f27032001-04-26 23:22:31 +00001217}
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001218#endif /* INTERACTIVE */
Eric Andersen25f27032001-04-26 23:22:31 +00001219
Eric Andersenc7bda1c2004-03-15 08:29:22 +00001220/* This is the magic location that prints prompts
Eric Andersen25f27032001-04-26 23:22:31 +00001221 * and gets data back from the user */
1222static int file_get(struct in_str *i)
1223{
1224 int ch;
1225
Eric Andersen25f27032001-04-26 23:22:31 +00001226 /* If there is data waiting, eat it up */
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001227 if (i->p && *i->p) {
Denis Vlasenko96f67dc2007-05-17 13:02:41 +00001228#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001229 take_cached:
Denis Vlasenko96f67dc2007-05-17 13:02:41 +00001230#endif
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001231 ch = *i->p++;
1232 if (i->eof_flag && !*i->p)
1233 ch = EOF;
Eric Andersen25f27032001-04-26 23:22:31 +00001234 } else {
1235 /* need to double check i->file because we might be doing something
1236 * more complicated by now, like sourcing or substituting. */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001237#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko5a1437d2007-05-24 13:22:47 +00001238 if (interactive_fd && i->promptme && i->file == stdin) {
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001239 do {
1240 get_user_input(i);
1241 } while (!*i->p); /* need non-empty line */
Denis Vlasenko5a1437d2007-05-24 13:22:47 +00001242 i->promptmode = 1; /* PS2 */
1243 i->promptme = 0;
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001244 goto take_cached;
Eric Andersen25f27032001-04-26 23:22:31 +00001245 }
Denis Vlasenko96f67dc2007-05-17 13:02:41 +00001246#endif
1247 ch = fgetc(i->file);
Eric Andersen25f27032001-04-26 23:22:31 +00001248 }
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001249 debug_printf("file_get: got a '%c' %d\n", ch, ch);
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001250#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001251 if (ch == '\n')
Denis Vlasenko5a1437d2007-05-24 13:22:47 +00001252 i->promptme = 1;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001253#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001254 return ch;
1255}
1256
1257/* All the callers guarantee this routine will never be
1258 * used right after a newline, so prompting is not needed.
1259 */
1260static int file_peek(struct in_str *i)
1261{
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00001262 int ch;
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001263 if (i->p && *i->p) {
1264 if (i->eof_flag && !i->p[1])
1265 return EOF;
1266 return *i->p;
Eric Andersen25f27032001-04-26 23:22:31 +00001267 }
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00001268 ch = fgetc(i->file);
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001269 i->eof_flag = (ch == EOF);
1270 i->peek_buf[0] = ch;
1271 i->peek_buf[1] = '\0';
1272 i->p = i->peek_buf;
1273 debug_printf("file_peek: got a '%c' %d\n", *i->p, *i->p);
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00001274 return ch;
Eric Andersen25f27032001-04-26 23:22:31 +00001275}
1276
1277static void setup_file_in_str(struct in_str *i, FILE *f)
1278{
1279 i->peek = file_peek;
1280 i->get = file_get;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001281#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko5a1437d2007-05-24 13:22:47 +00001282 i->promptme = 1;
1283 i->promptmode = 0; /* PS1 */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001284#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001285 i->file = f;
1286 i->p = NULL;
1287}
1288
1289static void setup_string_in_str(struct in_str *i, const char *s)
1290{
1291 i->peek = static_peek;
1292 i->get = static_get;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001293#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko5a1437d2007-05-24 13:22:47 +00001294 i->promptme = 1;
1295 i->promptmode = 0; /* PS1 */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001296#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001297 i->p = s;
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00001298 i->eof_flag = 0;
Eric Andersen25f27032001-04-26 23:22:31 +00001299}
1300
Eric Andersen25f27032001-04-26 23:22:31 +00001301/* squirrel != NULL means we squirrel away copies of stdin, stdout,
1302 * and stderr if they are redirected. */
1303static int setup_redirects(struct child_prog *prog, int squirrel[])
1304{
1305 int openfd, mode;
1306 struct redir_struct *redir;
1307
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001308 for (redir = prog->redirects; redir; redir = redir->next) {
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001309 if (redir->dup == -1 && redir->glob_word == NULL) {
Eric Andersen817e73c2001-06-06 17:56:09 +00001310 /* something went wrong in the parse. Pretend it didn't happen */
1311 continue;
1312 }
Eric Andersen25f27032001-04-26 23:22:31 +00001313 if (redir->dup == -1) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001314 mode = redir_table[redir->type].mode;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001315 openfd = open_or_warn(redir->glob_word[0], mode);
Eric Andersen25f27032001-04-26 23:22:31 +00001316 if (openfd < 0) {
1317 /* this could get lost if stderr has been redirected, but
1318 bash and ash both lose it as well (though zsh doesn't!) */
Eric Andersen25f27032001-04-26 23:22:31 +00001319 return 1;
1320 }
1321 } else {
1322 openfd = redir->dup;
1323 }
1324
1325 if (openfd != redir->fd) {
1326 if (squirrel && redir->fd < 3) {
1327 squirrel[redir->fd] = dup(redir->fd);
1328 }
Eric Andersen83a2ae22001-05-07 17:59:25 +00001329 if (openfd == -3) {
Denis Vlasenko8412d792007-10-01 09:59:47 +00001330 //close(openfd); // close(-3) ??!
Eric Andersen83a2ae22001-05-07 17:59:25 +00001331 } else {
1332 dup2(openfd, redir->fd);
Matt Kraaic616e532001-06-05 16:50:08 +00001333 if (redir->dup == -1)
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00001334 close(openfd);
Eric Andersen83a2ae22001-05-07 17:59:25 +00001335 }
Eric Andersen25f27032001-04-26 23:22:31 +00001336 }
1337 }
1338 return 0;
1339}
1340
1341static void restore_redirects(int squirrel[])
1342{
1343 int i, fd;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001344 for (i = 0; i < 3; i++) {
Eric Andersen25f27032001-04-26 23:22:31 +00001345 fd = squirrel[i];
1346 if (fd != -1) {
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00001347 /* We simply die on error */
1348 xmove_fd(fd, i);
Eric Andersen25f27032001-04-26 23:22:31 +00001349 }
1350 }
1351}
1352
Denis Vlasenko8412d792007-10-01 09:59:47 +00001353/* Called after [v]fork() in run_pipe_real(), or from builtin_exec().
1354 * Never returns.
1355 * XXX no exit() here. If you don't exec, use _exit instead.
Eric Andersen94ac2442001-05-22 19:05:18 +00001356 * The at_exit handlers apparently confuse the calling process,
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00001357 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
Denis Vlasenko1359da62007-04-21 23:27:30 +00001358static void pseudo_exec_argv(char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00001359{
Eric Andersen78a7c992001-05-15 16:30:25 +00001360 int i, rcode;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00001361 char *p;
"Vladimir N. Oleynik"485d7cb2005-10-17 09:48:57 +00001362 const struct built_in_command *x;
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00001363
Denis Vlasenko1359da62007-04-21 23:27:30 +00001364 for (i = 0; is_assignment(argv[i]); i++) {
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001365 debug_printf_exec("pid %d environment modification: %s\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00001366 getpid(), argv[i]);
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001367// FIXME: vfork case??
Denis Vlasenko170435c2007-05-23 13:01:10 +00001368 p = expand_string_to_string(argv[i]);
1369 putenv(p);
Denis Vlasenko1359da62007-04-21 23:27:30 +00001370 }
1371 argv += i;
1372 /* If a variable is assigned in a forest, and nobody listens,
1373 * was it ever really set?
1374 */
1375 if (argv[0] == NULL) {
1376 _exit(EXIT_SUCCESS);
1377 }
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00001378
Denis Vlasenko170435c2007-05-23 13:01:10 +00001379 argv = expand_strvec_to_strvec(argv);
Denis Vlasenko764d59d2007-05-14 16:23:23 +00001380
Denis Vlasenko1359da62007-04-21 23:27:30 +00001381 /*
1382 * Check if the command matches any of the builtins.
1383 * Depending on context, this might be redundant. But it's
1384 * easier to waste a few CPU cycles than it is to figure out
1385 * if this is one of those cases.
1386 */
1387 for (x = bltins; x->cmd; x++) {
1388 if (strcmp(argv[0], x->cmd) == 0) {
Denis Vlasenko764d59d2007-05-14 16:23:23 +00001389 debug_printf_exec("running builtin '%s'\n", argv[0]);
Denis Vlasenko1359da62007-04-21 23:27:30 +00001390 rcode = x->function(argv);
1391 fflush(stdout);
1392 _exit(rcode);
Eric Andersen94ac2442001-05-22 19:05:18 +00001393 }
Denis Vlasenko1359da62007-04-21 23:27:30 +00001394 }
Eric Andersen78a7c992001-05-15 16:30:25 +00001395
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001396 /* Check if the command matches any busybox applets */
Denis Vlasenko80d14be2007-04-10 23:03:30 +00001397#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001398 if (strchr(argv[0], '/') == NULL) {
1399 const struct bb_applet *a = find_applet_by_name(argv[0]);
1400 if (a) {
1401 if (a->noexec) {
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001402 debug_printf_exec("running applet '%s'\n", argv[0]);
Denis Vlasenko82d38da2007-10-10 14:38:47 +00001403// is it ok that run_appletstruct_and_exit() does exit(), not _exit()?
1404 run_appletstruct_and_exit(a, argv);
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001405 }
1406 /* re-exec ourselves with the new arguments */
1407 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
Denis Vlasenkobdbbb7e2007-06-08 15:02:55 +00001408 execvp(bb_busybox_exec_path, argv);
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001409 /* If they called chroot or otherwise made the binary no longer
1410 * executable, fall through */
1411 }
1412 }
Eric Andersenaac75e52001-04-30 18:18:45 +00001413#endif
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001414
1415 debug_printf_exec("execing '%s'\n", argv[0]);
Denis Vlasenko1359da62007-04-21 23:27:30 +00001416 execvp(argv[0], argv);
1417 bb_perror_msg("cannot exec '%s'", argv[0]);
1418 _exit(1);
1419}
1420
Denis Vlasenko8412d792007-10-01 09:59:47 +00001421/* Called after [v]fork() in run_pipe_real()
1422 */
Denis Vlasenko1359da62007-04-21 23:27:30 +00001423static void pseudo_exec(struct child_prog *child)
1424{
Denis Vlasenkof2fffd02007-05-02 23:39:04 +00001425// FIXME: buggy wrt NOMMU! Must not modify any global data
1426// until it does exec/_exit, but currently it does.
Denis Vlasenko1359da62007-04-21 23:27:30 +00001427 int rcode;
1428
1429 if (child->argv) {
1430 pseudo_exec_argv(child->argv);
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00001431 }
1432
1433 if (child->group) {
Denis Vlasenko8412d792007-10-01 09:59:47 +00001434#if !BB_MMU
1435 bb_error_msg_and_exit("nested lists are not supported on NOMMU");
1436#else
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001437#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001438 debug_printf_exec("pseudo_exec: setting interactive_fd=0\n");
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001439 interactive_fd = 0; /* crucial!!!! */
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001440#endif
Denis Vlasenkod01ff132007-05-02 21:40:23 +00001441 debug_printf_exec("pseudo_exec: run_list_real\n");
Eric Andersen25f27032001-04-26 23:22:31 +00001442 rcode = run_list_real(child->group);
Eric Andersenbf7df042001-05-23 22:18:35 +00001443 /* OK to leak memory by not calling free_pipe_list,
Eric Andersen25f27032001-04-26 23:22:31 +00001444 * since this process is about to exit */
Eric Andersen94ac2442001-05-22 19:05:18 +00001445 _exit(rcode);
Denis Vlasenko8412d792007-10-01 09:59:47 +00001446#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001447 }
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00001448
1449 /* Can happen. See what bash does with ">foo" by itself. */
1450 debug_printf("trying to pseudo_exec null command\n");
1451 _exit(EXIT_SUCCESS);
Eric Andersen25f27032001-04-26 23:22:31 +00001452}
1453
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001454#if ENABLE_HUSH_JOB
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00001455static const char *get_cmdtext(struct pipe *pi)
1456{
1457 char **argv;
1458 char *p;
1459 int len;
1460
1461 /* This is subtle. ->cmdtext is created only on first backgrounding.
1462 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001463 * On subsequent bg argv is trashed, but we won't use it */
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00001464 if (pi->cmdtext)
1465 return pi->cmdtext;
1466 argv = pi->progs[0].argv;
1467 if (!argv || !argv[0])
1468 return (pi->cmdtext = xzalloc(1));
1469
1470 len = 0;
1471 do len += strlen(*argv) + 1; while (*++argv);
1472 pi->cmdtext = p = xmalloc(len);
1473 argv = pi->progs[0].argv;
1474 do {
1475 len = strlen(*argv);
1476 memcpy(p, *argv, len);
1477 p += len;
1478 *p++ = ' ';
1479 } while (*++argv);
1480 p[-1] = '\0';
1481 return pi->cmdtext;
1482}
1483
Eric Andersenbafd94f2001-05-02 16:11:59 +00001484static void insert_bg_job(struct pipe *pi)
1485{
1486 struct pipe *thejob;
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001487 int i;
Eric Andersenbafd94f2001-05-02 16:11:59 +00001488
1489 /* Linear search for the ID of the job to use */
1490 pi->jobid = 1;
Eric Andersenc798b072001-06-22 06:23:03 +00001491 for (thejob = job_list; thejob; thejob = thejob->next)
Eric Andersenbafd94f2001-05-02 16:11:59 +00001492 if (thejob->jobid >= pi->jobid)
1493 pi->jobid = thejob->jobid + 1;
1494
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001495 /* Add thejob to the list of running jobs */
Eric Andersenc798b072001-06-22 06:23:03 +00001496 if (!job_list) {
Eric Andersen52a97ca2001-06-22 06:49:26 +00001497 thejob = job_list = xmalloc(sizeof(*thejob));
Eric Andersenbafd94f2001-05-02 16:11:59 +00001498 } else {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001499 for (thejob = job_list; thejob->next; thejob = thejob->next)
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00001500 continue;
Eric Andersenbafd94f2001-05-02 16:11:59 +00001501 thejob->next = xmalloc(sizeof(*thejob));
1502 thejob = thejob->next;
1503 }
1504
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001505 /* Physically copy the struct job */
Eric Andersen0fcd4472001-05-02 20:12:03 +00001506 memcpy(thejob, pi, sizeof(struct pipe));
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001507 thejob->progs = xzalloc(sizeof(pi->progs[0]) * pi->num_progs);
1508 /* We cannot copy entire pi->progs[] vector! Double free()s will happen */
1509 for (i = 0; i < pi->num_progs; i++) {
1510// TODO: do we really need to have so many fields which are just dead weight
1511// at execution stage?
1512 thejob->progs[i].pid = pi->progs[i].pid;
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001513 /* all other fields are not used and stay zero */
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001514 }
Eric Andersenbafd94f2001-05-02 16:11:59 +00001515 thejob->next = NULL;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00001516 thejob->cmdtext = xstrdup(get_cmdtext(pi));
Eric Andersenbafd94f2001-05-02 16:11:59 +00001517
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001518 /* We don't wait for background thejobs to return -- append it
Eric Andersenbafd94f2001-05-02 16:11:59 +00001519 to the list of backgrounded thejobs and leave it alone */
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00001520 printf("[%d] %d %s\n", thejob->jobid, thejob->progs[0].pid, thejob->cmdtext);
Eric Andersen1a6d39b2001-05-08 05:11:54 +00001521 last_bg_pid = thejob->progs[0].pid;
Eric Andersenc798b072001-06-22 06:23:03 +00001522 last_jobid = thejob->jobid;
Eric Andersenbafd94f2001-05-02 16:11:59 +00001523}
1524
Eric Andersenbafd94f2001-05-02 16:11:59 +00001525static void remove_bg_job(struct pipe *pi)
1526{
1527 struct pipe *prev_pipe;
1528
Eric Andersenc798b072001-06-22 06:23:03 +00001529 if (pi == job_list) {
Eric Andersen52a97ca2001-06-22 06:49:26 +00001530 job_list = pi->next;
Eric Andersenbafd94f2001-05-02 16:11:59 +00001531 } else {
Eric Andersenc798b072001-06-22 06:23:03 +00001532 prev_pipe = job_list;
Eric Andersenbafd94f2001-05-02 16:11:59 +00001533 while (prev_pipe->next != pi)
1534 prev_pipe = prev_pipe->next;
1535 prev_pipe->next = pi->next;
1536 }
Eric Andersen028b65b2001-06-28 01:10:11 +00001537 if (job_list)
1538 last_jobid = job_list->jobid;
1539 else
1540 last_jobid = 0;
Denis Vlasenko1359da62007-04-21 23:27:30 +00001541}
Eric Andersen028b65b2001-06-28 01:10:11 +00001542
Denis Vlasenko1359da62007-04-21 23:27:30 +00001543/* remove a backgrounded job */
1544static void delete_finished_bg_job(struct pipe *pi)
1545{
1546 remove_bg_job(pi);
Eric Andersen52a97ca2001-06-22 06:49:26 +00001547 pi->stopped_progs = 0;
Eric Andersenbf7df042001-05-23 22:18:35 +00001548 free_pipe(pi, 0);
Eric Andersenbafd94f2001-05-02 16:11:59 +00001549 free(pi);
1550}
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001551#endif /* JOB */
Eric Andersenbafd94f2001-05-02 16:11:59 +00001552
Eric Andersenc7bda1c2004-03-15 08:29:22 +00001553/* Checks to see if any processes have exited -- if they
Eric Andersenbafd94f2001-05-02 16:11:59 +00001554 have, figure out why and see if a job has completed */
Eric Andersenc798b072001-06-22 06:23:03 +00001555static int checkjobs(struct pipe* fg_pipe)
Eric Andersenbafd94f2001-05-02 16:11:59 +00001556{
Eric Andersenc798b072001-06-22 06:23:03 +00001557 int attributes;
1558 int status;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001559#if ENABLE_HUSH_JOB
Eric Andersenbafd94f2001-05-02 16:11:59 +00001560 int prognum = 0;
1561 struct pipe *pi;
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001562#endif
Eric Andersenbafd94f2001-05-02 16:11:59 +00001563 pid_t childpid;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001564 int rcode = 0;
Eric Andersenbafd94f2001-05-02 16:11:59 +00001565
Eric Andersenc798b072001-06-22 06:23:03 +00001566 attributes = WUNTRACED;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001567 if (fg_pipe == NULL) {
Eric Andersenc798b072001-06-22 06:23:03 +00001568 attributes |= WNOHANG;
1569 }
1570
Denis Vlasenko1359da62007-04-21 23:27:30 +00001571/* Do we do this right?
1572 * bash-3.00# sleep 20 | false
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001573 * <ctrl-Z pressed>
Denis Vlasenko1359da62007-04-21 23:27:30 +00001574 * [3]+ Stopped sleep 20 | false
1575 * bash-3.00# echo $?
1576 * 1 <========== bg pipe is not fully done, but exitcode is already known!
1577 */
1578
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001579//FIXME: non-interactive bash does not continue even if all processes in fg pipe
1580//are stopped. Testcase: "cat | cat" in a script (not on command line)
1581// + killall -STOP cat
1582
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001583 wait_more:
Eric Andersenc798b072001-06-22 06:23:03 +00001584 while ((childpid = waitpid(-1, &status, attributes)) > 0) {
Denis Vlasenko1359da62007-04-21 23:27:30 +00001585 const int dead = WIFEXITED(status) || WIFSIGNALED(status);
1586
1587#ifdef DEBUG_SHELL_JOBS
1588 if (WIFSTOPPED(status))
Denis Vlasenkod01ff132007-05-02 21:40:23 +00001589 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00001590 childpid, WSTOPSIG(status), WEXITSTATUS(status));
1591 if (WIFSIGNALED(status))
Denis Vlasenkod01ff132007-05-02 21:40:23 +00001592 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00001593 childpid, WTERMSIG(status), WEXITSTATUS(status));
1594 if (WIFEXITED(status))
Denis Vlasenkod01ff132007-05-02 21:40:23 +00001595 debug_printf_jobs("pid %d exited, exitcode %d\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00001596 childpid, WEXITSTATUS(status));
1597#endif
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001598 /* Were we asked to wait for fg pipe? */
Eric Andersenc798b072001-06-22 06:23:03 +00001599 if (fg_pipe) {
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001600 int i;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001601 for (i = 0; i < fg_pipe->num_progs; i++) {
Denis Vlasenkod01ff132007-05-02 21:40:23 +00001602 debug_printf_jobs("check pid %d\n", fg_pipe->progs[i].pid);
Eric Andersenc798b072001-06-22 06:23:03 +00001603 if (fg_pipe->progs[i].pid == childpid) {
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001604 /* printf("process %d exit %d\n", i, WEXITSTATUS(status)); */
Denis Vlasenko1359da62007-04-21 23:27:30 +00001605 if (dead) {
1606 fg_pipe->progs[i].pid = 0;
1607 fg_pipe->running_progs--;
1608 if (i == fg_pipe->num_progs-1)
1609 /* last process gives overall exitstatus */
1610 rcode = WEXITSTATUS(status);
1611 } else {
1612 fg_pipe->progs[i].is_stopped = 1;
1613 fg_pipe->stopped_progs++;
1614 }
Denis Vlasenkod01ff132007-05-02 21:40:23 +00001615 debug_printf_jobs("fg_pipe: running_progs %d stopped_progs %d\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00001616 fg_pipe->running_progs, fg_pipe->stopped_progs);
1617 if (fg_pipe->running_progs - fg_pipe->stopped_progs <= 0) {
1618 /* All processes in fg pipe have exited/stopped */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001619#if ENABLE_HUSH_JOB
Denis Vlasenko1359da62007-04-21 23:27:30 +00001620 if (fg_pipe->running_progs)
1621 insert_bg_job(fg_pipe);
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001622#endif
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001623 return rcode;
Denis Vlasenko1359da62007-04-21 23:27:30 +00001624 }
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001625 /* There are still running processes in the fg pipe */
1626 goto wait_more;
Eric Andersenc798b072001-06-22 06:23:03 +00001627 }
1628 }
Denis Vlasenko1359da62007-04-21 23:27:30 +00001629 /* fall through to searching process in bg pipes */
Eric Andersenc798b072001-06-22 06:23:03 +00001630 }
1631
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001632#if ENABLE_HUSH_JOB
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001633 /* We asked to wait for bg or orphaned children */
1634 /* No need to remember exitcode in this case */
Eric Andersenc798b072001-06-22 06:23:03 +00001635 for (pi = job_list; pi; pi = pi->next) {
Eric Andersenbafd94f2001-05-02 16:11:59 +00001636 prognum = 0;
Denis Vlasenko5f786c22007-04-20 08:35:45 +00001637 while (prognum < pi->num_progs) {
1638 if (pi->progs[prognum].pid == childpid)
1639 goto found_pi_and_prognum;
Eric Andersen52a97ca2001-06-22 06:49:26 +00001640 prognum++;
1641 }
Eric Andersenbafd94f2001-05-02 16:11:59 +00001642 }
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001643#endif
Eric Andersenbafd94f2001-05-02 16:11:59 +00001644
Denis Vlasenko5f786c22007-04-20 08:35:45 +00001645 /* Happens when shell is used as init process (init=/bin/sh) */
1646 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
Denis Vlasenko1359da62007-04-21 23:27:30 +00001647 goto wait_more;
Eric Andersenaeb44c42001-05-22 20:29:00 +00001648
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001649#if ENABLE_HUSH_JOB
Denis Vlasenko5f786c22007-04-20 08:35:45 +00001650 found_pi_and_prognum:
Denis Vlasenko1359da62007-04-21 23:27:30 +00001651 if (dead) {
Eric Andersenbafd94f2001-05-02 16:11:59 +00001652 /* child exited */
Eric Andersenbafd94f2001-05-02 16:11:59 +00001653 pi->progs[prognum].pid = 0;
Denis Vlasenko1359da62007-04-21 23:27:30 +00001654 pi->running_progs--;
Eric Andersenbafd94f2001-05-02 16:11:59 +00001655 if (!pi->running_progs) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001656 printf(JOB_STATUS_FORMAT, pi->jobid,
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00001657 "Done", pi->cmdtext);
Denis Vlasenko1359da62007-04-21 23:27:30 +00001658 delete_finished_bg_job(pi);
Eric Andersenbafd94f2001-05-02 16:11:59 +00001659 }
1660 } else {
1661 /* child stopped */
1662 pi->stopped_progs++;
1663 pi->progs[prognum].is_stopped = 1;
Eric Andersenbafd94f2001-05-02 16:11:59 +00001664 }
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001665#endif
Eric Andersenbafd94f2001-05-02 16:11:59 +00001666 }
1667
Denis Vlasenko1359da62007-04-21 23:27:30 +00001668 /* wait found no children or failed */
1669
1670 if (childpid && errno != ECHILD)
Manuel Novoa III cad53642003-03-19 09:13:01 +00001671 bb_perror_msg("waitpid");
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001672 return rcode;
Eric Andersenada18ff2001-05-21 16:18:22 +00001673}
1674
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001675#if ENABLE_HUSH_JOB
Denis Vlasenko52881e92007-04-21 13:42:52 +00001676static int checkjobs_and_fg_shell(struct pipe* fg_pipe)
1677{
1678 pid_t p;
1679 int rcode = checkjobs(fg_pipe);
1680 /* Job finished, move the shell to the foreground */
Denis Vlasenko170435c2007-05-23 13:01:10 +00001681 p = getpgid(0); /* pgid of our process */
1682 debug_printf_jobs("fg'ing ourself: getpgid(0)=%d\n", (int)p);
Denis Vlasenko52881e92007-04-21 13:42:52 +00001683 if (tcsetpgrp(interactive_fd, p) && errno != ENOTTY)
1684 bb_perror_msg("tcsetpgrp-4a");
1685 return rcode;
1686}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001687#endif
Denis Vlasenko52881e92007-04-21 13:42:52 +00001688
Eric Andersen25f27032001-04-26 23:22:31 +00001689/* run_pipe_real() starts all the jobs, but doesn't wait for anything
Eric Andersenc798b072001-06-22 06:23:03 +00001690 * to finish. See checkjobs().
Eric Andersen25f27032001-04-26 23:22:31 +00001691 *
1692 * return code is normally -1, when the caller has to wait for children
1693 * to finish to determine the exit status of the pipe. If the pipe
1694 * is a simple builtin command, however, the action is done by the
1695 * time run_pipe_real returns, and the exit code is provided as the
1696 * return value.
1697 *
1698 * The input of the pipe is always stdin, the output is always
1699 * stdout. The outpipe[] mechanism in BusyBox-0.48 lash is bogus,
1700 * because it tries to avoid running the command substitution in
1701 * subshell, when that is in fact necessary. The subshell process
1702 * now has its stdout directed to the input of the appropriate pipe,
1703 * so this routine is noticeably simpler.
Denis Vlasenko170435c2007-05-23 13:01:10 +00001704 *
1705 * Returns -1 only if started some children. IOW: we have to
1706 * mask out retvals of builtins etc with 0xff!
Eric Andersen25f27032001-04-26 23:22:31 +00001707 */
1708static int run_pipe_real(struct pipe *pi)
1709{
1710 int i;
1711 int nextin, nextout;
1712 int pipefds[2]; /* pipefds[0] is for reading */
Rob Landley53702e52006-07-19 21:43:53 +00001713 struct child_prog *child;
"Vladimir N. Oleynik"485d7cb2005-10-17 09:48:57 +00001714 const struct built_in_command *x;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00001715 char *p;
Denis Vlasenkof5294e12007-04-14 10:09:57 +00001716 /* it is not always needed, but we aim to smaller code */
1717 int squirrel[] = { -1, -1, -1 };
1718 int rcode;
Denis Vlasenko52881e92007-04-21 13:42:52 +00001719 const int single_fg = (pi->num_progs == 1 && pi->followup != PIPE_BG);
Eric Andersen25f27032001-04-26 23:22:31 +00001720
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001721 debug_printf_exec("run_pipe_real start: single_fg=%d\n", single_fg);
Denis Vlasenko4ac530c2007-05-02 15:35:45 +00001722
Eric Andersen25f27032001-04-26 23:22:31 +00001723 nextin = 0;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001724#if ENABLE_HUSH_JOB
Eric Andersenada18ff2001-05-21 16:18:22 +00001725 pi->pgrp = -1;
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001726#endif
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001727 pi->running_progs = 1;
Denis Vlasenko1359da62007-04-21 23:27:30 +00001728 pi->stopped_progs = 0;
Eric Andersen25f27032001-04-26 23:22:31 +00001729
1730 /* Check if this is a simple builtin (not part of a pipe).
1731 * Builtins within pipes have to fork anyway, and are handled in
1732 * pseudo_exec. "echo foo | read bar" doesn't work on bash, either.
1733 */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001734 child = &(pi->progs[0]);
Denis Vlasenko52881e92007-04-21 13:42:52 +00001735 if (single_fg && child->group && child->subshell == 0) {
Eric Andersen04407e52001-06-07 16:42:05 +00001736 debug_printf("non-subshell grouping\n");
1737 setup_redirects(child, squirrel);
Denis Vlasenkod01ff132007-05-02 21:40:23 +00001738 debug_printf_exec(": run_list_real\n");
Eric Andersen04407e52001-06-07 16:42:05 +00001739 rcode = run_list_real(child->group);
1740 restore_redirects(squirrel);
Denis Vlasenkod01ff132007-05-02 21:40:23 +00001741 debug_printf_exec("run_pipe_real return %d\n", rcode);
Denis Vlasenko170435c2007-05-23 13:01:10 +00001742 return rcode; // do we need to add '... & 0xff' ?
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00001743 }
1744
Denis Vlasenko1359da62007-04-21 23:27:30 +00001745 if (single_fg && child->argv != NULL) {
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001746 char **argv_expanded;
Denis Vlasenko1359da62007-04-21 23:27:30 +00001747 char **argv = child->argv;
1748
1749 for (i = 0; is_assignment(argv[i]); i++)
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00001750 continue;
Denis Vlasenko1359da62007-04-21 23:27:30 +00001751 if (i != 0 && argv[i] == NULL) {
Eric Andersen78a7c992001-05-15 16:30:25 +00001752 /* assignments, but no command: set the local environment */
Denis Vlasenko1359da62007-04-21 23:27:30 +00001753 for (i = 0; argv[i] != NULL; i++) {
Denis Vlasenkod76c0492007-05-25 02:16:25 +00001754 debug_printf("local environment set: %s\n", argv[i]);
Denis Vlasenko170435c2007-05-23 13:01:10 +00001755 p = expand_string_to_string(argv[i]);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00001756 set_local_var(p, 0);
Eric Andersen78a7c992001-05-15 16:30:25 +00001757 }
1758 return EXIT_SUCCESS; /* don't worry about errors in set_local_var() yet */
1759 }
Denis Vlasenko1359da62007-04-21 23:27:30 +00001760 for (i = 0; is_assignment(argv[i]); i++) {
Denis Vlasenko170435c2007-05-23 13:01:10 +00001761 p = expand_string_to_string(argv[i]);
1762 //sp: child->sp--;
1763 putenv(p);
Eric Andersen4c9b68f2002-04-13 12:33:41 +00001764 }
Eric Andersen25f27032001-04-26 23:22:31 +00001765 for (x = bltins; x->cmd; x++) {
Denis Vlasenko1359da62007-04-21 23:27:30 +00001766 if (strcmp(argv[i], x->cmd) == 0) {
1767 if (x->function == builtin_exec && argv[i+1] == NULL) {
Eric Andersen83a2ae22001-05-07 17:59:25 +00001768 debug_printf("magic exec\n");
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00001769 setup_redirects(child, NULL);
Eric Andersen83a2ae22001-05-07 17:59:25 +00001770 return EXIT_SUCCESS;
1771 }
Denis Vlasenko1359da62007-04-21 23:27:30 +00001772 debug_printf("builtin inline %s\n", argv[0]);
Eric Andersen25f27032001-04-26 23:22:31 +00001773 /* XXX setup_redirects acts on file descriptors, not FILEs.
1774 * This is perfect for work that comes after exec().
1775 * Is it really safe for inline use? Experimentally,
1776 * things seem to work with glibc. */
1777 setup_redirects(child, squirrel);
Denis Vlasenkod01ff132007-05-02 21:40:23 +00001778 debug_printf_exec(": builtin '%s' '%s'...\n", x->cmd, argv[i+1]);
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001779 //sp: if (child->sp) /* btw we can do it unconditionally... */
Denis Vlasenko170435c2007-05-23 13:01:10 +00001780 argv_expanded = expand_strvec_to_strvec(argv + i);
1781 rcode = x->function(argv_expanded) & 0xff;
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001782 free(argv_expanded);
Eric Andersen25f27032001-04-26 23:22:31 +00001783 restore_redirects(squirrel);
Denis Vlasenkod01ff132007-05-02 21:40:23 +00001784 debug_printf_exec("run_pipe_real return %d\n", rcode);
Eric Andersen25f27032001-04-26 23:22:31 +00001785 return rcode;
1786 }
1787 }
Denis Vlasenkof5294e12007-04-14 10:09:57 +00001788#if ENABLE_FEATURE_SH_STANDALONE
1789 {
Denis Vlasenko1359da62007-04-21 23:27:30 +00001790 const struct bb_applet *a = find_applet_by_name(argv[i]);
Denis Vlasenkof5294e12007-04-14 10:09:57 +00001791 if (a && a->nofork) {
1792 setup_redirects(child, squirrel);
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001793 save_nofork_data(&nofork_save);
Denis Vlasenko764d59d2007-05-14 16:23:23 +00001794 argv_expanded = argv + i;
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001795 //sp: if (child->sp)
Denis Vlasenko170435c2007-05-23 13:01:10 +00001796 argv_expanded = expand_strvec_to_strvec(argv + i);
Denis Vlasenko764d59d2007-05-14 16:23:23 +00001797 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n", argv_expanded[0], argv_expanded[1]);
Denis Vlasenko170435c2007-05-23 13:01:10 +00001798 rcode = run_nofork_applet_prime(&nofork_save, a, argv_expanded) & 0xff;
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001799 free(argv_expanded);
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00001800 restore_redirects(squirrel);
Denis Vlasenkod01ff132007-05-02 21:40:23 +00001801 debug_printf_exec("run_pipe_real return %d\n", rcode);
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00001802 return rcode;
Denis Vlasenkof5294e12007-04-14 10:09:57 +00001803 }
1804 }
1805#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001806 }
1807
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00001808 /* Going to fork a child per each pipe member */
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001809 pi->running_progs = 0;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00001810
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001811 /* Disable job control signals for shell (parent) and
1812 * for initial child code after fork */
1813 set_jobctrl_sighandler(SIG_IGN);
1814
Eric Andersen25f27032001-04-26 23:22:31 +00001815 for (i = 0; i < pi->num_progs; i++) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001816 child = &(pi->progs[i]);
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001817 if (child->argv)
1818 debug_printf_exec(": pipe member '%s' '%s'...\n", child->argv[0], child->argv[1]);
1819 else
1820 debug_printf_exec(": pipe member with no argv\n");
Eric Andersen25f27032001-04-26 23:22:31 +00001821
1822 /* pipes are inserted between pairs of commands */
1823 if ((i + 1) < pi->num_progs) {
Denis Vlasenko5a6aedd2007-05-26 16:44:20 +00001824 pipe(pipefds);
Eric Andersen25f27032001-04-26 23:22:31 +00001825 nextout = pipefds[1];
1826 } else {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001827 nextout = 1;
Eric Andersen25f27032001-04-26 23:22:31 +00001828 pipefds[0] = -1;
1829 }
1830
1831 /* XXX test for failed fork()? */
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00001832#if BB_MMU
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001833 child->pid = fork();
Eric Andersen72f9a422001-10-28 05:12:20 +00001834#else
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001835 child->pid = vfork();
Eric Andersen72f9a422001-10-28 05:12:20 +00001836#endif
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001837 if (!child->pid) { /* child */
1838 /* Every child adds itself to new process group
1839 * with pgid == pid of first child in pipe */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001840#if ENABLE_HUSH_JOB
Denis Vlasenko170435c2007-05-23 13:01:10 +00001841 if (run_list_level == 1 && interactive_fd) {
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00001842 /* Don't do pgrp restore anymore on fatal signals */
1843 set_fatal_sighandler(SIG_DFL);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001844 if (pi->pgrp < 0) /* true for 1st process only */
1845 pi->pgrp = getpid();
1846 if (setpgid(0, pi->pgrp) == 0 && pi->followup != PIPE_BG) {
1847 /* We do it in *every* child, not just first,
1848 * to avoid races */
1849 tcsetpgrp(interactive_fd, pi->pgrp);
1850 }
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001851 }
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001852#endif
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001853 /* in non-interactive case fatal sigs are already SIG_DFL */
Denis Vlasenko8412d792007-10-01 09:59:47 +00001854 xmove_fd(nextin, 0);
1855 xmove_fd(nextout, 1);
Denis Vlasenkobb81c582007-01-30 22:32:09 +00001856 if (pipefds[0] != -1) {
Eric Andersen25f27032001-04-26 23:22:31 +00001857 close(pipefds[0]); /* opposite end of our output pipe */
1858 }
Eric Andersen25f27032001-04-26 23:22:31 +00001859 /* Like bash, explicit redirects override pipes,
1860 * and the pipe fd is available for dup'ing. */
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00001861 setup_redirects(child, NULL);
Eric Andersen52a97ca2001-06-22 06:49:26 +00001862
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001863 /* Restore default handlers just prior to exec */
1864 set_jobctrl_sighandler(SIG_DFL);
1865 set_misc_sighandler(SIG_DFL);
1866 signal(SIGCHLD, SIG_DFL);
Eric Andersen25f27032001-04-26 23:22:31 +00001867 pseudo_exec(child);
1868 }
Eric Andersenc7bda1c2004-03-15 08:29:22 +00001869
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001870 pi->running_progs++;
1871
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001872#if ENABLE_HUSH_JOB
Denis Vlasenko2f1bb362007-04-21 10:01:14 +00001873 /* Second and next children need to know pid of first one */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001874 if (pi->pgrp < 0)
Eric Andersen0fcd4472001-05-02 20:12:03 +00001875 pi->pgrp = child->pid;
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001876#endif
Eric Andersen25f27032001-04-26 23:22:31 +00001877 if (nextin != 0)
1878 close(nextin);
1879 if (nextout != 1)
1880 close(nextout);
1881
Eric Andersenc7bda1c2004-03-15 08:29:22 +00001882 /* If there isn't another process, nextin is garbage
Eric Andersen25f27032001-04-26 23:22:31 +00001883 but it doesn't matter */
1884 nextin = pipefds[0];
1885 }
Denis Vlasenkod01ff132007-05-02 21:40:23 +00001886 debug_printf_exec("run_pipe_real return -1\n");
Eric Andersen25f27032001-04-26 23:22:31 +00001887 return -1;
1888}
1889
Denis Vlasenko4b924f32007-05-30 00:29:55 +00001890#ifndef debug_print_tree
Denis Vlasenko400c5b62007-05-04 13:07:27 +00001891static void debug_print_tree(struct pipe *pi, int lvl)
1892{
1893 static const char *PIPE[] = {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001894 [PIPE_SEQ] = "SEQ",
1895 [PIPE_AND] = "AND",
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001896 [PIPE_OR ] = "OR" ,
1897 [PIPE_BG ] = "BG" ,
Denis Vlasenko400c5b62007-05-04 13:07:27 +00001898 };
1899 static const char *RES[] = {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001900 [RES_NONE ] = "NONE" ,
Denis Vlasenko06810332007-05-21 23:30:54 +00001901#if ENABLE_HUSH_IF
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001902 [RES_IF ] = "IF" ,
1903 [RES_THEN ] = "THEN" ,
1904 [RES_ELIF ] = "ELIF" ,
1905 [RES_ELSE ] = "ELSE" ,
1906 [RES_FI ] = "FI" ,
Denis Vlasenko06810332007-05-21 23:30:54 +00001907#endif
1908#if ENABLE_HUSH_LOOPS
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001909 [RES_FOR ] = "FOR" ,
1910 [RES_WHILE] = "WHILE",
1911 [RES_UNTIL] = "UNTIL",
1912 [RES_DO ] = "DO" ,
1913 [RES_DONE ] = "DONE" ,
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001914 [RES_IN ] = "IN" ,
Denis Vlasenko06810332007-05-21 23:30:54 +00001915#endif
1916 [RES_XXXX ] = "XXXX" ,
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001917 [RES_SNTX ] = "SNTX" ,
Denis Vlasenko400c5b62007-05-04 13:07:27 +00001918 };
1919
1920 int pin, prn;
Denis Vlasenko219e88d2007-05-21 10:18:23 +00001921
Denis Vlasenko400c5b62007-05-04 13:07:27 +00001922 pin = 0;
1923 while (pi) {
Denis Vlasenko219e88d2007-05-21 10:18:23 +00001924 fprintf(stderr, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
1925 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
Denis Vlasenko400c5b62007-05-04 13:07:27 +00001926 prn = 0;
1927 while (prn < pi->num_progs) {
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00001928 struct child_prog *child = &pi->progs[prn];
1929 char **argv = child->argv;
1930
Denis Vlasenko400c5b62007-05-04 13:07:27 +00001931 fprintf(stderr, "%*s prog %d", lvl*2, "", prn);
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00001932 if (child->group) {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001933 fprintf(stderr, " group %s: (argv=%p)\n",
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00001934 (child->subshell ? "()" : "{}"),
1935 argv);
1936 debug_print_tree(child->group, lvl+1);
Denis Vlasenko400c5b62007-05-04 13:07:27 +00001937 prn++;
1938 continue;
1939 }
Denis Vlasenko400c5b62007-05-04 13:07:27 +00001940 if (argv) while (*argv) {
1941 fprintf(stderr, " '%s'", *argv);
1942 argv++;
Denis Vlasenko4b924f32007-05-30 00:29:55 +00001943 }
Denis Vlasenko400c5b62007-05-04 13:07:27 +00001944 fprintf(stderr, "\n");
1945 prn++;
1946 }
1947 pi = pi->next;
1948 pin++;
1949 }
1950}
1951#endif
1952
Denis Vlasenkoc666f712007-05-16 22:18:54 +00001953/* NB: called by pseudo_exec, and therefore must not modify any
1954 * global data until exec/_exit (we can be a child after vfork!) */
Eric Andersen25f27032001-04-26 23:22:31 +00001955static int run_list_real(struct pipe *pi)
1956{
Denis Vlasenko06810332007-05-21 23:30:54 +00001957 struct pipe *rpipe;
1958#if ENABLE_HUSH_LOOPS
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00001959 char *for_varname = NULL;
1960 char **for_lcur = NULL;
1961 char **for_list = NULL;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00001962 int flag_rep = 0;
Denis Vlasenko06810332007-05-21 23:30:54 +00001963#endif
Eric Andersen4c9b68f2002-04-13 12:33:41 +00001964 int save_num_progs;
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00001965 int flag_skip = 1;
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00001966 int rcode = 0; /* probably for gcc only */
Eric Andersen4c9b68f2002-04-13 12:33:41 +00001967 int flag_restore = 0;
Denis Vlasenko06810332007-05-21 23:30:54 +00001968#if ENABLE_HUSH_IF
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001969 int if_code = 0, next_if_code = 0; /* need double-buffer to handle elif */
Denis Vlasenko06810332007-05-21 23:30:54 +00001970#else
1971 enum { if_code = 0, next_if_code = 0 };
1972#endif
Denis Vlasenko219e88d2007-05-21 10:18:23 +00001973 reserved_style rword;
1974 reserved_style skip_more_for_this_rword = RES_XXXX;
Denis Vlasenko4ac530c2007-05-02 15:35:45 +00001975
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001976 debug_printf_exec("run_list_real start lvl %d\n", run_list_level + 1);
Denis Vlasenko4ac530c2007-05-02 15:35:45 +00001977
Denis Vlasenko06810332007-05-21 23:30:54 +00001978#if ENABLE_HUSH_LOOPS
Eric Andersen4c9b68f2002-04-13 12:33:41 +00001979 /* check syntax for "for" */
1980 for (rpipe = pi; rpipe; rpipe = rpipe->next) {
Denis Vlasenko219e88d2007-05-21 10:18:23 +00001981 if ((rpipe->res_word == RES_IN || rpipe->res_word == RES_FOR)
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001982 && (rpipe->next == NULL)
1983 ) {
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001984 syntax("malformed for"); /* no IN or no commands after IN */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001985 debug_printf_exec("run_list_real lvl %d return 1\n", run_list_level);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001986 return 1;
Eric Andersenc7bda1c2004-03-15 08:29:22 +00001987 }
Denis Vlasenko219e88d2007-05-21 10:18:23 +00001988 if ((rpipe->res_word == RES_IN && rpipe->next->res_word == RES_IN && rpipe->next->progs[0].argv != NULL)
1989 || (rpipe->res_word == RES_FOR && rpipe->next->res_word != RES_IN)
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001990 ) {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00001991 /* TODO: what is tested in the first condition? */
Denis Vlasenko90e485c2007-05-23 15:22:50 +00001992 syntax("malformed for"); /* 2nd condition: not followed by IN */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00001993 debug_printf_exec("run_list_real lvl %d return 1\n", run_list_level);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00001994 return 1;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00001995 }
1996 }
Denis Vlasenko06810332007-05-21 23:30:54 +00001997#else
1998 rpipe = NULL;
1999#endif
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002000
2001#if ENABLE_HUSH_JOB
2002 /* Example of nested list: "while true; do { sleep 1 | exit 2; } done".
2003 * We are saving state before entering outermost list ("while...done")
2004 * so that ctrl-Z will correctly background _entire_ outermost list,
2005 * not just a part of it (like "sleep 1 | exit 2") */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00002006 if (++run_list_level == 1 && interactive_fd) {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002007 if (sigsetjmp(toplevel_jb, 1)) {
2008 /* ctrl-Z forked and we are parent; or ctrl-C.
2009 * Sighandler has longjmped us here */
2010 signal(SIGINT, SIG_IGN);
2011 signal(SIGTSTP, SIG_IGN);
2012 /* Restore level (we can be coming from deep inside
2013 * nested levels) */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00002014 run_list_level = 1;
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002015#if ENABLE_FEATURE_SH_STANDALONE
2016 if (nofork_save.saved) { /* if save area is valid */
2017 debug_printf_jobs("exiting nofork early\n");
2018 restore_nofork_data(&nofork_save);
2019 }
2020#endif
2021 if (ctrl_z_flag) {
2022 /* ctrl-Z has forked and stored pid of the child in pi->pid.
2023 * Remember this child as background job */
2024 insert_bg_job(pi);
2025 } else {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002026 /* ctrl-C. We just stop doing whatever we were doing */
Denis Vlasenko4daad902007-09-27 10:20:47 +00002027 bb_putchar('\n');
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002028 }
2029 rcode = 0;
2030 goto ret;
2031 }
2032 /* ctrl-Z handler will store pid etc in pi */
2033 toplevel_list = pi;
2034 ctrl_z_flag = 0;
2035#if ENABLE_FEATURE_SH_STANDALONE
2036 nofork_save.saved = 0; /* in case we will run a nofork later */
2037#endif
2038 signal_SA_RESTART(SIGTSTP, handler_ctrl_z);
2039 signal(SIGINT, handler_ctrl_c);
2040 }
2041#endif
2042
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002043 for (; pi; pi = flag_restore ? rpipe : pi->next) {
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002044 rword = pi->res_word;
Denis Vlasenko06810332007-05-21 23:30:54 +00002045#if ENABLE_HUSH_LOOPS
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002046 if (rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002047 flag_restore = 0;
2048 if (!rpipe) {
2049 flag_rep = 0;
2050 rpipe = pi;
2051 }
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002052 }
Denis Vlasenko06810332007-05-21 23:30:54 +00002053#endif
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002054 debug_printf_exec(": rword=%d if_code=%d next_if_code=%d skip_more=%d\n",
2055 rword, if_code, next_if_code, skip_more_for_this_rword);
2056 if (rword == skip_more_for_this_rword && flag_skip) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002057 if (pi->followup == PIPE_SEQ)
2058 flag_skip = 0;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002059 continue;
2060 }
2061 flag_skip = 1;
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002062 skip_more_for_this_rword = RES_XXXX;
Denis Vlasenko06810332007-05-21 23:30:54 +00002063#if ENABLE_HUSH_IF
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002064 if (rword == RES_THEN || rword == RES_ELSE)
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002065 if_code = next_if_code;
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002066 if (rword == RES_THEN && if_code)
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002067 continue;
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002068 if (rword == RES_ELSE && !if_code)
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002069 continue;
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002070 if (rword == RES_ELIF && !if_code)
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002071 break;
Denis Vlasenko06810332007-05-21 23:30:54 +00002072#endif
2073#if ENABLE_HUSH_LOOPS
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002074 if (rword == RES_FOR && pi->num_progs) {
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002075 if (!for_lcur) {
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002076 /* first loop through for */
Eric Andersenc7bda1c2004-03-15 08:29:22 +00002077 /* if no variable values after "in" we skip "for" */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002078 if (!pi->next->progs->argv)
2079 continue;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002080 /* create list of variable values */
Denis Vlasenko170435c2007-05-23 13:01:10 +00002081 for_list = expand_strvec_to_strvec(pi->next->progs->argv);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002082 for_lcur = for_list;
2083 for_varname = pi->progs->argv[0];
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002084 pi->progs->argv[0] = NULL;
2085 flag_rep = 1;
Eric Andersenc7bda1c2004-03-15 08:29:22 +00002086 }
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002087 free(pi->progs->argv[0]);
2088 if (!*for_lcur) {
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002089 /* for loop is over, clean up */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002090 free(for_list);
2091 for_lcur = NULL;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002092 flag_rep = 0;
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002093 pi->progs->argv[0] = for_varname;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002094 continue;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002095 }
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002096 /* insert next value from for_lcur */
Denis Vlasenko764d59d2007-05-14 16:23:23 +00002097 /* vda: does it need escaping? */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002098 pi->progs->argv[0] = xasprintf("%s=%s", for_varname, *for_lcur++);
Eric Andersenc7bda1c2004-03-15 08:29:22 +00002099 }
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002100 if (rword == RES_IN)
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002101 continue;
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002102 if (rword == RES_DO) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002103 if (!flag_rep)
2104 continue;
Tim Rikerc1ef7bd2006-01-25 00:08:53 +00002105 }
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002106 if (rword == RES_DONE) {
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002107 if (flag_rep) {
2108 flag_restore = 1;
2109 } else {
2110 rpipe = NULL;
2111 }
Eric Andersenc7bda1c2004-03-15 08:29:22 +00002112 }
Denis Vlasenko06810332007-05-21 23:30:54 +00002113#endif
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002114 if (pi->num_progs == 0)
2115 continue;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002116 save_num_progs = pi->num_progs; /* save number of programs */
Denis Vlasenkod01ff132007-05-02 21:40:23 +00002117 debug_printf_exec(": run_pipe_real with %d members\n", pi->num_progs);
Eric Andersen25f27032001-04-26 23:22:31 +00002118 rcode = run_pipe_real(pi);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002119 if (rcode != -1) {
Eric Andersen25f27032001-04-26 23:22:31 +00002120 /* We only ran a builtin: rcode was set by the return value
2121 * of run_pipe_real(), and we don't need to wait for anything. */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002122 } else if (pi->followup == PIPE_BG) {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002123 /* What does bash do with attempts to background builtins? */
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002124 /* Even bash 3.2 doesn't do that well with nested bg:
2125 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
Denis Vlasenko170435c2007-05-23 13:01:10 +00002126 * I'm NOT treating inner &'s as jobs */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00002127#if ENABLE_HUSH_JOB
Denis Vlasenko4b924f32007-05-30 00:29:55 +00002128 if (run_list_level == 1)
Denis Vlasenko170435c2007-05-23 13:01:10 +00002129 insert_bg_job(pi);
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00002130#endif
Eric Andersen25f27032001-04-26 23:22:31 +00002131 rcode = EXIT_SUCCESS;
2132 } else {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00002133#if ENABLE_HUSH_JOB
Denis Vlasenko170435c2007-05-23 13:01:10 +00002134 /* Paranoia, just "interactive_fd" should be enough? */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00002135 if (run_list_level == 1 && interactive_fd) {
Denis Vlasenko170435c2007-05-23 13:01:10 +00002136 /* waits for completion, then fg's main shell */
Denis Vlasenko52881e92007-04-21 13:42:52 +00002137 rcode = checkjobs_and_fg_shell(pi);
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00002138 } else
2139#endif
2140 {
Denis Vlasenko170435c2007-05-23 13:01:10 +00002141 /* this one just waits for completion */
Eric Andersenc798b072001-06-22 06:23:03 +00002142 rcode = checkjobs(pi);
Eric Andersen25f27032001-04-26 23:22:31 +00002143 }
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002144 debug_printf_exec(": checkjobs returned %d\n", rcode);
Eric Andersen25f27032001-04-26 23:22:31 +00002145 }
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002146 debug_printf_exec(": setting last_return_code=%d\n", rcode);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002147 last_return_code = rcode;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002148 pi->num_progs = save_num_progs; /* restore number of programs */
Denis Vlasenko06810332007-05-21 23:30:54 +00002149#if ENABLE_HUSH_IF
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002150 if (rword == RES_IF || rword == RES_ELIF)
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002151 next_if_code = rcode; /* can be overwritten a number of times */
Denis Vlasenko06810332007-05-21 23:30:54 +00002152#endif
2153#if ENABLE_HUSH_LOOPS
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002154 if (rword == RES_WHILE)
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002155 flag_rep = !last_return_code;
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002156 if (rword == RES_UNTIL)
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002157 flag_rep = last_return_code;
Denis Vlasenko06810332007-05-21 23:30:54 +00002158#endif
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002159 if ((rcode == EXIT_SUCCESS && pi->followup == PIPE_OR)
2160 || (rcode != EXIT_SUCCESS && pi->followup == PIPE_AND)
2161 ) {
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002162 skip_more_for_this_rword = rword;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002163 }
Eric Andersen028b65b2001-06-28 01:10:11 +00002164 checkjobs(NULL);
Eric Andersen25f27032001-04-26 23:22:31 +00002165 }
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002166
2167#if ENABLE_HUSH_JOB
2168 if (ctrl_z_flag) {
2169 /* ctrl-Z forked somewhere in the past, we are the child,
2170 * and now we completed running the list. Exit. */
2171 exit(rcode);
2172 }
2173 ret:
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00002174 if (!--run_list_level && interactive_fd) {
2175 signal(SIGTSTP, SIG_IGN);
2176 signal(SIGINT, SIG_IGN);
2177 }
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002178#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00002179 debug_printf_exec("run_list_real lvl %d return %d\n", run_list_level + 1, rcode);
Eric Andersen25f27032001-04-26 23:22:31 +00002180 return rcode;
2181}
2182
Eric Andersen25f27032001-04-26 23:22:31 +00002183/* return code is the exit status of the pipe */
Eric Andersenbf7df042001-05-23 22:18:35 +00002184static int free_pipe(struct pipe *pi, int indent)
Eric Andersen25f27032001-04-26 23:22:31 +00002185{
2186 char **p;
2187 struct child_prog *child;
2188 struct redir_struct *r, *rnext;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002189 int a, i, ret_code = 0;
Eric Andersen52a97ca2001-06-22 06:49:26 +00002190
2191 if (pi->stopped_progs > 0)
2192 return ret_code;
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002193 debug_printf_clean("%s run pipe: (pid %d)\n", indenter(indent), getpid());
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002194 for (i = 0; i < pi->num_progs; i++) {
Eric Andersen25f27032001-04-26 23:22:31 +00002195 child = &pi->progs[i];
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002196 debug_printf_clean("%s command %d:\n", indenter(indent), i);
Eric Andersen25f27032001-04-26 23:22:31 +00002197 if (child->argv) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002198 for (a = 0, p = child->argv; *p; a++, p++) {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002199 debug_printf_clean("%s argv[%d] = %s\n", indenter(indent), a, *p);
Eric Andersen25f27032001-04-26 23:22:31 +00002200 }
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002201 free_strings(child->glob_result);
2202 child->glob_result = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00002203 } else if (child->group) {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002204 debug_printf_clean("%s begin group (subshell:%d)\n", indenter(indent), child->subshell);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002205 ret_code = free_pipe_list(child->group, indent+3);
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002206 debug_printf_clean("%s end group\n", indenter(indent));
Eric Andersen25f27032001-04-26 23:22:31 +00002207 } else {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002208 debug_printf_clean("%s (nil)\n", indenter(indent));
Eric Andersen25f27032001-04-26 23:22:31 +00002209 }
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002210 for (r = child->redirects; r; r = rnext) {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002211 debug_printf_clean("%s redirect %d%s", indenter(indent), r->fd, redir_table[r->type].descrip);
Eric Andersen25f27032001-04-26 23:22:31 +00002212 if (r->dup == -1) {
Eric Andersen817e73c2001-06-06 17:56:09 +00002213 /* guard against the case >$FOO, where foo is unset or blank */
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002214 if (r->glob_word) {
2215 debug_printf_clean(" %s\n", r->glob_word[0]);
2216 free_strings(r->glob_word);
2217 r->glob_word = NULL;
Eric Andersen817e73c2001-06-06 17:56:09 +00002218 }
Eric Andersen25f27032001-04-26 23:22:31 +00002219 } else {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002220 debug_printf_clean("&%d\n", r->dup);
Eric Andersen25f27032001-04-26 23:22:31 +00002221 }
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002222 rnext = r->next;
Eric Andersen25f27032001-04-26 23:22:31 +00002223 free(r);
2224 }
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002225 child->redirects = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00002226 }
2227 free(pi->progs); /* children are an array, they get freed all at once */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002228 pi->progs = NULL;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00002229#if ENABLE_HUSH_JOB
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00002230 free(pi->cmdtext);
2231 pi->cmdtext = NULL;
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00002232#endif
Eric Andersen25f27032001-04-26 23:22:31 +00002233 return ret_code;
2234}
2235
Eric Andersenbf7df042001-05-23 22:18:35 +00002236static int free_pipe_list(struct pipe *head, int indent)
Eric Andersen25f27032001-04-26 23:22:31 +00002237{
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002238 int rcode = 0; /* if list has no members */
Eric Andersen25f27032001-04-26 23:22:31 +00002239 struct pipe *pi, *next;
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002240
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002241 for (pi = head; pi; pi = next) {
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002242 debug_printf_clean("%s pipe reserved mode %d\n", indenter(indent), pi->res_word);
Eric Andersenbf7df042001-05-23 22:18:35 +00002243 rcode = free_pipe(pi, indent);
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002244 debug_printf_clean("%s pipe followup code %d\n", indenter(indent), pi->followup);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002245 next = pi->next;
Denis Vlasenko5f786c22007-04-20 08:35:45 +00002246 /*pi->next = NULL;*/
Eric Andersen25f27032001-04-26 23:22:31 +00002247 free(pi);
2248 }
Eric Andersenc7bda1c2004-03-15 08:29:22 +00002249 return rcode;
Eric Andersen25f27032001-04-26 23:22:31 +00002250}
2251
2252/* Select which version we will use */
2253static int run_list(struct pipe *pi)
2254{
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002255 int rcode = 0;
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002256 debug_printf_exec("run_list entered\n");
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002257 if (fake_mode == 0) {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002258 debug_printf_exec(": run_list_real with %d members\n", pi->num_progs);
Eric Andersen25f27032001-04-26 23:22:31 +00002259 rcode = run_list_real(pi);
Eric Andersenc7bda1c2004-03-15 08:29:22 +00002260 }
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002261 /* free_pipe_list has the side effect of clearing memory.
Eric Andersen25f27032001-04-26 23:22:31 +00002262 * In the long run that function can be merged with run_list_real,
2263 * but doing that now would hobble the debugging effort. */
Denis Vlasenko400c5b62007-05-04 13:07:27 +00002264 free_pipe_list(pi, 0);
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002265 debug_printf_exec("run_list return %d\n", rcode);
Eric Andersen25f27032001-04-26 23:22:31 +00002266 return rcode;
2267}
2268
Denis Vlasenkoff097622007-10-01 10:00:45 +00002269/* Whoever decided to muck with glob internal data is AN IDIOT! */
2270/* uclibc happily changed the way it works (and it has rights to do so!),
2271 all hell broke loose (SEGVs) */
2272
Eric Andersen25f27032001-04-26 23:22:31 +00002273/* The API for glob is arguably broken. This routine pushes a non-matching
2274 * string into the output structure, removing non-backslashed backslashes.
2275 * If someone can prove me wrong, by performing this function within the
2276 * original glob(3) api, feel free to rewrite this routine into oblivion.
Eric Andersen25f27032001-04-26 23:22:31 +00002277 * XXX broken if the last character is '\\', check that before calling.
2278 */
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002279static char **globhack(const char *src, char **strings)
Eric Andersen25f27032001-04-26 23:22:31 +00002280{
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002281 int cnt;
Eric Andersen25f27032001-04-26 23:22:31 +00002282 const char *s;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002283 char *v, *dest;
2284
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002285 for (cnt = 1, s = src; s && *s; s++) {
Eric Andersen25f27032001-04-26 23:22:31 +00002286 if (*s == '\\') s++;
2287 cnt++;
2288 }
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002289 v = dest = xmalloc(cnt);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002290 for (s = src; s && *s; s++, dest++) {
Eric Andersen25f27032001-04-26 23:22:31 +00002291 if (*s == '\\') s++;
2292 *dest = *s;
2293 }
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002294 *dest = '\0';
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002295
2296 return add_string_to_strings(strings, v);
Eric Andersen25f27032001-04-26 23:22:31 +00002297}
2298
2299/* XXX broken if the last character is '\\', check that before calling */
2300static int glob_needed(const char *s)
2301{
2302 for (; *s; s++) {
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002303 if (*s == '\\')
2304 s++;
2305 if (strchr("*[?", *s))
2306 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00002307 }
2308 return 0;
2309}
2310
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002311static int xglob(o_string *dest, char ***pglob)
Eric Andersen25f27032001-04-26 23:22:31 +00002312{
Tim Rikerc1ef7bd2006-01-25 00:08:53 +00002313 /* short-circuit for null word */
Eric Andersen25f27032001-04-26 23:22:31 +00002314 /* we can code this better when the debug_printf's are gone */
Tim Rikerc1ef7bd2006-01-25 00:08:53 +00002315 if (dest->length == 0) {
2316 if (dest->nonnull) {
2317 /* bash man page calls this an "explicit" null */
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002318 *pglob = globhack(dest->data, *pglob);
2319 }
2320 return 0;
2321 }
2322
2323 if (glob_needed(dest->data)) {
2324 glob_t globdata;
2325 int gr;
2326
2327 memset(&globdata, 0, sizeof(globdata));
2328 gr = glob(dest->data, 0, NULL, &globdata);
2329 debug_printf("glob returned %d\n", gr);
2330 if (gr == GLOB_NOSPACE)
2331 bb_error_msg_and_die("out of memory during glob");
2332 if (gr == GLOB_NOMATCH) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002333 debug_printf("globhack returned %d\n", gr);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002334 /* quote removal, or more accurately, backslash removal */
2335 *pglob = globhack(dest->data, *pglob);
Eric Andersen25f27032001-04-26 23:22:31 +00002336 return 0;
2337 }
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002338 if (gr != 0) { /* GLOB_ABORTED ? */
2339 bb_error_msg("glob(3) error %d", gr);
Eric Andersen25f27032001-04-26 23:22:31 +00002340 }
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002341 if (globdata.gl_pathv && globdata.gl_pathv[0])
2342 *pglob = add_strings_to_strings(1, *pglob, globdata.gl_pathv);
2343 /* globprint(glob_target); */
2344 globfree(&globdata);
2345 return gr;
Eric Andersen25f27032001-04-26 23:22:31 +00002346 }
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002347
2348 *pglob = globhack(dest->data, *pglob);
2349 return 0;
Eric Andersen25f27032001-04-26 23:22:31 +00002350}
2351
Denis Vlasenko170435c2007-05-23 13:01:10 +00002352/* expand_strvec_to_strvec() takes a list of strings, expands
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002353 * all variable references within and returns a pointer to
2354 * a list of expanded strings, possibly with larger number
2355 * of strings. (Think VAR="a b"; echo $VAR).
2356 * This new list is allocated as a single malloc block.
2357 * NULL-terminated list of char* pointers is at the beginning of it,
2358 * followed by strings themself.
2359 * Caller can deallocate entire list by single free(list). */
2360
2361/* Helpers first:
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00002362 * count_XXX estimates size of the block we need. It's okay
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002363 * to over-estimate sizes a bit, if it makes code simpler */
2364static int count_ifs(const char *str)
2365{
2366 int cnt = 0;
2367 debug_printf_expand("count_ifs('%s') ifs='%s'", str, ifs);
2368 while (1) {
2369 str += strcspn(str, ifs);
2370 if (!*str) break;
Denis Vlasenkoc666f712007-05-16 22:18:54 +00002371 str++; /* str += strspn(str, ifs); */
2372 cnt++; /* cnt += strspn(str, ifs); - but this code is larger */
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00002373 }
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002374 debug_printf_expand(" return %d\n", cnt);
2375 return cnt;
2376}
2377
2378static void count_var_expansion_space(int *countp, int *lenp, char *arg)
2379{
2380 char first_ch;
2381 int i;
2382 int len = *lenp;
2383 int count = *countp;
2384 const char *val;
2385 char *p;
2386
2387 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL))) {
2388 len += p - arg;
2389 arg = ++p;
2390 p = strchr(p, SPECIAL_VAR_SYMBOL);
2391 first_ch = arg[0];
2392
2393 switch (first_ch & 0x7f) {
2394 /* high bit in 1st_ch indicates that var is double-quoted */
2395 case '$': /* pid */
2396 case '!': /* bg pid */
2397 case '?': /* exitcode */
2398 case '#': /* argc */
2399 len += sizeof(int)*3 + 1; /* enough for int */
2400 break;
2401 case '*':
2402 case '@':
2403 for (i = 1; i < global_argc; i++) {
2404 len += strlen(global_argv[i]) + 1;
2405 count++;
2406 if (!(first_ch & 0x80))
2407 count += count_ifs(global_argv[i]);
2408 }
2409 break;
2410 default:
2411 *p = '\0';
2412 arg[0] = first_ch & 0x7f;
Denis Vlasenko764d59d2007-05-14 16:23:23 +00002413 if (isdigit(arg[0])) {
2414 i = xatoi_u(arg);
2415 val = NULL;
2416 if (i < global_argc)
2417 val = global_argv[i];
2418 } else
2419 val = lookup_param(arg);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002420 arg[0] = first_ch;
2421 *p = SPECIAL_VAR_SYMBOL;
2422
2423 if (val) {
2424 len += strlen(val) + 1;
2425 if (!(first_ch & 0x80))
2426 count += count_ifs(val);
2427 }
2428 }
2429 arg = ++p;
2430 }
2431
2432 len += strlen(arg) + 1;
2433 count++;
2434 *lenp = len;
2435 *countp = count;
2436}
2437
2438/* Store given string, finalizing the word and starting new one whenever
2439 * we encounter ifs char(s). This is used for expanding variable values.
Denis Vlasenko764d59d2007-05-14 16:23:23 +00002440 * End-of-string does NOT finalize word: think about 'echo -$VAR-' */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002441static int expand_on_ifs(char **list, int n, char **posp, const char *str)
2442{
2443 char *pos = *posp;
2444 while (1) {
2445 int word_len = strcspn(str, ifs);
2446 if (word_len) {
2447 memcpy(pos, str, word_len); /* store non-ifs chars */
2448 pos += word_len;
2449 str += word_len;
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002450 }
Denis Vlasenko764d59d2007-05-14 16:23:23 +00002451 if (!*str) /* EOL - do not finalize word */
2452 break;
2453 *pos++ = '\0';
2454 if (n) debug_printf_expand("expand_on_ifs finalized list[%d]=%p '%s' "
2455 "strlen=%d next=%p pos=%p\n", n-1, list[n-1], list[n-1],
2456 strlen(list[n-1]), list[n-1] + strlen(list[n-1]) + 1, pos);
2457 list[n++] = pos;
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002458 str += strspn(str, ifs); /* skip ifs chars */
2459 }
2460 *posp = pos;
2461 return n;
2462}
2463
2464/* Expand all variable references in given string, adding words to list[]
2465 * at n, n+1,... positions. Return updated n (so that list[n] is next one
2466 * to be filled). This routine is extremely tricky: has to deal with
2467 * variables/parameters with whitespace, $* and $@, and constructs like
2468 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002469/* NB: another bug is that we cannot detect empty strings yet:
2470 * "" or $empty"" expands to zero words, has to expand to empty word */
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002471static int expand_vars_to_list(char **list, int n, char **posp, char *arg, char or_mask)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002472{
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002473 /* or_mask is either 0 (normal case) or 0x80
2474 * (expansion of right-hand side of assignment == 1-element expand) */
2475
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002476 char first_ch, ored_ch;
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00002477 int i;
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002478 const char *val;
2479 char *p;
2480 char *pos = *posp;
2481
2482 ored_ch = 0;
2483
2484 if (n) debug_printf_expand("expand_vars_to_list finalized list[%d]=%p '%s' "
2485 "strlen=%d next=%p pos=%p\n", n-1, list[n-1], list[n-1],
2486 strlen(list[n-1]), list[n-1] + strlen(list[n-1]) + 1, pos);
2487 list[n++] = pos;
2488
2489 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL))) {
2490 memcpy(pos, arg, p - arg);
2491 pos += (p - arg);
2492 arg = ++p;
2493 p = strchr(p, SPECIAL_VAR_SYMBOL);
2494
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002495 first_ch = arg[0] | or_mask; /* forced to "quoted" if or_mask = 0x80 */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002496 ored_ch |= first_ch;
2497 val = NULL;
2498 switch (first_ch & 0x7f) {
2499 /* Highest bit in first_ch indicates that var is double-quoted */
2500 case '$': /* pid */
2501 /* FIXME: (echo $$) should still print pid of main shell */
2502 val = utoa(getpid());
2503 break;
2504 case '!': /* bg pid */
2505 val = last_bg_pid ? utoa(last_bg_pid) : (char*)"";
2506 break;
2507 case '?': /* exitcode */
2508 val = utoa(last_return_code);
2509 break;
2510 case '#': /* argc */
2511 val = utoa(global_argc ? global_argc-1 : 0);
2512 break;
2513 case '*':
2514 case '@':
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00002515 i = 1;
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002516 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002517 while (i < global_argc) {
2518 n = expand_on_ifs(list, n, &pos, global_argv[i]);
2519 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, global_argc-1);
2520 if (global_argv[i++][0] && i < global_argc) {
2521 /* this argv[] is not empty and not last:
2522 * put terminating NUL, start new word */
2523 *pos++ = '\0';
2524 if (n) debug_printf_expand("expand_vars_to_list 2 finalized list[%d]=%p '%s' "
2525 "strlen=%d next=%p pos=%p\n", n-1, list[n-1], list[n-1],
2526 strlen(list[n-1]), list[n-1] + strlen(list[n-1]) + 1, pos);
2527 list[n++] = pos;
2528 }
2529 }
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002530 } else
2531 /* If or_mask is nonzero, we handle assignment 'a=....$@.....'
2532 * and in this case should theat it like '$*' */
2533 if (first_ch == ('@'|0x80) && !or_mask) { /* quoted $@ */
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00002534 while (1) {
2535 strcpy(pos, global_argv[i]);
2536 pos += strlen(global_argv[i]);
2537 if (++i >= global_argc)
2538 break;
2539 *pos++ = '\0';
2540 if (n) debug_printf_expand("expand_vars_to_list 3 finalized list[%d]=%p '%s' "
2541 "strlen=%d next=%p pos=%p\n", n-1, list[n-1], list[n-1],
2542 strlen(list[n-1]), list[n-1] + strlen(list[n-1]) + 1, pos);
2543 list[n++] = pos;
2544 }
2545 } else { /* quoted $*: add as one word */
2546 while (1) {
2547 strcpy(pos, global_argv[i]);
2548 pos += strlen(global_argv[i]);
2549 if (++i >= global_argc)
2550 break;
2551 if (ifs[0])
2552 *pos++ = ifs[0];
2553 }
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002554 }
2555 break;
2556 default:
2557 *p = '\0';
2558 arg[0] = first_ch & 0x7f;
Denis Vlasenko764d59d2007-05-14 16:23:23 +00002559 if (isdigit(arg[0])) {
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00002560 i = xatoi_u(arg);
Denis Vlasenko764d59d2007-05-14 16:23:23 +00002561 val = NULL;
2562 if (i < global_argc)
2563 val = global_argv[i];
2564 } else
2565 val = lookup_param(arg);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002566 arg[0] = first_ch;
2567 *p = SPECIAL_VAR_SYMBOL;
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00002568 if (!(first_ch & 0x80)) { /* unquoted $VAR */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002569 if (val) {
2570 n = expand_on_ifs(list, n, &pos, val);
2571 val = NULL;
2572 }
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00002573 } /* else: quoted $VAR, val will be appended at pos */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002574 }
2575 if (val) {
2576 strcpy(pos, val);
2577 pos += strlen(val);
2578 }
2579 arg = ++p;
2580 }
2581 debug_printf_expand("expand_vars_to_list adding tail '%s' at %p\n", arg, pos);
2582 strcpy(pos, arg);
2583 pos += strlen(arg) + 1;
2584 if (pos == list[n-1] + 1) { /* expansion is empty */
2585 if (!(ored_ch & 0x80)) { /* all vars were not quoted... */
2586 debug_printf_expand("expand_vars_to_list list[%d] empty, going back\n", n);
2587 pos--;
2588 n--;
2589 }
2590 }
2591
2592 *posp = pos;
2593 return n;
2594}
2595
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002596static char **expand_variables(char **argv, char or_mask)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002597{
2598 int n;
2599 int count = 1;
2600 int len = 0;
2601 char *pos, **v, **list;
2602
2603 v = argv;
2604 if (!*v) debug_printf_expand("count_var_expansion_space: "
2605 "argv[0]=NULL count=%d len=%d alloc_space=%d\n",
2606 count, len, sizeof(char*) * count + len);
2607 while (*v) {
2608 count_var_expansion_space(&count, &len, *v);
2609 debug_printf_expand("count_var_expansion_space: "
2610 "'%s' count=%d len=%d alloc_space=%d\n",
2611 *v, count, len, sizeof(char*) * count + len);
2612 v++;
2613 }
2614 len += sizeof(char*) * count; /* total to alloc */
2615 list = xmalloc(len);
2616 pos = (char*)(list + count);
2617 debug_printf_expand("list=%p, list[0] should be %p\n", list, pos);
2618 n = 0;
2619 v = argv;
2620 while (*v)
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002621 n = expand_vars_to_list(list, n, &pos, *v++, or_mask);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002622
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002623 if (n) debug_printf_expand("finalized list[%d]=%p '%s' "
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002624 "strlen=%d next=%p pos=%p\n", n-1, list[n-1], list[n-1],
2625 strlen(list[n-1]), list[n-1] + strlen(list[n-1]) + 1, pos);
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00002626 list[n] = NULL;
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002627
2628#ifdef DEBUG_EXPAND
2629 {
2630 int m = 0;
2631 while (m <= n) {
2632 debug_printf_expand("list[%d]=%p '%s'\n", m, list[m], list[m]);
2633 m++;
2634 }
2635 debug_printf_expand("used_space=%d\n", pos - (char*)list);
2636 }
2637#endif
Denis Vlasenko170435c2007-05-23 13:01:10 +00002638 if (ENABLE_HUSH_DEBUG)
2639 if (pos - (char*)list > len)
2640 bb_error_msg_and_die("BUG in varexp");
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00002641 return list;
2642}
2643
Denis Vlasenko170435c2007-05-23 13:01:10 +00002644static char **expand_strvec_to_strvec(char **argv)
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00002645{
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002646 return expand_variables(argv, 0);
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00002647}
2648
Denis Vlasenko170435c2007-05-23 13:01:10 +00002649static char *expand_string_to_string(const char *str)
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002650{
2651 char *argv[2], **list;
2652
2653 argv[0] = (char*)str;
2654 argv[1] = NULL;
2655 list = expand_variables(argv, 0x80); /* 0x80: make one-element expansion */
Denis Vlasenko170435c2007-05-23 13:01:10 +00002656 if (ENABLE_HUSH_DEBUG)
2657 if (!list[0] || list[1])
2658 bb_error_msg_and_die("BUG in varexp2");
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002659 /* actually, just move string 2*sizeof(char*) bytes back */
2660 strcpy((char*)list, list[0]);
Denis Vlasenko170435c2007-05-23 13:01:10 +00002661 debug_printf_expand("string_to_string='%s'\n", (char*)list);
2662 return (char*)list;
2663}
2664
2665static char* expand_strvec_to_string(char **argv)
2666{
2667 char **list;
2668
2669 list = expand_variables(argv, 0x80);
2670 /* Convert all NULs to spaces */
2671 if (list[0]) {
2672 int n = 1;
2673 while (list[n]) {
2674 if (ENABLE_HUSH_DEBUG)
2675 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
2676 bb_error_msg_and_die("BUG in varexp3");
2677 list[n][-1] = ' '; /* TODO: or to ifs[0]? */
2678 n++;
2679 }
2680 }
2681 strcpy((char*)list, list[0]);
2682 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
Denis Vlasenkob6a741f2007-05-17 14:38:17 +00002683 return (char*)list;
2684}
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002685
Eric Andersenf72f5622001-05-15 23:21:41 +00002686/* This is used to get/check local shell variables */
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002687static struct variable *get_local_var(const char *name)
Eric Andersenf72f5622001-05-15 23:21:41 +00002688{
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002689 struct variable *cur;
2690 int len;
Eric Andersenf72f5622001-05-15 23:21:41 +00002691
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002692 if (!name)
Eric Andersenf72f5622001-05-15 23:21:41 +00002693 return NULL;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002694 len = strlen(name);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002695 for (cur = top_var; cur; cur = cur->next) {
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002696 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002697 return cur;
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00002698 }
Eric Andersenf72f5622001-05-15 23:21:41 +00002699 return NULL;
2700}
2701
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002702/* str holds "NAME=VAL" and is expected to be malloced.
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002703 * We take ownership of it. */
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002704static int set_local_var(char *str, int flg_export)
Eric Andersen78a7c992001-05-15 16:30:25 +00002705{
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002706 struct variable *cur;
2707 char *value;
2708 int name_len;
Eric Andersen20a69a72001-05-15 17:24:44 +00002709
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002710 value = strchr(str, '=');
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002711 if (!value) { /* not expected to ever happen? */
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002712 free(str);
Eric Andersen99785762001-05-22 21:37:48 +00002713 return -1;
2714 }
Eric Andersen20a69a72001-05-15 17:24:44 +00002715
Denis Vlasenko201c72a2007-05-25 10:00:36 +00002716 name_len = value - str + 1; /* including '=' */
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002717 cur = top_var; /* cannot be NULL (we have HUSH_VERSION and it's RO) */
2718 while (1) {
Denis Vlasenko201c72a2007-05-25 10:00:36 +00002719 if (strncmp(cur->varstr, str, name_len) != 0) {
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002720 if (!cur->next) {
Denis Vlasenko201c72a2007-05-25 10:00:36 +00002721 /* Bail out. Note that now cur points
2722 * to last var in linked list */
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002723 break;
Eric Andersen20a69a72001-05-15 17:24:44 +00002724 }
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002725 cur = cur->next;
2726 continue;
Eric Andersen20a69a72001-05-15 17:24:44 +00002727 }
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002728 /* We found an existing var with this name */
2729 *value = '\0';
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002730 if (cur->flg_read_only) {
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002731 bb_error_msg("%s: readonly variable", str);
2732 free(str);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002733 return -1;
2734 }
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002735 unsetenv(str); /* just in case */
2736 *value = '=';
2737 if (strcmp(cur->varstr, str) == 0) {
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002738 free_and_exp:
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002739 free(str);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002740 goto exp;
2741 }
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002742 if (cur->max_len >= strlen(str)) {
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002743 /* This one is from startup env, reuse space */
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002744 strcpy(cur->varstr, str);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002745 goto free_and_exp;
2746 }
2747 /* max_len == 0 signifies "malloced" var, which we can
2748 * (and has to) free */
2749 if (!cur->max_len)
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002750 free(cur->varstr);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002751 cur->max_len = 0;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002752 goto set_str_and_exp;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002753 }
Eric Andersen20a69a72001-05-15 17:24:44 +00002754
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002755 /* Not found - create next variable struct */
2756 cur->next = xzalloc(sizeof(*cur));
2757 cur = cur->next;
2758
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002759 set_str_and_exp:
2760 cur->varstr = str;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002761 exp:
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002762 if (flg_export)
2763 cur->flg_export = 1;
2764 if (cur->flg_export)
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002765 return putenv(cur->varstr);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002766 return 0;
Eric Andersen20a69a72001-05-15 17:24:44 +00002767}
2768
Eric Andersenf72f5622001-05-15 23:21:41 +00002769static void unset_local_var(const char *name)
Eric Andersen20a69a72001-05-15 17:24:44 +00002770{
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002771 struct variable *cur;
2772 struct variable *prev = prev; /* for gcc */
2773 int name_len;
Eric Andersen20a69a72001-05-15 17:24:44 +00002774
Denis Vlasenko5f786c22007-04-20 08:35:45 +00002775 if (!name)
2776 return;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002777 name_len = strlen(name);
2778 cur = top_var;
2779 while (cur) {
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002780 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002781 if (cur->flg_read_only) {
Manuel Novoa III cad53642003-03-19 09:13:01 +00002782 bb_error_msg("%s: readonly variable", name);
Eric Andersen94ac2442001-05-22 19:05:18 +00002783 return;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002784 }
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002785 /* prev is ok to use here because 1st variable, HUSH_VERSION,
2786 * is ro, and we cannot reach this code on the 1st pass */
2787 prev->next = cur->next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002788 unsetenv(cur->varstr);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002789 if (!cur->max_len)
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00002790 free(cur->varstr);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00002791 free(cur);
Denis Vlasenko5f786c22007-04-20 08:35:45 +00002792 return;
Eric Andersenf72f5622001-05-15 23:21:41 +00002793 }
Denis Vlasenkod76c0492007-05-25 02:16:25 +00002794 prev = cur;
2795 cur = cur->next;
Eric Andersen20a69a72001-05-15 17:24:44 +00002796 }
Eric Andersen78a7c992001-05-15 16:30:25 +00002797}
2798
2799static int is_assignment(const char *s)
2800{
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002801 if (!s || !isalpha(*s))
2802 return 0;
2803 s++;
2804 while (isalnum(*s) || *s == '_')
2805 s++;
2806 return *s == '=';
Eric Andersen78a7c992001-05-15 16:30:25 +00002807}
2808
Eric Andersen25f27032001-04-26 23:22:31 +00002809/* the src parameter allows us to peek forward to a possible &n syntax
2810 * for file descriptor duplication, e.g., "2>&1".
2811 * Return code is 0 normally, 1 if a syntax error is detected in src.
2812 * Resource errors (in xmalloc) cause the process to exit */
2813static int setup_redirect(struct p_context *ctx, int fd, redir_type style,
2814 struct in_str *input)
2815{
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002816 struct child_prog *child = ctx->child;
Eric Andersen25f27032001-04-26 23:22:31 +00002817 struct redir_struct *redir = child->redirects;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002818 struct redir_struct *last_redir = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00002819
2820 /* Create a new redir_struct and drop it onto the end of the linked list */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002821 while (redir) {
2822 last_redir = redir;
2823 redir = redir->next;
Eric Andersen25f27032001-04-26 23:22:31 +00002824 }
Denis Vlasenkoff097622007-10-01 10:00:45 +00002825 redir = xzalloc(sizeof(struct redir_struct));
2826 /* redir->next = NULL; */
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002827 /* redir->glob_word = NULL; */
Eric Andersen25f27032001-04-26 23:22:31 +00002828 if (last_redir) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002829 last_redir->next = redir;
Eric Andersen25f27032001-04-26 23:22:31 +00002830 } else {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002831 child->redirects = redir;
Eric Andersen25f27032001-04-26 23:22:31 +00002832 }
2833
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002834 redir->type = style;
2835 redir->fd = (fd == -1) ? redir_table[style].default_fd : fd;
Eric Andersen25f27032001-04-26 23:22:31 +00002836
2837 debug_printf("Redirect type %d%s\n", redir->fd, redir_table[style].descrip);
2838
Eric Andersenc7bda1c2004-03-15 08:29:22 +00002839 /* Check for a '2>&1' type redirect */
Eric Andersen25f27032001-04-26 23:22:31 +00002840 redir->dup = redirect_dup_num(input);
2841 if (redir->dup == -2) return 1; /* syntax error */
2842 if (redir->dup != -1) {
2843 /* Erik had a check here that the file descriptor in question
Eric Andersen83a2ae22001-05-07 17:59:25 +00002844 * is legit; I postpone that to "run time"
2845 * A "-" representation of "close me" shows up as a -3 here */
Eric Andersen25f27032001-04-26 23:22:31 +00002846 debug_printf("Duplicating redirect '%d>&%d'\n", redir->fd, redir->dup);
2847 } else {
2848 /* We do _not_ try to open the file that src points to,
2849 * since we need to return and let src be expanded first.
2850 * Set ctx->pending_redirect, so we know what to do at the
Denis Vlasenko201c72a2007-05-25 10:00:36 +00002851 * end of the next parsed word. */
Eric Andersen25f27032001-04-26 23:22:31 +00002852 ctx->pending_redirect = redir;
2853 }
2854 return 0;
2855}
2856
Denis Vlasenkoac678ec2007-04-16 22:32:04 +00002857static struct pipe *new_pipe(void)
2858{
Eric Andersen25f27032001-04-26 23:22:31 +00002859 struct pipe *pi;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00002860 pi = xzalloc(sizeof(struct pipe));
2861 /*pi->num_progs = 0;*/
2862 /*pi->progs = NULL;*/
2863 /*pi->next = NULL;*/
2864 /*pi->followup = 0; invalid */
2865 if (RES_NONE)
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002866 pi->res_word = RES_NONE;
Eric Andersen25f27032001-04-26 23:22:31 +00002867 return pi;
2868}
2869
2870static void initialize_context(struct p_context *ctx)
2871{
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002872 ctx->child = NULL;
Denis Vlasenko1a735862007-05-23 00:32:25 +00002873 ctx->pipe = ctx->list_head = new_pipe();
2874 ctx->pending_redirect = NULL;
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002875 ctx->res_w = RES_NONE;
Denis Vlasenko1a735862007-05-23 00:32:25 +00002876 //only ctx->parse_type is not touched... is this intentional?
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002877 ctx->old_flag = 0;
Denis Vlasenko1a735862007-05-23 00:32:25 +00002878 ctx->stack = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00002879 done_command(ctx); /* creates the memory for working child */
2880}
2881
2882/* normal return is 0
2883 * if a reserved word is found, and processed, return 1
2884 * should handle if, then, elif, else, fi, for, while, until, do, done.
2885 * case, function, and select are obnoxious, save those for later.
2886 */
Denis Vlasenko06810332007-05-21 23:30:54 +00002887#if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS
"Vladimir N. Oleynik"19c37012005-09-22 14:33:15 +00002888static int reserved_word(o_string *dest, struct p_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00002889{
2890 struct reserved_combo {
Denis Vlasenko5f786c22007-04-20 08:35:45 +00002891 char literal[7];
2892 unsigned char code;
2893 int flag;
Eric Andersen25f27032001-04-26 23:22:31 +00002894 };
2895 /* Mostly a list of accepted follow-up reserved words.
2896 * FLAG_END means we are done with the sequence, and are ready
2897 * to turn the compound list into a command.
2898 * FLAG_START means the word must start a new compound list.
2899 */
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00002900 static const struct reserved_combo reserved_list[] = {
Denis Vlasenko06810332007-05-21 23:30:54 +00002901#if ENABLE_HUSH_IF
Eric Andersen25f27032001-04-26 23:22:31 +00002902 { "if", RES_IF, FLAG_THEN | FLAG_START },
2903 { "then", RES_THEN, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
2904 { "elif", RES_ELIF, FLAG_THEN },
2905 { "else", RES_ELSE, FLAG_FI },
2906 { "fi", RES_FI, FLAG_END },
Denis Vlasenko06810332007-05-21 23:30:54 +00002907#endif
2908#if ENABLE_HUSH_LOOPS
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002909 { "for", RES_FOR, FLAG_IN | FLAG_START },
Eric Andersen25f27032001-04-26 23:22:31 +00002910 { "while", RES_WHILE, FLAG_DO | FLAG_START },
2911 { "until", RES_UNTIL, FLAG_DO | FLAG_START },
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002912 { "in", RES_IN, FLAG_DO },
Eric Andersen25f27032001-04-26 23:22:31 +00002913 { "do", RES_DO, FLAG_DONE },
2914 { "done", RES_DONE, FLAG_END }
Denis Vlasenko06810332007-05-21 23:30:54 +00002915#endif
Eric Andersen25f27032001-04-26 23:22:31 +00002916 };
Denis Vlasenko80b8b392007-06-25 10:55:35 +00002917
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00002918 const struct reserved_combo *r;
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00002919
Denis Vlasenko80b8b392007-06-25 10:55:35 +00002920 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
Denis Vlasenko1a735862007-05-23 00:32:25 +00002921 if (strcmp(dest->data, r->literal) != 0)
2922 continue;
2923 debug_printf("found reserved word %s, code %d\n", r->literal, r->code);
2924 if (r->flag & FLAG_START) {
2925 struct p_context *new;
2926 debug_printf("push stack\n");
Denis Vlasenko06810332007-05-21 23:30:54 +00002927#if ENABLE_HUSH_LOOPS
Denis Vlasenko1a735862007-05-23 00:32:25 +00002928 if (ctx->res_w == RES_IN || ctx->res_w == RES_FOR) {
Denis Vlasenko90e485c2007-05-23 15:22:50 +00002929 syntax("malformed for"); /* example: 'for if' */
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002930 ctx->res_w = RES_SNTX;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002931 b_reset(dest);
Eric Andersenaf44a0e2001-04-27 07:26:12 +00002932 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00002933 }
Denis Vlasenko1a735862007-05-23 00:32:25 +00002934#endif
2935 new = xmalloc(sizeof(*new));
2936 *new = *ctx; /* physical copy */
2937 initialize_context(ctx);
2938 ctx->stack = new;
2939 } else if (ctx->res_w == RES_NONE || !(ctx->old_flag & (1 << r->code))) {
Denis Vlasenko90e485c2007-05-23 15:22:50 +00002940 syntax(NULL);
Denis Vlasenko1a735862007-05-23 00:32:25 +00002941 ctx->res_w = RES_SNTX;
Denis Vlasenkoff131b92007-04-10 15:42:06 +00002942 b_reset(dest);
Eric Andersen25f27032001-04-26 23:22:31 +00002943 return 1;
2944 }
Denis Vlasenko1a735862007-05-23 00:32:25 +00002945 ctx->res_w = r->code;
2946 ctx->old_flag = r->flag;
2947 if (ctx->old_flag & FLAG_END) {
2948 struct p_context *old;
2949 debug_printf("pop stack\n");
2950 done_pipe(ctx, PIPE_SEQ);
2951 old = ctx->stack;
2952 old->child->group = ctx->list_head;
2953 old->child->subshell = 0;
2954 *ctx = *old; /* physical copy */
2955 free(old);
2956 }
2957 b_reset(dest);
2958 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00002959 }
2960 return 0;
2961}
Denis Vlasenko06810332007-05-21 23:30:54 +00002962#else
2963#define reserved_word(dest, ctx) ((int)0)
2964#endif
Eric Andersen25f27032001-04-26 23:22:31 +00002965
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00002966/* Normal return is 0.
Eric Andersen25f27032001-04-26 23:22:31 +00002967 * Syntax or xglob errors return 1. */
2968static int done_word(o_string *dest, struct p_context *ctx)
2969{
Denis Vlasenkobb81c582007-01-30 22:32:09 +00002970 struct child_prog *child = ctx->child;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002971 char ***glob_target;
2972 int gr;
Eric Andersen25f27032001-04-26 23:22:31 +00002973
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002974 debug_printf_parse("done_word entered: '%s' %p\n", dest->data, child);
Eric Andersen25f27032001-04-26 23:22:31 +00002975 if (dest->length == 0 && !dest->nonnull) {
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00002976 debug_printf_parse("done_word return 0: true null, ignored\n");
Eric Andersen25f27032001-04-26 23:22:31 +00002977 return 0;
2978 }
2979 if (ctx->pending_redirect) {
Denis Vlasenkoff097622007-10-01 10:00:45 +00002980 glob_target = &ctx->pending_redirect->glob_word;
Eric Andersen25f27032001-04-26 23:22:31 +00002981 } else {
2982 if (child->group) {
Denis Vlasenko90e485c2007-05-23 15:22:50 +00002983 syntax(NULL);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00002984 debug_printf_parse("done_word return 1: syntax error, groups and arglists don't mix\n");
2985 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00002986 }
Denis Vlasenko219e88d2007-05-21 10:18:23 +00002987 if (!child->argv && (ctx->parse_type & PARSEFLAG_SEMICOLON)) {
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002988 debug_printf_parse(": checking '%s' for reserved-ness\n", dest->data);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00002989 if (reserved_word(dest, ctx)) {
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00002990 debug_printf_parse("done_word return %d\n", (ctx->res_w == RES_SNTX));
2991 return (ctx->res_w == RES_SNTX);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00002992 }
Eric Andersen25f27032001-04-26 23:22:31 +00002993 }
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002994 glob_target = &child->argv;
Eric Andersen25f27032001-04-26 23:22:31 +00002995 }
Denis Vlasenkod65ea392007-10-01 10:02:25 +00002996 gr = xglob(dest, glob_target);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00002997 if (gr != 0) {
2998 debug_printf_parse("done_word return 1: xglob returned %d\n", gr);
2999 return 1;
3000 }
Eric Andersen25f27032001-04-26 23:22:31 +00003001
3002 b_reset(dest);
3003 if (ctx->pending_redirect) {
Denis Vlasenkod65ea392007-10-01 10:02:25 +00003004 if (ctx->pending_redirect->glob_word
3005 && ctx->pending_redirect->glob_word[0]
3006 && ctx->pending_redirect->glob_word[1]
3007 ) {
3008 /* more than one word resulted from globbing redir */
3009 ctx->pending_redirect = NULL;
Manuel Novoa III cad53642003-03-19 09:13:01 +00003010 bb_error_msg("ambiguous redirect");
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003011 debug_printf_parse("done_word return 1: ambiguous redirect\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003012 return 1;
3013 }
Denis Vlasenkod65ea392007-10-01 10:02:25 +00003014 ctx->pending_redirect = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00003015 }
Denis Vlasenko06810332007-05-21 23:30:54 +00003016#if ENABLE_HUSH_LOOPS
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003017 if (ctx->res_w == RES_FOR) {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003018 done_word(dest, ctx);
3019 done_pipe(ctx, PIPE_SEQ);
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003020 }
Denis Vlasenko06810332007-05-21 23:30:54 +00003021#endif
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003022 debug_printf_parse("done_word return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003023 return 0;
3024}
3025
3026/* The only possible error here is out of memory, in which case
3027 * xmalloc exits. */
3028static int done_command(struct p_context *ctx)
3029{
3030 /* The child is really already in the pipe structure, so
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003031 * advance the pipe counter and make a new, null child. */
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003032 struct pipe *pi = ctx->pipe;
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003033 struct child_prog *child = ctx->child;
Eric Andersen25f27032001-04-26 23:22:31 +00003034
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003035 if (child) {
3036 if (child->group == NULL
3037 && child->argv == NULL
3038 && child->redirects == NULL
3039 ) {
Denis Vlasenkodd4cb2b2007-05-05 15:11:40 +00003040 debug_printf_parse("done_command: skipping null cmd, num_progs=%d\n", pi->num_progs);
3041 return pi->num_progs;
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003042 }
Eric Andersen25f27032001-04-26 23:22:31 +00003043 pi->num_progs++;
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003044 debug_printf_parse("done_command: ++num_progs=%d\n", pi->num_progs);
Eric Andersen25f27032001-04-26 23:22:31 +00003045 } else {
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003046 debug_printf_parse("done_command: initializing, num_progs=%d\n", pi->num_progs);
Eric Andersen25f27032001-04-26 23:22:31 +00003047 }
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003048
3049 /* Only real trickiness here is that the uncommitted
3050 * child structure is not counted in pi->num_progs. */
Eric Andersen25f27032001-04-26 23:22:31 +00003051 pi->progs = xrealloc(pi->progs, sizeof(*pi->progs) * (pi->num_progs+1));
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003052 child = &pi->progs[pi->num_progs];
Eric Andersen25f27032001-04-26 23:22:31 +00003053
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003054 memset(child, 0, sizeof(*child));
3055 /*child->redirects = NULL;*/
3056 /*child->argv = NULL;*/
3057 /*child->is_stopped = 0;*/
3058 /*child->group = NULL;*/
Denis Vlasenkod65ea392007-10-01 10:02:25 +00003059 /*child->glob_result = NULL;*/
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003060 child->family = pi;
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003061 //sp: /*child->sp = 0;*/
Denis Vlasenko262d7652007-05-20 21:52:49 +00003062 //pt: child->parse_type = ctx->parse_type;
Eric Andersen25f27032001-04-26 23:22:31 +00003063
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003064 ctx->child = child;
Eric Andersen25f27032001-04-26 23:22:31 +00003065 /* but ctx->pipe and ctx->list_head remain unchanged */
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003066
Denis Vlasenkodd4cb2b2007-05-05 15:11:40 +00003067 return pi->num_progs; /* used only for 0/nonzero check */
Eric Andersen25f27032001-04-26 23:22:31 +00003068}
3069
3070static int done_pipe(struct p_context *ctx, pipe_style type)
3071{
3072 struct pipe *new_p;
Denis Vlasenkodd4cb2b2007-05-05 15:11:40 +00003073 int not_null;
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003074
3075 debug_printf_parse("done_pipe entered, followup %d\n", type);
Denis Vlasenkodd4cb2b2007-05-05 15:11:40 +00003076 not_null = done_command(ctx); /* implicit closure of previous command */
Eric Andersen25f27032001-04-26 23:22:31 +00003077 ctx->pipe->followup = type;
Denis Vlasenko219e88d2007-05-21 10:18:23 +00003078 ctx->pipe->res_word = ctx->res_w;
Denis Vlasenkodd4cb2b2007-05-05 15:11:40 +00003079 /* Without this check, even just <enter> on command line generates
3080 * tree of three NOPs (!). Which is harmless but annoying.
3081 * IOW: it is safe to do it unconditionally. */
3082 if (not_null) {
3083 new_p = new_pipe();
3084 ctx->pipe->next = new_p;
3085 ctx->pipe = new_p;
3086 ctx->child = NULL;
3087 done_command(ctx); /* set up new pipe to accept commands */
3088 }
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003089 debug_printf_parse("done_pipe return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003090 return 0;
3091}
3092
3093/* peek ahead in the in_str to find out if we have a "&n" construct,
3094 * as in "2>&1", that represents duplicating a file descriptor.
3095 * returns either -2 (syntax error), -1 (no &), or the number found.
3096 */
3097static int redirect_dup_num(struct in_str *input)
3098{
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003099 int ch, d = 0, ok = 0;
Eric Andersen25f27032001-04-26 23:22:31 +00003100 ch = b_peek(input);
3101 if (ch != '&') return -1;
3102
3103 b_getch(input); /* get the & */
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003104 ch = b_peek(input);
Eric Andersen83a2ae22001-05-07 17:59:25 +00003105 if (ch == '-') {
3106 b_getch(input);
3107 return -3; /* "-" represents "close me" */
3108 }
3109 while (isdigit(ch)) {
Denis Vlasenko7d4c44e2007-04-16 22:34:39 +00003110 d = d*10 + (ch-'0');
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003111 ok = 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003112 b_getch(input);
Eric Andersen83a2ae22001-05-07 17:59:25 +00003113 ch = b_peek(input);
Eric Andersen25f27032001-04-26 23:22:31 +00003114 }
3115 if (ok) return d;
3116
Manuel Novoa III cad53642003-03-19 09:13:01 +00003117 bb_error_msg("ambiguous redirect");
Eric Andersen25f27032001-04-26 23:22:31 +00003118 return -2;
3119}
3120
3121/* If a redirect is immediately preceded by a number, that number is
3122 * supposed to tell which file descriptor to redirect. This routine
3123 * looks for such preceding numbers. In an ideal world this routine
3124 * needs to handle all the following classes of redirects...
3125 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
3126 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
3127 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
3128 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
3129 * A -1 output from this program means no valid number was found, so the
3130 * caller should use the appropriate default for this redirection.
3131 */
3132static int redirect_opt_num(o_string *o)
3133{
3134 int num;
3135
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003136 if (o->length == 0)
3137 return -1;
3138 for (num = 0; num < o->length; num++) {
3139 if (!isdigit(*(o->data + num))) {
Eric Andersen25f27032001-04-26 23:22:31 +00003140 return -1;
3141 }
3142 }
3143 /* reuse num (and save an int) */
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003144 num = atoi(o->data);
Eric Andersen25f27032001-04-26 23:22:31 +00003145 b_reset(o);
3146 return num;
3147}
3148
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003149#if ENABLE_HUSH_TICK
Denis Vlasenko8412d792007-10-01 09:59:47 +00003150/* NB: currently disabled on NOMMU */
"Vladimir N. Oleynik"19c37012005-09-22 14:33:15 +00003151static FILE *generate_stream_from_list(struct pipe *head)
Eric Andersen25f27032001-04-26 23:22:31 +00003152{
3153 FILE *pf;
Eric Andersen25f27032001-04-26 23:22:31 +00003154 int pid, channel[2];
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00003155
Denis Vlasenko5a6aedd2007-05-26 16:44:20 +00003156 xpipe(channel);
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003157 pid = fork();
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003158 if (pid < 0) {
Manuel Novoa III cad53642003-03-19 09:13:01 +00003159 bb_perror_msg_and_die("fork");
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003160 } else if (pid == 0) {
Eric Andersen25f27032001-04-26 23:22:31 +00003161 close(channel[0]);
3162 if (channel[1] != 1) {
Denis Vlasenko7d4c44e2007-04-16 22:34:39 +00003163 dup2(channel[1], 1);
Eric Andersen25f27032001-04-26 23:22:31 +00003164 close(channel[1]);
3165 }
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00003166 /* Prevent it from trying to handle ctrl-z etc */
Denis Vlasenko27f79ff2007-05-30 00:55:52 +00003167#if ENABLE_HUSH_JOB
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00003168 run_list_level = 1;
Denis Vlasenko27f79ff2007-05-30 00:55:52 +00003169#endif
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00003170 /* Process substitution is not considered to be usual
3171 * 'command execution'.
3172 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not. */
3173 /* Not needed, we are relying on it being disabled
3174 * everywhere outside actual command execution. */
3175 /*set_jobctrl_sighandler(SIG_IGN);*/
3176 set_misc_sighandler(SIG_DFL);
Eric Andersen94ac2442001-05-22 19:05:18 +00003177 _exit(run_list_real(head)); /* leaks memory */
Eric Andersen25f27032001-04-26 23:22:31 +00003178 }
Eric Andersen25f27032001-04-26 23:22:31 +00003179 close(channel[1]);
Denis Vlasenko5f786c22007-04-20 08:35:45 +00003180 pf = fdopen(channel[0], "r");
Eric Andersen25f27032001-04-26 23:22:31 +00003181 return pf;
3182}
3183
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003184/* Return code is exit status of the process that is run. */
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003185static int process_command_subs(o_string *dest, struct p_context *ctx,
3186 struct in_str *input, const char *subst_end)
Eric Andersen25f27032001-04-26 23:22:31 +00003187{
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00003188 int retcode, ch, eol_cnt;
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003189 o_string result = NULL_O_STRING;
Eric Andersen25f27032001-04-26 23:22:31 +00003190 struct p_context inner;
3191 FILE *p;
3192 struct in_str pipe_str;
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00003193
Eric Andersen25f27032001-04-26 23:22:31 +00003194 initialize_context(&inner);
3195
3196 /* recursion to generate command */
3197 retcode = parse_stream(&result, &inner, input, subst_end);
Denis Vlasenko1a735862007-05-23 00:32:25 +00003198 if (retcode != 0)
3199 return retcode; /* syntax error or EOF */
Eric Andersen25f27032001-04-26 23:22:31 +00003200 done_word(&result, &inner);
3201 done_pipe(&inner, PIPE_SEQ);
3202 b_free(&result);
3203
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003204 p = generate_stream_from_list(inner.list_head);
3205 if (p == NULL) return 1;
Denis Vlasenkoa0898172007-10-01 09:59:01 +00003206 close_on_exec_on(fileno(p));
Eric Andersen25f27032001-04-26 23:22:31 +00003207 setup_file_in_str(&pipe_str, p);
3208
3209 /* now send results of command back into original context */
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00003210 eol_cnt = 0;
3211 while ((ch = b_getch(&pipe_str)) != EOF) {
3212 if (ch == '\n') {
3213 eol_cnt++;
3214 continue;
3215 }
3216 while (eol_cnt) {
Denis Vlasenkoff097622007-10-01 10:00:45 +00003217 b_addqchr(dest, '\n', dest->o_quote);
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00003218 eol_cnt--;
3219 }
Denis Vlasenkoff097622007-10-01 10:00:45 +00003220 b_addqchr(dest, ch, dest->o_quote);
Eric Andersen25f27032001-04-26 23:22:31 +00003221 }
3222
3223 debug_printf("done reading from pipe, pclose()ing\n");
3224 /* This is the step that wait()s for the child. Should be pretty
3225 * safe, since we just read an EOF from its stdout. We could try
Denis Vlasenko262d7652007-05-20 21:52:49 +00003226 * to do better, by using wait(), and keeping track of background jobs
Eric Andersen25f27032001-04-26 23:22:31 +00003227 * at the same time. That would be a lot of work, and contrary
3228 * to the KISS philosophy of this program. */
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00003229 retcode = fclose(p);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003230 free_pipe_list(inner.list_head, 0);
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00003231 debug_printf("closed FILE from child, retcode=%d\n", retcode);
Eric Andersen25f27032001-04-26 23:22:31 +00003232 return retcode;
3233}
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003234#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003235
3236static int parse_group(o_string *dest, struct p_context *ctx,
3237 struct in_str *input, int ch)
3238{
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003239 int rcode;
3240 const char *endch = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00003241 struct p_context sub;
3242 struct child_prog *child = ctx->child;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003243
3244 debug_printf_parse("parse_group entered\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003245 if (child->argv) {
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003246 syntax(NULL);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003247 debug_printf_parse("parse_group return 1: syntax error, groups and arglists don't mix\n");
3248 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003249 }
3250 initialize_context(&sub);
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003251 endch = "}";
3252 if (ch == '(') {
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003253 endch = ")";
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003254 child->subshell = 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003255 }
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003256 rcode = parse_stream(dest, &sub, input, endch);
Denis Vlasenko5a1437d2007-05-24 13:22:47 +00003257//vda: err chk?
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003258 done_word(dest, &sub); /* finish off the final word in the subcontext */
Eric Andersen25f27032001-04-26 23:22:31 +00003259 done_pipe(&sub, PIPE_SEQ); /* and the final command there, too */
3260 child->group = sub.list_head;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003261
3262 debug_printf_parse("parse_group return %d\n", rcode);
Eric Andersen25f27032001-04-26 23:22:31 +00003263 return rcode;
3264 /* child remains "open", available for possible redirects */
3265}
3266
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003267/* Basically useful version until someone wants to get fancier,
Eric Andersen25f27032001-04-26 23:22:31 +00003268 * see the bash man page under "Parameter Expansion" */
Denis Vlasenko15d78fb2007-01-30 22:28:21 +00003269static const char *lookup_param(const char *src)
Eric Andersen25f27032001-04-26 23:22:31 +00003270{
Denis Vlasenkod76c0492007-05-25 02:16:25 +00003271 struct variable *var = get_local_var(src);
3272 if (var)
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00003273 return strchr(var->varstr, '=') + 1;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00003274 return NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00003275}
3276
3277/* return code: 0 for OK, 1 for syntax error */
3278static int handle_dollar(o_string *dest, struct p_context *ctx, struct in_str *input)
3279{
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003280 int ch = b_peek(input); /* first character after the $ */
Denis Vlasenkoff097622007-10-01 10:00:45 +00003281 unsigned char quote_mask = dest->o_quote ? 0x80 : 0;
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003282
3283 debug_printf_parse("handle_dollar entered: ch='%c'\n", ch);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00003284 if (isalpha(ch)) {
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003285 b_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003286 //sp: ctx->child->sp++;
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003287 while (1) {
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003288 debug_printf_parse(": '%c'\n", ch);
Eric Andersen25f27032001-04-26 23:22:31 +00003289 b_getch(input);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00003290 b_addchr(dest, ch | quote_mask);
3291 quote_mask = 0;
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003292 ch = b_peek(input);
3293 if (!isalnum(ch) && ch != '_')
3294 break;
Eric Andersen25f27032001-04-26 23:22:31 +00003295 }
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003296 b_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00003297 } else if (isdigit(ch)) {
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003298 make_one_char_var:
3299 b_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003300 //sp: ctx->child->sp++;
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003301 debug_printf_parse(": '%c'\n", ch);
3302 b_getch(input);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00003303 b_addchr(dest, ch | quote_mask);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003304 b_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00003305 } else switch (ch) {
Denis Vlasenko602d13c2007-05-13 18:34:53 +00003306 case '$': /* pid */
3307 case '!': /* last bg pid */
3308 case '?': /* last exit code */
3309 case '#': /* number of args */
3310 case '*': /* args */
3311 case '@': /* args */
3312 goto make_one_char_var;
Eric Andersen25f27032001-04-26 23:22:31 +00003313 case '{':
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003314 b_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003315 //sp: ctx->child->sp++;
Eric Andersen25f27032001-04-26 23:22:31 +00003316 b_getch(input);
3317 /* XXX maybe someone will try to escape the '}' */
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003318 while (1) {
3319 ch = b_getch(input);
Denis Vlasenkob0550012007-05-24 12:18:16 +00003320 if (ch == '}')
3321 break;
3322 if (!isalnum(ch) && ch != '_') {
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003323 syntax("unterminated ${name}");
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003324 debug_printf_parse("handle_dollar return 1: unterminated ${name}\n");
3325 return 1;
3326 }
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003327 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00003328 b_addchr(dest, ch | quote_mask);
3329 quote_mask = 0;
Eric Andersen25f27032001-04-26 23:22:31 +00003330 }
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003331 b_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00003332 break;
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003333#if ENABLE_HUSH_TICK
Eric Andersen25f27032001-04-26 23:22:31 +00003334 case '(':
Matt Kraai9f8caf12001-05-02 16:26:12 +00003335 b_getch(input);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003336 process_command_subs(dest, ctx, input, ")");
Eric Andersen25f27032001-04-26 23:22:31 +00003337 break;
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003338#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003339 case '-':
3340 case '_':
3341 /* still unhandled, but should be eventually */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003342 bb_error_msg("unhandled syntax: $%c", ch);
Eric Andersen25f27032001-04-26 23:22:31 +00003343 return 1;
3344 break;
3345 default:
Denis Vlasenkoff097622007-10-01 10:00:45 +00003346 b_addqchr(dest, '$', dest->o_quote);
Eric Andersen25f27032001-04-26 23:22:31 +00003347 }
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00003348 debug_printf_parse("handle_dollar return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003349 return 0;
3350}
3351
Eric Andersen25f27032001-04-26 23:22:31 +00003352/* return code is 0 for normal exit, 1 for syntax error */
Denis Vlasenko5f786c22007-04-20 08:35:45 +00003353static int parse_stream(o_string *dest, struct p_context *ctx,
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003354 struct in_str *input, const char *end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00003355{
"Vladimir N. Oleynik"4ccd2b42006-01-31 09:27:48 +00003356 int ch, m;
Eric Andersen25f27032001-04-26 23:22:31 +00003357 int redir_fd;
3358 redir_type redir_style;
3359 int next;
3360
Denis Vlasenkoff097622007-10-01 10:00:45 +00003361 /* Only double-quote state is handled in the state variable dest->o_quote.
Eric Andersen25f27032001-04-26 23:22:31 +00003362 * A single-quote triggers a bypass of the main loop until its mate is
Denis Vlasenkoff097622007-10-01 10:00:45 +00003363 * found. When recursing, quote state is passed in via dest->o_quote. */
Eric Andersen25f27032001-04-26 23:22:31 +00003364
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003365 debug_printf_parse("parse_stream entered, end_trigger='%s'\n", end_trigger);
3366
Denis Vlasenko1a735862007-05-23 00:32:25 +00003367 while (1) {
Denis Vlasenko1a735862007-05-23 00:32:25 +00003368 m = CHAR_IFS;
3369 next = '\0';
Denis Vlasenko170435c2007-05-23 13:01:10 +00003370 ch = b_getch(input);
Denis Vlasenko1a735862007-05-23 00:32:25 +00003371 if (ch != EOF) {
3372 m = charmap[ch];
3373 if (ch != '\n')
3374 next = b_peek(input);
3375 }
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003376 debug_printf_parse(": ch=%c (%d) m=%d quote=%d\n",
Denis Vlasenkoff097622007-10-01 10:00:45 +00003377 ch, ch, m, dest->o_quote);
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003378 if (m == CHAR_ORDINARY
Denis Vlasenkoff097622007-10-01 10:00:45 +00003379 || (m != CHAR_SPECIAL && dest->o_quote)
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003380 ) {
Denis Vlasenko170435c2007-05-23 13:01:10 +00003381 if (ch == EOF) {
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003382 syntax("unterminated \"");
Denis Vlasenko170435c2007-05-23 13:01:10 +00003383 debug_printf_parse("parse_stream return 1: unterminated \"\n");
3384 return 1;
3385 }
Denis Vlasenkoff097622007-10-01 10:00:45 +00003386 b_addqchr(dest, ch, dest->o_quote);
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003387 continue;
3388 }
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003389 if (m == CHAR_IFS) {
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003390 if (done_word(dest, ctx)) {
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003391 debug_printf_parse("parse_stream return 1: done_word!=0\n");
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003392 return 1;
Eric Andersenaac75e52001-04-30 18:18:45 +00003393 }
Denis Vlasenko1a735862007-05-23 00:32:25 +00003394 if (ch == EOF)
3395 break;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003396 /* If we aren't performing a substitution, treat
3397 * a newline as a command separator.
3398 * [why we don't handle it exactly like ';'? --vda] */
3399 if (end_trigger && ch == '\n') {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003400 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003401 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003402 }
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003403 if ((end_trigger && strchr(end_trigger, ch))
Denis Vlasenkoff097622007-10-01 10:00:45 +00003404 && !dest->o_quote && ctx->res_w == RES_NONE
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003405 ) {
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003406 debug_printf_parse("parse_stream return 0: end_trigger char found\n");
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003407 return 0;
3408 }
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003409 if (m == CHAR_IFS)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003410 continue;
3411 switch (ch) {
Eric Andersen25f27032001-04-26 23:22:31 +00003412 case '#':
Denis Vlasenkoff097622007-10-01 10:00:45 +00003413 if (dest->length == 0 && !dest->o_quote) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003414 while (1) {
3415 ch = b_peek(input);
3416 if (ch == EOF || ch == '\n')
3417 break;
3418 b_getch(input);
3419 }
Eric Andersen25f27032001-04-26 23:22:31 +00003420 } else {
Denis Vlasenkoff097622007-10-01 10:00:45 +00003421 b_addqchr(dest, ch, dest->o_quote);
Eric Andersen25f27032001-04-26 23:22:31 +00003422 }
3423 break;
3424 case '\\':
3425 if (next == EOF) {
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003426 syntax("\\<eof>");
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003427 debug_printf_parse("parse_stream return 1: \\<eof>\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003428 return 1;
3429 }
Denis Vlasenkoff097622007-10-01 10:00:45 +00003430 b_addqchr(dest, '\\', dest->o_quote);
3431 b_addqchr(dest, b_getch(input), dest->o_quote);
Eric Andersen25f27032001-04-26 23:22:31 +00003432 break;
3433 case '$':
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003434 if (handle_dollar(dest, ctx, input) != 0) {
3435 debug_printf_parse("parse_stream return 1: handle_dollar returned non-0\n");
3436 return 1;
3437 }
Eric Andersen25f27032001-04-26 23:22:31 +00003438 break;
3439 case '\'':
3440 dest->nonnull = 1;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003441 while (1) {
3442 ch = b_getch(input);
3443 if (ch == EOF || ch == '\'')
3444 break;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003445 b_addchr(dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00003446 }
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003447 if (ch == EOF) {
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003448 syntax("unterminated '");
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003449 debug_printf_parse("parse_stream return 1: unterminated '\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003450 return 1;
3451 }
3452 break;
3453 case '"':
3454 dest->nonnull = 1;
Denis Vlasenkoff097622007-10-01 10:00:45 +00003455 dest->o_quote ^= 1; /* invert */
Eric Andersen25f27032001-04-26 23:22:31 +00003456 break;
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003457#if ENABLE_HUSH_TICK
Eric Andersen25f27032001-04-26 23:22:31 +00003458 case '`':
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003459 process_command_subs(dest, ctx, input, "`");
Eric Andersen25f27032001-04-26 23:22:31 +00003460 break;
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003461#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003462 case '>':
3463 redir_fd = redirect_opt_num(dest);
3464 done_word(dest, ctx);
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003465 redir_style = REDIRECT_OVERWRITE;
Eric Andersen25f27032001-04-26 23:22:31 +00003466 if (next == '>') {
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003467 redir_style = REDIRECT_APPEND;
Eric Andersen25f27032001-04-26 23:22:31 +00003468 b_getch(input);
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003469 }
3470#if 0
3471 else if (next == '(') {
3472 syntax(">(process) not supported");
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003473 debug_printf_parse("parse_stream return 1: >(process) not supported\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003474 return 1;
3475 }
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003476#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003477 setup_redirect(ctx, redir_fd, redir_style, input);
3478 break;
3479 case '<':
3480 redir_fd = redirect_opt_num(dest);
3481 done_word(dest, ctx);
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003482 redir_style = REDIRECT_INPUT;
Eric Andersen25f27032001-04-26 23:22:31 +00003483 if (next == '<') {
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003484 redir_style = REDIRECT_HEREIS;
Eric Andersen25f27032001-04-26 23:22:31 +00003485 b_getch(input);
3486 } else if (next == '>') {
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003487 redir_style = REDIRECT_IO;
Eric Andersen25f27032001-04-26 23:22:31 +00003488 b_getch(input);
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003489 }
3490#if 0
3491 else if (next == '(') {
3492 syntax("<(process) not supported");
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003493 debug_printf_parse("parse_stream return 1: <(process) not supported\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003494 return 1;
3495 }
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003496#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003497 setup_redirect(ctx, redir_fd, redir_style, input);
3498 break;
3499 case ';':
3500 done_word(dest, ctx);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003501 done_pipe(ctx, PIPE_SEQ);
Eric Andersen25f27032001-04-26 23:22:31 +00003502 break;
3503 case '&':
3504 done_word(dest, ctx);
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003505 if (next == '&') {
Eric Andersen25f27032001-04-26 23:22:31 +00003506 b_getch(input);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003507 done_pipe(ctx, PIPE_AND);
Eric Andersen25f27032001-04-26 23:22:31 +00003508 } else {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003509 done_pipe(ctx, PIPE_BG);
Eric Andersen25f27032001-04-26 23:22:31 +00003510 }
3511 break;
3512 case '|':
3513 done_word(dest, ctx);
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003514 if (next == '|') {
Eric Andersen25f27032001-04-26 23:22:31 +00003515 b_getch(input);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003516 done_pipe(ctx, PIPE_OR);
Eric Andersen25f27032001-04-26 23:22:31 +00003517 } else {
3518 /* we could pick up a file descriptor choice here
3519 * with redirect_opt_num(), but bash doesn't do it.
3520 * "echo foo 2| cat" yields "foo 2". */
3521 done_command(ctx);
3522 }
3523 break;
3524 case '(':
3525 case '{':
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003526 if (parse_group(dest, ctx, input, ch) != 0) {
3527 debug_printf_parse("parse_stream return 1: parse_group returned non-0\n");
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003528 return 1;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003529 }
Eric Andersen25f27032001-04-26 23:22:31 +00003530 break;
3531 case ')':
3532 case '}':
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003533 syntax("unexpected }"); /* Proper use of this character is caught by end_trigger */
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003534 debug_printf_parse("parse_stream return 1: unexpected '}'\n");
Eric Andersen25f27032001-04-26 23:22:31 +00003535 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003536 default:
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003537 if (ENABLE_HUSH_DEBUG)
3538 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
Eric Andersen25f27032001-04-26 23:22:31 +00003539 }
3540 }
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003541 /* Complain if quote? No, maybe we just finished a command substitution
Eric Andersen25f27032001-04-26 23:22:31 +00003542 * that was quoted. Example:
Eric Andersenc7bda1c2004-03-15 08:29:22 +00003543 * $ echo "`cat foo` plus more"
Eric Andersen25f27032001-04-26 23:22:31 +00003544 * and we just got the EOF generated by the subshell that ran "cat foo"
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003545 * The only real complaint is if we got an EOF when end_trigger != NULL,
Eric Andersen25f27032001-04-26 23:22:31 +00003546 * that is, we were really supposed to get end_trigger, and never got
3547 * one before the EOF. Can't use the standard "syntax error" return code,
3548 * so that parse_stream_outer can distinguish the EOF and exit smoothly. */
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003549 debug_printf_parse("parse_stream return %d\n", -(end_trigger != NULL));
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003550 if (end_trigger)
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00003551 return -1;
Eric Andersen25f27032001-04-26 23:22:31 +00003552 return 0;
3553}
3554
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003555static void set_in_charmap(const char *set, int code)
Eric Andersen25f27032001-04-26 23:22:31 +00003556{
Denis Vlasenkof5294e12007-04-14 10:09:57 +00003557 while (*set)
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003558 charmap[(unsigned char)*set++] = code;
Eric Andersen25f27032001-04-26 23:22:31 +00003559}
3560
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003561static void update_charmap(void)
Eric Andersen25f27032001-04-26 23:22:31 +00003562{
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003563 /* char *ifs and char charmap[256] are both globals. */
Eric Andersen25f27032001-04-26 23:22:31 +00003564 ifs = getenv("IFS");
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003565 if (ifs == NULL)
3566 ifs = " \t\n";
Eric Andersen25f27032001-04-26 23:22:31 +00003567 /* Precompute a list of 'flow through' behavior so it can be treated
3568 * quickly up front. Computation is necessary because of IFS.
3569 * Special case handling of IFS == " \t\n" is not implemented.
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003570 * The charmap[] array only really needs two bits each,
3571 * and on most machines that would be faster (reduced L1 cache use).
Eric Andersen25f27032001-04-26 23:22:31 +00003572 */
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003573 memset(charmap, CHAR_ORDINARY, sizeof(charmap));
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003574#if ENABLE_HUSH_TICK
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003575 set_in_charmap("\\$\"`", CHAR_SPECIAL);
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003576#else
3577 set_in_charmap("\\$\"", CHAR_SPECIAL);
3578#endif
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003579 set_in_charmap("<>;&|(){}#'", CHAR_ORDINARY_IF_QUOTED);
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00003580 set_in_charmap(ifs, CHAR_IFS); /* are ordinary if quoted */
Eric Andersen25f27032001-04-26 23:22:31 +00003581}
3582
Eric Andersenaff114c2004-04-14 17:51:38 +00003583/* most recursion does not come through here, the exception is
Denis Vlasenko170435c2007-05-23 13:01:10 +00003584 * from builtin_source() and builtin_eval() */
3585static int parse_and_run_stream(struct in_str *inp, int parse_flag)
Eric Andersen25f27032001-04-26 23:22:31 +00003586{
Eric Andersen25f27032001-04-26 23:22:31 +00003587 struct p_context ctx;
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003588 o_string temp = NULL_O_STRING;
Eric Andersen25f27032001-04-26 23:22:31 +00003589 int rcode;
3590 do {
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003591 ctx.parse_type = parse_flag;
Eric Andersen25f27032001-04-26 23:22:31 +00003592 initialize_context(&ctx);
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003593 update_charmap();
Denis Vlasenko219e88d2007-05-21 10:18:23 +00003594 if (!(parse_flag & PARSEFLAG_SEMICOLON) || (parse_flag & PARSEFLAG_REPARSING))
Denis Vlasenko8f6bdb42007-05-16 09:36:55 +00003595 set_in_charmap(";$&|", CHAR_ORDINARY);
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003596#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko5a1437d2007-05-24 13:22:47 +00003597 inp->promptmode = 0; /* PS1 */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003598#endif
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003599 /* We will stop & execute after each ';' or '\n'.
3600 * Example: "sleep 9999; echo TEST" + ctrl-C:
3601 * TEST should be printed */
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00003602 rcode = parse_stream(&temp, &ctx, inp, ";\n");
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003603 if (rcode != 1 && ctx.old_flag != 0) {
Denis Vlasenko90e485c2007-05-23 15:22:50 +00003604 syntax(NULL);
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003605 }
3606 if (rcode != 1 && ctx.old_flag == 0) {
3607 done_word(&temp, &ctx);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003608 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko400c5b62007-05-04 13:07:27 +00003609 debug_print_tree(ctx.list_head, 0);
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003610 debug_printf_exec("parse_stream_outer: run_list\n");
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003611 run_list(ctx.list_head);
3612 } else {
3613 if (ctx.old_flag != 0) {
3614 free(ctx.stack);
3615 b_reset(&temp);
Eric Andersenc7bda1c2004-03-15 08:29:22 +00003616 }
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003617 temp.nonnull = 0;
Denis Vlasenkoff097622007-10-01 10:00:45 +00003618 temp.o_quote = 0;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003619 inp->p = NULL;
Denis Vlasenko2f1bb362007-04-21 10:01:14 +00003620 free_pipe_list(ctx.list_head, 0);
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003621 }
Eric Andersena813afc2001-05-24 16:19:36 +00003622 b_free(&temp);
Denis Vlasenko219e88d2007-05-21 10:18:23 +00003623 } while (rcode != -1 && !(parse_flag & PARSEFLAG_EXIT_FROM_LOOP)); /* loop on syntax errors, return on EOF */
Eric Andersen25f27032001-04-26 23:22:31 +00003624 return 0;
3625}
3626
Denis Vlasenko170435c2007-05-23 13:01:10 +00003627static int parse_and_run_string(const char *s, int parse_flag)
Eric Andersen25f27032001-04-26 23:22:31 +00003628{
3629 struct in_str input;
3630 setup_string_in_str(&input, s);
Denis Vlasenko170435c2007-05-23 13:01:10 +00003631 return parse_and_run_stream(&input, parse_flag);
Eric Andersen25f27032001-04-26 23:22:31 +00003632}
3633
Denis Vlasenko170435c2007-05-23 13:01:10 +00003634static int parse_and_run_file(FILE *f)
Eric Andersen25f27032001-04-26 23:22:31 +00003635{
3636 int rcode;
3637 struct in_str input;
3638 setup_file_in_str(&input, f);
Denis Vlasenko170435c2007-05-23 13:01:10 +00003639 rcode = parse_and_run_stream(&input, PARSEFLAG_SEMICOLON);
Eric Andersen25f27032001-04-26 23:22:31 +00003640 return rcode;
3641}
3642
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003643#if ENABLE_HUSH_JOB
Eric Andersen6c947d22001-06-25 22:24:38 +00003644/* Make sure we have a controlling tty. If we get started under a job
3645 * aware app (like bash for example), make sure we are now in charge so
3646 * we don't fight over who gets the foreground */
Eric Anderseneaecbf32001-10-31 10:41:31 +00003647static void setup_job_control(void)
Eric Andersen52a97ca2001-06-22 06:49:26 +00003648{
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003649 pid_t shell_pgrp;
3650
Denis Vlasenkoa6a17852007-04-28 16:42:11 +00003651 saved_task_pgrp = shell_pgrp = getpgrp();
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003652 debug_printf_jobs("saved_task_pgrp=%d\n", saved_task_pgrp);
Denis Vlasenko96e1b382007-09-30 23:50:48 +00003653 close_on_exec_on(interactive_fd);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003654
Denis Vlasenkoa6a17852007-04-28 16:42:11 +00003655 /* If we were ran as 'hush &',
3656 * sleep until we are in the foreground. */
3657 while (tcgetpgrp(interactive_fd) != shell_pgrp) {
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00003658 /* Send TTIN to ourself (should stop us) */
Denis Vlasenkoff131b92007-04-10 15:42:06 +00003659 kill(- shell_pgrp, SIGTTIN);
Denis Vlasenkoa6a17852007-04-28 16:42:11 +00003660 shell_pgrp = getpgrp();
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003661 }
Eric Andersen52a97ca2001-06-22 06:49:26 +00003662
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003663 /* Ignore job-control and misc signals. */
3664 set_jobctrl_sighandler(SIG_IGN);
3665 set_misc_sighandler(SIG_IGN);
3666//huh? signal(SIGCHLD, SIG_IGN);
3667
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003668 /* We _must_ restore tty pgrp on fatal signals */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003669 set_fatal_sighandler(sigexit);
Eric Andersen6c947d22001-06-25 22:24:38 +00003670
3671 /* Put ourselves in our own process group. */
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00003672 setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
Eric Andersen6c947d22001-06-25 22:24:38 +00003673 /* Grab control of the terminal. */
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00003674 tcsetpgrp(interactive_fd, getpid());
Eric Andersen6c947d22001-06-25 22:24:38 +00003675}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00003676#endif
Eric Andersenada18ff2001-05-21 16:18:22 +00003677
Denis Vlasenko9b49a5e2007-10-11 10:05:36 +00003678int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Matt Kraai2d91deb2001-08-01 17:21:35 +00003679int hush_main(int argc, char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00003680{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00003681 static const char version_str[] ALIGN1 = "HUSH_VERSION="HUSH_VER_STR;
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00003682 static const struct variable const_shell_ver = {
3683 .next = NULL,
3684 .varstr = (char*)version_str,
3685 .max_len = 1, /* 0 can provoke free(name) */
3686 .flg_export = 1,
3687 .flg_read_only = 1,
3688 };
3689
Eric Andersen25f27032001-04-26 23:22:31 +00003690 int opt;
3691 FILE *input;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003692 char **e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00003693 struct variable *cur_var;
Eric Andersenbc604a22001-05-16 05:24:03 +00003694
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00003695 PTR_TO_GLOBALS = xzalloc(sizeof(G));
Denis Vlasenkod76c0492007-05-25 02:16:25 +00003696
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00003697 /* Deal with HUSH_VERSION */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00003698 shell_ver = const_shell_ver; /* copying struct here */
Denis Vlasenkod76c0492007-05-25 02:16:25 +00003699 top_var = &shell_ver;
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00003700 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
3701 /* Initialize our shell local variables with the values
Denis Vlasenkod76c0492007-05-25 02:16:25 +00003702 * currently living in the environment */
Denis Vlasenkod76c0492007-05-25 02:16:25 +00003703 cur_var = top_var;
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00003704 e = environ;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00003705 if (e) while (*e) {
3706 char *value = strchr(*e, '=');
3707 if (value) { /* paranoia */
3708 cur_var->next = xzalloc(sizeof(*cur_var));
3709 cur_var = cur_var->next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00003710 cur_var->varstr = *e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00003711 cur_var->max_len = strlen(*e);
3712 cur_var->flg_export = 1;
3713 }
3714 e++;
3715 }
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00003716 putenv((char *)version_str); /* reinstate HUSH_VERSION */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00003717
Denis Vlasenko38f63192007-01-22 09:03:07 +00003718#if ENABLE_FEATURE_EDITING
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00003719 line_input_state = new_line_input_t(FOR_SHELL);
3720#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003721 /* XXX what should these be while sourcing /etc/profile? */
3722 global_argc = argc;
3723 global_argv = argv;
Eric Andersen94ac2442001-05-22 19:05:18 +00003724 /* Initialize some more globals to non-zero values */
3725 set_cwd();
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003726#if ENABLE_HUSH_INTERACTIVE
3727#if ENABLE_FEATURE_EDITING
3728 cmdedit_set_initial_prompt();
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003729#endif
Eric Andersen94ac2442001-05-22 19:05:18 +00003730 PS2 = "> ";
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003731#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00003732
Denis Vlasenkod76c0492007-05-25 02:16:25 +00003733 if (EXIT_SUCCESS) /* otherwise is already done */
3734 last_return_code = EXIT_SUCCESS;
Eric Andersen25f27032001-04-26 23:22:31 +00003735
3736 if (argv[0] && argv[0][0] == '-') {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003737 debug_printf("sourcing /etc/profile\n");
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00003738 input = fopen("/etc/profile", "r");
3739 if (input != NULL) {
Denis Vlasenkoa0898172007-10-01 09:59:01 +00003740 close_on_exec_on(fileno(input));
Denis Vlasenko170435c2007-05-23 13:01:10 +00003741 parse_and_run_file(input);
Eric Andersena90f20b2001-06-26 23:00:21 +00003742 fclose(input);
3743 }
Eric Andersen25f27032001-04-26 23:22:31 +00003744 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003745 input = stdin;
Eric Andersenc7bda1c2004-03-15 08:29:22 +00003746
Eric Andersen25f27032001-04-26 23:22:31 +00003747 while ((opt = getopt(argc, argv, "c:xif")) > 0) {
3748 switch (opt) {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003749 case 'c':
Denis Vlasenko5f786c22007-04-20 08:35:45 +00003750 global_argv = argv + optind;
3751 global_argc = argc - optind;
Denis Vlasenko170435c2007-05-23 13:01:10 +00003752 opt = parse_and_run_string(optarg, PARSEFLAG_SEMICOLON);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003753 goto final_return;
3754 case 'i':
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003755 /* Well, we cannot just declare interactiveness,
3756 * we have to have some stuff (ctty, etc) */
3757 /* interactive_fd++; */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003758 break;
3759 case 'f':
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00003760 fake_mode = 1;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003761 break;
3762 default:
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00003763#ifndef BB_VER
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003764 fprintf(stderr, "Usage: sh [FILE]...\n"
3765 " or: sh -c command [args]...\n\n");
3766 exit(EXIT_FAILURE);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00003767#else
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003768 bb_show_usage();
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00003769#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003770 }
3771 }
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003772#if ENABLE_HUSH_JOB
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003773 /* A shell is interactive if the '-i' flag was given, or if all of
Eric Andersen25f27032001-04-26 23:22:31 +00003774 * the following conditions are met:
Denis Vlasenko55b2de72007-04-18 17:21:28 +00003775 * no -c command
Eric Andersen25f27032001-04-26 23:22:31 +00003776 * no arguments remaining or the -s flag given
3777 * standard input is a terminal
3778 * standard output is a terminal
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003779 * Refer to Posix.2, the description of the 'sh' utility. */
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003780 if (argv[optind] == NULL && input == stdin
3781 && isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)
3782 ) {
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003783 saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
3784 debug_printf("saved_tty_pgrp=%d\n", saved_tty_pgrp);
3785 if (saved_tty_pgrp >= 0) {
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003786 /* try to dup to high fd#, >= 255 */
3787 interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
3788 if (interactive_fd < 0) {
3789 /* try to dup to any fd */
3790 interactive_fd = dup(STDIN_FILENO);
3791 if (interactive_fd < 0)
3792 /* give up */
3793 interactive_fd = 0;
3794 }
Denis Vlasenko2f1bb362007-04-21 10:01:14 +00003795 // TODO: track & disallow any attempts of user
3796 // to (inadvertently) close/redirect it
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003797 }
Eric Andersen25f27032001-04-26 23:22:31 +00003798 }
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003799 debug_printf("interactive_fd=%d\n", interactive_fd);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003800 if (interactive_fd) {
Eric Andersen25f27032001-04-26 23:22:31 +00003801 /* Looks like they want an interactive shell */
Eric Andersen52a97ca2001-06-22 06:49:26 +00003802 setup_job_control();
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003803 /* Make xfuncs do cleanup on exit */
3804 die_sleep = -1; /* flag */
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003805// FIXME: should we reset die_sleep = 0 whereever we fork?
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003806 if (setjmp(die_jmp)) {
3807 /* xfunc has failed! die die die */
3808 hush_exit(xfunc_error_retval);
3809 }
Denis Vlasenko2f1bb362007-04-21 10:01:14 +00003810#if !ENABLE_FEATURE_SH_EXTRA_QUIET
Denis Vlasenkoca525b42007-06-13 12:27:17 +00003811 printf("\n\n%s hush - the humble shell v"HUSH_VER_STR"\n", bb_banner);
Denis Vlasenko2f1bb362007-04-21 10:01:14 +00003812 printf("Enter 'help' for a list of built-in commands.\n\n");
3813#endif
Eric Andersenada18ff2001-05-21 16:18:22 +00003814 }
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003815#elif ENABLE_HUSH_INTERACTIVE
3816/* no job control compiled, only prompt/line editing */
3817 if (argv[optind] == NULL && input == stdin
3818 && isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)
3819 ) {
3820 interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
3821 if (interactive_fd < 0) {
3822 /* try to dup to any fd */
3823 interactive_fd = dup(STDIN_FILENO);
3824 if (interactive_fd < 0)
3825 /* give up */
3826 interactive_fd = 0;
3827 }
3828 }
3829
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00003830#endif
Eric Andersenc7bda1c2004-03-15 08:29:22 +00003831
Denis Vlasenkobb81c582007-01-30 22:32:09 +00003832 if (argv[optind] == NULL) {
Denis Vlasenko170435c2007-05-23 13:01:10 +00003833 opt = parse_and_run_file(stdin);
Eric Andersene67c3ce2001-05-02 02:09:36 +00003834 goto final_return;
Eric Andersen25f27032001-04-26 23:22:31 +00003835 }
Eric Andersen25f27032001-04-26 23:22:31 +00003836
3837 debug_printf("\nrunning script '%s'\n", argv[optind]);
Denis Vlasenko4c978632007-02-03 03:31:13 +00003838 global_argv = argv + optind;
3839 global_argc = argc - optind;
Rob Landleyd921b2e2006-08-03 15:41:12 +00003840 input = xfopen(argv[optind], "r");
Denis Vlasenko170435c2007-05-23 13:01:10 +00003841 opt = parse_and_run_file(input);
Eric Andersen25f27032001-04-26 23:22:31 +00003842
Denis Vlasenkod76c0492007-05-25 02:16:25 +00003843 final_return:
3844
Denis Vlasenko38f63192007-01-22 09:03:07 +00003845#if ENABLE_FEATURE_CLEAN_UP
Eric Andersenaeb44c42001-05-22 20:29:00 +00003846 fclose(input);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00003847 if (cwd != bb_msg_unknown)
Eric Andersenaeb44c42001-05-22 20:29:00 +00003848 free((char*)cwd);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00003849 cur_var = top_var->next;
3850 while (cur_var) {
3851 struct variable *tmp = cur_var;
3852 if (!cur_var->max_len)
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00003853 free(cur_var->varstr);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00003854 cur_var = cur_var->next;
3855 free(tmp);
Eric Andersenaeb44c42001-05-22 20:29:00 +00003856 }
Eric Andersen25f27032001-04-26 23:22:31 +00003857#endif
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003858 hush_exit(opt ? opt : last_return_code);
Eric Andersen25f27032001-04-26 23:22:31 +00003859}