blob: 08ad0f451649529107c6d3af88a12a38f26c881a [file] [log] [blame]
Eric Andersendf82f612001-06-28 07:46:40 +00001/* vi: set sw=4 ts=4: */
2/*
3 * ash shell port for busybox
4 *
Denys Vlasenko73067272010-01-12 22:11:24 +01005 * This code is derived from software contributed to Berkeley by
6 * Kenneth Almquist.
7 *
8 * Original BSD copyright notice is retained at the end of this file.
9 *
Eric Andersendf82f612001-06-28 07:46:40 +000010 * Copyright (c) 1989, 1991, 1993, 1994
Eric Andersen2870d962001-07-02 17:27:21 +000011 * The Regents of the University of California. All rights reserved.
Eric Andersencb57d552001-06-28 07:25:16 +000012 *
"Vladimir N. Oleynik"ddc280e2005-12-15 12:01:49 +000013 * Copyright (c) 1997-2005 Herbert Xu <herbert@gondor.apana.org.au>
Eric Andersen81fe1232003-07-29 06:38:40 +000014 * was re-ported from NetBSD and debianized.
15 *
Bernhard Reutner-Fischer86f5c992006-01-22 22:55:11 +000016 * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
Eric Andersencb57d552001-06-28 07:25:16 +000017 */
18
Eric Andersenc470f442003-07-28 09:56:35 +000019/*
Denis Vlasenko653d8e72009-03-19 21:59:35 +000020 * The following should be set to reflect the type of system you have:
Eric Andersenc470f442003-07-28 09:56:35 +000021 * JOBS -> 1 if you have Berkeley job control, 0 otherwise.
22 * define SYSV if you are running under System V.
23 * define DEBUG=1 to compile in debugging ('set -o debug' to turn on)
24 * define DEBUG=2 to compile in and turn on debugging.
25 *
26 * When debugging is on, debugging info will be written to ./trace and
27 * a quit signal will generate a core dump.
28 */
Denis Vlasenkof1733952009-03-19 23:21:55 +000029#define DEBUG 0
Denis Vlasenko653d8e72009-03-19 21:59:35 +000030/* Tweak debug output verbosity here */
31#define DEBUG_TIME 0
32#define DEBUG_PID 1
33#define DEBUG_SIG 1
34
Eric Andersenc470f442003-07-28 09:56:35 +000035#define PROFILE 0
Denis Vlasenko0e6f6612008-02-15 15:02:15 +000036
Denis Vlasenko0e6f6612008-02-15 15:02:15 +000037#define JOBS ENABLE_ASH_JOB_CONTROL
Eric Andersenc470f442003-07-28 09:56:35 +000038
Denis Vlasenkob012b102007-02-19 22:43:01 +000039#if DEBUG
Denis Vlasenko653d8e72009-03-19 21:59:35 +000040# ifndef _GNU_SOURCE
41# define _GNU_SOURCE
42# endif
Denis Vlasenkoe26b2782008-02-12 07:40:29 +000043#endif
Denis Vlasenko0e6f6612008-02-15 15:02:15 +000044
Denis Vlasenko1aa7e472007-11-28 06:49:03 +000045#include "busybox.h" /* for applet_names */
Denis Vlasenkob012b102007-02-19 22:43:01 +000046#include <paths.h>
47#include <setjmp.h>
48#include <fnmatch.h>
Denys Vlasenko73067272010-01-12 22:11:24 +010049
50#include "shell_common.h"
Mike Frysinger98c52642009-04-02 10:02:37 +000051#include "math.h"
Denys Vlasenko3ea2e822009-10-09 20:59:04 +020052#if ENABLE_ASH_RANDOM_SUPPORT
53# include "random.h"
Denys Vlasenko36df0482009-10-19 16:07:28 +020054#else
55# define CLEAR_RANDOM_T(rnd) ((void)0)
Denys Vlasenko3ea2e822009-10-09 20:59:04 +020056#endif
Denis Vlasenko61befda2008-11-25 01:36:03 +000057
Denys Vlasenko14974842010-03-23 01:08:26 +010058#define SKIP_definitions 1
59#include "applet_tables.h"
60#undef SKIP_definitions
61#if NUM_APPLETS == 1
Denis Vlasenko61befda2008-11-25 01:36:03 +000062/* STANDALONE does not make sense, and won't compile */
Denys Vlasenko3ea2e822009-10-09 20:59:04 +020063# undef CONFIG_FEATURE_SH_STANDALONE
64# undef ENABLE_FEATURE_SH_STANDALONE
65# undef IF_FEATURE_SH_STANDALONE
Denys Vlasenko14974842010-03-23 01:08:26 +010066# undef IF_NOT_FEATURE_SH_STANDALONE
Denys Vlasenko3ea2e822009-10-09 20:59:04 +020067# define ENABLE_FEATURE_SH_STANDALONE 0
68# define IF_FEATURE_SH_STANDALONE(...)
69# define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
Eric Andersencb57d552001-06-28 07:25:16 +000070#endif
71
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000072#ifndef PIPE_BUF
Denis Vlasenko653d8e72009-03-19 21:59:35 +000073# define PIPE_BUF 4096 /* amount of buffering in a pipe */
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000074#endif
75
Denys Vlasenko153fcaa2010-02-21 05:17:41 +010076#if !BB_MMU
Denis Vlasenko653d8e72009-03-19 21:59:35 +000077# error "Do not even bother, ash will not run on NOMMU machine"
Denis Vlasenkob012b102007-02-19 22:43:01 +000078#endif
79
Denis Vlasenkob012b102007-02-19 22:43:01 +000080
Denis Vlasenko01631112007-12-16 17:20:38 +000081/* ============ Hash table sizes. Configurable. */
82
83#define VTABSIZE 39
84#define ATABSIZE 39
85#define CMDTABLESIZE 31 /* should be prime */
86
87
Denis Vlasenkob012b102007-02-19 22:43:01 +000088/* ============ Shell options */
89
90static const char *const optletters_optnames[] = {
91 "e" "errexit",
92 "f" "noglob",
93 "I" "ignoreeof",
94 "i" "interactive",
95 "m" "monitor",
96 "n" "noexec",
97 "s" "stdin",
98 "x" "xtrace",
99 "v" "verbose",
100 "C" "noclobber",
101 "a" "allexport",
102 "b" "notify",
103 "u" "nounset",
Denys Vlasenkoe9ac32a2009-12-05 02:01:25 +0100104 "\0" "vi"
Michael Abbott359da5e2009-12-04 23:03:29 +0100105#if ENABLE_ASH_BASH_COMPAT
Denys Vlasenkoe9ac32a2009-12-05 02:01:25 +0100106 ,"\0" "pipefail"
Michael Abbott359da5e2009-12-04 23:03:29 +0100107#endif
Denis Vlasenkob012b102007-02-19 22:43:01 +0000108#if DEBUG
Denis Vlasenko6ca409e2007-08-12 20:58:27 +0000109 ,"\0" "nolog"
110 ,"\0" "debug"
Denis Vlasenkob012b102007-02-19 22:43:01 +0000111#endif
112};
113
Denys Vlasenko285ad152009-12-04 23:02:27 +0100114#define optletters(n) optletters_optnames[n][0]
115#define optnames(n) (optletters_optnames[n] + 1)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000116
Denis Vlasenko80b8b392007-06-25 10:55:35 +0000117enum { NOPTS = ARRAY_SIZE(optletters_optnames) };
Denis Vlasenkob012b102007-02-19 22:43:01 +0000118
Eric Andersenc470f442003-07-28 09:56:35 +0000119
Denis Vlasenkob012b102007-02-19 22:43:01 +0000120/* ============ Misc data */
Eric Andersenc470f442003-07-28 09:56:35 +0000121
Denys Vlasenkoea8b2522010-06-02 12:57:26 +0200122#define msg_illnum "Illegal number: %s"
Denis Vlasenkoaa744452007-02-23 01:04:22 +0000123
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +0000124/*
Eric Andersenc470f442003-07-28 09:56:35 +0000125 * We enclose jmp_buf in a structure so that we can declare pointers to
126 * jump locations. The global variable handler contains the location to
Denis Vlasenkof1733952009-03-19 23:21:55 +0000127 * jump to when an exception occurs, and the global variable exception_type
Eric Andersenaff114c2004-04-14 17:51:38 +0000128 * contains a code identifying the exception. To implement nested
Eric Andersenc470f442003-07-28 09:56:35 +0000129 * exception handlers, the user should save the value of handler on entry
130 * to an inner scope, set handler to point to a jmploc structure for the
131 * inner scope, and restore handler on exit from the scope.
132 */
Eric Andersenc470f442003-07-28 09:56:35 +0000133struct jmploc {
134 jmp_buf loc;
135};
Denis Vlasenko01631112007-12-16 17:20:38 +0000136
137struct globals_misc {
138 /* pid of main shell */
139 int rootpid;
140 /* shell level: 0 for the main shell, 1 for its children, and so on */
141 int shlvl;
142#define rootshell (!shlvl)
143 char *minusc; /* argument to -c option */
144
145 char *curdir; // = nullstr; /* current working directory */
146 char *physdir; // = nullstr; /* physical working directory */
147
148 char *arg0; /* value of $0 */
149
150 struct jmploc *exception_handler;
Denis Vlasenko991a1da2008-02-10 19:02:53 +0000151
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200152 volatile int suppress_int; /* counter */
153 volatile /*sig_atomic_t*/ smallint pending_int; /* 1 = got SIGINT */
Denis Vlasenko991a1da2008-02-10 19:02:53 +0000154 /* last pending signal */
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200155 volatile /*sig_atomic_t*/ smallint pending_sig;
Denis Vlasenko7f88e342009-03-19 03:36:18 +0000156 smallint exception_type; /* kind of exception (0..5) */
Denis Vlasenko01631112007-12-16 17:20:38 +0000157 /* exceptions */
Eric Andersenc470f442003-07-28 09:56:35 +0000158#define EXINT 0 /* SIGINT received */
159#define EXERROR 1 /* a generic error */
160#define EXSHELLPROC 2 /* execute a shell procedure */
161#define EXEXEC 3 /* command execution failed */
162#define EXEXIT 4 /* exit the shell */
163#define EXSIG 5 /* trapped signal in wait(1) */
Eric Andersen2870d962001-07-02 17:27:21 +0000164
Denis Vlasenko01631112007-12-16 17:20:38 +0000165 smallint isloginsh;
Denis Vlasenkob07a4962008-06-22 13:16:23 +0000166 char nullstr[1]; /* zero length string */
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000167
168 char optlist[NOPTS];
169#define eflag optlist[0]
170#define fflag optlist[1]
171#define Iflag optlist[2]
172#define iflag optlist[3]
173#define mflag optlist[4]
174#define nflag optlist[5]
175#define sflag optlist[6]
176#define xflag optlist[7]
177#define vflag optlist[8]
178#define Cflag optlist[9]
179#define aflag optlist[10]
180#define bflag optlist[11]
181#define uflag optlist[12]
182#define viflag optlist[13]
Michael Abbott359da5e2009-12-04 23:03:29 +0100183#if ENABLE_ASH_BASH_COMPAT
184# define pipefail optlist[14]
185#else
186# define pipefail 0
187#endif
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000188#if DEBUG
Michael Abbott359da5e2009-12-04 23:03:29 +0100189# define nolog optlist[14 + ENABLE_ASH_BASH_COMPAT]
190# define debug optlist[15 + ENABLE_ASH_BASH_COMPAT]
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000191#endif
192
193 /* trap handler commands */
Denis Vlasenko01631112007-12-16 17:20:38 +0000194 /*
195 * Sigmode records the current value of the signal handlers for the various
196 * modes. A value of zero means that the current handler is not known.
Denis Vlasenkof8535cc2008-12-03 10:36:26 +0000197 * S_HARD_IGN indicates that the signal was ignored on entry to the shell.
Denis Vlasenko01631112007-12-16 17:20:38 +0000198 */
199 char sigmode[NSIG - 1];
Denis Vlasenkof8535cc2008-12-03 10:36:26 +0000200#define S_DFL 1 /* default signal handling (SIG_DFL) */
201#define S_CATCH 2 /* signal is caught */
202#define S_IGN 3 /* signal is ignored (SIG_IGN) */
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +0000203#define S_HARD_IGN 4 /* signal is ignored permenantly */
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +0000204
Denis Vlasenko01631112007-12-16 17:20:38 +0000205 /* indicates specified signal received */
Denis Vlasenko4b875702009-03-19 13:30:04 +0000206 uint8_t gotsig[NSIG - 1]; /* offset by 1: "signal" 0 is meaningless */
Denys Vlasenko238bf182010-05-18 15:49:07 +0200207 uint8_t may_have_traps; /* 0: definitely no traps are set, 1: some traps may be set */
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000208 char *trap[NSIG];
Denys Vlasenko21d87d42009-09-25 00:06:51 +0200209 char **trap_ptr; /* used only by "trap hack" */
Denis Vlasenko448d30e2008-06-27 00:24:11 +0000210
211 /* Rarely referenced stuff */
212#if ENABLE_ASH_RANDOM_SUPPORT
Denys Vlasenko3ea2e822009-10-09 20:59:04 +0200213 random_t random_gen;
Denis Vlasenko448d30e2008-06-27 00:24:11 +0000214#endif
215 pid_t backgndpid; /* pid of last background process */
216 smallint job_warning; /* user was warned about stopped jobs (can be 2, 1 or 0). */
Denis Vlasenko01631112007-12-16 17:20:38 +0000217};
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000218extern struct globals_misc *const ash_ptr_to_globals_misc;
219#define G_misc (*ash_ptr_to_globals_misc)
Denis Vlasenko26bc57d2008-06-27 00:29:34 +0000220#define rootpid (G_misc.rootpid )
221#define shlvl (G_misc.shlvl )
222#define minusc (G_misc.minusc )
223#define curdir (G_misc.curdir )
224#define physdir (G_misc.physdir )
225#define arg0 (G_misc.arg0 )
Denis Vlasenko01631112007-12-16 17:20:38 +0000226#define exception_handler (G_misc.exception_handler)
Denis Vlasenko7f88e342009-03-19 03:36:18 +0000227#define exception_type (G_misc.exception_type )
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200228#define suppress_int (G_misc.suppress_int )
229#define pending_int (G_misc.pending_int )
230#define pending_sig (G_misc.pending_sig )
Denis Vlasenko26bc57d2008-06-27 00:29:34 +0000231#define isloginsh (G_misc.isloginsh )
232#define nullstr (G_misc.nullstr )
233#define optlist (G_misc.optlist )
234#define sigmode (G_misc.sigmode )
235#define gotsig (G_misc.gotsig )
Denys Vlasenko238bf182010-05-18 15:49:07 +0200236#define may_have_traps (G_misc.may_have_traps )
Denis Vlasenko26bc57d2008-06-27 00:29:34 +0000237#define trap (G_misc.trap )
Denys Vlasenko21d87d42009-09-25 00:06:51 +0200238#define trap_ptr (G_misc.trap_ptr )
Denys Vlasenko3ea2e822009-10-09 20:59:04 +0200239#define random_gen (G_misc.random_gen )
Denis Vlasenko448d30e2008-06-27 00:24:11 +0000240#define backgndpid (G_misc.backgndpid )
241#define job_warning (G_misc.job_warning)
Denis Vlasenko01631112007-12-16 17:20:38 +0000242#define INIT_G_misc() do { \
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000243 (*(struct globals_misc**)&ash_ptr_to_globals_misc) = xzalloc(sizeof(G_misc)); \
244 barrier(); \
Denis Vlasenko01631112007-12-16 17:20:38 +0000245 curdir = nullstr; \
246 physdir = nullstr; \
Denys Vlasenko21d87d42009-09-25 00:06:51 +0200247 trap_ptr = trap; \
Denis Vlasenko01631112007-12-16 17:20:38 +0000248} while (0)
249
250
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000251/* ============ DEBUG */
252#if DEBUG
253static void trace_printf(const char *fmt, ...);
254static void trace_vprintf(const char *fmt, va_list va);
255# define TRACE(param) trace_printf param
256# define TRACEV(param) trace_vprintf param
Denis Vlasenko1bb3d7e2009-03-20 07:45:36 +0000257# define close(fd) do { \
258 int dfd = (fd); \
Denis Vlasenkob9e70dd2009-03-20 01:24:08 +0000259 if (close(dfd) < 0) \
Denys Vlasenko883cea42009-07-11 15:31:59 +0200260 bb_error_msg("bug on %d: closing %d(0x%x)", \
Denis Vlasenko1bb3d7e2009-03-20 07:45:36 +0000261 __LINE__, dfd, dfd); \
Denis Vlasenkob9e70dd2009-03-20 01:24:08 +0000262} while (0)
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000263#else
264# define TRACE(param)
265# define TRACEV(param)
266#endif
267
268
Denis Vlasenko559691a2008-10-05 18:39:31 +0000269/* ============ Utility functions */
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000270#define xbarrier() do { __asm__ __volatile__ ("": : :"memory"); } while (0)
271
Denis Vlasenko559691a2008-10-05 18:39:31 +0000272static int isdigit_str9(const char *str)
273{
274 int maxlen = 9 + 1; /* max 9 digits: 999999999 */
275 while (--maxlen && isdigit(*str))
276 str++;
277 return (*str == '\0');
278}
Denis Vlasenko01631112007-12-16 17:20:38 +0000279
Denys Vlasenko8837c5d2010-06-02 12:56:18 +0200280static const char *var_end(const char *var)
281{
282 while (*var)
283 if (*var++ == '=')
284 break;
285 return var;
286}
287
Denis Vlasenko559691a2008-10-05 18:39:31 +0000288
289/* ============ Interrupts / exceptions */
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +0000290/*
Eric Andersen2870d962001-07-02 17:27:21 +0000291 * These macros allow the user to suspend the handling of interrupt signals
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +0000292 * over a period of time. This is similar to SIGHOLD or to sigblock, but
Eric Andersen2870d962001-07-02 17:27:21 +0000293 * much more efficient and portable. (But hacking the kernel is so much
294 * more fun than worrying about efficiency and portability. :-))
295 */
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000296#define INT_OFF do { \
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200297 suppress_int++; \
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000298 xbarrier(); \
299} while (0)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000300
301/*
302 * Called to raise an exception. Since C doesn't include exceptions, we
303 * just do a longjmp to the exception handler. The type of exception is
Denis Vlasenko4b875702009-03-19 13:30:04 +0000304 * stored in the global variable "exception_type".
Denis Vlasenkob012b102007-02-19 22:43:01 +0000305 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +0000306static void raise_exception(int) NORETURN;
Denis Vlasenkob012b102007-02-19 22:43:01 +0000307static void
308raise_exception(int e)
309{
310#if DEBUG
Denis Vlasenko2da584f2007-02-19 22:44:05 +0000311 if (exception_handler == NULL)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000312 abort();
313#endif
314 INT_OFF;
Denis Vlasenko7f88e342009-03-19 03:36:18 +0000315 exception_type = e;
Denis Vlasenko2da584f2007-02-19 22:44:05 +0000316 longjmp(exception_handler->loc, 1);
Denis Vlasenkob012b102007-02-19 22:43:01 +0000317}
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000318#if DEBUG
319#define raise_exception(e) do { \
320 TRACE(("raising exception %d on line %d\n", (e), __LINE__)); \
321 raise_exception(e); \
322} while (0)
323#endif
Denis Vlasenkob012b102007-02-19 22:43:01 +0000324
325/*
326 * Called from trap.c when a SIGINT is received. (If the user specifies
327 * that SIGINT is to be trapped or ignored using the trap builtin, then
328 * this routine is not called.) Suppressint is nonzero when interrupts
329 * are held using the INT_OFF macro. (The test for iflag is just
330 * defensive programming.)
331 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +0000332static void raise_interrupt(void) NORETURN;
Denis Vlasenkob012b102007-02-19 22:43:01 +0000333static void
334raise_interrupt(void)
335{
Denis Vlasenko4b875702009-03-19 13:30:04 +0000336 int ex_type;
Denis Vlasenkob012b102007-02-19 22:43:01 +0000337
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200338 pending_int = 0;
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +0000339 /* Signal is not automatically unmasked after it is raised,
340 * do it ourself - unmask all signals */
Denis Vlasenko3f165fa2008-03-17 08:29:08 +0000341 sigprocmask_allsigs(SIG_UNBLOCK);
Denys Vlasenko238bf182010-05-18 15:49:07 +0200342 /* pending_sig = 0; - now done in signal_handler() */
Denis Vlasenko7c139b42007-03-21 20:17:27 +0000343
Denis Vlasenko4b875702009-03-19 13:30:04 +0000344 ex_type = EXSIG;
Denis Vlasenkob012b102007-02-19 22:43:01 +0000345 if (gotsig[SIGINT - 1] && !trap[SIGINT]) {
346 if (!(rootshell && iflag)) {
Denis Vlasenko991a1da2008-02-10 19:02:53 +0000347 /* Kill ourself with SIGINT */
Denis Vlasenkob012b102007-02-19 22:43:01 +0000348 signal(SIGINT, SIG_DFL);
349 raise(SIGINT);
350 }
Denis Vlasenko4b875702009-03-19 13:30:04 +0000351 ex_type = EXINT;
Denis Vlasenkob012b102007-02-19 22:43:01 +0000352 }
Denis Vlasenko4b875702009-03-19 13:30:04 +0000353 raise_exception(ex_type);
Denis Vlasenkob012b102007-02-19 22:43:01 +0000354 /* NOTREACHED */
355}
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000356#if DEBUG
357#define raise_interrupt() do { \
358 TRACE(("raising interrupt on line %d\n", __LINE__)); \
359 raise_interrupt(); \
360} while (0)
361#endif
Denis Vlasenkob012b102007-02-19 22:43:01 +0000362
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000363static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000364int_on(void)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000365{
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +0000366 xbarrier();
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200367 if (--suppress_int == 0 && pending_int) {
Denis Vlasenkob012b102007-02-19 22:43:01 +0000368 raise_interrupt();
369 }
370}
371#define INT_ON int_on()
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000372static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000373force_int_on(void)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000374{
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +0000375 xbarrier();
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200376 suppress_int = 0;
377 if (pending_int)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000378 raise_interrupt();
379}
380#define FORCE_INT_ON force_int_on()
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000381
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200382#define SAVE_INT(v) ((v) = suppress_int)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000383
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000384#define RESTORE_INT(v) do { \
385 xbarrier(); \
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200386 suppress_int = (v); \
387 if (suppress_int == 0 && pending_int) \
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000388 raise_interrupt(); \
389} while (0)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000390
Glenn L McGrath9fef17d2002-08-22 18:41:20 +0000391
Denis Vlasenkobc54cff2007-02-23 01:05:52 +0000392/* ============ Stdout/stderr output */
Eric Andersenc470f442003-07-28 09:56:35 +0000393
Eric Andersenc470f442003-07-28 09:56:35 +0000394static void
Denis Vlasenkob012b102007-02-19 22:43:01 +0000395outstr(const char *p, FILE *file)
Denis Vlasenkoe5570da2007-02-19 22:41:55 +0000396{
Denis Vlasenkob012b102007-02-19 22:43:01 +0000397 INT_OFF;
398 fputs(p, file);
399 INT_ON;
400}
401
402static void
403flush_stdout_stderr(void)
404{
405 INT_OFF;
Denys Vlasenko8131eea2009-11-02 14:19:51 +0100406 fflush_all();
Denis Vlasenkob012b102007-02-19 22:43:01 +0000407 INT_ON;
408}
409
410static void
411outcslow(int c, FILE *dest)
412{
413 INT_OFF;
414 putc(c, dest);
415 fflush(dest);
416 INT_ON;
417}
418
419static int out1fmt(const char *, ...) __attribute__((__format__(__printf__,1,2)));
420static int
421out1fmt(const char *fmt, ...)
422{
423 va_list ap;
424 int r;
425
426 INT_OFF;
427 va_start(ap, fmt);
428 r = vprintf(fmt, ap);
429 va_end(ap);
430 INT_ON;
431 return r;
432}
433
434static int fmtstr(char *, size_t, const char *, ...) __attribute__((__format__(__printf__,3,4)));
435static int
436fmtstr(char *outbuf, size_t length, const char *fmt, ...)
437{
438 va_list ap;
439 int ret;
440
441 va_start(ap, fmt);
442 INT_OFF;
443 ret = vsnprintf(outbuf, length, fmt, ap);
444 va_end(ap);
445 INT_ON;
446 return ret;
447}
448
449static void
450out1str(const char *p)
451{
452 outstr(p, stdout);
453}
454
455static void
456out2str(const char *p)
457{
458 outstr(p, stderr);
Denys Vlasenko8131eea2009-11-02 14:19:51 +0100459 flush_stdout_stderr();
Denis Vlasenkob012b102007-02-19 22:43:01 +0000460}
461
462
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +0000463/* ============ Parser structures */
Denis Vlasenko4d2183b2007-02-23 01:05:38 +0000464
Denis Vlasenko5651bfc2007-02-23 21:08:58 +0000465/* control characters in argument strings */
Denys Vlasenko2ce42e92009-11-29 02:18:13 +0100466#define CTL_FIRST CTLESC
Denys Vlasenkob6c84342009-08-29 20:23:20 +0200467#define CTLESC ((unsigned char)'\201') /* escape next character */
468#define CTLVAR ((unsigned char)'\202') /* variable defn */
469#define CTLENDVAR ((unsigned char)'\203')
470#define CTLBACKQ ((unsigned char)'\204')
Denis Vlasenko5651bfc2007-02-23 21:08:58 +0000471#define CTLQUOTE 01 /* ored with CTLBACKQ code if in quotes */
472/* CTLBACKQ | CTLQUOTE == '\205' */
Denys Vlasenkob6c84342009-08-29 20:23:20 +0200473#define CTLARI ((unsigned char)'\206') /* arithmetic expression */
474#define CTLENDARI ((unsigned char)'\207')
475#define CTLQUOTEMARK ((unsigned char)'\210')
Denys Vlasenko2ce42e92009-11-29 02:18:13 +0100476#define CTL_LAST CTLQUOTEMARK
Denis Vlasenko5651bfc2007-02-23 21:08:58 +0000477
478/* variable substitution byte (follows CTLVAR) */
479#define VSTYPE 0x0f /* type of variable substitution */
480#define VSNUL 0x10 /* colon--treat the empty string as unset */
481#define VSQUOTE 0x80 /* inside double quotes--suppress splitting */
482
483/* values of VSTYPE field */
Denis Vlasenko92e13c22008-03-25 01:17:40 +0000484#define VSNORMAL 0x1 /* normal variable: $var or ${var} */
485#define VSMINUS 0x2 /* ${var-text} */
486#define VSPLUS 0x3 /* ${var+text} */
487#define VSQUESTION 0x4 /* ${var?message} */
488#define VSASSIGN 0x5 /* ${var=text} */
489#define VSTRIMRIGHT 0x6 /* ${var%pattern} */
490#define VSTRIMRIGHTMAX 0x7 /* ${var%%pattern} */
491#define VSTRIMLEFT 0x8 /* ${var#pattern} */
492#define VSTRIMLEFTMAX 0x9 /* ${var##pattern} */
493#define VSLENGTH 0xa /* ${#var} */
494#if ENABLE_ASH_BASH_COMPAT
495#define VSSUBSTR 0xc /* ${var:position:length} */
496#define VSREPLACE 0xd /* ${var/pattern/replacement} */
497#define VSREPLACEALL 0xe /* ${var//pattern/replacement} */
498#endif
Denis Vlasenko5651bfc2007-02-23 21:08:58 +0000499
Denis Vlasenko6ca409e2007-08-12 20:58:27 +0000500static const char dolatstr[] ALIGN1 = {
501 CTLVAR, VSNORMAL|VSQUOTE, '@', '=', '\0'
502};
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +0000503
Denis Vlasenko559691a2008-10-05 18:39:31 +0000504#define NCMD 0
505#define NPIPE 1
506#define NREDIR 2
507#define NBACKGND 3
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000508#define NSUBSHELL 4
Denis Vlasenko559691a2008-10-05 18:39:31 +0000509#define NAND 5
510#define NOR 6
511#define NSEMI 7
512#define NIF 8
513#define NWHILE 9
514#define NUNTIL 10
515#define NFOR 11
516#define NCASE 12
517#define NCLIST 13
518#define NDEFUN 14
519#define NARG 15
520#define NTO 16
521#if ENABLE_ASH_BASH_COMPAT
522#define NTO2 17
523#endif
524#define NCLOBBER 18
525#define NFROM 19
526#define NFROMTO 20
527#define NAPPEND 21
528#define NTOFD 22
529#define NFROMFD 23
530#define NHERE 24
531#define NXHERE 25
532#define NNOT 26
Denis Vlasenko340299a2008-11-21 10:36:36 +0000533#define N_NUMBER 27
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000534
535union node;
536
537struct ncmd {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000538 smallint type; /* Nxxxx */
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000539 union node *assign;
540 union node *args;
541 union node *redirect;
542};
543
544struct npipe {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000545 smallint type;
546 smallint pipe_backgnd;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000547 struct nodelist *cmdlist;
548};
549
550struct nredir {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000551 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000552 union node *n;
553 union node *redirect;
554};
555
556struct nbinary {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000557 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000558 union node *ch1;
559 union node *ch2;
560};
561
562struct nif {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000563 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000564 union node *test;
565 union node *ifpart;
566 union node *elsepart;
567};
568
569struct nfor {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000570 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000571 union node *args;
572 union node *body;
573 char *var;
574};
575
576struct ncase {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000577 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000578 union node *expr;
579 union node *cases;
580};
581
582struct nclist {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000583 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000584 union node *next;
585 union node *pattern;
586 union node *body;
587};
588
589struct narg {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000590 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000591 union node *next;
592 char *text;
593 struct nodelist *backquote;
594};
595
Denis Vlasenko559691a2008-10-05 18:39:31 +0000596/* nfile and ndup layout must match!
597 * NTOFD (>&fdnum) uses ndup structure, but we may discover mid-flight
598 * that it is actually NTO2 (>&file), and change its type.
599 */
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000600struct nfile {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000601 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000602 union node *next;
603 int fd;
Denis Vlasenko559691a2008-10-05 18:39:31 +0000604 int _unused_dupfd;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000605 union node *fname;
606 char *expfname;
607};
608
609struct ndup {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000610 smallint type;
Denis Vlasenko559691a2008-10-05 18:39:31 +0000611 union node *next;
612 int fd;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000613 int dupfd;
614 union node *vname;
Denis Vlasenko559691a2008-10-05 18:39:31 +0000615 char *_unused_expfname;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000616};
617
618struct nhere {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000619 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000620 union node *next;
621 int fd;
622 union node *doc;
623};
624
625struct nnot {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000626 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000627 union node *com;
628};
629
630union node {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000631 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000632 struct ncmd ncmd;
633 struct npipe npipe;
634 struct nredir nredir;
635 struct nbinary nbinary;
636 struct nif nif;
637 struct nfor nfor;
638 struct ncase ncase;
639 struct nclist nclist;
640 struct narg narg;
641 struct nfile nfile;
642 struct ndup ndup;
643 struct nhere nhere;
644 struct nnot nnot;
645};
646
Denys Vlasenko86e83ec2009-07-23 22:07:07 +0200647/*
648 * NODE_EOF is returned by parsecmd when it encounters an end of file.
649 * It must be distinct from NULL.
650 */
651#define NODE_EOF ((union node *) -1L)
652
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000653struct nodelist {
654 struct nodelist *next;
655 union node *n;
656};
657
658struct funcnode {
659 int count;
660 union node n;
661};
662
Denis Vlasenko5651bfc2007-02-23 21:08:58 +0000663/*
664 * Free a parse tree.
665 */
666static void
667freefunc(struct funcnode *f)
668{
669 if (f && --f->count < 0)
670 free(f);
671}
672
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000673
674/* ============ Debugging output */
675
676#if DEBUG
677
678static FILE *tracefile;
679
680static void
681trace_printf(const char *fmt, ...)
682{
683 va_list va;
684
685 if (debug != 1)
686 return;
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000687 if (DEBUG_TIME)
688 fprintf(tracefile, "%u ", (int) time(NULL));
689 if (DEBUG_PID)
690 fprintf(tracefile, "[%u] ", (int) getpid());
691 if (DEBUG_SIG)
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200692 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000693 va_start(va, fmt);
694 vfprintf(tracefile, fmt, va);
695 va_end(va);
696}
697
698static void
699trace_vprintf(const char *fmt, va_list va)
700{
701 if (debug != 1)
702 return;
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000703 if (DEBUG_TIME)
704 fprintf(tracefile, "%u ", (int) time(NULL));
705 if (DEBUG_PID)
706 fprintf(tracefile, "[%u] ", (int) getpid());
707 if (DEBUG_SIG)
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200708 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000709 vfprintf(tracefile, fmt, va);
710}
711
712static void
713trace_puts(const char *s)
714{
715 if (debug != 1)
716 return;
717 fputs(s, tracefile);
718}
719
720static void
721trace_puts_quoted(char *s)
722{
723 char *p;
724 char c;
725
726 if (debug != 1)
727 return;
728 putc('"', tracefile);
729 for (p = s; *p; p++) {
Denys Vlasenkocd716832009-11-28 22:14:02 +0100730 switch ((unsigned char)*p) {
731 case '\n': c = 'n'; goto backslash;
732 case '\t': c = 't'; goto backslash;
733 case '\r': c = 'r'; goto backslash;
734 case '\"': c = '\"'; goto backslash;
735 case '\\': c = '\\'; goto backslash;
736 case CTLESC: c = 'e'; goto backslash;
737 case CTLVAR: c = 'v'; goto backslash;
738 case CTLVAR+CTLQUOTE: c = 'V'; goto backslash;
739 case CTLBACKQ: c = 'q'; goto backslash;
740 case CTLBACKQ+CTLQUOTE: c = 'Q'; goto backslash;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000741 backslash:
742 putc('\\', tracefile);
743 putc(c, tracefile);
744 break;
745 default:
746 if (*p >= ' ' && *p <= '~')
747 putc(*p, tracefile);
748 else {
749 putc('\\', tracefile);
Denys Vlasenkocd716832009-11-28 22:14:02 +0100750 putc((*p >> 6) & 03, tracefile);
751 putc((*p >> 3) & 07, tracefile);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000752 putc(*p & 07, tracefile);
753 }
754 break;
755 }
756 }
757 putc('"', tracefile);
758}
759
760static void
761trace_puts_args(char **ap)
762{
763 if (debug != 1)
764 return;
765 if (!*ap)
766 return;
767 while (1) {
768 trace_puts_quoted(*ap);
769 if (!*++ap) {
770 putc('\n', tracefile);
771 break;
772 }
773 putc(' ', tracefile);
774 }
775}
776
777static void
778opentrace(void)
779{
780 char s[100];
781#ifdef O_APPEND
782 int flags;
783#endif
784
785 if (debug != 1) {
786 if (tracefile)
787 fflush(tracefile);
788 /* leave open because libedit might be using it */
789 return;
790 }
791 strcpy(s, "./trace");
792 if (tracefile) {
793 if (!freopen(s, "a", tracefile)) {
794 fprintf(stderr, "Can't re-open %s\n", s);
795 debug = 0;
796 return;
797 }
798 } else {
799 tracefile = fopen(s, "a");
800 if (tracefile == NULL) {
801 fprintf(stderr, "Can't open %s\n", s);
802 debug = 0;
803 return;
804 }
805 }
806#ifdef O_APPEND
Denis Vlasenkod37f2222007-08-19 13:42:08 +0000807 flags = fcntl(fileno(tracefile), F_GETFL);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000808 if (flags >= 0)
809 fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
810#endif
811 setlinebuf(tracefile);
812 fputs("\nTracing started.\n", tracefile);
813}
814
815static void
816indent(int amount, char *pfx, FILE *fp)
817{
818 int i;
819
820 for (i = 0; i < amount; i++) {
821 if (pfx && i == amount - 1)
822 fputs(pfx, fp);
823 putc('\t', fp);
824 }
825}
826
827/* little circular references here... */
828static void shtree(union node *n, int ind, char *pfx, FILE *fp);
829
830static void
831sharg(union node *arg, FILE *fp)
832{
833 char *p;
834 struct nodelist *bqlist;
Denys Vlasenkocd716832009-11-28 22:14:02 +0100835 unsigned char subtype;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000836
837 if (arg->type != NARG) {
838 out1fmt("<node type %d>\n", arg->type);
839 abort();
840 }
841 bqlist = arg->narg.backquote;
842 for (p = arg->narg.text; *p; p++) {
Denys Vlasenkocd716832009-11-28 22:14:02 +0100843 switch ((unsigned char)*p) {
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000844 case CTLESC:
845 putc(*++p, fp);
846 break;
847 case CTLVAR:
848 putc('$', fp);
849 putc('{', fp);
850 subtype = *++p;
851 if (subtype == VSLENGTH)
852 putc('#', fp);
853
854 while (*p != '=')
855 putc(*p++, fp);
856
857 if (subtype & VSNUL)
858 putc(':', fp);
859
860 switch (subtype & VSTYPE) {
861 case VSNORMAL:
862 putc('}', fp);
863 break;
864 case VSMINUS:
865 putc('-', fp);
866 break;
867 case VSPLUS:
868 putc('+', fp);
869 break;
870 case VSQUESTION:
871 putc('?', fp);
872 break;
873 case VSASSIGN:
874 putc('=', fp);
875 break;
876 case VSTRIMLEFT:
877 putc('#', fp);
878 break;
879 case VSTRIMLEFTMAX:
880 putc('#', fp);
881 putc('#', fp);
882 break;
883 case VSTRIMRIGHT:
884 putc('%', fp);
885 break;
886 case VSTRIMRIGHTMAX:
887 putc('%', fp);
888 putc('%', fp);
889 break;
890 case VSLENGTH:
891 break;
892 default:
893 out1fmt("<subtype %d>", subtype);
894 }
895 break;
896 case CTLENDVAR:
897 putc('}', fp);
898 break;
899 case CTLBACKQ:
900 case CTLBACKQ|CTLQUOTE:
901 putc('$', fp);
902 putc('(', fp);
903 shtree(bqlist->n, -1, NULL, fp);
904 putc(')', fp);
905 break;
906 default:
907 putc(*p, fp);
908 break;
909 }
910 }
911}
912
Denys Vlasenko641dd7b2009-06-11 19:30:19 +0200913static void
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000914shcmd(union node *cmd, FILE *fp)
915{
916 union node *np;
917 int first;
918 const char *s;
919 int dftfd;
920
921 first = 1;
922 for (np = cmd->ncmd.args; np; np = np->narg.next) {
Denis Vlasenko40ba9982007-07-14 00:48:29 +0000923 if (!first)
924 putc(' ', fp);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000925 sharg(np, fp);
926 first = 0;
927 }
928 for (np = cmd->ncmd.redirect; np; np = np->nfile.next) {
Denis Vlasenko40ba9982007-07-14 00:48:29 +0000929 if (!first)
930 putc(' ', fp);
931 dftfd = 0;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000932 switch (np->nfile.type) {
Denis Vlasenko40ba9982007-07-14 00:48:29 +0000933 case NTO: s = ">>"+1; dftfd = 1; break;
934 case NCLOBBER: s = ">|"; dftfd = 1; break;
935 case NAPPEND: s = ">>"; dftfd = 1; break;
Denis Vlasenko559691a2008-10-05 18:39:31 +0000936#if ENABLE_ASH_BASH_COMPAT
937 case NTO2:
938#endif
Denis Vlasenko40ba9982007-07-14 00:48:29 +0000939 case NTOFD: s = ">&"; dftfd = 1; break;
Denis Vlasenko559691a2008-10-05 18:39:31 +0000940 case NFROM: s = "<"; break;
Denis Vlasenko40ba9982007-07-14 00:48:29 +0000941 case NFROMFD: s = "<&"; break;
942 case NFROMTO: s = "<>"; break;
943 default: s = "*error*"; break;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000944 }
945 if (np->nfile.fd != dftfd)
946 fprintf(fp, "%d", np->nfile.fd);
947 fputs(s, fp);
948 if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
949 fprintf(fp, "%d", np->ndup.dupfd);
950 } else {
951 sharg(np->nfile.fname, fp);
952 }
953 first = 0;
954 }
955}
956
957static void
958shtree(union node *n, int ind, char *pfx, FILE *fp)
959{
960 struct nodelist *lp;
961 const char *s;
962
963 if (n == NULL)
964 return;
965
966 indent(ind, pfx, fp);
Denys Vlasenko86e83ec2009-07-23 22:07:07 +0200967
968 if (n == NODE_EOF) {
969 fputs("<EOF>", fp);
970 return;
971 }
972
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000973 switch (n->type) {
974 case NSEMI:
975 s = "; ";
976 goto binop;
977 case NAND:
978 s = " && ";
979 goto binop;
980 case NOR:
981 s = " || ";
982 binop:
983 shtree(n->nbinary.ch1, ind, NULL, fp);
984 /* if (ind < 0) */
985 fputs(s, fp);
986 shtree(n->nbinary.ch2, ind, NULL, fp);
987 break;
988 case NCMD:
989 shcmd(n, fp);
990 if (ind >= 0)
991 putc('\n', fp);
992 break;
993 case NPIPE:
994 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
Denys Vlasenko7cee00e2009-07-24 01:08:03 +0200995 shtree(lp->n, 0, NULL, fp);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000996 if (lp->next)
997 fputs(" | ", fp);
998 }
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000999 if (n->npipe.pipe_backgnd)
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00001000 fputs(" &", fp);
1001 if (ind >= 0)
1002 putc('\n', fp);
1003 break;
1004 default:
1005 fprintf(fp, "<node type %d>", n->type);
1006 if (ind >= 0)
1007 putc('\n', fp);
1008 break;
1009 }
1010}
1011
1012static void
1013showtree(union node *n)
1014{
1015 trace_puts("showtree called\n");
Denys Vlasenko883cea42009-07-11 15:31:59 +02001016 shtree(n, 1, NULL, stderr);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00001017}
1018
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00001019#endif /* DEBUG */
1020
1021
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00001022/* ============ Parser data */
1023
1024/*
Denis Vlasenkob012b102007-02-19 22:43:01 +00001025 * ash_vmsg() needs parsefile->fd, hence parsefile definition is moved up.
1026 */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001027struct strlist {
1028 struct strlist *next;
1029 char *text;
1030};
1031
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00001032struct alias;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00001033
Denis Vlasenkob012b102007-02-19 22:43:01 +00001034struct strpush {
1035 struct strpush *prev; /* preceding string on stack */
Denis Vlasenko41eb3002008-11-28 03:42:31 +00001036 char *prev_string;
1037 int prev_left_in_line;
Denis Vlasenkob012b102007-02-19 22:43:01 +00001038#if ENABLE_ASH_ALIAS
1039 struct alias *ap; /* if push was associated with an alias */
1040#endif
1041 char *string; /* remember the string since it may change */
1042};
1043
1044struct parsefile {
1045 struct parsefile *prev; /* preceding file on stack */
1046 int linno; /* current line */
1047 int fd; /* file descriptor (or -1 if string) */
Denis Vlasenko41eb3002008-11-28 03:42:31 +00001048 int left_in_line; /* number of chars left in this line */
1049 int left_in_buffer; /* number of chars left in this buffer past the line */
1050 char *next_to_pgetc; /* next char in buffer */
Denis Vlasenkob012b102007-02-19 22:43:01 +00001051 char *buf; /* input buffer */
1052 struct strpush *strpush; /* for pushing strings at this level */
1053 struct strpush basestrpush; /* so pushing one is fast */
1054};
1055
Denis Vlasenko448d30e2008-06-27 00:24:11 +00001056static struct parsefile basepf; /* top level input file */
Denis Vlasenkob07a4962008-06-22 13:16:23 +00001057static struct parsefile *g_parsefile = &basepf; /* current input file */
Denis Vlasenkob012b102007-02-19 22:43:01 +00001058static int startlinno; /* line # where last token started */
1059static char *commandname; /* currently executing command */
1060static struct strlist *cmdenviron; /* environment for builtin command */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00001061static uint8_t exitstatus; /* exit status of last command */
Denis Vlasenkob012b102007-02-19 22:43:01 +00001062
1063
1064/* ============ Message printing */
1065
1066static void
1067ash_vmsg(const char *msg, va_list ap)
1068{
1069 fprintf(stderr, "%s: ", arg0);
1070 if (commandname) {
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00001071 if (strcmp(arg0, commandname))
1072 fprintf(stderr, "%s: ", commandname);
Denis Vlasenkob07a4962008-06-22 13:16:23 +00001073 if (!iflag || g_parsefile->fd)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00001074 fprintf(stderr, "line %d: ", startlinno);
Eric Andersenc470f442003-07-28 09:56:35 +00001075 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00001076 vfprintf(stderr, msg, ap);
1077 outcslow('\n', stderr);
Eric Andersenc470f442003-07-28 09:56:35 +00001078}
Denis Vlasenkob012b102007-02-19 22:43:01 +00001079
1080/*
1081 * Exverror is called to raise the error exception. If the second argument
1082 * is not NULL then error prints an error message using printf style
1083 * formatting. It then raises the error exception.
1084 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001085static void ash_vmsg_and_raise(int, const char *, va_list) NORETURN;
Denis Vlasenkob012b102007-02-19 22:43:01 +00001086static void
1087ash_vmsg_and_raise(int cond, const char *msg, va_list ap)
Eric Andersenc470f442003-07-28 09:56:35 +00001088{
Denis Vlasenkob012b102007-02-19 22:43:01 +00001089#if DEBUG
1090 if (msg) {
1091 TRACE(("ash_vmsg_and_raise(%d, \"", cond));
1092 TRACEV((msg, ap));
1093 TRACE(("\") pid=%d\n", getpid()));
1094 } else
1095 TRACE(("ash_vmsg_and_raise(%d, NULL) pid=%d\n", cond, getpid()));
1096 if (msg)
1097#endif
1098 ash_vmsg(msg, ap);
1099
1100 flush_stdout_stderr();
1101 raise_exception(cond);
1102 /* NOTREACHED */
Eric Andersenc470f442003-07-28 09:56:35 +00001103}
Denis Vlasenkob012b102007-02-19 22:43:01 +00001104
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001105static void ash_msg_and_raise_error(const char *, ...) NORETURN;
Denis Vlasenkob012b102007-02-19 22:43:01 +00001106static void
1107ash_msg_and_raise_error(const char *msg, ...)
1108{
1109 va_list ap;
1110
1111 va_start(ap, msg);
1112 ash_vmsg_and_raise(EXERROR, msg, ap);
1113 /* NOTREACHED */
1114 va_end(ap);
1115}
1116
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00001117static void raise_error_syntax(const char *) NORETURN;
1118static void
1119raise_error_syntax(const char *msg)
1120{
1121 ash_msg_and_raise_error("syntax error: %s", msg);
1122 /* NOTREACHED */
1123}
1124
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001125static void ash_msg_and_raise(int, const char *, ...) NORETURN;
Denis Vlasenkob012b102007-02-19 22:43:01 +00001126static void
1127ash_msg_and_raise(int cond, const char *msg, ...)
1128{
1129 va_list ap;
1130
1131 va_start(ap, msg);
1132 ash_vmsg_and_raise(cond, msg, ap);
1133 /* NOTREACHED */
1134 va_end(ap);
1135}
1136
1137/*
1138 * error/warning routines for external builtins
1139 */
1140static void
1141ash_msg(const char *fmt, ...)
1142{
1143 va_list ap;
1144
1145 va_start(ap, fmt);
1146 ash_vmsg(fmt, ap);
1147 va_end(ap);
1148}
1149
1150/*
1151 * Return a string describing an error. The returned string may be a
1152 * pointer to a static buffer that will be overwritten on the next call.
1153 * Action describes the operation that got the error.
1154 */
1155static const char *
1156errmsg(int e, const char *em)
1157{
1158 if (e == ENOENT || e == ENOTDIR) {
1159 return em;
1160 }
1161 return strerror(e);
1162}
1163
1164
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001165/* ============ Memory allocation */
1166
Denys Vlasenkoe7670ff2009-10-11 00:45:25 +02001167#if 0
1168/* I consider these wrappers nearly useless:
1169 * ok, they return you to nearest exception handler, but
1170 * how much memory do you leak in the process, making
1171 * memory starvation worse?
1172 */
1173static void *
1174ckrealloc(void * p, size_t nbytes)
1175{
1176 p = realloc(p, nbytes);
1177 if (!p)
1178 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1179 return p;
1180}
1181
1182static void *
1183ckmalloc(size_t nbytes)
1184{
1185 return ckrealloc(NULL, nbytes);
1186}
1187
1188static void *
1189ckzalloc(size_t nbytes)
1190{
1191 return memset(ckmalloc(nbytes), 0, nbytes);
1192}
1193
1194static char *
1195ckstrdup(const char *s)
1196{
1197 char *p = strdup(s);
1198 if (!p)
1199 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1200 return p;
1201}
1202#else
1203/* Using bbox equivalents. They exit if out of memory */
1204# define ckrealloc xrealloc
1205# define ckmalloc xmalloc
1206# define ckzalloc xzalloc
1207# define ckstrdup xstrdup
1208#endif
1209
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001210/*
1211 * It appears that grabstackstr() will barf with such alignments
1212 * because stalloc() will return a string allocated in a new stackblock.
1213 */
1214#define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
1215enum {
1216 /* Most machines require the value returned from malloc to be aligned
1217 * in some way. The following macro will get this right
1218 * on many machines. */
Denys Vlasenko0e5e4ea2009-10-11 00:36:20 +02001219 SHELL_SIZE = sizeof(union { int i; char *cp; double d; }) - 1,
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001220 /* Minimum size of a block */
Denis Vlasenko01631112007-12-16 17:20:38 +00001221 MINSIZE = SHELL_ALIGN(504),
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001222};
1223
1224struct stack_block {
1225 struct stack_block *prev;
1226 char space[MINSIZE];
1227};
1228
1229struct stackmark {
1230 struct stack_block *stackp;
1231 char *stacknxt;
1232 size_t stacknleft;
1233 struct stackmark *marknext;
1234};
1235
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001236
Denis Vlasenko01631112007-12-16 17:20:38 +00001237struct globals_memstack {
1238 struct stack_block *g_stackp; // = &stackbase;
1239 struct stackmark *markp;
1240 char *g_stacknxt; // = stackbase.space;
1241 char *sstrend; // = stackbase.space + MINSIZE;
1242 size_t g_stacknleft; // = MINSIZE;
1243 int herefd; // = -1;
1244 struct stack_block stackbase;
1245};
Denis Vlasenko574f2f42008-02-27 18:41:59 +00001246extern struct globals_memstack *const ash_ptr_to_globals_memstack;
1247#define G_memstack (*ash_ptr_to_globals_memstack)
Denis Vlasenko01631112007-12-16 17:20:38 +00001248#define g_stackp (G_memstack.g_stackp )
1249#define markp (G_memstack.markp )
1250#define g_stacknxt (G_memstack.g_stacknxt )
1251#define sstrend (G_memstack.sstrend )
1252#define g_stacknleft (G_memstack.g_stacknleft)
1253#define herefd (G_memstack.herefd )
1254#define stackbase (G_memstack.stackbase )
1255#define INIT_G_memstack() do { \
Denis Vlasenko574f2f42008-02-27 18:41:59 +00001256 (*(struct globals_memstack**)&ash_ptr_to_globals_memstack) = xzalloc(sizeof(G_memstack)); \
1257 barrier(); \
Denis Vlasenko01631112007-12-16 17:20:38 +00001258 g_stackp = &stackbase; \
1259 g_stacknxt = stackbase.space; \
1260 g_stacknleft = MINSIZE; \
1261 sstrend = stackbase.space + MINSIZE; \
1262 herefd = -1; \
1263} while (0)
1264
Denys Vlasenkoe7670ff2009-10-11 00:45:25 +02001265
Denis Vlasenko01631112007-12-16 17:20:38 +00001266#define stackblock() ((void *)g_stacknxt)
1267#define stackblocksize() g_stacknleft
1268
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001269/*
1270 * Parse trees for commands are allocated in lifo order, so we use a stack
1271 * to make this more efficient, and also to avoid all sorts of exception
1272 * handling code to handle interrupts in the middle of a parse.
1273 *
1274 * The size 504 was chosen because the Ultrix malloc handles that size
1275 * well.
1276 */
1277static void *
1278stalloc(size_t nbytes)
1279{
1280 char *p;
1281 size_t aligned;
1282
1283 aligned = SHELL_ALIGN(nbytes);
Denis Vlasenko01631112007-12-16 17:20:38 +00001284 if (aligned > g_stacknleft) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001285 size_t len;
1286 size_t blocksize;
1287 struct stack_block *sp;
1288
1289 blocksize = aligned;
1290 if (blocksize < MINSIZE)
1291 blocksize = MINSIZE;
1292 len = sizeof(struct stack_block) - MINSIZE + blocksize;
1293 if (len < blocksize)
1294 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1295 INT_OFF;
1296 sp = ckmalloc(len);
Denis Vlasenko01631112007-12-16 17:20:38 +00001297 sp->prev = g_stackp;
1298 g_stacknxt = sp->space;
1299 g_stacknleft = blocksize;
1300 sstrend = g_stacknxt + blocksize;
1301 g_stackp = sp;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001302 INT_ON;
1303 }
Denis Vlasenko01631112007-12-16 17:20:38 +00001304 p = g_stacknxt;
1305 g_stacknxt += aligned;
1306 g_stacknleft -= aligned;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001307 return p;
1308}
1309
Denis Vlasenko597906c2008-02-20 16:38:54 +00001310static void *
1311stzalloc(size_t nbytes)
1312{
1313 return memset(stalloc(nbytes), 0, nbytes);
1314}
1315
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001316static void
1317stunalloc(void *p)
1318{
1319#if DEBUG
Denis Vlasenko01631112007-12-16 17:20:38 +00001320 if (!p || (g_stacknxt < (char *)p) || ((char *)p < g_stackp->space)) {
Bernhard Reutner-Fischer5e25ddb2008-05-19 09:48:17 +00001321 write(STDERR_FILENO, "stunalloc\n", 10);
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001322 abort();
1323 }
1324#endif
Denis Vlasenko01631112007-12-16 17:20:38 +00001325 g_stacknleft += g_stacknxt - (char *)p;
1326 g_stacknxt = p;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001327}
1328
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001329/*
1330 * Like strdup but works with the ash stack.
1331 */
1332static char *
1333ststrdup(const char *p)
1334{
1335 size_t len = strlen(p) + 1;
1336 return memcpy(stalloc(len), p, len);
1337}
1338
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001339static void
1340setstackmark(struct stackmark *mark)
1341{
Denis Vlasenko01631112007-12-16 17:20:38 +00001342 mark->stackp = g_stackp;
1343 mark->stacknxt = g_stacknxt;
1344 mark->stacknleft = g_stacknleft;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001345 mark->marknext = markp;
1346 markp = mark;
1347}
1348
1349static void
1350popstackmark(struct stackmark *mark)
1351{
1352 struct stack_block *sp;
1353
Denis Vlasenko93ebd4f2007-03-13 20:55:36 +00001354 if (!mark->stackp)
1355 return;
1356
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001357 INT_OFF;
1358 markp = mark->marknext;
Denis Vlasenko01631112007-12-16 17:20:38 +00001359 while (g_stackp != mark->stackp) {
1360 sp = g_stackp;
1361 g_stackp = sp->prev;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001362 free(sp);
1363 }
Denis Vlasenko01631112007-12-16 17:20:38 +00001364 g_stacknxt = mark->stacknxt;
1365 g_stacknleft = mark->stacknleft;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001366 sstrend = mark->stacknxt + mark->stacknleft;
1367 INT_ON;
1368}
1369
1370/*
1371 * When the parser reads in a string, it wants to stick the string on the
1372 * stack and only adjust the stack pointer when it knows how big the
1373 * string is. Stackblock (defined in stack.h) returns a pointer to a block
1374 * of space on top of the stack and stackblocklen returns the length of
1375 * this block. Growstackblock will grow this space by at least one byte,
1376 * possibly moving it (like realloc). Grabstackblock actually allocates the
1377 * part of the block that has been used.
1378 */
1379static void
1380growstackblock(void)
1381{
1382 size_t newlen;
1383
Denis Vlasenko01631112007-12-16 17:20:38 +00001384 newlen = g_stacknleft * 2;
1385 if (newlen < g_stacknleft)
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001386 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1387 if (newlen < 128)
1388 newlen += 128;
1389
Denis Vlasenko01631112007-12-16 17:20:38 +00001390 if (g_stacknxt == g_stackp->space && g_stackp != &stackbase) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001391 struct stack_block *oldstackp;
1392 struct stackmark *xmark;
1393 struct stack_block *sp;
1394 struct stack_block *prevstackp;
1395 size_t grosslen;
1396
1397 INT_OFF;
Denis Vlasenko01631112007-12-16 17:20:38 +00001398 oldstackp = g_stackp;
1399 sp = g_stackp;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001400 prevstackp = sp->prev;
1401 grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
1402 sp = ckrealloc(sp, grosslen);
1403 sp->prev = prevstackp;
Denis Vlasenko01631112007-12-16 17:20:38 +00001404 g_stackp = sp;
1405 g_stacknxt = sp->space;
1406 g_stacknleft = newlen;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001407 sstrend = sp->space + newlen;
1408
1409 /*
1410 * Stack marks pointing to the start of the old block
1411 * must be relocated to point to the new block
1412 */
1413 xmark = markp;
1414 while (xmark != NULL && xmark->stackp == oldstackp) {
Denis Vlasenko01631112007-12-16 17:20:38 +00001415 xmark->stackp = g_stackp;
1416 xmark->stacknxt = g_stacknxt;
1417 xmark->stacknleft = g_stacknleft;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001418 xmark = xmark->marknext;
1419 }
1420 INT_ON;
1421 } else {
Denis Vlasenko01631112007-12-16 17:20:38 +00001422 char *oldspace = g_stacknxt;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00001423 size_t oldlen = g_stacknleft;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001424 char *p = stalloc(newlen);
1425
1426 /* free the space we just allocated */
Denis Vlasenko01631112007-12-16 17:20:38 +00001427 g_stacknxt = memcpy(p, oldspace, oldlen);
1428 g_stacknleft += newlen;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001429 }
1430}
1431
1432static void
1433grabstackblock(size_t len)
1434{
1435 len = SHELL_ALIGN(len);
Denis Vlasenko01631112007-12-16 17:20:38 +00001436 g_stacknxt += len;
1437 g_stacknleft -= len;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001438}
1439
1440/*
1441 * The following routines are somewhat easier to use than the above.
1442 * The user declares a variable of type STACKSTR, which may be declared
1443 * to be a register. The macro STARTSTACKSTR initializes things. Then
1444 * the user uses the macro STPUTC to add characters to the string. In
1445 * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
1446 * grown as necessary. When the user is done, she can just leave the
1447 * string there and refer to it using stackblock(). Or she can allocate
1448 * the space for it using grabstackstr(). If it is necessary to allow
1449 * someone else to use the stack temporarily and then continue to grow
1450 * the string, the user should use grabstack to allocate the space, and
1451 * then call ungrabstr(p) to return to the previous mode of operation.
1452 *
1453 * USTPUTC is like STPUTC except that it doesn't check for overflow.
1454 * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
1455 * is space for at least one character.
1456 */
1457static void *
1458growstackstr(void)
1459{
1460 size_t len = stackblocksize();
1461 if (herefd >= 0 && len >= 1024) {
1462 full_write(herefd, stackblock(), len);
1463 return stackblock();
1464 }
1465 growstackblock();
Denis Vlasenko29eb3592008-05-18 14:06:08 +00001466 return (char *)stackblock() + len;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001467}
1468
1469/*
1470 * Called from CHECKSTRSPACE.
1471 */
1472static char *
1473makestrspace(size_t newlen, char *p)
1474{
Denis Vlasenko01631112007-12-16 17:20:38 +00001475 size_t len = p - g_stacknxt;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001476 size_t size = stackblocksize();
1477
1478 for (;;) {
1479 size_t nleft;
1480
1481 size = stackblocksize();
1482 nleft = size - len;
1483 if (nleft >= newlen)
1484 break;
1485 growstackblock();
1486 }
Denis Vlasenko29eb3592008-05-18 14:06:08 +00001487 return (char *)stackblock() + len;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001488}
1489
1490static char *
1491stack_nputstr(const char *s, size_t n, char *p)
1492{
1493 p = makestrspace(n, p);
Denis Vlasenko29eb3592008-05-18 14:06:08 +00001494 p = (char *)memcpy(p, s, n) + n;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001495 return p;
1496}
1497
1498static char *
1499stack_putstr(const char *s, char *p)
1500{
1501 return stack_nputstr(s, strlen(s), p);
1502}
1503
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001504static char *
1505_STPUTC(int c, char *p)
1506{
1507 if (p == sstrend)
1508 p = growstackstr();
1509 *p++ = c;
1510 return p;
1511}
1512
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00001513#define STARTSTACKSTR(p) ((p) = stackblock())
1514#define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
Denis Vlasenko843cbd52008-06-27 00:23:18 +00001515#define CHECKSTRSPACE(n, p) do { \
1516 char *q = (p); \
1517 size_t l = (n); \
1518 size_t m = sstrend - q; \
1519 if (l > m) \
1520 (p) = makestrspace(l, q); \
1521} while (0)
Denis Vlasenkoef527f52008-06-23 01:52:30 +00001522#define USTPUTC(c, p) (*(p)++ = (c))
Denis Vlasenko843cbd52008-06-27 00:23:18 +00001523#define STACKSTRNUL(p) do { \
1524 if ((p) == sstrend) \
1525 (p) = growstackstr(); \
1526 *(p) = '\0'; \
1527} while (0)
Denis Vlasenkoef527f52008-06-23 01:52:30 +00001528#define STUNPUTC(p) (--(p))
1529#define STTOPC(p) ((p)[-1])
1530#define STADJUST(amount, p) ((p) += (amount))
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001531
1532#define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
Denis Vlasenkoef527f52008-06-23 01:52:30 +00001533#define ungrabstackstr(s, p) stunalloc(s)
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001534#define stackstrend() ((void *)sstrend)
1535
1536
1537/* ============ String helpers */
1538
1539/*
1540 * prefix -- see if pfx is a prefix of string.
1541 */
1542static char *
1543prefix(const char *string, const char *pfx)
1544{
1545 while (*pfx) {
1546 if (*pfx++ != *string++)
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00001547 return NULL;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001548 }
1549 return (char *) string;
1550}
1551
1552/*
1553 * Check for a valid number. This should be elsewhere.
1554 */
1555static int
1556is_number(const char *p)
1557{
1558 do {
1559 if (!isdigit(*p))
1560 return 0;
1561 } while (*++p != '\0');
1562 return 1;
1563}
1564
1565/*
1566 * Convert a string of digits to an integer, printing an error message on
1567 * failure.
1568 */
1569static int
1570number(const char *s)
1571{
1572 if (!is_number(s))
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02001573 ash_msg_and_raise_error(msg_illnum, s);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001574 return atoi(s);
1575}
1576
1577/*
1578 * Produce a possibly single quoted string suitable as input to the shell.
1579 * The return string is allocated on the stack.
1580 */
1581static char *
1582single_quote(const char *s)
1583{
1584 char *p;
1585
1586 STARTSTACKSTR(p);
1587
1588 do {
1589 char *q;
1590 size_t len;
1591
1592 len = strchrnul(s, '\'') - s;
1593
1594 q = p = makestrspace(len + 3, p);
1595
1596 *q++ = '\'';
Denis Vlasenko29eb3592008-05-18 14:06:08 +00001597 q = (char *)memcpy(q, s, len) + len;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001598 *q++ = '\'';
1599 s += len;
1600
1601 STADJUST(q - p, p);
1602
Denys Vlasenkocd716832009-11-28 22:14:02 +01001603 if (*s != '\'')
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001604 break;
Denys Vlasenkocd716832009-11-28 22:14:02 +01001605 len = 0;
1606 do len++; while (*++s == '\'');
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001607
1608 q = p = makestrspace(len + 3, p);
1609
1610 *q++ = '"';
Denys Vlasenkocd716832009-11-28 22:14:02 +01001611 q = (char *)memcpy(q, s - len, len) + len;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001612 *q++ = '"';
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001613
1614 STADJUST(q - p, p);
1615 } while (*s);
1616
Denys Vlasenkocd716832009-11-28 22:14:02 +01001617 USTPUTC('\0', p);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001618
1619 return stackblock();
1620}
1621
1622
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00001623/* ============ nextopt */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001624
1625static char **argptr; /* argument list for builtin commands */
1626static char *optionarg; /* set by nextopt (like getopt) */
1627static char *optptr; /* used by nextopt */
1628
1629/*
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001630 * XXX - should get rid of. Have all builtins use getopt(3).
1631 * The library getopt must have the BSD extension static variable
1632 * "optreset", otherwise it can't be used within the shell safely.
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001633 *
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001634 * Standard option processing (a la getopt) for builtin routines.
1635 * The only argument that is passed to nextopt is the option string;
1636 * the other arguments are unnecessary. It returns the character,
1637 * or '\0' on end of input.
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001638 */
1639static int
1640nextopt(const char *optstring)
1641{
1642 char *p;
1643 const char *q;
1644 char c;
1645
1646 p = optptr;
1647 if (p == NULL || *p == '\0') {
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001648 /* We ate entire "-param", take next one */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001649 p = *argptr;
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001650 if (p == NULL)
1651 return '\0';
1652 if (*p != '-')
1653 return '\0';
1654 if (*++p == '\0') /* just "-" ? */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001655 return '\0';
1656 argptr++;
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001657 if (LONE_DASH(p)) /* "--" ? */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001658 return '\0';
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001659 /* p => next "-param" */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001660 }
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001661 /* p => some option char in the middle of a "-param" */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001662 c = *p++;
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +00001663 for (q = optstring; *q != c;) {
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001664 if (*q == '\0')
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00001665 ash_msg_and_raise_error("illegal option -%c", c);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001666 if (*++q == ':')
1667 q++;
1668 }
1669 if (*++q == ':') {
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001670 if (*p == '\0') {
1671 p = *argptr++;
1672 if (p == NULL)
1673 ash_msg_and_raise_error("no arg for -%c option", c);
1674 }
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001675 optionarg = p;
1676 p = NULL;
1677 }
1678 optptr = p;
1679 return c;
1680}
1681
1682
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00001683/* ============ Shell variables */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001684
Denis Vlasenko01631112007-12-16 17:20:38 +00001685/*
1686 * The parsefile structure pointed to by the global variable parsefile
1687 * contains information about the current file being read.
1688 */
Denis Vlasenko01631112007-12-16 17:20:38 +00001689struct shparam {
1690 int nparam; /* # of positional parameters (without $0) */
1691#if ENABLE_ASH_GETOPTS
1692 int optind; /* next parameter to be processed by getopts */
1693 int optoff; /* used by getopts */
1694#endif
1695 unsigned char malloced; /* if parameter list dynamically allocated */
1696 char **p; /* parameter list */
1697};
1698
1699/*
1700 * Free the list of positional parameters.
1701 */
1702static void
1703freeparam(volatile struct shparam *param)
1704{
Denis Vlasenko01631112007-12-16 17:20:38 +00001705 if (param->malloced) {
Denis Vlasenko3177ba02008-07-13 20:39:23 +00001706 char **ap, **ap1;
1707 ap = ap1 = param->p;
1708 while (*ap)
1709 free(*ap++);
1710 free(ap1);
Denis Vlasenko01631112007-12-16 17:20:38 +00001711 }
1712}
1713
1714#if ENABLE_ASH_GETOPTS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001715static void FAST_FUNC getoptsreset(const char *value);
Denis Vlasenko01631112007-12-16 17:20:38 +00001716#endif
1717
1718struct var {
1719 struct var *next; /* next entry in hash list */
1720 int flags; /* flags are defined above */
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02001721 const char *var_text; /* name=value */
1722 void (*var_func)(const char *) FAST_FUNC; /* function to be called when */
Denis Vlasenko01631112007-12-16 17:20:38 +00001723 /* the variable gets set/unset */
1724};
1725
1726struct localvar {
1727 struct localvar *next; /* next local variable in list */
1728 struct var *vp; /* the variable that was made local */
1729 int flags; /* saved flags */
1730 const char *text; /* saved text */
1731};
1732
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001733/* flags */
1734#define VEXPORT 0x01 /* variable is exported */
1735#define VREADONLY 0x02 /* variable cannot be modified */
1736#define VSTRFIXED 0x04 /* variable struct is statically allocated */
1737#define VTEXTFIXED 0x08 /* text is statically allocated */
1738#define VSTACK 0x10 /* text is allocated on the stack */
1739#define VUNSET 0x20 /* the variable is not set */
1740#define VNOFUNC 0x40 /* don't call the callback function */
1741#define VNOSET 0x80 /* do not set variable - just readonly test */
1742#define VNOSAVE 0x100 /* when text is on the heap before setvareq */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00001743#if ENABLE_ASH_RANDOM_SUPPORT
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00001744# define VDYNAMIC 0x200 /* dynamic variable */
1745#else
1746# define VDYNAMIC 0
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001747#endif
1748
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00001749
Denis Vlasenko01631112007-12-16 17:20:38 +00001750/* Need to be before varinit_data[] */
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00001751#if ENABLE_LOCALE_SUPPORT
Denys Vlasenko2634bf32009-06-09 18:40:07 +02001752static void FAST_FUNC
Denis Vlasenkoa8915072007-02-23 21:10:06 +00001753change_lc_all(const char *value)
1754{
1755 if (value && *value != '\0')
1756 setlocale(LC_ALL, value);
1757}
Denys Vlasenko2634bf32009-06-09 18:40:07 +02001758static void FAST_FUNC
Denis Vlasenkoa8915072007-02-23 21:10:06 +00001759change_lc_ctype(const char *value)
1760{
1761 if (value && *value != '\0')
1762 setlocale(LC_CTYPE, value);
1763}
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00001764#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001765#if ENABLE_ASH_MAIL
1766static void chkmail(void);
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001767static void changemail(const char *) FAST_FUNC;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001768#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001769static void changepath(const char *) FAST_FUNC;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001770#if ENABLE_ASH_RANDOM_SUPPORT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001771static void change_random(const char *) FAST_FUNC;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001772#endif
1773
Denis Vlasenko01631112007-12-16 17:20:38 +00001774static const struct {
1775 int flags;
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02001776 const char *var_text;
1777 void (*var_func)(const char *) FAST_FUNC;
Denis Vlasenko01631112007-12-16 17:20:38 +00001778} varinit_data[] = {
Denis Vlasenko01631112007-12-16 17:20:38 +00001779 { VSTRFIXED|VTEXTFIXED , defifsvar , NULL },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001780#if ENABLE_ASH_MAIL
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02001781 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL" , changemail },
1782 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH" , changemail },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001783#endif
Denis Vlasenko01631112007-12-16 17:20:38 +00001784 { VSTRFIXED|VTEXTFIXED , bb_PATH_root_path, changepath },
1785 { VSTRFIXED|VTEXTFIXED , "PS1=$ " , NULL },
1786 { VSTRFIXED|VTEXTFIXED , "PS2=> " , NULL },
1787 { VSTRFIXED|VTEXTFIXED , "PS4=+ " , NULL },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001788#if ENABLE_ASH_GETOPTS
Denis Vlasenko01631112007-12-16 17:20:38 +00001789 { VSTRFIXED|VTEXTFIXED , "OPTIND=1" , getoptsreset },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001790#endif
1791#if ENABLE_ASH_RANDOM_SUPPORT
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02001792 { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM", change_random },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001793#endif
1794#if ENABLE_LOCALE_SUPPORT
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02001795 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL" , change_lc_all },
1796 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE" , change_lc_ctype },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001797#endif
1798#if ENABLE_FEATURE_EDITING_SAVEHISTORY
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02001799 { VSTRFIXED|VTEXTFIXED|VUNSET, "HISTFILE" , NULL },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001800#endif
1801};
1802
Denis Vlasenko0b769642008-07-24 07:54:57 +00001803struct redirtab;
Denis Vlasenko01631112007-12-16 17:20:38 +00001804
1805struct globals_var {
1806 struct shparam shellparam; /* $@ current positional parameters */
1807 struct redirtab *redirlist;
1808 int g_nullredirs;
1809 int preverrout_fd; /* save fd2 before print debug if xflag is set. */
1810 struct var *vartab[VTABSIZE];
1811 struct var varinit[ARRAY_SIZE(varinit_data)];
1812};
Denis Vlasenko574f2f42008-02-27 18:41:59 +00001813extern struct globals_var *const ash_ptr_to_globals_var;
1814#define G_var (*ash_ptr_to_globals_var)
Denis Vlasenko01631112007-12-16 17:20:38 +00001815#define shellparam (G_var.shellparam )
Denis Vlasenko0b769642008-07-24 07:54:57 +00001816//#define redirlist (G_var.redirlist )
Denis Vlasenko01631112007-12-16 17:20:38 +00001817#define g_nullredirs (G_var.g_nullredirs )
1818#define preverrout_fd (G_var.preverrout_fd)
1819#define vartab (G_var.vartab )
1820#define varinit (G_var.varinit )
1821#define INIT_G_var() do { \
Denis Vlasenko6b06cb82008-05-15 21:30:45 +00001822 unsigned i; \
Denis Vlasenko574f2f42008-02-27 18:41:59 +00001823 (*(struct globals_var**)&ash_ptr_to_globals_var) = xzalloc(sizeof(G_var)); \
1824 barrier(); \
Denis Vlasenko01631112007-12-16 17:20:38 +00001825 for (i = 0; i < ARRAY_SIZE(varinit_data); i++) { \
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02001826 varinit[i].flags = varinit_data[i].flags; \
1827 varinit[i].var_text = varinit_data[i].var_text; \
1828 varinit[i].var_func = varinit_data[i].var_func; \
Denis Vlasenko01631112007-12-16 17:20:38 +00001829 } \
1830} while (0)
1831
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001832#define vifs varinit[0]
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001833#if ENABLE_ASH_MAIL
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001834# define vmail (&vifs)[1]
1835# define vmpath (&vmail)[1]
1836# define vpath (&vmpath)[1]
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001837#else
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001838# define vpath (&vifs)[1]
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001839#endif
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001840#define vps1 (&vpath)[1]
1841#define vps2 (&vps1)[1]
1842#define vps4 (&vps2)[1]
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001843#if ENABLE_ASH_GETOPTS
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001844# define voptind (&vps4)[1]
1845# if ENABLE_ASH_RANDOM_SUPPORT
1846# define vrandom (&voptind)[1]
1847# endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001848#else
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001849# if ENABLE_ASH_RANDOM_SUPPORT
1850# define vrandom (&vps4)[1]
1851# endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001852#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001853
1854/*
1855 * The following macros access the values of the above variables.
1856 * They have to skip over the name. They return the null string
1857 * for unset variables.
1858 */
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02001859#define ifsval() (vifs.var_text + 4)
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001860#define ifsset() ((vifs.flags & VUNSET) == 0)
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001861#if ENABLE_ASH_MAIL
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02001862# define mailval() (vmail.var_text + 5)
1863# define mpathval() (vmpath.var_text + 9)
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001864# define mpathset() ((vmpath.flags & VUNSET) == 0)
1865#endif
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02001866#define pathval() (vpath.var_text + 5)
1867#define ps1val() (vps1.var_text + 4)
1868#define ps2val() (vps2.var_text + 4)
1869#define ps4val() (vps4.var_text + 4)
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001870#if ENABLE_ASH_GETOPTS
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02001871# define optindval() (voptind.var_text + 7)
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001872#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001873
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001874
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001875#define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
1876#define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
1877
Denis Vlasenko01631112007-12-16 17:20:38 +00001878#if ENABLE_ASH_GETOPTS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001879static void FAST_FUNC
Denis Vlasenko01631112007-12-16 17:20:38 +00001880getoptsreset(const char *value)
1881{
1882 shellparam.optind = number(value);
1883 shellparam.optoff = -1;
1884}
1885#endif
1886
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001887/*
1888 * Return of a legal variable name (a letter or underscore followed by zero or
1889 * more letters, underscores, and digits).
1890 */
Denys Vlasenko03dad222010-01-12 23:29:57 +01001891static char* FAST_FUNC
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001892endofname(const char *name)
1893{
1894 char *p;
1895
1896 p = (char *) name;
1897 if (!is_name(*p))
1898 return p;
1899 while (*++p) {
1900 if (!is_in_name(*p))
1901 break;
1902 }
1903 return p;
1904}
1905
1906/*
1907 * Compares two strings up to the first = or '\0'. The first
1908 * string must be terminated by '='; the second may be terminated by
1909 * either '=' or '\0'.
1910 */
1911static int
1912varcmp(const char *p, const char *q)
1913{
1914 int c, d;
1915
1916 while ((c = *p) == (d = *q)) {
1917 if (!c || c == '=')
1918 goto out;
1919 p++;
1920 q++;
1921 }
1922 if (c == '=')
Denis Vlasenko9650f362007-02-23 01:04:37 +00001923 c = '\0';
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001924 if (d == '=')
Denis Vlasenko9650f362007-02-23 01:04:37 +00001925 d = '\0';
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001926 out:
1927 return c - d;
1928}
1929
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001930/*
1931 * Find the appropriate entry in the hash table from the name.
1932 */
1933static struct var **
1934hashvar(const char *p)
1935{
1936 unsigned hashval;
1937
1938 hashval = ((unsigned char) *p) << 4;
1939 while (*p && *p != '=')
1940 hashval += (unsigned char) *p++;
1941 return &vartab[hashval % VTABSIZE];
1942}
1943
1944static int
1945vpcmp(const void *a, const void *b)
1946{
1947 return varcmp(*(const char **)a, *(const char **)b);
1948}
1949
1950/*
1951 * This routine initializes the builtin variables.
1952 */
1953static void
1954initvar(void)
1955{
1956 struct var *vp;
1957 struct var *end;
1958 struct var **vpp;
1959
1960 /*
1961 * PS1 depends on uid
1962 */
1963#if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02001964 vps1.var_text = "PS1=\\w \\$ ";
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001965#else
1966 if (!geteuid())
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02001967 vps1.var_text = "PS1=# ";
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001968#endif
1969 vp = varinit;
Denis Vlasenko80b8b392007-06-25 10:55:35 +00001970 end = vp + ARRAY_SIZE(varinit);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001971 do {
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02001972 vpp = hashvar(vp->var_text);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001973 vp->next = *vpp;
1974 *vpp = vp;
1975 } while (++vp < end);
1976}
1977
1978static struct var **
1979findvar(struct var **vpp, const char *name)
1980{
1981 for (; *vpp; vpp = &(*vpp)->next) {
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02001982 if (varcmp((*vpp)->var_text, name) == 0) {
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001983 break;
1984 }
1985 }
1986 return vpp;
1987}
1988
1989/*
1990 * Find the value of a variable. Returns NULL if not set.
1991 */
Denys Vlasenko03dad222010-01-12 23:29:57 +01001992static const char* FAST_FUNC
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001993lookupvar(const char *name)
1994{
1995 struct var *v;
1996
1997 v = *findvar(hashvar(name), name);
1998 if (v) {
Denis Vlasenko448d30e2008-06-27 00:24:11 +00001999#if ENABLE_ASH_RANDOM_SUPPORT
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002000 /*
2001 * Dynamic variables are implemented roughly the same way they are
2002 * in bash. Namely, they're "special" so long as they aren't unset.
2003 * As soon as they're unset, they're no longer dynamic, and dynamic
2004 * lookup will no longer happen at that point. -- PFM.
2005 */
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02002006 if (v->flags & VDYNAMIC)
2007 v->var_func(NULL);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002008#endif
2009 if (!(v->flags & VUNSET))
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02002010 return var_end(v->var_text);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002011 }
2012 return NULL;
2013}
2014
2015/*
2016 * Search the environment of a builtin command.
2017 */
Mike Frysinger98c52642009-04-02 10:02:37 +00002018static const char *
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002019bltinlookup(const char *name)
2020{
2021 struct strlist *sp;
2022
2023 for (sp = cmdenviron; sp; sp = sp->next) {
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02002024 if (varcmp(sp->text, name) == 0)
2025 return var_end(sp->text);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002026 }
2027 return lookupvar(name);
2028}
2029
2030/*
2031 * Same as setvar except that the variable and value are passed in
2032 * the first argument as name=value. Since the first argument will
2033 * be actually stored in the table, it should not be a string that
2034 * will go away.
2035 * Called with interrupts off.
2036 */
2037static void
2038setvareq(char *s, int flags)
2039{
2040 struct var *vp, **vpp;
2041
2042 vpp = hashvar(s);
2043 flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
2044 vp = *findvar(vpp, s);
2045 if (vp) {
2046 if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
2047 const char *n;
2048
2049 if (flags & VNOSAVE)
2050 free(s);
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02002051 n = vp->var_text;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002052 ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
2053 }
2054
2055 if (flags & VNOSET)
2056 return;
2057
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02002058 if (vp->var_func && !(flags & VNOFUNC))
2059 vp->var_func(var_end(s));
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002060
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02002061 if (!(vp->flags & (VTEXTFIXED|VSTACK)))
2062 free((char*)vp->var_text);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002063
2064 flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
2065 } else {
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02002066 /* variable s is not found */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002067 if (flags & VNOSET)
2068 return;
Denis Vlasenko597906c2008-02-20 16:38:54 +00002069 vp = ckzalloc(sizeof(*vp));
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002070 vp->next = *vpp;
Denis Vlasenko597906c2008-02-20 16:38:54 +00002071 /*vp->func = NULL; - ckzalloc did it */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002072 *vpp = vp;
2073 }
2074 if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
2075 s = ckstrdup(s);
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02002076 vp->var_text = s;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002077 vp->flags = flags;
2078}
2079
2080/*
2081 * Set the value of a variable. The flags argument is ored with the
2082 * flags of the variable. If val is NULL, the variable is unset.
2083 */
2084static void
2085setvar(const char *name, const char *val, int flags)
2086{
2087 char *p, *q;
2088 size_t namelen;
2089 char *nameeq;
2090 size_t vallen;
2091
2092 q = endofname(name);
2093 p = strchrnul(q, '=');
2094 namelen = p - name;
2095 if (!namelen || p != q)
2096 ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
2097 vallen = 0;
2098 if (val == NULL) {
2099 flags |= VUNSET;
2100 } else {
2101 vallen = strlen(val);
2102 }
2103 INT_OFF;
2104 nameeq = ckmalloc(namelen + vallen + 2);
Denis Vlasenko29eb3592008-05-18 14:06:08 +00002105 p = (char *)memcpy(nameeq, name, namelen) + namelen;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002106 if (val) {
2107 *p++ = '=';
Denis Vlasenko29eb3592008-05-18 14:06:08 +00002108 p = (char *)memcpy(p, val, vallen) + vallen;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002109 }
2110 *p = '\0';
2111 setvareq(nameeq, flags | VNOSAVE);
2112 INT_ON;
2113}
2114
Denys Vlasenko03dad222010-01-12 23:29:57 +01002115static void FAST_FUNC
2116setvar2(const char *name, const char *val)
2117{
2118 setvar(name, val, 0);
2119}
2120
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002121#if ENABLE_ASH_GETOPTS
2122/*
2123 * Safe version of setvar, returns 1 on success 0 on failure.
2124 */
2125static int
2126setvarsafe(const char *name, const char *val, int flags)
2127{
2128 int err;
2129 volatile int saveint;
2130 struct jmploc *volatile savehandler = exception_handler;
2131 struct jmploc jmploc;
2132
2133 SAVE_INT(saveint);
2134 if (setjmp(jmploc.loc))
2135 err = 1;
2136 else {
2137 exception_handler = &jmploc;
2138 setvar(name, val, flags);
2139 err = 0;
2140 }
2141 exception_handler = savehandler;
2142 RESTORE_INT(saveint);
2143 return err;
2144}
2145#endif
2146
2147/*
2148 * Unset the specified variable.
2149 */
2150static int
2151unsetvar(const char *s)
2152{
2153 struct var **vpp;
2154 struct var *vp;
2155 int retval;
2156
2157 vpp = findvar(hashvar(s), s);
2158 vp = *vpp;
2159 retval = 2;
2160 if (vp) {
2161 int flags = vp->flags;
2162
2163 retval = 1;
2164 if (flags & VREADONLY)
2165 goto out;
Denis Vlasenko448d30e2008-06-27 00:24:11 +00002166#if ENABLE_ASH_RANDOM_SUPPORT
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002167 vp->flags &= ~VDYNAMIC;
2168#endif
2169 if (flags & VUNSET)
2170 goto ok;
2171 if ((flags & VSTRFIXED) == 0) {
2172 INT_OFF;
2173 if ((flags & (VTEXTFIXED|VSTACK)) == 0)
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02002174 free((char*)vp->var_text);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002175 *vpp = vp->next;
2176 free(vp);
2177 INT_ON;
2178 } else {
2179 setvar(s, 0, 0);
2180 vp->flags &= ~VEXPORT;
2181 }
2182 ok:
2183 retval = 0;
2184 }
2185 out:
2186 return retval;
2187}
2188
2189/*
2190 * Process a linked list of variable assignments.
2191 */
2192static void
2193listsetvar(struct strlist *list_set_var, int flags)
2194{
2195 struct strlist *lp = list_set_var;
2196
2197 if (!lp)
2198 return;
2199 INT_OFF;
2200 do {
2201 setvareq(lp->text, flags);
Denis Vlasenko9650f362007-02-23 01:04:37 +00002202 lp = lp->next;
2203 } while (lp);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002204 INT_ON;
2205}
2206
2207/*
2208 * Generate a list of variables satisfying the given conditions.
2209 */
2210static char **
2211listvars(int on, int off, char ***end)
2212{
2213 struct var **vpp;
2214 struct var *vp;
2215 char **ep;
2216 int mask;
2217
2218 STARTSTACKSTR(ep);
2219 vpp = vartab;
2220 mask = on | off;
2221 do {
2222 for (vp = *vpp; vp; vp = vp->next) {
2223 if ((vp->flags & mask) == on) {
2224 if (ep == stackstrend())
2225 ep = growstackstr();
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02002226 *ep++ = (char*)vp->var_text;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002227 }
2228 }
2229 } while (++vpp < vartab + VTABSIZE);
2230 if (ep == stackstrend())
2231 ep = growstackstr();
2232 if (end)
2233 *end = ep;
2234 *ep++ = NULL;
2235 return grabstackstr(ep);
2236}
2237
2238
2239/* ============ Path search helper
2240 *
2241 * The variable path (passed by reference) should be set to the start
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02002242 * of the path before the first call; path_advance will update
2243 * this value as it proceeds. Successive calls to path_advance will return
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002244 * the possible path expansions in sequence. If an option (indicated by
2245 * a percent sign) appears in the path entry then the global variable
2246 * pathopt will be set to point to it; otherwise pathopt will be set to
2247 * NULL.
2248 */
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02002249static const char *pathopt; /* set by path_advance */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002250
2251static char *
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02002252path_advance(const char **path, const char *name)
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002253{
2254 const char *p;
2255 char *q;
2256 const char *start;
2257 size_t len;
2258
2259 if (*path == NULL)
2260 return NULL;
2261 start = *path;
Denis Vlasenkof7d56652008-03-25 05:51:41 +00002262 for (p = start; *p && *p != ':' && *p != '%'; p++)
2263 continue;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002264 len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
2265 while (stackblocksize() < len)
2266 growstackblock();
2267 q = stackblock();
2268 if (p != start) {
2269 memcpy(q, start, p - start);
2270 q += p - start;
2271 *q++ = '/';
2272 }
2273 strcpy(q, name);
2274 pathopt = NULL;
2275 if (*p == '%') {
2276 pathopt = ++p;
Denis Vlasenkof7d56652008-03-25 05:51:41 +00002277 while (*p && *p != ':')
2278 p++;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002279 }
2280 if (*p == ':')
2281 *path = p + 1;
2282 else
2283 *path = NULL;
2284 return stalloc(len);
2285}
2286
2287
2288/* ============ Prompt */
2289
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +00002290static smallint doprompt; /* if set, prompt the user */
2291static smallint needprompt; /* true if interactive and at start of line */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002292
2293#if ENABLE_FEATURE_EDITING
2294static line_input_t *line_input_state;
2295static const char *cmdedit_prompt;
2296static void
2297putprompt(const char *s)
2298{
2299 if (ENABLE_ASH_EXPAND_PRMT) {
2300 free((char*)cmdedit_prompt);
Denis Vlasenko4222ae42007-02-25 02:37:49 +00002301 cmdedit_prompt = ckstrdup(s);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002302 return;
2303 }
2304 cmdedit_prompt = s;
2305}
2306#else
2307static void
2308putprompt(const char *s)
2309{
2310 out2str(s);
2311}
2312#endif
2313
2314#if ENABLE_ASH_EXPAND_PRMT
2315/* expandstr() needs parsing machinery, so it is far away ahead... */
2316static const char *expandstr(const char *ps);
2317#else
2318#define expandstr(s) s
2319#endif
2320
2321static void
2322setprompt(int whichprompt)
2323{
2324 const char *prompt;
2325#if ENABLE_ASH_EXPAND_PRMT
2326 struct stackmark smark;
2327#endif
2328
2329 needprompt = 0;
2330
2331 switch (whichprompt) {
2332 case 1:
2333 prompt = ps1val();
2334 break;
2335 case 2:
2336 prompt = ps2val();
2337 break;
2338 default: /* 0 */
2339 prompt = nullstr;
2340 }
2341#if ENABLE_ASH_EXPAND_PRMT
2342 setstackmark(&smark);
2343 stalloc(stackblocksize());
2344#endif
2345 putprompt(expandstr(prompt));
2346#if ENABLE_ASH_EXPAND_PRMT
2347 popstackmark(&smark);
2348#endif
2349}
2350
2351
2352/* ============ The cd and pwd commands */
2353
2354#define CD_PHYSICAL 1
2355#define CD_PRINT 2
2356
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002357static int
2358cdopt(void)
2359{
2360 int flags = 0;
2361 int i, j;
2362
2363 j = 'L';
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02002364 while ((i = nextopt("LP")) != '\0') {
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002365 if (i != j) {
2366 flags ^= CD_PHYSICAL;
2367 j = i;
2368 }
2369 }
2370
2371 return flags;
2372}
2373
2374/*
2375 * Update curdir (the name of the current directory) in response to a
2376 * cd command.
2377 */
2378static const char *
2379updatepwd(const char *dir)
2380{
2381 char *new;
2382 char *p;
2383 char *cdcomppath;
2384 const char *lim;
2385
2386 cdcomppath = ststrdup(dir);
2387 STARTSTACKSTR(new);
2388 if (*dir != '/') {
2389 if (curdir == nullstr)
2390 return 0;
2391 new = stack_putstr(curdir, new);
2392 }
2393 new = makestrspace(strlen(dir) + 2, new);
Denis Vlasenko29eb3592008-05-18 14:06:08 +00002394 lim = (char *)stackblock() + 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002395 if (*dir != '/') {
2396 if (new[-1] != '/')
2397 USTPUTC('/', new);
2398 if (new > lim && *lim == '/')
2399 lim++;
2400 } else {
2401 USTPUTC('/', new);
2402 cdcomppath++;
2403 if (dir[1] == '/' && dir[2] != '/') {
2404 USTPUTC('/', new);
2405 cdcomppath++;
2406 lim++;
2407 }
2408 }
2409 p = strtok(cdcomppath, "/");
2410 while (p) {
2411 switch (*p) {
2412 case '.':
2413 if (p[1] == '.' && p[2] == '\0') {
2414 while (new > lim) {
2415 STUNPUTC(new);
2416 if (new[-1] == '/')
2417 break;
2418 }
2419 break;
Denis Vlasenko16abcd92007-04-13 23:59:52 +00002420 }
2421 if (p[1] == '\0')
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002422 break;
2423 /* fall through */
2424 default:
2425 new = stack_putstr(p, new);
2426 USTPUTC('/', new);
2427 }
2428 p = strtok(0, "/");
2429 }
2430 if (new > lim)
2431 STUNPUTC(new);
2432 *new = 0;
2433 return stackblock();
2434}
2435
2436/*
2437 * Find out what the current directory is. If we already know the current
2438 * directory, this routine returns immediately.
2439 */
2440static char *
2441getpwd(void)
2442{
Denis Vlasenko01631112007-12-16 17:20:38 +00002443 char *dir = getcwd(NULL, 0); /* huh, using glibc extension? */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002444 return dir ? dir : nullstr;
2445}
2446
2447static void
2448setpwd(const char *val, int setold)
2449{
2450 char *oldcur, *dir;
2451
2452 oldcur = dir = curdir;
2453
2454 if (setold) {
2455 setvar("OLDPWD", oldcur, VEXPORT);
2456 }
2457 INT_OFF;
2458 if (physdir != nullstr) {
2459 if (physdir != oldcur)
2460 free(physdir);
2461 physdir = nullstr;
2462 }
2463 if (oldcur == val || !val) {
2464 char *s = getpwd();
2465 physdir = s;
2466 if (!val)
2467 dir = s;
2468 } else
2469 dir = ckstrdup(val);
2470 if (oldcur != dir && oldcur != nullstr) {
2471 free(oldcur);
2472 }
2473 curdir = dir;
2474 INT_ON;
2475 setvar("PWD", dir, VEXPORT);
2476}
2477
2478static void hashcd(void);
2479
2480/*
2481 * Actually do the chdir. We also call hashcd to let the routines in exec.c
2482 * know that the current directory has changed.
2483 */
2484static int
2485docd(const char *dest, int flags)
2486{
Denys Vlasenko4b1100e2010-03-05 14:10:54 +01002487 const char *dir = NULL;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002488 int err;
2489
2490 TRACE(("docd(\"%s\", %d) called\n", dest, flags));
2491
2492 INT_OFF;
2493 if (!(flags & CD_PHYSICAL)) {
2494 dir = updatepwd(dest);
2495 if (dir)
2496 dest = dir;
2497 }
2498 err = chdir(dest);
2499 if (err)
2500 goto out;
2501 setpwd(dir, 1);
2502 hashcd();
2503 out:
2504 INT_ON;
2505 return err;
2506}
2507
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02002508static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00002509cdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002510{
2511 const char *dest;
2512 const char *path;
2513 const char *p;
2514 char c;
2515 struct stat statb;
2516 int flags;
2517
2518 flags = cdopt();
2519 dest = *argptr;
2520 if (!dest)
Denys Vlasenkoea8b2522010-06-02 12:57:26 +02002521 dest = bltinlookup("HOME");
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002522 else if (LONE_DASH(dest)) {
2523 dest = bltinlookup("OLDPWD");
2524 flags |= CD_PRINT;
2525 }
2526 if (!dest)
2527 dest = nullstr;
2528 if (*dest == '/')
2529 goto step7;
2530 if (*dest == '.') {
2531 c = dest[1];
2532 dotdot:
2533 switch (c) {
2534 case '\0':
2535 case '/':
2536 goto step6;
2537 case '.':
2538 c = dest[2];
2539 if (c != '.')
2540 goto dotdot;
2541 }
2542 }
2543 if (!*dest)
2544 dest = ".";
2545 path = bltinlookup("CDPATH");
2546 if (!path) {
2547 step6:
2548 step7:
2549 p = dest;
2550 goto docd;
2551 }
2552 do {
2553 c = *path;
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02002554 p = path_advance(&path, dest);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002555 if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
2556 if (c && c != ':')
2557 flags |= CD_PRINT;
2558 docd:
2559 if (!docd(p, flags))
2560 goto out;
2561 break;
2562 }
2563 } while (path);
2564 ash_msg_and_raise_error("can't cd to %s", dest);
2565 /* NOTREACHED */
2566 out:
2567 if (flags & CD_PRINT)
Denys Vlasenkoea8b2522010-06-02 12:57:26 +02002568 out1fmt("%s\n", curdir);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002569 return 0;
2570}
2571
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02002572static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00002573pwdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002574{
2575 int flags;
2576 const char *dir = curdir;
2577
2578 flags = cdopt();
2579 if (flags) {
2580 if (physdir == nullstr)
2581 setpwd(dir, 0);
2582 dir = physdir;
2583 }
Denys Vlasenkoea8b2522010-06-02 12:57:26 +02002584 out1fmt("%s\n", dir);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002585 return 0;
2586}
2587
Denis Vlasenko0c032a42007-02-23 01:03:40 +00002588
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00002589/* ============ ... */
Eric Andersenc470f442003-07-28 09:56:35 +00002590
Denis Vlasenko834dee72008-10-07 09:18:30 +00002591
Denys Vlasenko82dd14a2010-05-17 10:10:01 +02002592#define IBUFSIZ (ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 1024)
Eric Andersenc470f442003-07-28 09:56:35 +00002593
Eric Andersenc470f442003-07-28 09:56:35 +00002594/* Syntax classes */
Denis Vlasenko834dee72008-10-07 09:18:30 +00002595#define CWORD 0 /* character is nothing special */
2596#define CNL 1 /* newline character */
2597#define CBACK 2 /* a backslash character */
2598#define CSQUOTE 3 /* single quote */
2599#define CDQUOTE 4 /* double quote */
Eric Andersenc470f442003-07-28 09:56:35 +00002600#define CENDQUOTE 5 /* a terminating quote */
Denis Vlasenko834dee72008-10-07 09:18:30 +00002601#define CBQUOTE 6 /* backwards single quote */
2602#define CVAR 7 /* a dollar sign */
2603#define CENDVAR 8 /* a '}' character */
2604#define CLP 9 /* a left paren in arithmetic */
2605#define CRP 10 /* a right paren in arithmetic */
Eric Andersenc470f442003-07-28 09:56:35 +00002606#define CENDFILE 11 /* end of file */
Denis Vlasenko834dee72008-10-07 09:18:30 +00002607#define CCTL 12 /* like CWORD, except it must be escaped */
2608#define CSPCL 13 /* these terminate a word */
2609#define CIGN 14 /* character should be ignored */
Eric Andersenc470f442003-07-28 09:56:35 +00002610
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002611#define PEOF 256
Denis Vlasenko131ae172007-02-18 13:00:19 +00002612#if ENABLE_ASH_ALIAS
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002613# define PEOA 257
Eric Andersenc470f442003-07-28 09:56:35 +00002614#endif
2615
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002616#define USE_SIT_FUNCTION ENABLE_ASH_OPTIMIZE_FOR_SIZE
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002617
Mike Frysinger98c52642009-04-02 10:02:37 +00002618#if ENABLE_SH_MATH_SUPPORT
Denys Vlasenko76bc2d62009-11-29 01:37:46 +01002619# define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8) | (d << 12))
Eric Andersenc470f442003-07-28 09:56:35 +00002620#else
Denys Vlasenko76bc2d62009-11-29 01:37:46 +01002621# define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8))
Denys Vlasenko76bc2d62009-11-29 01:37:46 +01002622#endif
Denys Vlasenko068d3862009-11-29 01:41:11 +01002623static const uint16_t S_I_T[] = {
Denys Vlasenko76bc2d62009-11-29 01:37:46 +01002624#if ENABLE_ASH_ALIAS
2625 SIT_ITEM(CSPCL , CIGN , CIGN , CIGN ), /* 0, PEOA */
2626#endif
2627 SIT_ITEM(CSPCL , CWORD , CWORD, CWORD ), /* 1, ' ' */
2628 SIT_ITEM(CNL , CNL , CNL , CNL ), /* 2, \n */
2629 SIT_ITEM(CWORD , CCTL , CCTL , CWORD ), /* 3, !*-/:=?[]~ */
2630 SIT_ITEM(CDQUOTE , CENDQUOTE, CWORD, CWORD ), /* 4, '"' */
2631 SIT_ITEM(CVAR , CVAR , CWORD, CVAR ), /* 5, $ */
2632 SIT_ITEM(CSQUOTE , CWORD , CENDQUOTE, CWORD), /* 6, "'" */
2633 SIT_ITEM(CSPCL , CWORD , CWORD, CLP ), /* 7, ( */
2634 SIT_ITEM(CSPCL , CWORD , CWORD, CRP ), /* 8, ) */
2635 SIT_ITEM(CBACK , CBACK , CCTL , CBACK ), /* 9, \ */
2636 SIT_ITEM(CBQUOTE , CBQUOTE , CWORD, CBQUOTE), /* 10, ` */
2637 SIT_ITEM(CENDVAR , CENDVAR , CWORD, CENDVAR), /* 11, } */
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002638#if !USE_SIT_FUNCTION
Denys Vlasenko76bc2d62009-11-29 01:37:46 +01002639 SIT_ITEM(CENDFILE, CENDFILE , CENDFILE, CENDFILE),/* 12, PEOF */
2640 SIT_ITEM(CWORD , CWORD , CWORD, CWORD ), /* 13, 0-9A-Za-z */
2641 SIT_ITEM(CCTL , CCTL , CCTL , CCTL ) /* 14, CTLESC ... */
2642#endif
2643#undef SIT_ITEM
Eric Andersenc470f442003-07-28 09:56:35 +00002644};
Denys Vlasenko76bc2d62009-11-29 01:37:46 +01002645/* Constants below must match table above */
2646enum {
2647#if ENABLE_ASH_ALIAS
2648 CSPCL_CIGN_CIGN_CIGN , /* 0 */
2649#endif
2650 CSPCL_CWORD_CWORD_CWORD , /* 1 */
2651 CNL_CNL_CNL_CNL , /* 2 */
2652 CWORD_CCTL_CCTL_CWORD , /* 3 */
2653 CDQUOTE_CENDQUOTE_CWORD_CWORD , /* 4 */
2654 CVAR_CVAR_CWORD_CVAR , /* 5 */
2655 CSQUOTE_CWORD_CENDQUOTE_CWORD , /* 6 */
2656 CSPCL_CWORD_CWORD_CLP , /* 7 */
2657 CSPCL_CWORD_CWORD_CRP , /* 8 */
2658 CBACK_CBACK_CCTL_CBACK , /* 9 */
2659 CBQUOTE_CBQUOTE_CWORD_CBQUOTE , /* 10 */
2660 CENDVAR_CENDVAR_CWORD_CENDVAR , /* 11 */
2661 CENDFILE_CENDFILE_CENDFILE_CENDFILE, /* 12 */
2662 CWORD_CWORD_CWORD_CWORD , /* 13 */
2663 CCTL_CCTL_CCTL_CCTL , /* 14 */
2664};
Eric Andersen2870d962001-07-02 17:27:21 +00002665
Denys Vlasenkocd716832009-11-28 22:14:02 +01002666/* c in SIT(c, syntax) must be an *unsigned char* or PEOA or PEOF,
2667 * caller must ensure proper cast on it if c is *char_ptr!
2668 */
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002669/* Values for syntax param */
2670#define BASESYNTAX 0 /* not in quotes */
2671#define DQSYNTAX 1 /* in double quotes */
2672#define SQSYNTAX 2 /* in single quotes */
2673#define ARISYNTAX 3 /* in arithmetic */
2674#define PSSYNTAX 4 /* prompt. never passed to SIT() */
Denys Vlasenkocd716832009-11-28 22:14:02 +01002675
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002676#if USE_SIT_FUNCTION
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002677
Denis Vlasenko0c032a42007-02-23 01:03:40 +00002678static int
2679SIT(int c, int syntax)
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002680{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00002681 static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-/:;<=>?[\\]`|}~";
Denys Vlasenkocd716832009-11-28 22:14:02 +01002682# if ENABLE_ASH_ALIAS
2683 static const uint8_t syntax_index_table[] ALIGN1 = {
Eric Andersenc470f442003-07-28 09:56:35 +00002684 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
2685 7, 8, 3, 3, 3, 3, 1, 1, /* "()*-/:;<" */
2686 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
2687 11, 3 /* "}~" */
2688 };
Denys Vlasenkocd716832009-11-28 22:14:02 +01002689# else
2690 static const uint8_t syntax_index_table[] ALIGN1 = {
Eric Andersenc470f442003-07-28 09:56:35 +00002691 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
2692 6, 7, 2, 2, 2, 2, 0, 0, /* "()*-/:;<" */
2693 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
2694 10, 2 /* "}~" */
2695 };
Denys Vlasenkocd716832009-11-28 22:14:02 +01002696# endif
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002697 const char *s;
2698 int indx;
2699
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002700 if (c == PEOF)
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002701 return CENDFILE;
Denys Vlasenkocd716832009-11-28 22:14:02 +01002702# if ENABLE_ASH_ALIAS
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002703 if (c == PEOA)
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +00002704 indx = 0;
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002705 else
Denys Vlasenkocd716832009-11-28 22:14:02 +01002706# endif
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +00002707 {
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002708 /* Cast is purely for paranoia here,
2709 * just in case someone passed signed char to us */
2710 if ((unsigned char)c >= CTL_FIRST
2711 && (unsigned char)c <= CTL_LAST
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +00002712 ) {
2713 return CCTL;
2714 }
2715 s = strchrnul(spec_symbls, c);
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002716 if (*s == '\0')
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +00002717 return CWORD;
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +00002718 indx = syntax_index_table[s - spec_symbls];
2719 }
Denys Vlasenko76bc2d62009-11-29 01:37:46 +01002720 return (S_I_T[indx] >> (syntax*4)) & 0xf;
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002721}
2722
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00002723#else /* !USE_SIT_FUNCTION */
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002724
Denys Vlasenko76bc2d62009-11-29 01:37:46 +01002725static const uint8_t syntax_index_table[] = {
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00002726 /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
Denys Vlasenkocd716832009-11-28 22:14:02 +01002727 /* 0 */ CWORD_CWORD_CWORD_CWORD,
2728 /* 1 */ CWORD_CWORD_CWORD_CWORD,
2729 /* 2 */ CWORD_CWORD_CWORD_CWORD,
2730 /* 3 */ CWORD_CWORD_CWORD_CWORD,
2731 /* 4 */ CWORD_CWORD_CWORD_CWORD,
2732 /* 5 */ CWORD_CWORD_CWORD_CWORD,
2733 /* 6 */ CWORD_CWORD_CWORD_CWORD,
2734 /* 7 */ CWORD_CWORD_CWORD_CWORD,
2735 /* 8 */ CWORD_CWORD_CWORD_CWORD,
2736 /* 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
2737 /* 10 "\n" */ CNL_CNL_CNL_CNL,
2738 /* 11 */ CWORD_CWORD_CWORD_CWORD,
2739 /* 12 */ CWORD_CWORD_CWORD_CWORD,
2740 /* 13 */ CWORD_CWORD_CWORD_CWORD,
2741 /* 14 */ CWORD_CWORD_CWORD_CWORD,
2742 /* 15 */ CWORD_CWORD_CWORD_CWORD,
2743 /* 16 */ CWORD_CWORD_CWORD_CWORD,
2744 /* 17 */ CWORD_CWORD_CWORD_CWORD,
2745 /* 18 */ CWORD_CWORD_CWORD_CWORD,
2746 /* 19 */ CWORD_CWORD_CWORD_CWORD,
2747 /* 20 */ CWORD_CWORD_CWORD_CWORD,
2748 /* 21 */ CWORD_CWORD_CWORD_CWORD,
2749 /* 22 */ CWORD_CWORD_CWORD_CWORD,
2750 /* 23 */ CWORD_CWORD_CWORD_CWORD,
2751 /* 24 */ CWORD_CWORD_CWORD_CWORD,
2752 /* 25 */ CWORD_CWORD_CWORD_CWORD,
2753 /* 26 */ CWORD_CWORD_CWORD_CWORD,
2754 /* 27 */ CWORD_CWORD_CWORD_CWORD,
2755 /* 28 */ CWORD_CWORD_CWORD_CWORD,
2756 /* 29 */ CWORD_CWORD_CWORD_CWORD,
2757 /* 30 */ CWORD_CWORD_CWORD_CWORD,
2758 /* 31 */ CWORD_CWORD_CWORD_CWORD,
2759 /* 32 " " */ CSPCL_CWORD_CWORD_CWORD,
2760 /* 33 "!" */ CWORD_CCTL_CCTL_CWORD,
2761 /* 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
2762 /* 35 "#" */ CWORD_CWORD_CWORD_CWORD,
2763 /* 36 "$" */ CVAR_CVAR_CWORD_CVAR,
2764 /* 37 "%" */ CWORD_CWORD_CWORD_CWORD,
2765 /* 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
2766 /* 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
2767 /* 40 "(" */ CSPCL_CWORD_CWORD_CLP,
2768 /* 41 ")" */ CSPCL_CWORD_CWORD_CRP,
2769 /* 42 "*" */ CWORD_CCTL_CCTL_CWORD,
2770 /* 43 "+" */ CWORD_CWORD_CWORD_CWORD,
2771 /* 44 "," */ CWORD_CWORD_CWORD_CWORD,
2772 /* 45 "-" */ CWORD_CCTL_CCTL_CWORD,
2773 /* 46 "." */ CWORD_CWORD_CWORD_CWORD,
2774 /* 47 "/" */ CWORD_CCTL_CCTL_CWORD,
2775 /* 48 "0" */ CWORD_CWORD_CWORD_CWORD,
2776 /* 49 "1" */ CWORD_CWORD_CWORD_CWORD,
2777 /* 50 "2" */ CWORD_CWORD_CWORD_CWORD,
2778 /* 51 "3" */ CWORD_CWORD_CWORD_CWORD,
2779 /* 52 "4" */ CWORD_CWORD_CWORD_CWORD,
2780 /* 53 "5" */ CWORD_CWORD_CWORD_CWORD,
2781 /* 54 "6" */ CWORD_CWORD_CWORD_CWORD,
2782 /* 55 "7" */ CWORD_CWORD_CWORD_CWORD,
2783 /* 56 "8" */ CWORD_CWORD_CWORD_CWORD,
2784 /* 57 "9" */ CWORD_CWORD_CWORD_CWORD,
2785 /* 58 ":" */ CWORD_CCTL_CCTL_CWORD,
2786 /* 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
2787 /* 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
2788 /* 61 "=" */ CWORD_CCTL_CCTL_CWORD,
2789 /* 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
2790 /* 63 "?" */ CWORD_CCTL_CCTL_CWORD,
2791 /* 64 "@" */ CWORD_CWORD_CWORD_CWORD,
2792 /* 65 "A" */ CWORD_CWORD_CWORD_CWORD,
2793 /* 66 "B" */ CWORD_CWORD_CWORD_CWORD,
2794 /* 67 "C" */ CWORD_CWORD_CWORD_CWORD,
2795 /* 68 "D" */ CWORD_CWORD_CWORD_CWORD,
2796 /* 69 "E" */ CWORD_CWORD_CWORD_CWORD,
2797 /* 70 "F" */ CWORD_CWORD_CWORD_CWORD,
2798 /* 71 "G" */ CWORD_CWORD_CWORD_CWORD,
2799 /* 72 "H" */ CWORD_CWORD_CWORD_CWORD,
2800 /* 73 "I" */ CWORD_CWORD_CWORD_CWORD,
2801 /* 74 "J" */ CWORD_CWORD_CWORD_CWORD,
2802 /* 75 "K" */ CWORD_CWORD_CWORD_CWORD,
2803 /* 76 "L" */ CWORD_CWORD_CWORD_CWORD,
2804 /* 77 "M" */ CWORD_CWORD_CWORD_CWORD,
2805 /* 78 "N" */ CWORD_CWORD_CWORD_CWORD,
2806 /* 79 "O" */ CWORD_CWORD_CWORD_CWORD,
2807 /* 80 "P" */ CWORD_CWORD_CWORD_CWORD,
2808 /* 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
2809 /* 82 "R" */ CWORD_CWORD_CWORD_CWORD,
2810 /* 83 "S" */ CWORD_CWORD_CWORD_CWORD,
2811 /* 84 "T" */ CWORD_CWORD_CWORD_CWORD,
2812 /* 85 "U" */ CWORD_CWORD_CWORD_CWORD,
2813 /* 86 "V" */ CWORD_CWORD_CWORD_CWORD,
2814 /* 87 "W" */ CWORD_CWORD_CWORD_CWORD,
2815 /* 88 "X" */ CWORD_CWORD_CWORD_CWORD,
2816 /* 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
2817 /* 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
2818 /* 91 "[" */ CWORD_CCTL_CCTL_CWORD,
2819 /* 92 "\" */ CBACK_CBACK_CCTL_CBACK,
2820 /* 93 "]" */ CWORD_CCTL_CCTL_CWORD,
2821 /* 94 "^" */ CWORD_CWORD_CWORD_CWORD,
2822 /* 95 "_" */ CWORD_CWORD_CWORD_CWORD,
2823 /* 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
2824 /* 97 "a" */ CWORD_CWORD_CWORD_CWORD,
2825 /* 98 "b" */ CWORD_CWORD_CWORD_CWORD,
2826 /* 99 "c" */ CWORD_CWORD_CWORD_CWORD,
2827 /* 100 "d" */ CWORD_CWORD_CWORD_CWORD,
2828 /* 101 "e" */ CWORD_CWORD_CWORD_CWORD,
2829 /* 102 "f" */ CWORD_CWORD_CWORD_CWORD,
2830 /* 103 "g" */ CWORD_CWORD_CWORD_CWORD,
2831 /* 104 "h" */ CWORD_CWORD_CWORD_CWORD,
2832 /* 105 "i" */ CWORD_CWORD_CWORD_CWORD,
2833 /* 106 "j" */ CWORD_CWORD_CWORD_CWORD,
2834 /* 107 "k" */ CWORD_CWORD_CWORD_CWORD,
2835 /* 108 "l" */ CWORD_CWORD_CWORD_CWORD,
2836 /* 109 "m" */ CWORD_CWORD_CWORD_CWORD,
2837 /* 110 "n" */ CWORD_CWORD_CWORD_CWORD,
2838 /* 111 "o" */ CWORD_CWORD_CWORD_CWORD,
2839 /* 112 "p" */ CWORD_CWORD_CWORD_CWORD,
2840 /* 113 "q" */ CWORD_CWORD_CWORD_CWORD,
2841 /* 114 "r" */ CWORD_CWORD_CWORD_CWORD,
2842 /* 115 "s" */ CWORD_CWORD_CWORD_CWORD,
2843 /* 116 "t" */ CWORD_CWORD_CWORD_CWORD,
2844 /* 117 "u" */ CWORD_CWORD_CWORD_CWORD,
2845 /* 118 "v" */ CWORD_CWORD_CWORD_CWORD,
2846 /* 119 "w" */ CWORD_CWORD_CWORD_CWORD,
2847 /* 120 "x" */ CWORD_CWORD_CWORD_CWORD,
2848 /* 121 "y" */ CWORD_CWORD_CWORD_CWORD,
2849 /* 122 "z" */ CWORD_CWORD_CWORD_CWORD,
2850 /* 123 "{" */ CWORD_CWORD_CWORD_CWORD,
2851 /* 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
2852 /* 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
2853 /* 126 "~" */ CWORD_CCTL_CCTL_CWORD,
2854 /* 127 del */ CWORD_CWORD_CWORD_CWORD,
2855 /* 128 0x80 */ CWORD_CWORD_CWORD_CWORD,
2856 /* 129 CTLESC */ CCTL_CCTL_CCTL_CCTL,
2857 /* 130 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
2858 /* 131 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
2859 /* 132 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
2860 /* 133 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
2861 /* 134 CTLARI */ CCTL_CCTL_CCTL_CCTL,
2862 /* 135 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
2863 /* 136 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
2864 /* 137 */ CWORD_CWORD_CWORD_CWORD,
2865 /* 138 */ CWORD_CWORD_CWORD_CWORD,
2866 /* 139 */ CWORD_CWORD_CWORD_CWORD,
2867 /* 140 */ CWORD_CWORD_CWORD_CWORD,
2868 /* 141 */ CWORD_CWORD_CWORD_CWORD,
2869 /* 142 */ CWORD_CWORD_CWORD_CWORD,
2870 /* 143 */ CWORD_CWORD_CWORD_CWORD,
2871 /* 144 */ CWORD_CWORD_CWORD_CWORD,
2872 /* 145 */ CWORD_CWORD_CWORD_CWORD,
2873 /* 146 */ CWORD_CWORD_CWORD_CWORD,
2874 /* 147 */ CWORD_CWORD_CWORD_CWORD,
2875 /* 148 */ CWORD_CWORD_CWORD_CWORD,
2876 /* 149 */ CWORD_CWORD_CWORD_CWORD,
2877 /* 150 */ CWORD_CWORD_CWORD_CWORD,
2878 /* 151 */ CWORD_CWORD_CWORD_CWORD,
2879 /* 152 */ CWORD_CWORD_CWORD_CWORD,
2880 /* 153 */ CWORD_CWORD_CWORD_CWORD,
2881 /* 154 */ CWORD_CWORD_CWORD_CWORD,
2882 /* 155 */ CWORD_CWORD_CWORD_CWORD,
2883 /* 156 */ CWORD_CWORD_CWORD_CWORD,
2884 /* 157 */ CWORD_CWORD_CWORD_CWORD,
2885 /* 158 */ CWORD_CWORD_CWORD_CWORD,
2886 /* 159 */ CWORD_CWORD_CWORD_CWORD,
2887 /* 160 */ CWORD_CWORD_CWORD_CWORD,
2888 /* 161 */ CWORD_CWORD_CWORD_CWORD,
2889 /* 162 */ CWORD_CWORD_CWORD_CWORD,
2890 /* 163 */ CWORD_CWORD_CWORD_CWORD,
2891 /* 164 */ CWORD_CWORD_CWORD_CWORD,
2892 /* 165 */ CWORD_CWORD_CWORD_CWORD,
2893 /* 166 */ CWORD_CWORD_CWORD_CWORD,
2894 /* 167 */ CWORD_CWORD_CWORD_CWORD,
2895 /* 168 */ CWORD_CWORD_CWORD_CWORD,
2896 /* 169 */ CWORD_CWORD_CWORD_CWORD,
2897 /* 170 */ CWORD_CWORD_CWORD_CWORD,
2898 /* 171 */ CWORD_CWORD_CWORD_CWORD,
2899 /* 172 */ CWORD_CWORD_CWORD_CWORD,
2900 /* 173 */ CWORD_CWORD_CWORD_CWORD,
2901 /* 174 */ CWORD_CWORD_CWORD_CWORD,
2902 /* 175 */ CWORD_CWORD_CWORD_CWORD,
2903 /* 176 */ CWORD_CWORD_CWORD_CWORD,
2904 /* 177 */ CWORD_CWORD_CWORD_CWORD,
2905 /* 178 */ CWORD_CWORD_CWORD_CWORD,
2906 /* 179 */ CWORD_CWORD_CWORD_CWORD,
2907 /* 180 */ CWORD_CWORD_CWORD_CWORD,
2908 /* 181 */ CWORD_CWORD_CWORD_CWORD,
2909 /* 182 */ CWORD_CWORD_CWORD_CWORD,
2910 /* 183 */ CWORD_CWORD_CWORD_CWORD,
2911 /* 184 */ CWORD_CWORD_CWORD_CWORD,
2912 /* 185 */ CWORD_CWORD_CWORD_CWORD,
2913 /* 186 */ CWORD_CWORD_CWORD_CWORD,
2914 /* 187 */ CWORD_CWORD_CWORD_CWORD,
2915 /* 188 */ CWORD_CWORD_CWORD_CWORD,
2916 /* 189 */ CWORD_CWORD_CWORD_CWORD,
2917 /* 190 */ CWORD_CWORD_CWORD_CWORD,
2918 /* 191 */ CWORD_CWORD_CWORD_CWORD,
2919 /* 192 */ CWORD_CWORD_CWORD_CWORD,
2920 /* 193 */ CWORD_CWORD_CWORD_CWORD,
2921 /* 194 */ CWORD_CWORD_CWORD_CWORD,
2922 /* 195 */ CWORD_CWORD_CWORD_CWORD,
2923 /* 196 */ CWORD_CWORD_CWORD_CWORD,
2924 /* 197 */ CWORD_CWORD_CWORD_CWORD,
2925 /* 198 */ CWORD_CWORD_CWORD_CWORD,
2926 /* 199 */ CWORD_CWORD_CWORD_CWORD,
2927 /* 200 */ CWORD_CWORD_CWORD_CWORD,
2928 /* 201 */ CWORD_CWORD_CWORD_CWORD,
2929 /* 202 */ CWORD_CWORD_CWORD_CWORD,
2930 /* 203 */ CWORD_CWORD_CWORD_CWORD,
2931 /* 204 */ CWORD_CWORD_CWORD_CWORD,
2932 /* 205 */ CWORD_CWORD_CWORD_CWORD,
2933 /* 206 */ CWORD_CWORD_CWORD_CWORD,
2934 /* 207 */ CWORD_CWORD_CWORD_CWORD,
2935 /* 208 */ CWORD_CWORD_CWORD_CWORD,
2936 /* 209 */ CWORD_CWORD_CWORD_CWORD,
2937 /* 210 */ CWORD_CWORD_CWORD_CWORD,
2938 /* 211 */ CWORD_CWORD_CWORD_CWORD,
2939 /* 212 */ CWORD_CWORD_CWORD_CWORD,
2940 /* 213 */ CWORD_CWORD_CWORD_CWORD,
2941 /* 214 */ CWORD_CWORD_CWORD_CWORD,
2942 /* 215 */ CWORD_CWORD_CWORD_CWORD,
2943 /* 216 */ CWORD_CWORD_CWORD_CWORD,
2944 /* 217 */ CWORD_CWORD_CWORD_CWORD,
2945 /* 218 */ CWORD_CWORD_CWORD_CWORD,
2946 /* 219 */ CWORD_CWORD_CWORD_CWORD,
2947 /* 220 */ CWORD_CWORD_CWORD_CWORD,
2948 /* 221 */ CWORD_CWORD_CWORD_CWORD,
2949 /* 222 */ CWORD_CWORD_CWORD_CWORD,
2950 /* 223 */ CWORD_CWORD_CWORD_CWORD,
2951 /* 224 */ CWORD_CWORD_CWORD_CWORD,
2952 /* 225 */ CWORD_CWORD_CWORD_CWORD,
2953 /* 226 */ CWORD_CWORD_CWORD_CWORD,
2954 /* 227 */ CWORD_CWORD_CWORD_CWORD,
2955 /* 228 */ CWORD_CWORD_CWORD_CWORD,
2956 /* 229 */ CWORD_CWORD_CWORD_CWORD,
2957 /* 230 */ CWORD_CWORD_CWORD_CWORD,
2958 /* 231 */ CWORD_CWORD_CWORD_CWORD,
2959 /* 232 */ CWORD_CWORD_CWORD_CWORD,
2960 /* 233 */ CWORD_CWORD_CWORD_CWORD,
2961 /* 234 */ CWORD_CWORD_CWORD_CWORD,
2962 /* 235 */ CWORD_CWORD_CWORD_CWORD,
2963 /* 236 */ CWORD_CWORD_CWORD_CWORD,
2964 /* 237 */ CWORD_CWORD_CWORD_CWORD,
2965 /* 238 */ CWORD_CWORD_CWORD_CWORD,
2966 /* 239 */ CWORD_CWORD_CWORD_CWORD,
2967 /* 230 */ CWORD_CWORD_CWORD_CWORD,
2968 /* 241 */ CWORD_CWORD_CWORD_CWORD,
2969 /* 242 */ CWORD_CWORD_CWORD_CWORD,
2970 /* 243 */ CWORD_CWORD_CWORD_CWORD,
2971 /* 244 */ CWORD_CWORD_CWORD_CWORD,
2972 /* 245 */ CWORD_CWORD_CWORD_CWORD,
2973 /* 246 */ CWORD_CWORD_CWORD_CWORD,
2974 /* 247 */ CWORD_CWORD_CWORD_CWORD,
2975 /* 248 */ CWORD_CWORD_CWORD_CWORD,
2976 /* 249 */ CWORD_CWORD_CWORD_CWORD,
2977 /* 250 */ CWORD_CWORD_CWORD_CWORD,
2978 /* 251 */ CWORD_CWORD_CWORD_CWORD,
2979 /* 252 */ CWORD_CWORD_CWORD_CWORD,
2980 /* 253 */ CWORD_CWORD_CWORD_CWORD,
2981 /* 254 */ CWORD_CWORD_CWORD_CWORD,
2982 /* 255 */ CWORD_CWORD_CWORD_CWORD,
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002983 /* PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
Denys Vlasenkocd716832009-11-28 22:14:02 +01002984# if ENABLE_ASH_ALIAS
2985 /* PEOA */ CSPCL_CIGN_CIGN_CIGN,
2986# endif
Eric Andersen2870d962001-07-02 17:27:21 +00002987};
2988
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002989# define SIT(c, syntax) ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf)
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00002990
Denys Vlasenko76bc2d62009-11-29 01:37:46 +01002991#endif /* !USE_SIT_FUNCTION */
Eric Andersenc470f442003-07-28 09:56:35 +00002992
Eric Andersen2870d962001-07-02 17:27:21 +00002993
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00002994/* ============ Alias handling */
Denis Vlasenkofc06f292007-02-23 21:09:35 +00002995
Denis Vlasenko131ae172007-02-18 13:00:19 +00002996#if ENABLE_ASH_ALIAS
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00002997
2998#define ALIASINUSE 1
2999#define ALIASDEAD 2
3000
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00003001struct alias {
3002 struct alias *next;
3003 char *name;
3004 char *val;
3005 int flag;
3006};
3007
Denis Vlasenko01631112007-12-16 17:20:38 +00003008
3009static struct alias **atab; // [ATABSIZE];
3010#define INIT_G_alias() do { \
3011 atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
3012} while (0)
3013
Eric Andersen2870d962001-07-02 17:27:21 +00003014
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00003015static struct alias **
3016__lookupalias(const char *name) {
3017 unsigned int hashval;
3018 struct alias **app;
3019 const char *p;
3020 unsigned int ch;
3021
3022 p = name;
3023
3024 ch = (unsigned char)*p;
3025 hashval = ch << 4;
3026 while (ch) {
3027 hashval += ch;
3028 ch = (unsigned char)*++p;
3029 }
3030 app = &atab[hashval % ATABSIZE];
3031
3032 for (; *app; app = &(*app)->next) {
3033 if (strcmp(name, (*app)->name) == 0) {
3034 break;
3035 }
3036 }
3037
3038 return app;
3039}
3040
3041static struct alias *
3042lookupalias(const char *name, int check)
3043{
3044 struct alias *ap = *__lookupalias(name);
3045
3046 if (check && ap && (ap->flag & ALIASINUSE))
3047 return NULL;
3048 return ap;
3049}
3050
3051static struct alias *
3052freealias(struct alias *ap)
3053{
3054 struct alias *next;
3055
3056 if (ap->flag & ALIASINUSE) {
3057 ap->flag |= ALIASDEAD;
3058 return ap;
3059 }
3060
3061 next = ap->next;
3062 free(ap->name);
3063 free(ap->val);
3064 free(ap);
3065 return next;
3066}
Eric Andersencb57d552001-06-28 07:25:16 +00003067
Eric Andersenc470f442003-07-28 09:56:35 +00003068static void
3069setalias(const char *name, const char *val)
Eric Andersencb57d552001-06-28 07:25:16 +00003070{
3071 struct alias *ap, **app;
3072
3073 app = __lookupalias(name);
3074 ap = *app;
Denis Vlasenkob012b102007-02-19 22:43:01 +00003075 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +00003076 if (ap) {
3077 if (!(ap->flag & ALIASINUSE)) {
Denis Vlasenkob012b102007-02-19 22:43:01 +00003078 free(ap->val);
Eric Andersencb57d552001-06-28 07:25:16 +00003079 }
Denis Vlasenko0c032a42007-02-23 01:03:40 +00003080 ap->val = ckstrdup(val);
Eric Andersencb57d552001-06-28 07:25:16 +00003081 ap->flag &= ~ALIASDEAD;
3082 } else {
3083 /* not found */
Denis Vlasenko597906c2008-02-20 16:38:54 +00003084 ap = ckzalloc(sizeof(struct alias));
Denis Vlasenko0c032a42007-02-23 01:03:40 +00003085 ap->name = ckstrdup(name);
3086 ap->val = ckstrdup(val);
Denis Vlasenko597906c2008-02-20 16:38:54 +00003087 /*ap->flag = 0; - ckzalloc did it */
3088 /*ap->next = NULL;*/
Eric Andersencb57d552001-06-28 07:25:16 +00003089 *app = ap;
3090 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00003091 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00003092}
3093
Eric Andersenc470f442003-07-28 09:56:35 +00003094static int
3095unalias(const char *name)
Eric Andersen2870d962001-07-02 17:27:21 +00003096{
Eric Andersencb57d552001-06-28 07:25:16 +00003097 struct alias **app;
3098
3099 app = __lookupalias(name);
3100
3101 if (*app) {
Denis Vlasenkob012b102007-02-19 22:43:01 +00003102 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +00003103 *app = freealias(*app);
Denis Vlasenkob012b102007-02-19 22:43:01 +00003104 INT_ON;
Denis Vlasenko079f8af2006-11-27 16:49:31 +00003105 return 0;
Eric Andersencb57d552001-06-28 07:25:16 +00003106 }
3107
Denis Vlasenko079f8af2006-11-27 16:49:31 +00003108 return 1;
Eric Andersencb57d552001-06-28 07:25:16 +00003109}
3110
Eric Andersenc470f442003-07-28 09:56:35 +00003111static void
3112rmaliases(void)
Eric Andersen2870d962001-07-02 17:27:21 +00003113{
Eric Andersencb57d552001-06-28 07:25:16 +00003114 struct alias *ap, **app;
3115 int i;
3116
Denis Vlasenkob012b102007-02-19 22:43:01 +00003117 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +00003118 for (i = 0; i < ATABSIZE; i++) {
3119 app = &atab[i];
3120 for (ap = *app; ap; ap = *app) {
3121 *app = freealias(*app);
3122 if (ap == *app) {
3123 app = &ap->next;
3124 }
3125 }
3126 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00003127 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00003128}
3129
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00003130static void
3131printalias(const struct alias *ap)
3132{
3133 out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
3134}
3135
Eric Andersencb57d552001-06-28 07:25:16 +00003136/*
3137 * TODO - sort output
3138 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02003139static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00003140aliascmd(int argc UNUSED_PARAM, char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +00003141{
3142 char *n, *v;
3143 int ret = 0;
3144 struct alias *ap;
3145
Denis Vlasenko68404f12008-03-17 09:00:54 +00003146 if (!argv[1]) {
Eric Andersencb57d552001-06-28 07:25:16 +00003147 int i;
3148
Denis Vlasenko68404f12008-03-17 09:00:54 +00003149 for (i = 0; i < ATABSIZE; i++) {
Eric Andersencb57d552001-06-28 07:25:16 +00003150 for (ap = atab[i]; ap; ap = ap->next) {
3151 printalias(ap);
3152 }
Denis Vlasenko68404f12008-03-17 09:00:54 +00003153 }
Denis Vlasenko079f8af2006-11-27 16:49:31 +00003154 return 0;
Eric Andersencb57d552001-06-28 07:25:16 +00003155 }
3156 while ((n = *++argv) != NULL) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00003157 v = strchr(n+1, '=');
3158 if (v == NULL) { /* n+1: funny ksh stuff */
3159 ap = *__lookupalias(n);
3160 if (ap == NULL) {
Eric Andersenc470f442003-07-28 09:56:35 +00003161 fprintf(stderr, "%s: %s not found\n", "alias", n);
Eric Andersencb57d552001-06-28 07:25:16 +00003162 ret = 1;
3163 } else
3164 printalias(ap);
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00003165 } else {
Eric Andersencb57d552001-06-28 07:25:16 +00003166 *v++ = '\0';
3167 setalias(n, v);
3168 }
3169 }
3170
Denis Vlasenkod9e15f22006-11-27 16:49:55 +00003171 return ret;
Eric Andersencb57d552001-06-28 07:25:16 +00003172}
3173
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02003174static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00003175unaliascmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersencb57d552001-06-28 07:25:16 +00003176{
3177 int i;
3178
3179 while ((i = nextopt("a")) != '\0') {
3180 if (i == 'a') {
3181 rmaliases();
Denis Vlasenko079f8af2006-11-27 16:49:31 +00003182 return 0;
Eric Andersencb57d552001-06-28 07:25:16 +00003183 }
3184 }
3185 for (i = 0; *argptr; argptr++) {
3186 if (unalias(*argptr)) {
Eric Andersenc470f442003-07-28 09:56:35 +00003187 fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
Eric Andersencb57d552001-06-28 07:25:16 +00003188 i = 1;
3189 }
3190 }
3191
Denis Vlasenkod9e15f22006-11-27 16:49:55 +00003192 return i;
Eric Andersencb57d552001-06-28 07:25:16 +00003193}
Denis Vlasenkofc06f292007-02-23 21:09:35 +00003194
Denis Vlasenko131ae172007-02-18 13:00:19 +00003195#endif /* ASH_ALIAS */
Eric Andersencb57d552001-06-28 07:25:16 +00003196
Eric Andersenc470f442003-07-28 09:56:35 +00003197
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003198/* ============ jobs.c */
3199
3200/* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
Denys Vlasenko285ad152009-12-04 23:02:27 +01003201#define FORK_FG 0
3202#define FORK_BG 1
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003203#define FORK_NOJOB 2
3204
3205/* mode flags for showjob(s) */
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003206#define SHOW_ONLY_PGID 0x01 /* show only pgid (jobs -p) */
3207#define SHOW_PIDS 0x02 /* show individual pids, not just one line per job */
3208#define SHOW_CHANGED 0x04 /* only jobs whose state has changed */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003209
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003210/*
3211 * A job structure contains information about a job. A job is either a
3212 * single process or a set of processes contained in a pipeline. In the
3213 * latter case, pidlist will be non-NULL, and will point to a -1 terminated
3214 * array of pids.
3215 */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003216struct procstat {
Denys Vlasenko285ad152009-12-04 23:02:27 +01003217 pid_t ps_pid; /* process id */
3218 int ps_status; /* last process status from wait() */
3219 char *ps_cmd; /* text of command being run */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003220};
3221
3222struct job {
3223 struct procstat ps0; /* status of process */
3224 struct procstat *ps; /* status or processes when more than one */
3225#if JOBS
3226 int stopstatus; /* status of a stopped job */
3227#endif
3228 uint32_t
3229 nprocs: 16, /* number of processes */
3230 state: 8,
3231#define JOBRUNNING 0 /* at least one proc running */
3232#define JOBSTOPPED 1 /* all procs are stopped */
3233#define JOBDONE 2 /* all procs are completed */
3234#if JOBS
3235 sigint: 1, /* job was killed by SIGINT */
3236 jobctl: 1, /* job running under job control */
3237#endif
3238 waited: 1, /* true if this entry has been waited for */
3239 used: 1, /* true if this entry is in used */
3240 changed: 1; /* true if status has changed */
3241 struct job *prev_job; /* previous job */
3242};
3243
Denis Vlasenko68404f12008-03-17 09:00:54 +00003244static struct job *makejob(/*union node *,*/ int);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003245static int forkshell(struct job *, union node *, int);
3246static int waitforjob(struct job *);
3247
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003248#if !JOBS
Denis Vlasenkob07a4962008-06-22 13:16:23 +00003249enum { doing_jobctl = 0 };
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003250#define setjobctl(on) do {} while (0)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003251#else
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003252static smallint doing_jobctl; //references:8
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003253static void setjobctl(int);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003254#endif
3255
3256/*
Denis Vlasenko4b875702009-03-19 13:30:04 +00003257 * Ignore a signal.
3258 */
3259static void
3260ignoresig(int signo)
3261{
3262 /* Avoid unnecessary system calls. Is it already SIG_IGNed? */
3263 if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
3264 /* No, need to do it */
3265 signal(signo, SIG_IGN);
3266 }
3267 sigmode[signo - 1] = S_HARD_IGN;
3268}
3269
3270/*
Denys Vlasenko238bf182010-05-18 15:49:07 +02003271 * Only one usage site - in setsignal()
Denis Vlasenko4b875702009-03-19 13:30:04 +00003272 */
3273static void
Denys Vlasenko238bf182010-05-18 15:49:07 +02003274signal_handler(int signo)
Denis Vlasenko4b875702009-03-19 13:30:04 +00003275{
3276 gotsig[signo - 1] = 1;
3277
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02003278 if (signo == SIGINT && !trap[SIGINT]) {
3279 if (!suppress_int) {
3280 pending_sig = 0;
Denis Vlasenko4b875702009-03-19 13:30:04 +00003281 raise_interrupt(); /* does not return */
3282 }
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02003283 pending_int = 1;
Denis Vlasenko4b875702009-03-19 13:30:04 +00003284 } else {
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02003285 pending_sig = signo;
Denis Vlasenko4b875702009-03-19 13:30:04 +00003286 }
3287}
3288
3289/*
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003290 * Set the signal handler for the specified signal. The routine figures
3291 * out what it should be set to.
3292 */
3293static void
3294setsignal(int signo)
3295{
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003296 char *t;
3297 char cur_act, new_act;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003298 struct sigaction act;
3299
3300 t = trap[signo];
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003301 new_act = S_DFL;
3302 if (t != NULL) { /* trap for this sig is set */
3303 new_act = S_CATCH;
3304 if (t[0] == '\0') /* trap is "": ignore this sig */
3305 new_act = S_IGN;
3306 }
3307
3308 if (rootshell && new_act == S_DFL) {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003309 switch (signo) {
3310 case SIGINT:
3311 if (iflag || minusc || sflag == 0)
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003312 new_act = S_CATCH;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003313 break;
3314 case SIGQUIT:
3315#if DEBUG
3316 if (debug)
3317 break;
3318#endif
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003319 /* man bash:
3320 * "In all cases, bash ignores SIGQUIT. Non-builtin
3321 * commands run by bash have signal handlers
3322 * set to the values inherited by the shell
3323 * from its parent". */
3324 new_act = S_IGN;
3325 break;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003326 case SIGTERM:
3327 if (iflag)
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003328 new_act = S_IGN;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003329 break;
3330#if JOBS
3331 case SIGTSTP:
3332 case SIGTTOU:
3333 if (mflag)
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003334 new_act = S_IGN;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003335 break;
3336#endif
3337 }
3338 }
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003339//TODO: if !rootshell, we reset SIGQUIT to DFL,
3340//whereas we have to restore it to what shell got on entry
3341//from the parent. See comment above
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003342
3343 t = &sigmode[signo - 1];
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003344 cur_act = *t;
3345 if (cur_act == 0) {
3346 /* current setting is not yet known */
3347 if (sigaction(signo, NULL, &act)) {
3348 /* pretend it worked; maybe we should give a warning,
3349 * but other shells don't. We don't alter sigmode,
3350 * so we retry every time.
3351 * btw, in Linux it never fails. --vda */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003352 return;
3353 }
3354 if (act.sa_handler == SIG_IGN) {
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003355 cur_act = S_HARD_IGN;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003356 if (mflag
3357 && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
3358 ) {
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003359 cur_act = S_IGN; /* don't hard ignore these */
Denis Vlasenko991a1da2008-02-10 19:02:53 +00003360 }
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003361 }
3362 }
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003363 if (cur_act == S_HARD_IGN || cur_act == new_act)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003364 return;
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003365
Denis Vlasenko991a1da2008-02-10 19:02:53 +00003366 act.sa_handler = SIG_DFL;
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003367 switch (new_act) {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003368 case S_CATCH:
Denys Vlasenko238bf182010-05-18 15:49:07 +02003369 act.sa_handler = signal_handler;
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003370 act.sa_flags = 0; /* matters only if !DFL and !IGN */
3371 sigfillset(&act.sa_mask); /* ditto */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003372 break;
3373 case S_IGN:
3374 act.sa_handler = SIG_IGN;
3375 break;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003376 }
Denis Vlasenko8e2cfec2008-03-12 23:19:35 +00003377 sigaction_set(signo, &act);
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003378
3379 *t = new_act;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003380}
3381
3382/* mode flags for set_curjob */
3383#define CUR_DELETE 2
3384#define CUR_RUNNING 1
3385#define CUR_STOPPED 0
3386
3387/* mode flags for dowait */
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00003388#define DOWAIT_NONBLOCK WNOHANG
3389#define DOWAIT_BLOCK 0
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003390
3391#if JOBS
3392/* pgrp of shell on invocation */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003393static int initialpgrp; //references:2
3394static int ttyfd = -1; //5
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003395#endif
3396/* array of jobs */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003397static struct job *jobtab; //5
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003398/* size of array */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003399static unsigned njobs; //4
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003400/* current job */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003401static struct job *curjob; //lots
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003402/* number of presumed living untracked jobs */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003403static int jobless; //4
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003404
3405static void
3406set_curjob(struct job *jp, unsigned mode)
3407{
3408 struct job *jp1;
3409 struct job **jpp, **curp;
3410
3411 /* first remove from list */
3412 jpp = curp = &curjob;
3413 do {
3414 jp1 = *jpp;
3415 if (jp1 == jp)
3416 break;
3417 jpp = &jp1->prev_job;
3418 } while (1);
3419 *jpp = jp1->prev_job;
3420
3421 /* Then re-insert in correct position */
3422 jpp = curp;
3423 switch (mode) {
3424 default:
3425#if DEBUG
3426 abort();
3427#endif
3428 case CUR_DELETE:
3429 /* job being deleted */
3430 break;
3431 case CUR_RUNNING:
3432 /* newly created job or backgrounded job,
3433 put after all stopped jobs. */
3434 do {
3435 jp1 = *jpp;
3436#if JOBS
3437 if (!jp1 || jp1->state != JOBSTOPPED)
3438#endif
3439 break;
3440 jpp = &jp1->prev_job;
3441 } while (1);
3442 /* FALLTHROUGH */
3443#if JOBS
3444 case CUR_STOPPED:
3445#endif
3446 /* newly stopped job - becomes curjob */
3447 jp->prev_job = *jpp;
3448 *jpp = jp;
3449 break;
3450 }
3451}
3452
3453#if JOBS || DEBUG
3454static int
3455jobno(const struct job *jp)
3456{
3457 return jp - jobtab + 1;
3458}
3459#endif
3460
3461/*
3462 * Convert a job name to a job structure.
3463 */
Denis Vlasenko85c24712008-03-17 09:04:04 +00003464#if !JOBS
3465#define getjob(name, getctl) getjob(name)
3466#endif
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003467static struct job *
3468getjob(const char *name, int getctl)
3469{
3470 struct job *jp;
3471 struct job *found;
Denys Vlasenkoffc39202009-08-17 02:12:20 +02003472 const char *err_msg = "%s: no such job";
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003473 unsigned num;
3474 int c;
3475 const char *p;
3476 char *(*match)(const char *, const char *);
3477
3478 jp = curjob;
3479 p = name;
3480 if (!p)
3481 goto currentjob;
3482
3483 if (*p != '%')
3484 goto err;
3485
3486 c = *++p;
3487 if (!c)
3488 goto currentjob;
3489
3490 if (!p[1]) {
3491 if (c == '+' || c == '%') {
3492 currentjob:
3493 err_msg = "No current job";
3494 goto check;
3495 }
3496 if (c == '-') {
3497 if (jp)
3498 jp = jp->prev_job;
3499 err_msg = "No previous job";
3500 check:
3501 if (!jp)
3502 goto err;
3503 goto gotit;
3504 }
3505 }
3506
3507 if (is_number(p)) {
3508 num = atoi(p);
3509 if (num < njobs) {
3510 jp = jobtab + num - 1;
3511 if (jp->used)
3512 goto gotit;
3513 goto err;
3514 }
3515 }
3516
3517 match = prefix;
3518 if (*p == '?') {
3519 match = strstr;
3520 p++;
3521 }
3522
Denys Vlasenkoffc39202009-08-17 02:12:20 +02003523 found = NULL;
3524 while (jp) {
Denys Vlasenko285ad152009-12-04 23:02:27 +01003525 if (match(jp->ps[0].ps_cmd, p)) {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003526 if (found)
3527 goto err;
3528 found = jp;
3529 err_msg = "%s: ambiguous";
3530 }
3531 jp = jp->prev_job;
3532 }
Denys Vlasenkoffc39202009-08-17 02:12:20 +02003533 if (!found)
3534 goto err;
3535 jp = found;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003536
3537 gotit:
3538#if JOBS
3539 err_msg = "job %s not created under job control";
3540 if (getctl && jp->jobctl == 0)
3541 goto err;
3542#endif
3543 return jp;
3544 err:
3545 ash_msg_and_raise_error(err_msg, name);
3546}
3547
3548/*
3549 * Mark a job structure as unused.
3550 */
3551static void
3552freejob(struct job *jp)
3553{
3554 struct procstat *ps;
3555 int i;
3556
3557 INT_OFF;
3558 for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
Denys Vlasenko285ad152009-12-04 23:02:27 +01003559 if (ps->ps_cmd != nullstr)
3560 free(ps->ps_cmd);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003561 }
3562 if (jp->ps != &jp->ps0)
3563 free(jp->ps);
3564 jp->used = 0;
3565 set_curjob(jp, CUR_DELETE);
3566 INT_ON;
3567}
3568
3569#if JOBS
3570static void
3571xtcsetpgrp(int fd, pid_t pgrp)
3572{
3573 if (tcsetpgrp(fd, pgrp))
Bernhard Reutner-Fischera53de7f2008-07-21 13:46:54 +00003574 ash_msg_and_raise_error("can't set tty process group (%m)");
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003575}
3576
3577/*
3578 * Turn job control on and off.
3579 *
3580 * Note: This code assumes that the third arg to ioctl is a character
3581 * pointer, which is true on Berkeley systems but not System V. Since
3582 * System V doesn't have job control yet, this isn't a problem now.
3583 *
3584 * Called with interrupts off.
3585 */
3586static void
3587setjobctl(int on)
3588{
3589 int fd;
3590 int pgrp;
3591
Denis Vlasenkob07a4962008-06-22 13:16:23 +00003592 if (on == doing_jobctl || rootshell == 0)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003593 return;
3594 if (on) {
3595 int ofd;
3596 ofd = fd = open(_PATH_TTY, O_RDWR);
3597 if (fd < 0) {
3598 /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
3599 * That sometimes helps to acquire controlling tty.
3600 * Obviously, a workaround for bugs when someone
3601 * failed to provide a controlling tty to bash! :) */
Denis Vlasenkoed270a52007-11-26 05:37:07 +00003602 fd = 2;
3603 while (!isatty(fd))
3604 if (--fd < 0)
3605 goto out;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003606 }
3607 fd = fcntl(fd, F_DUPFD, 10);
Denis Vlasenkoed270a52007-11-26 05:37:07 +00003608 if (ofd >= 0)
3609 close(ofd);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003610 if (fd < 0)
3611 goto out;
Denis Vlasenkoed270a52007-11-26 05:37:07 +00003612 /* fd is a tty at this point */
Denis Vlasenko96e1b382007-09-30 23:50:48 +00003613 close_on_exec_on(fd);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003614 do { /* while we are in the background */
3615 pgrp = tcgetpgrp(fd);
3616 if (pgrp < 0) {
3617 out:
3618 ash_msg("can't access tty; job control turned off");
3619 mflag = on = 0;
3620 goto close;
3621 }
3622 if (pgrp == getpgrp())
3623 break;
3624 killpg(0, SIGTTIN);
3625 } while (1);
3626 initialpgrp = pgrp;
3627
3628 setsignal(SIGTSTP);
3629 setsignal(SIGTTOU);
3630 setsignal(SIGTTIN);
3631 pgrp = rootpid;
3632 setpgid(0, pgrp);
3633 xtcsetpgrp(fd, pgrp);
3634 } else {
3635 /* turning job control off */
3636 fd = ttyfd;
3637 pgrp = initialpgrp;
Denis Vlasenko08c8c1d2007-04-28 22:39:02 +00003638 /* was xtcsetpgrp, but this can make exiting ash
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00003639 * loop forever if pty is already deleted */
Denis Vlasenko08c8c1d2007-04-28 22:39:02 +00003640 tcsetpgrp(fd, pgrp);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003641 setpgid(0, pgrp);
3642 setsignal(SIGTSTP);
3643 setsignal(SIGTTOU);
3644 setsignal(SIGTTIN);
3645 close:
Denis Vlasenkoed270a52007-11-26 05:37:07 +00003646 if (fd >= 0)
3647 close(fd);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003648 fd = -1;
3649 }
3650 ttyfd = fd;
Denis Vlasenkob07a4962008-06-22 13:16:23 +00003651 doing_jobctl = on;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003652}
3653
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02003654static int FAST_FUNC
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003655killcmd(int argc, char **argv)
3656{
Denis Vlasenko68404f12008-03-17 09:00:54 +00003657 int i = 1;
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003658 if (argv[1] && strcmp(argv[1], "-l") != 0) {
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003659 do {
3660 if (argv[i][0] == '%') {
3661 struct job *jp = getjob(argv[i], 0);
Denys Vlasenko285ad152009-12-04 23:02:27 +01003662 unsigned pid = jp->ps[0].ps_pid;
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003663 /* Enough space for ' -NNN<nul>' */
3664 argv[i] = alloca(sizeof(int)*3 + 3);
3665 /* kill_main has matching code to expect
3666 * leading space. Needed to not confuse
3667 * negative pids with "kill -SIGNAL_NO" syntax */
3668 sprintf(argv[i], " -%u", pid);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003669 }
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003670 } while (argv[++i]);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003671 }
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003672 return kill_main(argc, argv);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003673}
3674
3675static void
Denys Vlasenko285ad152009-12-04 23:02:27 +01003676showpipe(struct job *jp /*, FILE *out*/)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003677{
Denys Vlasenko285ad152009-12-04 23:02:27 +01003678 struct procstat *ps;
3679 struct procstat *psend;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003680
Denys Vlasenko285ad152009-12-04 23:02:27 +01003681 psend = jp->ps + jp->nprocs;
3682 for (ps = jp->ps + 1; ps < psend; ps++)
3683 printf(" | %s", ps->ps_cmd);
3684 outcslow('\n', stdout);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003685 flush_stdout_stderr();
3686}
3687
3688
3689static int
3690restartjob(struct job *jp, int mode)
3691{
3692 struct procstat *ps;
3693 int i;
3694 int status;
3695 pid_t pgid;
3696
3697 INT_OFF;
3698 if (jp->state == JOBDONE)
3699 goto out;
3700 jp->state = JOBRUNNING;
Denys Vlasenko285ad152009-12-04 23:02:27 +01003701 pgid = jp->ps[0].ps_pid;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003702 if (mode == FORK_FG)
3703 xtcsetpgrp(ttyfd, pgid);
3704 killpg(pgid, SIGCONT);
3705 ps = jp->ps;
3706 i = jp->nprocs;
3707 do {
Denys Vlasenko285ad152009-12-04 23:02:27 +01003708 if (WIFSTOPPED(ps->ps_status)) {
3709 ps->ps_status = -1;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003710 }
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003711 ps++;
3712 } while (--i);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003713 out:
3714 status = (mode == FORK_FG) ? waitforjob(jp) : 0;
3715 INT_ON;
3716 return status;
3717}
3718
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02003719static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00003720fg_bgcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003721{
3722 struct job *jp;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003723 int mode;
3724 int retval;
3725
3726 mode = (**argv == 'f') ? FORK_FG : FORK_BG;
3727 nextopt(nullstr);
3728 argv = argptr;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003729 do {
3730 jp = getjob(*argv, 1);
3731 if (mode == FORK_BG) {
3732 set_curjob(jp, CUR_RUNNING);
Denys Vlasenko285ad152009-12-04 23:02:27 +01003733 printf("[%d] ", jobno(jp));
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003734 }
Denys Vlasenko285ad152009-12-04 23:02:27 +01003735 out1str(jp->ps[0].ps_cmd);
3736 showpipe(jp /*, stdout*/);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003737 retval = restartjob(jp, mode);
3738 } while (*argv && *++argv);
3739 return retval;
3740}
3741#endif
3742
3743static int
3744sprint_status(char *s, int status, int sigonly)
3745{
3746 int col;
3747 int st;
3748
3749 col = 0;
3750 if (!WIFEXITED(status)) {
3751#if JOBS
3752 if (WIFSTOPPED(status))
3753 st = WSTOPSIG(status);
3754 else
3755#endif
3756 st = WTERMSIG(status);
3757 if (sigonly) {
3758 if (st == SIGINT || st == SIGPIPE)
3759 goto out;
3760#if JOBS
3761 if (WIFSTOPPED(status))
3762 goto out;
3763#endif
3764 }
3765 st &= 0x7f;
3766 col = fmtstr(s, 32, strsignal(st));
3767 if (WCOREDUMP(status)) {
3768 col += fmtstr(s + col, 16, " (core dumped)");
3769 }
3770 } else if (!sigonly) {
3771 st = WEXITSTATUS(status);
3772 if (st)
3773 col = fmtstr(s, 16, "Done(%d)", st);
3774 else
3775 col = fmtstr(s, 16, "Done");
3776 }
3777 out:
3778 return col;
3779}
3780
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003781static int
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00003782dowait(int wait_flags, struct job *job)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003783{
3784 int pid;
3785 int status;
3786 struct job *jp;
3787 struct job *thisjob;
3788 int state;
3789
Denis Vlasenkobe54d6b2008-10-27 14:25:52 +00003790 TRACE(("dowait(0x%x) called\n", wait_flags));
3791
3792 /* Do a wait system call. If job control is compiled in, we accept
3793 * stopped processes. wait_flags may have WNOHANG, preventing blocking.
3794 * NB: _not_ safe_waitpid, we need to detect EINTR */
Denys Vlasenko285ad152009-12-04 23:02:27 +01003795 if (doing_jobctl)
3796 wait_flags |= WUNTRACED;
3797 pid = waitpid(-1, &status, wait_flags);
Denis Vlasenkob21f3792009-03-19 23:09:58 +00003798 TRACE(("wait returns pid=%d, status=0x%x, errno=%d(%s)\n",
3799 pid, status, errno, strerror(errno)));
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003800 if (pid <= 0)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003801 return pid;
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003802
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003803 INT_OFF;
3804 thisjob = NULL;
3805 for (jp = curjob; jp; jp = jp->prev_job) {
Denys Vlasenko285ad152009-12-04 23:02:27 +01003806 struct procstat *ps;
3807 struct procstat *psend;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003808 if (jp->state == JOBDONE)
3809 continue;
3810 state = JOBDONE;
Denys Vlasenko285ad152009-12-04 23:02:27 +01003811 ps = jp->ps;
3812 psend = ps + jp->nprocs;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003813 do {
Denys Vlasenko285ad152009-12-04 23:02:27 +01003814 if (ps->ps_pid == pid) {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003815 TRACE(("Job %d: changing status of proc %d "
3816 "from 0x%x to 0x%x\n",
Denys Vlasenko285ad152009-12-04 23:02:27 +01003817 jobno(jp), pid, ps->ps_status, status));
3818 ps->ps_status = status;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003819 thisjob = jp;
3820 }
Denys Vlasenko285ad152009-12-04 23:02:27 +01003821 if (ps->ps_status == -1)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003822 state = JOBRUNNING;
3823#if JOBS
3824 if (state == JOBRUNNING)
3825 continue;
Denys Vlasenko285ad152009-12-04 23:02:27 +01003826 if (WIFSTOPPED(ps->ps_status)) {
3827 jp->stopstatus = ps->ps_status;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003828 state = JOBSTOPPED;
3829 }
3830#endif
Denys Vlasenko285ad152009-12-04 23:02:27 +01003831 } while (++ps < psend);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003832 if (thisjob)
3833 goto gotjob;
3834 }
3835#if JOBS
3836 if (!WIFSTOPPED(status))
3837#endif
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003838 jobless--;
3839 goto out;
3840
3841 gotjob:
3842 if (state != JOBRUNNING) {
3843 thisjob->changed = 1;
3844
3845 if (thisjob->state != state) {
3846 TRACE(("Job %d: changing state from %d to %d\n",
3847 jobno(thisjob), thisjob->state, state));
3848 thisjob->state = state;
3849#if JOBS
3850 if (state == JOBSTOPPED) {
3851 set_curjob(thisjob, CUR_STOPPED);
3852 }
3853#endif
3854 }
3855 }
3856
3857 out:
3858 INT_ON;
3859
3860 if (thisjob && thisjob == job) {
3861 char s[48 + 1];
3862 int len;
3863
3864 len = sprint_status(s, status, 1);
3865 if (len) {
3866 s[len] = '\n';
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00003867 s[len + 1] = '\0';
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003868 out2str(s);
3869 }
3870 }
3871 return pid;
3872}
3873
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003874static int
Denys Vlasenko7c1ed9f2010-05-17 04:42:40 +02003875blocking_wait_with_raise_on_sig(void)
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003876{
Denys Vlasenko7c1ed9f2010-05-17 04:42:40 +02003877 pid_t pid = dowait(DOWAIT_BLOCK, NULL);
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02003878 if (pid <= 0 && pending_sig)
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003879 raise_exception(EXSIG);
3880 return pid;
3881}
3882
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003883#if JOBS
3884static void
3885showjob(FILE *out, struct job *jp, int mode)
3886{
3887 struct procstat *ps;
3888 struct procstat *psend;
3889 int col;
Denis Vlasenko40ba9982007-07-14 00:48:29 +00003890 int indent_col;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003891 char s[80];
3892
3893 ps = jp->ps;
3894
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003895 if (mode & SHOW_ONLY_PGID) { /* jobs -p */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003896 /* just output process (group) id of pipeline */
Denys Vlasenko285ad152009-12-04 23:02:27 +01003897 fprintf(out, "%d\n", ps->ps_pid);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003898 return;
3899 }
3900
3901 col = fmtstr(s, 16, "[%d] ", jobno(jp));
Denis Vlasenko40ba9982007-07-14 00:48:29 +00003902 indent_col = col;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003903
3904 if (jp == curjob)
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003905 s[col - 3] = '+';
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003906 else if (curjob && jp == curjob->prev_job)
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003907 s[col - 3] = '-';
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003908
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003909 if (mode & SHOW_PIDS)
Denys Vlasenko285ad152009-12-04 23:02:27 +01003910 col += fmtstr(s + col, 16, "%d ", ps->ps_pid);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003911
3912 psend = ps + jp->nprocs;
3913
3914 if (jp->state == JOBRUNNING) {
3915 strcpy(s + col, "Running");
3916 col += sizeof("Running") - 1;
3917 } else {
Denys Vlasenko285ad152009-12-04 23:02:27 +01003918 int status = psend[-1].ps_status;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003919 if (jp->state == JOBSTOPPED)
3920 status = jp->stopstatus;
3921 col += sprint_status(s + col, status, 0);
3922 }
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003923 /* By now, "[JOBID]* [maybe PID] STATUS" is printed */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003924
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003925 /* This loop either prints "<cmd1> | <cmd2> | <cmd3>" line
3926 * or prints several "PID | <cmdN>" lines,
3927 * depending on SHOW_PIDS bit.
3928 * We do not print status of individual processes
3929 * between PID and <cmdN>. bash does it, but not very well:
3930 * first line shows overall job status, not process status,
3931 * making it impossible to know 1st process status.
3932 */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003933 goto start;
Denys Vlasenko285ad152009-12-04 23:02:27 +01003934 do {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003935 /* for each process */
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003936 s[0] = '\0';
3937 col = 33;
3938 if (mode & SHOW_PIDS)
Denys Vlasenko285ad152009-12-04 23:02:27 +01003939 col = fmtstr(s, 48, "\n%*c%d ", indent_col, ' ', ps->ps_pid) - 1;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003940 start:
Denys Vlasenko285ad152009-12-04 23:02:27 +01003941 fprintf(out, "%s%*c%s%s",
3942 s,
3943 33 - col >= 0 ? 33 - col : 0, ' ',
3944 ps == jp->ps ? "" : "| ",
3945 ps->ps_cmd
3946 );
3947 } while (++ps != psend);
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003948 outcslow('\n', out);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003949
3950 jp->changed = 0;
3951
3952 if (jp->state == JOBDONE) {
3953 TRACE(("showjob: freeing job %d\n", jobno(jp)));
3954 freejob(jp);
3955 }
3956}
3957
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003958/*
3959 * Print a list of jobs. If "change" is nonzero, only print jobs whose
3960 * statuses have changed since the last call to showjobs.
3961 */
3962static void
3963showjobs(FILE *out, int mode)
3964{
3965 struct job *jp;
3966
Denys Vlasenko883cea42009-07-11 15:31:59 +02003967 TRACE(("showjobs(0x%x) called\n", mode));
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003968
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003969 /* Handle all finished jobs */
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00003970 while (dowait(DOWAIT_NONBLOCK, NULL) > 0)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003971 continue;
3972
3973 for (jp = curjob; jp; jp = jp->prev_job) {
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003974 if (!(mode & SHOW_CHANGED) || jp->changed) {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003975 showjob(out, jp, mode);
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003976 }
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003977 }
3978}
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003979
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02003980static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00003981jobscmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003982{
3983 int mode, m;
3984
3985 mode = 0;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02003986 while ((m = nextopt("lp")) != '\0') {
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003987 if (m == 'l')
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003988 mode |= SHOW_PIDS;
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003989 else
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003990 mode |= SHOW_ONLY_PGID;
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003991 }
3992
3993 argv = argptr;
3994 if (*argv) {
3995 do
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003996 showjob(stdout, getjob(*argv, 0), mode);
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003997 while (*++argv);
Denys Vlasenko285ad152009-12-04 23:02:27 +01003998 } else {
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003999 showjobs(stdout, mode);
Denys Vlasenko285ad152009-12-04 23:02:27 +01004000 }
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00004001
4002 return 0;
4003}
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004004#endif /* JOBS */
4005
Michael Abbott359da5e2009-12-04 23:03:29 +01004006/* Called only on finished or stopped jobs (no members are running) */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004007static int
4008getstatus(struct job *job)
4009{
4010 int status;
4011 int retval;
Michael Abbott359da5e2009-12-04 23:03:29 +01004012 struct procstat *ps;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004013
Michael Abbott359da5e2009-12-04 23:03:29 +01004014 /* Fetch last member's status */
4015 ps = job->ps + job->nprocs - 1;
4016 status = ps->ps_status;
4017 if (pipefail) {
4018 /* "set -o pipefail" mode: use last _nonzero_ status */
4019 while (status == 0 && --ps >= job->ps)
4020 status = ps->ps_status;
4021 }
4022
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004023 retval = WEXITSTATUS(status);
4024 if (!WIFEXITED(status)) {
4025#if JOBS
4026 retval = WSTOPSIG(status);
4027 if (!WIFSTOPPED(status))
4028#endif
4029 {
4030 /* XXX: limits number of signals */
4031 retval = WTERMSIG(status);
4032#if JOBS
4033 if (retval == SIGINT)
4034 job->sigint = 1;
4035#endif
4036 }
4037 retval += 128;
4038 }
Denys Vlasenko883cea42009-07-11 15:31:59 +02004039 TRACE(("getstatus: job %d, nproc %d, status 0x%x, retval 0x%x\n",
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004040 jobno(job), job->nprocs, status, retval));
4041 return retval;
4042}
4043
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02004044static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00004045waitcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004046{
4047 struct job *job;
4048 int retval;
4049 struct job *jp;
4050
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02004051 if (pending_sig)
Denis Vlasenko991a1da2008-02-10 19:02:53 +00004052 raise_exception(EXSIG);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004053
4054 nextopt(nullstr);
4055 retval = 0;
4056
4057 argv = argptr;
4058 if (!*argv) {
4059 /* wait for all jobs */
4060 for (;;) {
4061 jp = curjob;
4062 while (1) {
Denis Vlasenko991a1da2008-02-10 19:02:53 +00004063 if (!jp) /* no running procs */
4064 goto ret;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004065 if (jp->state == JOBRUNNING)
4066 break;
4067 jp->waited = 1;
4068 jp = jp->prev_job;
4069 }
Denys Vlasenko7c1ed9f2010-05-17 04:42:40 +02004070 blocking_wait_with_raise_on_sig();
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004071 /* man bash:
4072 * "When bash is waiting for an asynchronous command via
4073 * the wait builtin, the reception of a signal for which a trap
4074 * has been set will cause the wait builtin to return immediately
4075 * with an exit status greater than 128, immediately after which
4076 * the trap is executed."
Denys Vlasenko7c1ed9f2010-05-17 04:42:40 +02004077 *
4078 * blocking_wait_with_raise_on_sig raises signal handlers
4079 * if it gets no pid (pid < 0). However,
4080 * if child sends us a signal *and immediately exits*,
4081 * blocking_wait_with_raise_on_sig gets pid > 0
4082 * and does not handle pending_sig. Check this case: */
4083 if (pending_sig)
4084 raise_exception(EXSIG);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004085 }
4086 }
4087
4088 retval = 127;
4089 do {
4090 if (**argv != '%') {
4091 pid_t pid = number(*argv);
4092 job = curjob;
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00004093 while (1) {
4094 if (!job)
4095 goto repeat;
Denys Vlasenko285ad152009-12-04 23:02:27 +01004096 if (job->ps[job->nprocs - 1].ps_pid == pid)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004097 break;
4098 job = job->prev_job;
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00004099 }
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004100 } else
4101 job = getjob(*argv, 0);
4102 /* loop until process terminated or stopped */
4103 while (job->state == JOBRUNNING)
Denys Vlasenko7c1ed9f2010-05-17 04:42:40 +02004104 blocking_wait_with_raise_on_sig();
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004105 job->waited = 1;
4106 retval = getstatus(job);
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004107 repeat: ;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004108 } while (*++argv);
4109
Denis Vlasenko991a1da2008-02-10 19:02:53 +00004110 ret:
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004111 return retval;
4112}
4113
4114static struct job *
4115growjobtab(void)
4116{
4117 size_t len;
4118 ptrdiff_t offset;
4119 struct job *jp, *jq;
4120
4121 len = njobs * sizeof(*jp);
4122 jq = jobtab;
4123 jp = ckrealloc(jq, len + 4 * sizeof(*jp));
4124
4125 offset = (char *)jp - (char *)jq;
4126 if (offset) {
4127 /* Relocate pointers */
4128 size_t l = len;
4129
4130 jq = (struct job *)((char *)jq + l);
4131 while (l) {
4132 l -= sizeof(*jp);
4133 jq--;
4134#define joff(p) ((struct job *)((char *)(p) + l))
4135#define jmove(p) (p) = (void *)((char *)(p) + offset)
4136 if (joff(jp)->ps == &jq->ps0)
4137 jmove(joff(jp)->ps);
4138 if (joff(jp)->prev_job)
4139 jmove(joff(jp)->prev_job);
4140 }
4141 if (curjob)
4142 jmove(curjob);
4143#undef joff
4144#undef jmove
4145 }
4146
4147 njobs += 4;
4148 jobtab = jp;
4149 jp = (struct job *)((char *)jp + len);
4150 jq = jp + 3;
4151 do {
4152 jq->used = 0;
4153 } while (--jq >= jp);
4154 return jp;
4155}
4156
4157/*
4158 * Return a new job structure.
4159 * Called with interrupts off.
4160 */
4161static struct job *
Denis Vlasenko68404f12008-03-17 09:00:54 +00004162makejob(/*union node *node,*/ int nprocs)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004163{
4164 int i;
4165 struct job *jp;
4166
4167 for (i = njobs, jp = jobtab; ; jp++) {
4168 if (--i < 0) {
4169 jp = growjobtab();
4170 break;
4171 }
4172 if (jp->used == 0)
4173 break;
4174 if (jp->state != JOBDONE || !jp->waited)
4175 continue;
4176#if JOBS
Denis Vlasenkob07a4962008-06-22 13:16:23 +00004177 if (doing_jobctl)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004178 continue;
4179#endif
4180 freejob(jp);
4181 break;
4182 }
4183 memset(jp, 0, sizeof(*jp));
4184#if JOBS
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00004185 /* jp->jobctl is a bitfield.
4186 * "jp->jobctl |= jobctl" likely to give awful code */
Denis Vlasenkob07a4962008-06-22 13:16:23 +00004187 if (doing_jobctl)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004188 jp->jobctl = 1;
4189#endif
4190 jp->prev_job = curjob;
4191 curjob = jp;
4192 jp->used = 1;
4193 jp->ps = &jp->ps0;
4194 if (nprocs > 1) {
4195 jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
4196 }
Denis Vlasenko68404f12008-03-17 09:00:54 +00004197 TRACE(("makejob(%d) returns %%%d\n", nprocs,
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004198 jobno(jp)));
4199 return jp;
4200}
4201
4202#if JOBS
4203/*
4204 * Return a string identifying a command (to be printed by the
4205 * jobs command).
4206 */
4207static char *cmdnextc;
4208
4209static void
4210cmdputs(const char *s)
4211{
Denis Vlasenko92e13c22008-03-25 01:17:40 +00004212 static const char vstype[VSTYPE + 1][3] = {
4213 "", "}", "-", "+", "?", "=",
4214 "%", "%%", "#", "##"
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00004215 IF_ASH_BASH_COMPAT(, ":", "/", "//")
Denis Vlasenko92e13c22008-03-25 01:17:40 +00004216 };
4217
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004218 const char *p, *str;
Denys Vlasenko46a14772009-12-10 21:27:13 +01004219 char cc[2];
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004220 char *nextc;
Denys Vlasenkocd716832009-11-28 22:14:02 +01004221 unsigned char c;
4222 unsigned char subtype = 0;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004223 int quoted = 0;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004224
Denys Vlasenko46a14772009-12-10 21:27:13 +01004225 cc[1] = '\0';
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004226 nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
4227 p = s;
Denys Vlasenko46a14772009-12-10 21:27:13 +01004228 while ((c = *p++) != '\0') {
Denis Vlasenkoef527f52008-06-23 01:52:30 +00004229 str = NULL;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004230 switch (c) {
4231 case CTLESC:
4232 c = *p++;
4233 break;
4234 case CTLVAR:
4235 subtype = *p++;
4236 if ((subtype & VSTYPE) == VSLENGTH)
4237 str = "${#";
4238 else
4239 str = "${";
4240 if (!(subtype & VSQUOTE) == !(quoted & 1))
4241 goto dostr;
4242 quoted ^= 1;
4243 c = '"';
4244 break;
4245 case CTLENDVAR:
4246 str = "\"}" + !(quoted & 1);
4247 quoted >>= 1;
4248 subtype = 0;
4249 goto dostr;
4250 case CTLBACKQ:
4251 str = "$(...)";
4252 goto dostr;
4253 case CTLBACKQ+CTLQUOTE:
4254 str = "\"$(...)\"";
4255 goto dostr;
Mike Frysinger98c52642009-04-02 10:02:37 +00004256#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004257 case CTLARI:
4258 str = "$((";
4259 goto dostr;
4260 case CTLENDARI:
4261 str = "))";
4262 goto dostr;
4263#endif
4264 case CTLQUOTEMARK:
4265 quoted ^= 1;
4266 c = '"';
4267 break;
4268 case '=':
4269 if (subtype == 0)
4270 break;
4271 if ((subtype & VSTYPE) != VSNORMAL)
4272 quoted <<= 1;
4273 str = vstype[subtype & VSTYPE];
4274 if (subtype & VSNUL)
4275 c = ':';
4276 else
4277 goto checkstr;
4278 break;
4279 case '\'':
4280 case '\\':
4281 case '"':
4282 case '$':
4283 /* These can only happen inside quotes */
4284 cc[0] = c;
4285 str = cc;
4286 c = '\\';
4287 break;
4288 default:
4289 break;
4290 }
4291 USTPUTC(c, nextc);
4292 checkstr:
4293 if (!str)
4294 continue;
4295 dostr:
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02004296 while ((c = *str++) != '\0') {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004297 USTPUTC(c, nextc);
4298 }
Denys Vlasenko46a14772009-12-10 21:27:13 +01004299 } /* while *p++ not NUL */
4300
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004301 if (quoted & 1) {
4302 USTPUTC('"', nextc);
4303 }
4304 *nextc = 0;
4305 cmdnextc = nextc;
4306}
4307
4308/* cmdtxt() and cmdlist() call each other */
4309static void cmdtxt(union node *n);
4310
4311static void
4312cmdlist(union node *np, int sep)
4313{
4314 for (; np; np = np->narg.next) {
4315 if (!sep)
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00004316 cmdputs(" ");
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004317 cmdtxt(np);
4318 if (sep && np->narg.next)
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00004319 cmdputs(" ");
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004320 }
4321}
4322
4323static void
4324cmdtxt(union node *n)
4325{
4326 union node *np;
4327 struct nodelist *lp;
4328 const char *p;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004329
4330 if (!n)
4331 return;
4332 switch (n->type) {
4333 default:
4334#if DEBUG
4335 abort();
4336#endif
4337 case NPIPE:
4338 lp = n->npipe.cmdlist;
4339 for (;;) {
4340 cmdtxt(lp->n);
4341 lp = lp->next;
4342 if (!lp)
4343 break;
4344 cmdputs(" | ");
4345 }
4346 break;
4347 case NSEMI:
4348 p = "; ";
4349 goto binop;
4350 case NAND:
4351 p = " && ";
4352 goto binop;
4353 case NOR:
4354 p = " || ";
4355 binop:
4356 cmdtxt(n->nbinary.ch1);
4357 cmdputs(p);
4358 n = n->nbinary.ch2;
4359 goto donode;
4360 case NREDIR:
4361 case NBACKGND:
4362 n = n->nredir.n;
4363 goto donode;
4364 case NNOT:
4365 cmdputs("!");
4366 n = n->nnot.com;
4367 donode:
4368 cmdtxt(n);
4369 break;
4370 case NIF:
4371 cmdputs("if ");
4372 cmdtxt(n->nif.test);
4373 cmdputs("; then ");
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004374 if (n->nif.elsepart) {
Denys Vlasenko7cee00e2009-07-24 01:08:03 +02004375 cmdtxt(n->nif.ifpart);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004376 cmdputs("; else ");
4377 n = n->nif.elsepart;
Denys Vlasenko7cee00e2009-07-24 01:08:03 +02004378 } else {
4379 n = n->nif.ifpart;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004380 }
4381 p = "; fi";
4382 goto dotail;
4383 case NSUBSHELL:
4384 cmdputs("(");
4385 n = n->nredir.n;
4386 p = ")";
4387 goto dotail;
4388 case NWHILE:
4389 p = "while ";
4390 goto until;
4391 case NUNTIL:
4392 p = "until ";
4393 until:
4394 cmdputs(p);
4395 cmdtxt(n->nbinary.ch1);
4396 n = n->nbinary.ch2;
4397 p = "; done";
4398 dodo:
4399 cmdputs("; do ");
4400 dotail:
4401 cmdtxt(n);
4402 goto dotail2;
4403 case NFOR:
4404 cmdputs("for ");
4405 cmdputs(n->nfor.var);
4406 cmdputs(" in ");
4407 cmdlist(n->nfor.args, 1);
4408 n = n->nfor.body;
4409 p = "; done";
4410 goto dodo;
4411 case NDEFUN:
4412 cmdputs(n->narg.text);
4413 p = "() { ... }";
4414 goto dotail2;
4415 case NCMD:
4416 cmdlist(n->ncmd.args, 1);
4417 cmdlist(n->ncmd.redirect, 0);
4418 break;
4419 case NARG:
4420 p = n->narg.text;
4421 dotail2:
4422 cmdputs(p);
4423 break;
4424 case NHERE:
4425 case NXHERE:
4426 p = "<<...";
4427 goto dotail2;
4428 case NCASE:
4429 cmdputs("case ");
4430 cmdputs(n->ncase.expr->narg.text);
4431 cmdputs(" in ");
4432 for (np = n->ncase.cases; np; np = np->nclist.next) {
4433 cmdtxt(np->nclist.pattern);
4434 cmdputs(") ");
4435 cmdtxt(np->nclist.body);
4436 cmdputs(";; ");
4437 }
4438 p = "esac";
4439 goto dotail2;
4440 case NTO:
4441 p = ">";
4442 goto redir;
4443 case NCLOBBER:
4444 p = ">|";
4445 goto redir;
4446 case NAPPEND:
4447 p = ">>";
4448 goto redir;
Denis Vlasenko559691a2008-10-05 18:39:31 +00004449#if ENABLE_ASH_BASH_COMPAT
4450 case NTO2:
4451#endif
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004452 case NTOFD:
4453 p = ">&";
4454 goto redir;
4455 case NFROM:
4456 p = "<";
4457 goto redir;
4458 case NFROMFD:
4459 p = "<&";
4460 goto redir;
4461 case NFROMTO:
4462 p = "<>";
4463 redir:
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00004464 cmdputs(utoa(n->nfile.fd));
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004465 cmdputs(p);
4466 if (n->type == NTOFD || n->type == NFROMFD) {
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00004467 cmdputs(utoa(n->ndup.dupfd));
4468 break;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004469 }
4470 n = n->nfile.fname;
4471 goto donode;
4472 }
4473}
4474
4475static char *
4476commandtext(union node *n)
4477{
4478 char *name;
4479
4480 STARTSTACKSTR(cmdnextc);
4481 cmdtxt(n);
4482 name = stackblock();
4483 TRACE(("commandtext: name %p, end %p\n\t\"%s\"\n",
4484 name, cmdnextc, cmdnextc));
4485 return ckstrdup(name);
4486}
4487#endif /* JOBS */
4488
4489/*
4490 * Fork off a subshell. If we are doing job control, give the subshell its
4491 * own process group. Jp is a job structure that the job is to be added to.
4492 * N is the command that will be evaluated by the child. Both jp and n may
4493 * be NULL. The mode parameter can be one of the following:
4494 * FORK_FG - Fork off a foreground process.
4495 * FORK_BG - Fork off a background process.
4496 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
4497 * process group even if job control is on.
4498 *
4499 * When job control is turned off, background processes have their standard
4500 * input redirected to /dev/null (except for the second and later processes
4501 * in a pipeline).
4502 *
4503 * Called with interrupts off.
4504 */
4505/*
4506 * Clear traps on a fork.
4507 */
4508static void
4509clear_traps(void)
4510{
4511 char **tp;
4512
4513 for (tp = trap; tp < &trap[NSIG]; tp++) {
Denis Vlasenko991a1da2008-02-10 19:02:53 +00004514 if (*tp && **tp) { /* trap not NULL or "" (SIG_IGN) */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004515 INT_OFF;
Denys Vlasenkoe305c282009-09-25 02:12:27 +02004516 if (trap_ptr == trap)
4517 free(*tp);
4518 /* else: it "belongs" to trap_ptr vector, don't free */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004519 *tp = NULL;
Denys Vlasenko0800e3a2009-09-24 03:09:26 +02004520 if ((tp - trap) != 0)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004521 setsignal(tp - trap);
4522 INT_ON;
4523 }
4524 }
4525}
Denis Vlasenkobdc406d2007-07-15 01:13:25 +00004526
4527/* Lives far away from here, needed for forkchild */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004528static void closescript(void);
Denis Vlasenko41770222007-10-07 18:02:52 +00004529
Denis Vlasenkobdc406d2007-07-15 01:13:25 +00004530/* Called after fork(), in child */
Denys Vlasenko21d87d42009-09-25 00:06:51 +02004531static NOINLINE void
Denys Vlasenkoe56f22a2009-07-24 00:16:59 +02004532forkchild(struct job *jp, union node *n, int mode)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004533{
4534 int oldlvl;
4535
4536 TRACE(("Child shell %d\n", getpid()));
4537 oldlvl = shlvl;
4538 shlvl++;
4539
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004540 /* man bash: "Non-builtin commands run by bash have signal handlers
4541 * set to the values inherited by the shell from its parent".
4542 * Do we do it correctly? */
4543
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004544 closescript();
Denys Vlasenko844f9902009-09-23 03:25:52 +02004545
4546 if (mode == FORK_NOJOB /* is it `xxx` ? */
4547 && n && n->type == NCMD /* is it single cmd? */
4548 /* && n->ncmd.args->type == NARG - always true? */
Denys Vlasenko74269202010-02-21 01:26:42 +01004549 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "trap") == 0
Denys Vlasenko844f9902009-09-23 03:25:52 +02004550 && n->ncmd.args->narg.next == NULL /* "trap" with no arguments */
4551 /* && n->ncmd.args->narg.backquote == NULL - do we need to check this? */
4552 ) {
4553 TRACE(("Trap hack\n"));
4554 /* Awful hack for `trap` or $(trap).
4555 *
4556 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
4557 * contains an example where "trap" is executed in a subshell:
4558 *
4559 * save_traps=$(trap)
4560 * ...
4561 * eval "$save_traps"
4562 *
4563 * Standard does not say that "trap" in subshell shall print
4564 * parent shell's traps. It only says that its output
4565 * must have suitable form, but then, in the above example
4566 * (which is not supposed to be normative), it implies that.
4567 *
4568 * bash (and probably other shell) does implement it
4569 * (traps are reset to defaults, but "trap" still shows them),
4570 * but as a result, "trap" logic is hopelessly messed up:
4571 *
4572 * # trap
4573 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
4574 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
4575 * # true | trap <--- trap is in subshell - no output (ditto)
4576 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
4577 * trap -- 'echo Ho' SIGWINCH
4578 * # echo `(trap)` <--- in subshell in subshell - output
4579 * trap -- 'echo Ho' SIGWINCH
4580 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
4581 * trap -- 'echo Ho' SIGWINCH
4582 *
4583 * The rules when to forget and when to not forget traps
4584 * get really complex and nonsensical.
4585 *
4586 * Our solution: ONLY bare $(trap) or `trap` is special.
4587 */
Denys Vlasenko8f88d852009-09-25 12:12:53 +02004588 /* Save trap handler strings for trap builtin to print */
Denys Vlasenko21d87d42009-09-25 00:06:51 +02004589 trap_ptr = memcpy(xmalloc(sizeof(trap)), trap, sizeof(trap));
Denys Vlasenko8f88d852009-09-25 12:12:53 +02004590 /* Fall through into clearing traps */
Denys Vlasenko844f9902009-09-23 03:25:52 +02004591 }
Denys Vlasenkoe305c282009-09-25 02:12:27 +02004592 clear_traps();
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004593#if JOBS
4594 /* do job control only in root shell */
Denis Vlasenkob07a4962008-06-22 13:16:23 +00004595 doing_jobctl = 0;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004596 if (mode != FORK_NOJOB && jp->jobctl && !oldlvl) {
4597 pid_t pgrp;
4598
4599 if (jp->nprocs == 0)
4600 pgrp = getpid();
4601 else
Denys Vlasenko285ad152009-12-04 23:02:27 +01004602 pgrp = jp->ps[0].ps_pid;
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004603 /* this can fail because we are doing it in the parent also */
4604 setpgid(0, pgrp);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004605 if (mode == FORK_FG)
4606 xtcsetpgrp(ttyfd, pgrp);
4607 setsignal(SIGTSTP);
4608 setsignal(SIGTTOU);
4609 } else
4610#endif
4611 if (mode == FORK_BG) {
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004612 /* man bash: "When job control is not in effect,
4613 * asynchronous commands ignore SIGINT and SIGQUIT" */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004614 ignoresig(SIGINT);
4615 ignoresig(SIGQUIT);
4616 if (jp->nprocs == 0) {
4617 close(0);
4618 if (open(bb_dev_null, O_RDONLY) != 0)
Denis Vlasenko9604e1b2009-03-03 18:47:56 +00004619 ash_msg_and_raise_error("can't open '%s'", bb_dev_null);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004620 }
4621 }
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004622 if (!oldlvl) {
4623 if (iflag) { /* why if iflag only? */
4624 setsignal(SIGINT);
4625 setsignal(SIGTERM);
4626 }
4627 /* man bash:
4628 * "In all cases, bash ignores SIGQUIT. Non-builtin
4629 * commands run by bash have signal handlers
4630 * set to the values inherited by the shell
4631 * from its parent".
4632 * Take care of the second rule: */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004633 setsignal(SIGQUIT);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004634 }
Denys Vlasenkoe56f22a2009-07-24 00:16:59 +02004635#if JOBS
Denys Vlasenko844f9902009-09-23 03:25:52 +02004636 if (n && n->type == NCMD
Denys Vlasenko74269202010-02-21 01:26:42 +01004637 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "jobs") == 0
Denys Vlasenko844f9902009-09-23 03:25:52 +02004638 ) {
Denys Vlasenkoe56f22a2009-07-24 00:16:59 +02004639 TRACE(("Job hack\n"));
Denys Vlasenko844f9902009-09-23 03:25:52 +02004640 /* "jobs": we do not want to clear job list for it,
4641 * instead we remove only _its_ own_ job from job list.
4642 * This makes "jobs .... | cat" more useful.
4643 */
Denys Vlasenkoe56f22a2009-07-24 00:16:59 +02004644 freejob(curjob);
4645 return;
4646 }
4647#endif
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004648 for (jp = curjob; jp; jp = jp->prev_job)
4649 freejob(jp);
4650 jobless = 0;
4651}
4652
Denis Vlasenkobdc406d2007-07-15 01:13:25 +00004653/* Called after fork(), in parent */
Denis Vlasenko85c24712008-03-17 09:04:04 +00004654#if !JOBS
4655#define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
4656#endif
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004657static void
4658forkparent(struct job *jp, union node *n, int mode, pid_t pid)
4659{
4660 TRACE(("In parent shell: child = %d\n", pid));
4661 if (!jp) {
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00004662 while (jobless && dowait(DOWAIT_NONBLOCK, NULL) > 0)
4663 continue;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004664 jobless++;
4665 return;
4666 }
4667#if JOBS
4668 if (mode != FORK_NOJOB && jp->jobctl) {
4669 int pgrp;
4670
4671 if (jp->nprocs == 0)
4672 pgrp = pid;
4673 else
Denys Vlasenko285ad152009-12-04 23:02:27 +01004674 pgrp = jp->ps[0].ps_pid;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004675 /* This can fail because we are doing it in the child also */
4676 setpgid(pid, pgrp);
4677 }
4678#endif
4679 if (mode == FORK_BG) {
4680 backgndpid = pid; /* set $! */
4681 set_curjob(jp, CUR_RUNNING);
4682 }
4683 if (jp) {
4684 struct procstat *ps = &jp->ps[jp->nprocs++];
Denys Vlasenko285ad152009-12-04 23:02:27 +01004685 ps->ps_pid = pid;
4686 ps->ps_status = -1;
4687 ps->ps_cmd = nullstr;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004688#if JOBS
Denis Vlasenkob07a4962008-06-22 13:16:23 +00004689 if (doing_jobctl && n)
Denys Vlasenko285ad152009-12-04 23:02:27 +01004690 ps->ps_cmd = commandtext(n);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004691#endif
4692 }
4693}
4694
4695static int
4696forkshell(struct job *jp, union node *n, int mode)
4697{
4698 int pid;
4699
4700 TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
4701 pid = fork();
4702 if (pid < 0) {
4703 TRACE(("Fork failed, errno=%d", errno));
4704 if (jp)
4705 freejob(jp);
Denis Vlasenkofa0b56d2008-07-01 16:09:07 +00004706 ash_msg_and_raise_error("can't fork");
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004707 }
Denys Vlasenko76ace252009-10-12 15:25:01 +02004708 if (pid == 0) {
4709 CLEAR_RANDOM_T(&random_gen); /* or else $RANDOM repeats in child */
Denys Vlasenkoe56f22a2009-07-24 00:16:59 +02004710 forkchild(jp, n, mode);
Denys Vlasenko76ace252009-10-12 15:25:01 +02004711 } else {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004712 forkparent(jp, n, mode, pid);
Denys Vlasenko76ace252009-10-12 15:25:01 +02004713 }
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004714 return pid;
4715}
4716
4717/*
4718 * Wait for job to finish.
4719 *
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004720 * Under job control we have the problem that while a child process
4721 * is running interrupts generated by the user are sent to the child
4722 * but not to the shell. This means that an infinite loop started by
4723 * an interactive user may be hard to kill. With job control turned off,
4724 * an interactive user may place an interactive program inside a loop.
4725 * If the interactive program catches interrupts, the user doesn't want
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004726 * these interrupts to also abort the loop. The approach we take here
4727 * is to have the shell ignore interrupt signals while waiting for a
4728 * foreground process to terminate, and then send itself an interrupt
4729 * signal if the child process was terminated by an interrupt signal.
4730 * Unfortunately, some programs want to do a bit of cleanup and then
4731 * exit on interrupt; unless these processes terminate themselves by
4732 * sending a signal to themselves (instead of calling exit) they will
4733 * confuse this approach.
4734 *
4735 * Called with interrupts off.
4736 */
4737static int
4738waitforjob(struct job *jp)
4739{
4740 int st;
4741
4742 TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004743
4744 INT_OFF;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004745 while (jp->state == JOBRUNNING) {
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004746 /* In non-interactive shells, we _can_ get
4747 * a keyboard signal here and be EINTRed,
4748 * but we just loop back, waiting for command to complete.
4749 *
4750 * man bash:
4751 * "If bash is waiting for a command to complete and receives
4752 * a signal for which a trap has been set, the trap
4753 * will not be executed until the command completes."
4754 *
4755 * Reality is that even if trap is not set, bash
4756 * will not act on the signal until command completes.
4757 * Try this. sleep5intoff.c:
4758 * #include <signal.h>
4759 * #include <unistd.h>
4760 * int main() {
4761 * sigset_t set;
4762 * sigemptyset(&set);
4763 * sigaddset(&set, SIGINT);
4764 * sigaddset(&set, SIGQUIT);
4765 * sigprocmask(SIG_BLOCK, &set, NULL);
4766 * sleep(5);
4767 * return 0;
4768 * }
4769 * $ bash -c './sleep5intoff; echo hi'
4770 * ^C^C^C^C <--- pressing ^C once a second
4771 * $ _
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004772 * $ bash -c './sleep5intoff; echo hi'
4773 * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
4774 * $ _
4775 */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004776 dowait(DOWAIT_BLOCK, jp);
4777 }
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004778 INT_ON;
4779
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004780 st = getstatus(jp);
4781#if JOBS
4782 if (jp->jobctl) {
4783 xtcsetpgrp(ttyfd, rootpid);
4784 /*
4785 * This is truly gross.
4786 * If we're doing job control, then we did a TIOCSPGRP which
4787 * caused us (the shell) to no longer be in the controlling
4788 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
4789 * intuit from the subprocess exit status whether a SIGINT
4790 * occurred, and if so interrupt ourselves. Yuck. - mycroft
4791 */
Denis Vlasenko991a1da2008-02-10 19:02:53 +00004792 if (jp->sigint) /* TODO: do the same with all signals */
4793 raise(SIGINT); /* ... by raise(jp->sig) instead? */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004794 }
4795 if (jp->state == JOBDONE)
4796#endif
4797 freejob(jp);
4798 return st;
4799}
4800
4801/*
4802 * return 1 if there are stopped jobs, otherwise 0
4803 */
4804static int
4805stoppedjobs(void)
4806{
4807 struct job *jp;
4808 int retval;
4809
4810 retval = 0;
4811 if (job_warning)
4812 goto out;
4813 jp = curjob;
4814 if (jp && jp->state == JOBSTOPPED) {
4815 out2str("You have stopped jobs.\n");
4816 job_warning = 2;
4817 retval++;
4818 }
4819 out:
4820 return retval;
4821}
4822
4823
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004824/* ============ redir.c
4825 *
4826 * Code for dealing with input/output redirection.
4827 */
4828
4829#define EMPTY -2 /* marks an unused slot in redirtab */
Denis Vlasenko7d75a962007-11-22 08:16:57 +00004830#define CLOSED -3 /* marks a slot of previously-closed fd */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004831
4832/*
4833 * Open a file in noclobber mode.
4834 * The code was copied from bash.
4835 */
4836static int
4837noclobberopen(const char *fname)
4838{
4839 int r, fd;
4840 struct stat finfo, finfo2;
4841
4842 /*
4843 * If the file exists and is a regular file, return an error
4844 * immediately.
4845 */
4846 r = stat(fname, &finfo);
4847 if (r == 0 && S_ISREG(finfo.st_mode)) {
4848 errno = EEXIST;
4849 return -1;
4850 }
4851
4852 /*
4853 * If the file was not present (r != 0), make sure we open it
4854 * exclusively so that if it is created before we open it, our open
4855 * will fail. Make sure that we do not truncate an existing file.
4856 * Note that we don't turn on O_EXCL unless the stat failed -- if the
4857 * file was not a regular file, we leave O_EXCL off.
4858 */
4859 if (r != 0)
4860 return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
4861 fd = open(fname, O_WRONLY|O_CREAT, 0666);
4862
4863 /* If the open failed, return the file descriptor right away. */
4864 if (fd < 0)
4865 return fd;
4866
4867 /*
4868 * OK, the open succeeded, but the file may have been changed from a
4869 * non-regular file to a regular file between the stat and the open.
4870 * We are assuming that the O_EXCL open handles the case where FILENAME
4871 * did not exist and is symlinked to an existing file between the stat
4872 * and open.
4873 */
4874
4875 /*
4876 * If we can open it and fstat the file descriptor, and neither check
4877 * revealed that it was a regular file, and the file has not been
4878 * replaced, return the file descriptor.
4879 */
4880 if (fstat(fd, &finfo2) == 0 && !S_ISREG(finfo2.st_mode)
4881 && finfo.st_dev == finfo2.st_dev && finfo.st_ino == finfo2.st_ino)
4882 return fd;
4883
4884 /* The file has been replaced. badness. */
4885 close(fd);
4886 errno = EEXIST;
4887 return -1;
4888}
4889
4890/*
4891 * Handle here documents. Normally we fork off a process to write the
4892 * data to a pipe. If the document is short, we can stuff the data in
4893 * the pipe without forking.
4894 */
4895/* openhere needs this forward reference */
4896static void expandhere(union node *arg, int fd);
4897static int
4898openhere(union node *redir)
4899{
4900 int pip[2];
4901 size_t len = 0;
4902
4903 if (pipe(pip) < 0)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00004904 ash_msg_and_raise_error("pipe call failed");
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004905 if (redir->type == NHERE) {
4906 len = strlen(redir->nhere.doc->narg.text);
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00004907 if (len <= PIPE_BUF) {
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004908 full_write(pip[1], redir->nhere.doc->narg.text, len);
4909 goto out;
4910 }
4911 }
4912 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
Denis Vlasenko0b769642008-07-24 07:54:57 +00004913 /* child */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004914 close(pip[0]);
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004915 ignoresig(SIGINT); //signal(SIGINT, SIG_IGN);
4916 ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
4917 ignoresig(SIGHUP); //signal(SIGHUP, SIG_IGN);
4918 ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004919 signal(SIGPIPE, SIG_DFL);
4920 if (redir->type == NHERE)
4921 full_write(pip[1], redir->nhere.doc->narg.text, len);
Denis Vlasenko0b769642008-07-24 07:54:57 +00004922 else /* NXHERE */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004923 expandhere(redir->nhere.doc, pip[1]);
Bernhard Reutner-Fischer636a1f82008-05-19 09:29:47 +00004924 _exit(EXIT_SUCCESS);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004925 }
4926 out:
4927 close(pip[1]);
4928 return pip[0];
4929}
4930
4931static int
4932openredirect(union node *redir)
4933{
4934 char *fname;
4935 int f;
4936
4937 switch (redir->nfile.type) {
4938 case NFROM:
4939 fname = redir->nfile.expfname;
4940 f = open(fname, O_RDONLY);
4941 if (f < 0)
4942 goto eopen;
4943 break;
4944 case NFROMTO:
4945 fname = redir->nfile.expfname;
4946 f = open(fname, O_RDWR|O_CREAT|O_TRUNC, 0666);
4947 if (f < 0)
4948 goto ecreate;
4949 break;
4950 case NTO:
Denis Vlasenko559691a2008-10-05 18:39:31 +00004951#if ENABLE_ASH_BASH_COMPAT
4952 case NTO2:
4953#endif
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004954 /* Take care of noclobber mode. */
4955 if (Cflag) {
4956 fname = redir->nfile.expfname;
4957 f = noclobberopen(fname);
4958 if (f < 0)
4959 goto ecreate;
4960 break;
4961 }
4962 /* FALLTHROUGH */
4963 case NCLOBBER:
4964 fname = redir->nfile.expfname;
4965 f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
4966 if (f < 0)
4967 goto ecreate;
4968 break;
4969 case NAPPEND:
4970 fname = redir->nfile.expfname;
4971 f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
4972 if (f < 0)
4973 goto ecreate;
4974 break;
4975 default:
4976#if DEBUG
4977 abort();
4978#endif
4979 /* Fall through to eliminate warning. */
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00004980/* Our single caller does this itself */
Denis Vlasenko0b769642008-07-24 07:54:57 +00004981// case NTOFD:
4982// case NFROMFD:
4983// f = -1;
4984// break;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004985 case NHERE:
4986 case NXHERE:
4987 f = openhere(redir);
4988 break;
4989 }
4990
4991 return f;
4992 ecreate:
Bernhard Reutner-Fischera53de7f2008-07-21 13:46:54 +00004993 ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004994 eopen:
Bernhard Reutner-Fischera53de7f2008-07-21 13:46:54 +00004995 ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004996}
4997
4998/*
4999 * Copy a file descriptor to be >= to. Returns -1
5000 * if the source file descriptor is closed, EMPTY if there are no unused
5001 * file descriptors left.
5002 */
Denis Vlasenko5a867312008-07-24 19:46:38 +00005003/* 0x800..00: bit to set in "to" to request dup2 instead of fcntl(F_DUPFD).
5004 * old code was doing close(to) prior to copyfd() to achieve the same */
Denis Vlasenko22f74142008-07-24 22:34:43 +00005005enum {
5006 COPYFD_EXACT = (int)~(INT_MAX),
5007 COPYFD_RESTORE = (int)((unsigned)COPYFD_EXACT >> 1),
5008};
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005009static int
5010copyfd(int from, int to)
5011{
5012 int newfd;
5013
Denis Vlasenko5a867312008-07-24 19:46:38 +00005014 if (to & COPYFD_EXACT) {
5015 to &= ~COPYFD_EXACT;
5016 /*if (from != to)*/
5017 newfd = dup2(from, to);
5018 } else {
5019 newfd = fcntl(from, F_DUPFD, to);
5020 }
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005021 if (newfd < 0) {
5022 if (errno == EMFILE)
5023 return EMPTY;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005024 /* Happens when source fd is not open: try "echo >&99" */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005025 ash_msg_and_raise_error("%d: %m", from);
5026 }
5027 return newfd;
5028}
5029
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005030/* Struct def and variable are moved down to the first usage site */
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005031struct two_fd_t {
5032 int orig, copy;
5033};
Denis Vlasenko0b769642008-07-24 07:54:57 +00005034struct redirtab {
5035 struct redirtab *next;
Denis Vlasenko0b769642008-07-24 07:54:57 +00005036 int nullredirs;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005037 int pair_count;
Denys Vlasenko606291b2009-09-23 23:15:43 +02005038 struct two_fd_t two_fd[];
Denis Vlasenko0b769642008-07-24 07:54:57 +00005039};
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005040#define redirlist (G_var.redirlist)
Denis Vlasenko0b769642008-07-24 07:54:57 +00005041
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005042static int need_to_remember(struct redirtab *rp, int fd)
5043{
5044 int i;
5045
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005046 if (!rp) /* remembering was not requested */
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005047 return 0;
5048
5049 for (i = 0; i < rp->pair_count; i++) {
5050 if (rp->two_fd[i].orig == fd) {
5051 /* already remembered */
5052 return 0;
5053 }
5054 }
5055 return 1;
5056}
5057
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005058/* "hidden" fd is a fd used to read scripts, or a copy of such */
5059static int is_hidden_fd(struct redirtab *rp, int fd)
5060{
5061 int i;
Denis Vlasenko34c73c42008-08-16 11:48:02 +00005062 struct parsefile *pf;
5063
5064 if (fd == -1)
5065 return 0;
5066 pf = g_parsefile;
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005067 while (pf) {
5068 if (fd == pf->fd) {
5069 return 1;
5070 }
5071 pf = pf->prev;
5072 }
5073 if (!rp)
5074 return 0;
5075 fd |= COPYFD_RESTORE;
5076 for (i = 0; i < rp->pair_count; i++) {
5077 if (rp->two_fd[i].copy == fd) {
5078 return 1;
5079 }
5080 }
5081 return 0;
5082}
5083
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005084/*
5085 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
5086 * old file descriptors are stashed away so that the redirection can be
5087 * undone by calling popredir. If the REDIR_BACKQ flag is set, then the
5088 * standard output, and the standard error if it becomes a duplicate of
5089 * stdout, is saved in memory.
5090 */
5091/* flags passed to redirect */
5092#define REDIR_PUSH 01 /* save previous values of file descriptors */
5093#define REDIR_SAVEFD2 03 /* set preverrout */
5094static void
5095redirect(union node *redir, int flags)
5096{
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005097 struct redirtab *sv;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005098 int sv_pos;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005099 int i;
5100 int fd;
5101 int newfd;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005102 int copied_fd2 = -1;
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005103
Denis Vlasenko01631112007-12-16 17:20:38 +00005104 g_nullredirs++;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005105 if (!redir) {
5106 return;
5107 }
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005108
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005109 sv = NULL;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005110 sv_pos = 0;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005111 INT_OFF;
5112 if (flags & REDIR_PUSH) {
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005113 union node *tmp = redir;
5114 do {
5115 sv_pos++;
Denis Vlasenko559691a2008-10-05 18:39:31 +00005116#if ENABLE_ASH_BASH_COMPAT
Chris Metcalfc3c1fb62010-01-08 13:18:06 +01005117 if (tmp->nfile.type == NTO2)
Denis Vlasenko559691a2008-10-05 18:39:31 +00005118 sv_pos++;
5119#endif
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005120 tmp = tmp->nfile.next;
5121 } while (tmp);
5122 sv = ckmalloc(sizeof(*sv) + sv_pos * sizeof(sv->two_fd[0]));
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005123 sv->next = redirlist;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005124 sv->pair_count = sv_pos;
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005125 redirlist = sv;
Denis Vlasenko01631112007-12-16 17:20:38 +00005126 sv->nullredirs = g_nullredirs - 1;
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005127 g_nullredirs = 0;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005128 while (sv_pos > 0) {
5129 sv_pos--;
5130 sv->two_fd[sv_pos].orig = sv->two_fd[sv_pos].copy = EMPTY;
5131 }
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005132 }
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005133
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005134 do {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00005135 fd = redir->nfile.fd;
Denis Vlasenko0b769642008-07-24 07:54:57 +00005136 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005137 int right_fd = redir->ndup.dupfd;
5138 /* redirect from/to same file descriptor? */
5139 if (right_fd == fd)
5140 continue;
5141 /* echo >&10 and 10 is a fd opened to the sh script? */
5142 if (is_hidden_fd(sv, right_fd)) {
5143 errno = EBADF; /* as if it is closed */
5144 ash_msg_and_raise_error("%d: %m", right_fd);
5145 }
Denis Vlasenko0b769642008-07-24 07:54:57 +00005146 newfd = -1;
5147 } else {
5148 newfd = openredirect(redir); /* always >= 0 */
5149 if (fd == newfd) {
5150 /* Descriptor wasn't open before redirect.
5151 * Mark it for close in the future */
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005152 if (need_to_remember(sv, fd)) {
Denis Vlasenko5a867312008-07-24 19:46:38 +00005153 goto remember_to_close;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005154 }
Denis Vlasenko0b769642008-07-24 07:54:57 +00005155 continue;
5156 }
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005157 }
Denis Vlasenko559691a2008-10-05 18:39:31 +00005158#if ENABLE_ASH_BASH_COMPAT
5159 redirect_more:
5160#endif
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005161 if (need_to_remember(sv, fd)) {
Denis Vlasenko0b769642008-07-24 07:54:57 +00005162 /* Copy old descriptor */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005163 i = fcntl(fd, F_DUPFD, 10);
Denis Vlasenko5a867312008-07-24 19:46:38 +00005164/* You'd expect copy to be CLOEXECed. Currently these extra "saved" fds
5165 * are closed in popredir() in the child, preventing them from leaking
5166 * into child. (popredir() also cleans up the mess in case of failures)
5167 */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005168 if (i == -1) {
5169 i = errno;
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005170 if (i != EBADF) {
5171 /* Strange error (e.g. "too many files" EMFILE?) */
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005172 if (newfd >= 0)
5173 close(newfd);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005174 errno = i;
5175 ash_msg_and_raise_error("%d: %m", fd);
5176 /* NOTREACHED */
5177 }
Denis Vlasenko5a867312008-07-24 19:46:38 +00005178 /* EBADF: it is not open - good, remember to close it */
5179 remember_to_close:
5180 i = CLOSED;
Denis Vlasenko22f74142008-07-24 22:34:43 +00005181 } else { /* fd is open, save its copy */
5182 /* "exec fd>&-" should not close fds
5183 * which point to script file(s).
5184 * Force them to be restored afterwards */
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005185 if (is_hidden_fd(sv, fd))
5186 i |= COPYFD_RESTORE;
Denis Vlasenko22f74142008-07-24 22:34:43 +00005187 }
Denis Vlasenko5a867312008-07-24 19:46:38 +00005188 if (fd == 2)
5189 copied_fd2 = i;
5190 sv->two_fd[sv_pos].orig = fd;
5191 sv->two_fd[sv_pos].copy = i;
5192 sv_pos++;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005193 }
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005194 if (newfd < 0) {
5195 /* NTOFD/NFROMFD: copy redir->ndup.dupfd to fd */
Denis Vlasenko22f74142008-07-24 22:34:43 +00005196 if (redir->ndup.dupfd < 0) { /* "fd>&-" */
Denis Vlasenkob9e70dd2009-03-20 01:24:08 +00005197 /* Don't want to trigger debugging */
5198 if (fd != -1)
5199 close(fd);
Denis Vlasenko5a867312008-07-24 19:46:38 +00005200 } else {
5201 copyfd(redir->ndup.dupfd, fd | COPYFD_EXACT);
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005202 }
Denis Vlasenko5a867312008-07-24 19:46:38 +00005203 } else if (fd != newfd) { /* move newfd to fd */
5204 copyfd(newfd, fd | COPYFD_EXACT);
Denis Vlasenko559691a2008-10-05 18:39:31 +00005205#if ENABLE_ASH_BASH_COMPAT
5206 if (!(redir->nfile.type == NTO2 && fd == 2))
5207#endif
5208 close(newfd);
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005209 }
Denis Vlasenko559691a2008-10-05 18:39:31 +00005210#if ENABLE_ASH_BASH_COMPAT
5211 if (redir->nfile.type == NTO2 && fd == 1) {
5212 /* We already redirected it to fd 1, now copy it to 2 */
5213 newfd = 1;
5214 fd = 2;
5215 goto redirect_more;
5216 }
5217#endif
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00005218 } while ((redir = redir->nfile.next) != NULL);
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005219
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005220 INT_ON;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005221 if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
5222 preverrout_fd = copied_fd2;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005223}
5224
5225/*
5226 * Undo the effects of the last redirection.
5227 */
5228static void
Denis Vlasenko34c73c42008-08-16 11:48:02 +00005229popredir(int drop, int restore)
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005230{
5231 struct redirtab *rp;
5232 int i;
5233
Denis Vlasenko01631112007-12-16 17:20:38 +00005234 if (--g_nullredirs >= 0)
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005235 return;
5236 INT_OFF;
5237 rp = redirlist;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005238 for (i = 0; i < rp->pair_count; i++) {
5239 int fd = rp->two_fd[i].orig;
Denis Vlasenko22f74142008-07-24 22:34:43 +00005240 int copy = rp->two_fd[i].copy;
5241 if (copy == CLOSED) {
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005242 if (!drop)
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005243 close(fd);
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005244 continue;
5245 }
Denis Vlasenko22f74142008-07-24 22:34:43 +00005246 if (copy != EMPTY) {
Denis Vlasenko34c73c42008-08-16 11:48:02 +00005247 if (!drop || (restore && (copy & COPYFD_RESTORE))) {
Denis Vlasenko22f74142008-07-24 22:34:43 +00005248 copy &= ~COPYFD_RESTORE;
Denis Vlasenko5a867312008-07-24 19:46:38 +00005249 /*close(fd);*/
Denis Vlasenko22f74142008-07-24 22:34:43 +00005250 copyfd(copy, fd | COPYFD_EXACT);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005251 }
Denis Vlasenkob9e70dd2009-03-20 01:24:08 +00005252 close(copy & ~COPYFD_RESTORE);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005253 }
5254 }
5255 redirlist = rp->next;
Denis Vlasenko01631112007-12-16 17:20:38 +00005256 g_nullredirs = rp->nullredirs;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005257 free(rp);
5258 INT_ON;
5259}
5260
5261/*
5262 * Undo all redirections. Called on error or interrupt.
5263 */
5264
5265/*
5266 * Discard all saved file descriptors.
5267 */
5268static void
5269clearredir(int drop)
5270{
5271 for (;;) {
Denis Vlasenko01631112007-12-16 17:20:38 +00005272 g_nullredirs = 0;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005273 if (!redirlist)
5274 break;
Denis Vlasenko34c73c42008-08-16 11:48:02 +00005275 popredir(drop, /*restore:*/ 0);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005276 }
5277}
5278
5279static int
5280redirectsafe(union node *redir, int flags)
5281{
5282 int err;
5283 volatile int saveint;
5284 struct jmploc *volatile savehandler = exception_handler;
5285 struct jmploc jmploc;
5286
5287 SAVE_INT(saveint);
Denis Vlasenko5a867312008-07-24 19:46:38 +00005288 /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
5289 err = setjmp(jmploc.loc); // huh?? was = setjmp(jmploc.loc) * 2;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005290 if (!err) {
5291 exception_handler = &jmploc;
5292 redirect(redir, flags);
5293 }
5294 exception_handler = savehandler;
Denis Vlasenko7f88e342009-03-19 03:36:18 +00005295 if (err && exception_type != EXERROR)
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005296 longjmp(exception_handler->loc, 1);
5297 RESTORE_INT(saveint);
5298 return err;
5299}
5300
5301
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005302/* ============ Routines to expand arguments to commands
5303 *
5304 * We have to deal with backquotes, shell variables, and file metacharacters.
5305 */
5306
Mike Frysinger98c52642009-04-02 10:02:37 +00005307#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00005308static arith_t
5309ash_arith(const char *s)
5310{
5311 arith_eval_hooks_t math_hooks;
5312 arith_t result;
5313 int errcode = 0;
5314
5315 math_hooks.lookupvar = lookupvar;
Denys Vlasenko03dad222010-01-12 23:29:57 +01005316 math_hooks.setvar = setvar2;
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00005317 math_hooks.endofname = endofname;
5318
5319 INT_OFF;
5320 result = arith(s, &errcode, &math_hooks);
5321 if (errcode < 0) {
5322 if (errcode == -3)
5323 ash_msg_and_raise_error("exponent less than 0");
5324 if (errcode == -2)
5325 ash_msg_and_raise_error("divide by zero");
5326 if (errcode == -5)
5327 ash_msg_and_raise_error("expression recursion loop detected");
5328 raise_error_syntax(s);
5329 }
5330 INT_ON;
5331
5332 return result;
5333}
Denis Vlasenko448d30e2008-06-27 00:24:11 +00005334#endif
5335
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005336/*
5337 * expandarg flags
5338 */
5339#define EXP_FULL 0x1 /* perform word splitting & file globbing */
5340#define EXP_TILDE 0x2 /* do normal tilde expansion */
5341#define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
5342#define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
5343#define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
5344#define EXP_RECORD 0x20 /* need to record arguments for ifs breakup */
5345#define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
5346#define EXP_WORD 0x80 /* expand word in parameter expansion */
5347#define EXP_QWORD 0x100 /* expand word in quoted parameter expansion */
5348/*
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005349 * rmescape() flags
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005350 */
5351#define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
5352#define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
5353#define RMESCAPE_QUOTED 0x4 /* Remove CTLESC unless in quotes */
5354#define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
5355#define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
5356
5357/*
5358 * Structure specifying which parts of the string should be searched
5359 * for IFS characters.
5360 */
5361struct ifsregion {
5362 struct ifsregion *next; /* next region in list */
5363 int begoff; /* offset of start of region */
5364 int endoff; /* offset of end of region */
5365 int nulonly; /* search for nul bytes only */
5366};
5367
5368struct arglist {
5369 struct strlist *list;
5370 struct strlist **lastp;
5371};
5372
5373/* output of current string */
5374static char *expdest;
5375/* list of back quote expressions */
5376static struct nodelist *argbackq;
5377/* first struct in list of ifs regions */
5378static struct ifsregion ifsfirst;
5379/* last struct in list */
5380static struct ifsregion *ifslastp;
5381/* holds expanded arg list */
5382static struct arglist exparg;
5383
5384/*
5385 * Our own itoa().
5386 */
5387static int
5388cvtnum(arith_t num)
5389{
5390 int len;
5391
5392 expdest = makestrspace(32, expdest);
Mike Frysinger98c52642009-04-02 10:02:37 +00005393 len = fmtstr(expdest, 32, arith_t_fmt, num);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005394 STADJUST(len, expdest);
5395 return len;
5396}
5397
5398static size_t
5399esclen(const char *start, const char *p)
5400{
5401 size_t esc = 0;
5402
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005403 while (p > start && (unsigned char)*--p == CTLESC) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005404 esc++;
5405 }
5406 return esc;
5407}
5408
5409/*
5410 * Remove any CTLESC characters from a string.
5411 */
5412static char *
Denys Vlasenkob6c84342009-08-29 20:23:20 +02005413rmescapes(char *str, int flag)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005414{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00005415 static const char qchars[] ALIGN1 = { CTLESC, CTLQUOTEMARK, '\0' };
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00005416
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005417 char *p, *q, *r;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005418 unsigned inquotes;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005419 unsigned protect_against_glob;
5420 unsigned globbing;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005421
5422 p = strpbrk(str, qchars);
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005423 if (!p)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005424 return str;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005425
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005426 q = p;
5427 r = str;
5428 if (flag & RMESCAPE_ALLOC) {
5429 size_t len = p - str;
5430 size_t fulllen = len + strlen(p) + 1;
5431
5432 if (flag & RMESCAPE_GROW) {
Colin Watson3963d942010-04-26 14:21:27 +02005433 int strloc = str - (char *)stackblock();
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005434 r = makestrspace(fulllen, expdest);
Colin Watson3963d942010-04-26 14:21:27 +02005435 /* p and str may be invalidated by makestrspace */
5436 str = (char *)stackblock() + strloc;
5437 p = str + len;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005438 } else if (flag & RMESCAPE_HEAP) {
5439 r = ckmalloc(fulllen);
5440 } else {
5441 r = stalloc(fulllen);
5442 }
5443 q = r;
5444 if (len > 0) {
Denis Vlasenko29eb3592008-05-18 14:06:08 +00005445 q = (char *)memcpy(q, str, len) + len;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005446 }
5447 }
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005448
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005449 inquotes = (flag & RMESCAPE_QUOTED) ^ RMESCAPE_QUOTED;
5450 globbing = flag & RMESCAPE_GLOB;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005451 protect_against_glob = globbing;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005452 while (*p) {
Denys Vlasenkocd716832009-11-28 22:14:02 +01005453 if ((unsigned char)*p == CTLQUOTEMARK) {
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005454// TODO: if no RMESCAPE_QUOTED in flags, inquotes never becomes 0
5455// (alternates between RMESCAPE_QUOTED and ~RMESCAPE_QUOTED). Is it ok?
5456// Note: both inquotes and protect_against_glob only affect whether
5457// CTLESC,<ch> gets converted to <ch> or to \<ch>
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005458 inquotes = ~inquotes;
5459 p++;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005460 protect_against_glob = globbing;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005461 continue;
5462 }
5463 if (*p == '\\') {
5464 /* naked back slash */
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005465 protect_against_glob = 0;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005466 goto copy;
5467 }
Denys Vlasenkocd716832009-11-28 22:14:02 +01005468 if ((unsigned char)*p == CTLESC) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005469 p++;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005470 if (protect_against_glob && inquotes && *p != '/') {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005471 *q++ = '\\';
5472 }
5473 }
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005474 protect_against_glob = globbing;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005475 copy:
5476 *q++ = *p++;
5477 }
5478 *q = '\0';
5479 if (flag & RMESCAPE_GROW) {
5480 expdest = r;
5481 STADJUST(q - r + 1, expdest);
5482 }
5483 return r;
5484}
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005485#define pmatch(a, b) !fnmatch((a), (b), 0)
5486
5487/*
5488 * Prepare a pattern for a expmeta (internal glob(3)) call.
5489 *
5490 * Returns an stalloced string.
5491 */
5492static char *
5493preglob(const char *pattern, int quoted, int flag)
5494{
5495 flag |= RMESCAPE_GLOB;
5496 if (quoted) {
5497 flag |= RMESCAPE_QUOTED;
5498 }
Denys Vlasenkob6c84342009-08-29 20:23:20 +02005499 return rmescapes((char *)pattern, flag);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005500}
5501
5502/*
5503 * Put a string on the stack.
5504 */
5505static void
5506memtodest(const char *p, size_t len, int syntax, int quotes)
5507{
5508 char *q = expdest;
5509
Denys Vlasenkob6c84342009-08-29 20:23:20 +02005510 q = makestrspace(quotes ? len * 2 : len, q);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005511
5512 while (len--) {
Denys Vlasenkocd716832009-11-28 22:14:02 +01005513 unsigned char c = *p++;
5514 if (c == '\0')
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005515 continue;
Denys Vlasenkob6c84342009-08-29 20:23:20 +02005516 if (quotes) {
5517 int n = SIT(c, syntax);
5518 if (n == CCTL || n == CBACK)
5519 USTPUTC(CTLESC, q);
5520 }
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005521 USTPUTC(c, q);
5522 }
5523
5524 expdest = q;
5525}
5526
5527static void
5528strtodest(const char *p, int syntax, int quotes)
5529{
5530 memtodest(p, strlen(p), syntax, quotes);
5531}
5532
5533/*
5534 * Record the fact that we have to scan this region of the
5535 * string for IFS characters.
5536 */
5537static void
5538recordregion(int start, int end, int nulonly)
5539{
5540 struct ifsregion *ifsp;
5541
5542 if (ifslastp == NULL) {
5543 ifsp = &ifsfirst;
5544 } else {
5545 INT_OFF;
Denis Vlasenko597906c2008-02-20 16:38:54 +00005546 ifsp = ckzalloc(sizeof(*ifsp));
5547 /*ifsp->next = NULL; - ckzalloc did it */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005548 ifslastp->next = ifsp;
5549 INT_ON;
5550 }
5551 ifslastp = ifsp;
5552 ifslastp->begoff = start;
5553 ifslastp->endoff = end;
5554 ifslastp->nulonly = nulonly;
5555}
5556
5557static void
5558removerecordregions(int endoff)
5559{
5560 if (ifslastp == NULL)
5561 return;
5562
5563 if (ifsfirst.endoff > endoff) {
5564 while (ifsfirst.next != NULL) {
5565 struct ifsregion *ifsp;
5566 INT_OFF;
5567 ifsp = ifsfirst.next->next;
5568 free(ifsfirst.next);
5569 ifsfirst.next = ifsp;
5570 INT_ON;
5571 }
5572 if (ifsfirst.begoff > endoff)
5573 ifslastp = NULL;
5574 else {
5575 ifslastp = &ifsfirst;
5576 ifsfirst.endoff = endoff;
5577 }
5578 return;
5579 }
5580
5581 ifslastp = &ifsfirst;
5582 while (ifslastp->next && ifslastp->next->begoff < endoff)
5583 ifslastp=ifslastp->next;
5584 while (ifslastp->next != NULL) {
5585 struct ifsregion *ifsp;
5586 INT_OFF;
5587 ifsp = ifslastp->next->next;
5588 free(ifslastp->next);
5589 ifslastp->next = ifsp;
5590 INT_ON;
5591 }
5592 if (ifslastp->endoff > endoff)
5593 ifslastp->endoff = endoff;
5594}
5595
5596static char *
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005597exptilde(char *startp, char *p, int flags)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005598{
Denys Vlasenkocd716832009-11-28 22:14:02 +01005599 unsigned char c;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005600 char *name;
5601 struct passwd *pw;
5602 const char *home;
Denys Vlasenko1166d7b2009-09-16 16:20:31 +02005603 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005604 int startloc;
5605
5606 name = p + 1;
5607
5608 while ((c = *++p) != '\0') {
5609 switch (c) {
5610 case CTLESC:
5611 return startp;
5612 case CTLQUOTEMARK:
5613 return startp;
5614 case ':':
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005615 if (flags & EXP_VARTILDE)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005616 goto done;
5617 break;
5618 case '/':
5619 case CTLENDVAR:
5620 goto done;
5621 }
5622 }
5623 done:
5624 *p = '\0';
5625 if (*name == '\0') {
Denys Vlasenkoea8b2522010-06-02 12:57:26 +02005626 home = lookupvar("HOME");
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005627 } else {
5628 pw = getpwnam(name);
5629 if (pw == NULL)
5630 goto lose;
5631 home = pw->pw_dir;
5632 }
5633 if (!home || !*home)
5634 goto lose;
5635 *p = c;
5636 startloc = expdest - (char *)stackblock();
5637 strtodest(home, SQSYNTAX, quotes);
5638 recordregion(startloc, expdest - (char *)stackblock(), 0);
5639 return p;
5640 lose:
5641 *p = c;
5642 return startp;
5643}
5644
5645/*
5646 * Execute a command inside back quotes. If it's a builtin command, we
5647 * want to save its output in a block obtained from malloc. Otherwise
5648 * we fork off a subprocess and get the output of the command via a pipe.
5649 * Should be called with interrupts off.
5650 */
5651struct backcmd { /* result of evalbackcmd */
5652 int fd; /* file descriptor to read from */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005653 int nleft; /* number of chars in buffer */
Denis Vlasenkob07a4962008-06-22 13:16:23 +00005654 char *buf; /* buffer */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005655 struct job *jp; /* job structure for command */
5656};
5657
5658/* These forward decls are needed to use "eval" code for backticks handling: */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00005659static uint8_t back_exitstatus; /* exit status of backquoted command */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005660#define EV_EXIT 01 /* exit after evaluating tree */
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02005661static void evaltree(union node *, int);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005662
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02005663static void FAST_FUNC
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005664evalbackcmd(union node *n, struct backcmd *result)
5665{
5666 int saveherefd;
5667
5668 result->fd = -1;
5669 result->buf = NULL;
5670 result->nleft = 0;
5671 result->jp = NULL;
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00005672 if (n == NULL)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005673 goto out;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005674
5675 saveherefd = herefd;
5676 herefd = -1;
5677
5678 {
5679 int pip[2];
5680 struct job *jp;
5681
5682 if (pipe(pip) < 0)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00005683 ash_msg_and_raise_error("pipe call failed");
Denis Vlasenko68404f12008-03-17 09:00:54 +00005684 jp = makejob(/*n,*/ 1);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005685 if (forkshell(jp, n, FORK_NOJOB) == 0) {
5686 FORCE_INT_ON;
5687 close(pip[0]);
5688 if (pip[1] != 1) {
Denis Vlasenko5a867312008-07-24 19:46:38 +00005689 /*close(1);*/
5690 copyfd(pip[1], 1 | COPYFD_EXACT);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005691 close(pip[1]);
5692 }
5693 eflag = 0;
5694 evaltree(n, EV_EXIT); /* actually evaltreenr... */
5695 /* NOTREACHED */
5696 }
5697 close(pip[1]);
5698 result->fd = pip[0];
5699 result->jp = jp;
5700 }
5701 herefd = saveherefd;
5702 out:
5703 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
5704 result->fd, result->buf, result->nleft, result->jp));
5705}
5706
5707/*
5708 * Expand stuff in backwards quotes.
5709 */
5710static void
5711expbackq(union node *cmd, int quoted, int quotes)
5712{
5713 struct backcmd in;
5714 int i;
5715 char buf[128];
5716 char *p;
5717 char *dest;
5718 int startloc;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00005719 int syntax = quoted ? DQSYNTAX : BASESYNTAX;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005720 struct stackmark smark;
5721
5722 INT_OFF;
5723 setstackmark(&smark);
5724 dest = expdest;
5725 startloc = dest - (char *)stackblock();
5726 grabstackstr(dest);
5727 evalbackcmd(cmd, &in);
5728 popstackmark(&smark);
5729
5730 p = in.buf;
5731 i = in.nleft;
5732 if (i == 0)
5733 goto read;
5734 for (;;) {
5735 memtodest(p, i, syntax, quotes);
5736 read:
5737 if (in.fd < 0)
5738 break;
Denis Vlasenkoe376d452008-02-20 22:23:24 +00005739 i = nonblock_safe_read(in.fd, buf, sizeof(buf));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005740 TRACE(("expbackq: read returns %d\n", i));
5741 if (i <= 0)
5742 break;
5743 p = buf;
5744 }
5745
Denis Vlasenko60818682007-09-28 22:07:23 +00005746 free(in.buf);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005747 if (in.fd >= 0) {
5748 close(in.fd);
5749 back_exitstatus = waitforjob(in.jp);
5750 }
5751 INT_ON;
5752
5753 /* Eat all trailing newlines */
5754 dest = expdest;
5755 for (; dest > (char *)stackblock() && dest[-1] == '\n';)
5756 STUNPUTC(dest);
5757 expdest = dest;
5758
5759 if (quoted == 0)
5760 recordregion(startloc, dest - (char *)stackblock(), 0);
5761 TRACE(("evalbackq: size=%d: \"%.*s\"\n",
5762 (dest - (char *)stackblock()) - startloc,
5763 (dest - (char *)stackblock()) - startloc,
5764 stackblock() + startloc));
5765}
5766
Mike Frysinger98c52642009-04-02 10:02:37 +00005767#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005768/*
5769 * Expand arithmetic expression. Backup to start of expression,
5770 * evaluate, place result in (backed up) result, adjust string position.
5771 */
5772static void
5773expari(int quotes)
5774{
5775 char *p, *start;
5776 int begoff;
5777 int flag;
5778 int len;
5779
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00005780 /* ifsfree(); */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005781
5782 /*
5783 * This routine is slightly over-complicated for
5784 * efficiency. Next we scan backwards looking for the
5785 * start of arithmetic.
5786 */
5787 start = stackblock();
5788 p = expdest - 1;
5789 *p = '\0';
5790 p--;
5791 do {
5792 int esc;
5793
Denys Vlasenkocd716832009-11-28 22:14:02 +01005794 while ((unsigned char)*p != CTLARI) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005795 p--;
5796#if DEBUG
5797 if (p < start) {
5798 ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
5799 }
5800#endif
5801 }
5802
5803 esc = esclen(start, p);
5804 if (!(esc % 2)) {
5805 break;
5806 }
5807
5808 p -= esc + 1;
5809 } while (1);
5810
5811 begoff = p - start;
5812
5813 removerecordregions(begoff);
5814
5815 flag = p[1];
5816
5817 expdest = p;
5818
5819 if (quotes)
Denys Vlasenkob6c84342009-08-29 20:23:20 +02005820 rmescapes(p + 2, 0);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005821
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00005822 len = cvtnum(ash_arith(p + 2));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005823
5824 if (flag != '"')
5825 recordregion(begoff, begoff + len, 0);
5826}
5827#endif
5828
5829/* argstr needs it */
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005830static char *evalvar(char *p, int flags, struct strlist *var_str_list);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005831
5832/*
5833 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
5834 * characters to allow for further processing. Otherwise treat
5835 * $@ like $* since no splitting will be performed.
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00005836 *
5837 * var_str_list (can be NULL) is a list of "VAR=val" strings which take precedence
5838 * over shell varables. Needed for "A=a B=$A; echo $B" case - we use it
5839 * for correct expansion of "B=$A" word.
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005840 */
5841static void
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005842argstr(char *p, int flags, struct strlist *var_str_list)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005843{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00005844 static const char spclchars[] ALIGN1 = {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005845 '=',
5846 ':',
5847 CTLQUOTEMARK,
5848 CTLENDVAR,
5849 CTLESC,
5850 CTLVAR,
5851 CTLBACKQ,
5852 CTLBACKQ | CTLQUOTE,
Mike Frysinger98c52642009-04-02 10:02:37 +00005853#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005854 CTLENDARI,
5855#endif
Denys Vlasenkocd716832009-11-28 22:14:02 +01005856 '\0'
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005857 };
5858 const char *reject = spclchars;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005859 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR); /* do CTLESC */
5860 int breakall = flags & EXP_WORD;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005861 int inquotes;
5862 size_t length;
5863 int startloc;
5864
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005865 if (!(flags & EXP_VARTILDE)) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005866 reject += 2;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005867 } else if (flags & EXP_VARTILDE2) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005868 reject++;
5869 }
5870 inquotes = 0;
5871 length = 0;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005872 if (flags & EXP_TILDE) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005873 char *q;
5874
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005875 flags &= ~EXP_TILDE;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005876 tilde:
5877 q = p;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005878 if (*q == CTLESC && (flags & EXP_QWORD))
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005879 q++;
5880 if (*q == '~')
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005881 p = exptilde(p, q, flags);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005882 }
5883 start:
5884 startloc = expdest - (char *)stackblock();
5885 for (;;) {
Denys Vlasenkocd716832009-11-28 22:14:02 +01005886 unsigned char c;
5887
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005888 length += strcspn(p + length, reject);
Denys Vlasenkocd716832009-11-28 22:14:02 +01005889 c = p[length];
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005890 if (c) {
5891 if (!(c & 0x80)
Mike Frysinger98c52642009-04-02 10:02:37 +00005892#if ENABLE_SH_MATH_SUPPORT
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005893 || c == CTLENDARI
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005894#endif
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005895 ) {
5896 /* c == '=' || c == ':' || c == CTLENDARI */
5897 length++;
5898 }
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005899 }
5900 if (length > 0) {
5901 int newloc;
5902 expdest = stack_nputstr(p, length, expdest);
5903 newloc = expdest - (char *)stackblock();
5904 if (breakall && !inquotes && newloc > startloc) {
5905 recordregion(startloc, newloc, 0);
5906 }
5907 startloc = newloc;
5908 }
5909 p += length + 1;
5910 length = 0;
5911
5912 switch (c) {
5913 case '\0':
5914 goto breakloop;
5915 case '=':
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005916 if (flags & EXP_VARTILDE2) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005917 p--;
5918 continue;
5919 }
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005920 flags |= EXP_VARTILDE2;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005921 reject++;
5922 /* fall through */
5923 case ':':
5924 /*
5925 * sort of a hack - expand tildes in variable
5926 * assignments (after the first '=' and after ':'s).
5927 */
5928 if (*--p == '~') {
5929 goto tilde;
5930 }
5931 continue;
5932 }
5933
5934 switch (c) {
5935 case CTLENDVAR: /* ??? */
5936 goto breakloop;
5937 case CTLQUOTEMARK:
5938 /* "$@" syntax adherence hack */
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005939 if (!inquotes
5940 && memcmp(p, dolatstr, 4) == 0
5941 && ( p[4] == CTLQUOTEMARK
5942 || (p[4] == CTLENDVAR && p[5] == CTLQUOTEMARK)
5943 )
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005944 ) {
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005945 p = evalvar(p + 1, flags, /* var_str_list: */ NULL) + 1;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005946 goto start;
5947 }
5948 inquotes = !inquotes;
5949 addquote:
5950 if (quotes) {
5951 p--;
5952 length++;
5953 startloc++;
5954 }
5955 break;
5956 case CTLESC:
5957 startloc++;
5958 length++;
5959 goto addquote;
5960 case CTLVAR:
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005961 p = evalvar(p, flags, var_str_list);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005962 goto start;
5963 case CTLBACKQ:
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005964 c = '\0';
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005965 case CTLBACKQ|CTLQUOTE:
5966 expbackq(argbackq->n, c, quotes);
5967 argbackq = argbackq->next;
5968 goto start;
Mike Frysinger98c52642009-04-02 10:02:37 +00005969#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005970 case CTLENDARI:
5971 p--;
5972 expari(quotes);
5973 goto start;
5974#endif
5975 }
5976 }
5977 breakloop:
5978 ;
5979}
5980
5981static char *
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00005982scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM, char *str, int quotes,
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005983 int zero)
5984{
Denis Vlasenkoc7131c32008-04-14 01:59:53 +00005985// This commented out code was added by James Simmons <jsimmons@infradead.org>
5986// as part of a larger change when he added support for ${var/a/b}.
5987// However, it broke # and % operators:
5988//
5989//var=ababcdcd
5990// ok bad
5991//echo ${var#ab} abcdcd abcdcd
5992//echo ${var##ab} abcdcd abcdcd
5993//echo ${var#a*b} abcdcd ababcdcd (!)
5994//echo ${var##a*b} cdcd cdcd
5995//echo ${var#?} babcdcd ababcdcd (!)
5996//echo ${var##?} babcdcd babcdcd
5997//echo ${var#*} ababcdcd babcdcd (!)
5998//echo ${var##*}
5999//echo ${var%cd} ababcd ababcd
6000//echo ${var%%cd} ababcd abab (!)
6001//echo ${var%c*d} ababcd ababcd
6002//echo ${var%%c*d} abab ababcdcd (!)
6003//echo ${var%?} ababcdc ababcdc
6004//echo ${var%%?} ababcdc ababcdcd (!)
6005//echo ${var%*} ababcdcd ababcdcd
6006//echo ${var%%*}
6007//
6008// Commenting it back out helped. Remove it completely if it really
6009// is not needed.
6010
6011 char *loc, *loc2; //, *full;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006012 char c;
6013
6014 loc = startp;
6015 loc2 = rmesc;
6016 do {
Denis Vlasenkoc7131c32008-04-14 01:59:53 +00006017 int match; // = strlen(str);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006018 const char *s = loc2;
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006019
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006020 c = *loc2;
6021 if (zero) {
6022 *loc2 = '\0';
6023 s = rmesc;
6024 }
Denis Vlasenkoc7131c32008-04-14 01:59:53 +00006025 match = pmatch(str, s); // this line was deleted
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006026
Denis Vlasenkoc7131c32008-04-14 01:59:53 +00006027// // chop off end if its '*'
6028// full = strrchr(str, '*');
6029// if (full && full != str)
6030// match--;
6031//
6032// // If str starts with '*' replace with s.
6033// if ((*str == '*') && strlen(s) >= match) {
6034// full = xstrdup(s);
6035// strncpy(full+strlen(s)-match+1, str+1, match-1);
6036// } else
6037// full = xstrndup(str, match);
6038// match = strncmp(s, full, strlen(full));
6039// free(full);
6040//
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006041 *loc2 = c;
Denis Vlasenkoc7131c32008-04-14 01:59:53 +00006042 if (match) // if (!match)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006043 return loc;
Denys Vlasenkocd716832009-11-28 22:14:02 +01006044 if (quotes && (unsigned char)*loc == CTLESC)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006045 loc++;
6046 loc++;
6047 loc2++;
6048 } while (c);
6049 return 0;
6050}
6051
6052static char *
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006053scanright(char *startp, char *rmesc, char *rmescend, char *pattern, int quotes, int match_at_start)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006054{
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006055#if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6056 int try2optimize = match_at_start;
6057#endif
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006058 int esc = 0;
6059 char *loc;
6060 char *loc2;
6061
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006062 /* If we called by "${v/pattern/repl}" or "${v//pattern/repl}":
6063 * startp="escaped_value_of_v" rmesc="raw_value_of_v"
6064 * rmescend=""(ptr to NUL in rmesc) pattern="pattern" quotes=match_at_start=1
6065 * Logic:
6066 * loc starts at NUL at the end of startp, loc2 starts at the end of rmesc,
6067 * and on each iteration they go back two/one char until they reach the beginning.
6068 * We try to find a match in "raw_value_of_v", "raw_value_of_", "raw_value_of" etc.
6069 */
6070 /* TODO: document in what other circumstances we are called. */
6071
6072 for (loc = pattern - 1, loc2 = rmescend; loc >= startp; loc2--) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006073 int match;
6074 char c = *loc2;
6075 const char *s = loc2;
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006076 if (match_at_start) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006077 *loc2 = '\0';
6078 s = rmesc;
6079 }
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006080 match = pmatch(pattern, s);
6081 //bb_error_msg("pmatch(pattern:'%s',s:'%s'):%d", pattern, s, match);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006082 *loc2 = c;
6083 if (match)
6084 return loc;
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006085#if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6086 if (try2optimize) {
6087 /* Maybe we can optimize this:
6088 * if pattern ends with unescaped *, we can avoid checking
6089 * shorter strings: if "foo*" doesnt match "raw_value_of_v",
6090 * it wont match truncated "raw_value_of_" strings too.
6091 */
6092 unsigned plen = strlen(pattern);
6093 /* Does it end with "*"? */
6094 if (plen != 0 && pattern[--plen] == '*') {
6095 /* "xxxx*" is not escaped */
6096 /* "xxx\*" is escaped */
6097 /* "xx\\*" is not escaped */
6098 /* "x\\\*" is escaped */
6099 int slashes = 0;
6100 while (plen != 0 && pattern[--plen] == '\\')
6101 slashes++;
6102 if (!(slashes & 1))
6103 break; /* ends with unescaped "*" */
6104 }
6105 try2optimize = 0;
6106 }
6107#endif
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006108 loc--;
6109 if (quotes) {
6110 if (--esc < 0) {
6111 esc = esclen(startp, loc);
6112 }
6113 if (esc % 2) {
6114 esc--;
6115 loc--;
6116 }
6117 }
6118 }
6119 return 0;
6120}
6121
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00006122static void varunset(const char *, const char *, const char *, int) NORETURN;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006123static void
6124varunset(const char *end, const char *var, const char *umsg, int varflags)
6125{
6126 const char *msg;
6127 const char *tail;
6128
6129 tail = nullstr;
6130 msg = "parameter not set";
6131 if (umsg) {
Denys Vlasenkocd716832009-11-28 22:14:02 +01006132 if ((unsigned char)*end == CTLENDVAR) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006133 if (varflags & VSNUL)
6134 tail = " or null";
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00006135 } else {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006136 msg = umsg;
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00006137 }
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006138 }
6139 ash_msg_and_raise_error("%.*s: %s%s", end - var - 1, var, msg, tail);
6140}
6141
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006142#if ENABLE_ASH_BASH_COMPAT
6143static char *
6144parse_sub_pattern(char *arg, int inquotes)
6145{
6146 char *idx, *repl = NULL;
6147 unsigned char c;
6148
Denis Vlasenko2659c632008-06-14 06:04:59 +00006149 idx = arg;
6150 while (1) {
6151 c = *arg;
6152 if (!c)
6153 break;
6154 if (c == '/') {
6155 /* Only the first '/' seen is our separator */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006156 if (!repl) {
Denis Vlasenko2659c632008-06-14 06:04:59 +00006157 repl = idx + 1;
6158 c = '\0';
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006159 }
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006160 }
Denis Vlasenko2659c632008-06-14 06:04:59 +00006161 *idx++ = c;
6162 if (!inquotes && c == '\\' && arg[1] == '\\')
6163 arg++; /* skip both \\, not just first one */
6164 arg++;
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006165 }
Denis Vlasenko29038c02008-06-14 06:14:02 +00006166 *idx = c; /* NUL */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006167
6168 return repl;
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006169}
6170#endif /* ENABLE_ASH_BASH_COMPAT */
6171
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006172static const char *
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006173subevalvar(char *p, char *str, int strloc, int subtype,
6174 int startloc, int varflags, int quotes, struct strlist *var_str_list)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006175{
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006176 struct nodelist *saveargbackq = argbackq;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006177 char *startp;
6178 char *loc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006179 char *rmesc, *rmescend;
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00006180 IF_ASH_BASH_COMPAT(char *repl = NULL;)
6181 IF_ASH_BASH_COMPAT(char null = '\0';)
6182 IF_ASH_BASH_COMPAT(int pos, len, orig_len;)
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006183 int saveherefd = herefd;
6184 int amount, workloc, resetloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006185 int zero;
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006186 char *(*scan)(char*, char*, char*, char*, int, int);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006187
6188 herefd = -1;
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006189 argstr(p, (subtype != VSASSIGN && subtype != VSQUESTION) ? EXP_CASE : 0,
6190 var_str_list);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006191 STPUTC('\0', expdest);
6192 herefd = saveherefd;
6193 argbackq = saveargbackq;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00006194 startp = (char *)stackblock() + startloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006195
6196 switch (subtype) {
6197 case VSASSIGN:
6198 setvar(str, startp, 0);
6199 amount = startp - expdest;
6200 STADJUST(amount, expdest);
6201 return startp;
6202
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006203#if ENABLE_ASH_BASH_COMPAT
6204 case VSSUBSTR:
6205 loc = str = stackblock() + strloc;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006206 /* Read POS in ${var:POS:LEN} */
6207 pos = atoi(loc); /* number(loc) errors out on "1:4" */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006208 len = str - startp - 1;
6209
6210 /* *loc != '\0', guaranteed by parser */
6211 if (quotes) {
6212 char *ptr;
6213
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006214 /* Adjust the length by the number of escapes */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006215 for (ptr = startp; ptr < (str - 1); ptr++) {
Denys Vlasenkocd716832009-11-28 22:14:02 +01006216 if ((unsigned char)*ptr == CTLESC) {
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006217 len--;
6218 ptr++;
6219 }
6220 }
6221 }
6222 orig_len = len;
6223
6224 if (*loc++ == ':') {
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006225 /* ${var::LEN} */
6226 len = number(loc);
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006227 } else {
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006228 /* Skip POS in ${var:POS:LEN} */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006229 len = orig_len;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006230 while (*loc && *loc != ':') {
6231 /* TODO?
6232 * bash complains on: var=qwe; echo ${var:1a:123}
6233 if (!isdigit(*loc))
6234 ash_msg_and_raise_error(msg_illnum, str);
6235 */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006236 loc++;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006237 }
6238 if (*loc++ == ':') {
6239 len = number(loc);
6240 }
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006241 }
6242 if (pos >= orig_len) {
6243 pos = 0;
6244 len = 0;
6245 }
6246 if (len > (orig_len - pos))
6247 len = orig_len - pos;
6248
6249 for (str = startp; pos; str++, pos--) {
Denys Vlasenkocd716832009-11-28 22:14:02 +01006250 if (quotes && (unsigned char)*str == CTLESC)
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006251 str++;
6252 }
6253 for (loc = startp; len; len--) {
Denys Vlasenkocd716832009-11-28 22:14:02 +01006254 if (quotes && (unsigned char)*str == CTLESC)
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006255 *loc++ = *str++;
6256 *loc++ = *str++;
6257 }
6258 *loc = '\0';
6259 amount = loc - expdest;
6260 STADJUST(amount, expdest);
6261 return loc;
6262#endif
6263
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006264 case VSQUESTION:
6265 varunset(p, str, startp, varflags);
6266 /* NOTREACHED */
6267 }
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006268 resetloc = expdest - (char *)stackblock();
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006269
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006270 /* We'll comeback here if we grow the stack while handling
6271 * a VSREPLACE or VSREPLACEALL, since our pointers into the
6272 * stack will need rebasing, and we'll need to remove our work
6273 * areas each time
6274 */
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00006275 IF_ASH_BASH_COMPAT(restart:)
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006276
6277 amount = expdest - ((char *)stackblock() + resetloc);
6278 STADJUST(-amount, expdest);
Denis Vlasenko29eb3592008-05-18 14:06:08 +00006279 startp = (char *)stackblock() + startloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006280
6281 rmesc = startp;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00006282 rmescend = (char *)stackblock() + strloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006283 if (quotes) {
Denys Vlasenkob6c84342009-08-29 20:23:20 +02006284 rmesc = rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006285 if (rmesc != startp) {
6286 rmescend = expdest;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00006287 startp = (char *)stackblock() + startloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006288 }
6289 }
6290 rmescend--;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00006291 str = (char *)stackblock() + strloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006292 preglob(str, varflags & VSQUOTE, 0);
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006293 workloc = expdest - (char *)stackblock();
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006294
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006295#if ENABLE_ASH_BASH_COMPAT
6296 if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006297 char *idx, *end;
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006298
Denis Vlasenkod6855d12008-09-27 14:03:25 +00006299 if (!repl) {
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006300 repl = parse_sub_pattern(str, varflags & VSQUOTE);
6301 if (!repl)
6302 repl = &null;
6303 }
6304
6305 /* If there's no pattern to match, return the expansion unmolested */
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006306 if (str[0] == '\0')
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006307 return 0;
6308
6309 len = 0;
6310 idx = startp;
6311 end = str - 1;
6312 while (idx < end) {
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006313 try_to_match:
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006314 loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
6315 if (!loc) {
6316 /* No match, advance */
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006317 char *restart_detect = stackblock();
6318 skip_matching:
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006319 STPUTC(*idx, expdest);
Denys Vlasenkocd716832009-11-28 22:14:02 +01006320 if (quotes && (unsigned char)*idx == CTLESC) {
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006321 idx++;
6322 len++;
6323 STPUTC(*idx, expdest);
6324 }
6325 if (stackblock() != restart_detect)
6326 goto restart;
6327 idx++;
6328 len++;
6329 rmesc++;
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006330 /* continue; - prone to quadratic behavior, smarter code: */
6331 if (idx >= end)
6332 break;
6333 if (str[0] == '*') {
6334 /* Pattern is "*foo". If "*foo" does not match "long_string",
6335 * it would never match "ong_string" etc, no point in trying.
6336 */
6337 goto skip_matching;
6338 }
6339 goto try_to_match;
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006340 }
6341
6342 if (subtype == VSREPLACEALL) {
6343 while (idx < loc) {
Denys Vlasenkocd716832009-11-28 22:14:02 +01006344 if (quotes && (unsigned char)*idx == CTLESC)
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006345 idx++;
6346 idx++;
6347 rmesc++;
6348 }
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00006349 } else {
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006350 idx = loc;
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00006351 }
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006352
6353 for (loc = repl; *loc; loc++) {
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006354 char *restart_detect = stackblock();
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006355 STPUTC(*loc, expdest);
6356 if (stackblock() != restart_detect)
6357 goto restart;
6358 len++;
6359 }
6360
6361 if (subtype == VSREPLACE) {
6362 while (*idx) {
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006363 char *restart_detect = stackblock();
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006364 STPUTC(*idx, expdest);
6365 if (stackblock() != restart_detect)
6366 goto restart;
6367 len++;
6368 idx++;
6369 }
6370 break;
6371 }
6372 }
6373
6374 /* We've put the replaced text into a buffer at workloc, now
6375 * move it to the right place and adjust the stack.
6376 */
6377 startp = stackblock() + startloc;
6378 STPUTC('\0', expdest);
6379 memmove(startp, stackblock() + workloc, len);
6380 startp[len++] = '\0';
6381 amount = expdest - ((char *)stackblock() + startloc + len - 1);
6382 STADJUST(-amount, expdest);
6383 return startp;
6384 }
6385#endif /* ENABLE_ASH_BASH_COMPAT */
6386
6387 subtype -= VSTRIMRIGHT;
6388#if DEBUG
6389 if (subtype < 0 || subtype > 7)
6390 abort();
6391#endif
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006392 /* zero = (subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX) */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006393 zero = subtype >> 1;
6394 /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
6395 scan = (subtype & 1) ^ zero ? scanleft : scanright;
6396
6397 loc = scan(startp, rmesc, rmescend, str, quotes, zero);
6398 if (loc) {
6399 if (zero) {
6400 memmove(startp, loc, str - loc);
6401 loc = startp + (str - loc) - 1;
6402 }
6403 *loc = '\0';
6404 amount = loc - expdest;
6405 STADJUST(amount, expdest);
6406 }
6407 return loc;
6408}
6409
6410/*
6411 * Add the value of a specialized variable to the stack string.
Denys Vlasenko4d8873f2009-10-04 03:14:41 +02006412 * name parameter (examples):
6413 * ash -c 'echo $1' name:'1='
6414 * ash -c 'echo $qwe' name:'qwe='
6415 * ash -c 'echo $$' name:'$='
6416 * ash -c 'echo ${$}' name:'$='
6417 * ash -c 'echo ${$##q}' name:'$=q'
6418 * ash -c 'echo ${#$}' name:'$='
6419 * note: examples with bad shell syntax:
6420 * ash -c 'echo ${#$1}' name:'$=1'
6421 * ash -c 'echo ${#1#}' name:'1=#'
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006422 */
Denys Vlasenkoadf922e2009-10-08 14:35:37 +02006423static NOINLINE ssize_t
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006424varvalue(char *name, int varflags, int flags, struct strlist *var_str_list)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006425{
Mike Frysinger98c52642009-04-02 10:02:37 +00006426 const char *p;
Denys Vlasenko8eda4a92009-11-30 12:16:17 +01006427 int num;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006428 int i;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006429 int sepq = 0;
6430 ssize_t len = 0;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006431 int subtype = varflags & VSTYPE;
Denys Vlasenko1166d7b2009-09-16 16:20:31 +02006432 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR);
Denys Vlasenko8eda4a92009-11-30 12:16:17 +01006433 int quoted = varflags & VSQUOTE;
6434 int syntax = quoted ? DQSYNTAX : BASESYNTAX;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006435
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006436 switch (*name) {
6437 case '$':
6438 num = rootpid;
6439 goto numvar;
6440 case '?':
6441 num = exitstatus;
6442 goto numvar;
6443 case '#':
6444 num = shellparam.nparam;
6445 goto numvar;
6446 case '!':
6447 num = backgndpid;
6448 if (num == 0)
6449 return -1;
6450 numvar:
6451 len = cvtnum(num);
Denys Vlasenko4d8873f2009-10-04 03:14:41 +02006452 goto check_1char_name;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006453 case '-':
Mike Frysinger98c52642009-04-02 10:02:37 +00006454 expdest = makestrspace(NOPTS, expdest);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006455 for (i = NOPTS - 1; i >= 0; i--) {
6456 if (optlist[i]) {
Mike Frysinger98c52642009-04-02 10:02:37 +00006457 USTPUTC(optletters(i), expdest);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006458 len++;
6459 }
6460 }
Denys Vlasenko4d8873f2009-10-04 03:14:41 +02006461 check_1char_name:
6462#if 0
6463 /* handles cases similar to ${#$1} */
6464 if (name[2] != '\0')
6465 raise_error_syntax("bad substitution");
6466#endif
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006467 break;
Denys Vlasenko8eda4a92009-11-30 12:16:17 +01006468 case '@': {
6469 char **ap;
6470 int sep;
6471
6472 if (quoted && (flags & EXP_FULL)) {
6473 /* note: this is not meant as PEOF value */
6474 sep = 1 << CHAR_BIT;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006475 goto param;
Denys Vlasenko8eda4a92009-11-30 12:16:17 +01006476 }
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006477 /* fall through */
6478 case '*':
Denys Vlasenkocd716832009-11-28 22:14:02 +01006479 sep = ifsset() ? (unsigned char)(ifsval()[0]) : ' ';
Denys Vlasenko8eda4a92009-11-30 12:16:17 +01006480 i = SIT(sep, syntax);
6481 if (quotes && (i == CCTL || i == CBACK))
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006482 sepq = 1;
6483 param:
6484 ap = shellparam.p;
6485 if (!ap)
6486 return -1;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006487 while ((p = *ap++) != NULL) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006488 size_t partlen;
6489
6490 partlen = strlen(p);
6491 len += partlen;
6492
6493 if (!(subtype == VSPLUS || subtype == VSLENGTH))
6494 memtodest(p, partlen, syntax, quotes);
6495
6496 if (*ap && sep) {
6497 char *q;
6498
6499 len++;
6500 if (subtype == VSPLUS || subtype == VSLENGTH) {
6501 continue;
6502 }
6503 q = expdest;
6504 if (sepq)
6505 STPUTC(CTLESC, q);
Denys Vlasenko8eda4a92009-11-30 12:16:17 +01006506 /* note: may put NUL despite sep != 0
6507 * (see sep = 1 << CHAR_BIT above) */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006508 STPUTC(sep, q);
6509 expdest = q;
6510 }
6511 }
6512 return len;
Denys Vlasenko8eda4a92009-11-30 12:16:17 +01006513 } /* case '@' and '*' */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006514 case '0':
6515 case '1':
6516 case '2':
6517 case '3':
6518 case '4':
6519 case '5':
6520 case '6':
6521 case '7':
6522 case '8':
6523 case '9':
Denys Vlasenkoa00329c2009-08-30 20:05:10 +02006524 num = atoi(name); /* number(name) fails on ${N#str} etc */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006525 if (num < 0 || num > shellparam.nparam)
6526 return -1;
6527 p = num ? shellparam.p[num - 1] : arg0;
6528 goto value;
6529 default:
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006530 /* NB: name has form "VAR=..." */
6531
6532 /* "A=a B=$A" case: var_str_list is a list of "A=a" strings
6533 * which should be considered before we check variables. */
6534 if (var_str_list) {
6535 unsigned name_len = (strchrnul(name, '=') - name) + 1;
6536 p = NULL;
6537 do {
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00006538 char *str, *eq;
6539 str = var_str_list->text;
6540 eq = strchr(str, '=');
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006541 if (!eq) /* stop at first non-assignment */
6542 break;
6543 eq++;
Denis Vlasenko6b06cb82008-05-15 21:30:45 +00006544 if (name_len == (unsigned)(eq - str)
Denys Vlasenko8eda4a92009-11-30 12:16:17 +01006545 && strncmp(str, name, name_len) == 0
6546 ) {
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006547 p = eq;
6548 /* goto value; - WRONG! */
6549 /* think "A=1 A=2 B=$A" */
6550 }
6551 var_str_list = var_str_list->next;
6552 } while (var_str_list);
6553 if (p)
6554 goto value;
6555 }
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006556 p = lookupvar(name);
6557 value:
6558 if (!p)
6559 return -1;
6560
6561 len = strlen(p);
6562 if (!(subtype == VSPLUS || subtype == VSLENGTH))
6563 memtodest(p, len, syntax, quotes);
6564 return len;
6565 }
6566
6567 if (subtype == VSPLUS || subtype == VSLENGTH)
6568 STADJUST(-len, expdest);
6569 return len;
6570}
6571
6572/*
6573 * Expand a variable, and return a pointer to the next character in the
6574 * input string.
6575 */
6576static char *
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006577evalvar(char *p, int flags, struct strlist *var_str_list)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006578{
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006579 char varflags;
6580 char subtype;
6581 char quoted;
6582 char easy;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006583 char *var;
6584 int patloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006585 int startloc;
6586 ssize_t varlen;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006587
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006588 varflags = (unsigned char) *p++;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006589 subtype = varflags & VSTYPE;
6590 quoted = varflags & VSQUOTE;
6591 var = p;
6592 easy = (!quoted || (*var == '@' && shellparam.nparam));
6593 startloc = expdest - (char *)stackblock();
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02006594 p = strchr(p, '=') + 1; //TODO: use var_end(p)?
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006595
6596 again:
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006597 varlen = varvalue(var, varflags, flags, var_str_list);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006598 if (varflags & VSNUL)
6599 varlen--;
6600
6601 if (subtype == VSPLUS) {
6602 varlen = -1 - varlen;
6603 goto vsplus;
6604 }
6605
6606 if (subtype == VSMINUS) {
6607 vsplus:
6608 if (varlen < 0) {
6609 argstr(
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006610 p, flags | EXP_TILDE |
6611 (quoted ? EXP_QWORD : EXP_WORD),
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006612 var_str_list
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006613 );
6614 goto end;
6615 }
6616 if (easy)
6617 goto record;
6618 goto end;
6619 }
6620
6621 if (subtype == VSASSIGN || subtype == VSQUESTION) {
6622 if (varlen < 0) {
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006623 if (subevalvar(p, var, /* strloc: */ 0,
6624 subtype, startloc, varflags,
6625 /* quotes: */ 0,
6626 var_str_list)
6627 ) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006628 varflags &= ~VSNUL;
6629 /*
6630 * Remove any recorded regions beyond
6631 * start of variable
6632 */
6633 removerecordregions(startloc);
6634 goto again;
6635 }
6636 goto end;
6637 }
6638 if (easy)
6639 goto record;
6640 goto end;
6641 }
6642
6643 if (varlen < 0 && uflag)
6644 varunset(p, var, 0, 0);
6645
6646 if (subtype == VSLENGTH) {
6647 cvtnum(varlen > 0 ? varlen : 0);
6648 goto record;
6649 }
6650
6651 if (subtype == VSNORMAL) {
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006652 if (easy)
6653 goto record;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006654 goto end;
6655 }
6656
6657#if DEBUG
6658 switch (subtype) {
6659 case VSTRIMLEFT:
6660 case VSTRIMLEFTMAX:
6661 case VSTRIMRIGHT:
6662 case VSTRIMRIGHTMAX:
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006663#if ENABLE_ASH_BASH_COMPAT
6664 case VSSUBSTR:
6665 case VSREPLACE:
6666 case VSREPLACEALL:
6667#endif
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006668 break;
6669 default:
6670 abort();
6671 }
6672#endif
6673
6674 if (varlen >= 0) {
6675 /*
6676 * Terminate the string and start recording the pattern
6677 * right after it
6678 */
6679 STPUTC('\0', expdest);
6680 patloc = expdest - (char *)stackblock();
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006681 if (0 == subevalvar(p, /* str: */ NULL, patloc, subtype,
6682 startloc, varflags,
Denys Vlasenko1166d7b2009-09-16 16:20:31 +02006683//TODO: | EXP_REDIR too? All other such places do it too
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006684 /* quotes: */ flags & (EXP_FULL | EXP_CASE),
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006685 var_str_list)
6686 ) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006687 int amount = expdest - (
6688 (char *)stackblock() + patloc - 1
6689 );
6690 STADJUST(-amount, expdest);
6691 }
6692 /* Remove any recorded regions beyond start of variable */
6693 removerecordregions(startloc);
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006694 record:
6695 recordregion(startloc, expdest - (char *)stackblock(), quoted);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006696 }
6697
6698 end:
6699 if (subtype != VSNORMAL) { /* skip to end of alternative */
6700 int nesting = 1;
6701 for (;;) {
Denys Vlasenkocd716832009-11-28 22:14:02 +01006702 unsigned char c = *p++;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006703 if (c == CTLESC)
6704 p++;
6705 else if (c == CTLBACKQ || c == (CTLBACKQ|CTLQUOTE)) {
6706 if (varlen >= 0)
6707 argbackq = argbackq->next;
6708 } else if (c == CTLVAR) {
6709 if ((*p++ & VSTYPE) != VSNORMAL)
6710 nesting++;
6711 } else if (c == CTLENDVAR) {
6712 if (--nesting == 0)
6713 break;
6714 }
6715 }
6716 }
6717 return p;
6718}
6719
6720/*
6721 * Break the argument string into pieces based upon IFS and add the
6722 * strings to the argument list. The regions of the string to be
6723 * searched for IFS characters have been stored by recordregion.
6724 */
6725static void
6726ifsbreakup(char *string, struct arglist *arglist)
6727{
6728 struct ifsregion *ifsp;
6729 struct strlist *sp;
6730 char *start;
6731 char *p;
6732 char *q;
6733 const char *ifs, *realifs;
6734 int ifsspc;
6735 int nulonly;
6736
6737 start = string;
6738 if (ifslastp != NULL) {
6739 ifsspc = 0;
6740 nulonly = 0;
6741 realifs = ifsset() ? ifsval() : defifs;
6742 ifsp = &ifsfirst;
6743 do {
6744 p = string + ifsp->begoff;
6745 nulonly = ifsp->nulonly;
6746 ifs = nulonly ? nullstr : realifs;
6747 ifsspc = 0;
6748 while (p < string + ifsp->endoff) {
6749 q = p;
Denys Vlasenkocd716832009-11-28 22:14:02 +01006750 if ((unsigned char)*p == CTLESC)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006751 p++;
6752 if (!strchr(ifs, *p)) {
6753 p++;
6754 continue;
6755 }
6756 if (!nulonly)
6757 ifsspc = (strchr(defifs, *p) != NULL);
6758 /* Ignore IFS whitespace at start */
6759 if (q == start && ifsspc) {
6760 p++;
6761 start = p;
6762 continue;
6763 }
6764 *q = '\0';
Denis Vlasenko597906c2008-02-20 16:38:54 +00006765 sp = stzalloc(sizeof(*sp));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006766 sp->text = start;
6767 *arglist->lastp = sp;
6768 arglist->lastp = &sp->next;
6769 p++;
6770 if (!nulonly) {
6771 for (;;) {
6772 if (p >= string + ifsp->endoff) {
6773 break;
6774 }
6775 q = p;
Denys Vlasenkocd716832009-11-28 22:14:02 +01006776 if ((unsigned char)*p == CTLESC)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006777 p++;
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +00006778 if (strchr(ifs, *p) == NULL) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006779 p = q;
6780 break;
Denis Vlasenko597906c2008-02-20 16:38:54 +00006781 }
6782 if (strchr(defifs, *p) == NULL) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006783 if (ifsspc) {
6784 p++;
6785 ifsspc = 0;
6786 } else {
6787 p = q;
6788 break;
6789 }
6790 } else
6791 p++;
6792 }
6793 }
6794 start = p;
6795 } /* while */
6796 ifsp = ifsp->next;
6797 } while (ifsp != NULL);
6798 if (nulonly)
6799 goto add;
6800 }
6801
6802 if (!*start)
6803 return;
6804
6805 add:
Denis Vlasenko597906c2008-02-20 16:38:54 +00006806 sp = stzalloc(sizeof(*sp));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006807 sp->text = start;
6808 *arglist->lastp = sp;
6809 arglist->lastp = &sp->next;
6810}
6811
6812static void
6813ifsfree(void)
6814{
6815 struct ifsregion *p;
6816
6817 INT_OFF;
6818 p = ifsfirst.next;
6819 do {
6820 struct ifsregion *ifsp;
6821 ifsp = p->next;
6822 free(p);
6823 p = ifsp;
6824 } while (p);
6825 ifslastp = NULL;
6826 ifsfirst.next = NULL;
6827 INT_ON;
6828}
6829
6830/*
6831 * Add a file name to the list.
6832 */
6833static void
6834addfname(const char *name)
6835{
6836 struct strlist *sp;
6837
Denis Vlasenko597906c2008-02-20 16:38:54 +00006838 sp = stzalloc(sizeof(*sp));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006839 sp->text = ststrdup(name);
6840 *exparg.lastp = sp;
6841 exparg.lastp = &sp->next;
6842}
6843
6844static char *expdir;
6845
6846/*
6847 * Do metacharacter (i.e. *, ?, [...]) expansion.
6848 */
6849static void
6850expmeta(char *enddir, char *name)
6851{
6852 char *p;
6853 const char *cp;
6854 char *start;
6855 char *endname;
6856 int metaflag;
6857 struct stat statb;
6858 DIR *dirp;
6859 struct dirent *dp;
6860 int atend;
6861 int matchdot;
6862
6863 metaflag = 0;
6864 start = name;
6865 for (p = name; *p; p++) {
6866 if (*p == '*' || *p == '?')
6867 metaflag = 1;
6868 else if (*p == '[') {
6869 char *q = p + 1;
6870 if (*q == '!')
6871 q++;
6872 for (;;) {
6873 if (*q == '\\')
6874 q++;
6875 if (*q == '/' || *q == '\0')
6876 break;
6877 if (*++q == ']') {
6878 metaflag = 1;
6879 break;
6880 }
6881 }
6882 } else if (*p == '\\')
6883 p++;
6884 else if (*p == '/') {
6885 if (metaflag)
6886 goto out;
6887 start = p + 1;
6888 }
6889 }
6890 out:
6891 if (metaflag == 0) { /* we've reached the end of the file name */
6892 if (enddir != expdir)
6893 metaflag++;
6894 p = name;
6895 do {
6896 if (*p == '\\')
6897 p++;
6898 *enddir++ = *p;
6899 } while (*p++);
6900 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
6901 addfname(expdir);
6902 return;
6903 }
6904 endname = p;
6905 if (name < start) {
6906 p = name;
6907 do {
6908 if (*p == '\\')
6909 p++;
6910 *enddir++ = *p++;
6911 } while (p < start);
6912 }
6913 if (enddir == expdir) {
6914 cp = ".";
6915 } else if (enddir == expdir + 1 && *expdir == '/') {
6916 cp = "/";
6917 } else {
6918 cp = expdir;
6919 enddir[-1] = '\0';
6920 }
6921 dirp = opendir(cp);
6922 if (dirp == NULL)
6923 return;
6924 if (enddir != expdir)
6925 enddir[-1] = '/';
6926 if (*endname == 0) {
6927 atend = 1;
6928 } else {
6929 atend = 0;
6930 *endname++ = '\0';
6931 }
6932 matchdot = 0;
6933 p = start;
6934 if (*p == '\\')
6935 p++;
6936 if (*p == '.')
6937 matchdot++;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006938 while (!pending_int && (dp = readdir(dirp)) != NULL) {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00006939 if (dp->d_name[0] == '.' && !matchdot)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006940 continue;
6941 if (pmatch(start, dp->d_name)) {
6942 if (atend) {
6943 strcpy(enddir, dp->d_name);
6944 addfname(expdir);
6945 } else {
6946 for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
6947 continue;
6948 p[-1] = '/';
6949 expmeta(p, endname);
6950 }
6951 }
6952 }
6953 closedir(dirp);
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00006954 if (!atend)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006955 endname[-1] = '/';
6956}
6957
6958static struct strlist *
6959msort(struct strlist *list, int len)
6960{
6961 struct strlist *p, *q = NULL;
6962 struct strlist **lpp;
6963 int half;
6964 int n;
6965
6966 if (len <= 1)
6967 return list;
6968 half = len >> 1;
6969 p = list;
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +00006970 for (n = half; --n >= 0;) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006971 q = p;
6972 p = p->next;
6973 }
6974 q->next = NULL; /* terminate first half of list */
6975 q = msort(list, half); /* sort first half of list */
6976 p = msort(p, len - half); /* sort second half */
6977 lpp = &list;
6978 for (;;) {
6979#if ENABLE_LOCALE_SUPPORT
6980 if (strcoll(p->text, q->text) < 0)
6981#else
6982 if (strcmp(p->text, q->text) < 0)
6983#endif
6984 {
6985 *lpp = p;
6986 lpp = &p->next;
6987 p = *lpp;
6988 if (p == NULL) {
6989 *lpp = q;
6990 break;
6991 }
6992 } else {
6993 *lpp = q;
6994 lpp = &q->next;
6995 q = *lpp;
6996 if (q == NULL) {
6997 *lpp = p;
6998 break;
6999 }
7000 }
7001 }
7002 return list;
7003}
7004
7005/*
7006 * Sort the results of file name expansion. It calculates the number of
7007 * strings to sort and then calls msort (short for merge sort) to do the
7008 * work.
7009 */
7010static struct strlist *
7011expsort(struct strlist *str)
7012{
7013 int len;
7014 struct strlist *sp;
7015
7016 len = 0;
7017 for (sp = str; sp; sp = sp->next)
7018 len++;
7019 return msort(str, len);
7020}
7021
7022static void
Denis Vlasenko68404f12008-03-17 09:00:54 +00007023expandmeta(struct strlist *str /*, int flag*/)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007024{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00007025 static const char metachars[] ALIGN1 = {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007026 '*', '?', '[', 0
7027 };
7028 /* TODO - EXP_REDIR */
7029
7030 while (str) {
7031 struct strlist **savelastp;
7032 struct strlist *sp;
7033 char *p;
7034
7035 if (fflag)
7036 goto nometa;
7037 if (!strpbrk(str->text, metachars))
7038 goto nometa;
7039 savelastp = exparg.lastp;
7040
7041 INT_OFF;
7042 p = preglob(str->text, 0, RMESCAPE_ALLOC | RMESCAPE_HEAP);
7043 {
7044 int i = strlen(str->text);
7045 expdir = ckmalloc(i < 2048 ? 2048 : i); /* XXX */
7046 }
7047
7048 expmeta(expdir, p);
7049 free(expdir);
7050 if (p != str->text)
7051 free(p);
7052 INT_ON;
7053 if (exparg.lastp == savelastp) {
7054 /*
7055 * no matches
7056 */
7057 nometa:
7058 *exparg.lastp = str;
Denys Vlasenkob6c84342009-08-29 20:23:20 +02007059 rmescapes(str->text, 0);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007060 exparg.lastp = &str->next;
7061 } else {
7062 *exparg.lastp = NULL;
7063 *savelastp = sp = expsort(*savelastp);
7064 while (sp->next != NULL)
7065 sp = sp->next;
7066 exparg.lastp = &sp->next;
7067 }
7068 str = str->next;
7069 }
7070}
7071
7072/*
7073 * Perform variable substitution and command substitution on an argument,
7074 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
7075 * perform splitting and file name expansion. When arglist is NULL, perform
7076 * here document expansion.
7077 */
7078static void
7079expandarg(union node *arg, struct arglist *arglist, int flag)
7080{
7081 struct strlist *sp;
7082 char *p;
7083
7084 argbackq = arg->narg.backquote;
7085 STARTSTACKSTR(expdest);
7086 ifsfirst.next = NULL;
7087 ifslastp = NULL;
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00007088 argstr(arg->narg.text, flag,
7089 /* var_str_list: */ arglist ? arglist->list : NULL);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007090 p = _STPUTC('\0', expdest);
7091 expdest = p - 1;
7092 if (arglist == NULL) {
7093 return; /* here document expanded */
7094 }
7095 p = grabstackstr(p);
7096 exparg.lastp = &exparg.list;
7097 /*
7098 * TODO - EXP_REDIR
7099 */
7100 if (flag & EXP_FULL) {
7101 ifsbreakup(p, &exparg);
7102 *exparg.lastp = NULL;
7103 exparg.lastp = &exparg.list;
Denis Vlasenko68404f12008-03-17 09:00:54 +00007104 expandmeta(exparg.list /*, flag*/);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007105 } else {
7106 if (flag & EXP_REDIR) /*XXX - for now, just remove escapes */
Denys Vlasenkob6c84342009-08-29 20:23:20 +02007107 rmescapes(p, 0);
Denis Vlasenko597906c2008-02-20 16:38:54 +00007108 sp = stzalloc(sizeof(*sp));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007109 sp->text = p;
7110 *exparg.lastp = sp;
7111 exparg.lastp = &sp->next;
7112 }
7113 if (ifsfirst.next)
7114 ifsfree();
7115 *exparg.lastp = NULL;
7116 if (exparg.list) {
7117 *arglist->lastp = exparg.list;
7118 arglist->lastp = exparg.lastp;
7119 }
7120}
7121
7122/*
7123 * Expand shell variables and backquotes inside a here document.
7124 */
7125static void
7126expandhere(union node *arg, int fd)
7127{
7128 herefd = fd;
7129 expandarg(arg, (struct arglist *)NULL, 0);
7130 full_write(fd, stackblock(), expdest - (char *)stackblock());
7131}
7132
7133/*
7134 * Returns true if the pattern matches the string.
7135 */
7136static int
7137patmatch(char *pattern, const char *string)
7138{
7139 return pmatch(preglob(pattern, 0, 0), string);
7140}
7141
7142/*
7143 * See if a pattern matches in a case statement.
7144 */
7145static int
7146casematch(union node *pattern, char *val)
7147{
7148 struct stackmark smark;
7149 int result;
7150
7151 setstackmark(&smark);
7152 argbackq = pattern->narg.backquote;
7153 STARTSTACKSTR(expdest);
7154 ifslastp = NULL;
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00007155 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE,
7156 /* var_str_list: */ NULL);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007157 STACKSTRNUL(expdest);
7158 result = patmatch(stackblock(), val);
7159 popstackmark(&smark);
7160 return result;
7161}
7162
7163
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007164/* ============ find_command */
7165
7166struct builtincmd {
7167 const char *name;
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007168 int (*builtin)(int, char **) FAST_FUNC;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007169 /* unsigned flags; */
7170};
7171#define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
Denis Vlasenkoe26b2782008-02-12 07:40:29 +00007172/* "regular" builtins always take precedence over commands,
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007173 * regardless of PATH=....%builtin... position */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007174#define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007175#define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007176
7177struct cmdentry {
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00007178 smallint cmdtype; /* CMDxxx */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007179 union param {
7180 int index;
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00007181 /* index >= 0 for commands without path (slashes) */
7182 /* (TODO: what exactly does the value mean? PATH position?) */
7183 /* index == -1 for commands with slashes */
7184 /* index == (-2 - applet_no) for NOFORK applets */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007185 const struct builtincmd *cmd;
7186 struct funcnode *func;
7187 } u;
7188};
7189/* values of cmdtype */
7190#define CMDUNKNOWN -1 /* no entry in table for command */
7191#define CMDNORMAL 0 /* command is an executable program */
7192#define CMDFUNCTION 1 /* command is a shell function */
7193#define CMDBUILTIN 2 /* command is a shell builtin */
7194
7195/* action to find_command() */
7196#define DO_ERR 0x01 /* prints errors */
7197#define DO_ABS 0x02 /* checks absolute paths */
7198#define DO_NOFUNC 0x04 /* don't return shell functions, for command */
7199#define DO_ALTPATH 0x08 /* using alternate path */
7200#define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
7201
7202static void find_command(char *, struct cmdentry *, int, const char *);
7203
7204
7205/* ============ Hashing commands */
7206
7207/*
7208 * When commands are first encountered, they are entered in a hash table.
7209 * This ensures that a full path search will not have to be done for them
7210 * on each invocation.
7211 *
7212 * We should investigate converting to a linear search, even though that
7213 * would make the command name "hash" a misnomer.
7214 */
7215
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007216struct tblentry {
7217 struct tblentry *next; /* next entry in hash chain */
7218 union param param; /* definition of builtin function */
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00007219 smallint cmdtype; /* CMDxxx */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007220 char rehash; /* if set, cd done since entry created */
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007221 char cmdname[1]; /* name of command */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007222};
7223
Denis Vlasenko01631112007-12-16 17:20:38 +00007224static struct tblentry **cmdtable;
7225#define INIT_G_cmdtable() do { \
7226 cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
7227} while (0)
7228
7229static int builtinloc = -1; /* index in path of %builtin, or -1 */
7230
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007231
7232static void
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00007233tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) char *cmd, char **argv, char **envp)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007234{
7235 int repeated = 0;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007236
Denis Vlasenko80d14be2007-04-10 23:03:30 +00007237#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007238 if (applet_no >= 0) {
Denis Vlasenkob7304742008-10-20 08:15:51 +00007239 if (APPLET_IS_NOEXEC(applet_no)) {
7240 while (*envp)
7241 putenv(*envp++);
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007242 run_applet_no_and_exit(applet_no, argv);
Denis Vlasenkob7304742008-10-20 08:15:51 +00007243 }
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007244 /* re-exec ourselves with the new arguments */
7245 execve(bb_busybox_exec_path, argv, envp);
7246 /* If they called chroot or otherwise made the binary no longer
7247 * executable, fall through */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007248 }
7249#endif
7250
7251 repeat:
7252#ifdef SYSV
7253 do {
7254 execve(cmd, argv, envp);
7255 } while (errno == EINTR);
7256#else
7257 execve(cmd, argv, envp);
7258#endif
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007259 if (repeated) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007260 free(argv);
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007261 return;
7262 }
7263 if (errno == ENOEXEC) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007264 char **ap;
7265 char **new;
7266
7267 for (ap = argv; *ap; ap++)
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007268 continue;
7269 ap = new = ckmalloc((ap - argv + 2) * sizeof(ap[0]));
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007270 ap[1] = cmd;
Denis Vlasenkoc44ab012007-04-09 03:11:58 +00007271 ap[0] = cmd = (char *)DEFAULT_SHELL;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007272 ap += 2;
7273 argv++;
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007274 while ((*ap++ = *argv++) != NULL)
Denis Vlasenko597906c2008-02-20 16:38:54 +00007275 continue;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007276 argv = new;
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007277 repeated++;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007278 goto repeat;
7279 }
7280}
7281
7282/*
7283 * Exec a program. Never returns. If you change this routine, you may
7284 * have to change the find_command routine as well.
7285 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00007286static void shellexec(char **, const char *, int) NORETURN;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007287static void
7288shellexec(char **argv, const char *path, int idx)
7289{
7290 char *cmdname;
7291 int e;
7292 char **envp;
7293 int exerrno;
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007294#if ENABLE_FEATURE_SH_STANDALONE
7295 int applet_no = -1;
7296#endif
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007297
Denis Vlasenko34c73c42008-08-16 11:48:02 +00007298 clearredir(/*drop:*/ 1);
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007299 envp = listvars(VEXPORT, VUNSET, 0);
7300 if (strchr(argv[0], '/') != NULL
Denis Vlasenko80d14be2007-04-10 23:03:30 +00007301#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007302 || (applet_no = find_applet_by_name(argv[0])) >= 0
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007303#endif
7304 ) {
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00007305 tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) argv[0], argv, envp);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007306 e = errno;
7307 } else {
7308 e = ENOENT;
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02007309 while ((cmdname = path_advance(&path, argv[0])) != NULL) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007310 if (--idx < 0 && pathopt == NULL) {
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00007311 tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007312 if (errno != ENOENT && errno != ENOTDIR)
7313 e = errno;
7314 }
7315 stunalloc(cmdname);
7316 }
7317 }
7318
7319 /* Map to POSIX errors */
7320 switch (e) {
7321 case EACCES:
7322 exerrno = 126;
7323 break;
7324 case ENOENT:
7325 exerrno = 127;
7326 break;
7327 default:
7328 exerrno = 2;
7329 break;
7330 }
7331 exitstatus = exerrno;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02007332 TRACE(("shellexec failed for %s, errno %d, suppress_int %d\n",
7333 argv[0], e, suppress_int));
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007334 ash_msg_and_raise(EXEXEC, "%s: %s", argv[0], errmsg(e, "not found"));
7335 /* NOTREACHED */
7336}
7337
7338static void
7339printentry(struct tblentry *cmdp)
7340{
7341 int idx;
7342 const char *path;
7343 char *name;
7344
7345 idx = cmdp->param.index;
7346 path = pathval();
7347 do {
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02007348 name = path_advance(&path, cmdp->cmdname);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007349 stunalloc(name);
7350 } while (--idx >= 0);
7351 out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
7352}
7353
7354/*
7355 * Clear out command entries. The argument specifies the first entry in
7356 * PATH which has changed.
7357 */
7358static void
7359clearcmdentry(int firstchange)
7360{
7361 struct tblentry **tblp;
7362 struct tblentry **pp;
7363 struct tblentry *cmdp;
7364
7365 INT_OFF;
7366 for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
7367 pp = tblp;
7368 while ((cmdp = *pp) != NULL) {
7369 if ((cmdp->cmdtype == CMDNORMAL &&
7370 cmdp->param.index >= firstchange)
7371 || (cmdp->cmdtype == CMDBUILTIN &&
7372 builtinloc >= firstchange)
7373 ) {
7374 *pp = cmdp->next;
7375 free(cmdp);
7376 } else {
7377 pp = &cmdp->next;
7378 }
7379 }
7380 }
7381 INT_ON;
7382}
7383
7384/*
7385 * Locate a command in the command hash table. If "add" is nonzero,
7386 * add the command to the table if it is not already present. The
7387 * variable "lastcmdentry" is set to point to the address of the link
7388 * pointing to the entry, so that delete_cmd_entry can delete the
7389 * entry.
7390 *
7391 * Interrupts must be off if called with add != 0.
7392 */
7393static struct tblentry **lastcmdentry;
7394
7395static struct tblentry *
7396cmdlookup(const char *name, int add)
7397{
7398 unsigned int hashval;
7399 const char *p;
7400 struct tblentry *cmdp;
7401 struct tblentry **pp;
7402
7403 p = name;
7404 hashval = (unsigned char)*p << 4;
7405 while (*p)
7406 hashval += (unsigned char)*p++;
7407 hashval &= 0x7FFF;
7408 pp = &cmdtable[hashval % CMDTABLESIZE];
7409 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7410 if (strcmp(cmdp->cmdname, name) == 0)
7411 break;
7412 pp = &cmdp->next;
7413 }
7414 if (add && cmdp == NULL) {
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007415 cmdp = *pp = ckzalloc(sizeof(struct tblentry)
7416 + strlen(name)
7417 /* + 1 - already done because
7418 * tblentry::cmdname is char[1] */);
Denis Vlasenko597906c2008-02-20 16:38:54 +00007419 /*cmdp->next = NULL; - ckzalloc did it */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007420 cmdp->cmdtype = CMDUNKNOWN;
7421 strcpy(cmdp->cmdname, name);
7422 }
7423 lastcmdentry = pp;
7424 return cmdp;
7425}
7426
7427/*
7428 * Delete the command entry returned on the last lookup.
7429 */
7430static void
7431delete_cmd_entry(void)
7432{
7433 struct tblentry *cmdp;
7434
7435 INT_OFF;
7436 cmdp = *lastcmdentry;
7437 *lastcmdentry = cmdp->next;
7438 if (cmdp->cmdtype == CMDFUNCTION)
7439 freefunc(cmdp->param.func);
7440 free(cmdp);
7441 INT_ON;
7442}
7443
7444/*
7445 * Add a new command entry, replacing any existing command entry for
7446 * the same name - except special builtins.
7447 */
7448static void
7449addcmdentry(char *name, struct cmdentry *entry)
7450{
7451 struct tblentry *cmdp;
7452
7453 cmdp = cmdlookup(name, 1);
7454 if (cmdp->cmdtype == CMDFUNCTION) {
7455 freefunc(cmdp->param.func);
7456 }
7457 cmdp->cmdtype = entry->cmdtype;
7458 cmdp->param = entry->u;
7459 cmdp->rehash = 0;
7460}
7461
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007462static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00007463hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007464{
7465 struct tblentry **pp;
7466 struct tblentry *cmdp;
7467 int c;
7468 struct cmdentry entry;
7469 char *name;
7470
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007471 if (nextopt("r") != '\0') {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007472 clearcmdentry(0);
7473 return 0;
7474 }
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007475
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007476 if (*argptr == NULL) {
7477 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7478 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7479 if (cmdp->cmdtype == CMDNORMAL)
7480 printentry(cmdp);
7481 }
7482 }
7483 return 0;
7484 }
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007485
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007486 c = 0;
7487 while ((name = *argptr) != NULL) {
7488 cmdp = cmdlookup(name, 0);
7489 if (cmdp != NULL
7490 && (cmdp->cmdtype == CMDNORMAL
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007491 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
7492 ) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007493 delete_cmd_entry();
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007494 }
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007495 find_command(name, &entry, DO_ERR, pathval());
7496 if (entry.cmdtype == CMDUNKNOWN)
7497 c = 1;
7498 argptr++;
7499 }
7500 return c;
7501}
7502
7503/*
7504 * Called when a cd is done. Marks all commands so the next time they
7505 * are executed they will be rehashed.
7506 */
7507static void
7508hashcd(void)
7509{
7510 struct tblentry **pp;
7511 struct tblentry *cmdp;
7512
7513 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7514 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007515 if (cmdp->cmdtype == CMDNORMAL
7516 || (cmdp->cmdtype == CMDBUILTIN
7517 && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
7518 && builtinloc > 0)
7519 ) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007520 cmdp->rehash = 1;
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007521 }
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007522 }
7523 }
7524}
7525
7526/*
7527 * Fix command hash table when PATH changed.
7528 * Called before PATH is changed. The argument is the new value of PATH;
7529 * pathval() still returns the old value at this point.
7530 * Called with interrupts off.
7531 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007532static void FAST_FUNC
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007533changepath(const char *new)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007534{
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007535 const char *old;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007536 int firstchange;
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007537 int idx;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007538 int idx_bltin;
7539
7540 old = pathval();
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007541 firstchange = 9999; /* assume no change */
7542 idx = 0;
7543 idx_bltin = -1;
7544 for (;;) {
7545 if (*old != *new) {
7546 firstchange = idx;
7547 if ((*old == '\0' && *new == ':')
Denys Vlasenkoa0ec4f52010-05-20 12:50:42 +02007548 || (*old == ':' && *new == '\0')
7549 ) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007550 firstchange++;
Denys Vlasenkoa0ec4f52010-05-20 12:50:42 +02007551 }
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007552 old = new; /* ignore subsequent differences */
7553 }
7554 if (*new == '\0')
7555 break;
7556 if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
7557 idx_bltin = idx;
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007558 if (*new == ':')
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007559 idx++;
Denys Vlasenkoa0ec4f52010-05-20 12:50:42 +02007560 new++;
7561 old++;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007562 }
7563 if (builtinloc < 0 && idx_bltin >= 0)
7564 builtinloc = idx_bltin; /* zap builtins */
7565 if (builtinloc >= 0 && idx_bltin < 0)
7566 firstchange = 0;
7567 clearcmdentry(firstchange);
7568 builtinloc = idx_bltin;
7569}
7570
7571#define TEOF 0
7572#define TNL 1
7573#define TREDIR 2
7574#define TWORD 3
7575#define TSEMI 4
7576#define TBACKGND 5
7577#define TAND 6
7578#define TOR 7
7579#define TPIPE 8
7580#define TLP 9
7581#define TRP 10
7582#define TENDCASE 11
7583#define TENDBQUOTE 12
7584#define TNOT 13
7585#define TCASE 14
7586#define TDO 15
7587#define TDONE 16
7588#define TELIF 17
7589#define TELSE 18
7590#define TESAC 19
7591#define TFI 20
7592#define TFOR 21
7593#define TIF 22
7594#define TIN 23
7595#define TTHEN 24
7596#define TUNTIL 25
7597#define TWHILE 26
7598#define TBEGIN 27
7599#define TEND 28
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007600typedef smallint token_id_t;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007601
7602/* first char is indicating which tokens mark the end of a list */
7603static const char *const tokname_array[] = {
7604 "\1end of file",
7605 "\0newline",
7606 "\0redirection",
7607 "\0word",
7608 "\0;",
7609 "\0&",
7610 "\0&&",
7611 "\0||",
7612 "\0|",
7613 "\0(",
7614 "\1)",
7615 "\1;;",
7616 "\1`",
7617#define KWDOFFSET 13
7618 /* the following are keywords */
7619 "\0!",
7620 "\0case",
7621 "\1do",
7622 "\1done",
7623 "\1elif",
7624 "\1else",
7625 "\1esac",
7626 "\1fi",
7627 "\0for",
7628 "\0if",
7629 "\0in",
7630 "\1then",
7631 "\0until",
7632 "\0while",
7633 "\0{",
7634 "\1}",
7635};
7636
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007637/* Wrapper around strcmp for qsort/bsearch/... */
7638static int
7639pstrcmp(const void *a, const void *b)
7640{
Denis Vlasenko240a1cf2007-04-08 16:07:02 +00007641 return strcmp((char*) a, (*(char**) b) + 1);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007642}
7643
7644static const char *const *
7645findkwd(const char *s)
7646{
7647 return bsearch(s, tokname_array + KWDOFFSET,
Denis Vlasenko80b8b392007-06-25 10:55:35 +00007648 ARRAY_SIZE(tokname_array) - KWDOFFSET,
7649 sizeof(tokname_array[0]), pstrcmp);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007650}
7651
7652/*
7653 * Locate and print what a word is...
7654 */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007655static int
7656describe_command(char *command, int describe_command_verbose)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007657{
7658 struct cmdentry entry;
7659 struct tblentry *cmdp;
7660#if ENABLE_ASH_ALIAS
7661 const struct alias *ap;
7662#endif
7663 const char *path = pathval();
7664
7665 if (describe_command_verbose) {
7666 out1str(command);
7667 }
7668
7669 /* First look at the keywords */
7670 if (findkwd(command)) {
7671 out1str(describe_command_verbose ? " is a shell keyword" : command);
7672 goto out;
7673 }
7674
7675#if ENABLE_ASH_ALIAS
7676 /* Then look at the aliases */
7677 ap = lookupalias(command, 0);
7678 if (ap != NULL) {
Denis Vlasenko46846e22007-05-20 13:08:31 +00007679 if (!describe_command_verbose) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007680 out1str("alias ");
7681 printalias(ap);
7682 return 0;
7683 }
Denis Vlasenko46846e22007-05-20 13:08:31 +00007684 out1fmt(" is an alias for %s", ap->val);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007685 goto out;
7686 }
7687#endif
7688 /* Then check if it is a tracked alias */
7689 cmdp = cmdlookup(command, 0);
7690 if (cmdp != NULL) {
7691 entry.cmdtype = cmdp->cmdtype;
7692 entry.u = cmdp->param;
7693 } else {
7694 /* Finally use brute force */
7695 find_command(command, &entry, DO_ABS, path);
7696 }
7697
7698 switch (entry.cmdtype) {
7699 case CMDNORMAL: {
7700 int j = entry.u.index;
7701 char *p;
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00007702 if (j < 0) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007703 p = command;
7704 } else {
7705 do {
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02007706 p = path_advance(&path, command);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007707 stunalloc(p);
7708 } while (--j >= 0);
7709 }
7710 if (describe_command_verbose) {
7711 out1fmt(" is%s %s",
7712 (cmdp ? " a tracked alias for" : nullstr), p
7713 );
7714 } else {
7715 out1str(p);
7716 }
7717 break;
7718 }
7719
7720 case CMDFUNCTION:
7721 if (describe_command_verbose) {
7722 out1str(" is a shell function");
7723 } else {
7724 out1str(command);
7725 }
7726 break;
7727
7728 case CMDBUILTIN:
7729 if (describe_command_verbose) {
7730 out1fmt(" is a %sshell builtin",
7731 IS_BUILTIN_SPECIAL(entry.u.cmd) ?
7732 "special " : nullstr
7733 );
7734 } else {
7735 out1str(command);
7736 }
7737 break;
7738
7739 default:
7740 if (describe_command_verbose) {
7741 out1str(": not found\n");
7742 }
7743 return 127;
7744 }
7745 out:
Denys Vlasenko285ad152009-12-04 23:02:27 +01007746 out1str("\n");
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007747 return 0;
7748}
7749
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007750static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00007751typecmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007752{
Denis Vlasenko46846e22007-05-20 13:08:31 +00007753 int i = 1;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007754 int err = 0;
Denis Vlasenko46846e22007-05-20 13:08:31 +00007755 int verbose = 1;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007756
Denis Vlasenko46846e22007-05-20 13:08:31 +00007757 /* type -p ... ? (we don't bother checking for 'p') */
Denis Vlasenko1fc62382007-06-25 22:55:34 +00007758 if (argv[1] && argv[1][0] == '-') {
Denis Vlasenko46846e22007-05-20 13:08:31 +00007759 i++;
7760 verbose = 0;
7761 }
Denis Vlasenko68404f12008-03-17 09:00:54 +00007762 while (argv[i]) {
Denis Vlasenko46846e22007-05-20 13:08:31 +00007763 err |= describe_command(argv[i++], verbose);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007764 }
7765 return err;
7766}
7767
7768#if ENABLE_ASH_CMDCMD
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007769static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00007770commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007771{
7772 int c;
7773 enum {
7774 VERIFY_BRIEF = 1,
7775 VERIFY_VERBOSE = 2,
7776 } verify = 0;
7777
7778 while ((c = nextopt("pvV")) != '\0')
7779 if (c == 'V')
7780 verify |= VERIFY_VERBOSE;
7781 else if (c == 'v')
7782 verify |= VERIFY_BRIEF;
7783#if DEBUG
7784 else if (c != 'p')
7785 abort();
7786#endif
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00007787 /* Mimic bash: just "command -v" doesn't complain, it's a nop */
7788 if (verify && (*argptr != NULL)) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007789 return describe_command(*argptr, verify - VERIFY_BRIEF);
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00007790 }
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007791
7792 return 0;
7793}
7794#endif
7795
7796
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007797/* ============ eval.c */
Eric Andersencb57d552001-06-28 07:25:16 +00007798
Denis Vlasenko340299a2008-11-21 10:36:36 +00007799static int funcblocksize; /* size of structures in function */
7800static int funcstringsize; /* size of strings in node */
7801static void *funcblock; /* block to allocate function from */
7802static char *funcstring; /* block to allocate strings from */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007803
Eric Andersencb57d552001-06-28 07:25:16 +00007804/* flags in argument to evaltree */
Denis Vlasenko340299a2008-11-21 10:36:36 +00007805#define EV_EXIT 01 /* exit after evaluating tree */
7806#define EV_TESTED 02 /* exit status is checked; ignore -e flag */
Eric Andersenc470f442003-07-28 09:56:35 +00007807#define EV_BACKCMD 04 /* command executing within back quotes */
Eric Andersencb57d552001-06-28 07:25:16 +00007808
Denys Vlasenko0e5e4ea2009-10-11 00:36:20 +02007809static const uint8_t nodesize[N_NUMBER] = {
Denis Vlasenko340299a2008-11-21 10:36:36 +00007810 [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
7811 [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
7812 [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
7813 [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
7814 [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
7815 [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
7816 [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
7817 [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
7818 [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
7819 [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
7820 [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
7821 [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
7822 [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
7823 [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
7824 [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
7825 [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
7826 [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
Denis Vlasenkocc5feab2008-11-22 01:32:40 +00007827#if ENABLE_ASH_BASH_COMPAT
Denis Vlasenko340299a2008-11-21 10:36:36 +00007828 [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
Denis Vlasenkocc5feab2008-11-22 01:32:40 +00007829#endif
Denis Vlasenko340299a2008-11-21 10:36:36 +00007830 [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
7831 [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
7832 [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
7833 [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
7834 [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
7835 [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
7836 [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
7837 [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
7838 [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007839};
7840
7841static void calcsize(union node *n);
7842
7843static void
7844sizenodelist(struct nodelist *lp)
7845{
7846 while (lp) {
7847 funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
7848 calcsize(lp->n);
7849 lp = lp->next;
7850 }
7851}
7852
7853static void
7854calcsize(union node *n)
7855{
7856 if (n == NULL)
7857 return;
7858 funcblocksize += nodesize[n->type];
7859 switch (n->type) {
7860 case NCMD:
7861 calcsize(n->ncmd.redirect);
7862 calcsize(n->ncmd.args);
7863 calcsize(n->ncmd.assign);
7864 break;
7865 case NPIPE:
7866 sizenodelist(n->npipe.cmdlist);
7867 break;
7868 case NREDIR:
7869 case NBACKGND:
7870 case NSUBSHELL:
7871 calcsize(n->nredir.redirect);
7872 calcsize(n->nredir.n);
7873 break;
7874 case NAND:
7875 case NOR:
7876 case NSEMI:
7877 case NWHILE:
7878 case NUNTIL:
7879 calcsize(n->nbinary.ch2);
7880 calcsize(n->nbinary.ch1);
7881 break;
7882 case NIF:
7883 calcsize(n->nif.elsepart);
7884 calcsize(n->nif.ifpart);
7885 calcsize(n->nif.test);
7886 break;
7887 case NFOR:
7888 funcstringsize += strlen(n->nfor.var) + 1;
7889 calcsize(n->nfor.body);
7890 calcsize(n->nfor.args);
7891 break;
7892 case NCASE:
7893 calcsize(n->ncase.cases);
7894 calcsize(n->ncase.expr);
7895 break;
7896 case NCLIST:
7897 calcsize(n->nclist.body);
7898 calcsize(n->nclist.pattern);
7899 calcsize(n->nclist.next);
7900 break;
7901 case NDEFUN:
7902 case NARG:
7903 sizenodelist(n->narg.backquote);
7904 funcstringsize += strlen(n->narg.text) + 1;
7905 calcsize(n->narg.next);
7906 break;
7907 case NTO:
Denis Vlasenko559691a2008-10-05 18:39:31 +00007908#if ENABLE_ASH_BASH_COMPAT
7909 case NTO2:
7910#endif
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007911 case NCLOBBER:
7912 case NFROM:
7913 case NFROMTO:
7914 case NAPPEND:
7915 calcsize(n->nfile.fname);
7916 calcsize(n->nfile.next);
7917 break;
7918 case NTOFD:
7919 case NFROMFD:
7920 calcsize(n->ndup.vname);
7921 calcsize(n->ndup.next);
7922 break;
7923 case NHERE:
7924 case NXHERE:
7925 calcsize(n->nhere.doc);
7926 calcsize(n->nhere.next);
7927 break;
7928 case NNOT:
7929 calcsize(n->nnot.com);
7930 break;
7931 };
7932}
7933
7934static char *
7935nodeckstrdup(char *s)
7936{
7937 char *rtn = funcstring;
7938
7939 strcpy(funcstring, s);
7940 funcstring += strlen(s) + 1;
7941 return rtn;
7942}
7943
7944static union node *copynode(union node *);
7945
7946static struct nodelist *
7947copynodelist(struct nodelist *lp)
7948{
7949 struct nodelist *start;
7950 struct nodelist **lpp;
7951
7952 lpp = &start;
7953 while (lp) {
7954 *lpp = funcblock;
7955 funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
7956 (*lpp)->n = copynode(lp->n);
7957 lp = lp->next;
7958 lpp = &(*lpp)->next;
7959 }
7960 *lpp = NULL;
7961 return start;
7962}
7963
7964static union node *
7965copynode(union node *n)
7966{
7967 union node *new;
7968
7969 if (n == NULL)
7970 return NULL;
7971 new = funcblock;
7972 funcblock = (char *) funcblock + nodesize[n->type];
7973
7974 switch (n->type) {
7975 case NCMD:
7976 new->ncmd.redirect = copynode(n->ncmd.redirect);
7977 new->ncmd.args = copynode(n->ncmd.args);
7978 new->ncmd.assign = copynode(n->ncmd.assign);
7979 break;
7980 case NPIPE:
7981 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00007982 new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007983 break;
7984 case NREDIR:
7985 case NBACKGND:
7986 case NSUBSHELL:
7987 new->nredir.redirect = copynode(n->nredir.redirect);
7988 new->nredir.n = copynode(n->nredir.n);
7989 break;
7990 case NAND:
7991 case NOR:
7992 case NSEMI:
7993 case NWHILE:
7994 case NUNTIL:
7995 new->nbinary.ch2 = copynode(n->nbinary.ch2);
7996 new->nbinary.ch1 = copynode(n->nbinary.ch1);
7997 break;
7998 case NIF:
7999 new->nif.elsepart = copynode(n->nif.elsepart);
8000 new->nif.ifpart = copynode(n->nif.ifpart);
8001 new->nif.test = copynode(n->nif.test);
8002 break;
8003 case NFOR:
8004 new->nfor.var = nodeckstrdup(n->nfor.var);
8005 new->nfor.body = copynode(n->nfor.body);
8006 new->nfor.args = copynode(n->nfor.args);
8007 break;
8008 case NCASE:
8009 new->ncase.cases = copynode(n->ncase.cases);
8010 new->ncase.expr = copynode(n->ncase.expr);
8011 break;
8012 case NCLIST:
8013 new->nclist.body = copynode(n->nclist.body);
8014 new->nclist.pattern = copynode(n->nclist.pattern);
8015 new->nclist.next = copynode(n->nclist.next);
8016 break;
8017 case NDEFUN:
8018 case NARG:
8019 new->narg.backquote = copynodelist(n->narg.backquote);
8020 new->narg.text = nodeckstrdup(n->narg.text);
8021 new->narg.next = copynode(n->narg.next);
8022 break;
8023 case NTO:
Denis Vlasenko559691a2008-10-05 18:39:31 +00008024#if ENABLE_ASH_BASH_COMPAT
8025 case NTO2:
8026#endif
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008027 case NCLOBBER:
8028 case NFROM:
8029 case NFROMTO:
8030 case NAPPEND:
8031 new->nfile.fname = copynode(n->nfile.fname);
8032 new->nfile.fd = n->nfile.fd;
8033 new->nfile.next = copynode(n->nfile.next);
8034 break;
8035 case NTOFD:
8036 case NFROMFD:
8037 new->ndup.vname = copynode(n->ndup.vname);
8038 new->ndup.dupfd = n->ndup.dupfd;
8039 new->ndup.fd = n->ndup.fd;
8040 new->ndup.next = copynode(n->ndup.next);
8041 break;
8042 case NHERE:
8043 case NXHERE:
8044 new->nhere.doc = copynode(n->nhere.doc);
8045 new->nhere.fd = n->nhere.fd;
8046 new->nhere.next = copynode(n->nhere.next);
8047 break;
8048 case NNOT:
8049 new->nnot.com = copynode(n->nnot.com);
8050 break;
8051 };
8052 new->type = n->type;
8053 return new;
8054}
8055
8056/*
8057 * Make a copy of a parse tree.
8058 */
8059static struct funcnode *
8060copyfunc(union node *n)
8061{
8062 struct funcnode *f;
8063 size_t blocksize;
8064
8065 funcblocksize = offsetof(struct funcnode, n);
8066 funcstringsize = 0;
8067 calcsize(n);
8068 blocksize = funcblocksize;
8069 f = ckmalloc(blocksize + funcstringsize);
8070 funcblock = (char *) f + offsetof(struct funcnode, n);
8071 funcstring = (char *) f + blocksize;
8072 copynode(n);
8073 f->count = 0;
8074 return f;
8075}
8076
8077/*
8078 * Define a shell function.
8079 */
8080static void
8081defun(char *name, union node *func)
8082{
8083 struct cmdentry entry;
8084
8085 INT_OFF;
8086 entry.cmdtype = CMDFUNCTION;
8087 entry.u.func = copyfunc(func);
8088 addcmdentry(name, &entry);
8089 INT_ON;
8090}
8091
Denis Vlasenko4b875702009-03-19 13:30:04 +00008092/* Reasons for skipping commands (see comment on breakcmd routine) */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008093#define SKIPBREAK (1 << 0)
8094#define SKIPCONT (1 << 1)
8095#define SKIPFUNC (1 << 2)
8096#define SKIPFILE (1 << 3)
8097#define SKIPEVAL (1 << 4)
Denis Vlasenko4b875702009-03-19 13:30:04 +00008098static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008099static int skipcount; /* number of levels to skip */
8100static int funcnest; /* depth of function calls */
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +00008101static int loopnest; /* current loop nesting level */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008102
Denis Vlasenko4b875702009-03-19 13:30:04 +00008103/* Forward decl way out to parsing code - dotrap needs it */
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008104static int evalstring(char *s, int mask);
8105
Denis Vlasenko4b875702009-03-19 13:30:04 +00008106/* Called to execute a trap.
8107 * Single callsite - at the end of evaltree().
8108 * If we return non-zero, exaltree raises EXEXIT exception.
8109 *
8110 * Perhaps we should avoid entering new trap handlers
8111 * while we are executing a trap handler. [is it a TODO?]
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008112 */
8113static int
8114dotrap(void)
8115{
Denis Vlasenko4b875702009-03-19 13:30:04 +00008116 uint8_t *g;
8117 int sig;
8118 uint8_t savestatus;
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008119
8120 savestatus = exitstatus;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02008121 pending_sig = 0;
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008122 xbarrier();
8123
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008124 TRACE(("dotrap entered\n"));
Denis Vlasenko4b875702009-03-19 13:30:04 +00008125 for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
8126 int want_exexit;
8127 char *t;
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008128
Denis Vlasenko4b875702009-03-19 13:30:04 +00008129 if (*g == 0)
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008130 continue;
Denis Vlasenko4b875702009-03-19 13:30:04 +00008131 t = trap[sig];
8132 /* non-trapped SIGINT is handled separately by raise_interrupt,
8133 * don't upset it by resetting gotsig[SIGINT-1] */
8134 if (sig == SIGINT && !t)
8135 continue;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008136
8137 TRACE(("sig %d is active, will run handler '%s'\n", sig, t));
Denis Vlasenko4b875702009-03-19 13:30:04 +00008138 *g = 0;
8139 if (!t)
8140 continue;
8141 want_exexit = evalstring(t, SKIPEVAL);
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008142 exitstatus = savestatus;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008143 if (want_exexit) {
Denis Vlasenkob21f3792009-03-19 23:09:58 +00008144 TRACE(("dotrap returns %d\n", want_exexit));
Denis Vlasenko4b875702009-03-19 13:30:04 +00008145 return want_exexit;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008146 }
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008147 }
8148
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008149 TRACE(("dotrap returns 0\n"));
Denis Vlasenko991a1da2008-02-10 19:02:53 +00008150 return 0;
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008151}
8152
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00008153/* forward declarations - evaluation is fairly recursive business... */
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008154static void evalloop(union node *, int);
8155static void evalfor(union node *, int);
8156static void evalcase(union node *, int);
8157static void evalsubshell(union node *, int);
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00008158static void expredir(union node *);
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008159static void evalpipe(union node *, int);
8160static void evalcommand(union node *, int);
Eric Andersenc470f442003-07-28 09:56:35 +00008161static int evalbltin(const struct builtincmd *, int, char **);
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008162static void prehash(union node *);
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00008163
Eric Andersen62483552001-07-10 06:09:16 +00008164/*
Eric Andersenc470f442003-07-28 09:56:35 +00008165 * Evaluate a parse tree. The value is left in the global variable
8166 * exitstatus.
Eric Andersen62483552001-07-10 06:09:16 +00008167 */
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008168static void
Eric Andersenc470f442003-07-28 09:56:35 +00008169evaltree(union node *n, int flags)
Eric Andersen62483552001-07-10 06:09:16 +00008170{
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008171 struct jmploc *volatile savehandler = exception_handler;
8172 struct jmploc jmploc;
Eric Andersenc470f442003-07-28 09:56:35 +00008173 int checkexit = 0;
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008174 void (*evalfn)(union node *, int);
Eric Andersenc470f442003-07-28 09:56:35 +00008175 int status;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008176 int int_level;
8177
8178 SAVE_INT(int_level);
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008179
Eric Andersenc470f442003-07-28 09:56:35 +00008180 if (n == NULL) {
8181 TRACE(("evaltree(NULL) called\n"));
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008182 goto out1;
Eric Andersen62483552001-07-10 06:09:16 +00008183 }
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008184 TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008185
8186 exception_handler = &jmploc;
8187 {
8188 int err = setjmp(jmploc.loc);
8189 if (err) {
8190 /* if it was a signal, check for trap handlers */
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008191 if (exception_type == EXSIG) {
Denis Vlasenkob21f3792009-03-19 23:09:58 +00008192 TRACE(("exception %d (EXSIG) in evaltree, err=%d\n",
8193 exception_type, err));
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008194 goto out;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008195 }
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008196 /* continue on the way out */
Denis Vlasenkob21f3792009-03-19 23:09:58 +00008197 TRACE(("exception %d in evaltree, propagating err=%d\n",
8198 exception_type, err));
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008199 exception_handler = savehandler;
8200 longjmp(exception_handler->loc, err);
8201 }
8202 }
8203
Eric Andersenc470f442003-07-28 09:56:35 +00008204 switch (n->type) {
8205 default:
Denis Vlasenkoa7189f02006-11-17 20:29:00 +00008206#if DEBUG
Eric Andersenc470f442003-07-28 09:56:35 +00008207 out1fmt("Node type = %d\n", n->type);
Denys Vlasenko8131eea2009-11-02 14:19:51 +01008208 fflush_all();
Eric Andersenc470f442003-07-28 09:56:35 +00008209 break;
8210#endif
8211 case NNOT:
8212 evaltree(n->nnot.com, EV_TESTED);
8213 status = !exitstatus;
8214 goto setstatus;
8215 case NREDIR:
8216 expredir(n->nredir.redirect);
8217 status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
8218 if (!status) {
8219 evaltree(n->nredir.n, flags & EV_TESTED);
8220 status = exitstatus;
8221 }
Denis Vlasenko34c73c42008-08-16 11:48:02 +00008222 popredir(/*drop:*/ 0, /*restore:*/ 0 /* not sure */);
Eric Andersenc470f442003-07-28 09:56:35 +00008223 goto setstatus;
8224 case NCMD:
8225 evalfn = evalcommand;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008226 checkexit:
Eric Andersenc470f442003-07-28 09:56:35 +00008227 if (eflag && !(flags & EV_TESTED))
8228 checkexit = ~0;
8229 goto calleval;
8230 case NFOR:
8231 evalfn = evalfor;
8232 goto calleval;
8233 case NWHILE:
8234 case NUNTIL:
8235 evalfn = evalloop;
8236 goto calleval;
8237 case NSUBSHELL:
8238 case NBACKGND:
8239 evalfn = evalsubshell;
8240 goto calleval;
8241 case NPIPE:
8242 evalfn = evalpipe;
8243 goto checkexit;
8244 case NCASE:
8245 evalfn = evalcase;
8246 goto calleval;
8247 case NAND:
8248 case NOR:
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008249 case NSEMI: {
8250
Eric Andersenc470f442003-07-28 09:56:35 +00008251#if NAND + 1 != NOR
8252#error NAND + 1 != NOR
8253#endif
8254#if NOR + 1 != NSEMI
8255#error NOR + 1 != NSEMI
8256#endif
Denis Vlasenko87d5fd92008-07-26 13:48:35 +00008257 unsigned is_or = n->type - NAND;
Eric Andersenc470f442003-07-28 09:56:35 +00008258 evaltree(
8259 n->nbinary.ch1,
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008260 (flags | ((is_or >> 1) - 1)) & EV_TESTED
Eric Andersenc470f442003-07-28 09:56:35 +00008261 );
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008262 if (!exitstatus == is_or)
Eric Andersenc470f442003-07-28 09:56:35 +00008263 break;
8264 if (!evalskip) {
8265 n = n->nbinary.ch2;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008266 evaln:
Eric Andersenc470f442003-07-28 09:56:35 +00008267 evalfn = evaltree;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008268 calleval:
Eric Andersenc470f442003-07-28 09:56:35 +00008269 evalfn(n, flags);
8270 break;
8271 }
8272 break;
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008273 }
Eric Andersenc470f442003-07-28 09:56:35 +00008274 case NIF:
8275 evaltree(n->nif.test, EV_TESTED);
8276 if (evalskip)
8277 break;
8278 if (exitstatus == 0) {
8279 n = n->nif.ifpart;
8280 goto evaln;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008281 }
8282 if (n->nif.elsepart) {
Eric Andersenc470f442003-07-28 09:56:35 +00008283 n = n->nif.elsepart;
8284 goto evaln;
8285 }
8286 goto success;
8287 case NDEFUN:
8288 defun(n->narg.text, n->narg.next);
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008289 success:
Eric Andersenc470f442003-07-28 09:56:35 +00008290 status = 0;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008291 setstatus:
Eric Andersenc470f442003-07-28 09:56:35 +00008292 exitstatus = status;
8293 break;
8294 }
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008295
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008296 out:
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008297 exception_handler = savehandler;
8298 out1:
8299 if (checkexit & exitstatus)
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00008300 evalskip |= SKIPEVAL;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02008301 else if (pending_sig && dotrap())
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00008302 goto exexit;
8303
8304 if (flags & EV_EXIT) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008305 exexit:
Denis Vlasenkob012b102007-02-19 22:43:01 +00008306 raise_exception(EXEXIT);
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00008307 }
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008308
8309 RESTORE_INT(int_level);
8310 TRACE(("leaving evaltree (no interrupts)\n"));
Eric Andersen62483552001-07-10 06:09:16 +00008311}
8312
Eric Andersenc470f442003-07-28 09:56:35 +00008313#if !defined(__alpha__) || (defined(__GNUC__) && __GNUC__ >= 3)
8314static
8315#endif
8316void evaltreenr(union node *, int) __attribute__ ((alias("evaltree"),__noreturn__));
8317
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008318static void
Eric Andersenc470f442003-07-28 09:56:35 +00008319evalloop(union node *n, int flags)
Eric Andersencb57d552001-06-28 07:25:16 +00008320{
8321 int status;
8322
8323 loopnest++;
8324 status = 0;
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008325 flags &= EV_TESTED;
Eric Andersencb57d552001-06-28 07:25:16 +00008326 for (;;) {
Eric Andersenc470f442003-07-28 09:56:35 +00008327 int i;
8328
Eric Andersencb57d552001-06-28 07:25:16 +00008329 evaltree(n->nbinary.ch1, EV_TESTED);
8330 if (evalskip) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008331 skipping:
8332 if (evalskip == SKIPCONT && --skipcount <= 0) {
Eric Andersencb57d552001-06-28 07:25:16 +00008333 evalskip = 0;
8334 continue;
8335 }
8336 if (evalskip == SKIPBREAK && --skipcount <= 0)
8337 evalskip = 0;
8338 break;
8339 }
Eric Andersenc470f442003-07-28 09:56:35 +00008340 i = exitstatus;
8341 if (n->type != NWHILE)
8342 i = !i;
8343 if (i != 0)
8344 break;
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008345 evaltree(n->nbinary.ch2, flags);
Eric Andersencb57d552001-06-28 07:25:16 +00008346 status = exitstatus;
8347 if (evalskip)
8348 goto skipping;
8349 }
8350 loopnest--;
8351 exitstatus = status;
8352}
8353
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008354static void
Eric Andersenc470f442003-07-28 09:56:35 +00008355evalfor(union node *n, int flags)
Eric Andersencb57d552001-06-28 07:25:16 +00008356{
8357 struct arglist arglist;
8358 union node *argp;
8359 struct strlist *sp;
8360 struct stackmark smark;
8361
8362 setstackmark(&smark);
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00008363 arglist.list = NULL;
Eric Andersencb57d552001-06-28 07:25:16 +00008364 arglist.lastp = &arglist.list;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008365 for (argp = n->nfor.args; argp; argp = argp->narg.next) {
Eric Andersencb57d552001-06-28 07:25:16 +00008366 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE | EXP_RECORD);
Eric Andersenc470f442003-07-28 09:56:35 +00008367 /* XXX */
Eric Andersencb57d552001-06-28 07:25:16 +00008368 if (evalskip)
8369 goto out;
8370 }
8371 *arglist.lastp = NULL;
8372
8373 exitstatus = 0;
8374 loopnest++;
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008375 flags &= EV_TESTED;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008376 for (sp = arglist.list; sp; sp = sp->next) {
Eric Andersencb57d552001-06-28 07:25:16 +00008377 setvar(n->nfor.var, sp->text, 0);
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008378 evaltree(n->nfor.body, flags);
Eric Andersencb57d552001-06-28 07:25:16 +00008379 if (evalskip) {
8380 if (evalskip == SKIPCONT && --skipcount <= 0) {
8381 evalskip = 0;
8382 continue;
8383 }
8384 if (evalskip == SKIPBREAK && --skipcount <= 0)
8385 evalskip = 0;
8386 break;
8387 }
8388 }
8389 loopnest--;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008390 out:
Eric Andersencb57d552001-06-28 07:25:16 +00008391 popstackmark(&smark);
8392}
8393
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008394static void
Eric Andersenc470f442003-07-28 09:56:35 +00008395evalcase(union node *n, int flags)
Eric Andersencb57d552001-06-28 07:25:16 +00008396{
8397 union node *cp;
8398 union node *patp;
8399 struct arglist arglist;
8400 struct stackmark smark;
8401
8402 setstackmark(&smark);
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00008403 arglist.list = NULL;
Eric Andersencb57d552001-06-28 07:25:16 +00008404 arglist.lastp = &arglist.list;
Eric Andersencb57d552001-06-28 07:25:16 +00008405 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
Eric Andersenc470f442003-07-28 09:56:35 +00008406 exitstatus = 0;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008407 for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
8408 for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
Eric Andersencb57d552001-06-28 07:25:16 +00008409 if (casematch(patp, arglist.list->text)) {
8410 if (evalskip == 0) {
8411 evaltree(cp->nclist.body, flags);
8412 }
8413 goto out;
8414 }
8415 }
8416 }
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008417 out:
Eric Andersencb57d552001-06-28 07:25:16 +00008418 popstackmark(&smark);
8419}
8420
Eric Andersenc470f442003-07-28 09:56:35 +00008421/*
8422 * Kick off a subshell to evaluate a tree.
8423 */
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008424static void
Eric Andersenc470f442003-07-28 09:56:35 +00008425evalsubshell(union node *n, int flags)
8426{
8427 struct job *jp;
8428 int backgnd = (n->type == NBACKGND);
8429 int status;
8430
8431 expredir(n->nredir.redirect);
Denys Vlasenko238bf182010-05-18 15:49:07 +02008432 if (!backgnd && (flags & EV_EXIT) && !may_have_traps)
Eric Andersenc470f442003-07-28 09:56:35 +00008433 goto nofork;
Denis Vlasenkob012b102007-02-19 22:43:01 +00008434 INT_OFF;
Denis Vlasenko68404f12008-03-17 09:00:54 +00008435 jp = makejob(/*n,*/ 1);
Eric Andersenc470f442003-07-28 09:56:35 +00008436 if (forkshell(jp, n, backgnd) == 0) {
Denys Vlasenko238bf182010-05-18 15:49:07 +02008437 /* child */
Denis Vlasenkob012b102007-02-19 22:43:01 +00008438 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00008439 flags |= EV_EXIT;
8440 if (backgnd)
Denys Vlasenko238bf182010-05-18 15:49:07 +02008441 flags &= ~EV_TESTED;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00008442 nofork:
Eric Andersenc470f442003-07-28 09:56:35 +00008443 redirect(n->nredir.redirect, 0);
8444 evaltreenr(n->nredir.n, flags);
8445 /* never returns */
8446 }
8447 status = 0;
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00008448 if (!backgnd)
Eric Andersenc470f442003-07-28 09:56:35 +00008449 status = waitforjob(jp);
8450 exitstatus = status;
Denis Vlasenkob012b102007-02-19 22:43:01 +00008451 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00008452}
8453
Eric Andersenc470f442003-07-28 09:56:35 +00008454/*
8455 * Compute the names of the files in a redirection list.
8456 */
Denis Vlasenko99eb8502007-02-23 21:09:49 +00008457static void fixredir(union node *, const char *, int);
Eric Andersenc470f442003-07-28 09:56:35 +00008458static void
8459expredir(union node *n)
8460{
8461 union node *redir;
8462
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008463 for (redir = n; redir; redir = redir->nfile.next) {
Eric Andersenc470f442003-07-28 09:56:35 +00008464 struct arglist fn;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008465
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00008466 fn.list = NULL;
Eric Andersenc470f442003-07-28 09:56:35 +00008467 fn.lastp = &fn.list;
8468 switch (redir->type) {
8469 case NFROMTO:
8470 case NFROM:
8471 case NTO:
Denis Vlasenko559691a2008-10-05 18:39:31 +00008472#if ENABLE_ASH_BASH_COMPAT
8473 case NTO2:
8474#endif
Eric Andersenc470f442003-07-28 09:56:35 +00008475 case NCLOBBER:
8476 case NAPPEND:
8477 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
Denis Vlasenko559691a2008-10-05 18:39:31 +00008478#if ENABLE_ASH_BASH_COMPAT
8479 store_expfname:
8480#endif
Eric Andersenc470f442003-07-28 09:56:35 +00008481 redir->nfile.expfname = fn.list->text;
8482 break;
8483 case NFROMFD:
Denis Vlasenko559691a2008-10-05 18:39:31 +00008484 case NTOFD: /* >& */
Eric Andersenc470f442003-07-28 09:56:35 +00008485 if (redir->ndup.vname) {
8486 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008487 if (fn.list == NULL)
Denis Vlasenkob012b102007-02-19 22:43:01 +00008488 ash_msg_and_raise_error("redir error");
Denis Vlasenko559691a2008-10-05 18:39:31 +00008489#if ENABLE_ASH_BASH_COMPAT
8490//FIXME: we used expandarg with different args!
8491 if (!isdigit_str9(fn.list->text)) {
8492 /* >&file, not >&fd */
8493 if (redir->nfile.fd != 1) /* 123>&file - BAD */
8494 ash_msg_and_raise_error("redir error");
8495 redir->type = NTO2;
8496 goto store_expfname;
8497 }
8498#endif
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008499 fixredir(redir, fn.list->text, 1);
Eric Andersenc470f442003-07-28 09:56:35 +00008500 }
8501 break;
8502 }
8503 }
8504}
8505
Eric Andersencb57d552001-06-28 07:25:16 +00008506/*
Eric Andersencb57d552001-06-28 07:25:16 +00008507 * Evaluate a pipeline. All the processes in the pipeline are children
8508 * of the process creating the pipeline. (This differs from some versions
8509 * of the shell, which make the last process in a pipeline the parent
8510 * of all the rest.)
8511 */
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008512static void
Eric Andersenc470f442003-07-28 09:56:35 +00008513evalpipe(union node *n, int flags)
Eric Andersencb57d552001-06-28 07:25:16 +00008514{
8515 struct job *jp;
8516 struct nodelist *lp;
8517 int pipelen;
8518 int prevfd;
8519 int pip[2];
8520
Eric Andersenc470f442003-07-28 09:56:35 +00008521 TRACE(("evalpipe(0x%lx) called\n", (long)n));
Eric Andersencb57d552001-06-28 07:25:16 +00008522 pipelen = 0;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008523 for (lp = n->npipe.cmdlist; lp; lp = lp->next)
Eric Andersencb57d552001-06-28 07:25:16 +00008524 pipelen++;
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008525 flags |= EV_EXIT;
Denis Vlasenkob012b102007-02-19 22:43:01 +00008526 INT_OFF;
Denis Vlasenko68404f12008-03-17 09:00:54 +00008527 jp = makejob(/*n,*/ pipelen);
Eric Andersencb57d552001-06-28 07:25:16 +00008528 prevfd = -1;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008529 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008530 prehash(lp->n);
Eric Andersencb57d552001-06-28 07:25:16 +00008531 pip[1] = -1;
8532 if (lp->next) {
8533 if (pipe(pip) < 0) {
8534 close(prevfd);
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00008535 ash_msg_and_raise_error("pipe call failed");
Eric Andersencb57d552001-06-28 07:25:16 +00008536 }
8537 }
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00008538 if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
Denis Vlasenkob012b102007-02-19 22:43:01 +00008539 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00008540 if (pip[1] >= 0) {
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008541 close(pip[0]);
Eric Andersencb57d552001-06-28 07:25:16 +00008542 }
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008543 if (prevfd > 0) {
8544 dup2(prevfd, 0);
8545 close(prevfd);
8546 }
8547 if (pip[1] > 1) {
8548 dup2(pip[1], 1);
8549 close(pip[1]);
8550 }
Eric Andersenc470f442003-07-28 09:56:35 +00008551 evaltreenr(lp->n, flags);
8552 /* never returns */
Eric Andersencb57d552001-06-28 07:25:16 +00008553 }
8554 if (prevfd >= 0)
8555 close(prevfd);
8556 prevfd = pip[0];
Denis Vlasenkob9e70dd2009-03-20 01:24:08 +00008557 /* Don't want to trigger debugging */
8558 if (pip[1] != -1)
8559 close(pip[1]);
Eric Andersencb57d552001-06-28 07:25:16 +00008560 }
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00008561 if (n->npipe.pipe_backgnd == 0) {
Eric Andersencb57d552001-06-28 07:25:16 +00008562 exitstatus = waitforjob(jp);
8563 TRACE(("evalpipe: job done exit status %d\n", exitstatus));
Eric Andersencb57d552001-06-28 07:25:16 +00008564 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00008565 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00008566}
8567
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008568/*
8569 * Controls whether the shell is interactive or not.
8570 */
8571static void
8572setinteractive(int on)
8573{
Denis Vlasenkob07a4962008-06-22 13:16:23 +00008574 static smallint is_interactive;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008575
8576 if (++on == is_interactive)
8577 return;
8578 is_interactive = on;
8579 setsignal(SIGINT);
8580 setsignal(SIGQUIT);
8581 setsignal(SIGTERM);
8582#if !ENABLE_FEATURE_SH_EXTRA_QUIET
8583 if (is_interactive > 1) {
8584 /* Looks like they want an interactive shell */
Denis Vlasenkoca525b42007-06-13 12:27:17 +00008585 static smallint did_banner;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008586
Denis Vlasenkoca525b42007-06-13 12:27:17 +00008587 if (!did_banner) {
Denys Vlasenkoc34c0332009-09-29 12:25:30 +02008588 /* note: ash and hush share this string */
8589 out1fmt("\n\n%s %s\n"
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008590 "Enter 'help' for a list of built-in commands."
8591 "\n\n",
Denys Vlasenkoc34c0332009-09-29 12:25:30 +02008592 bb_banner,
8593 "built-in shell (ash)"
8594 );
Denis Vlasenkoca525b42007-06-13 12:27:17 +00008595 did_banner = 1;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008596 }
8597 }
8598#endif
8599}
8600
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008601static void
8602optschanged(void)
8603{
8604#if DEBUG
8605 opentrace();
8606#endif
8607 setinteractive(iflag);
8608 setjobctl(mflag);
Denis Vlasenkob07a4962008-06-22 13:16:23 +00008609#if ENABLE_FEATURE_EDITING_VI
8610 if (viflag)
8611 line_input_state->flags |= VI_MODE;
8612 else
8613 line_input_state->flags &= ~VI_MODE;
8614#else
8615 viflag = 0; /* forcibly keep the option off */
8616#endif
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008617}
8618
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008619static struct localvar *localvars;
8620
8621/*
8622 * Called after a function returns.
8623 * Interrupts must be off.
8624 */
8625static void
8626poplocalvars(void)
8627{
8628 struct localvar *lvp;
8629 struct var *vp;
8630
8631 while ((lvp = localvars) != NULL) {
8632 localvars = lvp->next;
8633 vp = lvp->vp;
Denys Vlasenko883cea42009-07-11 15:31:59 +02008634 TRACE(("poplocalvar %s\n", vp ? vp->text : "-"));
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008635 if (vp == NULL) { /* $- saved */
8636 memcpy(optlist, lvp->text, sizeof(optlist));
8637 free((char*)lvp->text);
8638 optschanged();
8639 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02008640 unsetvar(vp->var_text);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008641 } else {
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02008642 if (vp->var_func)
8643 vp->var_func(var_end(lvp->text));
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008644 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02008645 free((char*)vp->var_text);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008646 vp->flags = lvp->flags;
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02008647 vp->var_text = lvp->text;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008648 }
8649 free(lvp);
8650 }
8651}
8652
8653static int
8654evalfun(struct funcnode *func, int argc, char **argv, int flags)
8655{
8656 volatile struct shparam saveparam;
8657 struct localvar *volatile savelocalvars;
8658 struct jmploc *volatile savehandler;
8659 struct jmploc jmploc;
8660 int e;
8661
8662 saveparam = shellparam;
8663 savelocalvars = localvars;
8664 e = setjmp(jmploc.loc);
8665 if (e) {
8666 goto funcdone;
8667 }
8668 INT_OFF;
8669 savehandler = exception_handler;
8670 exception_handler = &jmploc;
8671 localvars = NULL;
Denis Vlasenko01631112007-12-16 17:20:38 +00008672 shellparam.malloced = 0;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008673 func->count++;
8674 funcnest++;
8675 INT_ON;
8676 shellparam.nparam = argc - 1;
8677 shellparam.p = argv + 1;
8678#if ENABLE_ASH_GETOPTS
8679 shellparam.optind = 1;
8680 shellparam.optoff = -1;
8681#endif
8682 evaltree(&func->n, flags & EV_TESTED);
Denis Vlasenko01631112007-12-16 17:20:38 +00008683 funcdone:
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008684 INT_OFF;
8685 funcnest--;
8686 freefunc(func);
8687 poplocalvars();
8688 localvars = savelocalvars;
8689 freeparam(&shellparam);
8690 shellparam = saveparam;
8691 exception_handler = savehandler;
8692 INT_ON;
8693 evalskip &= ~SKIPFUNC;
8694 return e;
8695}
8696
Denis Vlasenko131ae172007-02-18 13:00:19 +00008697#if ENABLE_ASH_CMDCMD
Denis Vlasenkoaa744452007-02-23 01:04:22 +00008698static char **
8699parse_command_args(char **argv, const char **path)
Eric Andersenc470f442003-07-28 09:56:35 +00008700{
8701 char *cp, c;
8702
8703 for (;;) {
8704 cp = *++argv;
8705 if (!cp)
8706 return 0;
8707 if (*cp++ != '-')
8708 break;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008709 c = *cp++;
8710 if (!c)
Eric Andersenc470f442003-07-28 09:56:35 +00008711 break;
8712 if (c == '-' && !*cp) {
8713 argv++;
8714 break;
8715 }
8716 do {
8717 switch (c) {
8718 case 'p':
Denis Vlasenkof5f75c52007-06-12 22:35:19 +00008719 *path = bb_default_path;
Eric Andersenc470f442003-07-28 09:56:35 +00008720 break;
8721 default:
8722 /* run 'typecmd' for other options */
8723 return 0;
8724 }
Denis Vlasenko9650f362007-02-23 01:04:37 +00008725 c = *cp++;
8726 } while (c);
Eric Andersenc470f442003-07-28 09:56:35 +00008727 }
8728 return argv;
8729}
8730#endif
8731
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008732/*
8733 * Make a variable a local variable. When a variable is made local, it's
8734 * value and flags are saved in a localvar structure. The saved values
8735 * will be restored when the shell function returns. We handle the name
8736 * "-" as a special case.
8737 */
8738static void
8739mklocal(char *name)
8740{
8741 struct localvar *lvp;
8742 struct var **vpp;
8743 struct var *vp;
8744
8745 INT_OFF;
Denis Vlasenko838ffd52008-02-21 04:32:08 +00008746 lvp = ckzalloc(sizeof(struct localvar));
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008747 if (LONE_DASH(name)) {
8748 char *p;
8749 p = ckmalloc(sizeof(optlist));
8750 lvp->text = memcpy(p, optlist, sizeof(optlist));
8751 vp = NULL;
8752 } else {
8753 char *eq;
8754
8755 vpp = hashvar(name);
8756 vp = *findvar(vpp, name);
8757 eq = strchr(name, '=');
8758 if (vp == NULL) {
8759 if (eq)
8760 setvareq(name, VSTRFIXED);
8761 else
8762 setvar(name, NULL, VSTRFIXED);
8763 vp = *vpp; /* the new variable */
8764 lvp->flags = VUNSET;
8765 } else {
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02008766 lvp->text = vp->var_text;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008767 lvp->flags = vp->flags;
8768 vp->flags |= VSTRFIXED|VTEXTFIXED;
8769 if (eq)
8770 setvareq(name, 0);
8771 }
8772 }
8773 lvp->vp = vp;
8774 lvp->next = localvars;
8775 localvars = lvp;
8776 INT_ON;
8777}
8778
8779/*
8780 * The "local" command.
8781 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008782static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008783localcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008784{
8785 char *name;
8786
8787 argv = argptr;
8788 while ((name = *argv++) != NULL) {
8789 mklocal(name);
8790 }
8791 return 0;
8792}
8793
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008794static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008795falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008796{
8797 return 1;
8798}
8799
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008800static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008801truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008802{
8803 return 0;
8804}
8805
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008806static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008807execcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008808{
Denis Vlasenko68404f12008-03-17 09:00:54 +00008809 if (argv[1]) {
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008810 iflag = 0; /* exit on error */
8811 mflag = 0;
8812 optschanged();
8813 shellexec(argv + 1, pathval(), 0);
8814 }
8815 return 0;
8816}
8817
8818/*
8819 * The return command.
8820 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008821static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008822returncmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008823{
8824 /*
8825 * If called outside a function, do what ksh does;
8826 * skip the rest of the file.
8827 */
8828 evalskip = funcnest ? SKIPFUNC : SKIPFILE;
8829 return argv[1] ? number(argv[1]) : exitstatus;
8830}
8831
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008832/* Forward declarations for builtintab[] */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008833static int breakcmd(int, char **) FAST_FUNC;
8834static int dotcmd(int, char **) FAST_FUNC;
8835static int evalcmd(int, char **) FAST_FUNC;
8836static int exitcmd(int, char **) FAST_FUNC;
8837static int exportcmd(int, char **) FAST_FUNC;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008838#if ENABLE_ASH_GETOPTS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008839static int getoptscmd(int, char **) FAST_FUNC;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008840#endif
Denis Vlasenko52764022007-02-24 13:42:56 +00008841#if !ENABLE_FEATURE_SH_EXTRA_QUIET
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008842static int helpcmd(int, char **) FAST_FUNC;
Denis Vlasenko52764022007-02-24 13:42:56 +00008843#endif
Mike Frysinger98c52642009-04-02 10:02:37 +00008844#if ENABLE_SH_MATH_SUPPORT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008845static int letcmd(int, char **) FAST_FUNC;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008846#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008847static int readcmd(int, char **) FAST_FUNC;
8848static int setcmd(int, char **) FAST_FUNC;
8849static int shiftcmd(int, char **) FAST_FUNC;
8850static int timescmd(int, char **) FAST_FUNC;
8851static int trapcmd(int, char **) FAST_FUNC;
8852static int umaskcmd(int, char **) FAST_FUNC;
8853static int unsetcmd(int, char **) FAST_FUNC;
8854static int ulimitcmd(int, char **) FAST_FUNC;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008855
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008856#define BUILTIN_NOSPEC "0"
8857#define BUILTIN_SPECIAL "1"
8858#define BUILTIN_REGULAR "2"
8859#define BUILTIN_SPEC_REG "3"
8860#define BUILTIN_ASSIGN "4"
8861#define BUILTIN_SPEC_ASSG "5"
8862#define BUILTIN_REG_ASSG "6"
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008863#define BUILTIN_SPEC_REG_ASSG "7"
8864
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008865/* Stubs for calling non-FAST_FUNC's */
Denys Vlasenko2634bf32009-06-09 18:40:07 +02008866#if ENABLE_ASH_BUILTIN_ECHO
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008867static int FAST_FUNC echocmd(int argc, char **argv) { return echo_main(argc, argv); }
Denys Vlasenko2634bf32009-06-09 18:40:07 +02008868#endif
8869#if ENABLE_ASH_BUILTIN_PRINTF
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008870static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
Denys Vlasenko2634bf32009-06-09 18:40:07 +02008871#endif
8872#if ENABLE_ASH_BUILTIN_TEST
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008873static int FAST_FUNC testcmd(int argc, char **argv) { return test_main(argc, argv); }
Denys Vlasenko2634bf32009-06-09 18:40:07 +02008874#endif
Denis Vlasenko468aea22008-04-01 14:47:57 +00008875
Denis Vlasenkof7d56652008-03-25 05:51:41 +00008876/* Keep these in proper order since it is searched via bsearch() */
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008877static const struct builtincmd builtintab[] = {
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008878 { BUILTIN_SPEC_REG "." , dotcmd },
8879 { BUILTIN_SPEC_REG ":" , truecmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008880#if ENABLE_ASH_BUILTIN_TEST
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008881 { BUILTIN_REGULAR "[" , testcmd },
Denis Vlasenko80591b02008-03-25 07:49:43 +00008882#if ENABLE_ASH_BASH_COMPAT
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008883 { BUILTIN_REGULAR "[[" , testcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008884#endif
Denis Vlasenko80591b02008-03-25 07:49:43 +00008885#endif
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008886#if ENABLE_ASH_ALIAS
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008887 { BUILTIN_REG_ASSG "alias" , aliascmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008888#endif
8889#if JOBS
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008890 { BUILTIN_REGULAR "bg" , fg_bgcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008891#endif
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008892 { BUILTIN_SPEC_REG "break" , breakcmd },
8893 { BUILTIN_REGULAR "cd" , cdcmd },
8894 { BUILTIN_NOSPEC "chdir" , cdcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008895#if ENABLE_ASH_CMDCMD
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008896 { BUILTIN_REGULAR "command" , commandcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008897#endif
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008898 { BUILTIN_SPEC_REG "continue", breakcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008899#if ENABLE_ASH_BUILTIN_ECHO
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008900 { BUILTIN_REGULAR "echo" , echocmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008901#endif
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008902 { BUILTIN_SPEC_REG "eval" , evalcmd },
8903 { BUILTIN_SPEC_REG "exec" , execcmd },
8904 { BUILTIN_SPEC_REG "exit" , exitcmd },
8905 { BUILTIN_SPEC_REG_ASSG "export" , exportcmd },
8906 { BUILTIN_REGULAR "false" , falsecmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008907#if JOBS
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008908 { BUILTIN_REGULAR "fg" , fg_bgcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008909#endif
8910#if ENABLE_ASH_GETOPTS
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008911 { BUILTIN_REGULAR "getopts" , getoptscmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008912#endif
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008913 { BUILTIN_NOSPEC "hash" , hashcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008914#if !ENABLE_FEATURE_SH_EXTRA_QUIET
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008915 { BUILTIN_NOSPEC "help" , helpcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008916#endif
8917#if JOBS
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008918 { BUILTIN_REGULAR "jobs" , jobscmd },
8919 { BUILTIN_REGULAR "kill" , killcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008920#endif
Mike Frysinger98c52642009-04-02 10:02:37 +00008921#if ENABLE_SH_MATH_SUPPORT
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008922 { BUILTIN_NOSPEC "let" , letcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008923#endif
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008924 { BUILTIN_ASSIGN "local" , localcmd },
Denis Vlasenkocd2663f2008-06-01 22:36:39 +00008925#if ENABLE_ASH_BUILTIN_PRINTF
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008926 { BUILTIN_REGULAR "printf" , printfcmd },
Denis Vlasenkocd2663f2008-06-01 22:36:39 +00008927#endif
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008928 { BUILTIN_NOSPEC "pwd" , pwdcmd },
8929 { BUILTIN_REGULAR "read" , readcmd },
8930 { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
8931 { BUILTIN_SPEC_REG "return" , returncmd },
8932 { BUILTIN_SPEC_REG "set" , setcmd },
8933 { BUILTIN_SPEC_REG "shift" , shiftcmd },
Denys Vlasenko82731b42010-05-17 17:49:52 +02008934#if ENABLE_ASH_BASH_COMPAT
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008935 { BUILTIN_SPEC_REG "source" , dotcmd },
Denys Vlasenko82731b42010-05-17 17:49:52 +02008936#endif
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008937#if ENABLE_ASH_BUILTIN_TEST
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008938 { BUILTIN_REGULAR "test" , testcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008939#endif
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008940 { BUILTIN_SPEC_REG "times" , timescmd },
8941 { BUILTIN_SPEC_REG "trap" , trapcmd },
8942 { BUILTIN_REGULAR "true" , truecmd },
8943 { BUILTIN_NOSPEC "type" , typecmd },
8944 { BUILTIN_NOSPEC "ulimit" , ulimitcmd },
8945 { BUILTIN_REGULAR "umask" , umaskcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008946#if ENABLE_ASH_ALIAS
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008947 { BUILTIN_REGULAR "unalias" , unaliascmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008948#endif
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008949 { BUILTIN_SPEC_REG "unset" , unsetcmd },
8950 { BUILTIN_REGULAR "wait" , waitcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008951};
8952
Denis Vlasenko80591b02008-03-25 07:49:43 +00008953/* Should match the above table! */
8954#define COMMANDCMD (builtintab + \
8955 2 + \
8956 1 * ENABLE_ASH_BUILTIN_TEST + \
8957 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
8958 1 * ENABLE_ASH_ALIAS + \
8959 1 * ENABLE_ASH_JOB_CONTROL + \
8960 3)
8961#define EXECCMD (builtintab + \
8962 2 + \
8963 1 * ENABLE_ASH_BUILTIN_TEST + \
8964 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
8965 1 * ENABLE_ASH_ALIAS + \
8966 1 * ENABLE_ASH_JOB_CONTROL + \
8967 3 + \
8968 1 * ENABLE_ASH_CMDCMD + \
8969 1 + \
8970 ENABLE_ASH_BUILTIN_ECHO + \
8971 1)
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008972
8973/*
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008974 * Search the table of builtin commands.
8975 */
8976static struct builtincmd *
8977find_builtin(const char *name)
8978{
8979 struct builtincmd *bp;
8980
8981 bp = bsearch(
Denis Vlasenko80b8b392007-06-25 10:55:35 +00008982 name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008983 pstrcmp
8984 );
8985 return bp;
8986}
8987
8988/*
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008989 * Execute a simple command.
8990 */
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008991static int
8992isassignment(const char *p)
Paul Foxc3850c82005-07-20 18:23:39 +00008993{
8994 const char *q = endofname(p);
8995 if (p == q)
8996 return 0;
8997 return *q == '=';
8998}
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008999static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00009000bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00009001{
9002 /* Preserve exitstatus of a previous possible redirection
9003 * as POSIX mandates */
9004 return back_exitstatus;
9005}
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02009006static void
Eric Andersenc470f442003-07-28 09:56:35 +00009007evalcommand(union node *cmd, int flags)
9008{
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00009009 static const struct builtincmd null_bltin = {
9010 "\0\0", bltincmd /* why three NULs? */
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00009011 };
Eric Andersenc470f442003-07-28 09:56:35 +00009012 struct stackmark smark;
9013 union node *argp;
9014 struct arglist arglist;
9015 struct arglist varlist;
9016 char **argv;
9017 int argc;
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009018 const struct strlist *sp;
Eric Andersenc470f442003-07-28 09:56:35 +00009019 struct cmdentry cmdentry;
9020 struct job *jp;
9021 char *lastarg;
9022 const char *path;
9023 int spclbltin;
Eric Andersenc470f442003-07-28 09:56:35 +00009024 int status;
9025 char **nargv;
Paul Foxc3850c82005-07-20 18:23:39 +00009026 struct builtincmd *bcmd;
Denis Vlasenko34c73c42008-08-16 11:48:02 +00009027 smallint cmd_is_exec;
9028 smallint pseudovarflag = 0;
Eric Andersenc470f442003-07-28 09:56:35 +00009029
9030 /* First expand the arguments. */
9031 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
9032 setstackmark(&smark);
9033 back_exitstatus = 0;
9034
9035 cmdentry.cmdtype = CMDBUILTIN;
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00009036 cmdentry.u.cmd = &null_bltin;
Eric Andersenc470f442003-07-28 09:56:35 +00009037 varlist.lastp = &varlist.list;
9038 *varlist.lastp = NULL;
9039 arglist.lastp = &arglist.list;
9040 *arglist.lastp = NULL;
9041
9042 argc = 0;
Denis Vlasenkob012b102007-02-19 22:43:01 +00009043 if (cmd->ncmd.args) {
Paul Foxc3850c82005-07-20 18:23:39 +00009044 bcmd = find_builtin(cmd->ncmd.args->narg.text);
9045 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
9046 }
9047
Eric Andersenc470f442003-07-28 09:56:35 +00009048 for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
9049 struct strlist **spp;
9050
9051 spp = arglist.lastp;
"Vladimir N. Oleynik"bef14d72005-09-05 13:25:11 +00009052 if (pseudovarflag && isassignment(argp->narg.text))
Paul Foxc3850c82005-07-20 18:23:39 +00009053 expandarg(argp, &arglist, EXP_VARTILDE);
9054 else
9055 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
9056
Eric Andersenc470f442003-07-28 09:56:35 +00009057 for (sp = *spp; sp; sp = sp->next)
9058 argc++;
9059 }
9060
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +00009061 argv = nargv = stalloc(sizeof(char *) * (argc + 1));
Denis Vlasenko2da584f2007-02-19 22:44:05 +00009062 for (sp = arglist.list; sp; sp = sp->next) {
Eric Andersenc470f442003-07-28 09:56:35 +00009063 TRACE(("evalcommand arg: %s\n", sp->text));
9064 *nargv++ = sp->text;
9065 }
9066 *nargv = NULL;
9067
9068 lastarg = NULL;
9069 if (iflag && funcnest == 0 && argc > 0)
9070 lastarg = nargv[-1];
9071
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009072 preverrout_fd = 2;
Eric Andersenc470f442003-07-28 09:56:35 +00009073 expredir(cmd->ncmd.redirect);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009074 status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
Eric Andersenc470f442003-07-28 09:56:35 +00009075
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02009076 path = vpath.var_text;
Eric Andersenc470f442003-07-28 09:56:35 +00009077 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
9078 struct strlist **spp;
9079 char *p;
9080
9081 spp = varlist.lastp;
9082 expandarg(argp, &varlist, EXP_VARTILDE);
9083
9084 /*
9085 * Modify the command lookup path, if a PATH= assignment
9086 * is present
9087 */
9088 p = (*spp)->text;
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02009089 if (varcmp(p, path) == 0)
Eric Andersenc470f442003-07-28 09:56:35 +00009090 path = p;
9091 }
9092
9093 /* Print the command if xflag is set. */
9094 if (xflag) {
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009095 int n;
9096 const char *p = " %s";
Eric Andersenc470f442003-07-28 09:56:35 +00009097
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009098 p++;
Denis Vlasenko0de37e12007-10-17 11:08:53 +00009099 fdprintf(preverrout_fd, p, expandstr(ps4val()));
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009100
9101 sp = varlist.list;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +00009102 for (n = 0; n < 2; n++) {
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009103 while (sp) {
Denis Vlasenko0de37e12007-10-17 11:08:53 +00009104 fdprintf(preverrout_fd, p, sp->text);
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009105 sp = sp->next;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +00009106 if (*p == '%') {
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009107 p--;
9108 }
9109 }
9110 sp = arglist.list;
9111 }
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00009112 safe_write(preverrout_fd, "\n", 1);
Eric Andersenc470f442003-07-28 09:56:35 +00009113 }
9114
9115 cmd_is_exec = 0;
9116 spclbltin = -1;
9117
9118 /* Now locate the command. */
9119 if (argc) {
9120 const char *oldpath;
9121 int cmd_flag = DO_ERR;
9122
9123 path += 5;
9124 oldpath = path;
9125 for (;;) {
9126 find_command(argv[0], &cmdentry, cmd_flag, path);
9127 if (cmdentry.cmdtype == CMDUNKNOWN) {
Denys Vlasenko8131eea2009-11-02 14:19:51 +01009128 flush_stdout_stderr();
Denis Vlasenko6514c5e2008-07-24 13:41:37 +00009129 status = 127;
Eric Andersenc470f442003-07-28 09:56:35 +00009130 goto bail;
9131 }
9132
9133 /* implement bltin and command here */
9134 if (cmdentry.cmdtype != CMDBUILTIN)
9135 break;
9136 if (spclbltin < 0)
9137 spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
9138 if (cmdentry.u.cmd == EXECCMD)
Denis Vlasenko34c73c42008-08-16 11:48:02 +00009139 cmd_is_exec = 1;
Denis Vlasenko131ae172007-02-18 13:00:19 +00009140#if ENABLE_ASH_CMDCMD
Eric Andersenc470f442003-07-28 09:56:35 +00009141 if (cmdentry.u.cmd == COMMANDCMD) {
Eric Andersenc470f442003-07-28 09:56:35 +00009142 path = oldpath;
9143 nargv = parse_command_args(argv, &path);
9144 if (!nargv)
9145 break;
9146 argc -= nargv - argv;
9147 argv = nargv;
9148 cmd_flag |= DO_NOFUNC;
9149 } else
9150#endif
9151 break;
9152 }
9153 }
9154
9155 if (status) {
9156 /* We have a redirection error. */
9157 if (spclbltin > 0)
Denis Vlasenkob012b102007-02-19 22:43:01 +00009158 raise_exception(EXERROR);
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009159 bail:
Eric Andersenc470f442003-07-28 09:56:35 +00009160 exitstatus = status;
9161 goto out;
9162 }
9163
9164 /* Execute the command. */
9165 switch (cmdentry.cmdtype) {
Denys Vlasenko42c4b2e2010-05-18 16:13:56 +02009166 default: {
Denis Vlasenkobe54d6b2008-10-27 14:25:52 +00009167
Denis Vlasenko9bc80d72008-04-12 20:07:53 +00009168#if ENABLE_FEATURE_SH_NOFORK
Denys Vlasenko42c4b2e2010-05-18 16:13:56 +02009169/* (1) BUG: if variables are set, we need to fork, or save/restore them
9170 * around run_nofork_applet() call.
9171 * (2) Should this check also be done in forkshell()?
9172 * (perhaps it should, so that "VAR=VAL nofork" at least avoids exec...)
9173 */
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00009174 /* find_command() encodes applet_no as (-2 - applet_no) */
9175 int applet_no = (- cmdentry.u.index - 2);
Denis Vlasenko9bc80d72008-04-12 20:07:53 +00009176 if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
Denis Vlasenko9bc80d72008-04-12 20:07:53 +00009177 listsetvar(varlist.list, VEXPORT|VSTACK);
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00009178 /* run <applet>_main() */
9179 exitstatus = run_nofork_applet(applet_no, argv);
Denis Vlasenko9bc80d72008-04-12 20:07:53 +00009180 break;
9181 }
Denis Vlasenko9bc80d72008-04-12 20:07:53 +00009182#endif
Denys Vlasenko42c4b2e2010-05-18 16:13:56 +02009183 /* Can we avoid forking off? For example, very last command
9184 * in a script or a subshell does not need forking,
9185 * we can just exec it.
9186 */
Denys Vlasenko238bf182010-05-18 15:49:07 +02009187 if (!(flags & EV_EXIT) || may_have_traps) {
Denys Vlasenko42c4b2e2010-05-18 16:13:56 +02009188 /* No, forking off a child is necessary */
Denis Vlasenkob012b102007-02-19 22:43:01 +00009189 INT_OFF;
Denis Vlasenko68404f12008-03-17 09:00:54 +00009190 jp = makejob(/*cmd,*/ 1);
Eric Andersenc470f442003-07-28 09:56:35 +00009191 if (forkshell(jp, cmd, FORK_FG) != 0) {
Denys Vlasenko238bf182010-05-18 15:49:07 +02009192 /* parent */
Eric Andersenc470f442003-07-28 09:56:35 +00009193 exitstatus = waitforjob(jp);
Denis Vlasenkob012b102007-02-19 22:43:01 +00009194 INT_ON;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00009195 TRACE(("forked child exited with %d\n", exitstatus));
Eric Andersenc470f442003-07-28 09:56:35 +00009196 break;
9197 }
Denys Vlasenko238bf182010-05-18 15:49:07 +02009198 /* child */
Denis Vlasenkob012b102007-02-19 22:43:01 +00009199 FORCE_INT_ON;
Denys Vlasenkoc7f95d22010-05-18 15:52:23 +02009200 /* fall through to exec'ing external program */
Eric Andersenc470f442003-07-28 09:56:35 +00009201 }
9202 listsetvar(varlist.list, VEXPORT|VSTACK);
9203 shellexec(argv, path, cmdentry.u.index);
9204 /* NOTREACHED */
Denys Vlasenko42c4b2e2010-05-18 16:13:56 +02009205 } /* default */
Eric Andersenc470f442003-07-28 09:56:35 +00009206 case CMDBUILTIN:
9207 cmdenviron = varlist.list;
9208 if (cmdenviron) {
9209 struct strlist *list = cmdenviron;
9210 int i = VNOSET;
9211 if (spclbltin > 0 || argc == 0) {
9212 i = 0;
9213 if (cmd_is_exec && argc > 1)
9214 i = VEXPORT;
9215 }
9216 listsetvar(list, i);
9217 }
Denis Vlasenkobe54d6b2008-10-27 14:25:52 +00009218 /* Tight loop with builtins only:
9219 * "while kill -0 $child; do true; done"
9220 * will never exit even if $child died, unless we do this
9221 * to reap the zombie and make kill detect that it's gone: */
9222 dowait(DOWAIT_NONBLOCK, NULL);
9223
Eric Andersenc470f442003-07-28 09:56:35 +00009224 if (evalbltin(cmdentry.u.cmd, argc, argv)) {
9225 int exit_status;
Denis Vlasenko7f88e342009-03-19 03:36:18 +00009226 int i = exception_type;
Eric Andersenc470f442003-07-28 09:56:35 +00009227 if (i == EXEXIT)
9228 goto raise;
Eric Andersenc470f442003-07-28 09:56:35 +00009229 exit_status = 2;
Eric Andersenc470f442003-07-28 09:56:35 +00009230 if (i == EXINT)
Denis Vlasenko991a1da2008-02-10 19:02:53 +00009231 exit_status = 128 + SIGINT;
Eric Andersenc470f442003-07-28 09:56:35 +00009232 if (i == EXSIG)
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02009233 exit_status = 128 + pending_sig;
Eric Andersenc470f442003-07-28 09:56:35 +00009234 exitstatus = exit_status;
Eric Andersenc470f442003-07-28 09:56:35 +00009235 if (i == EXINT || spclbltin > 0) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009236 raise:
Denis Vlasenko2da584f2007-02-19 22:44:05 +00009237 longjmp(exception_handler->loc, 1);
Eric Andersenc470f442003-07-28 09:56:35 +00009238 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00009239 FORCE_INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00009240 }
9241 break;
9242
9243 case CMDFUNCTION:
9244 listsetvar(varlist.list, 0);
Denis Vlasenkobe54d6b2008-10-27 14:25:52 +00009245 /* See above for the rationale */
9246 dowait(DOWAIT_NONBLOCK, NULL);
Eric Andersenc470f442003-07-28 09:56:35 +00009247 if (evalfun(cmdentry.u.func, argc, argv, flags))
9248 goto raise;
9249 break;
Denys Vlasenko42c4b2e2010-05-18 16:13:56 +02009250
9251 } /* switch */
Eric Andersenc470f442003-07-28 09:56:35 +00009252
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009253 out:
Denis Vlasenko34c73c42008-08-16 11:48:02 +00009254 popredir(/*drop:*/ cmd_is_exec, /*restore:*/ cmd_is_exec);
Denis Vlasenko6514c5e2008-07-24 13:41:37 +00009255 if (lastarg) {
Eric Andersenc470f442003-07-28 09:56:35 +00009256 /* dsl: I think this is intended to be used to support
9257 * '_' in 'vi' command mode during line editing...
9258 * However I implemented that within libedit itself.
9259 */
9260 setvar("_", lastarg, 0);
Denis Vlasenko6514c5e2008-07-24 13:41:37 +00009261 }
Eric Andersenc470f442003-07-28 09:56:35 +00009262 popstackmark(&smark);
9263}
9264
9265static int
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009266evalbltin(const struct builtincmd *cmd, int argc, char **argv)
9267{
Eric Andersenc470f442003-07-28 09:56:35 +00009268 char *volatile savecmdname;
9269 struct jmploc *volatile savehandler;
9270 struct jmploc jmploc;
9271 int i;
9272
9273 savecmdname = commandname;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009274 i = setjmp(jmploc.loc);
9275 if (i)
Eric Andersenc470f442003-07-28 09:56:35 +00009276 goto cmddone;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00009277 savehandler = exception_handler;
9278 exception_handler = &jmploc;
Eric Andersenc470f442003-07-28 09:56:35 +00009279 commandname = argv[0];
9280 argptr = argv + 1;
9281 optptr = NULL; /* initialize nextopt */
9282 exitstatus = (*cmd->builtin)(argc, argv);
Denis Vlasenkob012b102007-02-19 22:43:01 +00009283 flush_stdout_stderr();
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009284 cmddone:
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009285 exitstatus |= ferror(stdout);
Rob Landleyf296f0b2006-07-06 01:09:21 +00009286 clearerr(stdout);
Eric Andersenc470f442003-07-28 09:56:35 +00009287 commandname = savecmdname;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00009288 exception_handler = savehandler;
Eric Andersenc470f442003-07-28 09:56:35 +00009289
9290 return i;
9291}
9292
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009293static int
9294goodname(const char *p)
Glenn L McGrath16e45d72004-02-04 08:24:39 +00009295{
9296 return !*endofname(p);
9297}
9298
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009299
Glenn L McGrath50812ff2002-08-23 13:14:48 +00009300/*
9301 * Search for a command. This is called before we fork so that the
9302 * location of the command will be available in the parent as well as
Glenn L McGrath16e45d72004-02-04 08:24:39 +00009303 * the child. The check for "goodname" is an overly conservative
9304 * check that the name will not be subject to expansion.
Glenn L McGrath50812ff2002-08-23 13:14:48 +00009305 */
Eric Andersenc470f442003-07-28 09:56:35 +00009306static void
9307prehash(union node *n)
Glenn L McGrath50812ff2002-08-23 13:14:48 +00009308{
9309 struct cmdentry entry;
9310
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +00009311 if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
9312 find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
Glenn L McGrath50812ff2002-08-23 13:14:48 +00009313}
9314
Eric Andersencb57d552001-06-28 07:25:16 +00009315
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00009316/* ============ Builtin commands
9317 *
9318 * Builtin commands whose functions are closely tied to evaluation
9319 * are implemented here.
Eric Andersencb57d552001-06-28 07:25:16 +00009320 */
9321
9322/*
Eric Andersencb57d552001-06-28 07:25:16 +00009323 * Handle break and continue commands. Break, continue, and return are
9324 * all handled by setting the evalskip flag. The evaluation routines
9325 * above all check this flag, and if it is set they start skipping
9326 * commands rather than executing them. The variable skipcount is
9327 * the number of loops to break/continue, or the number of function
9328 * levels to return. (The latter is always 1.) It should probably
9329 * be an error to break out of more loops than exist, but it isn't
9330 * in the standard shell so we don't make it one here.
9331 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009332static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00009333breakcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +00009334{
Denis Vlasenko68404f12008-03-17 09:00:54 +00009335 int n = argv[1] ? number(argv[1]) : 1;
Eric Andersencb57d552001-06-28 07:25:16 +00009336
Aaron Lehmann2aef3a62001-12-31 06:03:12 +00009337 if (n <= 0)
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02009338 ash_msg_and_raise_error(msg_illnum, argv[1]);
Eric Andersencb57d552001-06-28 07:25:16 +00009339 if (n > loopnest)
9340 n = loopnest;
9341 if (n > 0) {
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00009342 evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
Eric Andersencb57d552001-06-28 07:25:16 +00009343 skipcount = n;
9344 }
9345 return 0;
9346}
9347
Eric Andersenc470f442003-07-28 09:56:35 +00009348
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009349/* ============ input.c
9350 *
Eric Andersen90898442003-08-06 11:20:52 +00009351 * This implements the input routines used by the parser.
Eric Andersencb57d552001-06-28 07:25:16 +00009352 */
Denis Vlasenko99eb8502007-02-23 21:09:49 +00009353
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009354enum {
9355 INPUT_PUSH_FILE = 1,
9356 INPUT_NOFILE_OK = 2,
9357};
Eric Andersencb57d552001-06-28 07:25:16 +00009358
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009359static smallint checkkwd;
Denis Vlasenko99eb8502007-02-23 21:09:49 +00009360/* values of checkkwd variable */
9361#define CHKALIAS 0x1
9362#define CHKKWD 0x2
9363#define CHKNL 0x4
9364
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009365/*
9366 * Push a string back onto the input at this current parsefile level.
9367 * We handle aliases this way.
9368 */
9369#if !ENABLE_ASH_ALIAS
9370#define pushstring(s, ap) pushstring(s)
9371#endif
9372static void
9373pushstring(char *s, struct alias *ap)
9374{
9375 struct strpush *sp;
9376 int len;
9377
9378 len = strlen(s);
9379 INT_OFF;
9380 if (g_parsefile->strpush) {
9381 sp = ckzalloc(sizeof(*sp));
9382 sp->prev = g_parsefile->strpush;
9383 } else {
9384 sp = &(g_parsefile->basestrpush);
9385 }
9386 g_parsefile->strpush = sp;
9387 sp->prev_string = g_parsefile->next_to_pgetc;
9388 sp->prev_left_in_line = g_parsefile->left_in_line;
9389#if ENABLE_ASH_ALIAS
9390 sp->ap = ap;
9391 if (ap) {
9392 ap->flag |= ALIASINUSE;
9393 sp->string = s;
9394 }
9395#endif
9396 g_parsefile->next_to_pgetc = s;
9397 g_parsefile->left_in_line = len;
9398 INT_ON;
9399}
9400
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009401static void
9402popstring(void)
Eric Andersenc470f442003-07-28 09:56:35 +00009403{
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009404 struct strpush *sp = g_parsefile->strpush;
Eric Andersenc470f442003-07-28 09:56:35 +00009405
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009406 INT_OFF;
Denis Vlasenko131ae172007-02-18 13:00:19 +00009407#if ENABLE_ASH_ALIAS
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009408 if (sp->ap) {
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009409 if (g_parsefile->next_to_pgetc[-1] == ' '
9410 || g_parsefile->next_to_pgetc[-1] == '\t'
9411 ) {
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009412 checkkwd |= CHKALIAS;
Glenn L McGrath28939ad2004-07-21 10:20:19 +00009413 }
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009414 if (sp->string != sp->ap->val) {
9415 free(sp->string);
9416 }
9417 sp->ap->flag &= ~ALIASINUSE;
9418 if (sp->ap->flag & ALIASDEAD) {
9419 unalias(sp->ap->name);
9420 }
Glenn L McGrath28939ad2004-07-21 10:20:19 +00009421 }
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009422#endif
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009423 g_parsefile->next_to_pgetc = sp->prev_string;
9424 g_parsefile->left_in_line = sp->prev_left_in_line;
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009425 g_parsefile->strpush = sp->prev;
9426 if (sp != &(g_parsefile->basestrpush))
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009427 free(sp);
9428 INT_ON;
9429}
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009430
Denis Vlasenkoe27dafd2008-11-28 04:01:03 +00009431//FIXME: BASH_COMPAT with "...&" does TWO pungetc():
9432//it peeks whether it is &>, and then pushes back both chars.
9433//This function needs to save last *next_to_pgetc to buf[0]
9434//to make two pungetc() reliable. Currently,
9435// pgetc (out of buf: does preadfd), pgetc, pungetc, pungetc won't work...
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009436static int
9437preadfd(void)
Eric Andersencb57d552001-06-28 07:25:16 +00009438{
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00009439 int nr;
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00009440 char *buf = g_parsefile->buf;
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00009441
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009442 g_parsefile->next_to_pgetc = buf;
Denis Vlasenko38f63192007-01-22 09:03:07 +00009443#if ENABLE_FEATURE_EDITING
Denis Vlasenko85c24712008-03-17 09:04:04 +00009444 retry:
Denis Vlasenko727752d2008-11-28 03:41:47 +00009445 if (!iflag || g_parsefile->fd != STDIN_FILENO)
Denys Vlasenko82dd14a2010-05-17 10:10:01 +02009446 nr = nonblock_safe_read(g_parsefile->fd, buf, IBUFSIZ - 1);
Eric Andersenc470f442003-07-28 09:56:35 +00009447 else {
Denis Vlasenko38f63192007-01-22 09:03:07 +00009448#if ENABLE_FEATURE_TAB_COMPLETION
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009449 line_input_state->path_lookup = pathval();
Eric Andersen4a79c0e2004-09-08 10:01:07 +00009450#endif
Denys Vlasenko82dd14a2010-05-17 10:10:01 +02009451 nr = read_line_input(cmdedit_prompt, buf, IBUFSIZ, line_input_state);
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009452 if (nr == 0) {
9453 /* Ctrl+C pressed */
9454 if (trap[SIGINT]) {
Glenn L McGrath16e45d72004-02-04 08:24:39 +00009455 buf[0] = '\n';
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009456 buf[1] = '\0';
Glenn L McGrath16e45d72004-02-04 08:24:39 +00009457 raise(SIGINT);
9458 return 1;
9459 }
Eric Andersenc470f442003-07-28 09:56:35 +00009460 goto retry;
9461 }
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009462 if (nr < 0 && errno == 0) {
Denis Vlasenko9cb220b2007-12-09 10:03:28 +00009463 /* Ctrl+D pressed */
Eric Andersenc470f442003-07-28 09:56:35 +00009464 nr = 0;
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00009465 }
Eric Andersencb57d552001-06-28 07:25:16 +00009466 }
9467#else
Denys Vlasenko82dd14a2010-05-17 10:10:01 +02009468 nr = nonblock_safe_read(g_parsefile->fd, buf, IBUFSIZ - 1);
Eric Andersencb57d552001-06-28 07:25:16 +00009469#endif
9470
Denis Vlasenkoe376d452008-02-20 22:23:24 +00009471#if 0
9472/* nonblock_safe_read() handles this problem */
Eric Andersencb57d552001-06-28 07:25:16 +00009473 if (nr < 0) {
Eric Andersencb57d552001-06-28 07:25:16 +00009474 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
Denis Vlasenkod37f2222007-08-19 13:42:08 +00009475 int flags = fcntl(0, F_GETFL);
Denis Vlasenko9cb220b2007-12-09 10:03:28 +00009476 if (flags >= 0 && (flags & O_NONBLOCK)) {
9477 flags &= ~O_NONBLOCK;
Eric Andersencb57d552001-06-28 07:25:16 +00009478 if (fcntl(0, F_SETFL, flags) >= 0) {
9479 out2str("sh: turning off NDELAY mode\n");
9480 goto retry;
9481 }
9482 }
9483 }
9484 }
Denis Vlasenkoe376d452008-02-20 22:23:24 +00009485#endif
Eric Andersencb57d552001-06-28 07:25:16 +00009486 return nr;
9487}
9488
9489/*
9490 * Refill the input buffer and return the next input character:
9491 *
9492 * 1) If a string was pushed back on the input, pop it;
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009493 * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
9494 * or we are reading from a string so we can't refill the buffer,
9495 * return EOF.
Denys Vlasenko883cea42009-07-11 15:31:59 +02009496 * 3) If there is more stuff in this buffer, use it else call read to fill it.
Eric Andersencb57d552001-06-28 07:25:16 +00009497 * 4) Process input up to the next newline, deleting nul characters.
9498 */
Denis Vlasenko727752d2008-11-28 03:41:47 +00009499//#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
9500#define pgetc_debug(...) ((void)0)
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009501static int
Eric Andersenc470f442003-07-28 09:56:35 +00009502preadbuffer(void)
Eric Andersencb57d552001-06-28 07:25:16 +00009503{
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009504 char *q;
Eric Andersencb57d552001-06-28 07:25:16 +00009505 int more;
Eric Andersencb57d552001-06-28 07:25:16 +00009506
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009507 while (g_parsefile->strpush) {
Denis Vlasenko131ae172007-02-18 13:00:19 +00009508#if ENABLE_ASH_ALIAS
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009509 if (g_parsefile->left_in_line == -1
9510 && g_parsefile->strpush->ap
9511 && g_parsefile->next_to_pgetc[-1] != ' '
9512 && g_parsefile->next_to_pgetc[-1] != '\t'
Denis Vlasenko16898402008-11-25 01:34:52 +00009513 ) {
Denis Vlasenko727752d2008-11-28 03:41:47 +00009514 pgetc_debug("preadbuffer PEOA");
Eric Andersencb57d552001-06-28 07:25:16 +00009515 return PEOA;
9516 }
Eric Andersen2870d962001-07-02 17:27:21 +00009517#endif
Eric Andersencb57d552001-06-28 07:25:16 +00009518 popstring();
Denis Vlasenko727752d2008-11-28 03:41:47 +00009519 /* try "pgetc" now: */
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009520 pgetc_debug("preadbuffer internal pgetc at %d:%p'%s'",
9521 g_parsefile->left_in_line,
9522 g_parsefile->next_to_pgetc,
9523 g_parsefile->next_to_pgetc);
9524 if (--g_parsefile->left_in_line >= 0)
9525 return (unsigned char)(*g_parsefile->next_to_pgetc++);
Eric Andersencb57d552001-06-28 07:25:16 +00009526 }
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009527 /* on both branches above g_parsefile->left_in_line < 0.
Denis Vlasenko727752d2008-11-28 03:41:47 +00009528 * "pgetc" needs refilling.
9529 */
9530
Denis Vlasenkoe27dafd2008-11-28 04:01:03 +00009531 /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009532 * pungetc() may increment it a few times.
Denis Vlasenkoe27dafd2008-11-28 04:01:03 +00009533 * Assuming it won't increment it to less than -90.
Denis Vlasenko727752d2008-11-28 03:41:47 +00009534 */
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009535 if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
Denis Vlasenko727752d2008-11-28 03:41:47 +00009536 pgetc_debug("preadbuffer PEOF1");
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009537 /* even in failure keep left_in_line and next_to_pgetc
9538 * in lock step, for correct multi-layer pungetc.
9539 * left_in_line was decremented before preadbuffer(),
9540 * must inc next_to_pgetc: */
9541 g_parsefile->next_to_pgetc++;
Eric Andersencb57d552001-06-28 07:25:16 +00009542 return PEOF;
Denis Vlasenko727752d2008-11-28 03:41:47 +00009543 }
Eric Andersencb57d552001-06-28 07:25:16 +00009544
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009545 more = g_parsefile->left_in_buffer;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009546 if (more <= 0) {
Denis Vlasenko727752d2008-11-28 03:41:47 +00009547 flush_stdout_stderr();
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009548 again:
9549 more = preadfd();
9550 if (more <= 0) {
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009551 /* don't try reading again */
9552 g_parsefile->left_in_line = -99;
Denis Vlasenko727752d2008-11-28 03:41:47 +00009553 pgetc_debug("preadbuffer PEOF2");
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009554 g_parsefile->next_to_pgetc++;
Eric Andersencb57d552001-06-28 07:25:16 +00009555 return PEOF;
9556 }
9557 }
9558
Denis Vlasenko727752d2008-11-28 03:41:47 +00009559 /* Find out where's the end of line.
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009560 * Set g_parsefile->left_in_line
9561 * and g_parsefile->left_in_buffer acordingly.
Denis Vlasenko727752d2008-11-28 03:41:47 +00009562 * NUL chars are deleted.
9563 */
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009564 q = g_parsefile->next_to_pgetc;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009565 for (;;) {
Denis Vlasenko727752d2008-11-28 03:41:47 +00009566 char c;
Eric Andersencb57d552001-06-28 07:25:16 +00009567
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009568 more--;
Eric Andersenc470f442003-07-28 09:56:35 +00009569
Denis Vlasenko727752d2008-11-28 03:41:47 +00009570 c = *q;
9571 if (c == '\0') {
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009572 memmove(q, q + 1, more);
Denis Vlasenko727752d2008-11-28 03:41:47 +00009573 } else {
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009574 q++;
9575 if (c == '\n') {
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009576 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009577 break;
9578 }
Eric Andersencb57d552001-06-28 07:25:16 +00009579 }
9580
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009581 if (more <= 0) {
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009582 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9583 if (g_parsefile->left_in_line < 0)
Eric Andersencb57d552001-06-28 07:25:16 +00009584 goto again;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009585 break;
Eric Andersencb57d552001-06-28 07:25:16 +00009586 }
9587 }
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009588 g_parsefile->left_in_buffer = more;
Eric Andersencb57d552001-06-28 07:25:16 +00009589
Eric Andersencb57d552001-06-28 07:25:16 +00009590 if (vflag) {
Denis Vlasenko727752d2008-11-28 03:41:47 +00009591 char save = *q;
9592 *q = '\0';
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009593 out2str(g_parsefile->next_to_pgetc);
Denis Vlasenko727752d2008-11-28 03:41:47 +00009594 *q = save;
Eric Andersencb57d552001-06-28 07:25:16 +00009595 }
9596
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009597 pgetc_debug("preadbuffer at %d:%p'%s'",
9598 g_parsefile->left_in_line,
9599 g_parsefile->next_to_pgetc,
9600 g_parsefile->next_to_pgetc);
Denys Vlasenkocd716832009-11-28 22:14:02 +01009601 return (unsigned char)*g_parsefile->next_to_pgetc++;
Eric Andersencb57d552001-06-28 07:25:16 +00009602}
9603
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009604#define pgetc_as_macro() \
9605 (--g_parsefile->left_in_line >= 0 \
Denys Vlasenkocd716832009-11-28 22:14:02 +01009606 ? (unsigned char)*g_parsefile->next_to_pgetc++ \
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009607 : preadbuffer() \
9608 )
Denis Vlasenko727752d2008-11-28 03:41:47 +00009609
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009610static int
9611pgetc(void)
9612{
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009613 pgetc_debug("pgetc_fast at %d:%p'%s'",
9614 g_parsefile->left_in_line,
9615 g_parsefile->next_to_pgetc,
9616 g_parsefile->next_to_pgetc);
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009617 return pgetc_as_macro();
9618}
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00009619
9620#if ENABLE_ASH_OPTIMIZE_FOR_SIZE
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01009621# define pgetc_fast() pgetc()
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009622#else
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01009623# define pgetc_fast() pgetc_as_macro()
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009624#endif
9625
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009626#if ENABLE_ASH_ALIAS
9627static int
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01009628pgetc_without_PEOA(void)
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009629{
9630 int c;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009631 do {
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009632 pgetc_debug("pgetc_fast at %d:%p'%s'",
9633 g_parsefile->left_in_line,
9634 g_parsefile->next_to_pgetc,
9635 g_parsefile->next_to_pgetc);
Denis Vlasenko834dee72008-10-07 09:18:30 +00009636 c = pgetc_fast();
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009637 } while (c == PEOA);
9638 return c;
9639}
9640#else
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01009641# define pgetc_without_PEOA() pgetc()
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009642#endif
9643
9644/*
9645 * Read a line from the script.
9646 */
9647static char *
9648pfgets(char *line, int len)
9649{
9650 char *p = line;
9651 int nleft = len;
9652 int c;
9653
9654 while (--nleft > 0) {
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01009655 c = pgetc_without_PEOA();
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009656 if (c == PEOF) {
9657 if (p == line)
9658 return NULL;
9659 break;
9660 }
9661 *p++ = c;
9662 if (c == '\n')
9663 break;
9664 }
9665 *p = '\0';
9666 return line;
9667}
9668
Eric Andersenc470f442003-07-28 09:56:35 +00009669/*
9670 * Undo the last call to pgetc. Only one character may be pushed back.
9671 * PEOF may be pushed back.
9672 */
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009673static void
Eric Andersenc470f442003-07-28 09:56:35 +00009674pungetc(void)
9675{
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009676 g_parsefile->left_in_line++;
9677 g_parsefile->next_to_pgetc--;
9678 pgetc_debug("pushed back to %d:%p'%s'",
9679 g_parsefile->left_in_line,
9680 g_parsefile->next_to_pgetc,
9681 g_parsefile->next_to_pgetc);
Eric Andersencb57d552001-06-28 07:25:16 +00009682}
9683
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009684/*
9685 * To handle the "." command, a stack of input files is used. Pushfile
9686 * adds a new entry to the stack and popfile restores the previous level.
9687 */
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009688static void
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009689pushfile(void)
Eric Andersenc470f442003-07-28 09:56:35 +00009690{
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009691 struct parsefile *pf;
9692
Denis Vlasenko597906c2008-02-20 16:38:54 +00009693 pf = ckzalloc(sizeof(*pf));
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009694 pf->prev = g_parsefile;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009695 pf->fd = -1;
Denis Vlasenko597906c2008-02-20 16:38:54 +00009696 /*pf->strpush = NULL; - ckzalloc did it */
9697 /*pf->basestrpush.prev = NULL;*/
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009698 g_parsefile = pf;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009699}
9700
9701static void
9702popfile(void)
9703{
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009704 struct parsefile *pf = g_parsefile;
Eric Andersenc470f442003-07-28 09:56:35 +00009705
Denis Vlasenkob012b102007-02-19 22:43:01 +00009706 INT_OFF;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009707 if (pf->fd >= 0)
9708 close(pf->fd);
Denis Vlasenko60818682007-09-28 22:07:23 +00009709 free(pf->buf);
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009710 while (pf->strpush)
9711 popstring();
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009712 g_parsefile = pf->prev;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009713 free(pf);
Denis Vlasenkob012b102007-02-19 22:43:01 +00009714 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00009715}
9716
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009717/*
9718 * Return to top level.
9719 */
9720static void
9721popallfiles(void)
9722{
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009723 while (g_parsefile != &basepf)
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009724 popfile();
9725}
9726
9727/*
9728 * Close the file(s) that the shell is reading commands from. Called
9729 * after a fork is done.
9730 */
9731static void
9732closescript(void)
9733{
9734 popallfiles();
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009735 if (g_parsefile->fd > 0) {
9736 close(g_parsefile->fd);
9737 g_parsefile->fd = 0;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009738 }
9739}
9740
9741/*
9742 * Like setinputfile, but takes an open file descriptor. Call this with
9743 * interrupts off.
9744 */
9745static void
9746setinputfd(int fd, int push)
9747{
Denis Vlasenko96e1b382007-09-30 23:50:48 +00009748 close_on_exec_on(fd);
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009749 if (push) {
9750 pushfile();
Denis Vlasenko727752d2008-11-28 03:41:47 +00009751 g_parsefile->buf = NULL;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009752 }
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009753 g_parsefile->fd = fd;
9754 if (g_parsefile->buf == NULL)
9755 g_parsefile->buf = ckmalloc(IBUFSIZ);
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009756 g_parsefile->left_in_buffer = 0;
9757 g_parsefile->left_in_line = 0;
9758 g_parsefile->linno = 1;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009759}
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009760
Eric Andersenc470f442003-07-28 09:56:35 +00009761/*
9762 * Set the input to take input from a file. If push is set, push the
9763 * old input onto the stack first.
9764 */
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009765static int
9766setinputfile(const char *fname, int flags)
Eric Andersenc470f442003-07-28 09:56:35 +00009767{
9768 int fd;
9769 int fd2;
9770
Denis Vlasenkob012b102007-02-19 22:43:01 +00009771 INT_OFF;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009772 fd = open(fname, O_RDONLY);
9773 if (fd < 0) {
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009774 if (flags & INPUT_NOFILE_OK)
9775 goto out;
Denis Vlasenko9604e1b2009-03-03 18:47:56 +00009776 ash_msg_and_raise_error("can't open '%s'", fname);
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009777 }
Eric Andersenc470f442003-07-28 09:56:35 +00009778 if (fd < 10) {
9779 fd2 = copyfd(fd, 10);
9780 close(fd);
9781 if (fd2 < 0)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00009782 ash_msg_and_raise_error("out of file descriptors");
Eric Andersenc470f442003-07-28 09:56:35 +00009783 fd = fd2;
9784 }
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009785 setinputfd(fd, flags & INPUT_PUSH_FILE);
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009786 out:
Denis Vlasenkob012b102007-02-19 22:43:01 +00009787 INT_ON;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009788 return fd;
Eric Andersenc470f442003-07-28 09:56:35 +00009789}
9790
Eric Andersencb57d552001-06-28 07:25:16 +00009791/*
9792 * Like setinputfile, but takes input from a string.
9793 */
Eric Andersenc470f442003-07-28 09:56:35 +00009794static void
9795setinputstring(char *string)
Eric Andersen62483552001-07-10 06:09:16 +00009796{
Denis Vlasenkob012b102007-02-19 22:43:01 +00009797 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +00009798 pushfile();
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009799 g_parsefile->next_to_pgetc = string;
9800 g_parsefile->left_in_line = strlen(string);
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009801 g_parsefile->buf = NULL;
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009802 g_parsefile->linno = 1;
Denis Vlasenkob012b102007-02-19 22:43:01 +00009803 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00009804}
9805
9806
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00009807/* ============ mail.c
9808 *
9809 * Routines to check for mail.
Eric Andersencb57d552001-06-28 07:25:16 +00009810 */
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00009811
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00009812#if ENABLE_ASH_MAIL
Eric Andersencb57d552001-06-28 07:25:16 +00009813
Eric Andersencb57d552001-06-28 07:25:16 +00009814#define MAXMBOXES 10
9815
Eric Andersenc470f442003-07-28 09:56:35 +00009816/* times of mailboxes */
9817static time_t mailtime[MAXMBOXES];
9818/* Set if MAIL or MAILPATH is changed. */
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +00009819static smallint mail_var_path_changed;
Eric Andersencb57d552001-06-28 07:25:16 +00009820
Eric Andersencb57d552001-06-28 07:25:16 +00009821/*
Eric Andersenc470f442003-07-28 09:56:35 +00009822 * Print appropriate message(s) if mail has arrived.
9823 * If mail_var_path_changed is set,
9824 * then the value of MAIL has mail_var_path_changed,
9825 * so we just update the values.
Eric Andersencb57d552001-06-28 07:25:16 +00009826 */
Eric Andersenc470f442003-07-28 09:56:35 +00009827static void
9828chkmail(void)
Eric Andersencb57d552001-06-28 07:25:16 +00009829{
Eric Andersencb57d552001-06-28 07:25:16 +00009830 const char *mpath;
9831 char *p;
9832 char *q;
Eric Andersenc470f442003-07-28 09:56:35 +00009833 time_t *mtp;
Eric Andersencb57d552001-06-28 07:25:16 +00009834 struct stackmark smark;
9835 struct stat statb;
9836
Eric Andersencb57d552001-06-28 07:25:16 +00009837 setstackmark(&smark);
Eric Andersenc470f442003-07-28 09:56:35 +00009838 mpath = mpathset() ? mpathval() : mailval();
9839 for (mtp = mailtime; mtp < mailtime + MAXMBOXES; mtp++) {
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02009840 p = path_advance(&mpath, nullstr);
Eric Andersencb57d552001-06-28 07:25:16 +00009841 if (p == NULL)
9842 break;
9843 if (*p == '\0')
9844 continue;
Denis Vlasenkof7d56652008-03-25 05:51:41 +00009845 for (q = p; *q; q++)
9846 continue;
Denis Vlasenkoa7189f02006-11-17 20:29:00 +00009847#if DEBUG
Eric Andersencb57d552001-06-28 07:25:16 +00009848 if (q[-1] != '/')
9849 abort();
9850#endif
Eric Andersenc470f442003-07-28 09:56:35 +00009851 q[-1] = '\0'; /* delete trailing '/' */
9852 if (stat(p, &statb) < 0) {
9853 *mtp = 0;
9854 continue;
Eric Andersencb57d552001-06-28 07:25:16 +00009855 }
Eric Andersenc470f442003-07-28 09:56:35 +00009856 if (!mail_var_path_changed && statb.st_mtime != *mtp) {
9857 fprintf(
Denys Vlasenkoea8b2522010-06-02 12:57:26 +02009858 stderr, "%s\n",
Eric Andersenc470f442003-07-28 09:56:35 +00009859 pathopt ? pathopt : "you have mail"
9860 );
9861 }
9862 *mtp = statb.st_mtime;
Eric Andersencb57d552001-06-28 07:25:16 +00009863 }
Eric Andersenc470f442003-07-28 09:56:35 +00009864 mail_var_path_changed = 0;
Eric Andersencb57d552001-06-28 07:25:16 +00009865 popstackmark(&smark);
9866}
Eric Andersencb57d552001-06-28 07:25:16 +00009867
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009868static void FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00009869changemail(const char *val UNUSED_PARAM)
Eric Andersenc470f442003-07-28 09:56:35 +00009870{
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +00009871 mail_var_path_changed = 1;
Eric Andersenc470f442003-07-28 09:56:35 +00009872}
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00009873
Denis Vlasenko131ae172007-02-18 13:00:19 +00009874#endif /* ASH_MAIL */
Eric Andersenc470f442003-07-28 09:56:35 +00009875
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00009876
9877/* ============ ??? */
9878
Eric Andersencb57d552001-06-28 07:25:16 +00009879/*
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009880 * Set the shell parameters.
Eric Andersencb57d552001-06-28 07:25:16 +00009881 */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009882static void
9883setparam(char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +00009884{
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009885 char **newparam;
9886 char **ap;
9887 int nparam;
Eric Andersencb57d552001-06-28 07:25:16 +00009888
Denis Vlasenkof7d56652008-03-25 05:51:41 +00009889 for (nparam = 0; argv[nparam]; nparam++)
9890 continue;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009891 ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
9892 while (*argv) {
9893 *ap++ = ckstrdup(*argv++);
Eric Andersencb57d552001-06-28 07:25:16 +00009894 }
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009895 *ap = NULL;
9896 freeparam(&shellparam);
Denis Vlasenko01631112007-12-16 17:20:38 +00009897 shellparam.malloced = 1;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009898 shellparam.nparam = nparam;
9899 shellparam.p = newparam;
9900#if ENABLE_ASH_GETOPTS
9901 shellparam.optind = 1;
9902 shellparam.optoff = -1;
9903#endif
Eric Andersencb57d552001-06-28 07:25:16 +00009904}
9905
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00009906/*
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009907 * Process shell options. The global variable argptr contains a pointer
9908 * to the argument list; we advance it past the options.
Denis Vlasenko94e87bc2008-02-14 16:51:58 +00009909 *
9910 * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
9911 * For a non-interactive shell, an error condition encountered
9912 * by a special built-in ... shall cause the shell to write a diagnostic message
9913 * to standard error and exit as shown in the following table:
Denis Vlasenko56244732008-02-17 15:14:04 +00009914 * Error Special Built-In
Denis Vlasenko94e87bc2008-02-14 16:51:58 +00009915 * ...
9916 * Utility syntax error (option or operand error) Shall exit
9917 * ...
9918 * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
9919 * we see that bash does not do that (set "finishes" with error code 1 instead,
9920 * and shell continues), and people rely on this behavior!
9921 * Testcase:
9922 * set -o barfoo 2>/dev/null
9923 * echo $?
9924 *
9925 * Oh well. Let's mimic that.
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00009926 */
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009927static int
Denis Vlasenkodddfaff2008-05-06 15:30:27 +00009928plus_minus_o(char *name, int val)
Eric Andersen62483552001-07-10 06:09:16 +00009929{
9930 int i;
9931
Denis Vlasenkoa624c112007-02-19 22:45:43 +00009932 if (name) {
9933 for (i = 0; i < NOPTS; i++) {
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00009934 if (strcmp(name, optnames(i)) == 0) {
Eric Andersenc470f442003-07-28 09:56:35 +00009935 optlist[i] = val;
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009936 return 0;
Eric Andersen62483552001-07-10 06:09:16 +00009937 }
Denis Vlasenkoa624c112007-02-19 22:45:43 +00009938 }
Denis Vlasenkodddfaff2008-05-06 15:30:27 +00009939 ash_msg("illegal option %co %s", val ? '-' : '+', name);
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009940 return 1;
Eric Andersen62483552001-07-10 06:09:16 +00009941 }
Denis Vlasenko6b06cb82008-05-15 21:30:45 +00009942 for (i = 0; i < NOPTS; i++) {
Denis Vlasenkodddfaff2008-05-06 15:30:27 +00009943 if (val) {
9944 out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
9945 } else {
9946 out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
9947 }
Denis Vlasenko6b06cb82008-05-15 21:30:45 +00009948 }
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009949 return 0;
Eric Andersen62483552001-07-10 06:09:16 +00009950}
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009951static void
9952setoption(int flag, int val)
9953{
9954 int i;
9955
9956 for (i = 0; i < NOPTS; i++) {
9957 if (optletters(i) == flag) {
9958 optlist[i] = val;
9959 return;
9960 }
9961 }
Denis Vlasenkodddfaff2008-05-06 15:30:27 +00009962 ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009963 /* NOTREACHED */
9964}
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009965static int
Eric Andersenc470f442003-07-28 09:56:35 +00009966options(int cmdline)
Eric Andersencb57d552001-06-28 07:25:16 +00009967{
9968 char *p;
9969 int val;
9970 int c;
9971
9972 if (cmdline)
9973 minusc = NULL;
9974 while ((p = *argptr) != NULL) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009975 c = *p++;
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +00009976 if (c != '-' && c != '+')
9977 break;
9978 argptr++;
9979 val = 0; /* val = 0 if c == '+' */
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009980 if (c == '-') {
Eric Andersencb57d552001-06-28 07:25:16 +00009981 val = 1;
Denis Vlasenko9f739442006-12-16 23:49:13 +00009982 if (p[0] == '\0' || LONE_DASH(p)) {
Eric Andersen2870d962001-07-02 17:27:21 +00009983 if (!cmdline) {
9984 /* "-" means turn off -x and -v */
9985 if (p[0] == '\0')
9986 xflag = vflag = 0;
9987 /* "--" means reset params */
9988 else if (*argptr == NULL)
Eric Andersencb57d552001-06-28 07:25:16 +00009989 setparam(argptr);
Eric Andersen2870d962001-07-02 17:27:21 +00009990 }
Eric Andersenc470f442003-07-28 09:56:35 +00009991 break; /* "-" or "--" terminates options */
Eric Andersencb57d552001-06-28 07:25:16 +00009992 }
Eric Andersencb57d552001-06-28 07:25:16 +00009993 }
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +00009994 /* first char was + or - */
Eric Andersencb57d552001-06-28 07:25:16 +00009995 while ((c = *p++) != '\0') {
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +00009996 /* bash 3.2 indeed handles -c CMD and +c CMD the same */
Eric Andersencb57d552001-06-28 07:25:16 +00009997 if (c == 'c' && cmdline) {
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +00009998 minusc = p; /* command is after shell args */
Eric Andersencb57d552001-06-28 07:25:16 +00009999 } else if (c == 'o') {
Denis Vlasenkodddfaff2008-05-06 15:30:27 +000010000 if (plus_minus_o(*argptr, val)) {
Denis Vlasenko28bf6712008-02-14 15:01:47 +000010001 /* it already printed err message */
10002 return 1; /* error */
10003 }
Eric Andersencb57d552001-06-28 07:25:16 +000010004 if (*argptr)
10005 argptr++;
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +000010006 } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
10007 isloginsh = 1;
10008 /* bash does not accept +-login, we also won't */
10009 } else if (cmdline && val && (c == '-')) { /* long options */
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010010 if (strcmp(p, "login") == 0)
Robert Griebl64f70cc2002-05-14 23:22:06 +000010011 isloginsh = 1;
10012 break;
Eric Andersencb57d552001-06-28 07:25:16 +000010013 } else {
10014 setoption(c, val);
10015 }
10016 }
10017 }
Denis Vlasenko28bf6712008-02-14 15:01:47 +000010018 return 0;
Eric Andersencb57d552001-06-28 07:25:16 +000010019}
10020
Eric Andersencb57d552001-06-28 07:25:16 +000010021/*
Eric Andersencb57d552001-06-28 07:25:16 +000010022 * The shift builtin command.
10023 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010024static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000010025shiftcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +000010026{
10027 int n;
10028 char **ap1, **ap2;
10029
10030 n = 1;
Denis Vlasenko68404f12008-03-17 09:00:54 +000010031 if (argv[1])
Eric Andersencb57d552001-06-28 07:25:16 +000010032 n = number(argv[1]);
10033 if (n > shellparam.nparam)
Denis Vlasenkoc90e1be2008-07-30 15:35:05 +000010034 n = 0; /* bash compat, was = shellparam.nparam; */
Denis Vlasenkob012b102007-02-19 22:43:01 +000010035 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +000010036 shellparam.nparam -= n;
Denis Vlasenko2da584f2007-02-19 22:44:05 +000010037 for (ap1 = shellparam.p; --n >= 0; ap1++) {
Denis Vlasenko01631112007-12-16 17:20:38 +000010038 if (shellparam.malloced)
Denis Vlasenkob012b102007-02-19 22:43:01 +000010039 free(*ap1);
Eric Andersencb57d552001-06-28 07:25:16 +000010040 }
10041 ap2 = shellparam.p;
Denis Vlasenkof7d56652008-03-25 05:51:41 +000010042 while ((*ap2++ = *ap1++) != NULL)
10043 continue;
Denis Vlasenko131ae172007-02-18 13:00:19 +000010044#if ENABLE_ASH_GETOPTS
Eric Andersencb57d552001-06-28 07:25:16 +000010045 shellparam.optind = 1;
10046 shellparam.optoff = -1;
Eric Andersenc470f442003-07-28 09:56:35 +000010047#endif
Denis Vlasenkob012b102007-02-19 22:43:01 +000010048 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +000010049 return 0;
10050}
10051
Eric Andersencb57d552001-06-28 07:25:16 +000010052/*
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010053 * POSIX requires that 'set' (but not export or readonly) output the
10054 * variables in lexicographic order - by the locale's collating order (sigh).
10055 * Maybe we could keep them in an ordered balanced binary tree
10056 * instead of hashed lists.
10057 * For now just roll 'em through qsort for printing...
10058 */
10059static int
10060showvars(const char *sep_prefix, int on, int off)
10061{
10062 const char *sep;
10063 char **ep, **epend;
10064
10065 ep = listvars(on, off, &epend);
10066 qsort(ep, epend - ep, sizeof(char *), vpcmp);
10067
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +000010068 sep = *sep_prefix ? " " : sep_prefix;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010069
10070 for (; ep < epend; ep++) {
10071 const char *p;
10072 const char *q;
10073
10074 p = strchrnul(*ep, '=');
10075 q = nullstr;
10076 if (*p)
10077 q = single_quote(++p);
10078 out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
10079 }
10080 return 0;
10081}
10082
10083/*
Eric Andersencb57d552001-06-28 07:25:16 +000010084 * The set command builtin.
10085 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010086static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000010087setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersencb57d552001-06-28 07:25:16 +000010088{
Denis Vlasenko28bf6712008-02-14 15:01:47 +000010089 int retval;
10090
Denis Vlasenko68404f12008-03-17 09:00:54 +000010091 if (!argv[1])
Eric Andersenc470f442003-07-28 09:56:35 +000010092 return showvars(nullstr, 0, VUNSET);
Denis Vlasenkob012b102007-02-19 22:43:01 +000010093 INT_OFF;
Denis Vlasenko28bf6712008-02-14 15:01:47 +000010094 retval = 1;
10095 if (!options(0)) { /* if no parse error... */
10096 retval = 0;
10097 optschanged();
10098 if (*argptr != NULL) {
10099 setparam(argptr);
10100 }
Eric Andersencb57d552001-06-28 07:25:16 +000010101 }
Denis Vlasenkob012b102007-02-19 22:43:01 +000010102 INT_ON;
Denis Vlasenko28bf6712008-02-14 15:01:47 +000010103 return retval;
Eric Andersencb57d552001-06-28 07:25:16 +000010104}
10105
Denis Vlasenko131ae172007-02-18 13:00:19 +000010106#if ENABLE_ASH_RANDOM_SUPPORT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010107static void FAST_FUNC
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000010108change_random(const char *value)
Eric Andersenef02f822004-03-11 13:34:24 +000010109{
Denys Vlasenko3ea2e822009-10-09 20:59:04 +020010110 uint32_t t;
10111
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010112 if (value == NULL) {
Eric Andersen16767e22004-03-16 05:14:10 +000010113 /* "get", generate */
Denys Vlasenko3ea2e822009-10-09 20:59:04 +020010114 t = next_random(&random_gen);
Eric Andersen16767e22004-03-16 05:14:10 +000010115 /* set without recursion */
Denys Vlasenko8837c5d2010-06-02 12:56:18 +020010116 setvar(vrandom.var_text, utoa(t), VNOFUNC);
Eric Andersen16767e22004-03-16 05:14:10 +000010117 vrandom.flags &= ~VNOFUNC;
10118 } else {
10119 /* set/reset */
Denys Vlasenko3ea2e822009-10-09 20:59:04 +020010120 t = strtoul(value, NULL, 10);
10121 INIT_RANDOM_T(&random_gen, (t ? t : 1), t);
Eric Andersen16767e22004-03-16 05:14:10 +000010122 }
Eric Andersenef02f822004-03-11 13:34:24 +000010123}
Eric Andersen16767e22004-03-16 05:14:10 +000010124#endif
10125
Denis Vlasenko131ae172007-02-18 13:00:19 +000010126#if ENABLE_ASH_GETOPTS
Eric Andersencb57d552001-06-28 07:25:16 +000010127static int
Eric Andersenc470f442003-07-28 09:56:35 +000010128getopts(char *optstr, char *optvar, char **optfirst, int *param_optind, int *optoff)
Eric Andersencb57d552001-06-28 07:25:16 +000010129{
10130 char *p, *q;
10131 char c = '?';
10132 int done = 0;
10133 int err = 0;
Eric Andersena48b0a32003-10-22 10:56:47 +000010134 char s[12];
10135 char **optnext;
Eric Andersencb57d552001-06-28 07:25:16 +000010136
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010137 if (*param_optind < 1)
Eric Andersena48b0a32003-10-22 10:56:47 +000010138 return 1;
10139 optnext = optfirst + *param_optind - 1;
10140
Denis Vlasenko6b06cb82008-05-15 21:30:45 +000010141 if (*param_optind <= 1 || *optoff < 0 || (int)strlen(optnext[-1]) < *optoff)
Eric Andersencb57d552001-06-28 07:25:16 +000010142 p = NULL;
10143 else
Eric Andersena48b0a32003-10-22 10:56:47 +000010144 p = optnext[-1] + *optoff;
Eric Andersencb57d552001-06-28 07:25:16 +000010145 if (p == NULL || *p == '\0') {
10146 /* Current word is done, advance */
Eric Andersencb57d552001-06-28 07:25:16 +000010147 p = *optnext;
10148 if (p == NULL || *p != '-' || *++p == '\0') {
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010149 atend:
Eric Andersencb57d552001-06-28 07:25:16 +000010150 p = NULL;
10151 done = 1;
10152 goto out;
10153 }
10154 optnext++;
Denis Vlasenko9f739442006-12-16 23:49:13 +000010155 if (LONE_DASH(p)) /* check for "--" */
Eric Andersencb57d552001-06-28 07:25:16 +000010156 goto atend;
10157 }
10158
10159 c = *p++;
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +000010160 for (q = optstr; *q != c;) {
Eric Andersencb57d552001-06-28 07:25:16 +000010161 if (*q == '\0') {
10162 if (optstr[0] == ':') {
10163 s[0] = c;
10164 s[1] = '\0';
10165 err |= setvarsafe("OPTARG", s, 0);
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010166 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000010167 fprintf(stderr, "Illegal option -%c\n", c);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010168 unsetvar("OPTARG");
Eric Andersencb57d552001-06-28 07:25:16 +000010169 }
10170 c = '?';
Eric Andersenc470f442003-07-28 09:56:35 +000010171 goto out;
Eric Andersencb57d552001-06-28 07:25:16 +000010172 }
10173 if (*++q == ':')
10174 q++;
10175 }
10176
10177 if (*++q == ':') {
10178 if (*p == '\0' && (p = *optnext) == NULL) {
10179 if (optstr[0] == ':') {
10180 s[0] = c;
10181 s[1] = '\0';
10182 err |= setvarsafe("OPTARG", s, 0);
10183 c = ':';
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010184 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000010185 fprintf(stderr, "No arg for -%c option\n", c);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010186 unsetvar("OPTARG");
Eric Andersencb57d552001-06-28 07:25:16 +000010187 c = '?';
10188 }
Eric Andersenc470f442003-07-28 09:56:35 +000010189 goto out;
Eric Andersencb57d552001-06-28 07:25:16 +000010190 }
10191
10192 if (p == *optnext)
10193 optnext++;
Eric Andersenc470f442003-07-28 09:56:35 +000010194 err |= setvarsafe("OPTARG", p, 0);
Eric Andersencb57d552001-06-28 07:25:16 +000010195 p = NULL;
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010196 } else
Eric Andersenc470f442003-07-28 09:56:35 +000010197 err |= setvarsafe("OPTARG", nullstr, 0);
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010198 out:
Eric Andersencb57d552001-06-28 07:25:16 +000010199 *optoff = p ? p - *(optnext - 1) : -1;
Eric Andersenc470f442003-07-28 09:56:35 +000010200 *param_optind = optnext - optfirst + 1;
10201 fmtstr(s, sizeof(s), "%d", *param_optind);
Eric Andersencb57d552001-06-28 07:25:16 +000010202 err |= setvarsafe("OPTIND", s, VNOFUNC);
10203 s[0] = c;
10204 s[1] = '\0';
10205 err |= setvarsafe(optvar, s, 0);
10206 if (err) {
Eric Andersenc470f442003-07-28 09:56:35 +000010207 *param_optind = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010208 *optoff = -1;
Denis Vlasenkob012b102007-02-19 22:43:01 +000010209 flush_stdout_stderr();
10210 raise_exception(EXERROR);
Eric Andersencb57d552001-06-28 07:25:16 +000010211 }
10212 return done;
10213}
Eric Andersenc470f442003-07-28 09:56:35 +000010214
10215/*
10216 * The getopts builtin. Shellparam.optnext points to the next argument
10217 * to be processed. Shellparam.optptr points to the next character to
10218 * be processed in the current argument. If shellparam.optnext is NULL,
10219 * then it's the first time getopts has been called.
10220 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010221static int FAST_FUNC
Eric Andersenc470f442003-07-28 09:56:35 +000010222getoptscmd(int argc, char **argv)
10223{
10224 char **optbase;
10225
10226 if (argc < 3)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +000010227 ash_msg_and_raise_error("usage: getopts optstring var [arg]");
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010228 if (argc == 3) {
Eric Andersenc470f442003-07-28 09:56:35 +000010229 optbase = shellparam.p;
10230 if (shellparam.optind > shellparam.nparam + 1) {
10231 shellparam.optind = 1;
10232 shellparam.optoff = -1;
10233 }
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010234 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000010235 optbase = &argv[3];
10236 if (shellparam.optind > argc - 2) {
10237 shellparam.optind = 1;
10238 shellparam.optoff = -1;
10239 }
10240 }
10241
10242 return getopts(argv[1], argv[2], optbase, &shellparam.optind,
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010243 &shellparam.optoff);
Eric Andersenc470f442003-07-28 09:56:35 +000010244}
Denis Vlasenko131ae172007-02-18 13:00:19 +000010245#endif /* ASH_GETOPTS */
Eric Andersencb57d552001-06-28 07:25:16 +000010246
Eric Andersencb57d552001-06-28 07:25:16 +000010247
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010248/* ============ Shell parser */
Eric Andersencb57d552001-06-28 07:25:16 +000010249
Denis Vlasenkob07a4962008-06-22 13:16:23 +000010250struct heredoc {
10251 struct heredoc *next; /* next here document in list */
10252 union node *here; /* redirection node */
10253 char *eofmark; /* string indicating end of input */
10254 smallint striptabs; /* if set, strip leading tabs */
10255};
10256
10257static smallint tokpushback; /* last token pushed back */
10258static smallint parsebackquote; /* nonzero if we are inside backquotes */
10259static smallint quoteflag; /* set if (part of) last token was quoted */
10260static token_id_t lasttoken; /* last token read (integer id Txxx) */
10261static struct heredoc *heredoclist; /* list of here documents to read */
10262static char *wordtext; /* text of last word returned by readtoken */
10263static struct nodelist *backquotelist;
10264static union node *redirnode;
10265static struct heredoc *heredoc;
Denis Vlasenko99eb8502007-02-23 21:09:49 +000010266
Denys Vlasenkoa0ec4f52010-05-20 12:50:42 +020010267static const char *
10268tokname(char *buf, int tok)
10269{
10270 if (tok < TSEMI)
10271 return tokname_array[tok] + 1;
10272 sprintf(buf, "\"%s\"", tokname_array[tok] + 1);
10273 return buf;
10274}
10275
10276/* raise_error_unexpected_syntax:
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010277 * Called when an unexpected token is read during the parse. The argument
10278 * is the token that is expected, or -1 if more than one type of token can
10279 * occur at this point.
10280 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000010281static void raise_error_unexpected_syntax(int) NORETURN;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010282static void
10283raise_error_unexpected_syntax(int token)
10284{
10285 char msg[64];
Denys Vlasenkoa0ec4f52010-05-20 12:50:42 +020010286 char buf[16];
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010287 int l;
10288
Denys Vlasenkoa0ec4f52010-05-20 12:50:42 +020010289 l = sprintf(msg, "unexpected %s", tokname(buf, lasttoken));
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010290 if (token >= 0)
Denys Vlasenkoa0ec4f52010-05-20 12:50:42 +020010291 sprintf(msg + l, " (expecting %s)", tokname(buf, token));
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010292 raise_error_syntax(msg);
10293 /* NOTREACHED */
10294}
Eric Andersencb57d552001-06-28 07:25:16 +000010295
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010296#define EOFMARKLEN 79
Eric Andersencb57d552001-06-28 07:25:16 +000010297
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010298/* parsing is heavily cross-recursive, need these forward decls */
10299static union node *andor(void);
10300static union node *pipeline(void);
10301static union node *parse_command(void);
10302static void parseheredoc(void);
10303static char peektoken(void);
10304static int readtoken(void);
Eric Andersencb57d552001-06-28 07:25:16 +000010305
Eric Andersenc470f442003-07-28 09:56:35 +000010306static union node *
10307list(int nlflag)
Eric Andersencb57d552001-06-28 07:25:16 +000010308{
10309 union node *n1, *n2, *n3;
10310 int tok;
10311
Eric Andersenc470f442003-07-28 09:56:35 +000010312 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10313 if (nlflag == 2 && peektoken())
Eric Andersencb57d552001-06-28 07:25:16 +000010314 return NULL;
10315 n1 = NULL;
10316 for (;;) {
10317 n2 = andor();
10318 tok = readtoken();
10319 if (tok == TBACKGND) {
Eric Andersenc470f442003-07-28 09:56:35 +000010320 if (n2->type == NPIPE) {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +000010321 n2->npipe.pipe_backgnd = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010322 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000010323 if (n2->type != NREDIR) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010324 n3 = stzalloc(sizeof(struct nredir));
Eric Andersenc470f442003-07-28 09:56:35 +000010325 n3->nredir.n = n2;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010326 /*n3->nredir.redirect = NULL; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000010327 n2 = n3;
10328 }
10329 n2->type = NBACKGND;
Eric Andersencb57d552001-06-28 07:25:16 +000010330 }
10331 }
10332 if (n1 == NULL) {
10333 n1 = n2;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010334 } else {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010335 n3 = stzalloc(sizeof(struct nbinary));
Eric Andersencb57d552001-06-28 07:25:16 +000010336 n3->type = NSEMI;
10337 n3->nbinary.ch1 = n1;
10338 n3->nbinary.ch2 = n2;
10339 n1 = n3;
10340 }
10341 switch (tok) {
10342 case TBACKGND:
10343 case TSEMI:
10344 tok = readtoken();
10345 /* fall through */
10346 case TNL:
10347 if (tok == TNL) {
10348 parseheredoc();
Eric Andersenc470f442003-07-28 09:56:35 +000010349 if (nlflag == 1)
Eric Andersencb57d552001-06-28 07:25:16 +000010350 return n1;
10351 } else {
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010352 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010353 }
Eric Andersenc470f442003-07-28 09:56:35 +000010354 checkkwd = CHKNL | CHKKWD | CHKALIAS;
Manuel Novoa III 16815d42001-08-10 19:36:07 +000010355 if (peektoken())
Eric Andersencb57d552001-06-28 07:25:16 +000010356 return n1;
10357 break;
10358 case TEOF:
10359 if (heredoclist)
10360 parseheredoc();
10361 else
Eric Andersenc470f442003-07-28 09:56:35 +000010362 pungetc(); /* push back EOF on input */
Eric Andersencb57d552001-06-28 07:25:16 +000010363 return n1;
10364 default:
Eric Andersenc470f442003-07-28 09:56:35 +000010365 if (nlflag == 1)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010366 raise_error_unexpected_syntax(-1);
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010367 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010368 return n1;
10369 }
10370 }
10371}
10372
Eric Andersenc470f442003-07-28 09:56:35 +000010373static union node *
10374andor(void)
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010375{
Eric Andersencb57d552001-06-28 07:25:16 +000010376 union node *n1, *n2, *n3;
10377 int t;
10378
Eric Andersencb57d552001-06-28 07:25:16 +000010379 n1 = pipeline();
10380 for (;;) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010381 t = readtoken();
10382 if (t == TAND) {
Eric Andersencb57d552001-06-28 07:25:16 +000010383 t = NAND;
10384 } else if (t == TOR) {
10385 t = NOR;
10386 } else {
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010387 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010388 return n1;
10389 }
Eric Andersenc470f442003-07-28 09:56:35 +000010390 checkkwd = CHKNL | CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010391 n2 = pipeline();
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010392 n3 = stzalloc(sizeof(struct nbinary));
Eric Andersencb57d552001-06-28 07:25:16 +000010393 n3->type = t;
10394 n3->nbinary.ch1 = n1;
10395 n3->nbinary.ch2 = n2;
10396 n1 = n3;
10397 }
10398}
10399
Eric Andersenc470f442003-07-28 09:56:35 +000010400static union node *
10401pipeline(void)
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010402{
Eric Andersencb57d552001-06-28 07:25:16 +000010403 union node *n1, *n2, *pipenode;
10404 struct nodelist *lp, *prev;
10405 int negate;
10406
10407 negate = 0;
10408 TRACE(("pipeline: entered\n"));
10409 if (readtoken() == TNOT) {
10410 negate = !negate;
Eric Andersenc470f442003-07-28 09:56:35 +000010411 checkkwd = CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010412 } else
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010413 tokpushback = 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010414 n1 = parse_command();
Eric Andersencb57d552001-06-28 07:25:16 +000010415 if (readtoken() == TPIPE) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010416 pipenode = stzalloc(sizeof(struct npipe));
Eric Andersencb57d552001-06-28 07:25:16 +000010417 pipenode->type = NPIPE;
Denis Vlasenko2dc240c2008-07-24 06:07:50 +000010418 /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010419 lp = stzalloc(sizeof(struct nodelist));
Eric Andersencb57d552001-06-28 07:25:16 +000010420 pipenode->npipe.cmdlist = lp;
10421 lp->n = n1;
10422 do {
10423 prev = lp;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010424 lp = stzalloc(sizeof(struct nodelist));
Eric Andersenc470f442003-07-28 09:56:35 +000010425 checkkwd = CHKNL | CHKKWD | CHKALIAS;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010426 lp->n = parse_command();
Eric Andersencb57d552001-06-28 07:25:16 +000010427 prev->next = lp;
10428 } while (readtoken() == TPIPE);
10429 lp->next = NULL;
10430 n1 = pipenode;
10431 }
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010432 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010433 if (negate) {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010434 n2 = stzalloc(sizeof(struct nnot));
Eric Andersencb57d552001-06-28 07:25:16 +000010435 n2->type = NNOT;
10436 n2->nnot.com = n1;
10437 return n2;
Denis Vlasenko2da584f2007-02-19 22:44:05 +000010438 }
10439 return n1;
Eric Andersencb57d552001-06-28 07:25:16 +000010440}
10441
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010442static union node *
10443makename(void)
10444{
10445 union node *n;
10446
Denis Vlasenko597906c2008-02-20 16:38:54 +000010447 n = stzalloc(sizeof(struct narg));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010448 n->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010449 /*n->narg.next = NULL; - stzalloc did it */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010450 n->narg.text = wordtext;
10451 n->narg.backquote = backquotelist;
10452 return n;
10453}
10454
10455static void
10456fixredir(union node *n, const char *text, int err)
10457{
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000010458 int fd;
10459
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010460 TRACE(("Fix redir %s %d\n", text, err));
10461 if (!err)
10462 n->ndup.vname = NULL;
10463
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000010464 fd = bb_strtou(text, NULL, 10);
10465 if (!errno && fd >= 0)
10466 n->ndup.dupfd = fd;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010467 else if (LONE_DASH(text))
10468 n->ndup.dupfd = -1;
10469 else {
10470 if (err)
Denis Vlasenko559691a2008-10-05 18:39:31 +000010471 raise_error_syntax("bad fd number");
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010472 n->ndup.vname = makename();
10473 }
10474}
10475
10476/*
10477 * Returns true if the text contains nothing to expand (no dollar signs
10478 * or backquotes).
10479 */
10480static int
Denis Vlasenko68819d12008-12-15 11:26:36 +000010481noexpand(const char *text)
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010482{
Denys Vlasenkocd716832009-11-28 22:14:02 +010010483 unsigned char c;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010484
Denys Vlasenkocd716832009-11-28 22:14:02 +010010485 while ((c = *text++) != '\0') {
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010486 if (c == CTLQUOTEMARK)
10487 continue;
10488 if (c == CTLESC)
Denys Vlasenkocd716832009-11-28 22:14:02 +010010489 text++;
Denys Vlasenko76bc2d62009-11-29 01:37:46 +010010490 else if (SIT(c, BASESYNTAX) == CCTL)
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010491 return 0;
10492 }
10493 return 1;
10494}
10495
10496static void
10497parsefname(void)
10498{
10499 union node *n = redirnode;
10500
10501 if (readtoken() != TWORD)
10502 raise_error_unexpected_syntax(-1);
10503 if (n->type == NHERE) {
10504 struct heredoc *here = heredoc;
10505 struct heredoc *p;
10506 int i;
10507
10508 if (quoteflag == 0)
10509 n->type = NXHERE;
10510 TRACE(("Here document %d\n", n->type));
10511 if (!noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
Denis Vlasenko559691a2008-10-05 18:39:31 +000010512 raise_error_syntax("illegal eof marker for << redirection");
Denys Vlasenkob6c84342009-08-29 20:23:20 +020010513 rmescapes(wordtext, 0);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010514 here->eofmark = wordtext;
10515 here->next = NULL;
10516 if (heredoclist == NULL)
10517 heredoclist = here;
10518 else {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010519 for (p = heredoclist; p->next; p = p->next)
10520 continue;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010521 p->next = here;
10522 }
10523 } else if (n->type == NTOFD || n->type == NFROMFD) {
10524 fixredir(n, wordtext, 0);
10525 } else {
10526 n->nfile.fname = makename();
10527 }
10528}
Eric Andersencb57d552001-06-28 07:25:16 +000010529
Eric Andersenc470f442003-07-28 09:56:35 +000010530static union node *
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010531simplecmd(void)
10532{
10533 union node *args, **app;
10534 union node *n = NULL;
10535 union node *vars, **vpp;
10536 union node **rpp, *redir;
10537 int savecheckkwd;
Denis Vlasenko80591b02008-03-25 07:49:43 +000010538#if ENABLE_ASH_BASH_COMPAT
10539 smallint double_brackets_flag = 0;
10540#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010541
10542 args = NULL;
10543 app = &args;
10544 vars = NULL;
10545 vpp = &vars;
10546 redir = NULL;
10547 rpp = &redir;
10548
10549 savecheckkwd = CHKALIAS;
10550 for (;;) {
Denis Vlasenko80591b02008-03-25 07:49:43 +000010551 int t;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010552 checkkwd = savecheckkwd;
Denis Vlasenko80591b02008-03-25 07:49:43 +000010553 t = readtoken();
10554 switch (t) {
10555#if ENABLE_ASH_BASH_COMPAT
10556 case TAND: /* "&&" */
10557 case TOR: /* "||" */
10558 if (!double_brackets_flag) {
10559 tokpushback = 1;
10560 goto out;
10561 }
10562 wordtext = (char *) (t == TAND ? "-a" : "-o");
10563#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010564 case TWORD:
Denis Vlasenko597906c2008-02-20 16:38:54 +000010565 n = stzalloc(sizeof(struct narg));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010566 n->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010567 /*n->narg.next = NULL; - stzalloc did it */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010568 n->narg.text = wordtext;
Denis Vlasenko80591b02008-03-25 07:49:43 +000010569#if ENABLE_ASH_BASH_COMPAT
10570 if (strcmp("[[", wordtext) == 0)
10571 double_brackets_flag = 1;
10572 else if (strcmp("]]", wordtext) == 0)
10573 double_brackets_flag = 0;
10574#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010575 n->narg.backquote = backquotelist;
10576 if (savecheckkwd && isassignment(wordtext)) {
10577 *vpp = n;
10578 vpp = &n->narg.next;
10579 } else {
10580 *app = n;
10581 app = &n->narg.next;
10582 savecheckkwd = 0;
10583 }
10584 break;
10585 case TREDIR:
10586 *rpp = n = redirnode;
10587 rpp = &n->nfile.next;
10588 parsefname(); /* read name of redirection file */
10589 break;
10590 case TLP:
10591 if (args && app == &args->narg.next
10592 && !vars && !redir
10593 ) {
10594 struct builtincmd *bcmd;
10595 const char *name;
10596
10597 /* We have a function */
10598 if (readtoken() != TRP)
10599 raise_error_unexpected_syntax(TRP);
10600 name = n->narg.text;
10601 if (!goodname(name)
10602 || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
10603 ) {
Denis Vlasenko559691a2008-10-05 18:39:31 +000010604 raise_error_syntax("bad function name");
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010605 }
10606 n->type = NDEFUN;
10607 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10608 n->narg.next = parse_command();
10609 return n;
10610 }
10611 /* fall through */
10612 default:
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010613 tokpushback = 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010614 goto out;
10615 }
10616 }
10617 out:
10618 *app = NULL;
10619 *vpp = NULL;
10620 *rpp = NULL;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010621 n = stzalloc(sizeof(struct ncmd));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010622 n->type = NCMD;
10623 n->ncmd.args = args;
10624 n->ncmd.assign = vars;
10625 n->ncmd.redirect = redir;
10626 return n;
10627}
10628
10629static union node *
10630parse_command(void)
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010631{
Eric Andersencb57d552001-06-28 07:25:16 +000010632 union node *n1, *n2;
10633 union node *ap, **app;
10634 union node *cp, **cpp;
10635 union node *redir, **rpp;
Eric Andersenc470f442003-07-28 09:56:35 +000010636 union node **rpp2;
Eric Andersencb57d552001-06-28 07:25:16 +000010637 int t;
10638
10639 redir = NULL;
Eric Andersenc470f442003-07-28 09:56:35 +000010640 rpp2 = &redir;
Eric Andersen88cec252001-09-06 17:35:20 +000010641
Eric Andersencb57d552001-06-28 07:25:16 +000010642 switch (readtoken()) {
Eric Andersenc470f442003-07-28 09:56:35 +000010643 default:
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010644 raise_error_unexpected_syntax(-1);
Eric Andersenc470f442003-07-28 09:56:35 +000010645 /* NOTREACHED */
Eric Andersencb57d552001-06-28 07:25:16 +000010646 case TIF:
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010647 n1 = stzalloc(sizeof(struct nif));
Eric Andersencb57d552001-06-28 07:25:16 +000010648 n1->type = NIF;
10649 n1->nif.test = list(0);
10650 if (readtoken() != TTHEN)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010651 raise_error_unexpected_syntax(TTHEN);
Eric Andersencb57d552001-06-28 07:25:16 +000010652 n1->nif.ifpart = list(0);
10653 n2 = n1;
10654 while (readtoken() == TELIF) {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010655 n2->nif.elsepart = stzalloc(sizeof(struct nif));
Eric Andersencb57d552001-06-28 07:25:16 +000010656 n2 = n2->nif.elsepart;
10657 n2->type = NIF;
10658 n2->nif.test = list(0);
10659 if (readtoken() != TTHEN)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010660 raise_error_unexpected_syntax(TTHEN);
Eric Andersencb57d552001-06-28 07:25:16 +000010661 n2->nif.ifpart = list(0);
10662 }
10663 if (lasttoken == TELSE)
10664 n2->nif.elsepart = list(0);
10665 else {
10666 n2->nif.elsepart = NULL;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010667 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010668 }
Eric Andersenc470f442003-07-28 09:56:35 +000010669 t = TFI;
Eric Andersencb57d552001-06-28 07:25:16 +000010670 break;
10671 case TWHILE:
Eric Andersenc470f442003-07-28 09:56:35 +000010672 case TUNTIL: {
Eric Andersencb57d552001-06-28 07:25:16 +000010673 int got;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010674 n1 = stzalloc(sizeof(struct nbinary));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010675 n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
Eric Andersencb57d552001-06-28 07:25:16 +000010676 n1->nbinary.ch1 = list(0);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010677 got = readtoken();
10678 if (got != TDO) {
Denys Vlasenkoa0ec4f52010-05-20 12:50:42 +020010679 TRACE(("expecting DO got '%s' %s\n", tokname_array[got] + 1,
Denis Vlasenko131ae172007-02-18 13:00:19 +000010680 got == TWORD ? wordtext : ""));
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010681 raise_error_unexpected_syntax(TDO);
Eric Andersencb57d552001-06-28 07:25:16 +000010682 }
10683 n1->nbinary.ch2 = list(0);
Eric Andersenc470f442003-07-28 09:56:35 +000010684 t = TDONE;
Eric Andersencb57d552001-06-28 07:25:16 +000010685 break;
10686 }
10687 case TFOR:
Denis Vlasenko2dc240c2008-07-24 06:07:50 +000010688 if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
Denis Vlasenko559691a2008-10-05 18:39:31 +000010689 raise_error_syntax("bad for loop variable");
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010690 n1 = stzalloc(sizeof(struct nfor));
Eric Andersencb57d552001-06-28 07:25:16 +000010691 n1->type = NFOR;
10692 n1->nfor.var = wordtext;
Eric Andersenc470f442003-07-28 09:56:35 +000010693 checkkwd = CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010694 if (readtoken() == TIN) {
10695 app = &ap;
10696 while (readtoken() == TWORD) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010697 n2 = stzalloc(sizeof(struct narg));
Eric Andersencb57d552001-06-28 07:25:16 +000010698 n2->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010699 /*n2->narg.next = NULL; - stzalloc did it */
Eric Andersencb57d552001-06-28 07:25:16 +000010700 n2->narg.text = wordtext;
10701 n2->narg.backquote = backquotelist;
10702 *app = n2;
10703 app = &n2->narg.next;
10704 }
10705 *app = NULL;
10706 n1->nfor.args = ap;
10707 if (lasttoken != TNL && lasttoken != TSEMI)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010708 raise_error_unexpected_syntax(-1);
Eric Andersencb57d552001-06-28 07:25:16 +000010709 } else {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010710 n2 = stzalloc(sizeof(struct narg));
Eric Andersencb57d552001-06-28 07:25:16 +000010711 n2->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010712 /*n2->narg.next = NULL; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000010713 n2->narg.text = (char *)dolatstr;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010714 /*n2->narg.backquote = NULL;*/
Eric Andersencb57d552001-06-28 07:25:16 +000010715 n1->nfor.args = n2;
10716 /*
10717 * Newline or semicolon here is optional (but note
10718 * that the original Bourne shell only allowed NL).
10719 */
10720 if (lasttoken != TNL && lasttoken != TSEMI)
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010721 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010722 }
Eric Andersenc470f442003-07-28 09:56:35 +000010723 checkkwd = CHKNL | CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010724 if (readtoken() != TDO)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010725 raise_error_unexpected_syntax(TDO);
Eric Andersencb57d552001-06-28 07:25:16 +000010726 n1->nfor.body = list(0);
Eric Andersenc470f442003-07-28 09:56:35 +000010727 t = TDONE;
Eric Andersencb57d552001-06-28 07:25:16 +000010728 break;
10729 case TCASE:
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010730 n1 = stzalloc(sizeof(struct ncase));
Eric Andersencb57d552001-06-28 07:25:16 +000010731 n1->type = NCASE;
10732 if (readtoken() != TWORD)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010733 raise_error_unexpected_syntax(TWORD);
Denis Vlasenko597906c2008-02-20 16:38:54 +000010734 n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
Eric Andersencb57d552001-06-28 07:25:16 +000010735 n2->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010736 /*n2->narg.next = NULL; - stzalloc did it */
Eric Andersencb57d552001-06-28 07:25:16 +000010737 n2->narg.text = wordtext;
10738 n2->narg.backquote = backquotelist;
Eric Andersencb57d552001-06-28 07:25:16 +000010739 do {
Eric Andersenc470f442003-07-28 09:56:35 +000010740 checkkwd = CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010741 } while (readtoken() == TNL);
10742 if (lasttoken != TIN)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010743 raise_error_unexpected_syntax(TIN);
Eric Andersencb57d552001-06-28 07:25:16 +000010744 cpp = &n1->ncase.cases;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010745 next_case:
Eric Andersenc470f442003-07-28 09:56:35 +000010746 checkkwd = CHKNL | CHKKWD;
10747 t = readtoken();
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010748 while (t != TESAC) {
Eric Andersencb57d552001-06-28 07:25:16 +000010749 if (lasttoken == TLP)
10750 readtoken();
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010751 *cpp = cp = stzalloc(sizeof(struct nclist));
Eric Andersencb57d552001-06-28 07:25:16 +000010752 cp->type = NCLIST;
10753 app = &cp->nclist.pattern;
10754 for (;;) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010755 *app = ap = stzalloc(sizeof(struct narg));
Eric Andersencb57d552001-06-28 07:25:16 +000010756 ap->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010757 /*ap->narg.next = NULL; - stzalloc did it */
Eric Andersencb57d552001-06-28 07:25:16 +000010758 ap->narg.text = wordtext;
10759 ap->narg.backquote = backquotelist;
Eric Andersenc470f442003-07-28 09:56:35 +000010760 if (readtoken() != TPIPE)
Eric Andersencb57d552001-06-28 07:25:16 +000010761 break;
10762 app = &ap->narg.next;
10763 readtoken();
10764 }
Denis Vlasenko597906c2008-02-20 16:38:54 +000010765 //ap->narg.next = NULL;
Eric Andersencb57d552001-06-28 07:25:16 +000010766 if (lasttoken != TRP)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010767 raise_error_unexpected_syntax(TRP);
Eric Andersenc470f442003-07-28 09:56:35 +000010768 cp->nclist.body = list(2);
Eric Andersencb57d552001-06-28 07:25:16 +000010769
Eric Andersenc470f442003-07-28 09:56:35 +000010770 cpp = &cp->nclist.next;
10771
10772 checkkwd = CHKNL | CHKKWD;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010773 t = readtoken();
10774 if (t != TESAC) {
Eric Andersencb57d552001-06-28 07:25:16 +000010775 if (t != TENDCASE)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010776 raise_error_unexpected_syntax(TENDCASE);
10777 goto next_case;
Eric Andersencb57d552001-06-28 07:25:16 +000010778 }
Eric Andersenc470f442003-07-28 09:56:35 +000010779 }
Eric Andersencb57d552001-06-28 07:25:16 +000010780 *cpp = NULL;
Eric Andersenc470f442003-07-28 09:56:35 +000010781 goto redir;
Eric Andersencb57d552001-06-28 07:25:16 +000010782 case TLP:
Denis Vlasenko597906c2008-02-20 16:38:54 +000010783 n1 = stzalloc(sizeof(struct nredir));
Eric Andersencb57d552001-06-28 07:25:16 +000010784 n1->type = NSUBSHELL;
10785 n1->nredir.n = list(0);
Denis Vlasenko597906c2008-02-20 16:38:54 +000010786 /*n1->nredir.redirect = NULL; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000010787 t = TRP;
Eric Andersencb57d552001-06-28 07:25:16 +000010788 break;
10789 case TBEGIN:
10790 n1 = list(0);
Eric Andersenc470f442003-07-28 09:56:35 +000010791 t = TEND;
Eric Andersencb57d552001-06-28 07:25:16 +000010792 break;
Eric Andersencb57d552001-06-28 07:25:16 +000010793 case TWORD:
Eric Andersenc470f442003-07-28 09:56:35 +000010794 case TREDIR:
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010795 tokpushback = 1;
Eric Andersenc470f442003-07-28 09:56:35 +000010796 return simplecmd();
Eric Andersencb57d552001-06-28 07:25:16 +000010797 }
10798
Eric Andersenc470f442003-07-28 09:56:35 +000010799 if (readtoken() != t)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010800 raise_error_unexpected_syntax(t);
Eric Andersenc470f442003-07-28 09:56:35 +000010801
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010802 redir:
Eric Andersencb57d552001-06-28 07:25:16 +000010803 /* Now check for redirection which may follow command */
Eric Andersenc470f442003-07-28 09:56:35 +000010804 checkkwd = CHKKWD | CHKALIAS;
10805 rpp = rpp2;
Eric Andersencb57d552001-06-28 07:25:16 +000010806 while (readtoken() == TREDIR) {
10807 *rpp = n2 = redirnode;
10808 rpp = &n2->nfile.next;
10809 parsefname();
10810 }
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010811 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010812 *rpp = NULL;
10813 if (redir) {
10814 if (n1->type != NSUBSHELL) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010815 n2 = stzalloc(sizeof(struct nredir));
Eric Andersencb57d552001-06-28 07:25:16 +000010816 n2->type = NREDIR;
10817 n2->nredir.n = n1;
10818 n1 = n2;
10819 }
10820 n1->nredir.redirect = redir;
10821 }
Eric Andersencb57d552001-06-28 07:25:16 +000010822 return n1;
10823}
10824
Denis Vlasenkoef527f52008-06-23 01:52:30 +000010825#if ENABLE_ASH_BASH_COMPAT
10826static int decode_dollar_squote(void)
10827{
10828 static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
10829 int c, cnt;
10830 char *p;
10831 char buf[4];
10832
10833 c = pgetc();
10834 p = strchr(C_escapes, c);
10835 if (p) {
10836 buf[0] = c;
10837 p = buf;
10838 cnt = 3;
10839 if ((unsigned char)(c - '0') <= 7) { /* \ooo */
10840 do {
10841 c = pgetc();
10842 *++p = c;
10843 } while ((unsigned char)(c - '0') <= 7 && --cnt);
10844 pungetc();
10845 } else if (c == 'x') { /* \xHH */
10846 do {
10847 c = pgetc();
10848 *++p = c;
10849 } while (isxdigit(c) && --cnt);
10850 pungetc();
10851 if (cnt == 3) { /* \x but next char is "bad" */
10852 c = 'x';
10853 goto unrecognized;
10854 }
10855 } else { /* simple seq like \\ or \t */
10856 p++;
10857 }
10858 *p = '\0';
10859 p = buf;
10860 c = bb_process_escape_sequence((void*)&p);
10861 } else { /* unrecognized "\z": print both chars unless ' or " */
10862 if (c != '\'' && c != '"') {
10863 unrecognized:
10864 c |= 0x100; /* "please encode \, then me" */
10865 }
10866 }
10867 return c;
10868}
10869#endif
10870
Eric Andersencb57d552001-06-28 07:25:16 +000010871/*
10872 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
10873 * is not NULL, read a here document. In the latter case, eofmark is the
10874 * word which marks the end of the document and striptabs is true if
Denys Vlasenkocd716832009-11-28 22:14:02 +010010875 * leading tabs should be stripped from the document. The argument c
Eric Andersencb57d552001-06-28 07:25:16 +000010876 * is the first character of the input token or document.
10877 *
10878 * Because C does not have internal subroutines, I have simulated them
10879 * using goto's to implement the subroutine linkage. The following macros
10880 * will run code that appears at the end of readtoken1.
10881 */
Eric Andersen2870d962001-07-02 17:27:21 +000010882#define CHECKEND() {goto checkend; checkend_return:;}
10883#define PARSEREDIR() {goto parseredir; parseredir_return:;}
10884#define PARSESUB() {goto parsesub; parsesub_return:;}
10885#define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
10886#define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
10887#define PARSEARITH() {goto parsearith; parsearith_return:;}
Eric Andersencb57d552001-06-28 07:25:16 +000010888static int
Denys Vlasenkocd716832009-11-28 22:14:02 +010010889readtoken1(int c, int syntax, char *eofmark, int striptabs)
Manuel Novoa III 16815d42001-08-10 19:36:07 +000010890{
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010891 /* NB: syntax parameter fits into smallint */
Denys Vlasenkocd716832009-11-28 22:14:02 +010010892 /* c parameter is an unsigned char or PEOF or PEOA */
Eric Andersencb57d552001-06-28 07:25:16 +000010893 char *out;
10894 int len;
10895 char line[EOFMARKLEN + 1];
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010896 struct nodelist *bqlist;
10897 smallint quotef;
10898 smallint dblquote;
10899 smallint oldstyle;
10900 smallint prevsyntax; /* syntax before arithmetic */
Denis Vlasenko46a53062007-09-24 18:30:02 +000010901#if ENABLE_ASH_EXPAND_PRMT
10902 smallint pssyntax; /* we are expanding a prompt string */
10903#endif
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010904 int varnest; /* levels of variables expansion */
10905 int arinest; /* levels of arithmetic expansion */
10906 int parenlevel; /* levels of parens in arithmetic */
10907 int dqvarnest; /* levels of variables expansion within double quotes */
10908
Denis Vlasenko5e34ff22009-04-21 11:09:40 +000010909 IF_ASH_BASH_COMPAT(smallint bash_dollar_squote = 0;)
Denis Vlasenkoef527f52008-06-23 01:52:30 +000010910
Eric Andersencb57d552001-06-28 07:25:16 +000010911#if __GNUC__
10912 /* Avoid longjmp clobbering */
10913 (void) &out;
10914 (void) &quotef;
10915 (void) &dblquote;
10916 (void) &varnest;
10917 (void) &arinest;
10918 (void) &parenlevel;
10919 (void) &dqvarnest;
10920 (void) &oldstyle;
10921 (void) &prevsyntax;
10922 (void) &syntax;
10923#endif
Denis Vlasenko41eb3002008-11-28 03:42:31 +000010924 startlinno = g_parsefile->linno;
Eric Andersencb57d552001-06-28 07:25:16 +000010925 bqlist = NULL;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010926 quotef = 0;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010927 oldstyle = 0;
10928 prevsyntax = 0;
Denis Vlasenko46a53062007-09-24 18:30:02 +000010929#if ENABLE_ASH_EXPAND_PRMT
10930 pssyntax = (syntax == PSSYNTAX);
10931 if (pssyntax)
10932 syntax = DQSYNTAX;
10933#endif
10934 dblquote = (syntax == DQSYNTAX);
Eric Andersencb57d552001-06-28 07:25:16 +000010935 varnest = 0;
10936 arinest = 0;
10937 parenlevel = 0;
10938 dqvarnest = 0;
10939
10940 STARTSTACKSTR(out);
Denis Vlasenko176d49d2008-10-06 09:51:47 +000010941 loop:
10942 /* For each line, until end of word */
10943 {
Eric Andersenc470f442003-07-28 09:56:35 +000010944 CHECKEND(); /* set c to PEOF if at end of here document */
10945 for (;;) { /* until end of line or end of word */
10946 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
Denis Vlasenkobf0a2012006-12-26 10:42:51 +000010947 switch (SIT(c, syntax)) {
Eric Andersenc470f442003-07-28 09:56:35 +000010948 case CNL: /* '\n' */
Eric Andersencb57d552001-06-28 07:25:16 +000010949 if (syntax == BASESYNTAX)
Eric Andersenc470f442003-07-28 09:56:35 +000010950 goto endword; /* exit outer loop */
Eric Andersencb57d552001-06-28 07:25:16 +000010951 USTPUTC(c, out);
Denis Vlasenko41eb3002008-11-28 03:42:31 +000010952 g_parsefile->linno++;
Eric Andersencb57d552001-06-28 07:25:16 +000010953 if (doprompt)
10954 setprompt(2);
Eric Andersencb57d552001-06-28 07:25:16 +000010955 c = pgetc();
Eric Andersenc470f442003-07-28 09:56:35 +000010956 goto loop; /* continue outer loop */
Eric Andersencb57d552001-06-28 07:25:16 +000010957 case CWORD:
10958 USTPUTC(c, out);
10959 break;
10960 case CCTL:
Eric Andersenc470f442003-07-28 09:56:35 +000010961 if (eofmark == NULL || dblquote)
Eric Andersencb57d552001-06-28 07:25:16 +000010962 USTPUTC(CTLESC, out);
Denis Vlasenkoef527f52008-06-23 01:52:30 +000010963#if ENABLE_ASH_BASH_COMPAT
10964 if (c == '\\' && bash_dollar_squote) {
10965 c = decode_dollar_squote();
10966 if (c & 0x100) {
10967 USTPUTC('\\', out);
10968 c = (unsigned char)c;
10969 }
10970 }
10971#endif
Eric Andersencb57d552001-06-28 07:25:16 +000010972 USTPUTC(c, out);
10973 break;
Eric Andersenc470f442003-07-28 09:56:35 +000010974 case CBACK: /* backslash */
Denys Vlasenko2ce42e92009-11-29 02:18:13 +010010975 c = pgetc_without_PEOA();
Eric Andersencb57d552001-06-28 07:25:16 +000010976 if (c == PEOF) {
Eric Andersenc470f442003-07-28 09:56:35 +000010977 USTPUTC(CTLESC, out);
Eric Andersencb57d552001-06-28 07:25:16 +000010978 USTPUTC('\\', out);
10979 pungetc();
10980 } else if (c == '\n') {
10981 if (doprompt)
10982 setprompt(2);
Eric Andersencb57d552001-06-28 07:25:16 +000010983 } else {
Denis Vlasenko46a53062007-09-24 18:30:02 +000010984#if ENABLE_ASH_EXPAND_PRMT
10985 if (c == '$' && pssyntax) {
10986 USTPUTC(CTLESC, out);
10987 USTPUTC('\\', out);
10988 }
10989#endif
Denis Vlasenkoef527f52008-06-23 01:52:30 +000010990 if (dblquote && c != '\\'
10991 && c != '`' && c != '$'
10992 && (c != '"' || eofmark != NULL)
Eric Andersenc470f442003-07-28 09:56:35 +000010993 ) {
10994 USTPUTC(CTLESC, out);
Eric Andersencb57d552001-06-28 07:25:16 +000010995 USTPUTC('\\', out);
Eric Andersenc470f442003-07-28 09:56:35 +000010996 }
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010997 if (SIT(c, SQSYNTAX) == CCTL)
Eric Andersencb57d552001-06-28 07:25:16 +000010998 USTPUTC(CTLESC, out);
Eric Andersencb57d552001-06-28 07:25:16 +000010999 USTPUTC(c, out);
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011000 quotef = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000011001 }
11002 break;
11003 case CSQUOTE:
Eric Andersencb57d552001-06-28 07:25:16 +000011004 syntax = SQSYNTAX;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011005 quotemark:
Eric Andersenc470f442003-07-28 09:56:35 +000011006 if (eofmark == NULL) {
11007 USTPUTC(CTLQUOTEMARK, out);
11008 }
Eric Andersencb57d552001-06-28 07:25:16 +000011009 break;
11010 case CDQUOTE:
Eric Andersencb57d552001-06-28 07:25:16 +000011011 syntax = DQSYNTAX;
11012 dblquote = 1;
Eric Andersenc470f442003-07-28 09:56:35 +000011013 goto quotemark;
Eric Andersencb57d552001-06-28 07:25:16 +000011014 case CENDQUOTE:
Denis Vlasenko5e34ff22009-04-21 11:09:40 +000011015 IF_ASH_BASH_COMPAT(bash_dollar_squote = 0;)
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011016 if (eofmark != NULL && arinest == 0
11017 && varnest == 0
11018 ) {
Eric Andersencb57d552001-06-28 07:25:16 +000011019 USTPUTC(c, out);
11020 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000011021 if (dqvarnest == 0) {
Eric Andersencb57d552001-06-28 07:25:16 +000011022 syntax = BASESYNTAX;
11023 dblquote = 0;
11024 }
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011025 quotef = 1;
Eric Andersenc470f442003-07-28 09:56:35 +000011026 goto quotemark;
Eric Andersencb57d552001-06-28 07:25:16 +000011027 }
11028 break;
Eric Andersenc470f442003-07-28 09:56:35 +000011029 case CVAR: /* '$' */
11030 PARSESUB(); /* parse substitution */
Eric Andersencb57d552001-06-28 07:25:16 +000011031 break;
Eric Andersenc470f442003-07-28 09:56:35 +000011032 case CENDVAR: /* '}' */
Eric Andersencb57d552001-06-28 07:25:16 +000011033 if (varnest > 0) {
11034 varnest--;
11035 if (dqvarnest > 0) {
11036 dqvarnest--;
11037 }
11038 USTPUTC(CTLENDVAR, out);
11039 } else {
11040 USTPUTC(c, out);
11041 }
11042 break;
Mike Frysinger98c52642009-04-02 10:02:37 +000011043#if ENABLE_SH_MATH_SUPPORT
Eric Andersenc470f442003-07-28 09:56:35 +000011044 case CLP: /* '(' in arithmetic */
Eric Andersencb57d552001-06-28 07:25:16 +000011045 parenlevel++;
11046 USTPUTC(c, out);
11047 break;
Eric Andersenc470f442003-07-28 09:56:35 +000011048 case CRP: /* ')' in arithmetic */
Eric Andersencb57d552001-06-28 07:25:16 +000011049 if (parenlevel > 0) {
11050 USTPUTC(c, out);
11051 --parenlevel;
11052 } else {
11053 if (pgetc() == ')') {
11054 if (--arinest == 0) {
11055 USTPUTC(CTLENDARI, out);
11056 syntax = prevsyntax;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011057 dblquote = (syntax == DQSYNTAX);
Eric Andersencb57d552001-06-28 07:25:16 +000011058 } else
11059 USTPUTC(')', out);
11060 } else {
11061 /*
11062 * unbalanced parens
11063 * (don't 2nd guess - no error)
11064 */
11065 pungetc();
11066 USTPUTC(')', out);
11067 }
11068 }
11069 break;
11070#endif
Eric Andersenc470f442003-07-28 09:56:35 +000011071 case CBQUOTE: /* '`' */
Eric Andersencb57d552001-06-28 07:25:16 +000011072 PARSEBACKQOLD();
11073 break;
Eric Andersen2870d962001-07-02 17:27:21 +000011074 case CENDFILE:
Eric Andersenc470f442003-07-28 09:56:35 +000011075 goto endword; /* exit outer loop */
Eric Andersencb57d552001-06-28 07:25:16 +000011076 case CIGN:
11077 break;
11078 default:
Denis Vlasenko834dee72008-10-07 09:18:30 +000011079 if (varnest == 0) {
11080#if ENABLE_ASH_BASH_COMPAT
11081 if (c == '&') {
11082 if (pgetc() == '>')
11083 c = 0x100 + '>'; /* flag &> */
11084 pungetc();
11085 }
11086#endif
Eric Andersenc470f442003-07-28 09:56:35 +000011087 goto endword; /* exit outer loop */
Denis Vlasenko834dee72008-10-07 09:18:30 +000011088 }
Denys Vlasenko2ce42e92009-11-29 02:18:13 +010011089 IF_ASH_ALIAS(if (c != PEOA))
Eric Andersencb57d552001-06-28 07:25:16 +000011090 USTPUTC(c, out);
Eric Andersen3102ac42001-07-06 04:26:23 +000011091
Eric Andersencb57d552001-06-28 07:25:16 +000011092 }
Denis Vlasenko834dee72008-10-07 09:18:30 +000011093 c = pgetc_fast();
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000011094 } /* for (;;) */
Eric Andersencb57d552001-06-28 07:25:16 +000011095 }
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011096 endword:
Mike Frysinger98c52642009-04-02 10:02:37 +000011097#if ENABLE_SH_MATH_SUPPORT
Eric Andersencb57d552001-06-28 07:25:16 +000011098 if (syntax == ARISYNTAX)
Denis Vlasenko559691a2008-10-05 18:39:31 +000011099 raise_error_syntax("missing '))'");
Eric Andersenc470f442003-07-28 09:56:35 +000011100#endif
Denis Vlasenko99eb8502007-02-23 21:09:49 +000011101 if (syntax != BASESYNTAX && !parsebackquote && eofmark == NULL)
Denis Vlasenko559691a2008-10-05 18:39:31 +000011102 raise_error_syntax("unterminated quoted string");
Eric Andersencb57d552001-06-28 07:25:16 +000011103 if (varnest != 0) {
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011104 startlinno = g_parsefile->linno;
Eric Andersenc470f442003-07-28 09:56:35 +000011105 /* { */
Denis Vlasenko559691a2008-10-05 18:39:31 +000011106 raise_error_syntax("missing '}'");
Eric Andersencb57d552001-06-28 07:25:16 +000011107 }
11108 USTPUTC('\0', out);
Eric Andersenc470f442003-07-28 09:56:35 +000011109 len = out - (char *)stackblock();
Eric Andersencb57d552001-06-28 07:25:16 +000011110 out = stackblock();
11111 if (eofmark == NULL) {
Denis Vlasenko5e34ff22009-04-21 11:09:40 +000011112 if ((c == '>' || c == '<' IF_ASH_BASH_COMPAT( || c == 0x100 + '>'))
Denis Vlasenko834dee72008-10-07 09:18:30 +000011113 && quotef == 0
11114 ) {
Denis Vlasenko559691a2008-10-05 18:39:31 +000011115 if (isdigit_str9(out)) {
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000011116 PARSEREDIR(); /* passed as params: out, c */
11117 lasttoken = TREDIR;
11118 return lasttoken;
11119 }
11120 /* else: non-number X seen, interpret it
11121 * as "NNNX>file" = "NNNX >file" */
Eric Andersencb57d552001-06-28 07:25:16 +000011122 }
Denis Vlasenkoef527f52008-06-23 01:52:30 +000011123 pungetc();
Eric Andersencb57d552001-06-28 07:25:16 +000011124 }
11125 quoteflag = quotef;
11126 backquotelist = bqlist;
11127 grabstackblock(len);
11128 wordtext = out;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011129 lasttoken = TWORD;
11130 return lasttoken;
Eric Andersencb57d552001-06-28 07:25:16 +000011131/* end of readtoken routine */
11132
Eric Andersencb57d552001-06-28 07:25:16 +000011133/*
11134 * Check to see whether we are at the end of the here document. When this
11135 * is called, c is set to the first character of the next input line. If
11136 * we are at the end of the here document, this routine sets the c to PEOF.
11137 */
Eric Andersenc470f442003-07-28 09:56:35 +000011138checkend: {
11139 if (eofmark) {
Denis Vlasenko131ae172007-02-18 13:00:19 +000011140#if ENABLE_ASH_ALIAS
Denys Vlasenko2ce42e92009-11-29 02:18:13 +010011141 if (c == PEOA)
11142 c = pgetc_without_PEOA();
Eric Andersenc470f442003-07-28 09:56:35 +000011143#endif
11144 if (striptabs) {
11145 while (c == '\t') {
Denys Vlasenko2ce42e92009-11-29 02:18:13 +010011146 c = pgetc_without_PEOA();
Eric Andersencb57d552001-06-28 07:25:16 +000011147 }
Eric Andersenc470f442003-07-28 09:56:35 +000011148 }
11149 if (c == *eofmark) {
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011150 if (pfgets(line, sizeof(line)) != NULL) {
Eric Andersenc470f442003-07-28 09:56:35 +000011151 char *p, *q;
Eric Andersencb57d552001-06-28 07:25:16 +000011152
Eric Andersenc470f442003-07-28 09:56:35 +000011153 p = line;
Denis Vlasenkof7d56652008-03-25 05:51:41 +000011154 for (q = eofmark + 1; *q && *p == *q; p++, q++)
11155 continue;
Eric Andersenc470f442003-07-28 09:56:35 +000011156 if (*p == '\n' && *q == '\0') {
11157 c = PEOF;
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011158 g_parsefile->linno++;
Eric Andersenc470f442003-07-28 09:56:35 +000011159 needprompt = doprompt;
11160 } else {
11161 pushstring(line, NULL);
Eric Andersencb57d552001-06-28 07:25:16 +000011162 }
11163 }
11164 }
11165 }
Eric Andersenc470f442003-07-28 09:56:35 +000011166 goto checkend_return;
11167}
Eric Andersencb57d552001-06-28 07:25:16 +000011168
Eric Andersencb57d552001-06-28 07:25:16 +000011169/*
11170 * Parse a redirection operator. The variable "out" points to a string
11171 * specifying the fd to be redirected. The variable "c" contains the
11172 * first character of the redirection operator.
11173 */
Eric Andersenc470f442003-07-28 09:56:35 +000011174parseredir: {
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000011175 /* out is already checked to be a valid number or "" */
11176 int fd = (*out == '\0' ? -1 : atoi(out));
Eric Andersenc470f442003-07-28 09:56:35 +000011177 union node *np;
Eric Andersencb57d552001-06-28 07:25:16 +000011178
Denis Vlasenko597906c2008-02-20 16:38:54 +000011179 np = stzalloc(sizeof(struct nfile));
Eric Andersenc470f442003-07-28 09:56:35 +000011180 if (c == '>') {
11181 np->nfile.fd = 1;
11182 c = pgetc();
11183 if (c == '>')
11184 np->type = NAPPEND;
11185 else if (c == '|')
11186 np->type = NCLOBBER;
11187 else if (c == '&')
11188 np->type = NTOFD;
Denis Vlasenko559691a2008-10-05 18:39:31 +000011189 /* it also can be NTO2 (>&file), but we can't figure it out yet */
Eric Andersenc470f442003-07-28 09:56:35 +000011190 else {
11191 np->type = NTO;
11192 pungetc();
Eric Andersencb57d552001-06-28 07:25:16 +000011193 }
Denis Vlasenko834dee72008-10-07 09:18:30 +000011194 }
11195#if ENABLE_ASH_BASH_COMPAT
11196 else if (c == 0x100 + '>') { /* this flags &> redirection */
11197 np->nfile.fd = 1;
11198 pgetc(); /* this is '>', no need to check */
11199 np->type = NTO2;
11200 }
11201#endif
11202 else { /* c == '<' */
Denis Vlasenko597906c2008-02-20 16:38:54 +000011203 /*np->nfile.fd = 0; - stzalloc did it */
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011204 c = pgetc();
11205 switch (c) {
Eric Andersenc470f442003-07-28 09:56:35 +000011206 case '<':
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011207 if (sizeof(struct nfile) != sizeof(struct nhere)) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000011208 np = stzalloc(sizeof(struct nhere));
11209 /*np->nfile.fd = 0; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000011210 }
11211 np->type = NHERE;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000011212 heredoc = stzalloc(sizeof(struct heredoc));
Eric Andersenc470f442003-07-28 09:56:35 +000011213 heredoc->here = np;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011214 c = pgetc();
11215 if (c == '-') {
Eric Andersenc470f442003-07-28 09:56:35 +000011216 heredoc->striptabs = 1;
11217 } else {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000011218 /*heredoc->striptabs = 0; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000011219 pungetc();
11220 }
11221 break;
11222
11223 case '&':
11224 np->type = NFROMFD;
11225 break;
11226
11227 case '>':
11228 np->type = NFROMTO;
11229 break;
11230
11231 default:
11232 np->type = NFROM;
11233 pungetc();
11234 break;
11235 }
Eric Andersencb57d552001-06-28 07:25:16 +000011236 }
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000011237 if (fd >= 0)
11238 np->nfile.fd = fd;
Eric Andersenc470f442003-07-28 09:56:35 +000011239 redirnode = np;
11240 goto parseredir_return;
11241}
Eric Andersencb57d552001-06-28 07:25:16 +000011242
Eric Andersencb57d552001-06-28 07:25:16 +000011243/*
11244 * Parse a substitution. At this point, we have read the dollar sign
11245 * and nothing else.
11246 */
Denis Vlasenkocc571512007-02-23 21:10:35 +000011247
11248/* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
11249 * (assuming ascii char codes, as the original implementation did) */
11250#define is_special(c) \
Denis Vlasenkoef527f52008-06-23 01:52:30 +000011251 (((unsigned)(c) - 33 < 32) \
11252 && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
Eric Andersenc470f442003-07-28 09:56:35 +000011253parsesub: {
Denys Vlasenkocd716832009-11-28 22:14:02 +010011254 unsigned char subtype;
Eric Andersenc470f442003-07-28 09:56:35 +000011255 int typeloc;
11256 int flags;
11257 char *p;
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011258 static const char types[] ALIGN1 = "}-+?=";
Eric Andersencb57d552001-06-28 07:25:16 +000011259
Eric Andersenc470f442003-07-28 09:56:35 +000011260 c = pgetc();
Denys Vlasenkocd716832009-11-28 22:14:02 +010011261 if (c > 255 /* PEOA or PEOF */
Denis Vlasenkoef527f52008-06-23 01:52:30 +000011262 || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
Eric Andersenc470f442003-07-28 09:56:35 +000011263 ) {
Denis Vlasenkoef527f52008-06-23 01:52:30 +000011264#if ENABLE_ASH_BASH_COMPAT
11265 if (c == '\'')
11266 bash_dollar_squote = 1;
11267 else
11268#endif
11269 USTPUTC('$', out);
Eric Andersenc470f442003-07-28 09:56:35 +000011270 pungetc();
11271 } else if (c == '(') { /* $(command) or $((arith)) */
11272 if (pgetc() == '(') {
Mike Frysinger98c52642009-04-02 10:02:37 +000011273#if ENABLE_SH_MATH_SUPPORT
Eric Andersenc470f442003-07-28 09:56:35 +000011274 PARSEARITH();
11275#else
Mike Frysinger98a6f562008-06-09 09:38:45 +000011276 raise_error_syntax("you disabled math support for $((arith)) syntax");
Eric Andersenc470f442003-07-28 09:56:35 +000011277#endif
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000011278 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000011279 pungetc();
11280 PARSEBACKQNEW();
11281 }
11282 } else {
11283 USTPUTC(CTLVAR, out);
11284 typeloc = out - (char *)stackblock();
11285 USTPUTC(VSNORMAL, out);
11286 subtype = VSNORMAL;
11287 if (c == '{') {
11288 c = pgetc();
11289 if (c == '#') {
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011290 c = pgetc();
11291 if (c == '}')
Eric Andersenc470f442003-07-28 09:56:35 +000011292 c = '#';
11293 else
11294 subtype = VSLENGTH;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011295 } else
Eric Andersenc470f442003-07-28 09:56:35 +000011296 subtype = 0;
11297 }
Denys Vlasenkocd716832009-11-28 22:14:02 +010011298 if (c <= 255 /* not PEOA or PEOF */ && is_name(c)) {
Eric Andersenc470f442003-07-28 09:56:35 +000011299 do {
11300 STPUTC(c, out);
Eric Andersencb57d552001-06-28 07:25:16 +000011301 c = pgetc();
Denys Vlasenkocd716832009-11-28 22:14:02 +010011302 } while (c <= 255 /* not PEOA or PEOF */ && is_in_name(c));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011303 } else if (isdigit(c)) {
Eric Andersenc470f442003-07-28 09:56:35 +000011304 do {
11305 STPUTC(c, out);
11306 c = pgetc();
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011307 } while (isdigit(c));
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011308 } else if (is_special(c)) {
Eric Andersenc470f442003-07-28 09:56:35 +000011309 USTPUTC(c, out);
11310 c = pgetc();
Denis Vlasenko559691a2008-10-05 18:39:31 +000011311 } else {
11312 badsub:
11313 raise_error_syntax("bad substitution");
11314 }
Cristian Ionescu-Idbohrn301f5ec2009-10-05 02:07:23 +020011315 if (c != '}' && subtype == VSLENGTH)
11316 goto badsub;
Eric Andersencb57d552001-06-28 07:25:16 +000011317
Eric Andersenc470f442003-07-28 09:56:35 +000011318 STPUTC('=', out);
11319 flags = 0;
11320 if (subtype == 0) {
11321 switch (c) {
11322 case ':':
Eric Andersenc470f442003-07-28 09:56:35 +000011323 c = pgetc();
Denis Vlasenko92e13c22008-03-25 01:17:40 +000011324#if ENABLE_ASH_BASH_COMPAT
11325 if (c == ':' || c == '$' || isdigit(c)) {
11326 pungetc();
11327 subtype = VSSUBSTR;
11328 break;
11329 }
11330#endif
11331 flags = VSNUL;
Eric Andersenc470f442003-07-28 09:56:35 +000011332 /*FALLTHROUGH*/
11333 default:
11334 p = strchr(types, c);
11335 if (p == NULL)
11336 goto badsub;
11337 subtype = p - types + VSNORMAL;
11338 break;
11339 case '%':
Denis Vlasenko92e13c22008-03-25 01:17:40 +000011340 case '#': {
11341 int cc = c;
11342 subtype = c == '#' ? VSTRIMLEFT : VSTRIMRIGHT;
11343 c = pgetc();
11344 if (c == cc)
11345 subtype++;
11346 else
11347 pungetc();
11348 break;
11349 }
11350#if ENABLE_ASH_BASH_COMPAT
11351 case '/':
11352 subtype = VSREPLACE;
11353 c = pgetc();
11354 if (c == '/')
11355 subtype++; /* VSREPLACEALL */
11356 else
11357 pungetc();
11358 break;
11359#endif
Eric Andersencb57d552001-06-28 07:25:16 +000011360 }
Eric Andersenc470f442003-07-28 09:56:35 +000011361 } else {
11362 pungetc();
11363 }
11364 if (dblquote || arinest)
11365 flags |= VSQUOTE;
Denys Vlasenkocd716832009-11-28 22:14:02 +010011366 ((unsigned char *)stackblock())[typeloc] = subtype | flags;
Eric Andersenc470f442003-07-28 09:56:35 +000011367 if (subtype != VSNORMAL) {
11368 varnest++;
11369 if (dblquote || arinest) {
11370 dqvarnest++;
Eric Andersencb57d552001-06-28 07:25:16 +000011371 }
11372 }
11373 }
Eric Andersenc470f442003-07-28 09:56:35 +000011374 goto parsesub_return;
11375}
Eric Andersencb57d552001-06-28 07:25:16 +000011376
Eric Andersencb57d552001-06-28 07:25:16 +000011377/*
11378 * Called to parse command substitutions. Newstyle is set if the command
11379 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
11380 * list of commands (passed by reference), and savelen is the number of
11381 * characters on the top of the stack which must be preserved.
11382 */
Eric Andersenc470f442003-07-28 09:56:35 +000011383parsebackq: {
11384 struct nodelist **nlpp;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011385 smallint savepbq;
Eric Andersenc470f442003-07-28 09:56:35 +000011386 union node *n;
11387 char *volatile str;
11388 struct jmploc jmploc;
11389 struct jmploc *volatile savehandler;
11390 size_t savelen;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011391 smallint saveprompt = 0;
11392
Eric Andersencb57d552001-06-28 07:25:16 +000011393#ifdef __GNUC__
Eric Andersenc470f442003-07-28 09:56:35 +000011394 (void) &saveprompt;
Eric Andersencb57d552001-06-28 07:25:16 +000011395#endif
Eric Andersenc470f442003-07-28 09:56:35 +000011396 savepbq = parsebackquote;
11397 if (setjmp(jmploc.loc)) {
Denis Vlasenko60818682007-09-28 22:07:23 +000011398 free(str);
Eric Andersenc470f442003-07-28 09:56:35 +000011399 parsebackquote = 0;
Denis Vlasenko2da584f2007-02-19 22:44:05 +000011400 exception_handler = savehandler;
11401 longjmp(exception_handler->loc, 1);
Eric Andersenc470f442003-07-28 09:56:35 +000011402 }
Denis Vlasenkob012b102007-02-19 22:43:01 +000011403 INT_OFF;
Eric Andersenc470f442003-07-28 09:56:35 +000011404 str = NULL;
11405 savelen = out - (char *)stackblock();
11406 if (savelen > 0) {
11407 str = ckmalloc(savelen);
11408 memcpy(str, stackblock(), savelen);
11409 }
Denis Vlasenko2da584f2007-02-19 22:44:05 +000011410 savehandler = exception_handler;
11411 exception_handler = &jmploc;
Denis Vlasenkob012b102007-02-19 22:43:01 +000011412 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +000011413 if (oldstyle) {
11414 /* We must read until the closing backquote, giving special
11415 treatment to some slashes, and then push the string and
11416 reread it as input, interpreting it normally. */
11417 char *pout;
11418 int pc;
11419 size_t psavelen;
11420 char *pstr;
11421
11422
11423 STARTSTACKSTR(pout);
11424 for (;;) {
11425 if (needprompt) {
11426 setprompt(2);
Eric Andersenc470f442003-07-28 09:56:35 +000011427 }
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011428 pc = pgetc();
11429 switch (pc) {
Eric Andersenc470f442003-07-28 09:56:35 +000011430 case '`':
11431 goto done;
11432
11433 case '\\':
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011434 pc = pgetc();
11435 if (pc == '\n') {
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011436 g_parsefile->linno++;
Eric Andersenc470f442003-07-28 09:56:35 +000011437 if (doprompt)
11438 setprompt(2);
11439 /*
11440 * If eating a newline, avoid putting
11441 * the newline into the new character
11442 * stream (via the STPUTC after the
11443 * switch).
11444 */
11445 continue;
11446 }
11447 if (pc != '\\' && pc != '`' && pc != '$'
Denys Vlasenko76bc2d62009-11-29 01:37:46 +010011448 && (!dblquote || pc != '"')
11449 ) {
Eric Andersenc470f442003-07-28 09:56:35 +000011450 STPUTC('\\', pout);
Denys Vlasenko76bc2d62009-11-29 01:37:46 +010011451 }
Denys Vlasenkocd716832009-11-28 22:14:02 +010011452 if (pc <= 255 /* not PEOA or PEOF */) {
Eric Andersenc470f442003-07-28 09:56:35 +000011453 break;
11454 }
11455 /* fall through */
11456
11457 case PEOF:
Denys Vlasenko2ce42e92009-11-29 02:18:13 +010011458 IF_ASH_ALIAS(case PEOA:)
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011459 startlinno = g_parsefile->linno;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000011460 raise_error_syntax("EOF in backquote substitution");
Eric Andersenc470f442003-07-28 09:56:35 +000011461
11462 case '\n':
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011463 g_parsefile->linno++;
Eric Andersenc470f442003-07-28 09:56:35 +000011464 needprompt = doprompt;
11465 break;
11466
11467 default:
11468 break;
11469 }
11470 STPUTC(pc, pout);
11471 }
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011472 done:
Eric Andersenc470f442003-07-28 09:56:35 +000011473 STPUTC('\0', pout);
11474 psavelen = pout - (char *)stackblock();
11475 if (psavelen > 0) {
11476 pstr = grabstackstr(pout);
11477 setinputstring(pstr);
11478 }
11479 }
11480 nlpp = &bqlist;
11481 while (*nlpp)
11482 nlpp = &(*nlpp)->next;
Denis Vlasenko597906c2008-02-20 16:38:54 +000011483 *nlpp = stzalloc(sizeof(**nlpp));
11484 /* (*nlpp)->next = NULL; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000011485 parsebackquote = oldstyle;
11486
11487 if (oldstyle) {
11488 saveprompt = doprompt;
11489 doprompt = 0;
Eric Andersencb57d552001-06-28 07:25:16 +000011490 }
11491
Eric Andersenc470f442003-07-28 09:56:35 +000011492 n = list(2);
11493
11494 if (oldstyle)
11495 doprompt = saveprompt;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011496 else if (readtoken() != TRP)
11497 raise_error_unexpected_syntax(TRP);
Eric Andersenc470f442003-07-28 09:56:35 +000011498
11499 (*nlpp)->n = n;
11500 if (oldstyle) {
11501 /*
11502 * Start reading from old file again, ignoring any pushed back
11503 * tokens left from the backquote parsing
11504 */
11505 popfile();
11506 tokpushback = 0;
11507 }
11508 while (stackblocksize() <= savelen)
11509 growstackblock();
11510 STARTSTACKSTR(out);
11511 if (str) {
11512 memcpy(out, str, savelen);
11513 STADJUST(savelen, out);
Denis Vlasenkob012b102007-02-19 22:43:01 +000011514 INT_OFF;
11515 free(str);
Eric Andersenc470f442003-07-28 09:56:35 +000011516 str = NULL;
Denis Vlasenkob012b102007-02-19 22:43:01 +000011517 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +000011518 }
11519 parsebackquote = savepbq;
Denis Vlasenko2da584f2007-02-19 22:44:05 +000011520 exception_handler = savehandler;
Eric Andersenc470f442003-07-28 09:56:35 +000011521 if (arinest || dblquote)
11522 USTPUTC(CTLBACKQ | CTLQUOTE, out);
11523 else
11524 USTPUTC(CTLBACKQ, out);
11525 if (oldstyle)
11526 goto parsebackq_oldreturn;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000011527 goto parsebackq_newreturn;
Eric Andersenc470f442003-07-28 09:56:35 +000011528}
11529
Mike Frysinger98c52642009-04-02 10:02:37 +000011530#if ENABLE_SH_MATH_SUPPORT
Eric Andersencb57d552001-06-28 07:25:16 +000011531/*
11532 * Parse an arithmetic expansion (indicate start of one and set state)
11533 */
Eric Andersenc470f442003-07-28 09:56:35 +000011534parsearith: {
Eric Andersenc470f442003-07-28 09:56:35 +000011535 if (++arinest == 1) {
11536 prevsyntax = syntax;
11537 syntax = ARISYNTAX;
11538 USTPUTC(CTLARI, out);
11539 if (dblquote)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000011540 USTPUTC('"', out);
Eric Andersenc470f442003-07-28 09:56:35 +000011541 else
Denis Vlasenkoa624c112007-02-19 22:45:43 +000011542 USTPUTC(' ', out);
Eric Andersenc470f442003-07-28 09:56:35 +000011543 } else {
11544 /*
11545 * we collapse embedded arithmetic expansion to
11546 * parenthesis, which should be equivalent
11547 */
11548 USTPUTC('(', out);
Eric Andersencb57d552001-06-28 07:25:16 +000011549 }
Eric Andersenc470f442003-07-28 09:56:35 +000011550 goto parsearith_return;
11551}
11552#endif
Eric Andersencb57d552001-06-28 07:25:16 +000011553
Eric Andersenc470f442003-07-28 09:56:35 +000011554} /* end of readtoken */
11555
Eric Andersencb57d552001-06-28 07:25:16 +000011556/*
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011557 * Read the next input token.
11558 * If the token is a word, we set backquotelist to the list of cmds in
11559 * backquotes. We set quoteflag to true if any part of the word was
11560 * quoted.
11561 * If the token is TREDIR, then we set redirnode to a structure containing
11562 * the redirection.
11563 * In all cases, the variable startlinno is set to the number of the line
11564 * on which the token starts.
11565 *
11566 * [Change comment: here documents and internal procedures]
11567 * [Readtoken shouldn't have any arguments. Perhaps we should make the
11568 * word parsing code into a separate routine. In this case, readtoken
11569 * doesn't need to have any internal procedures, but parseword does.
11570 * We could also make parseoperator in essence the main routine, and
11571 * have parseword (readtoken1?) handle both words and redirection.]
Eric Andersencb57d552001-06-28 07:25:16 +000011572 */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011573#define NEW_xxreadtoken
11574#ifdef NEW_xxreadtoken
11575/* singles must be first! */
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011576static const char xxreadtoken_chars[7] ALIGN1 = {
Denis Vlasenko834dee72008-10-07 09:18:30 +000011577 '\n', '(', ')', /* singles */
11578 '&', '|', ';', /* doubles */
11579 0
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011580};
Eric Andersencb57d552001-06-28 07:25:16 +000011581
Denis Vlasenko834dee72008-10-07 09:18:30 +000011582#define xxreadtoken_singles 3
11583#define xxreadtoken_doubles 3
11584
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011585static const char xxreadtoken_tokens[] ALIGN1 = {
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011586 TNL, TLP, TRP, /* only single occurrence allowed */
11587 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
11588 TEOF, /* corresponds to trailing nul */
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011589 TAND, TOR, TENDCASE /* if double occurrence */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011590};
11591
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011592static int
11593xxreadtoken(void)
11594{
11595 int c;
11596
11597 if (tokpushback) {
11598 tokpushback = 0;
11599 return lasttoken;
Eric Andersencb57d552001-06-28 07:25:16 +000011600 }
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011601 if (needprompt) {
11602 setprompt(2);
11603 }
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011604 startlinno = g_parsefile->linno;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011605 for (;;) { /* until token or start of word found */
Denis Vlasenko834dee72008-10-07 09:18:30 +000011606 c = pgetc_fast();
Denis Vlasenko5e34ff22009-04-21 11:09:40 +000011607 if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011608 continue;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011609
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011610 if (c == '#') {
11611 while ((c = pgetc()) != '\n' && c != PEOF)
11612 continue;
11613 pungetc();
11614 } else if (c == '\\') {
11615 if (pgetc() != '\n') {
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011616 pungetc();
Denis Vlasenko834dee72008-10-07 09:18:30 +000011617 break; /* return readtoken1(...) */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011618 }
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011619 startlinno = ++g_parsefile->linno;
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011620 if (doprompt)
11621 setprompt(2);
11622 } else {
11623 const char *p;
11624
11625 p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
11626 if (c != PEOF) {
11627 if (c == '\n') {
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011628 g_parsefile->linno++;
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011629 needprompt = doprompt;
11630 }
11631
11632 p = strchr(xxreadtoken_chars, c);
Denis Vlasenko834dee72008-10-07 09:18:30 +000011633 if (p == NULL)
11634 break; /* return readtoken1(...) */
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011635
Denis Vlasenko834dee72008-10-07 09:18:30 +000011636 if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
11637 int cc = pgetc();
11638 if (cc == c) { /* double occurrence? */
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011639 p += xxreadtoken_doubles + 1;
11640 } else {
11641 pungetc();
Denis Vlasenko834dee72008-10-07 09:18:30 +000011642#if ENABLE_ASH_BASH_COMPAT
11643 if (c == '&' && cc == '>') /* &> */
11644 break; /* return readtoken1(...) */
11645#endif
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011646 }
11647 }
11648 }
11649 lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
11650 return lasttoken;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011651 }
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011652 } /* for (;;) */
Denis Vlasenko834dee72008-10-07 09:18:30 +000011653
11654 return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011655}
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011656#else /* old xxreadtoken */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011657#define RETURN(token) return lasttoken = token
11658static int
11659xxreadtoken(void)
11660{
11661 int c;
11662
11663 if (tokpushback) {
11664 tokpushback = 0;
11665 return lasttoken;
11666 }
11667 if (needprompt) {
11668 setprompt(2);
11669 }
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011670 startlinno = g_parsefile->linno;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011671 for (;;) { /* until token or start of word found */
Denis Vlasenko834dee72008-10-07 09:18:30 +000011672 c = pgetc_fast();
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011673 switch (c) {
11674 case ' ': case '\t':
Denys Vlasenko2ce42e92009-11-29 02:18:13 +010011675 IF_ASH_ALIAS(case PEOA:)
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011676 continue;
11677 case '#':
Denis Vlasenkof7d56652008-03-25 05:51:41 +000011678 while ((c = pgetc()) != '\n' && c != PEOF)
11679 continue;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011680 pungetc();
11681 continue;
11682 case '\\':
11683 if (pgetc() == '\n') {
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011684 startlinno = ++g_parsefile->linno;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011685 if (doprompt)
11686 setprompt(2);
11687 continue;
11688 }
11689 pungetc();
11690 goto breakloop;
11691 case '\n':
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011692 g_parsefile->linno++;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011693 needprompt = doprompt;
11694 RETURN(TNL);
11695 case PEOF:
11696 RETURN(TEOF);
11697 case '&':
11698 if (pgetc() == '&')
11699 RETURN(TAND);
11700 pungetc();
11701 RETURN(TBACKGND);
11702 case '|':
11703 if (pgetc() == '|')
11704 RETURN(TOR);
11705 pungetc();
11706 RETURN(TPIPE);
11707 case ';':
11708 if (pgetc() == ';')
11709 RETURN(TENDCASE);
11710 pungetc();
11711 RETURN(TSEMI);
11712 case '(':
11713 RETURN(TLP);
11714 case ')':
11715 RETURN(TRP);
11716 default:
11717 goto breakloop;
11718 }
11719 }
11720 breakloop:
11721 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
11722#undef RETURN
11723}
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011724#endif /* old xxreadtoken */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011725
11726static int
11727readtoken(void)
11728{
11729 int t;
11730#if DEBUG
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011731 smallint alreadyseen = tokpushback;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011732#endif
11733
11734#if ENABLE_ASH_ALIAS
11735 top:
11736#endif
11737
11738 t = xxreadtoken();
11739
11740 /*
11741 * eat newlines
11742 */
11743 if (checkkwd & CHKNL) {
11744 while (t == TNL) {
11745 parseheredoc();
11746 t = xxreadtoken();
11747 }
11748 }
11749
11750 if (t != TWORD || quoteflag) {
11751 goto out;
11752 }
11753
11754 /*
11755 * check for keywords
11756 */
11757 if (checkkwd & CHKKWD) {
11758 const char *const *pp;
11759
11760 pp = findkwd(wordtext);
11761 if (pp) {
11762 lasttoken = t = pp - tokname_array;
Denys Vlasenkoa0ec4f52010-05-20 12:50:42 +020011763 TRACE(("keyword '%s' recognized\n", tokname_array[t] + 1));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011764 goto out;
11765 }
11766 }
11767
11768 if (checkkwd & CHKALIAS) {
11769#if ENABLE_ASH_ALIAS
11770 struct alias *ap;
11771 ap = lookupalias(wordtext, 1);
11772 if (ap != NULL) {
11773 if (*ap->val) {
11774 pushstring(ap->val, ap);
11775 }
11776 goto top;
11777 }
11778#endif
11779 }
11780 out:
11781 checkkwd = 0;
11782#if DEBUG
11783 if (!alreadyseen)
Denys Vlasenkoa0ec4f52010-05-20 12:50:42 +020011784 TRACE(("token '%s' %s\n", tokname_array[t] + 1, t == TWORD ? wordtext : ""));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011785 else
Denys Vlasenkoa0ec4f52010-05-20 12:50:42 +020011786 TRACE(("reread token '%s' %s\n", tokname_array[t] + 1, t == TWORD ? wordtext : ""));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011787#endif
11788 return t;
Eric Andersencb57d552001-06-28 07:25:16 +000011789}
11790
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011791static char
11792peektoken(void)
11793{
11794 int t;
11795
11796 t = readtoken();
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011797 tokpushback = 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011798 return tokname_array[t][0];
11799}
Eric Andersencb57d552001-06-28 07:25:16 +000011800
11801/*
Denys Vlasenko86e83ec2009-07-23 22:07:07 +020011802 * Read and parse a command. Returns NODE_EOF on end of file.
11803 * (NULL is a valid parse tree indicating a blank line.)
Eric Andersencb57d552001-06-28 07:25:16 +000011804 */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011805static union node *
11806parsecmd(int interact)
Eric Andersen90898442003-08-06 11:20:52 +000011807{
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011808 int t;
Eric Andersencb57d552001-06-28 07:25:16 +000011809
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011810 tokpushback = 0;
11811 doprompt = interact;
11812 if (doprompt)
11813 setprompt(doprompt);
11814 needprompt = 0;
11815 t = readtoken();
11816 if (t == TEOF)
Denys Vlasenko86e83ec2009-07-23 22:07:07 +020011817 return NODE_EOF;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011818 if (t == TNL)
11819 return NULL;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011820 tokpushback = 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011821 return list(1);
11822}
11823
11824/*
11825 * Input any here documents.
11826 */
11827static void
11828parseheredoc(void)
11829{
11830 struct heredoc *here;
11831 union node *n;
11832
11833 here = heredoclist;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000011834 heredoclist = NULL;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011835
11836 while (here) {
11837 if (needprompt) {
11838 setprompt(2);
11839 }
11840 readtoken1(pgetc(), here->here->type == NHERE? SQSYNTAX : DQSYNTAX,
11841 here->eofmark, here->striptabs);
Denis Vlasenko597906c2008-02-20 16:38:54 +000011842 n = stzalloc(sizeof(struct narg));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011843 n->narg.type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000011844 /*n->narg.next = NULL; - stzalloc did it */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011845 n->narg.text = wordtext;
11846 n->narg.backquote = backquotelist;
11847 here->here->nhere.doc = n;
11848 here = here->next;
Eric Andersencb57d552001-06-28 07:25:16 +000011849 }
Eric Andersencb57d552001-06-28 07:25:16 +000011850}
11851
11852
11853/*
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +000011854 * called by editline -- any expansions to the prompt should be added here.
Eric Andersencb57d552001-06-28 07:25:16 +000011855 */
Denis Vlasenko131ae172007-02-18 13:00:19 +000011856#if ENABLE_ASH_EXPAND_PRMT
"Vladimir N. Oleynik"bef14d72005-09-05 13:25:11 +000011857static const char *
11858expandstr(const char *ps)
11859{
11860 union node n;
11861
Denis Vlasenko5c2b8142009-03-19 01:59:59 +000011862 /* XXX Fix (char *) cast. It _is_ a bug. ps is variable's value,
11863 * and token processing _can_ alter it (delete NULs etc). */
"Vladimir N. Oleynik"bef14d72005-09-05 13:25:11 +000011864 setinputstring((char *)ps);
Denis Vlasenko46a53062007-09-24 18:30:02 +000011865 readtoken1(pgetc(), PSSYNTAX, nullstr, 0);
"Vladimir N. Oleynik"bef14d72005-09-05 13:25:11 +000011866 popfile();
11867
11868 n.narg.type = NARG;
11869 n.narg.next = NULL;
11870 n.narg.text = wordtext;
11871 n.narg.backquote = backquotelist;
11872
11873 expandarg(&n, NULL, 0);
11874 return stackblock();
11875}
11876#endif
11877
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011878/*
11879 * Execute a command or commands contained in a string.
11880 */
11881static int
11882evalstring(char *s, int mask)
Eric Andersenc470f442003-07-28 09:56:35 +000011883{
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011884 union node *n;
11885 struct stackmark smark;
11886 int skip;
11887
11888 setinputstring(s);
11889 setstackmark(&smark);
11890
11891 skip = 0;
Denys Vlasenko86e83ec2009-07-23 22:07:07 +020011892 while ((n = parsecmd(0)) != NODE_EOF) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011893 evaltree(n, 0);
11894 popstackmark(&smark);
11895 skip = evalskip;
11896 if (skip)
11897 break;
11898 }
11899 popfile();
11900
11901 skip &= mask;
11902 evalskip = skip;
11903 return skip;
Eric Andersenc470f442003-07-28 09:56:35 +000011904}
11905
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011906/*
11907 * The eval command.
11908 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011909static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000011910evalcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011911{
11912 char *p;
11913 char *concat;
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011914
Denis Vlasenko68404f12008-03-17 09:00:54 +000011915 if (argv[1]) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011916 p = argv[1];
Denis Vlasenko68404f12008-03-17 09:00:54 +000011917 argv += 2;
11918 if (argv[0]) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011919 STARTSTACKSTR(concat);
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011920 for (;;) {
11921 concat = stack_putstr(p, concat);
Denis Vlasenko68404f12008-03-17 09:00:54 +000011922 p = *argv++;
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011923 if (p == NULL)
11924 break;
11925 STPUTC(' ', concat);
11926 }
11927 STPUTC('\0', concat);
11928 p = grabstackstr(concat);
11929 }
11930 evalstring(p, ~SKIPEVAL);
11931
11932 }
11933 return exitstatus;
11934}
11935
11936/*
Denys Vlasenko285ad152009-12-04 23:02:27 +010011937 * Read and execute commands.
11938 * "Top" is nonzero for the top level command loop;
11939 * it turns on prompting if the shell is interactive.
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011940 */
11941static int
11942cmdloop(int top)
11943{
11944 union node *n;
11945 struct stackmark smark;
11946 int inter;
11947 int numeof = 0;
11948
11949 TRACE(("cmdloop(%d) called\n", top));
11950 for (;;) {
11951 int skip;
11952
11953 setstackmark(&smark);
11954#if JOBS
Denis Vlasenkob07a4962008-06-22 13:16:23 +000011955 if (doing_jobctl)
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011956 showjobs(stderr, SHOW_CHANGED);
11957#endif
11958 inter = 0;
11959 if (iflag && top) {
11960 inter++;
11961#if ENABLE_ASH_MAIL
11962 chkmail();
11963#endif
11964 }
11965 n = parsecmd(inter);
Denys Vlasenko7cee00e2009-07-24 01:08:03 +020011966#if DEBUG
11967 if (DEBUG > 2 && debug && (n != NODE_EOF))
Denys Vlasenko883cea42009-07-11 15:31:59 +020011968 showtree(n);
Denis Vlasenko135cecb2009-04-12 00:00:57 +000011969#endif
Denys Vlasenko86e83ec2009-07-23 22:07:07 +020011970 if (n == NODE_EOF) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011971 if (!top || numeof >= 50)
11972 break;
11973 if (!stoppedjobs()) {
11974 if (!Iflag)
11975 break;
11976 out2str("\nUse \"exit\" to leave shell.\n");
11977 }
11978 numeof++;
11979 } else if (nflag == 0) {
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +000011980 /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
11981 job_warning >>= 1;
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011982 numeof = 0;
11983 evaltree(n, 0);
11984 }
11985 popstackmark(&smark);
11986 skip = evalskip;
11987
11988 if (skip) {
11989 evalskip = 0;
11990 return skip & SKIPEVAL;
11991 }
11992 }
11993 return 0;
11994}
11995
Denis Vlasenko0dec6de2007-02-23 21:10:47 +000011996/*
11997 * Take commands from a file. To be compatible we should do a path
11998 * search for the file, which is necessary to find sub-commands.
11999 */
12000static char *
12001find_dot_file(char *name)
12002{
12003 char *fullname;
12004 const char *path = pathval();
12005 struct stat statb;
12006
12007 /* don't try this for absolute or relative paths */
12008 if (strchr(name, '/'))
12009 return name;
12010
Denis Vlasenko8ad78e12009-02-15 12:40:30 +000012011 /* IIRC standards do not say whether . is to be searched.
12012 * And it is even smaller this way, making it unconditional for now:
12013 */
12014 if (1) { /* ENABLE_ASH_BASH_COMPAT */
12015 fullname = name;
12016 goto try_cur_dir;
12017 }
12018
Denys Vlasenko82a6fb32009-06-14 19:42:12 +020012019 while ((fullname = path_advance(&path, name)) != NULL) {
Denis Vlasenko8ad78e12009-02-15 12:40:30 +000012020 try_cur_dir:
Denis Vlasenko0dec6de2007-02-23 21:10:47 +000012021 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
12022 /*
12023 * Don't bother freeing here, since it will
12024 * be freed by the caller.
12025 */
12026 return fullname;
12027 }
Denys Vlasenko82a6fb32009-06-14 19:42:12 +020012028 if (fullname != name)
12029 stunalloc(fullname);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +000012030 }
12031
12032 /* not found in the PATH */
12033 ash_msg_and_raise_error("%s: not found", name);
12034 /* NOTREACHED */
12035}
12036
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012037static int FAST_FUNC
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012038dotcmd(int argc, char **argv)
12039{
Denys Vlasenkoe66cf822010-05-18 09:12:53 +020012040 char *fullname;
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012041 struct strlist *sp;
12042 volatile struct shparam saveparam;
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012043
12044 for (sp = cmdenviron; sp; sp = sp->next)
Denis Vlasenko4222ae42007-02-25 02:37:49 +000012045 setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012046
Denys Vlasenkoe66cf822010-05-18 09:12:53 +020012047 if (!argv[1]) {
12048 /* bash says: "bash: .: filename argument required" */
12049 return 2; /* bash compat */
12050 }
12051
Denys Vlasenkocd10dc42010-05-17 17:10:46 +020012052 /* "false; . empty_file; echo $?" should print 0, not 1: */
12053 exitstatus = 0;
12054
Denys Vlasenkoe66cf822010-05-18 09:12:53 +020012055 fullname = find_dot_file(argv[1]);
Denys Vlasenkocd10dc42010-05-17 17:10:46 +020012056
Denys Vlasenkoe66cf822010-05-18 09:12:53 +020012057 argv += 2;
12058 argc -= 2;
12059 if (argc) { /* argc > 0, argv[0] != NULL */
12060 saveparam = shellparam;
12061 shellparam.malloced = 0;
12062 shellparam.nparam = argc;
12063 shellparam.p = argv;
12064 };
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012065
Denys Vlasenkoe66cf822010-05-18 09:12:53 +020012066 setinputfile(fullname, INPUT_PUSH_FILE);
12067 commandname = fullname;
12068 cmdloop(0);
12069 popfile();
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012070
Denys Vlasenkoe66cf822010-05-18 09:12:53 +020012071 if (argc) {
12072 freeparam(&shellparam);
12073 shellparam = saveparam;
12074 };
12075
Denys Vlasenkocd10dc42010-05-17 17:10:46 +020012076 return exitstatus;
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012077}
12078
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012079static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012080exitcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012081{
12082 if (stoppedjobs())
12083 return 0;
Denis Vlasenko68404f12008-03-17 09:00:54 +000012084 if (argv[1])
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012085 exitstatus = number(argv[1]);
12086 raise_exception(EXEXIT);
12087 /* NOTREACHED */
12088}
12089
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012090/*
12091 * Read a file containing shell functions.
12092 */
12093static void
12094readcmdfile(char *name)
12095{
12096 setinputfile(name, INPUT_PUSH_FILE);
12097 cmdloop(0);
12098 popfile();
12099}
12100
12101
Denis Vlasenkocc571512007-02-23 21:10:35 +000012102/* ============ find_command inplementation */
12103
12104/*
12105 * Resolve a command name. If you change this routine, you may have to
12106 * change the shellexec routine as well.
12107 */
12108static void
12109find_command(char *name, struct cmdentry *entry, int act, const char *path)
12110{
12111 struct tblentry *cmdp;
12112 int idx;
12113 int prev;
12114 char *fullname;
12115 struct stat statb;
12116 int e;
12117 int updatetbl;
12118 struct builtincmd *bcmd;
12119
12120 /* If name contains a slash, don't use PATH or hash table */
12121 if (strchr(name, '/') != NULL) {
12122 entry->u.index = -1;
12123 if (act & DO_ABS) {
12124 while (stat(name, &statb) < 0) {
12125#ifdef SYSV
12126 if (errno == EINTR)
12127 continue;
12128#endif
12129 entry->cmdtype = CMDUNKNOWN;
12130 return;
12131 }
12132 }
12133 entry->cmdtype = CMDNORMAL;
12134 return;
12135 }
12136
Denis Vlasenkof20de5b2007-04-29 23:42:54 +000012137/* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
Denis Vlasenkocc571512007-02-23 21:10:35 +000012138
12139 updatetbl = (path == pathval());
12140 if (!updatetbl) {
12141 act |= DO_ALTPATH;
12142 if (strstr(path, "%builtin") != NULL)
12143 act |= DO_ALTBLTIN;
12144 }
12145
12146 /* If name is in the table, check answer will be ok */
12147 cmdp = cmdlookup(name, 0);
12148 if (cmdp != NULL) {
12149 int bit;
12150
12151 switch (cmdp->cmdtype) {
12152 default:
12153#if DEBUG
12154 abort();
12155#endif
12156 case CMDNORMAL:
12157 bit = DO_ALTPATH;
12158 break;
12159 case CMDFUNCTION:
12160 bit = DO_NOFUNC;
12161 break;
12162 case CMDBUILTIN:
12163 bit = DO_ALTBLTIN;
12164 break;
12165 }
12166 if (act & bit) {
12167 updatetbl = 0;
12168 cmdp = NULL;
12169 } else if (cmdp->rehash == 0)
12170 /* if not invalidated by cd, we're done */
12171 goto success;
12172 }
12173
12174 /* If %builtin not in path, check for builtin next */
12175 bcmd = find_builtin(name);
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +000012176 if (bcmd) {
12177 if (IS_BUILTIN_REGULAR(bcmd))
12178 goto builtin_success;
12179 if (act & DO_ALTPATH) {
12180 if (!(act & DO_ALTBLTIN))
12181 goto builtin_success;
12182 } else if (builtinloc <= 0) {
12183 goto builtin_success;
Denis Vlasenko8e858e22007-03-07 09:35:43 +000012184 }
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +000012185 }
Denis Vlasenkocc571512007-02-23 21:10:35 +000012186
Denis Vlasenkof20de5b2007-04-29 23:42:54 +000012187#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko7465dbc2008-04-13 02:25:53 +000012188 {
12189 int applet_no = find_applet_by_name(name);
12190 if (applet_no >= 0) {
12191 entry->cmdtype = CMDNORMAL;
12192 entry->u.index = -2 - applet_no;
12193 return;
12194 }
Denis Vlasenkof20de5b2007-04-29 23:42:54 +000012195 }
12196#endif
12197
Denis Vlasenkocc571512007-02-23 21:10:35 +000012198 /* We have to search path. */
12199 prev = -1; /* where to start */
12200 if (cmdp && cmdp->rehash) { /* doing a rehash */
12201 if (cmdp->cmdtype == CMDBUILTIN)
12202 prev = builtinloc;
12203 else
12204 prev = cmdp->param.index;
12205 }
12206
12207 e = ENOENT;
12208 idx = -1;
12209 loop:
Denys Vlasenko82a6fb32009-06-14 19:42:12 +020012210 while ((fullname = path_advance(&path, name)) != NULL) {
Denis Vlasenkocc571512007-02-23 21:10:35 +000012211 stunalloc(fullname);
Denis Vlasenkodee82b62007-07-29 14:05:27 +000012212 /* NB: code below will still use fullname
12213 * despite it being "unallocated" */
Denis Vlasenkocc571512007-02-23 21:10:35 +000012214 idx++;
12215 if (pathopt) {
12216 if (prefix(pathopt, "builtin")) {
12217 if (bcmd)
12218 goto builtin_success;
12219 continue;
Denis Vlasenko4a9ca132008-04-12 20:07:08 +000012220 }
12221 if ((act & DO_NOFUNC)
12222 || !prefix(pathopt, "func")
12223 ) { /* ignore unimplemented options */
Denis Vlasenkocc571512007-02-23 21:10:35 +000012224 continue;
12225 }
12226 }
12227 /* if rehash, don't redo absolute path names */
12228 if (fullname[0] == '/' && idx <= prev) {
12229 if (idx < prev)
12230 continue;
12231 TRACE(("searchexec \"%s\": no change\n", name));
12232 goto success;
12233 }
12234 while (stat(fullname, &statb) < 0) {
12235#ifdef SYSV
12236 if (errno == EINTR)
12237 continue;
12238#endif
12239 if (errno != ENOENT && errno != ENOTDIR)
12240 e = errno;
12241 goto loop;
12242 }
12243 e = EACCES; /* if we fail, this will be the error */
12244 if (!S_ISREG(statb.st_mode))
12245 continue;
12246 if (pathopt) { /* this is a %func directory */
12247 stalloc(strlen(fullname) + 1);
Denis Vlasenkodee82b62007-07-29 14:05:27 +000012248 /* NB: stalloc will return space pointed by fullname
12249 * (because we don't have any intervening allocations
12250 * between stunalloc above and this stalloc) */
Denis Vlasenkocc571512007-02-23 21:10:35 +000012251 readcmdfile(fullname);
12252 cmdp = cmdlookup(name, 0);
12253 if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
12254 ash_msg_and_raise_error("%s not defined in %s", name, fullname);
12255 stunalloc(fullname);
12256 goto success;
12257 }
12258 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
12259 if (!updatetbl) {
12260 entry->cmdtype = CMDNORMAL;
12261 entry->u.index = idx;
12262 return;
12263 }
12264 INT_OFF;
12265 cmdp = cmdlookup(name, 1);
12266 cmdp->cmdtype = CMDNORMAL;
12267 cmdp->param.index = idx;
12268 INT_ON;
12269 goto success;
12270 }
12271
12272 /* We failed. If there was an entry for this command, delete it */
12273 if (cmdp && updatetbl)
12274 delete_cmd_entry();
12275 if (act & DO_ERR)
12276 ash_msg("%s: %s", name, errmsg(e, "not found"));
12277 entry->cmdtype = CMDUNKNOWN;
12278 return;
12279
12280 builtin_success:
12281 if (!updatetbl) {
12282 entry->cmdtype = CMDBUILTIN;
12283 entry->u.cmd = bcmd;
12284 return;
12285 }
12286 INT_OFF;
12287 cmdp = cmdlookup(name, 1);
12288 cmdp->cmdtype = CMDBUILTIN;
12289 cmdp->param.cmd = bcmd;
12290 INT_ON;
12291 success:
12292 cmdp->rehash = 0;
12293 entry->cmdtype = cmdp->cmdtype;
12294 entry->u = cmdp->param;
12295}
12296
12297
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012298/* ============ trap.c */
Eric Andersenc470f442003-07-28 09:56:35 +000012299
Eric Andersencb57d552001-06-28 07:25:16 +000012300/*
Eric Andersencb57d552001-06-28 07:25:16 +000012301 * The trap builtin.
12302 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012303static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012304trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersencb57d552001-06-28 07:25:16 +000012305{
12306 char *action;
12307 char **ap;
Denys Vlasenko496d5bf2010-03-26 15:52:24 +010012308 int signo, exitcode;
Eric Andersencb57d552001-06-28 07:25:16 +000012309
Eric Andersenc470f442003-07-28 09:56:35 +000012310 nextopt(nullstr);
12311 ap = argptr;
12312 if (!*ap) {
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012313 for (signo = 0; signo < NSIG; signo++) {
Denys Vlasenko21d87d42009-09-25 00:06:51 +020012314 char *tr = trap_ptr[signo];
12315 if (tr) {
Denys Vlasenkoe74aaf92009-09-27 02:05:45 +020012316 /* note: bash adds "SIG", but only if invoked
12317 * as "bash". If called as "sh", or if set -o posix,
12318 * then it prints short signal names.
12319 * We are printing short names: */
12320 out1fmt("trap -- %s %s\n",
Denys Vlasenko21d87d42009-09-25 00:06:51 +020012321 single_quote(tr),
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +000012322 get_signame(signo));
Denys Vlasenko726e1a02009-09-25 02:58:20 +020012323 /* trap_ptr != trap only if we are in special-cased `trap` code.
12324 * In this case, we will exit very soon, no need to free(). */
Denys Vlasenkoe74aaf92009-09-27 02:05:45 +020012325 /* if (trap_ptr != trap && tp[0]) */
Denys Vlasenko726e1a02009-09-25 02:58:20 +020012326 /* free(tr); */
Eric Andersencb57d552001-06-28 07:25:16 +000012327 }
12328 }
Denys Vlasenko726e1a02009-09-25 02:58:20 +020012329 /*
Denys Vlasenko21d87d42009-09-25 00:06:51 +020012330 if (trap_ptr != trap) {
12331 free(trap_ptr);
12332 trap_ptr = trap;
12333 }
Denys Vlasenko726e1a02009-09-25 02:58:20 +020012334 */
Eric Andersencb57d552001-06-28 07:25:16 +000012335 return 0;
12336 }
Denys Vlasenko21d87d42009-09-25 00:06:51 +020012337
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +000012338 action = NULL;
12339 if (ap[1])
Eric Andersencb57d552001-06-28 07:25:16 +000012340 action = *ap++;
Denys Vlasenko496d5bf2010-03-26 15:52:24 +010012341 exitcode = 0;
Eric Andersencb57d552001-06-28 07:25:16 +000012342 while (*ap) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +000012343 signo = get_signum(*ap);
Denys Vlasenko496d5bf2010-03-26 15:52:24 +010012344 if (signo < 0) {
12345 /* Mimic bash message exactly */
12346 ash_msg("%s: invalid signal specification", *ap);
12347 exitcode = 1;
12348 goto next;
12349 }
Denis Vlasenkob012b102007-02-19 22:43:01 +000012350 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +000012351 if (action) {
Denis Vlasenko9f739442006-12-16 23:49:13 +000012352 if (LONE_DASH(action))
Eric Andersencb57d552001-06-28 07:25:16 +000012353 action = NULL;
12354 else
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012355 action = ckstrdup(action);
Eric Andersencb57d552001-06-28 07:25:16 +000012356 }
Denis Vlasenko60818682007-09-28 22:07:23 +000012357 free(trap[signo]);
Denys Vlasenko238bf182010-05-18 15:49:07 +020012358 if (action)
12359 may_have_traps = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000012360 trap[signo] = action;
12361 if (signo != 0)
12362 setsignal(signo);
Denis Vlasenkob012b102007-02-19 22:43:01 +000012363 INT_ON;
Denys Vlasenko496d5bf2010-03-26 15:52:24 +010012364 next:
Eric Andersencb57d552001-06-28 07:25:16 +000012365 ap++;
12366 }
Denys Vlasenko496d5bf2010-03-26 15:52:24 +010012367 return exitcode;
Eric Andersencb57d552001-06-28 07:25:16 +000012368}
12369
Eric Andersenc470f442003-07-28 09:56:35 +000012370
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012371/* ============ Builtins */
Eric Andersenc470f442003-07-28 09:56:35 +000012372
Denis Vlasenko8e1c7152007-01-22 07:21:38 +000012373#if !ENABLE_FEATURE_SH_EXTRA_QUIET
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012374/*
12375 * Lists available builtins
12376 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012377static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012378helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersenc470f442003-07-28 09:56:35 +000012379{
Denis Vlasenko6b06cb82008-05-15 21:30:45 +000012380 unsigned col;
12381 unsigned i;
Eric Andersenc470f442003-07-28 09:56:35 +000012382
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +020012383 out1fmt(
Denis Vlasenko34d4d892009-04-04 20:24:37 +000012384 "Built-in commands:\n"
12385 "------------------\n");
Denis Vlasenkob71c6682007-07-21 15:08:09 +000012386 for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
Eric Andersenc470f442003-07-28 09:56:35 +000012387 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
Denis Vlasenko52764022007-02-24 13:42:56 +000012388 builtintab[i].name + 1);
Eric Andersenc470f442003-07-28 09:56:35 +000012389 if (col > 60) {
12390 out1fmt("\n");
12391 col = 0;
12392 }
12393 }
Denis Vlasenko80d14be2007-04-10 23:03:30 +000012394#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko1aa7e472007-11-28 06:49:03 +000012395 {
12396 const char *a = applet_names;
12397 while (*a) {
12398 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
12399 if (col > 60) {
12400 out1fmt("\n");
12401 col = 0;
12402 }
12403 a += strlen(a) + 1;
Eric Andersenc470f442003-07-28 09:56:35 +000012404 }
12405 }
12406#endif
12407 out1fmt("\n\n");
12408 return EXIT_SUCCESS;
12409}
Denis Vlasenko131ae172007-02-18 13:00:19 +000012410#endif /* FEATURE_SH_EXTRA_QUIET */
Eric Andersenc470f442003-07-28 09:56:35 +000012411
Eric Andersencb57d552001-06-28 07:25:16 +000012412/*
Eric Andersencb57d552001-06-28 07:25:16 +000012413 * The export and readonly commands.
12414 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012415static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012416exportcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +000012417{
12418 struct var *vp;
12419 char *name;
12420 const char *p;
Eric Andersenc470f442003-07-28 09:56:35 +000012421 char **aptr;
Denis Vlasenkob7304742008-10-20 08:15:51 +000012422 int flag = argv[0][0] == 'r' ? VREADONLY : VEXPORT;
Eric Andersencb57d552001-06-28 07:25:16 +000012423
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012424 if (nextopt("p") != 'p') {
12425 aptr = argptr;
12426 name = *aptr;
12427 if (name) {
12428 do {
12429 p = strchr(name, '=');
12430 if (p != NULL) {
12431 p++;
12432 } else {
12433 vp = *findvar(hashvar(name), name);
12434 if (vp) {
12435 vp->flags |= flag;
12436 continue;
12437 }
Eric Andersencb57d552001-06-28 07:25:16 +000012438 }
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012439 setvar(name, p, flag);
12440 } while ((name = *++aptr) != NULL);
12441 return 0;
12442 }
Eric Andersencb57d552001-06-28 07:25:16 +000012443 }
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012444 showvars(argv[0], flag, 0);
Eric Andersencb57d552001-06-28 07:25:16 +000012445 return 0;
12446}
12447
Eric Andersencb57d552001-06-28 07:25:16 +000012448/*
Denis Vlasenko5651bfc2007-02-23 21:08:58 +000012449 * Delete a function if it exists.
Eric Andersencb57d552001-06-28 07:25:16 +000012450 */
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012451static void
Denis Vlasenko5651bfc2007-02-23 21:08:58 +000012452unsetfunc(const char *name)
Aaron Lehmannb6ecbdc2001-12-06 03:37:38 +000012453{
Denis Vlasenko5651bfc2007-02-23 21:08:58 +000012454 struct tblentry *cmdp;
Eric Andersencb57d552001-06-28 07:25:16 +000012455
Denis Vlasenko5651bfc2007-02-23 21:08:58 +000012456 cmdp = cmdlookup(name, 0);
12457 if (cmdp!= NULL && cmdp->cmdtype == CMDFUNCTION)
12458 delete_cmd_entry();
Eric Andersenc470f442003-07-28 09:56:35 +000012459}
12460
Eric Andersencb57d552001-06-28 07:25:16 +000012461/*
Eric Andersencb57d552001-06-28 07:25:16 +000012462 * The unset builtin command. We unset the function before we unset the
12463 * variable to allow a function to be unset when there is a readonly variable
12464 * with the same name.
12465 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012466static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012467unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersencb57d552001-06-28 07:25:16 +000012468{
12469 char **ap;
12470 int i;
Eric Andersenc470f442003-07-28 09:56:35 +000012471 int flag = 0;
Eric Andersencb57d552001-06-28 07:25:16 +000012472 int ret = 0;
12473
12474 while ((i = nextopt("vf")) != '\0') {
Eric Andersenc470f442003-07-28 09:56:35 +000012475 flag = i;
Eric Andersencb57d552001-06-28 07:25:16 +000012476 }
Eric Andersencb57d552001-06-28 07:25:16 +000012477
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012478 for (ap = argptr; *ap; ap++) {
Eric Andersenc470f442003-07-28 09:56:35 +000012479 if (flag != 'f') {
12480 i = unsetvar(*ap);
12481 ret |= i;
12482 if (!(i & 2))
12483 continue;
12484 }
12485 if (flag != 'v')
Eric Andersencb57d552001-06-28 07:25:16 +000012486 unsetfunc(*ap);
Eric Andersencb57d552001-06-28 07:25:16 +000012487 }
Eric Andersenc470f442003-07-28 09:56:35 +000012488 return ret & 1;
Eric Andersencb57d552001-06-28 07:25:16 +000012489}
12490
12491
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +000012492/* setmode.c */
Eric Andersencb57d552001-06-28 07:25:16 +000012493
Eric Andersenc470f442003-07-28 09:56:35 +000012494#include <sys/times.h>
12495
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000012496static const unsigned char timescmd_str[] ALIGN1 = {
Manuel Novoa III 4456f252003-08-13 17:48:47 +000012497 ' ', offsetof(struct tms, tms_utime),
12498 '\n', offsetof(struct tms, tms_stime),
12499 ' ', offsetof(struct tms, tms_cutime),
12500 '\n', offsetof(struct tms, tms_cstime),
12501 0
12502};
Eric Andersencb57d552001-06-28 07:25:16 +000012503
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012504static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012505timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Manuel Novoa III 4456f252003-08-13 17:48:47 +000012506{
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012507 long clk_tck, s, t;
Manuel Novoa III 4456f252003-08-13 17:48:47 +000012508 const unsigned char *p;
12509 struct tms buf;
12510
12511 clk_tck = sysconf(_SC_CLK_TCK);
Eric Andersencb57d552001-06-28 07:25:16 +000012512 times(&buf);
Manuel Novoa III 4456f252003-08-13 17:48:47 +000012513
12514 p = timescmd_str;
12515 do {
12516 t = *(clock_t *)(((char *) &buf) + p[1]);
12517 s = t / clk_tck;
12518 out1fmt("%ldm%ld.%.3lds%c",
12519 s/60, s%60,
12520 ((t - s * clk_tck) * 1000) / clk_tck,
12521 p[0]);
12522 } while (*(p += 2));
12523
Eric Andersencb57d552001-06-28 07:25:16 +000012524 return 0;
12525}
12526
Mike Frysinger98c52642009-04-02 10:02:37 +000012527#if ENABLE_SH_MATH_SUPPORT
Eric Andersenc470f442003-07-28 09:56:35 +000012528/*
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +000012529 * The let builtin. partial stolen from GNU Bash, the Bourne Again SHell.
12530 * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
Eric Andersen90898442003-08-06 11:20:52 +000012531 *
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +000012532 * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
Eric Andersenc470f442003-07-28 09:56:35 +000012533 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012534static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012535letcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersenc470f442003-07-28 09:56:35 +000012536{
Denis Vlasenko68404f12008-03-17 09:00:54 +000012537 arith_t i;
Eric Andersenc470f442003-07-28 09:56:35 +000012538
Denis Vlasenko68404f12008-03-17 09:00:54 +000012539 argv++;
12540 if (!*argv)
Denis Vlasenkob012b102007-02-19 22:43:01 +000012541 ash_msg_and_raise_error("expression expected");
Denis Vlasenko68404f12008-03-17 09:00:54 +000012542 do {
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +000012543 i = ash_arith(*argv);
Denis Vlasenko68404f12008-03-17 09:00:54 +000012544 } while (*++argv);
Eric Andersenc470f442003-07-28 09:56:35 +000012545
Denis Vlasenkod9e15f22006-11-27 16:49:55 +000012546 return !i;
Eric Andersenc470f442003-07-28 09:56:35 +000012547}
Mike Frysinger98c52642009-04-02 10:02:37 +000012548#endif /* SH_MATH_SUPPORT */
Eric Andersenc470f442003-07-28 09:56:35 +000012549
Eric Andersenc470f442003-07-28 09:56:35 +000012550
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012551/* ============ miscbltin.c
12552 *
Eric Andersenaff114c2004-04-14 17:51:38 +000012553 * Miscellaneous builtins.
Eric Andersenc470f442003-07-28 09:56:35 +000012554 */
12555
12556#undef rflag
12557
Denis Vlasenko83e5d6f2006-12-18 21:49:06 +000012558#if defined(__GLIBC__) && __GLIBC__ == 2 && __GLIBC_MINOR__ < 1
Eric Andersenc470f442003-07-28 09:56:35 +000012559typedef enum __rlimit_resource rlim_t;
12560#endif
Eric Andersen74bcd162001-07-30 21:41:37 +000012561
Eric Andersenc470f442003-07-28 09:56:35 +000012562/*
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012563 * The read builtin. Options:
12564 * -r Do not interpret '\' specially
12565 * -s Turn off echo (tty only)
12566 * -n NCHARS Read NCHARS max
12567 * -p PROMPT Display PROMPT on stderr (if input is from tty)
12568 * -t SECONDS Timeout after SECONDS (tty or pipe only)
12569 * -u FD Read from given FD instead of fd 0
Eric Andersenc470f442003-07-28 09:56:35 +000012570 * This uses unbuffered input, which may be avoidable in some cases.
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012571 * TODO: bash also has:
12572 * -a ARRAY Read into array[0],[1],etc
12573 * -d DELIM End on DELIM char, not newline
12574 * -e Use line editing (tty only)
Eric Andersenc470f442003-07-28 09:56:35 +000012575 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012576static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012577readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersenc470f442003-07-28 09:56:35 +000012578{
Denys Vlasenko73067272010-01-12 22:11:24 +010012579 char *opt_n = NULL;
12580 char *opt_p = NULL;
12581 char *opt_t = NULL;
12582 char *opt_u = NULL;
12583 int read_flags = 0;
12584 const char *r;
Eric Andersenc470f442003-07-28 09:56:35 +000012585 int i;
12586
Denys Vlasenko73067272010-01-12 22:11:24 +010012587 while ((i = nextopt("p:u:rt:n:s")) != '\0') {
Denis Vlasenkobf0a2012006-12-26 10:42:51 +000012588 switch (i) {
Paul Fox02eb9342005-09-07 16:56:02 +000012589 case 'p':
Denys Vlasenko73067272010-01-12 22:11:24 +010012590 opt_p = optionarg;
Paul Fox02eb9342005-09-07 16:56:02 +000012591 break;
Paul Fox02eb9342005-09-07 16:56:02 +000012592 case 'n':
Denys Vlasenko73067272010-01-12 22:11:24 +010012593 opt_n = optionarg;
Paul Fox02eb9342005-09-07 16:56:02 +000012594 break;
12595 case 's':
Denys Vlasenko73067272010-01-12 22:11:24 +010012596 read_flags |= BUILTIN_READ_SILENT;
Paul Fox02eb9342005-09-07 16:56:02 +000012597 break;
Paul Fox02eb9342005-09-07 16:56:02 +000012598 case 't':
Denys Vlasenko73067272010-01-12 22:11:24 +010012599 opt_t = optionarg;
Paul Fox02eb9342005-09-07 16:56:02 +000012600 break;
Paul Fox02eb9342005-09-07 16:56:02 +000012601 case 'r':
Denys Vlasenko73067272010-01-12 22:11:24 +010012602 read_flags |= BUILTIN_READ_RAW;
Paul Fox02eb9342005-09-07 16:56:02 +000012603 break;
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012604 case 'u':
Denys Vlasenko73067272010-01-12 22:11:24 +010012605 opt_u = optionarg;
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012606 break;
Paul Fox02eb9342005-09-07 16:56:02 +000012607 default:
12608 break;
12609 }
Eric Andersenc470f442003-07-28 09:56:35 +000012610 }
Paul Fox02eb9342005-09-07 16:56:02 +000012611
Denys Vlasenko03dad222010-01-12 23:29:57 +010012612 r = shell_builtin_read(setvar2,
Denys Vlasenko73067272010-01-12 22:11:24 +010012613 argptr,
12614 bltinlookup("IFS"), /* can be NULL */
12615 read_flags,
12616 opt_n,
12617 opt_p,
12618 opt_t,
12619 opt_u
12620 );
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012621
Denys Vlasenko73067272010-01-12 22:11:24 +010012622 if ((uintptr_t)r > 1)
12623 ash_msg_and_raise_error(r);
Denis Vlasenko037576d2007-10-20 18:30:38 +000012624
Denys Vlasenko73067272010-01-12 22:11:24 +010012625 return (uintptr_t)r;
Eric Andersenc470f442003-07-28 09:56:35 +000012626}
12627
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012628static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012629umaskcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersenc470f442003-07-28 09:56:35 +000012630{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000012631 static const char permuser[3] ALIGN1 = "ugo";
12632 static const char permmode[3] ALIGN1 = "rwx";
12633 static const short permmask[] ALIGN2 = {
Eric Andersenc470f442003-07-28 09:56:35 +000012634 S_IRUSR, S_IWUSR, S_IXUSR,
12635 S_IRGRP, S_IWGRP, S_IXGRP,
12636 S_IROTH, S_IWOTH, S_IXOTH
12637 };
12638
Denis Vlasenkoeb858492009-04-18 02:06:54 +000012639 /* TODO: use bb_parse_mode() instead */
12640
Eric Andersenc470f442003-07-28 09:56:35 +000012641 char *ap;
12642 mode_t mask;
12643 int i;
12644 int symbolic_mode = 0;
12645
12646 while (nextopt("S") != '\0') {
12647 symbolic_mode = 1;
12648 }
12649
Denis Vlasenkob012b102007-02-19 22:43:01 +000012650 INT_OFF;
Eric Andersenc470f442003-07-28 09:56:35 +000012651 mask = umask(0);
12652 umask(mask);
Denis Vlasenkob012b102007-02-19 22:43:01 +000012653 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +000012654
Denis Vlasenko5cedb752007-02-18 19:56:41 +000012655 ap = *argptr;
12656 if (ap == NULL) {
Eric Andersenc470f442003-07-28 09:56:35 +000012657 if (symbolic_mode) {
12658 char buf[18];
12659 char *p = buf;
12660
12661 for (i = 0; i < 3; i++) {
12662 int j;
12663
12664 *p++ = permuser[i];
12665 *p++ = '=';
12666 for (j = 0; j < 3; j++) {
12667 if ((mask & permmask[3 * i + j]) == 0) {
12668 *p++ = permmode[j];
12669 }
12670 }
12671 *p++ = ',';
12672 }
12673 *--p = 0;
12674 puts(buf);
12675 } else {
12676 out1fmt("%.4o\n", mask);
12677 }
12678 } else {
Denis Vlasenkoaa744452007-02-23 01:04:22 +000012679 if (isdigit((unsigned char) *ap)) {
Eric Andersenc470f442003-07-28 09:56:35 +000012680 mask = 0;
12681 do {
12682 if (*ap >= '8' || *ap < '0')
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +020012683 ash_msg_and_raise_error(msg_illnum, argv[1]);
Eric Andersenc470f442003-07-28 09:56:35 +000012684 mask = (mask << 3) + (*ap - '0');
12685 } while (*++ap != '\0');
12686 umask(mask);
12687 } else {
12688 mask = ~mask & 0777;
12689 if (!bb_parse_mode(ap, &mask)) {
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +000012690 ash_msg_and_raise_error("illegal mode: %s", ap);
Eric Andersenc470f442003-07-28 09:56:35 +000012691 }
12692 umask(~mask & 0777);
12693 }
12694 }
12695 return 0;
12696}
12697
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012698static int FAST_FUNC
Denys Vlasenkof3c742f2010-03-06 20:12:00 +010012699ulimitcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersenc470f442003-07-28 09:56:35 +000012700{
Denys Vlasenkof3c742f2010-03-06 20:12:00 +010012701 return shell_builtin_ulimit(argv);
Eric Andersenc470f442003-07-28 09:56:35 +000012702}
12703
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012704/* ============ main() and helpers */
12705
12706/*
12707 * Called to exit the shell.
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012708 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012709static void exitshell(void) NORETURN;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012710static void
12711exitshell(void)
12712{
12713 struct jmploc loc;
12714 char *p;
12715 int status;
12716
12717 status = exitstatus;
12718 TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
12719 if (setjmp(loc.loc)) {
Denis Vlasenko7f88e342009-03-19 03:36:18 +000012720 if (exception_type == EXEXIT)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012721/* dash bug: it just does _exit(exitstatus) here
12722 * but we have to do setjobctl(0) first!
12723 * (bug is still not fixed in dash-0.5.3 - if you run dash
12724 * under Midnight Commander, on exit from dash MC is backgrounded) */
12725 status = exitstatus;
12726 goto out;
12727 }
12728 exception_handler = &loc;
12729 p = trap[0];
12730 if (p) {
12731 trap[0] = NULL;
12732 evalstring(p, 0);
Denys Vlasenko0800e3a2009-09-24 03:09:26 +020012733 free(p);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012734 }
12735 flush_stdout_stderr();
12736 out:
12737 setjobctl(0);
12738 _exit(status);
12739 /* NOTREACHED */
12740}
12741
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012742static void
12743init(void)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012744{
12745 /* from input.c: */
Denys Vlasenko82dd14a2010-05-17 10:10:01 +020012746 /* we will never free this */
12747 basepf.next_to_pgetc = basepf.buf = ckmalloc(IBUFSIZ);
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012748
12749 /* from trap.c: */
12750 signal(SIGCHLD, SIG_DFL);
Denys Vlasenko7a7b0342009-12-04 04:18:31 +010012751 /* bash re-enables SIGHUP which is SIG_IGNed on entry.
12752 * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
12753 */
12754 signal(SIGHUP, SIG_DFL);
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012755
12756 /* from var.c: */
12757 {
12758 char **envp;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012759 const char *p;
12760 struct stat st1, st2;
12761
12762 initvar();
12763 for (envp = environ; envp && *envp; envp++) {
12764 if (strchr(*envp, '=')) {
12765 setvareq(*envp, VEXPORT|VTEXTFIXED);
12766 }
12767 }
12768
Denys Vlasenko7bb346f2009-10-06 22:09:50 +020012769 setvar("PPID", utoa(getppid()), 0);
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012770
12771 p = lookupvar("PWD");
12772 if (p)
12773 if (*p != '/' || stat(p, &st1) || stat(".", &st2)
12774 || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino)
12775 p = '\0';
12776 setpwd(p, 0);
12777 }
12778}
12779
12780/*
12781 * Process the shell command line arguments.
12782 */
12783static void
Denis Vlasenko68404f12008-03-17 09:00:54 +000012784procargs(char **argv)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012785{
12786 int i;
12787 const char *xminusc;
12788 char **xargv;
12789
12790 xargv = argv;
12791 arg0 = xargv[0];
Denis Vlasenko68404f12008-03-17 09:00:54 +000012792 /* if (xargv[0]) - mmm, this is always true! */
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012793 xargv++;
12794 for (i = 0; i < NOPTS; i++)
12795 optlist[i] = 2;
12796 argptr = xargv;
Denis Vlasenko28bf6712008-02-14 15:01:47 +000012797 if (options(1)) {
12798 /* it already printed err message */
12799 raise_exception(EXERROR);
12800 }
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012801 xargv = argptr;
12802 xminusc = minusc;
12803 if (*xargv == NULL) {
12804 if (xminusc)
12805 ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
12806 sflag = 1;
12807 }
12808 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
12809 iflag = 1;
12810 if (mflag == 2)
12811 mflag = iflag;
12812 for (i = 0; i < NOPTS; i++)
12813 if (optlist[i] == 2)
12814 optlist[i] = 0;
12815#if DEBUG == 2
12816 debug = 1;
12817#endif
12818 /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
12819 if (xminusc) {
12820 minusc = *xargv++;
12821 if (*xargv)
12822 goto setarg0;
12823 } else if (!sflag) {
12824 setinputfile(*xargv, 0);
12825 setarg0:
12826 arg0 = *xargv++;
12827 commandname = arg0;
12828 }
12829
12830 shellparam.p = xargv;
12831#if ENABLE_ASH_GETOPTS
12832 shellparam.optind = 1;
12833 shellparam.optoff = -1;
12834#endif
Denis Vlasenko01631112007-12-16 17:20:38 +000012835 /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012836 while (*xargv) {
12837 shellparam.nparam++;
12838 xargv++;
12839 }
12840 optschanged();
12841}
12842
12843/*
12844 * Read /etc/profile or .profile.
12845 */
12846static void
12847read_profile(const char *name)
12848{
12849 int skip;
12850
12851 if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
12852 return;
12853 skip = cmdloop(0);
12854 popfile();
12855 if (skip)
12856 exitshell();
12857}
12858
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012859/*
12860 * This routine is called when an error or an interrupt occurs in an
12861 * interactive shell and control is returned to the main command loop.
12862 */
12863static void
12864reset(void)
12865{
12866 /* from eval.c: */
12867 evalskip = 0;
12868 loopnest = 0;
12869 /* from input.c: */
Denis Vlasenko41eb3002008-11-28 03:42:31 +000012870 g_parsefile->left_in_buffer = 0;
12871 g_parsefile->left_in_line = 0; /* clear input buffer */
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012872 popallfiles();
12873 /* from parser.c: */
12874 tokpushback = 0;
12875 checkkwd = 0;
12876 /* from redir.c: */
Denis Vlasenko34c73c42008-08-16 11:48:02 +000012877 clearredir(/*drop:*/ 0);
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012878}
12879
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012880#if PROFILE
12881static short profile_buf[16384];
12882extern int etext();
12883#endif
12884
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012885/*
12886 * Main routine. We initialize things, parse the arguments, execute
12887 * profiles if we're a login shell, and then call cmdloop to execute
12888 * commands. The setjmp call sets up the location to jump to when an
12889 * exception occurs. When an exception occurs the variable "state"
12890 * is used to figure out how far we had gotten.
12891 */
Denis Vlasenko9b49a5e2007-10-11 10:05:36 +000012892int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012893int ash_main(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012894{
Mike Frysinger98c52642009-04-02 10:02:37 +000012895 const char *shinit;
Denis Vlasenko4e12b1a2008-12-23 23:36:47 +000012896 volatile smallint state;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012897 struct jmploc jmploc;
12898 struct stackmark smark;
12899
Denis Vlasenko01631112007-12-16 17:20:38 +000012900 /* Initialize global data */
12901 INIT_G_misc();
12902 INIT_G_memstack();
12903 INIT_G_var();
Denis Vlasenkoee87ebf2007-12-21 22:18:16 +000012904#if ENABLE_ASH_ALIAS
Denis Vlasenko01631112007-12-16 17:20:38 +000012905 INIT_G_alias();
Denis Vlasenkoee87ebf2007-12-21 22:18:16 +000012906#endif
Denis Vlasenko01631112007-12-16 17:20:38 +000012907 INIT_G_cmdtable();
12908
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012909#if PROFILE
12910 monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
12911#endif
12912
12913#if ENABLE_FEATURE_EDITING
12914 line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
12915#endif
12916 state = 0;
12917 if (setjmp(jmploc.loc)) {
Denis Vlasenko7f88e342009-03-19 03:36:18 +000012918 smallint e;
Denis Vlasenko4e12b1a2008-12-23 23:36:47 +000012919 smallint s;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012920
12921 reset();
12922
Denis Vlasenko7f88e342009-03-19 03:36:18 +000012923 e = exception_type;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012924 if (e == EXERROR)
12925 exitstatus = 2;
12926 s = state;
12927 if (e == EXEXIT || s == 0 || iflag == 0 || shlvl)
12928 exitshell();
Denis Vlasenko7f88e342009-03-19 03:36:18 +000012929 if (e == EXINT)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012930 outcslow('\n', stderr);
Denis Vlasenko7f88e342009-03-19 03:36:18 +000012931
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012932 popstackmark(&smark);
12933 FORCE_INT_ON; /* enable interrupts */
12934 if (s == 1)
12935 goto state1;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000012936 if (s == 2)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012937 goto state2;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000012938 if (s == 3)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012939 goto state3;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000012940 goto state4;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012941 }
12942 exception_handler = &jmploc;
12943#if DEBUG
12944 opentrace();
Denis Vlasenko653d8e72009-03-19 21:59:35 +000012945 TRACE(("Shell args: "));
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000012946 trace_puts_args(argv);
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012947#endif
12948 rootpid = getpid();
12949
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012950 init();
12951 setstackmark(&smark);
Denis Vlasenko68404f12008-03-17 09:00:54 +000012952 procargs(argv);
12953
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012954#if ENABLE_FEATURE_EDITING_SAVEHISTORY
12955 if (iflag) {
12956 const char *hp = lookupvar("HISTFILE");
12957
12958 if (hp == NULL) {
12959 hp = lookupvar("HOME");
12960 if (hp != NULL) {
12961 char *defhp = concat_path_file(hp, ".ash_history");
12962 setvar("HISTFILE", defhp, 0);
12963 free(defhp);
12964 }
12965 }
12966 }
12967#endif
Denis Vlasenko4e12b1a2008-12-23 23:36:47 +000012968 if (/* argv[0] && */ argv[0][0] == '-')
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012969 isloginsh = 1;
12970 if (isloginsh) {
12971 state = 1;
12972 read_profile("/etc/profile");
12973 state1:
12974 state = 2;
12975 read_profile(".profile");
12976 }
12977 state2:
12978 state = 3;
12979 if (
12980#ifndef linux
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012981 getuid() == geteuid() && getgid() == getegid() &&
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012982#endif
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012983 iflag
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012984 ) {
12985 shinit = lookupvar("ENV");
12986 if (shinit != NULL && *shinit != '\0') {
12987 read_profile(shinit);
12988 }
12989 }
12990 state3:
12991 state = 4;
Denis Vlasenko5c2b8142009-03-19 01:59:59 +000012992 if (minusc) {
12993 /* evalstring pushes parsefile stack.
12994 * Ensure we don't falsely claim that 0 (stdin)
Denis Vlasenko5368ad52009-03-20 10:20:08 +000012995 * is one of stacked source fds.
12996 * Testcase: ash -c 'exec 1>&0' must not complain. */
Denis Vlasenko5c2b8142009-03-19 01:59:59 +000012997 if (!sflag)
12998 g_parsefile->fd = -1;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012999 evalstring(minusc, 0);
Denis Vlasenko5c2b8142009-03-19 01:59:59 +000013000 }
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013001
13002 if (sflag || minusc == NULL) {
Denys Vlasenko0337e032009-11-29 00:12:30 +010013003#if defined MAX_HISTORY && MAX_HISTORY > 0 && ENABLE_FEATURE_EDITING_SAVEHISTORY
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +000013004 if (iflag) {
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013005 const char *hp = lookupvar("HISTFILE");
Denis Vlasenko5c2b8142009-03-19 01:59:59 +000013006 if (hp)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013007 line_input_state->hist_file = hp;
13008 }
13009#endif
13010 state4: /* XXX ??? - why isn't this before the "if" statement */
13011 cmdloop(1);
13012 }
13013#if PROFILE
13014 monitor(0);
13015#endif
13016#ifdef GPROF
13017 {
13018 extern void _mcleanup(void);
13019 _mcleanup();
13020 }
13021#endif
13022 exitshell();
13023 /* NOTREACHED */
13024}
13025
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013026
Eric Andersendf82f612001-06-28 07:46:40 +000013027/*-
13028 * Copyright (c) 1989, 1991, 1993, 1994
Eric Andersen2870d962001-07-02 17:27:21 +000013029 * The Regents of the University of California. All rights reserved.
Eric Andersendf82f612001-06-28 07:46:40 +000013030 *
13031 * This code is derived from software contributed to Berkeley by
13032 * Kenneth Almquist.
13033 *
13034 * Redistribution and use in source and binary forms, with or without
13035 * modification, are permitted provided that the following conditions
13036 * are met:
13037 * 1. Redistributions of source code must retain the above copyright
13038 * notice, this list of conditions and the following disclaimer.
13039 * 2. Redistributions in binary form must reproduce the above copyright
13040 * notice, this list of conditions and the following disclaimer in the
13041 * documentation and/or other materials provided with the distribution.
"Vladimir N. Oleynik"ddc280e2005-12-15 12:01:49 +000013042 * 3. Neither the name of the University nor the names of its contributors
Eric Andersendf82f612001-06-28 07:46:40 +000013043 * may be used to endorse or promote products derived from this software
13044 * without specific prior written permission.
13045 *
13046 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
13047 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
13048 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
13049 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
13050 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
13051 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
13052 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
13053 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
13054 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
13055 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
13056 * SUCH DAMAGE.
13057 */