blob: 74fe8617b7840e5c5f86789c11496f60f13174dc [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 Vlasenko1ed2fb42010-06-18 14:09:48 +020049#include <sys/times.h>
Denys Vlasenko73067272010-01-12 22:11:24 +010050
51#include "shell_common.h"
Mike Frysinger98c52642009-04-02 10:02:37 +000052#include "math.h"
Denys Vlasenko3ea2e822009-10-09 20:59:04 +020053#if ENABLE_ASH_RANDOM_SUPPORT
54# include "random.h"
Denys Vlasenko36df0482009-10-19 16:07:28 +020055#else
56# define CLEAR_RANDOM_T(rnd) ((void)0)
Denys Vlasenko3ea2e822009-10-09 20:59:04 +020057#endif
Denis Vlasenko61befda2008-11-25 01:36:03 +000058
Denys Vlasenko14974842010-03-23 01:08:26 +010059#define SKIP_definitions 1
60#include "applet_tables.h"
61#undef SKIP_definitions
62#if NUM_APPLETS == 1
Denis Vlasenko61befda2008-11-25 01:36:03 +000063/* STANDALONE does not make sense, and won't compile */
Denys Vlasenko3ea2e822009-10-09 20:59:04 +020064# undef CONFIG_FEATURE_SH_STANDALONE
65# undef ENABLE_FEATURE_SH_STANDALONE
66# undef IF_FEATURE_SH_STANDALONE
Denys Vlasenko14974842010-03-23 01:08:26 +010067# undef IF_NOT_FEATURE_SH_STANDALONE
Denys Vlasenko3ea2e822009-10-09 20:59:04 +020068# define ENABLE_FEATURE_SH_STANDALONE 0
69# define IF_FEATURE_SH_STANDALONE(...)
70# define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
Eric Andersencb57d552001-06-28 07:25:16 +000071#endif
72
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000073#ifndef PIPE_BUF
Denis Vlasenko653d8e72009-03-19 21:59:35 +000074# define PIPE_BUF 4096 /* amount of buffering in a pipe */
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000075#endif
76
Denys Vlasenko153fcaa2010-02-21 05:17:41 +010077#if !BB_MMU
Denis Vlasenko653d8e72009-03-19 21:59:35 +000078# error "Do not even bother, ash will not run on NOMMU machine"
Denis Vlasenkob012b102007-02-19 22:43:01 +000079#endif
80
Denis Vlasenkob012b102007-02-19 22:43:01 +000081
Denis Vlasenko01631112007-12-16 17:20:38 +000082/* ============ Hash table sizes. Configurable. */
83
84#define VTABSIZE 39
85#define ATABSIZE 39
86#define CMDTABLESIZE 31 /* should be prime */
87
88
Denis Vlasenkob012b102007-02-19 22:43:01 +000089/* ============ Shell options */
90
91static const char *const optletters_optnames[] = {
92 "e" "errexit",
93 "f" "noglob",
94 "I" "ignoreeof",
95 "i" "interactive",
96 "m" "monitor",
97 "n" "noexec",
98 "s" "stdin",
99 "x" "xtrace",
100 "v" "verbose",
101 "C" "noclobber",
102 "a" "allexport",
103 "b" "notify",
104 "u" "nounset",
Denys Vlasenkoe9ac32a2009-12-05 02:01:25 +0100105 "\0" "vi"
Michael Abbott359da5e2009-12-04 23:03:29 +0100106#if ENABLE_ASH_BASH_COMPAT
Denys Vlasenkoe9ac32a2009-12-05 02:01:25 +0100107 ,"\0" "pipefail"
Michael Abbott359da5e2009-12-04 23:03:29 +0100108#endif
Denis Vlasenkob012b102007-02-19 22:43:01 +0000109#if DEBUG
Denis Vlasenko6ca409e2007-08-12 20:58:27 +0000110 ,"\0" "nolog"
111 ,"\0" "debug"
Denis Vlasenkob012b102007-02-19 22:43:01 +0000112#endif
113};
114
Denys Vlasenko285ad152009-12-04 23:02:27 +0100115#define optletters(n) optletters_optnames[n][0]
116#define optnames(n) (optletters_optnames[n] + 1)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000117
Denis Vlasenko80b8b392007-06-25 10:55:35 +0000118enum { NOPTS = ARRAY_SIZE(optletters_optnames) };
Denis Vlasenkob012b102007-02-19 22:43:01 +0000119
Eric Andersenc470f442003-07-28 09:56:35 +0000120
Denis Vlasenkob012b102007-02-19 22:43:01 +0000121/* ============ Misc data */
Eric Andersenc470f442003-07-28 09:56:35 +0000122
Denys Vlasenkoea8b2522010-06-02 12:57:26 +0200123#define msg_illnum "Illegal number: %s"
Denis Vlasenkoaa744452007-02-23 01:04:22 +0000124
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +0000125/*
Eric Andersenc470f442003-07-28 09:56:35 +0000126 * We enclose jmp_buf in a structure so that we can declare pointers to
127 * jump locations. The global variable handler contains the location to
Denis Vlasenkof1733952009-03-19 23:21:55 +0000128 * jump to when an exception occurs, and the global variable exception_type
Eric Andersenaff114c2004-04-14 17:51:38 +0000129 * contains a code identifying the exception. To implement nested
Eric Andersenc470f442003-07-28 09:56:35 +0000130 * exception handlers, the user should save the value of handler on entry
131 * to an inner scope, set handler to point to a jmploc structure for the
132 * inner scope, and restore handler on exit from the scope.
133 */
Eric Andersenc470f442003-07-28 09:56:35 +0000134struct jmploc {
135 jmp_buf loc;
136};
Denis Vlasenko01631112007-12-16 17:20:38 +0000137
138struct globals_misc {
139 /* pid of main shell */
140 int rootpid;
141 /* shell level: 0 for the main shell, 1 for its children, and so on */
142 int shlvl;
143#define rootshell (!shlvl)
144 char *minusc; /* argument to -c option */
145
146 char *curdir; // = nullstr; /* current working directory */
147 char *physdir; // = nullstr; /* physical working directory */
148
149 char *arg0; /* value of $0 */
150
151 struct jmploc *exception_handler;
Denis Vlasenko991a1da2008-02-10 19:02:53 +0000152
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200153 volatile int suppress_int; /* counter */
154 volatile /*sig_atomic_t*/ smallint pending_int; /* 1 = got SIGINT */
Denis Vlasenko991a1da2008-02-10 19:02:53 +0000155 /* last pending signal */
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200156 volatile /*sig_atomic_t*/ smallint pending_sig;
Denis Vlasenko7f88e342009-03-19 03:36:18 +0000157 smallint exception_type; /* kind of exception (0..5) */
Denis Vlasenko01631112007-12-16 17:20:38 +0000158 /* exceptions */
Eric Andersenc470f442003-07-28 09:56:35 +0000159#define EXINT 0 /* SIGINT received */
160#define EXERROR 1 /* a generic error */
161#define EXSHELLPROC 2 /* execute a shell procedure */
162#define EXEXEC 3 /* command execution failed */
163#define EXEXIT 4 /* exit the shell */
164#define EXSIG 5 /* trapped signal in wait(1) */
Eric Andersen2870d962001-07-02 17:27:21 +0000165
Denis Vlasenko01631112007-12-16 17:20:38 +0000166 smallint isloginsh;
Denis Vlasenkob07a4962008-06-22 13:16:23 +0000167 char nullstr[1]; /* zero length string */
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000168
169 char optlist[NOPTS];
170#define eflag optlist[0]
171#define fflag optlist[1]
172#define Iflag optlist[2]
173#define iflag optlist[3]
174#define mflag optlist[4]
175#define nflag optlist[5]
176#define sflag optlist[6]
177#define xflag optlist[7]
178#define vflag optlist[8]
179#define Cflag optlist[9]
180#define aflag optlist[10]
181#define bflag optlist[11]
182#define uflag optlist[12]
183#define viflag optlist[13]
Michael Abbott359da5e2009-12-04 23:03:29 +0100184#if ENABLE_ASH_BASH_COMPAT
185# define pipefail optlist[14]
186#else
187# define pipefail 0
188#endif
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000189#if DEBUG
Michael Abbott359da5e2009-12-04 23:03:29 +0100190# define nolog optlist[14 + ENABLE_ASH_BASH_COMPAT]
191# define debug optlist[15 + ENABLE_ASH_BASH_COMPAT]
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000192#endif
193
194 /* trap handler commands */
Denis Vlasenko01631112007-12-16 17:20:38 +0000195 /*
196 * Sigmode records the current value of the signal handlers for the various
197 * modes. A value of zero means that the current handler is not known.
Denis Vlasenkof8535cc2008-12-03 10:36:26 +0000198 * S_HARD_IGN indicates that the signal was ignored on entry to the shell.
Denis Vlasenko01631112007-12-16 17:20:38 +0000199 */
200 char sigmode[NSIG - 1];
Denis Vlasenkof8535cc2008-12-03 10:36:26 +0000201#define S_DFL 1 /* default signal handling (SIG_DFL) */
202#define S_CATCH 2 /* signal is caught */
203#define S_IGN 3 /* signal is ignored (SIG_IGN) */
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +0000204#define S_HARD_IGN 4 /* signal is ignored permenantly */
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +0000205
Denis Vlasenko01631112007-12-16 17:20:38 +0000206 /* indicates specified signal received */
Denis Vlasenko4b875702009-03-19 13:30:04 +0000207 uint8_t gotsig[NSIG - 1]; /* offset by 1: "signal" 0 is meaningless */
Denys Vlasenko238bf182010-05-18 15:49:07 +0200208 uint8_t may_have_traps; /* 0: definitely no traps are set, 1: some traps may be set */
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000209 char *trap[NSIG];
Denys Vlasenko21d87d42009-09-25 00:06:51 +0200210 char **trap_ptr; /* used only by "trap hack" */
Denis Vlasenko448d30e2008-06-27 00:24:11 +0000211
212 /* Rarely referenced stuff */
213#if ENABLE_ASH_RANDOM_SUPPORT
Denys Vlasenko3ea2e822009-10-09 20:59:04 +0200214 random_t random_gen;
Denis Vlasenko448d30e2008-06-27 00:24:11 +0000215#endif
216 pid_t backgndpid; /* pid of last background process */
217 smallint job_warning; /* user was warned about stopped jobs (can be 2, 1 or 0). */
Denis Vlasenko01631112007-12-16 17:20:38 +0000218};
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000219extern struct globals_misc *const ash_ptr_to_globals_misc;
220#define G_misc (*ash_ptr_to_globals_misc)
Denis Vlasenko26bc57d2008-06-27 00:29:34 +0000221#define rootpid (G_misc.rootpid )
222#define shlvl (G_misc.shlvl )
223#define minusc (G_misc.minusc )
224#define curdir (G_misc.curdir )
225#define physdir (G_misc.physdir )
226#define arg0 (G_misc.arg0 )
Denis Vlasenko01631112007-12-16 17:20:38 +0000227#define exception_handler (G_misc.exception_handler)
Denis Vlasenko7f88e342009-03-19 03:36:18 +0000228#define exception_type (G_misc.exception_type )
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200229#define suppress_int (G_misc.suppress_int )
230#define pending_int (G_misc.pending_int )
231#define pending_sig (G_misc.pending_sig )
Denis Vlasenko26bc57d2008-06-27 00:29:34 +0000232#define isloginsh (G_misc.isloginsh )
233#define nullstr (G_misc.nullstr )
234#define optlist (G_misc.optlist )
235#define sigmode (G_misc.sigmode )
236#define gotsig (G_misc.gotsig )
Denys Vlasenko238bf182010-05-18 15:49:07 +0200237#define may_have_traps (G_misc.may_have_traps )
Denis Vlasenko26bc57d2008-06-27 00:29:34 +0000238#define trap (G_misc.trap )
Denys Vlasenko21d87d42009-09-25 00:06:51 +0200239#define trap_ptr (G_misc.trap_ptr )
Denys Vlasenko3ea2e822009-10-09 20:59:04 +0200240#define random_gen (G_misc.random_gen )
Denis Vlasenko448d30e2008-06-27 00:24:11 +0000241#define backgndpid (G_misc.backgndpid )
242#define job_warning (G_misc.job_warning)
Denis Vlasenko01631112007-12-16 17:20:38 +0000243#define INIT_G_misc() do { \
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000244 (*(struct globals_misc**)&ash_ptr_to_globals_misc) = xzalloc(sizeof(G_misc)); \
245 barrier(); \
Denis Vlasenko01631112007-12-16 17:20:38 +0000246 curdir = nullstr; \
247 physdir = nullstr; \
Denys Vlasenko21d87d42009-09-25 00:06:51 +0200248 trap_ptr = trap; \
Denis Vlasenko01631112007-12-16 17:20:38 +0000249} while (0)
250
251
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000252/* ============ DEBUG */
253#if DEBUG
254static void trace_printf(const char *fmt, ...);
255static void trace_vprintf(const char *fmt, va_list va);
256# define TRACE(param) trace_printf param
257# define TRACEV(param) trace_vprintf param
Denis Vlasenko1bb3d7e2009-03-20 07:45:36 +0000258# define close(fd) do { \
259 int dfd = (fd); \
Denis Vlasenkob9e70dd2009-03-20 01:24:08 +0000260 if (close(dfd) < 0) \
Denys Vlasenko883cea42009-07-11 15:31:59 +0200261 bb_error_msg("bug on %d: closing %d(0x%x)", \
Denis Vlasenko1bb3d7e2009-03-20 07:45:36 +0000262 __LINE__, dfd, dfd); \
Denis Vlasenkob9e70dd2009-03-20 01:24:08 +0000263} while (0)
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000264#else
265# define TRACE(param)
266# define TRACEV(param)
267#endif
268
269
Denis Vlasenko559691a2008-10-05 18:39:31 +0000270/* ============ Utility functions */
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000271#define xbarrier() do { __asm__ __volatile__ ("": : :"memory"); } while (0)
272
Denis Vlasenko559691a2008-10-05 18:39:31 +0000273static int isdigit_str9(const char *str)
274{
275 int maxlen = 9 + 1; /* max 9 digits: 999999999 */
276 while (--maxlen && isdigit(*str))
277 str++;
278 return (*str == '\0');
279}
Denis Vlasenko01631112007-12-16 17:20:38 +0000280
Denys Vlasenko8837c5d2010-06-02 12:56:18 +0200281static const char *var_end(const char *var)
282{
283 while (*var)
284 if (*var++ == '=')
285 break;
286 return var;
287}
288
Denis Vlasenko559691a2008-10-05 18:39:31 +0000289
290/* ============ Interrupts / exceptions */
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +0000291/*
Eric Andersen2870d962001-07-02 17:27:21 +0000292 * These macros allow the user to suspend the handling of interrupt signals
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +0000293 * over a period of time. This is similar to SIGHOLD or to sigblock, but
Eric Andersen2870d962001-07-02 17:27:21 +0000294 * much more efficient and portable. (But hacking the kernel is so much
295 * more fun than worrying about efficiency and portability. :-))
296 */
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000297#define INT_OFF do { \
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200298 suppress_int++; \
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000299 xbarrier(); \
300} while (0)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000301
302/*
303 * Called to raise an exception. Since C doesn't include exceptions, we
304 * just do a longjmp to the exception handler. The type of exception is
Denis Vlasenko4b875702009-03-19 13:30:04 +0000305 * stored in the global variable "exception_type".
Denis Vlasenkob012b102007-02-19 22:43:01 +0000306 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +0000307static void raise_exception(int) NORETURN;
Denis Vlasenkob012b102007-02-19 22:43:01 +0000308static void
309raise_exception(int e)
310{
311#if DEBUG
Denis Vlasenko2da584f2007-02-19 22:44:05 +0000312 if (exception_handler == NULL)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000313 abort();
314#endif
315 INT_OFF;
Denis Vlasenko7f88e342009-03-19 03:36:18 +0000316 exception_type = e;
Denis Vlasenko2da584f2007-02-19 22:44:05 +0000317 longjmp(exception_handler->loc, 1);
Denis Vlasenkob012b102007-02-19 22:43:01 +0000318}
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000319#if DEBUG
320#define raise_exception(e) do { \
321 TRACE(("raising exception %d on line %d\n", (e), __LINE__)); \
322 raise_exception(e); \
323} while (0)
324#endif
Denis Vlasenkob012b102007-02-19 22:43:01 +0000325
326/*
327 * Called from trap.c when a SIGINT is received. (If the user specifies
328 * that SIGINT is to be trapped or ignored using the trap builtin, then
329 * this routine is not called.) Suppressint is nonzero when interrupts
330 * are held using the INT_OFF macro. (The test for iflag is just
331 * defensive programming.)
332 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +0000333static void raise_interrupt(void) NORETURN;
Denis Vlasenkob012b102007-02-19 22:43:01 +0000334static void
335raise_interrupt(void)
336{
Denis Vlasenko4b875702009-03-19 13:30:04 +0000337 int ex_type;
Denis Vlasenkob012b102007-02-19 22:43:01 +0000338
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200339 pending_int = 0;
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +0000340 /* Signal is not automatically unmasked after it is raised,
341 * do it ourself - unmask all signals */
Denis Vlasenko3f165fa2008-03-17 08:29:08 +0000342 sigprocmask_allsigs(SIG_UNBLOCK);
Denys Vlasenko238bf182010-05-18 15:49:07 +0200343 /* pending_sig = 0; - now done in signal_handler() */
Denis Vlasenko7c139b42007-03-21 20:17:27 +0000344
Denis Vlasenko4b875702009-03-19 13:30:04 +0000345 ex_type = EXSIG;
Denis Vlasenkob012b102007-02-19 22:43:01 +0000346 if (gotsig[SIGINT - 1] && !trap[SIGINT]) {
347 if (!(rootshell && iflag)) {
Denis Vlasenko991a1da2008-02-10 19:02:53 +0000348 /* Kill ourself with SIGINT */
Denis Vlasenkob012b102007-02-19 22:43:01 +0000349 signal(SIGINT, SIG_DFL);
350 raise(SIGINT);
351 }
Denis Vlasenko4b875702009-03-19 13:30:04 +0000352 ex_type = EXINT;
Denis Vlasenkob012b102007-02-19 22:43:01 +0000353 }
Denis Vlasenko4b875702009-03-19 13:30:04 +0000354 raise_exception(ex_type);
Denis Vlasenkob012b102007-02-19 22:43:01 +0000355 /* NOTREACHED */
356}
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000357#if DEBUG
358#define raise_interrupt() do { \
359 TRACE(("raising interrupt on line %d\n", __LINE__)); \
360 raise_interrupt(); \
361} while (0)
362#endif
Denis Vlasenkob012b102007-02-19 22:43:01 +0000363
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000364static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000365int_on(void)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000366{
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +0000367 xbarrier();
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200368 if (--suppress_int == 0 && pending_int) {
Denis Vlasenkob012b102007-02-19 22:43:01 +0000369 raise_interrupt();
370 }
371}
372#define INT_ON int_on()
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000373static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000374force_int_on(void)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000375{
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +0000376 xbarrier();
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200377 suppress_int = 0;
378 if (pending_int)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000379 raise_interrupt();
380}
381#define FORCE_INT_ON force_int_on()
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000382
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200383#define SAVE_INT(v) ((v) = suppress_int)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000384
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000385#define RESTORE_INT(v) do { \
386 xbarrier(); \
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200387 suppress_int = (v); \
388 if (suppress_int == 0 && pending_int) \
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000389 raise_interrupt(); \
390} while (0)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000391
Glenn L McGrath9fef17d2002-08-22 18:41:20 +0000392
Denis Vlasenkobc54cff2007-02-23 01:05:52 +0000393/* ============ Stdout/stderr output */
Eric Andersenc470f442003-07-28 09:56:35 +0000394
Eric Andersenc470f442003-07-28 09:56:35 +0000395static void
Denis Vlasenkob012b102007-02-19 22:43:01 +0000396outstr(const char *p, FILE *file)
Denis Vlasenkoe5570da2007-02-19 22:41:55 +0000397{
Denis Vlasenkob012b102007-02-19 22:43:01 +0000398 INT_OFF;
399 fputs(p, file);
400 INT_ON;
401}
402
403static void
404flush_stdout_stderr(void)
405{
406 INT_OFF;
Denys Vlasenko8131eea2009-11-02 14:19:51 +0100407 fflush_all();
Denis Vlasenkob012b102007-02-19 22:43:01 +0000408 INT_ON;
409}
410
411static void
412outcslow(int c, FILE *dest)
413{
414 INT_OFF;
415 putc(c, dest);
416 fflush(dest);
417 INT_ON;
418}
419
420static int out1fmt(const char *, ...) __attribute__((__format__(__printf__,1,2)));
421static int
422out1fmt(const char *fmt, ...)
423{
424 va_list ap;
425 int r;
426
427 INT_OFF;
428 va_start(ap, fmt);
429 r = vprintf(fmt, ap);
430 va_end(ap);
431 INT_ON;
432 return r;
433}
434
435static int fmtstr(char *, size_t, const char *, ...) __attribute__((__format__(__printf__,3,4)));
436static int
437fmtstr(char *outbuf, size_t length, const char *fmt, ...)
438{
439 va_list ap;
440 int ret;
441
442 va_start(ap, fmt);
443 INT_OFF;
444 ret = vsnprintf(outbuf, length, fmt, ap);
445 va_end(ap);
446 INT_ON;
447 return ret;
448}
449
450static void
451out1str(const char *p)
452{
453 outstr(p, stdout);
454}
455
456static void
457out2str(const char *p)
458{
459 outstr(p, stderr);
Denys Vlasenko8131eea2009-11-02 14:19:51 +0100460 flush_stdout_stderr();
Denis Vlasenkob012b102007-02-19 22:43:01 +0000461}
462
463
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +0000464/* ============ Parser structures */
Denis Vlasenko4d2183b2007-02-23 01:05:38 +0000465
Denis Vlasenko5651bfc2007-02-23 21:08:58 +0000466/* control characters in argument strings */
Denys Vlasenko2ce42e92009-11-29 02:18:13 +0100467#define CTL_FIRST CTLESC
Denys Vlasenkob6c84342009-08-29 20:23:20 +0200468#define CTLESC ((unsigned char)'\201') /* escape next character */
469#define CTLVAR ((unsigned char)'\202') /* variable defn */
470#define CTLENDVAR ((unsigned char)'\203')
471#define CTLBACKQ ((unsigned char)'\204')
Denis Vlasenko5651bfc2007-02-23 21:08:58 +0000472#define CTLQUOTE 01 /* ored with CTLBACKQ code if in quotes */
473/* CTLBACKQ | CTLQUOTE == '\205' */
Denys Vlasenkob6c84342009-08-29 20:23:20 +0200474#define CTLARI ((unsigned char)'\206') /* arithmetic expression */
475#define CTLENDARI ((unsigned char)'\207')
476#define CTLQUOTEMARK ((unsigned char)'\210')
Denys Vlasenko2ce42e92009-11-29 02:18:13 +0100477#define CTL_LAST CTLQUOTEMARK
Denis Vlasenko5651bfc2007-02-23 21:08:58 +0000478
479/* variable substitution byte (follows CTLVAR) */
480#define VSTYPE 0x0f /* type of variable substitution */
481#define VSNUL 0x10 /* colon--treat the empty string as unset */
482#define VSQUOTE 0x80 /* inside double quotes--suppress splitting */
483
484/* values of VSTYPE field */
Denis Vlasenko92e13c22008-03-25 01:17:40 +0000485#define VSNORMAL 0x1 /* normal variable: $var or ${var} */
486#define VSMINUS 0x2 /* ${var-text} */
487#define VSPLUS 0x3 /* ${var+text} */
488#define VSQUESTION 0x4 /* ${var?message} */
489#define VSASSIGN 0x5 /* ${var=text} */
490#define VSTRIMRIGHT 0x6 /* ${var%pattern} */
491#define VSTRIMRIGHTMAX 0x7 /* ${var%%pattern} */
492#define VSTRIMLEFT 0x8 /* ${var#pattern} */
493#define VSTRIMLEFTMAX 0x9 /* ${var##pattern} */
494#define VSLENGTH 0xa /* ${#var} */
495#if ENABLE_ASH_BASH_COMPAT
496#define VSSUBSTR 0xc /* ${var:position:length} */
497#define VSREPLACE 0xd /* ${var/pattern/replacement} */
498#define VSREPLACEALL 0xe /* ${var//pattern/replacement} */
499#endif
Denis Vlasenko5651bfc2007-02-23 21:08:58 +0000500
Denis Vlasenko6ca409e2007-08-12 20:58:27 +0000501static const char dolatstr[] ALIGN1 = {
502 CTLVAR, VSNORMAL|VSQUOTE, '@', '=', '\0'
503};
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +0000504
Denis Vlasenko559691a2008-10-05 18:39:31 +0000505#define NCMD 0
506#define NPIPE 1
507#define NREDIR 2
508#define NBACKGND 3
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000509#define NSUBSHELL 4
Denis Vlasenko559691a2008-10-05 18:39:31 +0000510#define NAND 5
511#define NOR 6
512#define NSEMI 7
513#define NIF 8
514#define NWHILE 9
515#define NUNTIL 10
516#define NFOR 11
517#define NCASE 12
518#define NCLIST 13
519#define NDEFUN 14
520#define NARG 15
521#define NTO 16
522#if ENABLE_ASH_BASH_COMPAT
523#define NTO2 17
524#endif
525#define NCLOBBER 18
526#define NFROM 19
527#define NFROMTO 20
528#define NAPPEND 21
529#define NTOFD 22
530#define NFROMFD 23
531#define NHERE 24
532#define NXHERE 25
533#define NNOT 26
Denis Vlasenko340299a2008-11-21 10:36:36 +0000534#define N_NUMBER 27
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000535
536union node;
537
538struct ncmd {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000539 smallint type; /* Nxxxx */
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000540 union node *assign;
541 union node *args;
542 union node *redirect;
543};
544
545struct npipe {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000546 smallint type;
547 smallint pipe_backgnd;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000548 struct nodelist *cmdlist;
549};
550
551struct nredir {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000552 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000553 union node *n;
554 union node *redirect;
555};
556
557struct nbinary {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000558 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000559 union node *ch1;
560 union node *ch2;
561};
562
563struct nif {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000564 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000565 union node *test;
566 union node *ifpart;
567 union node *elsepart;
568};
569
570struct nfor {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000571 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000572 union node *args;
573 union node *body;
574 char *var;
575};
576
577struct ncase {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000578 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000579 union node *expr;
580 union node *cases;
581};
582
583struct nclist {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000584 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000585 union node *next;
586 union node *pattern;
587 union node *body;
588};
589
590struct narg {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000591 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000592 union node *next;
593 char *text;
594 struct nodelist *backquote;
595};
596
Denis Vlasenko559691a2008-10-05 18:39:31 +0000597/* nfile and ndup layout must match!
598 * NTOFD (>&fdnum) uses ndup structure, but we may discover mid-flight
599 * that it is actually NTO2 (>&file), and change its type.
600 */
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000601struct nfile {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000602 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000603 union node *next;
604 int fd;
Denis Vlasenko559691a2008-10-05 18:39:31 +0000605 int _unused_dupfd;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000606 union node *fname;
607 char *expfname;
608};
609
610struct ndup {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000611 smallint type;
Denis Vlasenko559691a2008-10-05 18:39:31 +0000612 union node *next;
613 int fd;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000614 int dupfd;
615 union node *vname;
Denis Vlasenko559691a2008-10-05 18:39:31 +0000616 char *_unused_expfname;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000617};
618
619struct nhere {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000620 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000621 union node *next;
622 int fd;
623 union node *doc;
624};
625
626struct nnot {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000627 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000628 union node *com;
629};
630
631union node {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000632 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000633 struct ncmd ncmd;
634 struct npipe npipe;
635 struct nredir nredir;
636 struct nbinary nbinary;
637 struct nif nif;
638 struct nfor nfor;
639 struct ncase ncase;
640 struct nclist nclist;
641 struct narg narg;
642 struct nfile nfile;
643 struct ndup ndup;
644 struct nhere nhere;
645 struct nnot nnot;
646};
647
Denys Vlasenko86e83ec2009-07-23 22:07:07 +0200648/*
649 * NODE_EOF is returned by parsecmd when it encounters an end of file.
650 * It must be distinct from NULL.
651 */
652#define NODE_EOF ((union node *) -1L)
653
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000654struct nodelist {
655 struct nodelist *next;
656 union node *n;
657};
658
659struct funcnode {
660 int count;
661 union node n;
662};
663
Denis Vlasenko5651bfc2007-02-23 21:08:58 +0000664/*
665 * Free a parse tree.
666 */
667static void
668freefunc(struct funcnode *f)
669{
670 if (f && --f->count < 0)
671 free(f);
672}
673
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000674
675/* ============ Debugging output */
676
677#if DEBUG
678
679static FILE *tracefile;
680
681static void
682trace_printf(const char *fmt, ...)
683{
684 va_list va;
685
686 if (debug != 1)
687 return;
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000688 if (DEBUG_TIME)
689 fprintf(tracefile, "%u ", (int) time(NULL));
690 if (DEBUG_PID)
691 fprintf(tracefile, "[%u] ", (int) getpid());
692 if (DEBUG_SIG)
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200693 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000694 va_start(va, fmt);
695 vfprintf(tracefile, fmt, va);
696 va_end(va);
697}
698
699static void
700trace_vprintf(const char *fmt, va_list va)
701{
702 if (debug != 1)
703 return;
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000704 if (DEBUG_TIME)
705 fprintf(tracefile, "%u ", (int) time(NULL));
706 if (DEBUG_PID)
707 fprintf(tracefile, "[%u] ", (int) getpid());
708 if (DEBUG_SIG)
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200709 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000710 vfprintf(tracefile, fmt, va);
711}
712
713static void
714trace_puts(const char *s)
715{
716 if (debug != 1)
717 return;
718 fputs(s, tracefile);
719}
720
721static void
722trace_puts_quoted(char *s)
723{
724 char *p;
725 char c;
726
727 if (debug != 1)
728 return;
729 putc('"', tracefile);
730 for (p = s; *p; p++) {
Denys Vlasenkocd716832009-11-28 22:14:02 +0100731 switch ((unsigned char)*p) {
732 case '\n': c = 'n'; goto backslash;
733 case '\t': c = 't'; goto backslash;
734 case '\r': c = 'r'; goto backslash;
735 case '\"': c = '\"'; goto backslash;
736 case '\\': c = '\\'; goto backslash;
737 case CTLESC: c = 'e'; goto backslash;
738 case CTLVAR: c = 'v'; goto backslash;
739 case CTLVAR+CTLQUOTE: c = 'V'; goto backslash;
740 case CTLBACKQ: c = 'q'; goto backslash;
741 case CTLBACKQ+CTLQUOTE: c = 'Q'; goto backslash;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000742 backslash:
743 putc('\\', tracefile);
744 putc(c, tracefile);
745 break;
746 default:
747 if (*p >= ' ' && *p <= '~')
748 putc(*p, tracefile);
749 else {
750 putc('\\', tracefile);
Denys Vlasenkocd716832009-11-28 22:14:02 +0100751 putc((*p >> 6) & 03, tracefile);
752 putc((*p >> 3) & 07, tracefile);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000753 putc(*p & 07, tracefile);
754 }
755 break;
756 }
757 }
758 putc('"', tracefile);
759}
760
761static void
762trace_puts_args(char **ap)
763{
764 if (debug != 1)
765 return;
766 if (!*ap)
767 return;
768 while (1) {
769 trace_puts_quoted(*ap);
770 if (!*++ap) {
771 putc('\n', tracefile);
772 break;
773 }
774 putc(' ', tracefile);
775 }
776}
777
778static void
779opentrace(void)
780{
781 char s[100];
782#ifdef O_APPEND
783 int flags;
784#endif
785
786 if (debug != 1) {
787 if (tracefile)
788 fflush(tracefile);
789 /* leave open because libedit might be using it */
790 return;
791 }
792 strcpy(s, "./trace");
793 if (tracefile) {
794 if (!freopen(s, "a", tracefile)) {
795 fprintf(stderr, "Can't re-open %s\n", s);
796 debug = 0;
797 return;
798 }
799 } else {
800 tracefile = fopen(s, "a");
801 if (tracefile == NULL) {
802 fprintf(stderr, "Can't open %s\n", s);
803 debug = 0;
804 return;
805 }
806 }
807#ifdef O_APPEND
Denis Vlasenkod37f2222007-08-19 13:42:08 +0000808 flags = fcntl(fileno(tracefile), F_GETFL);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000809 if (flags >= 0)
810 fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
811#endif
812 setlinebuf(tracefile);
813 fputs("\nTracing started.\n", tracefile);
814}
815
816static void
817indent(int amount, char *pfx, FILE *fp)
818{
819 int i;
820
821 for (i = 0; i < amount; i++) {
822 if (pfx && i == amount - 1)
823 fputs(pfx, fp);
824 putc('\t', fp);
825 }
826}
827
828/* little circular references here... */
829static void shtree(union node *n, int ind, char *pfx, FILE *fp);
830
831static void
832sharg(union node *arg, FILE *fp)
833{
834 char *p;
835 struct nodelist *bqlist;
Denys Vlasenkocd716832009-11-28 22:14:02 +0100836 unsigned char subtype;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000837
838 if (arg->type != NARG) {
839 out1fmt("<node type %d>\n", arg->type);
840 abort();
841 }
842 bqlist = arg->narg.backquote;
843 for (p = arg->narg.text; *p; p++) {
Denys Vlasenkocd716832009-11-28 22:14:02 +0100844 switch ((unsigned char)*p) {
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000845 case CTLESC:
846 putc(*++p, fp);
847 break;
848 case CTLVAR:
849 putc('$', fp);
850 putc('{', fp);
851 subtype = *++p;
852 if (subtype == VSLENGTH)
853 putc('#', fp);
854
855 while (*p != '=')
856 putc(*p++, fp);
857
858 if (subtype & VSNUL)
859 putc(':', fp);
860
861 switch (subtype & VSTYPE) {
862 case VSNORMAL:
863 putc('}', fp);
864 break;
865 case VSMINUS:
866 putc('-', fp);
867 break;
868 case VSPLUS:
869 putc('+', fp);
870 break;
871 case VSQUESTION:
872 putc('?', fp);
873 break;
874 case VSASSIGN:
875 putc('=', fp);
876 break;
877 case VSTRIMLEFT:
878 putc('#', fp);
879 break;
880 case VSTRIMLEFTMAX:
881 putc('#', fp);
882 putc('#', fp);
883 break;
884 case VSTRIMRIGHT:
885 putc('%', fp);
886 break;
887 case VSTRIMRIGHTMAX:
888 putc('%', fp);
889 putc('%', fp);
890 break;
891 case VSLENGTH:
892 break;
893 default:
894 out1fmt("<subtype %d>", subtype);
895 }
896 break;
897 case CTLENDVAR:
898 putc('}', fp);
899 break;
900 case CTLBACKQ:
901 case CTLBACKQ|CTLQUOTE:
902 putc('$', fp);
903 putc('(', fp);
904 shtree(bqlist->n, -1, NULL, fp);
905 putc(')', fp);
906 break;
907 default:
908 putc(*p, fp);
909 break;
910 }
911 }
912}
913
Denys Vlasenko641dd7b2009-06-11 19:30:19 +0200914static void
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000915shcmd(union node *cmd, FILE *fp)
916{
917 union node *np;
918 int first;
919 const char *s;
920 int dftfd;
921
922 first = 1;
923 for (np = cmd->ncmd.args; np; np = np->narg.next) {
Denis Vlasenko40ba9982007-07-14 00:48:29 +0000924 if (!first)
925 putc(' ', fp);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000926 sharg(np, fp);
927 first = 0;
928 }
929 for (np = cmd->ncmd.redirect; np; np = np->nfile.next) {
Denis Vlasenko40ba9982007-07-14 00:48:29 +0000930 if (!first)
931 putc(' ', fp);
932 dftfd = 0;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000933 switch (np->nfile.type) {
Denis Vlasenko40ba9982007-07-14 00:48:29 +0000934 case NTO: s = ">>"+1; dftfd = 1; break;
935 case NCLOBBER: s = ">|"; dftfd = 1; break;
936 case NAPPEND: s = ">>"; dftfd = 1; break;
Denis Vlasenko559691a2008-10-05 18:39:31 +0000937#if ENABLE_ASH_BASH_COMPAT
938 case NTO2:
939#endif
Denis Vlasenko40ba9982007-07-14 00:48:29 +0000940 case NTOFD: s = ">&"; dftfd = 1; break;
Denis Vlasenko559691a2008-10-05 18:39:31 +0000941 case NFROM: s = "<"; break;
Denis Vlasenko40ba9982007-07-14 00:48:29 +0000942 case NFROMFD: s = "<&"; break;
943 case NFROMTO: s = "<>"; break;
944 default: s = "*error*"; break;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000945 }
946 if (np->nfile.fd != dftfd)
947 fprintf(fp, "%d", np->nfile.fd);
948 fputs(s, fp);
949 if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
950 fprintf(fp, "%d", np->ndup.dupfd);
951 } else {
952 sharg(np->nfile.fname, fp);
953 }
954 first = 0;
955 }
956}
957
958static void
959shtree(union node *n, int ind, char *pfx, FILE *fp)
960{
961 struct nodelist *lp;
962 const char *s;
963
964 if (n == NULL)
965 return;
966
967 indent(ind, pfx, fp);
Denys Vlasenko86e83ec2009-07-23 22:07:07 +0200968
969 if (n == NODE_EOF) {
970 fputs("<EOF>", fp);
971 return;
972 }
973
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000974 switch (n->type) {
975 case NSEMI:
976 s = "; ";
977 goto binop;
978 case NAND:
979 s = " && ";
980 goto binop;
981 case NOR:
982 s = " || ";
983 binop:
984 shtree(n->nbinary.ch1, ind, NULL, fp);
985 /* if (ind < 0) */
986 fputs(s, fp);
987 shtree(n->nbinary.ch2, ind, NULL, fp);
988 break;
989 case NCMD:
990 shcmd(n, fp);
991 if (ind >= 0)
992 putc('\n', fp);
993 break;
994 case NPIPE:
995 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
Denys Vlasenko7cee00e2009-07-24 01:08:03 +0200996 shtree(lp->n, 0, NULL, fp);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000997 if (lp->next)
998 fputs(" | ", fp);
999 }
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00001000 if (n->npipe.pipe_backgnd)
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00001001 fputs(" &", fp);
1002 if (ind >= 0)
1003 putc('\n', fp);
1004 break;
1005 default:
1006 fprintf(fp, "<node type %d>", n->type);
1007 if (ind >= 0)
1008 putc('\n', fp);
1009 break;
1010 }
1011}
1012
1013static void
1014showtree(union node *n)
1015{
1016 trace_puts("showtree called\n");
Denys Vlasenko883cea42009-07-11 15:31:59 +02001017 shtree(n, 1, NULL, stderr);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00001018}
1019
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00001020#endif /* DEBUG */
1021
1022
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00001023/* ============ Parser data */
1024
1025/*
Denis Vlasenkob012b102007-02-19 22:43:01 +00001026 * ash_vmsg() needs parsefile->fd, hence parsefile definition is moved up.
1027 */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001028struct strlist {
1029 struct strlist *next;
1030 char *text;
1031};
1032
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00001033struct alias;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00001034
Denis Vlasenkob012b102007-02-19 22:43:01 +00001035struct strpush {
1036 struct strpush *prev; /* preceding string on stack */
Denis Vlasenko41eb3002008-11-28 03:42:31 +00001037 char *prev_string;
1038 int prev_left_in_line;
Denis Vlasenkob012b102007-02-19 22:43:01 +00001039#if ENABLE_ASH_ALIAS
1040 struct alias *ap; /* if push was associated with an alias */
1041#endif
1042 char *string; /* remember the string since it may change */
1043};
1044
1045struct parsefile {
1046 struct parsefile *prev; /* preceding file on stack */
1047 int linno; /* current line */
Denys Vlasenko79b3d422010-06-03 04:29:08 +02001048 int pf_fd; /* file descriptor (or -1 if string) */
Denis Vlasenko41eb3002008-11-28 03:42:31 +00001049 int left_in_line; /* number of chars left in this line */
1050 int left_in_buffer; /* number of chars left in this buffer past the line */
1051 char *next_to_pgetc; /* next char in buffer */
Denis Vlasenkob012b102007-02-19 22:43:01 +00001052 char *buf; /* input buffer */
1053 struct strpush *strpush; /* for pushing strings at this level */
1054 struct strpush basestrpush; /* so pushing one is fast */
1055};
1056
Denis Vlasenko448d30e2008-06-27 00:24:11 +00001057static struct parsefile basepf; /* top level input file */
Denis Vlasenkob07a4962008-06-22 13:16:23 +00001058static struct parsefile *g_parsefile = &basepf; /* current input file */
Denis Vlasenkob012b102007-02-19 22:43:01 +00001059static int startlinno; /* line # where last token started */
1060static char *commandname; /* currently executing command */
1061static struct strlist *cmdenviron; /* environment for builtin command */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00001062static uint8_t exitstatus; /* exit status of last command */
Denis Vlasenkob012b102007-02-19 22:43:01 +00001063
1064
1065/* ============ Message printing */
1066
1067static void
1068ash_vmsg(const char *msg, va_list ap)
1069{
1070 fprintf(stderr, "%s: ", arg0);
1071 if (commandname) {
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00001072 if (strcmp(arg0, commandname))
1073 fprintf(stderr, "%s: ", commandname);
Denys Vlasenko79b3d422010-06-03 04:29:08 +02001074 if (!iflag || g_parsefile->pf_fd > 0)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00001075 fprintf(stderr, "line %d: ", startlinno);
Eric Andersenc470f442003-07-28 09:56:35 +00001076 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00001077 vfprintf(stderr, msg, ap);
1078 outcslow('\n', stderr);
Eric Andersenc470f442003-07-28 09:56:35 +00001079}
Denis Vlasenkob012b102007-02-19 22:43:01 +00001080
1081/*
1082 * Exverror is called to raise the error exception. If the second argument
1083 * is not NULL then error prints an error message using printf style
1084 * formatting. It then raises the error exception.
1085 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001086static void ash_vmsg_and_raise(int, const char *, va_list) NORETURN;
Denis Vlasenkob012b102007-02-19 22:43:01 +00001087static void
1088ash_vmsg_and_raise(int cond, const char *msg, va_list ap)
Eric Andersenc470f442003-07-28 09:56:35 +00001089{
Denis Vlasenkob012b102007-02-19 22:43:01 +00001090#if DEBUG
1091 if (msg) {
1092 TRACE(("ash_vmsg_and_raise(%d, \"", cond));
1093 TRACEV((msg, ap));
1094 TRACE(("\") pid=%d\n", getpid()));
1095 } else
1096 TRACE(("ash_vmsg_and_raise(%d, NULL) pid=%d\n", cond, getpid()));
1097 if (msg)
1098#endif
1099 ash_vmsg(msg, ap);
1100
1101 flush_stdout_stderr();
1102 raise_exception(cond);
1103 /* NOTREACHED */
Eric Andersenc470f442003-07-28 09:56:35 +00001104}
Denis Vlasenkob012b102007-02-19 22:43:01 +00001105
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001106static void ash_msg_and_raise_error(const char *, ...) NORETURN;
Denis Vlasenkob012b102007-02-19 22:43:01 +00001107static void
1108ash_msg_and_raise_error(const char *msg, ...)
1109{
1110 va_list ap;
1111
1112 va_start(ap, msg);
1113 ash_vmsg_and_raise(EXERROR, msg, ap);
1114 /* NOTREACHED */
1115 va_end(ap);
1116}
1117
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00001118static void raise_error_syntax(const char *) NORETURN;
1119static void
1120raise_error_syntax(const char *msg)
1121{
1122 ash_msg_and_raise_error("syntax error: %s", msg);
1123 /* NOTREACHED */
1124}
1125
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001126static void ash_msg_and_raise(int, const char *, ...) NORETURN;
Denis Vlasenkob012b102007-02-19 22:43:01 +00001127static void
1128ash_msg_and_raise(int cond, const char *msg, ...)
1129{
1130 va_list ap;
1131
1132 va_start(ap, msg);
1133 ash_vmsg_and_raise(cond, msg, ap);
1134 /* NOTREACHED */
1135 va_end(ap);
1136}
1137
1138/*
1139 * error/warning routines for external builtins
1140 */
1141static void
1142ash_msg(const char *fmt, ...)
1143{
1144 va_list ap;
1145
1146 va_start(ap, fmt);
1147 ash_vmsg(fmt, ap);
1148 va_end(ap);
1149}
1150
1151/*
1152 * Return a string describing an error. The returned string may be a
1153 * pointer to a static buffer that will be overwritten on the next call.
1154 * Action describes the operation that got the error.
1155 */
1156static const char *
1157errmsg(int e, const char *em)
1158{
1159 if (e == ENOENT || e == ENOTDIR) {
1160 return em;
1161 }
1162 return strerror(e);
1163}
1164
1165
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001166/* ============ Memory allocation */
1167
Denys Vlasenkoe7670ff2009-10-11 00:45:25 +02001168#if 0
1169/* I consider these wrappers nearly useless:
1170 * ok, they return you to nearest exception handler, but
1171 * how much memory do you leak in the process, making
1172 * memory starvation worse?
1173 */
1174static void *
1175ckrealloc(void * p, size_t nbytes)
1176{
1177 p = realloc(p, nbytes);
1178 if (!p)
1179 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1180 return p;
1181}
1182
1183static void *
1184ckmalloc(size_t nbytes)
1185{
1186 return ckrealloc(NULL, nbytes);
1187}
1188
1189static void *
1190ckzalloc(size_t nbytes)
1191{
1192 return memset(ckmalloc(nbytes), 0, nbytes);
1193}
1194
1195static char *
1196ckstrdup(const char *s)
1197{
1198 char *p = strdup(s);
1199 if (!p)
1200 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1201 return p;
1202}
1203#else
1204/* Using bbox equivalents. They exit if out of memory */
1205# define ckrealloc xrealloc
1206# define ckmalloc xmalloc
1207# define ckzalloc xzalloc
1208# define ckstrdup xstrdup
1209#endif
1210
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001211/*
1212 * It appears that grabstackstr() will barf with such alignments
1213 * because stalloc() will return a string allocated in a new stackblock.
1214 */
1215#define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
1216enum {
1217 /* Most machines require the value returned from malloc to be aligned
1218 * in some way. The following macro will get this right
1219 * on many machines. */
Denys Vlasenko0e5e4ea2009-10-11 00:36:20 +02001220 SHELL_SIZE = sizeof(union { int i; char *cp; double d; }) - 1,
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001221 /* Minimum size of a block */
Denis Vlasenko01631112007-12-16 17:20:38 +00001222 MINSIZE = SHELL_ALIGN(504),
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001223};
1224
1225struct stack_block {
1226 struct stack_block *prev;
1227 char space[MINSIZE];
1228};
1229
1230struct stackmark {
1231 struct stack_block *stackp;
1232 char *stacknxt;
1233 size_t stacknleft;
1234 struct stackmark *marknext;
1235};
1236
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001237
Denis Vlasenko01631112007-12-16 17:20:38 +00001238struct globals_memstack {
1239 struct stack_block *g_stackp; // = &stackbase;
1240 struct stackmark *markp;
1241 char *g_stacknxt; // = stackbase.space;
1242 char *sstrend; // = stackbase.space + MINSIZE;
1243 size_t g_stacknleft; // = MINSIZE;
1244 int herefd; // = -1;
1245 struct stack_block stackbase;
1246};
Denis Vlasenko574f2f42008-02-27 18:41:59 +00001247extern struct globals_memstack *const ash_ptr_to_globals_memstack;
1248#define G_memstack (*ash_ptr_to_globals_memstack)
Denis Vlasenko01631112007-12-16 17:20:38 +00001249#define g_stackp (G_memstack.g_stackp )
1250#define markp (G_memstack.markp )
1251#define g_stacknxt (G_memstack.g_stacknxt )
1252#define sstrend (G_memstack.sstrend )
1253#define g_stacknleft (G_memstack.g_stacknleft)
1254#define herefd (G_memstack.herefd )
1255#define stackbase (G_memstack.stackbase )
1256#define INIT_G_memstack() do { \
Denis Vlasenko574f2f42008-02-27 18:41:59 +00001257 (*(struct globals_memstack**)&ash_ptr_to_globals_memstack) = xzalloc(sizeof(G_memstack)); \
1258 barrier(); \
Denis Vlasenko01631112007-12-16 17:20:38 +00001259 g_stackp = &stackbase; \
1260 g_stacknxt = stackbase.space; \
1261 g_stacknleft = MINSIZE; \
1262 sstrend = stackbase.space + MINSIZE; \
1263 herefd = -1; \
1264} while (0)
1265
Denys Vlasenkoe7670ff2009-10-11 00:45:25 +02001266
Denis Vlasenko01631112007-12-16 17:20:38 +00001267#define stackblock() ((void *)g_stacknxt)
1268#define stackblocksize() g_stacknleft
1269
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001270/*
1271 * Parse trees for commands are allocated in lifo order, so we use a stack
1272 * to make this more efficient, and also to avoid all sorts of exception
1273 * handling code to handle interrupts in the middle of a parse.
1274 *
1275 * The size 504 was chosen because the Ultrix malloc handles that size
1276 * well.
1277 */
1278static void *
1279stalloc(size_t nbytes)
1280{
1281 char *p;
1282 size_t aligned;
1283
1284 aligned = SHELL_ALIGN(nbytes);
Denis Vlasenko01631112007-12-16 17:20:38 +00001285 if (aligned > g_stacknleft) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001286 size_t len;
1287 size_t blocksize;
1288 struct stack_block *sp;
1289
1290 blocksize = aligned;
1291 if (blocksize < MINSIZE)
1292 blocksize = MINSIZE;
1293 len = sizeof(struct stack_block) - MINSIZE + blocksize;
1294 if (len < blocksize)
1295 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1296 INT_OFF;
1297 sp = ckmalloc(len);
Denis Vlasenko01631112007-12-16 17:20:38 +00001298 sp->prev = g_stackp;
1299 g_stacknxt = sp->space;
1300 g_stacknleft = blocksize;
1301 sstrend = g_stacknxt + blocksize;
1302 g_stackp = sp;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001303 INT_ON;
1304 }
Denis Vlasenko01631112007-12-16 17:20:38 +00001305 p = g_stacknxt;
1306 g_stacknxt += aligned;
1307 g_stacknleft -= aligned;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001308 return p;
1309}
1310
Denis Vlasenko597906c2008-02-20 16:38:54 +00001311static void *
1312stzalloc(size_t nbytes)
1313{
1314 return memset(stalloc(nbytes), 0, nbytes);
1315}
1316
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001317static void
1318stunalloc(void *p)
1319{
1320#if DEBUG
Denis Vlasenko01631112007-12-16 17:20:38 +00001321 if (!p || (g_stacknxt < (char *)p) || ((char *)p < g_stackp->space)) {
Bernhard Reutner-Fischer5e25ddb2008-05-19 09:48:17 +00001322 write(STDERR_FILENO, "stunalloc\n", 10);
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001323 abort();
1324 }
1325#endif
Denis Vlasenko01631112007-12-16 17:20:38 +00001326 g_stacknleft += g_stacknxt - (char *)p;
1327 g_stacknxt = p;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001328}
1329
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001330/*
1331 * Like strdup but works with the ash stack.
1332 */
1333static char *
1334ststrdup(const char *p)
1335{
1336 size_t len = strlen(p) + 1;
1337 return memcpy(stalloc(len), p, len);
1338}
1339
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001340static void
1341setstackmark(struct stackmark *mark)
1342{
Denis Vlasenko01631112007-12-16 17:20:38 +00001343 mark->stackp = g_stackp;
1344 mark->stacknxt = g_stacknxt;
1345 mark->stacknleft = g_stacknleft;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001346 mark->marknext = markp;
1347 markp = mark;
1348}
1349
1350static void
1351popstackmark(struct stackmark *mark)
1352{
1353 struct stack_block *sp;
1354
Denis Vlasenko93ebd4f2007-03-13 20:55:36 +00001355 if (!mark->stackp)
1356 return;
1357
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001358 INT_OFF;
1359 markp = mark->marknext;
Denis Vlasenko01631112007-12-16 17:20:38 +00001360 while (g_stackp != mark->stackp) {
1361 sp = g_stackp;
1362 g_stackp = sp->prev;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001363 free(sp);
1364 }
Denis Vlasenko01631112007-12-16 17:20:38 +00001365 g_stacknxt = mark->stacknxt;
1366 g_stacknleft = mark->stacknleft;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001367 sstrend = mark->stacknxt + mark->stacknleft;
1368 INT_ON;
1369}
1370
1371/*
1372 * When the parser reads in a string, it wants to stick the string on the
1373 * stack and only adjust the stack pointer when it knows how big the
1374 * string is. Stackblock (defined in stack.h) returns a pointer to a block
1375 * of space on top of the stack and stackblocklen returns the length of
1376 * this block. Growstackblock will grow this space by at least one byte,
1377 * possibly moving it (like realloc). Grabstackblock actually allocates the
1378 * part of the block that has been used.
1379 */
1380static void
1381growstackblock(void)
1382{
1383 size_t newlen;
1384
Denis Vlasenko01631112007-12-16 17:20:38 +00001385 newlen = g_stacknleft * 2;
1386 if (newlen < g_stacknleft)
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001387 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1388 if (newlen < 128)
1389 newlen += 128;
1390
Denis Vlasenko01631112007-12-16 17:20:38 +00001391 if (g_stacknxt == g_stackp->space && g_stackp != &stackbase) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001392 struct stack_block *oldstackp;
1393 struct stackmark *xmark;
1394 struct stack_block *sp;
1395 struct stack_block *prevstackp;
1396 size_t grosslen;
1397
1398 INT_OFF;
Denis Vlasenko01631112007-12-16 17:20:38 +00001399 oldstackp = g_stackp;
1400 sp = g_stackp;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001401 prevstackp = sp->prev;
1402 grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
1403 sp = ckrealloc(sp, grosslen);
1404 sp->prev = prevstackp;
Denis Vlasenko01631112007-12-16 17:20:38 +00001405 g_stackp = sp;
1406 g_stacknxt = sp->space;
1407 g_stacknleft = newlen;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001408 sstrend = sp->space + newlen;
1409
1410 /*
1411 * Stack marks pointing to the start of the old block
1412 * must be relocated to point to the new block
1413 */
1414 xmark = markp;
1415 while (xmark != NULL && xmark->stackp == oldstackp) {
Denis Vlasenko01631112007-12-16 17:20:38 +00001416 xmark->stackp = g_stackp;
1417 xmark->stacknxt = g_stacknxt;
1418 xmark->stacknleft = g_stacknleft;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001419 xmark = xmark->marknext;
1420 }
1421 INT_ON;
1422 } else {
Denis Vlasenko01631112007-12-16 17:20:38 +00001423 char *oldspace = g_stacknxt;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00001424 size_t oldlen = g_stacknleft;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001425 char *p = stalloc(newlen);
1426
1427 /* free the space we just allocated */
Denis Vlasenko01631112007-12-16 17:20:38 +00001428 g_stacknxt = memcpy(p, oldspace, oldlen);
1429 g_stacknleft += newlen;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001430 }
1431}
1432
1433static void
1434grabstackblock(size_t len)
1435{
1436 len = SHELL_ALIGN(len);
Denis Vlasenko01631112007-12-16 17:20:38 +00001437 g_stacknxt += len;
1438 g_stacknleft -= len;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001439}
1440
1441/*
1442 * The following routines are somewhat easier to use than the above.
1443 * The user declares a variable of type STACKSTR, which may be declared
1444 * to be a register. The macro STARTSTACKSTR initializes things. Then
1445 * the user uses the macro STPUTC to add characters to the string. In
1446 * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
1447 * grown as necessary. When the user is done, she can just leave the
1448 * string there and refer to it using stackblock(). Or she can allocate
1449 * the space for it using grabstackstr(). If it is necessary to allow
1450 * someone else to use the stack temporarily and then continue to grow
1451 * the string, the user should use grabstack to allocate the space, and
1452 * then call ungrabstr(p) to return to the previous mode of operation.
1453 *
1454 * USTPUTC is like STPUTC except that it doesn't check for overflow.
1455 * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
1456 * is space for at least one character.
1457 */
1458static void *
1459growstackstr(void)
1460{
1461 size_t len = stackblocksize();
1462 if (herefd >= 0 && len >= 1024) {
1463 full_write(herefd, stackblock(), len);
1464 return stackblock();
1465 }
1466 growstackblock();
Denis Vlasenko29eb3592008-05-18 14:06:08 +00001467 return (char *)stackblock() + len;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001468}
1469
1470/*
1471 * Called from CHECKSTRSPACE.
1472 */
1473static char *
1474makestrspace(size_t newlen, char *p)
1475{
Denis Vlasenko01631112007-12-16 17:20:38 +00001476 size_t len = p - g_stacknxt;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001477 size_t size = stackblocksize();
1478
1479 for (;;) {
1480 size_t nleft;
1481
1482 size = stackblocksize();
1483 nleft = size - len;
1484 if (nleft >= newlen)
1485 break;
1486 growstackblock();
1487 }
Denis Vlasenko29eb3592008-05-18 14:06:08 +00001488 return (char *)stackblock() + len;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001489}
1490
1491static char *
1492stack_nputstr(const char *s, size_t n, char *p)
1493{
1494 p = makestrspace(n, p);
Denis Vlasenko29eb3592008-05-18 14:06:08 +00001495 p = (char *)memcpy(p, s, n) + n;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001496 return p;
1497}
1498
1499static char *
1500stack_putstr(const char *s, char *p)
1501{
1502 return stack_nputstr(s, strlen(s), p);
1503}
1504
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001505static char *
1506_STPUTC(int c, char *p)
1507{
1508 if (p == sstrend)
1509 p = growstackstr();
1510 *p++ = c;
1511 return p;
1512}
1513
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00001514#define STARTSTACKSTR(p) ((p) = stackblock())
1515#define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
Denis Vlasenko843cbd52008-06-27 00:23:18 +00001516#define CHECKSTRSPACE(n, p) do { \
1517 char *q = (p); \
1518 size_t l = (n); \
1519 size_t m = sstrend - q; \
1520 if (l > m) \
1521 (p) = makestrspace(l, q); \
1522} while (0)
Denis Vlasenkoef527f52008-06-23 01:52:30 +00001523#define USTPUTC(c, p) (*(p)++ = (c))
Denis Vlasenko843cbd52008-06-27 00:23:18 +00001524#define STACKSTRNUL(p) do { \
1525 if ((p) == sstrend) \
1526 (p) = growstackstr(); \
1527 *(p) = '\0'; \
1528} while (0)
Denis Vlasenkoef527f52008-06-23 01:52:30 +00001529#define STUNPUTC(p) (--(p))
1530#define STTOPC(p) ((p)[-1])
1531#define STADJUST(amount, p) ((p) += (amount))
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001532
1533#define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
Denis Vlasenkoef527f52008-06-23 01:52:30 +00001534#define ungrabstackstr(s, p) stunalloc(s)
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001535#define stackstrend() ((void *)sstrend)
1536
1537
1538/* ============ String helpers */
1539
1540/*
1541 * prefix -- see if pfx is a prefix of string.
1542 */
1543static char *
1544prefix(const char *string, const char *pfx)
1545{
1546 while (*pfx) {
1547 if (*pfx++ != *string++)
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00001548 return NULL;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001549 }
1550 return (char *) string;
1551}
1552
1553/*
1554 * Check for a valid number. This should be elsewhere.
1555 */
1556static int
1557is_number(const char *p)
1558{
1559 do {
1560 if (!isdigit(*p))
1561 return 0;
1562 } while (*++p != '\0');
1563 return 1;
1564}
1565
1566/*
1567 * Convert a string of digits to an integer, printing an error message on
1568 * failure.
1569 */
1570static int
1571number(const char *s)
1572{
1573 if (!is_number(s))
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02001574 ash_msg_and_raise_error(msg_illnum, s);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001575 return atoi(s);
1576}
1577
1578/*
1579 * Produce a possibly single quoted string suitable as input to the shell.
1580 * The return string is allocated on the stack.
1581 */
1582static char *
1583single_quote(const char *s)
1584{
1585 char *p;
1586
1587 STARTSTACKSTR(p);
1588
1589 do {
1590 char *q;
1591 size_t len;
1592
1593 len = strchrnul(s, '\'') - s;
1594
1595 q = p = makestrspace(len + 3, p);
1596
1597 *q++ = '\'';
Denis Vlasenko29eb3592008-05-18 14:06:08 +00001598 q = (char *)memcpy(q, s, len) + len;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001599 *q++ = '\'';
1600 s += len;
1601
1602 STADJUST(q - p, p);
1603
Denys Vlasenkocd716832009-11-28 22:14:02 +01001604 if (*s != '\'')
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001605 break;
Denys Vlasenkocd716832009-11-28 22:14:02 +01001606 len = 0;
1607 do len++; while (*++s == '\'');
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001608
1609 q = p = makestrspace(len + 3, p);
1610
1611 *q++ = '"';
Denys Vlasenkocd716832009-11-28 22:14:02 +01001612 q = (char *)memcpy(q, s - len, len) + len;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001613 *q++ = '"';
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001614
1615 STADJUST(q - p, p);
1616 } while (*s);
1617
Denys Vlasenkocd716832009-11-28 22:14:02 +01001618 USTPUTC('\0', p);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001619
1620 return stackblock();
1621}
1622
1623
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00001624/* ============ nextopt */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001625
1626static char **argptr; /* argument list for builtin commands */
1627static char *optionarg; /* set by nextopt (like getopt) */
1628static char *optptr; /* used by nextopt */
1629
1630/*
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001631 * XXX - should get rid of. Have all builtins use getopt(3).
1632 * The library getopt must have the BSD extension static variable
1633 * "optreset", otherwise it can't be used within the shell safely.
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001634 *
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001635 * Standard option processing (a la getopt) for builtin routines.
1636 * The only argument that is passed to nextopt is the option string;
1637 * the other arguments are unnecessary. It returns the character,
1638 * or '\0' on end of input.
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001639 */
1640static int
1641nextopt(const char *optstring)
1642{
1643 char *p;
1644 const char *q;
1645 char c;
1646
1647 p = optptr;
1648 if (p == NULL || *p == '\0') {
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001649 /* We ate entire "-param", take next one */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001650 p = *argptr;
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001651 if (p == NULL)
1652 return '\0';
1653 if (*p != '-')
1654 return '\0';
1655 if (*++p == '\0') /* just "-" ? */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001656 return '\0';
1657 argptr++;
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001658 if (LONE_DASH(p)) /* "--" ? */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001659 return '\0';
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001660 /* p => next "-param" */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001661 }
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001662 /* p => some option char in the middle of a "-param" */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001663 c = *p++;
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +00001664 for (q = optstring; *q != c;) {
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001665 if (*q == '\0')
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00001666 ash_msg_and_raise_error("illegal option -%c", c);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001667 if (*++q == ':')
1668 q++;
1669 }
1670 if (*++q == ':') {
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001671 if (*p == '\0') {
1672 p = *argptr++;
1673 if (p == NULL)
1674 ash_msg_and_raise_error("no arg for -%c option", c);
1675 }
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001676 optionarg = p;
1677 p = NULL;
1678 }
1679 optptr = p;
1680 return c;
1681}
1682
1683
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00001684/* ============ Shell variables */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001685
Denis Vlasenko01631112007-12-16 17:20:38 +00001686/*
1687 * The parsefile structure pointed to by the global variable parsefile
1688 * contains information about the current file being read.
1689 */
Denis Vlasenko01631112007-12-16 17:20:38 +00001690struct shparam {
1691 int nparam; /* # of positional parameters (without $0) */
1692#if ENABLE_ASH_GETOPTS
1693 int optind; /* next parameter to be processed by getopts */
1694 int optoff; /* used by getopts */
1695#endif
1696 unsigned char malloced; /* if parameter list dynamically allocated */
1697 char **p; /* parameter list */
1698};
1699
1700/*
1701 * Free the list of positional parameters.
1702 */
1703static void
1704freeparam(volatile struct shparam *param)
1705{
Denis Vlasenko01631112007-12-16 17:20:38 +00001706 if (param->malloced) {
Denis Vlasenko3177ba02008-07-13 20:39:23 +00001707 char **ap, **ap1;
1708 ap = ap1 = param->p;
1709 while (*ap)
1710 free(*ap++);
1711 free(ap1);
Denis Vlasenko01631112007-12-16 17:20:38 +00001712 }
1713}
1714
1715#if ENABLE_ASH_GETOPTS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001716static void FAST_FUNC getoptsreset(const char *value);
Denis Vlasenko01631112007-12-16 17:20:38 +00001717#endif
1718
1719struct var {
1720 struct var *next; /* next entry in hash list */
1721 int flags; /* flags are defined above */
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02001722 const char *var_text; /* name=value */
1723 void (*var_func)(const char *) FAST_FUNC; /* function to be called when */
Denis Vlasenko01631112007-12-16 17:20:38 +00001724 /* the variable gets set/unset */
1725};
1726
1727struct localvar {
1728 struct localvar *next; /* next local variable in list */
1729 struct var *vp; /* the variable that was made local */
1730 int flags; /* saved flags */
1731 const char *text; /* saved text */
1732};
1733
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001734/* flags */
1735#define VEXPORT 0x01 /* variable is exported */
1736#define VREADONLY 0x02 /* variable cannot be modified */
1737#define VSTRFIXED 0x04 /* variable struct is statically allocated */
1738#define VTEXTFIXED 0x08 /* text is statically allocated */
1739#define VSTACK 0x10 /* text is allocated on the stack */
1740#define VUNSET 0x20 /* the variable is not set */
1741#define VNOFUNC 0x40 /* don't call the callback function */
1742#define VNOSET 0x80 /* do not set variable - just readonly test */
1743#define VNOSAVE 0x100 /* when text is on the heap before setvareq */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00001744#if ENABLE_ASH_RANDOM_SUPPORT
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00001745# define VDYNAMIC 0x200 /* dynamic variable */
1746#else
1747# define VDYNAMIC 0
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001748#endif
1749
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00001750
Denis Vlasenko01631112007-12-16 17:20:38 +00001751/* Need to be before varinit_data[] */
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00001752#if ENABLE_LOCALE_SUPPORT
Denys Vlasenko2634bf32009-06-09 18:40:07 +02001753static void FAST_FUNC
Denis Vlasenkoa8915072007-02-23 21:10:06 +00001754change_lc_all(const char *value)
1755{
1756 if (value && *value != '\0')
1757 setlocale(LC_ALL, value);
1758}
Denys Vlasenko2634bf32009-06-09 18:40:07 +02001759static void FAST_FUNC
Denis Vlasenkoa8915072007-02-23 21:10:06 +00001760change_lc_ctype(const char *value)
1761{
1762 if (value && *value != '\0')
1763 setlocale(LC_CTYPE, value);
1764}
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00001765#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001766#if ENABLE_ASH_MAIL
1767static void chkmail(void);
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001768static void changemail(const char *) FAST_FUNC;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001769#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001770static void changepath(const char *) FAST_FUNC;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001771#if ENABLE_ASH_RANDOM_SUPPORT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001772static void change_random(const char *) FAST_FUNC;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001773#endif
1774
Denis Vlasenko01631112007-12-16 17:20:38 +00001775static const struct {
1776 int flags;
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02001777 const char *var_text;
1778 void (*var_func)(const char *) FAST_FUNC;
Denis Vlasenko01631112007-12-16 17:20:38 +00001779} varinit_data[] = {
Denis Vlasenko01631112007-12-16 17:20:38 +00001780 { VSTRFIXED|VTEXTFIXED , defifsvar , NULL },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001781#if ENABLE_ASH_MAIL
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02001782 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL" , changemail },
1783 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH" , changemail },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001784#endif
Denis Vlasenko01631112007-12-16 17:20:38 +00001785 { VSTRFIXED|VTEXTFIXED , bb_PATH_root_path, changepath },
1786 { VSTRFIXED|VTEXTFIXED , "PS1=$ " , NULL },
1787 { VSTRFIXED|VTEXTFIXED , "PS2=> " , NULL },
1788 { VSTRFIXED|VTEXTFIXED , "PS4=+ " , NULL },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001789#if ENABLE_ASH_GETOPTS
Denis Vlasenko01631112007-12-16 17:20:38 +00001790 { VSTRFIXED|VTEXTFIXED , "OPTIND=1" , getoptsreset },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001791#endif
1792#if ENABLE_ASH_RANDOM_SUPPORT
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02001793 { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM", change_random },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001794#endif
1795#if ENABLE_LOCALE_SUPPORT
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02001796 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL" , change_lc_all },
1797 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE" , change_lc_ctype },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001798#endif
1799#if ENABLE_FEATURE_EDITING_SAVEHISTORY
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02001800 { VSTRFIXED|VTEXTFIXED|VUNSET, "HISTFILE" , NULL },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001801#endif
1802};
1803
Denis Vlasenko0b769642008-07-24 07:54:57 +00001804struct redirtab;
Denis Vlasenko01631112007-12-16 17:20:38 +00001805
1806struct globals_var {
1807 struct shparam shellparam; /* $@ current positional parameters */
1808 struct redirtab *redirlist;
1809 int g_nullredirs;
1810 int preverrout_fd; /* save fd2 before print debug if xflag is set. */
1811 struct var *vartab[VTABSIZE];
1812 struct var varinit[ARRAY_SIZE(varinit_data)];
1813};
Denis Vlasenko574f2f42008-02-27 18:41:59 +00001814extern struct globals_var *const ash_ptr_to_globals_var;
1815#define G_var (*ash_ptr_to_globals_var)
Denis Vlasenko01631112007-12-16 17:20:38 +00001816#define shellparam (G_var.shellparam )
Denis Vlasenko0b769642008-07-24 07:54:57 +00001817//#define redirlist (G_var.redirlist )
Denis Vlasenko01631112007-12-16 17:20:38 +00001818#define g_nullredirs (G_var.g_nullredirs )
1819#define preverrout_fd (G_var.preverrout_fd)
1820#define vartab (G_var.vartab )
1821#define varinit (G_var.varinit )
1822#define INIT_G_var() do { \
Denis Vlasenko6b06cb82008-05-15 21:30:45 +00001823 unsigned i; \
Denis Vlasenko574f2f42008-02-27 18:41:59 +00001824 (*(struct globals_var**)&ash_ptr_to_globals_var) = xzalloc(sizeof(G_var)); \
1825 barrier(); \
Denis Vlasenko01631112007-12-16 17:20:38 +00001826 for (i = 0; i < ARRAY_SIZE(varinit_data); i++) { \
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02001827 varinit[i].flags = varinit_data[i].flags; \
1828 varinit[i].var_text = varinit_data[i].var_text; \
1829 varinit[i].var_func = varinit_data[i].var_func; \
Denis Vlasenko01631112007-12-16 17:20:38 +00001830 } \
1831} while (0)
1832
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001833#define vifs varinit[0]
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001834#if ENABLE_ASH_MAIL
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001835# define vmail (&vifs)[1]
1836# define vmpath (&vmail)[1]
1837# define vpath (&vmpath)[1]
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001838#else
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001839# define vpath (&vifs)[1]
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001840#endif
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001841#define vps1 (&vpath)[1]
1842#define vps2 (&vps1)[1]
1843#define vps4 (&vps2)[1]
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001844#if ENABLE_ASH_GETOPTS
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001845# define voptind (&vps4)[1]
1846# if ENABLE_ASH_RANDOM_SUPPORT
1847# define vrandom (&voptind)[1]
1848# endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001849#else
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001850# if ENABLE_ASH_RANDOM_SUPPORT
1851# define vrandom (&vps4)[1]
1852# endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001853#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001854
1855/*
1856 * The following macros access the values of the above variables.
1857 * They have to skip over the name. They return the null string
1858 * for unset variables.
1859 */
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02001860#define ifsval() (vifs.var_text + 4)
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001861#define ifsset() ((vifs.flags & VUNSET) == 0)
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001862#if ENABLE_ASH_MAIL
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02001863# define mailval() (vmail.var_text + 5)
1864# define mpathval() (vmpath.var_text + 9)
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001865# define mpathset() ((vmpath.flags & VUNSET) == 0)
1866#endif
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02001867#define pathval() (vpath.var_text + 5)
1868#define ps1val() (vps1.var_text + 4)
1869#define ps2val() (vps2.var_text + 4)
1870#define ps4val() (vps4.var_text + 4)
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001871#if ENABLE_ASH_GETOPTS
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02001872# define optindval() (voptind.var_text + 7)
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001873#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001874
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001875
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001876#define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
1877#define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
1878
Denis Vlasenko01631112007-12-16 17:20:38 +00001879#if ENABLE_ASH_GETOPTS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001880static void FAST_FUNC
Denis Vlasenko01631112007-12-16 17:20:38 +00001881getoptsreset(const char *value)
1882{
1883 shellparam.optind = number(value);
1884 shellparam.optoff = -1;
1885}
1886#endif
1887
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001888/*
1889 * Return of a legal variable name (a letter or underscore followed by zero or
1890 * more letters, underscores, and digits).
1891 */
Denys Vlasenko03dad222010-01-12 23:29:57 +01001892static char* FAST_FUNC
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001893endofname(const char *name)
1894{
1895 char *p;
1896
1897 p = (char *) name;
1898 if (!is_name(*p))
1899 return p;
1900 while (*++p) {
1901 if (!is_in_name(*p))
1902 break;
1903 }
1904 return p;
1905}
1906
1907/*
1908 * Compares two strings up to the first = or '\0'. The first
1909 * string must be terminated by '='; the second may be terminated by
1910 * either '=' or '\0'.
1911 */
1912static int
1913varcmp(const char *p, const char *q)
1914{
1915 int c, d;
1916
1917 while ((c = *p) == (d = *q)) {
1918 if (!c || c == '=')
1919 goto out;
1920 p++;
1921 q++;
1922 }
1923 if (c == '=')
Denis Vlasenko9650f362007-02-23 01:04:37 +00001924 c = '\0';
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001925 if (d == '=')
Denis Vlasenko9650f362007-02-23 01:04:37 +00001926 d = '\0';
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001927 out:
1928 return c - d;
1929}
1930
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001931/*
1932 * Find the appropriate entry in the hash table from the name.
1933 */
1934static struct var **
1935hashvar(const char *p)
1936{
1937 unsigned hashval;
1938
1939 hashval = ((unsigned char) *p) << 4;
1940 while (*p && *p != '=')
1941 hashval += (unsigned char) *p++;
1942 return &vartab[hashval % VTABSIZE];
1943}
1944
1945static int
1946vpcmp(const void *a, const void *b)
1947{
1948 return varcmp(*(const char **)a, *(const char **)b);
1949}
1950
1951/*
1952 * This routine initializes the builtin variables.
1953 */
1954static void
1955initvar(void)
1956{
1957 struct var *vp;
1958 struct var *end;
1959 struct var **vpp;
1960
1961 /*
1962 * PS1 depends on uid
1963 */
1964#if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02001965 vps1.var_text = "PS1=\\w \\$ ";
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001966#else
1967 if (!geteuid())
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02001968 vps1.var_text = "PS1=# ";
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001969#endif
1970 vp = varinit;
Denis Vlasenko80b8b392007-06-25 10:55:35 +00001971 end = vp + ARRAY_SIZE(varinit);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001972 do {
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02001973 vpp = hashvar(vp->var_text);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001974 vp->next = *vpp;
1975 *vpp = vp;
1976 } while (++vp < end);
1977}
1978
1979static struct var **
1980findvar(struct var **vpp, const char *name)
1981{
1982 for (; *vpp; vpp = &(*vpp)->next) {
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02001983 if (varcmp((*vpp)->var_text, name) == 0) {
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001984 break;
1985 }
1986 }
1987 return vpp;
1988}
1989
1990/*
1991 * Find the value of a variable. Returns NULL if not set.
1992 */
Denys Vlasenko03dad222010-01-12 23:29:57 +01001993static const char* FAST_FUNC
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001994lookupvar(const char *name)
1995{
1996 struct var *v;
1997
1998 v = *findvar(hashvar(name), name);
1999 if (v) {
Denis Vlasenko448d30e2008-06-27 00:24:11 +00002000#if ENABLE_ASH_RANDOM_SUPPORT
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002001 /*
2002 * Dynamic variables are implemented roughly the same way they are
2003 * in bash. Namely, they're "special" so long as they aren't unset.
2004 * As soon as they're unset, they're no longer dynamic, and dynamic
2005 * lookup will no longer happen at that point. -- PFM.
2006 */
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02002007 if (v->flags & VDYNAMIC)
2008 v->var_func(NULL);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002009#endif
2010 if (!(v->flags & VUNSET))
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02002011 return var_end(v->var_text);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002012 }
2013 return NULL;
2014}
2015
2016/*
2017 * Search the environment of a builtin command.
2018 */
Mike Frysinger98c52642009-04-02 10:02:37 +00002019static const char *
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002020bltinlookup(const char *name)
2021{
2022 struct strlist *sp;
2023
2024 for (sp = cmdenviron; sp; sp = sp->next) {
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02002025 if (varcmp(sp->text, name) == 0)
2026 return var_end(sp->text);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002027 }
2028 return lookupvar(name);
2029}
2030
2031/*
2032 * Same as setvar except that the variable and value are passed in
2033 * the first argument as name=value. Since the first argument will
2034 * be actually stored in the table, it should not be a string that
2035 * will go away.
2036 * Called with interrupts off.
2037 */
2038static void
2039setvareq(char *s, int flags)
2040{
2041 struct var *vp, **vpp;
2042
2043 vpp = hashvar(s);
2044 flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
2045 vp = *findvar(vpp, s);
2046 if (vp) {
2047 if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
2048 const char *n;
2049
2050 if (flags & VNOSAVE)
2051 free(s);
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02002052 n = vp->var_text;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002053 ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
2054 }
2055
2056 if (flags & VNOSET)
2057 return;
2058
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02002059 if (vp->var_func && !(flags & VNOFUNC))
2060 vp->var_func(var_end(s));
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002061
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02002062 if (!(vp->flags & (VTEXTFIXED|VSTACK)))
2063 free((char*)vp->var_text);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002064
2065 flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
2066 } else {
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02002067 /* variable s is not found */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002068 if (flags & VNOSET)
2069 return;
Denis Vlasenko597906c2008-02-20 16:38:54 +00002070 vp = ckzalloc(sizeof(*vp));
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002071 vp->next = *vpp;
Denis Vlasenko597906c2008-02-20 16:38:54 +00002072 /*vp->func = NULL; - ckzalloc did it */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002073 *vpp = vp;
2074 }
2075 if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
2076 s = ckstrdup(s);
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02002077 vp->var_text = s;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002078 vp->flags = flags;
2079}
2080
2081/*
2082 * Set the value of a variable. The flags argument is ored with the
2083 * flags of the variable. If val is NULL, the variable is unset.
2084 */
2085static void
2086setvar(const char *name, const char *val, int flags)
2087{
2088 char *p, *q;
2089 size_t namelen;
2090 char *nameeq;
2091 size_t vallen;
2092
2093 q = endofname(name);
2094 p = strchrnul(q, '=');
2095 namelen = p - name;
2096 if (!namelen || p != q)
2097 ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
2098 vallen = 0;
2099 if (val == NULL) {
2100 flags |= VUNSET;
2101 } else {
2102 vallen = strlen(val);
2103 }
2104 INT_OFF;
2105 nameeq = ckmalloc(namelen + vallen + 2);
Denis Vlasenko29eb3592008-05-18 14:06:08 +00002106 p = (char *)memcpy(nameeq, name, namelen) + namelen;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002107 if (val) {
2108 *p++ = '=';
Denis Vlasenko29eb3592008-05-18 14:06:08 +00002109 p = (char *)memcpy(p, val, vallen) + vallen;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002110 }
2111 *p = '\0';
2112 setvareq(nameeq, flags | VNOSAVE);
2113 INT_ON;
2114}
2115
Denys Vlasenko03dad222010-01-12 23:29:57 +01002116static void FAST_FUNC
2117setvar2(const char *name, const char *val)
2118{
2119 setvar(name, val, 0);
2120}
2121
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002122#if ENABLE_ASH_GETOPTS
2123/*
2124 * Safe version of setvar, returns 1 on success 0 on failure.
2125 */
2126static int
2127setvarsafe(const char *name, const char *val, int flags)
2128{
2129 int err;
2130 volatile int saveint;
2131 struct jmploc *volatile savehandler = exception_handler;
2132 struct jmploc jmploc;
2133
2134 SAVE_INT(saveint);
2135 if (setjmp(jmploc.loc))
2136 err = 1;
2137 else {
2138 exception_handler = &jmploc;
2139 setvar(name, val, flags);
2140 err = 0;
2141 }
2142 exception_handler = savehandler;
2143 RESTORE_INT(saveint);
2144 return err;
2145}
2146#endif
2147
2148/*
2149 * Unset the specified variable.
2150 */
2151static int
2152unsetvar(const char *s)
2153{
2154 struct var **vpp;
2155 struct var *vp;
2156 int retval;
2157
2158 vpp = findvar(hashvar(s), s);
2159 vp = *vpp;
2160 retval = 2;
2161 if (vp) {
2162 int flags = vp->flags;
2163
2164 retval = 1;
2165 if (flags & VREADONLY)
2166 goto out;
Denis Vlasenko448d30e2008-06-27 00:24:11 +00002167#if ENABLE_ASH_RANDOM_SUPPORT
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002168 vp->flags &= ~VDYNAMIC;
2169#endif
2170 if (flags & VUNSET)
2171 goto ok;
2172 if ((flags & VSTRFIXED) == 0) {
2173 INT_OFF;
2174 if ((flags & (VTEXTFIXED|VSTACK)) == 0)
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02002175 free((char*)vp->var_text);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002176 *vpp = vp->next;
2177 free(vp);
2178 INT_ON;
2179 } else {
2180 setvar(s, 0, 0);
2181 vp->flags &= ~VEXPORT;
2182 }
2183 ok:
2184 retval = 0;
2185 }
2186 out:
2187 return retval;
2188}
2189
2190/*
2191 * Process a linked list of variable assignments.
2192 */
2193static void
2194listsetvar(struct strlist *list_set_var, int flags)
2195{
2196 struct strlist *lp = list_set_var;
2197
2198 if (!lp)
2199 return;
2200 INT_OFF;
2201 do {
2202 setvareq(lp->text, flags);
Denis Vlasenko9650f362007-02-23 01:04:37 +00002203 lp = lp->next;
2204 } while (lp);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002205 INT_ON;
2206}
2207
2208/*
2209 * Generate a list of variables satisfying the given conditions.
2210 */
2211static char **
2212listvars(int on, int off, char ***end)
2213{
2214 struct var **vpp;
2215 struct var *vp;
2216 char **ep;
2217 int mask;
2218
2219 STARTSTACKSTR(ep);
2220 vpp = vartab;
2221 mask = on | off;
2222 do {
2223 for (vp = *vpp; vp; vp = vp->next) {
2224 if ((vp->flags & mask) == on) {
2225 if (ep == stackstrend())
2226 ep = growstackstr();
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02002227 *ep++ = (char*)vp->var_text;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002228 }
2229 }
2230 } while (++vpp < vartab + VTABSIZE);
2231 if (ep == stackstrend())
2232 ep = growstackstr();
2233 if (end)
2234 *end = ep;
2235 *ep++ = NULL;
2236 return grabstackstr(ep);
2237}
2238
2239
2240/* ============ Path search helper
2241 *
2242 * The variable path (passed by reference) should be set to the start
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02002243 * of the path before the first call; path_advance will update
2244 * this value as it proceeds. Successive calls to path_advance will return
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002245 * the possible path expansions in sequence. If an option (indicated by
2246 * a percent sign) appears in the path entry then the global variable
2247 * pathopt will be set to point to it; otherwise pathopt will be set to
2248 * NULL.
2249 */
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02002250static const char *pathopt; /* set by path_advance */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002251
2252static char *
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02002253path_advance(const char **path, const char *name)
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002254{
2255 const char *p;
2256 char *q;
2257 const char *start;
2258 size_t len;
2259
2260 if (*path == NULL)
2261 return NULL;
2262 start = *path;
Denis Vlasenkof7d56652008-03-25 05:51:41 +00002263 for (p = start; *p && *p != ':' && *p != '%'; p++)
2264 continue;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002265 len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
2266 while (stackblocksize() < len)
2267 growstackblock();
2268 q = stackblock();
2269 if (p != start) {
2270 memcpy(q, start, p - start);
2271 q += p - start;
2272 *q++ = '/';
2273 }
2274 strcpy(q, name);
2275 pathopt = NULL;
2276 if (*p == '%') {
2277 pathopt = ++p;
Denis Vlasenkof7d56652008-03-25 05:51:41 +00002278 while (*p && *p != ':')
2279 p++;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002280 }
2281 if (*p == ':')
2282 *path = p + 1;
2283 else
2284 *path = NULL;
2285 return stalloc(len);
2286}
2287
2288
2289/* ============ Prompt */
2290
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +00002291static smallint doprompt; /* if set, prompt the user */
2292static smallint needprompt; /* true if interactive and at start of line */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002293
2294#if ENABLE_FEATURE_EDITING
2295static line_input_t *line_input_state;
2296static const char *cmdedit_prompt;
2297static void
2298putprompt(const char *s)
2299{
2300 if (ENABLE_ASH_EXPAND_PRMT) {
2301 free((char*)cmdedit_prompt);
Denis Vlasenko4222ae42007-02-25 02:37:49 +00002302 cmdedit_prompt = ckstrdup(s);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002303 return;
2304 }
2305 cmdedit_prompt = s;
2306}
2307#else
2308static void
2309putprompt(const char *s)
2310{
2311 out2str(s);
2312}
2313#endif
2314
2315#if ENABLE_ASH_EXPAND_PRMT
2316/* expandstr() needs parsing machinery, so it is far away ahead... */
2317static const char *expandstr(const char *ps);
2318#else
2319#define expandstr(s) s
2320#endif
2321
2322static void
2323setprompt(int whichprompt)
2324{
2325 const char *prompt;
2326#if ENABLE_ASH_EXPAND_PRMT
2327 struct stackmark smark;
2328#endif
2329
2330 needprompt = 0;
2331
2332 switch (whichprompt) {
2333 case 1:
2334 prompt = ps1val();
2335 break;
2336 case 2:
2337 prompt = ps2val();
2338 break;
2339 default: /* 0 */
2340 prompt = nullstr;
2341 }
2342#if ENABLE_ASH_EXPAND_PRMT
2343 setstackmark(&smark);
2344 stalloc(stackblocksize());
2345#endif
2346 putprompt(expandstr(prompt));
2347#if ENABLE_ASH_EXPAND_PRMT
2348 popstackmark(&smark);
2349#endif
2350}
2351
2352
2353/* ============ The cd and pwd commands */
2354
2355#define CD_PHYSICAL 1
2356#define CD_PRINT 2
2357
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002358static int
2359cdopt(void)
2360{
2361 int flags = 0;
2362 int i, j;
2363
2364 j = 'L';
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02002365 while ((i = nextopt("LP")) != '\0') {
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002366 if (i != j) {
2367 flags ^= CD_PHYSICAL;
2368 j = i;
2369 }
2370 }
2371
2372 return flags;
2373}
2374
2375/*
2376 * Update curdir (the name of the current directory) in response to a
2377 * cd command.
2378 */
2379static const char *
2380updatepwd(const char *dir)
2381{
2382 char *new;
2383 char *p;
2384 char *cdcomppath;
2385 const char *lim;
2386
2387 cdcomppath = ststrdup(dir);
2388 STARTSTACKSTR(new);
2389 if (*dir != '/') {
2390 if (curdir == nullstr)
2391 return 0;
2392 new = stack_putstr(curdir, new);
2393 }
2394 new = makestrspace(strlen(dir) + 2, new);
Denis Vlasenko29eb3592008-05-18 14:06:08 +00002395 lim = (char *)stackblock() + 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002396 if (*dir != '/') {
2397 if (new[-1] != '/')
2398 USTPUTC('/', new);
2399 if (new > lim && *lim == '/')
2400 lim++;
2401 } else {
2402 USTPUTC('/', new);
2403 cdcomppath++;
2404 if (dir[1] == '/' && dir[2] != '/') {
2405 USTPUTC('/', new);
2406 cdcomppath++;
2407 lim++;
2408 }
2409 }
2410 p = strtok(cdcomppath, "/");
2411 while (p) {
2412 switch (*p) {
2413 case '.':
2414 if (p[1] == '.' && p[2] == '\0') {
2415 while (new > lim) {
2416 STUNPUTC(new);
2417 if (new[-1] == '/')
2418 break;
2419 }
2420 break;
Denis Vlasenko16abcd92007-04-13 23:59:52 +00002421 }
2422 if (p[1] == '\0')
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002423 break;
2424 /* fall through */
2425 default:
2426 new = stack_putstr(p, new);
2427 USTPUTC('/', new);
2428 }
2429 p = strtok(0, "/");
2430 }
2431 if (new > lim)
2432 STUNPUTC(new);
2433 *new = 0;
2434 return stackblock();
2435}
2436
2437/*
2438 * Find out what the current directory is. If we already know the current
2439 * directory, this routine returns immediately.
2440 */
2441static char *
2442getpwd(void)
2443{
Denis Vlasenko01631112007-12-16 17:20:38 +00002444 char *dir = getcwd(NULL, 0); /* huh, using glibc extension? */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002445 return dir ? dir : nullstr;
2446}
2447
2448static void
2449setpwd(const char *val, int setold)
2450{
2451 char *oldcur, *dir;
2452
2453 oldcur = dir = curdir;
2454
2455 if (setold) {
2456 setvar("OLDPWD", oldcur, VEXPORT);
2457 }
2458 INT_OFF;
2459 if (physdir != nullstr) {
2460 if (physdir != oldcur)
2461 free(physdir);
2462 physdir = nullstr;
2463 }
2464 if (oldcur == val || !val) {
2465 char *s = getpwd();
2466 physdir = s;
2467 if (!val)
2468 dir = s;
2469 } else
2470 dir = ckstrdup(val);
2471 if (oldcur != dir && oldcur != nullstr) {
2472 free(oldcur);
2473 }
2474 curdir = dir;
2475 INT_ON;
2476 setvar("PWD", dir, VEXPORT);
2477}
2478
2479static void hashcd(void);
2480
2481/*
2482 * Actually do the chdir. We also call hashcd to let the routines in exec.c
2483 * know that the current directory has changed.
2484 */
2485static int
2486docd(const char *dest, int flags)
2487{
Denys Vlasenko4b1100e2010-03-05 14:10:54 +01002488 const char *dir = NULL;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002489 int err;
2490
2491 TRACE(("docd(\"%s\", %d) called\n", dest, flags));
2492
2493 INT_OFF;
2494 if (!(flags & CD_PHYSICAL)) {
2495 dir = updatepwd(dest);
2496 if (dir)
2497 dest = dir;
2498 }
2499 err = chdir(dest);
2500 if (err)
2501 goto out;
2502 setpwd(dir, 1);
2503 hashcd();
2504 out:
2505 INT_ON;
2506 return err;
2507}
2508
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02002509static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00002510cdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002511{
2512 const char *dest;
2513 const char *path;
2514 const char *p;
2515 char c;
2516 struct stat statb;
2517 int flags;
2518
2519 flags = cdopt();
2520 dest = *argptr;
2521 if (!dest)
Denys Vlasenkoea8b2522010-06-02 12:57:26 +02002522 dest = bltinlookup("HOME");
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002523 else if (LONE_DASH(dest)) {
2524 dest = bltinlookup("OLDPWD");
2525 flags |= CD_PRINT;
2526 }
2527 if (!dest)
2528 dest = nullstr;
2529 if (*dest == '/')
2530 goto step7;
2531 if (*dest == '.') {
2532 c = dest[1];
2533 dotdot:
2534 switch (c) {
2535 case '\0':
2536 case '/':
2537 goto step6;
2538 case '.':
2539 c = dest[2];
2540 if (c != '.')
2541 goto dotdot;
2542 }
2543 }
2544 if (!*dest)
2545 dest = ".";
2546 path = bltinlookup("CDPATH");
2547 if (!path) {
2548 step6:
2549 step7:
2550 p = dest;
2551 goto docd;
2552 }
2553 do {
2554 c = *path;
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02002555 p = path_advance(&path, dest);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002556 if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
2557 if (c && c != ':')
2558 flags |= CD_PRINT;
2559 docd:
2560 if (!docd(p, flags))
2561 goto out;
2562 break;
2563 }
2564 } while (path);
2565 ash_msg_and_raise_error("can't cd to %s", dest);
2566 /* NOTREACHED */
2567 out:
2568 if (flags & CD_PRINT)
Denys Vlasenkoea8b2522010-06-02 12:57:26 +02002569 out1fmt("%s\n", curdir);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002570 return 0;
2571}
2572
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02002573static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00002574pwdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002575{
2576 int flags;
2577 const char *dir = curdir;
2578
2579 flags = cdopt();
2580 if (flags) {
2581 if (physdir == nullstr)
2582 setpwd(dir, 0);
2583 dir = physdir;
2584 }
Denys Vlasenkoea8b2522010-06-02 12:57:26 +02002585 out1fmt("%s\n", dir);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002586 return 0;
2587}
2588
Denis Vlasenko0c032a42007-02-23 01:03:40 +00002589
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00002590/* ============ ... */
Eric Andersenc470f442003-07-28 09:56:35 +00002591
Denis Vlasenko834dee72008-10-07 09:18:30 +00002592
Denys Vlasenko82dd14a2010-05-17 10:10:01 +02002593#define IBUFSIZ (ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 1024)
Eric Andersenc470f442003-07-28 09:56:35 +00002594
Eric Andersenc470f442003-07-28 09:56:35 +00002595/* Syntax classes */
Denis Vlasenko834dee72008-10-07 09:18:30 +00002596#define CWORD 0 /* character is nothing special */
2597#define CNL 1 /* newline character */
2598#define CBACK 2 /* a backslash character */
2599#define CSQUOTE 3 /* single quote */
2600#define CDQUOTE 4 /* double quote */
Eric Andersenc470f442003-07-28 09:56:35 +00002601#define CENDQUOTE 5 /* a terminating quote */
Denis Vlasenko834dee72008-10-07 09:18:30 +00002602#define CBQUOTE 6 /* backwards single quote */
2603#define CVAR 7 /* a dollar sign */
2604#define CENDVAR 8 /* a '}' character */
2605#define CLP 9 /* a left paren in arithmetic */
2606#define CRP 10 /* a right paren in arithmetic */
Eric Andersenc470f442003-07-28 09:56:35 +00002607#define CENDFILE 11 /* end of file */
Denis Vlasenko834dee72008-10-07 09:18:30 +00002608#define CCTL 12 /* like CWORD, except it must be escaped */
2609#define CSPCL 13 /* these terminate a word */
2610#define CIGN 14 /* character should be ignored */
Eric Andersenc470f442003-07-28 09:56:35 +00002611
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002612#define PEOF 256
Denis Vlasenko131ae172007-02-18 13:00:19 +00002613#if ENABLE_ASH_ALIAS
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002614# define PEOA 257
Eric Andersenc470f442003-07-28 09:56:35 +00002615#endif
2616
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002617#define USE_SIT_FUNCTION ENABLE_ASH_OPTIMIZE_FOR_SIZE
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002618
Mike Frysinger98c52642009-04-02 10:02:37 +00002619#if ENABLE_SH_MATH_SUPPORT
Denys Vlasenko76bc2d62009-11-29 01:37:46 +01002620# define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8) | (d << 12))
Eric Andersenc470f442003-07-28 09:56:35 +00002621#else
Denys Vlasenko76bc2d62009-11-29 01:37:46 +01002622# define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8))
Denys Vlasenko76bc2d62009-11-29 01:37:46 +01002623#endif
Denys Vlasenko068d3862009-11-29 01:41:11 +01002624static const uint16_t S_I_T[] = {
Denys Vlasenko76bc2d62009-11-29 01:37:46 +01002625#if ENABLE_ASH_ALIAS
2626 SIT_ITEM(CSPCL , CIGN , CIGN , CIGN ), /* 0, PEOA */
2627#endif
2628 SIT_ITEM(CSPCL , CWORD , CWORD, CWORD ), /* 1, ' ' */
2629 SIT_ITEM(CNL , CNL , CNL , CNL ), /* 2, \n */
2630 SIT_ITEM(CWORD , CCTL , CCTL , CWORD ), /* 3, !*-/:=?[]~ */
2631 SIT_ITEM(CDQUOTE , CENDQUOTE, CWORD, CWORD ), /* 4, '"' */
2632 SIT_ITEM(CVAR , CVAR , CWORD, CVAR ), /* 5, $ */
2633 SIT_ITEM(CSQUOTE , CWORD , CENDQUOTE, CWORD), /* 6, "'" */
2634 SIT_ITEM(CSPCL , CWORD , CWORD, CLP ), /* 7, ( */
2635 SIT_ITEM(CSPCL , CWORD , CWORD, CRP ), /* 8, ) */
2636 SIT_ITEM(CBACK , CBACK , CCTL , CBACK ), /* 9, \ */
2637 SIT_ITEM(CBQUOTE , CBQUOTE , CWORD, CBQUOTE), /* 10, ` */
2638 SIT_ITEM(CENDVAR , CENDVAR , CWORD, CENDVAR), /* 11, } */
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002639#if !USE_SIT_FUNCTION
Denys Vlasenko76bc2d62009-11-29 01:37:46 +01002640 SIT_ITEM(CENDFILE, CENDFILE , CENDFILE, CENDFILE),/* 12, PEOF */
2641 SIT_ITEM(CWORD , CWORD , CWORD, CWORD ), /* 13, 0-9A-Za-z */
2642 SIT_ITEM(CCTL , CCTL , CCTL , CCTL ) /* 14, CTLESC ... */
2643#endif
2644#undef SIT_ITEM
Eric Andersenc470f442003-07-28 09:56:35 +00002645};
Denys Vlasenko76bc2d62009-11-29 01:37:46 +01002646/* Constants below must match table above */
2647enum {
2648#if ENABLE_ASH_ALIAS
2649 CSPCL_CIGN_CIGN_CIGN , /* 0 */
2650#endif
2651 CSPCL_CWORD_CWORD_CWORD , /* 1 */
2652 CNL_CNL_CNL_CNL , /* 2 */
2653 CWORD_CCTL_CCTL_CWORD , /* 3 */
2654 CDQUOTE_CENDQUOTE_CWORD_CWORD , /* 4 */
2655 CVAR_CVAR_CWORD_CVAR , /* 5 */
2656 CSQUOTE_CWORD_CENDQUOTE_CWORD , /* 6 */
2657 CSPCL_CWORD_CWORD_CLP , /* 7 */
2658 CSPCL_CWORD_CWORD_CRP , /* 8 */
2659 CBACK_CBACK_CCTL_CBACK , /* 9 */
2660 CBQUOTE_CBQUOTE_CWORD_CBQUOTE , /* 10 */
2661 CENDVAR_CENDVAR_CWORD_CENDVAR , /* 11 */
2662 CENDFILE_CENDFILE_CENDFILE_CENDFILE, /* 12 */
2663 CWORD_CWORD_CWORD_CWORD , /* 13 */
2664 CCTL_CCTL_CCTL_CCTL , /* 14 */
2665};
Eric Andersen2870d962001-07-02 17:27:21 +00002666
Denys Vlasenkocd716832009-11-28 22:14:02 +01002667/* c in SIT(c, syntax) must be an *unsigned char* or PEOA or PEOF,
2668 * caller must ensure proper cast on it if c is *char_ptr!
2669 */
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002670/* Values for syntax param */
2671#define BASESYNTAX 0 /* not in quotes */
2672#define DQSYNTAX 1 /* in double quotes */
2673#define SQSYNTAX 2 /* in single quotes */
2674#define ARISYNTAX 3 /* in arithmetic */
2675#define PSSYNTAX 4 /* prompt. never passed to SIT() */
Denys Vlasenkocd716832009-11-28 22:14:02 +01002676
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002677#if USE_SIT_FUNCTION
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002678
Denis Vlasenko0c032a42007-02-23 01:03:40 +00002679static int
2680SIT(int c, int syntax)
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002681{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00002682 static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-/:;<=>?[\\]`|}~";
Denys Vlasenkocd716832009-11-28 22:14:02 +01002683# if ENABLE_ASH_ALIAS
2684 static const uint8_t syntax_index_table[] ALIGN1 = {
Eric Andersenc470f442003-07-28 09:56:35 +00002685 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
2686 7, 8, 3, 3, 3, 3, 1, 1, /* "()*-/:;<" */
2687 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
2688 11, 3 /* "}~" */
2689 };
Denys Vlasenkocd716832009-11-28 22:14:02 +01002690# else
2691 static const uint8_t syntax_index_table[] ALIGN1 = {
Eric Andersenc470f442003-07-28 09:56:35 +00002692 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
2693 6, 7, 2, 2, 2, 2, 0, 0, /* "()*-/:;<" */
2694 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
2695 10, 2 /* "}~" */
2696 };
Denys Vlasenkocd716832009-11-28 22:14:02 +01002697# endif
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002698 const char *s;
2699 int indx;
2700
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002701 if (c == PEOF)
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002702 return CENDFILE;
Denys Vlasenkocd716832009-11-28 22:14:02 +01002703# if ENABLE_ASH_ALIAS
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002704 if (c == PEOA)
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +00002705 indx = 0;
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002706 else
Denys Vlasenkocd716832009-11-28 22:14:02 +01002707# endif
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +00002708 {
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002709 /* Cast is purely for paranoia here,
2710 * just in case someone passed signed char to us */
2711 if ((unsigned char)c >= CTL_FIRST
2712 && (unsigned char)c <= CTL_LAST
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +00002713 ) {
2714 return CCTL;
2715 }
2716 s = strchrnul(spec_symbls, c);
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002717 if (*s == '\0')
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +00002718 return CWORD;
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +00002719 indx = syntax_index_table[s - spec_symbls];
2720 }
Denys Vlasenko76bc2d62009-11-29 01:37:46 +01002721 return (S_I_T[indx] >> (syntax*4)) & 0xf;
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002722}
2723
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00002724#else /* !USE_SIT_FUNCTION */
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002725
Denys Vlasenko76bc2d62009-11-29 01:37:46 +01002726static const uint8_t syntax_index_table[] = {
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00002727 /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
Denys Vlasenkocd716832009-11-28 22:14:02 +01002728 /* 0 */ CWORD_CWORD_CWORD_CWORD,
2729 /* 1 */ CWORD_CWORD_CWORD_CWORD,
2730 /* 2 */ CWORD_CWORD_CWORD_CWORD,
2731 /* 3 */ CWORD_CWORD_CWORD_CWORD,
2732 /* 4 */ CWORD_CWORD_CWORD_CWORD,
2733 /* 5 */ CWORD_CWORD_CWORD_CWORD,
2734 /* 6 */ CWORD_CWORD_CWORD_CWORD,
2735 /* 7 */ CWORD_CWORD_CWORD_CWORD,
2736 /* 8 */ CWORD_CWORD_CWORD_CWORD,
2737 /* 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
2738 /* 10 "\n" */ CNL_CNL_CNL_CNL,
2739 /* 11 */ CWORD_CWORD_CWORD_CWORD,
2740 /* 12 */ CWORD_CWORD_CWORD_CWORD,
2741 /* 13 */ CWORD_CWORD_CWORD_CWORD,
2742 /* 14 */ CWORD_CWORD_CWORD_CWORD,
2743 /* 15 */ CWORD_CWORD_CWORD_CWORD,
2744 /* 16 */ CWORD_CWORD_CWORD_CWORD,
2745 /* 17 */ CWORD_CWORD_CWORD_CWORD,
2746 /* 18 */ CWORD_CWORD_CWORD_CWORD,
2747 /* 19 */ CWORD_CWORD_CWORD_CWORD,
2748 /* 20 */ CWORD_CWORD_CWORD_CWORD,
2749 /* 21 */ CWORD_CWORD_CWORD_CWORD,
2750 /* 22 */ CWORD_CWORD_CWORD_CWORD,
2751 /* 23 */ CWORD_CWORD_CWORD_CWORD,
2752 /* 24 */ CWORD_CWORD_CWORD_CWORD,
2753 /* 25 */ CWORD_CWORD_CWORD_CWORD,
2754 /* 26 */ CWORD_CWORD_CWORD_CWORD,
2755 /* 27 */ CWORD_CWORD_CWORD_CWORD,
2756 /* 28 */ CWORD_CWORD_CWORD_CWORD,
2757 /* 29 */ CWORD_CWORD_CWORD_CWORD,
2758 /* 30 */ CWORD_CWORD_CWORD_CWORD,
2759 /* 31 */ CWORD_CWORD_CWORD_CWORD,
2760 /* 32 " " */ CSPCL_CWORD_CWORD_CWORD,
2761 /* 33 "!" */ CWORD_CCTL_CCTL_CWORD,
2762 /* 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
2763 /* 35 "#" */ CWORD_CWORD_CWORD_CWORD,
2764 /* 36 "$" */ CVAR_CVAR_CWORD_CVAR,
2765 /* 37 "%" */ CWORD_CWORD_CWORD_CWORD,
2766 /* 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
2767 /* 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
2768 /* 40 "(" */ CSPCL_CWORD_CWORD_CLP,
2769 /* 41 ")" */ CSPCL_CWORD_CWORD_CRP,
2770 /* 42 "*" */ CWORD_CCTL_CCTL_CWORD,
2771 /* 43 "+" */ CWORD_CWORD_CWORD_CWORD,
2772 /* 44 "," */ CWORD_CWORD_CWORD_CWORD,
2773 /* 45 "-" */ CWORD_CCTL_CCTL_CWORD,
2774 /* 46 "." */ CWORD_CWORD_CWORD_CWORD,
2775 /* 47 "/" */ CWORD_CCTL_CCTL_CWORD,
2776 /* 48 "0" */ CWORD_CWORD_CWORD_CWORD,
2777 /* 49 "1" */ CWORD_CWORD_CWORD_CWORD,
2778 /* 50 "2" */ CWORD_CWORD_CWORD_CWORD,
2779 /* 51 "3" */ CWORD_CWORD_CWORD_CWORD,
2780 /* 52 "4" */ CWORD_CWORD_CWORD_CWORD,
2781 /* 53 "5" */ CWORD_CWORD_CWORD_CWORD,
2782 /* 54 "6" */ CWORD_CWORD_CWORD_CWORD,
2783 /* 55 "7" */ CWORD_CWORD_CWORD_CWORD,
2784 /* 56 "8" */ CWORD_CWORD_CWORD_CWORD,
2785 /* 57 "9" */ CWORD_CWORD_CWORD_CWORD,
2786 /* 58 ":" */ CWORD_CCTL_CCTL_CWORD,
2787 /* 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
2788 /* 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
2789 /* 61 "=" */ CWORD_CCTL_CCTL_CWORD,
2790 /* 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
2791 /* 63 "?" */ CWORD_CCTL_CCTL_CWORD,
2792 /* 64 "@" */ CWORD_CWORD_CWORD_CWORD,
2793 /* 65 "A" */ CWORD_CWORD_CWORD_CWORD,
2794 /* 66 "B" */ CWORD_CWORD_CWORD_CWORD,
2795 /* 67 "C" */ CWORD_CWORD_CWORD_CWORD,
2796 /* 68 "D" */ CWORD_CWORD_CWORD_CWORD,
2797 /* 69 "E" */ CWORD_CWORD_CWORD_CWORD,
2798 /* 70 "F" */ CWORD_CWORD_CWORD_CWORD,
2799 /* 71 "G" */ CWORD_CWORD_CWORD_CWORD,
2800 /* 72 "H" */ CWORD_CWORD_CWORD_CWORD,
2801 /* 73 "I" */ CWORD_CWORD_CWORD_CWORD,
2802 /* 74 "J" */ CWORD_CWORD_CWORD_CWORD,
2803 /* 75 "K" */ CWORD_CWORD_CWORD_CWORD,
2804 /* 76 "L" */ CWORD_CWORD_CWORD_CWORD,
2805 /* 77 "M" */ CWORD_CWORD_CWORD_CWORD,
2806 /* 78 "N" */ CWORD_CWORD_CWORD_CWORD,
2807 /* 79 "O" */ CWORD_CWORD_CWORD_CWORD,
2808 /* 80 "P" */ CWORD_CWORD_CWORD_CWORD,
2809 /* 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
2810 /* 82 "R" */ CWORD_CWORD_CWORD_CWORD,
2811 /* 83 "S" */ CWORD_CWORD_CWORD_CWORD,
2812 /* 84 "T" */ CWORD_CWORD_CWORD_CWORD,
2813 /* 85 "U" */ CWORD_CWORD_CWORD_CWORD,
2814 /* 86 "V" */ CWORD_CWORD_CWORD_CWORD,
2815 /* 87 "W" */ CWORD_CWORD_CWORD_CWORD,
2816 /* 88 "X" */ CWORD_CWORD_CWORD_CWORD,
2817 /* 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
2818 /* 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
2819 /* 91 "[" */ CWORD_CCTL_CCTL_CWORD,
2820 /* 92 "\" */ CBACK_CBACK_CCTL_CBACK,
2821 /* 93 "]" */ CWORD_CCTL_CCTL_CWORD,
2822 /* 94 "^" */ CWORD_CWORD_CWORD_CWORD,
2823 /* 95 "_" */ CWORD_CWORD_CWORD_CWORD,
2824 /* 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
2825 /* 97 "a" */ CWORD_CWORD_CWORD_CWORD,
2826 /* 98 "b" */ CWORD_CWORD_CWORD_CWORD,
2827 /* 99 "c" */ CWORD_CWORD_CWORD_CWORD,
2828 /* 100 "d" */ CWORD_CWORD_CWORD_CWORD,
2829 /* 101 "e" */ CWORD_CWORD_CWORD_CWORD,
2830 /* 102 "f" */ CWORD_CWORD_CWORD_CWORD,
2831 /* 103 "g" */ CWORD_CWORD_CWORD_CWORD,
2832 /* 104 "h" */ CWORD_CWORD_CWORD_CWORD,
2833 /* 105 "i" */ CWORD_CWORD_CWORD_CWORD,
2834 /* 106 "j" */ CWORD_CWORD_CWORD_CWORD,
2835 /* 107 "k" */ CWORD_CWORD_CWORD_CWORD,
2836 /* 108 "l" */ CWORD_CWORD_CWORD_CWORD,
2837 /* 109 "m" */ CWORD_CWORD_CWORD_CWORD,
2838 /* 110 "n" */ CWORD_CWORD_CWORD_CWORD,
2839 /* 111 "o" */ CWORD_CWORD_CWORD_CWORD,
2840 /* 112 "p" */ CWORD_CWORD_CWORD_CWORD,
2841 /* 113 "q" */ CWORD_CWORD_CWORD_CWORD,
2842 /* 114 "r" */ CWORD_CWORD_CWORD_CWORD,
2843 /* 115 "s" */ CWORD_CWORD_CWORD_CWORD,
2844 /* 116 "t" */ CWORD_CWORD_CWORD_CWORD,
2845 /* 117 "u" */ CWORD_CWORD_CWORD_CWORD,
2846 /* 118 "v" */ CWORD_CWORD_CWORD_CWORD,
2847 /* 119 "w" */ CWORD_CWORD_CWORD_CWORD,
2848 /* 120 "x" */ CWORD_CWORD_CWORD_CWORD,
2849 /* 121 "y" */ CWORD_CWORD_CWORD_CWORD,
2850 /* 122 "z" */ CWORD_CWORD_CWORD_CWORD,
2851 /* 123 "{" */ CWORD_CWORD_CWORD_CWORD,
2852 /* 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
2853 /* 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
2854 /* 126 "~" */ CWORD_CCTL_CCTL_CWORD,
2855 /* 127 del */ CWORD_CWORD_CWORD_CWORD,
2856 /* 128 0x80 */ CWORD_CWORD_CWORD_CWORD,
2857 /* 129 CTLESC */ CCTL_CCTL_CCTL_CCTL,
2858 /* 130 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
2859 /* 131 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
2860 /* 132 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
2861 /* 133 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
2862 /* 134 CTLARI */ CCTL_CCTL_CCTL_CCTL,
2863 /* 135 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
2864 /* 136 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
2865 /* 137 */ CWORD_CWORD_CWORD_CWORD,
2866 /* 138 */ CWORD_CWORD_CWORD_CWORD,
2867 /* 139 */ CWORD_CWORD_CWORD_CWORD,
2868 /* 140 */ CWORD_CWORD_CWORD_CWORD,
2869 /* 141 */ CWORD_CWORD_CWORD_CWORD,
2870 /* 142 */ CWORD_CWORD_CWORD_CWORD,
2871 /* 143 */ CWORD_CWORD_CWORD_CWORD,
2872 /* 144 */ CWORD_CWORD_CWORD_CWORD,
2873 /* 145 */ CWORD_CWORD_CWORD_CWORD,
2874 /* 146 */ CWORD_CWORD_CWORD_CWORD,
2875 /* 147 */ CWORD_CWORD_CWORD_CWORD,
2876 /* 148 */ CWORD_CWORD_CWORD_CWORD,
2877 /* 149 */ CWORD_CWORD_CWORD_CWORD,
2878 /* 150 */ CWORD_CWORD_CWORD_CWORD,
2879 /* 151 */ CWORD_CWORD_CWORD_CWORD,
2880 /* 152 */ CWORD_CWORD_CWORD_CWORD,
2881 /* 153 */ CWORD_CWORD_CWORD_CWORD,
2882 /* 154 */ CWORD_CWORD_CWORD_CWORD,
2883 /* 155 */ CWORD_CWORD_CWORD_CWORD,
2884 /* 156 */ CWORD_CWORD_CWORD_CWORD,
2885 /* 157 */ CWORD_CWORD_CWORD_CWORD,
2886 /* 158 */ CWORD_CWORD_CWORD_CWORD,
2887 /* 159 */ CWORD_CWORD_CWORD_CWORD,
2888 /* 160 */ CWORD_CWORD_CWORD_CWORD,
2889 /* 161 */ CWORD_CWORD_CWORD_CWORD,
2890 /* 162 */ CWORD_CWORD_CWORD_CWORD,
2891 /* 163 */ CWORD_CWORD_CWORD_CWORD,
2892 /* 164 */ CWORD_CWORD_CWORD_CWORD,
2893 /* 165 */ CWORD_CWORD_CWORD_CWORD,
2894 /* 166 */ CWORD_CWORD_CWORD_CWORD,
2895 /* 167 */ CWORD_CWORD_CWORD_CWORD,
2896 /* 168 */ CWORD_CWORD_CWORD_CWORD,
2897 /* 169 */ CWORD_CWORD_CWORD_CWORD,
2898 /* 170 */ CWORD_CWORD_CWORD_CWORD,
2899 /* 171 */ CWORD_CWORD_CWORD_CWORD,
2900 /* 172 */ CWORD_CWORD_CWORD_CWORD,
2901 /* 173 */ CWORD_CWORD_CWORD_CWORD,
2902 /* 174 */ CWORD_CWORD_CWORD_CWORD,
2903 /* 175 */ CWORD_CWORD_CWORD_CWORD,
2904 /* 176 */ CWORD_CWORD_CWORD_CWORD,
2905 /* 177 */ CWORD_CWORD_CWORD_CWORD,
2906 /* 178 */ CWORD_CWORD_CWORD_CWORD,
2907 /* 179 */ CWORD_CWORD_CWORD_CWORD,
2908 /* 180 */ CWORD_CWORD_CWORD_CWORD,
2909 /* 181 */ CWORD_CWORD_CWORD_CWORD,
2910 /* 182 */ CWORD_CWORD_CWORD_CWORD,
2911 /* 183 */ CWORD_CWORD_CWORD_CWORD,
2912 /* 184 */ CWORD_CWORD_CWORD_CWORD,
2913 /* 185 */ CWORD_CWORD_CWORD_CWORD,
2914 /* 186 */ CWORD_CWORD_CWORD_CWORD,
2915 /* 187 */ CWORD_CWORD_CWORD_CWORD,
2916 /* 188 */ CWORD_CWORD_CWORD_CWORD,
2917 /* 189 */ CWORD_CWORD_CWORD_CWORD,
2918 /* 190 */ CWORD_CWORD_CWORD_CWORD,
2919 /* 191 */ CWORD_CWORD_CWORD_CWORD,
2920 /* 192 */ CWORD_CWORD_CWORD_CWORD,
2921 /* 193 */ CWORD_CWORD_CWORD_CWORD,
2922 /* 194 */ CWORD_CWORD_CWORD_CWORD,
2923 /* 195 */ CWORD_CWORD_CWORD_CWORD,
2924 /* 196 */ CWORD_CWORD_CWORD_CWORD,
2925 /* 197 */ CWORD_CWORD_CWORD_CWORD,
2926 /* 198 */ CWORD_CWORD_CWORD_CWORD,
2927 /* 199 */ CWORD_CWORD_CWORD_CWORD,
2928 /* 200 */ CWORD_CWORD_CWORD_CWORD,
2929 /* 201 */ CWORD_CWORD_CWORD_CWORD,
2930 /* 202 */ CWORD_CWORD_CWORD_CWORD,
2931 /* 203 */ CWORD_CWORD_CWORD_CWORD,
2932 /* 204 */ CWORD_CWORD_CWORD_CWORD,
2933 /* 205 */ CWORD_CWORD_CWORD_CWORD,
2934 /* 206 */ CWORD_CWORD_CWORD_CWORD,
2935 /* 207 */ CWORD_CWORD_CWORD_CWORD,
2936 /* 208 */ CWORD_CWORD_CWORD_CWORD,
2937 /* 209 */ CWORD_CWORD_CWORD_CWORD,
2938 /* 210 */ CWORD_CWORD_CWORD_CWORD,
2939 /* 211 */ CWORD_CWORD_CWORD_CWORD,
2940 /* 212 */ CWORD_CWORD_CWORD_CWORD,
2941 /* 213 */ CWORD_CWORD_CWORD_CWORD,
2942 /* 214 */ CWORD_CWORD_CWORD_CWORD,
2943 /* 215 */ CWORD_CWORD_CWORD_CWORD,
2944 /* 216 */ CWORD_CWORD_CWORD_CWORD,
2945 /* 217 */ CWORD_CWORD_CWORD_CWORD,
2946 /* 218 */ CWORD_CWORD_CWORD_CWORD,
2947 /* 219 */ CWORD_CWORD_CWORD_CWORD,
2948 /* 220 */ CWORD_CWORD_CWORD_CWORD,
2949 /* 221 */ CWORD_CWORD_CWORD_CWORD,
2950 /* 222 */ CWORD_CWORD_CWORD_CWORD,
2951 /* 223 */ CWORD_CWORD_CWORD_CWORD,
2952 /* 224 */ CWORD_CWORD_CWORD_CWORD,
2953 /* 225 */ CWORD_CWORD_CWORD_CWORD,
2954 /* 226 */ CWORD_CWORD_CWORD_CWORD,
2955 /* 227 */ CWORD_CWORD_CWORD_CWORD,
2956 /* 228 */ CWORD_CWORD_CWORD_CWORD,
2957 /* 229 */ CWORD_CWORD_CWORD_CWORD,
2958 /* 230 */ CWORD_CWORD_CWORD_CWORD,
2959 /* 231 */ CWORD_CWORD_CWORD_CWORD,
2960 /* 232 */ CWORD_CWORD_CWORD_CWORD,
2961 /* 233 */ CWORD_CWORD_CWORD_CWORD,
2962 /* 234 */ CWORD_CWORD_CWORD_CWORD,
2963 /* 235 */ CWORD_CWORD_CWORD_CWORD,
2964 /* 236 */ CWORD_CWORD_CWORD_CWORD,
2965 /* 237 */ CWORD_CWORD_CWORD_CWORD,
2966 /* 238 */ CWORD_CWORD_CWORD_CWORD,
2967 /* 239 */ CWORD_CWORD_CWORD_CWORD,
2968 /* 230 */ CWORD_CWORD_CWORD_CWORD,
2969 /* 241 */ CWORD_CWORD_CWORD_CWORD,
2970 /* 242 */ CWORD_CWORD_CWORD_CWORD,
2971 /* 243 */ CWORD_CWORD_CWORD_CWORD,
2972 /* 244 */ CWORD_CWORD_CWORD_CWORD,
2973 /* 245 */ CWORD_CWORD_CWORD_CWORD,
2974 /* 246 */ CWORD_CWORD_CWORD_CWORD,
2975 /* 247 */ CWORD_CWORD_CWORD_CWORD,
2976 /* 248 */ CWORD_CWORD_CWORD_CWORD,
2977 /* 249 */ CWORD_CWORD_CWORD_CWORD,
2978 /* 250 */ CWORD_CWORD_CWORD_CWORD,
2979 /* 251 */ CWORD_CWORD_CWORD_CWORD,
2980 /* 252 */ CWORD_CWORD_CWORD_CWORD,
2981 /* 253 */ CWORD_CWORD_CWORD_CWORD,
2982 /* 254 */ CWORD_CWORD_CWORD_CWORD,
2983 /* 255 */ CWORD_CWORD_CWORD_CWORD,
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002984 /* PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
Denys Vlasenkocd716832009-11-28 22:14:02 +01002985# if ENABLE_ASH_ALIAS
2986 /* PEOA */ CSPCL_CIGN_CIGN_CIGN,
2987# endif
Eric Andersen2870d962001-07-02 17:27:21 +00002988};
2989
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002990# define SIT(c, syntax) ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf)
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00002991
Denys Vlasenko76bc2d62009-11-29 01:37:46 +01002992#endif /* !USE_SIT_FUNCTION */
Eric Andersenc470f442003-07-28 09:56:35 +00002993
Eric Andersen2870d962001-07-02 17:27:21 +00002994
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00002995/* ============ Alias handling */
Denis Vlasenkofc06f292007-02-23 21:09:35 +00002996
Denis Vlasenko131ae172007-02-18 13:00:19 +00002997#if ENABLE_ASH_ALIAS
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00002998
2999#define ALIASINUSE 1
3000#define ALIASDEAD 2
3001
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00003002struct alias {
3003 struct alias *next;
3004 char *name;
3005 char *val;
3006 int flag;
3007};
3008
Denis Vlasenko01631112007-12-16 17:20:38 +00003009
3010static struct alias **atab; // [ATABSIZE];
3011#define INIT_G_alias() do { \
3012 atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
3013} while (0)
3014
Eric Andersen2870d962001-07-02 17:27:21 +00003015
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00003016static struct alias **
3017__lookupalias(const char *name) {
3018 unsigned int hashval;
3019 struct alias **app;
3020 const char *p;
3021 unsigned int ch;
3022
3023 p = name;
3024
3025 ch = (unsigned char)*p;
3026 hashval = ch << 4;
3027 while (ch) {
3028 hashval += ch;
3029 ch = (unsigned char)*++p;
3030 }
3031 app = &atab[hashval % ATABSIZE];
3032
3033 for (; *app; app = &(*app)->next) {
3034 if (strcmp(name, (*app)->name) == 0) {
3035 break;
3036 }
3037 }
3038
3039 return app;
3040}
3041
3042static struct alias *
3043lookupalias(const char *name, int check)
3044{
3045 struct alias *ap = *__lookupalias(name);
3046
3047 if (check && ap && (ap->flag & ALIASINUSE))
3048 return NULL;
3049 return ap;
3050}
3051
3052static struct alias *
3053freealias(struct alias *ap)
3054{
3055 struct alias *next;
3056
3057 if (ap->flag & ALIASINUSE) {
3058 ap->flag |= ALIASDEAD;
3059 return ap;
3060 }
3061
3062 next = ap->next;
3063 free(ap->name);
3064 free(ap->val);
3065 free(ap);
3066 return next;
3067}
Eric Andersencb57d552001-06-28 07:25:16 +00003068
Eric Andersenc470f442003-07-28 09:56:35 +00003069static void
3070setalias(const char *name, const char *val)
Eric Andersencb57d552001-06-28 07:25:16 +00003071{
3072 struct alias *ap, **app;
3073
3074 app = __lookupalias(name);
3075 ap = *app;
Denis Vlasenkob012b102007-02-19 22:43:01 +00003076 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +00003077 if (ap) {
3078 if (!(ap->flag & ALIASINUSE)) {
Denis Vlasenkob012b102007-02-19 22:43:01 +00003079 free(ap->val);
Eric Andersencb57d552001-06-28 07:25:16 +00003080 }
Denis Vlasenko0c032a42007-02-23 01:03:40 +00003081 ap->val = ckstrdup(val);
Eric Andersencb57d552001-06-28 07:25:16 +00003082 ap->flag &= ~ALIASDEAD;
3083 } else {
3084 /* not found */
Denis Vlasenko597906c2008-02-20 16:38:54 +00003085 ap = ckzalloc(sizeof(struct alias));
Denis Vlasenko0c032a42007-02-23 01:03:40 +00003086 ap->name = ckstrdup(name);
3087 ap->val = ckstrdup(val);
Denis Vlasenko597906c2008-02-20 16:38:54 +00003088 /*ap->flag = 0; - ckzalloc did it */
3089 /*ap->next = NULL;*/
Eric Andersencb57d552001-06-28 07:25:16 +00003090 *app = ap;
3091 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00003092 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00003093}
3094
Eric Andersenc470f442003-07-28 09:56:35 +00003095static int
3096unalias(const char *name)
Eric Andersen2870d962001-07-02 17:27:21 +00003097{
Eric Andersencb57d552001-06-28 07:25:16 +00003098 struct alias **app;
3099
3100 app = __lookupalias(name);
3101
3102 if (*app) {
Denis Vlasenkob012b102007-02-19 22:43:01 +00003103 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +00003104 *app = freealias(*app);
Denis Vlasenkob012b102007-02-19 22:43:01 +00003105 INT_ON;
Denis Vlasenko079f8af2006-11-27 16:49:31 +00003106 return 0;
Eric Andersencb57d552001-06-28 07:25:16 +00003107 }
3108
Denis Vlasenko079f8af2006-11-27 16:49:31 +00003109 return 1;
Eric Andersencb57d552001-06-28 07:25:16 +00003110}
3111
Eric Andersenc470f442003-07-28 09:56:35 +00003112static void
3113rmaliases(void)
Eric Andersen2870d962001-07-02 17:27:21 +00003114{
Eric Andersencb57d552001-06-28 07:25:16 +00003115 struct alias *ap, **app;
3116 int i;
3117
Denis Vlasenkob012b102007-02-19 22:43:01 +00003118 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +00003119 for (i = 0; i < ATABSIZE; i++) {
3120 app = &atab[i];
3121 for (ap = *app; ap; ap = *app) {
3122 *app = freealias(*app);
3123 if (ap == *app) {
3124 app = &ap->next;
3125 }
3126 }
3127 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00003128 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00003129}
3130
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00003131static void
3132printalias(const struct alias *ap)
3133{
3134 out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
3135}
3136
Eric Andersencb57d552001-06-28 07:25:16 +00003137/*
3138 * TODO - sort output
3139 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02003140static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00003141aliascmd(int argc UNUSED_PARAM, char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +00003142{
3143 char *n, *v;
3144 int ret = 0;
3145 struct alias *ap;
3146
Denis Vlasenko68404f12008-03-17 09:00:54 +00003147 if (!argv[1]) {
Eric Andersencb57d552001-06-28 07:25:16 +00003148 int i;
3149
Denis Vlasenko68404f12008-03-17 09:00:54 +00003150 for (i = 0; i < ATABSIZE; i++) {
Eric Andersencb57d552001-06-28 07:25:16 +00003151 for (ap = atab[i]; ap; ap = ap->next) {
3152 printalias(ap);
3153 }
Denis Vlasenko68404f12008-03-17 09:00:54 +00003154 }
Denis Vlasenko079f8af2006-11-27 16:49:31 +00003155 return 0;
Eric Andersencb57d552001-06-28 07:25:16 +00003156 }
3157 while ((n = *++argv) != NULL) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00003158 v = strchr(n+1, '=');
3159 if (v == NULL) { /* n+1: funny ksh stuff */
3160 ap = *__lookupalias(n);
3161 if (ap == NULL) {
Eric Andersenc470f442003-07-28 09:56:35 +00003162 fprintf(stderr, "%s: %s not found\n", "alias", n);
Eric Andersencb57d552001-06-28 07:25:16 +00003163 ret = 1;
3164 } else
3165 printalias(ap);
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00003166 } else {
Eric Andersencb57d552001-06-28 07:25:16 +00003167 *v++ = '\0';
3168 setalias(n, v);
3169 }
3170 }
3171
Denis Vlasenkod9e15f22006-11-27 16:49:55 +00003172 return ret;
Eric Andersencb57d552001-06-28 07:25:16 +00003173}
3174
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02003175static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00003176unaliascmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersencb57d552001-06-28 07:25:16 +00003177{
3178 int i;
3179
3180 while ((i = nextopt("a")) != '\0') {
3181 if (i == 'a') {
3182 rmaliases();
Denis Vlasenko079f8af2006-11-27 16:49:31 +00003183 return 0;
Eric Andersencb57d552001-06-28 07:25:16 +00003184 }
3185 }
3186 for (i = 0; *argptr; argptr++) {
3187 if (unalias(*argptr)) {
Eric Andersenc470f442003-07-28 09:56:35 +00003188 fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
Eric Andersencb57d552001-06-28 07:25:16 +00003189 i = 1;
3190 }
3191 }
3192
Denis Vlasenkod9e15f22006-11-27 16:49:55 +00003193 return i;
Eric Andersencb57d552001-06-28 07:25:16 +00003194}
Denis Vlasenkofc06f292007-02-23 21:09:35 +00003195
Denis Vlasenko131ae172007-02-18 13:00:19 +00003196#endif /* ASH_ALIAS */
Eric Andersencb57d552001-06-28 07:25:16 +00003197
Eric Andersenc470f442003-07-28 09:56:35 +00003198
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003199/* ============ jobs.c */
3200
3201/* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
Denys Vlasenko285ad152009-12-04 23:02:27 +01003202#define FORK_FG 0
3203#define FORK_BG 1
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003204#define FORK_NOJOB 2
3205
3206/* mode flags for showjob(s) */
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003207#define SHOW_ONLY_PGID 0x01 /* show only pgid (jobs -p) */
3208#define SHOW_PIDS 0x02 /* show individual pids, not just one line per job */
3209#define SHOW_CHANGED 0x04 /* only jobs whose state has changed */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003210
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003211/*
3212 * A job structure contains information about a job. A job is either a
3213 * single process or a set of processes contained in a pipeline. In the
3214 * latter case, pidlist will be non-NULL, and will point to a -1 terminated
3215 * array of pids.
3216 */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003217struct procstat {
Denys Vlasenko285ad152009-12-04 23:02:27 +01003218 pid_t ps_pid; /* process id */
3219 int ps_status; /* last process status from wait() */
3220 char *ps_cmd; /* text of command being run */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003221};
3222
3223struct job {
3224 struct procstat ps0; /* status of process */
3225 struct procstat *ps; /* status or processes when more than one */
3226#if JOBS
3227 int stopstatus; /* status of a stopped job */
3228#endif
3229 uint32_t
3230 nprocs: 16, /* number of processes */
3231 state: 8,
3232#define JOBRUNNING 0 /* at least one proc running */
3233#define JOBSTOPPED 1 /* all procs are stopped */
3234#define JOBDONE 2 /* all procs are completed */
3235#if JOBS
3236 sigint: 1, /* job was killed by SIGINT */
3237 jobctl: 1, /* job running under job control */
3238#endif
3239 waited: 1, /* true if this entry has been waited for */
3240 used: 1, /* true if this entry is in used */
3241 changed: 1; /* true if status has changed */
3242 struct job *prev_job; /* previous job */
3243};
3244
Denis Vlasenko68404f12008-03-17 09:00:54 +00003245static struct job *makejob(/*union node *,*/ int);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003246static int forkshell(struct job *, union node *, int);
3247static int waitforjob(struct job *);
3248
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003249#if !JOBS
Denis Vlasenkob07a4962008-06-22 13:16:23 +00003250enum { doing_jobctl = 0 };
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003251#define setjobctl(on) do {} while (0)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003252#else
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003253static smallint doing_jobctl; //references:8
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003254static void setjobctl(int);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003255#endif
3256
3257/*
Denis Vlasenko4b875702009-03-19 13:30:04 +00003258 * Ignore a signal.
3259 */
3260static void
3261ignoresig(int signo)
3262{
3263 /* Avoid unnecessary system calls. Is it already SIG_IGNed? */
3264 if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
3265 /* No, need to do it */
3266 signal(signo, SIG_IGN);
3267 }
3268 sigmode[signo - 1] = S_HARD_IGN;
3269}
3270
3271/*
Denys Vlasenko238bf182010-05-18 15:49:07 +02003272 * Only one usage site - in setsignal()
Denis Vlasenko4b875702009-03-19 13:30:04 +00003273 */
3274static void
Denys Vlasenko238bf182010-05-18 15:49:07 +02003275signal_handler(int signo)
Denis Vlasenko4b875702009-03-19 13:30:04 +00003276{
3277 gotsig[signo - 1] = 1;
3278
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02003279 if (signo == SIGINT && !trap[SIGINT]) {
3280 if (!suppress_int) {
3281 pending_sig = 0;
Denis Vlasenko4b875702009-03-19 13:30:04 +00003282 raise_interrupt(); /* does not return */
3283 }
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02003284 pending_int = 1;
Denis Vlasenko4b875702009-03-19 13:30:04 +00003285 } else {
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02003286 pending_sig = signo;
Denis Vlasenko4b875702009-03-19 13:30:04 +00003287 }
3288}
3289
3290/*
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003291 * Set the signal handler for the specified signal. The routine figures
3292 * out what it should be set to.
3293 */
3294static void
3295setsignal(int signo)
3296{
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003297 char *t;
3298 char cur_act, new_act;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003299 struct sigaction act;
3300
3301 t = trap[signo];
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003302 new_act = S_DFL;
3303 if (t != NULL) { /* trap for this sig is set */
3304 new_act = S_CATCH;
3305 if (t[0] == '\0') /* trap is "": ignore this sig */
3306 new_act = S_IGN;
3307 }
3308
3309 if (rootshell && new_act == S_DFL) {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003310 switch (signo) {
3311 case SIGINT:
3312 if (iflag || minusc || sflag == 0)
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003313 new_act = S_CATCH;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003314 break;
3315 case SIGQUIT:
3316#if DEBUG
3317 if (debug)
3318 break;
3319#endif
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003320 /* man bash:
3321 * "In all cases, bash ignores SIGQUIT. Non-builtin
3322 * commands run by bash have signal handlers
3323 * set to the values inherited by the shell
3324 * from its parent". */
3325 new_act = S_IGN;
3326 break;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003327 case SIGTERM:
3328 if (iflag)
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003329 new_act = S_IGN;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003330 break;
3331#if JOBS
3332 case SIGTSTP:
3333 case SIGTTOU:
3334 if (mflag)
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003335 new_act = S_IGN;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003336 break;
3337#endif
3338 }
3339 }
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003340//TODO: if !rootshell, we reset SIGQUIT to DFL,
3341//whereas we have to restore it to what shell got on entry
3342//from the parent. See comment above
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003343
3344 t = &sigmode[signo - 1];
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003345 cur_act = *t;
3346 if (cur_act == 0) {
3347 /* current setting is not yet known */
3348 if (sigaction(signo, NULL, &act)) {
3349 /* pretend it worked; maybe we should give a warning,
3350 * but other shells don't. We don't alter sigmode,
3351 * so we retry every time.
3352 * btw, in Linux it never fails. --vda */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003353 return;
3354 }
3355 if (act.sa_handler == SIG_IGN) {
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003356 cur_act = S_HARD_IGN;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003357 if (mflag
3358 && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
3359 ) {
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003360 cur_act = S_IGN; /* don't hard ignore these */
Denis Vlasenko991a1da2008-02-10 19:02:53 +00003361 }
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003362 }
3363 }
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003364 if (cur_act == S_HARD_IGN || cur_act == new_act)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003365 return;
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003366
Denis Vlasenko991a1da2008-02-10 19:02:53 +00003367 act.sa_handler = SIG_DFL;
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003368 switch (new_act) {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003369 case S_CATCH:
Denys Vlasenko238bf182010-05-18 15:49:07 +02003370 act.sa_handler = signal_handler;
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003371 act.sa_flags = 0; /* matters only if !DFL and !IGN */
3372 sigfillset(&act.sa_mask); /* ditto */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003373 break;
3374 case S_IGN:
3375 act.sa_handler = SIG_IGN;
3376 break;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003377 }
Denis Vlasenko8e2cfec2008-03-12 23:19:35 +00003378 sigaction_set(signo, &act);
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003379
3380 *t = new_act;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003381}
3382
3383/* mode flags for set_curjob */
3384#define CUR_DELETE 2
3385#define CUR_RUNNING 1
3386#define CUR_STOPPED 0
3387
3388/* mode flags for dowait */
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00003389#define DOWAIT_NONBLOCK WNOHANG
3390#define DOWAIT_BLOCK 0
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003391
3392#if JOBS
3393/* pgrp of shell on invocation */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003394static int initialpgrp; //references:2
3395static int ttyfd = -1; //5
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003396#endif
3397/* array of jobs */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003398static struct job *jobtab; //5
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003399/* size of array */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003400static unsigned njobs; //4
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003401/* current job */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003402static struct job *curjob; //lots
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003403/* number of presumed living untracked jobs */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003404static int jobless; //4
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003405
3406static void
3407set_curjob(struct job *jp, unsigned mode)
3408{
3409 struct job *jp1;
3410 struct job **jpp, **curp;
3411
3412 /* first remove from list */
3413 jpp = curp = &curjob;
3414 do {
3415 jp1 = *jpp;
3416 if (jp1 == jp)
3417 break;
3418 jpp = &jp1->prev_job;
3419 } while (1);
3420 *jpp = jp1->prev_job;
3421
3422 /* Then re-insert in correct position */
3423 jpp = curp;
3424 switch (mode) {
3425 default:
3426#if DEBUG
3427 abort();
3428#endif
3429 case CUR_DELETE:
3430 /* job being deleted */
3431 break;
3432 case CUR_RUNNING:
3433 /* newly created job or backgrounded job,
3434 put after all stopped jobs. */
3435 do {
3436 jp1 = *jpp;
3437#if JOBS
3438 if (!jp1 || jp1->state != JOBSTOPPED)
3439#endif
3440 break;
3441 jpp = &jp1->prev_job;
3442 } while (1);
3443 /* FALLTHROUGH */
3444#if JOBS
3445 case CUR_STOPPED:
3446#endif
3447 /* newly stopped job - becomes curjob */
3448 jp->prev_job = *jpp;
3449 *jpp = jp;
3450 break;
3451 }
3452}
3453
3454#if JOBS || DEBUG
3455static int
3456jobno(const struct job *jp)
3457{
3458 return jp - jobtab + 1;
3459}
3460#endif
3461
3462/*
3463 * Convert a job name to a job structure.
3464 */
Denis Vlasenko85c24712008-03-17 09:04:04 +00003465#if !JOBS
3466#define getjob(name, getctl) getjob(name)
3467#endif
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003468static struct job *
3469getjob(const char *name, int getctl)
3470{
3471 struct job *jp;
3472 struct job *found;
Denys Vlasenkoffc39202009-08-17 02:12:20 +02003473 const char *err_msg = "%s: no such job";
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003474 unsigned num;
3475 int c;
3476 const char *p;
3477 char *(*match)(const char *, const char *);
3478
3479 jp = curjob;
3480 p = name;
3481 if (!p)
3482 goto currentjob;
3483
3484 if (*p != '%')
3485 goto err;
3486
3487 c = *++p;
3488 if (!c)
3489 goto currentjob;
3490
3491 if (!p[1]) {
3492 if (c == '+' || c == '%') {
3493 currentjob:
3494 err_msg = "No current job";
3495 goto check;
3496 }
3497 if (c == '-') {
3498 if (jp)
3499 jp = jp->prev_job;
3500 err_msg = "No previous job";
3501 check:
3502 if (!jp)
3503 goto err;
3504 goto gotit;
3505 }
3506 }
3507
3508 if (is_number(p)) {
3509 num = atoi(p);
3510 if (num < njobs) {
3511 jp = jobtab + num - 1;
3512 if (jp->used)
3513 goto gotit;
3514 goto err;
3515 }
3516 }
3517
3518 match = prefix;
3519 if (*p == '?') {
3520 match = strstr;
3521 p++;
3522 }
3523
Denys Vlasenkoffc39202009-08-17 02:12:20 +02003524 found = NULL;
3525 while (jp) {
Denys Vlasenko285ad152009-12-04 23:02:27 +01003526 if (match(jp->ps[0].ps_cmd, p)) {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003527 if (found)
3528 goto err;
3529 found = jp;
3530 err_msg = "%s: ambiguous";
3531 }
3532 jp = jp->prev_job;
3533 }
Denys Vlasenkoffc39202009-08-17 02:12:20 +02003534 if (!found)
3535 goto err;
3536 jp = found;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003537
3538 gotit:
3539#if JOBS
3540 err_msg = "job %s not created under job control";
3541 if (getctl && jp->jobctl == 0)
3542 goto err;
3543#endif
3544 return jp;
3545 err:
3546 ash_msg_and_raise_error(err_msg, name);
3547}
3548
3549/*
3550 * Mark a job structure as unused.
3551 */
3552static void
3553freejob(struct job *jp)
3554{
3555 struct procstat *ps;
3556 int i;
3557
3558 INT_OFF;
3559 for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
Denys Vlasenko285ad152009-12-04 23:02:27 +01003560 if (ps->ps_cmd != nullstr)
3561 free(ps->ps_cmd);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003562 }
3563 if (jp->ps != &jp->ps0)
3564 free(jp->ps);
3565 jp->used = 0;
3566 set_curjob(jp, CUR_DELETE);
3567 INT_ON;
3568}
3569
3570#if JOBS
3571static void
3572xtcsetpgrp(int fd, pid_t pgrp)
3573{
3574 if (tcsetpgrp(fd, pgrp))
Bernhard Reutner-Fischera53de7f2008-07-21 13:46:54 +00003575 ash_msg_and_raise_error("can't set tty process group (%m)");
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003576}
3577
3578/*
3579 * Turn job control on and off.
3580 *
3581 * Note: This code assumes that the third arg to ioctl is a character
3582 * pointer, which is true on Berkeley systems but not System V. Since
3583 * System V doesn't have job control yet, this isn't a problem now.
3584 *
3585 * Called with interrupts off.
3586 */
3587static void
3588setjobctl(int on)
3589{
3590 int fd;
3591 int pgrp;
3592
Denis Vlasenkob07a4962008-06-22 13:16:23 +00003593 if (on == doing_jobctl || rootshell == 0)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003594 return;
3595 if (on) {
3596 int ofd;
3597 ofd = fd = open(_PATH_TTY, O_RDWR);
3598 if (fd < 0) {
3599 /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
3600 * That sometimes helps to acquire controlling tty.
3601 * Obviously, a workaround for bugs when someone
3602 * failed to provide a controlling tty to bash! :) */
Denis Vlasenkoed270a52007-11-26 05:37:07 +00003603 fd = 2;
3604 while (!isatty(fd))
3605 if (--fd < 0)
3606 goto out;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003607 }
3608 fd = fcntl(fd, F_DUPFD, 10);
Denis Vlasenkoed270a52007-11-26 05:37:07 +00003609 if (ofd >= 0)
3610 close(ofd);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003611 if (fd < 0)
3612 goto out;
Denis Vlasenkoed270a52007-11-26 05:37:07 +00003613 /* fd is a tty at this point */
Denis Vlasenko96e1b382007-09-30 23:50:48 +00003614 close_on_exec_on(fd);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003615 do { /* while we are in the background */
3616 pgrp = tcgetpgrp(fd);
3617 if (pgrp < 0) {
3618 out:
3619 ash_msg("can't access tty; job control turned off");
3620 mflag = on = 0;
3621 goto close;
3622 }
3623 if (pgrp == getpgrp())
3624 break;
3625 killpg(0, SIGTTIN);
3626 } while (1);
3627 initialpgrp = pgrp;
3628
3629 setsignal(SIGTSTP);
3630 setsignal(SIGTTOU);
3631 setsignal(SIGTTIN);
3632 pgrp = rootpid;
3633 setpgid(0, pgrp);
3634 xtcsetpgrp(fd, pgrp);
3635 } else {
3636 /* turning job control off */
3637 fd = ttyfd;
3638 pgrp = initialpgrp;
Denis Vlasenko08c8c1d2007-04-28 22:39:02 +00003639 /* was xtcsetpgrp, but this can make exiting ash
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00003640 * loop forever if pty is already deleted */
Denis Vlasenko08c8c1d2007-04-28 22:39:02 +00003641 tcsetpgrp(fd, pgrp);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003642 setpgid(0, pgrp);
3643 setsignal(SIGTSTP);
3644 setsignal(SIGTTOU);
3645 setsignal(SIGTTIN);
3646 close:
Denis Vlasenkoed270a52007-11-26 05:37:07 +00003647 if (fd >= 0)
3648 close(fd);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003649 fd = -1;
3650 }
3651 ttyfd = fd;
Denis Vlasenkob07a4962008-06-22 13:16:23 +00003652 doing_jobctl = on;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003653}
3654
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02003655static int FAST_FUNC
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003656killcmd(int argc, char **argv)
3657{
Denis Vlasenko68404f12008-03-17 09:00:54 +00003658 int i = 1;
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003659 if (argv[1] && strcmp(argv[1], "-l") != 0) {
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003660 do {
3661 if (argv[i][0] == '%') {
3662 struct job *jp = getjob(argv[i], 0);
Denys Vlasenko285ad152009-12-04 23:02:27 +01003663 unsigned pid = jp->ps[0].ps_pid;
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003664 /* Enough space for ' -NNN<nul>' */
3665 argv[i] = alloca(sizeof(int)*3 + 3);
3666 /* kill_main has matching code to expect
3667 * leading space. Needed to not confuse
3668 * negative pids with "kill -SIGNAL_NO" syntax */
3669 sprintf(argv[i], " -%u", pid);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003670 }
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003671 } while (argv[++i]);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003672 }
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003673 return kill_main(argc, argv);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003674}
3675
3676static void
Denys Vlasenko285ad152009-12-04 23:02:27 +01003677showpipe(struct job *jp /*, FILE *out*/)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003678{
Denys Vlasenko285ad152009-12-04 23:02:27 +01003679 struct procstat *ps;
3680 struct procstat *psend;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003681
Denys Vlasenko285ad152009-12-04 23:02:27 +01003682 psend = jp->ps + jp->nprocs;
3683 for (ps = jp->ps + 1; ps < psend; ps++)
3684 printf(" | %s", ps->ps_cmd);
3685 outcslow('\n', stdout);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003686 flush_stdout_stderr();
3687}
3688
3689
3690static int
3691restartjob(struct job *jp, int mode)
3692{
3693 struct procstat *ps;
3694 int i;
3695 int status;
3696 pid_t pgid;
3697
3698 INT_OFF;
3699 if (jp->state == JOBDONE)
3700 goto out;
3701 jp->state = JOBRUNNING;
Denys Vlasenko285ad152009-12-04 23:02:27 +01003702 pgid = jp->ps[0].ps_pid;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003703 if (mode == FORK_FG)
3704 xtcsetpgrp(ttyfd, pgid);
3705 killpg(pgid, SIGCONT);
3706 ps = jp->ps;
3707 i = jp->nprocs;
3708 do {
Denys Vlasenko285ad152009-12-04 23:02:27 +01003709 if (WIFSTOPPED(ps->ps_status)) {
3710 ps->ps_status = -1;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003711 }
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003712 ps++;
3713 } while (--i);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003714 out:
3715 status = (mode == FORK_FG) ? waitforjob(jp) : 0;
3716 INT_ON;
3717 return status;
3718}
3719
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02003720static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00003721fg_bgcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003722{
3723 struct job *jp;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003724 int mode;
3725 int retval;
3726
3727 mode = (**argv == 'f') ? FORK_FG : FORK_BG;
3728 nextopt(nullstr);
3729 argv = argptr;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003730 do {
3731 jp = getjob(*argv, 1);
3732 if (mode == FORK_BG) {
3733 set_curjob(jp, CUR_RUNNING);
Denys Vlasenko285ad152009-12-04 23:02:27 +01003734 printf("[%d] ", jobno(jp));
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003735 }
Denys Vlasenko285ad152009-12-04 23:02:27 +01003736 out1str(jp->ps[0].ps_cmd);
3737 showpipe(jp /*, stdout*/);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003738 retval = restartjob(jp, mode);
3739 } while (*argv && *++argv);
3740 return retval;
3741}
3742#endif
3743
3744static int
3745sprint_status(char *s, int status, int sigonly)
3746{
3747 int col;
3748 int st;
3749
3750 col = 0;
3751 if (!WIFEXITED(status)) {
3752#if JOBS
3753 if (WIFSTOPPED(status))
3754 st = WSTOPSIG(status);
3755 else
3756#endif
3757 st = WTERMSIG(status);
3758 if (sigonly) {
3759 if (st == SIGINT || st == SIGPIPE)
3760 goto out;
3761#if JOBS
3762 if (WIFSTOPPED(status))
3763 goto out;
3764#endif
3765 }
3766 st &= 0x7f;
3767 col = fmtstr(s, 32, strsignal(st));
3768 if (WCOREDUMP(status)) {
3769 col += fmtstr(s + col, 16, " (core dumped)");
3770 }
3771 } else if (!sigonly) {
3772 st = WEXITSTATUS(status);
3773 if (st)
3774 col = fmtstr(s, 16, "Done(%d)", st);
3775 else
3776 col = fmtstr(s, 16, "Done");
3777 }
3778 out:
3779 return col;
3780}
3781
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003782static int
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00003783dowait(int wait_flags, struct job *job)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003784{
3785 int pid;
3786 int status;
3787 struct job *jp;
3788 struct job *thisjob;
3789 int state;
3790
Denis Vlasenkobe54d6b2008-10-27 14:25:52 +00003791 TRACE(("dowait(0x%x) called\n", wait_flags));
3792
3793 /* Do a wait system call. If job control is compiled in, we accept
3794 * stopped processes. wait_flags may have WNOHANG, preventing blocking.
3795 * NB: _not_ safe_waitpid, we need to detect EINTR */
Denys Vlasenko285ad152009-12-04 23:02:27 +01003796 if (doing_jobctl)
3797 wait_flags |= WUNTRACED;
3798 pid = waitpid(-1, &status, wait_flags);
Denis Vlasenkob21f3792009-03-19 23:09:58 +00003799 TRACE(("wait returns pid=%d, status=0x%x, errno=%d(%s)\n",
3800 pid, status, errno, strerror(errno)));
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003801 if (pid <= 0)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003802 return pid;
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003803
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003804 INT_OFF;
3805 thisjob = NULL;
3806 for (jp = curjob; jp; jp = jp->prev_job) {
Denys Vlasenko285ad152009-12-04 23:02:27 +01003807 struct procstat *ps;
3808 struct procstat *psend;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003809 if (jp->state == JOBDONE)
3810 continue;
3811 state = JOBDONE;
Denys Vlasenko285ad152009-12-04 23:02:27 +01003812 ps = jp->ps;
3813 psend = ps + jp->nprocs;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003814 do {
Denys Vlasenko285ad152009-12-04 23:02:27 +01003815 if (ps->ps_pid == pid) {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003816 TRACE(("Job %d: changing status of proc %d "
3817 "from 0x%x to 0x%x\n",
Denys Vlasenko285ad152009-12-04 23:02:27 +01003818 jobno(jp), pid, ps->ps_status, status));
3819 ps->ps_status = status;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003820 thisjob = jp;
3821 }
Denys Vlasenko285ad152009-12-04 23:02:27 +01003822 if (ps->ps_status == -1)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003823 state = JOBRUNNING;
3824#if JOBS
3825 if (state == JOBRUNNING)
3826 continue;
Denys Vlasenko285ad152009-12-04 23:02:27 +01003827 if (WIFSTOPPED(ps->ps_status)) {
3828 jp->stopstatus = ps->ps_status;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003829 state = JOBSTOPPED;
3830 }
3831#endif
Denys Vlasenko285ad152009-12-04 23:02:27 +01003832 } while (++ps < psend);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003833 if (thisjob)
3834 goto gotjob;
3835 }
3836#if JOBS
3837 if (!WIFSTOPPED(status))
3838#endif
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003839 jobless--;
3840 goto out;
3841
3842 gotjob:
3843 if (state != JOBRUNNING) {
3844 thisjob->changed = 1;
3845
3846 if (thisjob->state != state) {
3847 TRACE(("Job %d: changing state from %d to %d\n",
3848 jobno(thisjob), thisjob->state, state));
3849 thisjob->state = state;
3850#if JOBS
3851 if (state == JOBSTOPPED) {
3852 set_curjob(thisjob, CUR_STOPPED);
3853 }
3854#endif
3855 }
3856 }
3857
3858 out:
3859 INT_ON;
3860
3861 if (thisjob && thisjob == job) {
3862 char s[48 + 1];
3863 int len;
3864
3865 len = sprint_status(s, status, 1);
3866 if (len) {
3867 s[len] = '\n';
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00003868 s[len + 1] = '\0';
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003869 out2str(s);
3870 }
3871 }
3872 return pid;
3873}
3874
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003875static int
Denys Vlasenko7c1ed9f2010-05-17 04:42:40 +02003876blocking_wait_with_raise_on_sig(void)
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003877{
Denys Vlasenko7c1ed9f2010-05-17 04:42:40 +02003878 pid_t pid = dowait(DOWAIT_BLOCK, NULL);
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02003879 if (pid <= 0 && pending_sig)
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003880 raise_exception(EXSIG);
3881 return pid;
3882}
3883
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003884#if JOBS
3885static void
3886showjob(FILE *out, struct job *jp, int mode)
3887{
3888 struct procstat *ps;
3889 struct procstat *psend;
3890 int col;
Denis Vlasenko40ba9982007-07-14 00:48:29 +00003891 int indent_col;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003892 char s[80];
3893
3894 ps = jp->ps;
3895
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003896 if (mode & SHOW_ONLY_PGID) { /* jobs -p */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003897 /* just output process (group) id of pipeline */
Denys Vlasenko285ad152009-12-04 23:02:27 +01003898 fprintf(out, "%d\n", ps->ps_pid);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003899 return;
3900 }
3901
3902 col = fmtstr(s, 16, "[%d] ", jobno(jp));
Denis Vlasenko40ba9982007-07-14 00:48:29 +00003903 indent_col = col;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003904
3905 if (jp == curjob)
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003906 s[col - 3] = '+';
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003907 else if (curjob && jp == curjob->prev_job)
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003908 s[col - 3] = '-';
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003909
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003910 if (mode & SHOW_PIDS)
Denys Vlasenko285ad152009-12-04 23:02:27 +01003911 col += fmtstr(s + col, 16, "%d ", ps->ps_pid);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003912
3913 psend = ps + jp->nprocs;
3914
3915 if (jp->state == JOBRUNNING) {
3916 strcpy(s + col, "Running");
3917 col += sizeof("Running") - 1;
3918 } else {
Denys Vlasenko285ad152009-12-04 23:02:27 +01003919 int status = psend[-1].ps_status;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003920 if (jp->state == JOBSTOPPED)
3921 status = jp->stopstatus;
3922 col += sprint_status(s + col, status, 0);
3923 }
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003924 /* By now, "[JOBID]* [maybe PID] STATUS" is printed */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003925
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003926 /* This loop either prints "<cmd1> | <cmd2> | <cmd3>" line
3927 * or prints several "PID | <cmdN>" lines,
3928 * depending on SHOW_PIDS bit.
3929 * We do not print status of individual processes
3930 * between PID and <cmdN>. bash does it, but not very well:
3931 * first line shows overall job status, not process status,
3932 * making it impossible to know 1st process status.
3933 */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003934 goto start;
Denys Vlasenko285ad152009-12-04 23:02:27 +01003935 do {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003936 /* for each process */
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003937 s[0] = '\0';
3938 col = 33;
3939 if (mode & SHOW_PIDS)
Denys Vlasenko285ad152009-12-04 23:02:27 +01003940 col = fmtstr(s, 48, "\n%*c%d ", indent_col, ' ', ps->ps_pid) - 1;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003941 start:
Denys Vlasenko285ad152009-12-04 23:02:27 +01003942 fprintf(out, "%s%*c%s%s",
3943 s,
3944 33 - col >= 0 ? 33 - col : 0, ' ',
3945 ps == jp->ps ? "" : "| ",
3946 ps->ps_cmd
3947 );
3948 } while (++ps != psend);
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003949 outcslow('\n', out);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003950
3951 jp->changed = 0;
3952
3953 if (jp->state == JOBDONE) {
3954 TRACE(("showjob: freeing job %d\n", jobno(jp)));
3955 freejob(jp);
3956 }
3957}
3958
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003959/*
3960 * Print a list of jobs. If "change" is nonzero, only print jobs whose
3961 * statuses have changed since the last call to showjobs.
3962 */
3963static void
3964showjobs(FILE *out, int mode)
3965{
3966 struct job *jp;
3967
Denys Vlasenko883cea42009-07-11 15:31:59 +02003968 TRACE(("showjobs(0x%x) called\n", mode));
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003969
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003970 /* Handle all finished jobs */
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00003971 while (dowait(DOWAIT_NONBLOCK, NULL) > 0)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003972 continue;
3973
3974 for (jp = curjob; jp; jp = jp->prev_job) {
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003975 if (!(mode & SHOW_CHANGED) || jp->changed) {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003976 showjob(out, jp, mode);
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003977 }
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003978 }
3979}
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003980
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02003981static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00003982jobscmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003983{
3984 int mode, m;
3985
3986 mode = 0;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02003987 while ((m = nextopt("lp")) != '\0') {
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003988 if (m == 'l')
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003989 mode |= SHOW_PIDS;
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003990 else
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003991 mode |= SHOW_ONLY_PGID;
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003992 }
3993
3994 argv = argptr;
3995 if (*argv) {
3996 do
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003997 showjob(stdout, getjob(*argv, 0), mode);
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003998 while (*++argv);
Denys Vlasenko285ad152009-12-04 23:02:27 +01003999 } else {
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00004000 showjobs(stdout, mode);
Denys Vlasenko285ad152009-12-04 23:02:27 +01004001 }
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00004002
4003 return 0;
4004}
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004005#endif /* JOBS */
4006
Michael Abbott359da5e2009-12-04 23:03:29 +01004007/* Called only on finished or stopped jobs (no members are running) */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004008static int
4009getstatus(struct job *job)
4010{
4011 int status;
4012 int retval;
Michael Abbott359da5e2009-12-04 23:03:29 +01004013 struct procstat *ps;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004014
Michael Abbott359da5e2009-12-04 23:03:29 +01004015 /* Fetch last member's status */
4016 ps = job->ps + job->nprocs - 1;
4017 status = ps->ps_status;
4018 if (pipefail) {
4019 /* "set -o pipefail" mode: use last _nonzero_ status */
4020 while (status == 0 && --ps >= job->ps)
4021 status = ps->ps_status;
4022 }
4023
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004024 retval = WEXITSTATUS(status);
4025 if (!WIFEXITED(status)) {
4026#if JOBS
4027 retval = WSTOPSIG(status);
4028 if (!WIFSTOPPED(status))
4029#endif
4030 {
4031 /* XXX: limits number of signals */
4032 retval = WTERMSIG(status);
4033#if JOBS
4034 if (retval == SIGINT)
4035 job->sigint = 1;
4036#endif
4037 }
4038 retval += 128;
4039 }
Denys Vlasenko883cea42009-07-11 15:31:59 +02004040 TRACE(("getstatus: job %d, nproc %d, status 0x%x, retval 0x%x\n",
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004041 jobno(job), job->nprocs, status, retval));
4042 return retval;
4043}
4044
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02004045static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00004046waitcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004047{
4048 struct job *job;
4049 int retval;
4050 struct job *jp;
4051
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02004052 if (pending_sig)
Denis Vlasenko991a1da2008-02-10 19:02:53 +00004053 raise_exception(EXSIG);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004054
4055 nextopt(nullstr);
4056 retval = 0;
4057
4058 argv = argptr;
4059 if (!*argv) {
4060 /* wait for all jobs */
4061 for (;;) {
4062 jp = curjob;
4063 while (1) {
Denis Vlasenko991a1da2008-02-10 19:02:53 +00004064 if (!jp) /* no running procs */
4065 goto ret;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004066 if (jp->state == JOBRUNNING)
4067 break;
4068 jp->waited = 1;
4069 jp = jp->prev_job;
4070 }
Denys Vlasenko7c1ed9f2010-05-17 04:42:40 +02004071 blocking_wait_with_raise_on_sig();
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004072 /* man bash:
4073 * "When bash is waiting for an asynchronous command via
4074 * the wait builtin, the reception of a signal for which a trap
4075 * has been set will cause the wait builtin to return immediately
4076 * with an exit status greater than 128, immediately after which
4077 * the trap is executed."
Denys Vlasenko7c1ed9f2010-05-17 04:42:40 +02004078 *
4079 * blocking_wait_with_raise_on_sig raises signal handlers
4080 * if it gets no pid (pid < 0). However,
4081 * if child sends us a signal *and immediately exits*,
4082 * blocking_wait_with_raise_on_sig gets pid > 0
4083 * and does not handle pending_sig. Check this case: */
4084 if (pending_sig)
4085 raise_exception(EXSIG);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004086 }
4087 }
4088
4089 retval = 127;
4090 do {
4091 if (**argv != '%') {
4092 pid_t pid = number(*argv);
4093 job = curjob;
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00004094 while (1) {
4095 if (!job)
4096 goto repeat;
Denys Vlasenko285ad152009-12-04 23:02:27 +01004097 if (job->ps[job->nprocs - 1].ps_pid == pid)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004098 break;
4099 job = job->prev_job;
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00004100 }
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004101 } else
4102 job = getjob(*argv, 0);
4103 /* loop until process terminated or stopped */
4104 while (job->state == JOBRUNNING)
Denys Vlasenko7c1ed9f2010-05-17 04:42:40 +02004105 blocking_wait_with_raise_on_sig();
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004106 job->waited = 1;
4107 retval = getstatus(job);
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004108 repeat: ;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004109 } while (*++argv);
4110
Denis Vlasenko991a1da2008-02-10 19:02:53 +00004111 ret:
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004112 return retval;
4113}
4114
4115static struct job *
4116growjobtab(void)
4117{
4118 size_t len;
4119 ptrdiff_t offset;
4120 struct job *jp, *jq;
4121
4122 len = njobs * sizeof(*jp);
4123 jq = jobtab;
4124 jp = ckrealloc(jq, len + 4 * sizeof(*jp));
4125
4126 offset = (char *)jp - (char *)jq;
4127 if (offset) {
4128 /* Relocate pointers */
4129 size_t l = len;
4130
4131 jq = (struct job *)((char *)jq + l);
4132 while (l) {
4133 l -= sizeof(*jp);
4134 jq--;
4135#define joff(p) ((struct job *)((char *)(p) + l))
4136#define jmove(p) (p) = (void *)((char *)(p) + offset)
4137 if (joff(jp)->ps == &jq->ps0)
4138 jmove(joff(jp)->ps);
4139 if (joff(jp)->prev_job)
4140 jmove(joff(jp)->prev_job);
4141 }
4142 if (curjob)
4143 jmove(curjob);
4144#undef joff
4145#undef jmove
4146 }
4147
4148 njobs += 4;
4149 jobtab = jp;
4150 jp = (struct job *)((char *)jp + len);
4151 jq = jp + 3;
4152 do {
4153 jq->used = 0;
4154 } while (--jq >= jp);
4155 return jp;
4156}
4157
4158/*
4159 * Return a new job structure.
4160 * Called with interrupts off.
4161 */
4162static struct job *
Denis Vlasenko68404f12008-03-17 09:00:54 +00004163makejob(/*union node *node,*/ int nprocs)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004164{
4165 int i;
4166 struct job *jp;
4167
4168 for (i = njobs, jp = jobtab; ; jp++) {
4169 if (--i < 0) {
4170 jp = growjobtab();
4171 break;
4172 }
4173 if (jp->used == 0)
4174 break;
4175 if (jp->state != JOBDONE || !jp->waited)
4176 continue;
4177#if JOBS
Denis Vlasenkob07a4962008-06-22 13:16:23 +00004178 if (doing_jobctl)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004179 continue;
4180#endif
4181 freejob(jp);
4182 break;
4183 }
4184 memset(jp, 0, sizeof(*jp));
4185#if JOBS
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00004186 /* jp->jobctl is a bitfield.
4187 * "jp->jobctl |= jobctl" likely to give awful code */
Denis Vlasenkob07a4962008-06-22 13:16:23 +00004188 if (doing_jobctl)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004189 jp->jobctl = 1;
4190#endif
4191 jp->prev_job = curjob;
4192 curjob = jp;
4193 jp->used = 1;
4194 jp->ps = &jp->ps0;
4195 if (nprocs > 1) {
4196 jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
4197 }
Denis Vlasenko68404f12008-03-17 09:00:54 +00004198 TRACE(("makejob(%d) returns %%%d\n", nprocs,
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004199 jobno(jp)));
4200 return jp;
4201}
4202
4203#if JOBS
4204/*
4205 * Return a string identifying a command (to be printed by the
4206 * jobs command).
4207 */
4208static char *cmdnextc;
4209
4210static void
4211cmdputs(const char *s)
4212{
Denis Vlasenko92e13c22008-03-25 01:17:40 +00004213 static const char vstype[VSTYPE + 1][3] = {
4214 "", "}", "-", "+", "?", "=",
4215 "%", "%%", "#", "##"
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00004216 IF_ASH_BASH_COMPAT(, ":", "/", "//")
Denis Vlasenko92e13c22008-03-25 01:17:40 +00004217 };
4218
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004219 const char *p, *str;
Denys Vlasenko46a14772009-12-10 21:27:13 +01004220 char cc[2];
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004221 char *nextc;
Denys Vlasenkocd716832009-11-28 22:14:02 +01004222 unsigned char c;
4223 unsigned char subtype = 0;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004224 int quoted = 0;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004225
Denys Vlasenko46a14772009-12-10 21:27:13 +01004226 cc[1] = '\0';
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004227 nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
4228 p = s;
Denys Vlasenko46a14772009-12-10 21:27:13 +01004229 while ((c = *p++) != '\0') {
Denis Vlasenkoef527f52008-06-23 01:52:30 +00004230 str = NULL;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004231 switch (c) {
4232 case CTLESC:
4233 c = *p++;
4234 break;
4235 case CTLVAR:
4236 subtype = *p++;
4237 if ((subtype & VSTYPE) == VSLENGTH)
4238 str = "${#";
4239 else
4240 str = "${";
4241 if (!(subtype & VSQUOTE) == !(quoted & 1))
4242 goto dostr;
4243 quoted ^= 1;
4244 c = '"';
4245 break;
4246 case CTLENDVAR:
4247 str = "\"}" + !(quoted & 1);
4248 quoted >>= 1;
4249 subtype = 0;
4250 goto dostr;
4251 case CTLBACKQ:
4252 str = "$(...)";
4253 goto dostr;
4254 case CTLBACKQ+CTLQUOTE:
4255 str = "\"$(...)\"";
4256 goto dostr;
Mike Frysinger98c52642009-04-02 10:02:37 +00004257#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004258 case CTLARI:
4259 str = "$((";
4260 goto dostr;
4261 case CTLENDARI:
4262 str = "))";
4263 goto dostr;
4264#endif
4265 case CTLQUOTEMARK:
4266 quoted ^= 1;
4267 c = '"';
4268 break;
4269 case '=':
4270 if (subtype == 0)
4271 break;
4272 if ((subtype & VSTYPE) != VSNORMAL)
4273 quoted <<= 1;
4274 str = vstype[subtype & VSTYPE];
4275 if (subtype & VSNUL)
4276 c = ':';
4277 else
4278 goto checkstr;
4279 break;
4280 case '\'':
4281 case '\\':
4282 case '"':
4283 case '$':
4284 /* These can only happen inside quotes */
4285 cc[0] = c;
4286 str = cc;
4287 c = '\\';
4288 break;
4289 default:
4290 break;
4291 }
4292 USTPUTC(c, nextc);
4293 checkstr:
4294 if (!str)
4295 continue;
4296 dostr:
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02004297 while ((c = *str++) != '\0') {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004298 USTPUTC(c, nextc);
4299 }
Denys Vlasenko46a14772009-12-10 21:27:13 +01004300 } /* while *p++ not NUL */
4301
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004302 if (quoted & 1) {
4303 USTPUTC('"', nextc);
4304 }
4305 *nextc = 0;
4306 cmdnextc = nextc;
4307}
4308
4309/* cmdtxt() and cmdlist() call each other */
4310static void cmdtxt(union node *n);
4311
4312static void
4313cmdlist(union node *np, int sep)
4314{
4315 for (; np; np = np->narg.next) {
4316 if (!sep)
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00004317 cmdputs(" ");
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004318 cmdtxt(np);
4319 if (sep && np->narg.next)
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00004320 cmdputs(" ");
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004321 }
4322}
4323
4324static void
4325cmdtxt(union node *n)
4326{
4327 union node *np;
4328 struct nodelist *lp;
4329 const char *p;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004330
4331 if (!n)
4332 return;
4333 switch (n->type) {
4334 default:
4335#if DEBUG
4336 abort();
4337#endif
4338 case NPIPE:
4339 lp = n->npipe.cmdlist;
4340 for (;;) {
4341 cmdtxt(lp->n);
4342 lp = lp->next;
4343 if (!lp)
4344 break;
4345 cmdputs(" | ");
4346 }
4347 break;
4348 case NSEMI:
4349 p = "; ";
4350 goto binop;
4351 case NAND:
4352 p = " && ";
4353 goto binop;
4354 case NOR:
4355 p = " || ";
4356 binop:
4357 cmdtxt(n->nbinary.ch1);
4358 cmdputs(p);
4359 n = n->nbinary.ch2;
4360 goto donode;
4361 case NREDIR:
4362 case NBACKGND:
4363 n = n->nredir.n;
4364 goto donode;
4365 case NNOT:
4366 cmdputs("!");
4367 n = n->nnot.com;
4368 donode:
4369 cmdtxt(n);
4370 break;
4371 case NIF:
4372 cmdputs("if ");
4373 cmdtxt(n->nif.test);
4374 cmdputs("; then ");
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004375 if (n->nif.elsepart) {
Denys Vlasenko7cee00e2009-07-24 01:08:03 +02004376 cmdtxt(n->nif.ifpart);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004377 cmdputs("; else ");
4378 n = n->nif.elsepart;
Denys Vlasenko7cee00e2009-07-24 01:08:03 +02004379 } else {
4380 n = n->nif.ifpart;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004381 }
4382 p = "; fi";
4383 goto dotail;
4384 case NSUBSHELL:
4385 cmdputs("(");
4386 n = n->nredir.n;
4387 p = ")";
4388 goto dotail;
4389 case NWHILE:
4390 p = "while ";
4391 goto until;
4392 case NUNTIL:
4393 p = "until ";
4394 until:
4395 cmdputs(p);
4396 cmdtxt(n->nbinary.ch1);
4397 n = n->nbinary.ch2;
4398 p = "; done";
4399 dodo:
4400 cmdputs("; do ");
4401 dotail:
4402 cmdtxt(n);
4403 goto dotail2;
4404 case NFOR:
4405 cmdputs("for ");
4406 cmdputs(n->nfor.var);
4407 cmdputs(" in ");
4408 cmdlist(n->nfor.args, 1);
4409 n = n->nfor.body;
4410 p = "; done";
4411 goto dodo;
4412 case NDEFUN:
4413 cmdputs(n->narg.text);
4414 p = "() { ... }";
4415 goto dotail2;
4416 case NCMD:
4417 cmdlist(n->ncmd.args, 1);
4418 cmdlist(n->ncmd.redirect, 0);
4419 break;
4420 case NARG:
4421 p = n->narg.text;
4422 dotail2:
4423 cmdputs(p);
4424 break;
4425 case NHERE:
4426 case NXHERE:
4427 p = "<<...";
4428 goto dotail2;
4429 case NCASE:
4430 cmdputs("case ");
4431 cmdputs(n->ncase.expr->narg.text);
4432 cmdputs(" in ");
4433 for (np = n->ncase.cases; np; np = np->nclist.next) {
4434 cmdtxt(np->nclist.pattern);
4435 cmdputs(") ");
4436 cmdtxt(np->nclist.body);
4437 cmdputs(";; ");
4438 }
4439 p = "esac";
4440 goto dotail2;
4441 case NTO:
4442 p = ">";
4443 goto redir;
4444 case NCLOBBER:
4445 p = ">|";
4446 goto redir;
4447 case NAPPEND:
4448 p = ">>";
4449 goto redir;
Denis Vlasenko559691a2008-10-05 18:39:31 +00004450#if ENABLE_ASH_BASH_COMPAT
4451 case NTO2:
4452#endif
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004453 case NTOFD:
4454 p = ">&";
4455 goto redir;
4456 case NFROM:
4457 p = "<";
4458 goto redir;
4459 case NFROMFD:
4460 p = "<&";
4461 goto redir;
4462 case NFROMTO:
4463 p = "<>";
4464 redir:
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00004465 cmdputs(utoa(n->nfile.fd));
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004466 cmdputs(p);
4467 if (n->type == NTOFD || n->type == NFROMFD) {
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00004468 cmdputs(utoa(n->ndup.dupfd));
4469 break;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004470 }
4471 n = n->nfile.fname;
4472 goto donode;
4473 }
4474}
4475
4476static char *
4477commandtext(union node *n)
4478{
4479 char *name;
4480
4481 STARTSTACKSTR(cmdnextc);
4482 cmdtxt(n);
4483 name = stackblock();
4484 TRACE(("commandtext: name %p, end %p\n\t\"%s\"\n",
4485 name, cmdnextc, cmdnextc));
4486 return ckstrdup(name);
4487}
4488#endif /* JOBS */
4489
4490/*
4491 * Fork off a subshell. If we are doing job control, give the subshell its
4492 * own process group. Jp is a job structure that the job is to be added to.
4493 * N is the command that will be evaluated by the child. Both jp and n may
4494 * be NULL. The mode parameter can be one of the following:
4495 * FORK_FG - Fork off a foreground process.
4496 * FORK_BG - Fork off a background process.
4497 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
4498 * process group even if job control is on.
4499 *
4500 * When job control is turned off, background processes have their standard
4501 * input redirected to /dev/null (except for the second and later processes
4502 * in a pipeline).
4503 *
4504 * Called with interrupts off.
4505 */
4506/*
4507 * Clear traps on a fork.
4508 */
4509static void
4510clear_traps(void)
4511{
4512 char **tp;
4513
4514 for (tp = trap; tp < &trap[NSIG]; tp++) {
Denis Vlasenko991a1da2008-02-10 19:02:53 +00004515 if (*tp && **tp) { /* trap not NULL or "" (SIG_IGN) */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004516 INT_OFF;
Denys Vlasenkoe305c282009-09-25 02:12:27 +02004517 if (trap_ptr == trap)
4518 free(*tp);
4519 /* else: it "belongs" to trap_ptr vector, don't free */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004520 *tp = NULL;
Denys Vlasenko0800e3a2009-09-24 03:09:26 +02004521 if ((tp - trap) != 0)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004522 setsignal(tp - trap);
4523 INT_ON;
4524 }
4525 }
4526}
Denis Vlasenkobdc406d2007-07-15 01:13:25 +00004527
4528/* Lives far away from here, needed for forkchild */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004529static void closescript(void);
Denis Vlasenko41770222007-10-07 18:02:52 +00004530
Denis Vlasenkobdc406d2007-07-15 01:13:25 +00004531/* Called after fork(), in child */
Denys Vlasenko21d87d42009-09-25 00:06:51 +02004532static NOINLINE void
Denys Vlasenkoe56f22a2009-07-24 00:16:59 +02004533forkchild(struct job *jp, union node *n, int mode)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004534{
4535 int oldlvl;
4536
4537 TRACE(("Child shell %d\n", getpid()));
4538 oldlvl = shlvl;
4539 shlvl++;
4540
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004541 /* man bash: "Non-builtin commands run by bash have signal handlers
4542 * set to the values inherited by the shell from its parent".
4543 * Do we do it correctly? */
4544
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004545 closescript();
Denys Vlasenko844f9902009-09-23 03:25:52 +02004546
4547 if (mode == FORK_NOJOB /* is it `xxx` ? */
4548 && n && n->type == NCMD /* is it single cmd? */
4549 /* && n->ncmd.args->type == NARG - always true? */
Denys Vlasenko74269202010-02-21 01:26:42 +01004550 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "trap") == 0
Denys Vlasenko844f9902009-09-23 03:25:52 +02004551 && n->ncmd.args->narg.next == NULL /* "trap" with no arguments */
4552 /* && n->ncmd.args->narg.backquote == NULL - do we need to check this? */
4553 ) {
4554 TRACE(("Trap hack\n"));
4555 /* Awful hack for `trap` or $(trap).
4556 *
4557 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
4558 * contains an example where "trap" is executed in a subshell:
4559 *
4560 * save_traps=$(trap)
4561 * ...
4562 * eval "$save_traps"
4563 *
4564 * Standard does not say that "trap" in subshell shall print
4565 * parent shell's traps. It only says that its output
4566 * must have suitable form, but then, in the above example
4567 * (which is not supposed to be normative), it implies that.
4568 *
4569 * bash (and probably other shell) does implement it
4570 * (traps are reset to defaults, but "trap" still shows them),
4571 * but as a result, "trap" logic is hopelessly messed up:
4572 *
4573 * # trap
4574 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
4575 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
4576 * # true | trap <--- trap is in subshell - no output (ditto)
4577 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
4578 * trap -- 'echo Ho' SIGWINCH
4579 * # echo `(trap)` <--- in subshell in subshell - output
4580 * trap -- 'echo Ho' SIGWINCH
4581 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
4582 * trap -- 'echo Ho' SIGWINCH
4583 *
4584 * The rules when to forget and when to not forget traps
4585 * get really complex and nonsensical.
4586 *
4587 * Our solution: ONLY bare $(trap) or `trap` is special.
4588 */
Denys Vlasenko8f88d852009-09-25 12:12:53 +02004589 /* Save trap handler strings for trap builtin to print */
Denys Vlasenko21d87d42009-09-25 00:06:51 +02004590 trap_ptr = memcpy(xmalloc(sizeof(trap)), trap, sizeof(trap));
Denys Vlasenko8f88d852009-09-25 12:12:53 +02004591 /* Fall through into clearing traps */
Denys Vlasenko844f9902009-09-23 03:25:52 +02004592 }
Denys Vlasenkoe305c282009-09-25 02:12:27 +02004593 clear_traps();
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004594#if JOBS
4595 /* do job control only in root shell */
Denis Vlasenkob07a4962008-06-22 13:16:23 +00004596 doing_jobctl = 0;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004597 if (mode != FORK_NOJOB && jp->jobctl && !oldlvl) {
4598 pid_t pgrp;
4599
4600 if (jp->nprocs == 0)
4601 pgrp = getpid();
4602 else
Denys Vlasenko285ad152009-12-04 23:02:27 +01004603 pgrp = jp->ps[0].ps_pid;
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004604 /* this can fail because we are doing it in the parent also */
4605 setpgid(0, pgrp);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004606 if (mode == FORK_FG)
4607 xtcsetpgrp(ttyfd, pgrp);
4608 setsignal(SIGTSTP);
4609 setsignal(SIGTTOU);
4610 } else
4611#endif
4612 if (mode == FORK_BG) {
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004613 /* man bash: "When job control is not in effect,
4614 * asynchronous commands ignore SIGINT and SIGQUIT" */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004615 ignoresig(SIGINT);
4616 ignoresig(SIGQUIT);
4617 if (jp->nprocs == 0) {
4618 close(0);
4619 if (open(bb_dev_null, O_RDONLY) != 0)
Denis Vlasenko9604e1b2009-03-03 18:47:56 +00004620 ash_msg_and_raise_error("can't open '%s'", bb_dev_null);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004621 }
4622 }
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004623 if (!oldlvl) {
4624 if (iflag) { /* why if iflag only? */
4625 setsignal(SIGINT);
4626 setsignal(SIGTERM);
4627 }
4628 /* man bash:
4629 * "In all cases, bash ignores SIGQUIT. Non-builtin
4630 * commands run by bash have signal handlers
4631 * set to the values inherited by the shell
4632 * from its parent".
4633 * Take care of the second rule: */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004634 setsignal(SIGQUIT);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004635 }
Denys Vlasenkoe56f22a2009-07-24 00:16:59 +02004636#if JOBS
Denys Vlasenko844f9902009-09-23 03:25:52 +02004637 if (n && n->type == NCMD
Denys Vlasenko74269202010-02-21 01:26:42 +01004638 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "jobs") == 0
Denys Vlasenko844f9902009-09-23 03:25:52 +02004639 ) {
Denys Vlasenkoe56f22a2009-07-24 00:16:59 +02004640 TRACE(("Job hack\n"));
Denys Vlasenko844f9902009-09-23 03:25:52 +02004641 /* "jobs": we do not want to clear job list for it,
4642 * instead we remove only _its_ own_ job from job list.
4643 * This makes "jobs .... | cat" more useful.
4644 */
Denys Vlasenkoe56f22a2009-07-24 00:16:59 +02004645 freejob(curjob);
4646 return;
4647 }
4648#endif
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004649 for (jp = curjob; jp; jp = jp->prev_job)
4650 freejob(jp);
4651 jobless = 0;
4652}
4653
Denis Vlasenkobdc406d2007-07-15 01:13:25 +00004654/* Called after fork(), in parent */
Denis Vlasenko85c24712008-03-17 09:04:04 +00004655#if !JOBS
4656#define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
4657#endif
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004658static void
4659forkparent(struct job *jp, union node *n, int mode, pid_t pid)
4660{
4661 TRACE(("In parent shell: child = %d\n", pid));
4662 if (!jp) {
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00004663 while (jobless && dowait(DOWAIT_NONBLOCK, NULL) > 0)
4664 continue;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004665 jobless++;
4666 return;
4667 }
4668#if JOBS
4669 if (mode != FORK_NOJOB && jp->jobctl) {
4670 int pgrp;
4671
4672 if (jp->nprocs == 0)
4673 pgrp = pid;
4674 else
Denys Vlasenko285ad152009-12-04 23:02:27 +01004675 pgrp = jp->ps[0].ps_pid;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004676 /* This can fail because we are doing it in the child also */
4677 setpgid(pid, pgrp);
4678 }
4679#endif
4680 if (mode == FORK_BG) {
4681 backgndpid = pid; /* set $! */
4682 set_curjob(jp, CUR_RUNNING);
4683 }
4684 if (jp) {
4685 struct procstat *ps = &jp->ps[jp->nprocs++];
Denys Vlasenko285ad152009-12-04 23:02:27 +01004686 ps->ps_pid = pid;
4687 ps->ps_status = -1;
4688 ps->ps_cmd = nullstr;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004689#if JOBS
Denis Vlasenkob07a4962008-06-22 13:16:23 +00004690 if (doing_jobctl && n)
Denys Vlasenko285ad152009-12-04 23:02:27 +01004691 ps->ps_cmd = commandtext(n);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004692#endif
4693 }
4694}
4695
4696static int
4697forkshell(struct job *jp, union node *n, int mode)
4698{
4699 int pid;
4700
4701 TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
4702 pid = fork();
4703 if (pid < 0) {
4704 TRACE(("Fork failed, errno=%d", errno));
4705 if (jp)
4706 freejob(jp);
Denis Vlasenkofa0b56d2008-07-01 16:09:07 +00004707 ash_msg_and_raise_error("can't fork");
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004708 }
Denys Vlasenko76ace252009-10-12 15:25:01 +02004709 if (pid == 0) {
4710 CLEAR_RANDOM_T(&random_gen); /* or else $RANDOM repeats in child */
Denys Vlasenkoe56f22a2009-07-24 00:16:59 +02004711 forkchild(jp, n, mode);
Denys Vlasenko76ace252009-10-12 15:25:01 +02004712 } else {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004713 forkparent(jp, n, mode, pid);
Denys Vlasenko76ace252009-10-12 15:25:01 +02004714 }
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004715 return pid;
4716}
4717
4718/*
4719 * Wait for job to finish.
4720 *
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004721 * Under job control we have the problem that while a child process
4722 * is running interrupts generated by the user are sent to the child
4723 * but not to the shell. This means that an infinite loop started by
4724 * an interactive user may be hard to kill. With job control turned off,
4725 * an interactive user may place an interactive program inside a loop.
4726 * If the interactive program catches interrupts, the user doesn't want
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004727 * these interrupts to also abort the loop. The approach we take here
4728 * is to have the shell ignore interrupt signals while waiting for a
4729 * foreground process to terminate, and then send itself an interrupt
4730 * signal if the child process was terminated by an interrupt signal.
4731 * Unfortunately, some programs want to do a bit of cleanup and then
4732 * exit on interrupt; unless these processes terminate themselves by
4733 * sending a signal to themselves (instead of calling exit) they will
4734 * confuse this approach.
4735 *
4736 * Called with interrupts off.
4737 */
4738static int
4739waitforjob(struct job *jp)
4740{
4741 int st;
4742
4743 TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004744
4745 INT_OFF;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004746 while (jp->state == JOBRUNNING) {
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004747 /* In non-interactive shells, we _can_ get
4748 * a keyboard signal here and be EINTRed,
4749 * but we just loop back, waiting for command to complete.
4750 *
4751 * man bash:
4752 * "If bash is waiting for a command to complete and receives
4753 * a signal for which a trap has been set, the trap
4754 * will not be executed until the command completes."
4755 *
4756 * Reality is that even if trap is not set, bash
4757 * will not act on the signal until command completes.
4758 * Try this. sleep5intoff.c:
4759 * #include <signal.h>
4760 * #include <unistd.h>
4761 * int main() {
4762 * sigset_t set;
4763 * sigemptyset(&set);
4764 * sigaddset(&set, SIGINT);
4765 * sigaddset(&set, SIGQUIT);
4766 * sigprocmask(SIG_BLOCK, &set, NULL);
4767 * sleep(5);
4768 * return 0;
4769 * }
4770 * $ bash -c './sleep5intoff; echo hi'
4771 * ^C^C^C^C <--- pressing ^C once a second
4772 * $ _
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004773 * $ bash -c './sleep5intoff; echo hi'
4774 * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
4775 * $ _
4776 */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004777 dowait(DOWAIT_BLOCK, jp);
4778 }
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004779 INT_ON;
4780
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004781 st = getstatus(jp);
4782#if JOBS
4783 if (jp->jobctl) {
4784 xtcsetpgrp(ttyfd, rootpid);
4785 /*
4786 * This is truly gross.
4787 * If we're doing job control, then we did a TIOCSPGRP which
4788 * caused us (the shell) to no longer be in the controlling
4789 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
4790 * intuit from the subprocess exit status whether a SIGINT
4791 * occurred, and if so interrupt ourselves. Yuck. - mycroft
4792 */
Denis Vlasenko991a1da2008-02-10 19:02:53 +00004793 if (jp->sigint) /* TODO: do the same with all signals */
4794 raise(SIGINT); /* ... by raise(jp->sig) instead? */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004795 }
4796 if (jp->state == JOBDONE)
4797#endif
4798 freejob(jp);
4799 return st;
4800}
4801
4802/*
4803 * return 1 if there are stopped jobs, otherwise 0
4804 */
4805static int
4806stoppedjobs(void)
4807{
4808 struct job *jp;
4809 int retval;
4810
4811 retval = 0;
4812 if (job_warning)
4813 goto out;
4814 jp = curjob;
4815 if (jp && jp->state == JOBSTOPPED) {
4816 out2str("You have stopped jobs.\n");
4817 job_warning = 2;
4818 retval++;
4819 }
4820 out:
4821 return retval;
4822}
4823
4824
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004825/* ============ redir.c
4826 *
4827 * Code for dealing with input/output redirection.
4828 */
4829
4830#define EMPTY -2 /* marks an unused slot in redirtab */
Denis Vlasenko7d75a962007-11-22 08:16:57 +00004831#define CLOSED -3 /* marks a slot of previously-closed fd */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004832
4833/*
4834 * Open a file in noclobber mode.
4835 * The code was copied from bash.
4836 */
4837static int
4838noclobberopen(const char *fname)
4839{
4840 int r, fd;
4841 struct stat finfo, finfo2;
4842
4843 /*
4844 * If the file exists and is a regular file, return an error
4845 * immediately.
4846 */
4847 r = stat(fname, &finfo);
4848 if (r == 0 && S_ISREG(finfo.st_mode)) {
4849 errno = EEXIST;
4850 return -1;
4851 }
4852
4853 /*
4854 * If the file was not present (r != 0), make sure we open it
4855 * exclusively so that if it is created before we open it, our open
4856 * will fail. Make sure that we do not truncate an existing file.
4857 * Note that we don't turn on O_EXCL unless the stat failed -- if the
4858 * file was not a regular file, we leave O_EXCL off.
4859 */
4860 if (r != 0)
4861 return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
4862 fd = open(fname, O_WRONLY|O_CREAT, 0666);
4863
4864 /* If the open failed, return the file descriptor right away. */
4865 if (fd < 0)
4866 return fd;
4867
4868 /*
4869 * OK, the open succeeded, but the file may have been changed from a
4870 * non-regular file to a regular file between the stat and the open.
4871 * We are assuming that the O_EXCL open handles the case where FILENAME
4872 * did not exist and is symlinked to an existing file between the stat
4873 * and open.
4874 */
4875
4876 /*
4877 * If we can open it and fstat the file descriptor, and neither check
4878 * revealed that it was a regular file, and the file has not been
4879 * replaced, return the file descriptor.
4880 */
4881 if (fstat(fd, &finfo2) == 0 && !S_ISREG(finfo2.st_mode)
4882 && finfo.st_dev == finfo2.st_dev && finfo.st_ino == finfo2.st_ino)
4883 return fd;
4884
4885 /* The file has been replaced. badness. */
4886 close(fd);
4887 errno = EEXIST;
4888 return -1;
4889}
4890
4891/*
4892 * Handle here documents. Normally we fork off a process to write the
4893 * data to a pipe. If the document is short, we can stuff the data in
4894 * the pipe without forking.
4895 */
4896/* openhere needs this forward reference */
4897static void expandhere(union node *arg, int fd);
4898static int
4899openhere(union node *redir)
4900{
4901 int pip[2];
4902 size_t len = 0;
4903
4904 if (pipe(pip) < 0)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00004905 ash_msg_and_raise_error("pipe call failed");
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004906 if (redir->type == NHERE) {
4907 len = strlen(redir->nhere.doc->narg.text);
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00004908 if (len <= PIPE_BUF) {
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004909 full_write(pip[1], redir->nhere.doc->narg.text, len);
4910 goto out;
4911 }
4912 }
4913 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
Denis Vlasenko0b769642008-07-24 07:54:57 +00004914 /* child */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004915 close(pip[0]);
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004916 ignoresig(SIGINT); //signal(SIGINT, SIG_IGN);
4917 ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
4918 ignoresig(SIGHUP); //signal(SIGHUP, SIG_IGN);
4919 ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004920 signal(SIGPIPE, SIG_DFL);
4921 if (redir->type == NHERE)
4922 full_write(pip[1], redir->nhere.doc->narg.text, len);
Denis Vlasenko0b769642008-07-24 07:54:57 +00004923 else /* NXHERE */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004924 expandhere(redir->nhere.doc, pip[1]);
Bernhard Reutner-Fischer636a1f82008-05-19 09:29:47 +00004925 _exit(EXIT_SUCCESS);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004926 }
4927 out:
4928 close(pip[1]);
4929 return pip[0];
4930}
4931
4932static int
4933openredirect(union node *redir)
4934{
4935 char *fname;
4936 int f;
4937
4938 switch (redir->nfile.type) {
4939 case NFROM:
4940 fname = redir->nfile.expfname;
4941 f = open(fname, O_RDONLY);
4942 if (f < 0)
4943 goto eopen;
4944 break;
4945 case NFROMTO:
4946 fname = redir->nfile.expfname;
4947 f = open(fname, O_RDWR|O_CREAT|O_TRUNC, 0666);
4948 if (f < 0)
4949 goto ecreate;
4950 break;
4951 case NTO:
Denis Vlasenko559691a2008-10-05 18:39:31 +00004952#if ENABLE_ASH_BASH_COMPAT
4953 case NTO2:
4954#endif
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004955 /* Take care of noclobber mode. */
4956 if (Cflag) {
4957 fname = redir->nfile.expfname;
4958 f = noclobberopen(fname);
4959 if (f < 0)
4960 goto ecreate;
4961 break;
4962 }
4963 /* FALLTHROUGH */
4964 case NCLOBBER:
4965 fname = redir->nfile.expfname;
4966 f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
4967 if (f < 0)
4968 goto ecreate;
4969 break;
4970 case NAPPEND:
4971 fname = redir->nfile.expfname;
4972 f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
4973 if (f < 0)
4974 goto ecreate;
4975 break;
4976 default:
4977#if DEBUG
4978 abort();
4979#endif
4980 /* Fall through to eliminate warning. */
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00004981/* Our single caller does this itself */
Denis Vlasenko0b769642008-07-24 07:54:57 +00004982// case NTOFD:
4983// case NFROMFD:
4984// f = -1;
4985// break;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004986 case NHERE:
4987 case NXHERE:
4988 f = openhere(redir);
4989 break;
4990 }
4991
4992 return f;
4993 ecreate:
Bernhard Reutner-Fischera53de7f2008-07-21 13:46:54 +00004994 ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004995 eopen:
Bernhard Reutner-Fischera53de7f2008-07-21 13:46:54 +00004996 ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004997}
4998
4999/*
5000 * Copy a file descriptor to be >= to. Returns -1
5001 * if the source file descriptor is closed, EMPTY if there are no unused
5002 * file descriptors left.
5003 */
Denis Vlasenko5a867312008-07-24 19:46:38 +00005004/* 0x800..00: bit to set in "to" to request dup2 instead of fcntl(F_DUPFD).
5005 * old code was doing close(to) prior to copyfd() to achieve the same */
Denis Vlasenko22f74142008-07-24 22:34:43 +00005006enum {
5007 COPYFD_EXACT = (int)~(INT_MAX),
5008 COPYFD_RESTORE = (int)((unsigned)COPYFD_EXACT >> 1),
5009};
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005010static int
5011copyfd(int from, int to)
5012{
5013 int newfd;
5014
Denis Vlasenko5a867312008-07-24 19:46:38 +00005015 if (to & COPYFD_EXACT) {
5016 to &= ~COPYFD_EXACT;
5017 /*if (from != to)*/
5018 newfd = dup2(from, to);
5019 } else {
5020 newfd = fcntl(from, F_DUPFD, to);
5021 }
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005022 if (newfd < 0) {
5023 if (errno == EMFILE)
5024 return EMPTY;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005025 /* Happens when source fd is not open: try "echo >&99" */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005026 ash_msg_and_raise_error("%d: %m", from);
5027 }
5028 return newfd;
5029}
5030
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005031/* Struct def and variable are moved down to the first usage site */
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005032struct two_fd_t {
5033 int orig, copy;
5034};
Denis Vlasenko0b769642008-07-24 07:54:57 +00005035struct redirtab {
5036 struct redirtab *next;
Denis Vlasenko0b769642008-07-24 07:54:57 +00005037 int nullredirs;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005038 int pair_count;
Denys Vlasenko606291b2009-09-23 23:15:43 +02005039 struct two_fd_t two_fd[];
Denis Vlasenko0b769642008-07-24 07:54:57 +00005040};
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005041#define redirlist (G_var.redirlist)
Denis Vlasenko0b769642008-07-24 07:54:57 +00005042
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005043static int need_to_remember(struct redirtab *rp, int fd)
5044{
5045 int i;
5046
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005047 if (!rp) /* remembering was not requested */
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005048 return 0;
5049
5050 for (i = 0; i < rp->pair_count; i++) {
5051 if (rp->two_fd[i].orig == fd) {
5052 /* already remembered */
5053 return 0;
5054 }
5055 }
5056 return 1;
5057}
5058
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005059/* "hidden" fd is a fd used to read scripts, or a copy of such */
5060static int is_hidden_fd(struct redirtab *rp, int fd)
5061{
5062 int i;
Denis Vlasenko34c73c42008-08-16 11:48:02 +00005063 struct parsefile *pf;
5064
5065 if (fd == -1)
5066 return 0;
Denys Vlasenko08d8b3c2010-06-03 04:28:28 +02005067 /* Check open scripts' fds */
Denis Vlasenko34c73c42008-08-16 11:48:02 +00005068 pf = g_parsefile;
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005069 while (pf) {
Denys Vlasenko79b3d422010-06-03 04:29:08 +02005070 /* We skip pf_fd == 0 case because of the following case:
Denys Vlasenko08d8b3c2010-06-03 04:28:28 +02005071 * $ ash # running ash interactively
5072 * $ . ./script.sh
5073 * and in script.sh: "exec 9>&0".
Denys Vlasenko79b3d422010-06-03 04:29:08 +02005074 * Even though top-level pf_fd _is_ 0,
Denys Vlasenko08d8b3c2010-06-03 04:28:28 +02005075 * it's still ok to use it: "read" builtin uses it,
5076 * why should we cripple "exec" builtin?
5077 */
Denys Vlasenko79b3d422010-06-03 04:29:08 +02005078 if (pf->pf_fd > 0 && fd == pf->pf_fd) {
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005079 return 1;
5080 }
5081 pf = pf->prev;
5082 }
Denys Vlasenko08d8b3c2010-06-03 04:28:28 +02005083
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005084 if (!rp)
5085 return 0;
Denys Vlasenko08d8b3c2010-06-03 04:28:28 +02005086 /* Check saved fds of redirects */
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005087 fd |= COPYFD_RESTORE;
5088 for (i = 0; i < rp->pair_count; i++) {
5089 if (rp->two_fd[i].copy == fd) {
5090 return 1;
5091 }
5092 }
5093 return 0;
5094}
5095
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005096/*
5097 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
5098 * old file descriptors are stashed away so that the redirection can be
Denys Vlasenko08d8b3c2010-06-03 04:28:28 +02005099 * undone by calling popredir.
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005100 */
5101/* flags passed to redirect */
5102#define REDIR_PUSH 01 /* save previous values of file descriptors */
5103#define REDIR_SAVEFD2 03 /* set preverrout */
5104static void
5105redirect(union node *redir, int flags)
5106{
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005107 struct redirtab *sv;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005108 int sv_pos;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005109 int i;
5110 int fd;
5111 int newfd;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005112 int copied_fd2 = -1;
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005113
Denis Vlasenko01631112007-12-16 17:20:38 +00005114 g_nullredirs++;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005115 if (!redir) {
5116 return;
5117 }
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005118
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005119 sv = NULL;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005120 sv_pos = 0;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005121 INT_OFF;
5122 if (flags & REDIR_PUSH) {
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005123 union node *tmp = redir;
5124 do {
5125 sv_pos++;
Denis Vlasenko559691a2008-10-05 18:39:31 +00005126#if ENABLE_ASH_BASH_COMPAT
Chris Metcalfc3c1fb62010-01-08 13:18:06 +01005127 if (tmp->nfile.type == NTO2)
Denis Vlasenko559691a2008-10-05 18:39:31 +00005128 sv_pos++;
5129#endif
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005130 tmp = tmp->nfile.next;
5131 } while (tmp);
5132 sv = ckmalloc(sizeof(*sv) + sv_pos * sizeof(sv->two_fd[0]));
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005133 sv->next = redirlist;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005134 sv->pair_count = sv_pos;
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005135 redirlist = sv;
Denis Vlasenko01631112007-12-16 17:20:38 +00005136 sv->nullredirs = g_nullredirs - 1;
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005137 g_nullredirs = 0;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005138 while (sv_pos > 0) {
5139 sv_pos--;
5140 sv->two_fd[sv_pos].orig = sv->two_fd[sv_pos].copy = EMPTY;
5141 }
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005142 }
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005143
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005144 do {
Denys Vlasenko08d8b3c2010-06-03 04:28:28 +02005145 int right_fd = -1;
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00005146 fd = redir->nfile.fd;
Denis Vlasenko0b769642008-07-24 07:54:57 +00005147 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
Denys Vlasenko08d8b3c2010-06-03 04:28:28 +02005148 right_fd = redir->ndup.dupfd;
5149 //bb_error_msg("doing %d > %d", fd, right_fd);
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005150 /* redirect from/to same file descriptor? */
5151 if (right_fd == fd)
5152 continue;
Denys Vlasenko08d8b3c2010-06-03 04:28:28 +02005153 /* "echo >&10" and 10 is a fd opened to a sh script? */
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005154 if (is_hidden_fd(sv, right_fd)) {
5155 errno = EBADF; /* as if it is closed */
5156 ash_msg_and_raise_error("%d: %m", right_fd);
5157 }
Denis Vlasenko0b769642008-07-24 07:54:57 +00005158 newfd = -1;
5159 } else {
5160 newfd = openredirect(redir); /* always >= 0 */
5161 if (fd == newfd) {
5162 /* Descriptor wasn't open before redirect.
5163 * Mark it for close in the future */
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005164 if (need_to_remember(sv, fd)) {
Denis Vlasenko5a867312008-07-24 19:46:38 +00005165 goto remember_to_close;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005166 }
Denis Vlasenko0b769642008-07-24 07:54:57 +00005167 continue;
5168 }
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005169 }
Denis Vlasenko559691a2008-10-05 18:39:31 +00005170#if ENABLE_ASH_BASH_COMPAT
5171 redirect_more:
5172#endif
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005173 if (need_to_remember(sv, fd)) {
Denis Vlasenko0b769642008-07-24 07:54:57 +00005174 /* Copy old descriptor */
Denys Vlasenko08d8b3c2010-06-03 04:28:28 +02005175 /* Careful to not accidentally "save"
5176 * to the same fd as right side fd in N>&M */
5177 int minfd = right_fd < 10 ? 10 : right_fd + 1;
5178 i = fcntl(fd, F_DUPFD, minfd);
Denis Vlasenko5a867312008-07-24 19:46:38 +00005179/* You'd expect copy to be CLOEXECed. Currently these extra "saved" fds
5180 * are closed in popredir() in the child, preventing them from leaking
5181 * into child. (popredir() also cleans up the mess in case of failures)
5182 */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005183 if (i == -1) {
5184 i = errno;
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005185 if (i != EBADF) {
5186 /* Strange error (e.g. "too many files" EMFILE?) */
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005187 if (newfd >= 0)
5188 close(newfd);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005189 errno = i;
5190 ash_msg_and_raise_error("%d: %m", fd);
5191 /* NOTREACHED */
5192 }
Denis Vlasenko5a867312008-07-24 19:46:38 +00005193 /* EBADF: it is not open - good, remember to close it */
5194 remember_to_close:
5195 i = CLOSED;
Denis Vlasenko22f74142008-07-24 22:34:43 +00005196 } else { /* fd is open, save its copy */
5197 /* "exec fd>&-" should not close fds
5198 * which point to script file(s).
5199 * Force them to be restored afterwards */
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005200 if (is_hidden_fd(sv, fd))
5201 i |= COPYFD_RESTORE;
Denis Vlasenko22f74142008-07-24 22:34:43 +00005202 }
Denis Vlasenko5a867312008-07-24 19:46:38 +00005203 if (fd == 2)
5204 copied_fd2 = i;
5205 sv->two_fd[sv_pos].orig = fd;
5206 sv->two_fd[sv_pos].copy = i;
5207 sv_pos++;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005208 }
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005209 if (newfd < 0) {
5210 /* NTOFD/NFROMFD: copy redir->ndup.dupfd to fd */
Denis Vlasenko22f74142008-07-24 22:34:43 +00005211 if (redir->ndup.dupfd < 0) { /* "fd>&-" */
Denis Vlasenkob9e70dd2009-03-20 01:24:08 +00005212 /* Don't want to trigger debugging */
5213 if (fd != -1)
5214 close(fd);
Denis Vlasenko5a867312008-07-24 19:46:38 +00005215 } else {
5216 copyfd(redir->ndup.dupfd, fd | COPYFD_EXACT);
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005217 }
Denis Vlasenko5a867312008-07-24 19:46:38 +00005218 } else if (fd != newfd) { /* move newfd to fd */
5219 copyfd(newfd, fd | COPYFD_EXACT);
Denis Vlasenko559691a2008-10-05 18:39:31 +00005220#if ENABLE_ASH_BASH_COMPAT
5221 if (!(redir->nfile.type == NTO2 && fd == 2))
5222#endif
5223 close(newfd);
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005224 }
Denis Vlasenko559691a2008-10-05 18:39:31 +00005225#if ENABLE_ASH_BASH_COMPAT
5226 if (redir->nfile.type == NTO2 && fd == 1) {
5227 /* We already redirected it to fd 1, now copy it to 2 */
5228 newfd = 1;
5229 fd = 2;
5230 goto redirect_more;
5231 }
5232#endif
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00005233 } while ((redir = redir->nfile.next) != NULL);
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005234
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005235 INT_ON;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005236 if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
5237 preverrout_fd = copied_fd2;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005238}
5239
5240/*
5241 * Undo the effects of the last redirection.
5242 */
5243static void
Denis Vlasenko34c73c42008-08-16 11:48:02 +00005244popredir(int drop, int restore)
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005245{
5246 struct redirtab *rp;
5247 int i;
5248
Denis Vlasenko01631112007-12-16 17:20:38 +00005249 if (--g_nullredirs >= 0)
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005250 return;
5251 INT_OFF;
5252 rp = redirlist;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005253 for (i = 0; i < rp->pair_count; i++) {
5254 int fd = rp->two_fd[i].orig;
Denis Vlasenko22f74142008-07-24 22:34:43 +00005255 int copy = rp->two_fd[i].copy;
5256 if (copy == CLOSED) {
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005257 if (!drop)
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005258 close(fd);
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005259 continue;
5260 }
Denis Vlasenko22f74142008-07-24 22:34:43 +00005261 if (copy != EMPTY) {
Denis Vlasenko34c73c42008-08-16 11:48:02 +00005262 if (!drop || (restore && (copy & COPYFD_RESTORE))) {
Denis Vlasenko22f74142008-07-24 22:34:43 +00005263 copy &= ~COPYFD_RESTORE;
Denis Vlasenko5a867312008-07-24 19:46:38 +00005264 /*close(fd);*/
Denis Vlasenko22f74142008-07-24 22:34:43 +00005265 copyfd(copy, fd | COPYFD_EXACT);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005266 }
Denis Vlasenkob9e70dd2009-03-20 01:24:08 +00005267 close(copy & ~COPYFD_RESTORE);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005268 }
5269 }
5270 redirlist = rp->next;
Denis Vlasenko01631112007-12-16 17:20:38 +00005271 g_nullredirs = rp->nullredirs;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005272 free(rp);
5273 INT_ON;
5274}
5275
5276/*
5277 * Undo all redirections. Called on error or interrupt.
5278 */
5279
5280/*
5281 * Discard all saved file descriptors.
5282 */
5283static void
5284clearredir(int drop)
5285{
5286 for (;;) {
Denis Vlasenko01631112007-12-16 17:20:38 +00005287 g_nullredirs = 0;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005288 if (!redirlist)
5289 break;
Denis Vlasenko34c73c42008-08-16 11:48:02 +00005290 popredir(drop, /*restore:*/ 0);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005291 }
5292}
5293
5294static int
5295redirectsafe(union node *redir, int flags)
5296{
5297 int err;
5298 volatile int saveint;
5299 struct jmploc *volatile savehandler = exception_handler;
5300 struct jmploc jmploc;
5301
5302 SAVE_INT(saveint);
Denis Vlasenko5a867312008-07-24 19:46:38 +00005303 /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
5304 err = setjmp(jmploc.loc); // huh?? was = setjmp(jmploc.loc) * 2;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005305 if (!err) {
5306 exception_handler = &jmploc;
5307 redirect(redir, flags);
5308 }
5309 exception_handler = savehandler;
Denis Vlasenko7f88e342009-03-19 03:36:18 +00005310 if (err && exception_type != EXERROR)
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005311 longjmp(exception_handler->loc, 1);
5312 RESTORE_INT(saveint);
5313 return err;
5314}
5315
5316
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005317/* ============ Routines to expand arguments to commands
5318 *
5319 * We have to deal with backquotes, shell variables, and file metacharacters.
5320 */
5321
Mike Frysinger98c52642009-04-02 10:02:37 +00005322#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00005323static arith_t
5324ash_arith(const char *s)
5325{
5326 arith_eval_hooks_t math_hooks;
5327 arith_t result;
5328 int errcode = 0;
5329
5330 math_hooks.lookupvar = lookupvar;
Denys Vlasenko03dad222010-01-12 23:29:57 +01005331 math_hooks.setvar = setvar2;
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00005332 math_hooks.endofname = endofname;
5333
5334 INT_OFF;
5335 result = arith(s, &errcode, &math_hooks);
5336 if (errcode < 0) {
5337 if (errcode == -3)
5338 ash_msg_and_raise_error("exponent less than 0");
5339 if (errcode == -2)
5340 ash_msg_and_raise_error("divide by zero");
5341 if (errcode == -5)
5342 ash_msg_and_raise_error("expression recursion loop detected");
5343 raise_error_syntax(s);
5344 }
5345 INT_ON;
5346
5347 return result;
5348}
Denis Vlasenko448d30e2008-06-27 00:24:11 +00005349#endif
5350
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005351/*
5352 * expandarg flags
5353 */
5354#define EXP_FULL 0x1 /* perform word splitting & file globbing */
5355#define EXP_TILDE 0x2 /* do normal tilde expansion */
5356#define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
5357#define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
5358#define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
5359#define EXP_RECORD 0x20 /* need to record arguments for ifs breakup */
5360#define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
5361#define EXP_WORD 0x80 /* expand word in parameter expansion */
5362#define EXP_QWORD 0x100 /* expand word in quoted parameter expansion */
5363/*
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005364 * rmescape() flags
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005365 */
5366#define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
5367#define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
5368#define RMESCAPE_QUOTED 0x4 /* Remove CTLESC unless in quotes */
5369#define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
5370#define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
5371
5372/*
5373 * Structure specifying which parts of the string should be searched
5374 * for IFS characters.
5375 */
5376struct ifsregion {
5377 struct ifsregion *next; /* next region in list */
5378 int begoff; /* offset of start of region */
5379 int endoff; /* offset of end of region */
5380 int nulonly; /* search for nul bytes only */
5381};
5382
5383struct arglist {
5384 struct strlist *list;
5385 struct strlist **lastp;
5386};
5387
5388/* output of current string */
5389static char *expdest;
5390/* list of back quote expressions */
5391static struct nodelist *argbackq;
5392/* first struct in list of ifs regions */
5393static struct ifsregion ifsfirst;
5394/* last struct in list */
5395static struct ifsregion *ifslastp;
5396/* holds expanded arg list */
5397static struct arglist exparg;
5398
5399/*
5400 * Our own itoa().
5401 */
5402static int
5403cvtnum(arith_t num)
5404{
5405 int len;
5406
5407 expdest = makestrspace(32, expdest);
Mike Frysinger98c52642009-04-02 10:02:37 +00005408 len = fmtstr(expdest, 32, arith_t_fmt, num);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005409 STADJUST(len, expdest);
5410 return len;
5411}
5412
5413static size_t
5414esclen(const char *start, const char *p)
5415{
5416 size_t esc = 0;
5417
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005418 while (p > start && (unsigned char)*--p == CTLESC) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005419 esc++;
5420 }
5421 return esc;
5422}
5423
5424/*
5425 * Remove any CTLESC characters from a string.
5426 */
5427static char *
Denys Vlasenkob6c84342009-08-29 20:23:20 +02005428rmescapes(char *str, int flag)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005429{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00005430 static const char qchars[] ALIGN1 = { CTLESC, CTLQUOTEMARK, '\0' };
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00005431
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005432 char *p, *q, *r;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005433 unsigned inquotes;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005434 unsigned protect_against_glob;
5435 unsigned globbing;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005436
5437 p = strpbrk(str, qchars);
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005438 if (!p)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005439 return str;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005440
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005441 q = p;
5442 r = str;
5443 if (flag & RMESCAPE_ALLOC) {
5444 size_t len = p - str;
5445 size_t fulllen = len + strlen(p) + 1;
5446
5447 if (flag & RMESCAPE_GROW) {
Colin Watson3963d942010-04-26 14:21:27 +02005448 int strloc = str - (char *)stackblock();
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005449 r = makestrspace(fulllen, expdest);
Colin Watson3963d942010-04-26 14:21:27 +02005450 /* p and str may be invalidated by makestrspace */
5451 str = (char *)stackblock() + strloc;
5452 p = str + len;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005453 } else if (flag & RMESCAPE_HEAP) {
5454 r = ckmalloc(fulllen);
5455 } else {
5456 r = stalloc(fulllen);
5457 }
5458 q = r;
5459 if (len > 0) {
Denis Vlasenko29eb3592008-05-18 14:06:08 +00005460 q = (char *)memcpy(q, str, len) + len;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005461 }
5462 }
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005463
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005464 inquotes = (flag & RMESCAPE_QUOTED) ^ RMESCAPE_QUOTED;
5465 globbing = flag & RMESCAPE_GLOB;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005466 protect_against_glob = globbing;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005467 while (*p) {
Denys Vlasenkocd716832009-11-28 22:14:02 +01005468 if ((unsigned char)*p == CTLQUOTEMARK) {
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005469// TODO: if no RMESCAPE_QUOTED in flags, inquotes never becomes 0
5470// (alternates between RMESCAPE_QUOTED and ~RMESCAPE_QUOTED). Is it ok?
5471// Note: both inquotes and protect_against_glob only affect whether
5472// CTLESC,<ch> gets converted to <ch> or to \<ch>
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005473 inquotes = ~inquotes;
5474 p++;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005475 protect_against_glob = globbing;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005476 continue;
5477 }
5478 if (*p == '\\') {
5479 /* naked back slash */
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005480 protect_against_glob = 0;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005481 goto copy;
5482 }
Denys Vlasenkocd716832009-11-28 22:14:02 +01005483 if ((unsigned char)*p == CTLESC) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005484 p++;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005485 if (protect_against_glob && inquotes && *p != '/') {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005486 *q++ = '\\';
5487 }
5488 }
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005489 protect_against_glob = globbing;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005490 copy:
5491 *q++ = *p++;
5492 }
5493 *q = '\0';
5494 if (flag & RMESCAPE_GROW) {
5495 expdest = r;
5496 STADJUST(q - r + 1, expdest);
5497 }
5498 return r;
5499}
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005500#define pmatch(a, b) !fnmatch((a), (b), 0)
5501
5502/*
5503 * Prepare a pattern for a expmeta (internal glob(3)) call.
5504 *
5505 * Returns an stalloced string.
5506 */
5507static char *
5508preglob(const char *pattern, int quoted, int flag)
5509{
5510 flag |= RMESCAPE_GLOB;
5511 if (quoted) {
5512 flag |= RMESCAPE_QUOTED;
5513 }
Denys Vlasenkob6c84342009-08-29 20:23:20 +02005514 return rmescapes((char *)pattern, flag);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005515}
5516
5517/*
5518 * Put a string on the stack.
5519 */
5520static void
5521memtodest(const char *p, size_t len, int syntax, int quotes)
5522{
5523 char *q = expdest;
5524
Denys Vlasenkob6c84342009-08-29 20:23:20 +02005525 q = makestrspace(quotes ? len * 2 : len, q);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005526
5527 while (len--) {
Denys Vlasenkocd716832009-11-28 22:14:02 +01005528 unsigned char c = *p++;
5529 if (c == '\0')
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005530 continue;
Denys Vlasenkob6c84342009-08-29 20:23:20 +02005531 if (quotes) {
5532 int n = SIT(c, syntax);
5533 if (n == CCTL || n == CBACK)
5534 USTPUTC(CTLESC, q);
5535 }
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005536 USTPUTC(c, q);
5537 }
5538
5539 expdest = q;
5540}
5541
5542static void
5543strtodest(const char *p, int syntax, int quotes)
5544{
5545 memtodest(p, strlen(p), syntax, quotes);
5546}
5547
5548/*
5549 * Record the fact that we have to scan this region of the
5550 * string for IFS characters.
5551 */
5552static void
5553recordregion(int start, int end, int nulonly)
5554{
5555 struct ifsregion *ifsp;
5556
5557 if (ifslastp == NULL) {
5558 ifsp = &ifsfirst;
5559 } else {
5560 INT_OFF;
Denis Vlasenko597906c2008-02-20 16:38:54 +00005561 ifsp = ckzalloc(sizeof(*ifsp));
5562 /*ifsp->next = NULL; - ckzalloc did it */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005563 ifslastp->next = ifsp;
5564 INT_ON;
5565 }
5566 ifslastp = ifsp;
5567 ifslastp->begoff = start;
5568 ifslastp->endoff = end;
5569 ifslastp->nulonly = nulonly;
5570}
5571
5572static void
5573removerecordregions(int endoff)
5574{
5575 if (ifslastp == NULL)
5576 return;
5577
5578 if (ifsfirst.endoff > endoff) {
5579 while (ifsfirst.next != NULL) {
5580 struct ifsregion *ifsp;
5581 INT_OFF;
5582 ifsp = ifsfirst.next->next;
5583 free(ifsfirst.next);
5584 ifsfirst.next = ifsp;
5585 INT_ON;
5586 }
5587 if (ifsfirst.begoff > endoff)
5588 ifslastp = NULL;
5589 else {
5590 ifslastp = &ifsfirst;
5591 ifsfirst.endoff = endoff;
5592 }
5593 return;
5594 }
5595
5596 ifslastp = &ifsfirst;
5597 while (ifslastp->next && ifslastp->next->begoff < endoff)
5598 ifslastp=ifslastp->next;
5599 while (ifslastp->next != NULL) {
5600 struct ifsregion *ifsp;
5601 INT_OFF;
5602 ifsp = ifslastp->next->next;
5603 free(ifslastp->next);
5604 ifslastp->next = ifsp;
5605 INT_ON;
5606 }
5607 if (ifslastp->endoff > endoff)
5608 ifslastp->endoff = endoff;
5609}
5610
5611static char *
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005612exptilde(char *startp, char *p, int flags)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005613{
Denys Vlasenkocd716832009-11-28 22:14:02 +01005614 unsigned char c;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005615 char *name;
5616 struct passwd *pw;
5617 const char *home;
Denys Vlasenko1166d7b2009-09-16 16:20:31 +02005618 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005619 int startloc;
5620
5621 name = p + 1;
5622
5623 while ((c = *++p) != '\0') {
5624 switch (c) {
5625 case CTLESC:
5626 return startp;
5627 case CTLQUOTEMARK:
5628 return startp;
5629 case ':':
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005630 if (flags & EXP_VARTILDE)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005631 goto done;
5632 break;
5633 case '/':
5634 case CTLENDVAR:
5635 goto done;
5636 }
5637 }
5638 done:
5639 *p = '\0';
5640 if (*name == '\0') {
Denys Vlasenkoea8b2522010-06-02 12:57:26 +02005641 home = lookupvar("HOME");
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005642 } else {
5643 pw = getpwnam(name);
5644 if (pw == NULL)
5645 goto lose;
5646 home = pw->pw_dir;
5647 }
5648 if (!home || !*home)
5649 goto lose;
5650 *p = c;
5651 startloc = expdest - (char *)stackblock();
5652 strtodest(home, SQSYNTAX, quotes);
5653 recordregion(startloc, expdest - (char *)stackblock(), 0);
5654 return p;
5655 lose:
5656 *p = c;
5657 return startp;
5658}
5659
5660/*
5661 * Execute a command inside back quotes. If it's a builtin command, we
5662 * want to save its output in a block obtained from malloc. Otherwise
5663 * we fork off a subprocess and get the output of the command via a pipe.
5664 * Should be called with interrupts off.
5665 */
5666struct backcmd { /* result of evalbackcmd */
5667 int fd; /* file descriptor to read from */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005668 int nleft; /* number of chars in buffer */
Denis Vlasenkob07a4962008-06-22 13:16:23 +00005669 char *buf; /* buffer */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005670 struct job *jp; /* job structure for command */
5671};
5672
5673/* These forward decls are needed to use "eval" code for backticks handling: */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00005674static uint8_t back_exitstatus; /* exit status of backquoted command */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005675#define EV_EXIT 01 /* exit after evaluating tree */
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02005676static void evaltree(union node *, int);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005677
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02005678static void FAST_FUNC
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005679evalbackcmd(union node *n, struct backcmd *result)
5680{
5681 int saveherefd;
5682
5683 result->fd = -1;
5684 result->buf = NULL;
5685 result->nleft = 0;
5686 result->jp = NULL;
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00005687 if (n == NULL)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005688 goto out;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005689
5690 saveherefd = herefd;
5691 herefd = -1;
5692
5693 {
5694 int pip[2];
5695 struct job *jp;
5696
5697 if (pipe(pip) < 0)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00005698 ash_msg_and_raise_error("pipe call failed");
Denis Vlasenko68404f12008-03-17 09:00:54 +00005699 jp = makejob(/*n,*/ 1);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005700 if (forkshell(jp, n, FORK_NOJOB) == 0) {
5701 FORCE_INT_ON;
5702 close(pip[0]);
5703 if (pip[1] != 1) {
Denis Vlasenko5a867312008-07-24 19:46:38 +00005704 /*close(1);*/
5705 copyfd(pip[1], 1 | COPYFD_EXACT);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005706 close(pip[1]);
5707 }
5708 eflag = 0;
5709 evaltree(n, EV_EXIT); /* actually evaltreenr... */
5710 /* NOTREACHED */
5711 }
5712 close(pip[1]);
5713 result->fd = pip[0];
5714 result->jp = jp;
5715 }
5716 herefd = saveherefd;
5717 out:
5718 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
5719 result->fd, result->buf, result->nleft, result->jp));
5720}
5721
5722/*
5723 * Expand stuff in backwards quotes.
5724 */
5725static void
5726expbackq(union node *cmd, int quoted, int quotes)
5727{
5728 struct backcmd in;
5729 int i;
5730 char buf[128];
5731 char *p;
5732 char *dest;
5733 int startloc;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00005734 int syntax = quoted ? DQSYNTAX : BASESYNTAX;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005735 struct stackmark smark;
5736
5737 INT_OFF;
5738 setstackmark(&smark);
5739 dest = expdest;
5740 startloc = dest - (char *)stackblock();
5741 grabstackstr(dest);
5742 evalbackcmd(cmd, &in);
5743 popstackmark(&smark);
5744
5745 p = in.buf;
5746 i = in.nleft;
5747 if (i == 0)
5748 goto read;
5749 for (;;) {
5750 memtodest(p, i, syntax, quotes);
5751 read:
5752 if (in.fd < 0)
5753 break;
Denis Vlasenkoe376d452008-02-20 22:23:24 +00005754 i = nonblock_safe_read(in.fd, buf, sizeof(buf));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005755 TRACE(("expbackq: read returns %d\n", i));
5756 if (i <= 0)
5757 break;
5758 p = buf;
5759 }
5760
Denis Vlasenko60818682007-09-28 22:07:23 +00005761 free(in.buf);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005762 if (in.fd >= 0) {
5763 close(in.fd);
5764 back_exitstatus = waitforjob(in.jp);
5765 }
5766 INT_ON;
5767
5768 /* Eat all trailing newlines */
5769 dest = expdest;
5770 for (; dest > (char *)stackblock() && dest[-1] == '\n';)
5771 STUNPUTC(dest);
5772 expdest = dest;
5773
5774 if (quoted == 0)
5775 recordregion(startloc, dest - (char *)stackblock(), 0);
5776 TRACE(("evalbackq: size=%d: \"%.*s\"\n",
5777 (dest - (char *)stackblock()) - startloc,
5778 (dest - (char *)stackblock()) - startloc,
5779 stackblock() + startloc));
5780}
5781
Mike Frysinger98c52642009-04-02 10:02:37 +00005782#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005783/*
5784 * Expand arithmetic expression. Backup to start of expression,
5785 * evaluate, place result in (backed up) result, adjust string position.
5786 */
5787static void
5788expari(int quotes)
5789{
5790 char *p, *start;
5791 int begoff;
5792 int flag;
5793 int len;
5794
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00005795 /* ifsfree(); */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005796
5797 /*
5798 * This routine is slightly over-complicated for
5799 * efficiency. Next we scan backwards looking for the
5800 * start of arithmetic.
5801 */
5802 start = stackblock();
5803 p = expdest - 1;
5804 *p = '\0';
5805 p--;
5806 do {
5807 int esc;
5808
Denys Vlasenkocd716832009-11-28 22:14:02 +01005809 while ((unsigned char)*p != CTLARI) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005810 p--;
5811#if DEBUG
5812 if (p < start) {
5813 ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
5814 }
5815#endif
5816 }
5817
5818 esc = esclen(start, p);
5819 if (!(esc % 2)) {
5820 break;
5821 }
5822
5823 p -= esc + 1;
5824 } while (1);
5825
5826 begoff = p - start;
5827
5828 removerecordregions(begoff);
5829
5830 flag = p[1];
5831
5832 expdest = p;
5833
5834 if (quotes)
Denys Vlasenkob6c84342009-08-29 20:23:20 +02005835 rmescapes(p + 2, 0);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005836
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00005837 len = cvtnum(ash_arith(p + 2));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005838
5839 if (flag != '"')
5840 recordregion(begoff, begoff + len, 0);
5841}
5842#endif
5843
5844/* argstr needs it */
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005845static char *evalvar(char *p, int flags, struct strlist *var_str_list);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005846
5847/*
5848 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
5849 * characters to allow for further processing. Otherwise treat
5850 * $@ like $* since no splitting will be performed.
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00005851 *
5852 * var_str_list (can be NULL) is a list of "VAR=val" strings which take precedence
5853 * over shell varables. Needed for "A=a B=$A; echo $B" case - we use it
5854 * for correct expansion of "B=$A" word.
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005855 */
5856static void
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005857argstr(char *p, int flags, struct strlist *var_str_list)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005858{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00005859 static const char spclchars[] ALIGN1 = {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005860 '=',
5861 ':',
5862 CTLQUOTEMARK,
5863 CTLENDVAR,
5864 CTLESC,
5865 CTLVAR,
5866 CTLBACKQ,
5867 CTLBACKQ | CTLQUOTE,
Mike Frysinger98c52642009-04-02 10:02:37 +00005868#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005869 CTLENDARI,
5870#endif
Denys Vlasenkocd716832009-11-28 22:14:02 +01005871 '\0'
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005872 };
5873 const char *reject = spclchars;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005874 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR); /* do CTLESC */
5875 int breakall = flags & EXP_WORD;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005876 int inquotes;
5877 size_t length;
5878 int startloc;
5879
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005880 if (!(flags & EXP_VARTILDE)) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005881 reject += 2;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005882 } else if (flags & EXP_VARTILDE2) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005883 reject++;
5884 }
5885 inquotes = 0;
5886 length = 0;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005887 if (flags & EXP_TILDE) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005888 char *q;
5889
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005890 flags &= ~EXP_TILDE;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005891 tilde:
5892 q = p;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005893 if (*q == CTLESC && (flags & EXP_QWORD))
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005894 q++;
5895 if (*q == '~')
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005896 p = exptilde(p, q, flags);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005897 }
5898 start:
5899 startloc = expdest - (char *)stackblock();
5900 for (;;) {
Denys Vlasenkocd716832009-11-28 22:14:02 +01005901 unsigned char c;
5902
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005903 length += strcspn(p + length, reject);
Denys Vlasenkocd716832009-11-28 22:14:02 +01005904 c = p[length];
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005905 if (c) {
5906 if (!(c & 0x80)
Mike Frysinger98c52642009-04-02 10:02:37 +00005907#if ENABLE_SH_MATH_SUPPORT
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005908 || c == CTLENDARI
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005909#endif
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005910 ) {
5911 /* c == '=' || c == ':' || c == CTLENDARI */
5912 length++;
5913 }
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005914 }
5915 if (length > 0) {
5916 int newloc;
5917 expdest = stack_nputstr(p, length, expdest);
5918 newloc = expdest - (char *)stackblock();
5919 if (breakall && !inquotes && newloc > startloc) {
5920 recordregion(startloc, newloc, 0);
5921 }
5922 startloc = newloc;
5923 }
5924 p += length + 1;
5925 length = 0;
5926
5927 switch (c) {
5928 case '\0':
5929 goto breakloop;
5930 case '=':
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005931 if (flags & EXP_VARTILDE2) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005932 p--;
5933 continue;
5934 }
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005935 flags |= EXP_VARTILDE2;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005936 reject++;
5937 /* fall through */
5938 case ':':
5939 /*
5940 * sort of a hack - expand tildes in variable
5941 * assignments (after the first '=' and after ':'s).
5942 */
5943 if (*--p == '~') {
5944 goto tilde;
5945 }
5946 continue;
5947 }
5948
5949 switch (c) {
5950 case CTLENDVAR: /* ??? */
5951 goto breakloop;
5952 case CTLQUOTEMARK:
5953 /* "$@" syntax adherence hack */
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005954 if (!inquotes
5955 && memcmp(p, dolatstr, 4) == 0
5956 && ( p[4] == CTLQUOTEMARK
5957 || (p[4] == CTLENDVAR && p[5] == CTLQUOTEMARK)
5958 )
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005959 ) {
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005960 p = evalvar(p + 1, flags, /* var_str_list: */ NULL) + 1;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005961 goto start;
5962 }
5963 inquotes = !inquotes;
5964 addquote:
5965 if (quotes) {
5966 p--;
5967 length++;
5968 startloc++;
5969 }
5970 break;
5971 case CTLESC:
5972 startloc++;
5973 length++;
5974 goto addquote;
5975 case CTLVAR:
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005976 p = evalvar(p, flags, var_str_list);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005977 goto start;
5978 case CTLBACKQ:
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005979 c = '\0';
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005980 case CTLBACKQ|CTLQUOTE:
5981 expbackq(argbackq->n, c, quotes);
5982 argbackq = argbackq->next;
5983 goto start;
Mike Frysinger98c52642009-04-02 10:02:37 +00005984#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005985 case CTLENDARI:
5986 p--;
5987 expari(quotes);
5988 goto start;
5989#endif
5990 }
5991 }
5992 breakloop:
5993 ;
5994}
5995
5996static char *
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00005997scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM, char *str, int quotes,
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005998 int zero)
5999{
Denis Vlasenkoc7131c32008-04-14 01:59:53 +00006000// This commented out code was added by James Simmons <jsimmons@infradead.org>
6001// as part of a larger change when he added support for ${var/a/b}.
6002// However, it broke # and % operators:
6003//
6004//var=ababcdcd
6005// ok bad
6006//echo ${var#ab} abcdcd abcdcd
6007//echo ${var##ab} abcdcd abcdcd
6008//echo ${var#a*b} abcdcd ababcdcd (!)
6009//echo ${var##a*b} cdcd cdcd
6010//echo ${var#?} babcdcd ababcdcd (!)
6011//echo ${var##?} babcdcd babcdcd
6012//echo ${var#*} ababcdcd babcdcd (!)
6013//echo ${var##*}
6014//echo ${var%cd} ababcd ababcd
6015//echo ${var%%cd} ababcd abab (!)
6016//echo ${var%c*d} ababcd ababcd
6017//echo ${var%%c*d} abab ababcdcd (!)
6018//echo ${var%?} ababcdc ababcdc
6019//echo ${var%%?} ababcdc ababcdcd (!)
6020//echo ${var%*} ababcdcd ababcdcd
6021//echo ${var%%*}
6022//
6023// Commenting it back out helped. Remove it completely if it really
6024// is not needed.
6025
6026 char *loc, *loc2; //, *full;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006027 char c;
6028
6029 loc = startp;
6030 loc2 = rmesc;
6031 do {
Denis Vlasenkoc7131c32008-04-14 01:59:53 +00006032 int match; // = strlen(str);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006033 const char *s = loc2;
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006034
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006035 c = *loc2;
6036 if (zero) {
6037 *loc2 = '\0';
6038 s = rmesc;
6039 }
Denis Vlasenkoc7131c32008-04-14 01:59:53 +00006040 match = pmatch(str, s); // this line was deleted
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006041
Denis Vlasenkoc7131c32008-04-14 01:59:53 +00006042// // chop off end if its '*'
6043// full = strrchr(str, '*');
6044// if (full && full != str)
6045// match--;
6046//
6047// // If str starts with '*' replace with s.
6048// if ((*str == '*') && strlen(s) >= match) {
6049// full = xstrdup(s);
6050// strncpy(full+strlen(s)-match+1, str+1, match-1);
6051// } else
6052// full = xstrndup(str, match);
6053// match = strncmp(s, full, strlen(full));
6054// free(full);
6055//
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006056 *loc2 = c;
Denis Vlasenkoc7131c32008-04-14 01:59:53 +00006057 if (match) // if (!match)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006058 return loc;
Denys Vlasenkocd716832009-11-28 22:14:02 +01006059 if (quotes && (unsigned char)*loc == CTLESC)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006060 loc++;
6061 loc++;
6062 loc2++;
6063 } while (c);
6064 return 0;
6065}
6066
6067static char *
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006068scanright(char *startp, char *rmesc, char *rmescend, char *pattern, int quotes, int match_at_start)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006069{
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006070#if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6071 int try2optimize = match_at_start;
6072#endif
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006073 int esc = 0;
6074 char *loc;
6075 char *loc2;
6076
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006077 /* If we called by "${v/pattern/repl}" or "${v//pattern/repl}":
6078 * startp="escaped_value_of_v" rmesc="raw_value_of_v"
6079 * rmescend=""(ptr to NUL in rmesc) pattern="pattern" quotes=match_at_start=1
6080 * Logic:
6081 * loc starts at NUL at the end of startp, loc2 starts at the end of rmesc,
6082 * and on each iteration they go back two/one char until they reach the beginning.
6083 * We try to find a match in "raw_value_of_v", "raw_value_of_", "raw_value_of" etc.
6084 */
6085 /* TODO: document in what other circumstances we are called. */
6086
6087 for (loc = pattern - 1, loc2 = rmescend; loc >= startp; loc2--) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006088 int match;
6089 char c = *loc2;
6090 const char *s = loc2;
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006091 if (match_at_start) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006092 *loc2 = '\0';
6093 s = rmesc;
6094 }
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006095 match = pmatch(pattern, s);
6096 //bb_error_msg("pmatch(pattern:'%s',s:'%s'):%d", pattern, s, match);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006097 *loc2 = c;
6098 if (match)
6099 return loc;
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006100#if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6101 if (try2optimize) {
6102 /* Maybe we can optimize this:
6103 * if pattern ends with unescaped *, we can avoid checking
6104 * shorter strings: if "foo*" doesnt match "raw_value_of_v",
6105 * it wont match truncated "raw_value_of_" strings too.
6106 */
6107 unsigned plen = strlen(pattern);
6108 /* Does it end with "*"? */
6109 if (plen != 0 && pattern[--plen] == '*') {
6110 /* "xxxx*" is not escaped */
6111 /* "xxx\*" is escaped */
6112 /* "xx\\*" is not escaped */
6113 /* "x\\\*" is escaped */
6114 int slashes = 0;
6115 while (plen != 0 && pattern[--plen] == '\\')
6116 slashes++;
6117 if (!(slashes & 1))
6118 break; /* ends with unescaped "*" */
6119 }
6120 try2optimize = 0;
6121 }
6122#endif
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006123 loc--;
6124 if (quotes) {
6125 if (--esc < 0) {
6126 esc = esclen(startp, loc);
6127 }
6128 if (esc % 2) {
6129 esc--;
6130 loc--;
6131 }
6132 }
6133 }
6134 return 0;
6135}
6136
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00006137static void varunset(const char *, const char *, const char *, int) NORETURN;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006138static void
6139varunset(const char *end, const char *var, const char *umsg, int varflags)
6140{
6141 const char *msg;
6142 const char *tail;
6143
6144 tail = nullstr;
6145 msg = "parameter not set";
6146 if (umsg) {
Denys Vlasenkocd716832009-11-28 22:14:02 +01006147 if ((unsigned char)*end == CTLENDVAR) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006148 if (varflags & VSNUL)
6149 tail = " or null";
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00006150 } else {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006151 msg = umsg;
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00006152 }
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006153 }
6154 ash_msg_and_raise_error("%.*s: %s%s", end - var - 1, var, msg, tail);
6155}
6156
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006157#if ENABLE_ASH_BASH_COMPAT
6158static char *
6159parse_sub_pattern(char *arg, int inquotes)
6160{
6161 char *idx, *repl = NULL;
6162 unsigned char c;
6163
Denis Vlasenko2659c632008-06-14 06:04:59 +00006164 idx = arg;
6165 while (1) {
6166 c = *arg;
6167 if (!c)
6168 break;
6169 if (c == '/') {
6170 /* Only the first '/' seen is our separator */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006171 if (!repl) {
Denis Vlasenko2659c632008-06-14 06:04:59 +00006172 repl = idx + 1;
6173 c = '\0';
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006174 }
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006175 }
Denis Vlasenko2659c632008-06-14 06:04:59 +00006176 *idx++ = c;
6177 if (!inquotes && c == '\\' && arg[1] == '\\')
6178 arg++; /* skip both \\, not just first one */
6179 arg++;
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006180 }
Denis Vlasenko29038c02008-06-14 06:14:02 +00006181 *idx = c; /* NUL */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006182
6183 return repl;
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006184}
6185#endif /* ENABLE_ASH_BASH_COMPAT */
6186
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006187static const char *
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006188subevalvar(char *p, char *str, int strloc, int subtype,
6189 int startloc, int varflags, int quotes, struct strlist *var_str_list)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006190{
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006191 struct nodelist *saveargbackq = argbackq;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006192 char *startp;
6193 char *loc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006194 char *rmesc, *rmescend;
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00006195 IF_ASH_BASH_COMPAT(char *repl = NULL;)
6196 IF_ASH_BASH_COMPAT(char null = '\0';)
6197 IF_ASH_BASH_COMPAT(int pos, len, orig_len;)
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006198 int saveherefd = herefd;
6199 int amount, workloc, resetloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006200 int zero;
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006201 char *(*scan)(char*, char*, char*, char*, int, int);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006202
6203 herefd = -1;
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006204 argstr(p, (subtype != VSASSIGN && subtype != VSQUESTION) ? EXP_CASE : 0,
6205 var_str_list);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006206 STPUTC('\0', expdest);
6207 herefd = saveherefd;
6208 argbackq = saveargbackq;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00006209 startp = (char *)stackblock() + startloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006210
6211 switch (subtype) {
6212 case VSASSIGN:
6213 setvar(str, startp, 0);
6214 amount = startp - expdest;
6215 STADJUST(amount, expdest);
6216 return startp;
6217
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006218#if ENABLE_ASH_BASH_COMPAT
6219 case VSSUBSTR:
6220 loc = str = stackblock() + strloc;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006221 /* Read POS in ${var:POS:LEN} */
6222 pos = atoi(loc); /* number(loc) errors out on "1:4" */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006223 len = str - startp - 1;
6224
6225 /* *loc != '\0', guaranteed by parser */
6226 if (quotes) {
6227 char *ptr;
6228
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006229 /* Adjust the length by the number of escapes */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006230 for (ptr = startp; ptr < (str - 1); ptr++) {
Denys Vlasenkocd716832009-11-28 22:14:02 +01006231 if ((unsigned char)*ptr == CTLESC) {
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006232 len--;
6233 ptr++;
6234 }
6235 }
6236 }
6237 orig_len = len;
6238
6239 if (*loc++ == ':') {
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006240 /* ${var::LEN} */
6241 len = number(loc);
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006242 } else {
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006243 /* Skip POS in ${var:POS:LEN} */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006244 len = orig_len;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006245 while (*loc && *loc != ':') {
6246 /* TODO?
6247 * bash complains on: var=qwe; echo ${var:1a:123}
6248 if (!isdigit(*loc))
6249 ash_msg_and_raise_error(msg_illnum, str);
6250 */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006251 loc++;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006252 }
6253 if (*loc++ == ':') {
6254 len = number(loc);
6255 }
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006256 }
6257 if (pos >= orig_len) {
6258 pos = 0;
6259 len = 0;
6260 }
6261 if (len > (orig_len - pos))
6262 len = orig_len - pos;
6263
6264 for (str = startp; pos; str++, pos--) {
Denys Vlasenkocd716832009-11-28 22:14:02 +01006265 if (quotes && (unsigned char)*str == CTLESC)
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006266 str++;
6267 }
6268 for (loc = startp; len; len--) {
Denys Vlasenkocd716832009-11-28 22:14:02 +01006269 if (quotes && (unsigned char)*str == CTLESC)
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006270 *loc++ = *str++;
6271 *loc++ = *str++;
6272 }
6273 *loc = '\0';
6274 amount = loc - expdest;
6275 STADJUST(amount, expdest);
6276 return loc;
6277#endif
6278
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006279 case VSQUESTION:
6280 varunset(p, str, startp, varflags);
6281 /* NOTREACHED */
6282 }
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006283 resetloc = expdest - (char *)stackblock();
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006284
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006285 /* We'll comeback here if we grow the stack while handling
6286 * a VSREPLACE or VSREPLACEALL, since our pointers into the
6287 * stack will need rebasing, and we'll need to remove our work
6288 * areas each time
6289 */
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00006290 IF_ASH_BASH_COMPAT(restart:)
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006291
6292 amount = expdest - ((char *)stackblock() + resetloc);
6293 STADJUST(-amount, expdest);
Denis Vlasenko29eb3592008-05-18 14:06:08 +00006294 startp = (char *)stackblock() + startloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006295
6296 rmesc = startp;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00006297 rmescend = (char *)stackblock() + strloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006298 if (quotes) {
Denys Vlasenkob6c84342009-08-29 20:23:20 +02006299 rmesc = rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006300 if (rmesc != startp) {
6301 rmescend = expdest;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00006302 startp = (char *)stackblock() + startloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006303 }
6304 }
6305 rmescend--;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00006306 str = (char *)stackblock() + strloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006307 preglob(str, varflags & VSQUOTE, 0);
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006308 workloc = expdest - (char *)stackblock();
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006309
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006310#if ENABLE_ASH_BASH_COMPAT
6311 if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006312 char *idx, *end;
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006313
Denis Vlasenkod6855d12008-09-27 14:03:25 +00006314 if (!repl) {
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006315 repl = parse_sub_pattern(str, varflags & VSQUOTE);
6316 if (!repl)
6317 repl = &null;
6318 }
6319
6320 /* If there's no pattern to match, return the expansion unmolested */
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006321 if (str[0] == '\0')
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006322 return 0;
6323
6324 len = 0;
6325 idx = startp;
6326 end = str - 1;
6327 while (idx < end) {
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006328 try_to_match:
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006329 loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
6330 if (!loc) {
6331 /* No match, advance */
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006332 char *restart_detect = stackblock();
6333 skip_matching:
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006334 STPUTC(*idx, expdest);
Denys Vlasenkocd716832009-11-28 22:14:02 +01006335 if (quotes && (unsigned char)*idx == CTLESC) {
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006336 idx++;
6337 len++;
6338 STPUTC(*idx, expdest);
6339 }
6340 if (stackblock() != restart_detect)
6341 goto restart;
6342 idx++;
6343 len++;
6344 rmesc++;
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006345 /* continue; - prone to quadratic behavior, smarter code: */
6346 if (idx >= end)
6347 break;
6348 if (str[0] == '*') {
6349 /* Pattern is "*foo". If "*foo" does not match "long_string",
6350 * it would never match "ong_string" etc, no point in trying.
6351 */
6352 goto skip_matching;
6353 }
6354 goto try_to_match;
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006355 }
6356
6357 if (subtype == VSREPLACEALL) {
6358 while (idx < loc) {
Denys Vlasenkocd716832009-11-28 22:14:02 +01006359 if (quotes && (unsigned char)*idx == CTLESC)
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006360 idx++;
6361 idx++;
6362 rmesc++;
6363 }
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00006364 } else {
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006365 idx = loc;
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00006366 }
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006367
6368 for (loc = repl; *loc; loc++) {
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006369 char *restart_detect = stackblock();
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006370 STPUTC(*loc, expdest);
6371 if (stackblock() != restart_detect)
6372 goto restart;
6373 len++;
6374 }
6375
6376 if (subtype == VSREPLACE) {
6377 while (*idx) {
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006378 char *restart_detect = stackblock();
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006379 STPUTC(*idx, expdest);
6380 if (stackblock() != restart_detect)
6381 goto restart;
6382 len++;
6383 idx++;
6384 }
6385 break;
6386 }
6387 }
6388
6389 /* We've put the replaced text into a buffer at workloc, now
6390 * move it to the right place and adjust the stack.
6391 */
6392 startp = stackblock() + startloc;
6393 STPUTC('\0', expdest);
6394 memmove(startp, stackblock() + workloc, len);
6395 startp[len++] = '\0';
6396 amount = expdest - ((char *)stackblock() + startloc + len - 1);
6397 STADJUST(-amount, expdest);
6398 return startp;
6399 }
6400#endif /* ENABLE_ASH_BASH_COMPAT */
6401
6402 subtype -= VSTRIMRIGHT;
6403#if DEBUG
6404 if (subtype < 0 || subtype > 7)
6405 abort();
6406#endif
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006407 /* zero = (subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX) */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006408 zero = subtype >> 1;
6409 /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
6410 scan = (subtype & 1) ^ zero ? scanleft : scanright;
6411
6412 loc = scan(startp, rmesc, rmescend, str, quotes, zero);
6413 if (loc) {
6414 if (zero) {
6415 memmove(startp, loc, str - loc);
6416 loc = startp + (str - loc) - 1;
6417 }
6418 *loc = '\0';
6419 amount = loc - expdest;
6420 STADJUST(amount, expdest);
6421 }
6422 return loc;
6423}
6424
6425/*
6426 * Add the value of a specialized variable to the stack string.
Denys Vlasenko4d8873f2009-10-04 03:14:41 +02006427 * name parameter (examples):
6428 * ash -c 'echo $1' name:'1='
6429 * ash -c 'echo $qwe' name:'qwe='
6430 * ash -c 'echo $$' name:'$='
6431 * ash -c 'echo ${$}' name:'$='
6432 * ash -c 'echo ${$##q}' name:'$=q'
6433 * ash -c 'echo ${#$}' name:'$='
6434 * note: examples with bad shell syntax:
6435 * ash -c 'echo ${#$1}' name:'$=1'
6436 * ash -c 'echo ${#1#}' name:'1=#'
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006437 */
Denys Vlasenkoadf922e2009-10-08 14:35:37 +02006438static NOINLINE ssize_t
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006439varvalue(char *name, int varflags, int flags, struct strlist *var_str_list)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006440{
Mike Frysinger98c52642009-04-02 10:02:37 +00006441 const char *p;
Denys Vlasenko8eda4a92009-11-30 12:16:17 +01006442 int num;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006443 int i;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006444 int sepq = 0;
6445 ssize_t len = 0;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006446 int subtype = varflags & VSTYPE;
Denys Vlasenko1166d7b2009-09-16 16:20:31 +02006447 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR);
Denys Vlasenko8eda4a92009-11-30 12:16:17 +01006448 int quoted = varflags & VSQUOTE;
6449 int syntax = quoted ? DQSYNTAX : BASESYNTAX;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006450
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006451 switch (*name) {
6452 case '$':
6453 num = rootpid;
6454 goto numvar;
6455 case '?':
6456 num = exitstatus;
6457 goto numvar;
6458 case '#':
6459 num = shellparam.nparam;
6460 goto numvar;
6461 case '!':
6462 num = backgndpid;
6463 if (num == 0)
6464 return -1;
6465 numvar:
6466 len = cvtnum(num);
Denys Vlasenko4d8873f2009-10-04 03:14:41 +02006467 goto check_1char_name;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006468 case '-':
Mike Frysinger98c52642009-04-02 10:02:37 +00006469 expdest = makestrspace(NOPTS, expdest);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006470 for (i = NOPTS - 1; i >= 0; i--) {
6471 if (optlist[i]) {
Mike Frysinger98c52642009-04-02 10:02:37 +00006472 USTPUTC(optletters(i), expdest);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006473 len++;
6474 }
6475 }
Denys Vlasenko4d8873f2009-10-04 03:14:41 +02006476 check_1char_name:
6477#if 0
6478 /* handles cases similar to ${#$1} */
6479 if (name[2] != '\0')
6480 raise_error_syntax("bad substitution");
6481#endif
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006482 break;
Denys Vlasenko8eda4a92009-11-30 12:16:17 +01006483 case '@': {
6484 char **ap;
6485 int sep;
6486
6487 if (quoted && (flags & EXP_FULL)) {
6488 /* note: this is not meant as PEOF value */
6489 sep = 1 << CHAR_BIT;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006490 goto param;
Denys Vlasenko8eda4a92009-11-30 12:16:17 +01006491 }
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006492 /* fall through */
6493 case '*':
Denys Vlasenkocd716832009-11-28 22:14:02 +01006494 sep = ifsset() ? (unsigned char)(ifsval()[0]) : ' ';
Denys Vlasenko8eda4a92009-11-30 12:16:17 +01006495 i = SIT(sep, syntax);
6496 if (quotes && (i == CCTL || i == CBACK))
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006497 sepq = 1;
6498 param:
6499 ap = shellparam.p;
6500 if (!ap)
6501 return -1;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006502 while ((p = *ap++) != NULL) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006503 size_t partlen;
6504
6505 partlen = strlen(p);
6506 len += partlen;
6507
6508 if (!(subtype == VSPLUS || subtype == VSLENGTH))
6509 memtodest(p, partlen, syntax, quotes);
6510
6511 if (*ap && sep) {
6512 char *q;
6513
6514 len++;
6515 if (subtype == VSPLUS || subtype == VSLENGTH) {
6516 continue;
6517 }
6518 q = expdest;
6519 if (sepq)
6520 STPUTC(CTLESC, q);
Denys Vlasenko8eda4a92009-11-30 12:16:17 +01006521 /* note: may put NUL despite sep != 0
6522 * (see sep = 1 << CHAR_BIT above) */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006523 STPUTC(sep, q);
6524 expdest = q;
6525 }
6526 }
6527 return len;
Denys Vlasenko8eda4a92009-11-30 12:16:17 +01006528 } /* case '@' and '*' */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006529 case '0':
6530 case '1':
6531 case '2':
6532 case '3':
6533 case '4':
6534 case '5':
6535 case '6':
6536 case '7':
6537 case '8':
6538 case '9':
Denys Vlasenkoa00329c2009-08-30 20:05:10 +02006539 num = atoi(name); /* number(name) fails on ${N#str} etc */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006540 if (num < 0 || num > shellparam.nparam)
6541 return -1;
6542 p = num ? shellparam.p[num - 1] : arg0;
6543 goto value;
6544 default:
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006545 /* NB: name has form "VAR=..." */
6546
6547 /* "A=a B=$A" case: var_str_list is a list of "A=a" strings
6548 * which should be considered before we check variables. */
6549 if (var_str_list) {
6550 unsigned name_len = (strchrnul(name, '=') - name) + 1;
6551 p = NULL;
6552 do {
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00006553 char *str, *eq;
6554 str = var_str_list->text;
6555 eq = strchr(str, '=');
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006556 if (!eq) /* stop at first non-assignment */
6557 break;
6558 eq++;
Denis Vlasenko6b06cb82008-05-15 21:30:45 +00006559 if (name_len == (unsigned)(eq - str)
Denys Vlasenko8eda4a92009-11-30 12:16:17 +01006560 && strncmp(str, name, name_len) == 0
6561 ) {
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006562 p = eq;
6563 /* goto value; - WRONG! */
6564 /* think "A=1 A=2 B=$A" */
6565 }
6566 var_str_list = var_str_list->next;
6567 } while (var_str_list);
6568 if (p)
6569 goto value;
6570 }
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006571 p = lookupvar(name);
6572 value:
6573 if (!p)
6574 return -1;
6575
6576 len = strlen(p);
6577 if (!(subtype == VSPLUS || subtype == VSLENGTH))
6578 memtodest(p, len, syntax, quotes);
6579 return len;
6580 }
6581
6582 if (subtype == VSPLUS || subtype == VSLENGTH)
6583 STADJUST(-len, expdest);
6584 return len;
6585}
6586
6587/*
6588 * Expand a variable, and return a pointer to the next character in the
6589 * input string.
6590 */
6591static char *
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006592evalvar(char *p, int flags, struct strlist *var_str_list)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006593{
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006594 char varflags;
6595 char subtype;
6596 char quoted;
6597 char easy;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006598 char *var;
6599 int patloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006600 int startloc;
6601 ssize_t varlen;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006602
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006603 varflags = (unsigned char) *p++;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006604 subtype = varflags & VSTYPE;
6605 quoted = varflags & VSQUOTE;
6606 var = p;
6607 easy = (!quoted || (*var == '@' && shellparam.nparam));
6608 startloc = expdest - (char *)stackblock();
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02006609 p = strchr(p, '=') + 1; //TODO: use var_end(p)?
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006610
6611 again:
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006612 varlen = varvalue(var, varflags, flags, var_str_list);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006613 if (varflags & VSNUL)
6614 varlen--;
6615
6616 if (subtype == VSPLUS) {
6617 varlen = -1 - varlen;
6618 goto vsplus;
6619 }
6620
6621 if (subtype == VSMINUS) {
6622 vsplus:
6623 if (varlen < 0) {
6624 argstr(
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006625 p, flags | EXP_TILDE |
6626 (quoted ? EXP_QWORD : EXP_WORD),
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006627 var_str_list
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006628 );
6629 goto end;
6630 }
6631 if (easy)
6632 goto record;
6633 goto end;
6634 }
6635
6636 if (subtype == VSASSIGN || subtype == VSQUESTION) {
6637 if (varlen < 0) {
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006638 if (subevalvar(p, var, /* strloc: */ 0,
6639 subtype, startloc, varflags,
6640 /* quotes: */ 0,
6641 var_str_list)
6642 ) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006643 varflags &= ~VSNUL;
6644 /*
6645 * Remove any recorded regions beyond
6646 * start of variable
6647 */
6648 removerecordregions(startloc);
6649 goto again;
6650 }
6651 goto end;
6652 }
6653 if (easy)
6654 goto record;
6655 goto end;
6656 }
6657
6658 if (varlen < 0 && uflag)
6659 varunset(p, var, 0, 0);
6660
6661 if (subtype == VSLENGTH) {
6662 cvtnum(varlen > 0 ? varlen : 0);
6663 goto record;
6664 }
6665
6666 if (subtype == VSNORMAL) {
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006667 if (easy)
6668 goto record;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006669 goto end;
6670 }
6671
6672#if DEBUG
6673 switch (subtype) {
6674 case VSTRIMLEFT:
6675 case VSTRIMLEFTMAX:
6676 case VSTRIMRIGHT:
6677 case VSTRIMRIGHTMAX:
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006678#if ENABLE_ASH_BASH_COMPAT
6679 case VSSUBSTR:
6680 case VSREPLACE:
6681 case VSREPLACEALL:
6682#endif
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006683 break;
6684 default:
6685 abort();
6686 }
6687#endif
6688
6689 if (varlen >= 0) {
6690 /*
6691 * Terminate the string and start recording the pattern
6692 * right after it
6693 */
6694 STPUTC('\0', expdest);
6695 patloc = expdest - (char *)stackblock();
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006696 if (0 == subevalvar(p, /* str: */ NULL, patloc, subtype,
6697 startloc, varflags,
Denys Vlasenko1166d7b2009-09-16 16:20:31 +02006698//TODO: | EXP_REDIR too? All other such places do it too
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006699 /* quotes: */ flags & (EXP_FULL | EXP_CASE),
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006700 var_str_list)
6701 ) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006702 int amount = expdest - (
6703 (char *)stackblock() + patloc - 1
6704 );
6705 STADJUST(-amount, expdest);
6706 }
6707 /* Remove any recorded regions beyond start of variable */
6708 removerecordregions(startloc);
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006709 record:
6710 recordregion(startloc, expdest - (char *)stackblock(), quoted);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006711 }
6712
6713 end:
6714 if (subtype != VSNORMAL) { /* skip to end of alternative */
6715 int nesting = 1;
6716 for (;;) {
Denys Vlasenkocd716832009-11-28 22:14:02 +01006717 unsigned char c = *p++;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006718 if (c == CTLESC)
6719 p++;
6720 else if (c == CTLBACKQ || c == (CTLBACKQ|CTLQUOTE)) {
6721 if (varlen >= 0)
6722 argbackq = argbackq->next;
6723 } else if (c == CTLVAR) {
6724 if ((*p++ & VSTYPE) != VSNORMAL)
6725 nesting++;
6726 } else if (c == CTLENDVAR) {
6727 if (--nesting == 0)
6728 break;
6729 }
6730 }
6731 }
6732 return p;
6733}
6734
6735/*
6736 * Break the argument string into pieces based upon IFS and add the
6737 * strings to the argument list. The regions of the string to be
6738 * searched for IFS characters have been stored by recordregion.
6739 */
6740static void
6741ifsbreakup(char *string, struct arglist *arglist)
6742{
6743 struct ifsregion *ifsp;
6744 struct strlist *sp;
6745 char *start;
6746 char *p;
6747 char *q;
6748 const char *ifs, *realifs;
6749 int ifsspc;
6750 int nulonly;
6751
6752 start = string;
6753 if (ifslastp != NULL) {
6754 ifsspc = 0;
6755 nulonly = 0;
6756 realifs = ifsset() ? ifsval() : defifs;
6757 ifsp = &ifsfirst;
6758 do {
6759 p = string + ifsp->begoff;
6760 nulonly = ifsp->nulonly;
6761 ifs = nulonly ? nullstr : realifs;
6762 ifsspc = 0;
6763 while (p < string + ifsp->endoff) {
6764 q = p;
Denys Vlasenkocd716832009-11-28 22:14:02 +01006765 if ((unsigned char)*p == CTLESC)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006766 p++;
6767 if (!strchr(ifs, *p)) {
6768 p++;
6769 continue;
6770 }
6771 if (!nulonly)
6772 ifsspc = (strchr(defifs, *p) != NULL);
6773 /* Ignore IFS whitespace at start */
6774 if (q == start && ifsspc) {
6775 p++;
6776 start = p;
6777 continue;
6778 }
6779 *q = '\0';
Denis Vlasenko597906c2008-02-20 16:38:54 +00006780 sp = stzalloc(sizeof(*sp));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006781 sp->text = start;
6782 *arglist->lastp = sp;
6783 arglist->lastp = &sp->next;
6784 p++;
6785 if (!nulonly) {
6786 for (;;) {
6787 if (p >= string + ifsp->endoff) {
6788 break;
6789 }
6790 q = p;
Denys Vlasenkocd716832009-11-28 22:14:02 +01006791 if ((unsigned char)*p == CTLESC)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006792 p++;
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +00006793 if (strchr(ifs, *p) == NULL) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006794 p = q;
6795 break;
Denis Vlasenko597906c2008-02-20 16:38:54 +00006796 }
6797 if (strchr(defifs, *p) == NULL) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006798 if (ifsspc) {
6799 p++;
6800 ifsspc = 0;
6801 } else {
6802 p = q;
6803 break;
6804 }
6805 } else
6806 p++;
6807 }
6808 }
6809 start = p;
6810 } /* while */
6811 ifsp = ifsp->next;
6812 } while (ifsp != NULL);
6813 if (nulonly)
6814 goto add;
6815 }
6816
6817 if (!*start)
6818 return;
6819
6820 add:
Denis Vlasenko597906c2008-02-20 16:38:54 +00006821 sp = stzalloc(sizeof(*sp));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006822 sp->text = start;
6823 *arglist->lastp = sp;
6824 arglist->lastp = &sp->next;
6825}
6826
6827static void
6828ifsfree(void)
6829{
6830 struct ifsregion *p;
6831
6832 INT_OFF;
6833 p = ifsfirst.next;
6834 do {
6835 struct ifsregion *ifsp;
6836 ifsp = p->next;
6837 free(p);
6838 p = ifsp;
6839 } while (p);
6840 ifslastp = NULL;
6841 ifsfirst.next = NULL;
6842 INT_ON;
6843}
6844
6845/*
6846 * Add a file name to the list.
6847 */
6848static void
6849addfname(const char *name)
6850{
6851 struct strlist *sp;
6852
Denis Vlasenko597906c2008-02-20 16:38:54 +00006853 sp = stzalloc(sizeof(*sp));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006854 sp->text = ststrdup(name);
6855 *exparg.lastp = sp;
6856 exparg.lastp = &sp->next;
6857}
6858
6859static char *expdir;
6860
6861/*
6862 * Do metacharacter (i.e. *, ?, [...]) expansion.
6863 */
6864static void
6865expmeta(char *enddir, char *name)
6866{
6867 char *p;
6868 const char *cp;
6869 char *start;
6870 char *endname;
6871 int metaflag;
6872 struct stat statb;
6873 DIR *dirp;
6874 struct dirent *dp;
6875 int atend;
6876 int matchdot;
6877
6878 metaflag = 0;
6879 start = name;
6880 for (p = name; *p; p++) {
6881 if (*p == '*' || *p == '?')
6882 metaflag = 1;
6883 else if (*p == '[') {
6884 char *q = p + 1;
6885 if (*q == '!')
6886 q++;
6887 for (;;) {
6888 if (*q == '\\')
6889 q++;
6890 if (*q == '/' || *q == '\0')
6891 break;
6892 if (*++q == ']') {
6893 metaflag = 1;
6894 break;
6895 }
6896 }
6897 } else if (*p == '\\')
6898 p++;
6899 else if (*p == '/') {
6900 if (metaflag)
6901 goto out;
6902 start = p + 1;
6903 }
6904 }
6905 out:
6906 if (metaflag == 0) { /* we've reached the end of the file name */
6907 if (enddir != expdir)
6908 metaflag++;
6909 p = name;
6910 do {
6911 if (*p == '\\')
6912 p++;
6913 *enddir++ = *p;
6914 } while (*p++);
6915 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
6916 addfname(expdir);
6917 return;
6918 }
6919 endname = p;
6920 if (name < start) {
6921 p = name;
6922 do {
6923 if (*p == '\\')
6924 p++;
6925 *enddir++ = *p++;
6926 } while (p < start);
6927 }
6928 if (enddir == expdir) {
6929 cp = ".";
6930 } else if (enddir == expdir + 1 && *expdir == '/') {
6931 cp = "/";
6932 } else {
6933 cp = expdir;
6934 enddir[-1] = '\0';
6935 }
6936 dirp = opendir(cp);
6937 if (dirp == NULL)
6938 return;
6939 if (enddir != expdir)
6940 enddir[-1] = '/';
6941 if (*endname == 0) {
6942 atend = 1;
6943 } else {
6944 atend = 0;
6945 *endname++ = '\0';
6946 }
6947 matchdot = 0;
6948 p = start;
6949 if (*p == '\\')
6950 p++;
6951 if (*p == '.')
6952 matchdot++;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006953 while (!pending_int && (dp = readdir(dirp)) != NULL) {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00006954 if (dp->d_name[0] == '.' && !matchdot)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006955 continue;
6956 if (pmatch(start, dp->d_name)) {
6957 if (atend) {
6958 strcpy(enddir, dp->d_name);
6959 addfname(expdir);
6960 } else {
6961 for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
6962 continue;
6963 p[-1] = '/';
6964 expmeta(p, endname);
6965 }
6966 }
6967 }
6968 closedir(dirp);
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00006969 if (!atend)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006970 endname[-1] = '/';
6971}
6972
6973static struct strlist *
6974msort(struct strlist *list, int len)
6975{
6976 struct strlist *p, *q = NULL;
6977 struct strlist **lpp;
6978 int half;
6979 int n;
6980
6981 if (len <= 1)
6982 return list;
6983 half = len >> 1;
6984 p = list;
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +00006985 for (n = half; --n >= 0;) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006986 q = p;
6987 p = p->next;
6988 }
6989 q->next = NULL; /* terminate first half of list */
6990 q = msort(list, half); /* sort first half of list */
6991 p = msort(p, len - half); /* sort second half */
6992 lpp = &list;
6993 for (;;) {
6994#if ENABLE_LOCALE_SUPPORT
6995 if (strcoll(p->text, q->text) < 0)
6996#else
6997 if (strcmp(p->text, q->text) < 0)
6998#endif
6999 {
7000 *lpp = p;
7001 lpp = &p->next;
7002 p = *lpp;
7003 if (p == NULL) {
7004 *lpp = q;
7005 break;
7006 }
7007 } else {
7008 *lpp = q;
7009 lpp = &q->next;
7010 q = *lpp;
7011 if (q == NULL) {
7012 *lpp = p;
7013 break;
7014 }
7015 }
7016 }
7017 return list;
7018}
7019
7020/*
7021 * Sort the results of file name expansion. It calculates the number of
7022 * strings to sort and then calls msort (short for merge sort) to do the
7023 * work.
7024 */
7025static struct strlist *
7026expsort(struct strlist *str)
7027{
7028 int len;
7029 struct strlist *sp;
7030
7031 len = 0;
7032 for (sp = str; sp; sp = sp->next)
7033 len++;
7034 return msort(str, len);
7035}
7036
7037static void
Denis Vlasenko68404f12008-03-17 09:00:54 +00007038expandmeta(struct strlist *str /*, int flag*/)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007039{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00007040 static const char metachars[] ALIGN1 = {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007041 '*', '?', '[', 0
7042 };
7043 /* TODO - EXP_REDIR */
7044
7045 while (str) {
7046 struct strlist **savelastp;
7047 struct strlist *sp;
7048 char *p;
7049
7050 if (fflag)
7051 goto nometa;
7052 if (!strpbrk(str->text, metachars))
7053 goto nometa;
7054 savelastp = exparg.lastp;
7055
7056 INT_OFF;
7057 p = preglob(str->text, 0, RMESCAPE_ALLOC | RMESCAPE_HEAP);
7058 {
7059 int i = strlen(str->text);
7060 expdir = ckmalloc(i < 2048 ? 2048 : i); /* XXX */
7061 }
7062
7063 expmeta(expdir, p);
7064 free(expdir);
7065 if (p != str->text)
7066 free(p);
7067 INT_ON;
7068 if (exparg.lastp == savelastp) {
7069 /*
7070 * no matches
7071 */
7072 nometa:
7073 *exparg.lastp = str;
Denys Vlasenkob6c84342009-08-29 20:23:20 +02007074 rmescapes(str->text, 0);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007075 exparg.lastp = &str->next;
7076 } else {
7077 *exparg.lastp = NULL;
7078 *savelastp = sp = expsort(*savelastp);
7079 while (sp->next != NULL)
7080 sp = sp->next;
7081 exparg.lastp = &sp->next;
7082 }
7083 str = str->next;
7084 }
7085}
7086
7087/*
7088 * Perform variable substitution and command substitution on an argument,
7089 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
7090 * perform splitting and file name expansion. When arglist is NULL, perform
7091 * here document expansion.
7092 */
7093static void
7094expandarg(union node *arg, struct arglist *arglist, int flag)
7095{
7096 struct strlist *sp;
7097 char *p;
7098
7099 argbackq = arg->narg.backquote;
7100 STARTSTACKSTR(expdest);
7101 ifsfirst.next = NULL;
7102 ifslastp = NULL;
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00007103 argstr(arg->narg.text, flag,
7104 /* var_str_list: */ arglist ? arglist->list : NULL);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007105 p = _STPUTC('\0', expdest);
7106 expdest = p - 1;
7107 if (arglist == NULL) {
7108 return; /* here document expanded */
7109 }
7110 p = grabstackstr(p);
7111 exparg.lastp = &exparg.list;
7112 /*
7113 * TODO - EXP_REDIR
7114 */
7115 if (flag & EXP_FULL) {
7116 ifsbreakup(p, &exparg);
7117 *exparg.lastp = NULL;
7118 exparg.lastp = &exparg.list;
Denis Vlasenko68404f12008-03-17 09:00:54 +00007119 expandmeta(exparg.list /*, flag*/);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007120 } else {
7121 if (flag & EXP_REDIR) /*XXX - for now, just remove escapes */
Denys Vlasenkob6c84342009-08-29 20:23:20 +02007122 rmescapes(p, 0);
Denis Vlasenko597906c2008-02-20 16:38:54 +00007123 sp = stzalloc(sizeof(*sp));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007124 sp->text = p;
7125 *exparg.lastp = sp;
7126 exparg.lastp = &sp->next;
7127 }
7128 if (ifsfirst.next)
7129 ifsfree();
7130 *exparg.lastp = NULL;
7131 if (exparg.list) {
7132 *arglist->lastp = exparg.list;
7133 arglist->lastp = exparg.lastp;
7134 }
7135}
7136
7137/*
7138 * Expand shell variables and backquotes inside a here document.
7139 */
7140static void
7141expandhere(union node *arg, int fd)
7142{
7143 herefd = fd;
7144 expandarg(arg, (struct arglist *)NULL, 0);
7145 full_write(fd, stackblock(), expdest - (char *)stackblock());
7146}
7147
7148/*
7149 * Returns true if the pattern matches the string.
7150 */
7151static int
7152patmatch(char *pattern, const char *string)
7153{
7154 return pmatch(preglob(pattern, 0, 0), string);
7155}
7156
7157/*
7158 * See if a pattern matches in a case statement.
7159 */
7160static int
7161casematch(union node *pattern, char *val)
7162{
7163 struct stackmark smark;
7164 int result;
7165
7166 setstackmark(&smark);
7167 argbackq = pattern->narg.backquote;
7168 STARTSTACKSTR(expdest);
7169 ifslastp = NULL;
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00007170 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE,
7171 /* var_str_list: */ NULL);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007172 STACKSTRNUL(expdest);
7173 result = patmatch(stackblock(), val);
7174 popstackmark(&smark);
7175 return result;
7176}
7177
7178
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007179/* ============ find_command */
7180
7181struct builtincmd {
7182 const char *name;
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007183 int (*builtin)(int, char **) FAST_FUNC;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007184 /* unsigned flags; */
7185};
7186#define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
Denis Vlasenkoe26b2782008-02-12 07:40:29 +00007187/* "regular" builtins always take precedence over commands,
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007188 * regardless of PATH=....%builtin... position */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007189#define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007190#define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007191
7192struct cmdentry {
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00007193 smallint cmdtype; /* CMDxxx */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007194 union param {
7195 int index;
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00007196 /* index >= 0 for commands without path (slashes) */
7197 /* (TODO: what exactly does the value mean? PATH position?) */
7198 /* index == -1 for commands with slashes */
7199 /* index == (-2 - applet_no) for NOFORK applets */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007200 const struct builtincmd *cmd;
7201 struct funcnode *func;
7202 } u;
7203};
7204/* values of cmdtype */
7205#define CMDUNKNOWN -1 /* no entry in table for command */
7206#define CMDNORMAL 0 /* command is an executable program */
7207#define CMDFUNCTION 1 /* command is a shell function */
7208#define CMDBUILTIN 2 /* command is a shell builtin */
7209
7210/* action to find_command() */
7211#define DO_ERR 0x01 /* prints errors */
7212#define DO_ABS 0x02 /* checks absolute paths */
7213#define DO_NOFUNC 0x04 /* don't return shell functions, for command */
7214#define DO_ALTPATH 0x08 /* using alternate path */
7215#define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
7216
7217static void find_command(char *, struct cmdentry *, int, const char *);
7218
7219
7220/* ============ Hashing commands */
7221
7222/*
7223 * When commands are first encountered, they are entered in a hash table.
7224 * This ensures that a full path search will not have to be done for them
7225 * on each invocation.
7226 *
7227 * We should investigate converting to a linear search, even though that
7228 * would make the command name "hash" a misnomer.
7229 */
7230
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007231struct tblentry {
7232 struct tblentry *next; /* next entry in hash chain */
7233 union param param; /* definition of builtin function */
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00007234 smallint cmdtype; /* CMDxxx */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007235 char rehash; /* if set, cd done since entry created */
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007236 char cmdname[1]; /* name of command */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007237};
7238
Denis Vlasenko01631112007-12-16 17:20:38 +00007239static struct tblentry **cmdtable;
7240#define INIT_G_cmdtable() do { \
7241 cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
7242} while (0)
7243
7244static int builtinloc = -1; /* index in path of %builtin, or -1 */
7245
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007246
7247static void
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00007248tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) char *cmd, char **argv, char **envp)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007249{
7250 int repeated = 0;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007251
Denis Vlasenko80d14be2007-04-10 23:03:30 +00007252#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007253 if (applet_no >= 0) {
Denis Vlasenkob7304742008-10-20 08:15:51 +00007254 if (APPLET_IS_NOEXEC(applet_no)) {
Denys Vlasenko7df28bb2010-06-18 14:23:47 +02007255 clearenv();
Denis Vlasenkob7304742008-10-20 08:15:51 +00007256 while (*envp)
7257 putenv(*envp++);
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007258 run_applet_no_and_exit(applet_no, argv);
Denis Vlasenkob7304742008-10-20 08:15:51 +00007259 }
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007260 /* re-exec ourselves with the new arguments */
7261 execve(bb_busybox_exec_path, argv, envp);
7262 /* If they called chroot or otherwise made the binary no longer
7263 * executable, fall through */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007264 }
7265#endif
7266
7267 repeat:
7268#ifdef SYSV
7269 do {
7270 execve(cmd, argv, envp);
7271 } while (errno == EINTR);
7272#else
7273 execve(cmd, argv, envp);
7274#endif
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007275 if (repeated) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007276 free(argv);
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007277 return;
7278 }
7279 if (errno == ENOEXEC) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007280 char **ap;
7281 char **new;
7282
7283 for (ap = argv; *ap; ap++)
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007284 continue;
7285 ap = new = ckmalloc((ap - argv + 2) * sizeof(ap[0]));
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007286 ap[1] = cmd;
Denis Vlasenkoc44ab012007-04-09 03:11:58 +00007287 ap[0] = cmd = (char *)DEFAULT_SHELL;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007288 ap += 2;
7289 argv++;
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007290 while ((*ap++ = *argv++) != NULL)
Denis Vlasenko597906c2008-02-20 16:38:54 +00007291 continue;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007292 argv = new;
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007293 repeated++;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007294 goto repeat;
7295 }
7296}
7297
7298/*
7299 * Exec a program. Never returns. If you change this routine, you may
7300 * have to change the find_command routine as well.
7301 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00007302static void shellexec(char **, const char *, int) NORETURN;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007303static void
7304shellexec(char **argv, const char *path, int idx)
7305{
7306 char *cmdname;
7307 int e;
7308 char **envp;
7309 int exerrno;
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007310#if ENABLE_FEATURE_SH_STANDALONE
7311 int applet_no = -1;
7312#endif
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007313
Denis Vlasenko34c73c42008-08-16 11:48:02 +00007314 clearredir(/*drop:*/ 1);
Denys Vlasenko1ed2fb42010-06-18 14:09:48 +02007315 envp = listvars(VEXPORT, VUNSET, /*end:*/ NULL);
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007316 if (strchr(argv[0], '/') != NULL
Denis Vlasenko80d14be2007-04-10 23:03:30 +00007317#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007318 || (applet_no = find_applet_by_name(argv[0])) >= 0
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007319#endif
7320 ) {
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00007321 tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) argv[0], argv, envp);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007322 e = errno;
7323 } else {
7324 e = ENOENT;
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02007325 while ((cmdname = path_advance(&path, argv[0])) != NULL) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007326 if (--idx < 0 && pathopt == NULL) {
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00007327 tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007328 if (errno != ENOENT && errno != ENOTDIR)
7329 e = errno;
7330 }
7331 stunalloc(cmdname);
7332 }
7333 }
7334
7335 /* Map to POSIX errors */
7336 switch (e) {
7337 case EACCES:
7338 exerrno = 126;
7339 break;
7340 case ENOENT:
7341 exerrno = 127;
7342 break;
7343 default:
7344 exerrno = 2;
7345 break;
7346 }
7347 exitstatus = exerrno;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02007348 TRACE(("shellexec failed for %s, errno %d, suppress_int %d\n",
7349 argv[0], e, suppress_int));
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007350 ash_msg_and_raise(EXEXEC, "%s: %s", argv[0], errmsg(e, "not found"));
7351 /* NOTREACHED */
7352}
7353
7354static void
7355printentry(struct tblentry *cmdp)
7356{
7357 int idx;
7358 const char *path;
7359 char *name;
7360
7361 idx = cmdp->param.index;
7362 path = pathval();
7363 do {
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02007364 name = path_advance(&path, cmdp->cmdname);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007365 stunalloc(name);
7366 } while (--idx >= 0);
7367 out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
7368}
7369
7370/*
7371 * Clear out command entries. The argument specifies the first entry in
7372 * PATH which has changed.
7373 */
7374static void
7375clearcmdentry(int firstchange)
7376{
7377 struct tblentry **tblp;
7378 struct tblentry **pp;
7379 struct tblentry *cmdp;
7380
7381 INT_OFF;
7382 for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
7383 pp = tblp;
7384 while ((cmdp = *pp) != NULL) {
7385 if ((cmdp->cmdtype == CMDNORMAL &&
7386 cmdp->param.index >= firstchange)
7387 || (cmdp->cmdtype == CMDBUILTIN &&
7388 builtinloc >= firstchange)
7389 ) {
7390 *pp = cmdp->next;
7391 free(cmdp);
7392 } else {
7393 pp = &cmdp->next;
7394 }
7395 }
7396 }
7397 INT_ON;
7398}
7399
7400/*
7401 * Locate a command in the command hash table. If "add" is nonzero,
7402 * add the command to the table if it is not already present. The
7403 * variable "lastcmdentry" is set to point to the address of the link
7404 * pointing to the entry, so that delete_cmd_entry can delete the
7405 * entry.
7406 *
7407 * Interrupts must be off if called with add != 0.
7408 */
7409static struct tblentry **lastcmdentry;
7410
7411static struct tblentry *
7412cmdlookup(const char *name, int add)
7413{
7414 unsigned int hashval;
7415 const char *p;
7416 struct tblentry *cmdp;
7417 struct tblentry **pp;
7418
7419 p = name;
7420 hashval = (unsigned char)*p << 4;
7421 while (*p)
7422 hashval += (unsigned char)*p++;
7423 hashval &= 0x7FFF;
7424 pp = &cmdtable[hashval % CMDTABLESIZE];
7425 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7426 if (strcmp(cmdp->cmdname, name) == 0)
7427 break;
7428 pp = &cmdp->next;
7429 }
7430 if (add && cmdp == NULL) {
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007431 cmdp = *pp = ckzalloc(sizeof(struct tblentry)
7432 + strlen(name)
7433 /* + 1 - already done because
7434 * tblentry::cmdname is char[1] */);
Denis Vlasenko597906c2008-02-20 16:38:54 +00007435 /*cmdp->next = NULL; - ckzalloc did it */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007436 cmdp->cmdtype = CMDUNKNOWN;
7437 strcpy(cmdp->cmdname, name);
7438 }
7439 lastcmdentry = pp;
7440 return cmdp;
7441}
7442
7443/*
7444 * Delete the command entry returned on the last lookup.
7445 */
7446static void
7447delete_cmd_entry(void)
7448{
7449 struct tblentry *cmdp;
7450
7451 INT_OFF;
7452 cmdp = *lastcmdentry;
7453 *lastcmdentry = cmdp->next;
7454 if (cmdp->cmdtype == CMDFUNCTION)
7455 freefunc(cmdp->param.func);
7456 free(cmdp);
7457 INT_ON;
7458}
7459
7460/*
7461 * Add a new command entry, replacing any existing command entry for
7462 * the same name - except special builtins.
7463 */
7464static void
7465addcmdentry(char *name, struct cmdentry *entry)
7466{
7467 struct tblentry *cmdp;
7468
7469 cmdp = cmdlookup(name, 1);
7470 if (cmdp->cmdtype == CMDFUNCTION) {
7471 freefunc(cmdp->param.func);
7472 }
7473 cmdp->cmdtype = entry->cmdtype;
7474 cmdp->param = entry->u;
7475 cmdp->rehash = 0;
7476}
7477
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007478static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00007479hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007480{
7481 struct tblentry **pp;
7482 struct tblentry *cmdp;
7483 int c;
7484 struct cmdentry entry;
7485 char *name;
7486
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007487 if (nextopt("r") != '\0') {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007488 clearcmdentry(0);
7489 return 0;
7490 }
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007491
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007492 if (*argptr == NULL) {
7493 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7494 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7495 if (cmdp->cmdtype == CMDNORMAL)
7496 printentry(cmdp);
7497 }
7498 }
7499 return 0;
7500 }
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007501
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007502 c = 0;
7503 while ((name = *argptr) != NULL) {
7504 cmdp = cmdlookup(name, 0);
7505 if (cmdp != NULL
7506 && (cmdp->cmdtype == CMDNORMAL
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007507 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
7508 ) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007509 delete_cmd_entry();
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007510 }
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007511 find_command(name, &entry, DO_ERR, pathval());
7512 if (entry.cmdtype == CMDUNKNOWN)
7513 c = 1;
7514 argptr++;
7515 }
7516 return c;
7517}
7518
7519/*
7520 * Called when a cd is done. Marks all commands so the next time they
7521 * are executed they will be rehashed.
7522 */
7523static void
7524hashcd(void)
7525{
7526 struct tblentry **pp;
7527 struct tblentry *cmdp;
7528
7529 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7530 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007531 if (cmdp->cmdtype == CMDNORMAL
7532 || (cmdp->cmdtype == CMDBUILTIN
7533 && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
7534 && builtinloc > 0)
7535 ) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007536 cmdp->rehash = 1;
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007537 }
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007538 }
7539 }
7540}
7541
7542/*
7543 * Fix command hash table when PATH changed.
7544 * Called before PATH is changed. The argument is the new value of PATH;
7545 * pathval() still returns the old value at this point.
7546 * Called with interrupts off.
7547 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007548static void FAST_FUNC
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007549changepath(const char *new)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007550{
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007551 const char *old;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007552 int firstchange;
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007553 int idx;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007554 int idx_bltin;
7555
7556 old = pathval();
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007557 firstchange = 9999; /* assume no change */
7558 idx = 0;
7559 idx_bltin = -1;
7560 for (;;) {
7561 if (*old != *new) {
7562 firstchange = idx;
7563 if ((*old == '\0' && *new == ':')
Denys Vlasenkoa0ec4f52010-05-20 12:50:42 +02007564 || (*old == ':' && *new == '\0')
7565 ) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007566 firstchange++;
Denys Vlasenkoa0ec4f52010-05-20 12:50:42 +02007567 }
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007568 old = new; /* ignore subsequent differences */
7569 }
7570 if (*new == '\0')
7571 break;
7572 if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
7573 idx_bltin = idx;
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007574 if (*new == ':')
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007575 idx++;
Denys Vlasenkoa0ec4f52010-05-20 12:50:42 +02007576 new++;
7577 old++;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007578 }
7579 if (builtinloc < 0 && idx_bltin >= 0)
7580 builtinloc = idx_bltin; /* zap builtins */
7581 if (builtinloc >= 0 && idx_bltin < 0)
7582 firstchange = 0;
7583 clearcmdentry(firstchange);
7584 builtinloc = idx_bltin;
7585}
7586
7587#define TEOF 0
7588#define TNL 1
7589#define TREDIR 2
7590#define TWORD 3
7591#define TSEMI 4
7592#define TBACKGND 5
7593#define TAND 6
7594#define TOR 7
7595#define TPIPE 8
7596#define TLP 9
7597#define TRP 10
7598#define TENDCASE 11
7599#define TENDBQUOTE 12
7600#define TNOT 13
7601#define TCASE 14
7602#define TDO 15
7603#define TDONE 16
7604#define TELIF 17
7605#define TELSE 18
7606#define TESAC 19
7607#define TFI 20
7608#define TFOR 21
7609#define TIF 22
7610#define TIN 23
7611#define TTHEN 24
7612#define TUNTIL 25
7613#define TWHILE 26
7614#define TBEGIN 27
7615#define TEND 28
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007616typedef smallint token_id_t;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007617
7618/* first char is indicating which tokens mark the end of a list */
7619static const char *const tokname_array[] = {
7620 "\1end of file",
7621 "\0newline",
7622 "\0redirection",
7623 "\0word",
7624 "\0;",
7625 "\0&",
7626 "\0&&",
7627 "\0||",
7628 "\0|",
7629 "\0(",
7630 "\1)",
7631 "\1;;",
7632 "\1`",
7633#define KWDOFFSET 13
7634 /* the following are keywords */
7635 "\0!",
7636 "\0case",
7637 "\1do",
7638 "\1done",
7639 "\1elif",
7640 "\1else",
7641 "\1esac",
7642 "\1fi",
7643 "\0for",
7644 "\0if",
7645 "\0in",
7646 "\1then",
7647 "\0until",
7648 "\0while",
7649 "\0{",
7650 "\1}",
7651};
7652
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007653/* Wrapper around strcmp for qsort/bsearch/... */
7654static int
7655pstrcmp(const void *a, const void *b)
7656{
Denis Vlasenko240a1cf2007-04-08 16:07:02 +00007657 return strcmp((char*) a, (*(char**) b) + 1);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007658}
7659
7660static const char *const *
7661findkwd(const char *s)
7662{
7663 return bsearch(s, tokname_array + KWDOFFSET,
Denis Vlasenko80b8b392007-06-25 10:55:35 +00007664 ARRAY_SIZE(tokname_array) - KWDOFFSET,
7665 sizeof(tokname_array[0]), pstrcmp);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007666}
7667
7668/*
7669 * Locate and print what a word is...
7670 */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007671static int
7672describe_command(char *command, int describe_command_verbose)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007673{
7674 struct cmdentry entry;
7675 struct tblentry *cmdp;
7676#if ENABLE_ASH_ALIAS
7677 const struct alias *ap;
7678#endif
7679 const char *path = pathval();
7680
7681 if (describe_command_verbose) {
7682 out1str(command);
7683 }
7684
7685 /* First look at the keywords */
7686 if (findkwd(command)) {
7687 out1str(describe_command_verbose ? " is a shell keyword" : command);
7688 goto out;
7689 }
7690
7691#if ENABLE_ASH_ALIAS
7692 /* Then look at the aliases */
7693 ap = lookupalias(command, 0);
7694 if (ap != NULL) {
Denis Vlasenko46846e22007-05-20 13:08:31 +00007695 if (!describe_command_verbose) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007696 out1str("alias ");
7697 printalias(ap);
7698 return 0;
7699 }
Denis Vlasenko46846e22007-05-20 13:08:31 +00007700 out1fmt(" is an alias for %s", ap->val);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007701 goto out;
7702 }
7703#endif
7704 /* Then check if it is a tracked alias */
7705 cmdp = cmdlookup(command, 0);
7706 if (cmdp != NULL) {
7707 entry.cmdtype = cmdp->cmdtype;
7708 entry.u = cmdp->param;
7709 } else {
7710 /* Finally use brute force */
7711 find_command(command, &entry, DO_ABS, path);
7712 }
7713
7714 switch (entry.cmdtype) {
7715 case CMDNORMAL: {
7716 int j = entry.u.index;
7717 char *p;
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00007718 if (j < 0) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007719 p = command;
7720 } else {
7721 do {
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02007722 p = path_advance(&path, command);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007723 stunalloc(p);
7724 } while (--j >= 0);
7725 }
7726 if (describe_command_verbose) {
7727 out1fmt(" is%s %s",
7728 (cmdp ? " a tracked alias for" : nullstr), p
7729 );
7730 } else {
7731 out1str(p);
7732 }
7733 break;
7734 }
7735
7736 case CMDFUNCTION:
7737 if (describe_command_verbose) {
7738 out1str(" is a shell function");
7739 } else {
7740 out1str(command);
7741 }
7742 break;
7743
7744 case CMDBUILTIN:
7745 if (describe_command_verbose) {
7746 out1fmt(" is a %sshell builtin",
7747 IS_BUILTIN_SPECIAL(entry.u.cmd) ?
7748 "special " : nullstr
7749 );
7750 } else {
7751 out1str(command);
7752 }
7753 break;
7754
7755 default:
7756 if (describe_command_verbose) {
7757 out1str(": not found\n");
7758 }
7759 return 127;
7760 }
7761 out:
Denys Vlasenko285ad152009-12-04 23:02:27 +01007762 out1str("\n");
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007763 return 0;
7764}
7765
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007766static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00007767typecmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007768{
Denis Vlasenko46846e22007-05-20 13:08:31 +00007769 int i = 1;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007770 int err = 0;
Denis Vlasenko46846e22007-05-20 13:08:31 +00007771 int verbose = 1;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007772
Denis Vlasenko46846e22007-05-20 13:08:31 +00007773 /* type -p ... ? (we don't bother checking for 'p') */
Denis Vlasenko1fc62382007-06-25 22:55:34 +00007774 if (argv[1] && argv[1][0] == '-') {
Denis Vlasenko46846e22007-05-20 13:08:31 +00007775 i++;
7776 verbose = 0;
7777 }
Denis Vlasenko68404f12008-03-17 09:00:54 +00007778 while (argv[i]) {
Denis Vlasenko46846e22007-05-20 13:08:31 +00007779 err |= describe_command(argv[i++], verbose);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007780 }
7781 return err;
7782}
7783
7784#if ENABLE_ASH_CMDCMD
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007785static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00007786commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007787{
7788 int c;
7789 enum {
7790 VERIFY_BRIEF = 1,
7791 VERIFY_VERBOSE = 2,
7792 } verify = 0;
7793
7794 while ((c = nextopt("pvV")) != '\0')
7795 if (c == 'V')
7796 verify |= VERIFY_VERBOSE;
7797 else if (c == 'v')
7798 verify |= VERIFY_BRIEF;
7799#if DEBUG
7800 else if (c != 'p')
7801 abort();
7802#endif
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00007803 /* Mimic bash: just "command -v" doesn't complain, it's a nop */
7804 if (verify && (*argptr != NULL)) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007805 return describe_command(*argptr, verify - VERIFY_BRIEF);
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00007806 }
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007807
7808 return 0;
7809}
7810#endif
7811
7812
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007813/* ============ eval.c */
Eric Andersencb57d552001-06-28 07:25:16 +00007814
Denis Vlasenko340299a2008-11-21 10:36:36 +00007815static int funcblocksize; /* size of structures in function */
7816static int funcstringsize; /* size of strings in node */
7817static void *funcblock; /* block to allocate function from */
7818static char *funcstring; /* block to allocate strings from */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007819
Eric Andersencb57d552001-06-28 07:25:16 +00007820/* flags in argument to evaltree */
Denis Vlasenko340299a2008-11-21 10:36:36 +00007821#define EV_EXIT 01 /* exit after evaluating tree */
7822#define EV_TESTED 02 /* exit status is checked; ignore -e flag */
Eric Andersenc470f442003-07-28 09:56:35 +00007823#define EV_BACKCMD 04 /* command executing within back quotes */
Eric Andersencb57d552001-06-28 07:25:16 +00007824
Denys Vlasenko0e5e4ea2009-10-11 00:36:20 +02007825static const uint8_t nodesize[N_NUMBER] = {
Denis Vlasenko340299a2008-11-21 10:36:36 +00007826 [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
7827 [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
7828 [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
7829 [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
7830 [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
7831 [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
7832 [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
7833 [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
7834 [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
7835 [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
7836 [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
7837 [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
7838 [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
7839 [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
7840 [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
7841 [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
7842 [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
Denis Vlasenkocc5feab2008-11-22 01:32:40 +00007843#if ENABLE_ASH_BASH_COMPAT
Denis Vlasenko340299a2008-11-21 10:36:36 +00007844 [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
Denis Vlasenkocc5feab2008-11-22 01:32:40 +00007845#endif
Denis Vlasenko340299a2008-11-21 10:36:36 +00007846 [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
7847 [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
7848 [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
7849 [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
7850 [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
7851 [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
7852 [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
7853 [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
7854 [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007855};
7856
7857static void calcsize(union node *n);
7858
7859static void
7860sizenodelist(struct nodelist *lp)
7861{
7862 while (lp) {
7863 funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
7864 calcsize(lp->n);
7865 lp = lp->next;
7866 }
7867}
7868
7869static void
7870calcsize(union node *n)
7871{
7872 if (n == NULL)
7873 return;
7874 funcblocksize += nodesize[n->type];
7875 switch (n->type) {
7876 case NCMD:
7877 calcsize(n->ncmd.redirect);
7878 calcsize(n->ncmd.args);
7879 calcsize(n->ncmd.assign);
7880 break;
7881 case NPIPE:
7882 sizenodelist(n->npipe.cmdlist);
7883 break;
7884 case NREDIR:
7885 case NBACKGND:
7886 case NSUBSHELL:
7887 calcsize(n->nredir.redirect);
7888 calcsize(n->nredir.n);
7889 break;
7890 case NAND:
7891 case NOR:
7892 case NSEMI:
7893 case NWHILE:
7894 case NUNTIL:
7895 calcsize(n->nbinary.ch2);
7896 calcsize(n->nbinary.ch1);
7897 break;
7898 case NIF:
7899 calcsize(n->nif.elsepart);
7900 calcsize(n->nif.ifpart);
7901 calcsize(n->nif.test);
7902 break;
7903 case NFOR:
7904 funcstringsize += strlen(n->nfor.var) + 1;
7905 calcsize(n->nfor.body);
7906 calcsize(n->nfor.args);
7907 break;
7908 case NCASE:
7909 calcsize(n->ncase.cases);
7910 calcsize(n->ncase.expr);
7911 break;
7912 case NCLIST:
7913 calcsize(n->nclist.body);
7914 calcsize(n->nclist.pattern);
7915 calcsize(n->nclist.next);
7916 break;
7917 case NDEFUN:
7918 case NARG:
7919 sizenodelist(n->narg.backquote);
7920 funcstringsize += strlen(n->narg.text) + 1;
7921 calcsize(n->narg.next);
7922 break;
7923 case NTO:
Denis Vlasenko559691a2008-10-05 18:39:31 +00007924#if ENABLE_ASH_BASH_COMPAT
7925 case NTO2:
7926#endif
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007927 case NCLOBBER:
7928 case NFROM:
7929 case NFROMTO:
7930 case NAPPEND:
7931 calcsize(n->nfile.fname);
7932 calcsize(n->nfile.next);
7933 break;
7934 case NTOFD:
7935 case NFROMFD:
7936 calcsize(n->ndup.vname);
7937 calcsize(n->ndup.next);
7938 break;
7939 case NHERE:
7940 case NXHERE:
7941 calcsize(n->nhere.doc);
7942 calcsize(n->nhere.next);
7943 break;
7944 case NNOT:
7945 calcsize(n->nnot.com);
7946 break;
7947 };
7948}
7949
7950static char *
7951nodeckstrdup(char *s)
7952{
7953 char *rtn = funcstring;
7954
7955 strcpy(funcstring, s);
7956 funcstring += strlen(s) + 1;
7957 return rtn;
7958}
7959
7960static union node *copynode(union node *);
7961
7962static struct nodelist *
7963copynodelist(struct nodelist *lp)
7964{
7965 struct nodelist *start;
7966 struct nodelist **lpp;
7967
7968 lpp = &start;
7969 while (lp) {
7970 *lpp = funcblock;
7971 funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
7972 (*lpp)->n = copynode(lp->n);
7973 lp = lp->next;
7974 lpp = &(*lpp)->next;
7975 }
7976 *lpp = NULL;
7977 return start;
7978}
7979
7980static union node *
7981copynode(union node *n)
7982{
7983 union node *new;
7984
7985 if (n == NULL)
7986 return NULL;
7987 new = funcblock;
7988 funcblock = (char *) funcblock + nodesize[n->type];
7989
7990 switch (n->type) {
7991 case NCMD:
7992 new->ncmd.redirect = copynode(n->ncmd.redirect);
7993 new->ncmd.args = copynode(n->ncmd.args);
7994 new->ncmd.assign = copynode(n->ncmd.assign);
7995 break;
7996 case NPIPE:
7997 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00007998 new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007999 break;
8000 case NREDIR:
8001 case NBACKGND:
8002 case NSUBSHELL:
8003 new->nredir.redirect = copynode(n->nredir.redirect);
8004 new->nredir.n = copynode(n->nredir.n);
8005 break;
8006 case NAND:
8007 case NOR:
8008 case NSEMI:
8009 case NWHILE:
8010 case NUNTIL:
8011 new->nbinary.ch2 = copynode(n->nbinary.ch2);
8012 new->nbinary.ch1 = copynode(n->nbinary.ch1);
8013 break;
8014 case NIF:
8015 new->nif.elsepart = copynode(n->nif.elsepart);
8016 new->nif.ifpart = copynode(n->nif.ifpart);
8017 new->nif.test = copynode(n->nif.test);
8018 break;
8019 case NFOR:
8020 new->nfor.var = nodeckstrdup(n->nfor.var);
8021 new->nfor.body = copynode(n->nfor.body);
8022 new->nfor.args = copynode(n->nfor.args);
8023 break;
8024 case NCASE:
8025 new->ncase.cases = copynode(n->ncase.cases);
8026 new->ncase.expr = copynode(n->ncase.expr);
8027 break;
8028 case NCLIST:
8029 new->nclist.body = copynode(n->nclist.body);
8030 new->nclist.pattern = copynode(n->nclist.pattern);
8031 new->nclist.next = copynode(n->nclist.next);
8032 break;
8033 case NDEFUN:
8034 case NARG:
8035 new->narg.backquote = copynodelist(n->narg.backquote);
8036 new->narg.text = nodeckstrdup(n->narg.text);
8037 new->narg.next = copynode(n->narg.next);
8038 break;
8039 case NTO:
Denis Vlasenko559691a2008-10-05 18:39:31 +00008040#if ENABLE_ASH_BASH_COMPAT
8041 case NTO2:
8042#endif
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008043 case NCLOBBER:
8044 case NFROM:
8045 case NFROMTO:
8046 case NAPPEND:
8047 new->nfile.fname = copynode(n->nfile.fname);
8048 new->nfile.fd = n->nfile.fd;
8049 new->nfile.next = copynode(n->nfile.next);
8050 break;
8051 case NTOFD:
8052 case NFROMFD:
8053 new->ndup.vname = copynode(n->ndup.vname);
8054 new->ndup.dupfd = n->ndup.dupfd;
8055 new->ndup.fd = n->ndup.fd;
8056 new->ndup.next = copynode(n->ndup.next);
8057 break;
8058 case NHERE:
8059 case NXHERE:
8060 new->nhere.doc = copynode(n->nhere.doc);
8061 new->nhere.fd = n->nhere.fd;
8062 new->nhere.next = copynode(n->nhere.next);
8063 break;
8064 case NNOT:
8065 new->nnot.com = copynode(n->nnot.com);
8066 break;
8067 };
8068 new->type = n->type;
8069 return new;
8070}
8071
8072/*
8073 * Make a copy of a parse tree.
8074 */
8075static struct funcnode *
8076copyfunc(union node *n)
8077{
8078 struct funcnode *f;
8079 size_t blocksize;
8080
8081 funcblocksize = offsetof(struct funcnode, n);
8082 funcstringsize = 0;
8083 calcsize(n);
8084 blocksize = funcblocksize;
8085 f = ckmalloc(blocksize + funcstringsize);
8086 funcblock = (char *) f + offsetof(struct funcnode, n);
8087 funcstring = (char *) f + blocksize;
8088 copynode(n);
8089 f->count = 0;
8090 return f;
8091}
8092
8093/*
8094 * Define a shell function.
8095 */
8096static void
8097defun(char *name, union node *func)
8098{
8099 struct cmdentry entry;
8100
8101 INT_OFF;
8102 entry.cmdtype = CMDFUNCTION;
8103 entry.u.func = copyfunc(func);
8104 addcmdentry(name, &entry);
8105 INT_ON;
8106}
8107
Denis Vlasenko4b875702009-03-19 13:30:04 +00008108/* Reasons for skipping commands (see comment on breakcmd routine) */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008109#define SKIPBREAK (1 << 0)
8110#define SKIPCONT (1 << 1)
8111#define SKIPFUNC (1 << 2)
8112#define SKIPFILE (1 << 3)
8113#define SKIPEVAL (1 << 4)
Denis Vlasenko4b875702009-03-19 13:30:04 +00008114static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008115static int skipcount; /* number of levels to skip */
8116static int funcnest; /* depth of function calls */
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +00008117static int loopnest; /* current loop nesting level */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008118
Denis Vlasenko4b875702009-03-19 13:30:04 +00008119/* Forward decl way out to parsing code - dotrap needs it */
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008120static int evalstring(char *s, int mask);
8121
Denis Vlasenko4b875702009-03-19 13:30:04 +00008122/* Called to execute a trap.
8123 * Single callsite - at the end of evaltree().
8124 * If we return non-zero, exaltree raises EXEXIT exception.
8125 *
8126 * Perhaps we should avoid entering new trap handlers
8127 * while we are executing a trap handler. [is it a TODO?]
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008128 */
8129static int
8130dotrap(void)
8131{
Denis Vlasenko4b875702009-03-19 13:30:04 +00008132 uint8_t *g;
8133 int sig;
8134 uint8_t savestatus;
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008135
8136 savestatus = exitstatus;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02008137 pending_sig = 0;
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008138 xbarrier();
8139
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008140 TRACE(("dotrap entered\n"));
Denis Vlasenko4b875702009-03-19 13:30:04 +00008141 for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
8142 int want_exexit;
8143 char *t;
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008144
Denis Vlasenko4b875702009-03-19 13:30:04 +00008145 if (*g == 0)
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008146 continue;
Denis Vlasenko4b875702009-03-19 13:30:04 +00008147 t = trap[sig];
8148 /* non-trapped SIGINT is handled separately by raise_interrupt,
8149 * don't upset it by resetting gotsig[SIGINT-1] */
8150 if (sig == SIGINT && !t)
8151 continue;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008152
8153 TRACE(("sig %d is active, will run handler '%s'\n", sig, t));
Denis Vlasenko4b875702009-03-19 13:30:04 +00008154 *g = 0;
8155 if (!t)
8156 continue;
8157 want_exexit = evalstring(t, SKIPEVAL);
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008158 exitstatus = savestatus;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008159 if (want_exexit) {
Denis Vlasenkob21f3792009-03-19 23:09:58 +00008160 TRACE(("dotrap returns %d\n", want_exexit));
Denis Vlasenko4b875702009-03-19 13:30:04 +00008161 return want_exexit;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008162 }
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008163 }
8164
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008165 TRACE(("dotrap returns 0\n"));
Denis Vlasenko991a1da2008-02-10 19:02:53 +00008166 return 0;
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008167}
8168
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00008169/* forward declarations - evaluation is fairly recursive business... */
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008170static void evalloop(union node *, int);
8171static void evalfor(union node *, int);
8172static void evalcase(union node *, int);
8173static void evalsubshell(union node *, int);
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00008174static void expredir(union node *);
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008175static void evalpipe(union node *, int);
8176static void evalcommand(union node *, int);
Eric Andersenc470f442003-07-28 09:56:35 +00008177static int evalbltin(const struct builtincmd *, int, char **);
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008178static void prehash(union node *);
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00008179
Eric Andersen62483552001-07-10 06:09:16 +00008180/*
Eric Andersenc470f442003-07-28 09:56:35 +00008181 * Evaluate a parse tree. The value is left in the global variable
8182 * exitstatus.
Eric Andersen62483552001-07-10 06:09:16 +00008183 */
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008184static void
Eric Andersenc470f442003-07-28 09:56:35 +00008185evaltree(union node *n, int flags)
Eric Andersen62483552001-07-10 06:09:16 +00008186{
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008187 struct jmploc *volatile savehandler = exception_handler;
8188 struct jmploc jmploc;
Eric Andersenc470f442003-07-28 09:56:35 +00008189 int checkexit = 0;
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008190 void (*evalfn)(union node *, int);
Eric Andersenc470f442003-07-28 09:56:35 +00008191 int status;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008192 int int_level;
8193
8194 SAVE_INT(int_level);
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008195
Eric Andersenc470f442003-07-28 09:56:35 +00008196 if (n == NULL) {
8197 TRACE(("evaltree(NULL) called\n"));
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008198 goto out1;
Eric Andersen62483552001-07-10 06:09:16 +00008199 }
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008200 TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008201
8202 exception_handler = &jmploc;
8203 {
8204 int err = setjmp(jmploc.loc);
8205 if (err) {
8206 /* if it was a signal, check for trap handlers */
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008207 if (exception_type == EXSIG) {
Denis Vlasenkob21f3792009-03-19 23:09:58 +00008208 TRACE(("exception %d (EXSIG) in evaltree, err=%d\n",
8209 exception_type, err));
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008210 goto out;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008211 }
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008212 /* continue on the way out */
Denis Vlasenkob21f3792009-03-19 23:09:58 +00008213 TRACE(("exception %d in evaltree, propagating err=%d\n",
8214 exception_type, err));
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008215 exception_handler = savehandler;
8216 longjmp(exception_handler->loc, err);
8217 }
8218 }
8219
Eric Andersenc470f442003-07-28 09:56:35 +00008220 switch (n->type) {
8221 default:
Denis Vlasenkoa7189f02006-11-17 20:29:00 +00008222#if DEBUG
Eric Andersenc470f442003-07-28 09:56:35 +00008223 out1fmt("Node type = %d\n", n->type);
Denys Vlasenko8131eea2009-11-02 14:19:51 +01008224 fflush_all();
Eric Andersenc470f442003-07-28 09:56:35 +00008225 break;
8226#endif
8227 case NNOT:
8228 evaltree(n->nnot.com, EV_TESTED);
8229 status = !exitstatus;
8230 goto setstatus;
8231 case NREDIR:
8232 expredir(n->nredir.redirect);
8233 status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
8234 if (!status) {
8235 evaltree(n->nredir.n, flags & EV_TESTED);
8236 status = exitstatus;
8237 }
Denis Vlasenko34c73c42008-08-16 11:48:02 +00008238 popredir(/*drop:*/ 0, /*restore:*/ 0 /* not sure */);
Eric Andersenc470f442003-07-28 09:56:35 +00008239 goto setstatus;
8240 case NCMD:
8241 evalfn = evalcommand;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008242 checkexit:
Eric Andersenc470f442003-07-28 09:56:35 +00008243 if (eflag && !(flags & EV_TESTED))
8244 checkexit = ~0;
8245 goto calleval;
8246 case NFOR:
8247 evalfn = evalfor;
8248 goto calleval;
8249 case NWHILE:
8250 case NUNTIL:
8251 evalfn = evalloop;
8252 goto calleval;
8253 case NSUBSHELL:
8254 case NBACKGND:
8255 evalfn = evalsubshell;
8256 goto calleval;
8257 case NPIPE:
8258 evalfn = evalpipe;
8259 goto checkexit;
8260 case NCASE:
8261 evalfn = evalcase;
8262 goto calleval;
8263 case NAND:
8264 case NOR:
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008265 case NSEMI: {
8266
Eric Andersenc470f442003-07-28 09:56:35 +00008267#if NAND + 1 != NOR
8268#error NAND + 1 != NOR
8269#endif
8270#if NOR + 1 != NSEMI
8271#error NOR + 1 != NSEMI
8272#endif
Denis Vlasenko87d5fd92008-07-26 13:48:35 +00008273 unsigned is_or = n->type - NAND;
Eric Andersenc470f442003-07-28 09:56:35 +00008274 evaltree(
8275 n->nbinary.ch1,
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008276 (flags | ((is_or >> 1) - 1)) & EV_TESTED
Eric Andersenc470f442003-07-28 09:56:35 +00008277 );
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008278 if (!exitstatus == is_or)
Eric Andersenc470f442003-07-28 09:56:35 +00008279 break;
8280 if (!evalskip) {
8281 n = n->nbinary.ch2;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008282 evaln:
Eric Andersenc470f442003-07-28 09:56:35 +00008283 evalfn = evaltree;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008284 calleval:
Eric Andersenc470f442003-07-28 09:56:35 +00008285 evalfn(n, flags);
8286 break;
8287 }
8288 break;
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008289 }
Eric Andersenc470f442003-07-28 09:56:35 +00008290 case NIF:
8291 evaltree(n->nif.test, EV_TESTED);
8292 if (evalskip)
8293 break;
8294 if (exitstatus == 0) {
8295 n = n->nif.ifpart;
8296 goto evaln;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008297 }
8298 if (n->nif.elsepart) {
Eric Andersenc470f442003-07-28 09:56:35 +00008299 n = n->nif.elsepart;
8300 goto evaln;
8301 }
8302 goto success;
8303 case NDEFUN:
8304 defun(n->narg.text, n->narg.next);
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008305 success:
Eric Andersenc470f442003-07-28 09:56:35 +00008306 status = 0;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008307 setstatus:
Eric Andersenc470f442003-07-28 09:56:35 +00008308 exitstatus = status;
8309 break;
8310 }
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008311
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008312 out:
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008313 exception_handler = savehandler;
8314 out1:
8315 if (checkexit & exitstatus)
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00008316 evalskip |= SKIPEVAL;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02008317 else if (pending_sig && dotrap())
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00008318 goto exexit;
8319
8320 if (flags & EV_EXIT) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008321 exexit:
Denis Vlasenkob012b102007-02-19 22:43:01 +00008322 raise_exception(EXEXIT);
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00008323 }
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008324
8325 RESTORE_INT(int_level);
8326 TRACE(("leaving evaltree (no interrupts)\n"));
Eric Andersen62483552001-07-10 06:09:16 +00008327}
8328
Eric Andersenc470f442003-07-28 09:56:35 +00008329#if !defined(__alpha__) || (defined(__GNUC__) && __GNUC__ >= 3)
8330static
8331#endif
8332void evaltreenr(union node *, int) __attribute__ ((alias("evaltree"),__noreturn__));
8333
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008334static void
Eric Andersenc470f442003-07-28 09:56:35 +00008335evalloop(union node *n, int flags)
Eric Andersencb57d552001-06-28 07:25:16 +00008336{
8337 int status;
8338
8339 loopnest++;
8340 status = 0;
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008341 flags &= EV_TESTED;
Eric Andersencb57d552001-06-28 07:25:16 +00008342 for (;;) {
Eric Andersenc470f442003-07-28 09:56:35 +00008343 int i;
8344
Eric Andersencb57d552001-06-28 07:25:16 +00008345 evaltree(n->nbinary.ch1, EV_TESTED);
8346 if (evalskip) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008347 skipping:
8348 if (evalskip == SKIPCONT && --skipcount <= 0) {
Eric Andersencb57d552001-06-28 07:25:16 +00008349 evalskip = 0;
8350 continue;
8351 }
8352 if (evalskip == SKIPBREAK && --skipcount <= 0)
8353 evalskip = 0;
8354 break;
8355 }
Eric Andersenc470f442003-07-28 09:56:35 +00008356 i = exitstatus;
8357 if (n->type != NWHILE)
8358 i = !i;
8359 if (i != 0)
8360 break;
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008361 evaltree(n->nbinary.ch2, flags);
Eric Andersencb57d552001-06-28 07:25:16 +00008362 status = exitstatus;
8363 if (evalskip)
8364 goto skipping;
8365 }
8366 loopnest--;
8367 exitstatus = status;
8368}
8369
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008370static void
Eric Andersenc470f442003-07-28 09:56:35 +00008371evalfor(union node *n, int flags)
Eric Andersencb57d552001-06-28 07:25:16 +00008372{
8373 struct arglist arglist;
8374 union node *argp;
8375 struct strlist *sp;
8376 struct stackmark smark;
8377
8378 setstackmark(&smark);
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00008379 arglist.list = NULL;
Eric Andersencb57d552001-06-28 07:25:16 +00008380 arglist.lastp = &arglist.list;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008381 for (argp = n->nfor.args; argp; argp = argp->narg.next) {
Eric Andersencb57d552001-06-28 07:25:16 +00008382 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE | EXP_RECORD);
Eric Andersenc470f442003-07-28 09:56:35 +00008383 /* XXX */
Eric Andersencb57d552001-06-28 07:25:16 +00008384 if (evalskip)
8385 goto out;
8386 }
8387 *arglist.lastp = NULL;
8388
8389 exitstatus = 0;
8390 loopnest++;
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008391 flags &= EV_TESTED;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008392 for (sp = arglist.list; sp; sp = sp->next) {
Eric Andersencb57d552001-06-28 07:25:16 +00008393 setvar(n->nfor.var, sp->text, 0);
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008394 evaltree(n->nfor.body, flags);
Eric Andersencb57d552001-06-28 07:25:16 +00008395 if (evalskip) {
8396 if (evalskip == SKIPCONT && --skipcount <= 0) {
8397 evalskip = 0;
8398 continue;
8399 }
8400 if (evalskip == SKIPBREAK && --skipcount <= 0)
8401 evalskip = 0;
8402 break;
8403 }
8404 }
8405 loopnest--;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008406 out:
Eric Andersencb57d552001-06-28 07:25:16 +00008407 popstackmark(&smark);
8408}
8409
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008410static void
Eric Andersenc470f442003-07-28 09:56:35 +00008411evalcase(union node *n, int flags)
Eric Andersencb57d552001-06-28 07:25:16 +00008412{
8413 union node *cp;
8414 union node *patp;
8415 struct arglist arglist;
8416 struct stackmark smark;
8417
8418 setstackmark(&smark);
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00008419 arglist.list = NULL;
Eric Andersencb57d552001-06-28 07:25:16 +00008420 arglist.lastp = &arglist.list;
Eric Andersencb57d552001-06-28 07:25:16 +00008421 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
Eric Andersenc470f442003-07-28 09:56:35 +00008422 exitstatus = 0;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008423 for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
8424 for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
Eric Andersencb57d552001-06-28 07:25:16 +00008425 if (casematch(patp, arglist.list->text)) {
8426 if (evalskip == 0) {
8427 evaltree(cp->nclist.body, flags);
8428 }
8429 goto out;
8430 }
8431 }
8432 }
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008433 out:
Eric Andersencb57d552001-06-28 07:25:16 +00008434 popstackmark(&smark);
8435}
8436
Eric Andersenc470f442003-07-28 09:56:35 +00008437/*
8438 * Kick off a subshell to evaluate a tree.
8439 */
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008440static void
Eric Andersenc470f442003-07-28 09:56:35 +00008441evalsubshell(union node *n, int flags)
8442{
8443 struct job *jp;
8444 int backgnd = (n->type == NBACKGND);
8445 int status;
8446
8447 expredir(n->nredir.redirect);
Denys Vlasenko238bf182010-05-18 15:49:07 +02008448 if (!backgnd && (flags & EV_EXIT) && !may_have_traps)
Eric Andersenc470f442003-07-28 09:56:35 +00008449 goto nofork;
Denis Vlasenkob012b102007-02-19 22:43:01 +00008450 INT_OFF;
Denis Vlasenko68404f12008-03-17 09:00:54 +00008451 jp = makejob(/*n,*/ 1);
Eric Andersenc470f442003-07-28 09:56:35 +00008452 if (forkshell(jp, n, backgnd) == 0) {
Denys Vlasenko238bf182010-05-18 15:49:07 +02008453 /* child */
Denis Vlasenkob012b102007-02-19 22:43:01 +00008454 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00008455 flags |= EV_EXIT;
8456 if (backgnd)
Denys Vlasenko238bf182010-05-18 15:49:07 +02008457 flags &= ~EV_TESTED;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00008458 nofork:
Eric Andersenc470f442003-07-28 09:56:35 +00008459 redirect(n->nredir.redirect, 0);
8460 evaltreenr(n->nredir.n, flags);
8461 /* never returns */
8462 }
8463 status = 0;
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00008464 if (!backgnd)
Eric Andersenc470f442003-07-28 09:56:35 +00008465 status = waitforjob(jp);
8466 exitstatus = status;
Denis Vlasenkob012b102007-02-19 22:43:01 +00008467 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00008468}
8469
Eric Andersenc470f442003-07-28 09:56:35 +00008470/*
8471 * Compute the names of the files in a redirection list.
8472 */
Denis Vlasenko99eb8502007-02-23 21:09:49 +00008473static void fixredir(union node *, const char *, int);
Eric Andersenc470f442003-07-28 09:56:35 +00008474static void
8475expredir(union node *n)
8476{
8477 union node *redir;
8478
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008479 for (redir = n; redir; redir = redir->nfile.next) {
Eric Andersenc470f442003-07-28 09:56:35 +00008480 struct arglist fn;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008481
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00008482 fn.list = NULL;
Eric Andersenc470f442003-07-28 09:56:35 +00008483 fn.lastp = &fn.list;
8484 switch (redir->type) {
8485 case NFROMTO:
8486 case NFROM:
8487 case NTO:
Denis Vlasenko559691a2008-10-05 18:39:31 +00008488#if ENABLE_ASH_BASH_COMPAT
8489 case NTO2:
8490#endif
Eric Andersenc470f442003-07-28 09:56:35 +00008491 case NCLOBBER:
8492 case NAPPEND:
8493 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
Denis Vlasenko559691a2008-10-05 18:39:31 +00008494#if ENABLE_ASH_BASH_COMPAT
8495 store_expfname:
8496#endif
Eric Andersenc470f442003-07-28 09:56:35 +00008497 redir->nfile.expfname = fn.list->text;
8498 break;
8499 case NFROMFD:
Denis Vlasenko559691a2008-10-05 18:39:31 +00008500 case NTOFD: /* >& */
Eric Andersenc470f442003-07-28 09:56:35 +00008501 if (redir->ndup.vname) {
8502 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008503 if (fn.list == NULL)
Denis Vlasenkob012b102007-02-19 22:43:01 +00008504 ash_msg_and_raise_error("redir error");
Denis Vlasenko559691a2008-10-05 18:39:31 +00008505#if ENABLE_ASH_BASH_COMPAT
8506//FIXME: we used expandarg with different args!
8507 if (!isdigit_str9(fn.list->text)) {
8508 /* >&file, not >&fd */
8509 if (redir->nfile.fd != 1) /* 123>&file - BAD */
8510 ash_msg_and_raise_error("redir error");
8511 redir->type = NTO2;
8512 goto store_expfname;
8513 }
8514#endif
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008515 fixredir(redir, fn.list->text, 1);
Eric Andersenc470f442003-07-28 09:56:35 +00008516 }
8517 break;
8518 }
8519 }
8520}
8521
Eric Andersencb57d552001-06-28 07:25:16 +00008522/*
Eric Andersencb57d552001-06-28 07:25:16 +00008523 * Evaluate a pipeline. All the processes in the pipeline are children
8524 * of the process creating the pipeline. (This differs from some versions
8525 * of the shell, which make the last process in a pipeline the parent
8526 * of all the rest.)
8527 */
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008528static void
Eric Andersenc470f442003-07-28 09:56:35 +00008529evalpipe(union node *n, int flags)
Eric Andersencb57d552001-06-28 07:25:16 +00008530{
8531 struct job *jp;
8532 struct nodelist *lp;
8533 int pipelen;
8534 int prevfd;
8535 int pip[2];
8536
Eric Andersenc470f442003-07-28 09:56:35 +00008537 TRACE(("evalpipe(0x%lx) called\n", (long)n));
Eric Andersencb57d552001-06-28 07:25:16 +00008538 pipelen = 0;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008539 for (lp = n->npipe.cmdlist; lp; lp = lp->next)
Eric Andersencb57d552001-06-28 07:25:16 +00008540 pipelen++;
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008541 flags |= EV_EXIT;
Denis Vlasenkob012b102007-02-19 22:43:01 +00008542 INT_OFF;
Denis Vlasenko68404f12008-03-17 09:00:54 +00008543 jp = makejob(/*n,*/ pipelen);
Eric Andersencb57d552001-06-28 07:25:16 +00008544 prevfd = -1;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008545 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008546 prehash(lp->n);
Eric Andersencb57d552001-06-28 07:25:16 +00008547 pip[1] = -1;
8548 if (lp->next) {
8549 if (pipe(pip) < 0) {
8550 close(prevfd);
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00008551 ash_msg_and_raise_error("pipe call failed");
Eric Andersencb57d552001-06-28 07:25:16 +00008552 }
8553 }
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00008554 if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
Denis Vlasenkob012b102007-02-19 22:43:01 +00008555 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00008556 if (pip[1] >= 0) {
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008557 close(pip[0]);
Eric Andersencb57d552001-06-28 07:25:16 +00008558 }
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008559 if (prevfd > 0) {
8560 dup2(prevfd, 0);
8561 close(prevfd);
8562 }
8563 if (pip[1] > 1) {
8564 dup2(pip[1], 1);
8565 close(pip[1]);
8566 }
Eric Andersenc470f442003-07-28 09:56:35 +00008567 evaltreenr(lp->n, flags);
8568 /* never returns */
Eric Andersencb57d552001-06-28 07:25:16 +00008569 }
8570 if (prevfd >= 0)
8571 close(prevfd);
8572 prevfd = pip[0];
Denis Vlasenkob9e70dd2009-03-20 01:24:08 +00008573 /* Don't want to trigger debugging */
8574 if (pip[1] != -1)
8575 close(pip[1]);
Eric Andersencb57d552001-06-28 07:25:16 +00008576 }
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00008577 if (n->npipe.pipe_backgnd == 0) {
Eric Andersencb57d552001-06-28 07:25:16 +00008578 exitstatus = waitforjob(jp);
8579 TRACE(("evalpipe: job done exit status %d\n", exitstatus));
Eric Andersencb57d552001-06-28 07:25:16 +00008580 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00008581 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00008582}
8583
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008584/*
8585 * Controls whether the shell is interactive or not.
8586 */
8587static void
8588setinteractive(int on)
8589{
Denis Vlasenkob07a4962008-06-22 13:16:23 +00008590 static smallint is_interactive;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008591
8592 if (++on == is_interactive)
8593 return;
8594 is_interactive = on;
8595 setsignal(SIGINT);
8596 setsignal(SIGQUIT);
8597 setsignal(SIGTERM);
8598#if !ENABLE_FEATURE_SH_EXTRA_QUIET
8599 if (is_interactive > 1) {
8600 /* Looks like they want an interactive shell */
Denis Vlasenkoca525b42007-06-13 12:27:17 +00008601 static smallint did_banner;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008602
Denis Vlasenkoca525b42007-06-13 12:27:17 +00008603 if (!did_banner) {
Denys Vlasenkoc34c0332009-09-29 12:25:30 +02008604 /* note: ash and hush share this string */
8605 out1fmt("\n\n%s %s\n"
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008606 "Enter 'help' for a list of built-in commands."
8607 "\n\n",
Denys Vlasenkoc34c0332009-09-29 12:25:30 +02008608 bb_banner,
8609 "built-in shell (ash)"
8610 );
Denis Vlasenkoca525b42007-06-13 12:27:17 +00008611 did_banner = 1;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008612 }
8613 }
8614#endif
8615}
8616
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008617static void
8618optschanged(void)
8619{
8620#if DEBUG
8621 opentrace();
8622#endif
8623 setinteractive(iflag);
8624 setjobctl(mflag);
Denis Vlasenkob07a4962008-06-22 13:16:23 +00008625#if ENABLE_FEATURE_EDITING_VI
8626 if (viflag)
8627 line_input_state->flags |= VI_MODE;
8628 else
8629 line_input_state->flags &= ~VI_MODE;
8630#else
8631 viflag = 0; /* forcibly keep the option off */
8632#endif
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008633}
8634
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008635static struct localvar *localvars;
8636
8637/*
8638 * Called after a function returns.
8639 * Interrupts must be off.
8640 */
8641static void
8642poplocalvars(void)
8643{
8644 struct localvar *lvp;
8645 struct var *vp;
8646
8647 while ((lvp = localvars) != NULL) {
8648 localvars = lvp->next;
8649 vp = lvp->vp;
Denys Vlasenko883cea42009-07-11 15:31:59 +02008650 TRACE(("poplocalvar %s\n", vp ? vp->text : "-"));
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008651 if (vp == NULL) { /* $- saved */
8652 memcpy(optlist, lvp->text, sizeof(optlist));
8653 free((char*)lvp->text);
8654 optschanged();
8655 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02008656 unsetvar(vp->var_text);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008657 } else {
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02008658 if (vp->var_func)
8659 vp->var_func(var_end(lvp->text));
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008660 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02008661 free((char*)vp->var_text);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008662 vp->flags = lvp->flags;
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02008663 vp->var_text = lvp->text;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008664 }
8665 free(lvp);
8666 }
8667}
8668
8669static int
8670evalfun(struct funcnode *func, int argc, char **argv, int flags)
8671{
8672 volatile struct shparam saveparam;
8673 struct localvar *volatile savelocalvars;
8674 struct jmploc *volatile savehandler;
8675 struct jmploc jmploc;
8676 int e;
8677
8678 saveparam = shellparam;
8679 savelocalvars = localvars;
8680 e = setjmp(jmploc.loc);
8681 if (e) {
8682 goto funcdone;
8683 }
8684 INT_OFF;
8685 savehandler = exception_handler;
8686 exception_handler = &jmploc;
8687 localvars = NULL;
Denis Vlasenko01631112007-12-16 17:20:38 +00008688 shellparam.malloced = 0;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008689 func->count++;
8690 funcnest++;
8691 INT_ON;
8692 shellparam.nparam = argc - 1;
8693 shellparam.p = argv + 1;
8694#if ENABLE_ASH_GETOPTS
8695 shellparam.optind = 1;
8696 shellparam.optoff = -1;
8697#endif
8698 evaltree(&func->n, flags & EV_TESTED);
Denis Vlasenko01631112007-12-16 17:20:38 +00008699 funcdone:
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008700 INT_OFF;
8701 funcnest--;
8702 freefunc(func);
8703 poplocalvars();
8704 localvars = savelocalvars;
8705 freeparam(&shellparam);
8706 shellparam = saveparam;
8707 exception_handler = savehandler;
8708 INT_ON;
8709 evalskip &= ~SKIPFUNC;
8710 return e;
8711}
8712
Denis Vlasenko131ae172007-02-18 13:00:19 +00008713#if ENABLE_ASH_CMDCMD
Denis Vlasenkoaa744452007-02-23 01:04:22 +00008714static char **
8715parse_command_args(char **argv, const char **path)
Eric Andersenc470f442003-07-28 09:56:35 +00008716{
8717 char *cp, c;
8718
8719 for (;;) {
8720 cp = *++argv;
8721 if (!cp)
8722 return 0;
8723 if (*cp++ != '-')
8724 break;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008725 c = *cp++;
8726 if (!c)
Eric Andersenc470f442003-07-28 09:56:35 +00008727 break;
8728 if (c == '-' && !*cp) {
8729 argv++;
8730 break;
8731 }
8732 do {
8733 switch (c) {
8734 case 'p':
Denis Vlasenkof5f75c52007-06-12 22:35:19 +00008735 *path = bb_default_path;
Eric Andersenc470f442003-07-28 09:56:35 +00008736 break;
8737 default:
8738 /* run 'typecmd' for other options */
8739 return 0;
8740 }
Denis Vlasenko9650f362007-02-23 01:04:37 +00008741 c = *cp++;
8742 } while (c);
Eric Andersenc470f442003-07-28 09:56:35 +00008743 }
8744 return argv;
8745}
8746#endif
8747
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008748/*
8749 * Make a variable a local variable. When a variable is made local, it's
8750 * value and flags are saved in a localvar structure. The saved values
8751 * will be restored when the shell function returns. We handle the name
8752 * "-" as a special case.
8753 */
8754static void
8755mklocal(char *name)
8756{
8757 struct localvar *lvp;
8758 struct var **vpp;
8759 struct var *vp;
8760
8761 INT_OFF;
Denis Vlasenko838ffd52008-02-21 04:32:08 +00008762 lvp = ckzalloc(sizeof(struct localvar));
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008763 if (LONE_DASH(name)) {
8764 char *p;
8765 p = ckmalloc(sizeof(optlist));
8766 lvp->text = memcpy(p, optlist, sizeof(optlist));
8767 vp = NULL;
8768 } else {
8769 char *eq;
8770
8771 vpp = hashvar(name);
8772 vp = *findvar(vpp, name);
8773 eq = strchr(name, '=');
8774 if (vp == NULL) {
8775 if (eq)
8776 setvareq(name, VSTRFIXED);
8777 else
8778 setvar(name, NULL, VSTRFIXED);
8779 vp = *vpp; /* the new variable */
8780 lvp->flags = VUNSET;
8781 } else {
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02008782 lvp->text = vp->var_text;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008783 lvp->flags = vp->flags;
8784 vp->flags |= VSTRFIXED|VTEXTFIXED;
8785 if (eq)
8786 setvareq(name, 0);
8787 }
8788 }
8789 lvp->vp = vp;
8790 lvp->next = localvars;
8791 localvars = lvp;
8792 INT_ON;
8793}
8794
8795/*
8796 * The "local" command.
8797 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008798static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008799localcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008800{
8801 char *name;
8802
8803 argv = argptr;
8804 while ((name = *argv++) != NULL) {
8805 mklocal(name);
8806 }
8807 return 0;
8808}
8809
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008810static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008811falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008812{
8813 return 1;
8814}
8815
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008816static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008817truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008818{
8819 return 0;
8820}
8821
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008822static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008823execcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008824{
Denis Vlasenko68404f12008-03-17 09:00:54 +00008825 if (argv[1]) {
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008826 iflag = 0; /* exit on error */
8827 mflag = 0;
8828 optschanged();
8829 shellexec(argv + 1, pathval(), 0);
8830 }
8831 return 0;
8832}
8833
8834/*
8835 * The return command.
8836 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008837static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008838returncmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008839{
8840 /*
8841 * If called outside a function, do what ksh does;
8842 * skip the rest of the file.
8843 */
8844 evalskip = funcnest ? SKIPFUNC : SKIPFILE;
8845 return argv[1] ? number(argv[1]) : exitstatus;
8846}
8847
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008848/* Forward declarations for builtintab[] */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008849static int breakcmd(int, char **) FAST_FUNC;
8850static int dotcmd(int, char **) FAST_FUNC;
8851static int evalcmd(int, char **) FAST_FUNC;
8852static int exitcmd(int, char **) FAST_FUNC;
8853static int exportcmd(int, char **) FAST_FUNC;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008854#if ENABLE_ASH_GETOPTS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008855static int getoptscmd(int, char **) FAST_FUNC;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008856#endif
Denis Vlasenko52764022007-02-24 13:42:56 +00008857#if !ENABLE_FEATURE_SH_EXTRA_QUIET
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008858static int helpcmd(int, char **) FAST_FUNC;
Denis Vlasenko52764022007-02-24 13:42:56 +00008859#endif
Mike Frysinger98c52642009-04-02 10:02:37 +00008860#if ENABLE_SH_MATH_SUPPORT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008861static int letcmd(int, char **) FAST_FUNC;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008862#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008863static int readcmd(int, char **) FAST_FUNC;
8864static int setcmd(int, char **) FAST_FUNC;
8865static int shiftcmd(int, char **) FAST_FUNC;
8866static int timescmd(int, char **) FAST_FUNC;
8867static int trapcmd(int, char **) FAST_FUNC;
8868static int umaskcmd(int, char **) FAST_FUNC;
8869static int unsetcmd(int, char **) FAST_FUNC;
8870static int ulimitcmd(int, char **) FAST_FUNC;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008871
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008872#define BUILTIN_NOSPEC "0"
8873#define BUILTIN_SPECIAL "1"
8874#define BUILTIN_REGULAR "2"
8875#define BUILTIN_SPEC_REG "3"
8876#define BUILTIN_ASSIGN "4"
8877#define BUILTIN_SPEC_ASSG "5"
8878#define BUILTIN_REG_ASSG "6"
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008879#define BUILTIN_SPEC_REG_ASSG "7"
8880
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008881/* Stubs for calling non-FAST_FUNC's */
Denys Vlasenko2634bf32009-06-09 18:40:07 +02008882#if ENABLE_ASH_BUILTIN_ECHO
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008883static int FAST_FUNC echocmd(int argc, char **argv) { return echo_main(argc, argv); }
Denys Vlasenko2634bf32009-06-09 18:40:07 +02008884#endif
8885#if ENABLE_ASH_BUILTIN_PRINTF
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008886static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
Denys Vlasenko2634bf32009-06-09 18:40:07 +02008887#endif
8888#if ENABLE_ASH_BUILTIN_TEST
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008889static int FAST_FUNC testcmd(int argc, char **argv) { return test_main(argc, argv); }
Denys Vlasenko2634bf32009-06-09 18:40:07 +02008890#endif
Denis Vlasenko468aea22008-04-01 14:47:57 +00008891
Denis Vlasenkof7d56652008-03-25 05:51:41 +00008892/* Keep these in proper order since it is searched via bsearch() */
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008893static const struct builtincmd builtintab[] = {
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008894 { BUILTIN_SPEC_REG "." , dotcmd },
8895 { BUILTIN_SPEC_REG ":" , truecmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008896#if ENABLE_ASH_BUILTIN_TEST
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008897 { BUILTIN_REGULAR "[" , testcmd },
Denis Vlasenko80591b02008-03-25 07:49:43 +00008898#if ENABLE_ASH_BASH_COMPAT
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008899 { BUILTIN_REGULAR "[[" , testcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008900#endif
Denis Vlasenko80591b02008-03-25 07:49:43 +00008901#endif
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008902#if ENABLE_ASH_ALIAS
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008903 { BUILTIN_REG_ASSG "alias" , aliascmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008904#endif
8905#if JOBS
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008906 { BUILTIN_REGULAR "bg" , fg_bgcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008907#endif
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008908 { BUILTIN_SPEC_REG "break" , breakcmd },
8909 { BUILTIN_REGULAR "cd" , cdcmd },
8910 { BUILTIN_NOSPEC "chdir" , cdcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008911#if ENABLE_ASH_CMDCMD
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008912 { BUILTIN_REGULAR "command" , commandcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008913#endif
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008914 { BUILTIN_SPEC_REG "continue", breakcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008915#if ENABLE_ASH_BUILTIN_ECHO
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008916 { BUILTIN_REGULAR "echo" , echocmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008917#endif
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008918 { BUILTIN_SPEC_REG "eval" , evalcmd },
8919 { BUILTIN_SPEC_REG "exec" , execcmd },
8920 { BUILTIN_SPEC_REG "exit" , exitcmd },
8921 { BUILTIN_SPEC_REG_ASSG "export" , exportcmd },
8922 { BUILTIN_REGULAR "false" , falsecmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008923#if JOBS
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008924 { BUILTIN_REGULAR "fg" , fg_bgcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008925#endif
8926#if ENABLE_ASH_GETOPTS
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008927 { BUILTIN_REGULAR "getopts" , getoptscmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008928#endif
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008929 { BUILTIN_NOSPEC "hash" , hashcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008930#if !ENABLE_FEATURE_SH_EXTRA_QUIET
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008931 { BUILTIN_NOSPEC "help" , helpcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008932#endif
8933#if JOBS
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008934 { BUILTIN_REGULAR "jobs" , jobscmd },
8935 { BUILTIN_REGULAR "kill" , killcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008936#endif
Mike Frysinger98c52642009-04-02 10:02:37 +00008937#if ENABLE_SH_MATH_SUPPORT
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008938 { BUILTIN_NOSPEC "let" , letcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008939#endif
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008940 { BUILTIN_ASSIGN "local" , localcmd },
Denis Vlasenkocd2663f2008-06-01 22:36:39 +00008941#if ENABLE_ASH_BUILTIN_PRINTF
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008942 { BUILTIN_REGULAR "printf" , printfcmd },
Denis Vlasenkocd2663f2008-06-01 22:36:39 +00008943#endif
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008944 { BUILTIN_NOSPEC "pwd" , pwdcmd },
8945 { BUILTIN_REGULAR "read" , readcmd },
8946 { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
8947 { BUILTIN_SPEC_REG "return" , returncmd },
8948 { BUILTIN_SPEC_REG "set" , setcmd },
8949 { BUILTIN_SPEC_REG "shift" , shiftcmd },
Denys Vlasenko82731b42010-05-17 17:49:52 +02008950#if ENABLE_ASH_BASH_COMPAT
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008951 { BUILTIN_SPEC_REG "source" , dotcmd },
Denys Vlasenko82731b42010-05-17 17:49:52 +02008952#endif
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008953#if ENABLE_ASH_BUILTIN_TEST
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008954 { BUILTIN_REGULAR "test" , testcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008955#endif
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008956 { BUILTIN_SPEC_REG "times" , timescmd },
8957 { BUILTIN_SPEC_REG "trap" , trapcmd },
8958 { BUILTIN_REGULAR "true" , truecmd },
8959 { BUILTIN_NOSPEC "type" , typecmd },
8960 { BUILTIN_NOSPEC "ulimit" , ulimitcmd },
8961 { BUILTIN_REGULAR "umask" , umaskcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008962#if ENABLE_ASH_ALIAS
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008963 { BUILTIN_REGULAR "unalias" , unaliascmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008964#endif
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008965 { BUILTIN_SPEC_REG "unset" , unsetcmd },
8966 { BUILTIN_REGULAR "wait" , waitcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008967};
8968
Denis Vlasenko80591b02008-03-25 07:49:43 +00008969/* Should match the above table! */
8970#define COMMANDCMD (builtintab + \
8971 2 + \
8972 1 * ENABLE_ASH_BUILTIN_TEST + \
8973 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
8974 1 * ENABLE_ASH_ALIAS + \
8975 1 * ENABLE_ASH_JOB_CONTROL + \
8976 3)
8977#define EXECCMD (builtintab + \
8978 2 + \
8979 1 * ENABLE_ASH_BUILTIN_TEST + \
8980 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
8981 1 * ENABLE_ASH_ALIAS + \
8982 1 * ENABLE_ASH_JOB_CONTROL + \
8983 3 + \
8984 1 * ENABLE_ASH_CMDCMD + \
8985 1 + \
8986 ENABLE_ASH_BUILTIN_ECHO + \
8987 1)
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008988
8989/*
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008990 * Search the table of builtin commands.
8991 */
8992static struct builtincmd *
8993find_builtin(const char *name)
8994{
8995 struct builtincmd *bp;
8996
8997 bp = bsearch(
Denis Vlasenko80b8b392007-06-25 10:55:35 +00008998 name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008999 pstrcmp
9000 );
9001 return bp;
9002}
9003
9004/*
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00009005 * Execute a simple command.
9006 */
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00009007static int
9008isassignment(const char *p)
Paul Foxc3850c82005-07-20 18:23:39 +00009009{
9010 const char *q = endofname(p);
9011 if (p == q)
9012 return 0;
9013 return *q == '=';
9014}
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009015static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00009016bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00009017{
9018 /* Preserve exitstatus of a previous possible redirection
9019 * as POSIX mandates */
9020 return back_exitstatus;
9021}
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02009022static void
Eric Andersenc470f442003-07-28 09:56:35 +00009023evalcommand(union node *cmd, int flags)
9024{
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00009025 static const struct builtincmd null_bltin = {
9026 "\0\0", bltincmd /* why three NULs? */
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00009027 };
Eric Andersenc470f442003-07-28 09:56:35 +00009028 struct stackmark smark;
9029 union node *argp;
9030 struct arglist arglist;
9031 struct arglist varlist;
9032 char **argv;
9033 int argc;
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009034 const struct strlist *sp;
Eric Andersenc470f442003-07-28 09:56:35 +00009035 struct cmdentry cmdentry;
9036 struct job *jp;
9037 char *lastarg;
9038 const char *path;
9039 int spclbltin;
Eric Andersenc470f442003-07-28 09:56:35 +00009040 int status;
9041 char **nargv;
Paul Foxc3850c82005-07-20 18:23:39 +00009042 struct builtincmd *bcmd;
Denis Vlasenko34c73c42008-08-16 11:48:02 +00009043 smallint cmd_is_exec;
9044 smallint pseudovarflag = 0;
Eric Andersenc470f442003-07-28 09:56:35 +00009045
9046 /* First expand the arguments. */
9047 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
9048 setstackmark(&smark);
9049 back_exitstatus = 0;
9050
9051 cmdentry.cmdtype = CMDBUILTIN;
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00009052 cmdentry.u.cmd = &null_bltin;
Eric Andersenc470f442003-07-28 09:56:35 +00009053 varlist.lastp = &varlist.list;
9054 *varlist.lastp = NULL;
9055 arglist.lastp = &arglist.list;
9056 *arglist.lastp = NULL;
9057
9058 argc = 0;
Denis Vlasenkob012b102007-02-19 22:43:01 +00009059 if (cmd->ncmd.args) {
Paul Foxc3850c82005-07-20 18:23:39 +00009060 bcmd = find_builtin(cmd->ncmd.args->narg.text);
9061 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
9062 }
9063
Eric Andersenc470f442003-07-28 09:56:35 +00009064 for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
9065 struct strlist **spp;
9066
9067 spp = arglist.lastp;
"Vladimir N. Oleynik"bef14d72005-09-05 13:25:11 +00009068 if (pseudovarflag && isassignment(argp->narg.text))
Paul Foxc3850c82005-07-20 18:23:39 +00009069 expandarg(argp, &arglist, EXP_VARTILDE);
9070 else
9071 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
9072
Eric Andersenc470f442003-07-28 09:56:35 +00009073 for (sp = *spp; sp; sp = sp->next)
9074 argc++;
9075 }
9076
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +00009077 argv = nargv = stalloc(sizeof(char *) * (argc + 1));
Denis Vlasenko2da584f2007-02-19 22:44:05 +00009078 for (sp = arglist.list; sp; sp = sp->next) {
Eric Andersenc470f442003-07-28 09:56:35 +00009079 TRACE(("evalcommand arg: %s\n", sp->text));
9080 *nargv++ = sp->text;
9081 }
9082 *nargv = NULL;
9083
9084 lastarg = NULL;
9085 if (iflag && funcnest == 0 && argc > 0)
9086 lastarg = nargv[-1];
9087
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009088 preverrout_fd = 2;
Eric Andersenc470f442003-07-28 09:56:35 +00009089 expredir(cmd->ncmd.redirect);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009090 status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
Eric Andersenc470f442003-07-28 09:56:35 +00009091
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02009092 path = vpath.var_text;
Eric Andersenc470f442003-07-28 09:56:35 +00009093 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
9094 struct strlist **spp;
9095 char *p;
9096
9097 spp = varlist.lastp;
9098 expandarg(argp, &varlist, EXP_VARTILDE);
9099
9100 /*
9101 * Modify the command lookup path, if a PATH= assignment
9102 * is present
9103 */
9104 p = (*spp)->text;
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02009105 if (varcmp(p, path) == 0)
Eric Andersenc470f442003-07-28 09:56:35 +00009106 path = p;
9107 }
9108
9109 /* Print the command if xflag is set. */
9110 if (xflag) {
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009111 int n;
9112 const char *p = " %s";
Eric Andersenc470f442003-07-28 09:56:35 +00009113
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009114 p++;
Denis Vlasenko0de37e12007-10-17 11:08:53 +00009115 fdprintf(preverrout_fd, p, expandstr(ps4val()));
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009116
9117 sp = varlist.list;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +00009118 for (n = 0; n < 2; n++) {
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009119 while (sp) {
Denis Vlasenko0de37e12007-10-17 11:08:53 +00009120 fdprintf(preverrout_fd, p, sp->text);
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009121 sp = sp->next;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +00009122 if (*p == '%') {
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009123 p--;
9124 }
9125 }
9126 sp = arglist.list;
9127 }
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00009128 safe_write(preverrout_fd, "\n", 1);
Eric Andersenc470f442003-07-28 09:56:35 +00009129 }
9130
9131 cmd_is_exec = 0;
9132 spclbltin = -1;
9133
9134 /* Now locate the command. */
9135 if (argc) {
9136 const char *oldpath;
9137 int cmd_flag = DO_ERR;
9138
9139 path += 5;
9140 oldpath = path;
9141 for (;;) {
9142 find_command(argv[0], &cmdentry, cmd_flag, path);
9143 if (cmdentry.cmdtype == CMDUNKNOWN) {
Denys Vlasenko8131eea2009-11-02 14:19:51 +01009144 flush_stdout_stderr();
Denis Vlasenko6514c5e2008-07-24 13:41:37 +00009145 status = 127;
Eric Andersenc470f442003-07-28 09:56:35 +00009146 goto bail;
9147 }
9148
9149 /* implement bltin and command here */
9150 if (cmdentry.cmdtype != CMDBUILTIN)
9151 break;
9152 if (spclbltin < 0)
9153 spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
9154 if (cmdentry.u.cmd == EXECCMD)
Denis Vlasenko34c73c42008-08-16 11:48:02 +00009155 cmd_is_exec = 1;
Denis Vlasenko131ae172007-02-18 13:00:19 +00009156#if ENABLE_ASH_CMDCMD
Eric Andersenc470f442003-07-28 09:56:35 +00009157 if (cmdentry.u.cmd == COMMANDCMD) {
Eric Andersenc470f442003-07-28 09:56:35 +00009158 path = oldpath;
9159 nargv = parse_command_args(argv, &path);
9160 if (!nargv)
9161 break;
9162 argc -= nargv - argv;
9163 argv = nargv;
9164 cmd_flag |= DO_NOFUNC;
9165 } else
9166#endif
9167 break;
9168 }
9169 }
9170
9171 if (status) {
9172 /* We have a redirection error. */
9173 if (spclbltin > 0)
Denis Vlasenkob012b102007-02-19 22:43:01 +00009174 raise_exception(EXERROR);
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009175 bail:
Eric Andersenc470f442003-07-28 09:56:35 +00009176 exitstatus = status;
9177 goto out;
9178 }
9179
9180 /* Execute the command. */
9181 switch (cmdentry.cmdtype) {
Denys Vlasenko42c4b2e2010-05-18 16:13:56 +02009182 default: {
Denis Vlasenkobe54d6b2008-10-27 14:25:52 +00009183
Denis Vlasenko9bc80d72008-04-12 20:07:53 +00009184#if ENABLE_FEATURE_SH_NOFORK
Denys Vlasenko42c4b2e2010-05-18 16:13:56 +02009185/* (1) BUG: if variables are set, we need to fork, or save/restore them
9186 * around run_nofork_applet() call.
9187 * (2) Should this check also be done in forkshell()?
9188 * (perhaps it should, so that "VAR=VAL nofork" at least avoids exec...)
9189 */
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00009190 /* find_command() encodes applet_no as (-2 - applet_no) */
9191 int applet_no = (- cmdentry.u.index - 2);
Denis Vlasenko9bc80d72008-04-12 20:07:53 +00009192 if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
Denis Vlasenko9bc80d72008-04-12 20:07:53 +00009193 listsetvar(varlist.list, VEXPORT|VSTACK);
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00009194 /* run <applet>_main() */
9195 exitstatus = run_nofork_applet(applet_no, argv);
Denis Vlasenko9bc80d72008-04-12 20:07:53 +00009196 break;
9197 }
Denis Vlasenko9bc80d72008-04-12 20:07:53 +00009198#endif
Denys Vlasenko42c4b2e2010-05-18 16:13:56 +02009199 /* Can we avoid forking off? For example, very last command
9200 * in a script or a subshell does not need forking,
9201 * we can just exec it.
9202 */
Denys Vlasenko238bf182010-05-18 15:49:07 +02009203 if (!(flags & EV_EXIT) || may_have_traps) {
Denys Vlasenko42c4b2e2010-05-18 16:13:56 +02009204 /* No, forking off a child is necessary */
Denis Vlasenkob012b102007-02-19 22:43:01 +00009205 INT_OFF;
Denis Vlasenko68404f12008-03-17 09:00:54 +00009206 jp = makejob(/*cmd,*/ 1);
Eric Andersenc470f442003-07-28 09:56:35 +00009207 if (forkshell(jp, cmd, FORK_FG) != 0) {
Denys Vlasenko238bf182010-05-18 15:49:07 +02009208 /* parent */
Eric Andersenc470f442003-07-28 09:56:35 +00009209 exitstatus = waitforjob(jp);
Denis Vlasenkob012b102007-02-19 22:43:01 +00009210 INT_ON;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00009211 TRACE(("forked child exited with %d\n", exitstatus));
Eric Andersenc470f442003-07-28 09:56:35 +00009212 break;
9213 }
Denys Vlasenko238bf182010-05-18 15:49:07 +02009214 /* child */
Denis Vlasenkob012b102007-02-19 22:43:01 +00009215 FORCE_INT_ON;
Denys Vlasenkoc7f95d22010-05-18 15:52:23 +02009216 /* fall through to exec'ing external program */
Eric Andersenc470f442003-07-28 09:56:35 +00009217 }
9218 listsetvar(varlist.list, VEXPORT|VSTACK);
9219 shellexec(argv, path, cmdentry.u.index);
9220 /* NOTREACHED */
Denys Vlasenko42c4b2e2010-05-18 16:13:56 +02009221 } /* default */
Eric Andersenc470f442003-07-28 09:56:35 +00009222 case CMDBUILTIN:
9223 cmdenviron = varlist.list;
9224 if (cmdenviron) {
9225 struct strlist *list = cmdenviron;
9226 int i = VNOSET;
9227 if (spclbltin > 0 || argc == 0) {
9228 i = 0;
9229 if (cmd_is_exec && argc > 1)
9230 i = VEXPORT;
9231 }
9232 listsetvar(list, i);
9233 }
Denis Vlasenkobe54d6b2008-10-27 14:25:52 +00009234 /* Tight loop with builtins only:
9235 * "while kill -0 $child; do true; done"
9236 * will never exit even if $child died, unless we do this
9237 * to reap the zombie and make kill detect that it's gone: */
9238 dowait(DOWAIT_NONBLOCK, NULL);
9239
Eric Andersenc470f442003-07-28 09:56:35 +00009240 if (evalbltin(cmdentry.u.cmd, argc, argv)) {
9241 int exit_status;
Denis Vlasenko7f88e342009-03-19 03:36:18 +00009242 int i = exception_type;
Eric Andersenc470f442003-07-28 09:56:35 +00009243 if (i == EXEXIT)
9244 goto raise;
Eric Andersenc470f442003-07-28 09:56:35 +00009245 exit_status = 2;
Eric Andersenc470f442003-07-28 09:56:35 +00009246 if (i == EXINT)
Denis Vlasenko991a1da2008-02-10 19:02:53 +00009247 exit_status = 128 + SIGINT;
Eric Andersenc470f442003-07-28 09:56:35 +00009248 if (i == EXSIG)
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02009249 exit_status = 128 + pending_sig;
Eric Andersenc470f442003-07-28 09:56:35 +00009250 exitstatus = exit_status;
Eric Andersenc470f442003-07-28 09:56:35 +00009251 if (i == EXINT || spclbltin > 0) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009252 raise:
Denis Vlasenko2da584f2007-02-19 22:44:05 +00009253 longjmp(exception_handler->loc, 1);
Eric Andersenc470f442003-07-28 09:56:35 +00009254 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00009255 FORCE_INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00009256 }
9257 break;
9258
9259 case CMDFUNCTION:
9260 listsetvar(varlist.list, 0);
Denis Vlasenkobe54d6b2008-10-27 14:25:52 +00009261 /* See above for the rationale */
9262 dowait(DOWAIT_NONBLOCK, NULL);
Eric Andersenc470f442003-07-28 09:56:35 +00009263 if (evalfun(cmdentry.u.func, argc, argv, flags))
9264 goto raise;
9265 break;
Denys Vlasenko42c4b2e2010-05-18 16:13:56 +02009266
9267 } /* switch */
Eric Andersenc470f442003-07-28 09:56:35 +00009268
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009269 out:
Denis Vlasenko34c73c42008-08-16 11:48:02 +00009270 popredir(/*drop:*/ cmd_is_exec, /*restore:*/ cmd_is_exec);
Denis Vlasenko6514c5e2008-07-24 13:41:37 +00009271 if (lastarg) {
Eric Andersenc470f442003-07-28 09:56:35 +00009272 /* dsl: I think this is intended to be used to support
9273 * '_' in 'vi' command mode during line editing...
9274 * However I implemented that within libedit itself.
9275 */
9276 setvar("_", lastarg, 0);
Denis Vlasenko6514c5e2008-07-24 13:41:37 +00009277 }
Eric Andersenc470f442003-07-28 09:56:35 +00009278 popstackmark(&smark);
9279}
9280
9281static int
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009282evalbltin(const struct builtincmd *cmd, int argc, char **argv)
9283{
Eric Andersenc470f442003-07-28 09:56:35 +00009284 char *volatile savecmdname;
9285 struct jmploc *volatile savehandler;
9286 struct jmploc jmploc;
9287 int i;
9288
9289 savecmdname = commandname;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009290 i = setjmp(jmploc.loc);
9291 if (i)
Eric Andersenc470f442003-07-28 09:56:35 +00009292 goto cmddone;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00009293 savehandler = exception_handler;
9294 exception_handler = &jmploc;
Eric Andersenc470f442003-07-28 09:56:35 +00009295 commandname = argv[0];
9296 argptr = argv + 1;
9297 optptr = NULL; /* initialize nextopt */
9298 exitstatus = (*cmd->builtin)(argc, argv);
Denis Vlasenkob012b102007-02-19 22:43:01 +00009299 flush_stdout_stderr();
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009300 cmddone:
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009301 exitstatus |= ferror(stdout);
Rob Landleyf296f0b2006-07-06 01:09:21 +00009302 clearerr(stdout);
Eric Andersenc470f442003-07-28 09:56:35 +00009303 commandname = savecmdname;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00009304 exception_handler = savehandler;
Eric Andersenc470f442003-07-28 09:56:35 +00009305
9306 return i;
9307}
9308
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009309static int
9310goodname(const char *p)
Glenn L McGrath16e45d72004-02-04 08:24:39 +00009311{
9312 return !*endofname(p);
9313}
9314
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009315
Glenn L McGrath50812ff2002-08-23 13:14:48 +00009316/*
9317 * Search for a command. This is called before we fork so that the
9318 * location of the command will be available in the parent as well as
Glenn L McGrath16e45d72004-02-04 08:24:39 +00009319 * the child. The check for "goodname" is an overly conservative
9320 * check that the name will not be subject to expansion.
Glenn L McGrath50812ff2002-08-23 13:14:48 +00009321 */
Eric Andersenc470f442003-07-28 09:56:35 +00009322static void
9323prehash(union node *n)
Glenn L McGrath50812ff2002-08-23 13:14:48 +00009324{
9325 struct cmdentry entry;
9326
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +00009327 if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
9328 find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
Glenn L McGrath50812ff2002-08-23 13:14:48 +00009329}
9330
Eric Andersencb57d552001-06-28 07:25:16 +00009331
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00009332/* ============ Builtin commands
9333 *
9334 * Builtin commands whose functions are closely tied to evaluation
9335 * are implemented here.
Eric Andersencb57d552001-06-28 07:25:16 +00009336 */
9337
9338/*
Eric Andersencb57d552001-06-28 07:25:16 +00009339 * Handle break and continue commands. Break, continue, and return are
9340 * all handled by setting the evalskip flag. The evaluation routines
9341 * above all check this flag, and if it is set they start skipping
9342 * commands rather than executing them. The variable skipcount is
9343 * the number of loops to break/continue, or the number of function
9344 * levels to return. (The latter is always 1.) It should probably
9345 * be an error to break out of more loops than exist, but it isn't
9346 * in the standard shell so we don't make it one here.
9347 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009348static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00009349breakcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +00009350{
Denis Vlasenko68404f12008-03-17 09:00:54 +00009351 int n = argv[1] ? number(argv[1]) : 1;
Eric Andersencb57d552001-06-28 07:25:16 +00009352
Aaron Lehmann2aef3a62001-12-31 06:03:12 +00009353 if (n <= 0)
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02009354 ash_msg_and_raise_error(msg_illnum, argv[1]);
Eric Andersencb57d552001-06-28 07:25:16 +00009355 if (n > loopnest)
9356 n = loopnest;
9357 if (n > 0) {
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00009358 evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
Eric Andersencb57d552001-06-28 07:25:16 +00009359 skipcount = n;
9360 }
9361 return 0;
9362}
9363
Eric Andersenc470f442003-07-28 09:56:35 +00009364
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009365/* ============ input.c
9366 *
Eric Andersen90898442003-08-06 11:20:52 +00009367 * This implements the input routines used by the parser.
Eric Andersencb57d552001-06-28 07:25:16 +00009368 */
Denis Vlasenko99eb8502007-02-23 21:09:49 +00009369
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009370enum {
9371 INPUT_PUSH_FILE = 1,
9372 INPUT_NOFILE_OK = 2,
9373};
Eric Andersencb57d552001-06-28 07:25:16 +00009374
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009375static smallint checkkwd;
Denis Vlasenko99eb8502007-02-23 21:09:49 +00009376/* values of checkkwd variable */
9377#define CHKALIAS 0x1
9378#define CHKKWD 0x2
9379#define CHKNL 0x4
9380
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009381/*
9382 * Push a string back onto the input at this current parsefile level.
9383 * We handle aliases this way.
9384 */
9385#if !ENABLE_ASH_ALIAS
9386#define pushstring(s, ap) pushstring(s)
9387#endif
9388static void
9389pushstring(char *s, struct alias *ap)
9390{
9391 struct strpush *sp;
9392 int len;
9393
9394 len = strlen(s);
9395 INT_OFF;
9396 if (g_parsefile->strpush) {
9397 sp = ckzalloc(sizeof(*sp));
9398 sp->prev = g_parsefile->strpush;
9399 } else {
9400 sp = &(g_parsefile->basestrpush);
9401 }
9402 g_parsefile->strpush = sp;
9403 sp->prev_string = g_parsefile->next_to_pgetc;
9404 sp->prev_left_in_line = g_parsefile->left_in_line;
9405#if ENABLE_ASH_ALIAS
9406 sp->ap = ap;
9407 if (ap) {
9408 ap->flag |= ALIASINUSE;
9409 sp->string = s;
9410 }
9411#endif
9412 g_parsefile->next_to_pgetc = s;
9413 g_parsefile->left_in_line = len;
9414 INT_ON;
9415}
9416
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009417static void
9418popstring(void)
Eric Andersenc470f442003-07-28 09:56:35 +00009419{
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009420 struct strpush *sp = g_parsefile->strpush;
Eric Andersenc470f442003-07-28 09:56:35 +00009421
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009422 INT_OFF;
Denis Vlasenko131ae172007-02-18 13:00:19 +00009423#if ENABLE_ASH_ALIAS
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009424 if (sp->ap) {
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009425 if (g_parsefile->next_to_pgetc[-1] == ' '
9426 || g_parsefile->next_to_pgetc[-1] == '\t'
9427 ) {
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009428 checkkwd |= CHKALIAS;
Glenn L McGrath28939ad2004-07-21 10:20:19 +00009429 }
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009430 if (sp->string != sp->ap->val) {
9431 free(sp->string);
9432 }
9433 sp->ap->flag &= ~ALIASINUSE;
9434 if (sp->ap->flag & ALIASDEAD) {
9435 unalias(sp->ap->name);
9436 }
Glenn L McGrath28939ad2004-07-21 10:20:19 +00009437 }
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009438#endif
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009439 g_parsefile->next_to_pgetc = sp->prev_string;
9440 g_parsefile->left_in_line = sp->prev_left_in_line;
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009441 g_parsefile->strpush = sp->prev;
9442 if (sp != &(g_parsefile->basestrpush))
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009443 free(sp);
9444 INT_ON;
9445}
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009446
Denis Vlasenkoe27dafd2008-11-28 04:01:03 +00009447//FIXME: BASH_COMPAT with "...&" does TWO pungetc():
9448//it peeks whether it is &>, and then pushes back both chars.
9449//This function needs to save last *next_to_pgetc to buf[0]
9450//to make two pungetc() reliable. Currently,
9451// pgetc (out of buf: does preadfd), pgetc, pungetc, pungetc won't work...
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009452static int
9453preadfd(void)
Eric Andersencb57d552001-06-28 07:25:16 +00009454{
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00009455 int nr;
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00009456 char *buf = g_parsefile->buf;
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00009457
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009458 g_parsefile->next_to_pgetc = buf;
Denis Vlasenko38f63192007-01-22 09:03:07 +00009459#if ENABLE_FEATURE_EDITING
Denis Vlasenko85c24712008-03-17 09:04:04 +00009460 retry:
Denys Vlasenko79b3d422010-06-03 04:29:08 +02009461 if (!iflag || g_parsefile->pf_fd != STDIN_FILENO)
9462 nr = nonblock_safe_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
Eric Andersenc470f442003-07-28 09:56:35 +00009463 else {
Denis Vlasenko38f63192007-01-22 09:03:07 +00009464#if ENABLE_FEATURE_TAB_COMPLETION
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009465 line_input_state->path_lookup = pathval();
Eric Andersen4a79c0e2004-09-08 10:01:07 +00009466#endif
Denys Vlasenko82dd14a2010-05-17 10:10:01 +02009467 nr = read_line_input(cmdedit_prompt, buf, IBUFSIZ, line_input_state);
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009468 if (nr == 0) {
9469 /* Ctrl+C pressed */
9470 if (trap[SIGINT]) {
Glenn L McGrath16e45d72004-02-04 08:24:39 +00009471 buf[0] = '\n';
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009472 buf[1] = '\0';
Glenn L McGrath16e45d72004-02-04 08:24:39 +00009473 raise(SIGINT);
9474 return 1;
9475 }
Eric Andersenc470f442003-07-28 09:56:35 +00009476 goto retry;
9477 }
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009478 if (nr < 0 && errno == 0) {
Denis Vlasenko9cb220b2007-12-09 10:03:28 +00009479 /* Ctrl+D pressed */
Eric Andersenc470f442003-07-28 09:56:35 +00009480 nr = 0;
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00009481 }
Eric Andersencb57d552001-06-28 07:25:16 +00009482 }
9483#else
Denys Vlasenko161bb8f2010-06-06 05:07:11 +02009484 nr = nonblock_safe_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
Eric Andersencb57d552001-06-28 07:25:16 +00009485#endif
9486
Denis Vlasenkoe376d452008-02-20 22:23:24 +00009487#if 0
9488/* nonblock_safe_read() handles this problem */
Eric Andersencb57d552001-06-28 07:25:16 +00009489 if (nr < 0) {
Eric Andersencb57d552001-06-28 07:25:16 +00009490 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
Denis Vlasenkod37f2222007-08-19 13:42:08 +00009491 int flags = fcntl(0, F_GETFL);
Denis Vlasenko9cb220b2007-12-09 10:03:28 +00009492 if (flags >= 0 && (flags & O_NONBLOCK)) {
9493 flags &= ~O_NONBLOCK;
Eric Andersencb57d552001-06-28 07:25:16 +00009494 if (fcntl(0, F_SETFL, flags) >= 0) {
9495 out2str("sh: turning off NDELAY mode\n");
9496 goto retry;
9497 }
9498 }
9499 }
9500 }
Denis Vlasenkoe376d452008-02-20 22:23:24 +00009501#endif
Eric Andersencb57d552001-06-28 07:25:16 +00009502 return nr;
9503}
9504
9505/*
9506 * Refill the input buffer and return the next input character:
9507 *
9508 * 1) If a string was pushed back on the input, pop it;
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009509 * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
9510 * or we are reading from a string so we can't refill the buffer,
9511 * return EOF.
Denys Vlasenko883cea42009-07-11 15:31:59 +02009512 * 3) If there is more stuff in this buffer, use it else call read to fill it.
Eric Andersencb57d552001-06-28 07:25:16 +00009513 * 4) Process input up to the next newline, deleting nul characters.
9514 */
Denis Vlasenko727752d2008-11-28 03:41:47 +00009515//#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
9516#define pgetc_debug(...) ((void)0)
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009517static int
Eric Andersenc470f442003-07-28 09:56:35 +00009518preadbuffer(void)
Eric Andersencb57d552001-06-28 07:25:16 +00009519{
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009520 char *q;
Eric Andersencb57d552001-06-28 07:25:16 +00009521 int more;
Eric Andersencb57d552001-06-28 07:25:16 +00009522
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009523 while (g_parsefile->strpush) {
Denis Vlasenko131ae172007-02-18 13:00:19 +00009524#if ENABLE_ASH_ALIAS
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009525 if (g_parsefile->left_in_line == -1
9526 && g_parsefile->strpush->ap
9527 && g_parsefile->next_to_pgetc[-1] != ' '
9528 && g_parsefile->next_to_pgetc[-1] != '\t'
Denis Vlasenko16898402008-11-25 01:34:52 +00009529 ) {
Denis Vlasenko727752d2008-11-28 03:41:47 +00009530 pgetc_debug("preadbuffer PEOA");
Eric Andersencb57d552001-06-28 07:25:16 +00009531 return PEOA;
9532 }
Eric Andersen2870d962001-07-02 17:27:21 +00009533#endif
Eric Andersencb57d552001-06-28 07:25:16 +00009534 popstring();
Denis Vlasenko727752d2008-11-28 03:41:47 +00009535 /* try "pgetc" now: */
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009536 pgetc_debug("preadbuffer internal pgetc at %d:%p'%s'",
9537 g_parsefile->left_in_line,
9538 g_parsefile->next_to_pgetc,
9539 g_parsefile->next_to_pgetc);
9540 if (--g_parsefile->left_in_line >= 0)
9541 return (unsigned char)(*g_parsefile->next_to_pgetc++);
Eric Andersencb57d552001-06-28 07:25:16 +00009542 }
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009543 /* on both branches above g_parsefile->left_in_line < 0.
Denis Vlasenko727752d2008-11-28 03:41:47 +00009544 * "pgetc" needs refilling.
9545 */
9546
Denis Vlasenkoe27dafd2008-11-28 04:01:03 +00009547 /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009548 * pungetc() may increment it a few times.
Denis Vlasenkoe27dafd2008-11-28 04:01:03 +00009549 * Assuming it won't increment it to less than -90.
Denis Vlasenko727752d2008-11-28 03:41:47 +00009550 */
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009551 if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
Denis Vlasenko727752d2008-11-28 03:41:47 +00009552 pgetc_debug("preadbuffer PEOF1");
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009553 /* even in failure keep left_in_line and next_to_pgetc
9554 * in lock step, for correct multi-layer pungetc.
9555 * left_in_line was decremented before preadbuffer(),
9556 * must inc next_to_pgetc: */
9557 g_parsefile->next_to_pgetc++;
Eric Andersencb57d552001-06-28 07:25:16 +00009558 return PEOF;
Denis Vlasenko727752d2008-11-28 03:41:47 +00009559 }
Eric Andersencb57d552001-06-28 07:25:16 +00009560
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009561 more = g_parsefile->left_in_buffer;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009562 if (more <= 0) {
Denis Vlasenko727752d2008-11-28 03:41:47 +00009563 flush_stdout_stderr();
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009564 again:
9565 more = preadfd();
9566 if (more <= 0) {
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009567 /* don't try reading again */
9568 g_parsefile->left_in_line = -99;
Denis Vlasenko727752d2008-11-28 03:41:47 +00009569 pgetc_debug("preadbuffer PEOF2");
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009570 g_parsefile->next_to_pgetc++;
Eric Andersencb57d552001-06-28 07:25:16 +00009571 return PEOF;
9572 }
9573 }
9574
Denis Vlasenko727752d2008-11-28 03:41:47 +00009575 /* Find out where's the end of line.
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009576 * Set g_parsefile->left_in_line
9577 * and g_parsefile->left_in_buffer acordingly.
Denis Vlasenko727752d2008-11-28 03:41:47 +00009578 * NUL chars are deleted.
9579 */
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009580 q = g_parsefile->next_to_pgetc;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009581 for (;;) {
Denis Vlasenko727752d2008-11-28 03:41:47 +00009582 char c;
Eric Andersencb57d552001-06-28 07:25:16 +00009583
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009584 more--;
Eric Andersenc470f442003-07-28 09:56:35 +00009585
Denis Vlasenko727752d2008-11-28 03:41:47 +00009586 c = *q;
9587 if (c == '\0') {
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009588 memmove(q, q + 1, more);
Denis Vlasenko727752d2008-11-28 03:41:47 +00009589 } else {
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009590 q++;
9591 if (c == '\n') {
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009592 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009593 break;
9594 }
Eric Andersencb57d552001-06-28 07:25:16 +00009595 }
9596
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009597 if (more <= 0) {
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009598 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9599 if (g_parsefile->left_in_line < 0)
Eric Andersencb57d552001-06-28 07:25:16 +00009600 goto again;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009601 break;
Eric Andersencb57d552001-06-28 07:25:16 +00009602 }
9603 }
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009604 g_parsefile->left_in_buffer = more;
Eric Andersencb57d552001-06-28 07:25:16 +00009605
Eric Andersencb57d552001-06-28 07:25:16 +00009606 if (vflag) {
Denis Vlasenko727752d2008-11-28 03:41:47 +00009607 char save = *q;
9608 *q = '\0';
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009609 out2str(g_parsefile->next_to_pgetc);
Denis Vlasenko727752d2008-11-28 03:41:47 +00009610 *q = save;
Eric Andersencb57d552001-06-28 07:25:16 +00009611 }
9612
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009613 pgetc_debug("preadbuffer at %d:%p'%s'",
9614 g_parsefile->left_in_line,
9615 g_parsefile->next_to_pgetc,
9616 g_parsefile->next_to_pgetc);
Denys Vlasenkocd716832009-11-28 22:14:02 +01009617 return (unsigned char)*g_parsefile->next_to_pgetc++;
Eric Andersencb57d552001-06-28 07:25:16 +00009618}
9619
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009620#define pgetc_as_macro() \
9621 (--g_parsefile->left_in_line >= 0 \
Denys Vlasenkocd716832009-11-28 22:14:02 +01009622 ? (unsigned char)*g_parsefile->next_to_pgetc++ \
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009623 : preadbuffer() \
9624 )
Denis Vlasenko727752d2008-11-28 03:41:47 +00009625
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009626static int
9627pgetc(void)
9628{
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009629 pgetc_debug("pgetc_fast at %d:%p'%s'",
9630 g_parsefile->left_in_line,
9631 g_parsefile->next_to_pgetc,
9632 g_parsefile->next_to_pgetc);
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009633 return pgetc_as_macro();
9634}
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00009635
9636#if ENABLE_ASH_OPTIMIZE_FOR_SIZE
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01009637# define pgetc_fast() pgetc()
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009638#else
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01009639# define pgetc_fast() pgetc_as_macro()
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009640#endif
9641
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009642#if ENABLE_ASH_ALIAS
9643static int
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01009644pgetc_without_PEOA(void)
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009645{
9646 int c;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009647 do {
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009648 pgetc_debug("pgetc_fast at %d:%p'%s'",
9649 g_parsefile->left_in_line,
9650 g_parsefile->next_to_pgetc,
9651 g_parsefile->next_to_pgetc);
Denis Vlasenko834dee72008-10-07 09:18:30 +00009652 c = pgetc_fast();
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009653 } while (c == PEOA);
9654 return c;
9655}
9656#else
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01009657# define pgetc_without_PEOA() pgetc()
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009658#endif
9659
9660/*
9661 * Read a line from the script.
9662 */
9663static char *
9664pfgets(char *line, int len)
9665{
9666 char *p = line;
9667 int nleft = len;
9668 int c;
9669
9670 while (--nleft > 0) {
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01009671 c = pgetc_without_PEOA();
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009672 if (c == PEOF) {
9673 if (p == line)
9674 return NULL;
9675 break;
9676 }
9677 *p++ = c;
9678 if (c == '\n')
9679 break;
9680 }
9681 *p = '\0';
9682 return line;
9683}
9684
Eric Andersenc470f442003-07-28 09:56:35 +00009685/*
9686 * Undo the last call to pgetc. Only one character may be pushed back.
9687 * PEOF may be pushed back.
9688 */
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009689static void
Eric Andersenc470f442003-07-28 09:56:35 +00009690pungetc(void)
9691{
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009692 g_parsefile->left_in_line++;
9693 g_parsefile->next_to_pgetc--;
9694 pgetc_debug("pushed back to %d:%p'%s'",
9695 g_parsefile->left_in_line,
9696 g_parsefile->next_to_pgetc,
9697 g_parsefile->next_to_pgetc);
Eric Andersencb57d552001-06-28 07:25:16 +00009698}
9699
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009700/*
9701 * To handle the "." command, a stack of input files is used. Pushfile
9702 * adds a new entry to the stack and popfile restores the previous level.
9703 */
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009704static void
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009705pushfile(void)
Eric Andersenc470f442003-07-28 09:56:35 +00009706{
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009707 struct parsefile *pf;
9708
Denis Vlasenko597906c2008-02-20 16:38:54 +00009709 pf = ckzalloc(sizeof(*pf));
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009710 pf->prev = g_parsefile;
Denys Vlasenko79b3d422010-06-03 04:29:08 +02009711 pf->pf_fd = -1;
Denis Vlasenko597906c2008-02-20 16:38:54 +00009712 /*pf->strpush = NULL; - ckzalloc did it */
9713 /*pf->basestrpush.prev = NULL;*/
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009714 g_parsefile = pf;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009715}
9716
9717static void
9718popfile(void)
9719{
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009720 struct parsefile *pf = g_parsefile;
Eric Andersenc470f442003-07-28 09:56:35 +00009721
Denis Vlasenkob012b102007-02-19 22:43:01 +00009722 INT_OFF;
Denys Vlasenko79b3d422010-06-03 04:29:08 +02009723 if (pf->pf_fd >= 0)
9724 close(pf->pf_fd);
Denis Vlasenko60818682007-09-28 22:07:23 +00009725 free(pf->buf);
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009726 while (pf->strpush)
9727 popstring();
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009728 g_parsefile = pf->prev;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009729 free(pf);
Denis Vlasenkob012b102007-02-19 22:43:01 +00009730 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00009731}
9732
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009733/*
9734 * Return to top level.
9735 */
9736static void
9737popallfiles(void)
9738{
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009739 while (g_parsefile != &basepf)
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009740 popfile();
9741}
9742
9743/*
9744 * Close the file(s) that the shell is reading commands from. Called
9745 * after a fork is done.
9746 */
9747static void
9748closescript(void)
9749{
9750 popallfiles();
Denys Vlasenko79b3d422010-06-03 04:29:08 +02009751 if (g_parsefile->pf_fd > 0) {
9752 close(g_parsefile->pf_fd);
9753 g_parsefile->pf_fd = 0;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009754 }
9755}
9756
9757/*
9758 * Like setinputfile, but takes an open file descriptor. Call this with
9759 * interrupts off.
9760 */
9761static void
9762setinputfd(int fd, int push)
9763{
Denis Vlasenko96e1b382007-09-30 23:50:48 +00009764 close_on_exec_on(fd);
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009765 if (push) {
9766 pushfile();
Denis Vlasenko727752d2008-11-28 03:41:47 +00009767 g_parsefile->buf = NULL;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009768 }
Denys Vlasenko79b3d422010-06-03 04:29:08 +02009769 g_parsefile->pf_fd = fd;
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009770 if (g_parsefile->buf == NULL)
9771 g_parsefile->buf = ckmalloc(IBUFSIZ);
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009772 g_parsefile->left_in_buffer = 0;
9773 g_parsefile->left_in_line = 0;
9774 g_parsefile->linno = 1;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009775}
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009776
Eric Andersenc470f442003-07-28 09:56:35 +00009777/*
9778 * Set the input to take input from a file. If push is set, push the
9779 * old input onto the stack first.
9780 */
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009781static int
9782setinputfile(const char *fname, int flags)
Eric Andersenc470f442003-07-28 09:56:35 +00009783{
9784 int fd;
9785 int fd2;
9786
Denis Vlasenkob012b102007-02-19 22:43:01 +00009787 INT_OFF;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009788 fd = open(fname, O_RDONLY);
9789 if (fd < 0) {
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009790 if (flags & INPUT_NOFILE_OK)
9791 goto out;
Denis Vlasenko9604e1b2009-03-03 18:47:56 +00009792 ash_msg_and_raise_error("can't open '%s'", fname);
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009793 }
Eric Andersenc470f442003-07-28 09:56:35 +00009794 if (fd < 10) {
9795 fd2 = copyfd(fd, 10);
9796 close(fd);
9797 if (fd2 < 0)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00009798 ash_msg_and_raise_error("out of file descriptors");
Eric Andersenc470f442003-07-28 09:56:35 +00009799 fd = fd2;
9800 }
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009801 setinputfd(fd, flags & INPUT_PUSH_FILE);
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009802 out:
Denis Vlasenkob012b102007-02-19 22:43:01 +00009803 INT_ON;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009804 return fd;
Eric Andersenc470f442003-07-28 09:56:35 +00009805}
9806
Eric Andersencb57d552001-06-28 07:25:16 +00009807/*
9808 * Like setinputfile, but takes input from a string.
9809 */
Eric Andersenc470f442003-07-28 09:56:35 +00009810static void
9811setinputstring(char *string)
Eric Andersen62483552001-07-10 06:09:16 +00009812{
Denis Vlasenkob012b102007-02-19 22:43:01 +00009813 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +00009814 pushfile();
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009815 g_parsefile->next_to_pgetc = string;
9816 g_parsefile->left_in_line = strlen(string);
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009817 g_parsefile->buf = NULL;
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009818 g_parsefile->linno = 1;
Denis Vlasenkob012b102007-02-19 22:43:01 +00009819 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00009820}
9821
9822
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00009823/* ============ mail.c
9824 *
9825 * Routines to check for mail.
Eric Andersencb57d552001-06-28 07:25:16 +00009826 */
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00009827
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00009828#if ENABLE_ASH_MAIL
Eric Andersencb57d552001-06-28 07:25:16 +00009829
Eric Andersencb57d552001-06-28 07:25:16 +00009830#define MAXMBOXES 10
9831
Eric Andersenc470f442003-07-28 09:56:35 +00009832/* times of mailboxes */
9833static time_t mailtime[MAXMBOXES];
9834/* Set if MAIL or MAILPATH is changed. */
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +00009835static smallint mail_var_path_changed;
Eric Andersencb57d552001-06-28 07:25:16 +00009836
Eric Andersencb57d552001-06-28 07:25:16 +00009837/*
Eric Andersenc470f442003-07-28 09:56:35 +00009838 * Print appropriate message(s) if mail has arrived.
9839 * If mail_var_path_changed is set,
9840 * then the value of MAIL has mail_var_path_changed,
9841 * so we just update the values.
Eric Andersencb57d552001-06-28 07:25:16 +00009842 */
Eric Andersenc470f442003-07-28 09:56:35 +00009843static void
9844chkmail(void)
Eric Andersencb57d552001-06-28 07:25:16 +00009845{
Eric Andersencb57d552001-06-28 07:25:16 +00009846 const char *mpath;
9847 char *p;
9848 char *q;
Eric Andersenc470f442003-07-28 09:56:35 +00009849 time_t *mtp;
Eric Andersencb57d552001-06-28 07:25:16 +00009850 struct stackmark smark;
9851 struct stat statb;
9852
Eric Andersencb57d552001-06-28 07:25:16 +00009853 setstackmark(&smark);
Eric Andersenc470f442003-07-28 09:56:35 +00009854 mpath = mpathset() ? mpathval() : mailval();
9855 for (mtp = mailtime; mtp < mailtime + MAXMBOXES; mtp++) {
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02009856 p = path_advance(&mpath, nullstr);
Eric Andersencb57d552001-06-28 07:25:16 +00009857 if (p == NULL)
9858 break;
9859 if (*p == '\0')
9860 continue;
Denis Vlasenkof7d56652008-03-25 05:51:41 +00009861 for (q = p; *q; q++)
9862 continue;
Denis Vlasenkoa7189f02006-11-17 20:29:00 +00009863#if DEBUG
Eric Andersencb57d552001-06-28 07:25:16 +00009864 if (q[-1] != '/')
9865 abort();
9866#endif
Eric Andersenc470f442003-07-28 09:56:35 +00009867 q[-1] = '\0'; /* delete trailing '/' */
9868 if (stat(p, &statb) < 0) {
9869 *mtp = 0;
9870 continue;
Eric Andersencb57d552001-06-28 07:25:16 +00009871 }
Eric Andersenc470f442003-07-28 09:56:35 +00009872 if (!mail_var_path_changed && statb.st_mtime != *mtp) {
9873 fprintf(
Denys Vlasenkoea8b2522010-06-02 12:57:26 +02009874 stderr, "%s\n",
Eric Andersenc470f442003-07-28 09:56:35 +00009875 pathopt ? pathopt : "you have mail"
9876 );
9877 }
9878 *mtp = statb.st_mtime;
Eric Andersencb57d552001-06-28 07:25:16 +00009879 }
Eric Andersenc470f442003-07-28 09:56:35 +00009880 mail_var_path_changed = 0;
Eric Andersencb57d552001-06-28 07:25:16 +00009881 popstackmark(&smark);
9882}
Eric Andersencb57d552001-06-28 07:25:16 +00009883
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009884static void FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00009885changemail(const char *val UNUSED_PARAM)
Eric Andersenc470f442003-07-28 09:56:35 +00009886{
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +00009887 mail_var_path_changed = 1;
Eric Andersenc470f442003-07-28 09:56:35 +00009888}
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00009889
Denis Vlasenko131ae172007-02-18 13:00:19 +00009890#endif /* ASH_MAIL */
Eric Andersenc470f442003-07-28 09:56:35 +00009891
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00009892
9893/* ============ ??? */
9894
Eric Andersencb57d552001-06-28 07:25:16 +00009895/*
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009896 * Set the shell parameters.
Eric Andersencb57d552001-06-28 07:25:16 +00009897 */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009898static void
9899setparam(char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +00009900{
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009901 char **newparam;
9902 char **ap;
9903 int nparam;
Eric Andersencb57d552001-06-28 07:25:16 +00009904
Denis Vlasenkof7d56652008-03-25 05:51:41 +00009905 for (nparam = 0; argv[nparam]; nparam++)
9906 continue;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009907 ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
9908 while (*argv) {
9909 *ap++ = ckstrdup(*argv++);
Eric Andersencb57d552001-06-28 07:25:16 +00009910 }
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009911 *ap = NULL;
9912 freeparam(&shellparam);
Denis Vlasenko01631112007-12-16 17:20:38 +00009913 shellparam.malloced = 1;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009914 shellparam.nparam = nparam;
9915 shellparam.p = newparam;
9916#if ENABLE_ASH_GETOPTS
9917 shellparam.optind = 1;
9918 shellparam.optoff = -1;
9919#endif
Eric Andersencb57d552001-06-28 07:25:16 +00009920}
9921
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00009922/*
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009923 * Process shell options. The global variable argptr contains a pointer
9924 * to the argument list; we advance it past the options.
Denis Vlasenko94e87bc2008-02-14 16:51:58 +00009925 *
9926 * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
9927 * For a non-interactive shell, an error condition encountered
9928 * by a special built-in ... shall cause the shell to write a diagnostic message
9929 * to standard error and exit as shown in the following table:
Denis Vlasenko56244732008-02-17 15:14:04 +00009930 * Error Special Built-In
Denis Vlasenko94e87bc2008-02-14 16:51:58 +00009931 * ...
9932 * Utility syntax error (option or operand error) Shall exit
9933 * ...
9934 * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
9935 * we see that bash does not do that (set "finishes" with error code 1 instead,
9936 * and shell continues), and people rely on this behavior!
9937 * Testcase:
9938 * set -o barfoo 2>/dev/null
9939 * echo $?
9940 *
9941 * Oh well. Let's mimic that.
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00009942 */
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009943static int
Denis Vlasenkodddfaff2008-05-06 15:30:27 +00009944plus_minus_o(char *name, int val)
Eric Andersen62483552001-07-10 06:09:16 +00009945{
9946 int i;
9947
Denis Vlasenkoa624c112007-02-19 22:45:43 +00009948 if (name) {
9949 for (i = 0; i < NOPTS; i++) {
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00009950 if (strcmp(name, optnames(i)) == 0) {
Eric Andersenc470f442003-07-28 09:56:35 +00009951 optlist[i] = val;
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009952 return 0;
Eric Andersen62483552001-07-10 06:09:16 +00009953 }
Denis Vlasenkoa624c112007-02-19 22:45:43 +00009954 }
Denis Vlasenkodddfaff2008-05-06 15:30:27 +00009955 ash_msg("illegal option %co %s", val ? '-' : '+', name);
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009956 return 1;
Eric Andersen62483552001-07-10 06:09:16 +00009957 }
Denis Vlasenko6b06cb82008-05-15 21:30:45 +00009958 for (i = 0; i < NOPTS; i++) {
Denis Vlasenkodddfaff2008-05-06 15:30:27 +00009959 if (val) {
9960 out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
9961 } else {
9962 out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
9963 }
Denis Vlasenko6b06cb82008-05-15 21:30:45 +00009964 }
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009965 return 0;
Eric Andersen62483552001-07-10 06:09:16 +00009966}
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009967static void
9968setoption(int flag, int val)
9969{
9970 int i;
9971
9972 for (i = 0; i < NOPTS; i++) {
9973 if (optletters(i) == flag) {
9974 optlist[i] = val;
9975 return;
9976 }
9977 }
Denis Vlasenkodddfaff2008-05-06 15:30:27 +00009978 ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009979 /* NOTREACHED */
9980}
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009981static int
Eric Andersenc470f442003-07-28 09:56:35 +00009982options(int cmdline)
Eric Andersencb57d552001-06-28 07:25:16 +00009983{
9984 char *p;
9985 int val;
9986 int c;
9987
9988 if (cmdline)
9989 minusc = NULL;
9990 while ((p = *argptr) != NULL) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009991 c = *p++;
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +00009992 if (c != '-' && c != '+')
9993 break;
9994 argptr++;
9995 val = 0; /* val = 0 if c == '+' */
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009996 if (c == '-') {
Eric Andersencb57d552001-06-28 07:25:16 +00009997 val = 1;
Denis Vlasenko9f739442006-12-16 23:49:13 +00009998 if (p[0] == '\0' || LONE_DASH(p)) {
Eric Andersen2870d962001-07-02 17:27:21 +00009999 if (!cmdline) {
10000 /* "-" means turn off -x and -v */
10001 if (p[0] == '\0')
10002 xflag = vflag = 0;
10003 /* "--" means reset params */
10004 else if (*argptr == NULL)
Eric Andersencb57d552001-06-28 07:25:16 +000010005 setparam(argptr);
Eric Andersen2870d962001-07-02 17:27:21 +000010006 }
Eric Andersenc470f442003-07-28 09:56:35 +000010007 break; /* "-" or "--" terminates options */
Eric Andersencb57d552001-06-28 07:25:16 +000010008 }
Eric Andersencb57d552001-06-28 07:25:16 +000010009 }
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +000010010 /* first char was + or - */
Eric Andersencb57d552001-06-28 07:25:16 +000010011 while ((c = *p++) != '\0') {
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +000010012 /* bash 3.2 indeed handles -c CMD and +c CMD the same */
Eric Andersencb57d552001-06-28 07:25:16 +000010013 if (c == 'c' && cmdline) {
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +000010014 minusc = p; /* command is after shell args */
Eric Andersencb57d552001-06-28 07:25:16 +000010015 } else if (c == 'o') {
Denis Vlasenkodddfaff2008-05-06 15:30:27 +000010016 if (plus_minus_o(*argptr, val)) {
Denis Vlasenko28bf6712008-02-14 15:01:47 +000010017 /* it already printed err message */
10018 return 1; /* error */
10019 }
Eric Andersencb57d552001-06-28 07:25:16 +000010020 if (*argptr)
10021 argptr++;
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +000010022 } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
10023 isloginsh = 1;
10024 /* bash does not accept +-login, we also won't */
10025 } else if (cmdline && val && (c == '-')) { /* long options */
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010026 if (strcmp(p, "login") == 0)
Robert Griebl64f70cc2002-05-14 23:22:06 +000010027 isloginsh = 1;
10028 break;
Eric Andersencb57d552001-06-28 07:25:16 +000010029 } else {
10030 setoption(c, val);
10031 }
10032 }
10033 }
Denis Vlasenko28bf6712008-02-14 15:01:47 +000010034 return 0;
Eric Andersencb57d552001-06-28 07:25:16 +000010035}
10036
Eric Andersencb57d552001-06-28 07:25:16 +000010037/*
Eric Andersencb57d552001-06-28 07:25:16 +000010038 * The shift builtin command.
10039 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010040static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000010041shiftcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +000010042{
10043 int n;
10044 char **ap1, **ap2;
10045
10046 n = 1;
Denis Vlasenko68404f12008-03-17 09:00:54 +000010047 if (argv[1])
Eric Andersencb57d552001-06-28 07:25:16 +000010048 n = number(argv[1]);
10049 if (n > shellparam.nparam)
Denis Vlasenkoc90e1be2008-07-30 15:35:05 +000010050 n = 0; /* bash compat, was = shellparam.nparam; */
Denis Vlasenkob012b102007-02-19 22:43:01 +000010051 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +000010052 shellparam.nparam -= n;
Denis Vlasenko2da584f2007-02-19 22:44:05 +000010053 for (ap1 = shellparam.p; --n >= 0; ap1++) {
Denis Vlasenko01631112007-12-16 17:20:38 +000010054 if (shellparam.malloced)
Denis Vlasenkob012b102007-02-19 22:43:01 +000010055 free(*ap1);
Eric Andersencb57d552001-06-28 07:25:16 +000010056 }
10057 ap2 = shellparam.p;
Denis Vlasenkof7d56652008-03-25 05:51:41 +000010058 while ((*ap2++ = *ap1++) != NULL)
10059 continue;
Denis Vlasenko131ae172007-02-18 13:00:19 +000010060#if ENABLE_ASH_GETOPTS
Eric Andersencb57d552001-06-28 07:25:16 +000010061 shellparam.optind = 1;
10062 shellparam.optoff = -1;
Eric Andersenc470f442003-07-28 09:56:35 +000010063#endif
Denis Vlasenkob012b102007-02-19 22:43:01 +000010064 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +000010065 return 0;
10066}
10067
Eric Andersencb57d552001-06-28 07:25:16 +000010068/*
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010069 * POSIX requires that 'set' (but not export or readonly) output the
10070 * variables in lexicographic order - by the locale's collating order (sigh).
10071 * Maybe we could keep them in an ordered balanced binary tree
10072 * instead of hashed lists.
10073 * For now just roll 'em through qsort for printing...
10074 */
10075static int
10076showvars(const char *sep_prefix, int on, int off)
10077{
10078 const char *sep;
10079 char **ep, **epend;
10080
10081 ep = listvars(on, off, &epend);
10082 qsort(ep, epend - ep, sizeof(char *), vpcmp);
10083
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +000010084 sep = *sep_prefix ? " " : sep_prefix;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010085
10086 for (; ep < epend; ep++) {
10087 const char *p;
10088 const char *q;
10089
10090 p = strchrnul(*ep, '=');
10091 q = nullstr;
10092 if (*p)
10093 q = single_quote(++p);
10094 out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
10095 }
10096 return 0;
10097}
10098
10099/*
Eric Andersencb57d552001-06-28 07:25:16 +000010100 * The set command builtin.
10101 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010102static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000010103setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersencb57d552001-06-28 07:25:16 +000010104{
Denis Vlasenko28bf6712008-02-14 15:01:47 +000010105 int retval;
10106
Denis Vlasenko68404f12008-03-17 09:00:54 +000010107 if (!argv[1])
Eric Andersenc470f442003-07-28 09:56:35 +000010108 return showvars(nullstr, 0, VUNSET);
Denis Vlasenkob012b102007-02-19 22:43:01 +000010109 INT_OFF;
Denis Vlasenko28bf6712008-02-14 15:01:47 +000010110 retval = 1;
10111 if (!options(0)) { /* if no parse error... */
10112 retval = 0;
10113 optschanged();
10114 if (*argptr != NULL) {
10115 setparam(argptr);
10116 }
Eric Andersencb57d552001-06-28 07:25:16 +000010117 }
Denis Vlasenkob012b102007-02-19 22:43:01 +000010118 INT_ON;
Denis Vlasenko28bf6712008-02-14 15:01:47 +000010119 return retval;
Eric Andersencb57d552001-06-28 07:25:16 +000010120}
10121
Denis Vlasenko131ae172007-02-18 13:00:19 +000010122#if ENABLE_ASH_RANDOM_SUPPORT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010123static void FAST_FUNC
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000010124change_random(const char *value)
Eric Andersenef02f822004-03-11 13:34:24 +000010125{
Denys Vlasenko3ea2e822009-10-09 20:59:04 +020010126 uint32_t t;
10127
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010128 if (value == NULL) {
Eric Andersen16767e22004-03-16 05:14:10 +000010129 /* "get", generate */
Denys Vlasenko3ea2e822009-10-09 20:59:04 +020010130 t = next_random(&random_gen);
Eric Andersen16767e22004-03-16 05:14:10 +000010131 /* set without recursion */
Denys Vlasenko8837c5d2010-06-02 12:56:18 +020010132 setvar(vrandom.var_text, utoa(t), VNOFUNC);
Eric Andersen16767e22004-03-16 05:14:10 +000010133 vrandom.flags &= ~VNOFUNC;
10134 } else {
10135 /* set/reset */
Denys Vlasenko3ea2e822009-10-09 20:59:04 +020010136 t = strtoul(value, NULL, 10);
10137 INIT_RANDOM_T(&random_gen, (t ? t : 1), t);
Eric Andersen16767e22004-03-16 05:14:10 +000010138 }
Eric Andersenef02f822004-03-11 13:34:24 +000010139}
Eric Andersen16767e22004-03-16 05:14:10 +000010140#endif
10141
Denis Vlasenko131ae172007-02-18 13:00:19 +000010142#if ENABLE_ASH_GETOPTS
Eric Andersencb57d552001-06-28 07:25:16 +000010143static int
Eric Andersenc470f442003-07-28 09:56:35 +000010144getopts(char *optstr, char *optvar, char **optfirst, int *param_optind, int *optoff)
Eric Andersencb57d552001-06-28 07:25:16 +000010145{
10146 char *p, *q;
10147 char c = '?';
10148 int done = 0;
10149 int err = 0;
Eric Andersena48b0a32003-10-22 10:56:47 +000010150 char s[12];
10151 char **optnext;
Eric Andersencb57d552001-06-28 07:25:16 +000010152
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010153 if (*param_optind < 1)
Eric Andersena48b0a32003-10-22 10:56:47 +000010154 return 1;
10155 optnext = optfirst + *param_optind - 1;
10156
Denis Vlasenko6b06cb82008-05-15 21:30:45 +000010157 if (*param_optind <= 1 || *optoff < 0 || (int)strlen(optnext[-1]) < *optoff)
Eric Andersencb57d552001-06-28 07:25:16 +000010158 p = NULL;
10159 else
Eric Andersena48b0a32003-10-22 10:56:47 +000010160 p = optnext[-1] + *optoff;
Eric Andersencb57d552001-06-28 07:25:16 +000010161 if (p == NULL || *p == '\0') {
10162 /* Current word is done, advance */
Eric Andersencb57d552001-06-28 07:25:16 +000010163 p = *optnext;
10164 if (p == NULL || *p != '-' || *++p == '\0') {
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010165 atend:
Eric Andersencb57d552001-06-28 07:25:16 +000010166 p = NULL;
10167 done = 1;
10168 goto out;
10169 }
10170 optnext++;
Denis Vlasenko9f739442006-12-16 23:49:13 +000010171 if (LONE_DASH(p)) /* check for "--" */
Eric Andersencb57d552001-06-28 07:25:16 +000010172 goto atend;
10173 }
10174
10175 c = *p++;
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +000010176 for (q = optstr; *q != c;) {
Eric Andersencb57d552001-06-28 07:25:16 +000010177 if (*q == '\0') {
10178 if (optstr[0] == ':') {
10179 s[0] = c;
10180 s[1] = '\0';
10181 err |= setvarsafe("OPTARG", s, 0);
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010182 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000010183 fprintf(stderr, "Illegal option -%c\n", c);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010184 unsetvar("OPTARG");
Eric Andersencb57d552001-06-28 07:25:16 +000010185 }
10186 c = '?';
Eric Andersenc470f442003-07-28 09:56:35 +000010187 goto out;
Eric Andersencb57d552001-06-28 07:25:16 +000010188 }
10189 if (*++q == ':')
10190 q++;
10191 }
10192
10193 if (*++q == ':') {
10194 if (*p == '\0' && (p = *optnext) == NULL) {
10195 if (optstr[0] == ':') {
10196 s[0] = c;
10197 s[1] = '\0';
10198 err |= setvarsafe("OPTARG", s, 0);
10199 c = ':';
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010200 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000010201 fprintf(stderr, "No arg for -%c option\n", c);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010202 unsetvar("OPTARG");
Eric Andersencb57d552001-06-28 07:25:16 +000010203 c = '?';
10204 }
Eric Andersenc470f442003-07-28 09:56:35 +000010205 goto out;
Eric Andersencb57d552001-06-28 07:25:16 +000010206 }
10207
10208 if (p == *optnext)
10209 optnext++;
Eric Andersenc470f442003-07-28 09:56:35 +000010210 err |= setvarsafe("OPTARG", p, 0);
Eric Andersencb57d552001-06-28 07:25:16 +000010211 p = NULL;
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010212 } else
Eric Andersenc470f442003-07-28 09:56:35 +000010213 err |= setvarsafe("OPTARG", nullstr, 0);
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010214 out:
Eric Andersencb57d552001-06-28 07:25:16 +000010215 *optoff = p ? p - *(optnext - 1) : -1;
Eric Andersenc470f442003-07-28 09:56:35 +000010216 *param_optind = optnext - optfirst + 1;
10217 fmtstr(s, sizeof(s), "%d", *param_optind);
Eric Andersencb57d552001-06-28 07:25:16 +000010218 err |= setvarsafe("OPTIND", s, VNOFUNC);
10219 s[0] = c;
10220 s[1] = '\0';
10221 err |= setvarsafe(optvar, s, 0);
10222 if (err) {
Eric Andersenc470f442003-07-28 09:56:35 +000010223 *param_optind = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010224 *optoff = -1;
Denis Vlasenkob012b102007-02-19 22:43:01 +000010225 flush_stdout_stderr();
10226 raise_exception(EXERROR);
Eric Andersencb57d552001-06-28 07:25:16 +000010227 }
10228 return done;
10229}
Eric Andersenc470f442003-07-28 09:56:35 +000010230
10231/*
10232 * The getopts builtin. Shellparam.optnext points to the next argument
10233 * to be processed. Shellparam.optptr points to the next character to
10234 * be processed in the current argument. If shellparam.optnext is NULL,
10235 * then it's the first time getopts has been called.
10236 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010237static int FAST_FUNC
Eric Andersenc470f442003-07-28 09:56:35 +000010238getoptscmd(int argc, char **argv)
10239{
10240 char **optbase;
10241
10242 if (argc < 3)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +000010243 ash_msg_and_raise_error("usage: getopts optstring var [arg]");
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010244 if (argc == 3) {
Eric Andersenc470f442003-07-28 09:56:35 +000010245 optbase = shellparam.p;
10246 if (shellparam.optind > shellparam.nparam + 1) {
10247 shellparam.optind = 1;
10248 shellparam.optoff = -1;
10249 }
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010250 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000010251 optbase = &argv[3];
10252 if (shellparam.optind > argc - 2) {
10253 shellparam.optind = 1;
10254 shellparam.optoff = -1;
10255 }
10256 }
10257
10258 return getopts(argv[1], argv[2], optbase, &shellparam.optind,
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010259 &shellparam.optoff);
Eric Andersenc470f442003-07-28 09:56:35 +000010260}
Denis Vlasenko131ae172007-02-18 13:00:19 +000010261#endif /* ASH_GETOPTS */
Eric Andersencb57d552001-06-28 07:25:16 +000010262
Eric Andersencb57d552001-06-28 07:25:16 +000010263
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010264/* ============ Shell parser */
Eric Andersencb57d552001-06-28 07:25:16 +000010265
Denis Vlasenkob07a4962008-06-22 13:16:23 +000010266struct heredoc {
10267 struct heredoc *next; /* next here document in list */
10268 union node *here; /* redirection node */
10269 char *eofmark; /* string indicating end of input */
10270 smallint striptabs; /* if set, strip leading tabs */
10271};
10272
10273static smallint tokpushback; /* last token pushed back */
10274static smallint parsebackquote; /* nonzero if we are inside backquotes */
10275static smallint quoteflag; /* set if (part of) last token was quoted */
10276static token_id_t lasttoken; /* last token read (integer id Txxx) */
10277static struct heredoc *heredoclist; /* list of here documents to read */
10278static char *wordtext; /* text of last word returned by readtoken */
10279static struct nodelist *backquotelist;
10280static union node *redirnode;
10281static struct heredoc *heredoc;
Denis Vlasenko99eb8502007-02-23 21:09:49 +000010282
Denys Vlasenkoa0ec4f52010-05-20 12:50:42 +020010283static const char *
10284tokname(char *buf, int tok)
10285{
10286 if (tok < TSEMI)
10287 return tokname_array[tok] + 1;
10288 sprintf(buf, "\"%s\"", tokname_array[tok] + 1);
10289 return buf;
10290}
10291
10292/* raise_error_unexpected_syntax:
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010293 * Called when an unexpected token is read during the parse. The argument
10294 * is the token that is expected, or -1 if more than one type of token can
10295 * occur at this point.
10296 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000010297static void raise_error_unexpected_syntax(int) NORETURN;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010298static void
10299raise_error_unexpected_syntax(int token)
10300{
10301 char msg[64];
Denys Vlasenkoa0ec4f52010-05-20 12:50:42 +020010302 char buf[16];
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010303 int l;
10304
Denys Vlasenkoa0ec4f52010-05-20 12:50:42 +020010305 l = sprintf(msg, "unexpected %s", tokname(buf, lasttoken));
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010306 if (token >= 0)
Denys Vlasenkoa0ec4f52010-05-20 12:50:42 +020010307 sprintf(msg + l, " (expecting %s)", tokname(buf, token));
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010308 raise_error_syntax(msg);
10309 /* NOTREACHED */
10310}
Eric Andersencb57d552001-06-28 07:25:16 +000010311
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010312#define EOFMARKLEN 79
Eric Andersencb57d552001-06-28 07:25:16 +000010313
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010314/* parsing is heavily cross-recursive, need these forward decls */
10315static union node *andor(void);
10316static union node *pipeline(void);
10317static union node *parse_command(void);
10318static void parseheredoc(void);
10319static char peektoken(void);
10320static int readtoken(void);
Eric Andersencb57d552001-06-28 07:25:16 +000010321
Eric Andersenc470f442003-07-28 09:56:35 +000010322static union node *
10323list(int nlflag)
Eric Andersencb57d552001-06-28 07:25:16 +000010324{
10325 union node *n1, *n2, *n3;
10326 int tok;
10327
Eric Andersenc470f442003-07-28 09:56:35 +000010328 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10329 if (nlflag == 2 && peektoken())
Eric Andersencb57d552001-06-28 07:25:16 +000010330 return NULL;
10331 n1 = NULL;
10332 for (;;) {
10333 n2 = andor();
10334 tok = readtoken();
10335 if (tok == TBACKGND) {
Eric Andersenc470f442003-07-28 09:56:35 +000010336 if (n2->type == NPIPE) {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +000010337 n2->npipe.pipe_backgnd = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010338 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000010339 if (n2->type != NREDIR) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010340 n3 = stzalloc(sizeof(struct nredir));
Eric Andersenc470f442003-07-28 09:56:35 +000010341 n3->nredir.n = n2;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010342 /*n3->nredir.redirect = NULL; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000010343 n2 = n3;
10344 }
10345 n2->type = NBACKGND;
Eric Andersencb57d552001-06-28 07:25:16 +000010346 }
10347 }
10348 if (n1 == NULL) {
10349 n1 = n2;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010350 } else {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010351 n3 = stzalloc(sizeof(struct nbinary));
Eric Andersencb57d552001-06-28 07:25:16 +000010352 n3->type = NSEMI;
10353 n3->nbinary.ch1 = n1;
10354 n3->nbinary.ch2 = n2;
10355 n1 = n3;
10356 }
10357 switch (tok) {
10358 case TBACKGND:
10359 case TSEMI:
10360 tok = readtoken();
10361 /* fall through */
10362 case TNL:
10363 if (tok == TNL) {
10364 parseheredoc();
Eric Andersenc470f442003-07-28 09:56:35 +000010365 if (nlflag == 1)
Eric Andersencb57d552001-06-28 07:25:16 +000010366 return n1;
10367 } else {
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010368 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010369 }
Eric Andersenc470f442003-07-28 09:56:35 +000010370 checkkwd = CHKNL | CHKKWD | CHKALIAS;
Manuel Novoa III 16815d42001-08-10 19:36:07 +000010371 if (peektoken())
Eric Andersencb57d552001-06-28 07:25:16 +000010372 return n1;
10373 break;
10374 case TEOF:
10375 if (heredoclist)
10376 parseheredoc();
10377 else
Eric Andersenc470f442003-07-28 09:56:35 +000010378 pungetc(); /* push back EOF on input */
Eric Andersencb57d552001-06-28 07:25:16 +000010379 return n1;
10380 default:
Eric Andersenc470f442003-07-28 09:56:35 +000010381 if (nlflag == 1)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010382 raise_error_unexpected_syntax(-1);
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010383 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010384 return n1;
10385 }
10386 }
10387}
10388
Eric Andersenc470f442003-07-28 09:56:35 +000010389static union node *
10390andor(void)
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010391{
Eric Andersencb57d552001-06-28 07:25:16 +000010392 union node *n1, *n2, *n3;
10393 int t;
10394
Eric Andersencb57d552001-06-28 07:25:16 +000010395 n1 = pipeline();
10396 for (;;) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010397 t = readtoken();
10398 if (t == TAND) {
Eric Andersencb57d552001-06-28 07:25:16 +000010399 t = NAND;
10400 } else if (t == TOR) {
10401 t = NOR;
10402 } else {
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010403 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010404 return n1;
10405 }
Eric Andersenc470f442003-07-28 09:56:35 +000010406 checkkwd = CHKNL | CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010407 n2 = pipeline();
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010408 n3 = stzalloc(sizeof(struct nbinary));
Eric Andersencb57d552001-06-28 07:25:16 +000010409 n3->type = t;
10410 n3->nbinary.ch1 = n1;
10411 n3->nbinary.ch2 = n2;
10412 n1 = n3;
10413 }
10414}
10415
Eric Andersenc470f442003-07-28 09:56:35 +000010416static union node *
10417pipeline(void)
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010418{
Eric Andersencb57d552001-06-28 07:25:16 +000010419 union node *n1, *n2, *pipenode;
10420 struct nodelist *lp, *prev;
10421 int negate;
10422
10423 negate = 0;
10424 TRACE(("pipeline: entered\n"));
10425 if (readtoken() == TNOT) {
10426 negate = !negate;
Eric Andersenc470f442003-07-28 09:56:35 +000010427 checkkwd = CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010428 } else
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010429 tokpushback = 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010430 n1 = parse_command();
Eric Andersencb57d552001-06-28 07:25:16 +000010431 if (readtoken() == TPIPE) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010432 pipenode = stzalloc(sizeof(struct npipe));
Eric Andersencb57d552001-06-28 07:25:16 +000010433 pipenode->type = NPIPE;
Denis Vlasenko2dc240c2008-07-24 06:07:50 +000010434 /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010435 lp = stzalloc(sizeof(struct nodelist));
Eric Andersencb57d552001-06-28 07:25:16 +000010436 pipenode->npipe.cmdlist = lp;
10437 lp->n = n1;
10438 do {
10439 prev = lp;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010440 lp = stzalloc(sizeof(struct nodelist));
Eric Andersenc470f442003-07-28 09:56:35 +000010441 checkkwd = CHKNL | CHKKWD | CHKALIAS;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010442 lp->n = parse_command();
Eric Andersencb57d552001-06-28 07:25:16 +000010443 prev->next = lp;
10444 } while (readtoken() == TPIPE);
10445 lp->next = NULL;
10446 n1 = pipenode;
10447 }
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010448 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010449 if (negate) {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010450 n2 = stzalloc(sizeof(struct nnot));
Eric Andersencb57d552001-06-28 07:25:16 +000010451 n2->type = NNOT;
10452 n2->nnot.com = n1;
10453 return n2;
Denis Vlasenko2da584f2007-02-19 22:44:05 +000010454 }
10455 return n1;
Eric Andersencb57d552001-06-28 07:25:16 +000010456}
10457
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010458static union node *
10459makename(void)
10460{
10461 union node *n;
10462
Denis Vlasenko597906c2008-02-20 16:38:54 +000010463 n = stzalloc(sizeof(struct narg));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010464 n->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010465 /*n->narg.next = NULL; - stzalloc did it */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010466 n->narg.text = wordtext;
10467 n->narg.backquote = backquotelist;
10468 return n;
10469}
10470
10471static void
10472fixredir(union node *n, const char *text, int err)
10473{
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000010474 int fd;
10475
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010476 TRACE(("Fix redir %s %d\n", text, err));
10477 if (!err)
10478 n->ndup.vname = NULL;
10479
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000010480 fd = bb_strtou(text, NULL, 10);
10481 if (!errno && fd >= 0)
10482 n->ndup.dupfd = fd;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010483 else if (LONE_DASH(text))
10484 n->ndup.dupfd = -1;
10485 else {
10486 if (err)
Denis Vlasenko559691a2008-10-05 18:39:31 +000010487 raise_error_syntax("bad fd number");
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010488 n->ndup.vname = makename();
10489 }
10490}
10491
10492/*
10493 * Returns true if the text contains nothing to expand (no dollar signs
10494 * or backquotes).
10495 */
10496static int
Denis Vlasenko68819d12008-12-15 11:26:36 +000010497noexpand(const char *text)
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010498{
Denys Vlasenkocd716832009-11-28 22:14:02 +010010499 unsigned char c;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010500
Denys Vlasenkocd716832009-11-28 22:14:02 +010010501 while ((c = *text++) != '\0') {
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010502 if (c == CTLQUOTEMARK)
10503 continue;
10504 if (c == CTLESC)
Denys Vlasenkocd716832009-11-28 22:14:02 +010010505 text++;
Denys Vlasenko76bc2d62009-11-29 01:37:46 +010010506 else if (SIT(c, BASESYNTAX) == CCTL)
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010507 return 0;
10508 }
10509 return 1;
10510}
10511
10512static void
10513parsefname(void)
10514{
10515 union node *n = redirnode;
10516
10517 if (readtoken() != TWORD)
10518 raise_error_unexpected_syntax(-1);
10519 if (n->type == NHERE) {
10520 struct heredoc *here = heredoc;
10521 struct heredoc *p;
10522 int i;
10523
10524 if (quoteflag == 0)
10525 n->type = NXHERE;
10526 TRACE(("Here document %d\n", n->type));
10527 if (!noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
Denis Vlasenko559691a2008-10-05 18:39:31 +000010528 raise_error_syntax("illegal eof marker for << redirection");
Denys Vlasenkob6c84342009-08-29 20:23:20 +020010529 rmescapes(wordtext, 0);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010530 here->eofmark = wordtext;
10531 here->next = NULL;
10532 if (heredoclist == NULL)
10533 heredoclist = here;
10534 else {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010535 for (p = heredoclist; p->next; p = p->next)
10536 continue;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010537 p->next = here;
10538 }
10539 } else if (n->type == NTOFD || n->type == NFROMFD) {
10540 fixredir(n, wordtext, 0);
10541 } else {
10542 n->nfile.fname = makename();
10543 }
10544}
Eric Andersencb57d552001-06-28 07:25:16 +000010545
Eric Andersenc470f442003-07-28 09:56:35 +000010546static union node *
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010547simplecmd(void)
10548{
10549 union node *args, **app;
10550 union node *n = NULL;
10551 union node *vars, **vpp;
10552 union node **rpp, *redir;
10553 int savecheckkwd;
Denis Vlasenko80591b02008-03-25 07:49:43 +000010554#if ENABLE_ASH_BASH_COMPAT
10555 smallint double_brackets_flag = 0;
10556#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010557
10558 args = NULL;
10559 app = &args;
10560 vars = NULL;
10561 vpp = &vars;
10562 redir = NULL;
10563 rpp = &redir;
10564
10565 savecheckkwd = CHKALIAS;
10566 for (;;) {
Denis Vlasenko80591b02008-03-25 07:49:43 +000010567 int t;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010568 checkkwd = savecheckkwd;
Denis Vlasenko80591b02008-03-25 07:49:43 +000010569 t = readtoken();
10570 switch (t) {
10571#if ENABLE_ASH_BASH_COMPAT
10572 case TAND: /* "&&" */
10573 case TOR: /* "||" */
10574 if (!double_brackets_flag) {
10575 tokpushback = 1;
10576 goto out;
10577 }
10578 wordtext = (char *) (t == TAND ? "-a" : "-o");
10579#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010580 case TWORD:
Denis Vlasenko597906c2008-02-20 16:38:54 +000010581 n = stzalloc(sizeof(struct narg));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010582 n->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010583 /*n->narg.next = NULL; - stzalloc did it */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010584 n->narg.text = wordtext;
Denis Vlasenko80591b02008-03-25 07:49:43 +000010585#if ENABLE_ASH_BASH_COMPAT
10586 if (strcmp("[[", wordtext) == 0)
10587 double_brackets_flag = 1;
10588 else if (strcmp("]]", wordtext) == 0)
10589 double_brackets_flag = 0;
10590#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010591 n->narg.backquote = backquotelist;
10592 if (savecheckkwd && isassignment(wordtext)) {
10593 *vpp = n;
10594 vpp = &n->narg.next;
10595 } else {
10596 *app = n;
10597 app = &n->narg.next;
10598 savecheckkwd = 0;
10599 }
10600 break;
10601 case TREDIR:
10602 *rpp = n = redirnode;
10603 rpp = &n->nfile.next;
10604 parsefname(); /* read name of redirection file */
10605 break;
10606 case TLP:
10607 if (args && app == &args->narg.next
10608 && !vars && !redir
10609 ) {
10610 struct builtincmd *bcmd;
10611 const char *name;
10612
10613 /* We have a function */
10614 if (readtoken() != TRP)
10615 raise_error_unexpected_syntax(TRP);
10616 name = n->narg.text;
10617 if (!goodname(name)
10618 || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
10619 ) {
Denis Vlasenko559691a2008-10-05 18:39:31 +000010620 raise_error_syntax("bad function name");
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010621 }
10622 n->type = NDEFUN;
10623 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10624 n->narg.next = parse_command();
10625 return n;
10626 }
10627 /* fall through */
10628 default:
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010629 tokpushback = 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010630 goto out;
10631 }
10632 }
10633 out:
10634 *app = NULL;
10635 *vpp = NULL;
10636 *rpp = NULL;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010637 n = stzalloc(sizeof(struct ncmd));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010638 n->type = NCMD;
10639 n->ncmd.args = args;
10640 n->ncmd.assign = vars;
10641 n->ncmd.redirect = redir;
10642 return n;
10643}
10644
10645static union node *
10646parse_command(void)
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010647{
Eric Andersencb57d552001-06-28 07:25:16 +000010648 union node *n1, *n2;
10649 union node *ap, **app;
10650 union node *cp, **cpp;
10651 union node *redir, **rpp;
Eric Andersenc470f442003-07-28 09:56:35 +000010652 union node **rpp2;
Eric Andersencb57d552001-06-28 07:25:16 +000010653 int t;
10654
10655 redir = NULL;
Eric Andersenc470f442003-07-28 09:56:35 +000010656 rpp2 = &redir;
Eric Andersen88cec252001-09-06 17:35:20 +000010657
Eric Andersencb57d552001-06-28 07:25:16 +000010658 switch (readtoken()) {
Eric Andersenc470f442003-07-28 09:56:35 +000010659 default:
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010660 raise_error_unexpected_syntax(-1);
Eric Andersenc470f442003-07-28 09:56:35 +000010661 /* NOTREACHED */
Eric Andersencb57d552001-06-28 07:25:16 +000010662 case TIF:
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010663 n1 = stzalloc(sizeof(struct nif));
Eric Andersencb57d552001-06-28 07:25:16 +000010664 n1->type = NIF;
10665 n1->nif.test = list(0);
10666 if (readtoken() != TTHEN)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010667 raise_error_unexpected_syntax(TTHEN);
Eric Andersencb57d552001-06-28 07:25:16 +000010668 n1->nif.ifpart = list(0);
10669 n2 = n1;
10670 while (readtoken() == TELIF) {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010671 n2->nif.elsepart = stzalloc(sizeof(struct nif));
Eric Andersencb57d552001-06-28 07:25:16 +000010672 n2 = n2->nif.elsepart;
10673 n2->type = NIF;
10674 n2->nif.test = list(0);
10675 if (readtoken() != TTHEN)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010676 raise_error_unexpected_syntax(TTHEN);
Eric Andersencb57d552001-06-28 07:25:16 +000010677 n2->nif.ifpart = list(0);
10678 }
10679 if (lasttoken == TELSE)
10680 n2->nif.elsepart = list(0);
10681 else {
10682 n2->nif.elsepart = NULL;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010683 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010684 }
Eric Andersenc470f442003-07-28 09:56:35 +000010685 t = TFI;
Eric Andersencb57d552001-06-28 07:25:16 +000010686 break;
10687 case TWHILE:
Eric Andersenc470f442003-07-28 09:56:35 +000010688 case TUNTIL: {
Eric Andersencb57d552001-06-28 07:25:16 +000010689 int got;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010690 n1 = stzalloc(sizeof(struct nbinary));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010691 n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
Eric Andersencb57d552001-06-28 07:25:16 +000010692 n1->nbinary.ch1 = list(0);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010693 got = readtoken();
10694 if (got != TDO) {
Denys Vlasenkoa0ec4f52010-05-20 12:50:42 +020010695 TRACE(("expecting DO got '%s' %s\n", tokname_array[got] + 1,
Denis Vlasenko131ae172007-02-18 13:00:19 +000010696 got == TWORD ? wordtext : ""));
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010697 raise_error_unexpected_syntax(TDO);
Eric Andersencb57d552001-06-28 07:25:16 +000010698 }
10699 n1->nbinary.ch2 = list(0);
Eric Andersenc470f442003-07-28 09:56:35 +000010700 t = TDONE;
Eric Andersencb57d552001-06-28 07:25:16 +000010701 break;
10702 }
10703 case TFOR:
Denis Vlasenko2dc240c2008-07-24 06:07:50 +000010704 if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
Denis Vlasenko559691a2008-10-05 18:39:31 +000010705 raise_error_syntax("bad for loop variable");
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010706 n1 = stzalloc(sizeof(struct nfor));
Eric Andersencb57d552001-06-28 07:25:16 +000010707 n1->type = NFOR;
10708 n1->nfor.var = wordtext;
Eric Andersenc470f442003-07-28 09:56:35 +000010709 checkkwd = CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010710 if (readtoken() == TIN) {
10711 app = &ap;
10712 while (readtoken() == TWORD) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010713 n2 = stzalloc(sizeof(struct narg));
Eric Andersencb57d552001-06-28 07:25:16 +000010714 n2->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010715 /*n2->narg.next = NULL; - stzalloc did it */
Eric Andersencb57d552001-06-28 07:25:16 +000010716 n2->narg.text = wordtext;
10717 n2->narg.backquote = backquotelist;
10718 *app = n2;
10719 app = &n2->narg.next;
10720 }
10721 *app = NULL;
10722 n1->nfor.args = ap;
10723 if (lasttoken != TNL && lasttoken != TSEMI)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010724 raise_error_unexpected_syntax(-1);
Eric Andersencb57d552001-06-28 07:25:16 +000010725 } else {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010726 n2 = stzalloc(sizeof(struct narg));
Eric Andersencb57d552001-06-28 07:25:16 +000010727 n2->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010728 /*n2->narg.next = NULL; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000010729 n2->narg.text = (char *)dolatstr;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010730 /*n2->narg.backquote = NULL;*/
Eric Andersencb57d552001-06-28 07:25:16 +000010731 n1->nfor.args = n2;
10732 /*
10733 * Newline or semicolon here is optional (but note
10734 * that the original Bourne shell only allowed NL).
10735 */
10736 if (lasttoken != TNL && lasttoken != TSEMI)
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010737 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010738 }
Eric Andersenc470f442003-07-28 09:56:35 +000010739 checkkwd = CHKNL | CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010740 if (readtoken() != TDO)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010741 raise_error_unexpected_syntax(TDO);
Eric Andersencb57d552001-06-28 07:25:16 +000010742 n1->nfor.body = list(0);
Eric Andersenc470f442003-07-28 09:56:35 +000010743 t = TDONE;
Eric Andersencb57d552001-06-28 07:25:16 +000010744 break;
10745 case TCASE:
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010746 n1 = stzalloc(sizeof(struct ncase));
Eric Andersencb57d552001-06-28 07:25:16 +000010747 n1->type = NCASE;
10748 if (readtoken() != TWORD)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010749 raise_error_unexpected_syntax(TWORD);
Denis Vlasenko597906c2008-02-20 16:38:54 +000010750 n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
Eric Andersencb57d552001-06-28 07:25:16 +000010751 n2->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010752 /*n2->narg.next = NULL; - stzalloc did it */
Eric Andersencb57d552001-06-28 07:25:16 +000010753 n2->narg.text = wordtext;
10754 n2->narg.backquote = backquotelist;
Eric Andersencb57d552001-06-28 07:25:16 +000010755 do {
Eric Andersenc470f442003-07-28 09:56:35 +000010756 checkkwd = CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010757 } while (readtoken() == TNL);
10758 if (lasttoken != TIN)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010759 raise_error_unexpected_syntax(TIN);
Eric Andersencb57d552001-06-28 07:25:16 +000010760 cpp = &n1->ncase.cases;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010761 next_case:
Eric Andersenc470f442003-07-28 09:56:35 +000010762 checkkwd = CHKNL | CHKKWD;
10763 t = readtoken();
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010764 while (t != TESAC) {
Eric Andersencb57d552001-06-28 07:25:16 +000010765 if (lasttoken == TLP)
10766 readtoken();
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010767 *cpp = cp = stzalloc(sizeof(struct nclist));
Eric Andersencb57d552001-06-28 07:25:16 +000010768 cp->type = NCLIST;
10769 app = &cp->nclist.pattern;
10770 for (;;) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010771 *app = ap = stzalloc(sizeof(struct narg));
Eric Andersencb57d552001-06-28 07:25:16 +000010772 ap->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010773 /*ap->narg.next = NULL; - stzalloc did it */
Eric Andersencb57d552001-06-28 07:25:16 +000010774 ap->narg.text = wordtext;
10775 ap->narg.backquote = backquotelist;
Eric Andersenc470f442003-07-28 09:56:35 +000010776 if (readtoken() != TPIPE)
Eric Andersencb57d552001-06-28 07:25:16 +000010777 break;
10778 app = &ap->narg.next;
10779 readtoken();
10780 }
Denis Vlasenko597906c2008-02-20 16:38:54 +000010781 //ap->narg.next = NULL;
Eric Andersencb57d552001-06-28 07:25:16 +000010782 if (lasttoken != TRP)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010783 raise_error_unexpected_syntax(TRP);
Eric Andersenc470f442003-07-28 09:56:35 +000010784 cp->nclist.body = list(2);
Eric Andersencb57d552001-06-28 07:25:16 +000010785
Eric Andersenc470f442003-07-28 09:56:35 +000010786 cpp = &cp->nclist.next;
10787
10788 checkkwd = CHKNL | CHKKWD;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010789 t = readtoken();
10790 if (t != TESAC) {
Eric Andersencb57d552001-06-28 07:25:16 +000010791 if (t != TENDCASE)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010792 raise_error_unexpected_syntax(TENDCASE);
10793 goto next_case;
Eric Andersencb57d552001-06-28 07:25:16 +000010794 }
Eric Andersenc470f442003-07-28 09:56:35 +000010795 }
Eric Andersencb57d552001-06-28 07:25:16 +000010796 *cpp = NULL;
Eric Andersenc470f442003-07-28 09:56:35 +000010797 goto redir;
Eric Andersencb57d552001-06-28 07:25:16 +000010798 case TLP:
Denis Vlasenko597906c2008-02-20 16:38:54 +000010799 n1 = stzalloc(sizeof(struct nredir));
Eric Andersencb57d552001-06-28 07:25:16 +000010800 n1->type = NSUBSHELL;
10801 n1->nredir.n = list(0);
Denis Vlasenko597906c2008-02-20 16:38:54 +000010802 /*n1->nredir.redirect = NULL; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000010803 t = TRP;
Eric Andersencb57d552001-06-28 07:25:16 +000010804 break;
10805 case TBEGIN:
10806 n1 = list(0);
Eric Andersenc470f442003-07-28 09:56:35 +000010807 t = TEND;
Eric Andersencb57d552001-06-28 07:25:16 +000010808 break;
Eric Andersencb57d552001-06-28 07:25:16 +000010809 case TWORD:
Eric Andersenc470f442003-07-28 09:56:35 +000010810 case TREDIR:
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010811 tokpushback = 1;
Eric Andersenc470f442003-07-28 09:56:35 +000010812 return simplecmd();
Eric Andersencb57d552001-06-28 07:25:16 +000010813 }
10814
Eric Andersenc470f442003-07-28 09:56:35 +000010815 if (readtoken() != t)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010816 raise_error_unexpected_syntax(t);
Eric Andersenc470f442003-07-28 09:56:35 +000010817
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010818 redir:
Eric Andersencb57d552001-06-28 07:25:16 +000010819 /* Now check for redirection which may follow command */
Eric Andersenc470f442003-07-28 09:56:35 +000010820 checkkwd = CHKKWD | CHKALIAS;
10821 rpp = rpp2;
Eric Andersencb57d552001-06-28 07:25:16 +000010822 while (readtoken() == TREDIR) {
10823 *rpp = n2 = redirnode;
10824 rpp = &n2->nfile.next;
10825 parsefname();
10826 }
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010827 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010828 *rpp = NULL;
10829 if (redir) {
10830 if (n1->type != NSUBSHELL) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010831 n2 = stzalloc(sizeof(struct nredir));
Eric Andersencb57d552001-06-28 07:25:16 +000010832 n2->type = NREDIR;
10833 n2->nredir.n = n1;
10834 n1 = n2;
10835 }
10836 n1->nredir.redirect = redir;
10837 }
Eric Andersencb57d552001-06-28 07:25:16 +000010838 return n1;
10839}
10840
Denis Vlasenkoef527f52008-06-23 01:52:30 +000010841#if ENABLE_ASH_BASH_COMPAT
10842static int decode_dollar_squote(void)
10843{
10844 static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
10845 int c, cnt;
10846 char *p;
10847 char buf[4];
10848
10849 c = pgetc();
10850 p = strchr(C_escapes, c);
10851 if (p) {
10852 buf[0] = c;
10853 p = buf;
10854 cnt = 3;
10855 if ((unsigned char)(c - '0') <= 7) { /* \ooo */
10856 do {
10857 c = pgetc();
10858 *++p = c;
10859 } while ((unsigned char)(c - '0') <= 7 && --cnt);
10860 pungetc();
10861 } else if (c == 'x') { /* \xHH */
10862 do {
10863 c = pgetc();
10864 *++p = c;
10865 } while (isxdigit(c) && --cnt);
10866 pungetc();
10867 if (cnt == 3) { /* \x but next char is "bad" */
10868 c = 'x';
10869 goto unrecognized;
10870 }
10871 } else { /* simple seq like \\ or \t */
10872 p++;
10873 }
10874 *p = '\0';
10875 p = buf;
10876 c = bb_process_escape_sequence((void*)&p);
10877 } else { /* unrecognized "\z": print both chars unless ' or " */
10878 if (c != '\'' && c != '"') {
10879 unrecognized:
10880 c |= 0x100; /* "please encode \, then me" */
10881 }
10882 }
10883 return c;
10884}
10885#endif
10886
Eric Andersencb57d552001-06-28 07:25:16 +000010887/*
10888 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
10889 * is not NULL, read a here document. In the latter case, eofmark is the
10890 * word which marks the end of the document and striptabs is true if
Denys Vlasenkocd716832009-11-28 22:14:02 +010010891 * leading tabs should be stripped from the document. The argument c
Eric Andersencb57d552001-06-28 07:25:16 +000010892 * is the first character of the input token or document.
10893 *
10894 * Because C does not have internal subroutines, I have simulated them
10895 * using goto's to implement the subroutine linkage. The following macros
10896 * will run code that appears at the end of readtoken1.
10897 */
Eric Andersen2870d962001-07-02 17:27:21 +000010898#define CHECKEND() {goto checkend; checkend_return:;}
10899#define PARSEREDIR() {goto parseredir; parseredir_return:;}
10900#define PARSESUB() {goto parsesub; parsesub_return:;}
10901#define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
10902#define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
10903#define PARSEARITH() {goto parsearith; parsearith_return:;}
Eric Andersencb57d552001-06-28 07:25:16 +000010904static int
Denys Vlasenkocd716832009-11-28 22:14:02 +010010905readtoken1(int c, int syntax, char *eofmark, int striptabs)
Manuel Novoa III 16815d42001-08-10 19:36:07 +000010906{
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010907 /* NB: syntax parameter fits into smallint */
Denys Vlasenkocd716832009-11-28 22:14:02 +010010908 /* c parameter is an unsigned char or PEOF or PEOA */
Eric Andersencb57d552001-06-28 07:25:16 +000010909 char *out;
10910 int len;
10911 char line[EOFMARKLEN + 1];
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010912 struct nodelist *bqlist;
10913 smallint quotef;
10914 smallint dblquote;
10915 smallint oldstyle;
10916 smallint prevsyntax; /* syntax before arithmetic */
Denis Vlasenko46a53062007-09-24 18:30:02 +000010917#if ENABLE_ASH_EXPAND_PRMT
10918 smallint pssyntax; /* we are expanding a prompt string */
10919#endif
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010920 int varnest; /* levels of variables expansion */
10921 int arinest; /* levels of arithmetic expansion */
10922 int parenlevel; /* levels of parens in arithmetic */
10923 int dqvarnest; /* levels of variables expansion within double quotes */
10924
Denis Vlasenko5e34ff22009-04-21 11:09:40 +000010925 IF_ASH_BASH_COMPAT(smallint bash_dollar_squote = 0;)
Denis Vlasenkoef527f52008-06-23 01:52:30 +000010926
Eric Andersencb57d552001-06-28 07:25:16 +000010927#if __GNUC__
10928 /* Avoid longjmp clobbering */
10929 (void) &out;
10930 (void) &quotef;
10931 (void) &dblquote;
10932 (void) &varnest;
10933 (void) &arinest;
10934 (void) &parenlevel;
10935 (void) &dqvarnest;
10936 (void) &oldstyle;
10937 (void) &prevsyntax;
10938 (void) &syntax;
10939#endif
Denis Vlasenko41eb3002008-11-28 03:42:31 +000010940 startlinno = g_parsefile->linno;
Eric Andersencb57d552001-06-28 07:25:16 +000010941 bqlist = NULL;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010942 quotef = 0;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010943 oldstyle = 0;
10944 prevsyntax = 0;
Denis Vlasenko46a53062007-09-24 18:30:02 +000010945#if ENABLE_ASH_EXPAND_PRMT
10946 pssyntax = (syntax == PSSYNTAX);
10947 if (pssyntax)
10948 syntax = DQSYNTAX;
10949#endif
10950 dblquote = (syntax == DQSYNTAX);
Eric Andersencb57d552001-06-28 07:25:16 +000010951 varnest = 0;
10952 arinest = 0;
10953 parenlevel = 0;
10954 dqvarnest = 0;
10955
10956 STARTSTACKSTR(out);
Denis Vlasenko176d49d2008-10-06 09:51:47 +000010957 loop:
10958 /* For each line, until end of word */
10959 {
Eric Andersenc470f442003-07-28 09:56:35 +000010960 CHECKEND(); /* set c to PEOF if at end of here document */
10961 for (;;) { /* until end of line or end of word */
10962 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
Denis Vlasenkobf0a2012006-12-26 10:42:51 +000010963 switch (SIT(c, syntax)) {
Eric Andersenc470f442003-07-28 09:56:35 +000010964 case CNL: /* '\n' */
Eric Andersencb57d552001-06-28 07:25:16 +000010965 if (syntax == BASESYNTAX)
Eric Andersenc470f442003-07-28 09:56:35 +000010966 goto endword; /* exit outer loop */
Eric Andersencb57d552001-06-28 07:25:16 +000010967 USTPUTC(c, out);
Denis Vlasenko41eb3002008-11-28 03:42:31 +000010968 g_parsefile->linno++;
Eric Andersencb57d552001-06-28 07:25:16 +000010969 if (doprompt)
10970 setprompt(2);
Eric Andersencb57d552001-06-28 07:25:16 +000010971 c = pgetc();
Eric Andersenc470f442003-07-28 09:56:35 +000010972 goto loop; /* continue outer loop */
Eric Andersencb57d552001-06-28 07:25:16 +000010973 case CWORD:
10974 USTPUTC(c, out);
10975 break;
10976 case CCTL:
Eric Andersenc470f442003-07-28 09:56:35 +000010977 if (eofmark == NULL || dblquote)
Eric Andersencb57d552001-06-28 07:25:16 +000010978 USTPUTC(CTLESC, out);
Denis Vlasenkoef527f52008-06-23 01:52:30 +000010979#if ENABLE_ASH_BASH_COMPAT
10980 if (c == '\\' && bash_dollar_squote) {
10981 c = decode_dollar_squote();
10982 if (c & 0x100) {
10983 USTPUTC('\\', out);
10984 c = (unsigned char)c;
10985 }
10986 }
10987#endif
Eric Andersencb57d552001-06-28 07:25:16 +000010988 USTPUTC(c, out);
10989 break;
Eric Andersenc470f442003-07-28 09:56:35 +000010990 case CBACK: /* backslash */
Denys Vlasenko2ce42e92009-11-29 02:18:13 +010010991 c = pgetc_without_PEOA();
Eric Andersencb57d552001-06-28 07:25:16 +000010992 if (c == PEOF) {
Eric Andersenc470f442003-07-28 09:56:35 +000010993 USTPUTC(CTLESC, out);
Eric Andersencb57d552001-06-28 07:25:16 +000010994 USTPUTC('\\', out);
10995 pungetc();
10996 } else if (c == '\n') {
10997 if (doprompt)
10998 setprompt(2);
Eric Andersencb57d552001-06-28 07:25:16 +000010999 } else {
Denis Vlasenko46a53062007-09-24 18:30:02 +000011000#if ENABLE_ASH_EXPAND_PRMT
11001 if (c == '$' && pssyntax) {
11002 USTPUTC(CTLESC, out);
11003 USTPUTC('\\', out);
11004 }
11005#endif
Denis Vlasenkoef527f52008-06-23 01:52:30 +000011006 if (dblquote && c != '\\'
11007 && c != '`' && c != '$'
11008 && (c != '"' || eofmark != NULL)
Eric Andersenc470f442003-07-28 09:56:35 +000011009 ) {
11010 USTPUTC(CTLESC, out);
Eric Andersencb57d552001-06-28 07:25:16 +000011011 USTPUTC('\\', out);
Eric Andersenc470f442003-07-28 09:56:35 +000011012 }
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000011013 if (SIT(c, SQSYNTAX) == CCTL)
Eric Andersencb57d552001-06-28 07:25:16 +000011014 USTPUTC(CTLESC, out);
Eric Andersencb57d552001-06-28 07:25:16 +000011015 USTPUTC(c, out);
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011016 quotef = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000011017 }
11018 break;
11019 case CSQUOTE:
Eric Andersencb57d552001-06-28 07:25:16 +000011020 syntax = SQSYNTAX;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011021 quotemark:
Eric Andersenc470f442003-07-28 09:56:35 +000011022 if (eofmark == NULL) {
11023 USTPUTC(CTLQUOTEMARK, out);
11024 }
Eric Andersencb57d552001-06-28 07:25:16 +000011025 break;
11026 case CDQUOTE:
Eric Andersencb57d552001-06-28 07:25:16 +000011027 syntax = DQSYNTAX;
11028 dblquote = 1;
Eric Andersenc470f442003-07-28 09:56:35 +000011029 goto quotemark;
Eric Andersencb57d552001-06-28 07:25:16 +000011030 case CENDQUOTE:
Denis Vlasenko5e34ff22009-04-21 11:09:40 +000011031 IF_ASH_BASH_COMPAT(bash_dollar_squote = 0;)
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011032 if (eofmark != NULL && arinest == 0
11033 && varnest == 0
11034 ) {
Eric Andersencb57d552001-06-28 07:25:16 +000011035 USTPUTC(c, out);
11036 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000011037 if (dqvarnest == 0) {
Eric Andersencb57d552001-06-28 07:25:16 +000011038 syntax = BASESYNTAX;
11039 dblquote = 0;
11040 }
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011041 quotef = 1;
Eric Andersenc470f442003-07-28 09:56:35 +000011042 goto quotemark;
Eric Andersencb57d552001-06-28 07:25:16 +000011043 }
11044 break;
Eric Andersenc470f442003-07-28 09:56:35 +000011045 case CVAR: /* '$' */
11046 PARSESUB(); /* parse substitution */
Eric Andersencb57d552001-06-28 07:25:16 +000011047 break;
Eric Andersenc470f442003-07-28 09:56:35 +000011048 case CENDVAR: /* '}' */
Eric Andersencb57d552001-06-28 07:25:16 +000011049 if (varnest > 0) {
11050 varnest--;
11051 if (dqvarnest > 0) {
11052 dqvarnest--;
11053 }
11054 USTPUTC(CTLENDVAR, out);
11055 } else {
11056 USTPUTC(c, out);
11057 }
11058 break;
Mike Frysinger98c52642009-04-02 10:02:37 +000011059#if ENABLE_SH_MATH_SUPPORT
Eric Andersenc470f442003-07-28 09:56:35 +000011060 case CLP: /* '(' in arithmetic */
Eric Andersencb57d552001-06-28 07:25:16 +000011061 parenlevel++;
11062 USTPUTC(c, out);
11063 break;
Eric Andersenc470f442003-07-28 09:56:35 +000011064 case CRP: /* ')' in arithmetic */
Eric Andersencb57d552001-06-28 07:25:16 +000011065 if (parenlevel > 0) {
11066 USTPUTC(c, out);
11067 --parenlevel;
11068 } else {
11069 if (pgetc() == ')') {
11070 if (--arinest == 0) {
11071 USTPUTC(CTLENDARI, out);
11072 syntax = prevsyntax;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011073 dblquote = (syntax == DQSYNTAX);
Eric Andersencb57d552001-06-28 07:25:16 +000011074 } else
11075 USTPUTC(')', out);
11076 } else {
11077 /*
11078 * unbalanced parens
11079 * (don't 2nd guess - no error)
11080 */
11081 pungetc();
11082 USTPUTC(')', out);
11083 }
11084 }
11085 break;
11086#endif
Eric Andersenc470f442003-07-28 09:56:35 +000011087 case CBQUOTE: /* '`' */
Eric Andersencb57d552001-06-28 07:25:16 +000011088 PARSEBACKQOLD();
11089 break;
Eric Andersen2870d962001-07-02 17:27:21 +000011090 case CENDFILE:
Eric Andersenc470f442003-07-28 09:56:35 +000011091 goto endword; /* exit outer loop */
Eric Andersencb57d552001-06-28 07:25:16 +000011092 case CIGN:
11093 break;
11094 default:
Denis Vlasenko834dee72008-10-07 09:18:30 +000011095 if (varnest == 0) {
11096#if ENABLE_ASH_BASH_COMPAT
11097 if (c == '&') {
11098 if (pgetc() == '>')
11099 c = 0x100 + '>'; /* flag &> */
11100 pungetc();
11101 }
11102#endif
Eric Andersenc470f442003-07-28 09:56:35 +000011103 goto endword; /* exit outer loop */
Denis Vlasenko834dee72008-10-07 09:18:30 +000011104 }
Denys Vlasenko2ce42e92009-11-29 02:18:13 +010011105 IF_ASH_ALIAS(if (c != PEOA))
Eric Andersencb57d552001-06-28 07:25:16 +000011106 USTPUTC(c, out);
Eric Andersen3102ac42001-07-06 04:26:23 +000011107
Eric Andersencb57d552001-06-28 07:25:16 +000011108 }
Denis Vlasenko834dee72008-10-07 09:18:30 +000011109 c = pgetc_fast();
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000011110 } /* for (;;) */
Eric Andersencb57d552001-06-28 07:25:16 +000011111 }
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011112 endword:
Mike Frysinger98c52642009-04-02 10:02:37 +000011113#if ENABLE_SH_MATH_SUPPORT
Eric Andersencb57d552001-06-28 07:25:16 +000011114 if (syntax == ARISYNTAX)
Denis Vlasenko559691a2008-10-05 18:39:31 +000011115 raise_error_syntax("missing '))'");
Eric Andersenc470f442003-07-28 09:56:35 +000011116#endif
Denis Vlasenko99eb8502007-02-23 21:09:49 +000011117 if (syntax != BASESYNTAX && !parsebackquote && eofmark == NULL)
Denis Vlasenko559691a2008-10-05 18:39:31 +000011118 raise_error_syntax("unterminated quoted string");
Eric Andersencb57d552001-06-28 07:25:16 +000011119 if (varnest != 0) {
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011120 startlinno = g_parsefile->linno;
Eric Andersenc470f442003-07-28 09:56:35 +000011121 /* { */
Denis Vlasenko559691a2008-10-05 18:39:31 +000011122 raise_error_syntax("missing '}'");
Eric Andersencb57d552001-06-28 07:25:16 +000011123 }
11124 USTPUTC('\0', out);
Eric Andersenc470f442003-07-28 09:56:35 +000011125 len = out - (char *)stackblock();
Eric Andersencb57d552001-06-28 07:25:16 +000011126 out = stackblock();
11127 if (eofmark == NULL) {
Denis Vlasenko5e34ff22009-04-21 11:09:40 +000011128 if ((c == '>' || c == '<' IF_ASH_BASH_COMPAT( || c == 0x100 + '>'))
Denis Vlasenko834dee72008-10-07 09:18:30 +000011129 && quotef == 0
11130 ) {
Denis Vlasenko559691a2008-10-05 18:39:31 +000011131 if (isdigit_str9(out)) {
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000011132 PARSEREDIR(); /* passed as params: out, c */
11133 lasttoken = TREDIR;
11134 return lasttoken;
11135 }
11136 /* else: non-number X seen, interpret it
11137 * as "NNNX>file" = "NNNX >file" */
Eric Andersencb57d552001-06-28 07:25:16 +000011138 }
Denis Vlasenkoef527f52008-06-23 01:52:30 +000011139 pungetc();
Eric Andersencb57d552001-06-28 07:25:16 +000011140 }
11141 quoteflag = quotef;
11142 backquotelist = bqlist;
11143 grabstackblock(len);
11144 wordtext = out;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011145 lasttoken = TWORD;
11146 return lasttoken;
Eric Andersencb57d552001-06-28 07:25:16 +000011147/* end of readtoken routine */
11148
Eric Andersencb57d552001-06-28 07:25:16 +000011149/*
11150 * Check to see whether we are at the end of the here document. When this
11151 * is called, c is set to the first character of the next input line. If
11152 * we are at the end of the here document, this routine sets the c to PEOF.
11153 */
Eric Andersenc470f442003-07-28 09:56:35 +000011154checkend: {
11155 if (eofmark) {
Denis Vlasenko131ae172007-02-18 13:00:19 +000011156#if ENABLE_ASH_ALIAS
Denys Vlasenko2ce42e92009-11-29 02:18:13 +010011157 if (c == PEOA)
11158 c = pgetc_without_PEOA();
Eric Andersenc470f442003-07-28 09:56:35 +000011159#endif
11160 if (striptabs) {
11161 while (c == '\t') {
Denys Vlasenko2ce42e92009-11-29 02:18:13 +010011162 c = pgetc_without_PEOA();
Eric Andersencb57d552001-06-28 07:25:16 +000011163 }
Eric Andersenc470f442003-07-28 09:56:35 +000011164 }
11165 if (c == *eofmark) {
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011166 if (pfgets(line, sizeof(line)) != NULL) {
Eric Andersenc470f442003-07-28 09:56:35 +000011167 char *p, *q;
Eric Andersencb57d552001-06-28 07:25:16 +000011168
Eric Andersenc470f442003-07-28 09:56:35 +000011169 p = line;
Denis Vlasenkof7d56652008-03-25 05:51:41 +000011170 for (q = eofmark + 1; *q && *p == *q; p++, q++)
11171 continue;
Eric Andersenc470f442003-07-28 09:56:35 +000011172 if (*p == '\n' && *q == '\0') {
11173 c = PEOF;
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011174 g_parsefile->linno++;
Eric Andersenc470f442003-07-28 09:56:35 +000011175 needprompt = doprompt;
11176 } else {
11177 pushstring(line, NULL);
Eric Andersencb57d552001-06-28 07:25:16 +000011178 }
11179 }
11180 }
11181 }
Eric Andersenc470f442003-07-28 09:56:35 +000011182 goto checkend_return;
11183}
Eric Andersencb57d552001-06-28 07:25:16 +000011184
Eric Andersencb57d552001-06-28 07:25:16 +000011185/*
11186 * Parse a redirection operator. The variable "out" points to a string
11187 * specifying the fd to be redirected. The variable "c" contains the
11188 * first character of the redirection operator.
11189 */
Eric Andersenc470f442003-07-28 09:56:35 +000011190parseredir: {
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000011191 /* out is already checked to be a valid number or "" */
11192 int fd = (*out == '\0' ? -1 : atoi(out));
Eric Andersenc470f442003-07-28 09:56:35 +000011193 union node *np;
Eric Andersencb57d552001-06-28 07:25:16 +000011194
Denis Vlasenko597906c2008-02-20 16:38:54 +000011195 np = stzalloc(sizeof(struct nfile));
Eric Andersenc470f442003-07-28 09:56:35 +000011196 if (c == '>') {
11197 np->nfile.fd = 1;
11198 c = pgetc();
11199 if (c == '>')
11200 np->type = NAPPEND;
11201 else if (c == '|')
11202 np->type = NCLOBBER;
11203 else if (c == '&')
11204 np->type = NTOFD;
Denis Vlasenko559691a2008-10-05 18:39:31 +000011205 /* it also can be NTO2 (>&file), but we can't figure it out yet */
Eric Andersenc470f442003-07-28 09:56:35 +000011206 else {
11207 np->type = NTO;
11208 pungetc();
Eric Andersencb57d552001-06-28 07:25:16 +000011209 }
Denis Vlasenko834dee72008-10-07 09:18:30 +000011210 }
11211#if ENABLE_ASH_BASH_COMPAT
11212 else if (c == 0x100 + '>') { /* this flags &> redirection */
11213 np->nfile.fd = 1;
11214 pgetc(); /* this is '>', no need to check */
11215 np->type = NTO2;
11216 }
11217#endif
11218 else { /* c == '<' */
Denis Vlasenko597906c2008-02-20 16:38:54 +000011219 /*np->nfile.fd = 0; - stzalloc did it */
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011220 c = pgetc();
11221 switch (c) {
Eric Andersenc470f442003-07-28 09:56:35 +000011222 case '<':
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011223 if (sizeof(struct nfile) != sizeof(struct nhere)) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000011224 np = stzalloc(sizeof(struct nhere));
11225 /*np->nfile.fd = 0; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000011226 }
11227 np->type = NHERE;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000011228 heredoc = stzalloc(sizeof(struct heredoc));
Eric Andersenc470f442003-07-28 09:56:35 +000011229 heredoc->here = np;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011230 c = pgetc();
11231 if (c == '-') {
Eric Andersenc470f442003-07-28 09:56:35 +000011232 heredoc->striptabs = 1;
11233 } else {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000011234 /*heredoc->striptabs = 0; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000011235 pungetc();
11236 }
11237 break;
11238
11239 case '&':
11240 np->type = NFROMFD;
11241 break;
11242
11243 case '>':
11244 np->type = NFROMTO;
11245 break;
11246
11247 default:
11248 np->type = NFROM;
11249 pungetc();
11250 break;
11251 }
Eric Andersencb57d552001-06-28 07:25:16 +000011252 }
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000011253 if (fd >= 0)
11254 np->nfile.fd = fd;
Eric Andersenc470f442003-07-28 09:56:35 +000011255 redirnode = np;
11256 goto parseredir_return;
11257}
Eric Andersencb57d552001-06-28 07:25:16 +000011258
Eric Andersencb57d552001-06-28 07:25:16 +000011259/*
11260 * Parse a substitution. At this point, we have read the dollar sign
11261 * and nothing else.
11262 */
Denis Vlasenkocc571512007-02-23 21:10:35 +000011263
11264/* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
11265 * (assuming ascii char codes, as the original implementation did) */
11266#define is_special(c) \
Denis Vlasenkoef527f52008-06-23 01:52:30 +000011267 (((unsigned)(c) - 33 < 32) \
11268 && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
Eric Andersenc470f442003-07-28 09:56:35 +000011269parsesub: {
Denys Vlasenkocd716832009-11-28 22:14:02 +010011270 unsigned char subtype;
Eric Andersenc470f442003-07-28 09:56:35 +000011271 int typeloc;
11272 int flags;
11273 char *p;
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011274 static const char types[] ALIGN1 = "}-+?=";
Eric Andersencb57d552001-06-28 07:25:16 +000011275
Eric Andersenc470f442003-07-28 09:56:35 +000011276 c = pgetc();
Denys Vlasenkocd716832009-11-28 22:14:02 +010011277 if (c > 255 /* PEOA or PEOF */
Denis Vlasenkoef527f52008-06-23 01:52:30 +000011278 || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
Eric Andersenc470f442003-07-28 09:56:35 +000011279 ) {
Denis Vlasenkoef527f52008-06-23 01:52:30 +000011280#if ENABLE_ASH_BASH_COMPAT
11281 if (c == '\'')
11282 bash_dollar_squote = 1;
11283 else
11284#endif
11285 USTPUTC('$', out);
Eric Andersenc470f442003-07-28 09:56:35 +000011286 pungetc();
11287 } else if (c == '(') { /* $(command) or $((arith)) */
11288 if (pgetc() == '(') {
Mike Frysinger98c52642009-04-02 10:02:37 +000011289#if ENABLE_SH_MATH_SUPPORT
Eric Andersenc470f442003-07-28 09:56:35 +000011290 PARSEARITH();
11291#else
Mike Frysinger98a6f562008-06-09 09:38:45 +000011292 raise_error_syntax("you disabled math support for $((arith)) syntax");
Eric Andersenc470f442003-07-28 09:56:35 +000011293#endif
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000011294 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000011295 pungetc();
11296 PARSEBACKQNEW();
11297 }
11298 } else {
11299 USTPUTC(CTLVAR, out);
11300 typeloc = out - (char *)stackblock();
11301 USTPUTC(VSNORMAL, out);
11302 subtype = VSNORMAL;
11303 if (c == '{') {
11304 c = pgetc();
11305 if (c == '#') {
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011306 c = pgetc();
11307 if (c == '}')
Eric Andersenc470f442003-07-28 09:56:35 +000011308 c = '#';
11309 else
11310 subtype = VSLENGTH;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011311 } else
Eric Andersenc470f442003-07-28 09:56:35 +000011312 subtype = 0;
11313 }
Denys Vlasenkocd716832009-11-28 22:14:02 +010011314 if (c <= 255 /* not PEOA or PEOF */ && is_name(c)) {
Eric Andersenc470f442003-07-28 09:56:35 +000011315 do {
11316 STPUTC(c, out);
Eric Andersencb57d552001-06-28 07:25:16 +000011317 c = pgetc();
Denys Vlasenkocd716832009-11-28 22:14:02 +010011318 } while (c <= 255 /* not PEOA or PEOF */ && is_in_name(c));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011319 } else if (isdigit(c)) {
Eric Andersenc470f442003-07-28 09:56:35 +000011320 do {
11321 STPUTC(c, out);
11322 c = pgetc();
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011323 } while (isdigit(c));
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011324 } else if (is_special(c)) {
Eric Andersenc470f442003-07-28 09:56:35 +000011325 USTPUTC(c, out);
11326 c = pgetc();
Denis Vlasenko559691a2008-10-05 18:39:31 +000011327 } else {
11328 badsub:
11329 raise_error_syntax("bad substitution");
11330 }
Cristian Ionescu-Idbohrn301f5ec2009-10-05 02:07:23 +020011331 if (c != '}' && subtype == VSLENGTH)
11332 goto badsub;
Eric Andersencb57d552001-06-28 07:25:16 +000011333
Eric Andersenc470f442003-07-28 09:56:35 +000011334 STPUTC('=', out);
11335 flags = 0;
11336 if (subtype == 0) {
11337 switch (c) {
11338 case ':':
Eric Andersenc470f442003-07-28 09:56:35 +000011339 c = pgetc();
Denis Vlasenko92e13c22008-03-25 01:17:40 +000011340#if ENABLE_ASH_BASH_COMPAT
11341 if (c == ':' || c == '$' || isdigit(c)) {
11342 pungetc();
11343 subtype = VSSUBSTR;
11344 break;
11345 }
11346#endif
11347 flags = VSNUL;
Eric Andersenc470f442003-07-28 09:56:35 +000011348 /*FALLTHROUGH*/
11349 default:
11350 p = strchr(types, c);
11351 if (p == NULL)
11352 goto badsub;
11353 subtype = p - types + VSNORMAL;
11354 break;
11355 case '%':
Denis Vlasenko92e13c22008-03-25 01:17:40 +000011356 case '#': {
11357 int cc = c;
11358 subtype = c == '#' ? VSTRIMLEFT : VSTRIMRIGHT;
11359 c = pgetc();
11360 if (c == cc)
11361 subtype++;
11362 else
11363 pungetc();
11364 break;
11365 }
11366#if ENABLE_ASH_BASH_COMPAT
11367 case '/':
11368 subtype = VSREPLACE;
11369 c = pgetc();
11370 if (c == '/')
11371 subtype++; /* VSREPLACEALL */
11372 else
11373 pungetc();
11374 break;
11375#endif
Eric Andersencb57d552001-06-28 07:25:16 +000011376 }
Eric Andersenc470f442003-07-28 09:56:35 +000011377 } else {
11378 pungetc();
11379 }
11380 if (dblquote || arinest)
11381 flags |= VSQUOTE;
Denys Vlasenkocd716832009-11-28 22:14:02 +010011382 ((unsigned char *)stackblock())[typeloc] = subtype | flags;
Eric Andersenc470f442003-07-28 09:56:35 +000011383 if (subtype != VSNORMAL) {
11384 varnest++;
11385 if (dblquote || arinest) {
11386 dqvarnest++;
Eric Andersencb57d552001-06-28 07:25:16 +000011387 }
11388 }
11389 }
Eric Andersenc470f442003-07-28 09:56:35 +000011390 goto parsesub_return;
11391}
Eric Andersencb57d552001-06-28 07:25:16 +000011392
Eric Andersencb57d552001-06-28 07:25:16 +000011393/*
11394 * Called to parse command substitutions. Newstyle is set if the command
11395 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
11396 * list of commands (passed by reference), and savelen is the number of
11397 * characters on the top of the stack which must be preserved.
11398 */
Eric Andersenc470f442003-07-28 09:56:35 +000011399parsebackq: {
11400 struct nodelist **nlpp;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011401 smallint savepbq;
Eric Andersenc470f442003-07-28 09:56:35 +000011402 union node *n;
11403 char *volatile str;
11404 struct jmploc jmploc;
11405 struct jmploc *volatile savehandler;
11406 size_t savelen;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011407 smallint saveprompt = 0;
11408
Eric Andersencb57d552001-06-28 07:25:16 +000011409#ifdef __GNUC__
Eric Andersenc470f442003-07-28 09:56:35 +000011410 (void) &saveprompt;
Eric Andersencb57d552001-06-28 07:25:16 +000011411#endif
Eric Andersenc470f442003-07-28 09:56:35 +000011412 savepbq = parsebackquote;
11413 if (setjmp(jmploc.loc)) {
Denis Vlasenko60818682007-09-28 22:07:23 +000011414 free(str);
Eric Andersenc470f442003-07-28 09:56:35 +000011415 parsebackquote = 0;
Denis Vlasenko2da584f2007-02-19 22:44:05 +000011416 exception_handler = savehandler;
11417 longjmp(exception_handler->loc, 1);
Eric Andersenc470f442003-07-28 09:56:35 +000011418 }
Denis Vlasenkob012b102007-02-19 22:43:01 +000011419 INT_OFF;
Eric Andersenc470f442003-07-28 09:56:35 +000011420 str = NULL;
11421 savelen = out - (char *)stackblock();
11422 if (savelen > 0) {
11423 str = ckmalloc(savelen);
11424 memcpy(str, stackblock(), savelen);
11425 }
Denis Vlasenko2da584f2007-02-19 22:44:05 +000011426 savehandler = exception_handler;
11427 exception_handler = &jmploc;
Denis Vlasenkob012b102007-02-19 22:43:01 +000011428 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +000011429 if (oldstyle) {
11430 /* We must read until the closing backquote, giving special
11431 treatment to some slashes, and then push the string and
11432 reread it as input, interpreting it normally. */
11433 char *pout;
11434 int pc;
11435 size_t psavelen;
11436 char *pstr;
11437
11438
11439 STARTSTACKSTR(pout);
11440 for (;;) {
11441 if (needprompt) {
11442 setprompt(2);
Eric Andersenc470f442003-07-28 09:56:35 +000011443 }
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011444 pc = pgetc();
11445 switch (pc) {
Eric Andersenc470f442003-07-28 09:56:35 +000011446 case '`':
11447 goto done;
11448
11449 case '\\':
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011450 pc = pgetc();
11451 if (pc == '\n') {
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011452 g_parsefile->linno++;
Eric Andersenc470f442003-07-28 09:56:35 +000011453 if (doprompt)
11454 setprompt(2);
11455 /*
11456 * If eating a newline, avoid putting
11457 * the newline into the new character
11458 * stream (via the STPUTC after the
11459 * switch).
11460 */
11461 continue;
11462 }
11463 if (pc != '\\' && pc != '`' && pc != '$'
Denys Vlasenko76bc2d62009-11-29 01:37:46 +010011464 && (!dblquote || pc != '"')
11465 ) {
Eric Andersenc470f442003-07-28 09:56:35 +000011466 STPUTC('\\', pout);
Denys Vlasenko76bc2d62009-11-29 01:37:46 +010011467 }
Denys Vlasenkocd716832009-11-28 22:14:02 +010011468 if (pc <= 255 /* not PEOA or PEOF */) {
Eric Andersenc470f442003-07-28 09:56:35 +000011469 break;
11470 }
11471 /* fall through */
11472
11473 case PEOF:
Denys Vlasenko2ce42e92009-11-29 02:18:13 +010011474 IF_ASH_ALIAS(case PEOA:)
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011475 startlinno = g_parsefile->linno;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000011476 raise_error_syntax("EOF in backquote substitution");
Eric Andersenc470f442003-07-28 09:56:35 +000011477
11478 case '\n':
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011479 g_parsefile->linno++;
Eric Andersenc470f442003-07-28 09:56:35 +000011480 needprompt = doprompt;
11481 break;
11482
11483 default:
11484 break;
11485 }
11486 STPUTC(pc, pout);
11487 }
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011488 done:
Eric Andersenc470f442003-07-28 09:56:35 +000011489 STPUTC('\0', pout);
11490 psavelen = pout - (char *)stackblock();
11491 if (psavelen > 0) {
11492 pstr = grabstackstr(pout);
11493 setinputstring(pstr);
11494 }
11495 }
11496 nlpp = &bqlist;
11497 while (*nlpp)
11498 nlpp = &(*nlpp)->next;
Denis Vlasenko597906c2008-02-20 16:38:54 +000011499 *nlpp = stzalloc(sizeof(**nlpp));
11500 /* (*nlpp)->next = NULL; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000011501 parsebackquote = oldstyle;
11502
11503 if (oldstyle) {
11504 saveprompt = doprompt;
11505 doprompt = 0;
Eric Andersencb57d552001-06-28 07:25:16 +000011506 }
11507
Eric Andersenc470f442003-07-28 09:56:35 +000011508 n = list(2);
11509
11510 if (oldstyle)
11511 doprompt = saveprompt;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011512 else if (readtoken() != TRP)
11513 raise_error_unexpected_syntax(TRP);
Eric Andersenc470f442003-07-28 09:56:35 +000011514
11515 (*nlpp)->n = n;
11516 if (oldstyle) {
11517 /*
11518 * Start reading from old file again, ignoring any pushed back
11519 * tokens left from the backquote parsing
11520 */
11521 popfile();
11522 tokpushback = 0;
11523 }
11524 while (stackblocksize() <= savelen)
11525 growstackblock();
11526 STARTSTACKSTR(out);
11527 if (str) {
11528 memcpy(out, str, savelen);
11529 STADJUST(savelen, out);
Denis Vlasenkob012b102007-02-19 22:43:01 +000011530 INT_OFF;
11531 free(str);
Eric Andersenc470f442003-07-28 09:56:35 +000011532 str = NULL;
Denis Vlasenkob012b102007-02-19 22:43:01 +000011533 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +000011534 }
11535 parsebackquote = savepbq;
Denis Vlasenko2da584f2007-02-19 22:44:05 +000011536 exception_handler = savehandler;
Eric Andersenc470f442003-07-28 09:56:35 +000011537 if (arinest || dblquote)
11538 USTPUTC(CTLBACKQ | CTLQUOTE, out);
11539 else
11540 USTPUTC(CTLBACKQ, out);
11541 if (oldstyle)
11542 goto parsebackq_oldreturn;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000011543 goto parsebackq_newreturn;
Eric Andersenc470f442003-07-28 09:56:35 +000011544}
11545
Mike Frysinger98c52642009-04-02 10:02:37 +000011546#if ENABLE_SH_MATH_SUPPORT
Eric Andersencb57d552001-06-28 07:25:16 +000011547/*
11548 * Parse an arithmetic expansion (indicate start of one and set state)
11549 */
Eric Andersenc470f442003-07-28 09:56:35 +000011550parsearith: {
Eric Andersenc470f442003-07-28 09:56:35 +000011551 if (++arinest == 1) {
11552 prevsyntax = syntax;
11553 syntax = ARISYNTAX;
11554 USTPUTC(CTLARI, out);
11555 if (dblquote)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000011556 USTPUTC('"', out);
Eric Andersenc470f442003-07-28 09:56:35 +000011557 else
Denis Vlasenkoa624c112007-02-19 22:45:43 +000011558 USTPUTC(' ', out);
Eric Andersenc470f442003-07-28 09:56:35 +000011559 } else {
11560 /*
11561 * we collapse embedded arithmetic expansion to
11562 * parenthesis, which should be equivalent
11563 */
11564 USTPUTC('(', out);
Eric Andersencb57d552001-06-28 07:25:16 +000011565 }
Eric Andersenc470f442003-07-28 09:56:35 +000011566 goto parsearith_return;
11567}
11568#endif
Eric Andersencb57d552001-06-28 07:25:16 +000011569
Eric Andersenc470f442003-07-28 09:56:35 +000011570} /* end of readtoken */
11571
Eric Andersencb57d552001-06-28 07:25:16 +000011572/*
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011573 * Read the next input token.
11574 * If the token is a word, we set backquotelist to the list of cmds in
11575 * backquotes. We set quoteflag to true if any part of the word was
11576 * quoted.
11577 * If the token is TREDIR, then we set redirnode to a structure containing
11578 * the redirection.
11579 * In all cases, the variable startlinno is set to the number of the line
11580 * on which the token starts.
11581 *
11582 * [Change comment: here documents and internal procedures]
11583 * [Readtoken shouldn't have any arguments. Perhaps we should make the
11584 * word parsing code into a separate routine. In this case, readtoken
11585 * doesn't need to have any internal procedures, but parseword does.
11586 * We could also make parseoperator in essence the main routine, and
11587 * have parseword (readtoken1?) handle both words and redirection.]
Eric Andersencb57d552001-06-28 07:25:16 +000011588 */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011589#define NEW_xxreadtoken
11590#ifdef NEW_xxreadtoken
11591/* singles must be first! */
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011592static const char xxreadtoken_chars[7] ALIGN1 = {
Denis Vlasenko834dee72008-10-07 09:18:30 +000011593 '\n', '(', ')', /* singles */
11594 '&', '|', ';', /* doubles */
11595 0
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011596};
Eric Andersencb57d552001-06-28 07:25:16 +000011597
Denis Vlasenko834dee72008-10-07 09:18:30 +000011598#define xxreadtoken_singles 3
11599#define xxreadtoken_doubles 3
11600
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011601static const char xxreadtoken_tokens[] ALIGN1 = {
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011602 TNL, TLP, TRP, /* only single occurrence allowed */
11603 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
11604 TEOF, /* corresponds to trailing nul */
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011605 TAND, TOR, TENDCASE /* if double occurrence */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011606};
11607
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011608static int
11609xxreadtoken(void)
11610{
11611 int c;
11612
11613 if (tokpushback) {
11614 tokpushback = 0;
11615 return lasttoken;
Eric Andersencb57d552001-06-28 07:25:16 +000011616 }
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011617 if (needprompt) {
11618 setprompt(2);
11619 }
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011620 startlinno = g_parsefile->linno;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011621 for (;;) { /* until token or start of word found */
Denis Vlasenko834dee72008-10-07 09:18:30 +000011622 c = pgetc_fast();
Denis Vlasenko5e34ff22009-04-21 11:09:40 +000011623 if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011624 continue;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011625
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011626 if (c == '#') {
11627 while ((c = pgetc()) != '\n' && c != PEOF)
11628 continue;
11629 pungetc();
11630 } else if (c == '\\') {
11631 if (pgetc() != '\n') {
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011632 pungetc();
Denis Vlasenko834dee72008-10-07 09:18:30 +000011633 break; /* return readtoken1(...) */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011634 }
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011635 startlinno = ++g_parsefile->linno;
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011636 if (doprompt)
11637 setprompt(2);
11638 } else {
11639 const char *p;
11640
11641 p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
11642 if (c != PEOF) {
11643 if (c == '\n') {
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011644 g_parsefile->linno++;
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011645 needprompt = doprompt;
11646 }
11647
11648 p = strchr(xxreadtoken_chars, c);
Denis Vlasenko834dee72008-10-07 09:18:30 +000011649 if (p == NULL)
11650 break; /* return readtoken1(...) */
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011651
Denis Vlasenko834dee72008-10-07 09:18:30 +000011652 if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
11653 int cc = pgetc();
11654 if (cc == c) { /* double occurrence? */
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011655 p += xxreadtoken_doubles + 1;
11656 } else {
11657 pungetc();
Denis Vlasenko834dee72008-10-07 09:18:30 +000011658#if ENABLE_ASH_BASH_COMPAT
11659 if (c == '&' && cc == '>') /* &> */
11660 break; /* return readtoken1(...) */
11661#endif
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011662 }
11663 }
11664 }
11665 lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
11666 return lasttoken;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011667 }
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011668 } /* for (;;) */
Denis Vlasenko834dee72008-10-07 09:18:30 +000011669
11670 return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011671}
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011672#else /* old xxreadtoken */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011673#define RETURN(token) return lasttoken = token
11674static int
11675xxreadtoken(void)
11676{
11677 int c;
11678
11679 if (tokpushback) {
11680 tokpushback = 0;
11681 return lasttoken;
11682 }
11683 if (needprompt) {
11684 setprompt(2);
11685 }
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011686 startlinno = g_parsefile->linno;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011687 for (;;) { /* until token or start of word found */
Denis Vlasenko834dee72008-10-07 09:18:30 +000011688 c = pgetc_fast();
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011689 switch (c) {
11690 case ' ': case '\t':
Denys Vlasenko2ce42e92009-11-29 02:18:13 +010011691 IF_ASH_ALIAS(case PEOA:)
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011692 continue;
11693 case '#':
Denis Vlasenkof7d56652008-03-25 05:51:41 +000011694 while ((c = pgetc()) != '\n' && c != PEOF)
11695 continue;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011696 pungetc();
11697 continue;
11698 case '\\':
11699 if (pgetc() == '\n') {
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011700 startlinno = ++g_parsefile->linno;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011701 if (doprompt)
11702 setprompt(2);
11703 continue;
11704 }
11705 pungetc();
11706 goto breakloop;
11707 case '\n':
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011708 g_parsefile->linno++;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011709 needprompt = doprompt;
11710 RETURN(TNL);
11711 case PEOF:
11712 RETURN(TEOF);
11713 case '&':
11714 if (pgetc() == '&')
11715 RETURN(TAND);
11716 pungetc();
11717 RETURN(TBACKGND);
11718 case '|':
11719 if (pgetc() == '|')
11720 RETURN(TOR);
11721 pungetc();
11722 RETURN(TPIPE);
11723 case ';':
11724 if (pgetc() == ';')
11725 RETURN(TENDCASE);
11726 pungetc();
11727 RETURN(TSEMI);
11728 case '(':
11729 RETURN(TLP);
11730 case ')':
11731 RETURN(TRP);
11732 default:
11733 goto breakloop;
11734 }
11735 }
11736 breakloop:
11737 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
11738#undef RETURN
11739}
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011740#endif /* old xxreadtoken */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011741
11742static int
11743readtoken(void)
11744{
11745 int t;
11746#if DEBUG
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011747 smallint alreadyseen = tokpushback;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011748#endif
11749
11750#if ENABLE_ASH_ALIAS
11751 top:
11752#endif
11753
11754 t = xxreadtoken();
11755
11756 /*
11757 * eat newlines
11758 */
11759 if (checkkwd & CHKNL) {
11760 while (t == TNL) {
11761 parseheredoc();
11762 t = xxreadtoken();
11763 }
11764 }
11765
11766 if (t != TWORD || quoteflag) {
11767 goto out;
11768 }
11769
11770 /*
11771 * check for keywords
11772 */
11773 if (checkkwd & CHKKWD) {
11774 const char *const *pp;
11775
11776 pp = findkwd(wordtext);
11777 if (pp) {
11778 lasttoken = t = pp - tokname_array;
Denys Vlasenkoa0ec4f52010-05-20 12:50:42 +020011779 TRACE(("keyword '%s' recognized\n", tokname_array[t] + 1));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011780 goto out;
11781 }
11782 }
11783
11784 if (checkkwd & CHKALIAS) {
11785#if ENABLE_ASH_ALIAS
11786 struct alias *ap;
11787 ap = lookupalias(wordtext, 1);
11788 if (ap != NULL) {
11789 if (*ap->val) {
11790 pushstring(ap->val, ap);
11791 }
11792 goto top;
11793 }
11794#endif
11795 }
11796 out:
11797 checkkwd = 0;
11798#if DEBUG
11799 if (!alreadyseen)
Denys Vlasenkoa0ec4f52010-05-20 12:50:42 +020011800 TRACE(("token '%s' %s\n", tokname_array[t] + 1, t == TWORD ? wordtext : ""));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011801 else
Denys Vlasenkoa0ec4f52010-05-20 12:50:42 +020011802 TRACE(("reread token '%s' %s\n", tokname_array[t] + 1, t == TWORD ? wordtext : ""));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011803#endif
11804 return t;
Eric Andersencb57d552001-06-28 07:25:16 +000011805}
11806
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011807static char
11808peektoken(void)
11809{
11810 int t;
11811
11812 t = readtoken();
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011813 tokpushback = 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011814 return tokname_array[t][0];
11815}
Eric Andersencb57d552001-06-28 07:25:16 +000011816
11817/*
Denys Vlasenko86e83ec2009-07-23 22:07:07 +020011818 * Read and parse a command. Returns NODE_EOF on end of file.
11819 * (NULL is a valid parse tree indicating a blank line.)
Eric Andersencb57d552001-06-28 07:25:16 +000011820 */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011821static union node *
11822parsecmd(int interact)
Eric Andersen90898442003-08-06 11:20:52 +000011823{
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011824 int t;
Eric Andersencb57d552001-06-28 07:25:16 +000011825
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011826 tokpushback = 0;
11827 doprompt = interact;
11828 if (doprompt)
11829 setprompt(doprompt);
11830 needprompt = 0;
11831 t = readtoken();
11832 if (t == TEOF)
Denys Vlasenko86e83ec2009-07-23 22:07:07 +020011833 return NODE_EOF;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011834 if (t == TNL)
11835 return NULL;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011836 tokpushback = 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011837 return list(1);
11838}
11839
11840/*
11841 * Input any here documents.
11842 */
11843static void
11844parseheredoc(void)
11845{
11846 struct heredoc *here;
11847 union node *n;
11848
11849 here = heredoclist;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000011850 heredoclist = NULL;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011851
11852 while (here) {
11853 if (needprompt) {
11854 setprompt(2);
11855 }
11856 readtoken1(pgetc(), here->here->type == NHERE? SQSYNTAX : DQSYNTAX,
11857 here->eofmark, here->striptabs);
Denis Vlasenko597906c2008-02-20 16:38:54 +000011858 n = stzalloc(sizeof(struct narg));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011859 n->narg.type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000011860 /*n->narg.next = NULL; - stzalloc did it */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011861 n->narg.text = wordtext;
11862 n->narg.backquote = backquotelist;
11863 here->here->nhere.doc = n;
11864 here = here->next;
Eric Andersencb57d552001-06-28 07:25:16 +000011865 }
Eric Andersencb57d552001-06-28 07:25:16 +000011866}
11867
11868
11869/*
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +000011870 * called by editline -- any expansions to the prompt should be added here.
Eric Andersencb57d552001-06-28 07:25:16 +000011871 */
Denis Vlasenko131ae172007-02-18 13:00:19 +000011872#if ENABLE_ASH_EXPAND_PRMT
"Vladimir N. Oleynik"bef14d72005-09-05 13:25:11 +000011873static const char *
11874expandstr(const char *ps)
11875{
11876 union node n;
11877
Denis Vlasenko5c2b8142009-03-19 01:59:59 +000011878 /* XXX Fix (char *) cast. It _is_ a bug. ps is variable's value,
11879 * and token processing _can_ alter it (delete NULs etc). */
"Vladimir N. Oleynik"bef14d72005-09-05 13:25:11 +000011880 setinputstring((char *)ps);
Denis Vlasenko46a53062007-09-24 18:30:02 +000011881 readtoken1(pgetc(), PSSYNTAX, nullstr, 0);
"Vladimir N. Oleynik"bef14d72005-09-05 13:25:11 +000011882 popfile();
11883
11884 n.narg.type = NARG;
11885 n.narg.next = NULL;
11886 n.narg.text = wordtext;
11887 n.narg.backquote = backquotelist;
11888
11889 expandarg(&n, NULL, 0);
11890 return stackblock();
11891}
11892#endif
11893
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011894/*
11895 * Execute a command or commands contained in a string.
11896 */
11897static int
11898evalstring(char *s, int mask)
Eric Andersenc470f442003-07-28 09:56:35 +000011899{
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011900 union node *n;
11901 struct stackmark smark;
11902 int skip;
11903
11904 setinputstring(s);
11905 setstackmark(&smark);
11906
11907 skip = 0;
Denys Vlasenko86e83ec2009-07-23 22:07:07 +020011908 while ((n = parsecmd(0)) != NODE_EOF) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011909 evaltree(n, 0);
11910 popstackmark(&smark);
11911 skip = evalskip;
11912 if (skip)
11913 break;
11914 }
11915 popfile();
11916
11917 skip &= mask;
11918 evalskip = skip;
11919 return skip;
Eric Andersenc470f442003-07-28 09:56:35 +000011920}
11921
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011922/*
11923 * The eval command.
11924 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011925static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000011926evalcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011927{
11928 char *p;
11929 char *concat;
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011930
Denis Vlasenko68404f12008-03-17 09:00:54 +000011931 if (argv[1]) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011932 p = argv[1];
Denis Vlasenko68404f12008-03-17 09:00:54 +000011933 argv += 2;
11934 if (argv[0]) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011935 STARTSTACKSTR(concat);
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011936 for (;;) {
11937 concat = stack_putstr(p, concat);
Denis Vlasenko68404f12008-03-17 09:00:54 +000011938 p = *argv++;
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011939 if (p == NULL)
11940 break;
11941 STPUTC(' ', concat);
11942 }
11943 STPUTC('\0', concat);
11944 p = grabstackstr(concat);
11945 }
11946 evalstring(p, ~SKIPEVAL);
11947
11948 }
11949 return exitstatus;
11950}
11951
11952/*
Denys Vlasenko285ad152009-12-04 23:02:27 +010011953 * Read and execute commands.
11954 * "Top" is nonzero for the top level command loop;
11955 * it turns on prompting if the shell is interactive.
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011956 */
11957static int
11958cmdloop(int top)
11959{
11960 union node *n;
11961 struct stackmark smark;
11962 int inter;
11963 int numeof = 0;
11964
11965 TRACE(("cmdloop(%d) called\n", top));
11966 for (;;) {
11967 int skip;
11968
11969 setstackmark(&smark);
11970#if JOBS
Denis Vlasenkob07a4962008-06-22 13:16:23 +000011971 if (doing_jobctl)
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011972 showjobs(stderr, SHOW_CHANGED);
11973#endif
11974 inter = 0;
11975 if (iflag && top) {
11976 inter++;
11977#if ENABLE_ASH_MAIL
11978 chkmail();
11979#endif
11980 }
11981 n = parsecmd(inter);
Denys Vlasenko7cee00e2009-07-24 01:08:03 +020011982#if DEBUG
11983 if (DEBUG > 2 && debug && (n != NODE_EOF))
Denys Vlasenko883cea42009-07-11 15:31:59 +020011984 showtree(n);
Denis Vlasenko135cecb2009-04-12 00:00:57 +000011985#endif
Denys Vlasenko86e83ec2009-07-23 22:07:07 +020011986 if (n == NODE_EOF) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011987 if (!top || numeof >= 50)
11988 break;
11989 if (!stoppedjobs()) {
11990 if (!Iflag)
11991 break;
11992 out2str("\nUse \"exit\" to leave shell.\n");
11993 }
11994 numeof++;
11995 } else if (nflag == 0) {
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +000011996 /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
11997 job_warning >>= 1;
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011998 numeof = 0;
11999 evaltree(n, 0);
12000 }
12001 popstackmark(&smark);
12002 skip = evalskip;
12003
12004 if (skip) {
12005 evalskip = 0;
12006 return skip & SKIPEVAL;
12007 }
12008 }
12009 return 0;
12010}
12011
Denis Vlasenko0dec6de2007-02-23 21:10:47 +000012012/*
12013 * Take commands from a file. To be compatible we should do a path
12014 * search for the file, which is necessary to find sub-commands.
12015 */
12016static char *
12017find_dot_file(char *name)
12018{
12019 char *fullname;
12020 const char *path = pathval();
12021 struct stat statb;
12022
12023 /* don't try this for absolute or relative paths */
12024 if (strchr(name, '/'))
12025 return name;
12026
Denis Vlasenko8ad78e12009-02-15 12:40:30 +000012027 /* IIRC standards do not say whether . is to be searched.
12028 * And it is even smaller this way, making it unconditional for now:
12029 */
12030 if (1) { /* ENABLE_ASH_BASH_COMPAT */
12031 fullname = name;
12032 goto try_cur_dir;
12033 }
12034
Denys Vlasenko82a6fb32009-06-14 19:42:12 +020012035 while ((fullname = path_advance(&path, name)) != NULL) {
Denis Vlasenko8ad78e12009-02-15 12:40:30 +000012036 try_cur_dir:
Denis Vlasenko0dec6de2007-02-23 21:10:47 +000012037 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
12038 /*
12039 * Don't bother freeing here, since it will
12040 * be freed by the caller.
12041 */
12042 return fullname;
12043 }
Denys Vlasenko82a6fb32009-06-14 19:42:12 +020012044 if (fullname != name)
12045 stunalloc(fullname);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +000012046 }
12047
12048 /* not found in the PATH */
12049 ash_msg_and_raise_error("%s: not found", name);
12050 /* NOTREACHED */
12051}
12052
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012053static int FAST_FUNC
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012054dotcmd(int argc, char **argv)
12055{
Denys Vlasenkoe66cf822010-05-18 09:12:53 +020012056 char *fullname;
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012057 struct strlist *sp;
12058 volatile struct shparam saveparam;
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012059
12060 for (sp = cmdenviron; sp; sp = sp->next)
Denis Vlasenko4222ae42007-02-25 02:37:49 +000012061 setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012062
Denys Vlasenkoe66cf822010-05-18 09:12:53 +020012063 if (!argv[1]) {
12064 /* bash says: "bash: .: filename argument required" */
12065 return 2; /* bash compat */
12066 }
12067
Denys Vlasenkocd10dc42010-05-17 17:10:46 +020012068 /* "false; . empty_file; echo $?" should print 0, not 1: */
12069 exitstatus = 0;
12070
Denys Vlasenkoe66cf822010-05-18 09:12:53 +020012071 fullname = find_dot_file(argv[1]);
Denys Vlasenkocd10dc42010-05-17 17:10:46 +020012072
Denys Vlasenkoe66cf822010-05-18 09:12:53 +020012073 argv += 2;
12074 argc -= 2;
12075 if (argc) { /* argc > 0, argv[0] != NULL */
12076 saveparam = shellparam;
12077 shellparam.malloced = 0;
12078 shellparam.nparam = argc;
12079 shellparam.p = argv;
12080 };
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012081
Denys Vlasenkoe66cf822010-05-18 09:12:53 +020012082 setinputfile(fullname, INPUT_PUSH_FILE);
12083 commandname = fullname;
12084 cmdloop(0);
12085 popfile();
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012086
Denys Vlasenkoe66cf822010-05-18 09:12:53 +020012087 if (argc) {
12088 freeparam(&shellparam);
12089 shellparam = saveparam;
12090 };
12091
Denys Vlasenkocd10dc42010-05-17 17:10:46 +020012092 return exitstatus;
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012093}
12094
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012095static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012096exitcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012097{
12098 if (stoppedjobs())
12099 return 0;
Denis Vlasenko68404f12008-03-17 09:00:54 +000012100 if (argv[1])
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012101 exitstatus = number(argv[1]);
12102 raise_exception(EXEXIT);
12103 /* NOTREACHED */
12104}
12105
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012106/*
12107 * Read a file containing shell functions.
12108 */
12109static void
12110readcmdfile(char *name)
12111{
12112 setinputfile(name, INPUT_PUSH_FILE);
12113 cmdloop(0);
12114 popfile();
12115}
12116
12117
Denis Vlasenkocc571512007-02-23 21:10:35 +000012118/* ============ find_command inplementation */
12119
12120/*
12121 * Resolve a command name. If you change this routine, you may have to
12122 * change the shellexec routine as well.
12123 */
12124static void
12125find_command(char *name, struct cmdentry *entry, int act, const char *path)
12126{
12127 struct tblentry *cmdp;
12128 int idx;
12129 int prev;
12130 char *fullname;
12131 struct stat statb;
12132 int e;
12133 int updatetbl;
12134 struct builtincmd *bcmd;
12135
12136 /* If name contains a slash, don't use PATH or hash table */
12137 if (strchr(name, '/') != NULL) {
12138 entry->u.index = -1;
12139 if (act & DO_ABS) {
12140 while (stat(name, &statb) < 0) {
12141#ifdef SYSV
12142 if (errno == EINTR)
12143 continue;
12144#endif
12145 entry->cmdtype = CMDUNKNOWN;
12146 return;
12147 }
12148 }
12149 entry->cmdtype = CMDNORMAL;
12150 return;
12151 }
12152
Denis Vlasenkof20de5b2007-04-29 23:42:54 +000012153/* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
Denis Vlasenkocc571512007-02-23 21:10:35 +000012154
12155 updatetbl = (path == pathval());
12156 if (!updatetbl) {
12157 act |= DO_ALTPATH;
12158 if (strstr(path, "%builtin") != NULL)
12159 act |= DO_ALTBLTIN;
12160 }
12161
12162 /* If name is in the table, check answer will be ok */
12163 cmdp = cmdlookup(name, 0);
12164 if (cmdp != NULL) {
12165 int bit;
12166
12167 switch (cmdp->cmdtype) {
12168 default:
12169#if DEBUG
12170 abort();
12171#endif
12172 case CMDNORMAL:
12173 bit = DO_ALTPATH;
12174 break;
12175 case CMDFUNCTION:
12176 bit = DO_NOFUNC;
12177 break;
12178 case CMDBUILTIN:
12179 bit = DO_ALTBLTIN;
12180 break;
12181 }
12182 if (act & bit) {
12183 updatetbl = 0;
12184 cmdp = NULL;
12185 } else if (cmdp->rehash == 0)
12186 /* if not invalidated by cd, we're done */
12187 goto success;
12188 }
12189
12190 /* If %builtin not in path, check for builtin next */
12191 bcmd = find_builtin(name);
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +000012192 if (bcmd) {
12193 if (IS_BUILTIN_REGULAR(bcmd))
12194 goto builtin_success;
12195 if (act & DO_ALTPATH) {
12196 if (!(act & DO_ALTBLTIN))
12197 goto builtin_success;
12198 } else if (builtinloc <= 0) {
12199 goto builtin_success;
Denis Vlasenko8e858e22007-03-07 09:35:43 +000012200 }
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +000012201 }
Denis Vlasenkocc571512007-02-23 21:10:35 +000012202
Denis Vlasenkof20de5b2007-04-29 23:42:54 +000012203#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko7465dbc2008-04-13 02:25:53 +000012204 {
12205 int applet_no = find_applet_by_name(name);
12206 if (applet_no >= 0) {
12207 entry->cmdtype = CMDNORMAL;
12208 entry->u.index = -2 - applet_no;
12209 return;
12210 }
Denis Vlasenkof20de5b2007-04-29 23:42:54 +000012211 }
12212#endif
12213
Denis Vlasenkocc571512007-02-23 21:10:35 +000012214 /* We have to search path. */
12215 prev = -1; /* where to start */
12216 if (cmdp && cmdp->rehash) { /* doing a rehash */
12217 if (cmdp->cmdtype == CMDBUILTIN)
12218 prev = builtinloc;
12219 else
12220 prev = cmdp->param.index;
12221 }
12222
12223 e = ENOENT;
12224 idx = -1;
12225 loop:
Denys Vlasenko82a6fb32009-06-14 19:42:12 +020012226 while ((fullname = path_advance(&path, name)) != NULL) {
Denis Vlasenkocc571512007-02-23 21:10:35 +000012227 stunalloc(fullname);
Denis Vlasenkodee82b62007-07-29 14:05:27 +000012228 /* NB: code below will still use fullname
12229 * despite it being "unallocated" */
Denis Vlasenkocc571512007-02-23 21:10:35 +000012230 idx++;
12231 if (pathopt) {
12232 if (prefix(pathopt, "builtin")) {
12233 if (bcmd)
12234 goto builtin_success;
12235 continue;
Denis Vlasenko4a9ca132008-04-12 20:07:08 +000012236 }
12237 if ((act & DO_NOFUNC)
12238 || !prefix(pathopt, "func")
12239 ) { /* ignore unimplemented options */
Denis Vlasenkocc571512007-02-23 21:10:35 +000012240 continue;
12241 }
12242 }
12243 /* if rehash, don't redo absolute path names */
12244 if (fullname[0] == '/' && idx <= prev) {
12245 if (idx < prev)
12246 continue;
12247 TRACE(("searchexec \"%s\": no change\n", name));
12248 goto success;
12249 }
12250 while (stat(fullname, &statb) < 0) {
12251#ifdef SYSV
12252 if (errno == EINTR)
12253 continue;
12254#endif
12255 if (errno != ENOENT && errno != ENOTDIR)
12256 e = errno;
12257 goto loop;
12258 }
12259 e = EACCES; /* if we fail, this will be the error */
12260 if (!S_ISREG(statb.st_mode))
12261 continue;
12262 if (pathopt) { /* this is a %func directory */
12263 stalloc(strlen(fullname) + 1);
Denis Vlasenkodee82b62007-07-29 14:05:27 +000012264 /* NB: stalloc will return space pointed by fullname
12265 * (because we don't have any intervening allocations
12266 * between stunalloc above and this stalloc) */
Denis Vlasenkocc571512007-02-23 21:10:35 +000012267 readcmdfile(fullname);
12268 cmdp = cmdlookup(name, 0);
12269 if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
12270 ash_msg_and_raise_error("%s not defined in %s", name, fullname);
12271 stunalloc(fullname);
12272 goto success;
12273 }
12274 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
12275 if (!updatetbl) {
12276 entry->cmdtype = CMDNORMAL;
12277 entry->u.index = idx;
12278 return;
12279 }
12280 INT_OFF;
12281 cmdp = cmdlookup(name, 1);
12282 cmdp->cmdtype = CMDNORMAL;
12283 cmdp->param.index = idx;
12284 INT_ON;
12285 goto success;
12286 }
12287
12288 /* We failed. If there was an entry for this command, delete it */
12289 if (cmdp && updatetbl)
12290 delete_cmd_entry();
12291 if (act & DO_ERR)
12292 ash_msg("%s: %s", name, errmsg(e, "not found"));
12293 entry->cmdtype = CMDUNKNOWN;
12294 return;
12295
12296 builtin_success:
12297 if (!updatetbl) {
12298 entry->cmdtype = CMDBUILTIN;
12299 entry->u.cmd = bcmd;
12300 return;
12301 }
12302 INT_OFF;
12303 cmdp = cmdlookup(name, 1);
12304 cmdp->cmdtype = CMDBUILTIN;
12305 cmdp->param.cmd = bcmd;
12306 INT_ON;
12307 success:
12308 cmdp->rehash = 0;
12309 entry->cmdtype = cmdp->cmdtype;
12310 entry->u = cmdp->param;
12311}
12312
12313
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012314/* ============ trap.c */
Eric Andersenc470f442003-07-28 09:56:35 +000012315
Eric Andersencb57d552001-06-28 07:25:16 +000012316/*
Eric Andersencb57d552001-06-28 07:25:16 +000012317 * The trap builtin.
12318 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012319static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012320trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersencb57d552001-06-28 07:25:16 +000012321{
12322 char *action;
12323 char **ap;
Denys Vlasenko496d5bf2010-03-26 15:52:24 +010012324 int signo, exitcode;
Eric Andersencb57d552001-06-28 07:25:16 +000012325
Eric Andersenc470f442003-07-28 09:56:35 +000012326 nextopt(nullstr);
12327 ap = argptr;
12328 if (!*ap) {
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012329 for (signo = 0; signo < NSIG; signo++) {
Denys Vlasenko21d87d42009-09-25 00:06:51 +020012330 char *tr = trap_ptr[signo];
12331 if (tr) {
Denys Vlasenkoe74aaf92009-09-27 02:05:45 +020012332 /* note: bash adds "SIG", but only if invoked
12333 * as "bash". If called as "sh", or if set -o posix,
12334 * then it prints short signal names.
12335 * We are printing short names: */
12336 out1fmt("trap -- %s %s\n",
Denys Vlasenko21d87d42009-09-25 00:06:51 +020012337 single_quote(tr),
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +000012338 get_signame(signo));
Denys Vlasenko726e1a02009-09-25 02:58:20 +020012339 /* trap_ptr != trap only if we are in special-cased `trap` code.
12340 * In this case, we will exit very soon, no need to free(). */
Denys Vlasenkoe74aaf92009-09-27 02:05:45 +020012341 /* if (trap_ptr != trap && tp[0]) */
Denys Vlasenko726e1a02009-09-25 02:58:20 +020012342 /* free(tr); */
Eric Andersencb57d552001-06-28 07:25:16 +000012343 }
12344 }
Denys Vlasenko726e1a02009-09-25 02:58:20 +020012345 /*
Denys Vlasenko21d87d42009-09-25 00:06:51 +020012346 if (trap_ptr != trap) {
12347 free(trap_ptr);
12348 trap_ptr = trap;
12349 }
Denys Vlasenko726e1a02009-09-25 02:58:20 +020012350 */
Eric Andersencb57d552001-06-28 07:25:16 +000012351 return 0;
12352 }
Denys Vlasenko21d87d42009-09-25 00:06:51 +020012353
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +000012354 action = NULL;
12355 if (ap[1])
Eric Andersencb57d552001-06-28 07:25:16 +000012356 action = *ap++;
Denys Vlasenko496d5bf2010-03-26 15:52:24 +010012357 exitcode = 0;
Eric Andersencb57d552001-06-28 07:25:16 +000012358 while (*ap) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +000012359 signo = get_signum(*ap);
Denys Vlasenko496d5bf2010-03-26 15:52:24 +010012360 if (signo < 0) {
12361 /* Mimic bash message exactly */
12362 ash_msg("%s: invalid signal specification", *ap);
12363 exitcode = 1;
12364 goto next;
12365 }
Denis Vlasenkob012b102007-02-19 22:43:01 +000012366 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +000012367 if (action) {
Denis Vlasenko9f739442006-12-16 23:49:13 +000012368 if (LONE_DASH(action))
Eric Andersencb57d552001-06-28 07:25:16 +000012369 action = NULL;
12370 else
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012371 action = ckstrdup(action);
Eric Andersencb57d552001-06-28 07:25:16 +000012372 }
Denis Vlasenko60818682007-09-28 22:07:23 +000012373 free(trap[signo]);
Denys Vlasenko238bf182010-05-18 15:49:07 +020012374 if (action)
12375 may_have_traps = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000012376 trap[signo] = action;
12377 if (signo != 0)
12378 setsignal(signo);
Denis Vlasenkob012b102007-02-19 22:43:01 +000012379 INT_ON;
Denys Vlasenko496d5bf2010-03-26 15:52:24 +010012380 next:
Eric Andersencb57d552001-06-28 07:25:16 +000012381 ap++;
12382 }
Denys Vlasenko496d5bf2010-03-26 15:52:24 +010012383 return exitcode;
Eric Andersencb57d552001-06-28 07:25:16 +000012384}
12385
Eric Andersenc470f442003-07-28 09:56:35 +000012386
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012387/* ============ Builtins */
Eric Andersenc470f442003-07-28 09:56:35 +000012388
Denis Vlasenko8e1c7152007-01-22 07:21:38 +000012389#if !ENABLE_FEATURE_SH_EXTRA_QUIET
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012390/*
12391 * Lists available builtins
12392 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012393static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012394helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersenc470f442003-07-28 09:56:35 +000012395{
Denis Vlasenko6b06cb82008-05-15 21:30:45 +000012396 unsigned col;
12397 unsigned i;
Eric Andersenc470f442003-07-28 09:56:35 +000012398
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +020012399 out1fmt(
Denis Vlasenko34d4d892009-04-04 20:24:37 +000012400 "Built-in commands:\n"
12401 "------------------\n");
Denis Vlasenkob71c6682007-07-21 15:08:09 +000012402 for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
Eric Andersenc470f442003-07-28 09:56:35 +000012403 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
Denis Vlasenko52764022007-02-24 13:42:56 +000012404 builtintab[i].name + 1);
Eric Andersenc470f442003-07-28 09:56:35 +000012405 if (col > 60) {
12406 out1fmt("\n");
12407 col = 0;
12408 }
12409 }
Denis Vlasenko80d14be2007-04-10 23:03:30 +000012410#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko1aa7e472007-11-28 06:49:03 +000012411 {
12412 const char *a = applet_names;
12413 while (*a) {
12414 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
12415 if (col > 60) {
12416 out1fmt("\n");
12417 col = 0;
12418 }
12419 a += strlen(a) + 1;
Eric Andersenc470f442003-07-28 09:56:35 +000012420 }
12421 }
12422#endif
12423 out1fmt("\n\n");
12424 return EXIT_SUCCESS;
12425}
Denis Vlasenko131ae172007-02-18 13:00:19 +000012426#endif /* FEATURE_SH_EXTRA_QUIET */
Eric Andersenc470f442003-07-28 09:56:35 +000012427
Eric Andersencb57d552001-06-28 07:25:16 +000012428/*
Eric Andersencb57d552001-06-28 07:25:16 +000012429 * The export and readonly commands.
12430 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012431static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012432exportcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +000012433{
12434 struct var *vp;
12435 char *name;
12436 const char *p;
Eric Andersenc470f442003-07-28 09:56:35 +000012437 char **aptr;
Denis Vlasenkob7304742008-10-20 08:15:51 +000012438 int flag = argv[0][0] == 'r' ? VREADONLY : VEXPORT;
Eric Andersencb57d552001-06-28 07:25:16 +000012439
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012440 if (nextopt("p") != 'p') {
12441 aptr = argptr;
12442 name = *aptr;
12443 if (name) {
12444 do {
12445 p = strchr(name, '=');
12446 if (p != NULL) {
12447 p++;
12448 } else {
12449 vp = *findvar(hashvar(name), name);
12450 if (vp) {
12451 vp->flags |= flag;
12452 continue;
12453 }
Eric Andersencb57d552001-06-28 07:25:16 +000012454 }
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012455 setvar(name, p, flag);
12456 } while ((name = *++aptr) != NULL);
12457 return 0;
12458 }
Eric Andersencb57d552001-06-28 07:25:16 +000012459 }
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012460 showvars(argv[0], flag, 0);
Eric Andersencb57d552001-06-28 07:25:16 +000012461 return 0;
12462}
12463
Eric Andersencb57d552001-06-28 07:25:16 +000012464/*
Denis Vlasenko5651bfc2007-02-23 21:08:58 +000012465 * Delete a function if it exists.
Eric Andersencb57d552001-06-28 07:25:16 +000012466 */
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012467static void
Denis Vlasenko5651bfc2007-02-23 21:08:58 +000012468unsetfunc(const char *name)
Aaron Lehmannb6ecbdc2001-12-06 03:37:38 +000012469{
Denis Vlasenko5651bfc2007-02-23 21:08:58 +000012470 struct tblentry *cmdp;
Eric Andersencb57d552001-06-28 07:25:16 +000012471
Denis Vlasenko5651bfc2007-02-23 21:08:58 +000012472 cmdp = cmdlookup(name, 0);
Denys Vlasenko1ed2fb42010-06-18 14:09:48 +020012473 if (cmdp != NULL && cmdp->cmdtype == CMDFUNCTION)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +000012474 delete_cmd_entry();
Eric Andersenc470f442003-07-28 09:56:35 +000012475}
12476
Eric Andersencb57d552001-06-28 07:25:16 +000012477/*
Eric Andersencb57d552001-06-28 07:25:16 +000012478 * The unset builtin command. We unset the function before we unset the
12479 * variable to allow a function to be unset when there is a readonly variable
12480 * with the same name.
12481 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012482static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012483unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersencb57d552001-06-28 07:25:16 +000012484{
12485 char **ap;
12486 int i;
Eric Andersenc470f442003-07-28 09:56:35 +000012487 int flag = 0;
Eric Andersencb57d552001-06-28 07:25:16 +000012488 int ret = 0;
12489
Denys Vlasenko1ed2fb42010-06-18 14:09:48 +020012490 while ((i = nextopt("vf")) != 0) {
Eric Andersenc470f442003-07-28 09:56:35 +000012491 flag = i;
Eric Andersencb57d552001-06-28 07:25:16 +000012492 }
Eric Andersencb57d552001-06-28 07:25:16 +000012493
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012494 for (ap = argptr; *ap; ap++) {
Eric Andersenc470f442003-07-28 09:56:35 +000012495 if (flag != 'f') {
12496 i = unsetvar(*ap);
12497 ret |= i;
12498 if (!(i & 2))
12499 continue;
12500 }
12501 if (flag != 'v')
Eric Andersencb57d552001-06-28 07:25:16 +000012502 unsetfunc(*ap);
Eric Andersencb57d552001-06-28 07:25:16 +000012503 }
Eric Andersenc470f442003-07-28 09:56:35 +000012504 return ret & 1;
Eric Andersencb57d552001-06-28 07:25:16 +000012505}
12506
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000012507static const unsigned char timescmd_str[] ALIGN1 = {
Manuel Novoa III 4456f252003-08-13 17:48:47 +000012508 ' ', offsetof(struct tms, tms_utime),
12509 '\n', offsetof(struct tms, tms_stime),
12510 ' ', offsetof(struct tms, tms_cutime),
12511 '\n', offsetof(struct tms, tms_cstime),
12512 0
12513};
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012514static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012515timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Manuel Novoa III 4456f252003-08-13 17:48:47 +000012516{
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012517 long clk_tck, s, t;
Manuel Novoa III 4456f252003-08-13 17:48:47 +000012518 const unsigned char *p;
12519 struct tms buf;
12520
12521 clk_tck = sysconf(_SC_CLK_TCK);
Eric Andersencb57d552001-06-28 07:25:16 +000012522 times(&buf);
Manuel Novoa III 4456f252003-08-13 17:48:47 +000012523
12524 p = timescmd_str;
12525 do {
12526 t = *(clock_t *)(((char *) &buf) + p[1]);
12527 s = t / clk_tck;
12528 out1fmt("%ldm%ld.%.3lds%c",
12529 s/60, s%60,
12530 ((t - s * clk_tck) * 1000) / clk_tck,
12531 p[0]);
Denys Vlasenko1ed2fb42010-06-18 14:09:48 +020012532 p += 2;
12533 } while (*p);
Manuel Novoa III 4456f252003-08-13 17:48:47 +000012534
Eric Andersencb57d552001-06-28 07:25:16 +000012535 return 0;
12536}
12537
Mike Frysinger98c52642009-04-02 10:02:37 +000012538#if ENABLE_SH_MATH_SUPPORT
Eric Andersenc470f442003-07-28 09:56:35 +000012539/*
Denys Vlasenko1ed2fb42010-06-18 14:09:48 +020012540 * The let builtin. Partially stolen from GNU Bash, the Bourne Again SHell.
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +000012541 * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
Eric Andersen90898442003-08-06 11:20:52 +000012542 *
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +000012543 * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
Eric Andersenc470f442003-07-28 09:56:35 +000012544 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012545static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012546letcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersenc470f442003-07-28 09:56:35 +000012547{
Denis Vlasenko68404f12008-03-17 09:00:54 +000012548 arith_t i;
Eric Andersenc470f442003-07-28 09:56:35 +000012549
Denis Vlasenko68404f12008-03-17 09:00:54 +000012550 argv++;
12551 if (!*argv)
Denis Vlasenkob012b102007-02-19 22:43:01 +000012552 ash_msg_and_raise_error("expression expected");
Denis Vlasenko68404f12008-03-17 09:00:54 +000012553 do {
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +000012554 i = ash_arith(*argv);
Denis Vlasenko68404f12008-03-17 09:00:54 +000012555 } while (*++argv);
Eric Andersenc470f442003-07-28 09:56:35 +000012556
Denis Vlasenkod9e15f22006-11-27 16:49:55 +000012557 return !i;
Eric Andersenc470f442003-07-28 09:56:35 +000012558}
Eric Andersenc470f442003-07-28 09:56:35 +000012559#endif
Eric Andersen74bcd162001-07-30 21:41:37 +000012560
Eric Andersenc470f442003-07-28 09:56:35 +000012561/*
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012562 * The read builtin. Options:
12563 * -r Do not interpret '\' specially
12564 * -s Turn off echo (tty only)
12565 * -n NCHARS Read NCHARS max
12566 * -p PROMPT Display PROMPT on stderr (if input is from tty)
12567 * -t SECONDS Timeout after SECONDS (tty or pipe only)
12568 * -u FD Read from given FD instead of fd 0
Eric Andersenc470f442003-07-28 09:56:35 +000012569 * This uses unbuffered input, which may be avoidable in some cases.
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012570 * TODO: bash also has:
12571 * -a ARRAY Read into array[0],[1],etc
12572 * -d DELIM End on DELIM char, not newline
12573 * -e Use line editing (tty only)
Eric Andersenc470f442003-07-28 09:56:35 +000012574 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012575static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012576readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersenc470f442003-07-28 09:56:35 +000012577{
Denys Vlasenko73067272010-01-12 22:11:24 +010012578 char *opt_n = NULL;
12579 char *opt_p = NULL;
12580 char *opt_t = NULL;
12581 char *opt_u = NULL;
12582 int read_flags = 0;
12583 const char *r;
Eric Andersenc470f442003-07-28 09:56:35 +000012584 int i;
12585
Denys Vlasenko73067272010-01-12 22:11:24 +010012586 while ((i = nextopt("p:u:rt:n:s")) != '\0') {
Denis Vlasenkobf0a2012006-12-26 10:42:51 +000012587 switch (i) {
Paul Fox02eb9342005-09-07 16:56:02 +000012588 case 'p':
Denys Vlasenko73067272010-01-12 22:11:24 +010012589 opt_p = optionarg;
Paul Fox02eb9342005-09-07 16:56:02 +000012590 break;
Paul Fox02eb9342005-09-07 16:56:02 +000012591 case 'n':
Denys Vlasenko73067272010-01-12 22:11:24 +010012592 opt_n = optionarg;
Paul Fox02eb9342005-09-07 16:56:02 +000012593 break;
12594 case 's':
Denys Vlasenko73067272010-01-12 22:11:24 +010012595 read_flags |= BUILTIN_READ_SILENT;
Paul Fox02eb9342005-09-07 16:56:02 +000012596 break;
Paul Fox02eb9342005-09-07 16:56:02 +000012597 case 't':
Denys Vlasenko73067272010-01-12 22:11:24 +010012598 opt_t = optionarg;
Paul Fox02eb9342005-09-07 16:56:02 +000012599 break;
Paul Fox02eb9342005-09-07 16:56:02 +000012600 case 'r':
Denys Vlasenko73067272010-01-12 22:11:24 +010012601 read_flags |= BUILTIN_READ_RAW;
Paul Fox02eb9342005-09-07 16:56:02 +000012602 break;
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012603 case 'u':
Denys Vlasenko73067272010-01-12 22:11:24 +010012604 opt_u = optionarg;
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012605 break;
Paul Fox02eb9342005-09-07 16:56:02 +000012606 default:
12607 break;
12608 }
Eric Andersenc470f442003-07-28 09:56:35 +000012609 }
Paul Fox02eb9342005-09-07 16:56:02 +000012610
Denys Vlasenko03dad222010-01-12 23:29:57 +010012611 r = shell_builtin_read(setvar2,
Denys Vlasenko73067272010-01-12 22:11:24 +010012612 argptr,
12613 bltinlookup("IFS"), /* can be NULL */
12614 read_flags,
12615 opt_n,
12616 opt_p,
12617 opt_t,
12618 opt_u
12619 );
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012620
Denys Vlasenko73067272010-01-12 22:11:24 +010012621 if ((uintptr_t)r > 1)
12622 ash_msg_and_raise_error(r);
Denis Vlasenko037576d2007-10-20 18:30:38 +000012623
Denys Vlasenko73067272010-01-12 22:11:24 +010012624 return (uintptr_t)r;
Eric Andersenc470f442003-07-28 09:56:35 +000012625}
12626
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012627static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012628umaskcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersenc470f442003-07-28 09:56:35 +000012629{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000012630 static const char permuser[3] ALIGN1 = "ugo";
12631 static const char permmode[3] ALIGN1 = "rwx";
12632 static const short permmask[] ALIGN2 = {
Eric Andersenc470f442003-07-28 09:56:35 +000012633 S_IRUSR, S_IWUSR, S_IXUSR,
12634 S_IRGRP, S_IWGRP, S_IXGRP,
12635 S_IROTH, S_IWOTH, S_IXOTH
12636 };
12637
Denis Vlasenkoeb858492009-04-18 02:06:54 +000012638 /* TODO: use bb_parse_mode() instead */
12639
Eric Andersenc470f442003-07-28 09:56:35 +000012640 char *ap;
12641 mode_t mask;
12642 int i;
12643 int symbolic_mode = 0;
12644
12645 while (nextopt("S") != '\0') {
12646 symbolic_mode = 1;
12647 }
12648
Denis Vlasenkob012b102007-02-19 22:43:01 +000012649 INT_OFF;
Eric Andersenc470f442003-07-28 09:56:35 +000012650 mask = umask(0);
12651 umask(mask);
Denis Vlasenkob012b102007-02-19 22:43:01 +000012652 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +000012653
Denis Vlasenko5cedb752007-02-18 19:56:41 +000012654 ap = *argptr;
12655 if (ap == NULL) {
Eric Andersenc470f442003-07-28 09:56:35 +000012656 if (symbolic_mode) {
12657 char buf[18];
12658 char *p = buf;
12659
12660 for (i = 0; i < 3; i++) {
12661 int j;
12662
12663 *p++ = permuser[i];
12664 *p++ = '=';
12665 for (j = 0; j < 3; j++) {
12666 if ((mask & permmask[3 * i + j]) == 0) {
12667 *p++ = permmode[j];
12668 }
12669 }
12670 *p++ = ',';
12671 }
12672 *--p = 0;
12673 puts(buf);
12674 } else {
12675 out1fmt("%.4o\n", mask);
12676 }
12677 } else {
Denis Vlasenkoaa744452007-02-23 01:04:22 +000012678 if (isdigit((unsigned char) *ap)) {
Eric Andersenc470f442003-07-28 09:56:35 +000012679 mask = 0;
12680 do {
12681 if (*ap >= '8' || *ap < '0')
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +020012682 ash_msg_and_raise_error(msg_illnum, argv[1]);
Eric Andersenc470f442003-07-28 09:56:35 +000012683 mask = (mask << 3) + (*ap - '0');
12684 } while (*++ap != '\0');
12685 umask(mask);
12686 } else {
12687 mask = ~mask & 0777;
12688 if (!bb_parse_mode(ap, &mask)) {
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +000012689 ash_msg_and_raise_error("illegal mode: %s", ap);
Eric Andersenc470f442003-07-28 09:56:35 +000012690 }
12691 umask(~mask & 0777);
12692 }
12693 }
12694 return 0;
12695}
12696
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012697static int FAST_FUNC
Denys Vlasenkof3c742f2010-03-06 20:12:00 +010012698ulimitcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersenc470f442003-07-28 09:56:35 +000012699{
Denys Vlasenkof3c742f2010-03-06 20:12:00 +010012700 return shell_builtin_ulimit(argv);
Eric Andersenc470f442003-07-28 09:56:35 +000012701}
12702
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012703/* ============ main() and helpers */
12704
12705/*
12706 * Called to exit the shell.
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012707 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012708static void exitshell(void) NORETURN;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012709static void
12710exitshell(void)
12711{
12712 struct jmploc loc;
12713 char *p;
12714 int status;
12715
12716 status = exitstatus;
12717 TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
12718 if (setjmp(loc.loc)) {
Denis Vlasenko7f88e342009-03-19 03:36:18 +000012719 if (exception_type == EXEXIT)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012720/* dash bug: it just does _exit(exitstatus) here
12721 * but we have to do setjobctl(0) first!
12722 * (bug is still not fixed in dash-0.5.3 - if you run dash
12723 * under Midnight Commander, on exit from dash MC is backgrounded) */
12724 status = exitstatus;
12725 goto out;
12726 }
12727 exception_handler = &loc;
12728 p = trap[0];
12729 if (p) {
12730 trap[0] = NULL;
12731 evalstring(p, 0);
Denys Vlasenko0800e3a2009-09-24 03:09:26 +020012732 free(p);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012733 }
12734 flush_stdout_stderr();
12735 out:
12736 setjobctl(0);
12737 _exit(status);
12738 /* NOTREACHED */
12739}
12740
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012741static void
12742init(void)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012743{
12744 /* from input.c: */
Denys Vlasenko82dd14a2010-05-17 10:10:01 +020012745 /* we will never free this */
12746 basepf.next_to_pgetc = basepf.buf = ckmalloc(IBUFSIZ);
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012747
12748 /* from trap.c: */
12749 signal(SIGCHLD, SIG_DFL);
Denys Vlasenko7a7b0342009-12-04 04:18:31 +010012750 /* bash re-enables SIGHUP which is SIG_IGNed on entry.
12751 * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
12752 */
12753 signal(SIGHUP, SIG_DFL);
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012754
12755 /* from var.c: */
12756 {
12757 char **envp;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012758 const char *p;
12759 struct stat st1, st2;
12760
12761 initvar();
12762 for (envp = environ; envp && *envp; envp++) {
12763 if (strchr(*envp, '=')) {
12764 setvareq(*envp, VEXPORT|VTEXTFIXED);
12765 }
12766 }
12767
Denys Vlasenko7bb346f2009-10-06 22:09:50 +020012768 setvar("PPID", utoa(getppid()), 0);
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012769
12770 p = lookupvar("PWD");
12771 if (p)
12772 if (*p != '/' || stat(p, &st1) || stat(".", &st2)
12773 || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino)
12774 p = '\0';
12775 setpwd(p, 0);
12776 }
12777}
12778
12779/*
12780 * Process the shell command line arguments.
12781 */
12782static void
Denis Vlasenko68404f12008-03-17 09:00:54 +000012783procargs(char **argv)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012784{
12785 int i;
12786 const char *xminusc;
12787 char **xargv;
12788
12789 xargv = argv;
12790 arg0 = xargv[0];
Denis Vlasenko68404f12008-03-17 09:00:54 +000012791 /* if (xargv[0]) - mmm, this is always true! */
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012792 xargv++;
12793 for (i = 0; i < NOPTS; i++)
12794 optlist[i] = 2;
12795 argptr = xargv;
Denis Vlasenko28bf6712008-02-14 15:01:47 +000012796 if (options(1)) {
12797 /* it already printed err message */
12798 raise_exception(EXERROR);
12799 }
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012800 xargv = argptr;
12801 xminusc = minusc;
12802 if (*xargv == NULL) {
12803 if (xminusc)
12804 ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
12805 sflag = 1;
12806 }
12807 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
12808 iflag = 1;
12809 if (mflag == 2)
12810 mflag = iflag;
12811 for (i = 0; i < NOPTS; i++)
12812 if (optlist[i] == 2)
12813 optlist[i] = 0;
12814#if DEBUG == 2
12815 debug = 1;
12816#endif
12817 /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
12818 if (xminusc) {
12819 minusc = *xargv++;
12820 if (*xargv)
12821 goto setarg0;
12822 } else if (!sflag) {
12823 setinputfile(*xargv, 0);
12824 setarg0:
12825 arg0 = *xargv++;
12826 commandname = arg0;
12827 }
12828
12829 shellparam.p = xargv;
12830#if ENABLE_ASH_GETOPTS
12831 shellparam.optind = 1;
12832 shellparam.optoff = -1;
12833#endif
Denis Vlasenko01631112007-12-16 17:20:38 +000012834 /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012835 while (*xargv) {
12836 shellparam.nparam++;
12837 xargv++;
12838 }
12839 optschanged();
12840}
12841
12842/*
12843 * Read /etc/profile or .profile.
12844 */
12845static void
12846read_profile(const char *name)
12847{
12848 int skip;
12849
12850 if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
12851 return;
12852 skip = cmdloop(0);
12853 popfile();
12854 if (skip)
12855 exitshell();
12856}
12857
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012858/*
12859 * This routine is called when an error or an interrupt occurs in an
12860 * interactive shell and control is returned to the main command loop.
12861 */
12862static void
12863reset(void)
12864{
12865 /* from eval.c: */
12866 evalskip = 0;
12867 loopnest = 0;
12868 /* from input.c: */
Denis Vlasenko41eb3002008-11-28 03:42:31 +000012869 g_parsefile->left_in_buffer = 0;
12870 g_parsefile->left_in_line = 0; /* clear input buffer */
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012871 popallfiles();
12872 /* from parser.c: */
12873 tokpushback = 0;
12874 checkkwd = 0;
12875 /* from redir.c: */
Denis Vlasenko34c73c42008-08-16 11:48:02 +000012876 clearredir(/*drop:*/ 0);
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012877}
12878
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012879#if PROFILE
12880static short profile_buf[16384];
12881extern int etext();
12882#endif
12883
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012884/*
12885 * Main routine. We initialize things, parse the arguments, execute
12886 * profiles if we're a login shell, and then call cmdloop to execute
12887 * commands. The setjmp call sets up the location to jump to when an
12888 * exception occurs. When an exception occurs the variable "state"
12889 * is used to figure out how far we had gotten.
12890 */
Denis Vlasenko9b49a5e2007-10-11 10:05:36 +000012891int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012892int ash_main(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012893{
Mike Frysinger98c52642009-04-02 10:02:37 +000012894 const char *shinit;
Denis Vlasenko4e12b1a2008-12-23 23:36:47 +000012895 volatile smallint state;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012896 struct jmploc jmploc;
12897 struct stackmark smark;
12898
Denis Vlasenko01631112007-12-16 17:20:38 +000012899 /* Initialize global data */
12900 INIT_G_misc();
12901 INIT_G_memstack();
12902 INIT_G_var();
Denis Vlasenkoee87ebf2007-12-21 22:18:16 +000012903#if ENABLE_ASH_ALIAS
Denis Vlasenko01631112007-12-16 17:20:38 +000012904 INIT_G_alias();
Denis Vlasenkoee87ebf2007-12-21 22:18:16 +000012905#endif
Denis Vlasenko01631112007-12-16 17:20:38 +000012906 INIT_G_cmdtable();
12907
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012908#if PROFILE
12909 monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
12910#endif
12911
12912#if ENABLE_FEATURE_EDITING
12913 line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
12914#endif
12915 state = 0;
12916 if (setjmp(jmploc.loc)) {
Denis Vlasenko7f88e342009-03-19 03:36:18 +000012917 smallint e;
Denis Vlasenko4e12b1a2008-12-23 23:36:47 +000012918 smallint s;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012919
12920 reset();
12921
Denis Vlasenko7f88e342009-03-19 03:36:18 +000012922 e = exception_type;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012923 if (e == EXERROR)
12924 exitstatus = 2;
12925 s = state;
12926 if (e == EXEXIT || s == 0 || iflag == 0 || shlvl)
12927 exitshell();
Denis Vlasenko7f88e342009-03-19 03:36:18 +000012928 if (e == EXINT)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012929 outcslow('\n', stderr);
Denis Vlasenko7f88e342009-03-19 03:36:18 +000012930
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012931 popstackmark(&smark);
12932 FORCE_INT_ON; /* enable interrupts */
12933 if (s == 1)
12934 goto state1;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000012935 if (s == 2)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012936 goto state2;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000012937 if (s == 3)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012938 goto state3;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000012939 goto state4;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012940 }
12941 exception_handler = &jmploc;
12942#if DEBUG
12943 opentrace();
Denis Vlasenko653d8e72009-03-19 21:59:35 +000012944 TRACE(("Shell args: "));
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000012945 trace_puts_args(argv);
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012946#endif
12947 rootpid = getpid();
12948
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012949 init();
12950 setstackmark(&smark);
Denis Vlasenko68404f12008-03-17 09:00:54 +000012951 procargs(argv);
12952
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012953#if ENABLE_FEATURE_EDITING_SAVEHISTORY
12954 if (iflag) {
12955 const char *hp = lookupvar("HISTFILE");
12956
12957 if (hp == NULL) {
12958 hp = lookupvar("HOME");
12959 if (hp != NULL) {
12960 char *defhp = concat_path_file(hp, ".ash_history");
12961 setvar("HISTFILE", defhp, 0);
12962 free(defhp);
12963 }
12964 }
12965 }
12966#endif
Denis Vlasenko4e12b1a2008-12-23 23:36:47 +000012967 if (/* argv[0] && */ argv[0][0] == '-')
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012968 isloginsh = 1;
12969 if (isloginsh) {
12970 state = 1;
12971 read_profile("/etc/profile");
12972 state1:
12973 state = 2;
12974 read_profile(".profile");
12975 }
12976 state2:
12977 state = 3;
12978 if (
12979#ifndef linux
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012980 getuid() == geteuid() && getgid() == getegid() &&
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012981#endif
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012982 iflag
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012983 ) {
12984 shinit = lookupvar("ENV");
12985 if (shinit != NULL && *shinit != '\0') {
12986 read_profile(shinit);
12987 }
12988 }
12989 state3:
12990 state = 4;
Denis Vlasenko5c2b8142009-03-19 01:59:59 +000012991 if (minusc) {
12992 /* evalstring pushes parsefile stack.
12993 * Ensure we don't falsely claim that 0 (stdin)
Denis Vlasenko5368ad52009-03-20 10:20:08 +000012994 * is one of stacked source fds.
12995 * Testcase: ash -c 'exec 1>&0' must not complain. */
Denys Vlasenko79b3d422010-06-03 04:29:08 +020012996 // if (!sflag) g_parsefile->pf_fd = -1;
Denys Vlasenko08d8b3c2010-06-03 04:28:28 +020012997 // ^^ not necessary since now we special-case fd 0
12998 // in is_hidden_fd() to not be considered "hidden fd"
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 */