blob: db99cc908ee00ffb170fccb3785d5fc8b2363d42 [file] [log] [blame]
Eric Andersen25f27032001-04-26 23:22:31 +00001/* vi: set sw=4 ts=4: */
2/*
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003 * 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.
Eric Andersen25f27032001-04-26 23:22:31 +00007 *
8 * Copyright (C) 2000,2001 Larry Doolittle <larry@doolittle.boa.org>
Denis Vlasenkoc8d27332009-04-06 10:47:21 +00009 * Copyright (C) 2008,2009 Denys Vlasenko <vda.linux@googlemail.com>
Eric Andersen25f27032001-04-26 23:22:31 +000010 *
11 * Credits:
12 * The parser routines proper are all original material, first
Eric Andersencb81e642003-07-14 21:21:08 +000013 * written Dec 2000 and Jan 2001 by Larry Doolittle. The
14 * execution engine, the builtins, and much of the underlying
15 * support has been adapted from busybox-0.49pre's lash, which is
Eric Andersenc7bda1c2004-03-15 08:29:22 +000016 * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
Eric Andersencb81e642003-07-14 21:21:08 +000017 * written by Erik Andersen <andersen@codepoet.org>. That, in turn,
18 * is based in part on ladsh.c, by Michael K. Johnson and Erik W.
19 * Troan, which they placed in the public domain. I don't know
20 * how much of the Johnson/Troan code has survived the repeated
21 * rewrites.
22 *
Eric Andersen25f27032001-04-26 23:22:31 +000023 * Other credits:
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +000024 * o_addchr derived from similar w_addchar function in glibc-2.2.
Denis Vlasenko50f3aa42009-04-07 10:52:40 +000025 * parse_redirect, redirect_opt_num, and big chunks of main
Denis Vlasenko424f79b2009-03-22 14:23:34 +000026 * and many builtins derived from contributions by Erik Andersen.
27 * Miscellaneous bugfixes from Matt Kraai.
Eric Andersen25f27032001-04-26 23:22:31 +000028 *
29 * There are two big (and related) architecture differences between
30 * this parser and the lash parser. One is that this version is
31 * actually designed from the ground up to understand nearly all
32 * of the Bourne grammar. The second, consequential change is that
33 * the parser and input reader have been turned inside out. Now,
34 * the parser is in control, and asks for input as needed. The old
35 * way had the input reader in control, and it asked for parsing to
36 * take place as needed. The new way makes it much easier to properly
37 * handle the recursion implicit in the various substitutions, especially
38 * across continuation lines.
39 *
Mike Frysinger25a6ca02009-03-28 13:59:26 +000040 * POSIX syntax not implemented:
Eric Andersen78a7c992001-05-15 16:30:25 +000041 * aliases
Eric Andersen25f27032001-04-26 23:22:31 +000042 * <(list) and >(list) Process Substitution
Eric Andersen25f27032001-04-26 23:22:31 +000043 * Functions
Mike Frysinger25a6ca02009-03-28 13:59:26 +000044 * Tilde Expansion
Mike Frysinger25a6ca02009-03-28 13:59:26 +000045 *
Denis Vlasenkoc8d27332009-04-06 10:47:21 +000046 * Bash stuff (maybe optionally enable?):
Mike Frysinger25a6ca02009-03-28 13:59:26 +000047 * &> and >& redirection of stdout+stderr
48 * Brace expansion
49 * reserved words: [[ ]] function select
Mike Frysinger6379bb42009-03-28 18:55:03 +000050 * substrings ${var:1:5}
Mike Frysinger25a6ca02009-03-28 13:59:26 +000051 *
Denis Vlasenkoc8d27332009-04-06 10:47:21 +000052 * TODOs:
53 * grep for "TODO" and fix (some of them are easy)
Eric Andersen83a2ae22001-05-07 17:59:25 +000054 * change { and } from special chars to reserved words
Denis Vlasenkoc8d27332009-04-06 10:47:21 +000055 * builtins: return, ulimit
Eric Andersen25f27032001-04-26 23:22:31 +000056 * follow IFS rules more precisely, including update semantics
Eric Andersen25f27032001-04-26 23:22:31 +000057 * figure out what to do with backslash-newline
Eric Andersen25f27032001-04-26 23:22:31 +000058 * continuation lines, both explicit and implicit - done?
Denis Vlasenkoc8d27332009-04-06 10:47:21 +000059 * SIGHUP handling
60 * ^Z handling (and explain it in comments for mere humans)
61 * separate job control from interactiveness
62 * (testcase: booting with init=/bin/hush does not show prompt (2009-04))
63 * functions
Eric Andersen25f27032001-04-26 23:22:31 +000064 *
Bernhard Reutner-Fischer86f5c992006-01-22 22:55:11 +000065 * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
Eric Andersen25f27032001-04-26 23:22:31 +000066 */
Denis Vlasenko1aa7e472007-11-28 06:49:03 +000067#include "busybox.h" /* for APPLET_IS_NOFORK/NOEXEC */
Denis Vlasenkobe709c22008-07-28 00:01:16 +000068#include <glob.h>
69/* #include <dmalloc.h> */
70#if ENABLE_HUSH_CASE
71#include <fnmatch.h>
72#endif
Mike Frysinger98c52642009-04-02 10:02:37 +000073#include "math.h"
Mike Frysingera4f331d2009-04-07 06:03:22 +000074#include "match.h"
Denis Vlasenko50f3aa42009-04-07 10:52:40 +000075#ifndef PIPE_BUF
76# define PIPE_BUF 4096 /* amount of buffering in a pipe */
77#endif
Mike Frysinger98c52642009-04-02 10:02:37 +000078
Denis Vlasenko1943aec2009-04-09 14:15:57 +000079
80/* Debug build knobs */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +000081#define LEAK_HUNTING 0
82#define BUILD_AS_NOMMU 0
83/* Enable/disable sanity checks. Ok to enable in production,
84 * only adds a bit of bloat. Set to >1 to get non-production level verbosity.
85 * Keeping 1 for now even in released versions.
86 */
87#define HUSH_DEBUG 1
88/* In progress... */
89#define ENABLE_HUSH_FUNCTIONS 0
Denis Vlasenko1943aec2009-04-09 14:15:57 +000090
91
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +000092#if BUILD_AS_NOMMU
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +000093# undef BB_MMU
94# undef USE_FOR_NOMMU
95# undef USE_FOR_MMU
96# define BB_MMU 0
97# define USE_FOR_NOMMU(...) __VA_ARGS__
98# define USE_FOR_MMU(...)
99#endif
100
Denis Vlasenko61befda2008-11-25 01:36:03 +0000101#if defined SINGLE_APPLET_MAIN
102/* STANDALONE does not make sense, and won't compile */
103#undef CONFIG_FEATURE_SH_STANDALONE
104#undef ENABLE_FEATURE_SH_STANDALONE
105#undef USE_FEATURE_SH_STANDALONE
106#define SKIP_FEATURE_SH_STANDALONE(...) __VA_ARGS__
107#define ENABLE_FEATURE_SH_STANDALONE 0
108#define USE_FEATURE_SH_STANDALONE(...)
109#define SKIP_FEATURE_SH_STANDALONE(...) __VA_ARGS__
110#endif
111
Denis Vlasenko05743d72008-02-10 12:10:08 +0000112#if !ENABLE_HUSH_INTERACTIVE
113#undef ENABLE_FEATURE_EDITING
114#define ENABLE_FEATURE_EDITING 0
115#undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
116#define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
Denis Vlasenko8412d792007-10-01 09:59:47 +0000117#endif
118
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000119/* Do we support ANY keywords? */
120#if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
121#define HAS_KEYWORDS 1
122#define IF_HAS_KEYWORDS(...) __VA_ARGS__
123#define IF_HAS_NO_KEYWORDS(...)
124#else
125#define HAS_KEYWORDS 0
126#define IF_HAS_KEYWORDS(...)
127#define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
128#endif
Denis Vlasenko8412d792007-10-01 09:59:47 +0000129
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000130/* If you comment out one of these below, it will be #defined later
131 * to perform debug printfs to stderr: */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000132#define debug_printf(...) do {} while (0)
Denis Vlasenko400c5b62007-05-04 13:07:27 +0000133/* Finer-grained debug switches */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000134#define debug_printf_parse(...) do {} while (0)
135#define debug_print_tree(a, b) do {} while (0)
136#define debug_printf_exec(...) do {} while (0)
Denis Vlasenkof886fd22008-10-13 12:36:05 +0000137#define debug_printf_env(...) do {} while (0)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000138#define debug_printf_jobs(...) do {} while (0)
139#define debug_printf_expand(...) do {} while (0)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +0000140#define debug_printf_glob(...) do {} while (0)
141#define debug_printf_list(...) do {} while (0)
Denis Vlasenko30c9cc52008-06-17 07:24:29 +0000142#define debug_printf_subst(...) do {} while (0)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000143#define debug_printf_clean(...) do {} while (0)
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000144
145#ifndef debug_printf
146#define debug_printf(...) fprintf(stderr, __VA_ARGS__)
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000147#endif
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000148
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +0000149#ifndef debug_printf_parse
150#define debug_printf_parse(...) fprintf(stderr, __VA_ARGS__)
Denis Vlasenkod01ff132007-05-02 21:40:23 +0000151#endif
152
153#ifndef debug_printf_exec
154#define debug_printf_exec(...) fprintf(stderr, __VA_ARGS__)
155#endif
156
Denis Vlasenkof886fd22008-10-13 12:36:05 +0000157#ifndef debug_printf_env
158#define debug_printf_env(...) fprintf(stderr, __VA_ARGS__)
159#endif
160
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +0000161#ifndef debug_printf_jobs
162#define debug_printf_jobs(...) fprintf(stderr, __VA_ARGS__)
Denis Vlasenkob61e13d2008-06-17 05:11:43 +0000163#define DEBUG_JOBS 1
164#else
165#define DEBUG_JOBS 0
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +0000166#endif
167
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000168#ifndef debug_printf_expand
169#define debug_printf_expand(...) fprintf(stderr, __VA_ARGS__)
170#define DEBUG_EXPAND 1
Denis Vlasenkob61e13d2008-06-17 05:11:43 +0000171#else
172#define DEBUG_EXPAND 0
173#endif
174
175#ifndef debug_printf_glob
176#define debug_printf_glob(...) fprintf(stderr, __VA_ARGS__)
177#define DEBUG_GLOB 1
178#else
179#define DEBUG_GLOB 0
180#endif
181
182#ifndef debug_printf_list
183#define debug_printf_list(...) fprintf(stderr, __VA_ARGS__)
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000184#endif
185
Denis Vlasenko30c9cc52008-06-17 07:24:29 +0000186#ifndef debug_printf_subst
187#define debug_printf_subst(...) fprintf(stderr, __VA_ARGS__)
188#endif
189
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +0000190#ifndef debug_printf_clean
191/* broken, of course, but OK for testing */
192static const char *indenter(int i)
193{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +0000194 static const char blanks[] ALIGN1 =
195 " ";
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +0000196 return &blanks[sizeof(blanks) - i - 1];
197}
198#define debug_printf_clean(...) fprintf(stderr, __VA_ARGS__)
Denis Vlasenkoc666f712007-05-16 22:18:54 +0000199#define DEBUG_CLEAN 1
Denis Vlasenkoa0e65122009-04-05 23:39:14 +0000200#else
201#define DEBUG_CLEAN 0
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +0000202#endif
203
Denis Vlasenkob61e13d2008-06-17 05:11:43 +0000204#if DEBUG_EXPAND
205static void debug_print_strings(const char *prefix, char **vv)
206{
207 fprintf(stderr, "%s:\n", prefix);
208 while (*vv)
209 fprintf(stderr, " '%s'\n", *vv++);
210}
211#else
212#define debug_print_strings(prefix, vv) ((void)0)
213#endif
214
Denis Vlasenkob6e65562009-04-03 16:49:04 +0000215#define ERR_PTR ((void*)(long)1)
216
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000217#define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000218
Denis Vlasenkob6e65562009-04-03 16:49:04 +0000219#define SPECIAL_VAR_SYMBOL 3
Eric Andersen25f27032001-04-26 23:22:31 +0000220
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000221static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
222
223/* This supports saving pointers malloced in vfork child,
224 * to be freed in the parent. One pointer is saved in
225 * G.argv_from_re_execing global var instead. TODO: unify.
226 */
227#if !BB_MMU
228typedef struct nommu_save_t {
229 char **new_env;
230 char **old_env;
231 char **argv;
232} nommu_save_t;
233#endif
234
Denis Vlasenko55789c62008-06-18 16:30:42 +0000235/* The descrip member of this structure is only used to make
236 * debugging output pretty */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +0000237static const struct {
238 int mode;
Denis Vlasenkoef36ead2007-05-02 15:34:47 +0000239 signed char default_fd;
240 char descrip[3];
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +0000241} redir_table[] = {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +0000242 { 0, 0, "??" },
Eric Andersen25f27032001-04-26 23:22:31 +0000243 { O_RDONLY, 0, "<" },
244 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
245 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +0000246 { O_RDONLY, 0, "<<" },
247 { O_CREAT|O_RDWR, 1, "<>" },
248/* Should not be needed. Bogus default_fd helps in debugging */
249/* { O_RDONLY, 77, "<<" }, */
Eric Andersen25f27032001-04-26 23:22:31 +0000250};
251
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000252typedef enum reserved_style {
Eric Andersen25f27032001-04-26 23:22:31 +0000253 RES_NONE = 0,
Denis Vlasenko06810332007-05-21 23:30:54 +0000254#if ENABLE_HUSH_IF
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000255 RES_IF ,
256 RES_THEN ,
257 RES_ELIF ,
258 RES_ELSE ,
259 RES_FI ,
Denis Vlasenko06810332007-05-21 23:30:54 +0000260#endif
261#if ENABLE_HUSH_LOOPS
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000262 RES_FOR ,
263 RES_WHILE ,
264 RES_UNTIL ,
265 RES_DO ,
266 RES_DONE ,
Denis Vlasenkod91afa32008-07-29 11:10:01 +0000267#endif
268#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000269 RES_IN ,
Denis Vlasenko06810332007-05-21 23:30:54 +0000270#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +0000271#if ENABLE_HUSH_CASE
272 RES_CASE ,
273 /* two pseudo-keywords support contrived "case" syntax: */
274 RES_MATCH , /* "word)" */
275 RES_CASEI , /* "this command is inside CASE" */
276 RES_ESAC ,
277#endif
278 RES_XXXX ,
279 RES_SNTX
Eric Andersen25f27032001-04-26 23:22:31 +0000280} reserved_style;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000281
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000282typedef struct o_string {
283 char *data;
284 int length; /* position where data is appended */
285 int maxlen;
286 /* Protect newly added chars against globbing
287 * (by prepending \ to *, ?, [, \) */
288 smallint o_escape;
289 smallint o_glob;
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000290 /* At least some part of the string was inside '' or "",
291 * possibly empty one: word"", wo''rd etc. */
292 smallint o_quoted;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000293 smallint has_empty_slot;
294 smallint o_assignment; /* 0:maybe, 1:yes, 2:no */
295} o_string;
296enum {
297 MAYBE_ASSIGNMENT = 0,
298 DEFINITELY_ASSIGNMENT = 1,
299 NOT_ASSIGNMENT = 2,
300 WORD_IS_KEYWORD = 3, /* not assigment, but next word may be: "if v=xyz cmd;" */
301};
302/* Used for initialization: o_string foo = NULL_O_STRING; */
303#define NULL_O_STRING { NULL }
304
305/* I can almost use ordinary FILE*. Is open_memstream() universally
306 * available? Where is it documented? */
307typedef struct in_str {
308 const char *p;
309 /* eof_flag=1: last char in ->p is really an EOF */
310 char eof_flag; /* meaningless if ->p == NULL */
311 char peek_buf[2];
312#if ENABLE_HUSH_INTERACTIVE
313 smallint promptme;
314 smallint promptmode; /* 0: PS1, 1: PS2 */
315#endif
316 FILE *file;
317 int (*get) (struct in_str *);
318 int (*peek) (struct in_str *);
319} in_str;
320#define i_getch(input) ((input)->get(input))
321#define i_peek(input) ((input)->peek(input))
322
Eric Andersen25f27032001-04-26 23:22:31 +0000323struct redir_struct {
Denis Vlasenko55789c62008-06-18 16:30:42 +0000324 struct redir_struct *next;
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000325 char *rd_filename; /* filename */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000326 int rd_fd; /* fd to redirect */
327 /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
328 int rd_dup;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000329 smallint rd_type; /* (enum redir_type) */
330 /* note: for heredocs, rd_filename contains heredoc delimiter,
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000331 * and subsequently heredoc itself; and rd_dup is a bitmask:
332 * 1: do we need to trim leading tabs?
333 * 2: is heredoc quoted (<<'dleim' syntax) ?
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000334 */
Eric Andersen25f27032001-04-26 23:22:31 +0000335};
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000336typedef enum redir_type {
337 REDIRECT_INVALID = 0,
338 REDIRECT_INPUT = 1,
339 REDIRECT_OVERWRITE = 2,
340 REDIRECT_APPEND = 3,
341 REDIRECT_HEREDOC = 4,
342 REDIRECT_IO = 5,
343 REDIRECT_HEREDOC2 = 6, /* REDIRECT_HEREDOC after heredoc is loaded */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +0000344
345 REDIRFD_CLOSE = -3,
346 REDIRFD_SYNTAX_ERR = -2,
347 REDIRFD_TO_FILE = -1, /* otherwise, rd_fd if redirected to rd_dup */
348
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +0000349 HEREDOC_SKIPTABS = 1,
350 HEREDOC_QUOTED = 2,
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +0000351} redir_type;
352
Eric Andersen25f27032001-04-26 23:22:31 +0000353
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000354struct command {
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000355 pid_t pid; /* 0 if exited */
Denis Vlasenko2b576b82008-08-04 00:46:07 +0000356 int assignment_cnt; /* how many argv[i] are assignments? */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000357 smallint is_stopped; /* is the command currently running? */
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000358 smallint grp_type; /* GRP_xxx */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000359 struct pipe *group; /* if non-NULL, this "command" is { list },
360 * ( list ), or a compound statement */
361#if !BB_MMU
362 char *group_as_string;
363#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000364 char **argv; /* command name and arguments */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000365 struct redir_struct *redirects; /* I/O redirections */
Eric Andersen25f27032001-04-26 23:22:31 +0000366};
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000367/* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
368 * and on execution these are substituted with their values.
369 * Substitution can make _several_ words out of one argv[n]!
370 * Example: argv[0]=='.^C*^C.' here: echo .$*.
Denis Vlasenkoc7985b72008-06-17 05:43:38 +0000371 * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +0000372 */
Denis Vlasenko371de4a2008-10-14 12:43:13 +0000373#define GRP_NORMAL 0
374#define GRP_SUBSHELL 1
375#if ENABLE_HUSH_FUNCTIONS
376#define GRP_FUNCTION 2
377#endif
Eric Andersen25f27032001-04-26 23:22:31 +0000378
379struct pipe {
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000380 struct pipe *next;
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000381 int num_cmds; /* total number of commands in job */
382 int alive_cmds; /* number of commands running (not exited) */
383 int stopped_cmds; /* number of commands alive, but stopped */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +0000384#if ENABLE_HUSH_JOB
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000385 int jobid; /* job number */
Denis Vlasenko0c886c62007-01-30 22:30:09 +0000386 pid_t pgrp; /* process group ID for the job */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000387 char *cmdtext; /* name of job */
Denis Vlasenkob81b3df2007-04-28 16:48:04 +0000388#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000389 struct command *cmds; /* array of commands in pipe */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000390 smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
Denis Vlasenko5ec61322008-06-24 00:50:07 +0000391 IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
392 IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
Eric Andersen25f27032001-04-26 23:22:31 +0000393};
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +0000394typedef enum pipe_style {
395 PIPE_SEQ = 1,
396 PIPE_AND = 2,
397 PIPE_OR = 3,
398 PIPE_BG = 4,
399} pipe_style;
Eric Andersen25f27032001-04-26 23:22:31 +0000400
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000401/* This holds pointers to the various results of parsing */
402struct parse_context {
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000403 /* linked list of pipes */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000404 struct pipe *list_head;
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000405 /* last pipe (being constructed right now) */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000406 struct pipe *pipe;
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000407 /* last command in pipe (being constructed right now) */
408 struct command *command;
409 /* last redirect in command->redirects list */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000410 struct redir_struct *pending_redirect;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +0000411#if !BB_MMU
412 o_string as_string;
413#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000414#if HAS_KEYWORDS
415 smallint ctx_res_w;
416 smallint ctx_inverted; /* "! cmd | cmd" */
417#if ENABLE_HUSH_CASE
418 smallint ctx_dsemicolon; /* ";;" seen */
419#endif
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000420 /* bitmask of FLAG_xxx, for figuring out valid reserved words */
421 int old_flag;
422 /* group we are enclosed in:
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000423 * example: "if pipe1; pipe2; then pipe3; fi"
424 * when we see "if" or "then", we malloc and copy current context,
425 * and make ->stack point to it. then we parse pipeN.
426 * when closing "then" / fi" / whatever is found,
427 * we move list_head into ->stack->command->group,
428 * copy ->stack into current context, and delete ->stack.
429 * (parsing of { list } and ( list ) doesn't use this method)
Denis Vlasenkof9f74292009-04-03 00:07:05 +0000430 */
Denis Vlasenko9af22c72008-10-09 12:54:58 +0000431 struct parse_context *stack;
432#endif
433};
434
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000435/* On program start, environ points to initial environment.
436 * putenv adds new pointers into it, unsetenv removes them.
437 * Neither of these (de)allocates the strings.
438 * setenv allocates new strings in malloc space and does putenv,
439 * and thus setenv is unusable (leaky) for shell's purposes */
440#define setenv(...) setenv_is_leaky_dont_use()
441struct variable {
442 struct variable *next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +0000443 char *varstr; /* points to "name=" portion */
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000444 int max_len; /* if > 0, name is part of initial env; else name is malloced */
445 smallint flg_export; /* putenv should be done on this var */
Denis Vlasenko219e88d2007-05-21 10:18:23 +0000446 smallint flg_read_only;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +0000447};
448
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000449enum {
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000450 BC_BREAK = 1,
451 BC_CONTINUE = 2,
452};
453
Denis Vlasenkod76c0492007-05-25 02:16:25 +0000454
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000455/* "Globals" within this file */
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000456/* Sorted roughly by size (smaller offsets == smaller code) */
457struct globals {
458#if ENABLE_HUSH_INTERACTIVE
459 /* 'interactive_fd' is a fd# open to ctty, if we have one
460 * _AND_ if we decided to act interactively */
461 int interactive_fd;
462 const char *PS1;
463 const char *PS2;
Denis Vlasenko60b392f2009-04-03 19:14:32 +0000464#define G_interactive_fd (G.interactive_fd)
465#else
466#define G_interactive_fd 0
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000467#endif
468#if ENABLE_FEATURE_EDITING
469 line_input_t *line_input_state;
470#endif
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +0000471 pid_t root_pid;
Denis Vlasenko87a86552008-07-29 19:43:10 +0000472 pid_t last_bg_pid;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000473#if ENABLE_HUSH_JOB
474 int run_list_level;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000475 pid_t saved_tty_pgrp;
476 int last_jobid;
477 struct pipe *job_list;
478 struct pipe *toplevel_list;
Denis Vlasenkod5762932009-03-31 11:22:57 +0000479//// smallint ctrl_z_flag;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000480#endif
Denis Vlasenko422cd7c2009-03-31 12:41:52 +0000481 smallint flag_SIGINT;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000482#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +0000483 smallint flag_break_continue;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000484#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000485 smallint fake_mode;
Denis Vlasenkoefea9d22009-04-09 13:43:11 +0000486 smallint exiting; /* used to prevent EXIT trap recursion */
Denis Vlasenkod5762932009-03-31 11:22:57 +0000487 /* These four support $?, $#, and $1 */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +0000488 smalluint last_exitcode;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000489 /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +0000490 smalluint global_args_malloced;
Denis Vlasenkoe1300f62009-03-22 11:41:18 +0000491 /* how many non-NULL argv's we have. NB: $# + 1 */
492 int global_argc;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000493 char **global_argv;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000494#if !BB_MMU
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +0000495 char *argv0_for_re_execing;
496 char **argv_from_re_execing;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +0000497#endif
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000498#if ENABLE_HUSH_LOOPS
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +0000499 unsigned depth_break_continue;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +0000500 unsigned depth_of_loop;
Denis Vlasenkodadfb492008-07-29 10:16:05 +0000501#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000502 const char *ifs;
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000503 const char *cwd;
Denis Vlasenko87a86552008-07-29 19:43:10 +0000504 struct variable *top_var; /* = &G.shell_ver (set in main()) */
Denis Vlasenko0a83fc32007-05-25 11:12:32 +0000505 struct variable shell_ver;
Denis Vlasenkod5762932009-03-31 11:22:57 +0000506 /* Signal and trap handling */
Denis Vlasenko7566bae2009-03-31 17:24:49 +0000507// unsigned count_SIGCHLD;
508// unsigned handled_SIGCHLD;
Denis Vlasenkod5762932009-03-31 11:22:57 +0000509 /* which signals have non-DFL handler (even with no traps set)? */
510 unsigned non_DFL_mask;
Denis Vlasenko7566bae2009-03-31 17:24:49 +0000511 char **traps; /* char *traps[NSIG] */
Denis Vlasenkod5762932009-03-31 11:22:57 +0000512 sigset_t blocked_set;
513 sigset_t inherited_set;
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000514#if HUSH_DEBUG
515 unsigned long memleak_value;
516#endif
Denis Vlasenko6da69cd2009-04-04 12:12:58 +0000517 char user_input_buf[ENABLE_FEATURE_EDITING ? BUFSIZ : 2];
518#if ENABLE_FEATURE_SH_STANDALONE
519 struct nofork_save_area nofork_save;
520#endif
521#if ENABLE_HUSH_JOB
522 sigjmp_buf toplevel_jb;
523#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000524};
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000525#define G (*ptr_to_globals)
Denis Vlasenko87a86552008-07-29 19:43:10 +0000526/* Not #defining name to G.name - this quickly gets unwieldy
527 * (too many defines). Also, I actually prefer to see when a variable
528 * is global, thus "G." prefix is a useful hint */
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000529#define INIT_G() do { \
530 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
531} while (0)
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000532
533
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000534/* Function prototypes for builtins */
535static int builtin_cd(char **argv);
536static int builtin_echo(char **argv);
537static int builtin_eval(char **argv);
538static int builtin_exec(char **argv);
539static int builtin_exit(char **argv);
540static int builtin_export(char **argv);
541#if ENABLE_HUSH_JOB
542static int builtin_fg_bg(char **argv);
543static int builtin_jobs(char **argv);
544#endif
545#if ENABLE_HUSH_HELP
546static int builtin_help(char **argv);
547#endif
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000548#if HUSH_DEBUG
549static int builtin_memleak(char **argv);
550#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000551static int builtin_pwd(char **argv);
552static int builtin_read(char **argv);
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000553static int builtin_set(char **argv);
554static int builtin_shift(char **argv);
555static int builtin_source(char **argv);
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000556static int builtin_test(char **argv);
557static int builtin_trap(char **argv);
558static int builtin_true(char **argv);
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000559static int builtin_umask(char **argv);
560static int builtin_unset(char **argv);
Mike Frysinger56bdea12009-03-28 20:01:58 +0000561static int builtin_wait(char **argv);
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000562#if ENABLE_HUSH_LOOPS
563static int builtin_break(char **argv);
564static int builtin_continue(char **argv);
565#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000566
567/* Table of built-in functions. They can be forked or not, depending on
568 * context: within pipes, they fork. As simple commands, they do not.
569 * When used in non-forking context, they can change global variables
570 * in the parent shell process. If forked, of course they cannot.
571 * For example, 'unset foo | whatever' will parse and run, but foo will
572 * still be set at the end. */
573struct built_in_command {
574 const char *cmd;
575 int (*function)(char **argv);
576#if ENABLE_HUSH_HELP
577 const char *descr;
578#define BLTIN(cmd, func, help) { cmd, func, help }
579#else
580#define BLTIN(cmd, func, help) { cmd, func }
581#endif
582};
583
584/* For now, echo and test are unconditionally enabled.
585 * Maybe make it configurable? */
586static const struct built_in_command bltins[] = {
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000587 BLTIN("." , builtin_source , "Run commands in a file"),
588 BLTIN(":" , builtin_true , "No-op"),
589 BLTIN("[" , builtin_test , "Test condition"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000590#if ENABLE_HUSH_JOB
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000591 BLTIN("bg" , builtin_fg_bg , "Resume a job in the background"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000592#endif
593#if ENABLE_HUSH_LOOPS
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000594 BLTIN("break" , builtin_break , "Exit from a loop"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000595#endif
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000596 BLTIN("cd" , builtin_cd , "Change directory"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000597#if ENABLE_HUSH_LOOPS
598 BLTIN("continue", builtin_continue, "Start new loop iteration"),
599#endif
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000600 BLTIN("echo" , builtin_echo , "Write to stdout"),
601 BLTIN("eval" , builtin_eval , "Construct and run shell command"),
602 BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
603 BLTIN("exit" , builtin_exit , "Exit"),
604 BLTIN("export" , builtin_export , "Set environment variable"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000605#if ENABLE_HUSH_JOB
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000606 BLTIN("fg" , builtin_fg_bg , "Bring job into the foreground"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000607#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000608#if ENABLE_HUSH_HELP
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000609 BLTIN("help" , builtin_help , "List shell built-in commands"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000610#endif
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000611#if ENABLE_HUSH_JOB
612 BLTIN("jobs" , builtin_jobs , "List active jobs"),
613#endif
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +0000614#if HUSH_DEBUG
615 BLTIN("memleak" , builtin_memleak , "Debug tool"),
616#endif
Denis Vlasenko34d4d892009-04-04 20:24:37 +0000617 BLTIN("pwd" , builtin_pwd , "Print current directory"),
618 BLTIN("read" , builtin_read , "Input environment variable"),
619// BLTIN("return" , builtin_return , "Return from a function"),
620 BLTIN("set" , builtin_set , "Set/unset shell local variables"),
621 BLTIN("shift" , builtin_shift , "Shift positional parameters"),
622 BLTIN("test" , builtin_test , "Test condition"),
623 BLTIN("trap" , builtin_trap , "Trap signals"),
624// BLTIN("ulimit" , builtin_return , "Control resource limits"),
625 BLTIN("umask" , builtin_umask , "Set file creation mask"),
626 BLTIN("unset" , builtin_unset , "Unset environment variable"),
627 BLTIN("wait" , builtin_wait , "Wait for process"),
Denis Vlasenko424f79b2009-03-22 14:23:34 +0000628};
629
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +0000630
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000631/* Leak hunting. Use hush_leaktool.sh for post-processing.
632 */
633#if LEAK_HUNTING
634static void *xxmalloc(int lineno, size_t size)
Denis Vlasenko90e485c2007-05-23 15:22:50 +0000635{
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000636 void *ptr = xmalloc((size + 0xff) & ~0xff);
637 fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
638 return ptr;
639}
640static void *xxrealloc(int lineno, void *ptr, size_t size)
641{
642 ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
643 fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
644 return ptr;
645}
646static char *xxstrdup(int lineno, const char *str)
647{
648 char *ptr = xstrdup(str);
649 fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
650 return ptr;
651}
652static void xxfree(void *ptr)
653{
654 fdprintf(2, "free %p\n", ptr);
655 free(ptr);
656}
657#define xmalloc(s) xxmalloc(__LINE__, s)
658#define xrealloc(p, s) xxrealloc(__LINE__, p, s)
659#define xstrdup(s) xxstrdup(__LINE__, s)
660#define free(p) xxfree(p)
661#endif
662
663
664/* Syntax and runtime errors. They always abort scripts.
665 * In interactive use they usually discard unparsed and/or unexecuted commands
666 * and return to the prompt.
667 * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
668 */
669#if HUSH_DEBUG < 2
Denis Vlasenkod68ae082009-04-09 20:41:34 +0000670# define die_if_script(lineno, fmt...) die_if_script(fmt)
671# define syntax_error(lineno, msg) syntax_error(msg)
672# define syntax_error_at(lineno, msg) syntax_error_at(msg)
673# define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
674# define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000675#endif
676
Denis Vlasenkod68ae082009-04-09 20:41:34 +0000677static void die_if_script(unsigned lineno, const char *fmt, ...)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000678{
Denis Vlasenkod68ae082009-04-09 20:41:34 +0000679 va_list p;
680
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000681#if HUSH_DEBUG >= 2
682 bb_error_msg("hush.c:%u", lineno);
683#endif
Denis Vlasenkod68ae082009-04-09 20:41:34 +0000684 va_start(p, fmt);
685 bb_verror_msg(fmt, p, NULL);
686 va_end(p);
687 if (!G_interactive_fd)
688 xfunc_die();
Mike Frysinger6379bb42009-03-28 18:55:03 +0000689}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000690
691static void syntax_error(unsigned lineno, const char *msg)
692{
693 if (msg)
694 die_if_script(lineno, "syntax error: %s", msg);
695 else
696 die_if_script(lineno, "syntax error", NULL);
697}
698
699static void syntax_error_at(unsigned lineno, const char *msg)
700{
701 die_if_script(lineno, "syntax error at '%s'", msg);
702}
703
Denis Vlasenkod68ae082009-04-09 20:41:34 +0000704static void syntax_error_unterm_ch(unsigned lineno, char ch)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000705{
706 char msg[2];
707 msg[0] = ch;
708 msg[1] = '\0';
709 die_if_script(lineno, "syntax error: unterminated %s", msg);
710}
711
Denis Vlasenkod68ae082009-04-09 20:41:34 +0000712static void syntax_error_unterm_str(unsigned lineno, const char *s)
713{
714 die_if_script(lineno, "syntax error: unterminated %s", s);
715}
716
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000717#if HUSH_DEBUG < 2
718# undef die_if_script
719# undef syntax_error
720# undef syntax_error_at
Denis Vlasenkod68ae082009-04-09 20:41:34 +0000721# undef syntax_error_unterm_ch
722# undef syntax_error_unterm_str
Denis Vlasenko90e485c2007-05-23 15:22:50 +0000723#else
Denis Vlasenkod68ae082009-04-09 20:41:34 +0000724# define die_if_script(fmt...) die_if_script(__LINE__, fmt)
725# define syntax_error(msg) syntax_error(__LINE__, msg)
726# define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
727# define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
728# define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
Denis Vlasenko90e485c2007-05-23 15:22:50 +0000729#endif
Eric Andersen25f27032001-04-26 23:22:31 +0000730
Denis Vlasenko552433b2009-04-04 19:29:21 +0000731
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000732/* Utility functions
733 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +0000734static int glob_needed(const char *s)
735{
736 while (*s) {
737 if (*s == '\\')
738 s++;
739 if (*s == '*' || *s == '[' || *s == '?')
740 return 1;
741 s++;
742 }
743 return 0;
744}
745
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000746static int is_well_formed_var_name(const char *s, char terminator)
Denis Vlasenko30c9cc52008-06-17 07:24:29 +0000747{
Denis Vlasenkod4981312008-07-31 10:34:48 +0000748 if (!s || !(isalpha(*s) || *s == '_'))
Denis Vlasenko30c9cc52008-06-17 07:24:29 +0000749 return 0;
750 s++;
751 while (isalnum(*s) || *s == '_')
752 s++;
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000753 return *s == terminator;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +0000754}
755
Denis Vlasenko55789c62008-06-18 16:30:42 +0000756/* Replace each \x with x in place, return ptr past NUL. */
757static char *unbackslash(char *src)
758{
759 char *dst = src;
760 while (1) {
761 if (*src == '\\')
762 src++;
763 if ((*dst++ = *src++) == '\0')
764 break;
765 }
766 return dst;
767}
768
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +0000769static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000770{
771 int i;
772 unsigned count1;
773 unsigned count2;
774 char **v;
775
776 v = strings;
777 count1 = 0;
778 if (v) {
779 while (*v) {
780 count1++;
781 v++;
782 }
783 }
784 count2 = 0;
785 v = add;
786 while (*v) {
787 count2++;
788 v++;
789 }
790 v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
791 v[count1 + count2] = NULL;
792 i = count2;
793 while (--i >= 0)
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +0000794 v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000795 return v;
796}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000797#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000798static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
799{
800 char **ptr = add_strings_to_strings(strings, add, need_to_dup);
801 fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
802 return ptr;
803}
804#define add_strings_to_strings(strings, add, need_to_dup) \
805 xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
806#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000807
Denis Vlasenko22d10a02008-10-13 08:53:43 +0000808static char **add_string_to_strings(char **strings, char *add)
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000809{
810 char *v[2];
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000811 v[0] = add;
812 v[1] = NULL;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +0000813 return add_strings_to_strings(strings, v, /*dup:*/ 0);
Denis Vlasenko22d10a02008-10-13 08:53:43 +0000814}
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +0000815#if LEAK_HUNTING
Denis Vlasenkocc90f442009-04-08 16:40:34 +0000816static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
817{
818 char **ptr = add_string_to_strings(strings, add);
819 fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
820 return ptr;
821}
822#define add_string_to_strings(strings, add) \
823 xx_add_string_to_strings(__LINE__, strings, add)
824#endif
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000825
Denis Vlasenko22d10a02008-10-13 08:53:43 +0000826static void putenv_all(char **strings)
827{
828 if (!strings)
829 return;
Denis Vlasenkof886fd22008-10-13 12:36:05 +0000830 while (*strings) {
831 debug_printf_env("putenv '%s'\n", *strings);
Denis Vlasenko22d10a02008-10-13 08:53:43 +0000832 putenv(*strings++);
Denis Vlasenkof886fd22008-10-13 12:36:05 +0000833 }
Denis Vlasenko22d10a02008-10-13 08:53:43 +0000834}
835
836static char **putenv_all_and_save_old(char **strings)
837{
838 char **old = NULL;
839 char **s = strings;
840
841 if (!strings)
842 return old;
843 while (*strings) {
Denis Vlasenkof886fd22008-10-13 12:36:05 +0000844 char *v, *eq;
845
846 eq = strchr(*strings, '=');
847 if (eq) {
848 *eq = '\0';
849 v = getenv(*strings);
850 *eq = '=';
851 if (v) {
852 /* v points to VAL in VAR=VAL, go back to VAR */
853 v -= (eq - *strings) + 1;
854 old = add_string_to_strings(old, v);
855 }
856 }
857 strings++;
Denis Vlasenko22d10a02008-10-13 08:53:43 +0000858 }
859 putenv_all(s);
860 return old;
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000861}
862
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +0000863static void free_strings_and_unsetenv(char **strings, int unset)
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000864{
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +0000865 char **v;
866
867 if (!strings)
868 return;
869
870 v = strings;
871 while (*v) {
872 if (unset) {
Denis Vlasenko76ddc2e2008-12-30 05:05:31 +0000873 debug_printf_env("unsetenv '%s'\n", *v);
874 bb_unsetenv(*v);
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +0000875 }
876 free(*v++);
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000877 }
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +0000878 free(strings);
Denis Vlasenkod65ea392007-10-01 10:02:25 +0000879}
880
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +0000881static void free_strings(char **strings)
Denis Vlasenko76d50412008-06-10 16:19:39 +0000882{
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +0000883 free_strings_and_unsetenv(strings, 0);
Denis Vlasenko76d50412008-06-10 16:19:39 +0000884}
Denis Vlasenko76d50412008-06-10 16:19:39 +0000885
886
Denis Vlasenkod5762932009-03-31 11:22:57 +0000887/* Basic theory of signal handling in shell
888 * ========================================
Denis Vlasenko7b830e72009-03-31 13:05:32 +0000889 * This does not describe what hush does, rather, it is current understanding
890 * what it _should_ do. If it doesn't, it's a bug.
Denis Vlasenkod5762932009-03-31 11:22:57 +0000891 * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
892 *
893 * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
894 * is finished or backgrounded. It is the same in interactive and
895 * non-interactive shells, and is the same regardless of whether
Denis Vlasenko7b830e72009-03-31 13:05:32 +0000896 * a user trap handler is installed or a shell special one is in effect.
Denis Vlasenkod5762932009-03-31 11:22:57 +0000897 * ^C or ^Z from keyboard seem to execute "at once" because it usually
898 * backgrounds (i.e. stops) or kills all members of currently running
899 * pipe.
900 *
901 * Wait builtin in interruptible by signals for which user trap is set
902 * or by SIGINT in interactive shell.
903 *
904 * Trap handlers will execute even within trap handlers. (right?)
905 *
Denis Vlasenkoefea9d22009-04-09 13:43:11 +0000906 * User trap handlers are forgotten when subshell ("(cmd)") is entered.
Denis Vlasenkod5762932009-03-31 11:22:57 +0000907 *
908 * If job control is off, backgrounded commands ("cmd &")
Denis Vlasenko7b830e72009-03-31 13:05:32 +0000909 * have SIGINT, SIGQUIT set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +0000910 *
911 * Commands run in command substitution ("`cmd`")
Denis Vlasenko7b830e72009-03-31 13:05:32 +0000912 * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
Denis Vlasenkod5762932009-03-31 11:22:57 +0000913 *
Denis Vlasenko7b830e72009-03-31 13:05:32 +0000914 * Ordinary commands have signals set to SIG_IGN/DFL set as inherited
915 * by the shell from its parent.
Denis Vlasenkod5762932009-03-31 11:22:57 +0000916 *
Denis Vlasenko7b830e72009-03-31 13:05:32 +0000917 * Siganls which differ from SIG_DFL action
918 * (note: child (i.e., [v]forked) shell is not an interactive shell):
Denis Vlasenkod5762932009-03-31 11:22:57 +0000919 *
920 * SIGQUIT: ignore
921 * SIGTERM (interactive): ignore
Denis Vlasenko7b830e72009-03-31 13:05:32 +0000922 * SIGHUP (interactive):
923 * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
Denis Vlasenkod5762932009-03-31 11:22:57 +0000924 * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
Denis Vlasenko7b830e72009-03-31 13:05:32 +0000925 * (note that ^Z is handled not by trapping SIGTSTP, but by seeing
926 * that all pipe members are stopped) (right?)
Denis Vlasenkod5762932009-03-31 11:22:57 +0000927 * SIGINT (interactive): wait for last pipe, ignore the rest
Denis Vlasenko7b830e72009-03-31 13:05:32 +0000928 * of the command line, show prompt. NB: ^C does not send SIGINT
929 * to interactive shell while shell is waiting for a pipe,
930 * since shell is bg'ed (is not in foreground process group).
931 * (check/expand this)
932 * Example 1: this waits 5 sec, but does not execute ls:
933 * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
934 * Example 2: this does not wait and does not execute ls:
935 * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
936 * Example 3: this does not wait 5 sec, but executes ls:
937 * "sleep 5; ls -l" + press ^C
Denis Vlasenkod5762932009-03-31 11:22:57 +0000938 *
939 * (What happens to signals which are IGN on shell start?)
940 * (What happens with signal mask on shell start?)
941 *
942 * Implementation in hush
943 * ======================
944 * We use in-kernel pending signal mask to determine which signals were sent.
945 * We block all signals which we don't want to take action immediately,
946 * i.e. we block all signals which need to have special handling as described
947 * above, and all signals which have traps set.
948 * After each pipe execution, we extract any pending signals via sigtimedwait()
949 * and act on them.
950 *
951 * unsigned non_DFL_mask: a mask of such "special" signals
952 * sigset_t blocked_set: current blocked signal set
953 *
Denis Vlasenko7b830e72009-03-31 13:05:32 +0000954 * "trap - SIGxxx":
Denis Vlasenko552433b2009-04-04 19:29:21 +0000955 * clear bit in blocked_set unless it is also in non_DFL_mask
Denis Vlasenko7b830e72009-03-31 13:05:32 +0000956 * "trap 'cmd' SIGxxx":
957 * set bit in blocked_set (even if 'cmd' is '')
Denis Vlasenkod5762932009-03-31 11:22:57 +0000958 * after [v]fork, if we plan to be a shell:
Denis Vlasenko7b830e72009-03-31 13:05:32 +0000959 * nothing for {} child shell (say, "true | { true; true; } | true")
Denis Vlasenkoefea9d22009-04-09 13:43:11 +0000960 * unset all traps if () shell.
Denis Vlasenkod5762932009-03-31 11:22:57 +0000961 * after [v]fork, if we plan to exec:
Denis Vlasenko7b830e72009-03-31 13:05:32 +0000962 * POSIX says pending signal mask is cleared in child - no need to clear it.
963 * Restore blocked signal set to one inherited by shell just prior to exec.
Denis Vlasenkod5762932009-03-31 11:22:57 +0000964 *
Denis Vlasenko7566bae2009-03-31 17:24:49 +0000965 * Note: as a result, we do not use signal handlers much. The only uses
966 * are to count SIGCHLDs [disabled - bug somewhere, + bloat]
967 * and to restore tty pgrp on signal-induced exit.
Denis Vlasenkod5762932009-03-31 11:22:57 +0000968 */
969
Denis Vlasenko7566bae2009-03-31 17:24:49 +0000970//static void SIGCHLD_handler(int sig UNUSED_PARAM)
971//{
972// G.count_SIGCHLD++;
973//}
974
Denis Vlasenko7566bae2009-03-31 17:24:49 +0000975static int check_and_run_traps(int sig)
Denis Vlasenkod5762932009-03-31 11:22:57 +0000976{
Denis Vlasenko7566bae2009-03-31 17:24:49 +0000977 static const struct timespec zero_timespec = { 0, 0 };
Denis Vlasenkod5762932009-03-31 11:22:57 +0000978 smalluint save_rcode;
Denis Vlasenko7566bae2009-03-31 17:24:49 +0000979 int last_sig = 0;
Denis Vlasenkod5762932009-03-31 11:22:57 +0000980
Denis Vlasenko7566bae2009-03-31 17:24:49 +0000981 if (sig)
982 goto jump_in;
Denis Vlasenkod5762932009-03-31 11:22:57 +0000983 while (1) {
Denis Vlasenko7566bae2009-03-31 17:24:49 +0000984 sig = sigtimedwait(&G.blocked_set, NULL, &zero_timespec);
Denis Vlasenkod5762932009-03-31 11:22:57 +0000985 if (sig <= 0)
986 break;
Denis Vlasenko7566bae2009-03-31 17:24:49 +0000987 jump_in:
988 last_sig = sig;
Denis Vlasenkod5762932009-03-31 11:22:57 +0000989 if (G.traps && G.traps[sig]) {
990 if (G.traps[sig][0]) {
991 /* We have user-defined handler */
992 char *argv[] = { NULL, xstrdup(G.traps[sig]), NULL };
Denis Vlasenkoab2b0642009-04-06 18:42:11 +0000993 save_rcode = G.last_exitcode;
Denis Vlasenkod5762932009-03-31 11:22:57 +0000994 builtin_eval(argv);
995 free(argv[1]);
Denis Vlasenkoab2b0642009-04-06 18:42:11 +0000996 G.last_exitcode = save_rcode;
Denis Vlasenkod5762932009-03-31 11:22:57 +0000997 } /* else: "" trap, ignoring signal */
998 continue;
999 }
1000 /* not a trap: special action */
Denis Vlasenkod5762932009-03-31 11:22:57 +00001001 switch (sig) {
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001002// case SIGCHLD:
1003// G.count_SIGCHLD++;
1004// break;
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001005 case SIGINT:
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001006 bb_putchar('\n');
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001007 G.flag_SIGINT = 1;
Denis Vlasenkod5762932009-03-31 11:22:57 +00001008 break;
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001009//TODO
1010// case SIGHUP: ...
1011// break;
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00001012 default: /* ignored: */
1013 /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001014 break;
Denis Vlasenkod5762932009-03-31 11:22:57 +00001015 }
Denis Vlasenkod5762932009-03-31 11:22:57 +00001016 }
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001017 return last_sig;
Denis Vlasenkod5762932009-03-31 11:22:57 +00001018}
1019
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00001020#if ENABLE_HUSH_JOB
Denis Vlasenko25af86f2009-04-07 13:29:27 +00001021
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001022/* After [v]fork, in child: do not restore tty pgrp on xfunc death */
1023#define disable_restore_tty_pgrp_on_exit() (die_sleep = 0)
Denis Vlasenko25af86f2009-04-07 13:29:27 +00001024/* After [v]fork, in parent: restore tty pgrp on xfunc death */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001025#define enable_restore_tty_pgrp_on_exit() (die_sleep = -1)
1026
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001027/* Restores tty foreground process group, and exits.
1028 * May be called as signal handler for fatal signal
1029 * (will faithfully resend signal to itself, producing correct exit state)
1030 * or called directly with -EXITCODE.
1031 * We also call it if xfunc is exiting. */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001032static void sigexit(int sig) NORETURN;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001033static void sigexit(int sig)
1034{
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001035 /* Disable all signals: job control, SIGPIPE, etc. */
Denis Vlasenko3f165fa2008-03-17 08:29:08 +00001036 sigprocmask_allsigs(SIG_BLOCK);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001037
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001038 /* Careful: we can end up here after [v]fork. Do not restore
Denis Vlasenko7b830e72009-03-31 13:05:32 +00001039 * tty pgrp then, only top-level shell process does that */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00001040 if (G_interactive_fd && getpid() == G.root_pid)
1041 tcsetpgrp(G_interactive_fd, G.saved_tty_pgrp);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001042
1043 /* Not a signal, just exit */
1044 if (sig <= 0)
1045 _exit(- sig);
1046
Denis Vlasenko400d8bb2008-02-24 13:36:01 +00001047 kill_myself_with_sig(sig); /* does not return */
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00001048}
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001049#else
1050
1051#define disable_restore_tty_pgrp_on_exit() ((void)0)
1052#define enable_restore_tty_pgrp_on_exit() ((void)0)
1053
Denis Vlasenkoe0755e52009-04-03 21:16:45 +00001054#endif
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001055
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001056/* Restores tty foreground process group, and exits. */
1057static void hush_exit(int exitcode) NORETURN;
1058static void hush_exit(int exitcode)
1059{
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00001060 if (G.exiting <= 0 && G.traps && G.traps[0] && G.traps[0][0]) {
1061 /* Prevent recursion:
1062 * trap "echo Hi; exit" EXIT; exit
1063 */
1064 char *argv[] = { NULL, G.traps[0], NULL };
1065 G.traps[0] = NULL;
1066 G.exiting = 1;
Denis Vlasenkod5762932009-03-31 11:22:57 +00001067 builtin_eval(argv);
1068 free(argv[1]);
1069 }
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001070
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00001071#if ENABLE_HUSH_JOB
1072 fflush(NULL); /* flush all streams */
1073 sigexit(- (exitcode & 0xff));
1074#else
1075 exit(exitcode);
1076#endif
Mike Frysinger9f8128f2009-03-29 23:49:37 +00001077}
1078
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00001079
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00001080static const char *set_cwd(void)
1081{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001082 /* xrealloc_getcwd_or_warn(arg) calls free(arg),
1083 * we must not try to free(bb_msg_unknown) */
Denis Vlasenko87a86552008-07-29 19:43:10 +00001084 if (G.cwd == bb_msg_unknown)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001085 G.cwd = NULL;
Denis Vlasenko87a86552008-07-29 19:43:10 +00001086 G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
1087 if (!G.cwd)
1088 G.cwd = bb_msg_unknown;
1089 return G.cwd;
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00001090}
1091
Denis Vlasenko83506862007-11-23 13:11:42 +00001092
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001093/* Get/check local shell variables */
1094static struct variable *get_local_var(const char *name)
1095{
1096 struct variable *cur;
1097 int len;
1098
1099 if (!name)
1100 return NULL;
1101 len = strlen(name);
1102 for (cur = G.top_var; cur; cur = cur->next) {
1103 if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
1104 return cur;
1105 }
1106 return NULL;
1107}
1108
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00001109static const char *get_local_var_value(const char *src)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001110{
1111 struct variable *var = get_local_var(src);
1112 if (var)
1113 return strchr(var->varstr, '=') + 1;
1114 return NULL;
1115}
1116
1117/* str holds "NAME=VAL" and is expected to be malloced.
Mike Frysinger6379bb42009-03-28 18:55:03 +00001118 * We take ownership of it.
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001119 * flg_export:
Mike Frysinger6379bb42009-03-28 18:55:03 +00001120 * 0: do not export
1121 * 1: export
1122 * -1: if NAME is set, leave export status alone
1123 * if NAME is not set, do not export
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001124 * flg_read_only is set only when we handle -R var=val
Mike Frysinger6379bb42009-03-28 18:55:03 +00001125 */
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001126#if BB_MMU
1127#define set_local_var(str, flg_export, flg_read_only) \
1128 set_local_var(str, flg_export)
1129#endif
1130static int set_local_var(char *str, int flg_export, int flg_read_only)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001131{
1132 struct variable *cur;
1133 char *value;
1134 int name_len;
1135
1136 value = strchr(str, '=');
1137 if (!value) { /* not expected to ever happen? */
1138 free(str);
1139 return -1;
1140 }
1141
1142 name_len = value - str + 1; /* including '=' */
1143 cur = G.top_var; /* cannot be NULL (we have HUSH_VERSION and it's RO) */
1144 while (1) {
1145 if (strncmp(cur->varstr, str, name_len) != 0) {
1146 if (!cur->next) {
1147 /* Bail out. Note that now cur points
1148 * to last var in linked list */
1149 break;
1150 }
1151 cur = cur->next;
1152 continue;
1153 }
1154 /* We found an existing var with this name */
1155 *value = '\0';
1156 if (cur->flg_read_only) {
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001157#if !BB_MMU
1158 if (!flg_read_only)
1159#endif
1160 bb_error_msg("%s: readonly variable", str);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001161 free(str);
1162 return -1;
1163 }
1164 debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
1165 unsetenv(str); /* just in case */
1166 *value = '=';
1167 if (strcmp(cur->varstr, str) == 0) {
1168 free_and_exp:
1169 free(str);
1170 goto exp;
1171 }
1172 if (cur->max_len >= strlen(str)) {
1173 /* This one is from startup env, reuse space */
1174 strcpy(cur->varstr, str);
1175 goto free_and_exp;
1176 }
1177 /* max_len == 0 signifies "malloced" var, which we can
1178 * (and has to) free */
1179 if (!cur->max_len)
1180 free(cur->varstr);
1181 cur->max_len = 0;
1182 goto set_str_and_exp;
1183 }
1184
1185 /* Not found - create next variable struct */
1186 cur->next = xzalloc(sizeof(*cur));
1187 cur = cur->next;
1188
1189 set_str_and_exp:
1190 cur->varstr = str;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00001191#if !BB_MMU
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001192 cur->flg_read_only = flg_read_only;
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00001193#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001194 exp:
Mike Frysinger6379bb42009-03-28 18:55:03 +00001195 if (flg_export == 1)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001196 cur->flg_export = 1;
1197 if (cur->flg_export) {
1198 debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
1199 return putenv(cur->varstr);
1200 }
1201 return 0;
1202}
1203
Mike Frysingerd690f682009-03-30 06:50:54 +00001204static int unset_local_var(const char *name)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001205{
1206 struct variable *cur;
1207 struct variable *prev = prev; /* for gcc */
1208 int name_len;
1209
1210 if (!name)
Mike Frysingerd690f682009-03-30 06:50:54 +00001211 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001212 name_len = strlen(name);
1213 cur = G.top_var;
1214 while (cur) {
1215 if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
1216 if (cur->flg_read_only) {
1217 bb_error_msg("%s: readonly variable", name);
Mike Frysingerd690f682009-03-30 06:50:54 +00001218 return EXIT_FAILURE;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001219 }
1220 /* prev is ok to use here because 1st variable, HUSH_VERSION,
1221 * is ro, and we cannot reach this code on the 1st pass */
1222 prev->next = cur->next;
1223 debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
1224 bb_unsetenv(cur->varstr);
1225 if (!cur->max_len)
1226 free(cur->varstr);
1227 free(cur);
Mike Frysingerd690f682009-03-30 06:50:54 +00001228 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001229 }
1230 prev = cur;
1231 cur = cur->next;
1232 }
Mike Frysingerd690f682009-03-30 06:50:54 +00001233 return EXIT_SUCCESS;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001234}
1235
Mike Frysinger98c52642009-04-02 10:02:37 +00001236#if ENABLE_SH_MATH_SUPPORT
1237#define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
1238#define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
1239static char *endofname(const char *name)
1240{
1241 char *p;
1242
1243 p = (char *) name;
1244 if (!is_name(*p))
1245 return p;
1246 while (*++p) {
1247 if (!is_in_name(*p))
1248 break;
1249 }
1250 return p;
1251}
1252
1253static void arith_set_local_var(const char *name, const char *val, int flags)
1254{
1255 /* arith code doesnt malloc space, so do it for it */
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00001256 char *var = xasprintf("%s=%s", name, val);
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00001257 set_local_var(var, flags, 0);
Mike Frysinger98c52642009-04-02 10:02:37 +00001258}
1259#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001260
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00001261
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001262/*
1263 * in_str support
1264 */
1265static int static_get(struct in_str *i)
1266{
1267 int ch = *i->p++;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00001268 if (ch != '\0')
1269 return ch;
1270 i->p--;
1271 return EOF;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001272}
1273
1274static int static_peek(struct in_str *i)
1275{
1276 return *i->p;
1277}
1278
1279#if ENABLE_HUSH_INTERACTIVE
1280
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001281static void cmdedit_set_initial_prompt(void)
1282{
Mike Frysingerec2c6552009-03-28 12:24:44 +00001283 if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1284 G.PS1 = getenv("PS1");
1285 if (G.PS1 == NULL)
1286 G.PS1 = "\\w \\$ ";
1287 } else
1288 G.PS1 = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001289}
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001290
1291static const char* setup_prompt_string(int promptmode)
1292{
1293 const char *prompt_str;
1294 debug_printf("setup_prompt_string %d ", promptmode);
Mike Frysingerec2c6552009-03-28 12:24:44 +00001295 if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
1296 /* Set up the prompt */
1297 if (promptmode == 0) { /* PS1 */
1298 free((char*)G.PS1);
1299 G.PS1 = xasprintf("%s %c ", G.cwd, (geteuid() != 0) ? '$' : '#');
1300 prompt_str = G.PS1;
1301 } else
1302 prompt_str = G.PS2;
1303 } else
1304 prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001305 debug_printf("result '%s'\n", prompt_str);
1306 return prompt_str;
1307}
1308
1309static void get_user_input(struct in_str *i)
1310{
1311 int r;
1312 const char *prompt_str;
1313
1314 prompt_str = setup_prompt_string(i->promptmode);
1315#if ENABLE_FEATURE_EDITING
1316 /* Enable command line editing only while a command line
1317 * is actually being read */
1318 do {
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001319 G.flag_SIGINT = 0;
1320 /* buglet: SIGINT will not make new prompt to appear _at once_,
1321 * only after <Enter>. (^C will work) */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001322 r = read_line_input(prompt_str, G.user_input_buf, BUFSIZ-1, G.line_input_state);
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001323 /* catch *SIGINT* etc (^C is handled by read_line_input) */
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001324 check_and_run_traps(0);
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001325 } while (r == 0 || G.flag_SIGINT); /* repeat if ^C or SIGINT */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001326 i->eof_flag = (r < 0);
1327 if (i->eof_flag) { /* EOF/error detected */
1328 G.user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
1329 G.user_input_buf[1] = '\0';
1330 }
1331#else
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001332 do {
1333 G.flag_SIGINT = 0;
1334 fputs(prompt_str, stdout);
1335 fflush(stdout);
1336 G.user_input_buf[0] = r = fgetc(i->file);
1337 /*G.user_input_buf[1] = '\0'; - already is and never changed */
Denis Vlasenko7566bae2009-03-31 17:24:49 +00001338//do we need check_and_run_traps(0)? (maybe only if stdin)
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00001339 } while (G.flag_SIGINT);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001340 i->eof_flag = (r == EOF);
1341#endif
1342 i->p = G.user_input_buf;
1343}
1344
1345#endif /* INTERACTIVE */
1346
1347/* This is the magic location that prints prompts
1348 * and gets data back from the user */
1349static int file_get(struct in_str *i)
1350{
1351 int ch;
1352
1353 /* If there is data waiting, eat it up */
1354 if (i->p && *i->p) {
1355#if ENABLE_HUSH_INTERACTIVE
1356 take_cached:
1357#endif
1358 ch = *i->p++;
1359 if (i->eof_flag && !*i->p)
1360 ch = EOF;
Denis Vlasenko913a2012009-04-05 22:17:04 +00001361 /* note: ch is never NUL */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001362 } else {
1363 /* need to double check i->file because we might be doing something
1364 * more complicated by now, like sourcing or substituting. */
1365#if ENABLE_HUSH_INTERACTIVE
Denis Vlasenko60b392f2009-04-03 19:14:32 +00001366 if (G_interactive_fd && i->promptme && i->file == stdin) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001367 do {
1368 get_user_input(i);
1369 } while (!*i->p); /* need non-empty line */
1370 i->promptmode = 1; /* PS2 */
1371 i->promptme = 0;
1372 goto take_cached;
1373 }
1374#endif
Denis Vlasenko913a2012009-04-05 22:17:04 +00001375 do ch = fgetc(i->file); while (ch == '\0');
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001376 }
Denis Vlasenko913a2012009-04-05 22:17:04 +00001377 debug_printf("file_get: got '%c' %d\n", ch, ch);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001378#if ENABLE_HUSH_INTERACTIVE
1379 if (ch == '\n')
1380 i->promptme = 1;
1381#endif
1382 return ch;
1383}
1384
Denis Vlasenko913a2012009-04-05 22:17:04 +00001385/* All callers guarantee this routine will never
1386 * be used right after a newline, so prompting is not needed.
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001387 */
1388static int file_peek(struct in_str *i)
1389{
1390 int ch;
1391 if (i->p && *i->p) {
1392 if (i->eof_flag && !i->p[1])
1393 return EOF;
1394 return *i->p;
Denis Vlasenko913a2012009-04-05 22:17:04 +00001395 /* note: ch is never NUL */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001396 }
Denis Vlasenko913a2012009-04-05 22:17:04 +00001397 do ch = fgetc(i->file); while (ch == '\0');
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001398 i->eof_flag = (ch == EOF);
1399 i->peek_buf[0] = ch;
1400 i->peek_buf[1] = '\0';
1401 i->p = i->peek_buf;
Denis Vlasenko913a2012009-04-05 22:17:04 +00001402 debug_printf("file_peek: got '%c' %d\n", ch, ch);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001403 return ch;
1404}
1405
1406static void setup_file_in_str(struct in_str *i, FILE *f)
1407{
1408 i->peek = file_peek;
1409 i->get = file_get;
1410#if ENABLE_HUSH_INTERACTIVE
1411 i->promptme = 1;
1412 i->promptmode = 0; /* PS1 */
1413#endif
1414 i->file = f;
1415 i->p = NULL;
1416}
1417
1418static void setup_string_in_str(struct in_str *i, const char *s)
1419{
1420 i->peek = static_peek;
1421 i->get = static_get;
1422#if ENABLE_HUSH_INTERACTIVE
1423 i->promptme = 1;
1424 i->promptmode = 0; /* PS1 */
1425#endif
1426 i->p = s;
1427 i->eof_flag = 0;
1428}
1429
1430
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001431/*
1432 * o_string support
1433 */
1434#define B_CHUNK (32 * sizeof(char*))
Eric Andersen25f27032001-04-26 23:22:31 +00001435
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001436static void o_reset(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00001437{
1438 o->length = 0;
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00001439 o->o_quoted = 0;
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001440 if (o->data)
1441 o->data[0] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00001442}
1443
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001444static void o_free(o_string *o)
Eric Andersen25f27032001-04-26 23:22:31 +00001445{
Aaron Lehmanna170e1c2002-11-28 11:27:31 +00001446 free(o->data);
Denis Vlasenkod65ea392007-10-01 10:02:25 +00001447 memset(o, 0, sizeof(*o));
Eric Andersen25f27032001-04-26 23:22:31 +00001448}
1449
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001450static ALWAYS_INLINE void o_free_unsafe(o_string *o)
1451{
1452 free(o->data);
1453}
1454
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001455static void o_grow_by(o_string *o, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001456{
1457 if (o->length + len > o->maxlen) {
1458 o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
1459 o->data = xrealloc(o->data, 1 + o->maxlen);
1460 }
1461}
1462
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001463static void o_addchr(o_string *o, int ch)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001464{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001465 debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
1466 o_grow_by(o, 1);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001467 o->data[o->length] = ch;
1468 o->length++;
1469 o->data[o->length] = '\0';
1470}
1471
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001472static void o_addblock(o_string *o, const char *str, int len)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001473{
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001474 o_grow_by(o, len);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001475 memcpy(&o->data[o->length], str, len);
1476 o->length += len;
1477 o->data[o->length] = '\0';
1478}
1479
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001480#if !BB_MMU
1481static void o_addstr(o_string *o, const char *str)
Mike Frysinger98c52642009-04-02 10:02:37 +00001482{
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001483 o_addblock(o, str, strlen(str));
1484}
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00001485static void nommu_addchr(o_string *o, int ch)
1486{
1487 if (o)
1488 o_addchr(o, ch);
1489}
1490#else
1491#define nommu_addchr(o, str) ((void)0)
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001492#endif
1493
1494static void o_addstr_with_NUL(o_string *o, const char *str)
1495{
1496 o_addblock(o, str, strlen(str) + 1);
Mike Frysinger98c52642009-04-02 10:02:37 +00001497}
1498
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001499static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
Denis Vlasenko55789c62008-06-18 16:30:42 +00001500{
1501 while (len) {
1502 o_addchr(o, *str);
1503 if (*str++ == '\\'
1504 && (*str != '*' && *str != '?' && *str != '[')
1505 ) {
1506 o_addchr(o, '\\');
1507 }
1508 len--;
1509 }
1510}
1511
Eric Andersen25f27032001-04-26 23:22:31 +00001512/* My analysis of quoting semantics tells me that state information
1513 * is associated with a destination, not a source.
1514 */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001515static void o_addqchr(o_string *o, int ch)
Eric Andersen25f27032001-04-26 23:22:31 +00001516{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001517 int sz = 1;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00001518 char *found = strchr("*?[\\", ch);
1519 if (found)
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001520 sz++;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00001521 o_grow_by(o, sz);
1522 if (found) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001523 o->data[o->length] = '\\';
1524 o->length++;
Eric Andersen25f27032001-04-26 23:22:31 +00001525 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001526 o->data[o->length] = ch;
1527 o->length++;
1528 o->data[o->length] = '\0';
Eric Andersen25f27032001-04-26 23:22:31 +00001529}
1530
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001531static void o_addQchr(o_string *o, int ch)
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00001532{
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001533 int sz = 1;
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00001534 if (o->o_escape && strchr("*?[\\", ch)) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001535 sz++;
1536 o->data[o->length] = '\\';
1537 o->length++;
1538 }
1539 o_grow_by(o, sz);
1540 o->data[o->length] = ch;
1541 o->length++;
1542 o->data[o->length] = '\0';
1543}
1544
1545static void o_addQstr(o_string *o, const char *str, int len)
1546{
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00001547 if (!o->o_escape) {
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001548 o_addblock(o, str, len);
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00001549 return;
1550 }
1551 while (len) {
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001552 char ch;
1553 int sz;
1554 int ordinary_cnt = strcspn(str, "*?[\\");
1555 if (ordinary_cnt > len) /* paranoia */
1556 ordinary_cnt = len;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001557 o_addblock(o, str, ordinary_cnt);
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001558 if (ordinary_cnt == len)
1559 return;
1560 str += ordinary_cnt;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001561 len -= ordinary_cnt + 1; /* we are processing + 1 char below */
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001562
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00001563 ch = *str++;
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001564 sz = 1;
1565 if (ch) { /* it is necessarily one of "*?[\\" */
1566 sz++;
1567 o->data[o->length] = '\\';
1568 o->length++;
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00001569 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00001570 o_grow_by(o, sz);
1571 o->data[o->length] = ch;
1572 o->length++;
1573 o->data[o->length] = '\0';
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00001574 }
1575}
1576
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001577/* A special kind of o_string for $VAR and `cmd` expansion.
1578 * It contains char* list[] at the beginning, which is grown in 16 element
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00001579 * increments. Actual string data starts at the next multiple of 16 * (char*).
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001580 * list[i] contains an INDEX (int!) into this string data.
1581 * It means that if list[] needs to grow, data needs to be moved higher up
1582 * but list[i]'s need not be modified.
1583 * NB: remembering how many list[i]'s you have there is crucial.
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001584 * o_finalize_list() operation post-processes this structure - calculates
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001585 * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
1586 */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001587#if DEBUG_EXPAND || DEBUG_GLOB
1588static void debug_print_list(const char *prefix, o_string *o, int n)
1589{
1590 char **list = (char**)o->data;
1591 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1592 int i = 0;
1593 fprintf(stderr, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d\n",
1594 prefix, list, n, string_start, o->length, o->maxlen);
1595 while (i < n) {
1596 fprintf(stderr, " list[%d]=%d '%s' %p\n", i, (int)list[i],
1597 o->data + (int)list[i] + string_start,
1598 o->data + (int)list[i] + string_start);
1599 i++;
1600 }
1601 if (n) {
1602 const char *p = o->data + (int)list[n - 1] + string_start;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00001603 fprintf(stderr, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001604 }
1605}
1606#else
1607#define debug_print_list(prefix, o, n) ((void)0)
1608#endif
1609
1610/* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
1611 * in list[n] so that it points past last stored byte so far.
1612 * It returns n+1. */
1613static int o_save_ptr_helper(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001614{
1615 char **list = (char**)o->data;
Denis Vlasenko895bea22008-06-10 18:06:24 +00001616 int string_start;
1617 int string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001618
1619 if (!o->has_empty_slot) {
Denis Vlasenko895bea22008-06-10 18:06:24 +00001620 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1621 string_len = o->length - string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001622 if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001623 debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001624 /* list[n] points to string_start, make space for 16 more pointers */
1625 o->maxlen += 0x10 * sizeof(list[0]);
1626 o->data = xrealloc(o->data, o->maxlen + 1);
Denis Vlasenko7049ff82008-06-25 09:53:17 +00001627 list = (char**)o->data;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001628 memmove(list + n + 0x10, list + n, string_len);
1629 o->length += 0x10 * sizeof(list[0]);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00001630 } else {
1631 debug_printf_list("list[%d]=%d string_start=%d\n",
1632 n, string_len, string_start);
1633 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001634 } else {
1635 /* We have empty slot at list[n], reuse without growth */
Denis Vlasenko895bea22008-06-10 18:06:24 +00001636 string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
1637 string_len = o->length - string_start;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00001638 debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
1639 n, string_len, string_start);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001640 o->has_empty_slot = 0;
1641 }
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +00001642 list[n] = (char*)(ptrdiff_t)string_len;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001643 return n + 1;
1644}
1645
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001646/* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001647static int o_get_last_ptr(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001648{
1649 char **list = (char**)o->data;
1650 int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1651
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +00001652 return ((int)(ptrdiff_t)list[n-1]) + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001653}
1654
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00001655/* o_glob performs globbing on last list[], saving each result
Denis Vlasenko55789c62008-06-18 16:30:42 +00001656 * as a new list[]. */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001657static int o_glob(o_string *o, int n)
1658{
1659 glob_t globdata;
1660 int gr;
1661 char *pattern;
1662
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001663 debug_printf_glob("start o_glob: n:%d o->data:%p\n", n, o->data);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001664 if (!o->data)
1665 return o_save_ptr_helper(o, n);
1666 pattern = o->data + o_get_last_ptr(o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001667 debug_printf_glob("glob pattern '%s'\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001668 if (!glob_needed(pattern)) {
1669 literal:
1670 o->length = unbackslash(pattern) - o->data;
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001671 debug_printf_glob("glob pattern '%s' is literal\n", pattern);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001672 return o_save_ptr_helper(o, n);
1673 }
1674
1675 memset(&globdata, 0, sizeof(globdata));
1676 gr = glob(pattern, 0, NULL, &globdata);
1677 debug_printf_glob("glob('%s'):%d\n", pattern, gr);
1678 if (gr == GLOB_NOSPACE)
1679 bb_error_msg_and_die("out of memory during glob");
1680 if (gr == GLOB_NOMATCH) {
1681 globfree(&globdata);
1682 goto literal;
1683 }
1684 if (gr != 0) { /* GLOB_ABORTED ? */
1685//TODO: testcase for bad glob pattern behavior
1686 bb_error_msg("glob(3) error %d on '%s'", gr, pattern);
1687 }
1688 if (globdata.gl_pathv && globdata.gl_pathv[0]) {
1689 char **argv = globdata.gl_pathv;
1690 o->length = pattern - o->data; /* "forget" pattern */
1691 while (1) {
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001692 o_addstr_with_NUL(o, *argv);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001693 n = o_save_ptr_helper(o, n);
1694 argv++;
1695 if (!*argv)
1696 break;
1697 }
1698 }
1699 globfree(&globdata);
1700 if (DEBUG_GLOB)
1701 debug_print_list("o_glob returning", o, n);
1702 return n;
1703}
1704
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00001705/* If o->o_glob == 1, glob the string so far remembered.
1706 * Otherwise, just finish current list[] and start new */
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001707static int o_save_ptr(o_string *o, int n)
1708{
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00001709 if (o->o_glob) { /* if globbing is requested */
1710 /* If o->has_empty_slot, list[n] was already globbed
1711 * (if it was requested back then when it was filled)
1712 * so don't do that again! */
1713 if (!o->has_empty_slot)
1714 return o_glob(o, n); /* o_save_ptr_helper is inside */
1715 }
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001716 return o_save_ptr_helper(o, n);
1717}
1718
1719/* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00001720static char **o_finalize_list(o_string *o, int n)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001721{
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001722 char **list;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001723 int string_start;
1724
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001725 n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
1726 if (DEBUG_EXPAND)
1727 debug_print_list("finalized", o, n);
Denis Vlasenko30c9cc52008-06-17 07:24:29 +00001728 debug_printf_expand("finalized n:%d\n", n);
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00001729 list = (char**)o->data;
1730 string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
1731 list[--n] = NULL;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001732 while (n) {
1733 n--;
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +00001734 list[n] = o->data + (int)(ptrdiff_t)list[n] + string_start;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001735 }
1736 return list;
1737}
1738
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00001739
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00001740/* Expansion can recurse */
1741#if ENABLE_HUSH_TICK
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00001742static int process_command_subs(o_string *dest, const char *s);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00001743#endif
1744static char *expand_string_to_string(const char *str);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001745#if BB_MMU
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00001746#define parse_stream_dquoted(as_string, dest, input, dquote_end) \
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001747 parse_stream_dquoted(dest, input, dquote_end)
1748#endif
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00001749static int parse_stream_dquoted(o_string *as_string,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001750 o_string *dest,
1751 struct in_str *input,
1752 int dquote_end);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00001753
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001754/* expand_strvec_to_strvec() takes a list of strings, expands
1755 * all variable references within and returns a pointer to
1756 * a list of expanded strings, possibly with larger number
1757 * of strings. (Think VAR="a b"; echo $VAR).
1758 * This new list is allocated as a single malloc block.
1759 * NULL-terminated list of char* pointers is at the beginning of it,
1760 * followed by strings themself.
1761 * Caller can deallocate entire list by single free(list). */
Eric Andersen25f27032001-04-26 23:22:31 +00001762
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001763/* Store given string, finalizing the word and starting new one whenever
1764 * we encounter IFS char(s). This is used for expanding variable values.
1765 * End-of-string does NOT finalize word: think about 'echo -$VAR-' */
1766static int expand_on_ifs(o_string *output, int n, const char *str)
Eric Andersen25f27032001-04-26 23:22:31 +00001767{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001768 while (1) {
1769 int word_len = strcspn(str, G.ifs);
1770 if (word_len) {
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00001771 if (output->o_escape || !output->o_glob)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001772 o_addQstr(output, str, word_len);
1773 else /* protect backslashes against globbing up :) */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001774 o_addblock_duplicate_backslash(output, str, word_len);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001775 str += word_len;
1776 }
1777 if (!*str) /* EOL - do not finalize word */
1778 break;
1779 o_addchr(output, '\0');
1780 debug_print_list("expand_on_ifs", output, n);
1781 n = o_save_ptr(output, n);
1782 str += strspn(str, G.ifs); /* skip ifs chars */
Eric Andersen25f27032001-04-26 23:22:31 +00001783 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001784 debug_print_list("expand_on_ifs[1]", output, n);
1785 return n;
Eric Andersen25f27032001-04-26 23:22:31 +00001786}
1787
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00001788/* Helper to expand $((...)) and heredoc body. These act as if
1789 * they are in double quotes, with the exception that they are not :).
1790 * Just the rules are similar: "expand only $var and `cmd`"
1791 *
1792 * Returns malloced string.
1793 * As an optimization, we return NULL if expansion is not needed.
1794 */
1795static char *expand_pseudo_dquoted(const char *str)
1796{
1797 char *exp_str;
1798 struct in_str input;
1799 o_string dest = NULL_O_STRING;
1800
1801 if (strchr(str, '$') == NULL
1802#if ENABLE_HUSH_TICK
1803 && strchr(str, '`') == NULL
1804#endif
1805 ) {
1806 return NULL;
1807 }
1808
1809 /* We need to expand. Example:
1810 * echo $(($a + `echo 1`)) $((1 + $((2)) ))
1811 */
1812 setup_string_in_str(&input, str);
1813 parse_stream_dquoted(NULL, &dest, &input, EOF);
1814 //bb_error_msg("'%s' -> '%s'", str, dest.data);
1815 exp_str = expand_string_to_string(dest.data);
1816 //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
1817 o_free_unsafe(&dest);
1818 return exp_str;
1819}
1820
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001821/* Expand all variable references in given string, adding words to list[]
1822 * at n, n+1,... positions. Return updated n (so that list[n] is next one
1823 * to be filled). This routine is extremely tricky: has to deal with
1824 * variables/parameters with whitespace, $* and $@, and constructs like
1825 * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
1826static int expand_vars_to_list(o_string *output, int n, char *arg, char or_mask)
Eric Andersen25f27032001-04-26 23:22:31 +00001827{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001828 /* or_mask is either 0 (normal case) or 0x80
1829 * (expansion of right-hand side of assignment == 1-element expand.
1830 * It will also do no globbing, and thus we must not backslash-quote!) */
Eric Andersen25f27032001-04-26 23:22:31 +00001831
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001832 char first_ch, ored_ch;
1833 int i;
1834 const char *val;
Mike Frysingera4f331d2009-04-07 06:03:22 +00001835 char *dyn_val, *p;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001836
Mike Frysingera4f331d2009-04-07 06:03:22 +00001837 dyn_val = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001838 ored_ch = 0;
1839
1840 debug_printf_expand("expand_vars_to_list: arg '%s'\n", arg);
1841 debug_print_list("expand_vars_to_list", output, n);
1842 n = o_save_ptr(output, n);
1843 debug_print_list("expand_vars_to_list[0]", output, n);
1844
1845 while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
1846#if ENABLE_HUSH_TICK
1847 o_string subst_result = NULL_O_STRING;
Denis Vlasenko96f67dc2007-05-17 13:02:41 +00001848#endif
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00001849#if ENABLE_SH_MATH_SUPPORT
1850 char arith_buf[sizeof(arith_t)*3 + 2];
1851#endif
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00001852 o_addblock(output, arg, p - arg);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001853 debug_print_list("expand_vars_to_list[1]", output, n);
1854 arg = ++p;
1855 p = strchr(p, SPECIAL_VAR_SYMBOL);
1856
1857 first_ch = arg[0] | or_mask; /* forced to "quoted" if or_mask = 0x80 */
1858 /* "$@" is special. Even if quoted, it can still
1859 * expand to nothing (not even an empty string) */
1860 if ((first_ch & 0x7f) != '@')
1861 ored_ch |= first_ch;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00001862
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001863 val = NULL;
1864 switch (first_ch & 0x7f) {
1865 /* Highest bit in first_ch indicates that var is double-quoted */
1866 case '$': /* pid */
1867 val = utoa(G.root_pid);
1868 break;
1869 case '!': /* bg pid */
1870 val = G.last_bg_pid ? utoa(G.last_bg_pid) : (char*)"";
1871 break;
1872 case '?': /* exitcode */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00001873 val = utoa(G.last_exitcode);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001874 break;
1875 case '#': /* argc */
Mike Frysinger6379bb42009-03-28 18:55:03 +00001876 if (arg[1] != SPECIAL_VAR_SYMBOL)
1877 /* actually, it's a ${#var} */
1878 goto case_default;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001879 val = utoa(G.global_argc ? G.global_argc-1 : 0);
1880 break;
1881 case '*':
1882 case '@':
1883 i = 1;
1884 if (!G.global_argv[i])
1885 break;
1886 ored_ch |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
1887 if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00001888 smallint sv = output->o_escape;
1889 /* unquoted var's contents should be globbed, so don't escape */
1890 output->o_escape = 0;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001891 while (G.global_argv[i]) {
1892 n = expand_on_ifs(output, n, G.global_argv[i]);
1893 debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
1894 if (G.global_argv[i++][0] && G.global_argv[i]) {
1895 /* this argv[] is not empty and not last:
1896 * put terminating NUL, start new word */
1897 o_addchr(output, '\0');
1898 debug_print_list("expand_vars_to_list[2]", output, n);
1899 n = o_save_ptr(output, n);
1900 debug_print_list("expand_vars_to_list[3]", output, n);
1901 }
1902 }
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00001903 output->o_escape = sv;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001904 } else
1905 /* If or_mask is nonzero, we handle assignment 'a=....$@.....'
1906 * and in this case should treat it like '$*' - see 'else...' below */
1907 if (first_ch == ('@'|0x80) && !or_mask) { /* quoted $@ */
1908 while (1) {
1909 o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i]));
1910 if (++i >= G.global_argc)
1911 break;
1912 o_addchr(output, '\0');
1913 debug_print_list("expand_vars_to_list[4]", output, n);
1914 n = o_save_ptr(output, n);
1915 }
1916 } else { /* quoted $*: add as one word */
1917 while (1) {
1918 o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i]));
1919 if (!G.global_argv[++i])
1920 break;
1921 if (G.ifs[0])
1922 o_addchr(output, G.ifs[0]);
1923 }
1924 }
1925 break;
1926 case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
1927 /* "Empty variable", used to make "" etc to not disappear */
1928 arg++;
1929 ored_ch = 0x80;
1930 break;
1931#if ENABLE_HUSH_TICK
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00001932 case '`': /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001933 *p = '\0';
1934 arg++;
1935//TODO: can we just stuff it into "output" directly?
1936 debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00001937 process_command_subs(&subst_result, arg);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001938 debug_printf_subst("SUBST RES '%s'\n", subst_result.data);
1939 val = subst_result.data;
1940 goto store_val;
Denis Vlasenko96f67dc2007-05-17 13:02:41 +00001941#endif
Mike Frysinger98c52642009-04-02 10:02:37 +00001942#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00001943 case '+': { /* <SPECIAL_VAR_SYMBOL>+cmd<SPECIAL_VAR_SYMBOL> */
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00001944 arith_eval_hooks_t hooks;
Mike Frysinger98c52642009-04-02 10:02:37 +00001945 arith_t res;
Mike Frysinger98c52642009-04-02 10:02:37 +00001946 int errcode;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00001947 char *exp_str;
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00001948
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00001949 arg++; /* skip '+' */
1950 *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
Mike Frysinger98c52642009-04-02 10:02:37 +00001951 debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00001952
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00001953 exp_str = expand_pseudo_dquoted(arg);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00001954 hooks.lookupvar = get_local_var_value;
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00001955 hooks.setvar = arith_set_local_var;
1956 hooks.endofname = endofname;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00001957 res = arith(exp_str ? exp_str : arg, &errcode, &hooks);
1958 free(exp_str);
1959
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00001960 if (errcode < 0) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001961 const char *msg = "error in arithmetic";
Mike Frysinger98c52642009-04-02 10:02:37 +00001962 switch (errcode) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00001963 case -3:
1964 msg = "exponent less than 0";
1965 break;
1966 case -2:
1967 msg = "divide by 0";
1968 break;
1969 case -5:
1970 msg = "expression recursion loop detected";
1971 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00001972 }
Denis Vlasenkod68ae082009-04-09 20:41:34 +00001973 die_if_script(msg);
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00001974 }
Mike Frysinger98c52642009-04-02 10:02:37 +00001975 debug_printf_subst("ARITH RES '"arith_t_fmt"'\n", res);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00001976 sprintf(arith_buf, arith_t_fmt, res);
1977 val = arith_buf;
Mike Frysinger98c52642009-04-02 10:02:37 +00001978 break;
1979 }
1980#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001981 default: /* <SPECIAL_VAR_SYMBOL>varname<SPECIAL_VAR_SYMBOL> */
Mike Frysinger6379bb42009-03-28 18:55:03 +00001982 case_default: {
Denis Vlasenko232be3e2009-04-05 09:16:00 +00001983 bool exp_len = false;
1984 bool exp_null = false;
1985 char *var = arg;
1986 char exp_save = exp_save; /* for compiler */
1987 char exp_op = exp_op; /* for compiler */
1988 char *exp_word = exp_word; /* for compiler */
Mike Frysinger6379bb42009-03-28 18:55:03 +00001989 size_t exp_off = 0;
Denis Vlasenko232be3e2009-04-05 09:16:00 +00001990
Denis Vlasenko424f79b2009-03-22 14:23:34 +00001991 *p = '\0';
1992 arg[0] = first_ch & 0x7f;
Mike Frysinger6379bb42009-03-28 18:55:03 +00001993
1994 /* prepare for expansions */
1995 if (var[0] == '#') {
1996 /* handle length expansion ${#var} */
1997 exp_len = true;
1998 ++var;
1999 } else {
2000 /* maybe handle parameter expansion */
Mike Frysingera4f331d2009-04-07 06:03:22 +00002001 exp_off = strcspn(var, ":-=+?%#");
Mike Frysinger6379bb42009-03-28 18:55:03 +00002002 if (!var[exp_off])
2003 exp_off = 0;
2004 if (exp_off) {
2005 exp_save = var[exp_off];
2006 exp_null = exp_save == ':';
2007 exp_word = var + exp_off;
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002008 if (exp_null)
2009 ++exp_word;
Mike Frysinger6379bb42009-03-28 18:55:03 +00002010 exp_op = *exp_word++;
2011 var[exp_off] = '\0';
2012 }
2013 }
2014
2015 /* lookup the variable in question */
2016 if (isdigit(var[0])) {
Mike Frysinger7c3e52c2009-03-28 21:06:22 +00002017 /* handle_dollar() should have vetted var for us */
Mike Frysinger6379bb42009-03-28 18:55:03 +00002018 i = xatoi_u(var);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002019 if (i < G.global_argc)
2020 val = G.global_argv[i];
2021 /* else val remains NULL: $N with too big N */
2022 } else
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00002023 val = get_local_var_value(var);
Mike Frysinger6379bb42009-03-28 18:55:03 +00002024
2025 /* handle any expansions */
2026 if (exp_len) {
2027 debug_printf_expand("expand: length of '%s' = ", val);
2028 val = utoa(val ? strlen(val) : 0);
2029 debug_printf_expand("%s\n", val);
2030 } else if (exp_off) {
Mike Frysingera4f331d2009-04-07 06:03:22 +00002031 if (exp_op == '%' || exp_op == '#') {
Mike Frysinger57e74672009-04-09 23:00:33 +00002032 if (val) {
2033 /* we need to do a pattern match */
2034 bool zero;
2035 char *loc;
2036 scan_t scan = pick_scan(exp_op, *exp_word, &zero);
2037 if (exp_op == *exp_word) /* ## or %% */
2038 ++exp_word;
2039 val = dyn_val = xstrdup(val);
2040 loc = scan(dyn_val, exp_word, zero);
2041 if (zero)
2042 val = loc;
2043 else
2044 *loc = '\0';
2045 }
Mike Frysingera4f331d2009-04-07 06:03:22 +00002046 } else {
2047 /* we need to do an expansion */
2048 int exp_test = (!val || (exp_null && !val[0]));
2049 if (exp_op == '+')
2050 exp_test = !exp_test;
2051 debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
2052 exp_null ? "true" : "false", exp_test);
2053 if (exp_test) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00002054 if (exp_op == '?') {
2055//TODO: how interactive bash aborts expansion mid-command?
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002056 /* ${var?[error_msg_if_unset]} */
2057 /* ${var:?[error_msg_if_unset_or_null]} */
2058 /* mimic bash message */
Denis Vlasenkod68ae082009-04-09 20:41:34 +00002059 die_if_script("%s: %s",
2060 var,
2061 exp_word[0] ? exp_word : "parameter null or not set"
2062 );
2063 } else {
Mike Frysingera4f331d2009-04-07 06:03:22 +00002064 val = exp_word;
Denis Vlasenkod68ae082009-04-09 20:41:34 +00002065 }
Mike Frysinger6379bb42009-03-28 18:55:03 +00002066
Mike Frysingera4f331d2009-04-07 06:03:22 +00002067 if (exp_op == '=') {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002068 /* ${var=[word]} or ${var:=[word]} */
Mike Frysingera4f331d2009-04-07 06:03:22 +00002069 if (isdigit(var[0]) || var[0] == '#') {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002070 /* mimic bash message */
2071 die_if_script("$%s: cannot assign in this way", var);
Mike Frysingera4f331d2009-04-07 06:03:22 +00002072 val = NULL;
2073 } else {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00002074 char *new_var = xasprintf("%s=%s", var, val);
Mike Frysingera4f331d2009-04-07 06:03:22 +00002075 set_local_var(new_var, -1, 0);
2076 }
Mike Frysinger6379bb42009-03-28 18:55:03 +00002077 }
2078 }
2079 }
Mike Frysingera4f331d2009-04-07 06:03:22 +00002080
Mike Frysinger6379bb42009-03-28 18:55:03 +00002081 var[exp_off] = exp_save;
2082 }
2083
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002084 arg[0] = first_ch;
2085#if ENABLE_HUSH_TICK
2086 store_val:
2087#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002088 if (!(first_ch & 0x80)) { /* unquoted $VAR */
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002089 debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val, output->o_escape);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002090 if (val) {
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002091 /* unquoted var's contents should be globbed, so don't escape */
2092 smallint sv = output->o_escape;
2093 output->o_escape = 0;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002094 n = expand_on_ifs(output, n, val);
2095 val = NULL;
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002096 output->o_escape = sv;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002097 }
2098 } else { /* quoted $VAR, val will be appended below */
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002099 debug_printf_expand("quoted '%s', output->o_escape:%d\n", val, output->o_escape);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002100 }
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002101 } /* default: */
2102 } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002103 if (val) {
2104 o_addQstr(output, val, strlen(val));
2105 }
Mike Frysingera4f331d2009-04-07 06:03:22 +00002106 free(dyn_val);
2107 dyn_val = NULL;
Mike Frysinger6379bb42009-03-28 18:55:03 +00002108 /* Do the check to avoid writing to a const string */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00002109 if (*p != SPECIAL_VAR_SYMBOL)
Mike Frysinger6379bb42009-03-28 18:55:03 +00002110 *p = SPECIAL_VAR_SYMBOL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002111
2112#if ENABLE_HUSH_TICK
2113 o_free(&subst_result);
2114#endif
2115 arg = ++p;
2116 } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
2117
2118 if (arg[0]) {
2119 debug_print_list("expand_vars_to_list[a]", output, n);
2120 /* this part is literal, and it was already pre-quoted
2121 * if needed (much earlier), do not use o_addQstr here! */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002122 o_addstr_with_NUL(output, arg);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002123 debug_print_list("expand_vars_to_list[b]", output, n);
2124 } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
2125 && !(ored_ch & 0x80) /* and all vars were not quoted. */
2126 ) {
2127 n--;
2128 /* allow to reuse list[n] later without re-growth */
2129 output->has_empty_slot = 1;
2130 } else {
2131 o_addchr(output, '\0');
Eric Andersen25f27032001-04-26 23:22:31 +00002132 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002133 return n;
Eric Andersen25f27032001-04-26 23:22:31 +00002134}
2135
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002136static char **expand_variables(char **argv, int or_mask)
Eric Andersen25f27032001-04-26 23:22:31 +00002137{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002138 int n;
2139 char **list;
2140 char **v;
2141 o_string output = NULL_O_STRING;
2142
2143 if (or_mask & 0x100) {
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00002144 output.o_escape = 1; /* protect against globbing for "$var" */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002145 /* (unquoted $var will temporarily switch it off) */
2146 output.o_glob = 1;
Eric Andersen25f27032001-04-26 23:22:31 +00002147 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002148
2149 n = 0;
2150 v = argv;
2151 while (*v) {
2152 n = expand_vars_to_list(&output, n, *v, (char)or_mask);
2153 v++;
2154 }
2155 debug_print_list("expand_variables", &output, n);
2156
2157 /* output.data (malloced in one block) gets returned in "list" */
2158 list = o_finalize_list(&output, n);
2159 debug_print_strings("expand_variables[1]", list);
2160 return list;
Eric Andersen25f27032001-04-26 23:22:31 +00002161}
2162
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002163static char **expand_strvec_to_strvec(char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00002164{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002165 return expand_variables(argv, 0x100);
Eric Andersen25f27032001-04-26 23:22:31 +00002166}
2167
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002168/* Used for expansion of right hand of assignments */
2169/* NB: should NOT do globbing! "export v=/bin/c*; env | grep ^v=" outputs
2170 * "v=/bin/c*" */
2171static char *expand_string_to_string(const char *str)
Eric Andersen25f27032001-04-26 23:22:31 +00002172{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002173 char *argv[2], **list;
2174
2175 argv[0] = (char*)str;
2176 argv[1] = NULL;
2177 list = expand_variables(argv, 0x80); /* 0x80: make one-element expansion */
2178 if (HUSH_DEBUG)
2179 if (!list[0] || list[1])
2180 bb_error_msg_and_die("BUG in varexp2");
2181 /* actually, just move string 2*sizeof(char*) bytes back */
2182 overlapping_strcpy((char*)list, list[0]);
2183 debug_printf_expand("string_to_string='%s'\n", (char*)list);
2184 return (char*)list;
2185}
2186
2187/* Used for "eval" builtin */
2188static char* expand_strvec_to_string(char **argv)
2189{
2190 char **list;
2191
2192 list = expand_variables(argv, 0x80);
2193 /* Convert all NULs to spaces */
2194 if (list[0]) {
2195 int n = 1;
2196 while (list[n]) {
2197 if (HUSH_DEBUG)
2198 if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
2199 bb_error_msg_and_die("BUG in varexp3");
2200 list[n][-1] = ' '; /* TODO: or to G.ifs[0]? */
2201 n++;
2202 }
2203 }
2204 overlapping_strcpy((char*)list, list[0]);
2205 debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
2206 return (char*)list;
2207}
2208
2209static char **expand_assignments(char **argv, int count)
2210{
2211 int i;
2212 char **p = NULL;
2213 /* Expand assignments into one string each */
2214 for (i = 0; i < count; i++) {
2215 p = add_string_to_strings(p, expand_string_to_string(argv[i]));
2216 }
2217 return p;
Eric Andersen25f27032001-04-26 23:22:31 +00002218}
2219
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002220
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002221#if BB_MMU
2222void re_execute_shell(const char *s, int is_heredoc); /* never called */
2223#define clean_up_after_re_execute() ((void)0)
2224static void reset_traps_to_defaults(void)
2225{
2226 unsigned sig;
2227 int dirty;
2228
2229 if (!G.traps)
2230 return;
2231 dirty = 0;
2232 for (sig = 0; sig < NSIG; sig++) {
2233 if (!G.traps[sig])
2234 continue;
2235 free(G.traps[sig]);
2236 G.traps[sig] = NULL;
2237 /* There is no signal for 0 (EXIT) */
2238 if (sig == 0)
2239 continue;
2240 /* there was a trap handler, we are removing it
2241 * (if sig has non-DFL handling,
2242 * we don't need to do anything) */
2243 if (sig < 32 && (G.non_DFL_mask & (1 << sig)))
2244 continue;
2245 sigdelset(&G.blocked_set, sig);
2246 dirty = 1;
2247 }
2248 if (dirty)
2249 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
2250}
2251
2252#else /* !BB_MMU */
2253
2254static void re_execute_shell(const char *s, int is_heredoc) NORETURN;
2255static void re_execute_shell(const char *s, int is_heredoc)
2256{
2257 char param_buf[sizeof("-$%x:%x:%x:%x") + sizeof(unsigned) * 4];
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00002258 char *heredoc_argv[4];
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002259 struct variable *cur;
2260 char **argv, **pp, **pp2;
2261 unsigned cnt;
2262
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00002263 if (is_heredoc) {
2264 argv = heredoc_argv;
2265 argv[0] = (char *) G.argv0_for_re_execing;
2266 argv[1] = (char *) "-<";
2267 argv[2] = (char *) s;
2268 argv[3] = NULL;
Denis Vlasenkof50caac2009-04-09 01:40:15 +00002269 pp = &argv[3]; /* used as pointer to empty environment */
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00002270 goto do_exec;
2271 }
2272
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002273 sprintf(param_buf, "-$%x:%x:%x" USE_HUSH_LOOPS(":%x")
2274 , (unsigned) G.root_pid
2275 , (unsigned) G.last_bg_pid
2276 , (unsigned) G.last_exitcode
2277 USE_HUSH_LOOPS(, G.depth_of_loop)
2278 );
2279 /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<depth> <vars...>
2280 * 3:-c 4:<cmd> <argN...> 5:NULL
2281 */
2282 cnt = 5 + G.global_argc;
2283 for (cur = G.top_var; cur; cur = cur->next) {
2284 if (!cur->flg_export || cur->flg_read_only)
2285 cnt += 2;
2286 }
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00002287 G.argv_from_re_execing = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002288 *pp++ = (char *) G.argv0_for_re_execing;
2289 *pp++ = param_buf;
2290 for (cur = G.top_var; cur; cur = cur->next) {
2291 if (cur->varstr == hush_version_str)
2292 continue;
2293 if (cur->flg_read_only) {
2294 *pp++ = (char *) "-R";
2295 *pp++ = cur->varstr;
2296 } else if (!cur->flg_export) {
2297 *pp++ = (char *) "-V";
2298 *pp++ = cur->varstr;
2299 }
2300 }
2301//TODO: pass functions
2302 /* We can pass activated traps here. Say, -Tnn:trap_string
2303 *
2304 * However, POSIX says that subshells reset signals with traps
2305 * to SIG_DFL.
2306 * I tested bash-3.2 and it not only does that with true subshells
2307 * of the form ( list ), but with any forked children shells.
2308 * I set trap "echo W" WINCH; and then tried:
2309 *
2310 * { echo 1; sleep 20; echo 2; } &
2311 * while true; do echo 1; sleep 20; echo 2; break; done &
2312 * true | { echo 1; sleep 20; echo 2; } | cat
2313 *
2314 * In all these cases sending SIGWINCH to the child shell
2315 * did not run the trap. If I add trap "echo V" WINCH;
2316 * _inside_ group (just before echo 1), it works.
2317 *
2318 * I conclude it means we don't need to pass active traps here.
2319 * exec syscall below resets them to SIG_DFL for us.
2320 */
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00002321 *pp++ = (char *) "-c";
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002322 *pp++ = (char *) s;
2323 pp2 = G.global_argv;
2324 while (*pp2)
2325 *pp++ = *pp2++;
2326 /* *pp = NULL; - is already there */
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00002327 pp = environ;
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002328
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00002329 do_exec:
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002330 debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
2331 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00002332 execve(bb_busybox_exec_path, argv, pp);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002333 /* Fallback. Useful for init=/bin/hush usage etc */
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00002334 if (argv[0][0] == '/')
2335 execve(argv[0], argv, pp);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002336 xfunc_error_retval = 127;
2337 bb_error_msg_and_die("can't re-execute the shell");
2338}
2339
2340static void clean_up_after_re_execute(void)
2341{
2342 char **pp = G.argv_from_re_execing;
2343 if (pp) {
2344 /* Must match re_execute_shell's allocations (if any) */
2345 free(pp);
2346 G.argv_from_re_execing = NULL;
2347 }
2348}
2349#endif /* !BB_MMU */
2350
2351
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002352static void setup_heredoc(struct redir_struct *redir)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002353{
2354 struct fd_pair pair;
2355 pid_t pid;
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002356 int len, written;
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002357 /* the _body_ of heredoc (misleading field name) */
2358 const char *heredoc = redir->rd_filename;
2359 char *expanded;
2360
2361 expanded = NULL;
2362 if (!(redir->rd_dup & HEREDOC_QUOTED)) {
2363 expanded = expand_pseudo_dquoted(heredoc);
2364 if (expanded)
2365 heredoc = expanded;
2366 }
2367 len = strlen(heredoc);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002368
Denis Vlasenkoa2218dd2009-04-09 01:39:02 +00002369 close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002370 xpiped_pair(pair);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002371 xmove_fd(pair.rd, redir->rd_fd);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002372
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002373 /* Try writing without forking. Newer kernels have
2374 * dynamically growing pipes. Must use non-blocking write! */
2375 ndelay_on(pair.wr);
2376 while (1) {
2377 written = write(pair.wr, heredoc, len);
2378 if (written <= 0)
2379 break;
2380 len -= written;
2381 if (len == 0) {
2382 close(pair.wr);
Denis Vlasenko1943aec2009-04-09 14:15:57 +00002383 free(expanded);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002384 return;
2385 }
2386 heredoc += written;
2387 }
2388 ndelay_off(pair.wr);
2389
2390 /* Okay, pipe buffer was not big enough */
2391 /* Note: we must not create a stray child (bastard? :)
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002392 * for the unsuspecting parent process. Child creates a grandchild
2393 * and exits before parent execs the process which consumes heredoc
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002394 * (that exec happens after we return from this function) */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002395 pid = vfork();
2396 if (pid < 0)
2397 bb_perror_msg_and_die("vfork");
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002398 if (pid == 0) {
2399 /* child */
2400 pid = BB_MMU ? fork() : vfork();
2401 if (pid < 0)
2402 bb_perror_msg_and_die(BB_MMU ? "fork" : "vfork");
2403 if (pid != 0)
2404 _exit(0);
2405 /* grandchild */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002406 close(redir->rd_fd); /* read side of the pipe */
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002407#if BB_MMU
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002408 full_write(pair.wr, heredoc, len); /* may loop or block */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002409 _exit(0);
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002410#else
2411 /* Delegate blocking writes to another process */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002412 disable_restore_tty_pgrp_on_exit();
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002413 xmove_fd(pair.wr, STDOUT_FILENO);
2414 re_execute_shell(heredoc, 1);
2415#endif
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002416 }
2417 /* parent */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002418 enable_restore_tty_pgrp_on_exit();
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002419 clean_up_after_re_execute();
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002420 close(pair.wr);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002421 free(expanded);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002422 wait(NULL); /* wait till child has died */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002423}
2424
Eric Andersen25f27032001-04-26 23:22:31 +00002425/* squirrel != NULL means we squirrel away copies of stdin, stdout,
2426 * and stderr if they are redirected. */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002427static int setup_redirects(struct command *prog, int squirrel[])
Eric Andersen25f27032001-04-26 23:22:31 +00002428{
2429 int openfd, mode;
2430 struct redir_struct *redir;
2431
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002432 for (redir = prog->redirects; redir; redir = redir->next) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002433 if (redir->rd_type == REDIRECT_HEREDOC2) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00002434 /* rd_fd<<HERE case */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002435 if (squirrel && redir->rd_fd < 3) {
2436 squirrel[redir->rd_fd] = dup(redir->rd_fd);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002437 }
2438 /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
2439 * of the heredoc */
2440 debug_printf_parse("set heredoc '%s'\n",
2441 redir->rd_filename);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002442 setup_heredoc(redir);
Eric Andersen817e73c2001-06-06 17:56:09 +00002443 continue;
2444 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002445
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00002446 if (redir->rd_dup == REDIRFD_TO_FILE) {
2447 /* rd_fd<*>file case (<*> is <,>,>>,<>) */
Denis Vlasenkocccdc4e2007-11-23 21:08:38 +00002448 char *p;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002449 if (redir->rd_filename == NULL) {
2450 /* Something went wrong in the parse.
2451 * Pretend it didn't happen */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00002452 bb_error_msg("bug in redirect parse");
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002453 continue;
2454 }
Denis Vlasenko55789c62008-06-18 16:30:42 +00002455 mode = redir_table[redir->rd_type].mode;
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00002456 p = expand_string_to_string(redir->rd_filename);
Denis Vlasenkocccdc4e2007-11-23 21:08:38 +00002457 openfd = open_or_warn(p, mode);
2458 free(p);
Eric Andersen25f27032001-04-26 23:22:31 +00002459 if (openfd < 0) {
2460 /* this could get lost if stderr has been redirected, but
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00002461 * bash and ash both lose it as well (though zsh doesn't!) */
2462//what the above comment tries to say?
Eric Andersen25f27032001-04-26 23:22:31 +00002463 return 1;
2464 }
2465 } else {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00002466 /* rd_fd<*>rd_dup or rd_fd<*>- cases */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002467 openfd = redir->rd_dup;
Eric Andersen25f27032001-04-26 23:22:31 +00002468 }
2469
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002470 if (openfd != redir->rd_fd) {
2471 if (squirrel && redir->rd_fd < 3) {
2472 squirrel[redir->rd_fd] = dup(redir->rd_fd);
Eric Andersen25f27032001-04-26 23:22:31 +00002473 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002474 if (openfd == REDIRFD_CLOSE) {
2475 /* "n>-" means "close me" */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00002476 close(redir->rd_fd);
Eric Andersen83a2ae22001-05-07 17:59:25 +00002477 } else {
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002478 xdup2(openfd, redir->rd_fd);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00002479 if (redir->rd_dup == REDIRFD_TO_FILE)
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00002480 close(openfd);
Eric Andersen83a2ae22001-05-07 17:59:25 +00002481 }
Eric Andersen25f27032001-04-26 23:22:31 +00002482 }
2483 }
2484 return 0;
2485}
2486
2487static void restore_redirects(int squirrel[])
2488{
2489 int i, fd;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00002490 for (i = 0; i < 3; i++) {
Eric Andersen25f27032001-04-26 23:22:31 +00002491 fd = squirrel[i];
2492 if (fd != -1) {
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00002493 /* We simply die on error */
2494 xmove_fd(fd, i);
Eric Andersen25f27032001-04-26 23:22:31 +00002495 }
2496 }
2497}
2498
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002499
Denis Vlasenkoa0e65122009-04-05 23:39:14 +00002500#if !DEBUG_CLEAN
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002501#define free_pipe_list(head, indent) free_pipe_list(head)
2502#define free_pipe(pi, indent) free_pipe(pi)
2503#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002504static void free_pipe_list(struct pipe *head, int indent);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002505
Denis Vlasenko34d4d892009-04-04 20:24:37 +00002506/* Return code is the exit status of the pipe */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002507static void free_pipe(struct pipe *pi, int indent)
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002508{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002509 char **p;
2510 struct command *command;
2511 struct redir_struct *r, *rnext;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002512 int a, i;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002513
Denis Vlasenko34d4d892009-04-04 20:24:37 +00002514 if (pi->stopped_cmds > 0) /* why? */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002515 return;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002516 debug_printf_clean("%s run pipe: (pid %d)\n", indenter(indent), getpid());
2517 for (i = 0; i < pi->num_cmds; i++) {
2518 command = &pi->cmds[i];
2519 debug_printf_clean("%s command %d:\n", indenter(indent), i);
2520 if (command->argv) {
2521 for (a = 0, p = command->argv; *p; a++, p++) {
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002522 debug_printf_clean("%s argv[%d] = %s\n",
2523 indenter(indent), a, *p);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002524 }
2525 free_strings(command->argv);
2526 command->argv = NULL;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002527 }
2528 /* not "else if": on syntax error, we may have both! */
2529 if (command->group) {
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002530 debug_printf_clean("%s begin group (grp_type:%d)\n",
2531 indenter(indent), command->grp_type);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002532 free_pipe_list(command->group, indent+3);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002533 debug_printf_clean("%s end group\n", indenter(indent));
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002534 command->group = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002535 }
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002536#if !BB_MMU
2537 free(command->group_as_string);
2538 command->group_as_string = NULL;
2539#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002540 for (r = command->redirects; r; r = rnext) {
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002541 debug_printf_clean("%s redirect %d%s", indenter(indent),
2542 r->fd, redir_table[r->rd_type].descrip);
2543 /* guard against the case >$FOO, where foo is unset or blank */
2544 if (r->rd_filename) {
2545 debug_printf_clean(" fname:'%s'\n", r->rd_filename);
2546 free(r->rd_filename);
2547 r->rd_filename = NULL;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002548 }
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00002549 debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002550 rnext = r->next;
2551 free(r);
2552 }
2553 command->redirects = NULL;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002554 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002555 free(pi->cmds); /* children are an array, they get freed all at once */
2556 pi->cmds = NULL;
2557#if ENABLE_HUSH_JOB
2558 free(pi->cmdtext);
2559 pi->cmdtext = NULL;
2560#endif
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002561}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00002562
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002563static void free_pipe_list(struct pipe *head, int indent)
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002564{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002565 struct pipe *pi, *next;
2566
2567 for (pi = head; pi; pi = next) {
2568#if HAS_KEYWORDS
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00002569 debug_printf_clean("%s pipe reserved word %d\n", indenter(indent), pi->res_word);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002570#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00002571 free_pipe(pi, indent);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002572 debug_printf_clean("%s pipe followup code %d\n", indenter(indent), pi->followup);
2573 next = pi->next;
2574 /*pi->next = NULL;*/
2575 free(pi);
2576 }
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002577}
2578
2579
Denis Vlasenkocc90f442009-04-08 16:40:34 +00002580#if BB_MMU
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002581#define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
2582 pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
2583#define pseudo_exec(nommu_save, command, argv_expanded) \
2584 pseudo_exec(command, argv_expanded)
2585#endif
2586
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00002587/* Called after [v]fork() in run_pipe, or from builtin_exec.
Denis Vlasenko8412d792007-10-01 09:59:47 +00002588 * Never returns.
2589 * XXX no exit() here. If you don't exec, use _exit instead.
Eric Andersen94ac2442001-05-22 19:05:18 +00002590 * The at_exit handlers apparently confuse the calling process,
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00002591 * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00002592static void pseudo_exec_argv(nommu_save_t *nommu_save,
2593 char **argv, int assignment_cnt,
2594 char **argv_expanded) NORETURN;
2595static void pseudo_exec_argv(nommu_save_t *nommu_save,
2596 char **argv, int assignment_cnt,
2597 char **argv_expanded)
Eric Andersen25f27032001-04-26 23:22:31 +00002598{
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002599 char **new_env;
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00002600
Denis Vlasenko34d4d892009-04-04 20:24:37 +00002601 /* Case when we are here: ... | var=val | ... */
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00002602 if (!argv[assignment_cnt])
Denis Vlasenko1359da62007-04-21 23:27:30 +00002603 _exit(EXIT_SUCCESS);
Denis Vlasenko87cb2db2007-04-21 10:00:01 +00002604
Denis Vlasenko9504e442008-10-29 01:19:15 +00002605 new_env = expand_assignments(argv, assignment_cnt);
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002606#if BB_MMU
2607 putenv_all(new_env);
2608 free(new_env); /* optional */
2609#else
2610 nommu_save->new_env = new_env;
2611 nommu_save->old_env = putenv_all_and_save_old(new_env);
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00002612#endif
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00002613 if (argv_expanded) {
2614 argv = argv_expanded;
2615 } else {
Denis Vlasenko37181682009-04-03 03:19:15 +00002616 argv = expand_strvec_to_strvec(argv + assignment_cnt);
Denis Vlasenko76d50412008-06-10 16:19:39 +00002617#if !BB_MMU
Denis Vlasenkof886fd22008-10-13 12:36:05 +00002618 nommu_save->argv = argv;
Denis Vlasenko76d50412008-06-10 16:19:39 +00002619#endif
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00002620 }
Denis Vlasenko764d59d2007-05-14 16:23:23 +00002621
Denis Vlasenko34d4d892009-04-04 20:24:37 +00002622 /* On NOMMU, we must never block!
2623 * Example: { sleep 99999 | read line } & echo Ok
2624 * read builtin will block on read syscall, leaving parent blocked
2625 * in vfork. Therefore we can't do this:
2626 */
2627#if BB_MMU
2628 /* Check if the command matches any of the builtins.
Denis Vlasenko1359da62007-04-21 23:27:30 +00002629 * Depending on context, this might be redundant. But it's
2630 * easier to waste a few CPU cycles than it is to figure out
2631 * if this is one of those cases.
2632 */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00002633 {
2634 int rcode;
2635 const struct built_in_command *x;
2636 for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) {
2637 if (strcmp(argv[0], x->cmd) == 0) {
2638 debug_printf_exec("running builtin '%s'\n",
2639 argv[0]);
2640 rcode = x->function(argv);
2641 fflush(NULL);
2642 _exit(rcode);
2643 }
Eric Andersen94ac2442001-05-22 19:05:18 +00002644 }
Denis Vlasenko1359da62007-04-21 23:27:30 +00002645 }
Denis Vlasenko34d4d892009-04-04 20:24:37 +00002646#endif
Eric Andersen78a7c992001-05-15 16:30:25 +00002647
Denis Vlasenko80d14be2007-04-10 23:03:30 +00002648#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko34d4d892009-04-04 20:24:37 +00002649 /* Check if the command matches any busybox applets */
Denis Vlasenkoc666f712007-05-16 22:18:54 +00002650 if (strchr(argv[0], '/') == NULL) {
Denis Vlasenko1aa7e472007-11-28 06:49:03 +00002651 int a = find_applet_by_name(argv[0]);
2652 if (a >= 0) {
Denis Vlasenko34d4d892009-04-04 20:24:37 +00002653#if BB_MMU /* see above why on NOMMU it is not allowed */
Denis Vlasenko1aa7e472007-11-28 06:49:03 +00002654 if (APPLET_IS_NOEXEC(a)) {
Denis Vlasenkoc666f712007-05-16 22:18:54 +00002655 debug_printf_exec("running applet '%s'\n", argv[0]);
Denis Vlasenko1aa7e472007-11-28 06:49:03 +00002656 run_applet_no_and_exit(a, argv);
Denis Vlasenkoc666f712007-05-16 22:18:54 +00002657 }
Denis Vlasenko34d4d892009-04-04 20:24:37 +00002658#endif
2659 /* Re-exec ourselves */
Denis Vlasenkoc666f712007-05-16 22:18:54 +00002660 debug_printf_exec("re-execing applet '%s'\n", argv[0]);
Denis Vlasenko34d4d892009-04-04 20:24:37 +00002661 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
2662 execv(bb_busybox_exec_path, argv);
Denis Vlasenkoc666f712007-05-16 22:18:54 +00002663 /* If they called chroot or otherwise made the binary no longer
2664 * executable, fall through */
2665 }
2666 }
Eric Andersenaac75e52001-04-30 18:18:45 +00002667#endif
Denis Vlasenkoc666f712007-05-16 22:18:54 +00002668
2669 debug_printf_exec("execing '%s'\n", argv[0]);
Denis Vlasenko34d4d892009-04-04 20:24:37 +00002670 sigprocmask(SIG_SETMASK, &G.inherited_set, NULL);
Denis Vlasenko1359da62007-04-21 23:27:30 +00002671 execvp(argv[0], argv);
Bernhard Reutner-Fischera53de7f2008-07-21 13:46:54 +00002672 bb_perror_msg("can't exec '%s'", argv[0]);
Bernhard Reutner-Fischer636a1f82008-05-19 09:29:47 +00002673 _exit(EXIT_FAILURE);
Denis Vlasenko1359da62007-04-21 23:27:30 +00002674}
2675
Denis Vlasenko424f79b2009-03-22 14:23:34 +00002676static int run_list(struct pipe *pi);
2677
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00002678/* Called after [v]fork() in run_pipe
Denis Vlasenko8412d792007-10-01 09:59:47 +00002679 */
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00002680static void pseudo_exec(nommu_save_t *nommu_save,
2681 struct command *command,
2682 char **argv_expanded) NORETURN;
2683static void pseudo_exec(nommu_save_t *nommu_save,
2684 struct command *command,
2685 char **argv_expanded)
Denis Vlasenko1359da62007-04-21 23:27:30 +00002686{
Denis Vlasenko552433b2009-04-04 19:29:21 +00002687 if (command->argv) {
2688 pseudo_exec_argv(nommu_save, command->argv,
2689 command->assignment_cnt, argv_expanded);
2690 }
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00002691
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002692 if (command->group) {
Denis Vlasenko552433b2009-04-04 19:29:21 +00002693 /* Cases when we are here:
2694 * ( list )
2695 * { list } &
2696 * ... | ( list ) | ...
2697 * ... | { list } | ...
2698 */
2699#if BB_MMU
Denis Vlasenko3b492162007-12-24 14:26:57 +00002700 int rcode;
Denis Vlasenko05743d72008-02-10 12:10:08 +00002701 debug_printf_exec("pseudo_exec: run_list\n");
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00002702 reset_traps_to_defaults();
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002703 rcode = run_list(command->group);
Eric Andersenbf7df042001-05-23 22:18:35 +00002704 /* OK to leak memory by not calling free_pipe_list,
Eric Andersen25f27032001-04-26 23:22:31 +00002705 * since this process is about to exit */
Eric Andersen94ac2442001-05-22 19:05:18 +00002706 _exit(rcode);
Denis Vlasenko552433b2009-04-04 19:29:21 +00002707#else
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00002708 re_execute_shell(command->group_as_string, 0);
Denis Vlasenko8412d792007-10-01 09:59:47 +00002709#endif
Eric Andersen25f27032001-04-26 23:22:31 +00002710 }
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00002711
Denis Vlasenko34d4d892009-04-04 20:24:37 +00002712 /* Case when we are here: ... | >file */
2713 debug_printf_exec("pseudo_exec'ed null command\n");
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00002714 _exit(EXIT_SUCCESS);
Eric Andersen25f27032001-04-26 23:22:31 +00002715}
2716
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00002717#if ENABLE_HUSH_JOB
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00002718static const char *get_cmdtext(struct pipe *pi)
2719{
2720 char **argv;
2721 char *p;
2722 int len;
2723
2724 /* This is subtle. ->cmdtext is created only on first backgrounding.
2725 * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002726 * On subsequent bg argv is trashed, but we won't use it */
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00002727 if (pi->cmdtext)
2728 return pi->cmdtext;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002729 argv = pi->cmds[0].argv;
Denis Vlasenkoa8442002008-06-14 11:00:17 +00002730 if (!argv || !argv[0]) {
2731 pi->cmdtext = xzalloc(1);
2732 return pi->cmdtext;
2733 }
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00002734
2735 len = 0;
2736 do len += strlen(*argv) + 1; while (*++argv);
2737 pi->cmdtext = p = xmalloc(len);
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002738 argv = pi->cmds[0].argv;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00002739 do {
2740 len = strlen(*argv);
2741 memcpy(p, *argv, len);
2742 p += len;
2743 *p++ = ' ';
2744 } while (*++argv);
2745 p[-1] = '\0';
2746 return pi->cmdtext;
2747}
2748
Eric Andersenbafd94f2001-05-02 16:11:59 +00002749static void insert_bg_job(struct pipe *pi)
2750{
2751 struct pipe *thejob;
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002752 int i;
Eric Andersenbafd94f2001-05-02 16:11:59 +00002753
2754 /* Linear search for the ID of the job to use */
2755 pi->jobid = 1;
Denis Vlasenko87a86552008-07-29 19:43:10 +00002756 for (thejob = G.job_list; thejob; thejob = thejob->next)
Eric Andersenbafd94f2001-05-02 16:11:59 +00002757 if (thejob->jobid >= pi->jobid)
2758 pi->jobid = thejob->jobid + 1;
2759
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002760 /* Add thejob to the list of running jobs */
Denis Vlasenko87a86552008-07-29 19:43:10 +00002761 if (!G.job_list) {
2762 thejob = G.job_list = xmalloc(sizeof(*thejob));
Eric Andersenbafd94f2001-05-02 16:11:59 +00002763 } else {
Denis Vlasenko87a86552008-07-29 19:43:10 +00002764 for (thejob = G.job_list; thejob->next; thejob = thejob->next)
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00002765 continue;
Eric Andersenbafd94f2001-05-02 16:11:59 +00002766 thejob->next = xmalloc(sizeof(*thejob));
2767 thejob = thejob->next;
2768 }
2769
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002770 /* Physically copy the struct job */
Eric Andersen0fcd4472001-05-02 20:12:03 +00002771 memcpy(thejob, pi, sizeof(struct pipe));
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002772 thejob->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
2773 /* We cannot copy entire pi->cmds[] vector! Double free()s will happen */
2774 for (i = 0; i < pi->num_cmds; i++) {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002775// TODO: do we really need to have so many fields which are just dead weight
2776// at execution stage?
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002777 thejob->cmds[i].pid = pi->cmds[i].pid;
Denis Vlasenkoc666f712007-05-16 22:18:54 +00002778 /* all other fields are not used and stay zero */
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002779 }
Eric Andersenbafd94f2001-05-02 16:11:59 +00002780 thejob->next = NULL;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00002781 thejob->cmdtext = xstrdup(get_cmdtext(pi));
Eric Andersenbafd94f2001-05-02 16:11:59 +00002782
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002783 /* We don't wait for background thejobs to return -- append it
Eric Andersenbafd94f2001-05-02 16:11:59 +00002784 to the list of backgrounded thejobs and leave it alone */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00002785 if (G_interactive_fd)
Mike Frysinger87824e02009-03-30 00:19:30 +00002786 printf("[%d] %d %s\n", thejob->jobid, thejob->cmds[0].pid, thejob->cmdtext);
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002787 G.last_bg_pid = thejob->cmds[0].pid;
Denis Vlasenko87a86552008-07-29 19:43:10 +00002788 G.last_jobid = thejob->jobid;
Eric Andersenbafd94f2001-05-02 16:11:59 +00002789}
2790
Eric Andersenbafd94f2001-05-02 16:11:59 +00002791static void remove_bg_job(struct pipe *pi)
2792{
2793 struct pipe *prev_pipe;
2794
Denis Vlasenko87a86552008-07-29 19:43:10 +00002795 if (pi == G.job_list) {
2796 G.job_list = pi->next;
Eric Andersenbafd94f2001-05-02 16:11:59 +00002797 } else {
Denis Vlasenko87a86552008-07-29 19:43:10 +00002798 prev_pipe = G.job_list;
Eric Andersenbafd94f2001-05-02 16:11:59 +00002799 while (prev_pipe->next != pi)
2800 prev_pipe = prev_pipe->next;
2801 prev_pipe->next = pi->next;
2802 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00002803 if (G.job_list)
2804 G.last_jobid = G.job_list->jobid;
Eric Andersen028b65b2001-06-28 01:10:11 +00002805 else
Denis Vlasenko87a86552008-07-29 19:43:10 +00002806 G.last_jobid = 0;
Denis Vlasenko1359da62007-04-21 23:27:30 +00002807}
Eric Andersen028b65b2001-06-28 01:10:11 +00002808
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00002809/* Remove a backgrounded job */
Denis Vlasenko1359da62007-04-21 23:27:30 +00002810static void delete_finished_bg_job(struct pipe *pi)
2811{
2812 remove_bg_job(pi);
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002813 pi->stopped_cmds = 0;
Eric Andersenbf7df042001-05-23 22:18:35 +00002814 free_pipe(pi, 0);
Eric Andersenbafd94f2001-05-02 16:11:59 +00002815 free(pi);
2816}
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00002817#endif /* JOB */
Eric Andersenbafd94f2001-05-02 16:11:59 +00002818
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00002819/* Check to see if any processes have exited -- if they
2820 * have, figure out why and see if a job has completed */
Eric Andersenc798b072001-06-22 06:23:03 +00002821static int checkjobs(struct pipe* fg_pipe)
Eric Andersenbafd94f2001-05-02 16:11:59 +00002822{
Eric Andersenc798b072001-06-22 06:23:03 +00002823 int attributes;
2824 int status;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00002825#if ENABLE_HUSH_JOB
Eric Andersenbafd94f2001-05-02 16:11:59 +00002826 struct pipe *pi;
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00002827#endif
Eric Andersenbafd94f2001-05-02 16:11:59 +00002828 pid_t childpid;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00002829 int rcode = 0;
Eric Andersenbafd94f2001-05-02 16:11:59 +00002830
Denis Vlasenkod5762932009-03-31 11:22:57 +00002831 debug_printf_jobs("checkjobs %p\n", fg_pipe);
2832
Denis Vlasenko7566bae2009-03-31 17:24:49 +00002833 errno = 0;
2834// if (G.handled_SIGCHLD == G.count_SIGCHLD)
2835// /* avoid doing syscall, nothing there anyway */
2836// return rcode;
2837
Eric Andersenc798b072001-06-22 06:23:03 +00002838 attributes = WUNTRACED;
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00002839 if (fg_pipe == NULL)
Eric Andersenc798b072001-06-22 06:23:03 +00002840 attributes |= WNOHANG;
Eric Andersenc798b072001-06-22 06:23:03 +00002841
Denis Vlasenko1359da62007-04-21 23:27:30 +00002842/* Do we do this right?
2843 * bash-3.00# sleep 20 | false
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00002844 * <ctrl-Z pressed>
Denis Vlasenko1359da62007-04-21 23:27:30 +00002845 * [3]+ Stopped sleep 20 | false
2846 * bash-3.00# echo $?
2847 * 1 <========== bg pipe is not fully done, but exitcode is already known!
2848 */
2849
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00002850//FIXME: non-interactive bash does not continue even if all processes in fg pipe
2851//are stopped. Testcase: "cat | cat" in a script (not on command line)
2852// + killall -STOP cat
2853
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00002854 wait_more:
Denis Vlasenko7566bae2009-03-31 17:24:49 +00002855 while (1) {
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00002856 int i;
Denis Vlasenko7566bae2009-03-31 17:24:49 +00002857 int dead;
2858
2859// i = G.count_SIGCHLD;
2860 childpid = waitpid(-1, &status, attributes);
2861 if (childpid <= 0) {
2862 if (childpid && errno != ECHILD)
2863 bb_perror_msg("waitpid");
2864// else /* Until next SIGCHLD, waitpid's are useless */
2865// G.handled_SIGCHLD = i;
2866 break;
2867 }
2868 dead = WIFEXITED(status) || WIFSIGNALED(status);
2869
Denis Vlasenkob61e13d2008-06-17 05:11:43 +00002870#if DEBUG_JOBS
Denis Vlasenko1359da62007-04-21 23:27:30 +00002871 if (WIFSTOPPED(status))
Denis Vlasenkod01ff132007-05-02 21:40:23 +00002872 debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00002873 childpid, WSTOPSIG(status), WEXITSTATUS(status));
2874 if (WIFSIGNALED(status))
Denis Vlasenkod01ff132007-05-02 21:40:23 +00002875 debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00002876 childpid, WTERMSIG(status), WEXITSTATUS(status));
2877 if (WIFEXITED(status))
Denis Vlasenkod01ff132007-05-02 21:40:23 +00002878 debug_printf_jobs("pid %d exited, exitcode %d\n",
Denis Vlasenko1359da62007-04-21 23:27:30 +00002879 childpid, WEXITSTATUS(status));
2880#endif
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00002881 /* Were we asked to wait for fg pipe? */
Eric Andersenc798b072001-06-22 06:23:03 +00002882 if (fg_pipe) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002883 for (i = 0; i < fg_pipe->num_cmds; i++) {
2884 debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
2885 if (fg_pipe->cmds[i].pid != childpid)
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00002886 continue;
2887 /* printf("process %d exit %d\n", i, WEXITSTATUS(status)); */
2888 if (dead) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002889 fg_pipe->cmds[i].pid = 0;
2890 fg_pipe->alive_cmds--;
2891 if (i == fg_pipe->num_cmds - 1) {
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00002892 /* last process gives overall exitstatus */
2893 rcode = WEXITSTATUS(status);
Denis Vlasenko5ec61322008-06-24 00:50:07 +00002894 IF_HAS_KEYWORDS(if (fg_pipe->pi_inverted) rcode = !rcode;)
Denis Vlasenko1359da62007-04-21 23:27:30 +00002895 }
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00002896 } else {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002897 fg_pipe->cmds[i].is_stopped = 1;
2898 fg_pipe->stopped_cmds++;
Eric Andersenc798b072001-06-22 06:23:03 +00002899 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002900 debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
2901 fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
2902 if (fg_pipe->alive_cmds - fg_pipe->stopped_cmds <= 0) {
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00002903 /* All processes in fg pipe have exited/stopped */
2904#if ENABLE_HUSH_JOB
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002905 if (fg_pipe->alive_cmds)
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00002906 insert_bg_job(fg_pipe);
2907#endif
2908 return rcode;
2909 }
2910 /* There are still running processes in the fg pipe */
2911 goto wait_more; /* do waitpid again */
Eric Andersenc798b072001-06-22 06:23:03 +00002912 }
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00002913 /* it wasnt fg_pipe, look for process in bg pipes */
Eric Andersenc798b072001-06-22 06:23:03 +00002914 }
2915
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00002916#if ENABLE_HUSH_JOB
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00002917 /* We asked to wait for bg or orphaned children */
2918 /* No need to remember exitcode in this case */
Denis Vlasenko87a86552008-07-29 19:43:10 +00002919 for (pi = G.job_list; pi; pi = pi->next) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002920 for (i = 0; i < pi->num_cmds; i++) {
2921 if (pi->cmds[i].pid == childpid)
Denis Vlasenko5f786c22007-04-20 08:35:45 +00002922 goto found_pi_and_prognum;
Eric Andersen52a97ca2001-06-22 06:49:26 +00002923 }
Eric Andersenbafd94f2001-05-02 16:11:59 +00002924 }
Denis Vlasenko5f786c22007-04-20 08:35:45 +00002925 /* Happens when shell is used as init process (init=/bin/sh) */
2926 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00002927 continue; /* do waitpid again */
Eric Andersenaeb44c42001-05-22 20:29:00 +00002928
Denis Vlasenko5f786c22007-04-20 08:35:45 +00002929 found_pi_and_prognum:
Denis Vlasenko1359da62007-04-21 23:27:30 +00002930 if (dead) {
Eric Andersenbafd94f2001-05-02 16:11:59 +00002931 /* child exited */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002932 pi->cmds[i].pid = 0;
2933 pi->alive_cmds--;
2934 if (!pi->alive_cmds) {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00002935 if (G_interactive_fd)
Mike Frysinger87824e02009-03-30 00:19:30 +00002936 printf(JOB_STATUS_FORMAT, pi->jobid,
2937 "Done", pi->cmdtext);
Denis Vlasenko1359da62007-04-21 23:27:30 +00002938 delete_finished_bg_job(pi);
Eric Andersenbafd94f2001-05-02 16:11:59 +00002939 }
2940 } else {
2941 /* child stopped */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002942 pi->cmds[i].is_stopped = 1;
2943 pi->stopped_cmds++;
Eric Andersenbafd94f2001-05-02 16:11:59 +00002944 }
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00002945#endif
Denis Vlasenko003f9fb2008-06-24 00:47:58 +00002946 } /* while (waitpid succeeds)... */
Eric Andersenbafd94f2001-05-02 16:11:59 +00002947
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00002948 return rcode;
Eric Andersenada18ff2001-05-21 16:18:22 +00002949}
2950
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00002951#if ENABLE_HUSH_JOB
Denis Vlasenko52881e92007-04-21 13:42:52 +00002952static int checkjobs_and_fg_shell(struct pipe* fg_pipe)
2953{
2954 pid_t p;
2955 int rcode = checkjobs(fg_pipe);
2956 /* Job finished, move the shell to the foreground */
Denis Vlasenko170435c2007-05-23 13:01:10 +00002957 p = getpgid(0); /* pgid of our process */
2958 debug_printf_jobs("fg'ing ourself: getpgid(0)=%d\n", (int)p);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00002959 tcsetpgrp(G_interactive_fd, p);
Denis Vlasenko52881e92007-04-21 13:42:52 +00002960 return rcode;
2961}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00002962#endif
Denis Vlasenko52881e92007-04-21 13:42:52 +00002963
Denis Vlasenko34d4d892009-04-04 20:24:37 +00002964/* Start all the jobs, but don't wait for anything to finish.
2965 * See checkjobs().
Eric Andersen25f27032001-04-26 23:22:31 +00002966 *
Denis Vlasenko552433b2009-04-04 19:29:21 +00002967 * Return code is normally -1, when the caller has to wait for children
Eric Andersen25f27032001-04-26 23:22:31 +00002968 * to finish to determine the exit status of the pipe. If the pipe
2969 * is a simple builtin command, however, the action is done by the
Denis Vlasenko05743d72008-02-10 12:10:08 +00002970 * time run_pipe returns, and the exit code is provided as the
Eric Andersen25f27032001-04-26 23:22:31 +00002971 * return value.
2972 *
Denis Vlasenko170435c2007-05-23 13:01:10 +00002973 * Returns -1 only if started some children. IOW: we have to
2974 * mask out retvals of builtins etc with 0xff!
Denis Vlasenko552433b2009-04-04 19:29:21 +00002975 *
2976 * The only case when we do not need to [v]fork is when the pipe
2977 * is single, non-backgrounded, non-subshell command. Examples:
2978 * cmd ; ... { list } ; ...
2979 * cmd && ... { list } && ...
2980 * cmd || ... { list } || ...
2981 * If it is, then we can run cmd as a builtin, NOFORK [do we do this?],
2982 * or (if SH_STANDALONE) an applet, and we can run the { list }
Denis Vlasenko34d4d892009-04-04 20:24:37 +00002983 * with run_list(). If it isn't one of these, we fork and exec cmd.
Denis Vlasenko552433b2009-04-04 19:29:21 +00002984 *
2985 * Cases when we must fork:
2986 * non-single: cmd | cmd
2987 * backgrounded: cmd & { list } &
2988 * subshell: ( list ) [&]
Eric Andersen25f27032001-04-26 23:22:31 +00002989 */
Denis Vlasenko05743d72008-02-10 12:10:08 +00002990static int run_pipe(struct pipe *pi)
Eric Andersen25f27032001-04-26 23:22:31 +00002991{
Denis Vlasenko552433b2009-04-04 19:29:21 +00002992 static const char *const null_ptr = NULL;
Eric Andersen25f27032001-04-26 23:22:31 +00002993 int i;
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00002994 int nextin;
2995 int pipefds[2]; /* pipefds[0] is for reading */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00002996 struct command *command;
Denis Vlasenko22d10a02008-10-13 08:53:43 +00002997 char **argv_expanded;
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00002998 char **argv;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00002999 char *p;
Denis Vlasenkof5294e12007-04-14 10:09:57 +00003000 /* it is not always needed, but we aim to smaller code */
3001 int squirrel[] = { -1, -1, -1 };
3002 int rcode;
Eric Andersen25f27032001-04-26 23:22:31 +00003003
Denis Vlasenko552433b2009-04-04 19:29:21 +00003004 debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
Denis Vlasenko4ac530c2007-05-02 15:35:45 +00003005
Denis Vlasenko552433b2009-04-04 19:29:21 +00003006 USE_HUSH_JOB(pi->pgrp = -1;)
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003007 pi->stopped_cmds = 0;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003008 command = &(pi->cmds[0]);
Denis Vlasenko552433b2009-04-04 19:29:21 +00003009 argv_expanded = NULL;
Denis Vlasenko22d10a02008-10-13 08:53:43 +00003010
Denis Vlasenko552433b2009-04-04 19:29:21 +00003011 if (pi->num_cmds != 1
3012 || pi->followup == PIPE_BG
3013 || command->grp_type == GRP_SUBSHELL
3014 ) {
3015 goto must_fork;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003016 }
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003017
Denis Vlasenko552433b2009-04-04 19:29:21 +00003018 pi->alive_cmds = 1;
3019
3020 debug_printf_exec(": group:%p argv:'%s'\n",
3021 command->group, command->argv ? command->argv[0] : "NONE");
3022
3023 if (command->group) {
3024#if ENABLE_HUSH_FUNCTIONS
3025 if (command->grp_type == GRP_FUNCTION) {
3026 /* func () { list } */
3027 bb_error_msg("here we ought to remember function definition, and go on");
3028 return EXIT_SUCCESS;
3029 }
3030#endif
3031 /* { list } */
3032 debug_printf("non-subshell group\n");
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00003033 rcode = 1; /* exitcode if redir failed */
3034 if (setup_redirects(command, squirrel) == 0) {
3035 debug_printf_exec(": run_list\n");
3036 rcode = run_list(command->group) & 0xff;
3037 debug_printf_exec("run_pipe return %d\n", rcode);
3038 }
Eric Andersen04407e52001-06-07 16:42:05 +00003039 restore_redirects(squirrel);
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003040 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
Denis Vlasenko05743d72008-02-10 12:10:08 +00003041 return rcode;
Denis Vlasenkof03dbed2007-04-13 19:55:50 +00003042 }
3043
Denis Vlasenko552433b2009-04-04 19:29:21 +00003044 argv = command->argv ? command->argv : (char **) &null_ptr;
3045 {
3046 const struct built_in_command *x;
Denis Vlasenko22d10a02008-10-13 08:53:43 +00003047 char **new_env = NULL;
3048 char **old_env = NULL;
3049
Denis Vlasenko552433b2009-04-04 19:29:21 +00003050 if (argv[command->assignment_cnt] == NULL) {
3051 /* Assignments, but no command */
3052 /* Ensure redirects take effect. Try "a=t >file" */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00003053 rcode = setup_redirects(command, squirrel);
Denis Vlasenko552433b2009-04-04 19:29:21 +00003054 restore_redirects(squirrel);
3055 /* Set shell variables */
3056 while (*argv) {
3057 p = expand_string_to_string(*argv);
3058 debug_printf_exec("set shell var:'%s'->'%s'\n",
3059 *argv, p);
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00003060 set_local_var(p, 0, 0);
Denis Vlasenko552433b2009-04-04 19:29:21 +00003061 argv++;
Eric Andersen78a7c992001-05-15 16:30:25 +00003062 }
Denis Vlasenko552433b2009-04-04 19:29:21 +00003063 /* Do we need to flag set_local_var() errors?
3064 * "assignment to readonly var" and "putenv error"
3065 */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00003066 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
3067 return rcode;
Eric Andersen78a7c992001-05-15 16:30:25 +00003068 }
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00003069
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00003070 /* Expand the rest into (possibly) many strings each */
Denis Vlasenko552433b2009-04-04 19:29:21 +00003071 argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00003072
Denis Vlasenkodd316dd2008-06-14 15:50:55 +00003073 for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) {
Denis Vlasenko22d10a02008-10-13 08:53:43 +00003074 if (strcmp(argv_expanded[0], x->cmd) != 0)
3075 continue;
3076 if (x->function == builtin_exec && argv_expanded[1] == NULL) {
3077 debug_printf("exec with redirects only\n");
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00003078 rcode = setup_redirects(command, NULL);
Denis Vlasenko22d10a02008-10-13 08:53:43 +00003079 goto clean_up_and_ret1;
Eric Andersen25f27032001-04-26 23:22:31 +00003080 }
Denis Vlasenko22d10a02008-10-13 08:53:43 +00003081 debug_printf("builtin inline %s\n", argv_expanded[0]);
3082 /* XXX setup_redirects acts on file descriptors, not FILEs.
3083 * This is perfect for work that comes after exec().
3084 * Is it really safe for inline use? Experimentally,
3085 * things seem to work with glibc. */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00003086 rcode = setup_redirects(command, squirrel);
3087 if (rcode == 0) {
3088 new_env = expand_assignments(argv, command->assignment_cnt);
3089 old_env = putenv_all_and_save_old(new_env);
3090 debug_printf_exec(": builtin '%s' '%s'...\n",
3091 x->cmd, argv_expanded[1]);
3092 rcode = x->function(argv_expanded) & 0xff;
3093 }
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003094#if ENABLE_FEATURE_SH_STANDALONE
3095 clean_up_and_ret:
3096#endif
Denis Vlasenko22d10a02008-10-13 08:53:43 +00003097 restore_redirects(squirrel);
3098 free_strings_and_unsetenv(new_env, 1);
3099 putenv_all(old_env);
Denis Vlasenkocc90f442009-04-08 16:40:34 +00003100 /* Free the pointers, but the strings themselves
3101 * are in environ now, don't use free_strings! */
3102 free(old_env);
Denis Vlasenko22d10a02008-10-13 08:53:43 +00003103 clean_up_and_ret1:
3104 free(argv_expanded);
3105 IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
3106 debug_printf_exec("run_pipe return %d\n", rcode);
3107 return rcode;
Eric Andersen25f27032001-04-26 23:22:31 +00003108 }
Denis Vlasenkof5294e12007-04-14 10:09:57 +00003109#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko22d10a02008-10-13 08:53:43 +00003110 i = find_applet_by_name(argv_expanded[0]);
3111 if (i >= 0 && APPLET_IS_NOFORK(i)) {
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00003112 rcode = setup_redirects(command, squirrel);
3113 if (rcode == 0) {
3114 save_nofork_data(&G.nofork_save);
3115 new_env = expand_assignments(argv, command->assignment_cnt);
3116 old_env = putenv_all_and_save_old(new_env);
3117 debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003118 argv_expanded[0], argv_expanded[1]);
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00003119 rcode = run_nofork_applet_prime(&G.nofork_save, i, argv_expanded);
3120 }
Denis Vlasenko22d10a02008-10-13 08:53:43 +00003121 goto clean_up_and_ret;
Denis Vlasenkof5294e12007-04-14 10:09:57 +00003122 }
3123#endif
Denis Vlasenko552433b2009-04-04 19:29:21 +00003124 /* It is neither builtin nor applet. We must fork. */
Eric Andersen25f27032001-04-26 23:22:31 +00003125 }
3126
Denis Vlasenko552433b2009-04-04 19:29:21 +00003127 must_fork:
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00003128 /* NB: argv_expanded may already be created, and that
3129 * might include `cmd` runs! Do not rerun it! We *must*
3130 * use argv_expanded if it's non-NULL */
3131
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00003132 /* Going to fork a child per each pipe member */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003133 pi->alive_cmds = 0;
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00003134 nextin = 0;
3135
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003136 for (i = 0; i < pi->num_cmds; i++) {
Denis Vlasenko76d50412008-06-10 16:19:39 +00003137#if !BB_MMU
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003138 volatile nommu_save_t nommu_save;
3139 nommu_save.new_env = NULL;
3140 nommu_save.old_env = NULL;
3141 nommu_save.argv = NULL;
Denis Vlasenko76d50412008-06-10 16:19:39 +00003142#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003143 command = &(pi->cmds[i]);
3144 if (command->argv) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003145 debug_printf_exec(": pipe member '%s' '%s'...\n",
3146 command->argv[0], command->argv[1]);
Denis Vlasenko552433b2009-04-04 19:29:21 +00003147 } else {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003148 debug_printf_exec(": pipe member with no argv\n");
Denis Vlasenko552433b2009-04-04 19:29:21 +00003149 }
Eric Andersen25f27032001-04-26 23:22:31 +00003150
3151 /* pipes are inserted between pairs of commands */
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00003152 pipefds[0] = 0;
3153 pipefds[1] = 1;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003154 if ((i + 1) < pi->num_cmds)
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00003155 xpipe(pipefds);
Eric Andersen25f27032001-04-26 23:22:31 +00003156
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003157 command->pid = BB_MMU ? fork() : vfork();
3158 if (!command->pid) { /* child */
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00003159#if ENABLE_HUSH_JOB
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003160 disable_restore_tty_pgrp_on_exit();
Denis Vlasenkod5762932009-03-31 11:22:57 +00003161
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003162 /* Every child adds itself to new process group
Denis Vlasenko05743d72008-02-10 12:10:08 +00003163 * with pgid == pid_of_first_child_in_pipe */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00003164 if (G.run_list_level == 1 && G_interactive_fd) {
Denis Vlasenko05743d72008-02-10 12:10:08 +00003165 pid_t pgrp;
Denis Vlasenko05743d72008-02-10 12:10:08 +00003166 pgrp = pi->pgrp;
3167 if (pgrp < 0) /* true for 1st process only */
3168 pgrp = getpid();
3169 if (setpgid(0, pgrp) == 0 && pi->followup != PIPE_BG) {
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003170 /* We do it in *every* child, not just first,
3171 * to avoid races */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00003172 tcsetpgrp(G_interactive_fd, pgrp);
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003173 }
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003174 }
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00003175#endif
Denis Vlasenko8412d792007-10-01 09:59:47 +00003176 xmove_fd(nextin, 0);
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00003177 xmove_fd(pipefds[1], 1); /* write end */
3178 if (pipefds[0] > 1)
3179 close(pipefds[0]); /* read end */
Eric Andersen25f27032001-04-26 23:22:31 +00003180 /* Like bash, explicit redirects override pipes,
3181 * and the pipe fd is available for dup'ing. */
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00003182 if (setup_redirects(command, NULL))
3183 _exit(1);
Eric Andersen52a97ca2001-06-22 06:49:26 +00003184
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00003185 /* Restore default handlers just prior to exec */
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00003186 /*signal(SIGCHLD, SIG_DFL); - so far we don't have any handlers */
3187
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003188 /* Stores to nommu_save list of env vars putenv'ed
3189 * (NOMMU, on MMU we don't need that) */
3190 /* cast away volatility... */
3191 pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00003192 /* pseudo_exec() does not return */
Eric Andersen25f27032001-04-26 23:22:31 +00003193 }
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00003194
Denis Vlasenkof9375282009-04-05 19:13:39 +00003195 /* parent or error */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00003196 enable_restore_tty_pgrp_on_exit();
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00003197#if !BB_MMU
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003198 /* Clean up after vforked child */
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00003199 clean_up_after_re_execute();
Denis Vlasenkof886fd22008-10-13 12:36:05 +00003200 free(nommu_save.argv);
3201 free_strings_and_unsetenv(nommu_save.new_env, 1);
3202 putenv_all(nommu_save.old_env);
Denis Vlasenkocc90f442009-04-08 16:40:34 +00003203 /* Free the pointers, but the strings themselves
3204 * are in environ now, don't use free_strings! */
3205 free(nommu_save.old_env);
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00003206#endif
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00003207 free(argv_expanded);
3208 argv_expanded = NULL;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003209 if (command->pid < 0) { /* [v]fork failed */
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00003210 /* Clearly indicate, was it fork or vfork */
Denis Vlasenko82604e92008-07-01 15:59:42 +00003211 bb_perror_msg(BB_MMU ? "fork" : "vfork");
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00003212 } else {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003213 pi->alive_cmds++;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003214#if ENABLE_HUSH_JOB
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00003215 /* Second and next children need to know pid of first one */
3216 if (pi->pgrp < 0)
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003217 pi->pgrp = command->pid;
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00003218#endif
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00003219 }
Eric Andersen25f27032001-04-26 23:22:31 +00003220
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00003221 if (i)
3222 close(nextin);
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003223 if ((i + 1) < pi->num_cmds)
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00003224 close(pipefds[1]); /* write end */
3225 /* Pass read (output) pipe end to next iteration */
Eric Andersen25f27032001-04-26 23:22:31 +00003226 nextin = pipefds[0];
3227 }
Denis Vlasenkod2c450c2008-01-08 20:32:12 +00003228
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003229 if (!pi->alive_cmds) {
Denis Vlasenko05743d72008-02-10 12:10:08 +00003230 debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
3231 return 1;
3232 }
3233
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003234 debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
Eric Andersen25f27032001-04-26 23:22:31 +00003235 return -1;
3236}
3237
Denis Vlasenko4b924f32007-05-30 00:29:55 +00003238#ifndef debug_print_tree
Denis Vlasenko400c5b62007-05-04 13:07:27 +00003239static void debug_print_tree(struct pipe *pi, int lvl)
3240{
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003241 static const char *const PIPE[] = {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00003242 [PIPE_SEQ] = "SEQ",
3243 [PIPE_AND] = "AND",
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003244 [PIPE_OR ] = "OR" ,
3245 [PIPE_BG ] = "BG" ,
Denis Vlasenko400c5b62007-05-04 13:07:27 +00003246 };
3247 static const char *RES[] = {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00003248 [RES_NONE ] = "NONE" ,
Denis Vlasenko06810332007-05-21 23:30:54 +00003249#if ENABLE_HUSH_IF
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00003250 [RES_IF ] = "IF" ,
3251 [RES_THEN ] = "THEN" ,
3252 [RES_ELIF ] = "ELIF" ,
3253 [RES_ELSE ] = "ELSE" ,
3254 [RES_FI ] = "FI" ,
Denis Vlasenko06810332007-05-21 23:30:54 +00003255#endif
3256#if ENABLE_HUSH_LOOPS
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00003257 [RES_FOR ] = "FOR" ,
3258 [RES_WHILE] = "WHILE",
3259 [RES_UNTIL] = "UNTIL",
3260 [RES_DO ] = "DO" ,
3261 [RES_DONE ] = "DONE" ,
Denis Vlasenkod91afa32008-07-29 11:10:01 +00003262#endif
3263#if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00003264 [RES_IN ] = "IN" ,
Denis Vlasenko06810332007-05-21 23:30:54 +00003265#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003266#if ENABLE_HUSH_CASE
3267 [RES_CASE ] = "CASE" ,
3268 [RES_MATCH] = "MATCH",
3269 [RES_CASEI] = "CASEI",
3270 [RES_ESAC ] = "ESAC" ,
3271#endif
Denis Vlasenko06810332007-05-21 23:30:54 +00003272 [RES_XXXX ] = "XXXX" ,
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00003273 [RES_SNTX ] = "SNTX" ,
Denis Vlasenko400c5b62007-05-04 13:07:27 +00003274 };
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003275 static const char *const GRPTYPE[] = {
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003276 "{}",
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00003277 "()",
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003278#if ENABLE_HUSH_FUNCTIONS
3279 "func()",
3280#endif
3281 };
Denis Vlasenko400c5b62007-05-04 13:07:27 +00003282
3283 int pin, prn;
Denis Vlasenko219e88d2007-05-21 10:18:23 +00003284
Denis Vlasenko400c5b62007-05-04 13:07:27 +00003285 pin = 0;
3286 while (pi) {
Denis Vlasenko219e88d2007-05-21 10:18:23 +00003287 fprintf(stderr, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
3288 pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
Denis Vlasenko400c5b62007-05-04 13:07:27 +00003289 prn = 0;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003290 while (prn < pi->num_cmds) {
3291 struct command *command = &pi->cmds[prn];
3292 char **argv = command->argv;
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003293
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003294 fprintf(stderr, "%*s cmd %d assignment_cnt:%d",
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003295 lvl*2, "", prn,
3296 command->assignment_cnt);
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003297 if (command->group) {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00003298 fprintf(stderr, " group %s: (argv=%p)\n",
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003299 GRPTYPE[command->grp_type],
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00003300 argv);
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003301 debug_print_tree(command->group, lvl+1);
Denis Vlasenko400c5b62007-05-04 13:07:27 +00003302 prn++;
3303 continue;
3304 }
Denis Vlasenko400c5b62007-05-04 13:07:27 +00003305 if (argv) while (*argv) {
3306 fprintf(stderr, " '%s'", *argv);
3307 argv++;
Denis Vlasenko4b924f32007-05-30 00:29:55 +00003308 }
Denis Vlasenko400c5b62007-05-04 13:07:27 +00003309 fprintf(stderr, "\n");
3310 prn++;
3311 }
3312 pi = pi->next;
3313 pin++;
3314 }
3315}
3316#endif
3317
Denis Vlasenkoc666f712007-05-16 22:18:54 +00003318/* NB: called by pseudo_exec, and therefore must not modify any
3319 * global data until exec/_exit (we can be a child after vfork!) */
Denis Vlasenko05743d72008-02-10 12:10:08 +00003320static int run_list(struct pipe *pi)
Eric Andersen25f27032001-04-26 23:22:31 +00003321{
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003322#if ENABLE_HUSH_CASE
3323 char *case_word = NULL;
3324#endif
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00003325#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +00003326 struct pipe *loop_top = NULL;
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00003327 char *for_varname = NULL;
3328 char **for_lcur = NULL;
3329 char **for_list = NULL;
Denis Vlasenko06810332007-05-21 23:30:54 +00003330#endif
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00003331 smallint last_followup;
3332 smalluint rcode;
Denis Vlasenkod91afa32008-07-29 11:10:01 +00003333#if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00003334 smalluint cond_code = 0;
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00003335#else
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00003336 enum { cond_code = 0 };
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00003337#endif
Denis Vlasenko0e151382009-04-06 18:40:31 +00003338#if HAS_KEYWORDS
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003339 smallint rword; /* enum reserved_style */
3340 smallint last_rword; /* ditto */
Denis Vlasenko0e151382009-04-06 18:40:31 +00003341#endif
Denis Vlasenko4ac530c2007-05-02 15:35:45 +00003342
Denis Vlasenko87a86552008-07-29 19:43:10 +00003343 debug_printf_exec("run_list start lvl %d\n", G.run_list_level + 1);
Denis Vlasenko4ac530c2007-05-02 15:35:45 +00003344
Denis Vlasenko06810332007-05-21 23:30:54 +00003345#if ENABLE_HUSH_LOOPS
Denis Vlasenkobcb25532008-07-28 23:04:34 +00003346 /* Check syntax for "for" */
Denis Vlasenkocf22c892008-07-28 15:17:44 +00003347 for (struct pipe *cpipe = pi; cpipe; cpipe = cpipe->next) {
3348 if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003349 continue;
3350 /* current word is FOR or IN (BOLD in comments below) */
Denis Vlasenkocf22c892008-07-28 15:17:44 +00003351 if (cpipe->next == NULL) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003352 syntax_error("malformed for");
Denis Vlasenko87a86552008-07-29 19:43:10 +00003353 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003354 return 1;
Eric Andersenc7bda1c2004-03-15 08:29:22 +00003355 }
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003356 /* "FOR v; do ..." and "for v IN a b; do..." are ok */
Denis Vlasenkocf22c892008-07-28 15:17:44 +00003357 if (cpipe->next->res_word == RES_DO)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003358 continue;
3359 /* next word is not "do". It must be "in" then ("FOR v in ...") */
Denis Vlasenkocf22c892008-07-28 15:17:44 +00003360 if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
3361 || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003362 ) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003363 syntax_error("malformed for");
Denis Vlasenko87a86552008-07-29 19:43:10 +00003364 debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003365 return 1;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003366 }
3367 }
Denis Vlasenko06810332007-05-21 23:30:54 +00003368#endif
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00003369
Denis Vlasenkobe709c22008-07-28 00:01:16 +00003370 /* Past this point, all code paths should jump to ret: label
Denis Vlasenko12acec52008-07-28 15:15:59 +00003371 * in order to return, no direct "return" statements please.
3372 * This helps to ensure that no memory is leaked. */
Denis Vlasenkobe709c22008-07-28 00:01:16 +00003373
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00003374////TODO: ctrl-Z handling needs re-thinking and re-testing
Denis Vlasenkod5762932009-03-31 11:22:57 +00003375
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00003376#if ENABLE_HUSH_JOB
3377 /* Example of nested list: "while true; do { sleep 1 | exit 2; } done".
3378 * We are saving state before entering outermost list ("while...done")
3379 * so that ctrl-Z will correctly background _entire_ outermost list,
3380 * not just a part of it (like "sleep 1 | exit 2") */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00003381 if (++G.run_list_level == 1 && G_interactive_fd) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00003382 if (sigsetjmp(G.toplevel_jb, 1)) {
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00003383 /* ctrl-Z forked and we are parent; or ctrl-C.
3384 * Sighandler has longjmped us here */
3385 signal(SIGINT, SIG_IGN);
3386 signal(SIGTSTP, SIG_IGN);
3387 /* Restore level (we can be coming from deep inside
3388 * nested levels) */
Denis Vlasenko87a86552008-07-29 19:43:10 +00003389 G.run_list_level = 1;
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00003390#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko87a86552008-07-29 19:43:10 +00003391 if (G.nofork_save.saved) { /* if save area is valid */
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00003392 debug_printf_jobs("exiting nofork early\n");
Denis Vlasenko87a86552008-07-29 19:43:10 +00003393 restore_nofork_data(&G.nofork_save);
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00003394 }
3395#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +00003396//// if (G.ctrl_z_flag) {
3397//// /* ctrl-Z has forked and stored pid of the child in pi->pid.
3398//// * Remember this child as background job */
3399//// insert_bg_job(pi);
3400//// } else {
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003401 /* ctrl-C. We just stop doing whatever we were doing */
Denis Vlasenko4daad902007-09-27 10:20:47 +00003402 bb_putchar('\n');
Denis Vlasenkod5762932009-03-31 11:22:57 +00003403//// }
Denis Vlasenkoff29b4f2008-07-29 13:57:59 +00003404 USE_HUSH_LOOPS(loop_top = NULL;)
Denis Vlasenko87a86552008-07-29 19:43:10 +00003405 USE_HUSH_LOOPS(G.depth_of_loop = 0;)
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00003406 rcode = 0;
3407 goto ret;
3408 }
Denis Vlasenkod5762932009-03-31 11:22:57 +00003409//// /* ctrl-Z handler will store pid etc in pi */
3410//// G.toplevel_list = pi;
3411//// G.ctrl_z_flag = 0;
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00003412#if ENABLE_FEATURE_SH_STANDALONE
3413 G.nofork_save.saved = 0; /* in case we will run a nofork later */
3414#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +00003415//// signal_SA_RESTART_empty_mask(SIGTSTP, handler_ctrl_z);
3416//// signal(SIGINT, handler_ctrl_c);
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00003417 }
Denis Vlasenko05743d72008-02-10 12:10:08 +00003418#endif /* JOB */
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00003419
Denis Vlasenko0e151382009-04-06 18:40:31 +00003420#if HAS_KEYWORDS
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00003421 rword = RES_NONE;
3422 last_rword = RES_XXXX;
Denis Vlasenko0e151382009-04-06 18:40:31 +00003423#endif
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00003424 last_followup = PIPE_SEQ;
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00003425 rcode = G.last_exitcode;
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00003426
Denis Vlasenkobcb25532008-07-28 23:04:34 +00003427 /* Go through list of pipes, (maybe) executing them. */
3428 for (; pi; pi = USE_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
Denis Vlasenko422cd7c2009-03-31 12:41:52 +00003429 if (G.flag_SIGINT)
3430 break;
3431
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003432 IF_HAS_KEYWORDS(rword = pi->res_word;)
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00003433 debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
3434 rword, cond_code, last_rword);
Denis Vlasenko06810332007-05-21 23:30:54 +00003435#if ENABLE_HUSH_LOOPS
Denis Vlasenko4554b722008-07-29 13:36:09 +00003436 if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
Denis Vlasenko87a86552008-07-29 19:43:10 +00003437 && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
Denis Vlasenko4554b722008-07-29 13:36:09 +00003438 ) {
Denis Vlasenkobcb25532008-07-28 23:04:34 +00003439 /* start of a loop: remember where loop starts */
3440 loop_top = pi;
Denis Vlasenko87a86552008-07-29 19:43:10 +00003441 G.depth_of_loop++;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003442 }
Denis Vlasenko06810332007-05-21 23:30:54 +00003443#endif
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00003444 /* Still in the same "if...", "then..." or "do..." branch? */
Denis Vlasenko0e151382009-04-06 18:40:31 +00003445 if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00003446 if ((rcode == 0 && last_followup == PIPE_OR)
3447 || (rcode != 0 && last_followup == PIPE_AND)
3448 ) {
3449 /* It is "<true> || CMD" or "<false> && CMD"
3450 * and we should not execute CMD */
3451 debug_printf_exec("skipped cmd because of || or &&\n");
3452 last_followup = pi->followup;
3453 continue;
3454 }
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003455 }
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00003456 last_followup = pi->followup;
Denis Vlasenko0e151382009-04-06 18:40:31 +00003457 IF_HAS_KEYWORDS(last_rword = rword;)
Denis Vlasenko06810332007-05-21 23:30:54 +00003458#if ENABLE_HUSH_IF
Denis Vlasenkobcb25532008-07-28 23:04:34 +00003459 if (cond_code) {
3460 if (rword == RES_THEN) {
Denis Vlasenko0e151382009-04-06 18:40:31 +00003461 /* if false; then ... fi has exitcode 0! */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00003462 G.last_exitcode = rcode = EXIT_SUCCESS;
Denis Vlasenkobcb25532008-07-28 23:04:34 +00003463 /* "if <false> THEN cmd": skip cmd */
3464 continue;
3465 }
3466 } else {
3467 if (rword == RES_ELSE || rword == RES_ELIF) {
3468 /* "if <true> then ... ELSE/ELIF cmd":
3469 * skip cmd and all following ones */
3470 break;
3471 }
3472 }
Denis Vlasenko06810332007-05-21 23:30:54 +00003473#endif
3474#if ENABLE_HUSH_LOOPS
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003475 if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00003476 if (!for_lcur) {
Denis Vlasenkod65ea392007-10-01 10:02:25 +00003477 /* first loop through for */
Denis Vlasenkoff182a32008-07-05 20:29:59 +00003478
3479 static const char encoded_dollar_at[] ALIGN1 = {
3480 SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
3481 }; /* encoded representation of "$@" */
3482 static const char *const encoded_dollar_at_argv[] = {
3483 encoded_dollar_at, NULL
3484 }; /* argv list with one element: "$@" */
3485 char **vals;
3486
3487 vals = (char**)encoded_dollar_at_argv;
Denis Vlasenkocf22c892008-07-28 15:17:44 +00003488 if (pi->next->res_word == RES_IN) {
Denis Vlasenkoff182a32008-07-05 20:29:59 +00003489 /* if no variable values after "in" we skip "for" */
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00003490 if (!pi->next->cmds[0].argv) {
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00003491 G.last_exitcode = rcode = EXIT_SUCCESS;
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00003492 debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
Denis Vlasenkobcb25532008-07-28 23:04:34 +00003493 break;
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00003494 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003495 vals = pi->next->cmds[0].argv;
Denis Vlasenkoff182a32008-07-05 20:29:59 +00003496 } /* else: "for var; do..." -> assume "$@" list */
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003497 /* create list of variable values */
Denis Vlasenkoff182a32008-07-05 20:29:59 +00003498 debug_print_strings("for_list made from", vals);
3499 for_list = expand_strvec_to_strvec(vals);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00003500 for_lcur = for_list;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003501 debug_print_strings("for_list", for_list);
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003502 for_varname = pi->cmds[0].argv[0];
3503 pi->cmds[0].argv[0] = NULL;
Eric Andersenc7bda1c2004-03-15 08:29:22 +00003504 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003505 free(pi->cmds[0].argv[0]);
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00003506 if (!*for_lcur) {
Denis Vlasenko12acec52008-07-28 15:15:59 +00003507 /* "for" loop is over, clean up */
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00003508 free(for_list);
Denis Vlasenkobe709c22008-07-28 00:01:16 +00003509 for_list = NULL;
Denis Vlasenko03eb8bf2007-05-14 16:19:34 +00003510 for_lcur = NULL;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003511 pi->cmds[0].argv[0] = for_varname;
Denis Vlasenkobcb25532008-07-28 23:04:34 +00003512 break;
Eric Andersen4c9b68f2002-04-13 12:33:41 +00003513 }
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00003514 /* Insert next value from for_lcur */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003515 /* note: *for_lcur already has quotes removed, $var expanded, etc */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003516 pi->cmds[0].argv[0] = xasprintf("%s=%s", for_varname, *for_lcur++);
3517 pi->cmds[0].assignment_cnt = 1;
Eric Andersenc7bda1c2004-03-15 08:29:22 +00003518 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00003519 if (rword == RES_IN) {
3520 continue; /* "for v IN list;..." - "in" has no cmds anyway */
3521 }
Denis Vlasenkobcb25532008-07-28 23:04:34 +00003522 if (rword == RES_DONE) {
3523 continue; /* "done" has no cmds too */
Eric Andersenc7bda1c2004-03-15 08:29:22 +00003524 }
Denis Vlasenko06810332007-05-21 23:30:54 +00003525#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003526#if ENABLE_HUSH_CASE
3527 if (rword == RES_CASE) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003528 case_word = expand_strvec_to_string(pi->cmds->argv);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003529 continue;
3530 }
3531 if (rword == RES_MATCH) {
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00003532 char **argv;
3533
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00003534 if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
3535 break;
3536 /* all prev words didn't match, does this one match? */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003537 argv = pi->cmds->argv;
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00003538 while (*argv) {
3539 char *pattern = expand_string_to_string(*argv);
3540 /* TODO: which FNM_xxx flags to use? */
3541 cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
3542 free(pattern);
3543 if (cond_code == 0) { /* match! we will execute this branch */
3544 free(case_word); /* make future "word)" stop */
3545 case_word = NULL;
3546 break;
3547 }
3548 argv++;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003549 }
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00003550 continue;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003551 }
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00003552 if (rword == RES_CASEI) { /* inside of a case branch */
Denis Vlasenkobcb25532008-07-28 23:04:34 +00003553 if (cond_code != 0)
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00003554 continue; /* not matched yet, skip this pipe */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003555 }
3556#endif
Denis Vlasenkod5762932009-03-31 11:22:57 +00003557 /* Just pressing <enter> in shell should check for jobs.
3558 * OTOH, in non-interactive shell this is useless
3559 * and only leads to extra job checks */
3560 if (pi->num_cmds == 0) {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00003561 if (G_interactive_fd)
Denis Vlasenkod5762932009-03-31 11:22:57 +00003562 goto check_jobs_and_continue;
3563 continue;
3564 }
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00003565
Denis Vlasenkobcb25532008-07-28 23:04:34 +00003566 /* After analyzing all keywords and conditions, we decided
Denis Vlasenkod5762932009-03-31 11:22:57 +00003567 * to execute this pipe. NB: have to do checkjobs(NULL)
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00003568 * after run_pipe to collect any background children,
Denis Vlasenkobcb25532008-07-28 23:04:34 +00003569 * even if list execution is to be stopped. */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003570 debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00003571 {
3572 int r;
Denis Vlasenkodadfb492008-07-29 10:16:05 +00003573#if ENABLE_HUSH_LOOPS
Denis Vlasenko87a86552008-07-29 19:43:10 +00003574 G.flag_break_continue = 0;
Denis Vlasenkodadfb492008-07-29 10:16:05 +00003575#endif
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00003576 rcode = r = run_pipe(pi); /* NB: rcode is a smallint */
3577 if (r != -1) {
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00003578 /* We only ran a builtin: rcode is already known
Denis Vlasenkobcb25532008-07-28 23:04:34 +00003579 * and we don't need to wait for anything. */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00003580 G.last_exitcode = rcode;
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00003581 debug_printf_exec(": builtin exitcode %d\n", rcode);
Denis Vlasenko7566bae2009-03-31 17:24:49 +00003582 check_and_run_traps(0);
Denis Vlasenkodadfb492008-07-29 10:16:05 +00003583#if ENABLE_HUSH_LOOPS
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00003584 /* Was it "break" or "continue"? */
Denis Vlasenko87a86552008-07-29 19:43:10 +00003585 if (G.flag_break_continue) {
3586 smallint fbc = G.flag_break_continue;
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00003587 /* We might fall into outer *loop*,
Denis Vlasenkobcb25532008-07-28 23:04:34 +00003588 * don't want to break it too */
Denis Vlasenkobcb25532008-07-28 23:04:34 +00003589 if (loop_top) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00003590 G.depth_break_continue--;
3591 if (G.depth_break_continue == 0)
3592 G.flag_break_continue = 0;
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00003593 /* else: e.g. "continue 2" should *break* once, *then* continue */
3594 } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
Denis Vlasenko87a86552008-07-29 19:43:10 +00003595 if (G.depth_break_continue != 0 || fbc == BC_BREAK)
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00003596 goto check_jobs_and_break;
3597 /* "continue": simulate end of loop */
3598 rword = RES_DONE;
3599 continue;
Denis Vlasenkobcb25532008-07-28 23:04:34 +00003600 }
Denis Vlasenkodadfb492008-07-29 10:16:05 +00003601#endif
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00003602 } else if (pi->followup == PIPE_BG) {
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00003603 /* What does bash do with attempts to background builtins? */
Denis Vlasenkobcb25532008-07-28 23:04:34 +00003604 /* even bash 3.2 doesn't do that well with nested bg:
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00003605 * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
3606 * I'm NOT treating inner &'s as jobs */
Denis Vlasenko7566bae2009-03-31 17:24:49 +00003607 check_and_run_traps(0);
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003608#if ENABLE_HUSH_JOB
Denis Vlasenko87a86552008-07-29 19:43:10 +00003609 if (G.run_list_level == 1)
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00003610 insert_bg_job(pi);
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00003611#endif
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00003612 G.last_exitcode = rcode = EXIT_SUCCESS;
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00003613 debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00003614 } else {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003615#if ENABLE_HUSH_JOB
Denis Vlasenko60b392f2009-04-03 19:14:32 +00003616 if (G.run_list_level == 1 && G_interactive_fd) {
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00003617 /* Waits for completion, then fg's main shell */
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00003618 rcode = checkjobs_and_fg_shell(pi);
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00003619 debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
Denis Vlasenko7566bae2009-03-31 17:24:49 +00003620 check_and_run_traps(0);
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00003621 } else
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00003622#endif
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00003623 { /* This one just waits for completion */
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00003624 rcode = checkjobs(pi);
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00003625 debug_printf_exec(": checkjobs exitcode %d\n", rcode);
Denis Vlasenko7566bae2009-03-31 17:24:49 +00003626 check_and_run_traps(0);
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00003627 }
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00003628 G.last_exitcode = rcode;
Eric Andersen25f27032001-04-26 23:22:31 +00003629 }
3630 }
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00003631
3632 /* Analyze how result affects subsequent commands */
Denis Vlasenko06810332007-05-21 23:30:54 +00003633#if ENABLE_HUSH_IF
Denis Vlasenko219e88d2007-05-21 10:18:23 +00003634 if (rword == RES_IF || rword == RES_ELIF)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00003635 cond_code = rcode;
Denis Vlasenko06810332007-05-21 23:30:54 +00003636#endif
3637#if ENABLE_HUSH_LOOPS
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003638 /* Beware of "while false; true; do ..."! */
3639 if (pi->next && pi->next->res_word == RES_DO) {
3640 if (rword == RES_WHILE) {
3641 if (rcode) {
3642 /* "while false; do...done" - exitcode 0 */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00003643 G.last_exitcode = rcode = EXIT_SUCCESS;
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003644 debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
3645 goto check_jobs_and_break;
3646 }
Denis Vlasenko918a34b2008-07-28 23:17:31 +00003647 }
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003648 if (rword == RES_UNTIL) {
3649 if (!rcode) {
3650 debug_printf_exec(": until expr is true: breaking\n");
Denis Vlasenkobcb25532008-07-28 23:04:34 +00003651 check_jobs_and_break:
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003652 checkjobs(NULL);
3653 break;
3654 }
Denis Vlasenkobcb25532008-07-28 23:04:34 +00003655 }
Denis Vlasenko5e052ca2008-07-28 15:15:09 +00003656 }
Denis Vlasenko06810332007-05-21 23:30:54 +00003657#endif
Mike Frysinger8ec1c9d2009-03-29 00:45:26 +00003658
3659 check_jobs_and_continue:
Eric Andersen028b65b2001-06-28 01:10:11 +00003660 checkjobs(NULL);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003661 } /* for (pi) */
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00003662
3663#if ENABLE_HUSH_JOB
Denis Vlasenkod5762932009-03-31 11:22:57 +00003664//// if (G.ctrl_z_flag) {
3665//// /* ctrl-Z forked somewhere in the past, we are the child,
3666//// * and now we completed running the list. Exit. */
3667//////TODO: _exit?
3668//// exit(rcode);
3669//// }
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00003670 ret:
Denis Vlasenkod5762932009-03-31 11:22:57 +00003671 G.run_list_level--;
Denis Vlasenko60b392f2009-04-03 19:14:32 +00003672//// if (!G.run_list_level && G_interactive_fd) {
Denis Vlasenkod5762932009-03-31 11:22:57 +00003673//// signal(SIGTSTP, SIG_IGN);
3674//// signal(SIGINT, SIG_IGN);
3675//// }
Denis Vlasenkoac0e5ab2007-05-04 21:37:27 +00003676#endif
Denis Vlasenko87a86552008-07-29 19:43:10 +00003677 debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
Denis Vlasenkobe709c22008-07-28 00:01:16 +00003678#if ENABLE_HUSH_LOOPS
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00003679 if (loop_top)
Denis Vlasenko87a86552008-07-29 19:43:10 +00003680 G.depth_of_loop--;
Denis Vlasenkobe709c22008-07-28 00:01:16 +00003681 free(for_list);
3682#endif
3683#if ENABLE_HUSH_CASE
3684 free(case_word);
3685#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003686 return rcode;
3687}
3688
Eric Andersen25f27032001-04-26 23:22:31 +00003689/* Select which version we will use */
Denis Vlasenko05743d72008-02-10 12:10:08 +00003690static int run_and_free_list(struct pipe *pi)
Eric Andersen25f27032001-04-26 23:22:31 +00003691{
Denis Vlasenko0c886c62007-01-30 22:30:09 +00003692 int rcode = 0;
Denis Vlasenko05743d72008-02-10 12:10:08 +00003693 debug_printf_exec("run_and_free_list entered\n");
Denis Vlasenko87a86552008-07-29 19:43:10 +00003694 if (!G.fake_mode) {
Denis Vlasenkoa2b11e32009-04-06 14:11:13 +00003695 debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
Denis Vlasenko05743d72008-02-10 12:10:08 +00003696 rcode = run_list(pi);
Eric Andersenc7bda1c2004-03-15 08:29:22 +00003697 }
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00003698 /* free_pipe_list has the side effect of clearing memory.
Denis Vlasenko05743d72008-02-10 12:10:08 +00003699 * In the long run that function can be merged with run_list,
Eric Andersen25f27032001-04-26 23:22:31 +00003700 * but doing that now would hobble the debugging effort. */
Denis Vlasenko05743d72008-02-10 12:10:08 +00003701 free_pipe_list(pi, /* indent: */ 0);
Denis Vlasenko87f40ba2008-06-10 22:39:37 +00003702 debug_printf_exec("run_and_free_list return %d\n", rcode);
Eric Andersen25f27032001-04-26 23:22:31 +00003703 return rcode;
3704}
3705
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00003706
Denis Vlasenkoac678ec2007-04-16 22:32:04 +00003707static struct pipe *new_pipe(void)
3708{
Eric Andersen25f27032001-04-26 23:22:31 +00003709 struct pipe *pi;
Denis Vlasenko3ac0e002007-04-28 16:45:22 +00003710 pi = xzalloc(sizeof(struct pipe));
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003711 /*pi->followup = 0; - deliberately invalid value */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003712 /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
Eric Andersen25f27032001-04-26 23:22:31 +00003713 return pi;
3714}
3715
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003716/* Command (member of a pipe) is complete. The only possible error here
3717 * is out of memory, in which case xmalloc exits. */
3718static int done_command(struct parse_context *ctx)
3719{
3720 /* The command is really already in the pipe structure, so
3721 * advance the pipe counter and make a new, null command. */
3722 struct pipe *pi = ctx->pipe;
3723 struct command *command = ctx->command;
3724
3725 if (command) {
3726 if (command->group == NULL
3727 && command->argv == NULL
3728 && command->redirects == NULL
3729 ) {
3730 debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003731 memset(command, 0, sizeof(*command)); /* paranoia */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003732 return pi->num_cmds;
3733 }
3734 pi->num_cmds++;
3735 debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003736 //debug_print_tree(ctx->list_head, 20);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003737 } else {
3738 debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
3739 }
3740
3741 /* Only real trickiness here is that the uncommitted
3742 * command structure is not counted in pi->num_cmds. */
3743 pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
3744 command = &pi->cmds[pi->num_cmds];
3745 memset(command, 0, sizeof(*command));
3746
3747 ctx->command = command;
3748 /* but ctx->pipe and ctx->list_head remain unchanged */
3749
3750 return pi->num_cmds; /* used only for 0/nonzero check */
3751}
3752
3753static void done_pipe(struct parse_context *ctx, pipe_style type)
3754{
3755 int not_null;
3756
3757 debug_printf_parse("done_pipe entered, followup %d\n", type);
3758 /* Close previous command */
3759 not_null = done_command(ctx);
3760 ctx->pipe->followup = type;
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003761#if HAS_KEYWORDS
3762 ctx->pipe->pi_inverted = ctx->ctx_inverted;
3763 ctx->ctx_inverted = 0;
3764 ctx->pipe->res_word = ctx->ctx_res_w;
3765#endif
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003766
3767 /* Without this check, even just <enter> on command line generates
3768 * tree of three NOPs (!). Which is harmless but annoying.
3769 * IOW: it is safe to do it unconditionally.
3770 * RES_NONE case is for "for a in; do ..." (empty IN set)
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003771 * and other cases to work. */
3772 if (not_null
3773#if HAS_KEYWORDS
3774 || ctx->ctx_res_w == RES_FI
3775 || ctx->ctx_res_w == RES_DONE
3776 || ctx->ctx_res_w == RES_FOR
3777 || ctx->ctx_res_w == RES_IN
3778 || ctx->ctx_res_w == RES_ESAC
3779#endif
3780 ) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003781 struct pipe *new_p;
3782 debug_printf_parse("done_pipe: adding new pipe: "
3783 "not_null:%d ctx->ctx_res_w:%d\n",
3784 not_null, ctx->ctx_res_w);
3785 new_p = new_pipe();
3786 ctx->pipe->next = new_p;
3787 ctx->pipe = new_p;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003788 /* RES_THEN, RES_DO etc are "sticky" -
3789 * they remain set for commands inside if/while.
3790 * This is used to control execution.
3791 * RES_FOR and RES_IN are NOT sticky (needed to support
3792 * cases where variable or value happens to match a keyword):
3793 */
3794#if ENABLE_HUSH_LOOPS
3795 if (ctx->ctx_res_w == RES_FOR
3796 || ctx->ctx_res_w == RES_IN)
3797 ctx->ctx_res_w = RES_NONE;
3798#endif
3799#if ENABLE_HUSH_CASE
3800 if (ctx->ctx_res_w == RES_MATCH)
3801 ctx->ctx_res_w = RES_CASEI;
3802#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003803 ctx->command = NULL; /* trick done_command below */
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003804 /* Create the memory for command, roughly:
3805 * ctx->pipe->cmds = new struct command;
3806 * ctx->command = &ctx->pipe->cmds[0];
3807 */
3808 done_command(ctx);
Denis Vlasenkocd418a22009-04-06 18:08:35 +00003809 //debug_print_tree(ctx->list_head, 10);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00003810 }
3811 debug_printf_parse("done_pipe return\n");
3812}
3813
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003814static void initialize_context(struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00003815{
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003816 memset(ctx, 0, sizeof(*ctx));
Denis Vlasenko1a735862007-05-23 00:32:25 +00003817 ctx->pipe = ctx->list_head = new_pipe();
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003818 /* Create the memory for command, roughly:
3819 * ctx->pipe->cmds = new struct command;
3820 * ctx->command = &ctx->pipe->cmds[0];
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003821 */
3822 done_command(ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00003823}
3824
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003825/* If a reserved word is found and processed, parse context is modified
3826 * and 1 is returned.
Eric Andersen25f27032001-04-26 23:22:31 +00003827 */
Denis Vlasenko5ec61322008-06-24 00:50:07 +00003828#if HAS_KEYWORDS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003829struct reserved_combo {
3830 char literal[6];
3831 unsigned char res;
3832 unsigned char assignment_flag;
3833 int flag;
3834};
3835enum {
3836 FLAG_END = (1 << RES_NONE ),
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003837#if ENABLE_HUSH_IF
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003838 FLAG_IF = (1 << RES_IF ),
3839 FLAG_THEN = (1 << RES_THEN ),
3840 FLAG_ELIF = (1 << RES_ELIF ),
3841 FLAG_ELSE = (1 << RES_ELSE ),
3842 FLAG_FI = (1 << RES_FI ),
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003843#endif
3844#if ENABLE_HUSH_LOOPS
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003845 FLAG_FOR = (1 << RES_FOR ),
3846 FLAG_WHILE = (1 << RES_WHILE),
3847 FLAG_UNTIL = (1 << RES_UNTIL),
3848 FLAG_DO = (1 << RES_DO ),
3849 FLAG_DONE = (1 << RES_DONE ),
3850 FLAG_IN = (1 << RES_IN ),
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003851#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003852#if ENABLE_HUSH_CASE
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003853 FLAG_MATCH = (1 << RES_MATCH),
3854 FLAG_ESAC = (1 << RES_ESAC ),
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003855#endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003856 FLAG_START = (1 << RES_XXXX ),
3857};
3858
3859static const struct reserved_combo* match_reserved_word(o_string *word)
3860{
Eric Andersen25f27032001-04-26 23:22:31 +00003861 /* Mostly a list of accepted follow-up reserved words.
3862 * FLAG_END means we are done with the sequence, and are ready
3863 * to turn the compound list into a command.
3864 * FLAG_START means the word must start a new compound list.
3865 */
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003866 static const struct reserved_combo reserved_list[] = {
Denis Vlasenko06810332007-05-21 23:30:54 +00003867#if ENABLE_HUSH_IF
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003868 { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
3869 { "if", RES_IF, WORD_IS_KEYWORD, FLAG_THEN | FLAG_START },
3870 { "then", RES_THEN, WORD_IS_KEYWORD, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
3871 { "elif", RES_ELIF, WORD_IS_KEYWORD, FLAG_THEN },
3872 { "else", RES_ELSE, WORD_IS_KEYWORD, FLAG_FI },
3873 { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
Denis Vlasenko06810332007-05-21 23:30:54 +00003874#endif
3875#if ENABLE_HUSH_LOOPS
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003876 { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
3877 { "while", RES_WHILE, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
3878 { "until", RES_UNTIL, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
3879 { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
3880 { "do", RES_DO, WORD_IS_KEYWORD, FLAG_DONE },
3881 { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003882#endif
3883#if ENABLE_HUSH_CASE
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003884 { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
3885 { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
Denis Vlasenko06810332007-05-21 23:30:54 +00003886#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003887 };
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003888 const struct reserved_combo *r;
3889
3890 for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
3891 if (strcmp(word->data, r->literal) == 0)
3892 return r;
3893 }
3894 return NULL;
3895}
3896static int reserved_word(o_string *word, struct parse_context *ctx)
3897{
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003898#if ENABLE_HUSH_CASE
3899 static const struct reserved_combo reserved_match = {
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003900 "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003901 };
3902#endif
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003903 const struct reserved_combo *r;
Denis Vlasenkoc72c1ed2007-01-30 22:31:26 +00003904
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003905 r = match_reserved_word(word);
3906 if (!r)
3907 return 0;
3908
3909 debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003910#if ENABLE_HUSH_CASE
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003911 if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE)
3912 /* "case word IN ..." - IN part starts first match part */
3913 r = &reserved_match;
3914 else
Denis Vlasenko17f02e72008-07-14 04:32:29 +00003915#endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003916 if (r->flag == 0) { /* '!' */
3917 if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003918 syntax_error("! ! command");
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003919 IF_HAS_KEYWORDS(ctx->ctx_res_w = RES_SNTX;)
Eric Andersen25f27032001-04-26 23:22:31 +00003920 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003921 ctx->ctx_inverted = 1;
Denis Vlasenko1a735862007-05-23 00:32:25 +00003922 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003923 }
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003924 if (r->flag & FLAG_START) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003925 struct parse_context *old;
3926 old = xmalloc(sizeof(*old));
3927 debug_printf_parse("push stack %p\n", old);
3928 *old = *ctx; /* physical copy */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003929 initialize_context(ctx);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003930 ctx->stack = old;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003931 } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00003932 syntax_error_at(word->data);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003933 ctx->ctx_res_w = RES_SNTX;
3934 return 1;
3935 }
3936 ctx->ctx_res_w = r->res;
3937 ctx->old_flag = r->flag;
3938 if (ctx->old_flag & FLAG_END) {
3939 struct parse_context *old;
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003940 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003941 debug_printf_parse("pop stack %p\n", ctx->stack);
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003942 old = ctx->stack;
3943 old->command->group = ctx->list_head;
Denis Vlasenko371de4a2008-10-14 12:43:13 +00003944 old->command->grp_type = GRP_NORMAL;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00003945#if !BB_MMU
3946 o_addstr(&old->as_string, ctx->as_string.data);
3947 o_free_unsafe(&ctx->as_string);
3948 old->command->group_as_string = xstrdup(old->as_string.data);
3949 debug_printf_parse("pop, remembering as:'%s'\n",
3950 old->command->group_as_string);
3951#endif
Denis Vlasenkoc3735272008-10-09 12:58:26 +00003952 *ctx = *old; /* physical copy */
3953 free(old);
3954 }
3955 word->o_assignment = r->assignment_flag;
3956 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00003957}
Denis Vlasenko06810332007-05-21 23:30:54 +00003958#endif
Eric Andersen25f27032001-04-26 23:22:31 +00003959
Denis Vlasenkoa8442002008-06-14 11:00:17 +00003960/* Word is complete, look at it and update parsing context.
Denis Vlasenkob6e65562009-04-03 16:49:04 +00003961 * Normal return is 0. Syntax errors return 1.
3962 * Note: on return, word is reset, but not o_free'd!
3963 */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003964static int done_word(o_string *word, struct parse_context *ctx)
Eric Andersen25f27032001-04-26 23:22:31 +00003965{
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003966 struct command *command = ctx->command;
Eric Andersen25f27032001-04-26 23:22:31 +00003967
Denis Vlasenko9af22c72008-10-09 12:54:58 +00003968 debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003969 if (word->length == 0 && word->o_quoted == 0) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003970 debug_printf_parse("done_word return 0: true null, ignored\n");
3971 return 0;
Eric Andersen25f27032001-04-26 23:22:31 +00003972 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00003973
Eric Andersen25f27032001-04-26 23:22:31 +00003974 if (ctx->pending_redirect) {
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003975 /* We do not glob in e.g. >*.tmp case. bash seems to glob here
3976 * only if run as "bash", not "sh" */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00003977 /* http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
3978 * "2.7 Redirection
3979 * ...the word that follows the redirection operator
3980 * shall be subjected to tilde expansion, parameter expansion,
3981 * command substitution, arithmetic expansion, and quote
3982 * removal. Pathname expansion shall not be performed
3983 * on the word by a non-interactive shell; an interactive
3984 * shell may perform it, but shall do so only when
3985 * the expansion would result in one word."
3986 */
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00003987 ctx->pending_redirect->rd_filename = xstrdup(word->data);
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00003988 /* Cater for >\file case:
3989 * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
3990 * Same with heredocs:
3991 * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
3992 */
3993 unbackslash(ctx->pending_redirect->rd_filename);
3994 /* Is it <<"HEREDOC"? */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00003995 if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC
3996 && word->o_quoted
3997 ) {
3998 ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
3999 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004000 debug_printf_parse("word stored in rd_filename: '%s'\n", word->data);
Eric Andersen25f27032001-04-26 23:22:31 +00004001 } else {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004002 /* If this word wasn't an assignment, next ones definitely
4003 * can't be assignments. Even if they look like ones. */
4004 if (word->o_assignment != DEFINITELY_ASSIGNMENT
4005 && word->o_assignment != WORD_IS_KEYWORD
4006 ) {
4007 word->o_assignment = NOT_ASSIGNMENT;
4008 } else {
4009 if (word->o_assignment == DEFINITELY_ASSIGNMENT)
4010 command->assignment_cnt++;
4011 word->o_assignment = MAYBE_ASSIGNMENT;
4012 }
4013
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004014 if (command->group) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004015 /* "{ echo foo; } echo bar" - bad */
4016 /* NB: bash allows e.g.:
4017 * if true; then { echo foo; } fi
4018 * while if false; then false; fi do break; done
4019 * and disallows:
4020 * while if false; then false; fi; do; break; done
4021 * TODO? */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004022 syntax_error_at(word->data);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004023 debug_printf_parse("done_word return 1: syntax error, "
4024 "groups and arglists don't mix\n");
Denis Vlasenko395ae452008-07-14 06:29:38 +00004025 return 1;
4026 }
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004027#if HAS_KEYWORDS
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004028# if ENABLE_HUSH_CASE
Denis Vlasenko757361f2008-07-14 08:26:47 +00004029 if (ctx->ctx_dsemicolon
4030 && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
4031 ) {
Denis Vlasenko395ae452008-07-14 06:29:38 +00004032 /* already done when ctx_dsemicolon was set to 1: */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004033 /* ctx->ctx_res_w = RES_MATCH; */
4034 ctx->ctx_dsemicolon = 0;
4035 } else
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004036# endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004037 if (!command->argv /* if it's the first word... */
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004038# if ENABLE_HUSH_LOOPS
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004039 && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
4040 && ctx->ctx_res_w != RES_IN
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004041# endif
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004042 ) {
Denis Vlasenkoa8442002008-06-14 11:00:17 +00004043 debug_printf_parse(": checking '%s' for reserved-ness\n", word->data);
4044 if (reserved_word(word, ctx)) {
4045 o_reset(word);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004046 debug_printf_parse("done_word return %d\n",
4047 (ctx->ctx_res_w == RES_SNTX));
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004048 return (ctx->ctx_res_w == RES_SNTX);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004049 }
Eric Andersen25f27032001-04-26 23:22:31 +00004050 }
Denis Vlasenko5ec61322008-06-24 00:50:07 +00004051#endif
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004052 if (word->o_quoted /* word had "xx" or 'xx' at least as part of it. */
Denis Vlasenko55789c62008-06-18 16:30:42 +00004053 /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
4054 && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004055 /* (otherwise it's known to be not empty and is already safe) */
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00004056 ) {
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004057 /* exclude "$@" - it can expand to no word despite "" */
Denis Vlasenkoafdcd122008-07-05 17:40:04 +00004058 char *p = word->data;
4059 while (p[0] == SPECIAL_VAR_SYMBOL
4060 && (p[1] & 0x7f) == '@'
4061 && p[2] == SPECIAL_VAR_SYMBOL
4062 ) {
4063 p += 3;
4064 }
4065 if (p == word->data || p[0] != '\0') {
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004066 /* saw no "$@", or not only "$@" but some
4067 * real text is there too */
4068 /* insert "empty variable" reference, this makes
Denis Vlasenkoafdcd122008-07-05 17:40:04 +00004069 * e.g. "", $empty"" etc to not disappear */
4070 o_addchr(word, SPECIAL_VAR_SYMBOL);
4071 o_addchr(word, SPECIAL_VAR_SYMBOL);
4072 }
Denis Vlasenkoc1c63b62008-06-18 09:20:35 +00004073 }
Denis Vlasenko22d10a02008-10-13 08:53:43 +00004074 command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004075 debug_print_strings("word appended to argv", command->argv);
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004076 }
Eric Andersen25f27032001-04-26 23:22:31 +00004077
Denis Vlasenkoa8442002008-06-14 11:00:17 +00004078 o_reset(word);
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00004079 ctx->pending_redirect = NULL;
4080
Denis Vlasenko06810332007-05-21 23:30:54 +00004081#if ENABLE_HUSH_LOOPS
Denis Vlasenkoab876cd2008-06-18 16:29:32 +00004082 /* Force FOR to have just one word (variable name) */
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004083 /* NB: basically, this makes hush see "for v in ..." syntax as if
4084 * as it is "for v; in ...". FOR and IN become two pipe structs
4085 * in parse tree. */
4086 if (ctx->ctx_res_w == RES_FOR) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004087 if (!is_well_formed_var_name(command->argv[0], '\0')) {
4088 syntax_error("malformed variable name in for");
4089 return 1;
4090 }
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00004091 done_pipe(ctx, PIPE_SEQ);
Denis Vlasenko733e3fb2008-07-06 10:01:13 +00004092 }
Denis Vlasenko06810332007-05-21 23:30:54 +00004093#endif
Denis Vlasenko17f02e72008-07-14 04:32:29 +00004094#if ENABLE_HUSH_CASE
4095 /* Force CASE to have just one word */
4096 if (ctx->ctx_res_w == RES_CASE) {
4097 done_pipe(ctx, PIPE_SEQ);
4098 }
4099#endif
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004100 debug_printf_parse("done_word return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00004101 return 0;
4102}
4103
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004104
4105/* Peek ahead in the input to find out if we have a "&n" construct,
4106 * as in "2>&1", that represents duplicating a file descriptor.
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004107 * Return:
4108 * REDIRFD_CLOSE if >&- "close fd" construct is seen,
4109 * REDIRFD_SYNTAX_ERR if syntax error,
4110 * REDIRFD_TO_FILE if no & was seen,
4111 * or the number found.
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004112 */
4113#if BB_MMU
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004114#define parse_redir_right_fd(as_string, input) \
4115 parse_redir_right_fd(input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004116#endif
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004117static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004118{
4119 int ch, d, ok;
4120
4121 ch = i_peek(input);
4122 if (ch != '&')
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004123 return REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004124
4125 ch = i_getch(input); /* get the & */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004126 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004127 ch = i_peek(input);
4128 if (ch == '-') {
4129 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004130 nommu_addchr(as_string, ch);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004131 return REDIRFD_CLOSE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004132 }
4133 d = 0;
4134 ok = 0;
4135 while (ch != EOF && isdigit(ch)) {
4136 d = d*10 + (ch-'0');
4137 ok = 1;
4138 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004139 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004140 ch = i_peek(input);
4141 }
4142 if (ok) return d;
4143
4144//TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
4145
4146 bb_error_msg("ambiguous redirect");
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004147 return REDIRFD_SYNTAX_ERR;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004148}
4149
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004150/* Return code is 0 normal, 1 if a syntax error is detected
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004151 */
4152static int parse_redirect(struct parse_context *ctx,
4153 int fd,
4154 redir_type style,
4155 struct in_str *input)
4156{
4157 struct command *command = ctx->command;
4158 struct redir_struct *redir;
4159 struct redir_struct **redirp;
4160 int dup_num;
4161
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004162 dup_num = REDIRFD_TO_FILE;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004163 if (style != REDIRECT_HEREDOC) {
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004164 /* Check for a '>&1' type redirect */
4165 dup_num = parse_redir_right_fd(&ctx->as_string, input);
4166 if (dup_num == REDIRFD_SYNTAX_ERR)
4167 return 1;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004168 } else {
4169 int ch = i_peek(input);
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004170 dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004171 if (dup_num) { /* <<-... */
4172 ch = i_getch(input);
4173 nommu_addchr(&ctx->as_string, ch);
4174 ch = i_peek(input);
4175 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004176 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004177
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004178 if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004179 int ch = i_peek(input);
4180 if (ch == '|') {
4181 /* >|FILE redirect ("clobbering" >).
4182 * Since we do not support "set -o noclobber" yet,
4183 * >| and > are the same for now. Just eat |.
4184 */
4185 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004186 nommu_addchr(&ctx->as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004187 }
4188 }
4189
4190 /* Create a new redir_struct and append it to the linked list */
4191 redirp = &command->redirects;
4192 while ((redir = *redirp) != NULL) {
4193 redirp = &(redir->next);
4194 }
4195 *redirp = redir = xzalloc(sizeof(*redir));
4196 /* redir->next = NULL; */
4197 /* redir->rd_filename = NULL; */
4198 redir->rd_type = style;
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004199 redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004200
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004201 debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
4202 redir_table[style].descrip);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004203
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004204 redir->rd_dup = dup_num;
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00004205 if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004206 /* Erik had a check here that the file descriptor in question
4207 * is legit; I postpone that to "run time"
4208 * A "-" representation of "close me" shows up as a -3 here */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004209 debug_printf_parse("duplicating redirect '%d>&%d'\n",
4210 redir->rd_fd, redir->rd_dup);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004211 } else {
4212 /* Set ctx->pending_redirect, so we know what to do at the
4213 * end of the next parsed word. */
4214 ctx->pending_redirect = redir;
4215 }
4216 return 0;
4217}
4218
Eric Andersen25f27032001-04-26 23:22:31 +00004219/* If a redirect is immediately preceded by a number, that number is
4220 * supposed to tell which file descriptor to redirect. This routine
4221 * looks for such preceding numbers. In an ideal world this routine
4222 * needs to handle all the following classes of redirects...
4223 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
4224 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
4225 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
4226 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004227 *
4228 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
4229 * "2.7 Redirection
4230 * ... If n is quoted, the number shall not be recognized as part of
4231 * the redirection expression. For example:
4232 * echo \2>a
4233 * writes the character 2 into file a"
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004234 * We are getting it right by setting ->o_quoted on any \<char>
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004235 *
4236 * A -1 return means no valid number was found,
4237 * the caller should use the appropriate default for this redirection.
Eric Andersen25f27032001-04-26 23:22:31 +00004238 */
4239static int redirect_opt_num(o_string *o)
4240{
4241 int num;
4242
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004243 if (o->data == NULL)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00004244 return -1;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004245 num = bb_strtou(o->data, NULL, 10);
4246 if (errno || num < 0)
4247 return -1;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004248 o_reset(o);
Eric Andersen25f27032001-04-26 23:22:31 +00004249 return num;
4250}
4251
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004252#if BB_MMU
4253#define fetch_till_str(as_string, input, word, skip_tabs) \
4254 fetch_till_str(input, word, skip_tabs)
4255#endif
4256static char *fetch_till_str(o_string *as_string,
4257 struct in_str *input,
4258 const char *word,
4259 int skip_tabs)
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004260{
4261 o_string heredoc = NULL_O_STRING;
4262 int past_EOL = 0;
4263 int ch;
4264
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004265 goto jump_in;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004266 while (1) {
4267 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004268 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004269 if (ch == '\n') {
4270 if (strcmp(heredoc.data + past_EOL, word) == 0) {
4271 heredoc.data[past_EOL] = '\0';
4272 debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
4273 return heredoc.data;
4274 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004275 do {
4276 o_addchr(&heredoc, ch);
4277 past_EOL = heredoc.length;
4278 jump_in:
4279 do {
4280 ch = i_getch(input);
4281 nommu_addchr(as_string, ch);
4282 } while (skip_tabs && ch == '\t');
4283 } while (ch == '\n');
4284 }
4285 if (ch == EOF) {
4286 o_free_unsafe(&heredoc);
4287 return NULL;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004288 }
4289 o_addchr(&heredoc, ch);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004290 nommu_addchr(as_string, ch);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004291 }
4292}
4293
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004294/* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
4295 * and load them all. There should be exactly heredoc_cnt of them.
4296 */
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004297static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
4298{
4299 struct pipe *pi = ctx->list_head;
4300
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004301 while (pi && heredoc_cnt) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004302 int i;
4303 struct command *cmd = pi->cmds;
4304
4305 debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
4306 pi->num_cmds,
4307 cmd->argv ? cmd->argv[0] : "NONE");
4308 for (i = 0; i < pi->num_cmds; i++) {
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004309 struct redir_struct *redir = cmd->redirects;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004310
4311 debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
4312 i, cmd->argv ? cmd->argv[0] : "NONE");
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004313 while (redir) {
4314 if (redir->rd_type == REDIRECT_HEREDOC) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004315 char *p;
4316
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004317 redir->rd_type = REDIRECT_HEREDOC2;
4318 /* redir->dup is (ab)used to indicate <<- */
4319 p = fetch_till_str(&ctx->as_string, input,
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004320 redir->rd_filename, redir->rd_dup & HEREDOC_SKIPTABS);
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004321 if (!p) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004322 syntax_error("unexpected EOF in here document");
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004323 return 1;
4324 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004325 free(redir->rd_filename);
4326 redir->rd_filename = p;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004327 heredoc_cnt--;
4328 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004329 redir = redir->next;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004330 }
4331 cmd++;
4332 }
4333 pi = pi->next;
4334 }
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004335#if 0
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004336 /* Should be 0. If it isn't, it's a parse error */
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004337 if (heredoc_cnt)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004338 bb_error_msg_and_die("heredoc BUG 2");
4339#endif
4340 return 0;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004341}
4342
4343
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004344#if BB_MMU
4345#define parse_stream(pstring, input, end_trigger) \
4346 parse_stream(input, end_trigger)
4347#endif
4348static struct pipe *parse_stream(char **pstring,
4349 struct in_str *input,
4350 int end_trigger);
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00004351static void parse_and_run_string(const char *s);
Mike Frysingerddbee972009-03-22 22:48:41 +00004352
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00004353#if ENABLE_HUSH_TICK
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00004354static FILE *generate_stream_from_string(const char *s)
Eric Andersen25f27032001-04-26 23:22:31 +00004355{
4356 FILE *pf;
Eric Andersen25f27032001-04-26 23:22:31 +00004357 int pid, channel[2];
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00004358
Denis Vlasenko5a6aedd2007-05-26 16:44:20 +00004359 xpipe(channel);
Denis Vlasenko82604e92008-07-01 15:59:42 +00004360 pid = BB_MMU ? fork() : vfork();
4361 if (pid < 0)
4362 bb_perror_msg_and_die(BB_MMU ? "fork" : "vfork");
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00004363
Denis Vlasenko05743d72008-02-10 12:10:08 +00004364 if (pid == 0) { /* child */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004365 disable_restore_tty_pgrp_on_exit();
Denis Vlasenkoba7cf262007-05-25 14:34:30 +00004366 /* Process substitution is not considered to be usual
4367 * 'command execution'.
Denis Vlasenkoabedaac2009-03-31 12:03:40 +00004368 * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
4369 */
Denis Vlasenkoe0755e52009-04-03 21:16:45 +00004370 bb_signals(0
4371 + (1 << SIGTSTP)
4372 + (1 << SIGTTIN)
4373 + (1 << SIGTTOU)
4374 , SIG_IGN);
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00004375 close(channel[0]); /* NB: close _first_, then move fd! */
4376 xmove_fd(channel[1], 1);
4377 /* Prevent it from trying to handle ctrl-z etc */
4378 USE_HUSH_JOB(G.run_list_level = 1;)
4379#if BB_MMU
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00004380 reset_traps_to_defaults();
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00004381 parse_and_run_string(s);
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00004382 _exit(G.last_exitcode);
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00004383#else
4384 /* We re-execute after vfork on NOMMU. This makes this script safe:
Denis Vlasenkof9375282009-04-05 19:13:39 +00004385 * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
4386 * huge=`cat BIG` # was blocking here forever
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00004387 * echo OK
4388 */
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00004389 re_execute_shell(s, 0);
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00004390#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004391 }
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00004392
4393 /* parent */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004394 enable_restore_tty_pgrp_on_exit();
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00004395 clean_up_after_re_execute();
Eric Andersen25f27032001-04-26 23:22:31 +00004396 close(channel[1]);
Denis Vlasenko5f786c22007-04-20 08:35:45 +00004397 pf = fdopen(channel[0], "r");
Eric Andersen25f27032001-04-26 23:22:31 +00004398 return pf;
4399}
4400
Denis Vlasenko21f0d4c2007-05-06 14:15:42 +00004401/* Return code is exit status of the process that is run. */
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00004402static int process_command_subs(o_string *dest, const char *s)
Eric Andersen25f27032001-04-26 23:22:31 +00004403{
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00004404 FILE *pf;
Eric Andersen25f27032001-04-26 23:22:31 +00004405 struct in_str pipe_str;
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00004406 int ch, eol_cnt;
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00004407
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00004408 pf = generate_stream_from_string(s);
4409 if (pf == NULL)
Denis Vlasenko05743d72008-02-10 12:10:08 +00004410 return 1;
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00004411 close_on_exec_on(fileno(pf));
Eric Andersen25f27032001-04-26 23:22:31 +00004412
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004413 /* Now send results of command back into original context */
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00004414 setup_file_in_str(&pipe_str, pf);
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00004415 eol_cnt = 0;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004416 while ((ch = i_getch(&pipe_str)) != EOF) {
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00004417 if (ch == '\n') {
4418 eol_cnt++;
4419 continue;
4420 }
4421 while (eol_cnt) {
Denis Vlasenko55789c62008-06-18 16:30:42 +00004422 o_addchr(dest, '\n');
Denis Vlasenko3e9aaae2007-05-11 12:56:43 +00004423 eol_cnt--;
4424 }
Denis Vlasenko7e3d33b2008-06-12 13:31:04 +00004425 o_addQchr(dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00004426 }
4427
4428 debug_printf("done reading from pipe, pclose()ing\n");
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004429 /* Note: we got EOF, and we just close the read end of the pipe.
4430 * We do not wait for the `cmd` child to terminate. bash and ash do.
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00004431 * Try these:
4432 * echo `echo Hi; exec 1>&-; sleep 2` - bash waits 2 sec
4433 * `false`; echo $? - bash outputs "1"
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004434 */
Denis Vlasenkodb2a9b62009-04-03 22:31:18 +00004435 fclose(pf);
4436 debug_printf("closed FILE from child. return 0\n");
4437 return 0;
Eric Andersen25f27032001-04-26 23:22:31 +00004438}
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00004439#endif
Eric Andersen25f27032001-04-26 23:22:31 +00004440
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004441static int parse_group(o_string *dest, struct parse_context *ctx,
Eric Andersen25f27032001-04-26 23:22:31 +00004442 struct in_str *input, int ch)
4443{
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004444 /* dest contains characters seen prior to ( or {.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00004445 * Typically it's empty, but for function defs,
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004446 * it contains function name (without '()'). */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004447 struct pipe *pipe_list;
Denis Vlasenko240c2552009-04-03 03:45:05 +00004448 int endch;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004449 struct command *command = ctx->command;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004450
4451 debug_printf_parse("parse_group entered\n");
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004452#if ENABLE_HUSH_FUNCTIONS
4453 if (ch == 'F') { /* function definition? */
4454 bb_error_msg("aha '%s' is a function, parsing it...", dest->data);
4455 //command->fname = dest->data;
4456 command->grp_type = GRP_FUNCTION;
4457//TODO: review every o_reset() location... do they handle all o_string fields correctly?
4458 memset(dest, 0, sizeof(*dest));
4459 }
4460#endif
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004461 if (command->argv /* word [word](... */
4462 || dest->length /* word(... */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00004463 || dest->o_quoted /* ""(... */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004464 ) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004465 syntax_error(NULL);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004466 debug_printf_parse("parse_group return 1: "
4467 "syntax error, groups and arglists don't mix\n");
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004468 return 1;
Eric Andersen25f27032001-04-26 23:22:31 +00004469 }
Denis Vlasenko240c2552009-04-03 03:45:05 +00004470 endch = '}';
Denis Vlasenko90e485c2007-05-23 15:22:50 +00004471 if (ch == '(') {
Denis Vlasenko240c2552009-04-03 03:45:05 +00004472 endch = ')';
Denis Vlasenko371de4a2008-10-14 12:43:13 +00004473 command->grp_type = GRP_SUBSHELL;
Eric Andersen25f27032001-04-26 23:22:31 +00004474 }
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004475 {
4476#if !BB_MMU
4477 char *as_string = NULL;
4478#endif
4479 pipe_list = parse_stream(&as_string, input, endch);
4480#if !BB_MMU
4481 if (as_string)
4482 o_addstr(&ctx->as_string, as_string);
4483#endif
4484 /* empty ()/{} or parse error? */
4485 if (!pipe_list || pipe_list == ERR_PTR) {
4486#if !BB_MMU
4487 free(as_string);
4488#endif
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004489 syntax_error(NULL);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004490 debug_printf_parse("parse_group return 1: "
4491 "parse_stream returned %p\n", pipe_list);
4492 return 1;
4493 }
4494 command->group = pipe_list;
4495#if !BB_MMU
4496 as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
4497 command->group_as_string = as_string;
4498 debug_printf_parse("end of group, remembering as:'%s'\n",
4499 command->group_as_string);
4500#endif
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00004501 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004502 debug_printf_parse("parse_group return 0\n");
4503 return 0;
Denis Vlasenko9af22c72008-10-09 12:54:58 +00004504 /* command remains "open", available for possible redirects */
Eric Andersen25f27032001-04-26 23:22:31 +00004505}
4506
Mike Frysinger98c52642009-04-02 10:02:37 +00004507#if ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004508/* Subroutines for copying $(...) and `...` things */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004509static int add_till_backquote(o_string *dest, struct in_str *input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004510/* '...' */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004511static int add_till_single_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004512{
4513 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004514 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004515 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004516 syntax_error_unterm_ch('\'');
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004517 return 1;
4518 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004519 if (ch == '\'')
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004520 return 0;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004521 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004522 }
4523}
4524/* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004525static int add_till_double_quote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004526{
4527 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004528 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004529 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004530 syntax_error_unterm_ch('"');
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004531 return 1;
4532 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004533 if (ch == '"')
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004534 return 0;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004535 if (ch == '\\') { /* \x. Copy both chars. */
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004536 o_addchr(dest, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004537 ch = i_getch(input);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004538 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004539 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004540 if (ch == '`') {
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004541 if (add_till_backquote(dest, input))
4542 return 1;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004543 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004544 continue;
4545 }
Denis Vlasenko5703c222008-06-15 11:49:42 +00004546 //if (ch == '$') ...
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004547 }
4548}
4549/* Process `cmd` - copy contents until "`" is seen. Complicated by
4550 * \` quoting.
4551 * "Within the backquoted style of command substitution, backslash
4552 * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
4553 * The search for the matching backquote shall be satisfied by the first
4554 * backquote found without a preceding backslash; during this search,
4555 * if a non-escaped backquote is encountered within a shell comment,
4556 * a here-document, an embedded command substitution of the $(command)
4557 * form, or a quoted string, undefined results occur. A single-quoted
4558 * or double-quoted string that begins, but does not end, within the
4559 * "`...`" sequence produces undefined results."
4560 * Example Output
4561 * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
4562 */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004563static int add_till_backquote(o_string *dest, struct in_str *input)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004564{
4565 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004566 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004567 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004568 syntax_error_unterm_ch('`');
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004569 return 1;
4570 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004571 if (ch == '`')
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004572 return 0;
4573 if (ch == '\\') {
4574 /* \x. Copy both chars unless it is \` */
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004575 int ch2 = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004576 if (ch2 == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004577 syntax_error_unterm_ch('`');
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004578 return 1;
4579 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004580 if (ch2 != '`' && ch2 != '$' && ch2 != '\\')
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004581 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004582 ch = ch2;
4583 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004584 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004585 }
4586}
4587/* Process $(cmd) - copy contents until ")" is seen. Complicated by
4588 * quoting and nested ()s.
4589 * "With the $(command) style of command substitution, all characters
4590 * following the open parenthesis to the matching closing parenthesis
4591 * constitute the command. Any valid shell script can be used for command,
4592 * except a script consisting solely of redirections which produces
4593 * unspecified results."
4594 * Example Output
4595 * echo $(echo '(TEST)' BEST) (TEST) BEST
4596 * echo $(echo 'TEST)' BEST) TEST) BEST
4597 * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
4598 */
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004599static int add_till_closing_paren(o_string *dest, struct in_str *input, bool dbl)
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004600{
4601 int count = 0;
4602 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004603 int ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004604 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004605 syntax_error_unterm_ch(')');
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004606 return 1;
4607 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004608 if (ch == '(')
4609 count++;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004610 if (ch == ')') {
Mike Frysinger98c52642009-04-02 10:02:37 +00004611 if (--count < 0) {
4612 if (!dbl)
4613 break;
4614 if (i_peek(input) == ')') {
4615 i_getch(input);
4616 break;
4617 }
4618 }
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004619 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004620 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004621 if (ch == '\'') {
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004622 if (add_till_single_quote(dest, input))
4623 return 1;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004624 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004625 continue;
4626 }
4627 if (ch == '"') {
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004628 if (add_till_double_quote(dest, input))
4629 return 1;
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004630 o_addchr(dest, ch);
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004631 continue;
4632 }
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004633 if (ch == '\\') {
4634 /* \x. Copy verbatim. Important for \(, \) */
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00004635 ch = i_getch(input);
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004636 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004637 syntax_error_unterm_ch(')');
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004638 return 1;
4639 }
Denis Vlasenko82dfec32008-06-16 12:47:11 +00004640 o_addchr(dest, ch);
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00004641 continue;
4642 }
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004643 }
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004644 return 0;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004645}
Mike Frysinger98c52642009-04-02 10:02:37 +00004646#endif /* ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT */
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00004647
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00004648/* Return code: 0 for OK, 1 for syntax error */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004649#if BB_MMU
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00004650#define handle_dollar(as_string, dest, input) \
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004651 handle_dollar(dest, input)
4652#endif
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00004653static int handle_dollar(o_string *as_string,
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004654 o_string *dest,
4655 struct in_str *input)
Eric Andersen25f27032001-04-26 23:22:31 +00004656{
Mike Frysinger6379bb42009-03-28 18:55:03 +00004657 int expansion;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004658 int ch = i_peek(input); /* first character after the $ */
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00004659 unsigned char quote_mask = dest->o_escape ? 0x80 : 0;
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00004660
4661 debug_printf_parse("handle_dollar entered: ch='%c'\n", ch);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00004662 if (isalpha(ch)) {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004663 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004664 nommu_addchr(as_string, ch);
Denis Vlasenkod4981312008-07-31 10:34:48 +00004665 make_var:
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004666 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00004667 while (1) {
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00004668 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004669 o_addchr(dest, ch | quote_mask);
Denis Vlasenko1f4cf512007-05-16 10:39:24 +00004670 quote_mask = 0;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004671 ch = i_peek(input);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00004672 if (!isalnum(ch) && ch != '_')
4673 break;
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004674 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004675 nommu_addchr(as_string, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00004676 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004677 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00004678 } else if (isdigit(ch)) {
Denis Vlasenko602d13c2007-05-13 18:34:53 +00004679 make_one_char_var:
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004680 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004681 nommu_addchr(as_string, ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004682 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenko602d13c2007-05-13 18:34:53 +00004683 debug_printf_parse(": '%c'\n", ch);
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004684 o_addchr(dest, ch | quote_mask);
4685 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00004686 } else switch (ch) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004687 case '$': /* pid */
4688 case '!': /* last bg pid */
4689 case '?': /* last exit code */
4690 case '#': /* number of args */
4691 case '*': /* args */
4692 case '@': /* args */
4693 goto make_one_char_var;
4694 case '{': {
4695 bool first_char, all_digits;
Mike Frysinger6379bb42009-03-28 18:55:03 +00004696
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004697 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004698 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004699 nommu_addchr(as_string, ch);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004700 /* XXX maybe someone will try to escape the '}' */
4701 expansion = 0;
4702 first_char = true;
4703 all_digits = false;
4704 while (1) {
4705 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004706 nommu_addchr(as_string, ch);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004707 if (ch == '}')
Mike Frysinger98c52642009-04-02 10:02:37 +00004708 break;
Mike Frysinger98c52642009-04-02 10:02:37 +00004709
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004710 if (first_char) {
4711 if (ch == '#')
4712 /* ${#var}: length of var contents */
4713 goto char_ok;
4714 else if (isdigit(ch)) {
4715 all_digits = true;
4716 goto char_ok;
4717 }
4718 }
4719
4720 if (expansion < 2
4721 && ( (all_digits && !isdigit(ch))
4722 || (!all_digits && !isalnum(ch) && ch != '_')
4723 )
4724 ) {
4725 /* handle parameter expansions
4726 * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
4727 */
4728 if (first_char)
4729 goto case_default;
4730 switch (ch) {
4731 case ':': /* null modifier */
4732 if (expansion == 0) {
4733 debug_printf_parse(": null modifier\n");
4734 ++expansion;
4735 break;
4736 }
4737 goto case_default;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004738 case '#': /* remove prefix */
4739 case '%': /* remove suffix */
4740 if (expansion == 0) {
4741 debug_printf_parse(": remove suffix/prefix\n");
4742 expansion = 2;
4743 break;
4744 }
4745 goto case_default;
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004746 case '-': /* default value */
4747 case '=': /* assign default */
4748 case '+': /* alternative */
4749 case '?': /* error indicate */
4750 debug_printf_parse(": parameter expansion\n");
4751 expansion = 2;
4752 break;
4753 default:
4754 case_default:
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004755 syntax_error_unterm_str("${name}");
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004756 debug_printf_parse("handle_dollar return 1: unterminated ${name}\n");
4757 return 1;
4758 }
4759 }
4760 char_ok:
4761 debug_printf_parse(": '%c'\n", ch);
4762 o_addchr(dest, ch | quote_mask);
4763 quote_mask = 0;
4764 first_char = false;
4765 }
4766 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4767 break;
4768 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004769#if (ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_TICK)
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004770 case '(': {
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004771# if !BB_MMU
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00004772 int pos;
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004773# endif
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004774 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004775 nommu_addchr(as_string, ch);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004776# if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004777 if (i_peek(input) == '(') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004778 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004779 nommu_addchr(as_string, ch);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004780 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4781 o_addchr(dest, /*quote_mask |*/ '+');
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004782# if !BB_MMU
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00004783 pos = dest->length;
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004784# endif
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004785 if (add_till_closing_paren(dest, input, true))
4786 return 1;
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004787# if !BB_MMU
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00004788 if (as_string) {
4789 o_addstr(as_string, dest->data + pos);
4790 o_addchr(as_string, ')');
4791 o_addchr(as_string, ')');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00004792 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004793# endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004794 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Eric Andersen25f27032001-04-26 23:22:31 +00004795 break;
Denis Vlasenko76db5ad2008-06-12 12:58:20 +00004796 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004797# endif
4798# if ENABLE_HUSH_TICK
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004799 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4800 o_addchr(dest, quote_mask | '`');
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004801# if !BB_MMU
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00004802 pos = dest->length;
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004803# endif
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004804 if (add_till_closing_paren(dest, input, false))
4805 return 1;
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004806# if !BB_MMU
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00004807 if (as_string) {
4808 o_addstr(as_string, dest->data + pos);
4809 o_addchr(as_string, '`');
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00004810 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004811# endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004812 o_addchr(dest, SPECIAL_VAR_SYMBOL);
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004813# endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004814 break;
4815 }
Denis Vlasenkod85a5df2009-04-05 08:43:57 +00004816#endif
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004817 case '_':
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00004818 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004819 nommu_addchr(as_string, ch);
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004820 ch = i_peek(input);
4821 if (isalnum(ch)) { /* it's $_name or $_123 */
4822 ch = '_';
4823 goto make_var;
4824 }
4825 /* else: it's $_ */
4826 /* TODO: */
4827 /* $_ Shell or shell script name; or last cmd name */
4828 /* $- Option flags set by set builtin or shell options (-i etc) */
4829 default:
4830 o_addQchr(dest, '$');
Eric Andersen25f27032001-04-26 23:22:31 +00004831 }
Denis Vlasenkoe0a33672007-05-10 23:06:55 +00004832 debug_printf_parse("handle_dollar return 0\n");
Eric Andersen25f27032001-04-26 23:22:31 +00004833 return 0;
4834}
4835
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004836#if BB_MMU
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00004837#define parse_stream_dquoted(as_string, dest, input, dquote_end) \
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004838 parse_stream_dquoted(dest, input, dquote_end)
4839#endif
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00004840static int parse_stream_dquoted(o_string *as_string,
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004841 o_string *dest,
4842 struct in_str *input,
4843 int dquote_end)
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004844{
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004845 int ch;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004846 int next;
4847
4848 again:
4849 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00004850 if (ch != EOF)
4851 nommu_addchr(as_string, ch);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004852 if (ch == dquote_end) { /* may be only '"' or EOF */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004853 if (dest->o_assignment == NOT_ASSIGNMENT)
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00004854 dest->o_escape ^= 1;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004855 debug_printf_parse("parse_stream_dquoted return 0\n");
4856 return 0;
4857 }
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004858 /* note: can't move it above ch == dquote_end check! */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004859 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004860 syntax_error_unterm_ch('"');
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004861 debug_printf_parse("parse_stream_dquoted return 1: unterminated \"\n");
4862 return 1;
4863 }
4864 next = '\0';
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004865 if (ch != '\n') {
4866 next = i_peek(input);
4867 }
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00004868 debug_printf_parse(": ch=%c (%d) escape=%d\n",
4869 ch, ch, dest->o_escape);
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004870 if (ch == '\\') {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004871//TODO: check interactive behavior
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004872 if (next == EOF) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004873 syntax_error("\\<eof>");
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004874 debug_printf_parse("parse_stream_dquoted return 1: \\<eof>\n");
4875 return 1;
4876 }
4877 /* bash:
4878 * "The backslash retains its special meaning [in "..."]
4879 * only when followed by one of the following characters:
4880 * $, `, ", \, or <newline>. A double quote may be quoted
4881 * within double quotes by preceding it with a backslash.
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004882 */
4883 if (strchr("$`\"\\", next) != NULL) {
4884 o_addqchr(dest, i_getch(input));
4885 } else {
4886 o_addqchr(dest, '\\');
4887 }
4888 goto again;
4889 }
4890 if (ch == '$') {
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00004891 if (handle_dollar(as_string, dest, input) != 0) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004892 debug_printf_parse("parse_stream_dquoted return 1: "
4893 "handle_dollar returned non-0\n");
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004894 return 1;
4895 }
4896 goto again;
4897 }
4898#if ENABLE_HUSH_TICK
4899 if (ch == '`') {
4900 //int pos = dest->length;
4901 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4902 o_addchr(dest, 0x80 | '`');
Denis Vlasenko5c090a92009-04-08 21:51:33 +00004903 if (add_till_backquote(dest, input))
4904 return 1;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004905 o_addchr(dest, SPECIAL_VAR_SYMBOL);
4906 //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
Denis Vlasenkof328e002009-04-02 16:55:38 +00004907 goto again;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004908 }
4909#endif
Denis Vlasenkof328e002009-04-02 16:55:38 +00004910 o_addQchr(dest, ch);
4911 if (ch == '='
4912 && (dest->o_assignment == MAYBE_ASSIGNMENT
4913 || dest->o_assignment == WORD_IS_KEYWORD)
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00004914 && is_well_formed_var_name(dest->data, '=')
Denis Vlasenkof328e002009-04-02 16:55:38 +00004915 ) {
4916 dest->o_assignment = DEFINITELY_ASSIGNMENT;
4917 }
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004918 goto again;
4919}
4920
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004921/*
4922 * Scan input until EOF or end_trigger char.
4923 * Return a list of pipes to execute, or NULL on EOF
4924 * or if end_trigger character is met.
4925 * On syntax error, exit is shell is not interactive,
4926 * reset parsing machinery and start parsing anew,
4927 * or return ERR_PTR.
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00004928 */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004929static struct pipe *parse_stream(char **pstring,
4930 struct in_str *input,
4931 int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00004932{
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004933 struct parse_context ctx;
4934 o_string dest = NULL_O_STRING;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004935 int is_in_dquote;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004936 int heredoc_cnt;
Eric Andersen25f27032001-04-26 23:22:31 +00004937
Denis Vlasenkob7aaae92009-04-02 20:17:49 +00004938 /* Double-quote state is handled in the state variable is_in_dquote.
Eric Andersen25f27032001-04-26 23:22:31 +00004939 * A single-quote triggers a bypass of the main loop until its mate is
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00004940 * found. When recursing, quote state is passed in via dest->o_escape.
4941 */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004942 debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
4943 end_trigger ? : 'X');
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00004944
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004945 G.ifs = get_local_var_value("IFS");
4946 if (G.ifs == NULL)
4947 G.ifs = " \t\n";
4948
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004949 reset:
4950#if ENABLE_HUSH_INTERACTIVE
4951 input->promptmode = 0; /* PS1 */
4952#endif
4953 /* dest.o_assignment = MAYBE_ASSIGNMENT; - already is */
4954 initialize_context(&ctx);
4955 is_in_dquote = 0;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004956 heredoc_cnt = 0;
Denis Vlasenko1a735862007-05-23 00:32:25 +00004957 while (1) {
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004958 const char *is_ifs;
4959 const char *is_special;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004960 int ch;
4961 int next;
4962 int redir_fd;
4963 redir_type redir_style;
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004964
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004965 if (is_in_dquote) {
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00004966 /* dest.o_quoted = 1; - already is (see below) */
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00004967 if (parse_stream_dquoted(&ctx.as_string, &dest, input, '"')) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00004968 goto parse_error;
4969 }
4970 /* We reached closing '"' */
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00004971 is_in_dquote = 0;
4972 }
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00004973 ch = i_getch(input);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004974 debug_printf_parse(": ch=%c (%d) escape=%d\n",
4975 ch, ch, dest.o_escape);
4976 if (ch == EOF) {
4977 struct pipe *pi;
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004978
4979 if (heredoc_cnt) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00004980 syntax_error_unterm_str("here document");
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00004981 goto parse_error;
4982 }
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004983 if (done_word(&dest, &ctx)) {
4984 goto parse_error;
Denis Vlasenko55789c62008-06-18 16:30:42 +00004985 }
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004986 o_free(&dest);
4987 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004988 pi = ctx.list_head;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004989 /* If we got nothing... */
4990// TODO: test script consisting of just "&"
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00004991 if (pi->num_cmds == 0
4992 IF_HAS_KEYWORDS( && pi->res_word == RES_NONE)
4993 ) {
4994 free_pipe_list(pi, 0);
4995 pi = NULL;
4996 }
4997 debug_printf_parse("parse_stream return %p\n", pi);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00004998#if !BB_MMU
4999 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
5000 if (pstring)
5001 *pstring = ctx.as_string.data;
5002 else
5003 o_free_unsafe(&ctx.as_string);
5004#endif
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005005 return pi;
Denis Vlasenko1a735862007-05-23 00:32:25 +00005006 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005007 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005008 is_ifs = strchr(G.ifs, ch);
5009 is_special = strchr("<>;&|(){}#'" /* special outside of "str" */
5010 "\\$\"" USE_HUSH_TICK("`") /* always special */
5011 , ch);
5012
5013 if (!is_special && !is_ifs) { /* ordinary char */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005014 o_addQchr(&dest, ch);
5015 if ((dest.o_assignment == MAYBE_ASSIGNMENT
5016 || dest.o_assignment == WORD_IS_KEYWORD)
Denis Vlasenko55789c62008-06-18 16:30:42 +00005017 && ch == '='
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005018 && is_well_formed_var_name(dest.data, '=')
Denis Vlasenko55789c62008-06-18 16:30:42 +00005019 ) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005020 dest.o_assignment = DEFINITELY_ASSIGNMENT;
Denis Vlasenko55789c62008-06-18 16:30:42 +00005021 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005022 continue;
5023 }
Denis Vlasenko240c2552009-04-03 03:45:05 +00005024
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005025 if (is_ifs) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005026 if (done_word(&dest, &ctx)) {
5027 goto parse_error;
Eric Andersenaac75e52001-04-30 18:18:45 +00005028 }
Denis Vlasenko37181682009-04-03 03:19:15 +00005029 if (ch == '\n') {
Denis Vlasenkof1736072008-07-31 10:09:26 +00005030#if ENABLE_HUSH_CASE
5031 /* "case ... in <newline> word) ..." -
5032 * newlines are ignored (but ';' wouldn't be) */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005033 if (ctx.command->argv == NULL
5034 && ctx.ctx_res_w == RES_MATCH
Denis Vlasenkof1736072008-07-31 10:09:26 +00005035 ) {
5036 continue;
5037 }
5038#endif
Denis Vlasenko240c2552009-04-03 03:45:05 +00005039 /* Treat newline as a command separator. */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005040 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005041 debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
5042 if (heredoc_cnt) {
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005043 if (fetch_heredocs(heredoc_cnt, &ctx, input)) {
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005044 goto parse_error;
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005045 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005046 heredoc_cnt = 0;
5047 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005048 dest.o_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenko240c2552009-04-03 03:45:05 +00005049 ch = ';';
Denis Vlasenko7c986122009-04-04 12:15:42 +00005050 /* note: if (is_ifs) continue;
Denis Vlasenko240c2552009-04-03 03:45:05 +00005051 * will still trigger for us */
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005052 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005053 }
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005054 if (end_trigger && end_trigger == ch
5055 && (heredoc_cnt == 0 || end_trigger != ';')
5056 ) {
Denis Vlasenko240c2552009-04-03 03:45:05 +00005057//TODO: disallow "{ cmd }" without semicolon
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005058 if (heredoc_cnt) {
5059 /* This is technically valid:
5060 * { cat <<HERE; }; echo Ok
5061 * heredoc
5062 * heredoc
5063 * heredoc
5064 * HERE
5065 * but we don't support this.
5066 * We require heredoc to be in enclosing {}/(),
5067 * if any.
5068 */
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005069 syntax_error_unterm_str("here document");
Denis Vlasenko6c9be7f2009-04-07 02:29:51 +00005070 goto parse_error;
5071 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005072 if (done_word(&dest, &ctx)) {
5073 goto parse_error;
5074 }
5075 done_pipe(&ctx, PIPE_SEQ);
5076 dest.o_assignment = MAYBE_ASSIGNMENT;
Denis Vlasenko240c2552009-04-03 03:45:05 +00005077 /* Do we sit outside of any if's, loops or case's? */
Denis Vlasenko37181682009-04-03 03:19:15 +00005078 if (!HAS_KEYWORDS
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005079 IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
Denis Vlasenko37181682009-04-03 03:19:15 +00005080 ) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005081 debug_printf_parse("parse_stream return %p: "
5082 "end_trigger char found\n",
5083 ctx.list_head);
5084 o_free(&dest);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005085#if !BB_MMU
5086 debug_printf_parse("as_string '%s'\n", ctx.as_string.data);
5087 if (pstring)
5088 *pstring = ctx.as_string.data;
5089 else
5090 o_free_unsafe(&ctx.as_string);
5091#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005092 return ctx.list_head;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005093 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005094 }
Denis Vlasenko6da69cd2009-04-04 12:12:58 +00005095 if (is_ifs)
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005096 continue;
Denis Vlasenko55789c62008-06-18 16:30:42 +00005097
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005098 next = '\0';
5099 if (ch != '\n') {
5100 next = i_peek(input);
5101 }
5102
Denis Vlasenkoc96865f2009-04-10 00:20:58 +00005103 /* Catch <, > before deciding whether this word is
5104 * an assignment. a=1 2>z b=2: b=2 is still assignment */
5105 switch (ch) {
5106 case '>':
5107 redir_fd = redirect_opt_num(&dest);
5108 if (done_word(&dest, &ctx)) {
5109 goto parse_error;
5110 }
5111 redir_style = REDIRECT_OVERWRITE;
5112 if (next == '>') {
5113 redir_style = REDIRECT_APPEND;
5114 ch = i_getch(input);
5115 nommu_addchr(&ctx.as_string, ch);
5116 }
5117#if 0
5118 else if (next == '(') {
5119 syntax_error(">(process) not supported");
5120 goto parse_error;
5121 }
5122#endif
5123 if (parse_redirect(&ctx, redir_fd, redir_style, input))
5124 goto parse_error;
5125 continue; /* back to top of while (1) */
5126 case '<':
5127 redir_fd = redirect_opt_num(&dest);
5128 if (done_word(&dest, &ctx)) {
5129 goto parse_error;
5130 }
5131 redir_style = REDIRECT_INPUT;
5132 if (next == '<') {
5133 redir_style = REDIRECT_HEREDOC;
5134 heredoc_cnt++;
5135 debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
5136 ch = i_getch(input);
5137 nommu_addchr(&ctx.as_string, ch);
5138 } else if (next == '>') {
5139 redir_style = REDIRECT_IO;
5140 ch = i_getch(input);
5141 nommu_addchr(&ctx.as_string, ch);
5142 }
5143#if 0
5144 else if (next == '(') {
5145 syntax_error("<(process) not supported");
5146 goto parse_error;
5147 }
5148#endif
5149 if (parse_redirect(&ctx, redir_fd, redir_style, input))
5150 goto parse_error;
5151 continue; /* back to top of while (1) */
5152 }
5153
5154 if (dest.o_assignment == MAYBE_ASSIGNMENT
5155 /* check that we are not in word in "a=1 2>word b=1": */
5156 && !ctx.pending_redirect
5157 ) {
5158 /* ch is a special char and thus this word
5159 * cannot be an assignment */
5160 dest.o_assignment = NOT_ASSIGNMENT;
5161 }
5162
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005163 switch (ch) {
Eric Andersen25f27032001-04-26 23:22:31 +00005164 case '#':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005165 if (dest.length == 0) {
Denis Vlasenko0c886c62007-01-30 22:30:09 +00005166 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005167 ch = i_peek(input);
Denis Vlasenko0c886c62007-01-30 22:30:09 +00005168 if (ch == EOF || ch == '\n')
5169 break;
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005170 i_getch(input);
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005171 /* note: we do not add it to &ctx.as_string */
Denis Vlasenko0c886c62007-01-30 22:30:09 +00005172 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005173 nommu_addchr(&ctx.as_string, '\n');
Eric Andersen25f27032001-04-26 23:22:31 +00005174 } else {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005175 o_addQchr(&dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00005176 }
5177 break;
5178 case '\\':
5179 if (next == EOF) {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005180 syntax_error("\\<eof>");
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005181 goto parse_error;
Eric Andersen25f27032001-04-26 23:22:31 +00005182 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005183 o_addchr(&dest, '\\');
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005184 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005185 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenko3dfb0352009-04-08 09:29:14 +00005186 o_addchr(&dest, ch);
5187 /* Example: echo Hello \2>file
5188 * we need to know that word 2 is quoted */
5189 dest.o_quoted = 1;
Eric Andersen25f27032001-04-26 23:22:31 +00005190 break;
5191 case '$':
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00005192 if (handle_dollar(&ctx.as_string, &dest, input) != 0) {
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005193 debug_printf_parse("parse_stream parse error: "
5194 "handle_dollar returned non-0\n");
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005195 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005196 }
Eric Andersen25f27032001-04-26 23:22:31 +00005197 break;
5198 case '\'':
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00005199 dest.o_quoted = 1;
Denis Vlasenko0c886c62007-01-30 22:30:09 +00005200 while (1) {
Denis Vlasenko46ccdcb2008-06-10 18:05:12 +00005201 ch = i_getch(input);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005202 if (ch == EOF) {
Denis Vlasenkod68ae082009-04-09 20:41:34 +00005203 syntax_error_unterm_ch('\'');
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005204 goto parse_error;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005205 }
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005206 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005207 if (ch == '\'')
Denis Vlasenko0c886c62007-01-30 22:30:09 +00005208 break;
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005209 if (dest.o_assignment == NOT_ASSIGNMENT)
5210 o_addqchr(&dest, ch);
Denis Vlasenko55789c62008-06-18 16:30:42 +00005211 else
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005212 o_addchr(&dest, ch);
Eric Andersen25f27032001-04-26 23:22:31 +00005213 }
Eric Andersen25f27032001-04-26 23:22:31 +00005214 break;
5215 case '"':
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00005216 dest.o_quoted = 1;
Denis Vlasenko2f1d3942009-04-02 16:31:29 +00005217 is_in_dquote ^= 1; /* invert */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005218 if (dest.o_assignment == NOT_ASSIGNMENT)
5219 dest.o_escape ^= 1;
Eric Andersen25f27032001-04-26 23:22:31 +00005220 break;
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00005221#if ENABLE_HUSH_TICK
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005222 case '`': {
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005223#if !BB_MMU
5224 int pos;
5225#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005226 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5227 o_addchr(&dest, '`');
Denis Vlasenko5c090a92009-04-08 21:51:33 +00005228#if !BB_MMU
5229 pos = dest.length;
5230#endif
5231 if (add_till_backquote(&dest, input))
5232 goto parse_error;
5233#if !BB_MMU
5234 o_addstr(&ctx.as_string, dest.data + pos);
5235 o_addchr(&ctx.as_string, '`');
5236#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005237 o_addchr(&dest, SPECIAL_VAR_SYMBOL);
5238 //debug_printf_subst("SUBST RES3 '%s'\n", dest.data + pos);
Eric Andersen25f27032001-04-26 23:22:31 +00005239 break;
Denis Vlasenko7b4f3f12008-06-10 18:04:32 +00005240 }
Denis Vlasenko14b5dd92007-05-20 21:51:38 +00005241#endif
Eric Andersen25f27032001-04-26 23:22:31 +00005242 case ';':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005243#if ENABLE_HUSH_CASE
5244 case_semi:
5245#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005246 if (done_word(&dest, &ctx)) {
5247 goto parse_error;
5248 }
5249 done_pipe(&ctx, PIPE_SEQ);
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005250#if ENABLE_HUSH_CASE
5251 /* Eat multiple semicolons, detect
5252 * whether it means something special */
5253 while (1) {
5254 ch = i_peek(input);
5255 if (ch != ';')
5256 break;
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005257 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005258 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005259 if (ctx.ctx_res_w == RES_CASEI) {
5260 ctx.ctx_dsemicolon = 1;
5261 ctx.ctx_res_w = RES_MATCH;
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005262 break;
5263 }
5264 }
5265#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005266 new_cmd:
5267 /* We just finished a cmd. New one may start
5268 * with an assignment */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005269 dest.o_assignment = MAYBE_ASSIGNMENT;
Eric Andersen25f27032001-04-26 23:22:31 +00005270 break;
5271 case '&':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005272 if (done_word(&dest, &ctx)) {
5273 goto parse_error;
5274 }
Denis Vlasenkobb81c582007-01-30 22:32:09 +00005275 if (next == '&') {
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005276 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005277 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005278 done_pipe(&ctx, PIPE_AND);
Eric Andersen25f27032001-04-26 23:22:31 +00005279 } else {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005280 done_pipe(&ctx, PIPE_BG);
Eric Andersen25f27032001-04-26 23:22:31 +00005281 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005282 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00005283 case '|':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005284 if (done_word(&dest, &ctx)) {
5285 goto parse_error;
5286 }
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00005287#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005288 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenkof1736072008-07-31 10:09:26 +00005289 break; /* we are in case's "word | word)" */
Denis Vlasenkofbeeb322008-07-31 00:17:01 +00005290#endif
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005291 if (next == '|') { /* || */
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005292 ch = i_getch(input);
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005293 nommu_addchr(&ctx.as_string, ch);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005294 done_pipe(&ctx, PIPE_OR);
Eric Andersen25f27032001-04-26 23:22:31 +00005295 } else {
5296 /* we could pick up a file descriptor choice here
5297 * with redirect_opt_num(), but bash doesn't do it.
5298 * "echo foo 2| cat" yields "foo 2". */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005299 done_command(&ctx);
Eric Andersen25f27032001-04-26 23:22:31 +00005300 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005301 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00005302 case '(':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005303#if ENABLE_HUSH_CASE
Denis Vlasenkof1736072008-07-31 10:09:26 +00005304 /* "case... in [(]word)..." - skip '(' */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005305 if (ctx.ctx_res_w == RES_MATCH
5306 && ctx.command->argv == NULL /* not (word|(... */
5307 && dest.length == 0 /* not word(... */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00005308 && dest.o_quoted == 0 /* not ""(... */
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005309 ) {
5310 continue;
5311 }
5312#endif
Denis Vlasenko371de4a2008-10-14 12:43:13 +00005313#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005314 if (dest.length != 0 /* not just () but word() */
Denis Vlasenko02d6f1a2009-04-07 19:56:55 +00005315 && dest.o_quoted == 0 /* not a"b"c() */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005316 && ctx.command->argv == NULL /* it's the first word */
Denis Vlasenko371de4a2008-10-14 12:43:13 +00005317//TODO: "func ( ) {...}" - note spaces - is valid format too in bash
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005318 && i_peek(input) == ')'
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005319 && !match_reserved_word(&dest)
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005320 ) {
5321 bb_error_msg("seems like a function definition");
Denis Vlasenko22d10a02008-10-13 08:53:43 +00005322 i_getch(input);
Denis Vlasenko609f2ab2009-04-04 23:15:14 +00005323//if !BB_MMU o_addchr(&ctx.as_string...
Denis Vlasenko22d10a02008-10-13 08:53:43 +00005324 do {
Denis Vlasenko371de4a2008-10-14 12:43:13 +00005325//TODO: do it properly.
Denis Vlasenko22d10a02008-10-13 08:53:43 +00005326 ch = i_getch(input);
5327 } while (ch == ' ' || ch == '\n');
5328 if (ch != '{') {
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005329 syntax_error("was expecting {");
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005330 goto parse_error;
Denis Vlasenko22d10a02008-10-13 08:53:43 +00005331 }
Denis Vlasenko371de4a2008-10-14 12:43:13 +00005332 ch = 'F'; /* magic value */
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005333 }
5334#endif
Eric Andersen25f27032001-04-26 23:22:31 +00005335 case '{':
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005336 if (parse_group(&dest, &ctx, input, ch) != 0) {
5337 goto parse_error;
Denis Vlasenkoe725bfe2007-05-03 22:45:39 +00005338 }
Denis Vlasenko2b576b82008-08-04 00:46:07 +00005339 goto new_cmd;
Eric Andersen25f27032001-04-26 23:22:31 +00005340 case ')':
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005341#if ENABLE_HUSH_CASE
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005342 if (ctx.ctx_res_w == RES_MATCH)
Denis Vlasenko17f02e72008-07-14 04:32:29 +00005343 goto case_semi;
5344#endif
Eric Andersen25f27032001-04-26 23:22:31 +00005345 case '}':
Denis Vlasenkoc3735272008-10-09 12:58:26 +00005346 /* proper use of this character is caught by end_trigger:
5347 * if we see {, we call parse_group(..., end_trigger='}')
5348 * and it will match } earlier (not here). */
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00005349 syntax_error("unexpected } or )");
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005350 goto parse_error;
Eric Andersen25f27032001-04-26 23:22:31 +00005351 default:
Denis Vlasenko5ec61322008-06-24 00:50:07 +00005352 if (HUSH_DEBUG)
Denis Vlasenko90e485c2007-05-23 15:22:50 +00005353 bb_error_msg_and_die("BUG: unexpected %c\n", ch);
Eric Andersen25f27032001-04-26 23:22:31 +00005354 }
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005355 } /* while (1) */
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00005356
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005357 parse_error:
5358 {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005359 struct parse_context *pctx;
5360 IF_HAS_KEYWORDS(struct parse_context *p2;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005361
5362 /* Clean up allocated tree.
5363 * Samples for finding leaks on syntax error recovery path.
Denis Vlasenkoa24c8ca2009-04-04 15:24:40 +00005364 * Run them from interactive shell, watch pmap `pidof hush`.
5365 * while if false; then false; fi do break; done
5366 * (bash accepts it)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005367 * while if false; then false; fi; do break; fi
Denis Vlasenkocc4c6932009-04-05 07:38:48 +00005368 * Samples to catch leaks at execution:
5369 * while if (true | {true;}); then echo ok; fi; do break; done
5370 * while if (true | {true;}); then echo ok; fi; do (if echo ok; break; then :; fi) | cat; break; done
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005371 */
5372 pctx = &ctx;
5373 do {
5374 /* Update pipe/command counts,
5375 * otherwise freeing may miss some */
5376 done_pipe(pctx, PIPE_SEQ);
5377 debug_printf_clean("freeing list %p from ctx %p\n",
5378 pctx->list_head, pctx);
5379 debug_print_tree(pctx->list_head, 0);
5380 free_pipe_list(pctx->list_head, 0);
5381 debug_printf_clean("freed list %p\n", pctx->list_head);
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005382#if !BB_MMU
5383 o_free_unsafe(&pctx->as_string);
5384#endif
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005385 IF_HAS_KEYWORDS(p2 = pctx->stack;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005386 if (pctx != &ctx) {
5387 free(pctx);
5388 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005389 IF_HAS_KEYWORDS(pctx = p2;)
5390 } while (HAS_KEYWORDS && pctx);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005391 /* Free text, clear all dest fields */
5392 o_free(&dest);
5393 /* If we are not in top-level parse, we return,
5394 * our caller will propagate error.
5395 */
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005396 if (end_trigger != ';') {
5397#if !BB_MMU
5398 if (pstring)
5399 *pstring = NULL;
5400#endif
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005401 return ERR_PTR;
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005402 }
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005403 /* Discard cached input, force prompt */
5404 input->p = NULL;
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005405 USE_HUSH_INTERACTIVE(input->promptme = 1;)
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005406 goto reset;
Denis Vlasenko027e3fd2009-04-02 22:50:40 +00005407 }
Eric Andersen25f27032001-04-26 23:22:31 +00005408}
5409
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005410/* Executing from string: eval, sh -c '...'
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005411 * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
5412 * end_trigger controls how often we stop parsing
5413 * NUL: parse all, execute, return
5414 * ';': parse till ';' or newline, execute, repeat till EOF
5415 */
5416static void parse_and_run_stream(struct in_str *inp, int end_trigger)
Eric Andersen25f27032001-04-26 23:22:31 +00005417{
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005418 while (1) {
5419 struct pipe *pipe_list;
Denis Vlasenkof8d01d32008-06-14 17:13:20 +00005420
Denis Vlasenko9aa7d6f2009-04-04 22:47:50 +00005421 pipe_list = parse_stream(NULL, inp, end_trigger);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005422 if (!pipe_list) /* EOF */
5423 break;
5424 debug_print_tree(pipe_list, 0);
5425 debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
5426 run_and_free_list(pipe_list);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005427 }
Eric Andersen25f27032001-04-26 23:22:31 +00005428}
5429
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005430static void parse_and_run_string(const char *s)
Eric Andersen25f27032001-04-26 23:22:31 +00005431{
5432 struct in_str input;
5433 setup_string_in_str(&input, s);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005434 parse_and_run_stream(&input, '\0');
Eric Andersen25f27032001-04-26 23:22:31 +00005435}
5436
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005437static void parse_and_run_file(FILE *f)
Eric Andersen25f27032001-04-26 23:22:31 +00005438{
Eric Andersen25f27032001-04-26 23:22:31 +00005439 struct in_str input;
5440 setup_file_in_str(&input, f);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005441 parse_and_run_stream(&input, ';');
Eric Andersen25f27032001-04-26 23:22:31 +00005442}
5443
Denis Vlasenkof9375282009-04-05 19:13:39 +00005444/* Called a few times only (or even once if "sh -c") */
5445static void block_signals(int second_time)
Eric Andersen52a97ca2001-06-22 06:49:26 +00005446{
Denis Vlasenkof9375282009-04-05 19:13:39 +00005447 unsigned sig;
5448 unsigned mask;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00005449
Denis Vlasenkof9375282009-04-05 19:13:39 +00005450 mask = (1 << SIGQUIT);
5451 if (G_interactive_fd) {
5452 mask = 0
5453 | (1 << SIGQUIT)
5454 | (1 << SIGTERM)
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00005455//TODO | (1 << SIGHUP)
Denis Vlasenkof9375282009-04-05 19:13:39 +00005456#if ENABLE_HUSH_JOB
5457 | (1 << SIGTTIN) | (1 << SIGTTOU) | (1 << SIGTSTP)
5458#endif
5459 | (1 << SIGINT)
5460 ;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00005461 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00005462 G.non_DFL_mask = mask;
Eric Andersen52a97ca2001-06-22 06:49:26 +00005463
Denis Vlasenkof9375282009-04-05 19:13:39 +00005464 if (!second_time)
5465 sigprocmask(SIG_SETMASK, NULL, &G.blocked_set);
5466 sig = 0;
5467 while (mask) {
5468 if (mask & 1)
5469 sigaddset(&G.blocked_set, sig);
5470 mask >>= 1;
5471 sig++;
5472 }
5473 sigdelset(&G.blocked_set, SIGCHLD);
5474
5475 sigprocmask(SIG_SETMASK, &G.blocked_set,
5476 second_time ? NULL : &G.inherited_set);
5477 /* POSIX allows shell to re-enable SIGCHLD
5478 * even if it was SIG_IGN on entry */
5479// G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
5480 if (!second_time)
5481 signal(SIGCHLD, SIG_DFL); // SIGCHLD_handler);
5482}
5483
5484#if ENABLE_HUSH_JOB
5485/* helper */
5486static void maybe_set_to_sigexit(int sig)
5487{
5488 void (*handler)(int);
5489 /* non_DFL_mask'ed signals are, well, masked,
5490 * no need to set handler for them.
5491 */
5492 if (!((G.non_DFL_mask >> sig) & 1)) {
5493 handler = signal(sig, sigexit);
5494 if (handler == SIG_IGN) /* oops... restore back to IGN! */
5495 signal(sig, handler);
5496 }
5497}
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00005498/* Set handlers to restore tty pgrp and exit */
Denis Vlasenkof9375282009-04-05 19:13:39 +00005499static void set_fatal_handlers(void)
5500{
Denis Vlasenkoa6c467f2007-05-05 15:10:52 +00005501 /* We _must_ restore tty pgrp on fatal signals */
Denis Vlasenkof9375282009-04-05 19:13:39 +00005502 if (HUSH_DEBUG) {
5503 maybe_set_to_sigexit(SIGILL );
5504 maybe_set_to_sigexit(SIGFPE );
5505 maybe_set_to_sigexit(SIGBUS );
5506 maybe_set_to_sigexit(SIGSEGV);
5507 maybe_set_to_sigexit(SIGTRAP);
5508 } /* else: hush is perfect. what SEGV? */
5509 maybe_set_to_sigexit(SIGABRT);
5510 /* bash 3.2 seems to handle these just like 'fatal' ones */
5511 maybe_set_to_sigexit(SIGPIPE);
5512 maybe_set_to_sigexit(SIGALRM);
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00005513//TODO: disable and move down when proper SIGHUP handling is added
Denis Vlasenkof9375282009-04-05 19:13:39 +00005514 maybe_set_to_sigexit(SIGHUP );
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00005515 /* if we are interactive, [SIGHUP,] SIGTERM and SIGINT are masked.
Denis Vlasenkof9375282009-04-05 19:13:39 +00005516 * if we aren't interactive... but in this case
5517 * we never want to restore pgrp on exit, and this fn is not called */
5518 /*maybe_set_to_sigexit(SIGTERM);*/
5519 /*maybe_set_to_sigexit(SIGINT );*/
Eric Andersen6c947d22001-06-25 22:24:38 +00005520}
Denis Vlasenkob81b3df2007-04-28 16:48:04 +00005521#endif
Eric Andersenada18ff2001-05-21 16:18:22 +00005522
Denis Vlasenkod5762932009-03-31 11:22:57 +00005523static int set_mode(const char cstate, const char mode)
5524{
5525 int state = (cstate == '-' ? 1 : 0);
5526 switch (mode) {
5527 case 'n': G.fake_mode = state; break;
5528 case 'x': /*G.debug_mode = state;*/ break;
5529 default: return EXIT_FAILURE;
5530 }
5531 return EXIT_SUCCESS;
5532}
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00005533
Denis Vlasenko9b49a5e2007-10-11 10:05:36 +00005534int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Matt Kraai2d91deb2001-08-01 17:21:35 +00005535int hush_main(int argc, char **argv)
Eric Andersen25f27032001-04-26 23:22:31 +00005536{
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00005537 static const struct variable const_shell_ver = {
5538 .next = NULL,
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00005539 .varstr = (char*)hush_version_str,
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00005540 .max_len = 1, /* 0 can provoke free(name) */
5541 .flg_export = 1,
5542 .flg_read_only = 1,
5543 };
Denis Vlasenkof9375282009-04-05 19:13:39 +00005544 int signal_mask_is_inited = 0;
Eric Andersen25f27032001-04-26 23:22:31 +00005545 int opt;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00005546 char **e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00005547 struct variable *cur_var;
Eric Andersenbc604a22001-05-16 05:24:03 +00005548
Denis Vlasenko574f2f42008-02-27 18:41:59 +00005549 INIT_G();
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00005550 if (EXIT_SUCCESS) /* if EXIT_SUCCESS == 0, is already done */
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00005551 G.last_exitcode = EXIT_SUCCESS;
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00005552#if !BB_MMU
5553 G.argv0_for_re_execing = argv[0];
5554#endif
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00005555 /* Deal with HUSH_VERSION */
Denis Vlasenko87a86552008-07-29 19:43:10 +00005556 G.shell_ver = const_shell_ver; /* copying struct here */
5557 G.top_var = &G.shell_ver;
Denis Vlasenkof886fd22008-10-13 12:36:05 +00005558 debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00005559 unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
5560 /* Initialize our shell local variables with the values
Denis Vlasenkod76c0492007-05-25 02:16:25 +00005561 * currently living in the environment */
Denis Vlasenko87a86552008-07-29 19:43:10 +00005562 cur_var = G.top_var;
Denis Vlasenko0a83fc32007-05-25 11:12:32 +00005563 e = environ;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00005564 if (e) while (*e) {
5565 char *value = strchr(*e, '=');
5566 if (value) { /* paranoia */
5567 cur_var->next = xzalloc(sizeof(*cur_var));
5568 cur_var = cur_var->next;
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00005569 cur_var->varstr = *e;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00005570 cur_var->max_len = strlen(*e);
5571 cur_var->flg_export = 1;
5572 }
5573 e++;
5574 }
Denis Vlasenkof886fd22008-10-13 12:36:05 +00005575 debug_printf_env("putenv '%s'\n", hush_version_str);
Denis Vlasenkoafd7a8d2008-10-09 16:29:44 +00005576 putenv((char *)hush_version_str); /* reinstate HUSH_VERSION */
Denis Vlasenko38f63192007-01-22 09:03:07 +00005577#if ENABLE_FEATURE_EDITING
Denis Vlasenko87a86552008-07-29 19:43:10 +00005578 G.line_input_state = new_line_input_t(FOR_SHELL);
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00005579#endif
Denis Vlasenko87a86552008-07-29 19:43:10 +00005580 G.global_argc = argc;
5581 G.global_argv = argv;
Eric Andersen94ac2442001-05-22 19:05:18 +00005582 /* Initialize some more globals to non-zero values */
5583 set_cwd();
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00005584#if ENABLE_HUSH_INTERACTIVE
Mike Frysingerec2c6552009-03-28 12:24:44 +00005585 if (ENABLE_FEATURE_EDITING)
5586 cmdedit_set_initial_prompt();
Denis Vlasenko87a86552008-07-29 19:43:10 +00005587 G.PS2 = "> ";
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00005588#endif
Denis Vlasenkoc8be5ee2007-05-17 15:38:46 +00005589
Denis Vlasenkoed782372009-04-10 00:45:02 +00005590 if (setjmp(die_jmp)) {
5591 /* xfunc has failed! die die die */
5592 /* no EXIT traps, this is an escape hatch! */
5593 G.exiting = 1;
5594 hush_exit(xfunc_error_retval);
5595 }
5596
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00005597 /* Shell is non-interactive at first. We need to call
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00005598 * block_signals(0) if we are going to execute "sh <script>",
5599 * "sh -c <cmds>" or login shell's /etc/profile and friends.
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00005600 * If we later decide that we are interactive, we run block_signals(0)
5601 * (or re-run block_signals(1) if we ran block_signals(0) before)
5602 * in order to intercept (more) signals.
5603 */
5604
5605 /* Parse options */
Mike Frysinger19a7ea12009-03-28 13:02:11 +00005606 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00005607 while (1) {
5608 opt = getopt(argc, argv, "c:xins"
5609#if !BB_MMU
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00005610 "<:$:!:?:D:R:V:"
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00005611#endif
5612 );
5613 if (opt <= 0)
5614 break;
Eric Andersen25f27032001-04-26 23:22:31 +00005615 switch (opt) {
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00005616 case 'c':
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00005617 if (!G.root_pid)
5618 G.root_pid = getpid();
Denis Vlasenko87a86552008-07-29 19:43:10 +00005619 G.global_argv = argv + optind;
Denis Vlasenkoa8b6dff2009-03-20 12:05:14 +00005620 if (!argv[optind]) {
5621 /* -c 'script' (no params): prevent empty $0 */
5622 *--G.global_argv = argv[0];
5623 optind--;
5624 } /* else -c 'script' PAR0 PAR1: $0 is PAR0 */
Denis Vlasenko87a86552008-07-29 19:43:10 +00005625 G.global_argc = argc - optind;
Denis Vlasenkof9375282009-04-05 19:13:39 +00005626 block_signals(0); /* 0: called 1st time */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005627 parse_and_run_string(optarg);
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00005628 goto final_return;
5629 case 'i':
Denis Vlasenkoc666f712007-05-16 22:18:54 +00005630 /* Well, we cannot just declare interactiveness,
5631 * we have to have some stuff (ctty, etc) */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005632 /* G_interactive_fd++; */
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00005633 break;
Mike Frysinger19a7ea12009-03-28 13:02:11 +00005634 case 's':
5635 /* "-s" means "read from stdin", but this is how we always
5636 * operate, so simply do nothing here. */
5637 break;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00005638#if !BB_MMU
Denis Vlasenko50f3aa42009-04-07 10:52:40 +00005639 case '<': /* "big heredoc" support */
5640 full_write(STDOUT_FILENO, optarg, strlen(optarg));
5641 _exit(0);
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00005642 case '$':
Denis Vlasenko34e573d2009-04-06 12:56:28 +00005643 G.root_pid = bb_strtou(optarg, &optarg, 16);
5644 optarg++;
5645 G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
5646 optarg++;
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00005647 G.last_exitcode = bb_strtou(optarg, &optarg, 16);
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00005648# if ENABLE_HUSH_LOOPS
Denis Vlasenko34e573d2009-04-06 12:56:28 +00005649 optarg++;
5650 G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00005651# endif
Denis Vlasenko34e573d2009-04-06 12:56:28 +00005652 break;
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00005653 case 'R':
5654 case 'V':
5655 set_local_var(xstrdup(optarg), 0, opt == 'R');
5656 break;
5657#endif
Mike Frysingerad88d5a2009-03-28 13:44:51 +00005658 case 'n':
5659 case 'x':
Denis Vlasenkod5762932009-03-31 11:22:57 +00005660 if (!set_mode('-', opt))
Mike Frysingerad88d5a2009-03-28 13:44:51 +00005661 break;
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00005662 default:
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00005663#ifndef BB_VER
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00005664 fprintf(stderr, "Usage: sh [FILE]...\n"
5665 " or: sh -c command [args]...\n\n");
5666 exit(EXIT_FAILURE);
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00005667#else
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00005668 bb_show_usage();
Eric Andersen9ffb7dd2001-05-19 03:00:46 +00005669#endif
Eric Andersen25f27032001-04-26 23:22:31 +00005670 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00005671 } /* option parsing loop */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00005672
5673 if (!G.root_pid)
5674 G.root_pid = getpid();
Denis Vlasenkof9375282009-04-05 19:13:39 +00005675
5676 /* If we are login shell... */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00005677 if (argv[0] && argv[0][0] == '-') {
5678 FILE *input;
5679 /* XXX what should argv be while sourcing /etc/profile? */
5680 debug_printf("sourcing /etc/profile\n");
5681 input = fopen_for_read("/etc/profile");
5682 if (input != NULL) {
5683 close_on_exec_on(fileno(input));
Denis Vlasenkof9375282009-04-05 19:13:39 +00005684 block_signals(0); /* 0: called 1st time */
5685 signal_mask_is_inited = 1;
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00005686 parse_and_run_file(input);
5687 fclose(input);
5688 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00005689 /* bash: after sourcing /etc/profile,
5690 * tries to source (in the given order):
5691 * ~/.bash_profile, ~/.bash_login, ~/.profile,
5692 * stopping of first found. --noprofile turns this off.
5693 * bash also sources ~/.bash_logout on exit.
5694 * If called as sh, skips .bash_XXX files.
5695 */
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00005696 }
5697
Denis Vlasenkof9375282009-04-05 19:13:39 +00005698 if (argv[optind]) {
5699 FILE *input;
5700 /*
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00005701 * "bash <script>" (which is never interactive (unless -i?))
5702 * sources $BASH_ENV here (without scanning $PATH).
Denis Vlasenkof9375282009-04-05 19:13:39 +00005703 * If called as sh, does the same but with $ENV.
5704 */
5705 debug_printf("running script '%s'\n", argv[optind]);
5706 G.global_argv = argv + optind;
5707 G.global_argc = argc - optind;
5708 input = xfopen_for_read(argv[optind]);
5709 close_on_exec_on(fileno(input));
5710 if (!signal_mask_is_inited)
5711 block_signals(0); /* 0: called 1st time */
5712 parse_and_run_file(input);
5713#if ENABLE_FEATURE_CLEAN_UP
5714 fclose(input);
5715#endif
5716 goto final_return;
5717 }
5718
Denis Vlasenkoc4a7af52009-04-05 20:33:27 +00005719 /* Up to here, shell was non-interactive. Now it may become one.
5720 * NB: don't forget to (re)run block_signals(0/1) as needed.
5721 */
Denis Vlasenkof9375282009-04-05 19:13:39 +00005722
Denis Vlasenkofbf6dea2007-04-13 19:56:56 +00005723 /* A shell is interactive if the '-i' flag was given, or if all of
Eric Andersen25f27032001-04-26 23:22:31 +00005724 * the following conditions are met:
Denis Vlasenko55b2de72007-04-18 17:21:28 +00005725 * no -c command
Eric Andersen25f27032001-04-26 23:22:31 +00005726 * no arguments remaining or the -s flag given
5727 * standard input is a terminal
5728 * standard output is a terminal
Denis Vlasenkof9375282009-04-05 19:13:39 +00005729 * Refer to Posix.2, the description of the 'sh' utility.
5730 */
5731#if ENABLE_HUSH_JOB
5732 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00005733 G.saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
Denis Vlasenkof9375282009-04-05 19:13:39 +00005734 debug_printf("saved_tty_pgrp:%d\n", G.saved_tty_pgrp);
Denis Vlasenkod3f973e2009-04-06 10:21:42 +00005735//TODO: "interactive" and "have job control" are two different things.
5736//If tcgetpgrp fails here, "have job control" is false, but "interactive"
5737//should stay on! Currently, we mix these into one.
Denis Vlasenko87a86552008-07-29 19:43:10 +00005738 if (G.saved_tty_pgrp >= 0) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00005739 /* try to dup stdin to high fd#, >= 255 */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005740 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
5741 if (G_interactive_fd < 0) {
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00005742 /* try to dup to any fd */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005743 G_interactive_fd = dup(STDIN_FILENO);
5744 if (G_interactive_fd < 0)
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00005745 /* give up */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005746 G_interactive_fd = 0;
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00005747 }
Denis Vlasenko46f9b6d2009-04-05 10:39:03 +00005748// TODO: track & disallow any attempts of user
5749// to (inadvertently) close/redirect it
Denis Vlasenko54e7ffb2007-04-21 00:03:36 +00005750 }
Eric Andersen25f27032001-04-26 23:22:31 +00005751 }
Denis Vlasenkof9375282009-04-05 19:13:39 +00005752 debug_printf("interactive_fd:%d\n", G_interactive_fd);
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005753 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00005754 pid_t shell_pgrp;
5755
5756 /* We are indeed interactive shell, and we will perform
5757 * job control. Setting up for that. */
5758
5759 close_on_exec_on(G_interactive_fd);
5760 /* If we were run as 'hush &', sleep until we are
5761 * in the foreground (tty pgrp == our pgrp).
5762 * If we get started under a job aware app (like bash),
5763 * make sure we are now in charge so we don't fight over
5764 * who gets the foreground */
5765 while (1) {
5766 shell_pgrp = getpgrp();
5767 G.saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
5768 if (G.saved_tty_pgrp == shell_pgrp)
5769 break;
5770 /* send TTIN to ourself (should stop us) */
5771 kill(- shell_pgrp, SIGTTIN);
5772 }
5773 /* Block some signals */
5774 block_signals(signal_mask_is_inited);
5775 /* Set other signals to restore saved_tty_pgrp */
5776 set_fatal_handlers();
5777 /* Put ourselves in our own process group */
5778 bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
5779 /* Grab control of the terminal */
5780 tcsetpgrp(G_interactive_fd, getpid());
Denis Vlasenko4ecfcdc2008-02-11 08:32:31 +00005781 /* -1 is special - makes xfuncs longjmp, not exit
Denis Vlasenkoc04163a2008-02-11 08:30:53 +00005782 * (we reset die_sleep = 0 whereever we [v]fork) */
Denis Vlasenkoaf07b7c2009-04-07 13:26:18 +00005783 enable_restore_tty_pgrp_on_exit(); /* sets die_sleep = -1 */
Denis Vlasenkof9375282009-04-05 19:13:39 +00005784 } else if (!signal_mask_is_inited) {
5785 block_signals(0); /* 0: called 1st time */
5786 } /* else: block_signals(0) was done before */
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00005787#elif ENABLE_HUSH_INTERACTIVE
Denis Vlasenkof9375282009-04-05 19:13:39 +00005788 /* No job control compiled in, only prompt/line editing */
5789 if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005790 G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
5791 if (G_interactive_fd < 0) {
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00005792 /* try to dup to any fd */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005793 G_interactive_fd = dup(STDIN_FILENO);
5794 if (G_interactive_fd < 0)
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00005795 /* give up */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005796 G_interactive_fd = 0;
Denis Vlasenkoe3f2f892007-04-28 16:48:27 +00005797 }
5798 }
Denis Vlasenko60b392f2009-04-03 19:14:32 +00005799 if (G_interactive_fd) {
Denis Vlasenkof9375282009-04-05 19:13:39 +00005800 close_on_exec_on(G_interactive_fd);
5801 block_signals(signal_mask_is_inited);
5802 } else if (!signal_mask_is_inited) {
5803 block_signals(0);
5804 }
5805#else
5806 /* We have interactiveness code disabled */
5807 if (!signal_mask_is_inited) {
5808 block_signals(0);
5809 }
5810#endif
5811 /* bash:
5812 * if interactive but not a login shell, sources ~/.bashrc
5813 * (--norc turns this off, --rcfile <file> overrides)
5814 */
5815
5816 if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
Mike Frysinger258275d2009-04-05 21:19:43 +00005817 printf("\n\n%s hush - the humble shell\n", bb_banner);
Mike Frysingerb2705e12009-03-23 08:44:02 +00005818 printf("Enter 'help' for a list of built-in commands.\n\n");
5819 }
5820
Denis Vlasenkof9375282009-04-05 19:13:39 +00005821 parse_and_run_file(stdin);
Eric Andersen25f27032001-04-26 23:22:31 +00005822
Denis Vlasenkod76c0492007-05-25 02:16:25 +00005823 final_return:
Denis Vlasenko38f63192007-01-22 09:03:07 +00005824#if ENABLE_FEATURE_CLEAN_UP
Denis Vlasenko87a86552008-07-29 19:43:10 +00005825 if (G.cwd != bb_msg_unknown)
5826 free((char*)G.cwd);
5827 cur_var = G.top_var->next;
Denis Vlasenkod76c0492007-05-25 02:16:25 +00005828 while (cur_var) {
5829 struct variable *tmp = cur_var;
5830 if (!cur_var->max_len)
Denis Vlasenko28c0f0f2007-05-25 02:46:01 +00005831 free(cur_var->varstr);
Denis Vlasenkod76c0492007-05-25 02:16:25 +00005832 cur_var = cur_var->next;
5833 free(tmp);
Eric Andersenaeb44c42001-05-22 20:29:00 +00005834 }
Eric Andersen25f27032001-04-26 23:22:31 +00005835#endif
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00005836 hush_exit(G.last_exitcode);
Eric Andersen25f27032001-04-26 23:22:31 +00005837}
Denis Vlasenko96702ca2007-11-23 23:28:55 +00005838
5839
5840#if ENABLE_LASH
5841int lash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
5842int lash_main(int argc, char **argv)
5843{
5844 //bb_error_msg("lash is deprecated, please use hush instead");
5845 return hush_main(argc, argv);
5846}
5847#endif
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00005848
5849
5850/*
5851 * Built-ins
5852 */
Mike Frysinger9f8128f2009-03-29 23:49:37 +00005853static int builtin_trap(char **argv)
5854{
Denis Vlasenkod5762932009-03-31 11:22:57 +00005855 int i;
Mike Frysinger9f8128f2009-03-29 23:49:37 +00005856 int sig;
Denis Vlasenkod5762932009-03-31 11:22:57 +00005857 char *new_cmd;
Mike Frysinger9f8128f2009-03-29 23:49:37 +00005858
5859 if (!G.traps)
Denis Vlasenkod5762932009-03-31 11:22:57 +00005860 G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
Mike Frysinger9f8128f2009-03-29 23:49:37 +00005861
Denis Vlasenkoc8d27332009-04-06 10:47:21 +00005862 argv++;
5863 if (!*argv) {
5864 /* No args: print all trapped. This isn't 100% correct as we
5865 * should be escaping the cmd so that it can be pasted back in
Mike Frysinger9f8128f2009-03-29 23:49:37 +00005866 */
5867 for (i = 0; i < NSIG; ++i)
Denis Vlasenkod5762932009-03-31 11:22:57 +00005868 if (G.traps[i])
5869 printf("trap -- '%s' %s\n", G.traps[i], get_signame(i));
Mike Frysinger9f8128f2009-03-29 23:49:37 +00005870 return EXIT_SUCCESS;
5871 }
5872
Denis Vlasenkod5762932009-03-31 11:22:57 +00005873 new_cmd = NULL;
5874 i = 0;
Denis Vlasenkoc8d27332009-04-06 10:47:21 +00005875 /* If first arg is decimal: reset all specified signals */
5876 sig = bb_strtou(*argv, NULL, 10);
Mike Frysinger9f8128f2009-03-29 23:49:37 +00005877 if (errno == 0) {
5878 int ret;
Mike Frysinger9f8128f2009-03-29 23:49:37 +00005879 set_all:
5880 ret = EXIT_SUCCESS;
Denis Vlasenkod5762932009-03-31 11:22:57 +00005881 while (*argv) {
5882 sig = get_signum(*argv++);
Mike Frysinger9f8128f2009-03-29 23:49:37 +00005883 if (sig < 0 || sig >= NSIG) {
5884 ret = EXIT_FAILURE;
Denis Vlasenkoc8d27332009-04-06 10:47:21 +00005885 /* Mimic bash message exactly */
Mike Frysinger9f8128f2009-03-29 23:49:37 +00005886 bb_perror_msg("trap: %s: invalid signal specification", argv[i]);
5887 continue;
5888 }
5889
Denis Vlasenkod5762932009-03-31 11:22:57 +00005890 free(G.traps[sig]);
5891 G.traps[sig] = xstrdup(new_cmd);
Mike Frysinger9f8128f2009-03-29 23:49:37 +00005892
Denis Vlasenkod5762932009-03-31 11:22:57 +00005893 debug_printf("trap: setting SIG%s (%i) to '%s'",
5894 get_signame(sig), sig, G.traps[sig]);
Mike Frysinger9f8128f2009-03-29 23:49:37 +00005895
5896 /* There is no signal for 0 (EXIT) */
5897 if (sig == 0)
5898 continue;
5899
5900 if (new_cmd) {
Denis Vlasenkod5762932009-03-31 11:22:57 +00005901 sigaddset(&G.blocked_set, sig);
5902 } else {
Denis Vlasenkoc8d27332009-04-06 10:47:21 +00005903 /* There was a trap handler, we are removing it
Denis Vlasenkod5762932009-03-31 11:22:57 +00005904 * (if sig has non-DFL handling,
5905 * we don't need to do anything) */
5906 if (sig < 32 && (G.non_DFL_mask & (1 << sig)))
5907 continue;
5908 sigdelset(&G.blocked_set, sig);
5909 }
5910 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
Mike Frysinger9f8128f2009-03-29 23:49:37 +00005911 }
5912 return ret;
5913 }
5914
Denis Vlasenkoc8d27332009-04-06 10:47:21 +00005915 /* First arg is "-": reset all specified to default */
5916 /* First arg is "": ignore all specified */
5917 /* Everything else: execute first arg upon signal */
Denis Vlasenkod5762932009-03-31 11:22:57 +00005918 if (!argv[1]) {
Mike Frysinger9f8128f2009-03-29 23:49:37 +00005919 bb_error_msg("trap: invalid arguments");
5920 return EXIT_FAILURE;
5921 }
Denis Vlasenkoc8d27332009-04-06 10:47:21 +00005922 if (NOT_LONE_DASH(*argv))
Denis Vlasenkod5762932009-03-31 11:22:57 +00005923 new_cmd = *argv;
5924 argv++;
Mike Frysinger9f8128f2009-03-29 23:49:37 +00005925 goto set_all;
5926}
5927
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00005928static int builtin_true(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00005929{
5930 return 0;
5931}
5932
5933static int builtin_test(char **argv)
5934{
5935 int argc = 0;
5936 while (*argv) {
5937 argc++;
5938 argv++;
5939 }
5940 return test_main(argc, argv - argc);
5941}
5942
5943static int builtin_echo(char **argv)
5944{
5945 int argc = 0;
5946 while (*argv) {
5947 argc++;
5948 argv++;
5949 }
5950 return echo_main(argc, argv - argc);
5951}
5952
5953static int builtin_eval(char **argv)
5954{
5955 int rcode = EXIT_SUCCESS;
5956
Denis Vlasenkob0a64782009-04-06 11:33:07 +00005957 if (*++argv) {
5958 char *str = expand_strvec_to_string(argv);
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005959 /* bash:
5960 * eval "echo Hi; done" ("done" is syntax error):
5961 * "echo Hi" will not execute too.
5962 */
5963 parse_and_run_string(str);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00005964 free(str);
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00005965 rcode = G.last_exitcode;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00005966 }
5967 return rcode;
5968}
5969
5970static int builtin_cd(char **argv)
5971{
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00005972 const char *newdir = argv[1];
5973 if (newdir == NULL) {
Denis Vlasenkob6e65562009-04-03 16:49:04 +00005974 /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
5975 * bash says "bash: cd: HOME not set" and does nothing (exitcode 1)
5976 */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00005977 newdir = getenv("HOME") ? : "/";
Denis Vlasenkob0a64782009-04-06 11:33:07 +00005978 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00005979 if (chdir(newdir)) {
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00005980 /* Mimic bash message exactly */
5981 bb_perror_msg("cd: %s", newdir);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00005982 return EXIT_FAILURE;
5983 }
5984 set_cwd();
5985 return EXIT_SUCCESS;
5986}
5987
5988static int builtin_exec(char **argv)
5989{
Denis Vlasenkob0a64782009-04-06 11:33:07 +00005990 if (*++argv == NULL)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00005991 return EXIT_SUCCESS; /* bash does this */
5992 {
5993#if !BB_MMU
Denis Vlasenkof886fd22008-10-13 12:36:05 +00005994 nommu_save_t dummy;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00005995#endif
5996// FIXME: if exec fails, bash does NOT exit! We do...
Denis Vlasenkob0a64782009-04-06 11:33:07 +00005997 pseudo_exec_argv(&dummy, argv, 0, NULL);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00005998 /* never returns */
5999 }
6000}
6001
6002static int builtin_exit(char **argv)
6003{
Denis Vlasenkocd418a22009-04-06 18:08:35 +00006004 debug_printf_exec("%s()\n", __func__);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006005// TODO: bash does it ONLY on top-level sh exit (+interacive only?)
6006 //puts("exit"); /* bash does it */
6007// TODO: warn if we have background jobs: "There are stopped jobs"
6008// On second consecutive 'exit', exit anyway.
Denis Vlasenkoefea9d22009-04-09 13:43:11 +00006009// perhaps use G.exiting = -1 as indicator "last cmd was exit"
6010
6011 /* note: EXIT trap is run by hush_exit */
Denis Vlasenkob0a64782009-04-06 11:33:07 +00006012 if (*++argv == NULL)
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00006013 hush_exit(G.last_exitcode);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006014 /* mimic bash: exit 123abc == exit 255 + error msg */
6015 xfunc_error_retval = 255;
6016 /* bash: exit -2 == exit 254, no error msg */
Denis Vlasenkob0a64782009-04-06 11:33:07 +00006017 hush_exit(xatoi(*argv) & 0xff);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006018}
6019
6020static int builtin_export(char **argv)
6021{
Denis Vlasenkob0a64782009-04-06 11:33:07 +00006022 if (*++argv == NULL) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006023 // TODO:
6024 // ash emits: export VAR='VAL'
6025 // bash: declare -x VAR="VAL"
6026 // (both also escape as needed (quotes, $, etc))
6027 char **e = environ;
6028 if (e)
6029 while (*e)
6030 puts(*e++);
6031 return EXIT_SUCCESS;
6032 }
6033
Denis Vlasenkob0a64782009-04-06 11:33:07 +00006034 do {
6035 const char *value;
6036 char *name = *argv;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006037
Denis Vlasenkob0a64782009-04-06 11:33:07 +00006038 value = strchr(name, '=');
6039 if (!value) {
6040 /* They are exporting something without a =VALUE */
6041 struct variable *var;
6042
6043 var = get_local_var(name);
6044 if (var) {
6045 var->flg_export = 1;
6046 debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
6047 putenv(var->varstr);
6048 }
6049 /* bash does not return an error when trying to export
6050 * an undefined variable. Do likewise. */
6051 continue;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006052 }
Denis Vlasenkob0a64782009-04-06 11:33:07 +00006053 set_local_var(xstrdup(name), 1, 0);
6054 } while (*++argv);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006055
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006056 return EXIT_SUCCESS;
6057}
6058
6059#if ENABLE_HUSH_JOB
6060/* built-in 'fg' and 'bg' handler */
6061static int builtin_fg_bg(char **argv)
6062{
6063 int i, jobnum;
6064 struct pipe *pi;
6065
Denis Vlasenko60b392f2009-04-03 19:14:32 +00006066 if (!G_interactive_fd)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006067 return EXIT_FAILURE;
6068 /* If they gave us no args, assume they want the last backgrounded task */
6069 if (!argv[1]) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00006070 for (pi = G.job_list; pi; pi = pi->next) {
6071 if (pi->jobid == G.last_jobid) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006072 goto found;
6073 }
6074 }
6075 bb_error_msg("%s: no current job", argv[0]);
6076 return EXIT_FAILURE;
6077 }
6078 if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
6079 bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
6080 return EXIT_FAILURE;
6081 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00006082 for (pi = G.job_list; pi; pi = pi->next) {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006083 if (pi->jobid == jobnum) {
6084 goto found;
6085 }
6086 }
6087 bb_error_msg("%s: %d: no such job", argv[0], jobnum);
6088 return EXIT_FAILURE;
6089 found:
6090 // TODO: bash prints a string representation
6091 // of job being foregrounded (like "sleep 1 | cat")
Denis Vlasenko34d4d892009-04-04 20:24:37 +00006092 if (argv[0][0] == 'f') {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006093 /* Put the job into the foreground. */
Denis Vlasenko60b392f2009-04-03 19:14:32 +00006094 tcsetpgrp(G_interactive_fd, pi->pgrp);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006095 }
6096
6097 /* Restart the processes in the job */
Denis Vlasenko9af22c72008-10-09 12:54:58 +00006098 debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
6099 for (i = 0; i < pi->num_cmds; i++) {
6100 debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
6101 pi->cmds[i].is_stopped = 0;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006102 }
Denis Vlasenko9af22c72008-10-09 12:54:58 +00006103 pi->stopped_cmds = 0;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006104
6105 i = kill(- pi->pgrp, SIGCONT);
6106 if (i < 0) {
6107 if (errno == ESRCH) {
6108 delete_finished_bg_job(pi);
6109 return EXIT_SUCCESS;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006110 }
Denis Vlasenko34d4d892009-04-04 20:24:37 +00006111 bb_perror_msg("kill (SIGCONT)");
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006112 }
6113
Denis Vlasenko34d4d892009-04-04 20:24:37 +00006114 if (argv[0][0] == 'f') {
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006115 remove_bg_job(pi);
6116 return checkjobs_and_fg_shell(pi);
6117 }
6118 return EXIT_SUCCESS;
6119}
6120#endif
6121
6122#if ENABLE_HUSH_HELP
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00006123static int builtin_help(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006124{
6125 const struct built_in_command *x;
6126
Denis Vlasenko34d4d892009-04-04 20:24:37 +00006127 printf("\n"
6128 "Built-in commands:\n"
6129 "------------------\n");
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006130 for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) {
6131 printf("%s\t%s\n", x->cmd, x->descr);
6132 }
6133 printf("\n\n");
6134 return EXIT_SUCCESS;
6135}
6136#endif
6137
6138#if ENABLE_HUSH_JOB
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00006139static int builtin_jobs(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006140{
6141 struct pipe *job;
6142 const char *status_string;
6143
Denis Vlasenko87a86552008-07-29 19:43:10 +00006144 for (job = G.job_list; job; job = job->next) {
Denis Vlasenko9af22c72008-10-09 12:54:58 +00006145 if (job->alive_cmds == job->stopped_cmds)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006146 status_string = "Stopped";
6147 else
6148 status_string = "Running";
6149
6150 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
6151 }
6152 return EXIT_SUCCESS;
6153}
6154#endif
6155
Denis Vlasenkoc73b70c2009-04-08 11:48:57 +00006156#if HUSH_DEBUG
6157static int builtin_memleak(char **argv UNUSED_PARAM)
6158{
6159 void *p;
6160 unsigned long l;
6161
6162 /* Crude attempt to find where "free memory" starts,
6163 * sans fragmentation. */
6164 p = malloc(240);
6165 l = (unsigned long)p;
6166 free(p);
6167 p = malloc(3400);
6168 if (l < (unsigned long)p) l = (unsigned long)p;
6169 free(p);
6170
6171 if (!G.memleak_value)
6172 G.memleak_value = l;
6173
6174 l -= G.memleak_value;
6175 if ((long)l < 0)
6176 l = 0;
6177 l /= 1024;
6178 if (l > 127)
6179 l = 127;
6180
6181 /* Exitcode is "how many kilobytes we leaked since 1st call" */
6182 return l;
6183}
6184#endif
6185
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00006186static int builtin_pwd(char **argv UNUSED_PARAM)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006187{
6188 puts(set_cwd());
6189 return EXIT_SUCCESS;
6190}
6191
6192static int builtin_read(char **argv)
6193{
6194 char *string;
Denis Vlasenko05d3b7c2009-04-09 19:16:15 +00006195 const char *name = "REPLY";
6196
6197 if (argv[1]) {
6198 name = argv[1];
6199 if (!is_well_formed_var_name(name, '\0')) {
6200 /* Mimic bash message */
6201 bb_error_msg("read: '%s': not a valid identifier", name);
6202 return 1;
6203 }
6204 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006205
6206 string = xmalloc_reads(STDIN_FILENO, xasprintf("%s=", name), NULL);
Denis Vlasenko0bb4a232009-04-05 01:42:59 +00006207 return set_local_var(string, 0, 0);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006208}
6209
Mike Frysingerad88d5a2009-03-28 13:44:51 +00006210/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
6211 * built-in 'set' handler
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00006212 * SUSv3 says:
Mike Frysingerad88d5a2009-03-28 13:44:51 +00006213 * set [-abCefhmnuvx] [-o option] [argument...]
6214 * set [+abCefhmnuvx] [+o option] [argument...]
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00006215 * set -- [argument...]
6216 * set -o
6217 * set +o
6218 * Implementations shall support the options in both their hyphen and
6219 * plus-sign forms. These options can also be specified as options to sh.
6220 * Examples:
6221 * Write out all variables and their values: set
6222 * Set $1, $2, and $3 and set "$#" to 3: set c a b
6223 * Turn on the -x and -v options: set -xv
6224 * Unset all positional parameters: set --
6225 * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
6226 * Set the positional parameters to the expansion of x, even if x expands
6227 * with a leading '-' or '+': set -- $x
6228 *
Mike Frysingerad88d5a2009-03-28 13:44:51 +00006229 * So far, we only support "set -- [argument...]" and some of the short names.
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00006230 */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006231static int builtin_set(char **argv)
6232{
Denis Vlasenko424f79b2009-03-22 14:23:34 +00006233 int n;
6234 char **pp, **g_argv;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00006235 char *arg = *++argv;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006236
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00006237 if (arg == NULL) {
Denis Vlasenko424f79b2009-03-22 14:23:34 +00006238 struct variable *e;
Denis Vlasenko87a86552008-07-29 19:43:10 +00006239 for (e = G.top_var; e; e = e->next)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006240 puts(e->varstr);
Denis Vlasenko424f79b2009-03-22 14:23:34 +00006241 return EXIT_SUCCESS;
Denis Vlasenko11fb7cf2009-03-20 10:13:08 +00006242 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006243
Mike Frysingerad88d5a2009-03-28 13:44:51 +00006244 do {
6245 if (!strcmp(arg, "--")) {
6246 ++argv;
6247 goto set_argv;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00006248 }
Mike Frysingerad88d5a2009-03-28 13:44:51 +00006249
6250 if (arg[0] == '+' || arg[0] == '-') {
6251 for (n = 1; arg[n]; ++n)
Denis Vlasenkod5762932009-03-31 11:22:57 +00006252 if (set_mode(arg[0], arg[n]))
Mike Frysingerad88d5a2009-03-28 13:44:51 +00006253 goto error;
6254 continue;
6255 }
6256
6257 break;
Denis Vlasenko424f79b2009-03-22 14:23:34 +00006258 } while ((arg = *++argv) != NULL);
6259 /* Now argv[0] is 1st argument */
6260
Mike Frysingerad88d5a2009-03-28 13:44:51 +00006261 /* Only reset global_argv if we didn't process anything */
6262 if (arg == NULL)
6263 return EXIT_SUCCESS;
6264 set_argv:
6265
Denis Vlasenko424f79b2009-03-22 14:23:34 +00006266 /* NB: G.global_argv[0] ($0) is never freed/changed */
6267 g_argv = G.global_argv;
6268 if (G.global_args_malloced) {
6269 pp = g_argv;
6270 while (*++pp)
6271 free(*pp);
6272 g_argv[1] = NULL;
6273 } else {
6274 G.global_args_malloced = 1;
6275 pp = xzalloc(sizeof(pp[0]) * 2);
6276 pp[0] = g_argv[0]; /* retain $0 */
6277 g_argv = pp;
6278 }
6279 /* This realloc's G.global_argv */
6280 G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
6281
6282 n = 1;
6283 while (*++pp)
6284 n++;
6285 G.global_argc = n;
6286
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006287 return EXIT_SUCCESS;
Mike Frysingerad88d5a2009-03-28 13:44:51 +00006288
6289 /* Nothing known, so abort */
6290 error:
6291 bb_error_msg("set: %s: invalid option", arg);
6292 return EXIT_FAILURE;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006293}
6294
6295static int builtin_shift(char **argv)
6296{
6297 int n = 1;
6298 if (argv[1]) {
6299 n = atoi(argv[1]);
6300 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00006301 if (n >= 0 && n < G.global_argc) {
Denis Vlasenkoe1300f62009-03-22 11:41:18 +00006302 if (G.global_args_malloced) {
6303 int m = 1;
6304 while (m <= n)
6305 free(G.global_argv[m++]);
6306 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00006307 G.global_argc -= n;
Denis Vlasenkoe1300f62009-03-22 11:41:18 +00006308 memmove(&G.global_argv[1], &G.global_argv[n+1],
6309 G.global_argc * sizeof(G.global_argv[0]));
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006310 return EXIT_SUCCESS;
6311 }
6312 return EXIT_FAILURE;
6313}
6314
6315static int builtin_source(char **argv)
6316{
6317 FILE *input;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006318
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00006319 if (*++argv == NULL)
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006320 return EXIT_FAILURE;
6321
6322 /* XXX search through $PATH is missing */
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00006323 input = fopen_or_warn(*argv, "r");
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006324 if (!input) {
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00006325 /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006326 return EXIT_FAILURE;
6327 }
6328 close_on_exec_on(fileno(input));
6329
6330 /* Now run the file */
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00006331//TODO:
Denis Vlasenko87a86552008-07-29 19:43:10 +00006332 /* XXX argv and argc are broken; need to save old G.global_argv
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006333 * (pointer only is OK!) on this stack frame,
Denis Vlasenko87a86552008-07-29 19:43:10 +00006334 * set G.global_argv=argv+1, recurse, and restore. */
Denis Vlasenkob6e65562009-04-03 16:49:04 +00006335 parse_and_run_file(input);
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006336 fclose(input);
Denis Vlasenkoab2b0642009-04-06 18:42:11 +00006337 return G.last_exitcode;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006338}
6339
6340static int builtin_umask(char **argv)
6341{
6342 mode_t new_umask;
6343 const char *arg = argv[1];
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006344 if (arg) {
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00006345//TODO: umask may take chmod-like symbolic masks
Mike Frysinger40b8dc42009-03-29 00:50:30 +00006346 new_umask = bb_strtou(arg, NULL, 8);
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00006347 if (errno) {
6348 //Message? bash examples:
6349 //bash: umask: 'q': invalid symbolic mode operator
6350 //bash: umask: 999: octal number out of range
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006351 return EXIT_FAILURE;
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00006352 }
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006353 } else {
6354 new_umask = umask(0);
6355 printf("%.3o\n", (unsigned) new_umask);
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00006356 /* fall through and restore new_umask which we set to 0 */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006357 }
6358 umask(new_umask);
6359 return EXIT_SUCCESS;
6360}
6361
Mike Frysingerd690f682009-03-30 06:50:54 +00006362/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006363static int builtin_unset(char **argv)
6364{
Mike Frysingerd690f682009-03-30 06:50:54 +00006365 int ret;
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00006366 char var;
Mike Frysingerd690f682009-03-30 06:50:54 +00006367
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00006368 if (!*++argv)
Mike Frysingerd690f682009-03-30 06:50:54 +00006369 return EXIT_SUCCESS;
6370
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00006371 var = 'v';
6372 if (argv[0][0] == '-') {
6373 switch (argv[0][1]) {
6374 case 'v':
6375 case 'f':
6376 var = argv[0][1];
6377 break;
Mike Frysingerd690f682009-03-30 06:50:54 +00006378 default:
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00006379 bb_error_msg("unset: %s: invalid option", *argv);
Mike Frysingerd690f682009-03-30 06:50:54 +00006380 return EXIT_FAILURE;
6381 }
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00006382//TODO: disallow "unset -vf ..." too
6383 argv++;
Mike Frysingerd690f682009-03-30 06:50:54 +00006384 }
6385
6386 ret = EXIT_SUCCESS;
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00006387 while (*argv) {
6388 if (var == 'v') {
6389 if (unset_local_var(*argv)) {
6390 /* unset <nonexistent_var> doesn't fail.
6391 * Error is when one tries to unset RO var.
6392 * Message was printed by unset_local_var. */
Mike Frysingerd690f682009-03-30 06:50:54 +00006393 ret = EXIT_FAILURE;
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00006394 }
Mike Frysingerd690f682009-03-30 06:50:54 +00006395 }
6396#if ENABLE_HUSH_FUNCTIONS
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00006397 else {
6398 unset_local_func(*argv);
6399 }
Mike Frysingerd690f682009-03-30 06:50:54 +00006400#endif
Denis Vlasenkobfbc9712009-04-06 12:04:42 +00006401 argv++;
Mike Frysingerd690f682009-03-30 06:50:54 +00006402 }
6403 return ret;
Denis Vlasenkoc7985b72008-06-17 05:43:38 +00006404}
Denis Vlasenkobcb25532008-07-28 23:04:34 +00006405
Mike Frysinger56bdea12009-03-28 20:01:58 +00006406/* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
6407static int builtin_wait(char **argv)
6408{
6409 int ret = EXIT_SUCCESS;
Denis Vlasenko7566bae2009-03-31 17:24:49 +00006410 int status, sig;
Mike Frysinger56bdea12009-03-28 20:01:58 +00006411
Denis Vlasenko7566bae2009-03-31 17:24:49 +00006412 if (*++argv == NULL) {
6413 /* Don't care about wait results */
6414 /* Note 1: must wait until there are no more children */
6415 /* Note 2: must be interruptible */
6416 /* Examples:
6417 * $ sleep 3 & sleep 6 & wait
6418 * [1] 30934 sleep 3
6419 * [2] 30935 sleep 6
6420 * [1] Done sleep 3
6421 * [2] Done sleep 6
6422 * $ sleep 3 & sleep 6 & wait
6423 * [1] 30936 sleep 3
6424 * [2] 30937 sleep 6
6425 * [1] Done sleep 3
6426 * ^C <-- after ~4 sec from keyboard
6427 * $
6428 */
6429 sigaddset(&G.blocked_set, SIGCHLD);
6430 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
6431 while (1) {
6432 checkjobs(NULL);
6433 if (errno == ECHILD)
6434 break;
6435 /* Wait for SIGCHLD or any other signal of interest */
6436 /* sigtimedwait with infinite timeout: */
6437 sig = sigwaitinfo(&G.blocked_set, NULL);
6438 if (sig > 0) {
6439 sig = check_and_run_traps(sig);
6440 if (sig && sig != SIGCHLD) { /* see note 2 */
6441 ret = 128 + sig;
6442 break;
6443 }
6444 }
6445 }
6446 sigdelset(&G.blocked_set, SIGCHLD);
6447 sigprocmask(SIG_SETMASK, &G.blocked_set, NULL);
6448 return ret;
6449 }
Mike Frysinger56bdea12009-03-28 20:01:58 +00006450
Denis Vlasenko7566bae2009-03-31 17:24:49 +00006451 /* This is probably buggy wrt interruptible-ness */
Denis Vlasenkod5762932009-03-31 11:22:57 +00006452 while (*argv) {
6453 pid_t pid = bb_strtou(*argv, NULL, 10);
Mike Frysinger40b8dc42009-03-29 00:50:30 +00006454 if (errno) {
Denis Vlasenkod5762932009-03-31 11:22:57 +00006455 /* mimic bash message */
6456 bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
Mike Frysinger56bdea12009-03-28 20:01:58 +00006457 return EXIT_FAILURE;
Denis Vlasenkod5762932009-03-31 11:22:57 +00006458 }
6459 if (waitpid(pid, &status, 0) == pid) {
Mike Frysinger56bdea12009-03-28 20:01:58 +00006460 if (WIFSIGNALED(status))
6461 ret = 128 + WTERMSIG(status);
6462 else if (WIFEXITED(status))
6463 ret = WEXITSTATUS(status);
Denis Vlasenkod5762932009-03-31 11:22:57 +00006464 else /* wtf? */
Mike Frysinger56bdea12009-03-28 20:01:58 +00006465 ret = EXIT_FAILURE;
6466 } else {
Denis Vlasenkod5762932009-03-31 11:22:57 +00006467 bb_perror_msg("wait %s", *argv);
Mike Frysinger56bdea12009-03-28 20:01:58 +00006468 ret = 127;
6469 }
Denis Vlasenkod5762932009-03-31 11:22:57 +00006470 argv++;
Mike Frysinger56bdea12009-03-28 20:01:58 +00006471 }
6472
6473 return ret;
6474}
6475
Denis Vlasenkodadfb492008-07-29 10:16:05 +00006476#if ENABLE_HUSH_LOOPS
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00006477static int builtin_break(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00006478{
Denis Vlasenko87a86552008-07-29 19:43:10 +00006479 if (G.depth_of_loop == 0) {
Denis Vlasenko4f504a92008-07-29 19:48:30 +00006480 bb_error_msg("%s: only meaningful in a loop", argv[0]);
Denis Vlasenkofcf37c32008-07-29 11:37:15 +00006481 return EXIT_SUCCESS; /* bash compat */
6482 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00006483 G.flag_break_continue++; /* BC_BREAK = 1 */
6484 G.depth_break_continue = 1;
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00006485 if (argv[1]) {
Denis Vlasenko87a86552008-07-29 19:43:10 +00006486 G.depth_break_continue = bb_strtou(argv[1], NULL, 10);
6487 if (errno || !G.depth_break_continue || argv[2]) {
Denis Vlasenko4f504a92008-07-29 19:48:30 +00006488 bb_error_msg("%s: bad arguments", argv[0]);
Denis Vlasenko87a86552008-07-29 19:43:10 +00006489 G.flag_break_continue = BC_BREAK;
6490 G.depth_break_continue = UINT_MAX;
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00006491 }
6492 }
Denis Vlasenko87a86552008-07-29 19:43:10 +00006493 if (G.depth_of_loop < G.depth_break_continue)
6494 G.depth_break_continue = G.depth_of_loop;
Denis Vlasenkobcb25532008-07-28 23:04:34 +00006495 return EXIT_SUCCESS;
6496}
6497
Denis Vlasenko6a2d40f2008-07-28 23:07:06 +00006498static int builtin_continue(char **argv)
Denis Vlasenkobcb25532008-07-28 23:04:34 +00006499{
Denis Vlasenko4f504a92008-07-29 19:48:30 +00006500 G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
6501 return builtin_break(argv);
Denis Vlasenkobcb25532008-07-28 23:04:34 +00006502}
Denis Vlasenkodadfb492008-07-29 10:16:05 +00006503#endif