blob: ef22da1b68021d88057efc79bfa3812a5fe9bdec [file] [log] [blame]
Eric Andersendf82f612001-06-28 07:46:40 +00001/* vi: set sw=4 ts=4: */
2/*
3 * ash shell port for busybox
4 *
Denys Vlasenko73067272010-01-12 22:11:24 +01005 * This code is derived from software contributed to Berkeley by
6 * Kenneth Almquist.
7 *
8 * Original BSD copyright notice is retained at the end of this file.
9 *
Eric Andersendf82f612001-06-28 07:46:40 +000010 * Copyright (c) 1989, 1991, 1993, 1994
Eric Andersen2870d962001-07-02 17:27:21 +000011 * The Regents of the University of California. All rights reserved.
Eric Andersencb57d552001-06-28 07:25:16 +000012 *
"Vladimir N. Oleynik"ddc280e2005-12-15 12:01:49 +000013 * Copyright (c) 1997-2005 Herbert Xu <herbert@gondor.apana.org.au>
Eric Andersen81fe1232003-07-29 06:38:40 +000014 * was re-ported from NetBSD and debianized.
15 *
Bernhard Reutner-Fischer86f5c992006-01-22 22:55:11 +000016 * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
Eric Andersencb57d552001-06-28 07:25:16 +000017 */
18
Eric Andersenc470f442003-07-28 09:56:35 +000019/*
Denis Vlasenko653d8e72009-03-19 21:59:35 +000020 * The following should be set to reflect the type of system you have:
Eric Andersenc470f442003-07-28 09:56:35 +000021 * JOBS -> 1 if you have Berkeley job control, 0 otherwise.
22 * define SYSV if you are running under System V.
23 * define DEBUG=1 to compile in debugging ('set -o debug' to turn on)
24 * define DEBUG=2 to compile in and turn on debugging.
25 *
26 * When debugging is on, debugging info will be written to ./trace and
27 * a quit signal will generate a core dump.
28 */
Denis Vlasenkof1733952009-03-19 23:21:55 +000029#define DEBUG 0
Denis Vlasenko653d8e72009-03-19 21:59:35 +000030/* Tweak debug output verbosity here */
31#define DEBUG_TIME 0
32#define DEBUG_PID 1
33#define DEBUG_SIG 1
34
Eric Andersenc470f442003-07-28 09:56:35 +000035#define PROFILE 0
Denis Vlasenko0e6f6612008-02-15 15:02:15 +000036
Denis Vlasenko0e6f6612008-02-15 15:02:15 +000037#define JOBS ENABLE_ASH_JOB_CONTROL
Eric Andersenc470f442003-07-28 09:56:35 +000038
Denis Vlasenkob012b102007-02-19 22:43:01 +000039#if DEBUG
Denis Vlasenko653d8e72009-03-19 21:59:35 +000040# ifndef _GNU_SOURCE
41# define _GNU_SOURCE
42# endif
Denis Vlasenkoe26b2782008-02-12 07:40:29 +000043#endif
Denis Vlasenko0e6f6612008-02-15 15:02:15 +000044
Denis Vlasenko1aa7e472007-11-28 06:49:03 +000045#include "busybox.h" /* for applet_names */
Denis Vlasenkob012b102007-02-19 22:43:01 +000046#include <paths.h>
47#include <setjmp.h>
48#include <fnmatch.h>
Denys Vlasenko73067272010-01-12 22:11:24 +010049
50#include "shell_common.h"
51#include "builtin_read.h"
Denys Vlasenkof3c742f2010-03-06 20:12:00 +010052#include "builtin_ulimit.h"
Mike Frysinger98c52642009-04-02 10:02:37 +000053#include "math.h"
Denys Vlasenko3ea2e822009-10-09 20:59:04 +020054#if ENABLE_ASH_RANDOM_SUPPORT
55# include "random.h"
Denys Vlasenko36df0482009-10-19 16:07:28 +020056#else
57# define CLEAR_RANDOM_T(rnd) ((void)0)
Denys Vlasenko3ea2e822009-10-09 20:59:04 +020058#endif
Denis Vlasenko61befda2008-11-25 01:36:03 +000059
Denys Vlasenko14974842010-03-23 01:08:26 +010060#define SKIP_definitions 1
61#include "applet_tables.h"
62#undef SKIP_definitions
63#if NUM_APPLETS == 1
Denis Vlasenko61befda2008-11-25 01:36:03 +000064/* STANDALONE does not make sense, and won't compile */
Denys Vlasenko3ea2e822009-10-09 20:59:04 +020065# undef CONFIG_FEATURE_SH_STANDALONE
66# undef ENABLE_FEATURE_SH_STANDALONE
67# undef IF_FEATURE_SH_STANDALONE
Denys Vlasenko14974842010-03-23 01:08:26 +010068# undef IF_NOT_FEATURE_SH_STANDALONE
Denys Vlasenko3ea2e822009-10-09 20:59:04 +020069# define ENABLE_FEATURE_SH_STANDALONE 0
70# define IF_FEATURE_SH_STANDALONE(...)
71# define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
Eric Andersencb57d552001-06-28 07:25:16 +000072#endif
73
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000074#ifndef PIPE_BUF
Denis Vlasenko653d8e72009-03-19 21:59:35 +000075# define PIPE_BUF 4096 /* amount of buffering in a pipe */
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000076#endif
77
Denys Vlasenko153fcaa2010-02-21 05:17:41 +010078#if !BB_MMU
Denis Vlasenko653d8e72009-03-19 21:59:35 +000079# error "Do not even bother, ash will not run on NOMMU machine"
Denis Vlasenkob012b102007-02-19 22:43:01 +000080#endif
81
Denis Vlasenkob012b102007-02-19 22:43:01 +000082
Denis Vlasenko01631112007-12-16 17:20:38 +000083/* ============ Hash table sizes. Configurable. */
84
85#define VTABSIZE 39
86#define ATABSIZE 39
87#define CMDTABLESIZE 31 /* should be prime */
88
89
Denis Vlasenkob012b102007-02-19 22:43:01 +000090/* ============ Shell options */
91
92static const char *const optletters_optnames[] = {
93 "e" "errexit",
94 "f" "noglob",
95 "I" "ignoreeof",
96 "i" "interactive",
97 "m" "monitor",
98 "n" "noexec",
99 "s" "stdin",
100 "x" "xtrace",
101 "v" "verbose",
102 "C" "noclobber",
103 "a" "allexport",
104 "b" "notify",
105 "u" "nounset",
Denys Vlasenkoe9ac32a2009-12-05 02:01:25 +0100106 "\0" "vi"
Michael Abbott359da5e2009-12-04 23:03:29 +0100107#if ENABLE_ASH_BASH_COMPAT
Denys Vlasenkoe9ac32a2009-12-05 02:01:25 +0100108 ,"\0" "pipefail"
Michael Abbott359da5e2009-12-04 23:03:29 +0100109#endif
Denis Vlasenkob012b102007-02-19 22:43:01 +0000110#if DEBUG
Denis Vlasenko6ca409e2007-08-12 20:58:27 +0000111 ,"\0" "nolog"
112 ,"\0" "debug"
Denis Vlasenkob012b102007-02-19 22:43:01 +0000113#endif
114};
115
Denys Vlasenko285ad152009-12-04 23:02:27 +0100116#define optletters(n) optletters_optnames[n][0]
117#define optnames(n) (optletters_optnames[n] + 1)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000118
Denis Vlasenko80b8b392007-06-25 10:55:35 +0000119enum { NOPTS = ARRAY_SIZE(optletters_optnames) };
Denis Vlasenkob012b102007-02-19 22:43:01 +0000120
Eric Andersenc470f442003-07-28 09:56:35 +0000121
Denis Vlasenkob012b102007-02-19 22:43:01 +0000122/* ============ Misc data */
Eric Andersenc470f442003-07-28 09:56:35 +0000123
Denis Vlasenko6ca409e2007-08-12 20:58:27 +0000124static const char homestr[] ALIGN1 = "HOME";
125static const char snlfmt[] ALIGN1 = "%s\n";
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200126static const char msg_illnum[] ALIGN1 = "Illegal number: %s";
Denis Vlasenkoaa744452007-02-23 01:04:22 +0000127
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +0000128/*
Eric Andersenc470f442003-07-28 09:56:35 +0000129 * We enclose jmp_buf in a structure so that we can declare pointers to
130 * jump locations. The global variable handler contains the location to
Denis Vlasenkof1733952009-03-19 23:21:55 +0000131 * jump to when an exception occurs, and the global variable exception_type
Eric Andersenaff114c2004-04-14 17:51:38 +0000132 * contains a code identifying the exception. To implement nested
Eric Andersenc470f442003-07-28 09:56:35 +0000133 * exception handlers, the user should save the value of handler on entry
134 * to an inner scope, set handler to point to a jmploc structure for the
135 * inner scope, and restore handler on exit from the scope.
136 */
Eric Andersenc470f442003-07-28 09:56:35 +0000137struct jmploc {
138 jmp_buf loc;
139};
Denis Vlasenko01631112007-12-16 17:20:38 +0000140
141struct globals_misc {
142 /* pid of main shell */
143 int rootpid;
144 /* shell level: 0 for the main shell, 1 for its children, and so on */
145 int shlvl;
146#define rootshell (!shlvl)
147 char *minusc; /* argument to -c option */
148
149 char *curdir; // = nullstr; /* current working directory */
150 char *physdir; // = nullstr; /* physical working directory */
151
152 char *arg0; /* value of $0 */
153
154 struct jmploc *exception_handler;
Denis Vlasenko991a1da2008-02-10 19:02:53 +0000155
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200156 volatile int suppress_int; /* counter */
157 volatile /*sig_atomic_t*/ smallint pending_int; /* 1 = got SIGINT */
Denis Vlasenko991a1da2008-02-10 19:02:53 +0000158 /* last pending signal */
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200159 volatile /*sig_atomic_t*/ smallint pending_sig;
Denis Vlasenko7f88e342009-03-19 03:36:18 +0000160 smallint exception_type; /* kind of exception (0..5) */
Denis Vlasenko01631112007-12-16 17:20:38 +0000161 /* exceptions */
Eric Andersenc470f442003-07-28 09:56:35 +0000162#define EXINT 0 /* SIGINT received */
163#define EXERROR 1 /* a generic error */
164#define EXSHELLPROC 2 /* execute a shell procedure */
165#define EXEXEC 3 /* command execution failed */
166#define EXEXIT 4 /* exit the shell */
167#define EXSIG 5 /* trapped signal in wait(1) */
Eric Andersen2870d962001-07-02 17:27:21 +0000168
Denis Vlasenko01631112007-12-16 17:20:38 +0000169 smallint isloginsh;
Denis Vlasenkob07a4962008-06-22 13:16:23 +0000170 char nullstr[1]; /* zero length string */
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000171
172 char optlist[NOPTS];
173#define eflag optlist[0]
174#define fflag optlist[1]
175#define Iflag optlist[2]
176#define iflag optlist[3]
177#define mflag optlist[4]
178#define nflag optlist[5]
179#define sflag optlist[6]
180#define xflag optlist[7]
181#define vflag optlist[8]
182#define Cflag optlist[9]
183#define aflag optlist[10]
184#define bflag optlist[11]
185#define uflag optlist[12]
186#define viflag optlist[13]
Michael Abbott359da5e2009-12-04 23:03:29 +0100187#if ENABLE_ASH_BASH_COMPAT
188# define pipefail optlist[14]
189#else
190# define pipefail 0
191#endif
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000192#if DEBUG
Michael Abbott359da5e2009-12-04 23:03:29 +0100193# define nolog optlist[14 + ENABLE_ASH_BASH_COMPAT]
194# define debug optlist[15 + ENABLE_ASH_BASH_COMPAT]
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000195#endif
196
197 /* trap handler commands */
Denis Vlasenko01631112007-12-16 17:20:38 +0000198 /*
199 * Sigmode records the current value of the signal handlers for the various
200 * modes. A value of zero means that the current handler is not known.
Denis Vlasenkof8535cc2008-12-03 10:36:26 +0000201 * S_HARD_IGN indicates that the signal was ignored on entry to the shell.
Denis Vlasenko01631112007-12-16 17:20:38 +0000202 */
203 char sigmode[NSIG - 1];
Denis Vlasenkof8535cc2008-12-03 10:36:26 +0000204#define S_DFL 1 /* default signal handling (SIG_DFL) */
205#define S_CATCH 2 /* signal is caught */
206#define S_IGN 3 /* signal is ignored (SIG_IGN) */
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +0000207#define S_HARD_IGN 4 /* signal is ignored permenantly */
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +0000208
Denis Vlasenko01631112007-12-16 17:20:38 +0000209 /* indicates specified signal received */
Denis Vlasenko4b875702009-03-19 13:30:04 +0000210 uint8_t gotsig[NSIG - 1]; /* offset by 1: "signal" 0 is meaningless */
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000211 char *trap[NSIG];
Denys Vlasenko21d87d42009-09-25 00:06:51 +0200212 char **trap_ptr; /* used only by "trap hack" */
Denis Vlasenko448d30e2008-06-27 00:24:11 +0000213
214 /* Rarely referenced stuff */
215#if ENABLE_ASH_RANDOM_SUPPORT
Denys Vlasenko3ea2e822009-10-09 20:59:04 +0200216 random_t random_gen;
Denis Vlasenko448d30e2008-06-27 00:24:11 +0000217#endif
218 pid_t backgndpid; /* pid of last background process */
219 smallint job_warning; /* user was warned about stopped jobs (can be 2, 1 or 0). */
Denis Vlasenko01631112007-12-16 17:20:38 +0000220};
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000221extern struct globals_misc *const ash_ptr_to_globals_misc;
222#define G_misc (*ash_ptr_to_globals_misc)
Denis Vlasenko26bc57d2008-06-27 00:29:34 +0000223#define rootpid (G_misc.rootpid )
224#define shlvl (G_misc.shlvl )
225#define minusc (G_misc.minusc )
226#define curdir (G_misc.curdir )
227#define physdir (G_misc.physdir )
228#define arg0 (G_misc.arg0 )
Denis Vlasenko01631112007-12-16 17:20:38 +0000229#define exception_handler (G_misc.exception_handler)
Denis Vlasenko7f88e342009-03-19 03:36:18 +0000230#define exception_type (G_misc.exception_type )
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200231#define suppress_int (G_misc.suppress_int )
232#define pending_int (G_misc.pending_int )
233#define pending_sig (G_misc.pending_sig )
Denis Vlasenko26bc57d2008-06-27 00:29:34 +0000234#define isloginsh (G_misc.isloginsh )
235#define nullstr (G_misc.nullstr )
236#define optlist (G_misc.optlist )
237#define sigmode (G_misc.sigmode )
238#define gotsig (G_misc.gotsig )
239#define trap (G_misc.trap )
Denys Vlasenko21d87d42009-09-25 00:06:51 +0200240#define trap_ptr (G_misc.trap_ptr )
Denys Vlasenko3ea2e822009-10-09 20:59:04 +0200241#define random_gen (G_misc.random_gen )
Denis Vlasenko448d30e2008-06-27 00:24:11 +0000242#define backgndpid (G_misc.backgndpid )
243#define job_warning (G_misc.job_warning)
Denis Vlasenko01631112007-12-16 17:20:38 +0000244#define INIT_G_misc() do { \
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000245 (*(struct globals_misc**)&ash_ptr_to_globals_misc) = xzalloc(sizeof(G_misc)); \
246 barrier(); \
Denis Vlasenko01631112007-12-16 17:20:38 +0000247 curdir = nullstr; \
248 physdir = nullstr; \
Denys Vlasenko21d87d42009-09-25 00:06:51 +0200249 trap_ptr = trap; \
Denis Vlasenko01631112007-12-16 17:20:38 +0000250} while (0)
251
252
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000253/* ============ DEBUG */
254#if DEBUG
255static void trace_printf(const char *fmt, ...);
256static void trace_vprintf(const char *fmt, va_list va);
257# define TRACE(param) trace_printf param
258# define TRACEV(param) trace_vprintf param
Denis Vlasenko1bb3d7e2009-03-20 07:45:36 +0000259# define close(fd) do { \
260 int dfd = (fd); \
Denis Vlasenkob9e70dd2009-03-20 01:24:08 +0000261 if (close(dfd) < 0) \
Denys Vlasenko883cea42009-07-11 15:31:59 +0200262 bb_error_msg("bug on %d: closing %d(0x%x)", \
Denis Vlasenko1bb3d7e2009-03-20 07:45:36 +0000263 __LINE__, dfd, dfd); \
Denis Vlasenkob9e70dd2009-03-20 01:24:08 +0000264} while (0)
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000265#else
266# define TRACE(param)
267# define TRACEV(param)
268#endif
269
270
Denis Vlasenko559691a2008-10-05 18:39:31 +0000271/* ============ Utility functions */
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000272#define xbarrier() do { __asm__ __volatile__ ("": : :"memory"); } while (0)
273
Denis Vlasenko559691a2008-10-05 18:39:31 +0000274static int isdigit_str9(const char *str)
275{
276 int maxlen = 9 + 1; /* max 9 digits: 999999999 */
277 while (--maxlen && isdigit(*str))
278 str++;
279 return (*str == '\0');
280}
Denis Vlasenko01631112007-12-16 17:20:38 +0000281
Denis Vlasenko559691a2008-10-05 18:39:31 +0000282
283/* ============ Interrupts / exceptions */
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +0000284/*
Eric Andersen2870d962001-07-02 17:27:21 +0000285 * These macros allow the user to suspend the handling of interrupt signals
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +0000286 * over a period of time. This is similar to SIGHOLD or to sigblock, but
Eric Andersen2870d962001-07-02 17:27:21 +0000287 * much more efficient and portable. (But hacking the kernel is so much
288 * more fun than worrying about efficiency and portability. :-))
289 */
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000290#define INT_OFF do { \
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200291 suppress_int++; \
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000292 xbarrier(); \
293} while (0)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000294
295/*
296 * Called to raise an exception. Since C doesn't include exceptions, we
297 * just do a longjmp to the exception handler. The type of exception is
Denis Vlasenko4b875702009-03-19 13:30:04 +0000298 * stored in the global variable "exception_type".
Denis Vlasenkob012b102007-02-19 22:43:01 +0000299 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +0000300static void raise_exception(int) NORETURN;
Denis Vlasenkob012b102007-02-19 22:43:01 +0000301static void
302raise_exception(int e)
303{
304#if DEBUG
Denis Vlasenko2da584f2007-02-19 22:44:05 +0000305 if (exception_handler == NULL)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000306 abort();
307#endif
308 INT_OFF;
Denis Vlasenko7f88e342009-03-19 03:36:18 +0000309 exception_type = e;
Denis Vlasenko2da584f2007-02-19 22:44:05 +0000310 longjmp(exception_handler->loc, 1);
Denis Vlasenkob012b102007-02-19 22:43:01 +0000311}
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000312#if DEBUG
313#define raise_exception(e) do { \
314 TRACE(("raising exception %d on line %d\n", (e), __LINE__)); \
315 raise_exception(e); \
316} while (0)
317#endif
Denis Vlasenkob012b102007-02-19 22:43:01 +0000318
319/*
320 * Called from trap.c when a SIGINT is received. (If the user specifies
321 * that SIGINT is to be trapped or ignored using the trap builtin, then
322 * this routine is not called.) Suppressint is nonzero when interrupts
323 * are held using the INT_OFF macro. (The test for iflag is just
324 * defensive programming.)
325 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +0000326static void raise_interrupt(void) NORETURN;
Denis Vlasenkob012b102007-02-19 22:43:01 +0000327static void
328raise_interrupt(void)
329{
Denis Vlasenko4b875702009-03-19 13:30:04 +0000330 int ex_type;
Denis Vlasenkob012b102007-02-19 22:43:01 +0000331
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200332 pending_int = 0;
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +0000333 /* Signal is not automatically unmasked after it is raised,
334 * do it ourself - unmask all signals */
Denis Vlasenko3f165fa2008-03-17 08:29:08 +0000335 sigprocmask_allsigs(SIG_UNBLOCK);
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200336 /* pending_sig = 0; - now done in onsig() */
Denis Vlasenko7c139b42007-03-21 20:17:27 +0000337
Denis Vlasenko4b875702009-03-19 13:30:04 +0000338 ex_type = EXSIG;
Denis Vlasenkob012b102007-02-19 22:43:01 +0000339 if (gotsig[SIGINT - 1] && !trap[SIGINT]) {
340 if (!(rootshell && iflag)) {
Denis Vlasenko991a1da2008-02-10 19:02:53 +0000341 /* Kill ourself with SIGINT */
Denis Vlasenkob012b102007-02-19 22:43:01 +0000342 signal(SIGINT, SIG_DFL);
343 raise(SIGINT);
344 }
Denis Vlasenko4b875702009-03-19 13:30:04 +0000345 ex_type = EXINT;
Denis Vlasenkob012b102007-02-19 22:43:01 +0000346 }
Denis Vlasenko4b875702009-03-19 13:30:04 +0000347 raise_exception(ex_type);
Denis Vlasenkob012b102007-02-19 22:43:01 +0000348 /* NOTREACHED */
349}
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000350#if DEBUG
351#define raise_interrupt() do { \
352 TRACE(("raising interrupt on line %d\n", __LINE__)); \
353 raise_interrupt(); \
354} while (0)
355#endif
Denis Vlasenkob012b102007-02-19 22:43:01 +0000356
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000357static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000358int_on(void)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000359{
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +0000360 xbarrier();
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200361 if (--suppress_int == 0 && pending_int) {
Denis Vlasenkob012b102007-02-19 22:43:01 +0000362 raise_interrupt();
363 }
364}
365#define INT_ON int_on()
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000366static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000367force_int_on(void)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000368{
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +0000369 xbarrier();
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200370 suppress_int = 0;
371 if (pending_int)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000372 raise_interrupt();
373}
374#define FORCE_INT_ON force_int_on()
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000375
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200376#define SAVE_INT(v) ((v) = suppress_int)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000377
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000378#define RESTORE_INT(v) do { \
379 xbarrier(); \
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200380 suppress_int = (v); \
381 if (suppress_int == 0 && pending_int) \
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000382 raise_interrupt(); \
383} while (0)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000384
Glenn L McGrath9fef17d2002-08-22 18:41:20 +0000385
Denis Vlasenkobc54cff2007-02-23 01:05:52 +0000386/* ============ Stdout/stderr output */
Eric Andersenc470f442003-07-28 09:56:35 +0000387
Eric Andersenc470f442003-07-28 09:56:35 +0000388static void
Denis Vlasenkob012b102007-02-19 22:43:01 +0000389outstr(const char *p, FILE *file)
Denis Vlasenkoe5570da2007-02-19 22:41:55 +0000390{
Denis Vlasenkob012b102007-02-19 22:43:01 +0000391 INT_OFF;
392 fputs(p, file);
393 INT_ON;
394}
395
396static void
397flush_stdout_stderr(void)
398{
399 INT_OFF;
Denys Vlasenko8131eea2009-11-02 14:19:51 +0100400 fflush_all();
Denis Vlasenkob012b102007-02-19 22:43:01 +0000401 INT_ON;
402}
403
404static void
405outcslow(int c, FILE *dest)
406{
407 INT_OFF;
408 putc(c, dest);
409 fflush(dest);
410 INT_ON;
411}
412
413static int out1fmt(const char *, ...) __attribute__((__format__(__printf__,1,2)));
414static int
415out1fmt(const char *fmt, ...)
416{
417 va_list ap;
418 int r;
419
420 INT_OFF;
421 va_start(ap, fmt);
422 r = vprintf(fmt, ap);
423 va_end(ap);
424 INT_ON;
425 return r;
426}
427
428static int fmtstr(char *, size_t, const char *, ...) __attribute__((__format__(__printf__,3,4)));
429static int
430fmtstr(char *outbuf, size_t length, const char *fmt, ...)
431{
432 va_list ap;
433 int ret;
434
435 va_start(ap, fmt);
436 INT_OFF;
437 ret = vsnprintf(outbuf, length, fmt, ap);
438 va_end(ap);
439 INT_ON;
440 return ret;
441}
442
443static void
444out1str(const char *p)
445{
446 outstr(p, stdout);
447}
448
449static void
450out2str(const char *p)
451{
452 outstr(p, stderr);
Denys Vlasenko8131eea2009-11-02 14:19:51 +0100453 flush_stdout_stderr();
Denis Vlasenkob012b102007-02-19 22:43:01 +0000454}
455
456
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +0000457/* ============ Parser structures */
Denis Vlasenko4d2183b2007-02-23 01:05:38 +0000458
Denis Vlasenko5651bfc2007-02-23 21:08:58 +0000459/* control characters in argument strings */
Denys Vlasenko2ce42e92009-11-29 02:18:13 +0100460#define CTL_FIRST CTLESC
Denys Vlasenkob6c84342009-08-29 20:23:20 +0200461#define CTLESC ((unsigned char)'\201') /* escape next character */
462#define CTLVAR ((unsigned char)'\202') /* variable defn */
463#define CTLENDVAR ((unsigned char)'\203')
464#define CTLBACKQ ((unsigned char)'\204')
Denis Vlasenko5651bfc2007-02-23 21:08:58 +0000465#define CTLQUOTE 01 /* ored with CTLBACKQ code if in quotes */
466/* CTLBACKQ | CTLQUOTE == '\205' */
Denys Vlasenkob6c84342009-08-29 20:23:20 +0200467#define CTLARI ((unsigned char)'\206') /* arithmetic expression */
468#define CTLENDARI ((unsigned char)'\207')
469#define CTLQUOTEMARK ((unsigned char)'\210')
Denys Vlasenko2ce42e92009-11-29 02:18:13 +0100470#define CTL_LAST CTLQUOTEMARK
Denis Vlasenko5651bfc2007-02-23 21:08:58 +0000471
472/* variable substitution byte (follows CTLVAR) */
473#define VSTYPE 0x0f /* type of variable substitution */
474#define VSNUL 0x10 /* colon--treat the empty string as unset */
475#define VSQUOTE 0x80 /* inside double quotes--suppress splitting */
476
477/* values of VSTYPE field */
Denis Vlasenko92e13c22008-03-25 01:17:40 +0000478#define VSNORMAL 0x1 /* normal variable: $var or ${var} */
479#define VSMINUS 0x2 /* ${var-text} */
480#define VSPLUS 0x3 /* ${var+text} */
481#define VSQUESTION 0x4 /* ${var?message} */
482#define VSASSIGN 0x5 /* ${var=text} */
483#define VSTRIMRIGHT 0x6 /* ${var%pattern} */
484#define VSTRIMRIGHTMAX 0x7 /* ${var%%pattern} */
485#define VSTRIMLEFT 0x8 /* ${var#pattern} */
486#define VSTRIMLEFTMAX 0x9 /* ${var##pattern} */
487#define VSLENGTH 0xa /* ${#var} */
488#if ENABLE_ASH_BASH_COMPAT
489#define VSSUBSTR 0xc /* ${var:position:length} */
490#define VSREPLACE 0xd /* ${var/pattern/replacement} */
491#define VSREPLACEALL 0xe /* ${var//pattern/replacement} */
492#endif
Denis Vlasenko5651bfc2007-02-23 21:08:58 +0000493
Denis Vlasenko6ca409e2007-08-12 20:58:27 +0000494static const char dolatstr[] ALIGN1 = {
495 CTLVAR, VSNORMAL|VSQUOTE, '@', '=', '\0'
496};
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +0000497
Denis Vlasenko559691a2008-10-05 18:39:31 +0000498#define NCMD 0
499#define NPIPE 1
500#define NREDIR 2
501#define NBACKGND 3
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000502#define NSUBSHELL 4
Denis Vlasenko559691a2008-10-05 18:39:31 +0000503#define NAND 5
504#define NOR 6
505#define NSEMI 7
506#define NIF 8
507#define NWHILE 9
508#define NUNTIL 10
509#define NFOR 11
510#define NCASE 12
511#define NCLIST 13
512#define NDEFUN 14
513#define NARG 15
514#define NTO 16
515#if ENABLE_ASH_BASH_COMPAT
516#define NTO2 17
517#endif
518#define NCLOBBER 18
519#define NFROM 19
520#define NFROMTO 20
521#define NAPPEND 21
522#define NTOFD 22
523#define NFROMFD 23
524#define NHERE 24
525#define NXHERE 25
526#define NNOT 26
Denis Vlasenko340299a2008-11-21 10:36:36 +0000527#define N_NUMBER 27
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000528
529union node;
530
531struct ncmd {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000532 smallint type; /* Nxxxx */
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000533 union node *assign;
534 union node *args;
535 union node *redirect;
536};
537
538struct npipe {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000539 smallint type;
540 smallint pipe_backgnd;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000541 struct nodelist *cmdlist;
542};
543
544struct nredir {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000545 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000546 union node *n;
547 union node *redirect;
548};
549
550struct nbinary {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000551 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000552 union node *ch1;
553 union node *ch2;
554};
555
556struct nif {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000557 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000558 union node *test;
559 union node *ifpart;
560 union node *elsepart;
561};
562
563struct nfor {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000564 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000565 union node *args;
566 union node *body;
567 char *var;
568};
569
570struct ncase {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000571 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000572 union node *expr;
573 union node *cases;
574};
575
576struct nclist {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000577 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000578 union node *next;
579 union node *pattern;
580 union node *body;
581};
582
583struct narg {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000584 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000585 union node *next;
586 char *text;
587 struct nodelist *backquote;
588};
589
Denis Vlasenko559691a2008-10-05 18:39:31 +0000590/* nfile and ndup layout must match!
591 * NTOFD (>&fdnum) uses ndup structure, but we may discover mid-flight
592 * that it is actually NTO2 (>&file), and change its type.
593 */
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000594struct nfile {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000595 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000596 union node *next;
597 int fd;
Denis Vlasenko559691a2008-10-05 18:39:31 +0000598 int _unused_dupfd;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000599 union node *fname;
600 char *expfname;
601};
602
603struct ndup {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000604 smallint type;
Denis Vlasenko559691a2008-10-05 18:39:31 +0000605 union node *next;
606 int fd;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000607 int dupfd;
608 union node *vname;
Denis Vlasenko559691a2008-10-05 18:39:31 +0000609 char *_unused_expfname;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000610};
611
612struct nhere {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000613 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000614 union node *next;
615 int fd;
616 union node *doc;
617};
618
619struct nnot {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000620 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000621 union node *com;
622};
623
624union node {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000625 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000626 struct ncmd ncmd;
627 struct npipe npipe;
628 struct nredir nredir;
629 struct nbinary nbinary;
630 struct nif nif;
631 struct nfor nfor;
632 struct ncase ncase;
633 struct nclist nclist;
634 struct narg narg;
635 struct nfile nfile;
636 struct ndup ndup;
637 struct nhere nhere;
638 struct nnot nnot;
639};
640
Denys Vlasenko86e83ec2009-07-23 22:07:07 +0200641/*
642 * NODE_EOF is returned by parsecmd when it encounters an end of file.
643 * It must be distinct from NULL.
644 */
645#define NODE_EOF ((union node *) -1L)
646
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000647struct nodelist {
648 struct nodelist *next;
649 union node *n;
650};
651
652struct funcnode {
653 int count;
654 union node n;
655};
656
Denis Vlasenko5651bfc2007-02-23 21:08:58 +0000657/*
658 * Free a parse tree.
659 */
660static void
661freefunc(struct funcnode *f)
662{
663 if (f && --f->count < 0)
664 free(f);
665}
666
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000667
668/* ============ Debugging output */
669
670#if DEBUG
671
672static FILE *tracefile;
673
674static void
675trace_printf(const char *fmt, ...)
676{
677 va_list va;
678
679 if (debug != 1)
680 return;
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000681 if (DEBUG_TIME)
682 fprintf(tracefile, "%u ", (int) time(NULL));
683 if (DEBUG_PID)
684 fprintf(tracefile, "[%u] ", (int) getpid());
685 if (DEBUG_SIG)
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200686 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000687 va_start(va, fmt);
688 vfprintf(tracefile, fmt, va);
689 va_end(va);
690}
691
692static void
693trace_vprintf(const char *fmt, va_list va)
694{
695 if (debug != 1)
696 return;
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000697 if (DEBUG_TIME)
698 fprintf(tracefile, "%u ", (int) time(NULL));
699 if (DEBUG_PID)
700 fprintf(tracefile, "[%u] ", (int) getpid());
701 if (DEBUG_SIG)
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200702 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000703 vfprintf(tracefile, fmt, va);
704}
705
706static void
707trace_puts(const char *s)
708{
709 if (debug != 1)
710 return;
711 fputs(s, tracefile);
712}
713
714static void
715trace_puts_quoted(char *s)
716{
717 char *p;
718 char c;
719
720 if (debug != 1)
721 return;
722 putc('"', tracefile);
723 for (p = s; *p; p++) {
Denys Vlasenkocd716832009-11-28 22:14:02 +0100724 switch ((unsigned char)*p) {
725 case '\n': c = 'n'; goto backslash;
726 case '\t': c = 't'; goto backslash;
727 case '\r': c = 'r'; goto backslash;
728 case '\"': c = '\"'; goto backslash;
729 case '\\': c = '\\'; goto backslash;
730 case CTLESC: c = 'e'; goto backslash;
731 case CTLVAR: c = 'v'; goto backslash;
732 case CTLVAR+CTLQUOTE: c = 'V'; goto backslash;
733 case CTLBACKQ: c = 'q'; goto backslash;
734 case CTLBACKQ+CTLQUOTE: c = 'Q'; goto backslash;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000735 backslash:
736 putc('\\', tracefile);
737 putc(c, tracefile);
738 break;
739 default:
740 if (*p >= ' ' && *p <= '~')
741 putc(*p, tracefile);
742 else {
743 putc('\\', tracefile);
Denys Vlasenkocd716832009-11-28 22:14:02 +0100744 putc((*p >> 6) & 03, tracefile);
745 putc((*p >> 3) & 07, tracefile);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000746 putc(*p & 07, tracefile);
747 }
748 break;
749 }
750 }
751 putc('"', tracefile);
752}
753
754static void
755trace_puts_args(char **ap)
756{
757 if (debug != 1)
758 return;
759 if (!*ap)
760 return;
761 while (1) {
762 trace_puts_quoted(*ap);
763 if (!*++ap) {
764 putc('\n', tracefile);
765 break;
766 }
767 putc(' ', tracefile);
768 }
769}
770
771static void
772opentrace(void)
773{
774 char s[100];
775#ifdef O_APPEND
776 int flags;
777#endif
778
779 if (debug != 1) {
780 if (tracefile)
781 fflush(tracefile);
782 /* leave open because libedit might be using it */
783 return;
784 }
785 strcpy(s, "./trace");
786 if (tracefile) {
787 if (!freopen(s, "a", tracefile)) {
788 fprintf(stderr, "Can't re-open %s\n", s);
789 debug = 0;
790 return;
791 }
792 } else {
793 tracefile = fopen(s, "a");
794 if (tracefile == NULL) {
795 fprintf(stderr, "Can't open %s\n", s);
796 debug = 0;
797 return;
798 }
799 }
800#ifdef O_APPEND
Denis Vlasenkod37f2222007-08-19 13:42:08 +0000801 flags = fcntl(fileno(tracefile), F_GETFL);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000802 if (flags >= 0)
803 fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
804#endif
805 setlinebuf(tracefile);
806 fputs("\nTracing started.\n", tracefile);
807}
808
809static void
810indent(int amount, char *pfx, FILE *fp)
811{
812 int i;
813
814 for (i = 0; i < amount; i++) {
815 if (pfx && i == amount - 1)
816 fputs(pfx, fp);
817 putc('\t', fp);
818 }
819}
820
821/* little circular references here... */
822static void shtree(union node *n, int ind, char *pfx, FILE *fp);
823
824static void
825sharg(union node *arg, FILE *fp)
826{
827 char *p;
828 struct nodelist *bqlist;
Denys Vlasenkocd716832009-11-28 22:14:02 +0100829 unsigned char subtype;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000830
831 if (arg->type != NARG) {
832 out1fmt("<node type %d>\n", arg->type);
833 abort();
834 }
835 bqlist = arg->narg.backquote;
836 for (p = arg->narg.text; *p; p++) {
Denys Vlasenkocd716832009-11-28 22:14:02 +0100837 switch ((unsigned char)*p) {
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000838 case CTLESC:
839 putc(*++p, fp);
840 break;
841 case CTLVAR:
842 putc('$', fp);
843 putc('{', fp);
844 subtype = *++p;
845 if (subtype == VSLENGTH)
846 putc('#', fp);
847
848 while (*p != '=')
849 putc(*p++, fp);
850
851 if (subtype & VSNUL)
852 putc(':', fp);
853
854 switch (subtype & VSTYPE) {
855 case VSNORMAL:
856 putc('}', fp);
857 break;
858 case VSMINUS:
859 putc('-', fp);
860 break;
861 case VSPLUS:
862 putc('+', fp);
863 break;
864 case VSQUESTION:
865 putc('?', fp);
866 break;
867 case VSASSIGN:
868 putc('=', fp);
869 break;
870 case VSTRIMLEFT:
871 putc('#', fp);
872 break;
873 case VSTRIMLEFTMAX:
874 putc('#', fp);
875 putc('#', fp);
876 break;
877 case VSTRIMRIGHT:
878 putc('%', fp);
879 break;
880 case VSTRIMRIGHTMAX:
881 putc('%', fp);
882 putc('%', fp);
883 break;
884 case VSLENGTH:
885 break;
886 default:
887 out1fmt("<subtype %d>", subtype);
888 }
889 break;
890 case CTLENDVAR:
891 putc('}', fp);
892 break;
893 case CTLBACKQ:
894 case CTLBACKQ|CTLQUOTE:
895 putc('$', fp);
896 putc('(', fp);
897 shtree(bqlist->n, -1, NULL, fp);
898 putc(')', fp);
899 break;
900 default:
901 putc(*p, fp);
902 break;
903 }
904 }
905}
906
Denys Vlasenko641dd7b2009-06-11 19:30:19 +0200907static void
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000908shcmd(union node *cmd, FILE *fp)
909{
910 union node *np;
911 int first;
912 const char *s;
913 int dftfd;
914
915 first = 1;
916 for (np = cmd->ncmd.args; np; np = np->narg.next) {
Denis Vlasenko40ba9982007-07-14 00:48:29 +0000917 if (!first)
918 putc(' ', fp);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000919 sharg(np, fp);
920 first = 0;
921 }
922 for (np = cmd->ncmd.redirect; np; np = np->nfile.next) {
Denis Vlasenko40ba9982007-07-14 00:48:29 +0000923 if (!first)
924 putc(' ', fp);
925 dftfd = 0;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000926 switch (np->nfile.type) {
Denis Vlasenko40ba9982007-07-14 00:48:29 +0000927 case NTO: s = ">>"+1; dftfd = 1; break;
928 case NCLOBBER: s = ">|"; dftfd = 1; break;
929 case NAPPEND: s = ">>"; dftfd = 1; break;
Denis Vlasenko559691a2008-10-05 18:39:31 +0000930#if ENABLE_ASH_BASH_COMPAT
931 case NTO2:
932#endif
Denis Vlasenko40ba9982007-07-14 00:48:29 +0000933 case NTOFD: s = ">&"; dftfd = 1; break;
Denis Vlasenko559691a2008-10-05 18:39:31 +0000934 case NFROM: s = "<"; break;
Denis Vlasenko40ba9982007-07-14 00:48:29 +0000935 case NFROMFD: s = "<&"; break;
936 case NFROMTO: s = "<>"; break;
937 default: s = "*error*"; break;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000938 }
939 if (np->nfile.fd != dftfd)
940 fprintf(fp, "%d", np->nfile.fd);
941 fputs(s, fp);
942 if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
943 fprintf(fp, "%d", np->ndup.dupfd);
944 } else {
945 sharg(np->nfile.fname, fp);
946 }
947 first = 0;
948 }
949}
950
951static void
952shtree(union node *n, int ind, char *pfx, FILE *fp)
953{
954 struct nodelist *lp;
955 const char *s;
956
957 if (n == NULL)
958 return;
959
960 indent(ind, pfx, fp);
Denys Vlasenko86e83ec2009-07-23 22:07:07 +0200961
962 if (n == NODE_EOF) {
963 fputs("<EOF>", fp);
964 return;
965 }
966
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000967 switch (n->type) {
968 case NSEMI:
969 s = "; ";
970 goto binop;
971 case NAND:
972 s = " && ";
973 goto binop;
974 case NOR:
975 s = " || ";
976 binop:
977 shtree(n->nbinary.ch1, ind, NULL, fp);
978 /* if (ind < 0) */
979 fputs(s, fp);
980 shtree(n->nbinary.ch2, ind, NULL, fp);
981 break;
982 case NCMD:
983 shcmd(n, fp);
984 if (ind >= 0)
985 putc('\n', fp);
986 break;
987 case NPIPE:
988 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
Denys Vlasenko7cee00e2009-07-24 01:08:03 +0200989 shtree(lp->n, 0, NULL, fp);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000990 if (lp->next)
991 fputs(" | ", fp);
992 }
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000993 if (n->npipe.pipe_backgnd)
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000994 fputs(" &", fp);
995 if (ind >= 0)
996 putc('\n', fp);
997 break;
998 default:
999 fprintf(fp, "<node type %d>", n->type);
1000 if (ind >= 0)
1001 putc('\n', fp);
1002 break;
1003 }
1004}
1005
1006static void
1007showtree(union node *n)
1008{
1009 trace_puts("showtree called\n");
Denys Vlasenko883cea42009-07-11 15:31:59 +02001010 shtree(n, 1, NULL, stderr);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00001011}
1012
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00001013#endif /* DEBUG */
1014
1015
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00001016/* ============ Parser data */
1017
1018/*
Denis Vlasenkob012b102007-02-19 22:43:01 +00001019 * ash_vmsg() needs parsefile->fd, hence parsefile definition is moved up.
1020 */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001021struct strlist {
1022 struct strlist *next;
1023 char *text;
1024};
1025
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00001026struct alias;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00001027
Denis Vlasenkob012b102007-02-19 22:43:01 +00001028struct strpush {
1029 struct strpush *prev; /* preceding string on stack */
Denis Vlasenko41eb3002008-11-28 03:42:31 +00001030 char *prev_string;
1031 int prev_left_in_line;
Denis Vlasenkob012b102007-02-19 22:43:01 +00001032#if ENABLE_ASH_ALIAS
1033 struct alias *ap; /* if push was associated with an alias */
1034#endif
1035 char *string; /* remember the string since it may change */
1036};
1037
1038struct parsefile {
1039 struct parsefile *prev; /* preceding file on stack */
1040 int linno; /* current line */
1041 int fd; /* file descriptor (or -1 if string) */
Denis Vlasenko41eb3002008-11-28 03:42:31 +00001042 int left_in_line; /* number of chars left in this line */
1043 int left_in_buffer; /* number of chars left in this buffer past the line */
1044 char *next_to_pgetc; /* next char in buffer */
Denis Vlasenkob012b102007-02-19 22:43:01 +00001045 char *buf; /* input buffer */
1046 struct strpush *strpush; /* for pushing strings at this level */
1047 struct strpush basestrpush; /* so pushing one is fast */
1048};
1049
Denis Vlasenko448d30e2008-06-27 00:24:11 +00001050static struct parsefile basepf; /* top level input file */
Denis Vlasenkob07a4962008-06-22 13:16:23 +00001051static struct parsefile *g_parsefile = &basepf; /* current input file */
Denis Vlasenkob012b102007-02-19 22:43:01 +00001052static int startlinno; /* line # where last token started */
1053static char *commandname; /* currently executing command */
1054static struct strlist *cmdenviron; /* environment for builtin command */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00001055static uint8_t exitstatus; /* exit status of last command */
Denis Vlasenkob012b102007-02-19 22:43:01 +00001056
1057
1058/* ============ Message printing */
1059
1060static void
1061ash_vmsg(const char *msg, va_list ap)
1062{
1063 fprintf(stderr, "%s: ", arg0);
1064 if (commandname) {
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00001065 if (strcmp(arg0, commandname))
1066 fprintf(stderr, "%s: ", commandname);
Denis Vlasenkob07a4962008-06-22 13:16:23 +00001067 if (!iflag || g_parsefile->fd)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00001068 fprintf(stderr, "line %d: ", startlinno);
Eric Andersenc470f442003-07-28 09:56:35 +00001069 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00001070 vfprintf(stderr, msg, ap);
1071 outcslow('\n', stderr);
Eric Andersenc470f442003-07-28 09:56:35 +00001072}
Denis Vlasenkob012b102007-02-19 22:43:01 +00001073
1074/*
1075 * Exverror is called to raise the error exception. If the second argument
1076 * is not NULL then error prints an error message using printf style
1077 * formatting. It then raises the error exception.
1078 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001079static void ash_vmsg_and_raise(int, const char *, va_list) NORETURN;
Denis Vlasenkob012b102007-02-19 22:43:01 +00001080static void
1081ash_vmsg_and_raise(int cond, const char *msg, va_list ap)
Eric Andersenc470f442003-07-28 09:56:35 +00001082{
Denis Vlasenkob012b102007-02-19 22:43:01 +00001083#if DEBUG
1084 if (msg) {
1085 TRACE(("ash_vmsg_and_raise(%d, \"", cond));
1086 TRACEV((msg, ap));
1087 TRACE(("\") pid=%d\n", getpid()));
1088 } else
1089 TRACE(("ash_vmsg_and_raise(%d, NULL) pid=%d\n", cond, getpid()));
1090 if (msg)
1091#endif
1092 ash_vmsg(msg, ap);
1093
1094 flush_stdout_stderr();
1095 raise_exception(cond);
1096 /* NOTREACHED */
Eric Andersenc470f442003-07-28 09:56:35 +00001097}
Denis Vlasenkob012b102007-02-19 22:43:01 +00001098
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001099static void ash_msg_and_raise_error(const char *, ...) NORETURN;
Denis Vlasenkob012b102007-02-19 22:43:01 +00001100static void
1101ash_msg_and_raise_error(const char *msg, ...)
1102{
1103 va_list ap;
1104
1105 va_start(ap, msg);
1106 ash_vmsg_and_raise(EXERROR, msg, ap);
1107 /* NOTREACHED */
1108 va_end(ap);
1109}
1110
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00001111static void raise_error_syntax(const char *) NORETURN;
1112static void
1113raise_error_syntax(const char *msg)
1114{
1115 ash_msg_and_raise_error("syntax error: %s", msg);
1116 /* NOTREACHED */
1117}
1118
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001119static void ash_msg_and_raise(int, const char *, ...) NORETURN;
Denis Vlasenkob012b102007-02-19 22:43:01 +00001120static void
1121ash_msg_and_raise(int cond, const char *msg, ...)
1122{
1123 va_list ap;
1124
1125 va_start(ap, msg);
1126 ash_vmsg_and_raise(cond, msg, ap);
1127 /* NOTREACHED */
1128 va_end(ap);
1129}
1130
1131/*
1132 * error/warning routines for external builtins
1133 */
1134static void
1135ash_msg(const char *fmt, ...)
1136{
1137 va_list ap;
1138
1139 va_start(ap, fmt);
1140 ash_vmsg(fmt, ap);
1141 va_end(ap);
1142}
1143
1144/*
1145 * Return a string describing an error. The returned string may be a
1146 * pointer to a static buffer that will be overwritten on the next call.
1147 * Action describes the operation that got the error.
1148 */
1149static const char *
1150errmsg(int e, const char *em)
1151{
1152 if (e == ENOENT || e == ENOTDIR) {
1153 return em;
1154 }
1155 return strerror(e);
1156}
1157
1158
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001159/* ============ Memory allocation */
1160
Denys Vlasenkoe7670ff2009-10-11 00:45:25 +02001161#if 0
1162/* I consider these wrappers nearly useless:
1163 * ok, they return you to nearest exception handler, but
1164 * how much memory do you leak in the process, making
1165 * memory starvation worse?
1166 */
1167static void *
1168ckrealloc(void * p, size_t nbytes)
1169{
1170 p = realloc(p, nbytes);
1171 if (!p)
1172 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1173 return p;
1174}
1175
1176static void *
1177ckmalloc(size_t nbytes)
1178{
1179 return ckrealloc(NULL, nbytes);
1180}
1181
1182static void *
1183ckzalloc(size_t nbytes)
1184{
1185 return memset(ckmalloc(nbytes), 0, nbytes);
1186}
1187
1188static char *
1189ckstrdup(const char *s)
1190{
1191 char *p = strdup(s);
1192 if (!p)
1193 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1194 return p;
1195}
1196#else
1197/* Using bbox equivalents. They exit if out of memory */
1198# define ckrealloc xrealloc
1199# define ckmalloc xmalloc
1200# define ckzalloc xzalloc
1201# define ckstrdup xstrdup
1202#endif
1203
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001204/*
1205 * It appears that grabstackstr() will barf with such alignments
1206 * because stalloc() will return a string allocated in a new stackblock.
1207 */
1208#define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
1209enum {
1210 /* Most machines require the value returned from malloc to be aligned
1211 * in some way. The following macro will get this right
1212 * on many machines. */
Denys Vlasenko0e5e4ea2009-10-11 00:36:20 +02001213 SHELL_SIZE = sizeof(union { int i; char *cp; double d; }) - 1,
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001214 /* Minimum size of a block */
Denis Vlasenko01631112007-12-16 17:20:38 +00001215 MINSIZE = SHELL_ALIGN(504),
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001216};
1217
1218struct stack_block {
1219 struct stack_block *prev;
1220 char space[MINSIZE];
1221};
1222
1223struct stackmark {
1224 struct stack_block *stackp;
1225 char *stacknxt;
1226 size_t stacknleft;
1227 struct stackmark *marknext;
1228};
1229
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001230
Denis Vlasenko01631112007-12-16 17:20:38 +00001231struct globals_memstack {
1232 struct stack_block *g_stackp; // = &stackbase;
1233 struct stackmark *markp;
1234 char *g_stacknxt; // = stackbase.space;
1235 char *sstrend; // = stackbase.space + MINSIZE;
1236 size_t g_stacknleft; // = MINSIZE;
1237 int herefd; // = -1;
1238 struct stack_block stackbase;
1239};
Denis Vlasenko574f2f42008-02-27 18:41:59 +00001240extern struct globals_memstack *const ash_ptr_to_globals_memstack;
1241#define G_memstack (*ash_ptr_to_globals_memstack)
Denis Vlasenko01631112007-12-16 17:20:38 +00001242#define g_stackp (G_memstack.g_stackp )
1243#define markp (G_memstack.markp )
1244#define g_stacknxt (G_memstack.g_stacknxt )
1245#define sstrend (G_memstack.sstrend )
1246#define g_stacknleft (G_memstack.g_stacknleft)
1247#define herefd (G_memstack.herefd )
1248#define stackbase (G_memstack.stackbase )
1249#define INIT_G_memstack() do { \
Denis Vlasenko574f2f42008-02-27 18:41:59 +00001250 (*(struct globals_memstack**)&ash_ptr_to_globals_memstack) = xzalloc(sizeof(G_memstack)); \
1251 barrier(); \
Denis Vlasenko01631112007-12-16 17:20:38 +00001252 g_stackp = &stackbase; \
1253 g_stacknxt = stackbase.space; \
1254 g_stacknleft = MINSIZE; \
1255 sstrend = stackbase.space + MINSIZE; \
1256 herefd = -1; \
1257} while (0)
1258
Denys Vlasenkoe7670ff2009-10-11 00:45:25 +02001259
Denis Vlasenko01631112007-12-16 17:20:38 +00001260#define stackblock() ((void *)g_stacknxt)
1261#define stackblocksize() g_stacknleft
1262
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001263/*
1264 * Parse trees for commands are allocated in lifo order, so we use a stack
1265 * to make this more efficient, and also to avoid all sorts of exception
1266 * handling code to handle interrupts in the middle of a parse.
1267 *
1268 * The size 504 was chosen because the Ultrix malloc handles that size
1269 * well.
1270 */
1271static void *
1272stalloc(size_t nbytes)
1273{
1274 char *p;
1275 size_t aligned;
1276
1277 aligned = SHELL_ALIGN(nbytes);
Denis Vlasenko01631112007-12-16 17:20:38 +00001278 if (aligned > g_stacknleft) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001279 size_t len;
1280 size_t blocksize;
1281 struct stack_block *sp;
1282
1283 blocksize = aligned;
1284 if (blocksize < MINSIZE)
1285 blocksize = MINSIZE;
1286 len = sizeof(struct stack_block) - MINSIZE + blocksize;
1287 if (len < blocksize)
1288 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1289 INT_OFF;
1290 sp = ckmalloc(len);
Denis Vlasenko01631112007-12-16 17:20:38 +00001291 sp->prev = g_stackp;
1292 g_stacknxt = sp->space;
1293 g_stacknleft = blocksize;
1294 sstrend = g_stacknxt + blocksize;
1295 g_stackp = sp;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001296 INT_ON;
1297 }
Denis Vlasenko01631112007-12-16 17:20:38 +00001298 p = g_stacknxt;
1299 g_stacknxt += aligned;
1300 g_stacknleft -= aligned;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001301 return p;
1302}
1303
Denis Vlasenko597906c2008-02-20 16:38:54 +00001304static void *
1305stzalloc(size_t nbytes)
1306{
1307 return memset(stalloc(nbytes), 0, nbytes);
1308}
1309
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001310static void
1311stunalloc(void *p)
1312{
1313#if DEBUG
Denis Vlasenko01631112007-12-16 17:20:38 +00001314 if (!p || (g_stacknxt < (char *)p) || ((char *)p < g_stackp->space)) {
Bernhard Reutner-Fischer5e25ddb2008-05-19 09:48:17 +00001315 write(STDERR_FILENO, "stunalloc\n", 10);
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001316 abort();
1317 }
1318#endif
Denis Vlasenko01631112007-12-16 17:20:38 +00001319 g_stacknleft += g_stacknxt - (char *)p;
1320 g_stacknxt = p;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001321}
1322
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001323/*
1324 * Like strdup but works with the ash stack.
1325 */
1326static char *
1327ststrdup(const char *p)
1328{
1329 size_t len = strlen(p) + 1;
1330 return memcpy(stalloc(len), p, len);
1331}
1332
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001333static void
1334setstackmark(struct stackmark *mark)
1335{
Denis Vlasenko01631112007-12-16 17:20:38 +00001336 mark->stackp = g_stackp;
1337 mark->stacknxt = g_stacknxt;
1338 mark->stacknleft = g_stacknleft;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001339 mark->marknext = markp;
1340 markp = mark;
1341}
1342
1343static void
1344popstackmark(struct stackmark *mark)
1345{
1346 struct stack_block *sp;
1347
Denis Vlasenko93ebd4f2007-03-13 20:55:36 +00001348 if (!mark->stackp)
1349 return;
1350
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001351 INT_OFF;
1352 markp = mark->marknext;
Denis Vlasenko01631112007-12-16 17:20:38 +00001353 while (g_stackp != mark->stackp) {
1354 sp = g_stackp;
1355 g_stackp = sp->prev;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001356 free(sp);
1357 }
Denis Vlasenko01631112007-12-16 17:20:38 +00001358 g_stacknxt = mark->stacknxt;
1359 g_stacknleft = mark->stacknleft;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001360 sstrend = mark->stacknxt + mark->stacknleft;
1361 INT_ON;
1362}
1363
1364/*
1365 * When the parser reads in a string, it wants to stick the string on the
1366 * stack and only adjust the stack pointer when it knows how big the
1367 * string is. Stackblock (defined in stack.h) returns a pointer to a block
1368 * of space on top of the stack and stackblocklen returns the length of
1369 * this block. Growstackblock will grow this space by at least one byte,
1370 * possibly moving it (like realloc). Grabstackblock actually allocates the
1371 * part of the block that has been used.
1372 */
1373static void
1374growstackblock(void)
1375{
1376 size_t newlen;
1377
Denis Vlasenko01631112007-12-16 17:20:38 +00001378 newlen = g_stacknleft * 2;
1379 if (newlen < g_stacknleft)
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001380 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1381 if (newlen < 128)
1382 newlen += 128;
1383
Denis Vlasenko01631112007-12-16 17:20:38 +00001384 if (g_stacknxt == g_stackp->space && g_stackp != &stackbase) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001385 struct stack_block *oldstackp;
1386 struct stackmark *xmark;
1387 struct stack_block *sp;
1388 struct stack_block *prevstackp;
1389 size_t grosslen;
1390
1391 INT_OFF;
Denis Vlasenko01631112007-12-16 17:20:38 +00001392 oldstackp = g_stackp;
1393 sp = g_stackp;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001394 prevstackp = sp->prev;
1395 grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
1396 sp = ckrealloc(sp, grosslen);
1397 sp->prev = prevstackp;
Denis Vlasenko01631112007-12-16 17:20:38 +00001398 g_stackp = sp;
1399 g_stacknxt = sp->space;
1400 g_stacknleft = newlen;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001401 sstrend = sp->space + newlen;
1402
1403 /*
1404 * Stack marks pointing to the start of the old block
1405 * must be relocated to point to the new block
1406 */
1407 xmark = markp;
1408 while (xmark != NULL && xmark->stackp == oldstackp) {
Denis Vlasenko01631112007-12-16 17:20:38 +00001409 xmark->stackp = g_stackp;
1410 xmark->stacknxt = g_stacknxt;
1411 xmark->stacknleft = g_stacknleft;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001412 xmark = xmark->marknext;
1413 }
1414 INT_ON;
1415 } else {
Denis Vlasenko01631112007-12-16 17:20:38 +00001416 char *oldspace = g_stacknxt;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00001417 size_t oldlen = g_stacknleft;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001418 char *p = stalloc(newlen);
1419
1420 /* free the space we just allocated */
Denis Vlasenko01631112007-12-16 17:20:38 +00001421 g_stacknxt = memcpy(p, oldspace, oldlen);
1422 g_stacknleft += newlen;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001423 }
1424}
1425
1426static void
1427grabstackblock(size_t len)
1428{
1429 len = SHELL_ALIGN(len);
Denis Vlasenko01631112007-12-16 17:20:38 +00001430 g_stacknxt += len;
1431 g_stacknleft -= len;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001432}
1433
1434/*
1435 * The following routines are somewhat easier to use than the above.
1436 * The user declares a variable of type STACKSTR, which may be declared
1437 * to be a register. The macro STARTSTACKSTR initializes things. Then
1438 * the user uses the macro STPUTC to add characters to the string. In
1439 * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
1440 * grown as necessary. When the user is done, she can just leave the
1441 * string there and refer to it using stackblock(). Or she can allocate
1442 * the space for it using grabstackstr(). If it is necessary to allow
1443 * someone else to use the stack temporarily and then continue to grow
1444 * the string, the user should use grabstack to allocate the space, and
1445 * then call ungrabstr(p) to return to the previous mode of operation.
1446 *
1447 * USTPUTC is like STPUTC except that it doesn't check for overflow.
1448 * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
1449 * is space for at least one character.
1450 */
1451static void *
1452growstackstr(void)
1453{
1454 size_t len = stackblocksize();
1455 if (herefd >= 0 && len >= 1024) {
1456 full_write(herefd, stackblock(), len);
1457 return stackblock();
1458 }
1459 growstackblock();
Denis Vlasenko29eb3592008-05-18 14:06:08 +00001460 return (char *)stackblock() + len;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001461}
1462
1463/*
1464 * Called from CHECKSTRSPACE.
1465 */
1466static char *
1467makestrspace(size_t newlen, char *p)
1468{
Denis Vlasenko01631112007-12-16 17:20:38 +00001469 size_t len = p - g_stacknxt;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001470 size_t size = stackblocksize();
1471
1472 for (;;) {
1473 size_t nleft;
1474
1475 size = stackblocksize();
1476 nleft = size - len;
1477 if (nleft >= newlen)
1478 break;
1479 growstackblock();
1480 }
Denis Vlasenko29eb3592008-05-18 14:06:08 +00001481 return (char *)stackblock() + len;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001482}
1483
1484static char *
1485stack_nputstr(const char *s, size_t n, char *p)
1486{
1487 p = makestrspace(n, p);
Denis Vlasenko29eb3592008-05-18 14:06:08 +00001488 p = (char *)memcpy(p, s, n) + n;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001489 return p;
1490}
1491
1492static char *
1493stack_putstr(const char *s, char *p)
1494{
1495 return stack_nputstr(s, strlen(s), p);
1496}
1497
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001498static char *
1499_STPUTC(int c, char *p)
1500{
1501 if (p == sstrend)
1502 p = growstackstr();
1503 *p++ = c;
1504 return p;
1505}
1506
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00001507#define STARTSTACKSTR(p) ((p) = stackblock())
1508#define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
Denis Vlasenko843cbd52008-06-27 00:23:18 +00001509#define CHECKSTRSPACE(n, p) do { \
1510 char *q = (p); \
1511 size_t l = (n); \
1512 size_t m = sstrend - q; \
1513 if (l > m) \
1514 (p) = makestrspace(l, q); \
1515} while (0)
Denis Vlasenkoef527f52008-06-23 01:52:30 +00001516#define USTPUTC(c, p) (*(p)++ = (c))
Denis Vlasenko843cbd52008-06-27 00:23:18 +00001517#define STACKSTRNUL(p) do { \
1518 if ((p) == sstrend) \
1519 (p) = growstackstr(); \
1520 *(p) = '\0'; \
1521} while (0)
Denis Vlasenkoef527f52008-06-23 01:52:30 +00001522#define STUNPUTC(p) (--(p))
1523#define STTOPC(p) ((p)[-1])
1524#define STADJUST(amount, p) ((p) += (amount))
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001525
1526#define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
Denis Vlasenkoef527f52008-06-23 01:52:30 +00001527#define ungrabstackstr(s, p) stunalloc(s)
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001528#define stackstrend() ((void *)sstrend)
1529
1530
1531/* ============ String helpers */
1532
1533/*
1534 * prefix -- see if pfx is a prefix of string.
1535 */
1536static char *
1537prefix(const char *string, const char *pfx)
1538{
1539 while (*pfx) {
1540 if (*pfx++ != *string++)
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00001541 return NULL;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001542 }
1543 return (char *) string;
1544}
1545
1546/*
1547 * Check for a valid number. This should be elsewhere.
1548 */
1549static int
1550is_number(const char *p)
1551{
1552 do {
1553 if (!isdigit(*p))
1554 return 0;
1555 } while (*++p != '\0');
1556 return 1;
1557}
1558
1559/*
1560 * Convert a string of digits to an integer, printing an error message on
1561 * failure.
1562 */
1563static int
1564number(const char *s)
1565{
1566 if (!is_number(s))
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02001567 ash_msg_and_raise_error(msg_illnum, s);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001568 return atoi(s);
1569}
1570
1571/*
1572 * Produce a possibly single quoted string suitable as input to the shell.
1573 * The return string is allocated on the stack.
1574 */
1575static char *
1576single_quote(const char *s)
1577{
1578 char *p;
1579
1580 STARTSTACKSTR(p);
1581
1582 do {
1583 char *q;
1584 size_t len;
1585
1586 len = strchrnul(s, '\'') - s;
1587
1588 q = p = makestrspace(len + 3, p);
1589
1590 *q++ = '\'';
Denis Vlasenko29eb3592008-05-18 14:06:08 +00001591 q = (char *)memcpy(q, s, len) + len;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001592 *q++ = '\'';
1593 s += len;
1594
1595 STADJUST(q - p, p);
1596
Denys Vlasenkocd716832009-11-28 22:14:02 +01001597 if (*s != '\'')
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001598 break;
Denys Vlasenkocd716832009-11-28 22:14:02 +01001599 len = 0;
1600 do len++; while (*++s == '\'');
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001601
1602 q = p = makestrspace(len + 3, p);
1603
1604 *q++ = '"';
Denys Vlasenkocd716832009-11-28 22:14:02 +01001605 q = (char *)memcpy(q, s - len, len) + len;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001606 *q++ = '"';
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001607
1608 STADJUST(q - p, p);
1609 } while (*s);
1610
Denys Vlasenkocd716832009-11-28 22:14:02 +01001611 USTPUTC('\0', p);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001612
1613 return stackblock();
1614}
1615
1616
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00001617/* ============ nextopt */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001618
1619static char **argptr; /* argument list for builtin commands */
1620static char *optionarg; /* set by nextopt (like getopt) */
1621static char *optptr; /* used by nextopt */
1622
1623/*
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001624 * XXX - should get rid of. Have all builtins use getopt(3).
1625 * The library getopt must have the BSD extension static variable
1626 * "optreset", otherwise it can't be used within the shell safely.
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001627 *
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001628 * Standard option processing (a la getopt) for builtin routines.
1629 * The only argument that is passed to nextopt is the option string;
1630 * the other arguments are unnecessary. It returns the character,
1631 * or '\0' on end of input.
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001632 */
1633static int
1634nextopt(const char *optstring)
1635{
1636 char *p;
1637 const char *q;
1638 char c;
1639
1640 p = optptr;
1641 if (p == NULL || *p == '\0') {
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001642 /* We ate entire "-param", take next one */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001643 p = *argptr;
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001644 if (p == NULL)
1645 return '\0';
1646 if (*p != '-')
1647 return '\0';
1648 if (*++p == '\0') /* just "-" ? */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001649 return '\0';
1650 argptr++;
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001651 if (LONE_DASH(p)) /* "--" ? */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001652 return '\0';
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001653 /* p => next "-param" */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001654 }
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001655 /* p => some option char in the middle of a "-param" */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001656 c = *p++;
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +00001657 for (q = optstring; *q != c;) {
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001658 if (*q == '\0')
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00001659 ash_msg_and_raise_error("illegal option -%c", c);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001660 if (*++q == ':')
1661 q++;
1662 }
1663 if (*++q == ':') {
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001664 if (*p == '\0') {
1665 p = *argptr++;
1666 if (p == NULL)
1667 ash_msg_and_raise_error("no arg for -%c option", c);
1668 }
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001669 optionarg = p;
1670 p = NULL;
1671 }
1672 optptr = p;
1673 return c;
1674}
1675
1676
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00001677/* ============ Shell variables */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001678
Denis Vlasenko01631112007-12-16 17:20:38 +00001679/*
1680 * The parsefile structure pointed to by the global variable parsefile
1681 * contains information about the current file being read.
1682 */
Denis Vlasenko01631112007-12-16 17:20:38 +00001683struct shparam {
1684 int nparam; /* # of positional parameters (without $0) */
1685#if ENABLE_ASH_GETOPTS
1686 int optind; /* next parameter to be processed by getopts */
1687 int optoff; /* used by getopts */
1688#endif
1689 unsigned char malloced; /* if parameter list dynamically allocated */
1690 char **p; /* parameter list */
1691};
1692
1693/*
1694 * Free the list of positional parameters.
1695 */
1696static void
1697freeparam(volatile struct shparam *param)
1698{
Denis Vlasenko01631112007-12-16 17:20:38 +00001699 if (param->malloced) {
Denis Vlasenko3177ba02008-07-13 20:39:23 +00001700 char **ap, **ap1;
1701 ap = ap1 = param->p;
1702 while (*ap)
1703 free(*ap++);
1704 free(ap1);
Denis Vlasenko01631112007-12-16 17:20:38 +00001705 }
1706}
1707
1708#if ENABLE_ASH_GETOPTS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001709static void FAST_FUNC getoptsreset(const char *value);
Denis Vlasenko01631112007-12-16 17:20:38 +00001710#endif
1711
1712struct var {
1713 struct var *next; /* next entry in hash list */
1714 int flags; /* flags are defined above */
1715 const char *text; /* name=value */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001716 void (*func)(const char *) FAST_FUNC; /* function to be called when */
Denis Vlasenko01631112007-12-16 17:20:38 +00001717 /* the variable gets set/unset */
1718};
1719
1720struct localvar {
1721 struct localvar *next; /* next local variable in list */
1722 struct var *vp; /* the variable that was made local */
1723 int flags; /* saved flags */
1724 const char *text; /* saved text */
1725};
1726
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001727/* flags */
1728#define VEXPORT 0x01 /* variable is exported */
1729#define VREADONLY 0x02 /* variable cannot be modified */
1730#define VSTRFIXED 0x04 /* variable struct is statically allocated */
1731#define VTEXTFIXED 0x08 /* text is statically allocated */
1732#define VSTACK 0x10 /* text is allocated on the stack */
1733#define VUNSET 0x20 /* the variable is not set */
1734#define VNOFUNC 0x40 /* don't call the callback function */
1735#define VNOSET 0x80 /* do not set variable - just readonly test */
1736#define VNOSAVE 0x100 /* when text is on the heap before setvareq */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00001737#if ENABLE_ASH_RANDOM_SUPPORT
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00001738# define VDYNAMIC 0x200 /* dynamic variable */
1739#else
1740# define VDYNAMIC 0
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001741#endif
1742
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00001743
Denis Vlasenko01631112007-12-16 17:20:38 +00001744/* Need to be before varinit_data[] */
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00001745#if ENABLE_LOCALE_SUPPORT
Denys Vlasenko2634bf32009-06-09 18:40:07 +02001746static void FAST_FUNC
Denis Vlasenkoa8915072007-02-23 21:10:06 +00001747change_lc_all(const char *value)
1748{
1749 if (value && *value != '\0')
1750 setlocale(LC_ALL, value);
1751}
Denys Vlasenko2634bf32009-06-09 18:40:07 +02001752static void FAST_FUNC
Denis Vlasenkoa8915072007-02-23 21:10:06 +00001753change_lc_ctype(const char *value)
1754{
1755 if (value && *value != '\0')
1756 setlocale(LC_CTYPE, value);
1757}
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00001758#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001759#if ENABLE_ASH_MAIL
1760static void chkmail(void);
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001761static void changemail(const char *) FAST_FUNC;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001762#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001763static void changepath(const char *) FAST_FUNC;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001764#if ENABLE_ASH_RANDOM_SUPPORT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001765static void change_random(const char *) FAST_FUNC;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001766#endif
1767
Denis Vlasenko01631112007-12-16 17:20:38 +00001768static const struct {
1769 int flags;
1770 const char *text;
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001771 void (*func)(const char *) FAST_FUNC;
Denis Vlasenko01631112007-12-16 17:20:38 +00001772} varinit_data[] = {
Denis Vlasenko01631112007-12-16 17:20:38 +00001773 { VSTRFIXED|VTEXTFIXED , defifsvar , NULL },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001774#if ENABLE_ASH_MAIL
Denis Vlasenko01631112007-12-16 17:20:38 +00001775 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL\0" , changemail },
1776 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH\0", changemail },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001777#endif
Denis Vlasenko01631112007-12-16 17:20:38 +00001778 { VSTRFIXED|VTEXTFIXED , bb_PATH_root_path, changepath },
1779 { VSTRFIXED|VTEXTFIXED , "PS1=$ " , NULL },
1780 { VSTRFIXED|VTEXTFIXED , "PS2=> " , NULL },
1781 { VSTRFIXED|VTEXTFIXED , "PS4=+ " , NULL },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001782#if ENABLE_ASH_GETOPTS
Denis Vlasenko01631112007-12-16 17:20:38 +00001783 { VSTRFIXED|VTEXTFIXED , "OPTIND=1" , getoptsreset },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001784#endif
1785#if ENABLE_ASH_RANDOM_SUPPORT
Denis Vlasenko01631112007-12-16 17:20:38 +00001786 { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM\0", change_random },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001787#endif
1788#if ENABLE_LOCALE_SUPPORT
Denis Vlasenko01631112007-12-16 17:20:38 +00001789 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL\0" , change_lc_all },
1790 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE\0", change_lc_ctype },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001791#endif
1792#if ENABLE_FEATURE_EDITING_SAVEHISTORY
Denis Vlasenko01631112007-12-16 17:20:38 +00001793 { VSTRFIXED|VTEXTFIXED|VUNSET, "HISTFILE\0", NULL },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001794#endif
1795};
1796
Denis Vlasenko0b769642008-07-24 07:54:57 +00001797struct redirtab;
Denis Vlasenko01631112007-12-16 17:20:38 +00001798
1799struct globals_var {
1800 struct shparam shellparam; /* $@ current positional parameters */
1801 struct redirtab *redirlist;
1802 int g_nullredirs;
1803 int preverrout_fd; /* save fd2 before print debug if xflag is set. */
1804 struct var *vartab[VTABSIZE];
1805 struct var varinit[ARRAY_SIZE(varinit_data)];
1806};
Denis Vlasenko574f2f42008-02-27 18:41:59 +00001807extern struct globals_var *const ash_ptr_to_globals_var;
1808#define G_var (*ash_ptr_to_globals_var)
Denis Vlasenko01631112007-12-16 17:20:38 +00001809#define shellparam (G_var.shellparam )
Denis Vlasenko0b769642008-07-24 07:54:57 +00001810//#define redirlist (G_var.redirlist )
Denis Vlasenko01631112007-12-16 17:20:38 +00001811#define g_nullredirs (G_var.g_nullredirs )
1812#define preverrout_fd (G_var.preverrout_fd)
1813#define vartab (G_var.vartab )
1814#define varinit (G_var.varinit )
1815#define INIT_G_var() do { \
Denis Vlasenko6b06cb82008-05-15 21:30:45 +00001816 unsigned i; \
Denis Vlasenko574f2f42008-02-27 18:41:59 +00001817 (*(struct globals_var**)&ash_ptr_to_globals_var) = xzalloc(sizeof(G_var)); \
1818 barrier(); \
Denis Vlasenko01631112007-12-16 17:20:38 +00001819 for (i = 0; i < ARRAY_SIZE(varinit_data); i++) { \
1820 varinit[i].flags = varinit_data[i].flags; \
1821 varinit[i].text = varinit_data[i].text; \
1822 varinit[i].func = varinit_data[i].func; \
1823 } \
1824} while (0)
1825
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001826#define vifs varinit[0]
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001827#if ENABLE_ASH_MAIL
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001828# define vmail (&vifs)[1]
1829# define vmpath (&vmail)[1]
1830# define vpath (&vmpath)[1]
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001831#else
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001832# define vpath (&vifs)[1]
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001833#endif
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001834#define vps1 (&vpath)[1]
1835#define vps2 (&vps1)[1]
1836#define vps4 (&vps2)[1]
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001837#if ENABLE_ASH_GETOPTS
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001838# define voptind (&vps4)[1]
1839# if ENABLE_ASH_RANDOM_SUPPORT
1840# define vrandom (&voptind)[1]
1841# endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001842#else
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001843# if ENABLE_ASH_RANDOM_SUPPORT
1844# define vrandom (&vps4)[1]
1845# endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001846#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001847
1848/*
1849 * The following macros access the values of the above variables.
1850 * They have to skip over the name. They return the null string
1851 * for unset variables.
1852 */
1853#define ifsval() (vifs.text + 4)
1854#define ifsset() ((vifs.flags & VUNSET) == 0)
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001855#if ENABLE_ASH_MAIL
1856# define mailval() (vmail.text + 5)
1857# define mpathval() (vmpath.text + 9)
1858# define mpathset() ((vmpath.flags & VUNSET) == 0)
1859#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001860#define pathval() (vpath.text + 5)
1861#define ps1val() (vps1.text + 4)
1862#define ps2val() (vps2.text + 4)
1863#define ps4val() (vps4.text + 4)
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001864#if ENABLE_ASH_GETOPTS
1865# define optindval() (voptind.text + 7)
1866#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001867
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001868
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001869#define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
1870#define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
1871
Denis Vlasenko01631112007-12-16 17:20:38 +00001872#if ENABLE_ASH_GETOPTS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001873static void FAST_FUNC
Denis Vlasenko01631112007-12-16 17:20:38 +00001874getoptsreset(const char *value)
1875{
1876 shellparam.optind = number(value);
1877 shellparam.optoff = -1;
1878}
1879#endif
1880
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001881/*
1882 * Return of a legal variable name (a letter or underscore followed by zero or
1883 * more letters, underscores, and digits).
1884 */
Denys Vlasenko03dad222010-01-12 23:29:57 +01001885static char* FAST_FUNC
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001886endofname(const char *name)
1887{
1888 char *p;
1889
1890 p = (char *) name;
1891 if (!is_name(*p))
1892 return p;
1893 while (*++p) {
1894 if (!is_in_name(*p))
1895 break;
1896 }
1897 return p;
1898}
1899
1900/*
1901 * Compares two strings up to the first = or '\0'. The first
1902 * string must be terminated by '='; the second may be terminated by
1903 * either '=' or '\0'.
1904 */
1905static int
1906varcmp(const char *p, const char *q)
1907{
1908 int c, d;
1909
1910 while ((c = *p) == (d = *q)) {
1911 if (!c || c == '=')
1912 goto out;
1913 p++;
1914 q++;
1915 }
1916 if (c == '=')
Denis Vlasenko9650f362007-02-23 01:04:37 +00001917 c = '\0';
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001918 if (d == '=')
Denis Vlasenko9650f362007-02-23 01:04:37 +00001919 d = '\0';
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001920 out:
1921 return c - d;
1922}
1923
1924static int
1925varequal(const char *a, const char *b)
1926{
1927 return !varcmp(a, b);
1928}
1929
1930/*
1931 * Find the appropriate entry in the hash table from the name.
1932 */
1933static struct var **
1934hashvar(const char *p)
1935{
1936 unsigned hashval;
1937
1938 hashval = ((unsigned char) *p) << 4;
1939 while (*p && *p != '=')
1940 hashval += (unsigned char) *p++;
1941 return &vartab[hashval % VTABSIZE];
1942}
1943
1944static int
1945vpcmp(const void *a, const void *b)
1946{
1947 return varcmp(*(const char **)a, *(const char **)b);
1948}
1949
1950/*
1951 * This routine initializes the builtin variables.
1952 */
1953static void
1954initvar(void)
1955{
1956 struct var *vp;
1957 struct var *end;
1958 struct var **vpp;
1959
1960 /*
1961 * PS1 depends on uid
1962 */
1963#if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
1964 vps1.text = "PS1=\\w \\$ ";
1965#else
1966 if (!geteuid())
1967 vps1.text = "PS1=# ";
1968#endif
1969 vp = varinit;
Denis Vlasenko80b8b392007-06-25 10:55:35 +00001970 end = vp + ARRAY_SIZE(varinit);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001971 do {
1972 vpp = hashvar(vp->text);
1973 vp->next = *vpp;
1974 *vpp = vp;
1975 } while (++vp < end);
1976}
1977
1978static struct var **
1979findvar(struct var **vpp, const char *name)
1980{
1981 for (; *vpp; vpp = &(*vpp)->next) {
1982 if (varequal((*vpp)->text, name)) {
1983 break;
1984 }
1985 }
1986 return vpp;
1987}
1988
1989/*
1990 * Find the value of a variable. Returns NULL if not set.
1991 */
Denys Vlasenko03dad222010-01-12 23:29:57 +01001992static const char* FAST_FUNC
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001993lookupvar(const char *name)
1994{
1995 struct var *v;
1996
1997 v = *findvar(hashvar(name), name);
1998 if (v) {
Denis Vlasenko448d30e2008-06-27 00:24:11 +00001999#if ENABLE_ASH_RANDOM_SUPPORT
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002000 /*
2001 * Dynamic variables are implemented roughly the same way they are
2002 * in bash. Namely, they're "special" so long as they aren't unset.
2003 * As soon as they're unset, they're no longer dynamic, and dynamic
2004 * lookup will no longer happen at that point. -- PFM.
2005 */
2006 if ((v->flags & VDYNAMIC))
2007 (*v->func)(NULL);
2008#endif
2009 if (!(v->flags & VUNSET))
2010 return strchrnul(v->text, '=') + 1;
2011 }
2012 return NULL;
2013}
2014
2015/*
2016 * Search the environment of a builtin command.
2017 */
Mike Frysinger98c52642009-04-02 10:02:37 +00002018static const char *
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002019bltinlookup(const char *name)
2020{
2021 struct strlist *sp;
2022
2023 for (sp = cmdenviron; sp; sp = sp->next) {
2024 if (varequal(sp->text, name))
2025 return strchrnul(sp->text, '=') + 1;
2026 }
2027 return lookupvar(name);
2028}
2029
2030/*
2031 * Same as setvar except that the variable and value are passed in
2032 * the first argument as name=value. Since the first argument will
2033 * be actually stored in the table, it should not be a string that
2034 * will go away.
2035 * Called with interrupts off.
2036 */
2037static void
2038setvareq(char *s, int flags)
2039{
2040 struct var *vp, **vpp;
2041
2042 vpp = hashvar(s);
2043 flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
2044 vp = *findvar(vpp, s);
2045 if (vp) {
2046 if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
2047 const char *n;
2048
2049 if (flags & VNOSAVE)
2050 free(s);
2051 n = vp->text;
2052 ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
2053 }
2054
2055 if (flags & VNOSET)
2056 return;
2057
2058 if (vp->func && (flags & VNOFUNC) == 0)
2059 (*vp->func)(strchrnul(s, '=') + 1);
2060
2061 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
2062 free((char*)vp->text);
2063
2064 flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
2065 } else {
2066 if (flags & VNOSET)
2067 return;
2068 /* not found */
Denis Vlasenko597906c2008-02-20 16:38:54 +00002069 vp = ckzalloc(sizeof(*vp));
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002070 vp->next = *vpp;
Denis Vlasenko597906c2008-02-20 16:38:54 +00002071 /*vp->func = NULL; - ckzalloc did it */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002072 *vpp = vp;
2073 }
2074 if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
2075 s = ckstrdup(s);
2076 vp->text = s;
2077 vp->flags = flags;
2078}
2079
2080/*
2081 * Set the value of a variable. The flags argument is ored with the
2082 * flags of the variable. If val is NULL, the variable is unset.
2083 */
2084static void
2085setvar(const char *name, const char *val, int flags)
2086{
2087 char *p, *q;
2088 size_t namelen;
2089 char *nameeq;
2090 size_t vallen;
2091
2092 q = endofname(name);
2093 p = strchrnul(q, '=');
2094 namelen = p - name;
2095 if (!namelen || p != q)
2096 ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
2097 vallen = 0;
2098 if (val == NULL) {
2099 flags |= VUNSET;
2100 } else {
2101 vallen = strlen(val);
2102 }
2103 INT_OFF;
2104 nameeq = ckmalloc(namelen + vallen + 2);
Denis Vlasenko29eb3592008-05-18 14:06:08 +00002105 p = (char *)memcpy(nameeq, name, namelen) + namelen;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002106 if (val) {
2107 *p++ = '=';
Denis Vlasenko29eb3592008-05-18 14:06:08 +00002108 p = (char *)memcpy(p, val, vallen) + vallen;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002109 }
2110 *p = '\0';
2111 setvareq(nameeq, flags | VNOSAVE);
2112 INT_ON;
2113}
2114
Denys Vlasenko03dad222010-01-12 23:29:57 +01002115static void FAST_FUNC
2116setvar2(const char *name, const char *val)
2117{
2118 setvar(name, val, 0);
2119}
2120
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002121#if ENABLE_ASH_GETOPTS
2122/*
2123 * Safe version of setvar, returns 1 on success 0 on failure.
2124 */
2125static int
2126setvarsafe(const char *name, const char *val, int flags)
2127{
2128 int err;
2129 volatile int saveint;
2130 struct jmploc *volatile savehandler = exception_handler;
2131 struct jmploc jmploc;
2132
2133 SAVE_INT(saveint);
2134 if (setjmp(jmploc.loc))
2135 err = 1;
2136 else {
2137 exception_handler = &jmploc;
2138 setvar(name, val, flags);
2139 err = 0;
2140 }
2141 exception_handler = savehandler;
2142 RESTORE_INT(saveint);
2143 return err;
2144}
2145#endif
2146
2147/*
2148 * Unset the specified variable.
2149 */
2150static int
2151unsetvar(const char *s)
2152{
2153 struct var **vpp;
2154 struct var *vp;
2155 int retval;
2156
2157 vpp = findvar(hashvar(s), s);
2158 vp = *vpp;
2159 retval = 2;
2160 if (vp) {
2161 int flags = vp->flags;
2162
2163 retval = 1;
2164 if (flags & VREADONLY)
2165 goto out;
Denis Vlasenko448d30e2008-06-27 00:24:11 +00002166#if ENABLE_ASH_RANDOM_SUPPORT
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002167 vp->flags &= ~VDYNAMIC;
2168#endif
2169 if (flags & VUNSET)
2170 goto ok;
2171 if ((flags & VSTRFIXED) == 0) {
2172 INT_OFF;
2173 if ((flags & (VTEXTFIXED|VSTACK)) == 0)
2174 free((char*)vp->text);
2175 *vpp = vp->next;
2176 free(vp);
2177 INT_ON;
2178 } else {
2179 setvar(s, 0, 0);
2180 vp->flags &= ~VEXPORT;
2181 }
2182 ok:
2183 retval = 0;
2184 }
2185 out:
2186 return retval;
2187}
2188
2189/*
2190 * Process a linked list of variable assignments.
2191 */
2192static void
2193listsetvar(struct strlist *list_set_var, int flags)
2194{
2195 struct strlist *lp = list_set_var;
2196
2197 if (!lp)
2198 return;
2199 INT_OFF;
2200 do {
2201 setvareq(lp->text, flags);
Denis Vlasenko9650f362007-02-23 01:04:37 +00002202 lp = lp->next;
2203 } while (lp);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002204 INT_ON;
2205}
2206
2207/*
2208 * Generate a list of variables satisfying the given conditions.
2209 */
2210static char **
2211listvars(int on, int off, char ***end)
2212{
2213 struct var **vpp;
2214 struct var *vp;
2215 char **ep;
2216 int mask;
2217
2218 STARTSTACKSTR(ep);
2219 vpp = vartab;
2220 mask = on | off;
2221 do {
2222 for (vp = *vpp; vp; vp = vp->next) {
2223 if ((vp->flags & mask) == on) {
2224 if (ep == stackstrend())
2225 ep = growstackstr();
2226 *ep++ = (char *) vp->text;
2227 }
2228 }
2229 } while (++vpp < vartab + VTABSIZE);
2230 if (ep == stackstrend())
2231 ep = growstackstr();
2232 if (end)
2233 *end = ep;
2234 *ep++ = NULL;
2235 return grabstackstr(ep);
2236}
2237
2238
2239/* ============ Path search helper
2240 *
2241 * The variable path (passed by reference) should be set to the start
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02002242 * of the path before the first call; path_advance will update
2243 * this value as it proceeds. Successive calls to path_advance will return
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002244 * the possible path expansions in sequence. If an option (indicated by
2245 * a percent sign) appears in the path entry then the global variable
2246 * pathopt will be set to point to it; otherwise pathopt will be set to
2247 * NULL.
2248 */
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02002249static const char *pathopt; /* set by path_advance */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002250
2251static char *
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02002252path_advance(const char **path, const char *name)
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002253{
2254 const char *p;
2255 char *q;
2256 const char *start;
2257 size_t len;
2258
2259 if (*path == NULL)
2260 return NULL;
2261 start = *path;
Denis Vlasenkof7d56652008-03-25 05:51:41 +00002262 for (p = start; *p && *p != ':' && *p != '%'; p++)
2263 continue;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002264 len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
2265 while (stackblocksize() < len)
2266 growstackblock();
2267 q = stackblock();
2268 if (p != start) {
2269 memcpy(q, start, p - start);
2270 q += p - start;
2271 *q++ = '/';
2272 }
2273 strcpy(q, name);
2274 pathopt = NULL;
2275 if (*p == '%') {
2276 pathopt = ++p;
Denis Vlasenkof7d56652008-03-25 05:51:41 +00002277 while (*p && *p != ':')
2278 p++;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002279 }
2280 if (*p == ':')
2281 *path = p + 1;
2282 else
2283 *path = NULL;
2284 return stalloc(len);
2285}
2286
2287
2288/* ============ Prompt */
2289
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +00002290static smallint doprompt; /* if set, prompt the user */
2291static smallint needprompt; /* true if interactive and at start of line */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002292
2293#if ENABLE_FEATURE_EDITING
2294static line_input_t *line_input_state;
2295static const char *cmdedit_prompt;
2296static void
2297putprompt(const char *s)
2298{
2299 if (ENABLE_ASH_EXPAND_PRMT) {
2300 free((char*)cmdedit_prompt);
Denis Vlasenko4222ae42007-02-25 02:37:49 +00002301 cmdedit_prompt = ckstrdup(s);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002302 return;
2303 }
2304 cmdedit_prompt = s;
2305}
2306#else
2307static void
2308putprompt(const char *s)
2309{
2310 out2str(s);
2311}
2312#endif
2313
2314#if ENABLE_ASH_EXPAND_PRMT
2315/* expandstr() needs parsing machinery, so it is far away ahead... */
2316static const char *expandstr(const char *ps);
2317#else
2318#define expandstr(s) s
2319#endif
2320
2321static void
2322setprompt(int whichprompt)
2323{
2324 const char *prompt;
2325#if ENABLE_ASH_EXPAND_PRMT
2326 struct stackmark smark;
2327#endif
2328
2329 needprompt = 0;
2330
2331 switch (whichprompt) {
2332 case 1:
2333 prompt = ps1val();
2334 break;
2335 case 2:
2336 prompt = ps2val();
2337 break;
2338 default: /* 0 */
2339 prompt = nullstr;
2340 }
2341#if ENABLE_ASH_EXPAND_PRMT
2342 setstackmark(&smark);
2343 stalloc(stackblocksize());
2344#endif
2345 putprompt(expandstr(prompt));
2346#if ENABLE_ASH_EXPAND_PRMT
2347 popstackmark(&smark);
2348#endif
2349}
2350
2351
2352/* ============ The cd and pwd commands */
2353
2354#define CD_PHYSICAL 1
2355#define CD_PRINT 2
2356
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002357static int
2358cdopt(void)
2359{
2360 int flags = 0;
2361 int i, j;
2362
2363 j = 'L';
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02002364 while ((i = nextopt("LP")) != '\0') {
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002365 if (i != j) {
2366 flags ^= CD_PHYSICAL;
2367 j = i;
2368 }
2369 }
2370
2371 return flags;
2372}
2373
2374/*
2375 * Update curdir (the name of the current directory) in response to a
2376 * cd command.
2377 */
2378static const char *
2379updatepwd(const char *dir)
2380{
2381 char *new;
2382 char *p;
2383 char *cdcomppath;
2384 const char *lim;
2385
2386 cdcomppath = ststrdup(dir);
2387 STARTSTACKSTR(new);
2388 if (*dir != '/') {
2389 if (curdir == nullstr)
2390 return 0;
2391 new = stack_putstr(curdir, new);
2392 }
2393 new = makestrspace(strlen(dir) + 2, new);
Denis Vlasenko29eb3592008-05-18 14:06:08 +00002394 lim = (char *)stackblock() + 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002395 if (*dir != '/') {
2396 if (new[-1] != '/')
2397 USTPUTC('/', new);
2398 if (new > lim && *lim == '/')
2399 lim++;
2400 } else {
2401 USTPUTC('/', new);
2402 cdcomppath++;
2403 if (dir[1] == '/' && dir[2] != '/') {
2404 USTPUTC('/', new);
2405 cdcomppath++;
2406 lim++;
2407 }
2408 }
2409 p = strtok(cdcomppath, "/");
2410 while (p) {
2411 switch (*p) {
2412 case '.':
2413 if (p[1] == '.' && p[2] == '\0') {
2414 while (new > lim) {
2415 STUNPUTC(new);
2416 if (new[-1] == '/')
2417 break;
2418 }
2419 break;
Denis Vlasenko16abcd92007-04-13 23:59:52 +00002420 }
2421 if (p[1] == '\0')
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002422 break;
2423 /* fall through */
2424 default:
2425 new = stack_putstr(p, new);
2426 USTPUTC('/', new);
2427 }
2428 p = strtok(0, "/");
2429 }
2430 if (new > lim)
2431 STUNPUTC(new);
2432 *new = 0;
2433 return stackblock();
2434}
2435
2436/*
2437 * Find out what the current directory is. If we already know the current
2438 * directory, this routine returns immediately.
2439 */
2440static char *
2441getpwd(void)
2442{
Denis Vlasenko01631112007-12-16 17:20:38 +00002443 char *dir = getcwd(NULL, 0); /* huh, using glibc extension? */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002444 return dir ? dir : nullstr;
2445}
2446
2447static void
2448setpwd(const char *val, int setold)
2449{
2450 char *oldcur, *dir;
2451
2452 oldcur = dir = curdir;
2453
2454 if (setold) {
2455 setvar("OLDPWD", oldcur, VEXPORT);
2456 }
2457 INT_OFF;
2458 if (physdir != nullstr) {
2459 if (physdir != oldcur)
2460 free(physdir);
2461 physdir = nullstr;
2462 }
2463 if (oldcur == val || !val) {
2464 char *s = getpwd();
2465 physdir = s;
2466 if (!val)
2467 dir = s;
2468 } else
2469 dir = ckstrdup(val);
2470 if (oldcur != dir && oldcur != nullstr) {
2471 free(oldcur);
2472 }
2473 curdir = dir;
2474 INT_ON;
2475 setvar("PWD", dir, VEXPORT);
2476}
2477
2478static void hashcd(void);
2479
2480/*
2481 * Actually do the chdir. We also call hashcd to let the routines in exec.c
2482 * know that the current directory has changed.
2483 */
2484static int
2485docd(const char *dest, int flags)
2486{
Denys Vlasenko4b1100e2010-03-05 14:10:54 +01002487 const char *dir = NULL;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002488 int err;
2489
2490 TRACE(("docd(\"%s\", %d) called\n", dest, flags));
2491
2492 INT_OFF;
2493 if (!(flags & CD_PHYSICAL)) {
2494 dir = updatepwd(dest);
2495 if (dir)
2496 dest = dir;
2497 }
2498 err = chdir(dest);
2499 if (err)
2500 goto out;
2501 setpwd(dir, 1);
2502 hashcd();
2503 out:
2504 INT_ON;
2505 return err;
2506}
2507
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02002508static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00002509cdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002510{
2511 const char *dest;
2512 const char *path;
2513 const char *p;
2514 char c;
2515 struct stat statb;
2516 int flags;
2517
2518 flags = cdopt();
2519 dest = *argptr;
2520 if (!dest)
2521 dest = bltinlookup(homestr);
2522 else if (LONE_DASH(dest)) {
2523 dest = bltinlookup("OLDPWD");
2524 flags |= CD_PRINT;
2525 }
2526 if (!dest)
2527 dest = nullstr;
2528 if (*dest == '/')
2529 goto step7;
2530 if (*dest == '.') {
2531 c = dest[1];
2532 dotdot:
2533 switch (c) {
2534 case '\0':
2535 case '/':
2536 goto step6;
2537 case '.':
2538 c = dest[2];
2539 if (c != '.')
2540 goto dotdot;
2541 }
2542 }
2543 if (!*dest)
2544 dest = ".";
2545 path = bltinlookup("CDPATH");
2546 if (!path) {
2547 step6:
2548 step7:
2549 p = dest;
2550 goto docd;
2551 }
2552 do {
2553 c = *path;
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02002554 p = path_advance(&path, dest);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002555 if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
2556 if (c && c != ':')
2557 flags |= CD_PRINT;
2558 docd:
2559 if (!docd(p, flags))
2560 goto out;
2561 break;
2562 }
2563 } while (path);
2564 ash_msg_and_raise_error("can't cd to %s", dest);
2565 /* NOTREACHED */
2566 out:
2567 if (flags & CD_PRINT)
2568 out1fmt(snlfmt, curdir);
2569 return 0;
2570}
2571
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02002572static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00002573pwdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002574{
2575 int flags;
2576 const char *dir = curdir;
2577
2578 flags = cdopt();
2579 if (flags) {
2580 if (physdir == nullstr)
2581 setpwd(dir, 0);
2582 dir = physdir;
2583 }
2584 out1fmt(snlfmt, dir);
2585 return 0;
2586}
2587
Denis Vlasenko0c032a42007-02-23 01:03:40 +00002588
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00002589/* ============ ... */
Eric Andersenc470f442003-07-28 09:56:35 +00002590
Denis Vlasenko834dee72008-10-07 09:18:30 +00002591
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +00002592#define IBUFSIZ COMMON_BUFSIZE
Denis Vlasenko834dee72008-10-07 09:18:30 +00002593/* buffer for top level input file */
2594#define basebuf bb_common_bufsiz1
Eric Andersenc470f442003-07-28 09:56:35 +00002595
Eric Andersenc470f442003-07-28 09:56:35 +00002596/* Syntax classes */
Denis Vlasenko834dee72008-10-07 09:18:30 +00002597#define CWORD 0 /* character is nothing special */
2598#define CNL 1 /* newline character */
2599#define CBACK 2 /* a backslash character */
2600#define CSQUOTE 3 /* single quote */
2601#define CDQUOTE 4 /* double quote */
Eric Andersenc470f442003-07-28 09:56:35 +00002602#define CENDQUOTE 5 /* a terminating quote */
Denis Vlasenko834dee72008-10-07 09:18:30 +00002603#define CBQUOTE 6 /* backwards single quote */
2604#define CVAR 7 /* a dollar sign */
2605#define CENDVAR 8 /* a '}' character */
2606#define CLP 9 /* a left paren in arithmetic */
2607#define CRP 10 /* a right paren in arithmetic */
Eric Andersenc470f442003-07-28 09:56:35 +00002608#define CENDFILE 11 /* end of file */
Denis Vlasenko834dee72008-10-07 09:18:30 +00002609#define CCTL 12 /* like CWORD, except it must be escaped */
2610#define CSPCL 13 /* these terminate a word */
2611#define CIGN 14 /* character should be ignored */
Eric Andersenc470f442003-07-28 09:56:35 +00002612
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002613#define PEOF 256
Denis Vlasenko131ae172007-02-18 13:00:19 +00002614#if ENABLE_ASH_ALIAS
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002615# define PEOA 257
Eric Andersenc470f442003-07-28 09:56:35 +00002616#endif
2617
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002618#define USE_SIT_FUNCTION ENABLE_ASH_OPTIMIZE_FOR_SIZE
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002619
Mike Frysinger98c52642009-04-02 10:02:37 +00002620#if ENABLE_SH_MATH_SUPPORT
Denys Vlasenko76bc2d62009-11-29 01:37:46 +01002621# define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8) | (d << 12))
Eric Andersenc470f442003-07-28 09:56:35 +00002622#else
Denys Vlasenko76bc2d62009-11-29 01:37:46 +01002623# define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8))
Denys Vlasenko76bc2d62009-11-29 01:37:46 +01002624#endif
Denys Vlasenko068d3862009-11-29 01:41:11 +01002625static const uint16_t S_I_T[] = {
Denys Vlasenko76bc2d62009-11-29 01:37:46 +01002626#if ENABLE_ASH_ALIAS
2627 SIT_ITEM(CSPCL , CIGN , CIGN , CIGN ), /* 0, PEOA */
2628#endif
2629 SIT_ITEM(CSPCL , CWORD , CWORD, CWORD ), /* 1, ' ' */
2630 SIT_ITEM(CNL , CNL , CNL , CNL ), /* 2, \n */
2631 SIT_ITEM(CWORD , CCTL , CCTL , CWORD ), /* 3, !*-/:=?[]~ */
2632 SIT_ITEM(CDQUOTE , CENDQUOTE, CWORD, CWORD ), /* 4, '"' */
2633 SIT_ITEM(CVAR , CVAR , CWORD, CVAR ), /* 5, $ */
2634 SIT_ITEM(CSQUOTE , CWORD , CENDQUOTE, CWORD), /* 6, "'" */
2635 SIT_ITEM(CSPCL , CWORD , CWORD, CLP ), /* 7, ( */
2636 SIT_ITEM(CSPCL , CWORD , CWORD, CRP ), /* 8, ) */
2637 SIT_ITEM(CBACK , CBACK , CCTL , CBACK ), /* 9, \ */
2638 SIT_ITEM(CBQUOTE , CBQUOTE , CWORD, CBQUOTE), /* 10, ` */
2639 SIT_ITEM(CENDVAR , CENDVAR , CWORD, CENDVAR), /* 11, } */
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002640#if !USE_SIT_FUNCTION
Denys Vlasenko76bc2d62009-11-29 01:37:46 +01002641 SIT_ITEM(CENDFILE, CENDFILE , CENDFILE, CENDFILE),/* 12, PEOF */
2642 SIT_ITEM(CWORD , CWORD , CWORD, CWORD ), /* 13, 0-9A-Za-z */
2643 SIT_ITEM(CCTL , CCTL , CCTL , CCTL ) /* 14, CTLESC ... */
2644#endif
2645#undef SIT_ITEM
Eric Andersenc470f442003-07-28 09:56:35 +00002646};
Denys Vlasenko76bc2d62009-11-29 01:37:46 +01002647/* Constants below must match table above */
2648enum {
2649#if ENABLE_ASH_ALIAS
2650 CSPCL_CIGN_CIGN_CIGN , /* 0 */
2651#endif
2652 CSPCL_CWORD_CWORD_CWORD , /* 1 */
2653 CNL_CNL_CNL_CNL , /* 2 */
2654 CWORD_CCTL_CCTL_CWORD , /* 3 */
2655 CDQUOTE_CENDQUOTE_CWORD_CWORD , /* 4 */
2656 CVAR_CVAR_CWORD_CVAR , /* 5 */
2657 CSQUOTE_CWORD_CENDQUOTE_CWORD , /* 6 */
2658 CSPCL_CWORD_CWORD_CLP , /* 7 */
2659 CSPCL_CWORD_CWORD_CRP , /* 8 */
2660 CBACK_CBACK_CCTL_CBACK , /* 9 */
2661 CBQUOTE_CBQUOTE_CWORD_CBQUOTE , /* 10 */
2662 CENDVAR_CENDVAR_CWORD_CENDVAR , /* 11 */
2663 CENDFILE_CENDFILE_CENDFILE_CENDFILE, /* 12 */
2664 CWORD_CWORD_CWORD_CWORD , /* 13 */
2665 CCTL_CCTL_CCTL_CCTL , /* 14 */
2666};
Eric Andersen2870d962001-07-02 17:27:21 +00002667
Denys Vlasenkocd716832009-11-28 22:14:02 +01002668/* c in SIT(c, syntax) must be an *unsigned char* or PEOA or PEOF,
2669 * caller must ensure proper cast on it if c is *char_ptr!
2670 */
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002671/* Values for syntax param */
2672#define BASESYNTAX 0 /* not in quotes */
2673#define DQSYNTAX 1 /* in double quotes */
2674#define SQSYNTAX 2 /* in single quotes */
2675#define ARISYNTAX 3 /* in arithmetic */
2676#define PSSYNTAX 4 /* prompt. never passed to SIT() */
Denys Vlasenkocd716832009-11-28 22:14:02 +01002677
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002678#if USE_SIT_FUNCTION
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002679
Denis Vlasenko0c032a42007-02-23 01:03:40 +00002680static int
2681SIT(int c, int syntax)
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002682{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00002683 static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-/:;<=>?[\\]`|}~";
Denys Vlasenkocd716832009-11-28 22:14:02 +01002684# if ENABLE_ASH_ALIAS
2685 static const uint8_t syntax_index_table[] ALIGN1 = {
Eric Andersenc470f442003-07-28 09:56:35 +00002686 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
2687 7, 8, 3, 3, 3, 3, 1, 1, /* "()*-/:;<" */
2688 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
2689 11, 3 /* "}~" */
2690 };
Denys Vlasenkocd716832009-11-28 22:14:02 +01002691# else
2692 static const uint8_t syntax_index_table[] ALIGN1 = {
Eric Andersenc470f442003-07-28 09:56:35 +00002693 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
2694 6, 7, 2, 2, 2, 2, 0, 0, /* "()*-/:;<" */
2695 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
2696 10, 2 /* "}~" */
2697 };
Denys Vlasenkocd716832009-11-28 22:14:02 +01002698# endif
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002699 const char *s;
2700 int indx;
2701
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002702 if (c == PEOF)
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002703 return CENDFILE;
Denys Vlasenkocd716832009-11-28 22:14:02 +01002704# if ENABLE_ASH_ALIAS
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002705 if (c == PEOA)
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +00002706 indx = 0;
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002707 else
Denys Vlasenkocd716832009-11-28 22:14:02 +01002708# endif
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +00002709 {
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002710 /* Cast is purely for paranoia here,
2711 * just in case someone passed signed char to us */
2712 if ((unsigned char)c >= CTL_FIRST
2713 && (unsigned char)c <= CTL_LAST
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +00002714 ) {
2715 return CCTL;
2716 }
2717 s = strchrnul(spec_symbls, c);
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002718 if (*s == '\0')
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +00002719 return CWORD;
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +00002720 indx = syntax_index_table[s - spec_symbls];
2721 }
Denys Vlasenko76bc2d62009-11-29 01:37:46 +01002722 return (S_I_T[indx] >> (syntax*4)) & 0xf;
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002723}
2724
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00002725#else /* !USE_SIT_FUNCTION */
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002726
Denys Vlasenko76bc2d62009-11-29 01:37:46 +01002727static const uint8_t syntax_index_table[] = {
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00002728 /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
Denys Vlasenkocd716832009-11-28 22:14:02 +01002729 /* 0 */ CWORD_CWORD_CWORD_CWORD,
2730 /* 1 */ CWORD_CWORD_CWORD_CWORD,
2731 /* 2 */ CWORD_CWORD_CWORD_CWORD,
2732 /* 3 */ CWORD_CWORD_CWORD_CWORD,
2733 /* 4 */ CWORD_CWORD_CWORD_CWORD,
2734 /* 5 */ CWORD_CWORD_CWORD_CWORD,
2735 /* 6 */ CWORD_CWORD_CWORD_CWORD,
2736 /* 7 */ CWORD_CWORD_CWORD_CWORD,
2737 /* 8 */ CWORD_CWORD_CWORD_CWORD,
2738 /* 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
2739 /* 10 "\n" */ CNL_CNL_CNL_CNL,
2740 /* 11 */ CWORD_CWORD_CWORD_CWORD,
2741 /* 12 */ CWORD_CWORD_CWORD_CWORD,
2742 /* 13 */ CWORD_CWORD_CWORD_CWORD,
2743 /* 14 */ CWORD_CWORD_CWORD_CWORD,
2744 /* 15 */ CWORD_CWORD_CWORD_CWORD,
2745 /* 16 */ CWORD_CWORD_CWORD_CWORD,
2746 /* 17 */ CWORD_CWORD_CWORD_CWORD,
2747 /* 18 */ CWORD_CWORD_CWORD_CWORD,
2748 /* 19 */ CWORD_CWORD_CWORD_CWORD,
2749 /* 20 */ CWORD_CWORD_CWORD_CWORD,
2750 /* 21 */ CWORD_CWORD_CWORD_CWORD,
2751 /* 22 */ CWORD_CWORD_CWORD_CWORD,
2752 /* 23 */ CWORD_CWORD_CWORD_CWORD,
2753 /* 24 */ CWORD_CWORD_CWORD_CWORD,
2754 /* 25 */ CWORD_CWORD_CWORD_CWORD,
2755 /* 26 */ CWORD_CWORD_CWORD_CWORD,
2756 /* 27 */ CWORD_CWORD_CWORD_CWORD,
2757 /* 28 */ CWORD_CWORD_CWORD_CWORD,
2758 /* 29 */ CWORD_CWORD_CWORD_CWORD,
2759 /* 30 */ CWORD_CWORD_CWORD_CWORD,
2760 /* 31 */ CWORD_CWORD_CWORD_CWORD,
2761 /* 32 " " */ CSPCL_CWORD_CWORD_CWORD,
2762 /* 33 "!" */ CWORD_CCTL_CCTL_CWORD,
2763 /* 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
2764 /* 35 "#" */ CWORD_CWORD_CWORD_CWORD,
2765 /* 36 "$" */ CVAR_CVAR_CWORD_CVAR,
2766 /* 37 "%" */ CWORD_CWORD_CWORD_CWORD,
2767 /* 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
2768 /* 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
2769 /* 40 "(" */ CSPCL_CWORD_CWORD_CLP,
2770 /* 41 ")" */ CSPCL_CWORD_CWORD_CRP,
2771 /* 42 "*" */ CWORD_CCTL_CCTL_CWORD,
2772 /* 43 "+" */ CWORD_CWORD_CWORD_CWORD,
2773 /* 44 "," */ CWORD_CWORD_CWORD_CWORD,
2774 /* 45 "-" */ CWORD_CCTL_CCTL_CWORD,
2775 /* 46 "." */ CWORD_CWORD_CWORD_CWORD,
2776 /* 47 "/" */ CWORD_CCTL_CCTL_CWORD,
2777 /* 48 "0" */ CWORD_CWORD_CWORD_CWORD,
2778 /* 49 "1" */ CWORD_CWORD_CWORD_CWORD,
2779 /* 50 "2" */ CWORD_CWORD_CWORD_CWORD,
2780 /* 51 "3" */ CWORD_CWORD_CWORD_CWORD,
2781 /* 52 "4" */ CWORD_CWORD_CWORD_CWORD,
2782 /* 53 "5" */ CWORD_CWORD_CWORD_CWORD,
2783 /* 54 "6" */ CWORD_CWORD_CWORD_CWORD,
2784 /* 55 "7" */ CWORD_CWORD_CWORD_CWORD,
2785 /* 56 "8" */ CWORD_CWORD_CWORD_CWORD,
2786 /* 57 "9" */ CWORD_CWORD_CWORD_CWORD,
2787 /* 58 ":" */ CWORD_CCTL_CCTL_CWORD,
2788 /* 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
2789 /* 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
2790 /* 61 "=" */ CWORD_CCTL_CCTL_CWORD,
2791 /* 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
2792 /* 63 "?" */ CWORD_CCTL_CCTL_CWORD,
2793 /* 64 "@" */ CWORD_CWORD_CWORD_CWORD,
2794 /* 65 "A" */ CWORD_CWORD_CWORD_CWORD,
2795 /* 66 "B" */ CWORD_CWORD_CWORD_CWORD,
2796 /* 67 "C" */ CWORD_CWORD_CWORD_CWORD,
2797 /* 68 "D" */ CWORD_CWORD_CWORD_CWORD,
2798 /* 69 "E" */ CWORD_CWORD_CWORD_CWORD,
2799 /* 70 "F" */ CWORD_CWORD_CWORD_CWORD,
2800 /* 71 "G" */ CWORD_CWORD_CWORD_CWORD,
2801 /* 72 "H" */ CWORD_CWORD_CWORD_CWORD,
2802 /* 73 "I" */ CWORD_CWORD_CWORD_CWORD,
2803 /* 74 "J" */ CWORD_CWORD_CWORD_CWORD,
2804 /* 75 "K" */ CWORD_CWORD_CWORD_CWORD,
2805 /* 76 "L" */ CWORD_CWORD_CWORD_CWORD,
2806 /* 77 "M" */ CWORD_CWORD_CWORD_CWORD,
2807 /* 78 "N" */ CWORD_CWORD_CWORD_CWORD,
2808 /* 79 "O" */ CWORD_CWORD_CWORD_CWORD,
2809 /* 80 "P" */ CWORD_CWORD_CWORD_CWORD,
2810 /* 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
2811 /* 82 "R" */ CWORD_CWORD_CWORD_CWORD,
2812 /* 83 "S" */ CWORD_CWORD_CWORD_CWORD,
2813 /* 84 "T" */ CWORD_CWORD_CWORD_CWORD,
2814 /* 85 "U" */ CWORD_CWORD_CWORD_CWORD,
2815 /* 86 "V" */ CWORD_CWORD_CWORD_CWORD,
2816 /* 87 "W" */ CWORD_CWORD_CWORD_CWORD,
2817 /* 88 "X" */ CWORD_CWORD_CWORD_CWORD,
2818 /* 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
2819 /* 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
2820 /* 91 "[" */ CWORD_CCTL_CCTL_CWORD,
2821 /* 92 "\" */ CBACK_CBACK_CCTL_CBACK,
2822 /* 93 "]" */ CWORD_CCTL_CCTL_CWORD,
2823 /* 94 "^" */ CWORD_CWORD_CWORD_CWORD,
2824 /* 95 "_" */ CWORD_CWORD_CWORD_CWORD,
2825 /* 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
2826 /* 97 "a" */ CWORD_CWORD_CWORD_CWORD,
2827 /* 98 "b" */ CWORD_CWORD_CWORD_CWORD,
2828 /* 99 "c" */ CWORD_CWORD_CWORD_CWORD,
2829 /* 100 "d" */ CWORD_CWORD_CWORD_CWORD,
2830 /* 101 "e" */ CWORD_CWORD_CWORD_CWORD,
2831 /* 102 "f" */ CWORD_CWORD_CWORD_CWORD,
2832 /* 103 "g" */ CWORD_CWORD_CWORD_CWORD,
2833 /* 104 "h" */ CWORD_CWORD_CWORD_CWORD,
2834 /* 105 "i" */ CWORD_CWORD_CWORD_CWORD,
2835 /* 106 "j" */ CWORD_CWORD_CWORD_CWORD,
2836 /* 107 "k" */ CWORD_CWORD_CWORD_CWORD,
2837 /* 108 "l" */ CWORD_CWORD_CWORD_CWORD,
2838 /* 109 "m" */ CWORD_CWORD_CWORD_CWORD,
2839 /* 110 "n" */ CWORD_CWORD_CWORD_CWORD,
2840 /* 111 "o" */ CWORD_CWORD_CWORD_CWORD,
2841 /* 112 "p" */ CWORD_CWORD_CWORD_CWORD,
2842 /* 113 "q" */ CWORD_CWORD_CWORD_CWORD,
2843 /* 114 "r" */ CWORD_CWORD_CWORD_CWORD,
2844 /* 115 "s" */ CWORD_CWORD_CWORD_CWORD,
2845 /* 116 "t" */ CWORD_CWORD_CWORD_CWORD,
2846 /* 117 "u" */ CWORD_CWORD_CWORD_CWORD,
2847 /* 118 "v" */ CWORD_CWORD_CWORD_CWORD,
2848 /* 119 "w" */ CWORD_CWORD_CWORD_CWORD,
2849 /* 120 "x" */ CWORD_CWORD_CWORD_CWORD,
2850 /* 121 "y" */ CWORD_CWORD_CWORD_CWORD,
2851 /* 122 "z" */ CWORD_CWORD_CWORD_CWORD,
2852 /* 123 "{" */ CWORD_CWORD_CWORD_CWORD,
2853 /* 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
2854 /* 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
2855 /* 126 "~" */ CWORD_CCTL_CCTL_CWORD,
2856 /* 127 del */ CWORD_CWORD_CWORD_CWORD,
2857 /* 128 0x80 */ CWORD_CWORD_CWORD_CWORD,
2858 /* 129 CTLESC */ CCTL_CCTL_CCTL_CCTL,
2859 /* 130 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
2860 /* 131 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
2861 /* 132 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
2862 /* 133 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
2863 /* 134 CTLARI */ CCTL_CCTL_CCTL_CCTL,
2864 /* 135 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
2865 /* 136 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
2866 /* 137 */ CWORD_CWORD_CWORD_CWORD,
2867 /* 138 */ CWORD_CWORD_CWORD_CWORD,
2868 /* 139 */ CWORD_CWORD_CWORD_CWORD,
2869 /* 140 */ CWORD_CWORD_CWORD_CWORD,
2870 /* 141 */ CWORD_CWORD_CWORD_CWORD,
2871 /* 142 */ CWORD_CWORD_CWORD_CWORD,
2872 /* 143 */ CWORD_CWORD_CWORD_CWORD,
2873 /* 144 */ CWORD_CWORD_CWORD_CWORD,
2874 /* 145 */ CWORD_CWORD_CWORD_CWORD,
2875 /* 146 */ CWORD_CWORD_CWORD_CWORD,
2876 /* 147 */ CWORD_CWORD_CWORD_CWORD,
2877 /* 148 */ CWORD_CWORD_CWORD_CWORD,
2878 /* 149 */ CWORD_CWORD_CWORD_CWORD,
2879 /* 150 */ CWORD_CWORD_CWORD_CWORD,
2880 /* 151 */ CWORD_CWORD_CWORD_CWORD,
2881 /* 152 */ CWORD_CWORD_CWORD_CWORD,
2882 /* 153 */ CWORD_CWORD_CWORD_CWORD,
2883 /* 154 */ CWORD_CWORD_CWORD_CWORD,
2884 /* 155 */ CWORD_CWORD_CWORD_CWORD,
2885 /* 156 */ CWORD_CWORD_CWORD_CWORD,
2886 /* 157 */ CWORD_CWORD_CWORD_CWORD,
2887 /* 158 */ CWORD_CWORD_CWORD_CWORD,
2888 /* 159 */ CWORD_CWORD_CWORD_CWORD,
2889 /* 160 */ CWORD_CWORD_CWORD_CWORD,
2890 /* 161 */ CWORD_CWORD_CWORD_CWORD,
2891 /* 162 */ CWORD_CWORD_CWORD_CWORD,
2892 /* 163 */ CWORD_CWORD_CWORD_CWORD,
2893 /* 164 */ CWORD_CWORD_CWORD_CWORD,
2894 /* 165 */ CWORD_CWORD_CWORD_CWORD,
2895 /* 166 */ CWORD_CWORD_CWORD_CWORD,
2896 /* 167 */ CWORD_CWORD_CWORD_CWORD,
2897 /* 168 */ CWORD_CWORD_CWORD_CWORD,
2898 /* 169 */ CWORD_CWORD_CWORD_CWORD,
2899 /* 170 */ CWORD_CWORD_CWORD_CWORD,
2900 /* 171 */ CWORD_CWORD_CWORD_CWORD,
2901 /* 172 */ CWORD_CWORD_CWORD_CWORD,
2902 /* 173 */ CWORD_CWORD_CWORD_CWORD,
2903 /* 174 */ CWORD_CWORD_CWORD_CWORD,
2904 /* 175 */ CWORD_CWORD_CWORD_CWORD,
2905 /* 176 */ CWORD_CWORD_CWORD_CWORD,
2906 /* 177 */ CWORD_CWORD_CWORD_CWORD,
2907 /* 178 */ CWORD_CWORD_CWORD_CWORD,
2908 /* 179 */ CWORD_CWORD_CWORD_CWORD,
2909 /* 180 */ CWORD_CWORD_CWORD_CWORD,
2910 /* 181 */ CWORD_CWORD_CWORD_CWORD,
2911 /* 182 */ CWORD_CWORD_CWORD_CWORD,
2912 /* 183 */ CWORD_CWORD_CWORD_CWORD,
2913 /* 184 */ CWORD_CWORD_CWORD_CWORD,
2914 /* 185 */ CWORD_CWORD_CWORD_CWORD,
2915 /* 186 */ CWORD_CWORD_CWORD_CWORD,
2916 /* 187 */ CWORD_CWORD_CWORD_CWORD,
2917 /* 188 */ CWORD_CWORD_CWORD_CWORD,
2918 /* 189 */ CWORD_CWORD_CWORD_CWORD,
2919 /* 190 */ CWORD_CWORD_CWORD_CWORD,
2920 /* 191 */ CWORD_CWORD_CWORD_CWORD,
2921 /* 192 */ CWORD_CWORD_CWORD_CWORD,
2922 /* 193 */ CWORD_CWORD_CWORD_CWORD,
2923 /* 194 */ CWORD_CWORD_CWORD_CWORD,
2924 /* 195 */ CWORD_CWORD_CWORD_CWORD,
2925 /* 196 */ CWORD_CWORD_CWORD_CWORD,
2926 /* 197 */ CWORD_CWORD_CWORD_CWORD,
2927 /* 198 */ CWORD_CWORD_CWORD_CWORD,
2928 /* 199 */ CWORD_CWORD_CWORD_CWORD,
2929 /* 200 */ CWORD_CWORD_CWORD_CWORD,
2930 /* 201 */ CWORD_CWORD_CWORD_CWORD,
2931 /* 202 */ CWORD_CWORD_CWORD_CWORD,
2932 /* 203 */ CWORD_CWORD_CWORD_CWORD,
2933 /* 204 */ CWORD_CWORD_CWORD_CWORD,
2934 /* 205 */ CWORD_CWORD_CWORD_CWORD,
2935 /* 206 */ CWORD_CWORD_CWORD_CWORD,
2936 /* 207 */ CWORD_CWORD_CWORD_CWORD,
2937 /* 208 */ CWORD_CWORD_CWORD_CWORD,
2938 /* 209 */ CWORD_CWORD_CWORD_CWORD,
2939 /* 210 */ CWORD_CWORD_CWORD_CWORD,
2940 /* 211 */ CWORD_CWORD_CWORD_CWORD,
2941 /* 212 */ CWORD_CWORD_CWORD_CWORD,
2942 /* 213 */ CWORD_CWORD_CWORD_CWORD,
2943 /* 214 */ CWORD_CWORD_CWORD_CWORD,
2944 /* 215 */ CWORD_CWORD_CWORD_CWORD,
2945 /* 216 */ CWORD_CWORD_CWORD_CWORD,
2946 /* 217 */ CWORD_CWORD_CWORD_CWORD,
2947 /* 218 */ CWORD_CWORD_CWORD_CWORD,
2948 /* 219 */ CWORD_CWORD_CWORD_CWORD,
2949 /* 220 */ CWORD_CWORD_CWORD_CWORD,
2950 /* 221 */ CWORD_CWORD_CWORD_CWORD,
2951 /* 222 */ CWORD_CWORD_CWORD_CWORD,
2952 /* 223 */ CWORD_CWORD_CWORD_CWORD,
2953 /* 224 */ CWORD_CWORD_CWORD_CWORD,
2954 /* 225 */ CWORD_CWORD_CWORD_CWORD,
2955 /* 226 */ CWORD_CWORD_CWORD_CWORD,
2956 /* 227 */ CWORD_CWORD_CWORD_CWORD,
2957 /* 228 */ CWORD_CWORD_CWORD_CWORD,
2958 /* 229 */ CWORD_CWORD_CWORD_CWORD,
2959 /* 230 */ CWORD_CWORD_CWORD_CWORD,
2960 /* 231 */ CWORD_CWORD_CWORD_CWORD,
2961 /* 232 */ CWORD_CWORD_CWORD_CWORD,
2962 /* 233 */ CWORD_CWORD_CWORD_CWORD,
2963 /* 234 */ CWORD_CWORD_CWORD_CWORD,
2964 /* 235 */ CWORD_CWORD_CWORD_CWORD,
2965 /* 236 */ CWORD_CWORD_CWORD_CWORD,
2966 /* 237 */ CWORD_CWORD_CWORD_CWORD,
2967 /* 238 */ CWORD_CWORD_CWORD_CWORD,
2968 /* 239 */ CWORD_CWORD_CWORD_CWORD,
2969 /* 230 */ CWORD_CWORD_CWORD_CWORD,
2970 /* 241 */ CWORD_CWORD_CWORD_CWORD,
2971 /* 242 */ CWORD_CWORD_CWORD_CWORD,
2972 /* 243 */ CWORD_CWORD_CWORD_CWORD,
2973 /* 244 */ CWORD_CWORD_CWORD_CWORD,
2974 /* 245 */ CWORD_CWORD_CWORD_CWORD,
2975 /* 246 */ CWORD_CWORD_CWORD_CWORD,
2976 /* 247 */ CWORD_CWORD_CWORD_CWORD,
2977 /* 248 */ CWORD_CWORD_CWORD_CWORD,
2978 /* 249 */ CWORD_CWORD_CWORD_CWORD,
2979 /* 250 */ CWORD_CWORD_CWORD_CWORD,
2980 /* 251 */ CWORD_CWORD_CWORD_CWORD,
2981 /* 252 */ CWORD_CWORD_CWORD_CWORD,
2982 /* 253 */ CWORD_CWORD_CWORD_CWORD,
2983 /* 254 */ CWORD_CWORD_CWORD_CWORD,
2984 /* 255 */ CWORD_CWORD_CWORD_CWORD,
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002985 /* PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
Denys Vlasenkocd716832009-11-28 22:14:02 +01002986# if ENABLE_ASH_ALIAS
2987 /* PEOA */ CSPCL_CIGN_CIGN_CIGN,
2988# endif
Eric Andersen2870d962001-07-02 17:27:21 +00002989};
2990
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002991# define SIT(c, syntax) ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf)
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00002992
Denys Vlasenko76bc2d62009-11-29 01:37:46 +01002993#endif /* !USE_SIT_FUNCTION */
Eric Andersenc470f442003-07-28 09:56:35 +00002994
Eric Andersen2870d962001-07-02 17:27:21 +00002995
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00002996/* ============ Alias handling */
Denis Vlasenkofc06f292007-02-23 21:09:35 +00002997
Denis Vlasenko131ae172007-02-18 13:00:19 +00002998#if ENABLE_ASH_ALIAS
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00002999
3000#define ALIASINUSE 1
3001#define ALIASDEAD 2
3002
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00003003struct alias {
3004 struct alias *next;
3005 char *name;
3006 char *val;
3007 int flag;
3008};
3009
Denis Vlasenko01631112007-12-16 17:20:38 +00003010
3011static struct alias **atab; // [ATABSIZE];
3012#define INIT_G_alias() do { \
3013 atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
3014} while (0)
3015
Eric Andersen2870d962001-07-02 17:27:21 +00003016
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00003017static struct alias **
3018__lookupalias(const char *name) {
3019 unsigned int hashval;
3020 struct alias **app;
3021 const char *p;
3022 unsigned int ch;
3023
3024 p = name;
3025
3026 ch = (unsigned char)*p;
3027 hashval = ch << 4;
3028 while (ch) {
3029 hashval += ch;
3030 ch = (unsigned char)*++p;
3031 }
3032 app = &atab[hashval % ATABSIZE];
3033
3034 for (; *app; app = &(*app)->next) {
3035 if (strcmp(name, (*app)->name) == 0) {
3036 break;
3037 }
3038 }
3039
3040 return app;
3041}
3042
3043static struct alias *
3044lookupalias(const char *name, int check)
3045{
3046 struct alias *ap = *__lookupalias(name);
3047
3048 if (check && ap && (ap->flag & ALIASINUSE))
3049 return NULL;
3050 return ap;
3051}
3052
3053static struct alias *
3054freealias(struct alias *ap)
3055{
3056 struct alias *next;
3057
3058 if (ap->flag & ALIASINUSE) {
3059 ap->flag |= ALIASDEAD;
3060 return ap;
3061 }
3062
3063 next = ap->next;
3064 free(ap->name);
3065 free(ap->val);
3066 free(ap);
3067 return next;
3068}
Eric Andersencb57d552001-06-28 07:25:16 +00003069
Eric Andersenc470f442003-07-28 09:56:35 +00003070static void
3071setalias(const char *name, const char *val)
Eric Andersencb57d552001-06-28 07:25:16 +00003072{
3073 struct alias *ap, **app;
3074
3075 app = __lookupalias(name);
3076 ap = *app;
Denis Vlasenkob012b102007-02-19 22:43:01 +00003077 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +00003078 if (ap) {
3079 if (!(ap->flag & ALIASINUSE)) {
Denis Vlasenkob012b102007-02-19 22:43:01 +00003080 free(ap->val);
Eric Andersencb57d552001-06-28 07:25:16 +00003081 }
Denis Vlasenko0c032a42007-02-23 01:03:40 +00003082 ap->val = ckstrdup(val);
Eric Andersencb57d552001-06-28 07:25:16 +00003083 ap->flag &= ~ALIASDEAD;
3084 } else {
3085 /* not found */
Denis Vlasenko597906c2008-02-20 16:38:54 +00003086 ap = ckzalloc(sizeof(struct alias));
Denis Vlasenko0c032a42007-02-23 01:03:40 +00003087 ap->name = ckstrdup(name);
3088 ap->val = ckstrdup(val);
Denis Vlasenko597906c2008-02-20 16:38:54 +00003089 /*ap->flag = 0; - ckzalloc did it */
3090 /*ap->next = NULL;*/
Eric Andersencb57d552001-06-28 07:25:16 +00003091 *app = ap;
3092 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00003093 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00003094}
3095
Eric Andersenc470f442003-07-28 09:56:35 +00003096static int
3097unalias(const char *name)
Eric Andersen2870d962001-07-02 17:27:21 +00003098{
Eric Andersencb57d552001-06-28 07:25:16 +00003099 struct alias **app;
3100
3101 app = __lookupalias(name);
3102
3103 if (*app) {
Denis Vlasenkob012b102007-02-19 22:43:01 +00003104 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +00003105 *app = freealias(*app);
Denis Vlasenkob012b102007-02-19 22:43:01 +00003106 INT_ON;
Denis Vlasenko079f8af2006-11-27 16:49:31 +00003107 return 0;
Eric Andersencb57d552001-06-28 07:25:16 +00003108 }
3109
Denis Vlasenko079f8af2006-11-27 16:49:31 +00003110 return 1;
Eric Andersencb57d552001-06-28 07:25:16 +00003111}
3112
Eric Andersenc470f442003-07-28 09:56:35 +00003113static void
3114rmaliases(void)
Eric Andersen2870d962001-07-02 17:27:21 +00003115{
Eric Andersencb57d552001-06-28 07:25:16 +00003116 struct alias *ap, **app;
3117 int i;
3118
Denis Vlasenkob012b102007-02-19 22:43:01 +00003119 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +00003120 for (i = 0; i < ATABSIZE; i++) {
3121 app = &atab[i];
3122 for (ap = *app; ap; ap = *app) {
3123 *app = freealias(*app);
3124 if (ap == *app) {
3125 app = &ap->next;
3126 }
3127 }
3128 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00003129 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00003130}
3131
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00003132static void
3133printalias(const struct alias *ap)
3134{
3135 out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
3136}
3137
Eric Andersencb57d552001-06-28 07:25:16 +00003138/*
3139 * TODO - sort output
3140 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02003141static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00003142aliascmd(int argc UNUSED_PARAM, char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +00003143{
3144 char *n, *v;
3145 int ret = 0;
3146 struct alias *ap;
3147
Denis Vlasenko68404f12008-03-17 09:00:54 +00003148 if (!argv[1]) {
Eric Andersencb57d552001-06-28 07:25:16 +00003149 int i;
3150
Denis Vlasenko68404f12008-03-17 09:00:54 +00003151 for (i = 0; i < ATABSIZE; i++) {
Eric Andersencb57d552001-06-28 07:25:16 +00003152 for (ap = atab[i]; ap; ap = ap->next) {
3153 printalias(ap);
3154 }
Denis Vlasenko68404f12008-03-17 09:00:54 +00003155 }
Denis Vlasenko079f8af2006-11-27 16:49:31 +00003156 return 0;
Eric Andersencb57d552001-06-28 07:25:16 +00003157 }
3158 while ((n = *++argv) != NULL) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00003159 v = strchr(n+1, '=');
3160 if (v == NULL) { /* n+1: funny ksh stuff */
3161 ap = *__lookupalias(n);
3162 if (ap == NULL) {
Eric Andersenc470f442003-07-28 09:56:35 +00003163 fprintf(stderr, "%s: %s not found\n", "alias", n);
Eric Andersencb57d552001-06-28 07:25:16 +00003164 ret = 1;
3165 } else
3166 printalias(ap);
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00003167 } else {
Eric Andersencb57d552001-06-28 07:25:16 +00003168 *v++ = '\0';
3169 setalias(n, v);
3170 }
3171 }
3172
Denis Vlasenkod9e15f22006-11-27 16:49:55 +00003173 return ret;
Eric Andersencb57d552001-06-28 07:25:16 +00003174}
3175
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02003176static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00003177unaliascmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersencb57d552001-06-28 07:25:16 +00003178{
3179 int i;
3180
3181 while ((i = nextopt("a")) != '\0') {
3182 if (i == 'a') {
3183 rmaliases();
Denis Vlasenko079f8af2006-11-27 16:49:31 +00003184 return 0;
Eric Andersencb57d552001-06-28 07:25:16 +00003185 }
3186 }
3187 for (i = 0; *argptr; argptr++) {
3188 if (unalias(*argptr)) {
Eric Andersenc470f442003-07-28 09:56:35 +00003189 fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
Eric Andersencb57d552001-06-28 07:25:16 +00003190 i = 1;
3191 }
3192 }
3193
Denis Vlasenkod9e15f22006-11-27 16:49:55 +00003194 return i;
Eric Andersencb57d552001-06-28 07:25:16 +00003195}
Denis Vlasenkofc06f292007-02-23 21:09:35 +00003196
Denis Vlasenko131ae172007-02-18 13:00:19 +00003197#endif /* ASH_ALIAS */
Eric Andersencb57d552001-06-28 07:25:16 +00003198
Eric Andersenc470f442003-07-28 09:56:35 +00003199
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003200/* ============ jobs.c */
3201
3202/* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
Denys Vlasenko285ad152009-12-04 23:02:27 +01003203#define FORK_FG 0
3204#define FORK_BG 1
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003205#define FORK_NOJOB 2
3206
3207/* mode flags for showjob(s) */
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003208#define SHOW_ONLY_PGID 0x01 /* show only pgid (jobs -p) */
3209#define SHOW_PIDS 0x02 /* show individual pids, not just one line per job */
3210#define SHOW_CHANGED 0x04 /* only jobs whose state has changed */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003211
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003212/*
3213 * A job structure contains information about a job. A job is either a
3214 * single process or a set of processes contained in a pipeline. In the
3215 * latter case, pidlist will be non-NULL, and will point to a -1 terminated
3216 * array of pids.
3217 */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003218struct procstat {
Denys Vlasenko285ad152009-12-04 23:02:27 +01003219 pid_t ps_pid; /* process id */
3220 int ps_status; /* last process status from wait() */
3221 char *ps_cmd; /* text of command being run */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003222};
3223
3224struct job {
3225 struct procstat ps0; /* status of process */
3226 struct procstat *ps; /* status or processes when more than one */
3227#if JOBS
3228 int stopstatus; /* status of a stopped job */
3229#endif
3230 uint32_t
3231 nprocs: 16, /* number of processes */
3232 state: 8,
3233#define JOBRUNNING 0 /* at least one proc running */
3234#define JOBSTOPPED 1 /* all procs are stopped */
3235#define JOBDONE 2 /* all procs are completed */
3236#if JOBS
3237 sigint: 1, /* job was killed by SIGINT */
3238 jobctl: 1, /* job running under job control */
3239#endif
3240 waited: 1, /* true if this entry has been waited for */
3241 used: 1, /* true if this entry is in used */
3242 changed: 1; /* true if status has changed */
3243 struct job *prev_job; /* previous job */
3244};
3245
Denis Vlasenko68404f12008-03-17 09:00:54 +00003246static struct job *makejob(/*union node *,*/ int);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003247static int forkshell(struct job *, union node *, int);
3248static int waitforjob(struct job *);
3249
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003250#if !JOBS
Denis Vlasenkob07a4962008-06-22 13:16:23 +00003251enum { doing_jobctl = 0 };
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003252#define setjobctl(on) do {} while (0)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003253#else
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003254static smallint doing_jobctl; //references:8
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003255static void setjobctl(int);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003256#endif
3257
3258/*
Denis Vlasenko4b875702009-03-19 13:30:04 +00003259 * Ignore a signal.
3260 */
3261static void
3262ignoresig(int signo)
3263{
3264 /* Avoid unnecessary system calls. Is it already SIG_IGNed? */
3265 if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
3266 /* No, need to do it */
3267 signal(signo, SIG_IGN);
3268 }
3269 sigmode[signo - 1] = S_HARD_IGN;
3270}
3271
3272/*
3273 * Signal handler. Only one usage site - in setsignal()
3274 */
3275static void
3276onsig(int signo)
3277{
3278 gotsig[signo - 1] = 1;
3279
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02003280 if (signo == SIGINT && !trap[SIGINT]) {
3281 if (!suppress_int) {
3282 pending_sig = 0;
Denis Vlasenko4b875702009-03-19 13:30:04 +00003283 raise_interrupt(); /* does not return */
3284 }
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02003285 pending_int = 1;
Denis Vlasenko4b875702009-03-19 13:30:04 +00003286 } else {
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02003287 pending_sig = signo;
Denis Vlasenko4b875702009-03-19 13:30:04 +00003288 }
3289}
3290
3291/*
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003292 * Set the signal handler for the specified signal. The routine figures
3293 * out what it should be set to.
3294 */
3295static void
3296setsignal(int signo)
3297{
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003298 char *t;
3299 char cur_act, new_act;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003300 struct sigaction act;
3301
3302 t = trap[signo];
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003303 new_act = S_DFL;
3304 if (t != NULL) { /* trap for this sig is set */
3305 new_act = S_CATCH;
3306 if (t[0] == '\0') /* trap is "": ignore this sig */
3307 new_act = S_IGN;
3308 }
3309
3310 if (rootshell && new_act == S_DFL) {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003311 switch (signo) {
3312 case SIGINT:
3313 if (iflag || minusc || sflag == 0)
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003314 new_act = S_CATCH;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003315 break;
3316 case SIGQUIT:
3317#if DEBUG
3318 if (debug)
3319 break;
3320#endif
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003321 /* man bash:
3322 * "In all cases, bash ignores SIGQUIT. Non-builtin
3323 * commands run by bash have signal handlers
3324 * set to the values inherited by the shell
3325 * from its parent". */
3326 new_act = S_IGN;
3327 break;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003328 case SIGTERM:
3329 if (iflag)
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003330 new_act = S_IGN;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003331 break;
3332#if JOBS
3333 case SIGTSTP:
3334 case SIGTTOU:
3335 if (mflag)
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003336 new_act = S_IGN;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003337 break;
3338#endif
3339 }
3340 }
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003341//TODO: if !rootshell, we reset SIGQUIT to DFL,
3342//whereas we have to restore it to what shell got on entry
3343//from the parent. See comment above
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003344
3345 t = &sigmode[signo - 1];
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003346 cur_act = *t;
3347 if (cur_act == 0) {
3348 /* current setting is not yet known */
3349 if (sigaction(signo, NULL, &act)) {
3350 /* pretend it worked; maybe we should give a warning,
3351 * but other shells don't. We don't alter sigmode,
3352 * so we retry every time.
3353 * btw, in Linux it never fails. --vda */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003354 return;
3355 }
3356 if (act.sa_handler == SIG_IGN) {
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003357 cur_act = S_HARD_IGN;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003358 if (mflag
3359 && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
3360 ) {
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003361 cur_act = S_IGN; /* don't hard ignore these */
Denis Vlasenko991a1da2008-02-10 19:02:53 +00003362 }
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003363 }
3364 }
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003365 if (cur_act == S_HARD_IGN || cur_act == new_act)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003366 return;
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003367
Denis Vlasenko991a1da2008-02-10 19:02:53 +00003368 act.sa_handler = SIG_DFL;
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003369 switch (new_act) {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003370 case S_CATCH:
3371 act.sa_handler = onsig;
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003372 act.sa_flags = 0; /* matters only if !DFL and !IGN */
3373 sigfillset(&act.sa_mask); /* ditto */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003374 break;
3375 case S_IGN:
3376 act.sa_handler = SIG_IGN;
3377 break;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003378 }
Denis Vlasenko8e2cfec2008-03-12 23:19:35 +00003379 sigaction_set(signo, &act);
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003380
3381 *t = new_act;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003382}
3383
3384/* mode flags for set_curjob */
3385#define CUR_DELETE 2
3386#define CUR_RUNNING 1
3387#define CUR_STOPPED 0
3388
3389/* mode flags for dowait */
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00003390#define DOWAIT_NONBLOCK WNOHANG
3391#define DOWAIT_BLOCK 0
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003392
3393#if JOBS
3394/* pgrp of shell on invocation */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003395static int initialpgrp; //references:2
3396static int ttyfd = -1; //5
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003397#endif
3398/* array of jobs */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003399static struct job *jobtab; //5
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003400/* size of array */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003401static unsigned njobs; //4
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003402/* current job */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003403static struct job *curjob; //lots
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003404/* number of presumed living untracked jobs */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003405static int jobless; //4
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003406
3407static void
3408set_curjob(struct job *jp, unsigned mode)
3409{
3410 struct job *jp1;
3411 struct job **jpp, **curp;
3412
3413 /* first remove from list */
3414 jpp = curp = &curjob;
3415 do {
3416 jp1 = *jpp;
3417 if (jp1 == jp)
3418 break;
3419 jpp = &jp1->prev_job;
3420 } while (1);
3421 *jpp = jp1->prev_job;
3422
3423 /* Then re-insert in correct position */
3424 jpp = curp;
3425 switch (mode) {
3426 default:
3427#if DEBUG
3428 abort();
3429#endif
3430 case CUR_DELETE:
3431 /* job being deleted */
3432 break;
3433 case CUR_RUNNING:
3434 /* newly created job or backgrounded job,
3435 put after all stopped jobs. */
3436 do {
3437 jp1 = *jpp;
3438#if JOBS
3439 if (!jp1 || jp1->state != JOBSTOPPED)
3440#endif
3441 break;
3442 jpp = &jp1->prev_job;
3443 } while (1);
3444 /* FALLTHROUGH */
3445#if JOBS
3446 case CUR_STOPPED:
3447#endif
3448 /* newly stopped job - becomes curjob */
3449 jp->prev_job = *jpp;
3450 *jpp = jp;
3451 break;
3452 }
3453}
3454
3455#if JOBS || DEBUG
3456static int
3457jobno(const struct job *jp)
3458{
3459 return jp - jobtab + 1;
3460}
3461#endif
3462
3463/*
3464 * Convert a job name to a job structure.
3465 */
Denis Vlasenko85c24712008-03-17 09:04:04 +00003466#if !JOBS
3467#define getjob(name, getctl) getjob(name)
3468#endif
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003469static struct job *
3470getjob(const char *name, int getctl)
3471{
3472 struct job *jp;
3473 struct job *found;
Denys Vlasenkoffc39202009-08-17 02:12:20 +02003474 const char *err_msg = "%s: no such job";
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003475 unsigned num;
3476 int c;
3477 const char *p;
3478 char *(*match)(const char *, const char *);
3479
3480 jp = curjob;
3481 p = name;
3482 if (!p)
3483 goto currentjob;
3484
3485 if (*p != '%')
3486 goto err;
3487
3488 c = *++p;
3489 if (!c)
3490 goto currentjob;
3491
3492 if (!p[1]) {
3493 if (c == '+' || c == '%') {
3494 currentjob:
3495 err_msg = "No current job";
3496 goto check;
3497 }
3498 if (c == '-') {
3499 if (jp)
3500 jp = jp->prev_job;
3501 err_msg = "No previous job";
3502 check:
3503 if (!jp)
3504 goto err;
3505 goto gotit;
3506 }
3507 }
3508
3509 if (is_number(p)) {
3510 num = atoi(p);
3511 if (num < njobs) {
3512 jp = jobtab + num - 1;
3513 if (jp->used)
3514 goto gotit;
3515 goto err;
3516 }
3517 }
3518
3519 match = prefix;
3520 if (*p == '?') {
3521 match = strstr;
3522 p++;
3523 }
3524
Denys Vlasenkoffc39202009-08-17 02:12:20 +02003525 found = NULL;
3526 while (jp) {
Denys Vlasenko285ad152009-12-04 23:02:27 +01003527 if (match(jp->ps[0].ps_cmd, p)) {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003528 if (found)
3529 goto err;
3530 found = jp;
3531 err_msg = "%s: ambiguous";
3532 }
3533 jp = jp->prev_job;
3534 }
Denys Vlasenkoffc39202009-08-17 02:12:20 +02003535 if (!found)
3536 goto err;
3537 jp = found;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003538
3539 gotit:
3540#if JOBS
3541 err_msg = "job %s not created under job control";
3542 if (getctl && jp->jobctl == 0)
3543 goto err;
3544#endif
3545 return jp;
3546 err:
3547 ash_msg_and_raise_error(err_msg, name);
3548}
3549
3550/*
3551 * Mark a job structure as unused.
3552 */
3553static void
3554freejob(struct job *jp)
3555{
3556 struct procstat *ps;
3557 int i;
3558
3559 INT_OFF;
3560 for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
Denys Vlasenko285ad152009-12-04 23:02:27 +01003561 if (ps->ps_cmd != nullstr)
3562 free(ps->ps_cmd);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003563 }
3564 if (jp->ps != &jp->ps0)
3565 free(jp->ps);
3566 jp->used = 0;
3567 set_curjob(jp, CUR_DELETE);
3568 INT_ON;
3569}
3570
3571#if JOBS
3572static void
3573xtcsetpgrp(int fd, pid_t pgrp)
3574{
3575 if (tcsetpgrp(fd, pgrp))
Bernhard Reutner-Fischera53de7f2008-07-21 13:46:54 +00003576 ash_msg_and_raise_error("can't set tty process group (%m)");
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003577}
3578
3579/*
3580 * Turn job control on and off.
3581 *
3582 * Note: This code assumes that the third arg to ioctl is a character
3583 * pointer, which is true on Berkeley systems but not System V. Since
3584 * System V doesn't have job control yet, this isn't a problem now.
3585 *
3586 * Called with interrupts off.
3587 */
3588static void
3589setjobctl(int on)
3590{
3591 int fd;
3592 int pgrp;
3593
Denis Vlasenkob07a4962008-06-22 13:16:23 +00003594 if (on == doing_jobctl || rootshell == 0)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003595 return;
3596 if (on) {
3597 int ofd;
3598 ofd = fd = open(_PATH_TTY, O_RDWR);
3599 if (fd < 0) {
3600 /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
3601 * That sometimes helps to acquire controlling tty.
3602 * Obviously, a workaround for bugs when someone
3603 * failed to provide a controlling tty to bash! :) */
Denis Vlasenkoed270a52007-11-26 05:37:07 +00003604 fd = 2;
3605 while (!isatty(fd))
3606 if (--fd < 0)
3607 goto out;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003608 }
3609 fd = fcntl(fd, F_DUPFD, 10);
Denis Vlasenkoed270a52007-11-26 05:37:07 +00003610 if (ofd >= 0)
3611 close(ofd);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003612 if (fd < 0)
3613 goto out;
Denis Vlasenkoed270a52007-11-26 05:37:07 +00003614 /* fd is a tty at this point */
Denis Vlasenko96e1b382007-09-30 23:50:48 +00003615 close_on_exec_on(fd);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003616 do { /* while we are in the background */
3617 pgrp = tcgetpgrp(fd);
3618 if (pgrp < 0) {
3619 out:
3620 ash_msg("can't access tty; job control turned off");
3621 mflag = on = 0;
3622 goto close;
3623 }
3624 if (pgrp == getpgrp())
3625 break;
3626 killpg(0, SIGTTIN);
3627 } while (1);
3628 initialpgrp = pgrp;
3629
3630 setsignal(SIGTSTP);
3631 setsignal(SIGTTOU);
3632 setsignal(SIGTTIN);
3633 pgrp = rootpid;
3634 setpgid(0, pgrp);
3635 xtcsetpgrp(fd, pgrp);
3636 } else {
3637 /* turning job control off */
3638 fd = ttyfd;
3639 pgrp = initialpgrp;
Denis Vlasenko08c8c1d2007-04-28 22:39:02 +00003640 /* was xtcsetpgrp, but this can make exiting ash
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00003641 * loop forever if pty is already deleted */
Denis Vlasenko08c8c1d2007-04-28 22:39:02 +00003642 tcsetpgrp(fd, pgrp);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003643 setpgid(0, pgrp);
3644 setsignal(SIGTSTP);
3645 setsignal(SIGTTOU);
3646 setsignal(SIGTTIN);
3647 close:
Denis Vlasenkoed270a52007-11-26 05:37:07 +00003648 if (fd >= 0)
3649 close(fd);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003650 fd = -1;
3651 }
3652 ttyfd = fd;
Denis Vlasenkob07a4962008-06-22 13:16:23 +00003653 doing_jobctl = on;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003654}
3655
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02003656static int FAST_FUNC
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003657killcmd(int argc, char **argv)
3658{
Denis Vlasenko68404f12008-03-17 09:00:54 +00003659 int i = 1;
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003660 if (argv[1] && strcmp(argv[1], "-l") != 0) {
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003661 do {
3662 if (argv[i][0] == '%') {
3663 struct job *jp = getjob(argv[i], 0);
Denys Vlasenko285ad152009-12-04 23:02:27 +01003664 unsigned pid = jp->ps[0].ps_pid;
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003665 /* Enough space for ' -NNN<nul>' */
3666 argv[i] = alloca(sizeof(int)*3 + 3);
3667 /* kill_main has matching code to expect
3668 * leading space. Needed to not confuse
3669 * negative pids with "kill -SIGNAL_NO" syntax */
3670 sprintf(argv[i], " -%u", pid);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003671 }
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003672 } while (argv[++i]);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003673 }
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003674 return kill_main(argc, argv);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003675}
3676
3677static void
Denys Vlasenko285ad152009-12-04 23:02:27 +01003678showpipe(struct job *jp /*, FILE *out*/)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003679{
Denys Vlasenko285ad152009-12-04 23:02:27 +01003680 struct procstat *ps;
3681 struct procstat *psend;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003682
Denys Vlasenko285ad152009-12-04 23:02:27 +01003683 psend = jp->ps + jp->nprocs;
3684 for (ps = jp->ps + 1; ps < psend; ps++)
3685 printf(" | %s", ps->ps_cmd);
3686 outcslow('\n', stdout);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003687 flush_stdout_stderr();
3688}
3689
3690
3691static int
3692restartjob(struct job *jp, int mode)
3693{
3694 struct procstat *ps;
3695 int i;
3696 int status;
3697 pid_t pgid;
3698
3699 INT_OFF;
3700 if (jp->state == JOBDONE)
3701 goto out;
3702 jp->state = JOBRUNNING;
Denys Vlasenko285ad152009-12-04 23:02:27 +01003703 pgid = jp->ps[0].ps_pid;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003704 if (mode == FORK_FG)
3705 xtcsetpgrp(ttyfd, pgid);
3706 killpg(pgid, SIGCONT);
3707 ps = jp->ps;
3708 i = jp->nprocs;
3709 do {
Denys Vlasenko285ad152009-12-04 23:02:27 +01003710 if (WIFSTOPPED(ps->ps_status)) {
3711 ps->ps_status = -1;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003712 }
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003713 ps++;
3714 } while (--i);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003715 out:
3716 status = (mode == FORK_FG) ? waitforjob(jp) : 0;
3717 INT_ON;
3718 return status;
3719}
3720
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02003721static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00003722fg_bgcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003723{
3724 struct job *jp;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003725 int mode;
3726 int retval;
3727
3728 mode = (**argv == 'f') ? FORK_FG : FORK_BG;
3729 nextopt(nullstr);
3730 argv = argptr;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003731 do {
3732 jp = getjob(*argv, 1);
3733 if (mode == FORK_BG) {
3734 set_curjob(jp, CUR_RUNNING);
Denys Vlasenko285ad152009-12-04 23:02:27 +01003735 printf("[%d] ", jobno(jp));
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003736 }
Denys Vlasenko285ad152009-12-04 23:02:27 +01003737 out1str(jp->ps[0].ps_cmd);
3738 showpipe(jp /*, stdout*/);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003739 retval = restartjob(jp, mode);
3740 } while (*argv && *++argv);
3741 return retval;
3742}
3743#endif
3744
3745static int
3746sprint_status(char *s, int status, int sigonly)
3747{
3748 int col;
3749 int st;
3750
3751 col = 0;
3752 if (!WIFEXITED(status)) {
3753#if JOBS
3754 if (WIFSTOPPED(status))
3755 st = WSTOPSIG(status);
3756 else
3757#endif
3758 st = WTERMSIG(status);
3759 if (sigonly) {
3760 if (st == SIGINT || st == SIGPIPE)
3761 goto out;
3762#if JOBS
3763 if (WIFSTOPPED(status))
3764 goto out;
3765#endif
3766 }
3767 st &= 0x7f;
3768 col = fmtstr(s, 32, strsignal(st));
3769 if (WCOREDUMP(status)) {
3770 col += fmtstr(s + col, 16, " (core dumped)");
3771 }
3772 } else if (!sigonly) {
3773 st = WEXITSTATUS(status);
3774 if (st)
3775 col = fmtstr(s, 16, "Done(%d)", st);
3776 else
3777 col = fmtstr(s, 16, "Done");
3778 }
3779 out:
3780 return col;
3781}
3782
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003783static int
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00003784dowait(int wait_flags, struct job *job)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003785{
3786 int pid;
3787 int status;
3788 struct job *jp;
3789 struct job *thisjob;
3790 int state;
3791
Denis Vlasenkobe54d6b2008-10-27 14:25:52 +00003792 TRACE(("dowait(0x%x) called\n", wait_flags));
3793
3794 /* Do a wait system call. If job control is compiled in, we accept
3795 * stopped processes. wait_flags may have WNOHANG, preventing blocking.
3796 * NB: _not_ safe_waitpid, we need to detect EINTR */
Denys Vlasenko285ad152009-12-04 23:02:27 +01003797 if (doing_jobctl)
3798 wait_flags |= WUNTRACED;
3799 pid = waitpid(-1, &status, wait_flags);
Denis Vlasenkob21f3792009-03-19 23:09:58 +00003800 TRACE(("wait returns pid=%d, status=0x%x, errno=%d(%s)\n",
3801 pid, status, errno, strerror(errno)));
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003802 if (pid <= 0)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003803 return pid;
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003804
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003805 INT_OFF;
3806 thisjob = NULL;
3807 for (jp = curjob; jp; jp = jp->prev_job) {
Denys Vlasenko285ad152009-12-04 23:02:27 +01003808 struct procstat *ps;
3809 struct procstat *psend;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003810 if (jp->state == JOBDONE)
3811 continue;
3812 state = JOBDONE;
Denys Vlasenko285ad152009-12-04 23:02:27 +01003813 ps = jp->ps;
3814 psend = ps + jp->nprocs;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003815 do {
Denys Vlasenko285ad152009-12-04 23:02:27 +01003816 if (ps->ps_pid == pid) {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003817 TRACE(("Job %d: changing status of proc %d "
3818 "from 0x%x to 0x%x\n",
Denys Vlasenko285ad152009-12-04 23:02:27 +01003819 jobno(jp), pid, ps->ps_status, status));
3820 ps->ps_status = status;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003821 thisjob = jp;
3822 }
Denys Vlasenko285ad152009-12-04 23:02:27 +01003823 if (ps->ps_status == -1)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003824 state = JOBRUNNING;
3825#if JOBS
3826 if (state == JOBRUNNING)
3827 continue;
Denys Vlasenko285ad152009-12-04 23:02:27 +01003828 if (WIFSTOPPED(ps->ps_status)) {
3829 jp->stopstatus = ps->ps_status;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003830 state = JOBSTOPPED;
3831 }
3832#endif
Denys Vlasenko285ad152009-12-04 23:02:27 +01003833 } while (++ps < psend);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003834 if (thisjob)
3835 goto gotjob;
3836 }
3837#if JOBS
3838 if (!WIFSTOPPED(status))
3839#endif
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003840 jobless--;
3841 goto out;
3842
3843 gotjob:
3844 if (state != JOBRUNNING) {
3845 thisjob->changed = 1;
3846
3847 if (thisjob->state != state) {
3848 TRACE(("Job %d: changing state from %d to %d\n",
3849 jobno(thisjob), thisjob->state, state));
3850 thisjob->state = state;
3851#if JOBS
3852 if (state == JOBSTOPPED) {
3853 set_curjob(thisjob, CUR_STOPPED);
3854 }
3855#endif
3856 }
3857 }
3858
3859 out:
3860 INT_ON;
3861
3862 if (thisjob && thisjob == job) {
3863 char s[48 + 1];
3864 int len;
3865
3866 len = sprint_status(s, status, 1);
3867 if (len) {
3868 s[len] = '\n';
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00003869 s[len + 1] = '\0';
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003870 out2str(s);
3871 }
3872 }
3873 return pid;
3874}
3875
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003876static int
Denys Vlasenko7c1ed9f2010-05-17 04:42:40 +02003877blocking_wait_with_raise_on_sig(void)
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003878{
Denys Vlasenko7c1ed9f2010-05-17 04:42:40 +02003879 pid_t pid = dowait(DOWAIT_BLOCK, NULL);
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02003880 if (pid <= 0 && pending_sig)
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003881 raise_exception(EXSIG);
3882 return pid;
3883}
3884
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003885#if JOBS
3886static void
3887showjob(FILE *out, struct job *jp, int mode)
3888{
3889 struct procstat *ps;
3890 struct procstat *psend;
3891 int col;
Denis Vlasenko40ba9982007-07-14 00:48:29 +00003892 int indent_col;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003893 char s[80];
3894
3895 ps = jp->ps;
3896
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003897 if (mode & SHOW_ONLY_PGID) { /* jobs -p */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003898 /* just output process (group) id of pipeline */
Denys Vlasenko285ad152009-12-04 23:02:27 +01003899 fprintf(out, "%d\n", ps->ps_pid);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003900 return;
3901 }
3902
3903 col = fmtstr(s, 16, "[%d] ", jobno(jp));
Denis Vlasenko40ba9982007-07-14 00:48:29 +00003904 indent_col = col;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003905
3906 if (jp == curjob)
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003907 s[col - 3] = '+';
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003908 else if (curjob && jp == curjob->prev_job)
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003909 s[col - 3] = '-';
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003910
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003911 if (mode & SHOW_PIDS)
Denys Vlasenko285ad152009-12-04 23:02:27 +01003912 col += fmtstr(s + col, 16, "%d ", ps->ps_pid);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003913
3914 psend = ps + jp->nprocs;
3915
3916 if (jp->state == JOBRUNNING) {
3917 strcpy(s + col, "Running");
3918 col += sizeof("Running") - 1;
3919 } else {
Denys Vlasenko285ad152009-12-04 23:02:27 +01003920 int status = psend[-1].ps_status;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003921 if (jp->state == JOBSTOPPED)
3922 status = jp->stopstatus;
3923 col += sprint_status(s + col, status, 0);
3924 }
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003925 /* By now, "[JOBID]* [maybe PID] STATUS" is printed */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003926
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003927 /* This loop either prints "<cmd1> | <cmd2> | <cmd3>" line
3928 * or prints several "PID | <cmdN>" lines,
3929 * depending on SHOW_PIDS bit.
3930 * We do not print status of individual processes
3931 * between PID and <cmdN>. bash does it, but not very well:
3932 * first line shows overall job status, not process status,
3933 * making it impossible to know 1st process status.
3934 */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003935 goto start;
Denys Vlasenko285ad152009-12-04 23:02:27 +01003936 do {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003937 /* for each process */
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003938 s[0] = '\0';
3939 col = 33;
3940 if (mode & SHOW_PIDS)
Denys Vlasenko285ad152009-12-04 23:02:27 +01003941 col = fmtstr(s, 48, "\n%*c%d ", indent_col, ' ', ps->ps_pid) - 1;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003942 start:
Denys Vlasenko285ad152009-12-04 23:02:27 +01003943 fprintf(out, "%s%*c%s%s",
3944 s,
3945 33 - col >= 0 ? 33 - col : 0, ' ',
3946 ps == jp->ps ? "" : "| ",
3947 ps->ps_cmd
3948 );
3949 } while (++ps != psend);
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003950 outcslow('\n', out);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003951
3952 jp->changed = 0;
3953
3954 if (jp->state == JOBDONE) {
3955 TRACE(("showjob: freeing job %d\n", jobno(jp)));
3956 freejob(jp);
3957 }
3958}
3959
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003960/*
3961 * Print a list of jobs. If "change" is nonzero, only print jobs whose
3962 * statuses have changed since the last call to showjobs.
3963 */
3964static void
3965showjobs(FILE *out, int mode)
3966{
3967 struct job *jp;
3968
Denys Vlasenko883cea42009-07-11 15:31:59 +02003969 TRACE(("showjobs(0x%x) called\n", mode));
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003970
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003971 /* Handle all finished jobs */
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00003972 while (dowait(DOWAIT_NONBLOCK, NULL) > 0)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003973 continue;
3974
3975 for (jp = curjob; jp; jp = jp->prev_job) {
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003976 if (!(mode & SHOW_CHANGED) || jp->changed) {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003977 showjob(out, jp, mode);
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003978 }
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003979 }
3980}
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003981
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02003982static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00003983jobscmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003984{
3985 int mode, m;
3986
3987 mode = 0;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02003988 while ((m = nextopt("lp")) != '\0') {
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003989 if (m == 'l')
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003990 mode |= SHOW_PIDS;
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003991 else
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003992 mode |= SHOW_ONLY_PGID;
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003993 }
3994
3995 argv = argptr;
3996 if (*argv) {
3997 do
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003998 showjob(stdout, getjob(*argv, 0), mode);
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003999 while (*++argv);
Denys Vlasenko285ad152009-12-04 23:02:27 +01004000 } else {
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00004001 showjobs(stdout, mode);
Denys Vlasenko285ad152009-12-04 23:02:27 +01004002 }
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00004003
4004 return 0;
4005}
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004006#endif /* JOBS */
4007
Michael Abbott359da5e2009-12-04 23:03:29 +01004008/* Called only on finished or stopped jobs (no members are running) */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004009static int
4010getstatus(struct job *job)
4011{
4012 int status;
4013 int retval;
Michael Abbott359da5e2009-12-04 23:03:29 +01004014 struct procstat *ps;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004015
Michael Abbott359da5e2009-12-04 23:03:29 +01004016 /* Fetch last member's status */
4017 ps = job->ps + job->nprocs - 1;
4018 status = ps->ps_status;
4019 if (pipefail) {
4020 /* "set -o pipefail" mode: use last _nonzero_ status */
4021 while (status == 0 && --ps >= job->ps)
4022 status = ps->ps_status;
4023 }
4024
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004025 retval = WEXITSTATUS(status);
4026 if (!WIFEXITED(status)) {
4027#if JOBS
4028 retval = WSTOPSIG(status);
4029 if (!WIFSTOPPED(status))
4030#endif
4031 {
4032 /* XXX: limits number of signals */
4033 retval = WTERMSIG(status);
4034#if JOBS
4035 if (retval == SIGINT)
4036 job->sigint = 1;
4037#endif
4038 }
4039 retval += 128;
4040 }
Denys Vlasenko883cea42009-07-11 15:31:59 +02004041 TRACE(("getstatus: job %d, nproc %d, status 0x%x, retval 0x%x\n",
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004042 jobno(job), job->nprocs, status, retval));
4043 return retval;
4044}
4045
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02004046static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00004047waitcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004048{
4049 struct job *job;
4050 int retval;
4051 struct job *jp;
4052
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02004053 if (pending_sig)
Denis Vlasenko991a1da2008-02-10 19:02:53 +00004054 raise_exception(EXSIG);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004055
4056 nextopt(nullstr);
4057 retval = 0;
4058
4059 argv = argptr;
4060 if (!*argv) {
4061 /* wait for all jobs */
4062 for (;;) {
4063 jp = curjob;
4064 while (1) {
Denis Vlasenko991a1da2008-02-10 19:02:53 +00004065 if (!jp) /* no running procs */
4066 goto ret;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004067 if (jp->state == JOBRUNNING)
4068 break;
4069 jp->waited = 1;
4070 jp = jp->prev_job;
4071 }
Denys Vlasenko7c1ed9f2010-05-17 04:42:40 +02004072 blocking_wait_with_raise_on_sig();
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004073 /* man bash:
4074 * "When bash is waiting for an asynchronous command via
4075 * the wait builtin, the reception of a signal for which a trap
4076 * has been set will cause the wait builtin to return immediately
4077 * with an exit status greater than 128, immediately after which
4078 * the trap is executed."
Denys Vlasenko7c1ed9f2010-05-17 04:42:40 +02004079 *
4080 * blocking_wait_with_raise_on_sig raises signal handlers
4081 * if it gets no pid (pid < 0). However,
4082 * if child sends us a signal *and immediately exits*,
4083 * blocking_wait_with_raise_on_sig gets pid > 0
4084 * and does not handle pending_sig. Check this case: */
4085 if (pending_sig)
4086 raise_exception(EXSIG);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004087 }
4088 }
4089
4090 retval = 127;
4091 do {
4092 if (**argv != '%') {
4093 pid_t pid = number(*argv);
4094 job = curjob;
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00004095 while (1) {
4096 if (!job)
4097 goto repeat;
Denys Vlasenko285ad152009-12-04 23:02:27 +01004098 if (job->ps[job->nprocs - 1].ps_pid == pid)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004099 break;
4100 job = job->prev_job;
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00004101 }
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004102 } else
4103 job = getjob(*argv, 0);
4104 /* loop until process terminated or stopped */
4105 while (job->state == JOBRUNNING)
Denys Vlasenko7c1ed9f2010-05-17 04:42:40 +02004106 blocking_wait_with_raise_on_sig();
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004107 job->waited = 1;
4108 retval = getstatus(job);
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004109 repeat: ;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004110 } while (*++argv);
4111
Denis Vlasenko991a1da2008-02-10 19:02:53 +00004112 ret:
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004113 return retval;
4114}
4115
4116static struct job *
4117growjobtab(void)
4118{
4119 size_t len;
4120 ptrdiff_t offset;
4121 struct job *jp, *jq;
4122
4123 len = njobs * sizeof(*jp);
4124 jq = jobtab;
4125 jp = ckrealloc(jq, len + 4 * sizeof(*jp));
4126
4127 offset = (char *)jp - (char *)jq;
4128 if (offset) {
4129 /* Relocate pointers */
4130 size_t l = len;
4131
4132 jq = (struct job *)((char *)jq + l);
4133 while (l) {
4134 l -= sizeof(*jp);
4135 jq--;
4136#define joff(p) ((struct job *)((char *)(p) + l))
4137#define jmove(p) (p) = (void *)((char *)(p) + offset)
4138 if (joff(jp)->ps == &jq->ps0)
4139 jmove(joff(jp)->ps);
4140 if (joff(jp)->prev_job)
4141 jmove(joff(jp)->prev_job);
4142 }
4143 if (curjob)
4144 jmove(curjob);
4145#undef joff
4146#undef jmove
4147 }
4148
4149 njobs += 4;
4150 jobtab = jp;
4151 jp = (struct job *)((char *)jp + len);
4152 jq = jp + 3;
4153 do {
4154 jq->used = 0;
4155 } while (--jq >= jp);
4156 return jp;
4157}
4158
4159/*
4160 * Return a new job structure.
4161 * Called with interrupts off.
4162 */
4163static struct job *
Denis Vlasenko68404f12008-03-17 09:00:54 +00004164makejob(/*union node *node,*/ int nprocs)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004165{
4166 int i;
4167 struct job *jp;
4168
4169 for (i = njobs, jp = jobtab; ; jp++) {
4170 if (--i < 0) {
4171 jp = growjobtab();
4172 break;
4173 }
4174 if (jp->used == 0)
4175 break;
4176 if (jp->state != JOBDONE || !jp->waited)
4177 continue;
4178#if JOBS
Denis Vlasenkob07a4962008-06-22 13:16:23 +00004179 if (doing_jobctl)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004180 continue;
4181#endif
4182 freejob(jp);
4183 break;
4184 }
4185 memset(jp, 0, sizeof(*jp));
4186#if JOBS
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00004187 /* jp->jobctl is a bitfield.
4188 * "jp->jobctl |= jobctl" likely to give awful code */
Denis Vlasenkob07a4962008-06-22 13:16:23 +00004189 if (doing_jobctl)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004190 jp->jobctl = 1;
4191#endif
4192 jp->prev_job = curjob;
4193 curjob = jp;
4194 jp->used = 1;
4195 jp->ps = &jp->ps0;
4196 if (nprocs > 1) {
4197 jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
4198 }
Denis Vlasenko68404f12008-03-17 09:00:54 +00004199 TRACE(("makejob(%d) returns %%%d\n", nprocs,
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004200 jobno(jp)));
4201 return jp;
4202}
4203
4204#if JOBS
4205/*
4206 * Return a string identifying a command (to be printed by the
4207 * jobs command).
4208 */
4209static char *cmdnextc;
4210
4211static void
4212cmdputs(const char *s)
4213{
Denis Vlasenko92e13c22008-03-25 01:17:40 +00004214 static const char vstype[VSTYPE + 1][3] = {
4215 "", "}", "-", "+", "?", "=",
4216 "%", "%%", "#", "##"
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00004217 IF_ASH_BASH_COMPAT(, ":", "/", "//")
Denis Vlasenko92e13c22008-03-25 01:17:40 +00004218 };
4219
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004220 const char *p, *str;
Denys Vlasenko46a14772009-12-10 21:27:13 +01004221 char cc[2];
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004222 char *nextc;
Denys Vlasenkocd716832009-11-28 22:14:02 +01004223 unsigned char c;
4224 unsigned char subtype = 0;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004225 int quoted = 0;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004226
Denys Vlasenko46a14772009-12-10 21:27:13 +01004227 cc[1] = '\0';
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004228 nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
4229 p = s;
Denys Vlasenko46a14772009-12-10 21:27:13 +01004230 while ((c = *p++) != '\0') {
Denis Vlasenkoef527f52008-06-23 01:52:30 +00004231 str = NULL;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004232 switch (c) {
4233 case CTLESC:
4234 c = *p++;
4235 break;
4236 case CTLVAR:
4237 subtype = *p++;
4238 if ((subtype & VSTYPE) == VSLENGTH)
4239 str = "${#";
4240 else
4241 str = "${";
4242 if (!(subtype & VSQUOTE) == !(quoted & 1))
4243 goto dostr;
4244 quoted ^= 1;
4245 c = '"';
4246 break;
4247 case CTLENDVAR:
4248 str = "\"}" + !(quoted & 1);
4249 quoted >>= 1;
4250 subtype = 0;
4251 goto dostr;
4252 case CTLBACKQ:
4253 str = "$(...)";
4254 goto dostr;
4255 case CTLBACKQ+CTLQUOTE:
4256 str = "\"$(...)\"";
4257 goto dostr;
Mike Frysinger98c52642009-04-02 10:02:37 +00004258#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004259 case CTLARI:
4260 str = "$((";
4261 goto dostr;
4262 case CTLENDARI:
4263 str = "))";
4264 goto dostr;
4265#endif
4266 case CTLQUOTEMARK:
4267 quoted ^= 1;
4268 c = '"';
4269 break;
4270 case '=':
4271 if (subtype == 0)
4272 break;
4273 if ((subtype & VSTYPE) != VSNORMAL)
4274 quoted <<= 1;
4275 str = vstype[subtype & VSTYPE];
4276 if (subtype & VSNUL)
4277 c = ':';
4278 else
4279 goto checkstr;
4280 break;
4281 case '\'':
4282 case '\\':
4283 case '"':
4284 case '$':
4285 /* These can only happen inside quotes */
4286 cc[0] = c;
4287 str = cc;
4288 c = '\\';
4289 break;
4290 default:
4291 break;
4292 }
4293 USTPUTC(c, nextc);
4294 checkstr:
4295 if (!str)
4296 continue;
4297 dostr:
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02004298 while ((c = *str++) != '\0') {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004299 USTPUTC(c, nextc);
4300 }
Denys Vlasenko46a14772009-12-10 21:27:13 +01004301 } /* while *p++ not NUL */
4302
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004303 if (quoted & 1) {
4304 USTPUTC('"', nextc);
4305 }
4306 *nextc = 0;
4307 cmdnextc = nextc;
4308}
4309
4310/* cmdtxt() and cmdlist() call each other */
4311static void cmdtxt(union node *n);
4312
4313static void
4314cmdlist(union node *np, int sep)
4315{
4316 for (; np; np = np->narg.next) {
4317 if (!sep)
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00004318 cmdputs(" ");
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004319 cmdtxt(np);
4320 if (sep && np->narg.next)
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00004321 cmdputs(" ");
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004322 }
4323}
4324
4325static void
4326cmdtxt(union node *n)
4327{
4328 union node *np;
4329 struct nodelist *lp;
4330 const char *p;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004331
4332 if (!n)
4333 return;
4334 switch (n->type) {
4335 default:
4336#if DEBUG
4337 abort();
4338#endif
4339 case NPIPE:
4340 lp = n->npipe.cmdlist;
4341 for (;;) {
4342 cmdtxt(lp->n);
4343 lp = lp->next;
4344 if (!lp)
4345 break;
4346 cmdputs(" | ");
4347 }
4348 break;
4349 case NSEMI:
4350 p = "; ";
4351 goto binop;
4352 case NAND:
4353 p = " && ";
4354 goto binop;
4355 case NOR:
4356 p = " || ";
4357 binop:
4358 cmdtxt(n->nbinary.ch1);
4359 cmdputs(p);
4360 n = n->nbinary.ch2;
4361 goto donode;
4362 case NREDIR:
4363 case NBACKGND:
4364 n = n->nredir.n;
4365 goto donode;
4366 case NNOT:
4367 cmdputs("!");
4368 n = n->nnot.com;
4369 donode:
4370 cmdtxt(n);
4371 break;
4372 case NIF:
4373 cmdputs("if ");
4374 cmdtxt(n->nif.test);
4375 cmdputs("; then ");
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004376 if (n->nif.elsepart) {
Denys Vlasenko7cee00e2009-07-24 01:08:03 +02004377 cmdtxt(n->nif.ifpart);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004378 cmdputs("; else ");
4379 n = n->nif.elsepart;
Denys Vlasenko7cee00e2009-07-24 01:08:03 +02004380 } else {
4381 n = n->nif.ifpart;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004382 }
4383 p = "; fi";
4384 goto dotail;
4385 case NSUBSHELL:
4386 cmdputs("(");
4387 n = n->nredir.n;
4388 p = ")";
4389 goto dotail;
4390 case NWHILE:
4391 p = "while ";
4392 goto until;
4393 case NUNTIL:
4394 p = "until ";
4395 until:
4396 cmdputs(p);
4397 cmdtxt(n->nbinary.ch1);
4398 n = n->nbinary.ch2;
4399 p = "; done";
4400 dodo:
4401 cmdputs("; do ");
4402 dotail:
4403 cmdtxt(n);
4404 goto dotail2;
4405 case NFOR:
4406 cmdputs("for ");
4407 cmdputs(n->nfor.var);
4408 cmdputs(" in ");
4409 cmdlist(n->nfor.args, 1);
4410 n = n->nfor.body;
4411 p = "; done";
4412 goto dodo;
4413 case NDEFUN:
4414 cmdputs(n->narg.text);
4415 p = "() { ... }";
4416 goto dotail2;
4417 case NCMD:
4418 cmdlist(n->ncmd.args, 1);
4419 cmdlist(n->ncmd.redirect, 0);
4420 break;
4421 case NARG:
4422 p = n->narg.text;
4423 dotail2:
4424 cmdputs(p);
4425 break;
4426 case NHERE:
4427 case NXHERE:
4428 p = "<<...";
4429 goto dotail2;
4430 case NCASE:
4431 cmdputs("case ");
4432 cmdputs(n->ncase.expr->narg.text);
4433 cmdputs(" in ");
4434 for (np = n->ncase.cases; np; np = np->nclist.next) {
4435 cmdtxt(np->nclist.pattern);
4436 cmdputs(") ");
4437 cmdtxt(np->nclist.body);
4438 cmdputs(";; ");
4439 }
4440 p = "esac";
4441 goto dotail2;
4442 case NTO:
4443 p = ">";
4444 goto redir;
4445 case NCLOBBER:
4446 p = ">|";
4447 goto redir;
4448 case NAPPEND:
4449 p = ">>";
4450 goto redir;
Denis Vlasenko559691a2008-10-05 18:39:31 +00004451#if ENABLE_ASH_BASH_COMPAT
4452 case NTO2:
4453#endif
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004454 case NTOFD:
4455 p = ">&";
4456 goto redir;
4457 case NFROM:
4458 p = "<";
4459 goto redir;
4460 case NFROMFD:
4461 p = "<&";
4462 goto redir;
4463 case NFROMTO:
4464 p = "<>";
4465 redir:
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00004466 cmdputs(utoa(n->nfile.fd));
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004467 cmdputs(p);
4468 if (n->type == NTOFD || n->type == NFROMFD) {
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00004469 cmdputs(utoa(n->ndup.dupfd));
4470 break;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004471 }
4472 n = n->nfile.fname;
4473 goto donode;
4474 }
4475}
4476
4477static char *
4478commandtext(union node *n)
4479{
4480 char *name;
4481
4482 STARTSTACKSTR(cmdnextc);
4483 cmdtxt(n);
4484 name = stackblock();
4485 TRACE(("commandtext: name %p, end %p\n\t\"%s\"\n",
4486 name, cmdnextc, cmdnextc));
4487 return ckstrdup(name);
4488}
4489#endif /* JOBS */
4490
4491/*
4492 * Fork off a subshell. If we are doing job control, give the subshell its
4493 * own process group. Jp is a job structure that the job is to be added to.
4494 * N is the command that will be evaluated by the child. Both jp and n may
4495 * be NULL. The mode parameter can be one of the following:
4496 * FORK_FG - Fork off a foreground process.
4497 * FORK_BG - Fork off a background process.
4498 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
4499 * process group even if job control is on.
4500 *
4501 * When job control is turned off, background processes have their standard
4502 * input redirected to /dev/null (except for the second and later processes
4503 * in a pipeline).
4504 *
4505 * Called with interrupts off.
4506 */
4507/*
4508 * Clear traps on a fork.
4509 */
4510static void
4511clear_traps(void)
4512{
4513 char **tp;
4514
4515 for (tp = trap; tp < &trap[NSIG]; tp++) {
Denis Vlasenko991a1da2008-02-10 19:02:53 +00004516 if (*tp && **tp) { /* trap not NULL or "" (SIG_IGN) */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004517 INT_OFF;
Denys Vlasenkoe305c282009-09-25 02:12:27 +02004518 if (trap_ptr == trap)
4519 free(*tp);
4520 /* else: it "belongs" to trap_ptr vector, don't free */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004521 *tp = NULL;
Denys Vlasenko0800e3a2009-09-24 03:09:26 +02004522 if ((tp - trap) != 0)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004523 setsignal(tp - trap);
4524 INT_ON;
4525 }
4526 }
4527}
Denis Vlasenkobdc406d2007-07-15 01:13:25 +00004528
4529/* Lives far away from here, needed for forkchild */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004530static void closescript(void);
Denis Vlasenko41770222007-10-07 18:02:52 +00004531
Denis Vlasenkobdc406d2007-07-15 01:13:25 +00004532/* Called after fork(), in child */
Denys Vlasenko21d87d42009-09-25 00:06:51 +02004533static NOINLINE void
Denys Vlasenkoe56f22a2009-07-24 00:16:59 +02004534forkchild(struct job *jp, union node *n, int mode)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004535{
4536 int oldlvl;
4537
4538 TRACE(("Child shell %d\n", getpid()));
4539 oldlvl = shlvl;
4540 shlvl++;
4541
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004542 /* man bash: "Non-builtin commands run by bash have signal handlers
4543 * set to the values inherited by the shell from its parent".
4544 * Do we do it correctly? */
4545
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004546 closescript();
Denys Vlasenko844f9902009-09-23 03:25:52 +02004547
4548 if (mode == FORK_NOJOB /* is it `xxx` ? */
4549 && n && n->type == NCMD /* is it single cmd? */
4550 /* && n->ncmd.args->type == NARG - always true? */
Denys Vlasenko74269202010-02-21 01:26:42 +01004551 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "trap") == 0
Denys Vlasenko844f9902009-09-23 03:25:52 +02004552 && n->ncmd.args->narg.next == NULL /* "trap" with no arguments */
4553 /* && n->ncmd.args->narg.backquote == NULL - do we need to check this? */
4554 ) {
4555 TRACE(("Trap hack\n"));
4556 /* Awful hack for `trap` or $(trap).
4557 *
4558 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
4559 * contains an example where "trap" is executed in a subshell:
4560 *
4561 * save_traps=$(trap)
4562 * ...
4563 * eval "$save_traps"
4564 *
4565 * Standard does not say that "trap" in subshell shall print
4566 * parent shell's traps. It only says that its output
4567 * must have suitable form, but then, in the above example
4568 * (which is not supposed to be normative), it implies that.
4569 *
4570 * bash (and probably other shell) does implement it
4571 * (traps are reset to defaults, but "trap" still shows them),
4572 * but as a result, "trap" logic is hopelessly messed up:
4573 *
4574 * # trap
4575 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
4576 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
4577 * # true | trap <--- trap is in subshell - no output (ditto)
4578 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
4579 * trap -- 'echo Ho' SIGWINCH
4580 * # echo `(trap)` <--- in subshell in subshell - output
4581 * trap -- 'echo Ho' SIGWINCH
4582 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
4583 * trap -- 'echo Ho' SIGWINCH
4584 *
4585 * The rules when to forget and when to not forget traps
4586 * get really complex and nonsensical.
4587 *
4588 * Our solution: ONLY bare $(trap) or `trap` is special.
4589 */
Denys Vlasenko8f88d852009-09-25 12:12:53 +02004590 /* Save trap handler strings for trap builtin to print */
Denys Vlasenko21d87d42009-09-25 00:06:51 +02004591 trap_ptr = memcpy(xmalloc(sizeof(trap)), trap, sizeof(trap));
Denys Vlasenko8f88d852009-09-25 12:12:53 +02004592 /* Fall through into clearing traps */
Denys Vlasenko844f9902009-09-23 03:25:52 +02004593 }
Denys Vlasenkoe305c282009-09-25 02:12:27 +02004594 clear_traps();
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004595#if JOBS
4596 /* do job control only in root shell */
Denis Vlasenkob07a4962008-06-22 13:16:23 +00004597 doing_jobctl = 0;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004598 if (mode != FORK_NOJOB && jp->jobctl && !oldlvl) {
4599 pid_t pgrp;
4600
4601 if (jp->nprocs == 0)
4602 pgrp = getpid();
4603 else
Denys Vlasenko285ad152009-12-04 23:02:27 +01004604 pgrp = jp->ps[0].ps_pid;
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004605 /* this can fail because we are doing it in the parent also */
4606 setpgid(0, pgrp);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004607 if (mode == FORK_FG)
4608 xtcsetpgrp(ttyfd, pgrp);
4609 setsignal(SIGTSTP);
4610 setsignal(SIGTTOU);
4611 } else
4612#endif
4613 if (mode == FORK_BG) {
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004614 /* man bash: "When job control is not in effect,
4615 * asynchronous commands ignore SIGINT and SIGQUIT" */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004616 ignoresig(SIGINT);
4617 ignoresig(SIGQUIT);
4618 if (jp->nprocs == 0) {
4619 close(0);
4620 if (open(bb_dev_null, O_RDONLY) != 0)
Denis Vlasenko9604e1b2009-03-03 18:47:56 +00004621 ash_msg_and_raise_error("can't open '%s'", bb_dev_null);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004622 }
4623 }
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004624 if (!oldlvl) {
4625 if (iflag) { /* why if iflag only? */
4626 setsignal(SIGINT);
4627 setsignal(SIGTERM);
4628 }
4629 /* man bash:
4630 * "In all cases, bash ignores SIGQUIT. Non-builtin
4631 * commands run by bash have signal handlers
4632 * set to the values inherited by the shell
4633 * from its parent".
4634 * Take care of the second rule: */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004635 setsignal(SIGQUIT);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004636 }
Denys Vlasenkoe56f22a2009-07-24 00:16:59 +02004637#if JOBS
Denys Vlasenko844f9902009-09-23 03:25:52 +02004638 if (n && n->type == NCMD
Denys Vlasenko74269202010-02-21 01:26:42 +01004639 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "jobs") == 0
Denys Vlasenko844f9902009-09-23 03:25:52 +02004640 ) {
Denys Vlasenkoe56f22a2009-07-24 00:16:59 +02004641 TRACE(("Job hack\n"));
Denys Vlasenko844f9902009-09-23 03:25:52 +02004642 /* "jobs": we do not want to clear job list for it,
4643 * instead we remove only _its_ own_ job from job list.
4644 * This makes "jobs .... | cat" more useful.
4645 */
Denys Vlasenkoe56f22a2009-07-24 00:16:59 +02004646 freejob(curjob);
4647 return;
4648 }
4649#endif
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004650 for (jp = curjob; jp; jp = jp->prev_job)
4651 freejob(jp);
4652 jobless = 0;
4653}
4654
Denis Vlasenkobdc406d2007-07-15 01:13:25 +00004655/* Called after fork(), in parent */
Denis Vlasenko85c24712008-03-17 09:04:04 +00004656#if !JOBS
4657#define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
4658#endif
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004659static void
4660forkparent(struct job *jp, union node *n, int mode, pid_t pid)
4661{
4662 TRACE(("In parent shell: child = %d\n", pid));
4663 if (!jp) {
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00004664 while (jobless && dowait(DOWAIT_NONBLOCK, NULL) > 0)
4665 continue;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004666 jobless++;
4667 return;
4668 }
4669#if JOBS
4670 if (mode != FORK_NOJOB && jp->jobctl) {
4671 int pgrp;
4672
4673 if (jp->nprocs == 0)
4674 pgrp = pid;
4675 else
Denys Vlasenko285ad152009-12-04 23:02:27 +01004676 pgrp = jp->ps[0].ps_pid;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004677 /* This can fail because we are doing it in the child also */
4678 setpgid(pid, pgrp);
4679 }
4680#endif
4681 if (mode == FORK_BG) {
4682 backgndpid = pid; /* set $! */
4683 set_curjob(jp, CUR_RUNNING);
4684 }
4685 if (jp) {
4686 struct procstat *ps = &jp->ps[jp->nprocs++];
Denys Vlasenko285ad152009-12-04 23:02:27 +01004687 ps->ps_pid = pid;
4688 ps->ps_status = -1;
4689 ps->ps_cmd = nullstr;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004690#if JOBS
Denis Vlasenkob07a4962008-06-22 13:16:23 +00004691 if (doing_jobctl && n)
Denys Vlasenko285ad152009-12-04 23:02:27 +01004692 ps->ps_cmd = commandtext(n);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004693#endif
4694 }
4695}
4696
4697static int
4698forkshell(struct job *jp, union node *n, int mode)
4699{
4700 int pid;
4701
4702 TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
4703 pid = fork();
4704 if (pid < 0) {
4705 TRACE(("Fork failed, errno=%d", errno));
4706 if (jp)
4707 freejob(jp);
Denis Vlasenkofa0b56d2008-07-01 16:09:07 +00004708 ash_msg_and_raise_error("can't fork");
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004709 }
Denys Vlasenko76ace252009-10-12 15:25:01 +02004710 if (pid == 0) {
4711 CLEAR_RANDOM_T(&random_gen); /* or else $RANDOM repeats in child */
Denys Vlasenkoe56f22a2009-07-24 00:16:59 +02004712 forkchild(jp, n, mode);
Denys Vlasenko76ace252009-10-12 15:25:01 +02004713 } else {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004714 forkparent(jp, n, mode, pid);
Denys Vlasenko76ace252009-10-12 15:25:01 +02004715 }
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004716 return pid;
4717}
4718
4719/*
4720 * Wait for job to finish.
4721 *
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004722 * Under job control we have the problem that while a child process
4723 * is running interrupts generated by the user are sent to the child
4724 * but not to the shell. This means that an infinite loop started by
4725 * an interactive user may be hard to kill. With job control turned off,
4726 * an interactive user may place an interactive program inside a loop.
4727 * If the interactive program catches interrupts, the user doesn't want
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004728 * these interrupts to also abort the loop. The approach we take here
4729 * is to have the shell ignore interrupt signals while waiting for a
4730 * foreground process to terminate, and then send itself an interrupt
4731 * signal if the child process was terminated by an interrupt signal.
4732 * Unfortunately, some programs want to do a bit of cleanup and then
4733 * exit on interrupt; unless these processes terminate themselves by
4734 * sending a signal to themselves (instead of calling exit) they will
4735 * confuse this approach.
4736 *
4737 * Called with interrupts off.
4738 */
4739static int
4740waitforjob(struct job *jp)
4741{
4742 int st;
4743
4744 TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004745
4746 INT_OFF;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004747 while (jp->state == JOBRUNNING) {
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004748 /* In non-interactive shells, we _can_ get
4749 * a keyboard signal here and be EINTRed,
4750 * but we just loop back, waiting for command to complete.
4751 *
4752 * man bash:
4753 * "If bash is waiting for a command to complete and receives
4754 * a signal for which a trap has been set, the trap
4755 * will not be executed until the command completes."
4756 *
4757 * Reality is that even if trap is not set, bash
4758 * will not act on the signal until command completes.
4759 * Try this. sleep5intoff.c:
4760 * #include <signal.h>
4761 * #include <unistd.h>
4762 * int main() {
4763 * sigset_t set;
4764 * sigemptyset(&set);
4765 * sigaddset(&set, SIGINT);
4766 * sigaddset(&set, SIGQUIT);
4767 * sigprocmask(SIG_BLOCK, &set, NULL);
4768 * sleep(5);
4769 * return 0;
4770 * }
4771 * $ bash -c './sleep5intoff; echo hi'
4772 * ^C^C^C^C <--- pressing ^C once a second
4773 * $ _
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004774 * $ bash -c './sleep5intoff; echo hi'
4775 * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
4776 * $ _
4777 */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004778 dowait(DOWAIT_BLOCK, jp);
4779 }
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004780 INT_ON;
4781
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004782 st = getstatus(jp);
4783#if JOBS
4784 if (jp->jobctl) {
4785 xtcsetpgrp(ttyfd, rootpid);
4786 /*
4787 * This is truly gross.
4788 * If we're doing job control, then we did a TIOCSPGRP which
4789 * caused us (the shell) to no longer be in the controlling
4790 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
4791 * intuit from the subprocess exit status whether a SIGINT
4792 * occurred, and if so interrupt ourselves. Yuck. - mycroft
4793 */
Denis Vlasenko991a1da2008-02-10 19:02:53 +00004794 if (jp->sigint) /* TODO: do the same with all signals */
4795 raise(SIGINT); /* ... by raise(jp->sig) instead? */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004796 }
4797 if (jp->state == JOBDONE)
4798#endif
4799 freejob(jp);
4800 return st;
4801}
4802
4803/*
4804 * return 1 if there are stopped jobs, otherwise 0
4805 */
4806static int
4807stoppedjobs(void)
4808{
4809 struct job *jp;
4810 int retval;
4811
4812 retval = 0;
4813 if (job_warning)
4814 goto out;
4815 jp = curjob;
4816 if (jp && jp->state == JOBSTOPPED) {
4817 out2str("You have stopped jobs.\n");
4818 job_warning = 2;
4819 retval++;
4820 }
4821 out:
4822 return retval;
4823}
4824
4825
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004826/* ============ redir.c
4827 *
4828 * Code for dealing with input/output redirection.
4829 */
4830
4831#define EMPTY -2 /* marks an unused slot in redirtab */
Denis Vlasenko7d75a962007-11-22 08:16:57 +00004832#define CLOSED -3 /* marks a slot of previously-closed fd */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004833
4834/*
4835 * Open a file in noclobber mode.
4836 * The code was copied from bash.
4837 */
4838static int
4839noclobberopen(const char *fname)
4840{
4841 int r, fd;
4842 struct stat finfo, finfo2;
4843
4844 /*
4845 * If the file exists and is a regular file, return an error
4846 * immediately.
4847 */
4848 r = stat(fname, &finfo);
4849 if (r == 0 && S_ISREG(finfo.st_mode)) {
4850 errno = EEXIST;
4851 return -1;
4852 }
4853
4854 /*
4855 * If the file was not present (r != 0), make sure we open it
4856 * exclusively so that if it is created before we open it, our open
4857 * will fail. Make sure that we do not truncate an existing file.
4858 * Note that we don't turn on O_EXCL unless the stat failed -- if the
4859 * file was not a regular file, we leave O_EXCL off.
4860 */
4861 if (r != 0)
4862 return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
4863 fd = open(fname, O_WRONLY|O_CREAT, 0666);
4864
4865 /* If the open failed, return the file descriptor right away. */
4866 if (fd < 0)
4867 return fd;
4868
4869 /*
4870 * OK, the open succeeded, but the file may have been changed from a
4871 * non-regular file to a regular file between the stat and the open.
4872 * We are assuming that the O_EXCL open handles the case where FILENAME
4873 * did not exist and is symlinked to an existing file between the stat
4874 * and open.
4875 */
4876
4877 /*
4878 * If we can open it and fstat the file descriptor, and neither check
4879 * revealed that it was a regular file, and the file has not been
4880 * replaced, return the file descriptor.
4881 */
4882 if (fstat(fd, &finfo2) == 0 && !S_ISREG(finfo2.st_mode)
4883 && finfo.st_dev == finfo2.st_dev && finfo.st_ino == finfo2.st_ino)
4884 return fd;
4885
4886 /* The file has been replaced. badness. */
4887 close(fd);
4888 errno = EEXIST;
4889 return -1;
4890}
4891
4892/*
4893 * Handle here documents. Normally we fork off a process to write the
4894 * data to a pipe. If the document is short, we can stuff the data in
4895 * the pipe without forking.
4896 */
4897/* openhere needs this forward reference */
4898static void expandhere(union node *arg, int fd);
4899static int
4900openhere(union node *redir)
4901{
4902 int pip[2];
4903 size_t len = 0;
4904
4905 if (pipe(pip) < 0)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00004906 ash_msg_and_raise_error("pipe call failed");
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004907 if (redir->type == NHERE) {
4908 len = strlen(redir->nhere.doc->narg.text);
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00004909 if (len <= PIPE_BUF) {
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004910 full_write(pip[1], redir->nhere.doc->narg.text, len);
4911 goto out;
4912 }
4913 }
4914 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
Denis Vlasenko0b769642008-07-24 07:54:57 +00004915 /* child */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004916 close(pip[0]);
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004917 ignoresig(SIGINT); //signal(SIGINT, SIG_IGN);
4918 ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
4919 ignoresig(SIGHUP); //signal(SIGHUP, SIG_IGN);
4920 ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004921 signal(SIGPIPE, SIG_DFL);
4922 if (redir->type == NHERE)
4923 full_write(pip[1], redir->nhere.doc->narg.text, len);
Denis Vlasenko0b769642008-07-24 07:54:57 +00004924 else /* NXHERE */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004925 expandhere(redir->nhere.doc, pip[1]);
Bernhard Reutner-Fischer636a1f82008-05-19 09:29:47 +00004926 _exit(EXIT_SUCCESS);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004927 }
4928 out:
4929 close(pip[1]);
4930 return pip[0];
4931}
4932
4933static int
4934openredirect(union node *redir)
4935{
4936 char *fname;
4937 int f;
4938
4939 switch (redir->nfile.type) {
4940 case NFROM:
4941 fname = redir->nfile.expfname;
4942 f = open(fname, O_RDONLY);
4943 if (f < 0)
4944 goto eopen;
4945 break;
4946 case NFROMTO:
4947 fname = redir->nfile.expfname;
4948 f = open(fname, O_RDWR|O_CREAT|O_TRUNC, 0666);
4949 if (f < 0)
4950 goto ecreate;
4951 break;
4952 case NTO:
Denis Vlasenko559691a2008-10-05 18:39:31 +00004953#if ENABLE_ASH_BASH_COMPAT
4954 case NTO2:
4955#endif
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004956 /* Take care of noclobber mode. */
4957 if (Cflag) {
4958 fname = redir->nfile.expfname;
4959 f = noclobberopen(fname);
4960 if (f < 0)
4961 goto ecreate;
4962 break;
4963 }
4964 /* FALLTHROUGH */
4965 case NCLOBBER:
4966 fname = redir->nfile.expfname;
4967 f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
4968 if (f < 0)
4969 goto ecreate;
4970 break;
4971 case NAPPEND:
4972 fname = redir->nfile.expfname;
4973 f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
4974 if (f < 0)
4975 goto ecreate;
4976 break;
4977 default:
4978#if DEBUG
4979 abort();
4980#endif
4981 /* Fall through to eliminate warning. */
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00004982/* Our single caller does this itself */
Denis Vlasenko0b769642008-07-24 07:54:57 +00004983// case NTOFD:
4984// case NFROMFD:
4985// f = -1;
4986// break;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004987 case NHERE:
4988 case NXHERE:
4989 f = openhere(redir);
4990 break;
4991 }
4992
4993 return f;
4994 ecreate:
Bernhard Reutner-Fischera53de7f2008-07-21 13:46:54 +00004995 ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004996 eopen:
Bernhard Reutner-Fischera53de7f2008-07-21 13:46:54 +00004997 ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004998}
4999
5000/*
5001 * Copy a file descriptor to be >= to. Returns -1
5002 * if the source file descriptor is closed, EMPTY if there are no unused
5003 * file descriptors left.
5004 */
Denis Vlasenko5a867312008-07-24 19:46:38 +00005005/* 0x800..00: bit to set in "to" to request dup2 instead of fcntl(F_DUPFD).
5006 * old code was doing close(to) prior to copyfd() to achieve the same */
Denis Vlasenko22f74142008-07-24 22:34:43 +00005007enum {
5008 COPYFD_EXACT = (int)~(INT_MAX),
5009 COPYFD_RESTORE = (int)((unsigned)COPYFD_EXACT >> 1),
5010};
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005011static int
5012copyfd(int from, int to)
5013{
5014 int newfd;
5015
Denis Vlasenko5a867312008-07-24 19:46:38 +00005016 if (to & COPYFD_EXACT) {
5017 to &= ~COPYFD_EXACT;
5018 /*if (from != to)*/
5019 newfd = dup2(from, to);
5020 } else {
5021 newfd = fcntl(from, F_DUPFD, to);
5022 }
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005023 if (newfd < 0) {
5024 if (errno == EMFILE)
5025 return EMPTY;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005026 /* Happens when source fd is not open: try "echo >&99" */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005027 ash_msg_and_raise_error("%d: %m", from);
5028 }
5029 return newfd;
5030}
5031
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005032/* Struct def and variable are moved down to the first usage site */
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005033struct two_fd_t {
5034 int orig, copy;
5035};
Denis Vlasenko0b769642008-07-24 07:54:57 +00005036struct redirtab {
5037 struct redirtab *next;
Denis Vlasenko0b769642008-07-24 07:54:57 +00005038 int nullredirs;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005039 int pair_count;
Denys Vlasenko606291b2009-09-23 23:15:43 +02005040 struct two_fd_t two_fd[];
Denis Vlasenko0b769642008-07-24 07:54:57 +00005041};
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005042#define redirlist (G_var.redirlist)
Denis Vlasenko0b769642008-07-24 07:54:57 +00005043
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005044static int need_to_remember(struct redirtab *rp, int fd)
5045{
5046 int i;
5047
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005048 if (!rp) /* remembering was not requested */
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005049 return 0;
5050
5051 for (i = 0; i < rp->pair_count; i++) {
5052 if (rp->two_fd[i].orig == fd) {
5053 /* already remembered */
5054 return 0;
5055 }
5056 }
5057 return 1;
5058}
5059
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005060/* "hidden" fd is a fd used to read scripts, or a copy of such */
5061static int is_hidden_fd(struct redirtab *rp, int fd)
5062{
5063 int i;
Denis Vlasenko34c73c42008-08-16 11:48:02 +00005064 struct parsefile *pf;
5065
5066 if (fd == -1)
5067 return 0;
5068 pf = g_parsefile;
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005069 while (pf) {
5070 if (fd == pf->fd) {
5071 return 1;
5072 }
5073 pf = pf->prev;
5074 }
5075 if (!rp)
5076 return 0;
5077 fd |= COPYFD_RESTORE;
5078 for (i = 0; i < rp->pair_count; i++) {
5079 if (rp->two_fd[i].copy == fd) {
5080 return 1;
5081 }
5082 }
5083 return 0;
5084}
5085
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005086/*
5087 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
5088 * old file descriptors are stashed away so that the redirection can be
5089 * undone by calling popredir. If the REDIR_BACKQ flag is set, then the
5090 * standard output, and the standard error if it becomes a duplicate of
5091 * stdout, is saved in memory.
5092 */
5093/* flags passed to redirect */
5094#define REDIR_PUSH 01 /* save previous values of file descriptors */
5095#define REDIR_SAVEFD2 03 /* set preverrout */
5096static void
5097redirect(union node *redir, int flags)
5098{
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005099 struct redirtab *sv;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005100 int sv_pos;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005101 int i;
5102 int fd;
5103 int newfd;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005104 int copied_fd2 = -1;
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005105
Denis Vlasenko01631112007-12-16 17:20:38 +00005106 g_nullredirs++;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005107 if (!redir) {
5108 return;
5109 }
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005110
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005111 sv = NULL;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005112 sv_pos = 0;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005113 INT_OFF;
5114 if (flags & REDIR_PUSH) {
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005115 union node *tmp = redir;
5116 do {
5117 sv_pos++;
Denis Vlasenko559691a2008-10-05 18:39:31 +00005118#if ENABLE_ASH_BASH_COMPAT
Chris Metcalfc3c1fb62010-01-08 13:18:06 +01005119 if (tmp->nfile.type == NTO2)
Denis Vlasenko559691a2008-10-05 18:39:31 +00005120 sv_pos++;
5121#endif
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005122 tmp = tmp->nfile.next;
5123 } while (tmp);
5124 sv = ckmalloc(sizeof(*sv) + sv_pos * sizeof(sv->two_fd[0]));
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005125 sv->next = redirlist;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005126 sv->pair_count = sv_pos;
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005127 redirlist = sv;
Denis Vlasenko01631112007-12-16 17:20:38 +00005128 sv->nullredirs = g_nullredirs - 1;
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005129 g_nullredirs = 0;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005130 while (sv_pos > 0) {
5131 sv_pos--;
5132 sv->two_fd[sv_pos].orig = sv->two_fd[sv_pos].copy = EMPTY;
5133 }
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005134 }
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005135
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005136 do {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00005137 fd = redir->nfile.fd;
Denis Vlasenko0b769642008-07-24 07:54:57 +00005138 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005139 int right_fd = redir->ndup.dupfd;
5140 /* redirect from/to same file descriptor? */
5141 if (right_fd == fd)
5142 continue;
5143 /* echo >&10 and 10 is a fd opened to the sh script? */
5144 if (is_hidden_fd(sv, right_fd)) {
5145 errno = EBADF; /* as if it is closed */
5146 ash_msg_and_raise_error("%d: %m", right_fd);
5147 }
Denis Vlasenko0b769642008-07-24 07:54:57 +00005148 newfd = -1;
5149 } else {
5150 newfd = openredirect(redir); /* always >= 0 */
5151 if (fd == newfd) {
5152 /* Descriptor wasn't open before redirect.
5153 * Mark it for close in the future */
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005154 if (need_to_remember(sv, fd)) {
Denis Vlasenko5a867312008-07-24 19:46:38 +00005155 goto remember_to_close;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005156 }
Denis Vlasenko0b769642008-07-24 07:54:57 +00005157 continue;
5158 }
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005159 }
Denis Vlasenko559691a2008-10-05 18:39:31 +00005160#if ENABLE_ASH_BASH_COMPAT
5161 redirect_more:
5162#endif
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005163 if (need_to_remember(sv, fd)) {
Denis Vlasenko0b769642008-07-24 07:54:57 +00005164 /* Copy old descriptor */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005165 i = fcntl(fd, F_DUPFD, 10);
Denis Vlasenko5a867312008-07-24 19:46:38 +00005166/* You'd expect copy to be CLOEXECed. Currently these extra "saved" fds
5167 * are closed in popredir() in the child, preventing them from leaking
5168 * into child. (popredir() also cleans up the mess in case of failures)
5169 */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005170 if (i == -1) {
5171 i = errno;
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005172 if (i != EBADF) {
5173 /* Strange error (e.g. "too many files" EMFILE?) */
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005174 if (newfd >= 0)
5175 close(newfd);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005176 errno = i;
5177 ash_msg_and_raise_error("%d: %m", fd);
5178 /* NOTREACHED */
5179 }
Denis Vlasenko5a867312008-07-24 19:46:38 +00005180 /* EBADF: it is not open - good, remember to close it */
5181 remember_to_close:
5182 i = CLOSED;
Denis Vlasenko22f74142008-07-24 22:34:43 +00005183 } else { /* fd is open, save its copy */
5184 /* "exec fd>&-" should not close fds
5185 * which point to script file(s).
5186 * Force them to be restored afterwards */
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005187 if (is_hidden_fd(sv, fd))
5188 i |= COPYFD_RESTORE;
Denis Vlasenko22f74142008-07-24 22:34:43 +00005189 }
Denis Vlasenko5a867312008-07-24 19:46:38 +00005190 if (fd == 2)
5191 copied_fd2 = i;
5192 sv->two_fd[sv_pos].orig = fd;
5193 sv->two_fd[sv_pos].copy = i;
5194 sv_pos++;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005195 }
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005196 if (newfd < 0) {
5197 /* NTOFD/NFROMFD: copy redir->ndup.dupfd to fd */
Denis Vlasenko22f74142008-07-24 22:34:43 +00005198 if (redir->ndup.dupfd < 0) { /* "fd>&-" */
Denis Vlasenkob9e70dd2009-03-20 01:24:08 +00005199 /* Don't want to trigger debugging */
5200 if (fd != -1)
5201 close(fd);
Denis Vlasenko5a867312008-07-24 19:46:38 +00005202 } else {
5203 copyfd(redir->ndup.dupfd, fd | COPYFD_EXACT);
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005204 }
Denis Vlasenko5a867312008-07-24 19:46:38 +00005205 } else if (fd != newfd) { /* move newfd to fd */
5206 copyfd(newfd, fd | COPYFD_EXACT);
Denis Vlasenko559691a2008-10-05 18:39:31 +00005207#if ENABLE_ASH_BASH_COMPAT
5208 if (!(redir->nfile.type == NTO2 && fd == 2))
5209#endif
5210 close(newfd);
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005211 }
Denis Vlasenko559691a2008-10-05 18:39:31 +00005212#if ENABLE_ASH_BASH_COMPAT
5213 if (redir->nfile.type == NTO2 && fd == 1) {
5214 /* We already redirected it to fd 1, now copy it to 2 */
5215 newfd = 1;
5216 fd = 2;
5217 goto redirect_more;
5218 }
5219#endif
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00005220 } while ((redir = redir->nfile.next) != NULL);
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005221
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005222 INT_ON;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005223 if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
5224 preverrout_fd = copied_fd2;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005225}
5226
5227/*
5228 * Undo the effects of the last redirection.
5229 */
5230static void
Denis Vlasenko34c73c42008-08-16 11:48:02 +00005231popredir(int drop, int restore)
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005232{
5233 struct redirtab *rp;
5234 int i;
5235
Denis Vlasenko01631112007-12-16 17:20:38 +00005236 if (--g_nullredirs >= 0)
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005237 return;
5238 INT_OFF;
5239 rp = redirlist;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005240 for (i = 0; i < rp->pair_count; i++) {
5241 int fd = rp->two_fd[i].orig;
Denis Vlasenko22f74142008-07-24 22:34:43 +00005242 int copy = rp->two_fd[i].copy;
5243 if (copy == CLOSED) {
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005244 if (!drop)
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005245 close(fd);
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005246 continue;
5247 }
Denis Vlasenko22f74142008-07-24 22:34:43 +00005248 if (copy != EMPTY) {
Denis Vlasenko34c73c42008-08-16 11:48:02 +00005249 if (!drop || (restore && (copy & COPYFD_RESTORE))) {
Denis Vlasenko22f74142008-07-24 22:34:43 +00005250 copy &= ~COPYFD_RESTORE;
Denis Vlasenko5a867312008-07-24 19:46:38 +00005251 /*close(fd);*/
Denis Vlasenko22f74142008-07-24 22:34:43 +00005252 copyfd(copy, fd | COPYFD_EXACT);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005253 }
Denis Vlasenkob9e70dd2009-03-20 01:24:08 +00005254 close(copy & ~COPYFD_RESTORE);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005255 }
5256 }
5257 redirlist = rp->next;
Denis Vlasenko01631112007-12-16 17:20:38 +00005258 g_nullredirs = rp->nullredirs;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005259 free(rp);
5260 INT_ON;
5261}
5262
5263/*
5264 * Undo all redirections. Called on error or interrupt.
5265 */
5266
5267/*
5268 * Discard all saved file descriptors.
5269 */
5270static void
5271clearredir(int drop)
5272{
5273 for (;;) {
Denis Vlasenko01631112007-12-16 17:20:38 +00005274 g_nullredirs = 0;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005275 if (!redirlist)
5276 break;
Denis Vlasenko34c73c42008-08-16 11:48:02 +00005277 popredir(drop, /*restore:*/ 0);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005278 }
5279}
5280
5281static int
5282redirectsafe(union node *redir, int flags)
5283{
5284 int err;
5285 volatile int saveint;
5286 struct jmploc *volatile savehandler = exception_handler;
5287 struct jmploc jmploc;
5288
5289 SAVE_INT(saveint);
Denis Vlasenko5a867312008-07-24 19:46:38 +00005290 /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
5291 err = setjmp(jmploc.loc); // huh?? was = setjmp(jmploc.loc) * 2;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005292 if (!err) {
5293 exception_handler = &jmploc;
5294 redirect(redir, flags);
5295 }
5296 exception_handler = savehandler;
Denis Vlasenko7f88e342009-03-19 03:36:18 +00005297 if (err && exception_type != EXERROR)
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005298 longjmp(exception_handler->loc, 1);
5299 RESTORE_INT(saveint);
5300 return err;
5301}
5302
5303
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005304/* ============ Routines to expand arguments to commands
5305 *
5306 * We have to deal with backquotes, shell variables, and file metacharacters.
5307 */
5308
Mike Frysinger98c52642009-04-02 10:02:37 +00005309#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00005310static arith_t
5311ash_arith(const char *s)
5312{
5313 arith_eval_hooks_t math_hooks;
5314 arith_t result;
5315 int errcode = 0;
5316
5317 math_hooks.lookupvar = lookupvar;
Denys Vlasenko03dad222010-01-12 23:29:57 +01005318 math_hooks.setvar = setvar2;
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00005319 math_hooks.endofname = endofname;
5320
5321 INT_OFF;
5322 result = arith(s, &errcode, &math_hooks);
5323 if (errcode < 0) {
5324 if (errcode == -3)
5325 ash_msg_and_raise_error("exponent less than 0");
5326 if (errcode == -2)
5327 ash_msg_and_raise_error("divide by zero");
5328 if (errcode == -5)
5329 ash_msg_and_raise_error("expression recursion loop detected");
5330 raise_error_syntax(s);
5331 }
5332 INT_ON;
5333
5334 return result;
5335}
Denis Vlasenko448d30e2008-06-27 00:24:11 +00005336#endif
5337
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005338/*
5339 * expandarg flags
5340 */
5341#define EXP_FULL 0x1 /* perform word splitting & file globbing */
5342#define EXP_TILDE 0x2 /* do normal tilde expansion */
5343#define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
5344#define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
5345#define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
5346#define EXP_RECORD 0x20 /* need to record arguments for ifs breakup */
5347#define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
5348#define EXP_WORD 0x80 /* expand word in parameter expansion */
5349#define EXP_QWORD 0x100 /* expand word in quoted parameter expansion */
5350/*
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005351 * rmescape() flags
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005352 */
5353#define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
5354#define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
5355#define RMESCAPE_QUOTED 0x4 /* Remove CTLESC unless in quotes */
5356#define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
5357#define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
5358
5359/*
5360 * Structure specifying which parts of the string should be searched
5361 * for IFS characters.
5362 */
5363struct ifsregion {
5364 struct ifsregion *next; /* next region in list */
5365 int begoff; /* offset of start of region */
5366 int endoff; /* offset of end of region */
5367 int nulonly; /* search for nul bytes only */
5368};
5369
5370struct arglist {
5371 struct strlist *list;
5372 struct strlist **lastp;
5373};
5374
5375/* output of current string */
5376static char *expdest;
5377/* list of back quote expressions */
5378static struct nodelist *argbackq;
5379/* first struct in list of ifs regions */
5380static struct ifsregion ifsfirst;
5381/* last struct in list */
5382static struct ifsregion *ifslastp;
5383/* holds expanded arg list */
5384static struct arglist exparg;
5385
5386/*
5387 * Our own itoa().
5388 */
5389static int
5390cvtnum(arith_t num)
5391{
5392 int len;
5393
5394 expdest = makestrspace(32, expdest);
Mike Frysinger98c52642009-04-02 10:02:37 +00005395 len = fmtstr(expdest, 32, arith_t_fmt, num);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005396 STADJUST(len, expdest);
5397 return len;
5398}
5399
5400static size_t
5401esclen(const char *start, const char *p)
5402{
5403 size_t esc = 0;
5404
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005405 while (p > start && (unsigned char)*--p == CTLESC) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005406 esc++;
5407 }
5408 return esc;
5409}
5410
5411/*
5412 * Remove any CTLESC characters from a string.
5413 */
5414static char *
Denys Vlasenkob6c84342009-08-29 20:23:20 +02005415rmescapes(char *str, int flag)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005416{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00005417 static const char qchars[] ALIGN1 = { CTLESC, CTLQUOTEMARK, '\0' };
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00005418
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005419 char *p, *q, *r;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005420 unsigned inquotes;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005421 unsigned protect_against_glob;
5422 unsigned globbing;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005423
5424 p = strpbrk(str, qchars);
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005425 if (!p)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005426 return str;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005427
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005428 q = p;
5429 r = str;
5430 if (flag & RMESCAPE_ALLOC) {
5431 size_t len = p - str;
5432 size_t fulllen = len + strlen(p) + 1;
5433
5434 if (flag & RMESCAPE_GROW) {
Colin Watson3963d942010-04-26 14:21:27 +02005435 int strloc = str - (char *)stackblock();
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005436 r = makestrspace(fulllen, expdest);
Colin Watson3963d942010-04-26 14:21:27 +02005437 /* p and str may be invalidated by makestrspace */
5438 str = (char *)stackblock() + strloc;
5439 p = str + len;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005440 } else if (flag & RMESCAPE_HEAP) {
5441 r = ckmalloc(fulllen);
5442 } else {
5443 r = stalloc(fulllen);
5444 }
5445 q = r;
5446 if (len > 0) {
Denis Vlasenko29eb3592008-05-18 14:06:08 +00005447 q = (char *)memcpy(q, str, len) + len;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005448 }
5449 }
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005450
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005451 inquotes = (flag & RMESCAPE_QUOTED) ^ RMESCAPE_QUOTED;
5452 globbing = flag & RMESCAPE_GLOB;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005453 protect_against_glob = globbing;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005454 while (*p) {
Denys Vlasenkocd716832009-11-28 22:14:02 +01005455 if ((unsigned char)*p == CTLQUOTEMARK) {
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005456// TODO: if no RMESCAPE_QUOTED in flags, inquotes never becomes 0
5457// (alternates between RMESCAPE_QUOTED and ~RMESCAPE_QUOTED). Is it ok?
5458// Note: both inquotes and protect_against_glob only affect whether
5459// CTLESC,<ch> gets converted to <ch> or to \<ch>
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005460 inquotes = ~inquotes;
5461 p++;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005462 protect_against_glob = globbing;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005463 continue;
5464 }
5465 if (*p == '\\') {
5466 /* naked back slash */
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005467 protect_against_glob = 0;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005468 goto copy;
5469 }
Denys Vlasenkocd716832009-11-28 22:14:02 +01005470 if ((unsigned char)*p == CTLESC) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005471 p++;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005472 if (protect_against_glob && inquotes && *p != '/') {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005473 *q++ = '\\';
5474 }
5475 }
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005476 protect_against_glob = globbing;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005477 copy:
5478 *q++ = *p++;
5479 }
5480 *q = '\0';
5481 if (flag & RMESCAPE_GROW) {
5482 expdest = r;
5483 STADJUST(q - r + 1, expdest);
5484 }
5485 return r;
5486}
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005487#define pmatch(a, b) !fnmatch((a), (b), 0)
5488
5489/*
5490 * Prepare a pattern for a expmeta (internal glob(3)) call.
5491 *
5492 * Returns an stalloced string.
5493 */
5494static char *
5495preglob(const char *pattern, int quoted, int flag)
5496{
5497 flag |= RMESCAPE_GLOB;
5498 if (quoted) {
5499 flag |= RMESCAPE_QUOTED;
5500 }
Denys Vlasenkob6c84342009-08-29 20:23:20 +02005501 return rmescapes((char *)pattern, flag);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005502}
5503
5504/*
5505 * Put a string on the stack.
5506 */
5507static void
5508memtodest(const char *p, size_t len, int syntax, int quotes)
5509{
5510 char *q = expdest;
5511
Denys Vlasenkob6c84342009-08-29 20:23:20 +02005512 q = makestrspace(quotes ? len * 2 : len, q);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005513
5514 while (len--) {
Denys Vlasenkocd716832009-11-28 22:14:02 +01005515 unsigned char c = *p++;
5516 if (c == '\0')
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005517 continue;
Denys Vlasenkob6c84342009-08-29 20:23:20 +02005518 if (quotes) {
5519 int n = SIT(c, syntax);
5520 if (n == CCTL || n == CBACK)
5521 USTPUTC(CTLESC, q);
5522 }
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005523 USTPUTC(c, q);
5524 }
5525
5526 expdest = q;
5527}
5528
5529static void
5530strtodest(const char *p, int syntax, int quotes)
5531{
5532 memtodest(p, strlen(p), syntax, quotes);
5533}
5534
5535/*
5536 * Record the fact that we have to scan this region of the
5537 * string for IFS characters.
5538 */
5539static void
5540recordregion(int start, int end, int nulonly)
5541{
5542 struct ifsregion *ifsp;
5543
5544 if (ifslastp == NULL) {
5545 ifsp = &ifsfirst;
5546 } else {
5547 INT_OFF;
Denis Vlasenko597906c2008-02-20 16:38:54 +00005548 ifsp = ckzalloc(sizeof(*ifsp));
5549 /*ifsp->next = NULL; - ckzalloc did it */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005550 ifslastp->next = ifsp;
5551 INT_ON;
5552 }
5553 ifslastp = ifsp;
5554 ifslastp->begoff = start;
5555 ifslastp->endoff = end;
5556 ifslastp->nulonly = nulonly;
5557}
5558
5559static void
5560removerecordregions(int endoff)
5561{
5562 if (ifslastp == NULL)
5563 return;
5564
5565 if (ifsfirst.endoff > endoff) {
5566 while (ifsfirst.next != NULL) {
5567 struct ifsregion *ifsp;
5568 INT_OFF;
5569 ifsp = ifsfirst.next->next;
5570 free(ifsfirst.next);
5571 ifsfirst.next = ifsp;
5572 INT_ON;
5573 }
5574 if (ifsfirst.begoff > endoff)
5575 ifslastp = NULL;
5576 else {
5577 ifslastp = &ifsfirst;
5578 ifsfirst.endoff = endoff;
5579 }
5580 return;
5581 }
5582
5583 ifslastp = &ifsfirst;
5584 while (ifslastp->next && ifslastp->next->begoff < endoff)
5585 ifslastp=ifslastp->next;
5586 while (ifslastp->next != NULL) {
5587 struct ifsregion *ifsp;
5588 INT_OFF;
5589 ifsp = ifslastp->next->next;
5590 free(ifslastp->next);
5591 ifslastp->next = ifsp;
5592 INT_ON;
5593 }
5594 if (ifslastp->endoff > endoff)
5595 ifslastp->endoff = endoff;
5596}
5597
5598static char *
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005599exptilde(char *startp, char *p, int flags)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005600{
Denys Vlasenkocd716832009-11-28 22:14:02 +01005601 unsigned char c;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005602 char *name;
5603 struct passwd *pw;
5604 const char *home;
Denys Vlasenko1166d7b2009-09-16 16:20:31 +02005605 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005606 int startloc;
5607
5608 name = p + 1;
5609
5610 while ((c = *++p) != '\0') {
5611 switch (c) {
5612 case CTLESC:
5613 return startp;
5614 case CTLQUOTEMARK:
5615 return startp;
5616 case ':':
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005617 if (flags & EXP_VARTILDE)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005618 goto done;
5619 break;
5620 case '/':
5621 case CTLENDVAR:
5622 goto done;
5623 }
5624 }
5625 done:
5626 *p = '\0';
5627 if (*name == '\0') {
5628 home = lookupvar(homestr);
5629 } else {
5630 pw = getpwnam(name);
5631 if (pw == NULL)
5632 goto lose;
5633 home = pw->pw_dir;
5634 }
5635 if (!home || !*home)
5636 goto lose;
5637 *p = c;
5638 startloc = expdest - (char *)stackblock();
5639 strtodest(home, SQSYNTAX, quotes);
5640 recordregion(startloc, expdest - (char *)stackblock(), 0);
5641 return p;
5642 lose:
5643 *p = c;
5644 return startp;
5645}
5646
5647/*
5648 * Execute a command inside back quotes. If it's a builtin command, we
5649 * want to save its output in a block obtained from malloc. Otherwise
5650 * we fork off a subprocess and get the output of the command via a pipe.
5651 * Should be called with interrupts off.
5652 */
5653struct backcmd { /* result of evalbackcmd */
5654 int fd; /* file descriptor to read from */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005655 int nleft; /* number of chars in buffer */
Denis Vlasenkob07a4962008-06-22 13:16:23 +00005656 char *buf; /* buffer */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005657 struct job *jp; /* job structure for command */
5658};
5659
5660/* These forward decls are needed to use "eval" code for backticks handling: */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00005661static uint8_t back_exitstatus; /* exit status of backquoted command */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005662#define EV_EXIT 01 /* exit after evaluating tree */
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02005663static void evaltree(union node *, int);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005664
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02005665static void FAST_FUNC
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005666evalbackcmd(union node *n, struct backcmd *result)
5667{
5668 int saveherefd;
5669
5670 result->fd = -1;
5671 result->buf = NULL;
5672 result->nleft = 0;
5673 result->jp = NULL;
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00005674 if (n == NULL)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005675 goto out;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005676
5677 saveherefd = herefd;
5678 herefd = -1;
5679
5680 {
5681 int pip[2];
5682 struct job *jp;
5683
5684 if (pipe(pip) < 0)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00005685 ash_msg_and_raise_error("pipe call failed");
Denis Vlasenko68404f12008-03-17 09:00:54 +00005686 jp = makejob(/*n,*/ 1);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005687 if (forkshell(jp, n, FORK_NOJOB) == 0) {
5688 FORCE_INT_ON;
5689 close(pip[0]);
5690 if (pip[1] != 1) {
Denis Vlasenko5a867312008-07-24 19:46:38 +00005691 /*close(1);*/
5692 copyfd(pip[1], 1 | COPYFD_EXACT);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005693 close(pip[1]);
5694 }
5695 eflag = 0;
5696 evaltree(n, EV_EXIT); /* actually evaltreenr... */
5697 /* NOTREACHED */
5698 }
5699 close(pip[1]);
5700 result->fd = pip[0];
5701 result->jp = jp;
5702 }
5703 herefd = saveherefd;
5704 out:
5705 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
5706 result->fd, result->buf, result->nleft, result->jp));
5707}
5708
5709/*
5710 * Expand stuff in backwards quotes.
5711 */
5712static void
5713expbackq(union node *cmd, int quoted, int quotes)
5714{
5715 struct backcmd in;
5716 int i;
5717 char buf[128];
5718 char *p;
5719 char *dest;
5720 int startloc;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00005721 int syntax = quoted ? DQSYNTAX : BASESYNTAX;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005722 struct stackmark smark;
5723
5724 INT_OFF;
5725 setstackmark(&smark);
5726 dest = expdest;
5727 startloc = dest - (char *)stackblock();
5728 grabstackstr(dest);
5729 evalbackcmd(cmd, &in);
5730 popstackmark(&smark);
5731
5732 p = in.buf;
5733 i = in.nleft;
5734 if (i == 0)
5735 goto read;
5736 for (;;) {
5737 memtodest(p, i, syntax, quotes);
5738 read:
5739 if (in.fd < 0)
5740 break;
Denis Vlasenkoe376d452008-02-20 22:23:24 +00005741 i = nonblock_safe_read(in.fd, buf, sizeof(buf));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005742 TRACE(("expbackq: read returns %d\n", i));
5743 if (i <= 0)
5744 break;
5745 p = buf;
5746 }
5747
Denis Vlasenko60818682007-09-28 22:07:23 +00005748 free(in.buf);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005749 if (in.fd >= 0) {
5750 close(in.fd);
5751 back_exitstatus = waitforjob(in.jp);
5752 }
5753 INT_ON;
5754
5755 /* Eat all trailing newlines */
5756 dest = expdest;
5757 for (; dest > (char *)stackblock() && dest[-1] == '\n';)
5758 STUNPUTC(dest);
5759 expdest = dest;
5760
5761 if (quoted == 0)
5762 recordregion(startloc, dest - (char *)stackblock(), 0);
5763 TRACE(("evalbackq: size=%d: \"%.*s\"\n",
5764 (dest - (char *)stackblock()) - startloc,
5765 (dest - (char *)stackblock()) - startloc,
5766 stackblock() + startloc));
5767}
5768
Mike Frysinger98c52642009-04-02 10:02:37 +00005769#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005770/*
5771 * Expand arithmetic expression. Backup to start of expression,
5772 * evaluate, place result in (backed up) result, adjust string position.
5773 */
5774static void
5775expari(int quotes)
5776{
5777 char *p, *start;
5778 int begoff;
5779 int flag;
5780 int len;
5781
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00005782 /* ifsfree(); */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005783
5784 /*
5785 * This routine is slightly over-complicated for
5786 * efficiency. Next we scan backwards looking for the
5787 * start of arithmetic.
5788 */
5789 start = stackblock();
5790 p = expdest - 1;
5791 *p = '\0';
5792 p--;
5793 do {
5794 int esc;
5795
Denys Vlasenkocd716832009-11-28 22:14:02 +01005796 while ((unsigned char)*p != CTLARI) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005797 p--;
5798#if DEBUG
5799 if (p < start) {
5800 ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
5801 }
5802#endif
5803 }
5804
5805 esc = esclen(start, p);
5806 if (!(esc % 2)) {
5807 break;
5808 }
5809
5810 p -= esc + 1;
5811 } while (1);
5812
5813 begoff = p - start;
5814
5815 removerecordregions(begoff);
5816
5817 flag = p[1];
5818
5819 expdest = p;
5820
5821 if (quotes)
Denys Vlasenkob6c84342009-08-29 20:23:20 +02005822 rmescapes(p + 2, 0);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005823
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00005824 len = cvtnum(ash_arith(p + 2));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005825
5826 if (flag != '"')
5827 recordregion(begoff, begoff + len, 0);
5828}
5829#endif
5830
5831/* argstr needs it */
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005832static char *evalvar(char *p, int flags, struct strlist *var_str_list);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005833
5834/*
5835 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
5836 * characters to allow for further processing. Otherwise treat
5837 * $@ like $* since no splitting will be performed.
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00005838 *
5839 * var_str_list (can be NULL) is a list of "VAR=val" strings which take precedence
5840 * over shell varables. Needed for "A=a B=$A; echo $B" case - we use it
5841 * for correct expansion of "B=$A" word.
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005842 */
5843static void
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005844argstr(char *p, int flags, struct strlist *var_str_list)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005845{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00005846 static const char spclchars[] ALIGN1 = {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005847 '=',
5848 ':',
5849 CTLQUOTEMARK,
5850 CTLENDVAR,
5851 CTLESC,
5852 CTLVAR,
5853 CTLBACKQ,
5854 CTLBACKQ | CTLQUOTE,
Mike Frysinger98c52642009-04-02 10:02:37 +00005855#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005856 CTLENDARI,
5857#endif
Denys Vlasenkocd716832009-11-28 22:14:02 +01005858 '\0'
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005859 };
5860 const char *reject = spclchars;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005861 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR); /* do CTLESC */
5862 int breakall = flags & EXP_WORD;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005863 int inquotes;
5864 size_t length;
5865 int startloc;
5866
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005867 if (!(flags & EXP_VARTILDE)) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005868 reject += 2;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005869 } else if (flags & EXP_VARTILDE2) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005870 reject++;
5871 }
5872 inquotes = 0;
5873 length = 0;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005874 if (flags & EXP_TILDE) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005875 char *q;
5876
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005877 flags &= ~EXP_TILDE;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005878 tilde:
5879 q = p;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005880 if (*q == CTLESC && (flags & EXP_QWORD))
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005881 q++;
5882 if (*q == '~')
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005883 p = exptilde(p, q, flags);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005884 }
5885 start:
5886 startloc = expdest - (char *)stackblock();
5887 for (;;) {
Denys Vlasenkocd716832009-11-28 22:14:02 +01005888 unsigned char c;
5889
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005890 length += strcspn(p + length, reject);
Denys Vlasenkocd716832009-11-28 22:14:02 +01005891 c = p[length];
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005892 if (c) {
5893 if (!(c & 0x80)
Mike Frysinger98c52642009-04-02 10:02:37 +00005894#if ENABLE_SH_MATH_SUPPORT
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005895 || c == CTLENDARI
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005896#endif
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005897 ) {
5898 /* c == '=' || c == ':' || c == CTLENDARI */
5899 length++;
5900 }
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005901 }
5902 if (length > 0) {
5903 int newloc;
5904 expdest = stack_nputstr(p, length, expdest);
5905 newloc = expdest - (char *)stackblock();
5906 if (breakall && !inquotes && newloc > startloc) {
5907 recordregion(startloc, newloc, 0);
5908 }
5909 startloc = newloc;
5910 }
5911 p += length + 1;
5912 length = 0;
5913
5914 switch (c) {
5915 case '\0':
5916 goto breakloop;
5917 case '=':
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005918 if (flags & EXP_VARTILDE2) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005919 p--;
5920 continue;
5921 }
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005922 flags |= EXP_VARTILDE2;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005923 reject++;
5924 /* fall through */
5925 case ':':
5926 /*
5927 * sort of a hack - expand tildes in variable
5928 * assignments (after the first '=' and after ':'s).
5929 */
5930 if (*--p == '~') {
5931 goto tilde;
5932 }
5933 continue;
5934 }
5935
5936 switch (c) {
5937 case CTLENDVAR: /* ??? */
5938 goto breakloop;
5939 case CTLQUOTEMARK:
5940 /* "$@" syntax adherence hack */
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005941 if (!inquotes
5942 && memcmp(p, dolatstr, 4) == 0
5943 && ( p[4] == CTLQUOTEMARK
5944 || (p[4] == CTLENDVAR && p[5] == CTLQUOTEMARK)
5945 )
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005946 ) {
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005947 p = evalvar(p + 1, flags, /* var_str_list: */ NULL) + 1;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005948 goto start;
5949 }
5950 inquotes = !inquotes;
5951 addquote:
5952 if (quotes) {
5953 p--;
5954 length++;
5955 startloc++;
5956 }
5957 break;
5958 case CTLESC:
5959 startloc++;
5960 length++;
5961 goto addquote;
5962 case CTLVAR:
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005963 p = evalvar(p, flags, var_str_list);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005964 goto start;
5965 case CTLBACKQ:
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005966 c = '\0';
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005967 case CTLBACKQ|CTLQUOTE:
5968 expbackq(argbackq->n, c, quotes);
5969 argbackq = argbackq->next;
5970 goto start;
Mike Frysinger98c52642009-04-02 10:02:37 +00005971#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005972 case CTLENDARI:
5973 p--;
5974 expari(quotes);
5975 goto start;
5976#endif
5977 }
5978 }
5979 breakloop:
5980 ;
5981}
5982
5983static char *
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00005984scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM, char *str, int quotes,
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005985 int zero)
5986{
Denis Vlasenkoc7131c32008-04-14 01:59:53 +00005987// This commented out code was added by James Simmons <jsimmons@infradead.org>
5988// as part of a larger change when he added support for ${var/a/b}.
5989// However, it broke # and % operators:
5990//
5991//var=ababcdcd
5992// ok bad
5993//echo ${var#ab} abcdcd abcdcd
5994//echo ${var##ab} abcdcd abcdcd
5995//echo ${var#a*b} abcdcd ababcdcd (!)
5996//echo ${var##a*b} cdcd cdcd
5997//echo ${var#?} babcdcd ababcdcd (!)
5998//echo ${var##?} babcdcd babcdcd
5999//echo ${var#*} ababcdcd babcdcd (!)
6000//echo ${var##*}
6001//echo ${var%cd} ababcd ababcd
6002//echo ${var%%cd} ababcd abab (!)
6003//echo ${var%c*d} ababcd ababcd
6004//echo ${var%%c*d} abab ababcdcd (!)
6005//echo ${var%?} ababcdc ababcdc
6006//echo ${var%%?} ababcdc ababcdcd (!)
6007//echo ${var%*} ababcdcd ababcdcd
6008//echo ${var%%*}
6009//
6010// Commenting it back out helped. Remove it completely if it really
6011// is not needed.
6012
6013 char *loc, *loc2; //, *full;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006014 char c;
6015
6016 loc = startp;
6017 loc2 = rmesc;
6018 do {
Denis Vlasenkoc7131c32008-04-14 01:59:53 +00006019 int match; // = strlen(str);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006020 const char *s = loc2;
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006021
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006022 c = *loc2;
6023 if (zero) {
6024 *loc2 = '\0';
6025 s = rmesc;
6026 }
Denis Vlasenkoc7131c32008-04-14 01:59:53 +00006027 match = pmatch(str, s); // this line was deleted
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006028
Denis Vlasenkoc7131c32008-04-14 01:59:53 +00006029// // chop off end if its '*'
6030// full = strrchr(str, '*');
6031// if (full && full != str)
6032// match--;
6033//
6034// // If str starts with '*' replace with s.
6035// if ((*str == '*') && strlen(s) >= match) {
6036// full = xstrdup(s);
6037// strncpy(full+strlen(s)-match+1, str+1, match-1);
6038// } else
6039// full = xstrndup(str, match);
6040// match = strncmp(s, full, strlen(full));
6041// free(full);
6042//
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006043 *loc2 = c;
Denis Vlasenkoc7131c32008-04-14 01:59:53 +00006044 if (match) // if (!match)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006045 return loc;
Denys Vlasenkocd716832009-11-28 22:14:02 +01006046 if (quotes && (unsigned char)*loc == CTLESC)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006047 loc++;
6048 loc++;
6049 loc2++;
6050 } while (c);
6051 return 0;
6052}
6053
6054static char *
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006055scanright(char *startp, char *rmesc, char *rmescend, char *pattern, int quotes, int match_at_start)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006056{
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006057#if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6058 int try2optimize = match_at_start;
6059#endif
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006060 int esc = 0;
6061 char *loc;
6062 char *loc2;
6063
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006064 /* If we called by "${v/pattern/repl}" or "${v//pattern/repl}":
6065 * startp="escaped_value_of_v" rmesc="raw_value_of_v"
6066 * rmescend=""(ptr to NUL in rmesc) pattern="pattern" quotes=match_at_start=1
6067 * Logic:
6068 * loc starts at NUL at the end of startp, loc2 starts at the end of rmesc,
6069 * and on each iteration they go back two/one char until they reach the beginning.
6070 * We try to find a match in "raw_value_of_v", "raw_value_of_", "raw_value_of" etc.
6071 */
6072 /* TODO: document in what other circumstances we are called. */
6073
6074 for (loc = pattern - 1, loc2 = rmescend; loc >= startp; loc2--) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006075 int match;
6076 char c = *loc2;
6077 const char *s = loc2;
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006078 if (match_at_start) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006079 *loc2 = '\0';
6080 s = rmesc;
6081 }
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006082 match = pmatch(pattern, s);
6083 //bb_error_msg("pmatch(pattern:'%s',s:'%s'):%d", pattern, s, match);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006084 *loc2 = c;
6085 if (match)
6086 return loc;
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006087#if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6088 if (try2optimize) {
6089 /* Maybe we can optimize this:
6090 * if pattern ends with unescaped *, we can avoid checking
6091 * shorter strings: if "foo*" doesnt match "raw_value_of_v",
6092 * it wont match truncated "raw_value_of_" strings too.
6093 */
6094 unsigned plen = strlen(pattern);
6095 /* Does it end with "*"? */
6096 if (plen != 0 && pattern[--plen] == '*') {
6097 /* "xxxx*" is not escaped */
6098 /* "xxx\*" is escaped */
6099 /* "xx\\*" is not escaped */
6100 /* "x\\\*" is escaped */
6101 int slashes = 0;
6102 while (plen != 0 && pattern[--plen] == '\\')
6103 slashes++;
6104 if (!(slashes & 1))
6105 break; /* ends with unescaped "*" */
6106 }
6107 try2optimize = 0;
6108 }
6109#endif
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006110 loc--;
6111 if (quotes) {
6112 if (--esc < 0) {
6113 esc = esclen(startp, loc);
6114 }
6115 if (esc % 2) {
6116 esc--;
6117 loc--;
6118 }
6119 }
6120 }
6121 return 0;
6122}
6123
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00006124static void varunset(const char *, const char *, const char *, int) NORETURN;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006125static void
6126varunset(const char *end, const char *var, const char *umsg, int varflags)
6127{
6128 const char *msg;
6129 const char *tail;
6130
6131 tail = nullstr;
6132 msg = "parameter not set";
6133 if (umsg) {
Denys Vlasenkocd716832009-11-28 22:14:02 +01006134 if ((unsigned char)*end == CTLENDVAR) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006135 if (varflags & VSNUL)
6136 tail = " or null";
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00006137 } else {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006138 msg = umsg;
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00006139 }
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006140 }
6141 ash_msg_and_raise_error("%.*s: %s%s", end - var - 1, var, msg, tail);
6142}
6143
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006144#if ENABLE_ASH_BASH_COMPAT
6145static char *
6146parse_sub_pattern(char *arg, int inquotes)
6147{
6148 char *idx, *repl = NULL;
6149 unsigned char c;
6150
Denis Vlasenko2659c632008-06-14 06:04:59 +00006151 idx = arg;
6152 while (1) {
6153 c = *arg;
6154 if (!c)
6155 break;
6156 if (c == '/') {
6157 /* Only the first '/' seen is our separator */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006158 if (!repl) {
Denis Vlasenko2659c632008-06-14 06:04:59 +00006159 repl = idx + 1;
6160 c = '\0';
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006161 }
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006162 }
Denis Vlasenko2659c632008-06-14 06:04:59 +00006163 *idx++ = c;
6164 if (!inquotes && c == '\\' && arg[1] == '\\')
6165 arg++; /* skip both \\, not just first one */
6166 arg++;
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006167 }
Denis Vlasenko29038c02008-06-14 06:14:02 +00006168 *idx = c; /* NUL */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006169
6170 return repl;
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006171}
6172#endif /* ENABLE_ASH_BASH_COMPAT */
6173
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006174static const char *
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006175subevalvar(char *p, char *str, int strloc, int subtype,
6176 int startloc, int varflags, int quotes, struct strlist *var_str_list)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006177{
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006178 struct nodelist *saveargbackq = argbackq;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006179 char *startp;
6180 char *loc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006181 char *rmesc, *rmescend;
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00006182 IF_ASH_BASH_COMPAT(char *repl = NULL;)
6183 IF_ASH_BASH_COMPAT(char null = '\0';)
6184 IF_ASH_BASH_COMPAT(int pos, len, orig_len;)
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006185 int saveherefd = herefd;
6186 int amount, workloc, resetloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006187 int zero;
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006188 char *(*scan)(char*, char*, char*, char*, int, int);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006189
6190 herefd = -1;
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006191 argstr(p, (subtype != VSASSIGN && subtype != VSQUESTION) ? EXP_CASE : 0,
6192 var_str_list);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006193 STPUTC('\0', expdest);
6194 herefd = saveherefd;
6195 argbackq = saveargbackq;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00006196 startp = (char *)stackblock() + startloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006197
6198 switch (subtype) {
6199 case VSASSIGN:
6200 setvar(str, startp, 0);
6201 amount = startp - expdest;
6202 STADJUST(amount, expdest);
6203 return startp;
6204
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006205#if ENABLE_ASH_BASH_COMPAT
6206 case VSSUBSTR:
6207 loc = str = stackblock() + strloc;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006208 /* Read POS in ${var:POS:LEN} */
6209 pos = atoi(loc); /* number(loc) errors out on "1:4" */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006210 len = str - startp - 1;
6211
6212 /* *loc != '\0', guaranteed by parser */
6213 if (quotes) {
6214 char *ptr;
6215
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006216 /* Adjust the length by the number of escapes */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006217 for (ptr = startp; ptr < (str - 1); ptr++) {
Denys Vlasenkocd716832009-11-28 22:14:02 +01006218 if ((unsigned char)*ptr == CTLESC) {
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006219 len--;
6220 ptr++;
6221 }
6222 }
6223 }
6224 orig_len = len;
6225
6226 if (*loc++ == ':') {
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006227 /* ${var::LEN} */
6228 len = number(loc);
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006229 } else {
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006230 /* Skip POS in ${var:POS:LEN} */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006231 len = orig_len;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006232 while (*loc && *loc != ':') {
6233 /* TODO?
6234 * bash complains on: var=qwe; echo ${var:1a:123}
6235 if (!isdigit(*loc))
6236 ash_msg_and_raise_error(msg_illnum, str);
6237 */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006238 loc++;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006239 }
6240 if (*loc++ == ':') {
6241 len = number(loc);
6242 }
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006243 }
6244 if (pos >= orig_len) {
6245 pos = 0;
6246 len = 0;
6247 }
6248 if (len > (orig_len - pos))
6249 len = orig_len - pos;
6250
6251 for (str = startp; pos; str++, pos--) {
Denys Vlasenkocd716832009-11-28 22:14:02 +01006252 if (quotes && (unsigned char)*str == CTLESC)
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006253 str++;
6254 }
6255 for (loc = startp; len; len--) {
Denys Vlasenkocd716832009-11-28 22:14:02 +01006256 if (quotes && (unsigned char)*str == CTLESC)
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006257 *loc++ = *str++;
6258 *loc++ = *str++;
6259 }
6260 *loc = '\0';
6261 amount = loc - expdest;
6262 STADJUST(amount, expdest);
6263 return loc;
6264#endif
6265
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006266 case VSQUESTION:
6267 varunset(p, str, startp, varflags);
6268 /* NOTREACHED */
6269 }
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006270 resetloc = expdest - (char *)stackblock();
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006271
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006272 /* We'll comeback here if we grow the stack while handling
6273 * a VSREPLACE or VSREPLACEALL, since our pointers into the
6274 * stack will need rebasing, and we'll need to remove our work
6275 * areas each time
6276 */
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00006277 IF_ASH_BASH_COMPAT(restart:)
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006278
6279 amount = expdest - ((char *)stackblock() + resetloc);
6280 STADJUST(-amount, expdest);
Denis Vlasenko29eb3592008-05-18 14:06:08 +00006281 startp = (char *)stackblock() + startloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006282
6283 rmesc = startp;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00006284 rmescend = (char *)stackblock() + strloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006285 if (quotes) {
Denys Vlasenkob6c84342009-08-29 20:23:20 +02006286 rmesc = rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006287 if (rmesc != startp) {
6288 rmescend = expdest;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00006289 startp = (char *)stackblock() + startloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006290 }
6291 }
6292 rmescend--;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00006293 str = (char *)stackblock() + strloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006294 preglob(str, varflags & VSQUOTE, 0);
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006295 workloc = expdest - (char *)stackblock();
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006296
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006297#if ENABLE_ASH_BASH_COMPAT
6298 if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006299 char *idx, *end;
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006300
Denis Vlasenkod6855d12008-09-27 14:03:25 +00006301 if (!repl) {
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006302 repl = parse_sub_pattern(str, varflags & VSQUOTE);
6303 if (!repl)
6304 repl = &null;
6305 }
6306
6307 /* If there's no pattern to match, return the expansion unmolested */
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006308 if (str[0] == '\0')
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006309 return 0;
6310
6311 len = 0;
6312 idx = startp;
6313 end = str - 1;
6314 while (idx < end) {
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006315 try_to_match:
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006316 loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
6317 if (!loc) {
6318 /* No match, advance */
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006319 char *restart_detect = stackblock();
6320 skip_matching:
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006321 STPUTC(*idx, expdest);
Denys Vlasenkocd716832009-11-28 22:14:02 +01006322 if (quotes && (unsigned char)*idx == CTLESC) {
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006323 idx++;
6324 len++;
6325 STPUTC(*idx, expdest);
6326 }
6327 if (stackblock() != restart_detect)
6328 goto restart;
6329 idx++;
6330 len++;
6331 rmesc++;
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006332 /* continue; - prone to quadratic behavior, smarter code: */
6333 if (idx >= end)
6334 break;
6335 if (str[0] == '*') {
6336 /* Pattern is "*foo". If "*foo" does not match "long_string",
6337 * it would never match "ong_string" etc, no point in trying.
6338 */
6339 goto skip_matching;
6340 }
6341 goto try_to_match;
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006342 }
6343
6344 if (subtype == VSREPLACEALL) {
6345 while (idx < loc) {
Denys Vlasenkocd716832009-11-28 22:14:02 +01006346 if (quotes && (unsigned char)*idx == CTLESC)
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006347 idx++;
6348 idx++;
6349 rmesc++;
6350 }
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00006351 } else {
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006352 idx = loc;
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00006353 }
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006354
6355 for (loc = repl; *loc; loc++) {
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006356 char *restart_detect = stackblock();
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006357 STPUTC(*loc, expdest);
6358 if (stackblock() != restart_detect)
6359 goto restart;
6360 len++;
6361 }
6362
6363 if (subtype == VSREPLACE) {
6364 while (*idx) {
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006365 char *restart_detect = stackblock();
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006366 STPUTC(*idx, expdest);
6367 if (stackblock() != restart_detect)
6368 goto restart;
6369 len++;
6370 idx++;
6371 }
6372 break;
6373 }
6374 }
6375
6376 /* We've put the replaced text into a buffer at workloc, now
6377 * move it to the right place and adjust the stack.
6378 */
6379 startp = stackblock() + startloc;
6380 STPUTC('\0', expdest);
6381 memmove(startp, stackblock() + workloc, len);
6382 startp[len++] = '\0';
6383 amount = expdest - ((char *)stackblock() + startloc + len - 1);
6384 STADJUST(-amount, expdest);
6385 return startp;
6386 }
6387#endif /* ENABLE_ASH_BASH_COMPAT */
6388
6389 subtype -= VSTRIMRIGHT;
6390#if DEBUG
6391 if (subtype < 0 || subtype > 7)
6392 abort();
6393#endif
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006394 /* zero = (subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX) */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006395 zero = subtype >> 1;
6396 /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
6397 scan = (subtype & 1) ^ zero ? scanleft : scanright;
6398
6399 loc = scan(startp, rmesc, rmescend, str, quotes, zero);
6400 if (loc) {
6401 if (zero) {
6402 memmove(startp, loc, str - loc);
6403 loc = startp + (str - loc) - 1;
6404 }
6405 *loc = '\0';
6406 amount = loc - expdest;
6407 STADJUST(amount, expdest);
6408 }
6409 return loc;
6410}
6411
6412/*
6413 * Add the value of a specialized variable to the stack string.
Denys Vlasenko4d8873f2009-10-04 03:14:41 +02006414 * name parameter (examples):
6415 * ash -c 'echo $1' name:'1='
6416 * ash -c 'echo $qwe' name:'qwe='
6417 * ash -c 'echo $$' name:'$='
6418 * ash -c 'echo ${$}' name:'$='
6419 * ash -c 'echo ${$##q}' name:'$=q'
6420 * ash -c 'echo ${#$}' name:'$='
6421 * note: examples with bad shell syntax:
6422 * ash -c 'echo ${#$1}' name:'$=1'
6423 * ash -c 'echo ${#1#}' name:'1=#'
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006424 */
Denys Vlasenkoadf922e2009-10-08 14:35:37 +02006425static NOINLINE ssize_t
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006426varvalue(char *name, int varflags, int flags, struct strlist *var_str_list)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006427{
Mike Frysinger98c52642009-04-02 10:02:37 +00006428 const char *p;
Denys Vlasenko8eda4a92009-11-30 12:16:17 +01006429 int num;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006430 int i;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006431 int sepq = 0;
6432 ssize_t len = 0;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006433 int subtype = varflags & VSTYPE;
Denys Vlasenko1166d7b2009-09-16 16:20:31 +02006434 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR);
Denys Vlasenko8eda4a92009-11-30 12:16:17 +01006435 int quoted = varflags & VSQUOTE;
6436 int syntax = quoted ? DQSYNTAX : BASESYNTAX;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006437
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006438 switch (*name) {
6439 case '$':
6440 num = rootpid;
6441 goto numvar;
6442 case '?':
6443 num = exitstatus;
6444 goto numvar;
6445 case '#':
6446 num = shellparam.nparam;
6447 goto numvar;
6448 case '!':
6449 num = backgndpid;
6450 if (num == 0)
6451 return -1;
6452 numvar:
6453 len = cvtnum(num);
Denys Vlasenko4d8873f2009-10-04 03:14:41 +02006454 goto check_1char_name;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006455 case '-':
Mike Frysinger98c52642009-04-02 10:02:37 +00006456 expdest = makestrspace(NOPTS, expdest);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006457 for (i = NOPTS - 1; i >= 0; i--) {
6458 if (optlist[i]) {
Mike Frysinger98c52642009-04-02 10:02:37 +00006459 USTPUTC(optletters(i), expdest);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006460 len++;
6461 }
6462 }
Denys Vlasenko4d8873f2009-10-04 03:14:41 +02006463 check_1char_name:
6464#if 0
6465 /* handles cases similar to ${#$1} */
6466 if (name[2] != '\0')
6467 raise_error_syntax("bad substitution");
6468#endif
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006469 break;
Denys Vlasenko8eda4a92009-11-30 12:16:17 +01006470 case '@': {
6471 char **ap;
6472 int sep;
6473
6474 if (quoted && (flags & EXP_FULL)) {
6475 /* note: this is not meant as PEOF value */
6476 sep = 1 << CHAR_BIT;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006477 goto param;
Denys Vlasenko8eda4a92009-11-30 12:16:17 +01006478 }
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006479 /* fall through */
6480 case '*':
Denys Vlasenkocd716832009-11-28 22:14:02 +01006481 sep = ifsset() ? (unsigned char)(ifsval()[0]) : ' ';
Denys Vlasenko8eda4a92009-11-30 12:16:17 +01006482 i = SIT(sep, syntax);
6483 if (quotes && (i == CCTL || i == CBACK))
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006484 sepq = 1;
6485 param:
6486 ap = shellparam.p;
6487 if (!ap)
6488 return -1;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006489 while ((p = *ap++) != NULL) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006490 size_t partlen;
6491
6492 partlen = strlen(p);
6493 len += partlen;
6494
6495 if (!(subtype == VSPLUS || subtype == VSLENGTH))
6496 memtodest(p, partlen, syntax, quotes);
6497
6498 if (*ap && sep) {
6499 char *q;
6500
6501 len++;
6502 if (subtype == VSPLUS || subtype == VSLENGTH) {
6503 continue;
6504 }
6505 q = expdest;
6506 if (sepq)
6507 STPUTC(CTLESC, q);
Denys Vlasenko8eda4a92009-11-30 12:16:17 +01006508 /* note: may put NUL despite sep != 0
6509 * (see sep = 1 << CHAR_BIT above) */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006510 STPUTC(sep, q);
6511 expdest = q;
6512 }
6513 }
6514 return len;
Denys Vlasenko8eda4a92009-11-30 12:16:17 +01006515 } /* case '@' and '*' */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006516 case '0':
6517 case '1':
6518 case '2':
6519 case '3':
6520 case '4':
6521 case '5':
6522 case '6':
6523 case '7':
6524 case '8':
6525 case '9':
Denys Vlasenkoa00329c2009-08-30 20:05:10 +02006526 num = atoi(name); /* number(name) fails on ${N#str} etc */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006527 if (num < 0 || num > shellparam.nparam)
6528 return -1;
6529 p = num ? shellparam.p[num - 1] : arg0;
6530 goto value;
6531 default:
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006532 /* NB: name has form "VAR=..." */
6533
6534 /* "A=a B=$A" case: var_str_list is a list of "A=a" strings
6535 * which should be considered before we check variables. */
6536 if (var_str_list) {
6537 unsigned name_len = (strchrnul(name, '=') - name) + 1;
6538 p = NULL;
6539 do {
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00006540 char *str, *eq;
6541 str = var_str_list->text;
6542 eq = strchr(str, '=');
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006543 if (!eq) /* stop at first non-assignment */
6544 break;
6545 eq++;
Denis Vlasenko6b06cb82008-05-15 21:30:45 +00006546 if (name_len == (unsigned)(eq - str)
Denys Vlasenko8eda4a92009-11-30 12:16:17 +01006547 && strncmp(str, name, name_len) == 0
6548 ) {
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006549 p = eq;
6550 /* goto value; - WRONG! */
6551 /* think "A=1 A=2 B=$A" */
6552 }
6553 var_str_list = var_str_list->next;
6554 } while (var_str_list);
6555 if (p)
6556 goto value;
6557 }
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006558 p = lookupvar(name);
6559 value:
6560 if (!p)
6561 return -1;
6562
6563 len = strlen(p);
6564 if (!(subtype == VSPLUS || subtype == VSLENGTH))
6565 memtodest(p, len, syntax, quotes);
6566 return len;
6567 }
6568
6569 if (subtype == VSPLUS || subtype == VSLENGTH)
6570 STADJUST(-len, expdest);
6571 return len;
6572}
6573
6574/*
6575 * Expand a variable, and return a pointer to the next character in the
6576 * input string.
6577 */
6578static char *
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006579evalvar(char *p, int flags, struct strlist *var_str_list)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006580{
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006581 char varflags;
6582 char subtype;
6583 char quoted;
6584 char easy;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006585 char *var;
6586 int patloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006587 int startloc;
6588 ssize_t varlen;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006589
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006590 varflags = (unsigned char) *p++;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006591 subtype = varflags & VSTYPE;
6592 quoted = varflags & VSQUOTE;
6593 var = p;
6594 easy = (!quoted || (*var == '@' && shellparam.nparam));
6595 startloc = expdest - (char *)stackblock();
6596 p = strchr(p, '=') + 1;
6597
6598 again:
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006599 varlen = varvalue(var, varflags, flags, var_str_list);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006600 if (varflags & VSNUL)
6601 varlen--;
6602
6603 if (subtype == VSPLUS) {
6604 varlen = -1 - varlen;
6605 goto vsplus;
6606 }
6607
6608 if (subtype == VSMINUS) {
6609 vsplus:
6610 if (varlen < 0) {
6611 argstr(
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006612 p, flags | EXP_TILDE |
6613 (quoted ? EXP_QWORD : EXP_WORD),
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006614 var_str_list
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006615 );
6616 goto end;
6617 }
6618 if (easy)
6619 goto record;
6620 goto end;
6621 }
6622
6623 if (subtype == VSASSIGN || subtype == VSQUESTION) {
6624 if (varlen < 0) {
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006625 if (subevalvar(p, var, /* strloc: */ 0,
6626 subtype, startloc, varflags,
6627 /* quotes: */ 0,
6628 var_str_list)
6629 ) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006630 varflags &= ~VSNUL;
6631 /*
6632 * Remove any recorded regions beyond
6633 * start of variable
6634 */
6635 removerecordregions(startloc);
6636 goto again;
6637 }
6638 goto end;
6639 }
6640 if (easy)
6641 goto record;
6642 goto end;
6643 }
6644
6645 if (varlen < 0 && uflag)
6646 varunset(p, var, 0, 0);
6647
6648 if (subtype == VSLENGTH) {
6649 cvtnum(varlen > 0 ? varlen : 0);
6650 goto record;
6651 }
6652
6653 if (subtype == VSNORMAL) {
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006654 if (easy)
6655 goto record;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006656 goto end;
6657 }
6658
6659#if DEBUG
6660 switch (subtype) {
6661 case VSTRIMLEFT:
6662 case VSTRIMLEFTMAX:
6663 case VSTRIMRIGHT:
6664 case VSTRIMRIGHTMAX:
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006665#if ENABLE_ASH_BASH_COMPAT
6666 case VSSUBSTR:
6667 case VSREPLACE:
6668 case VSREPLACEALL:
6669#endif
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006670 break;
6671 default:
6672 abort();
6673 }
6674#endif
6675
6676 if (varlen >= 0) {
6677 /*
6678 * Terminate the string and start recording the pattern
6679 * right after it
6680 */
6681 STPUTC('\0', expdest);
6682 patloc = expdest - (char *)stackblock();
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006683 if (0 == subevalvar(p, /* str: */ NULL, patloc, subtype,
6684 startloc, varflags,
Denys Vlasenko1166d7b2009-09-16 16:20:31 +02006685//TODO: | EXP_REDIR too? All other such places do it too
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006686 /* quotes: */ flags & (EXP_FULL | EXP_CASE),
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006687 var_str_list)
6688 ) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006689 int amount = expdest - (
6690 (char *)stackblock() + patloc - 1
6691 );
6692 STADJUST(-amount, expdest);
6693 }
6694 /* Remove any recorded regions beyond start of variable */
6695 removerecordregions(startloc);
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006696 record:
6697 recordregion(startloc, expdest - (char *)stackblock(), quoted);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006698 }
6699
6700 end:
6701 if (subtype != VSNORMAL) { /* skip to end of alternative */
6702 int nesting = 1;
6703 for (;;) {
Denys Vlasenkocd716832009-11-28 22:14:02 +01006704 unsigned char c = *p++;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006705 if (c == CTLESC)
6706 p++;
6707 else if (c == CTLBACKQ || c == (CTLBACKQ|CTLQUOTE)) {
6708 if (varlen >= 0)
6709 argbackq = argbackq->next;
6710 } else if (c == CTLVAR) {
6711 if ((*p++ & VSTYPE) != VSNORMAL)
6712 nesting++;
6713 } else if (c == CTLENDVAR) {
6714 if (--nesting == 0)
6715 break;
6716 }
6717 }
6718 }
6719 return p;
6720}
6721
6722/*
6723 * Break the argument string into pieces based upon IFS and add the
6724 * strings to the argument list. The regions of the string to be
6725 * searched for IFS characters have been stored by recordregion.
6726 */
6727static void
6728ifsbreakup(char *string, struct arglist *arglist)
6729{
6730 struct ifsregion *ifsp;
6731 struct strlist *sp;
6732 char *start;
6733 char *p;
6734 char *q;
6735 const char *ifs, *realifs;
6736 int ifsspc;
6737 int nulonly;
6738
6739 start = string;
6740 if (ifslastp != NULL) {
6741 ifsspc = 0;
6742 nulonly = 0;
6743 realifs = ifsset() ? ifsval() : defifs;
6744 ifsp = &ifsfirst;
6745 do {
6746 p = string + ifsp->begoff;
6747 nulonly = ifsp->nulonly;
6748 ifs = nulonly ? nullstr : realifs;
6749 ifsspc = 0;
6750 while (p < string + ifsp->endoff) {
6751 q = p;
Denys Vlasenkocd716832009-11-28 22:14:02 +01006752 if ((unsigned char)*p == CTLESC)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006753 p++;
6754 if (!strchr(ifs, *p)) {
6755 p++;
6756 continue;
6757 }
6758 if (!nulonly)
6759 ifsspc = (strchr(defifs, *p) != NULL);
6760 /* Ignore IFS whitespace at start */
6761 if (q == start && ifsspc) {
6762 p++;
6763 start = p;
6764 continue;
6765 }
6766 *q = '\0';
Denis Vlasenko597906c2008-02-20 16:38:54 +00006767 sp = stzalloc(sizeof(*sp));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006768 sp->text = start;
6769 *arglist->lastp = sp;
6770 arglist->lastp = &sp->next;
6771 p++;
6772 if (!nulonly) {
6773 for (;;) {
6774 if (p >= string + ifsp->endoff) {
6775 break;
6776 }
6777 q = p;
Denys Vlasenkocd716832009-11-28 22:14:02 +01006778 if ((unsigned char)*p == CTLESC)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006779 p++;
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +00006780 if (strchr(ifs, *p) == NULL) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006781 p = q;
6782 break;
Denis Vlasenko597906c2008-02-20 16:38:54 +00006783 }
6784 if (strchr(defifs, *p) == NULL) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006785 if (ifsspc) {
6786 p++;
6787 ifsspc = 0;
6788 } else {
6789 p = q;
6790 break;
6791 }
6792 } else
6793 p++;
6794 }
6795 }
6796 start = p;
6797 } /* while */
6798 ifsp = ifsp->next;
6799 } while (ifsp != NULL);
6800 if (nulonly)
6801 goto add;
6802 }
6803
6804 if (!*start)
6805 return;
6806
6807 add:
Denis Vlasenko597906c2008-02-20 16:38:54 +00006808 sp = stzalloc(sizeof(*sp));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006809 sp->text = start;
6810 *arglist->lastp = sp;
6811 arglist->lastp = &sp->next;
6812}
6813
6814static void
6815ifsfree(void)
6816{
6817 struct ifsregion *p;
6818
6819 INT_OFF;
6820 p = ifsfirst.next;
6821 do {
6822 struct ifsregion *ifsp;
6823 ifsp = p->next;
6824 free(p);
6825 p = ifsp;
6826 } while (p);
6827 ifslastp = NULL;
6828 ifsfirst.next = NULL;
6829 INT_ON;
6830}
6831
6832/*
6833 * Add a file name to the list.
6834 */
6835static void
6836addfname(const char *name)
6837{
6838 struct strlist *sp;
6839
Denis Vlasenko597906c2008-02-20 16:38:54 +00006840 sp = stzalloc(sizeof(*sp));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006841 sp->text = ststrdup(name);
6842 *exparg.lastp = sp;
6843 exparg.lastp = &sp->next;
6844}
6845
6846static char *expdir;
6847
6848/*
6849 * Do metacharacter (i.e. *, ?, [...]) expansion.
6850 */
6851static void
6852expmeta(char *enddir, char *name)
6853{
6854 char *p;
6855 const char *cp;
6856 char *start;
6857 char *endname;
6858 int metaflag;
6859 struct stat statb;
6860 DIR *dirp;
6861 struct dirent *dp;
6862 int atend;
6863 int matchdot;
6864
6865 metaflag = 0;
6866 start = name;
6867 for (p = name; *p; p++) {
6868 if (*p == '*' || *p == '?')
6869 metaflag = 1;
6870 else if (*p == '[') {
6871 char *q = p + 1;
6872 if (*q == '!')
6873 q++;
6874 for (;;) {
6875 if (*q == '\\')
6876 q++;
6877 if (*q == '/' || *q == '\0')
6878 break;
6879 if (*++q == ']') {
6880 metaflag = 1;
6881 break;
6882 }
6883 }
6884 } else if (*p == '\\')
6885 p++;
6886 else if (*p == '/') {
6887 if (metaflag)
6888 goto out;
6889 start = p + 1;
6890 }
6891 }
6892 out:
6893 if (metaflag == 0) { /* we've reached the end of the file name */
6894 if (enddir != expdir)
6895 metaflag++;
6896 p = name;
6897 do {
6898 if (*p == '\\')
6899 p++;
6900 *enddir++ = *p;
6901 } while (*p++);
6902 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
6903 addfname(expdir);
6904 return;
6905 }
6906 endname = p;
6907 if (name < start) {
6908 p = name;
6909 do {
6910 if (*p == '\\')
6911 p++;
6912 *enddir++ = *p++;
6913 } while (p < start);
6914 }
6915 if (enddir == expdir) {
6916 cp = ".";
6917 } else if (enddir == expdir + 1 && *expdir == '/') {
6918 cp = "/";
6919 } else {
6920 cp = expdir;
6921 enddir[-1] = '\0';
6922 }
6923 dirp = opendir(cp);
6924 if (dirp == NULL)
6925 return;
6926 if (enddir != expdir)
6927 enddir[-1] = '/';
6928 if (*endname == 0) {
6929 atend = 1;
6930 } else {
6931 atend = 0;
6932 *endname++ = '\0';
6933 }
6934 matchdot = 0;
6935 p = start;
6936 if (*p == '\\')
6937 p++;
6938 if (*p == '.')
6939 matchdot++;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006940 while (!pending_int && (dp = readdir(dirp)) != NULL) {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00006941 if (dp->d_name[0] == '.' && !matchdot)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006942 continue;
6943 if (pmatch(start, dp->d_name)) {
6944 if (atend) {
6945 strcpy(enddir, dp->d_name);
6946 addfname(expdir);
6947 } else {
6948 for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
6949 continue;
6950 p[-1] = '/';
6951 expmeta(p, endname);
6952 }
6953 }
6954 }
6955 closedir(dirp);
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00006956 if (!atend)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006957 endname[-1] = '/';
6958}
6959
6960static struct strlist *
6961msort(struct strlist *list, int len)
6962{
6963 struct strlist *p, *q = NULL;
6964 struct strlist **lpp;
6965 int half;
6966 int n;
6967
6968 if (len <= 1)
6969 return list;
6970 half = len >> 1;
6971 p = list;
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +00006972 for (n = half; --n >= 0;) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006973 q = p;
6974 p = p->next;
6975 }
6976 q->next = NULL; /* terminate first half of list */
6977 q = msort(list, half); /* sort first half of list */
6978 p = msort(p, len - half); /* sort second half */
6979 lpp = &list;
6980 for (;;) {
6981#if ENABLE_LOCALE_SUPPORT
6982 if (strcoll(p->text, q->text) < 0)
6983#else
6984 if (strcmp(p->text, q->text) < 0)
6985#endif
6986 {
6987 *lpp = p;
6988 lpp = &p->next;
6989 p = *lpp;
6990 if (p == NULL) {
6991 *lpp = q;
6992 break;
6993 }
6994 } else {
6995 *lpp = q;
6996 lpp = &q->next;
6997 q = *lpp;
6998 if (q == NULL) {
6999 *lpp = p;
7000 break;
7001 }
7002 }
7003 }
7004 return list;
7005}
7006
7007/*
7008 * Sort the results of file name expansion. It calculates the number of
7009 * strings to sort and then calls msort (short for merge sort) to do the
7010 * work.
7011 */
7012static struct strlist *
7013expsort(struct strlist *str)
7014{
7015 int len;
7016 struct strlist *sp;
7017
7018 len = 0;
7019 for (sp = str; sp; sp = sp->next)
7020 len++;
7021 return msort(str, len);
7022}
7023
7024static void
Denis Vlasenko68404f12008-03-17 09:00:54 +00007025expandmeta(struct strlist *str /*, int flag*/)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007026{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00007027 static const char metachars[] ALIGN1 = {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007028 '*', '?', '[', 0
7029 };
7030 /* TODO - EXP_REDIR */
7031
7032 while (str) {
7033 struct strlist **savelastp;
7034 struct strlist *sp;
7035 char *p;
7036
7037 if (fflag)
7038 goto nometa;
7039 if (!strpbrk(str->text, metachars))
7040 goto nometa;
7041 savelastp = exparg.lastp;
7042
7043 INT_OFF;
7044 p = preglob(str->text, 0, RMESCAPE_ALLOC | RMESCAPE_HEAP);
7045 {
7046 int i = strlen(str->text);
7047 expdir = ckmalloc(i < 2048 ? 2048 : i); /* XXX */
7048 }
7049
7050 expmeta(expdir, p);
7051 free(expdir);
7052 if (p != str->text)
7053 free(p);
7054 INT_ON;
7055 if (exparg.lastp == savelastp) {
7056 /*
7057 * no matches
7058 */
7059 nometa:
7060 *exparg.lastp = str;
Denys Vlasenkob6c84342009-08-29 20:23:20 +02007061 rmescapes(str->text, 0);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007062 exparg.lastp = &str->next;
7063 } else {
7064 *exparg.lastp = NULL;
7065 *savelastp = sp = expsort(*savelastp);
7066 while (sp->next != NULL)
7067 sp = sp->next;
7068 exparg.lastp = &sp->next;
7069 }
7070 str = str->next;
7071 }
7072}
7073
7074/*
7075 * Perform variable substitution and command substitution on an argument,
7076 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
7077 * perform splitting and file name expansion. When arglist is NULL, perform
7078 * here document expansion.
7079 */
7080static void
7081expandarg(union node *arg, struct arglist *arglist, int flag)
7082{
7083 struct strlist *sp;
7084 char *p;
7085
7086 argbackq = arg->narg.backquote;
7087 STARTSTACKSTR(expdest);
7088 ifsfirst.next = NULL;
7089 ifslastp = NULL;
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00007090 argstr(arg->narg.text, flag,
7091 /* var_str_list: */ arglist ? arglist->list : NULL);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007092 p = _STPUTC('\0', expdest);
7093 expdest = p - 1;
7094 if (arglist == NULL) {
7095 return; /* here document expanded */
7096 }
7097 p = grabstackstr(p);
7098 exparg.lastp = &exparg.list;
7099 /*
7100 * TODO - EXP_REDIR
7101 */
7102 if (flag & EXP_FULL) {
7103 ifsbreakup(p, &exparg);
7104 *exparg.lastp = NULL;
7105 exparg.lastp = &exparg.list;
Denis Vlasenko68404f12008-03-17 09:00:54 +00007106 expandmeta(exparg.list /*, flag*/);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007107 } else {
7108 if (flag & EXP_REDIR) /*XXX - for now, just remove escapes */
Denys Vlasenkob6c84342009-08-29 20:23:20 +02007109 rmescapes(p, 0);
Denis Vlasenko597906c2008-02-20 16:38:54 +00007110 sp = stzalloc(sizeof(*sp));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007111 sp->text = p;
7112 *exparg.lastp = sp;
7113 exparg.lastp = &sp->next;
7114 }
7115 if (ifsfirst.next)
7116 ifsfree();
7117 *exparg.lastp = NULL;
7118 if (exparg.list) {
7119 *arglist->lastp = exparg.list;
7120 arglist->lastp = exparg.lastp;
7121 }
7122}
7123
7124/*
7125 * Expand shell variables and backquotes inside a here document.
7126 */
7127static void
7128expandhere(union node *arg, int fd)
7129{
7130 herefd = fd;
7131 expandarg(arg, (struct arglist *)NULL, 0);
7132 full_write(fd, stackblock(), expdest - (char *)stackblock());
7133}
7134
7135/*
7136 * Returns true if the pattern matches the string.
7137 */
7138static int
7139patmatch(char *pattern, const char *string)
7140{
7141 return pmatch(preglob(pattern, 0, 0), string);
7142}
7143
7144/*
7145 * See if a pattern matches in a case statement.
7146 */
7147static int
7148casematch(union node *pattern, char *val)
7149{
7150 struct stackmark smark;
7151 int result;
7152
7153 setstackmark(&smark);
7154 argbackq = pattern->narg.backquote;
7155 STARTSTACKSTR(expdest);
7156 ifslastp = NULL;
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00007157 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE,
7158 /* var_str_list: */ NULL);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007159 STACKSTRNUL(expdest);
7160 result = patmatch(stackblock(), val);
7161 popstackmark(&smark);
7162 return result;
7163}
7164
7165
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007166/* ============ find_command */
7167
7168struct builtincmd {
7169 const char *name;
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007170 int (*builtin)(int, char **) FAST_FUNC;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007171 /* unsigned flags; */
7172};
7173#define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
Denis Vlasenkoe26b2782008-02-12 07:40:29 +00007174/* "regular" builtins always take precedence over commands,
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007175 * regardless of PATH=....%builtin... position */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007176#define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007177#define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007178
7179struct cmdentry {
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00007180 smallint cmdtype; /* CMDxxx */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007181 union param {
7182 int index;
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00007183 /* index >= 0 for commands without path (slashes) */
7184 /* (TODO: what exactly does the value mean? PATH position?) */
7185 /* index == -1 for commands with slashes */
7186 /* index == (-2 - applet_no) for NOFORK applets */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007187 const struct builtincmd *cmd;
7188 struct funcnode *func;
7189 } u;
7190};
7191/* values of cmdtype */
7192#define CMDUNKNOWN -1 /* no entry in table for command */
7193#define CMDNORMAL 0 /* command is an executable program */
7194#define CMDFUNCTION 1 /* command is a shell function */
7195#define CMDBUILTIN 2 /* command is a shell builtin */
7196
7197/* action to find_command() */
7198#define DO_ERR 0x01 /* prints errors */
7199#define DO_ABS 0x02 /* checks absolute paths */
7200#define DO_NOFUNC 0x04 /* don't return shell functions, for command */
7201#define DO_ALTPATH 0x08 /* using alternate path */
7202#define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
7203
7204static void find_command(char *, struct cmdentry *, int, const char *);
7205
7206
7207/* ============ Hashing commands */
7208
7209/*
7210 * When commands are first encountered, they are entered in a hash table.
7211 * This ensures that a full path search will not have to be done for them
7212 * on each invocation.
7213 *
7214 * We should investigate converting to a linear search, even though that
7215 * would make the command name "hash" a misnomer.
7216 */
7217
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007218struct tblentry {
7219 struct tblentry *next; /* next entry in hash chain */
7220 union param param; /* definition of builtin function */
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00007221 smallint cmdtype; /* CMDxxx */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007222 char rehash; /* if set, cd done since entry created */
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007223 char cmdname[1]; /* name of command */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007224};
7225
Denis Vlasenko01631112007-12-16 17:20:38 +00007226static struct tblentry **cmdtable;
7227#define INIT_G_cmdtable() do { \
7228 cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
7229} while (0)
7230
7231static int builtinloc = -1; /* index in path of %builtin, or -1 */
7232
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007233
7234static void
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00007235tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) char *cmd, char **argv, char **envp)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007236{
7237 int repeated = 0;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007238
Denis Vlasenko80d14be2007-04-10 23:03:30 +00007239#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007240 if (applet_no >= 0) {
Denis Vlasenkob7304742008-10-20 08:15:51 +00007241 if (APPLET_IS_NOEXEC(applet_no)) {
7242 while (*envp)
7243 putenv(*envp++);
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007244 run_applet_no_and_exit(applet_no, argv);
Denis Vlasenkob7304742008-10-20 08:15:51 +00007245 }
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007246 /* re-exec ourselves with the new arguments */
7247 execve(bb_busybox_exec_path, argv, envp);
7248 /* If they called chroot or otherwise made the binary no longer
7249 * executable, fall through */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007250 }
7251#endif
7252
7253 repeat:
7254#ifdef SYSV
7255 do {
7256 execve(cmd, argv, envp);
7257 } while (errno == EINTR);
7258#else
7259 execve(cmd, argv, envp);
7260#endif
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007261 if (repeated) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007262 free(argv);
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007263 return;
7264 }
7265 if (errno == ENOEXEC) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007266 char **ap;
7267 char **new;
7268
7269 for (ap = argv; *ap; ap++)
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007270 continue;
7271 ap = new = ckmalloc((ap - argv + 2) * sizeof(ap[0]));
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007272 ap[1] = cmd;
Denis Vlasenkoc44ab012007-04-09 03:11:58 +00007273 ap[0] = cmd = (char *)DEFAULT_SHELL;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007274 ap += 2;
7275 argv++;
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007276 while ((*ap++ = *argv++) != NULL)
Denis Vlasenko597906c2008-02-20 16:38:54 +00007277 continue;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007278 argv = new;
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007279 repeated++;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007280 goto repeat;
7281 }
7282}
7283
7284/*
7285 * Exec a program. Never returns. If you change this routine, you may
7286 * have to change the find_command routine as well.
7287 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00007288static void shellexec(char **, const char *, int) NORETURN;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007289static void
7290shellexec(char **argv, const char *path, int idx)
7291{
7292 char *cmdname;
7293 int e;
7294 char **envp;
7295 int exerrno;
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007296#if ENABLE_FEATURE_SH_STANDALONE
7297 int applet_no = -1;
7298#endif
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007299
Denis Vlasenko34c73c42008-08-16 11:48:02 +00007300 clearredir(/*drop:*/ 1);
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007301 envp = listvars(VEXPORT, VUNSET, 0);
7302 if (strchr(argv[0], '/') != NULL
Denis Vlasenko80d14be2007-04-10 23:03:30 +00007303#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007304 || (applet_no = find_applet_by_name(argv[0])) >= 0
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007305#endif
7306 ) {
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00007307 tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) argv[0], argv, envp);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007308 e = errno;
7309 } else {
7310 e = ENOENT;
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02007311 while ((cmdname = path_advance(&path, argv[0])) != NULL) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007312 if (--idx < 0 && pathopt == NULL) {
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00007313 tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007314 if (errno != ENOENT && errno != ENOTDIR)
7315 e = errno;
7316 }
7317 stunalloc(cmdname);
7318 }
7319 }
7320
7321 /* Map to POSIX errors */
7322 switch (e) {
7323 case EACCES:
7324 exerrno = 126;
7325 break;
7326 case ENOENT:
7327 exerrno = 127;
7328 break;
7329 default:
7330 exerrno = 2;
7331 break;
7332 }
7333 exitstatus = exerrno;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02007334 TRACE(("shellexec failed for %s, errno %d, suppress_int %d\n",
7335 argv[0], e, suppress_int));
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007336 ash_msg_and_raise(EXEXEC, "%s: %s", argv[0], errmsg(e, "not found"));
7337 /* NOTREACHED */
7338}
7339
7340static void
7341printentry(struct tblentry *cmdp)
7342{
7343 int idx;
7344 const char *path;
7345 char *name;
7346
7347 idx = cmdp->param.index;
7348 path = pathval();
7349 do {
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02007350 name = path_advance(&path, cmdp->cmdname);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007351 stunalloc(name);
7352 } while (--idx >= 0);
7353 out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
7354}
7355
7356/*
7357 * Clear out command entries. The argument specifies the first entry in
7358 * PATH which has changed.
7359 */
7360static void
7361clearcmdentry(int firstchange)
7362{
7363 struct tblentry **tblp;
7364 struct tblentry **pp;
7365 struct tblentry *cmdp;
7366
7367 INT_OFF;
7368 for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
7369 pp = tblp;
7370 while ((cmdp = *pp) != NULL) {
7371 if ((cmdp->cmdtype == CMDNORMAL &&
7372 cmdp->param.index >= firstchange)
7373 || (cmdp->cmdtype == CMDBUILTIN &&
7374 builtinloc >= firstchange)
7375 ) {
7376 *pp = cmdp->next;
7377 free(cmdp);
7378 } else {
7379 pp = &cmdp->next;
7380 }
7381 }
7382 }
7383 INT_ON;
7384}
7385
7386/*
7387 * Locate a command in the command hash table. If "add" is nonzero,
7388 * add the command to the table if it is not already present. The
7389 * variable "lastcmdentry" is set to point to the address of the link
7390 * pointing to the entry, so that delete_cmd_entry can delete the
7391 * entry.
7392 *
7393 * Interrupts must be off if called with add != 0.
7394 */
7395static struct tblentry **lastcmdentry;
7396
7397static struct tblentry *
7398cmdlookup(const char *name, int add)
7399{
7400 unsigned int hashval;
7401 const char *p;
7402 struct tblentry *cmdp;
7403 struct tblentry **pp;
7404
7405 p = name;
7406 hashval = (unsigned char)*p << 4;
7407 while (*p)
7408 hashval += (unsigned char)*p++;
7409 hashval &= 0x7FFF;
7410 pp = &cmdtable[hashval % CMDTABLESIZE];
7411 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7412 if (strcmp(cmdp->cmdname, name) == 0)
7413 break;
7414 pp = &cmdp->next;
7415 }
7416 if (add && cmdp == NULL) {
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007417 cmdp = *pp = ckzalloc(sizeof(struct tblentry)
7418 + strlen(name)
7419 /* + 1 - already done because
7420 * tblentry::cmdname is char[1] */);
Denis Vlasenko597906c2008-02-20 16:38:54 +00007421 /*cmdp->next = NULL; - ckzalloc did it */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007422 cmdp->cmdtype = CMDUNKNOWN;
7423 strcpy(cmdp->cmdname, name);
7424 }
7425 lastcmdentry = pp;
7426 return cmdp;
7427}
7428
7429/*
7430 * Delete the command entry returned on the last lookup.
7431 */
7432static void
7433delete_cmd_entry(void)
7434{
7435 struct tblentry *cmdp;
7436
7437 INT_OFF;
7438 cmdp = *lastcmdentry;
7439 *lastcmdentry = cmdp->next;
7440 if (cmdp->cmdtype == CMDFUNCTION)
7441 freefunc(cmdp->param.func);
7442 free(cmdp);
7443 INT_ON;
7444}
7445
7446/*
7447 * Add a new command entry, replacing any existing command entry for
7448 * the same name - except special builtins.
7449 */
7450static void
7451addcmdentry(char *name, struct cmdentry *entry)
7452{
7453 struct tblentry *cmdp;
7454
7455 cmdp = cmdlookup(name, 1);
7456 if (cmdp->cmdtype == CMDFUNCTION) {
7457 freefunc(cmdp->param.func);
7458 }
7459 cmdp->cmdtype = entry->cmdtype;
7460 cmdp->param = entry->u;
7461 cmdp->rehash = 0;
7462}
7463
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007464static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00007465hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007466{
7467 struct tblentry **pp;
7468 struct tblentry *cmdp;
7469 int c;
7470 struct cmdentry entry;
7471 char *name;
7472
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007473 if (nextopt("r") != '\0') {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007474 clearcmdentry(0);
7475 return 0;
7476 }
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007477
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007478 if (*argptr == NULL) {
7479 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7480 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7481 if (cmdp->cmdtype == CMDNORMAL)
7482 printentry(cmdp);
7483 }
7484 }
7485 return 0;
7486 }
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007487
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007488 c = 0;
7489 while ((name = *argptr) != NULL) {
7490 cmdp = cmdlookup(name, 0);
7491 if (cmdp != NULL
7492 && (cmdp->cmdtype == CMDNORMAL
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007493 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
7494 ) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007495 delete_cmd_entry();
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007496 }
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007497 find_command(name, &entry, DO_ERR, pathval());
7498 if (entry.cmdtype == CMDUNKNOWN)
7499 c = 1;
7500 argptr++;
7501 }
7502 return c;
7503}
7504
7505/*
7506 * Called when a cd is done. Marks all commands so the next time they
7507 * are executed they will be rehashed.
7508 */
7509static void
7510hashcd(void)
7511{
7512 struct tblentry **pp;
7513 struct tblentry *cmdp;
7514
7515 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7516 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007517 if (cmdp->cmdtype == CMDNORMAL
7518 || (cmdp->cmdtype == CMDBUILTIN
7519 && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
7520 && builtinloc > 0)
7521 ) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007522 cmdp->rehash = 1;
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007523 }
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007524 }
7525 }
7526}
7527
7528/*
7529 * Fix command hash table when PATH changed.
7530 * Called before PATH is changed. The argument is the new value of PATH;
7531 * pathval() still returns the old value at this point.
7532 * Called with interrupts off.
7533 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007534static void FAST_FUNC
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007535changepath(const char *new)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007536{
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007537 const char *old;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007538 int firstchange;
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007539 int idx;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007540 int idx_bltin;
7541
7542 old = pathval();
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007543 firstchange = 9999; /* assume no change */
7544 idx = 0;
7545 idx_bltin = -1;
7546 for (;;) {
7547 if (*old != *new) {
7548 firstchange = idx;
7549 if ((*old == '\0' && *new == ':')
7550 || (*old == ':' && *new == '\0'))
7551 firstchange++;
7552 old = new; /* ignore subsequent differences */
7553 }
7554 if (*new == '\0')
7555 break;
7556 if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
7557 idx_bltin = idx;
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007558 if (*new == ':')
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007559 idx++;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007560 new++, old++;
7561 }
7562 if (builtinloc < 0 && idx_bltin >= 0)
7563 builtinloc = idx_bltin; /* zap builtins */
7564 if (builtinloc >= 0 && idx_bltin < 0)
7565 firstchange = 0;
7566 clearcmdentry(firstchange);
7567 builtinloc = idx_bltin;
7568}
7569
7570#define TEOF 0
7571#define TNL 1
7572#define TREDIR 2
7573#define TWORD 3
7574#define TSEMI 4
7575#define TBACKGND 5
7576#define TAND 6
7577#define TOR 7
7578#define TPIPE 8
7579#define TLP 9
7580#define TRP 10
7581#define TENDCASE 11
7582#define TENDBQUOTE 12
7583#define TNOT 13
7584#define TCASE 14
7585#define TDO 15
7586#define TDONE 16
7587#define TELIF 17
7588#define TELSE 18
7589#define TESAC 19
7590#define TFI 20
7591#define TFOR 21
7592#define TIF 22
7593#define TIN 23
7594#define TTHEN 24
7595#define TUNTIL 25
7596#define TWHILE 26
7597#define TBEGIN 27
7598#define TEND 28
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007599typedef smallint token_id_t;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007600
7601/* first char is indicating which tokens mark the end of a list */
7602static const char *const tokname_array[] = {
7603 "\1end of file",
7604 "\0newline",
7605 "\0redirection",
7606 "\0word",
7607 "\0;",
7608 "\0&",
7609 "\0&&",
7610 "\0||",
7611 "\0|",
7612 "\0(",
7613 "\1)",
7614 "\1;;",
7615 "\1`",
7616#define KWDOFFSET 13
7617 /* the following are keywords */
7618 "\0!",
7619 "\0case",
7620 "\1do",
7621 "\1done",
7622 "\1elif",
7623 "\1else",
7624 "\1esac",
7625 "\1fi",
7626 "\0for",
7627 "\0if",
7628 "\0in",
7629 "\1then",
7630 "\0until",
7631 "\0while",
7632 "\0{",
7633 "\1}",
7634};
7635
7636static const char *
7637tokname(int tok)
7638{
7639 static char buf[16];
7640
Denis Vlasenko240a1cf2007-04-08 16:07:02 +00007641//try this:
7642//if (tok < TSEMI) return tokname_array[tok] + 1;
7643//sprintf(buf, "\"%s\"", tokname_array[tok] + 1);
7644//return buf;
7645
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007646 if (tok >= TSEMI)
7647 buf[0] = '"';
7648 sprintf(buf + (tok >= TSEMI), "%s%c",
7649 tokname_array[tok] + 1, (tok >= TSEMI ? '"' : 0));
7650 return buf;
7651}
7652
7653/* 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);
8448 if (!backgnd && flags & EV_EXIT && !trap[0])
8449 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) {
Denis Vlasenkob012b102007-02-19 22:43:01 +00008453 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00008454 flags |= EV_EXIT;
8455 if (backgnd)
8456 flags &=~ EV_TESTED;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00008457 nofork:
Eric Andersenc470f442003-07-28 09:56:35 +00008458 redirect(n->nredir.redirect, 0);
8459 evaltreenr(n->nredir.n, flags);
8460 /* never returns */
8461 }
8462 status = 0;
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00008463 if (!backgnd)
Eric Andersenc470f442003-07-28 09:56:35 +00008464 status = waitforjob(jp);
8465 exitstatus = status;
Denis Vlasenkob012b102007-02-19 22:43:01 +00008466 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00008467}
8468
Eric Andersenc470f442003-07-28 09:56:35 +00008469/*
8470 * Compute the names of the files in a redirection list.
8471 */
Denis Vlasenko99eb8502007-02-23 21:09:49 +00008472static void fixredir(union node *, const char *, int);
Eric Andersenc470f442003-07-28 09:56:35 +00008473static void
8474expredir(union node *n)
8475{
8476 union node *redir;
8477
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008478 for (redir = n; redir; redir = redir->nfile.next) {
Eric Andersenc470f442003-07-28 09:56:35 +00008479 struct arglist fn;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008480
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00008481 fn.list = NULL;
Eric Andersenc470f442003-07-28 09:56:35 +00008482 fn.lastp = &fn.list;
8483 switch (redir->type) {
8484 case NFROMTO:
8485 case NFROM:
8486 case NTO:
Denis Vlasenko559691a2008-10-05 18:39:31 +00008487#if ENABLE_ASH_BASH_COMPAT
8488 case NTO2:
8489#endif
Eric Andersenc470f442003-07-28 09:56:35 +00008490 case NCLOBBER:
8491 case NAPPEND:
8492 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
Denis Vlasenko559691a2008-10-05 18:39:31 +00008493#if ENABLE_ASH_BASH_COMPAT
8494 store_expfname:
8495#endif
Eric Andersenc470f442003-07-28 09:56:35 +00008496 redir->nfile.expfname = fn.list->text;
8497 break;
8498 case NFROMFD:
Denis Vlasenko559691a2008-10-05 18:39:31 +00008499 case NTOFD: /* >& */
Eric Andersenc470f442003-07-28 09:56:35 +00008500 if (redir->ndup.vname) {
8501 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008502 if (fn.list == NULL)
Denis Vlasenkob012b102007-02-19 22:43:01 +00008503 ash_msg_and_raise_error("redir error");
Denis Vlasenko559691a2008-10-05 18:39:31 +00008504#if ENABLE_ASH_BASH_COMPAT
8505//FIXME: we used expandarg with different args!
8506 if (!isdigit_str9(fn.list->text)) {
8507 /* >&file, not >&fd */
8508 if (redir->nfile.fd != 1) /* 123>&file - BAD */
8509 ash_msg_and_raise_error("redir error");
8510 redir->type = NTO2;
8511 goto store_expfname;
8512 }
8513#endif
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008514 fixredir(redir, fn.list->text, 1);
Eric Andersenc470f442003-07-28 09:56:35 +00008515 }
8516 break;
8517 }
8518 }
8519}
8520
Eric Andersencb57d552001-06-28 07:25:16 +00008521/*
Eric Andersencb57d552001-06-28 07:25:16 +00008522 * Evaluate a pipeline. All the processes in the pipeline are children
8523 * of the process creating the pipeline. (This differs from some versions
8524 * of the shell, which make the last process in a pipeline the parent
8525 * of all the rest.)
8526 */
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008527static void
Eric Andersenc470f442003-07-28 09:56:35 +00008528evalpipe(union node *n, int flags)
Eric Andersencb57d552001-06-28 07:25:16 +00008529{
8530 struct job *jp;
8531 struct nodelist *lp;
8532 int pipelen;
8533 int prevfd;
8534 int pip[2];
8535
Eric Andersenc470f442003-07-28 09:56:35 +00008536 TRACE(("evalpipe(0x%lx) called\n", (long)n));
Eric Andersencb57d552001-06-28 07:25:16 +00008537 pipelen = 0;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008538 for (lp = n->npipe.cmdlist; lp; lp = lp->next)
Eric Andersencb57d552001-06-28 07:25:16 +00008539 pipelen++;
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008540 flags |= EV_EXIT;
Denis Vlasenkob012b102007-02-19 22:43:01 +00008541 INT_OFF;
Denis Vlasenko68404f12008-03-17 09:00:54 +00008542 jp = makejob(/*n,*/ pipelen);
Eric Andersencb57d552001-06-28 07:25:16 +00008543 prevfd = -1;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008544 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008545 prehash(lp->n);
Eric Andersencb57d552001-06-28 07:25:16 +00008546 pip[1] = -1;
8547 if (lp->next) {
8548 if (pipe(pip) < 0) {
8549 close(prevfd);
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00008550 ash_msg_and_raise_error("pipe call failed");
Eric Andersencb57d552001-06-28 07:25:16 +00008551 }
8552 }
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00008553 if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
Denis Vlasenkob012b102007-02-19 22:43:01 +00008554 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00008555 if (pip[1] >= 0) {
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008556 close(pip[0]);
Eric Andersencb57d552001-06-28 07:25:16 +00008557 }
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008558 if (prevfd > 0) {
8559 dup2(prevfd, 0);
8560 close(prevfd);
8561 }
8562 if (pip[1] > 1) {
8563 dup2(pip[1], 1);
8564 close(pip[1]);
8565 }
Eric Andersenc470f442003-07-28 09:56:35 +00008566 evaltreenr(lp->n, flags);
8567 /* never returns */
Eric Andersencb57d552001-06-28 07:25:16 +00008568 }
8569 if (prevfd >= 0)
8570 close(prevfd);
8571 prevfd = pip[0];
Denis Vlasenkob9e70dd2009-03-20 01:24:08 +00008572 /* Don't want to trigger debugging */
8573 if (pip[1] != -1)
8574 close(pip[1]);
Eric Andersencb57d552001-06-28 07:25:16 +00008575 }
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00008576 if (n->npipe.pipe_backgnd == 0) {
Eric Andersencb57d552001-06-28 07:25:16 +00008577 exitstatus = waitforjob(jp);
8578 TRACE(("evalpipe: job done exit status %d\n", exitstatus));
Eric Andersencb57d552001-06-28 07:25:16 +00008579 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00008580 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00008581}
8582
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008583/*
8584 * Controls whether the shell is interactive or not.
8585 */
8586static void
8587setinteractive(int on)
8588{
Denis Vlasenkob07a4962008-06-22 13:16:23 +00008589 static smallint is_interactive;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008590
8591 if (++on == is_interactive)
8592 return;
8593 is_interactive = on;
8594 setsignal(SIGINT);
8595 setsignal(SIGQUIT);
8596 setsignal(SIGTERM);
8597#if !ENABLE_FEATURE_SH_EXTRA_QUIET
8598 if (is_interactive > 1) {
8599 /* Looks like they want an interactive shell */
Denis Vlasenkoca525b42007-06-13 12:27:17 +00008600 static smallint did_banner;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008601
Denis Vlasenkoca525b42007-06-13 12:27:17 +00008602 if (!did_banner) {
Denys Vlasenkoc34c0332009-09-29 12:25:30 +02008603 /* note: ash and hush share this string */
8604 out1fmt("\n\n%s %s\n"
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008605 "Enter 'help' for a list of built-in commands."
8606 "\n\n",
Denys Vlasenkoc34c0332009-09-29 12:25:30 +02008607 bb_banner,
8608 "built-in shell (ash)"
8609 );
Denis Vlasenkoca525b42007-06-13 12:27:17 +00008610 did_banner = 1;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008611 }
8612 }
8613#endif
8614}
8615
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008616static void
8617optschanged(void)
8618{
8619#if DEBUG
8620 opentrace();
8621#endif
8622 setinteractive(iflag);
8623 setjobctl(mflag);
Denis Vlasenkob07a4962008-06-22 13:16:23 +00008624#if ENABLE_FEATURE_EDITING_VI
8625 if (viflag)
8626 line_input_state->flags |= VI_MODE;
8627 else
8628 line_input_state->flags &= ~VI_MODE;
8629#else
8630 viflag = 0; /* forcibly keep the option off */
8631#endif
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008632}
8633
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008634static struct localvar *localvars;
8635
8636/*
8637 * Called after a function returns.
8638 * Interrupts must be off.
8639 */
8640static void
8641poplocalvars(void)
8642{
8643 struct localvar *lvp;
8644 struct var *vp;
8645
8646 while ((lvp = localvars) != NULL) {
8647 localvars = lvp->next;
8648 vp = lvp->vp;
Denys Vlasenko883cea42009-07-11 15:31:59 +02008649 TRACE(("poplocalvar %s\n", vp ? vp->text : "-"));
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008650 if (vp == NULL) { /* $- saved */
8651 memcpy(optlist, lvp->text, sizeof(optlist));
8652 free((char*)lvp->text);
8653 optschanged();
8654 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
8655 unsetvar(vp->text);
8656 } else {
8657 if (vp->func)
8658 (*vp->func)(strchrnul(lvp->text, '=') + 1);
8659 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
8660 free((char*)vp->text);
8661 vp->flags = lvp->flags;
8662 vp->text = lvp->text;
8663 }
8664 free(lvp);
8665 }
8666}
8667
8668static int
8669evalfun(struct funcnode *func, int argc, char **argv, int flags)
8670{
8671 volatile struct shparam saveparam;
8672 struct localvar *volatile savelocalvars;
8673 struct jmploc *volatile savehandler;
8674 struct jmploc jmploc;
8675 int e;
8676
8677 saveparam = shellparam;
8678 savelocalvars = localvars;
8679 e = setjmp(jmploc.loc);
8680 if (e) {
8681 goto funcdone;
8682 }
8683 INT_OFF;
8684 savehandler = exception_handler;
8685 exception_handler = &jmploc;
8686 localvars = NULL;
Denis Vlasenko01631112007-12-16 17:20:38 +00008687 shellparam.malloced = 0;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008688 func->count++;
8689 funcnest++;
8690 INT_ON;
8691 shellparam.nparam = argc - 1;
8692 shellparam.p = argv + 1;
8693#if ENABLE_ASH_GETOPTS
8694 shellparam.optind = 1;
8695 shellparam.optoff = -1;
8696#endif
8697 evaltree(&func->n, flags & EV_TESTED);
Denis Vlasenko01631112007-12-16 17:20:38 +00008698 funcdone:
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008699 INT_OFF;
8700 funcnest--;
8701 freefunc(func);
8702 poplocalvars();
8703 localvars = savelocalvars;
8704 freeparam(&shellparam);
8705 shellparam = saveparam;
8706 exception_handler = savehandler;
8707 INT_ON;
8708 evalskip &= ~SKIPFUNC;
8709 return e;
8710}
8711
Denis Vlasenko131ae172007-02-18 13:00:19 +00008712#if ENABLE_ASH_CMDCMD
Denis Vlasenkoaa744452007-02-23 01:04:22 +00008713static char **
8714parse_command_args(char **argv, const char **path)
Eric Andersenc470f442003-07-28 09:56:35 +00008715{
8716 char *cp, c;
8717
8718 for (;;) {
8719 cp = *++argv;
8720 if (!cp)
8721 return 0;
8722 if (*cp++ != '-')
8723 break;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008724 c = *cp++;
8725 if (!c)
Eric Andersenc470f442003-07-28 09:56:35 +00008726 break;
8727 if (c == '-' && !*cp) {
8728 argv++;
8729 break;
8730 }
8731 do {
8732 switch (c) {
8733 case 'p':
Denis Vlasenkof5f75c52007-06-12 22:35:19 +00008734 *path = bb_default_path;
Eric Andersenc470f442003-07-28 09:56:35 +00008735 break;
8736 default:
8737 /* run 'typecmd' for other options */
8738 return 0;
8739 }
Denis Vlasenko9650f362007-02-23 01:04:37 +00008740 c = *cp++;
8741 } while (c);
Eric Andersenc470f442003-07-28 09:56:35 +00008742 }
8743 return argv;
8744}
8745#endif
8746
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008747/*
8748 * Make a variable a local variable. When a variable is made local, it's
8749 * value and flags are saved in a localvar structure. The saved values
8750 * will be restored when the shell function returns. We handle the name
8751 * "-" as a special case.
8752 */
8753static void
8754mklocal(char *name)
8755{
8756 struct localvar *lvp;
8757 struct var **vpp;
8758 struct var *vp;
8759
8760 INT_OFF;
Denis Vlasenko838ffd52008-02-21 04:32:08 +00008761 lvp = ckzalloc(sizeof(struct localvar));
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008762 if (LONE_DASH(name)) {
8763 char *p;
8764 p = ckmalloc(sizeof(optlist));
8765 lvp->text = memcpy(p, optlist, sizeof(optlist));
8766 vp = NULL;
8767 } else {
8768 char *eq;
8769
8770 vpp = hashvar(name);
8771 vp = *findvar(vpp, name);
8772 eq = strchr(name, '=');
8773 if (vp == NULL) {
8774 if (eq)
8775 setvareq(name, VSTRFIXED);
8776 else
8777 setvar(name, NULL, VSTRFIXED);
8778 vp = *vpp; /* the new variable */
8779 lvp->flags = VUNSET;
8780 } else {
8781 lvp->text = vp->text;
8782 lvp->flags = vp->flags;
8783 vp->flags |= VSTRFIXED|VTEXTFIXED;
8784 if (eq)
8785 setvareq(name, 0);
8786 }
8787 }
8788 lvp->vp = vp;
8789 lvp->next = localvars;
8790 localvars = lvp;
8791 INT_ON;
8792}
8793
8794/*
8795 * The "local" command.
8796 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008797static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008798localcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008799{
8800 char *name;
8801
8802 argv = argptr;
8803 while ((name = *argv++) != NULL) {
8804 mklocal(name);
8805 }
8806 return 0;
8807}
8808
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008809static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008810falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008811{
8812 return 1;
8813}
8814
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008815static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008816truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008817{
8818 return 0;
8819}
8820
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008821static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008822execcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008823{
Denis Vlasenko68404f12008-03-17 09:00:54 +00008824 if (argv[1]) {
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008825 iflag = 0; /* exit on error */
8826 mflag = 0;
8827 optschanged();
8828 shellexec(argv + 1, pathval(), 0);
8829 }
8830 return 0;
8831}
8832
8833/*
8834 * The return command.
8835 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008836static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008837returncmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008838{
8839 /*
8840 * If called outside a function, do what ksh does;
8841 * skip the rest of the file.
8842 */
8843 evalskip = funcnest ? SKIPFUNC : SKIPFILE;
8844 return argv[1] ? number(argv[1]) : exitstatus;
8845}
8846
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008847/* Forward declarations for builtintab[] */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008848static int breakcmd(int, char **) FAST_FUNC;
8849static int dotcmd(int, char **) FAST_FUNC;
8850static int evalcmd(int, char **) FAST_FUNC;
8851static int exitcmd(int, char **) FAST_FUNC;
8852static int exportcmd(int, char **) FAST_FUNC;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008853#if ENABLE_ASH_GETOPTS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008854static int getoptscmd(int, char **) FAST_FUNC;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008855#endif
Denis Vlasenko52764022007-02-24 13:42:56 +00008856#if !ENABLE_FEATURE_SH_EXTRA_QUIET
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008857static int helpcmd(int, char **) FAST_FUNC;
Denis Vlasenko52764022007-02-24 13:42:56 +00008858#endif
Mike Frysinger98c52642009-04-02 10:02:37 +00008859#if ENABLE_SH_MATH_SUPPORT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008860static int letcmd(int, char **) FAST_FUNC;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008861#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008862static int readcmd(int, char **) FAST_FUNC;
8863static int setcmd(int, char **) FAST_FUNC;
8864static int shiftcmd(int, char **) FAST_FUNC;
8865static int timescmd(int, char **) FAST_FUNC;
8866static int trapcmd(int, char **) FAST_FUNC;
8867static int umaskcmd(int, char **) FAST_FUNC;
8868static int unsetcmd(int, char **) FAST_FUNC;
8869static int ulimitcmd(int, char **) FAST_FUNC;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008870
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008871#define BUILTIN_NOSPEC "0"
8872#define BUILTIN_SPECIAL "1"
8873#define BUILTIN_REGULAR "2"
8874#define BUILTIN_SPEC_REG "3"
8875#define BUILTIN_ASSIGN "4"
8876#define BUILTIN_SPEC_ASSG "5"
8877#define BUILTIN_REG_ASSG "6"
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008878#define BUILTIN_SPEC_REG_ASSG "7"
8879
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008880/* Stubs for calling non-FAST_FUNC's */
Denys Vlasenko2634bf32009-06-09 18:40:07 +02008881#if ENABLE_ASH_BUILTIN_ECHO
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008882static int FAST_FUNC echocmd(int argc, char **argv) { return echo_main(argc, argv); }
Denys Vlasenko2634bf32009-06-09 18:40:07 +02008883#endif
8884#if ENABLE_ASH_BUILTIN_PRINTF
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008885static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
Denys Vlasenko2634bf32009-06-09 18:40:07 +02008886#endif
8887#if ENABLE_ASH_BUILTIN_TEST
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008888static int FAST_FUNC testcmd(int argc, char **argv) { return test_main(argc, argv); }
Denys Vlasenko2634bf32009-06-09 18:40:07 +02008889#endif
Denis Vlasenko468aea22008-04-01 14:47:57 +00008890
Denis Vlasenkof7d56652008-03-25 05:51:41 +00008891/* Keep these in proper order since it is searched via bsearch() */
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008892static const struct builtincmd builtintab[] = {
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008893 { BUILTIN_SPEC_REG "." , dotcmd },
8894 { BUILTIN_SPEC_REG ":" , truecmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008895#if ENABLE_ASH_BUILTIN_TEST
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008896 { BUILTIN_REGULAR "[" , testcmd },
Denis Vlasenko80591b02008-03-25 07:49:43 +00008897#if ENABLE_ASH_BASH_COMPAT
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008898 { BUILTIN_REGULAR "[[" , testcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008899#endif
Denis Vlasenko80591b02008-03-25 07:49:43 +00008900#endif
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008901#if ENABLE_ASH_ALIAS
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008902 { BUILTIN_REG_ASSG "alias" , aliascmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008903#endif
8904#if JOBS
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008905 { BUILTIN_REGULAR "bg" , fg_bgcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008906#endif
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008907 { BUILTIN_SPEC_REG "break" , breakcmd },
8908 { BUILTIN_REGULAR "cd" , cdcmd },
8909 { BUILTIN_NOSPEC "chdir" , cdcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008910#if ENABLE_ASH_CMDCMD
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008911 { BUILTIN_REGULAR "command" , commandcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008912#endif
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008913 { BUILTIN_SPEC_REG "continue", breakcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008914#if ENABLE_ASH_BUILTIN_ECHO
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008915 { BUILTIN_REGULAR "echo" , echocmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008916#endif
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008917 { BUILTIN_SPEC_REG "eval" , evalcmd },
8918 { BUILTIN_SPEC_REG "exec" , execcmd },
8919 { BUILTIN_SPEC_REG "exit" , exitcmd },
8920 { BUILTIN_SPEC_REG_ASSG "export" , exportcmd },
8921 { BUILTIN_REGULAR "false" , falsecmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008922#if JOBS
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008923 { BUILTIN_REGULAR "fg" , fg_bgcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008924#endif
8925#if ENABLE_ASH_GETOPTS
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008926 { BUILTIN_REGULAR "getopts" , getoptscmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008927#endif
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008928 { BUILTIN_NOSPEC "hash" , hashcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008929#if !ENABLE_FEATURE_SH_EXTRA_QUIET
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008930 { BUILTIN_NOSPEC "help" , helpcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008931#endif
8932#if JOBS
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008933 { BUILTIN_REGULAR "jobs" , jobscmd },
8934 { BUILTIN_REGULAR "kill" , killcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008935#endif
Mike Frysinger98c52642009-04-02 10:02:37 +00008936#if ENABLE_SH_MATH_SUPPORT
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008937 { BUILTIN_NOSPEC "let" , letcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008938#endif
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008939 { BUILTIN_ASSIGN "local" , localcmd },
Denis Vlasenkocd2663f2008-06-01 22:36:39 +00008940#if ENABLE_ASH_BUILTIN_PRINTF
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008941 { BUILTIN_REGULAR "printf" , printfcmd },
Denis Vlasenkocd2663f2008-06-01 22:36:39 +00008942#endif
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008943 { BUILTIN_NOSPEC "pwd" , pwdcmd },
8944 { BUILTIN_REGULAR "read" , readcmd },
8945 { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
8946 { BUILTIN_SPEC_REG "return" , returncmd },
8947 { BUILTIN_SPEC_REG "set" , setcmd },
8948 { BUILTIN_SPEC_REG "shift" , shiftcmd },
8949 { BUILTIN_SPEC_REG "source" , dotcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008950#if ENABLE_ASH_BUILTIN_TEST
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008951 { BUILTIN_REGULAR "test" , testcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008952#endif
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008953 { BUILTIN_SPEC_REG "times" , timescmd },
8954 { BUILTIN_SPEC_REG "trap" , trapcmd },
8955 { BUILTIN_REGULAR "true" , truecmd },
8956 { BUILTIN_NOSPEC "type" , typecmd },
8957 { BUILTIN_NOSPEC "ulimit" , ulimitcmd },
8958 { BUILTIN_REGULAR "umask" , umaskcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008959#if ENABLE_ASH_ALIAS
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008960 { BUILTIN_REGULAR "unalias" , unaliascmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008961#endif
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008962 { BUILTIN_SPEC_REG "unset" , unsetcmd },
8963 { BUILTIN_REGULAR "wait" , waitcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008964};
8965
Denis Vlasenko80591b02008-03-25 07:49:43 +00008966/* Should match the above table! */
8967#define COMMANDCMD (builtintab + \
8968 2 + \
8969 1 * ENABLE_ASH_BUILTIN_TEST + \
8970 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
8971 1 * ENABLE_ASH_ALIAS + \
8972 1 * ENABLE_ASH_JOB_CONTROL + \
8973 3)
8974#define EXECCMD (builtintab + \
8975 2 + \
8976 1 * ENABLE_ASH_BUILTIN_TEST + \
8977 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
8978 1 * ENABLE_ASH_ALIAS + \
8979 1 * ENABLE_ASH_JOB_CONTROL + \
8980 3 + \
8981 1 * ENABLE_ASH_CMDCMD + \
8982 1 + \
8983 ENABLE_ASH_BUILTIN_ECHO + \
8984 1)
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008985
8986/*
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008987 * Search the table of builtin commands.
8988 */
8989static struct builtincmd *
8990find_builtin(const char *name)
8991{
8992 struct builtincmd *bp;
8993
8994 bp = bsearch(
Denis Vlasenko80b8b392007-06-25 10:55:35 +00008995 name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008996 pstrcmp
8997 );
8998 return bp;
8999}
9000
9001/*
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00009002 * Execute a simple command.
9003 */
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00009004static int
9005isassignment(const char *p)
Paul Foxc3850c82005-07-20 18:23:39 +00009006{
9007 const char *q = endofname(p);
9008 if (p == q)
9009 return 0;
9010 return *q == '=';
9011}
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009012static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00009013bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00009014{
9015 /* Preserve exitstatus of a previous possible redirection
9016 * as POSIX mandates */
9017 return back_exitstatus;
9018}
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02009019static void
Eric Andersenc470f442003-07-28 09:56:35 +00009020evalcommand(union node *cmd, int flags)
9021{
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00009022 static const struct builtincmd null_bltin = {
9023 "\0\0", bltincmd /* why three NULs? */
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00009024 };
Eric Andersenc470f442003-07-28 09:56:35 +00009025 struct stackmark smark;
9026 union node *argp;
9027 struct arglist arglist;
9028 struct arglist varlist;
9029 char **argv;
9030 int argc;
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009031 const struct strlist *sp;
Eric Andersenc470f442003-07-28 09:56:35 +00009032 struct cmdentry cmdentry;
9033 struct job *jp;
9034 char *lastarg;
9035 const char *path;
9036 int spclbltin;
Eric Andersenc470f442003-07-28 09:56:35 +00009037 int status;
9038 char **nargv;
Paul Foxc3850c82005-07-20 18:23:39 +00009039 struct builtincmd *bcmd;
Denis Vlasenko34c73c42008-08-16 11:48:02 +00009040 smallint cmd_is_exec;
9041 smallint pseudovarflag = 0;
Eric Andersenc470f442003-07-28 09:56:35 +00009042
9043 /* First expand the arguments. */
9044 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
9045 setstackmark(&smark);
9046 back_exitstatus = 0;
9047
9048 cmdentry.cmdtype = CMDBUILTIN;
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00009049 cmdentry.u.cmd = &null_bltin;
Eric Andersenc470f442003-07-28 09:56:35 +00009050 varlist.lastp = &varlist.list;
9051 *varlist.lastp = NULL;
9052 arglist.lastp = &arglist.list;
9053 *arglist.lastp = NULL;
9054
9055 argc = 0;
Denis Vlasenkob012b102007-02-19 22:43:01 +00009056 if (cmd->ncmd.args) {
Paul Foxc3850c82005-07-20 18:23:39 +00009057 bcmd = find_builtin(cmd->ncmd.args->narg.text);
9058 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
9059 }
9060
Eric Andersenc470f442003-07-28 09:56:35 +00009061 for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
9062 struct strlist **spp;
9063
9064 spp = arglist.lastp;
"Vladimir N. Oleynik"bef14d72005-09-05 13:25:11 +00009065 if (pseudovarflag && isassignment(argp->narg.text))
Paul Foxc3850c82005-07-20 18:23:39 +00009066 expandarg(argp, &arglist, EXP_VARTILDE);
9067 else
9068 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
9069
Eric Andersenc470f442003-07-28 09:56:35 +00009070 for (sp = *spp; sp; sp = sp->next)
9071 argc++;
9072 }
9073
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +00009074 argv = nargv = stalloc(sizeof(char *) * (argc + 1));
Denis Vlasenko2da584f2007-02-19 22:44:05 +00009075 for (sp = arglist.list; sp; sp = sp->next) {
Eric Andersenc470f442003-07-28 09:56:35 +00009076 TRACE(("evalcommand arg: %s\n", sp->text));
9077 *nargv++ = sp->text;
9078 }
9079 *nargv = NULL;
9080
9081 lastarg = NULL;
9082 if (iflag && funcnest == 0 && argc > 0)
9083 lastarg = nargv[-1];
9084
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009085 preverrout_fd = 2;
Eric Andersenc470f442003-07-28 09:56:35 +00009086 expredir(cmd->ncmd.redirect);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009087 status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
Eric Andersenc470f442003-07-28 09:56:35 +00009088
9089 path = vpath.text;
9090 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
9091 struct strlist **spp;
9092 char *p;
9093
9094 spp = varlist.lastp;
9095 expandarg(argp, &varlist, EXP_VARTILDE);
9096
9097 /*
9098 * Modify the command lookup path, if a PATH= assignment
9099 * is present
9100 */
9101 p = (*spp)->text;
9102 if (varequal(p, path))
9103 path = p;
9104 }
9105
9106 /* Print the command if xflag is set. */
9107 if (xflag) {
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009108 int n;
9109 const char *p = " %s";
Eric Andersenc470f442003-07-28 09:56:35 +00009110
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009111 p++;
Denis Vlasenko0de37e12007-10-17 11:08:53 +00009112 fdprintf(preverrout_fd, p, expandstr(ps4val()));
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009113
9114 sp = varlist.list;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +00009115 for (n = 0; n < 2; n++) {
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009116 while (sp) {
Denis Vlasenko0de37e12007-10-17 11:08:53 +00009117 fdprintf(preverrout_fd, p, sp->text);
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009118 sp = sp->next;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +00009119 if (*p == '%') {
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009120 p--;
9121 }
9122 }
9123 sp = arglist.list;
9124 }
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00009125 safe_write(preverrout_fd, "\n", 1);
Eric Andersenc470f442003-07-28 09:56:35 +00009126 }
9127
9128 cmd_is_exec = 0;
9129 spclbltin = -1;
9130
9131 /* Now locate the command. */
9132 if (argc) {
9133 const char *oldpath;
9134 int cmd_flag = DO_ERR;
9135
9136 path += 5;
9137 oldpath = path;
9138 for (;;) {
9139 find_command(argv[0], &cmdentry, cmd_flag, path);
9140 if (cmdentry.cmdtype == CMDUNKNOWN) {
Denys Vlasenko8131eea2009-11-02 14:19:51 +01009141 flush_stdout_stderr();
Denis Vlasenko6514c5e2008-07-24 13:41:37 +00009142 status = 127;
Eric Andersenc470f442003-07-28 09:56:35 +00009143 goto bail;
9144 }
9145
9146 /* implement bltin and command here */
9147 if (cmdentry.cmdtype != CMDBUILTIN)
9148 break;
9149 if (spclbltin < 0)
9150 spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
9151 if (cmdentry.u.cmd == EXECCMD)
Denis Vlasenko34c73c42008-08-16 11:48:02 +00009152 cmd_is_exec = 1;
Denis Vlasenko131ae172007-02-18 13:00:19 +00009153#if ENABLE_ASH_CMDCMD
Eric Andersenc470f442003-07-28 09:56:35 +00009154 if (cmdentry.u.cmd == COMMANDCMD) {
Eric Andersenc470f442003-07-28 09:56:35 +00009155 path = oldpath;
9156 nargv = parse_command_args(argv, &path);
9157 if (!nargv)
9158 break;
9159 argc -= nargv - argv;
9160 argv = nargv;
9161 cmd_flag |= DO_NOFUNC;
9162 } else
9163#endif
9164 break;
9165 }
9166 }
9167
9168 if (status) {
9169 /* We have a redirection error. */
9170 if (spclbltin > 0)
Denis Vlasenkob012b102007-02-19 22:43:01 +00009171 raise_exception(EXERROR);
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009172 bail:
Eric Andersenc470f442003-07-28 09:56:35 +00009173 exitstatus = status;
9174 goto out;
9175 }
9176
9177 /* Execute the command. */
9178 switch (cmdentry.cmdtype) {
9179 default:
Denis Vlasenkobe54d6b2008-10-27 14:25:52 +00009180
Denis Vlasenko9bc80d72008-04-12 20:07:53 +00009181#if ENABLE_FEATURE_SH_NOFORK
Denis Vlasenkobe54d6b2008-10-27 14:25:52 +00009182/* Hmmm... shouldn't it happen somewhere in forkshell() instead?
9183 * Why "fork off a child process if necessary" doesn't apply to NOFORK? */
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00009184 {
9185 /* find_command() encodes applet_no as (-2 - applet_no) */
9186 int applet_no = (- cmdentry.u.index - 2);
Denis Vlasenko9bc80d72008-04-12 20:07:53 +00009187 if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
Denis Vlasenko9bc80d72008-04-12 20:07:53 +00009188 listsetvar(varlist.list, VEXPORT|VSTACK);
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00009189 /* run <applet>_main() */
9190 exitstatus = run_nofork_applet(applet_no, argv);
Denis Vlasenko9bc80d72008-04-12 20:07:53 +00009191 break;
9192 }
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00009193 }
Denis Vlasenko9bc80d72008-04-12 20:07:53 +00009194#endif
Eric Andersenc470f442003-07-28 09:56:35 +00009195 /* Fork off a child process if necessary. */
9196 if (!(flags & EV_EXIT) || trap[0]) {
Denis Vlasenkob012b102007-02-19 22:43:01 +00009197 INT_OFF;
Denis Vlasenko68404f12008-03-17 09:00:54 +00009198 jp = makejob(/*cmd,*/ 1);
Eric Andersenc470f442003-07-28 09:56:35 +00009199 if (forkshell(jp, cmd, FORK_FG) != 0) {
9200 exitstatus = waitforjob(jp);
Denis Vlasenkob012b102007-02-19 22:43:01 +00009201 INT_ON;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00009202 TRACE(("forked child exited with %d\n", exitstatus));
Eric Andersenc470f442003-07-28 09:56:35 +00009203 break;
9204 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00009205 FORCE_INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00009206 }
9207 listsetvar(varlist.list, VEXPORT|VSTACK);
9208 shellexec(argv, path, cmdentry.u.index);
9209 /* NOTREACHED */
9210
9211 case CMDBUILTIN:
9212 cmdenviron = varlist.list;
9213 if (cmdenviron) {
9214 struct strlist *list = cmdenviron;
9215 int i = VNOSET;
9216 if (spclbltin > 0 || argc == 0) {
9217 i = 0;
9218 if (cmd_is_exec && argc > 1)
9219 i = VEXPORT;
9220 }
9221 listsetvar(list, i);
9222 }
Denis Vlasenkobe54d6b2008-10-27 14:25:52 +00009223 /* Tight loop with builtins only:
9224 * "while kill -0 $child; do true; done"
9225 * will never exit even if $child died, unless we do this
9226 * to reap the zombie and make kill detect that it's gone: */
9227 dowait(DOWAIT_NONBLOCK, NULL);
9228
Eric Andersenc470f442003-07-28 09:56:35 +00009229 if (evalbltin(cmdentry.u.cmd, argc, argv)) {
9230 int exit_status;
Denis Vlasenko7f88e342009-03-19 03:36:18 +00009231 int i = exception_type;
Eric Andersenc470f442003-07-28 09:56:35 +00009232 if (i == EXEXIT)
9233 goto raise;
Eric Andersenc470f442003-07-28 09:56:35 +00009234 exit_status = 2;
Eric Andersenc470f442003-07-28 09:56:35 +00009235 if (i == EXINT)
Denis Vlasenko991a1da2008-02-10 19:02:53 +00009236 exit_status = 128 + SIGINT;
Eric Andersenc470f442003-07-28 09:56:35 +00009237 if (i == EXSIG)
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02009238 exit_status = 128 + pending_sig;
Eric Andersenc470f442003-07-28 09:56:35 +00009239 exitstatus = exit_status;
Eric Andersenc470f442003-07-28 09:56:35 +00009240 if (i == EXINT || spclbltin > 0) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009241 raise:
Denis Vlasenko2da584f2007-02-19 22:44:05 +00009242 longjmp(exception_handler->loc, 1);
Eric Andersenc470f442003-07-28 09:56:35 +00009243 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00009244 FORCE_INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00009245 }
9246 break;
9247
9248 case CMDFUNCTION:
9249 listsetvar(varlist.list, 0);
Denis Vlasenkobe54d6b2008-10-27 14:25:52 +00009250 /* See above for the rationale */
9251 dowait(DOWAIT_NONBLOCK, NULL);
Eric Andersenc470f442003-07-28 09:56:35 +00009252 if (evalfun(cmdentry.u.func, argc, argv, flags))
9253 goto raise;
9254 break;
9255 }
9256
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009257 out:
Denis Vlasenko34c73c42008-08-16 11:48:02 +00009258 popredir(/*drop:*/ cmd_is_exec, /*restore:*/ cmd_is_exec);
Denis Vlasenko6514c5e2008-07-24 13:41:37 +00009259 if (lastarg) {
Eric Andersenc470f442003-07-28 09:56:35 +00009260 /* dsl: I think this is intended to be used to support
9261 * '_' in 'vi' command mode during line editing...
9262 * However I implemented that within libedit itself.
9263 */
9264 setvar("_", lastarg, 0);
Denis Vlasenko6514c5e2008-07-24 13:41:37 +00009265 }
Eric Andersenc470f442003-07-28 09:56:35 +00009266 popstackmark(&smark);
9267}
9268
9269static int
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009270evalbltin(const struct builtincmd *cmd, int argc, char **argv)
9271{
Eric Andersenc470f442003-07-28 09:56:35 +00009272 char *volatile savecmdname;
9273 struct jmploc *volatile savehandler;
9274 struct jmploc jmploc;
9275 int i;
9276
9277 savecmdname = commandname;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009278 i = setjmp(jmploc.loc);
9279 if (i)
Eric Andersenc470f442003-07-28 09:56:35 +00009280 goto cmddone;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00009281 savehandler = exception_handler;
9282 exception_handler = &jmploc;
Eric Andersenc470f442003-07-28 09:56:35 +00009283 commandname = argv[0];
9284 argptr = argv + 1;
9285 optptr = NULL; /* initialize nextopt */
9286 exitstatus = (*cmd->builtin)(argc, argv);
Denis Vlasenkob012b102007-02-19 22:43:01 +00009287 flush_stdout_stderr();
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009288 cmddone:
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009289 exitstatus |= ferror(stdout);
Rob Landleyf296f0b2006-07-06 01:09:21 +00009290 clearerr(stdout);
Eric Andersenc470f442003-07-28 09:56:35 +00009291 commandname = savecmdname;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00009292 exception_handler = savehandler;
Eric Andersenc470f442003-07-28 09:56:35 +00009293
9294 return i;
9295}
9296
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009297static int
9298goodname(const char *p)
Glenn L McGrath16e45d72004-02-04 08:24:39 +00009299{
9300 return !*endofname(p);
9301}
9302
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009303
Glenn L McGrath50812ff2002-08-23 13:14:48 +00009304/*
9305 * Search for a command. This is called before we fork so that the
9306 * location of the command will be available in the parent as well as
Glenn L McGrath16e45d72004-02-04 08:24:39 +00009307 * the child. The check for "goodname" is an overly conservative
9308 * check that the name will not be subject to expansion.
Glenn L McGrath50812ff2002-08-23 13:14:48 +00009309 */
Eric Andersenc470f442003-07-28 09:56:35 +00009310static void
9311prehash(union node *n)
Glenn L McGrath50812ff2002-08-23 13:14:48 +00009312{
9313 struct cmdentry entry;
9314
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +00009315 if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
9316 find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
Glenn L McGrath50812ff2002-08-23 13:14:48 +00009317}
9318
Eric Andersencb57d552001-06-28 07:25:16 +00009319
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00009320/* ============ Builtin commands
9321 *
9322 * Builtin commands whose functions are closely tied to evaluation
9323 * are implemented here.
Eric Andersencb57d552001-06-28 07:25:16 +00009324 */
9325
9326/*
Eric Andersencb57d552001-06-28 07:25:16 +00009327 * Handle break and continue commands. Break, continue, and return are
9328 * all handled by setting the evalskip flag. The evaluation routines
9329 * above all check this flag, and if it is set they start skipping
9330 * commands rather than executing them. The variable skipcount is
9331 * the number of loops to break/continue, or the number of function
9332 * levels to return. (The latter is always 1.) It should probably
9333 * be an error to break out of more loops than exist, but it isn't
9334 * in the standard shell so we don't make it one here.
9335 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009336static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00009337breakcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +00009338{
Denis Vlasenko68404f12008-03-17 09:00:54 +00009339 int n = argv[1] ? number(argv[1]) : 1;
Eric Andersencb57d552001-06-28 07:25:16 +00009340
Aaron Lehmann2aef3a62001-12-31 06:03:12 +00009341 if (n <= 0)
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02009342 ash_msg_and_raise_error(msg_illnum, argv[1]);
Eric Andersencb57d552001-06-28 07:25:16 +00009343 if (n > loopnest)
9344 n = loopnest;
9345 if (n > 0) {
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00009346 evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
Eric Andersencb57d552001-06-28 07:25:16 +00009347 skipcount = n;
9348 }
9349 return 0;
9350}
9351
Eric Andersenc470f442003-07-28 09:56:35 +00009352
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009353/* ============ input.c
9354 *
Eric Andersen90898442003-08-06 11:20:52 +00009355 * This implements the input routines used by the parser.
Eric Andersencb57d552001-06-28 07:25:16 +00009356 */
Denis Vlasenko99eb8502007-02-23 21:09:49 +00009357
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009358enum {
9359 INPUT_PUSH_FILE = 1,
9360 INPUT_NOFILE_OK = 2,
9361};
Eric Andersencb57d552001-06-28 07:25:16 +00009362
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009363static smallint checkkwd;
Denis Vlasenko99eb8502007-02-23 21:09:49 +00009364/* values of checkkwd variable */
9365#define CHKALIAS 0x1
9366#define CHKKWD 0x2
9367#define CHKNL 0x4
9368
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009369/*
9370 * Push a string back onto the input at this current parsefile level.
9371 * We handle aliases this way.
9372 */
9373#if !ENABLE_ASH_ALIAS
9374#define pushstring(s, ap) pushstring(s)
9375#endif
9376static void
9377pushstring(char *s, struct alias *ap)
9378{
9379 struct strpush *sp;
9380 int len;
9381
9382 len = strlen(s);
9383 INT_OFF;
9384 if (g_parsefile->strpush) {
9385 sp = ckzalloc(sizeof(*sp));
9386 sp->prev = g_parsefile->strpush;
9387 } else {
9388 sp = &(g_parsefile->basestrpush);
9389 }
9390 g_parsefile->strpush = sp;
9391 sp->prev_string = g_parsefile->next_to_pgetc;
9392 sp->prev_left_in_line = g_parsefile->left_in_line;
9393#if ENABLE_ASH_ALIAS
9394 sp->ap = ap;
9395 if (ap) {
9396 ap->flag |= ALIASINUSE;
9397 sp->string = s;
9398 }
9399#endif
9400 g_parsefile->next_to_pgetc = s;
9401 g_parsefile->left_in_line = len;
9402 INT_ON;
9403}
9404
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009405static void
9406popstring(void)
Eric Andersenc470f442003-07-28 09:56:35 +00009407{
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009408 struct strpush *sp = g_parsefile->strpush;
Eric Andersenc470f442003-07-28 09:56:35 +00009409
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009410 INT_OFF;
Denis Vlasenko131ae172007-02-18 13:00:19 +00009411#if ENABLE_ASH_ALIAS
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009412 if (sp->ap) {
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009413 if (g_parsefile->next_to_pgetc[-1] == ' '
9414 || g_parsefile->next_to_pgetc[-1] == '\t'
9415 ) {
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009416 checkkwd |= CHKALIAS;
Glenn L McGrath28939ad2004-07-21 10:20:19 +00009417 }
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009418 if (sp->string != sp->ap->val) {
9419 free(sp->string);
9420 }
9421 sp->ap->flag &= ~ALIASINUSE;
9422 if (sp->ap->flag & ALIASDEAD) {
9423 unalias(sp->ap->name);
9424 }
Glenn L McGrath28939ad2004-07-21 10:20:19 +00009425 }
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009426#endif
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009427 g_parsefile->next_to_pgetc = sp->prev_string;
9428 g_parsefile->left_in_line = sp->prev_left_in_line;
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009429 g_parsefile->strpush = sp->prev;
9430 if (sp != &(g_parsefile->basestrpush))
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009431 free(sp);
9432 INT_ON;
9433}
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009434
Denis Vlasenkoe27dafd2008-11-28 04:01:03 +00009435//FIXME: BASH_COMPAT with "...&" does TWO pungetc():
9436//it peeks whether it is &>, and then pushes back both chars.
9437//This function needs to save last *next_to_pgetc to buf[0]
9438//to make two pungetc() reliable. Currently,
9439// pgetc (out of buf: does preadfd), pgetc, pungetc, pungetc won't work...
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009440static int
9441preadfd(void)
Eric Andersencb57d552001-06-28 07:25:16 +00009442{
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00009443 int nr;
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00009444 char *buf = g_parsefile->buf;
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00009445
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009446 g_parsefile->next_to_pgetc = buf;
Denis Vlasenko38f63192007-01-22 09:03:07 +00009447#if ENABLE_FEATURE_EDITING
Denis Vlasenko85c24712008-03-17 09:04:04 +00009448 retry:
Denis Vlasenko727752d2008-11-28 03:41:47 +00009449 if (!iflag || g_parsefile->fd != STDIN_FILENO)
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009450 nr = nonblock_safe_read(g_parsefile->fd, buf, BUFSIZ - 1);
Eric Andersenc470f442003-07-28 09:56:35 +00009451 else {
Denis Vlasenko38f63192007-01-22 09:03:07 +00009452#if ENABLE_FEATURE_TAB_COMPLETION
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009453 line_input_state->path_lookup = pathval();
Eric Andersen4a79c0e2004-09-08 10:01:07 +00009454#endif
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009455 nr = read_line_input(cmdedit_prompt, buf, BUFSIZ, line_input_state);
9456 if (nr == 0) {
9457 /* Ctrl+C pressed */
9458 if (trap[SIGINT]) {
Glenn L McGrath16e45d72004-02-04 08:24:39 +00009459 buf[0] = '\n';
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009460 buf[1] = '\0';
Glenn L McGrath16e45d72004-02-04 08:24:39 +00009461 raise(SIGINT);
9462 return 1;
9463 }
Eric Andersenc470f442003-07-28 09:56:35 +00009464 goto retry;
9465 }
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009466 if (nr < 0 && errno == 0) {
Denis Vlasenko9cb220b2007-12-09 10:03:28 +00009467 /* Ctrl+D pressed */
Eric Andersenc470f442003-07-28 09:56:35 +00009468 nr = 0;
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00009469 }
Eric Andersencb57d552001-06-28 07:25:16 +00009470 }
9471#else
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +00009472 nr = nonblock_safe_read(g_parsefile->fd, buf, BUFSIZ - 1);
Eric Andersencb57d552001-06-28 07:25:16 +00009473#endif
9474
Denis Vlasenkoe376d452008-02-20 22:23:24 +00009475#if 0
9476/* nonblock_safe_read() handles this problem */
Eric Andersencb57d552001-06-28 07:25:16 +00009477 if (nr < 0) {
Eric Andersencb57d552001-06-28 07:25:16 +00009478 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
Denis Vlasenkod37f2222007-08-19 13:42:08 +00009479 int flags = fcntl(0, F_GETFL);
Denis Vlasenko9cb220b2007-12-09 10:03:28 +00009480 if (flags >= 0 && (flags & O_NONBLOCK)) {
9481 flags &= ~O_NONBLOCK;
Eric Andersencb57d552001-06-28 07:25:16 +00009482 if (fcntl(0, F_SETFL, flags) >= 0) {
9483 out2str("sh: turning off NDELAY mode\n");
9484 goto retry;
9485 }
9486 }
9487 }
9488 }
Denis Vlasenkoe376d452008-02-20 22:23:24 +00009489#endif
Eric Andersencb57d552001-06-28 07:25:16 +00009490 return nr;
9491}
9492
9493/*
9494 * Refill the input buffer and return the next input character:
9495 *
9496 * 1) If a string was pushed back on the input, pop it;
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009497 * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
9498 * or we are reading from a string so we can't refill the buffer,
9499 * return EOF.
Denys Vlasenko883cea42009-07-11 15:31:59 +02009500 * 3) If there is more stuff in this buffer, use it else call read to fill it.
Eric Andersencb57d552001-06-28 07:25:16 +00009501 * 4) Process input up to the next newline, deleting nul characters.
9502 */
Denis Vlasenko727752d2008-11-28 03:41:47 +00009503//#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
9504#define pgetc_debug(...) ((void)0)
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009505static int
Eric Andersenc470f442003-07-28 09:56:35 +00009506preadbuffer(void)
Eric Andersencb57d552001-06-28 07:25:16 +00009507{
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009508 char *q;
Eric Andersencb57d552001-06-28 07:25:16 +00009509 int more;
Eric Andersencb57d552001-06-28 07:25:16 +00009510
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009511 while (g_parsefile->strpush) {
Denis Vlasenko131ae172007-02-18 13:00:19 +00009512#if ENABLE_ASH_ALIAS
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009513 if (g_parsefile->left_in_line == -1
9514 && g_parsefile->strpush->ap
9515 && g_parsefile->next_to_pgetc[-1] != ' '
9516 && g_parsefile->next_to_pgetc[-1] != '\t'
Denis Vlasenko16898402008-11-25 01:34:52 +00009517 ) {
Denis Vlasenko727752d2008-11-28 03:41:47 +00009518 pgetc_debug("preadbuffer PEOA");
Eric Andersencb57d552001-06-28 07:25:16 +00009519 return PEOA;
9520 }
Eric Andersen2870d962001-07-02 17:27:21 +00009521#endif
Eric Andersencb57d552001-06-28 07:25:16 +00009522 popstring();
Denis Vlasenko727752d2008-11-28 03:41:47 +00009523 /* try "pgetc" now: */
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009524 pgetc_debug("preadbuffer internal pgetc at %d:%p'%s'",
9525 g_parsefile->left_in_line,
9526 g_parsefile->next_to_pgetc,
9527 g_parsefile->next_to_pgetc);
9528 if (--g_parsefile->left_in_line >= 0)
9529 return (unsigned char)(*g_parsefile->next_to_pgetc++);
Eric Andersencb57d552001-06-28 07:25:16 +00009530 }
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009531 /* on both branches above g_parsefile->left_in_line < 0.
Denis Vlasenko727752d2008-11-28 03:41:47 +00009532 * "pgetc" needs refilling.
9533 */
9534
Denis Vlasenkoe27dafd2008-11-28 04:01:03 +00009535 /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009536 * pungetc() may increment it a few times.
Denis Vlasenkoe27dafd2008-11-28 04:01:03 +00009537 * Assuming it won't increment it to less than -90.
Denis Vlasenko727752d2008-11-28 03:41:47 +00009538 */
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009539 if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
Denis Vlasenko727752d2008-11-28 03:41:47 +00009540 pgetc_debug("preadbuffer PEOF1");
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009541 /* even in failure keep left_in_line and next_to_pgetc
9542 * in lock step, for correct multi-layer pungetc.
9543 * left_in_line was decremented before preadbuffer(),
9544 * must inc next_to_pgetc: */
9545 g_parsefile->next_to_pgetc++;
Eric Andersencb57d552001-06-28 07:25:16 +00009546 return PEOF;
Denis Vlasenko727752d2008-11-28 03:41:47 +00009547 }
Eric Andersencb57d552001-06-28 07:25:16 +00009548
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009549 more = g_parsefile->left_in_buffer;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009550 if (more <= 0) {
Denis Vlasenko727752d2008-11-28 03:41:47 +00009551 flush_stdout_stderr();
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009552 again:
9553 more = preadfd();
9554 if (more <= 0) {
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009555 /* don't try reading again */
9556 g_parsefile->left_in_line = -99;
Denis Vlasenko727752d2008-11-28 03:41:47 +00009557 pgetc_debug("preadbuffer PEOF2");
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009558 g_parsefile->next_to_pgetc++;
Eric Andersencb57d552001-06-28 07:25:16 +00009559 return PEOF;
9560 }
9561 }
9562
Denis Vlasenko727752d2008-11-28 03:41:47 +00009563 /* Find out where's the end of line.
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009564 * Set g_parsefile->left_in_line
9565 * and g_parsefile->left_in_buffer acordingly.
Denis Vlasenko727752d2008-11-28 03:41:47 +00009566 * NUL chars are deleted.
9567 */
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009568 q = g_parsefile->next_to_pgetc;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009569 for (;;) {
Denis Vlasenko727752d2008-11-28 03:41:47 +00009570 char c;
Eric Andersencb57d552001-06-28 07:25:16 +00009571
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009572 more--;
Eric Andersenc470f442003-07-28 09:56:35 +00009573
Denis Vlasenko727752d2008-11-28 03:41:47 +00009574 c = *q;
9575 if (c == '\0') {
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009576 memmove(q, q + 1, more);
Denis Vlasenko727752d2008-11-28 03:41:47 +00009577 } else {
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009578 q++;
9579 if (c == '\n') {
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009580 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009581 break;
9582 }
Eric Andersencb57d552001-06-28 07:25:16 +00009583 }
9584
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009585 if (more <= 0) {
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009586 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9587 if (g_parsefile->left_in_line < 0)
Eric Andersencb57d552001-06-28 07:25:16 +00009588 goto again;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009589 break;
Eric Andersencb57d552001-06-28 07:25:16 +00009590 }
9591 }
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009592 g_parsefile->left_in_buffer = more;
Eric Andersencb57d552001-06-28 07:25:16 +00009593
Eric Andersencb57d552001-06-28 07:25:16 +00009594 if (vflag) {
Denis Vlasenko727752d2008-11-28 03:41:47 +00009595 char save = *q;
9596 *q = '\0';
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009597 out2str(g_parsefile->next_to_pgetc);
Denis Vlasenko727752d2008-11-28 03:41:47 +00009598 *q = save;
Eric Andersencb57d552001-06-28 07:25:16 +00009599 }
9600
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009601 pgetc_debug("preadbuffer at %d:%p'%s'",
9602 g_parsefile->left_in_line,
9603 g_parsefile->next_to_pgetc,
9604 g_parsefile->next_to_pgetc);
Denys Vlasenkocd716832009-11-28 22:14:02 +01009605 return (unsigned char)*g_parsefile->next_to_pgetc++;
Eric Andersencb57d552001-06-28 07:25:16 +00009606}
9607
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009608#define pgetc_as_macro() \
9609 (--g_parsefile->left_in_line >= 0 \
Denys Vlasenkocd716832009-11-28 22:14:02 +01009610 ? (unsigned char)*g_parsefile->next_to_pgetc++ \
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009611 : preadbuffer() \
9612 )
Denis Vlasenko727752d2008-11-28 03:41:47 +00009613
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009614static int
9615pgetc(void)
9616{
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009617 pgetc_debug("pgetc_fast at %d:%p'%s'",
9618 g_parsefile->left_in_line,
9619 g_parsefile->next_to_pgetc,
9620 g_parsefile->next_to_pgetc);
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009621 return pgetc_as_macro();
9622}
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00009623
9624#if ENABLE_ASH_OPTIMIZE_FOR_SIZE
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01009625# define pgetc_fast() pgetc()
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009626#else
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01009627# define pgetc_fast() pgetc_as_macro()
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009628#endif
9629
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009630#if ENABLE_ASH_ALIAS
9631static int
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01009632pgetc_without_PEOA(void)
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009633{
9634 int c;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009635 do {
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009636 pgetc_debug("pgetc_fast at %d:%p'%s'",
9637 g_parsefile->left_in_line,
9638 g_parsefile->next_to_pgetc,
9639 g_parsefile->next_to_pgetc);
Denis Vlasenko834dee72008-10-07 09:18:30 +00009640 c = pgetc_fast();
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009641 } while (c == PEOA);
9642 return c;
9643}
9644#else
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01009645# define pgetc_without_PEOA() pgetc()
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009646#endif
9647
9648/*
9649 * Read a line from the script.
9650 */
9651static char *
9652pfgets(char *line, int len)
9653{
9654 char *p = line;
9655 int nleft = len;
9656 int c;
9657
9658 while (--nleft > 0) {
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01009659 c = pgetc_without_PEOA();
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009660 if (c == PEOF) {
9661 if (p == line)
9662 return NULL;
9663 break;
9664 }
9665 *p++ = c;
9666 if (c == '\n')
9667 break;
9668 }
9669 *p = '\0';
9670 return line;
9671}
9672
Eric Andersenc470f442003-07-28 09:56:35 +00009673/*
9674 * Undo the last call to pgetc. Only one character may be pushed back.
9675 * PEOF may be pushed back.
9676 */
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009677static void
Eric Andersenc470f442003-07-28 09:56:35 +00009678pungetc(void)
9679{
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009680 g_parsefile->left_in_line++;
9681 g_parsefile->next_to_pgetc--;
9682 pgetc_debug("pushed back to %d:%p'%s'",
9683 g_parsefile->left_in_line,
9684 g_parsefile->next_to_pgetc,
9685 g_parsefile->next_to_pgetc);
Eric Andersencb57d552001-06-28 07:25:16 +00009686}
9687
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009688/*
9689 * To handle the "." command, a stack of input files is used. Pushfile
9690 * adds a new entry to the stack and popfile restores the previous level.
9691 */
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009692static void
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009693pushfile(void)
Eric Andersenc470f442003-07-28 09:56:35 +00009694{
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009695 struct parsefile *pf;
9696
Denis Vlasenko597906c2008-02-20 16:38:54 +00009697 pf = ckzalloc(sizeof(*pf));
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009698 pf->prev = g_parsefile;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009699 pf->fd = -1;
Denis Vlasenko597906c2008-02-20 16:38:54 +00009700 /*pf->strpush = NULL; - ckzalloc did it */
9701 /*pf->basestrpush.prev = NULL;*/
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009702 g_parsefile = pf;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009703}
9704
9705static void
9706popfile(void)
9707{
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009708 struct parsefile *pf = g_parsefile;
Eric Andersenc470f442003-07-28 09:56:35 +00009709
Denis Vlasenkob012b102007-02-19 22:43:01 +00009710 INT_OFF;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009711 if (pf->fd >= 0)
9712 close(pf->fd);
Denis Vlasenko60818682007-09-28 22:07:23 +00009713 free(pf->buf);
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009714 while (pf->strpush)
9715 popstring();
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009716 g_parsefile = pf->prev;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009717 free(pf);
Denis Vlasenkob012b102007-02-19 22:43:01 +00009718 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00009719}
9720
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009721/*
9722 * Return to top level.
9723 */
9724static void
9725popallfiles(void)
9726{
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009727 while (g_parsefile != &basepf)
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009728 popfile();
9729}
9730
9731/*
9732 * Close the file(s) that the shell is reading commands from. Called
9733 * after a fork is done.
9734 */
9735static void
9736closescript(void)
9737{
9738 popallfiles();
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009739 if (g_parsefile->fd > 0) {
9740 close(g_parsefile->fd);
9741 g_parsefile->fd = 0;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009742 }
9743}
9744
9745/*
9746 * Like setinputfile, but takes an open file descriptor. Call this with
9747 * interrupts off.
9748 */
9749static void
9750setinputfd(int fd, int push)
9751{
Denis Vlasenko96e1b382007-09-30 23:50:48 +00009752 close_on_exec_on(fd);
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009753 if (push) {
9754 pushfile();
Denis Vlasenko727752d2008-11-28 03:41:47 +00009755 g_parsefile->buf = NULL;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009756 }
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009757 g_parsefile->fd = fd;
9758 if (g_parsefile->buf == NULL)
9759 g_parsefile->buf = ckmalloc(IBUFSIZ);
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009760 g_parsefile->left_in_buffer = 0;
9761 g_parsefile->left_in_line = 0;
9762 g_parsefile->linno = 1;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009763}
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009764
Eric Andersenc470f442003-07-28 09:56:35 +00009765/*
9766 * Set the input to take input from a file. If push is set, push the
9767 * old input onto the stack first.
9768 */
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009769static int
9770setinputfile(const char *fname, int flags)
Eric Andersenc470f442003-07-28 09:56:35 +00009771{
9772 int fd;
9773 int fd2;
9774
Denis Vlasenkob012b102007-02-19 22:43:01 +00009775 INT_OFF;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009776 fd = open(fname, O_RDONLY);
9777 if (fd < 0) {
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009778 if (flags & INPUT_NOFILE_OK)
9779 goto out;
Denis Vlasenko9604e1b2009-03-03 18:47:56 +00009780 ash_msg_and_raise_error("can't open '%s'", fname);
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009781 }
Eric Andersenc470f442003-07-28 09:56:35 +00009782 if (fd < 10) {
9783 fd2 = copyfd(fd, 10);
9784 close(fd);
9785 if (fd2 < 0)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00009786 ash_msg_and_raise_error("out of file descriptors");
Eric Andersenc470f442003-07-28 09:56:35 +00009787 fd = fd2;
9788 }
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009789 setinputfd(fd, flags & INPUT_PUSH_FILE);
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009790 out:
Denis Vlasenkob012b102007-02-19 22:43:01 +00009791 INT_ON;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009792 return fd;
Eric Andersenc470f442003-07-28 09:56:35 +00009793}
9794
Eric Andersencb57d552001-06-28 07:25:16 +00009795/*
9796 * Like setinputfile, but takes input from a string.
9797 */
Eric Andersenc470f442003-07-28 09:56:35 +00009798static void
9799setinputstring(char *string)
Eric Andersen62483552001-07-10 06:09:16 +00009800{
Denis Vlasenkob012b102007-02-19 22:43:01 +00009801 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +00009802 pushfile();
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009803 g_parsefile->next_to_pgetc = string;
9804 g_parsefile->left_in_line = strlen(string);
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009805 g_parsefile->buf = NULL;
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009806 g_parsefile->linno = 1;
Denis Vlasenkob012b102007-02-19 22:43:01 +00009807 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00009808}
9809
9810
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00009811/* ============ mail.c
9812 *
9813 * Routines to check for mail.
Eric Andersencb57d552001-06-28 07:25:16 +00009814 */
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00009815
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00009816#if ENABLE_ASH_MAIL
Eric Andersencb57d552001-06-28 07:25:16 +00009817
Eric Andersencb57d552001-06-28 07:25:16 +00009818#define MAXMBOXES 10
9819
Eric Andersenc470f442003-07-28 09:56:35 +00009820/* times of mailboxes */
9821static time_t mailtime[MAXMBOXES];
9822/* Set if MAIL or MAILPATH is changed. */
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +00009823static smallint mail_var_path_changed;
Eric Andersencb57d552001-06-28 07:25:16 +00009824
Eric Andersencb57d552001-06-28 07:25:16 +00009825/*
Eric Andersenc470f442003-07-28 09:56:35 +00009826 * Print appropriate message(s) if mail has arrived.
9827 * If mail_var_path_changed is set,
9828 * then the value of MAIL has mail_var_path_changed,
9829 * so we just update the values.
Eric Andersencb57d552001-06-28 07:25:16 +00009830 */
Eric Andersenc470f442003-07-28 09:56:35 +00009831static void
9832chkmail(void)
Eric Andersencb57d552001-06-28 07:25:16 +00009833{
Eric Andersencb57d552001-06-28 07:25:16 +00009834 const char *mpath;
9835 char *p;
9836 char *q;
Eric Andersenc470f442003-07-28 09:56:35 +00009837 time_t *mtp;
Eric Andersencb57d552001-06-28 07:25:16 +00009838 struct stackmark smark;
9839 struct stat statb;
9840
Eric Andersencb57d552001-06-28 07:25:16 +00009841 setstackmark(&smark);
Eric Andersenc470f442003-07-28 09:56:35 +00009842 mpath = mpathset() ? mpathval() : mailval();
9843 for (mtp = mailtime; mtp < mailtime + MAXMBOXES; mtp++) {
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02009844 p = path_advance(&mpath, nullstr);
Eric Andersencb57d552001-06-28 07:25:16 +00009845 if (p == NULL)
9846 break;
9847 if (*p == '\0')
9848 continue;
Denis Vlasenkof7d56652008-03-25 05:51:41 +00009849 for (q = p; *q; q++)
9850 continue;
Denis Vlasenkoa7189f02006-11-17 20:29:00 +00009851#if DEBUG
Eric Andersencb57d552001-06-28 07:25:16 +00009852 if (q[-1] != '/')
9853 abort();
9854#endif
Eric Andersenc470f442003-07-28 09:56:35 +00009855 q[-1] = '\0'; /* delete trailing '/' */
9856 if (stat(p, &statb) < 0) {
9857 *mtp = 0;
9858 continue;
Eric Andersencb57d552001-06-28 07:25:16 +00009859 }
Eric Andersenc470f442003-07-28 09:56:35 +00009860 if (!mail_var_path_changed && statb.st_mtime != *mtp) {
9861 fprintf(
9862 stderr, snlfmt,
9863 pathopt ? pathopt : "you have mail"
9864 );
9865 }
9866 *mtp = statb.st_mtime;
Eric Andersencb57d552001-06-28 07:25:16 +00009867 }
Eric Andersenc470f442003-07-28 09:56:35 +00009868 mail_var_path_changed = 0;
Eric Andersencb57d552001-06-28 07:25:16 +00009869 popstackmark(&smark);
9870}
Eric Andersencb57d552001-06-28 07:25:16 +00009871
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009872static void FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00009873changemail(const char *val UNUSED_PARAM)
Eric Andersenc470f442003-07-28 09:56:35 +00009874{
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +00009875 mail_var_path_changed = 1;
Eric Andersenc470f442003-07-28 09:56:35 +00009876}
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00009877
Denis Vlasenko131ae172007-02-18 13:00:19 +00009878#endif /* ASH_MAIL */
Eric Andersenc470f442003-07-28 09:56:35 +00009879
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00009880
9881/* ============ ??? */
9882
Eric Andersencb57d552001-06-28 07:25:16 +00009883/*
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009884 * Set the shell parameters.
Eric Andersencb57d552001-06-28 07:25:16 +00009885 */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009886static void
9887setparam(char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +00009888{
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009889 char **newparam;
9890 char **ap;
9891 int nparam;
Eric Andersencb57d552001-06-28 07:25:16 +00009892
Denis Vlasenkof7d56652008-03-25 05:51:41 +00009893 for (nparam = 0; argv[nparam]; nparam++)
9894 continue;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009895 ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
9896 while (*argv) {
9897 *ap++ = ckstrdup(*argv++);
Eric Andersencb57d552001-06-28 07:25:16 +00009898 }
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009899 *ap = NULL;
9900 freeparam(&shellparam);
Denis Vlasenko01631112007-12-16 17:20:38 +00009901 shellparam.malloced = 1;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009902 shellparam.nparam = nparam;
9903 shellparam.p = newparam;
9904#if ENABLE_ASH_GETOPTS
9905 shellparam.optind = 1;
9906 shellparam.optoff = -1;
9907#endif
Eric Andersencb57d552001-06-28 07:25:16 +00009908}
9909
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00009910/*
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009911 * Process shell options. The global variable argptr contains a pointer
9912 * to the argument list; we advance it past the options.
Denis Vlasenko94e87bc2008-02-14 16:51:58 +00009913 *
9914 * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
9915 * For a non-interactive shell, an error condition encountered
9916 * by a special built-in ... shall cause the shell to write a diagnostic message
9917 * to standard error and exit as shown in the following table:
Denis Vlasenko56244732008-02-17 15:14:04 +00009918 * Error Special Built-In
Denis Vlasenko94e87bc2008-02-14 16:51:58 +00009919 * ...
9920 * Utility syntax error (option or operand error) Shall exit
9921 * ...
9922 * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
9923 * we see that bash does not do that (set "finishes" with error code 1 instead,
9924 * and shell continues), and people rely on this behavior!
9925 * Testcase:
9926 * set -o barfoo 2>/dev/null
9927 * echo $?
9928 *
9929 * Oh well. Let's mimic that.
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00009930 */
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009931static int
Denis Vlasenkodddfaff2008-05-06 15:30:27 +00009932plus_minus_o(char *name, int val)
Eric Andersen62483552001-07-10 06:09:16 +00009933{
9934 int i;
9935
Denis Vlasenkoa624c112007-02-19 22:45:43 +00009936 if (name) {
9937 for (i = 0; i < NOPTS; i++) {
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00009938 if (strcmp(name, optnames(i)) == 0) {
Eric Andersenc470f442003-07-28 09:56:35 +00009939 optlist[i] = val;
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009940 return 0;
Eric Andersen62483552001-07-10 06:09:16 +00009941 }
Denis Vlasenkoa624c112007-02-19 22:45:43 +00009942 }
Denis Vlasenkodddfaff2008-05-06 15:30:27 +00009943 ash_msg("illegal option %co %s", val ? '-' : '+', name);
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009944 return 1;
Eric Andersen62483552001-07-10 06:09:16 +00009945 }
Denis Vlasenko6b06cb82008-05-15 21:30:45 +00009946 for (i = 0; i < NOPTS; i++) {
Denis Vlasenkodddfaff2008-05-06 15:30:27 +00009947 if (val) {
9948 out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
9949 } else {
9950 out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
9951 }
Denis Vlasenko6b06cb82008-05-15 21:30:45 +00009952 }
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009953 return 0;
Eric Andersen62483552001-07-10 06:09:16 +00009954}
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009955static void
9956setoption(int flag, int val)
9957{
9958 int i;
9959
9960 for (i = 0; i < NOPTS; i++) {
9961 if (optletters(i) == flag) {
9962 optlist[i] = val;
9963 return;
9964 }
9965 }
Denis Vlasenkodddfaff2008-05-06 15:30:27 +00009966 ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009967 /* NOTREACHED */
9968}
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009969static int
Eric Andersenc470f442003-07-28 09:56:35 +00009970options(int cmdline)
Eric Andersencb57d552001-06-28 07:25:16 +00009971{
9972 char *p;
9973 int val;
9974 int c;
9975
9976 if (cmdline)
9977 minusc = NULL;
9978 while ((p = *argptr) != NULL) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009979 c = *p++;
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +00009980 if (c != '-' && c != '+')
9981 break;
9982 argptr++;
9983 val = 0; /* val = 0 if c == '+' */
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009984 if (c == '-') {
Eric Andersencb57d552001-06-28 07:25:16 +00009985 val = 1;
Denis Vlasenko9f739442006-12-16 23:49:13 +00009986 if (p[0] == '\0' || LONE_DASH(p)) {
Eric Andersen2870d962001-07-02 17:27:21 +00009987 if (!cmdline) {
9988 /* "-" means turn off -x and -v */
9989 if (p[0] == '\0')
9990 xflag = vflag = 0;
9991 /* "--" means reset params */
9992 else if (*argptr == NULL)
Eric Andersencb57d552001-06-28 07:25:16 +00009993 setparam(argptr);
Eric Andersen2870d962001-07-02 17:27:21 +00009994 }
Eric Andersenc470f442003-07-28 09:56:35 +00009995 break; /* "-" or "--" terminates options */
Eric Andersencb57d552001-06-28 07:25:16 +00009996 }
Eric Andersencb57d552001-06-28 07:25:16 +00009997 }
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +00009998 /* first char was + or - */
Eric Andersencb57d552001-06-28 07:25:16 +00009999 while ((c = *p++) != '\0') {
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +000010000 /* bash 3.2 indeed handles -c CMD and +c CMD the same */
Eric Andersencb57d552001-06-28 07:25:16 +000010001 if (c == 'c' && cmdline) {
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +000010002 minusc = p; /* command is after shell args */
Eric Andersencb57d552001-06-28 07:25:16 +000010003 } else if (c == 'o') {
Denis Vlasenkodddfaff2008-05-06 15:30:27 +000010004 if (plus_minus_o(*argptr, val)) {
Denis Vlasenko28bf6712008-02-14 15:01:47 +000010005 /* it already printed err message */
10006 return 1; /* error */
10007 }
Eric Andersencb57d552001-06-28 07:25:16 +000010008 if (*argptr)
10009 argptr++;
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +000010010 } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
10011 isloginsh = 1;
10012 /* bash does not accept +-login, we also won't */
10013 } else if (cmdline && val && (c == '-')) { /* long options */
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010014 if (strcmp(p, "login") == 0)
Robert Griebl64f70cc2002-05-14 23:22:06 +000010015 isloginsh = 1;
10016 break;
Eric Andersencb57d552001-06-28 07:25:16 +000010017 } else {
10018 setoption(c, val);
10019 }
10020 }
10021 }
Denis Vlasenko28bf6712008-02-14 15:01:47 +000010022 return 0;
Eric Andersencb57d552001-06-28 07:25:16 +000010023}
10024
Eric Andersencb57d552001-06-28 07:25:16 +000010025/*
Eric Andersencb57d552001-06-28 07:25:16 +000010026 * The shift builtin command.
10027 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010028static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000010029shiftcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +000010030{
10031 int n;
10032 char **ap1, **ap2;
10033
10034 n = 1;
Denis Vlasenko68404f12008-03-17 09:00:54 +000010035 if (argv[1])
Eric Andersencb57d552001-06-28 07:25:16 +000010036 n = number(argv[1]);
10037 if (n > shellparam.nparam)
Denis Vlasenkoc90e1be2008-07-30 15:35:05 +000010038 n = 0; /* bash compat, was = shellparam.nparam; */
Denis Vlasenkob012b102007-02-19 22:43:01 +000010039 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +000010040 shellparam.nparam -= n;
Denis Vlasenko2da584f2007-02-19 22:44:05 +000010041 for (ap1 = shellparam.p; --n >= 0; ap1++) {
Denis Vlasenko01631112007-12-16 17:20:38 +000010042 if (shellparam.malloced)
Denis Vlasenkob012b102007-02-19 22:43:01 +000010043 free(*ap1);
Eric Andersencb57d552001-06-28 07:25:16 +000010044 }
10045 ap2 = shellparam.p;
Denis Vlasenkof7d56652008-03-25 05:51:41 +000010046 while ((*ap2++ = *ap1++) != NULL)
10047 continue;
Denis Vlasenko131ae172007-02-18 13:00:19 +000010048#if ENABLE_ASH_GETOPTS
Eric Andersencb57d552001-06-28 07:25:16 +000010049 shellparam.optind = 1;
10050 shellparam.optoff = -1;
Eric Andersenc470f442003-07-28 09:56:35 +000010051#endif
Denis Vlasenkob012b102007-02-19 22:43:01 +000010052 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +000010053 return 0;
10054}
10055
Eric Andersencb57d552001-06-28 07:25:16 +000010056/*
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010057 * POSIX requires that 'set' (but not export or readonly) output the
10058 * variables in lexicographic order - by the locale's collating order (sigh).
10059 * Maybe we could keep them in an ordered balanced binary tree
10060 * instead of hashed lists.
10061 * For now just roll 'em through qsort for printing...
10062 */
10063static int
10064showvars(const char *sep_prefix, int on, int off)
10065{
10066 const char *sep;
10067 char **ep, **epend;
10068
10069 ep = listvars(on, off, &epend);
10070 qsort(ep, epend - ep, sizeof(char *), vpcmp);
10071
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +000010072 sep = *sep_prefix ? " " : sep_prefix;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010073
10074 for (; ep < epend; ep++) {
10075 const char *p;
10076 const char *q;
10077
10078 p = strchrnul(*ep, '=');
10079 q = nullstr;
10080 if (*p)
10081 q = single_quote(++p);
10082 out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
10083 }
10084 return 0;
10085}
10086
10087/*
Eric Andersencb57d552001-06-28 07:25:16 +000010088 * The set command builtin.
10089 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010090static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000010091setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersencb57d552001-06-28 07:25:16 +000010092{
Denis Vlasenko28bf6712008-02-14 15:01:47 +000010093 int retval;
10094
Denis Vlasenko68404f12008-03-17 09:00:54 +000010095 if (!argv[1])
Eric Andersenc470f442003-07-28 09:56:35 +000010096 return showvars(nullstr, 0, VUNSET);
Denis Vlasenkob012b102007-02-19 22:43:01 +000010097 INT_OFF;
Denis Vlasenko28bf6712008-02-14 15:01:47 +000010098 retval = 1;
10099 if (!options(0)) { /* if no parse error... */
10100 retval = 0;
10101 optschanged();
10102 if (*argptr != NULL) {
10103 setparam(argptr);
10104 }
Eric Andersencb57d552001-06-28 07:25:16 +000010105 }
Denis Vlasenkob012b102007-02-19 22:43:01 +000010106 INT_ON;
Denis Vlasenko28bf6712008-02-14 15:01:47 +000010107 return retval;
Eric Andersencb57d552001-06-28 07:25:16 +000010108}
10109
Denis Vlasenko131ae172007-02-18 13:00:19 +000010110#if ENABLE_ASH_RANDOM_SUPPORT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010111static void FAST_FUNC
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000010112change_random(const char *value)
Eric Andersenef02f822004-03-11 13:34:24 +000010113{
Denys Vlasenko3ea2e822009-10-09 20:59:04 +020010114 uint32_t t;
10115
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010116 if (value == NULL) {
Eric Andersen16767e22004-03-16 05:14:10 +000010117 /* "get", generate */
Denys Vlasenko3ea2e822009-10-09 20:59:04 +020010118 t = next_random(&random_gen);
Eric Andersen16767e22004-03-16 05:14:10 +000010119 /* set without recursion */
Denis Vlasenko448d30e2008-06-27 00:24:11 +000010120 setvar(vrandom.text, utoa(t), VNOFUNC);
Eric Andersen16767e22004-03-16 05:14:10 +000010121 vrandom.flags &= ~VNOFUNC;
10122 } else {
10123 /* set/reset */
Denys Vlasenko3ea2e822009-10-09 20:59:04 +020010124 t = strtoul(value, NULL, 10);
10125 INIT_RANDOM_T(&random_gen, (t ? t : 1), t);
Eric Andersen16767e22004-03-16 05:14:10 +000010126 }
Eric Andersenef02f822004-03-11 13:34:24 +000010127}
Eric Andersen16767e22004-03-16 05:14:10 +000010128#endif
10129
Denis Vlasenko131ae172007-02-18 13:00:19 +000010130#if ENABLE_ASH_GETOPTS
Eric Andersencb57d552001-06-28 07:25:16 +000010131static int
Eric Andersenc470f442003-07-28 09:56:35 +000010132getopts(char *optstr, char *optvar, char **optfirst, int *param_optind, int *optoff)
Eric Andersencb57d552001-06-28 07:25:16 +000010133{
10134 char *p, *q;
10135 char c = '?';
10136 int done = 0;
10137 int err = 0;
Eric Andersena48b0a32003-10-22 10:56:47 +000010138 char s[12];
10139 char **optnext;
Eric Andersencb57d552001-06-28 07:25:16 +000010140
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010141 if (*param_optind < 1)
Eric Andersena48b0a32003-10-22 10:56:47 +000010142 return 1;
10143 optnext = optfirst + *param_optind - 1;
10144
Denis Vlasenko6b06cb82008-05-15 21:30:45 +000010145 if (*param_optind <= 1 || *optoff < 0 || (int)strlen(optnext[-1]) < *optoff)
Eric Andersencb57d552001-06-28 07:25:16 +000010146 p = NULL;
10147 else
Eric Andersena48b0a32003-10-22 10:56:47 +000010148 p = optnext[-1] + *optoff;
Eric Andersencb57d552001-06-28 07:25:16 +000010149 if (p == NULL || *p == '\0') {
10150 /* Current word is done, advance */
Eric Andersencb57d552001-06-28 07:25:16 +000010151 p = *optnext;
10152 if (p == NULL || *p != '-' || *++p == '\0') {
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010153 atend:
Eric Andersencb57d552001-06-28 07:25:16 +000010154 p = NULL;
10155 done = 1;
10156 goto out;
10157 }
10158 optnext++;
Denis Vlasenko9f739442006-12-16 23:49:13 +000010159 if (LONE_DASH(p)) /* check for "--" */
Eric Andersencb57d552001-06-28 07:25:16 +000010160 goto atend;
10161 }
10162
10163 c = *p++;
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +000010164 for (q = optstr; *q != c;) {
Eric Andersencb57d552001-06-28 07:25:16 +000010165 if (*q == '\0') {
10166 if (optstr[0] == ':') {
10167 s[0] = c;
10168 s[1] = '\0';
10169 err |= setvarsafe("OPTARG", s, 0);
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010170 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000010171 fprintf(stderr, "Illegal option -%c\n", c);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010172 unsetvar("OPTARG");
Eric Andersencb57d552001-06-28 07:25:16 +000010173 }
10174 c = '?';
Eric Andersenc470f442003-07-28 09:56:35 +000010175 goto out;
Eric Andersencb57d552001-06-28 07:25:16 +000010176 }
10177 if (*++q == ':')
10178 q++;
10179 }
10180
10181 if (*++q == ':') {
10182 if (*p == '\0' && (p = *optnext) == NULL) {
10183 if (optstr[0] == ':') {
10184 s[0] = c;
10185 s[1] = '\0';
10186 err |= setvarsafe("OPTARG", s, 0);
10187 c = ':';
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010188 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000010189 fprintf(stderr, "No arg for -%c option\n", c);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010190 unsetvar("OPTARG");
Eric Andersencb57d552001-06-28 07:25:16 +000010191 c = '?';
10192 }
Eric Andersenc470f442003-07-28 09:56:35 +000010193 goto out;
Eric Andersencb57d552001-06-28 07:25:16 +000010194 }
10195
10196 if (p == *optnext)
10197 optnext++;
Eric Andersenc470f442003-07-28 09:56:35 +000010198 err |= setvarsafe("OPTARG", p, 0);
Eric Andersencb57d552001-06-28 07:25:16 +000010199 p = NULL;
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010200 } else
Eric Andersenc470f442003-07-28 09:56:35 +000010201 err |= setvarsafe("OPTARG", nullstr, 0);
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010202 out:
Eric Andersencb57d552001-06-28 07:25:16 +000010203 *optoff = p ? p - *(optnext - 1) : -1;
Eric Andersenc470f442003-07-28 09:56:35 +000010204 *param_optind = optnext - optfirst + 1;
10205 fmtstr(s, sizeof(s), "%d", *param_optind);
Eric Andersencb57d552001-06-28 07:25:16 +000010206 err |= setvarsafe("OPTIND", s, VNOFUNC);
10207 s[0] = c;
10208 s[1] = '\0';
10209 err |= setvarsafe(optvar, s, 0);
10210 if (err) {
Eric Andersenc470f442003-07-28 09:56:35 +000010211 *param_optind = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010212 *optoff = -1;
Denis Vlasenkob012b102007-02-19 22:43:01 +000010213 flush_stdout_stderr();
10214 raise_exception(EXERROR);
Eric Andersencb57d552001-06-28 07:25:16 +000010215 }
10216 return done;
10217}
Eric Andersenc470f442003-07-28 09:56:35 +000010218
10219/*
10220 * The getopts builtin. Shellparam.optnext points to the next argument
10221 * to be processed. Shellparam.optptr points to the next character to
10222 * be processed in the current argument. If shellparam.optnext is NULL,
10223 * then it's the first time getopts has been called.
10224 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010225static int FAST_FUNC
Eric Andersenc470f442003-07-28 09:56:35 +000010226getoptscmd(int argc, char **argv)
10227{
10228 char **optbase;
10229
10230 if (argc < 3)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +000010231 ash_msg_and_raise_error("usage: getopts optstring var [arg]");
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010232 if (argc == 3) {
Eric Andersenc470f442003-07-28 09:56:35 +000010233 optbase = shellparam.p;
10234 if (shellparam.optind > shellparam.nparam + 1) {
10235 shellparam.optind = 1;
10236 shellparam.optoff = -1;
10237 }
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010238 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000010239 optbase = &argv[3];
10240 if (shellparam.optind > argc - 2) {
10241 shellparam.optind = 1;
10242 shellparam.optoff = -1;
10243 }
10244 }
10245
10246 return getopts(argv[1], argv[2], optbase, &shellparam.optind,
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010247 &shellparam.optoff);
Eric Andersenc470f442003-07-28 09:56:35 +000010248}
Denis Vlasenko131ae172007-02-18 13:00:19 +000010249#endif /* ASH_GETOPTS */
Eric Andersencb57d552001-06-28 07:25:16 +000010250
Eric Andersencb57d552001-06-28 07:25:16 +000010251
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010252/* ============ Shell parser */
Eric Andersencb57d552001-06-28 07:25:16 +000010253
Denis Vlasenkob07a4962008-06-22 13:16:23 +000010254struct heredoc {
10255 struct heredoc *next; /* next here document in list */
10256 union node *here; /* redirection node */
10257 char *eofmark; /* string indicating end of input */
10258 smallint striptabs; /* if set, strip leading tabs */
10259};
10260
10261static smallint tokpushback; /* last token pushed back */
10262static smallint parsebackquote; /* nonzero if we are inside backquotes */
10263static smallint quoteflag; /* set if (part of) last token was quoted */
10264static token_id_t lasttoken; /* last token read (integer id Txxx) */
10265static struct heredoc *heredoclist; /* list of here documents to read */
10266static char *wordtext; /* text of last word returned by readtoken */
10267static struct nodelist *backquotelist;
10268static union node *redirnode;
10269static struct heredoc *heredoc;
Denis Vlasenko99eb8502007-02-23 21:09:49 +000010270
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010271/*
10272 * Called when an unexpected token is read during the parse. The argument
10273 * is the token that is expected, or -1 if more than one type of token can
10274 * occur at this point.
10275 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000010276static void raise_error_unexpected_syntax(int) NORETURN;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010277static void
10278raise_error_unexpected_syntax(int token)
10279{
10280 char msg[64];
10281 int l;
10282
Denis Vlasenko7b2294e2008-11-28 03:50:46 +000010283 l = sprintf(msg, "unexpected %s", tokname(lasttoken));
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010284 if (token >= 0)
10285 sprintf(msg + l, " (expecting %s)", tokname(token));
10286 raise_error_syntax(msg);
10287 /* NOTREACHED */
10288}
Eric Andersencb57d552001-06-28 07:25:16 +000010289
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010290#define EOFMARKLEN 79
Eric Andersencb57d552001-06-28 07:25:16 +000010291
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010292/* parsing is heavily cross-recursive, need these forward decls */
10293static union node *andor(void);
10294static union node *pipeline(void);
10295static union node *parse_command(void);
10296static void parseheredoc(void);
10297static char peektoken(void);
10298static int readtoken(void);
Eric Andersencb57d552001-06-28 07:25:16 +000010299
Eric Andersenc470f442003-07-28 09:56:35 +000010300static union node *
10301list(int nlflag)
Eric Andersencb57d552001-06-28 07:25:16 +000010302{
10303 union node *n1, *n2, *n3;
10304 int tok;
10305
Eric Andersenc470f442003-07-28 09:56:35 +000010306 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10307 if (nlflag == 2 && peektoken())
Eric Andersencb57d552001-06-28 07:25:16 +000010308 return NULL;
10309 n1 = NULL;
10310 for (;;) {
10311 n2 = andor();
10312 tok = readtoken();
10313 if (tok == TBACKGND) {
Eric Andersenc470f442003-07-28 09:56:35 +000010314 if (n2->type == NPIPE) {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +000010315 n2->npipe.pipe_backgnd = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010316 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000010317 if (n2->type != NREDIR) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010318 n3 = stzalloc(sizeof(struct nredir));
Eric Andersenc470f442003-07-28 09:56:35 +000010319 n3->nredir.n = n2;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010320 /*n3->nredir.redirect = NULL; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000010321 n2 = n3;
10322 }
10323 n2->type = NBACKGND;
Eric Andersencb57d552001-06-28 07:25:16 +000010324 }
10325 }
10326 if (n1 == NULL) {
10327 n1 = n2;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010328 } else {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010329 n3 = stzalloc(sizeof(struct nbinary));
Eric Andersencb57d552001-06-28 07:25:16 +000010330 n3->type = NSEMI;
10331 n3->nbinary.ch1 = n1;
10332 n3->nbinary.ch2 = n2;
10333 n1 = n3;
10334 }
10335 switch (tok) {
10336 case TBACKGND:
10337 case TSEMI:
10338 tok = readtoken();
10339 /* fall through */
10340 case TNL:
10341 if (tok == TNL) {
10342 parseheredoc();
Eric Andersenc470f442003-07-28 09:56:35 +000010343 if (nlflag == 1)
Eric Andersencb57d552001-06-28 07:25:16 +000010344 return n1;
10345 } else {
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010346 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010347 }
Eric Andersenc470f442003-07-28 09:56:35 +000010348 checkkwd = CHKNL | CHKKWD | CHKALIAS;
Manuel Novoa III 16815d42001-08-10 19:36:07 +000010349 if (peektoken())
Eric Andersencb57d552001-06-28 07:25:16 +000010350 return n1;
10351 break;
10352 case TEOF:
10353 if (heredoclist)
10354 parseheredoc();
10355 else
Eric Andersenc470f442003-07-28 09:56:35 +000010356 pungetc(); /* push back EOF on input */
Eric Andersencb57d552001-06-28 07:25:16 +000010357 return n1;
10358 default:
Eric Andersenc470f442003-07-28 09:56:35 +000010359 if (nlflag == 1)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010360 raise_error_unexpected_syntax(-1);
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010361 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010362 return n1;
10363 }
10364 }
10365}
10366
Eric Andersenc470f442003-07-28 09:56:35 +000010367static union node *
10368andor(void)
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010369{
Eric Andersencb57d552001-06-28 07:25:16 +000010370 union node *n1, *n2, *n3;
10371 int t;
10372
Eric Andersencb57d552001-06-28 07:25:16 +000010373 n1 = pipeline();
10374 for (;;) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010375 t = readtoken();
10376 if (t == TAND) {
Eric Andersencb57d552001-06-28 07:25:16 +000010377 t = NAND;
10378 } else if (t == TOR) {
10379 t = NOR;
10380 } else {
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010381 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010382 return n1;
10383 }
Eric Andersenc470f442003-07-28 09:56:35 +000010384 checkkwd = CHKNL | CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010385 n2 = pipeline();
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010386 n3 = stzalloc(sizeof(struct nbinary));
Eric Andersencb57d552001-06-28 07:25:16 +000010387 n3->type = t;
10388 n3->nbinary.ch1 = n1;
10389 n3->nbinary.ch2 = n2;
10390 n1 = n3;
10391 }
10392}
10393
Eric Andersenc470f442003-07-28 09:56:35 +000010394static union node *
10395pipeline(void)
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010396{
Eric Andersencb57d552001-06-28 07:25:16 +000010397 union node *n1, *n2, *pipenode;
10398 struct nodelist *lp, *prev;
10399 int negate;
10400
10401 negate = 0;
10402 TRACE(("pipeline: entered\n"));
10403 if (readtoken() == TNOT) {
10404 negate = !negate;
Eric Andersenc470f442003-07-28 09:56:35 +000010405 checkkwd = CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010406 } else
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010407 tokpushback = 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010408 n1 = parse_command();
Eric Andersencb57d552001-06-28 07:25:16 +000010409 if (readtoken() == TPIPE) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010410 pipenode = stzalloc(sizeof(struct npipe));
Eric Andersencb57d552001-06-28 07:25:16 +000010411 pipenode->type = NPIPE;
Denis Vlasenko2dc240c2008-07-24 06:07:50 +000010412 /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010413 lp = stzalloc(sizeof(struct nodelist));
Eric Andersencb57d552001-06-28 07:25:16 +000010414 pipenode->npipe.cmdlist = lp;
10415 lp->n = n1;
10416 do {
10417 prev = lp;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010418 lp = stzalloc(sizeof(struct nodelist));
Eric Andersenc470f442003-07-28 09:56:35 +000010419 checkkwd = CHKNL | CHKKWD | CHKALIAS;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010420 lp->n = parse_command();
Eric Andersencb57d552001-06-28 07:25:16 +000010421 prev->next = lp;
10422 } while (readtoken() == TPIPE);
10423 lp->next = NULL;
10424 n1 = pipenode;
10425 }
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010426 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010427 if (negate) {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010428 n2 = stzalloc(sizeof(struct nnot));
Eric Andersencb57d552001-06-28 07:25:16 +000010429 n2->type = NNOT;
10430 n2->nnot.com = n1;
10431 return n2;
Denis Vlasenko2da584f2007-02-19 22:44:05 +000010432 }
10433 return n1;
Eric Andersencb57d552001-06-28 07:25:16 +000010434}
10435
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010436static union node *
10437makename(void)
10438{
10439 union node *n;
10440
Denis Vlasenko597906c2008-02-20 16:38:54 +000010441 n = stzalloc(sizeof(struct narg));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010442 n->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010443 /*n->narg.next = NULL; - stzalloc did it */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010444 n->narg.text = wordtext;
10445 n->narg.backquote = backquotelist;
10446 return n;
10447}
10448
10449static void
10450fixredir(union node *n, const char *text, int err)
10451{
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000010452 int fd;
10453
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010454 TRACE(("Fix redir %s %d\n", text, err));
10455 if (!err)
10456 n->ndup.vname = NULL;
10457
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000010458 fd = bb_strtou(text, NULL, 10);
10459 if (!errno && fd >= 0)
10460 n->ndup.dupfd = fd;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010461 else if (LONE_DASH(text))
10462 n->ndup.dupfd = -1;
10463 else {
10464 if (err)
Denis Vlasenko559691a2008-10-05 18:39:31 +000010465 raise_error_syntax("bad fd number");
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010466 n->ndup.vname = makename();
10467 }
10468}
10469
10470/*
10471 * Returns true if the text contains nothing to expand (no dollar signs
10472 * or backquotes).
10473 */
10474static int
Denis Vlasenko68819d12008-12-15 11:26:36 +000010475noexpand(const char *text)
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010476{
Denys Vlasenkocd716832009-11-28 22:14:02 +010010477 unsigned char c;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010478
Denys Vlasenkocd716832009-11-28 22:14:02 +010010479 while ((c = *text++) != '\0') {
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010480 if (c == CTLQUOTEMARK)
10481 continue;
10482 if (c == CTLESC)
Denys Vlasenkocd716832009-11-28 22:14:02 +010010483 text++;
Denys Vlasenko76bc2d62009-11-29 01:37:46 +010010484 else if (SIT(c, BASESYNTAX) == CCTL)
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010485 return 0;
10486 }
10487 return 1;
10488}
10489
10490static void
10491parsefname(void)
10492{
10493 union node *n = redirnode;
10494
10495 if (readtoken() != TWORD)
10496 raise_error_unexpected_syntax(-1);
10497 if (n->type == NHERE) {
10498 struct heredoc *here = heredoc;
10499 struct heredoc *p;
10500 int i;
10501
10502 if (quoteflag == 0)
10503 n->type = NXHERE;
10504 TRACE(("Here document %d\n", n->type));
10505 if (!noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
Denis Vlasenko559691a2008-10-05 18:39:31 +000010506 raise_error_syntax("illegal eof marker for << redirection");
Denys Vlasenkob6c84342009-08-29 20:23:20 +020010507 rmescapes(wordtext, 0);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010508 here->eofmark = wordtext;
10509 here->next = NULL;
10510 if (heredoclist == NULL)
10511 heredoclist = here;
10512 else {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010513 for (p = heredoclist; p->next; p = p->next)
10514 continue;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010515 p->next = here;
10516 }
10517 } else if (n->type == NTOFD || n->type == NFROMFD) {
10518 fixredir(n, wordtext, 0);
10519 } else {
10520 n->nfile.fname = makename();
10521 }
10522}
Eric Andersencb57d552001-06-28 07:25:16 +000010523
Eric Andersenc470f442003-07-28 09:56:35 +000010524static union node *
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010525simplecmd(void)
10526{
10527 union node *args, **app;
10528 union node *n = NULL;
10529 union node *vars, **vpp;
10530 union node **rpp, *redir;
10531 int savecheckkwd;
Denis Vlasenko80591b02008-03-25 07:49:43 +000010532#if ENABLE_ASH_BASH_COMPAT
10533 smallint double_brackets_flag = 0;
10534#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010535
10536 args = NULL;
10537 app = &args;
10538 vars = NULL;
10539 vpp = &vars;
10540 redir = NULL;
10541 rpp = &redir;
10542
10543 savecheckkwd = CHKALIAS;
10544 for (;;) {
Denis Vlasenko80591b02008-03-25 07:49:43 +000010545 int t;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010546 checkkwd = savecheckkwd;
Denis Vlasenko80591b02008-03-25 07:49:43 +000010547 t = readtoken();
10548 switch (t) {
10549#if ENABLE_ASH_BASH_COMPAT
10550 case TAND: /* "&&" */
10551 case TOR: /* "||" */
10552 if (!double_brackets_flag) {
10553 tokpushback = 1;
10554 goto out;
10555 }
10556 wordtext = (char *) (t == TAND ? "-a" : "-o");
10557#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010558 case TWORD:
Denis Vlasenko597906c2008-02-20 16:38:54 +000010559 n = stzalloc(sizeof(struct narg));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010560 n->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010561 /*n->narg.next = NULL; - stzalloc did it */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010562 n->narg.text = wordtext;
Denis Vlasenko80591b02008-03-25 07:49:43 +000010563#if ENABLE_ASH_BASH_COMPAT
10564 if (strcmp("[[", wordtext) == 0)
10565 double_brackets_flag = 1;
10566 else if (strcmp("]]", wordtext) == 0)
10567 double_brackets_flag = 0;
10568#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010569 n->narg.backquote = backquotelist;
10570 if (savecheckkwd && isassignment(wordtext)) {
10571 *vpp = n;
10572 vpp = &n->narg.next;
10573 } else {
10574 *app = n;
10575 app = &n->narg.next;
10576 savecheckkwd = 0;
10577 }
10578 break;
10579 case TREDIR:
10580 *rpp = n = redirnode;
10581 rpp = &n->nfile.next;
10582 parsefname(); /* read name of redirection file */
10583 break;
10584 case TLP:
10585 if (args && app == &args->narg.next
10586 && !vars && !redir
10587 ) {
10588 struct builtincmd *bcmd;
10589 const char *name;
10590
10591 /* We have a function */
10592 if (readtoken() != TRP)
10593 raise_error_unexpected_syntax(TRP);
10594 name = n->narg.text;
10595 if (!goodname(name)
10596 || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
10597 ) {
Denis Vlasenko559691a2008-10-05 18:39:31 +000010598 raise_error_syntax("bad function name");
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010599 }
10600 n->type = NDEFUN;
10601 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10602 n->narg.next = parse_command();
10603 return n;
10604 }
10605 /* fall through */
10606 default:
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010607 tokpushback = 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010608 goto out;
10609 }
10610 }
10611 out:
10612 *app = NULL;
10613 *vpp = NULL;
10614 *rpp = NULL;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010615 n = stzalloc(sizeof(struct ncmd));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010616 n->type = NCMD;
10617 n->ncmd.args = args;
10618 n->ncmd.assign = vars;
10619 n->ncmd.redirect = redir;
10620 return n;
10621}
10622
10623static union node *
10624parse_command(void)
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010625{
Eric Andersencb57d552001-06-28 07:25:16 +000010626 union node *n1, *n2;
10627 union node *ap, **app;
10628 union node *cp, **cpp;
10629 union node *redir, **rpp;
Eric Andersenc470f442003-07-28 09:56:35 +000010630 union node **rpp2;
Eric Andersencb57d552001-06-28 07:25:16 +000010631 int t;
10632
10633 redir = NULL;
Eric Andersenc470f442003-07-28 09:56:35 +000010634 rpp2 = &redir;
Eric Andersen88cec252001-09-06 17:35:20 +000010635
Eric Andersencb57d552001-06-28 07:25:16 +000010636 switch (readtoken()) {
Eric Andersenc470f442003-07-28 09:56:35 +000010637 default:
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010638 raise_error_unexpected_syntax(-1);
Eric Andersenc470f442003-07-28 09:56:35 +000010639 /* NOTREACHED */
Eric Andersencb57d552001-06-28 07:25:16 +000010640 case TIF:
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010641 n1 = stzalloc(sizeof(struct nif));
Eric Andersencb57d552001-06-28 07:25:16 +000010642 n1->type = NIF;
10643 n1->nif.test = list(0);
10644 if (readtoken() != TTHEN)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010645 raise_error_unexpected_syntax(TTHEN);
Eric Andersencb57d552001-06-28 07:25:16 +000010646 n1->nif.ifpart = list(0);
10647 n2 = n1;
10648 while (readtoken() == TELIF) {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010649 n2->nif.elsepart = stzalloc(sizeof(struct nif));
Eric Andersencb57d552001-06-28 07:25:16 +000010650 n2 = n2->nif.elsepart;
10651 n2->type = NIF;
10652 n2->nif.test = list(0);
10653 if (readtoken() != TTHEN)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010654 raise_error_unexpected_syntax(TTHEN);
Eric Andersencb57d552001-06-28 07:25:16 +000010655 n2->nif.ifpart = list(0);
10656 }
10657 if (lasttoken == TELSE)
10658 n2->nif.elsepart = list(0);
10659 else {
10660 n2->nif.elsepart = NULL;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010661 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010662 }
Eric Andersenc470f442003-07-28 09:56:35 +000010663 t = TFI;
Eric Andersencb57d552001-06-28 07:25:16 +000010664 break;
10665 case TWHILE:
Eric Andersenc470f442003-07-28 09:56:35 +000010666 case TUNTIL: {
Eric Andersencb57d552001-06-28 07:25:16 +000010667 int got;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010668 n1 = stzalloc(sizeof(struct nbinary));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010669 n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
Eric Andersencb57d552001-06-28 07:25:16 +000010670 n1->nbinary.ch1 = list(0);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010671 got = readtoken();
10672 if (got != TDO) {
Denis Vlasenko131ae172007-02-18 13:00:19 +000010673 TRACE(("expecting DO got %s %s\n", tokname(got),
10674 got == TWORD ? wordtext : ""));
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010675 raise_error_unexpected_syntax(TDO);
Eric Andersencb57d552001-06-28 07:25:16 +000010676 }
10677 n1->nbinary.ch2 = list(0);
Eric Andersenc470f442003-07-28 09:56:35 +000010678 t = TDONE;
Eric Andersencb57d552001-06-28 07:25:16 +000010679 break;
10680 }
10681 case TFOR:
Denis Vlasenko2dc240c2008-07-24 06:07:50 +000010682 if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
Denis Vlasenko559691a2008-10-05 18:39:31 +000010683 raise_error_syntax("bad for loop variable");
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010684 n1 = stzalloc(sizeof(struct nfor));
Eric Andersencb57d552001-06-28 07:25:16 +000010685 n1->type = NFOR;
10686 n1->nfor.var = wordtext;
Eric Andersenc470f442003-07-28 09:56:35 +000010687 checkkwd = CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010688 if (readtoken() == TIN) {
10689 app = &ap;
10690 while (readtoken() == TWORD) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010691 n2 = stzalloc(sizeof(struct narg));
Eric Andersencb57d552001-06-28 07:25:16 +000010692 n2->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010693 /*n2->narg.next = NULL; - stzalloc did it */
Eric Andersencb57d552001-06-28 07:25:16 +000010694 n2->narg.text = wordtext;
10695 n2->narg.backquote = backquotelist;
10696 *app = n2;
10697 app = &n2->narg.next;
10698 }
10699 *app = NULL;
10700 n1->nfor.args = ap;
10701 if (lasttoken != TNL && lasttoken != TSEMI)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010702 raise_error_unexpected_syntax(-1);
Eric Andersencb57d552001-06-28 07:25:16 +000010703 } else {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010704 n2 = stzalloc(sizeof(struct narg));
Eric Andersencb57d552001-06-28 07:25:16 +000010705 n2->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010706 /*n2->narg.next = NULL; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000010707 n2->narg.text = (char *)dolatstr;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010708 /*n2->narg.backquote = NULL;*/
Eric Andersencb57d552001-06-28 07:25:16 +000010709 n1->nfor.args = n2;
10710 /*
10711 * Newline or semicolon here is optional (but note
10712 * that the original Bourne shell only allowed NL).
10713 */
10714 if (lasttoken != TNL && lasttoken != TSEMI)
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010715 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010716 }
Eric Andersenc470f442003-07-28 09:56:35 +000010717 checkkwd = CHKNL | CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010718 if (readtoken() != TDO)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010719 raise_error_unexpected_syntax(TDO);
Eric Andersencb57d552001-06-28 07:25:16 +000010720 n1->nfor.body = list(0);
Eric Andersenc470f442003-07-28 09:56:35 +000010721 t = TDONE;
Eric Andersencb57d552001-06-28 07:25:16 +000010722 break;
10723 case TCASE:
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010724 n1 = stzalloc(sizeof(struct ncase));
Eric Andersencb57d552001-06-28 07:25:16 +000010725 n1->type = NCASE;
10726 if (readtoken() != TWORD)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010727 raise_error_unexpected_syntax(TWORD);
Denis Vlasenko597906c2008-02-20 16:38:54 +000010728 n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
Eric Andersencb57d552001-06-28 07:25:16 +000010729 n2->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010730 /*n2->narg.next = NULL; - stzalloc did it */
Eric Andersencb57d552001-06-28 07:25:16 +000010731 n2->narg.text = wordtext;
10732 n2->narg.backquote = backquotelist;
Eric Andersencb57d552001-06-28 07:25:16 +000010733 do {
Eric Andersenc470f442003-07-28 09:56:35 +000010734 checkkwd = CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010735 } while (readtoken() == TNL);
10736 if (lasttoken != TIN)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010737 raise_error_unexpected_syntax(TIN);
Eric Andersencb57d552001-06-28 07:25:16 +000010738 cpp = &n1->ncase.cases;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010739 next_case:
Eric Andersenc470f442003-07-28 09:56:35 +000010740 checkkwd = CHKNL | CHKKWD;
10741 t = readtoken();
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010742 while (t != TESAC) {
Eric Andersencb57d552001-06-28 07:25:16 +000010743 if (lasttoken == TLP)
10744 readtoken();
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010745 *cpp = cp = stzalloc(sizeof(struct nclist));
Eric Andersencb57d552001-06-28 07:25:16 +000010746 cp->type = NCLIST;
10747 app = &cp->nclist.pattern;
10748 for (;;) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010749 *app = ap = stzalloc(sizeof(struct narg));
Eric Andersencb57d552001-06-28 07:25:16 +000010750 ap->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010751 /*ap->narg.next = NULL; - stzalloc did it */
Eric Andersencb57d552001-06-28 07:25:16 +000010752 ap->narg.text = wordtext;
10753 ap->narg.backquote = backquotelist;
Eric Andersenc470f442003-07-28 09:56:35 +000010754 if (readtoken() != TPIPE)
Eric Andersencb57d552001-06-28 07:25:16 +000010755 break;
10756 app = &ap->narg.next;
10757 readtoken();
10758 }
Denis Vlasenko597906c2008-02-20 16:38:54 +000010759 //ap->narg.next = NULL;
Eric Andersencb57d552001-06-28 07:25:16 +000010760 if (lasttoken != TRP)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010761 raise_error_unexpected_syntax(TRP);
Eric Andersenc470f442003-07-28 09:56:35 +000010762 cp->nclist.body = list(2);
Eric Andersencb57d552001-06-28 07:25:16 +000010763
Eric Andersenc470f442003-07-28 09:56:35 +000010764 cpp = &cp->nclist.next;
10765
10766 checkkwd = CHKNL | CHKKWD;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010767 t = readtoken();
10768 if (t != TESAC) {
Eric Andersencb57d552001-06-28 07:25:16 +000010769 if (t != TENDCASE)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010770 raise_error_unexpected_syntax(TENDCASE);
10771 goto next_case;
Eric Andersencb57d552001-06-28 07:25:16 +000010772 }
Eric Andersenc470f442003-07-28 09:56:35 +000010773 }
Eric Andersencb57d552001-06-28 07:25:16 +000010774 *cpp = NULL;
Eric Andersenc470f442003-07-28 09:56:35 +000010775 goto redir;
Eric Andersencb57d552001-06-28 07:25:16 +000010776 case TLP:
Denis Vlasenko597906c2008-02-20 16:38:54 +000010777 n1 = stzalloc(sizeof(struct nredir));
Eric Andersencb57d552001-06-28 07:25:16 +000010778 n1->type = NSUBSHELL;
10779 n1->nredir.n = list(0);
Denis Vlasenko597906c2008-02-20 16:38:54 +000010780 /*n1->nredir.redirect = NULL; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000010781 t = TRP;
Eric Andersencb57d552001-06-28 07:25:16 +000010782 break;
10783 case TBEGIN:
10784 n1 = list(0);
Eric Andersenc470f442003-07-28 09:56:35 +000010785 t = TEND;
Eric Andersencb57d552001-06-28 07:25:16 +000010786 break;
Eric Andersencb57d552001-06-28 07:25:16 +000010787 case TWORD:
Eric Andersenc470f442003-07-28 09:56:35 +000010788 case TREDIR:
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010789 tokpushback = 1;
Eric Andersenc470f442003-07-28 09:56:35 +000010790 return simplecmd();
Eric Andersencb57d552001-06-28 07:25:16 +000010791 }
10792
Eric Andersenc470f442003-07-28 09:56:35 +000010793 if (readtoken() != t)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010794 raise_error_unexpected_syntax(t);
Eric Andersenc470f442003-07-28 09:56:35 +000010795
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010796 redir:
Eric Andersencb57d552001-06-28 07:25:16 +000010797 /* Now check for redirection which may follow command */
Eric Andersenc470f442003-07-28 09:56:35 +000010798 checkkwd = CHKKWD | CHKALIAS;
10799 rpp = rpp2;
Eric Andersencb57d552001-06-28 07:25:16 +000010800 while (readtoken() == TREDIR) {
10801 *rpp = n2 = redirnode;
10802 rpp = &n2->nfile.next;
10803 parsefname();
10804 }
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010805 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010806 *rpp = NULL;
10807 if (redir) {
10808 if (n1->type != NSUBSHELL) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010809 n2 = stzalloc(sizeof(struct nredir));
Eric Andersencb57d552001-06-28 07:25:16 +000010810 n2->type = NREDIR;
10811 n2->nredir.n = n1;
10812 n1 = n2;
10813 }
10814 n1->nredir.redirect = redir;
10815 }
Eric Andersencb57d552001-06-28 07:25:16 +000010816 return n1;
10817}
10818
Denis Vlasenkoef527f52008-06-23 01:52:30 +000010819#if ENABLE_ASH_BASH_COMPAT
10820static int decode_dollar_squote(void)
10821{
10822 static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
10823 int c, cnt;
10824 char *p;
10825 char buf[4];
10826
10827 c = pgetc();
10828 p = strchr(C_escapes, c);
10829 if (p) {
10830 buf[0] = c;
10831 p = buf;
10832 cnt = 3;
10833 if ((unsigned char)(c - '0') <= 7) { /* \ooo */
10834 do {
10835 c = pgetc();
10836 *++p = c;
10837 } while ((unsigned char)(c - '0') <= 7 && --cnt);
10838 pungetc();
10839 } else if (c == 'x') { /* \xHH */
10840 do {
10841 c = pgetc();
10842 *++p = c;
10843 } while (isxdigit(c) && --cnt);
10844 pungetc();
10845 if (cnt == 3) { /* \x but next char is "bad" */
10846 c = 'x';
10847 goto unrecognized;
10848 }
10849 } else { /* simple seq like \\ or \t */
10850 p++;
10851 }
10852 *p = '\0';
10853 p = buf;
10854 c = bb_process_escape_sequence((void*)&p);
10855 } else { /* unrecognized "\z": print both chars unless ' or " */
10856 if (c != '\'' && c != '"') {
10857 unrecognized:
10858 c |= 0x100; /* "please encode \, then me" */
10859 }
10860 }
10861 return c;
10862}
10863#endif
10864
Eric Andersencb57d552001-06-28 07:25:16 +000010865/*
10866 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
10867 * is not NULL, read a here document. In the latter case, eofmark is the
10868 * word which marks the end of the document and striptabs is true if
Denys Vlasenkocd716832009-11-28 22:14:02 +010010869 * leading tabs should be stripped from the document. The argument c
Eric Andersencb57d552001-06-28 07:25:16 +000010870 * is the first character of the input token or document.
10871 *
10872 * Because C does not have internal subroutines, I have simulated them
10873 * using goto's to implement the subroutine linkage. The following macros
10874 * will run code that appears at the end of readtoken1.
10875 */
Eric Andersen2870d962001-07-02 17:27:21 +000010876#define CHECKEND() {goto checkend; checkend_return:;}
10877#define PARSEREDIR() {goto parseredir; parseredir_return:;}
10878#define PARSESUB() {goto parsesub; parsesub_return:;}
10879#define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
10880#define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
10881#define PARSEARITH() {goto parsearith; parsearith_return:;}
Eric Andersencb57d552001-06-28 07:25:16 +000010882static int
Denys Vlasenkocd716832009-11-28 22:14:02 +010010883readtoken1(int c, int syntax, char *eofmark, int striptabs)
Manuel Novoa III 16815d42001-08-10 19:36:07 +000010884{
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010885 /* NB: syntax parameter fits into smallint */
Denys Vlasenkocd716832009-11-28 22:14:02 +010010886 /* c parameter is an unsigned char or PEOF or PEOA */
Eric Andersencb57d552001-06-28 07:25:16 +000010887 char *out;
10888 int len;
10889 char line[EOFMARKLEN + 1];
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010890 struct nodelist *bqlist;
10891 smallint quotef;
10892 smallint dblquote;
10893 smallint oldstyle;
10894 smallint prevsyntax; /* syntax before arithmetic */
Denis Vlasenko46a53062007-09-24 18:30:02 +000010895#if ENABLE_ASH_EXPAND_PRMT
10896 smallint pssyntax; /* we are expanding a prompt string */
10897#endif
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010898 int varnest; /* levels of variables expansion */
10899 int arinest; /* levels of arithmetic expansion */
10900 int parenlevel; /* levels of parens in arithmetic */
10901 int dqvarnest; /* levels of variables expansion within double quotes */
10902
Denis Vlasenko5e34ff22009-04-21 11:09:40 +000010903 IF_ASH_BASH_COMPAT(smallint bash_dollar_squote = 0;)
Denis Vlasenkoef527f52008-06-23 01:52:30 +000010904
Eric Andersencb57d552001-06-28 07:25:16 +000010905#if __GNUC__
10906 /* Avoid longjmp clobbering */
10907 (void) &out;
10908 (void) &quotef;
10909 (void) &dblquote;
10910 (void) &varnest;
10911 (void) &arinest;
10912 (void) &parenlevel;
10913 (void) &dqvarnest;
10914 (void) &oldstyle;
10915 (void) &prevsyntax;
10916 (void) &syntax;
10917#endif
Denis Vlasenko41eb3002008-11-28 03:42:31 +000010918 startlinno = g_parsefile->linno;
Eric Andersencb57d552001-06-28 07:25:16 +000010919 bqlist = NULL;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010920 quotef = 0;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010921 oldstyle = 0;
10922 prevsyntax = 0;
Denis Vlasenko46a53062007-09-24 18:30:02 +000010923#if ENABLE_ASH_EXPAND_PRMT
10924 pssyntax = (syntax == PSSYNTAX);
10925 if (pssyntax)
10926 syntax = DQSYNTAX;
10927#endif
10928 dblquote = (syntax == DQSYNTAX);
Eric Andersencb57d552001-06-28 07:25:16 +000010929 varnest = 0;
10930 arinest = 0;
10931 parenlevel = 0;
10932 dqvarnest = 0;
10933
10934 STARTSTACKSTR(out);
Denis Vlasenko176d49d2008-10-06 09:51:47 +000010935 loop:
10936 /* For each line, until end of word */
10937 {
Eric Andersenc470f442003-07-28 09:56:35 +000010938 CHECKEND(); /* set c to PEOF if at end of here document */
10939 for (;;) { /* until end of line or end of word */
10940 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
Denis Vlasenkobf0a2012006-12-26 10:42:51 +000010941 switch (SIT(c, syntax)) {
Eric Andersenc470f442003-07-28 09:56:35 +000010942 case CNL: /* '\n' */
Eric Andersencb57d552001-06-28 07:25:16 +000010943 if (syntax == BASESYNTAX)
Eric Andersenc470f442003-07-28 09:56:35 +000010944 goto endword; /* exit outer loop */
Eric Andersencb57d552001-06-28 07:25:16 +000010945 USTPUTC(c, out);
Denis Vlasenko41eb3002008-11-28 03:42:31 +000010946 g_parsefile->linno++;
Eric Andersencb57d552001-06-28 07:25:16 +000010947 if (doprompt)
10948 setprompt(2);
Eric Andersencb57d552001-06-28 07:25:16 +000010949 c = pgetc();
Eric Andersenc470f442003-07-28 09:56:35 +000010950 goto loop; /* continue outer loop */
Eric Andersencb57d552001-06-28 07:25:16 +000010951 case CWORD:
10952 USTPUTC(c, out);
10953 break;
10954 case CCTL:
Eric Andersenc470f442003-07-28 09:56:35 +000010955 if (eofmark == NULL || dblquote)
Eric Andersencb57d552001-06-28 07:25:16 +000010956 USTPUTC(CTLESC, out);
Denis Vlasenkoef527f52008-06-23 01:52:30 +000010957#if ENABLE_ASH_BASH_COMPAT
10958 if (c == '\\' && bash_dollar_squote) {
10959 c = decode_dollar_squote();
10960 if (c & 0x100) {
10961 USTPUTC('\\', out);
10962 c = (unsigned char)c;
10963 }
10964 }
10965#endif
Eric Andersencb57d552001-06-28 07:25:16 +000010966 USTPUTC(c, out);
10967 break;
Eric Andersenc470f442003-07-28 09:56:35 +000010968 case CBACK: /* backslash */
Denys Vlasenko2ce42e92009-11-29 02:18:13 +010010969 c = pgetc_without_PEOA();
Eric Andersencb57d552001-06-28 07:25:16 +000010970 if (c == PEOF) {
Eric Andersenc470f442003-07-28 09:56:35 +000010971 USTPUTC(CTLESC, out);
Eric Andersencb57d552001-06-28 07:25:16 +000010972 USTPUTC('\\', out);
10973 pungetc();
10974 } else if (c == '\n') {
10975 if (doprompt)
10976 setprompt(2);
Eric Andersencb57d552001-06-28 07:25:16 +000010977 } else {
Denis Vlasenko46a53062007-09-24 18:30:02 +000010978#if ENABLE_ASH_EXPAND_PRMT
10979 if (c == '$' && pssyntax) {
10980 USTPUTC(CTLESC, out);
10981 USTPUTC('\\', out);
10982 }
10983#endif
Denis Vlasenkoef527f52008-06-23 01:52:30 +000010984 if (dblquote && c != '\\'
10985 && c != '`' && c != '$'
10986 && (c != '"' || eofmark != NULL)
Eric Andersenc470f442003-07-28 09:56:35 +000010987 ) {
10988 USTPUTC(CTLESC, out);
Eric Andersencb57d552001-06-28 07:25:16 +000010989 USTPUTC('\\', out);
Eric Andersenc470f442003-07-28 09:56:35 +000010990 }
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010991 if (SIT(c, SQSYNTAX) == CCTL)
Eric Andersencb57d552001-06-28 07:25:16 +000010992 USTPUTC(CTLESC, out);
Eric Andersencb57d552001-06-28 07:25:16 +000010993 USTPUTC(c, out);
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010994 quotef = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010995 }
10996 break;
10997 case CSQUOTE:
Eric Andersencb57d552001-06-28 07:25:16 +000010998 syntax = SQSYNTAX;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010999 quotemark:
Eric Andersenc470f442003-07-28 09:56:35 +000011000 if (eofmark == NULL) {
11001 USTPUTC(CTLQUOTEMARK, out);
11002 }
Eric Andersencb57d552001-06-28 07:25:16 +000011003 break;
11004 case CDQUOTE:
Eric Andersencb57d552001-06-28 07:25:16 +000011005 syntax = DQSYNTAX;
11006 dblquote = 1;
Eric Andersenc470f442003-07-28 09:56:35 +000011007 goto quotemark;
Eric Andersencb57d552001-06-28 07:25:16 +000011008 case CENDQUOTE:
Denis Vlasenko5e34ff22009-04-21 11:09:40 +000011009 IF_ASH_BASH_COMPAT(bash_dollar_squote = 0;)
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011010 if (eofmark != NULL && arinest == 0
11011 && varnest == 0
11012 ) {
Eric Andersencb57d552001-06-28 07:25:16 +000011013 USTPUTC(c, out);
11014 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000011015 if (dqvarnest == 0) {
Eric Andersencb57d552001-06-28 07:25:16 +000011016 syntax = BASESYNTAX;
11017 dblquote = 0;
11018 }
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011019 quotef = 1;
Eric Andersenc470f442003-07-28 09:56:35 +000011020 goto quotemark;
Eric Andersencb57d552001-06-28 07:25:16 +000011021 }
11022 break;
Eric Andersenc470f442003-07-28 09:56:35 +000011023 case CVAR: /* '$' */
11024 PARSESUB(); /* parse substitution */
Eric Andersencb57d552001-06-28 07:25:16 +000011025 break;
Eric Andersenc470f442003-07-28 09:56:35 +000011026 case CENDVAR: /* '}' */
Eric Andersencb57d552001-06-28 07:25:16 +000011027 if (varnest > 0) {
11028 varnest--;
11029 if (dqvarnest > 0) {
11030 dqvarnest--;
11031 }
11032 USTPUTC(CTLENDVAR, out);
11033 } else {
11034 USTPUTC(c, out);
11035 }
11036 break;
Mike Frysinger98c52642009-04-02 10:02:37 +000011037#if ENABLE_SH_MATH_SUPPORT
Eric Andersenc470f442003-07-28 09:56:35 +000011038 case CLP: /* '(' in arithmetic */
Eric Andersencb57d552001-06-28 07:25:16 +000011039 parenlevel++;
11040 USTPUTC(c, out);
11041 break;
Eric Andersenc470f442003-07-28 09:56:35 +000011042 case CRP: /* ')' in arithmetic */
Eric Andersencb57d552001-06-28 07:25:16 +000011043 if (parenlevel > 0) {
11044 USTPUTC(c, out);
11045 --parenlevel;
11046 } else {
11047 if (pgetc() == ')') {
11048 if (--arinest == 0) {
11049 USTPUTC(CTLENDARI, out);
11050 syntax = prevsyntax;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011051 dblquote = (syntax == DQSYNTAX);
Eric Andersencb57d552001-06-28 07:25:16 +000011052 } else
11053 USTPUTC(')', out);
11054 } else {
11055 /*
11056 * unbalanced parens
11057 * (don't 2nd guess - no error)
11058 */
11059 pungetc();
11060 USTPUTC(')', out);
11061 }
11062 }
11063 break;
11064#endif
Eric Andersenc470f442003-07-28 09:56:35 +000011065 case CBQUOTE: /* '`' */
Eric Andersencb57d552001-06-28 07:25:16 +000011066 PARSEBACKQOLD();
11067 break;
Eric Andersen2870d962001-07-02 17:27:21 +000011068 case CENDFILE:
Eric Andersenc470f442003-07-28 09:56:35 +000011069 goto endword; /* exit outer loop */
Eric Andersencb57d552001-06-28 07:25:16 +000011070 case CIGN:
11071 break;
11072 default:
Denis Vlasenko834dee72008-10-07 09:18:30 +000011073 if (varnest == 0) {
11074#if ENABLE_ASH_BASH_COMPAT
11075 if (c == '&') {
11076 if (pgetc() == '>')
11077 c = 0x100 + '>'; /* flag &> */
11078 pungetc();
11079 }
11080#endif
Eric Andersenc470f442003-07-28 09:56:35 +000011081 goto endword; /* exit outer loop */
Denis Vlasenko834dee72008-10-07 09:18:30 +000011082 }
Denys Vlasenko2ce42e92009-11-29 02:18:13 +010011083 IF_ASH_ALIAS(if (c != PEOA))
Eric Andersencb57d552001-06-28 07:25:16 +000011084 USTPUTC(c, out);
Eric Andersen3102ac42001-07-06 04:26:23 +000011085
Eric Andersencb57d552001-06-28 07:25:16 +000011086 }
Denis Vlasenko834dee72008-10-07 09:18:30 +000011087 c = pgetc_fast();
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000011088 } /* for (;;) */
Eric Andersencb57d552001-06-28 07:25:16 +000011089 }
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011090 endword:
Mike Frysinger98c52642009-04-02 10:02:37 +000011091#if ENABLE_SH_MATH_SUPPORT
Eric Andersencb57d552001-06-28 07:25:16 +000011092 if (syntax == ARISYNTAX)
Denis Vlasenko559691a2008-10-05 18:39:31 +000011093 raise_error_syntax("missing '))'");
Eric Andersenc470f442003-07-28 09:56:35 +000011094#endif
Denis Vlasenko99eb8502007-02-23 21:09:49 +000011095 if (syntax != BASESYNTAX && !parsebackquote && eofmark == NULL)
Denis Vlasenko559691a2008-10-05 18:39:31 +000011096 raise_error_syntax("unterminated quoted string");
Eric Andersencb57d552001-06-28 07:25:16 +000011097 if (varnest != 0) {
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011098 startlinno = g_parsefile->linno;
Eric Andersenc470f442003-07-28 09:56:35 +000011099 /* { */
Denis Vlasenko559691a2008-10-05 18:39:31 +000011100 raise_error_syntax("missing '}'");
Eric Andersencb57d552001-06-28 07:25:16 +000011101 }
11102 USTPUTC('\0', out);
Eric Andersenc470f442003-07-28 09:56:35 +000011103 len = out - (char *)stackblock();
Eric Andersencb57d552001-06-28 07:25:16 +000011104 out = stackblock();
11105 if (eofmark == NULL) {
Denis Vlasenko5e34ff22009-04-21 11:09:40 +000011106 if ((c == '>' || c == '<' IF_ASH_BASH_COMPAT( || c == 0x100 + '>'))
Denis Vlasenko834dee72008-10-07 09:18:30 +000011107 && quotef == 0
11108 ) {
Denis Vlasenko559691a2008-10-05 18:39:31 +000011109 if (isdigit_str9(out)) {
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000011110 PARSEREDIR(); /* passed as params: out, c */
11111 lasttoken = TREDIR;
11112 return lasttoken;
11113 }
11114 /* else: non-number X seen, interpret it
11115 * as "NNNX>file" = "NNNX >file" */
Eric Andersencb57d552001-06-28 07:25:16 +000011116 }
Denis Vlasenkoef527f52008-06-23 01:52:30 +000011117 pungetc();
Eric Andersencb57d552001-06-28 07:25:16 +000011118 }
11119 quoteflag = quotef;
11120 backquotelist = bqlist;
11121 grabstackblock(len);
11122 wordtext = out;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011123 lasttoken = TWORD;
11124 return lasttoken;
Eric Andersencb57d552001-06-28 07:25:16 +000011125/* end of readtoken routine */
11126
Eric Andersencb57d552001-06-28 07:25:16 +000011127/*
11128 * Check to see whether we are at the end of the here document. When this
11129 * is called, c is set to the first character of the next input line. If
11130 * we are at the end of the here document, this routine sets the c to PEOF.
11131 */
Eric Andersenc470f442003-07-28 09:56:35 +000011132checkend: {
11133 if (eofmark) {
Denis Vlasenko131ae172007-02-18 13:00:19 +000011134#if ENABLE_ASH_ALIAS
Denys Vlasenko2ce42e92009-11-29 02:18:13 +010011135 if (c == PEOA)
11136 c = pgetc_without_PEOA();
Eric Andersenc470f442003-07-28 09:56:35 +000011137#endif
11138 if (striptabs) {
11139 while (c == '\t') {
Denys Vlasenko2ce42e92009-11-29 02:18:13 +010011140 c = pgetc_without_PEOA();
Eric Andersencb57d552001-06-28 07:25:16 +000011141 }
Eric Andersenc470f442003-07-28 09:56:35 +000011142 }
11143 if (c == *eofmark) {
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011144 if (pfgets(line, sizeof(line)) != NULL) {
Eric Andersenc470f442003-07-28 09:56:35 +000011145 char *p, *q;
Eric Andersencb57d552001-06-28 07:25:16 +000011146
Eric Andersenc470f442003-07-28 09:56:35 +000011147 p = line;
Denis Vlasenkof7d56652008-03-25 05:51:41 +000011148 for (q = eofmark + 1; *q && *p == *q; p++, q++)
11149 continue;
Eric Andersenc470f442003-07-28 09:56:35 +000011150 if (*p == '\n' && *q == '\0') {
11151 c = PEOF;
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011152 g_parsefile->linno++;
Eric Andersenc470f442003-07-28 09:56:35 +000011153 needprompt = doprompt;
11154 } else {
11155 pushstring(line, NULL);
Eric Andersencb57d552001-06-28 07:25:16 +000011156 }
11157 }
11158 }
11159 }
Eric Andersenc470f442003-07-28 09:56:35 +000011160 goto checkend_return;
11161}
Eric Andersencb57d552001-06-28 07:25:16 +000011162
Eric Andersencb57d552001-06-28 07:25:16 +000011163/*
11164 * Parse a redirection operator. The variable "out" points to a string
11165 * specifying the fd to be redirected. The variable "c" contains the
11166 * first character of the redirection operator.
11167 */
Eric Andersenc470f442003-07-28 09:56:35 +000011168parseredir: {
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000011169 /* out is already checked to be a valid number or "" */
11170 int fd = (*out == '\0' ? -1 : atoi(out));
Eric Andersenc470f442003-07-28 09:56:35 +000011171 union node *np;
Eric Andersencb57d552001-06-28 07:25:16 +000011172
Denis Vlasenko597906c2008-02-20 16:38:54 +000011173 np = stzalloc(sizeof(struct nfile));
Eric Andersenc470f442003-07-28 09:56:35 +000011174 if (c == '>') {
11175 np->nfile.fd = 1;
11176 c = pgetc();
11177 if (c == '>')
11178 np->type = NAPPEND;
11179 else if (c == '|')
11180 np->type = NCLOBBER;
11181 else if (c == '&')
11182 np->type = NTOFD;
Denis Vlasenko559691a2008-10-05 18:39:31 +000011183 /* it also can be NTO2 (>&file), but we can't figure it out yet */
Eric Andersenc470f442003-07-28 09:56:35 +000011184 else {
11185 np->type = NTO;
11186 pungetc();
Eric Andersencb57d552001-06-28 07:25:16 +000011187 }
Denis Vlasenko834dee72008-10-07 09:18:30 +000011188 }
11189#if ENABLE_ASH_BASH_COMPAT
11190 else if (c == 0x100 + '>') { /* this flags &> redirection */
11191 np->nfile.fd = 1;
11192 pgetc(); /* this is '>', no need to check */
11193 np->type = NTO2;
11194 }
11195#endif
11196 else { /* c == '<' */
Denis Vlasenko597906c2008-02-20 16:38:54 +000011197 /*np->nfile.fd = 0; - stzalloc did it */
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011198 c = pgetc();
11199 switch (c) {
Eric Andersenc470f442003-07-28 09:56:35 +000011200 case '<':
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011201 if (sizeof(struct nfile) != sizeof(struct nhere)) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000011202 np = stzalloc(sizeof(struct nhere));
11203 /*np->nfile.fd = 0; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000011204 }
11205 np->type = NHERE;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000011206 heredoc = stzalloc(sizeof(struct heredoc));
Eric Andersenc470f442003-07-28 09:56:35 +000011207 heredoc->here = np;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011208 c = pgetc();
11209 if (c == '-') {
Eric Andersenc470f442003-07-28 09:56:35 +000011210 heredoc->striptabs = 1;
11211 } else {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000011212 /*heredoc->striptabs = 0; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000011213 pungetc();
11214 }
11215 break;
11216
11217 case '&':
11218 np->type = NFROMFD;
11219 break;
11220
11221 case '>':
11222 np->type = NFROMTO;
11223 break;
11224
11225 default:
11226 np->type = NFROM;
11227 pungetc();
11228 break;
11229 }
Eric Andersencb57d552001-06-28 07:25:16 +000011230 }
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000011231 if (fd >= 0)
11232 np->nfile.fd = fd;
Eric Andersenc470f442003-07-28 09:56:35 +000011233 redirnode = np;
11234 goto parseredir_return;
11235}
Eric Andersencb57d552001-06-28 07:25:16 +000011236
Eric Andersencb57d552001-06-28 07:25:16 +000011237/*
11238 * Parse a substitution. At this point, we have read the dollar sign
11239 * and nothing else.
11240 */
Denis Vlasenkocc571512007-02-23 21:10:35 +000011241
11242/* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
11243 * (assuming ascii char codes, as the original implementation did) */
11244#define is_special(c) \
Denis Vlasenkoef527f52008-06-23 01:52:30 +000011245 (((unsigned)(c) - 33 < 32) \
11246 && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
Eric Andersenc470f442003-07-28 09:56:35 +000011247parsesub: {
Denys Vlasenkocd716832009-11-28 22:14:02 +010011248 unsigned char subtype;
Eric Andersenc470f442003-07-28 09:56:35 +000011249 int typeloc;
11250 int flags;
11251 char *p;
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011252 static const char types[] ALIGN1 = "}-+?=";
Eric Andersencb57d552001-06-28 07:25:16 +000011253
Eric Andersenc470f442003-07-28 09:56:35 +000011254 c = pgetc();
Denys Vlasenkocd716832009-11-28 22:14:02 +010011255 if (c > 255 /* PEOA or PEOF */
Denis Vlasenkoef527f52008-06-23 01:52:30 +000011256 || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
Eric Andersenc470f442003-07-28 09:56:35 +000011257 ) {
Denis Vlasenkoef527f52008-06-23 01:52:30 +000011258#if ENABLE_ASH_BASH_COMPAT
11259 if (c == '\'')
11260 bash_dollar_squote = 1;
11261 else
11262#endif
11263 USTPUTC('$', out);
Eric Andersenc470f442003-07-28 09:56:35 +000011264 pungetc();
11265 } else if (c == '(') { /* $(command) or $((arith)) */
11266 if (pgetc() == '(') {
Mike Frysinger98c52642009-04-02 10:02:37 +000011267#if ENABLE_SH_MATH_SUPPORT
Eric Andersenc470f442003-07-28 09:56:35 +000011268 PARSEARITH();
11269#else
Mike Frysinger98a6f562008-06-09 09:38:45 +000011270 raise_error_syntax("you disabled math support for $((arith)) syntax");
Eric Andersenc470f442003-07-28 09:56:35 +000011271#endif
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000011272 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000011273 pungetc();
11274 PARSEBACKQNEW();
11275 }
11276 } else {
11277 USTPUTC(CTLVAR, out);
11278 typeloc = out - (char *)stackblock();
11279 USTPUTC(VSNORMAL, out);
11280 subtype = VSNORMAL;
11281 if (c == '{') {
11282 c = pgetc();
11283 if (c == '#') {
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011284 c = pgetc();
11285 if (c == '}')
Eric Andersenc470f442003-07-28 09:56:35 +000011286 c = '#';
11287 else
11288 subtype = VSLENGTH;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011289 } else
Eric Andersenc470f442003-07-28 09:56:35 +000011290 subtype = 0;
11291 }
Denys Vlasenkocd716832009-11-28 22:14:02 +010011292 if (c <= 255 /* not PEOA or PEOF */ && is_name(c)) {
Eric Andersenc470f442003-07-28 09:56:35 +000011293 do {
11294 STPUTC(c, out);
Eric Andersencb57d552001-06-28 07:25:16 +000011295 c = pgetc();
Denys Vlasenkocd716832009-11-28 22:14:02 +010011296 } while (c <= 255 /* not PEOA or PEOF */ && is_in_name(c));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011297 } else if (isdigit(c)) {
Eric Andersenc470f442003-07-28 09:56:35 +000011298 do {
11299 STPUTC(c, out);
11300 c = pgetc();
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011301 } while (isdigit(c));
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011302 } else if (is_special(c)) {
Eric Andersenc470f442003-07-28 09:56:35 +000011303 USTPUTC(c, out);
11304 c = pgetc();
Denis Vlasenko559691a2008-10-05 18:39:31 +000011305 } else {
11306 badsub:
11307 raise_error_syntax("bad substitution");
11308 }
Cristian Ionescu-Idbohrn301f5ec2009-10-05 02:07:23 +020011309 if (c != '}' && subtype == VSLENGTH)
11310 goto badsub;
Eric Andersencb57d552001-06-28 07:25:16 +000011311
Eric Andersenc470f442003-07-28 09:56:35 +000011312 STPUTC('=', out);
11313 flags = 0;
11314 if (subtype == 0) {
11315 switch (c) {
11316 case ':':
Eric Andersenc470f442003-07-28 09:56:35 +000011317 c = pgetc();
Denis Vlasenko92e13c22008-03-25 01:17:40 +000011318#if ENABLE_ASH_BASH_COMPAT
11319 if (c == ':' || c == '$' || isdigit(c)) {
11320 pungetc();
11321 subtype = VSSUBSTR;
11322 break;
11323 }
11324#endif
11325 flags = VSNUL;
Eric Andersenc470f442003-07-28 09:56:35 +000011326 /*FALLTHROUGH*/
11327 default:
11328 p = strchr(types, c);
11329 if (p == NULL)
11330 goto badsub;
11331 subtype = p - types + VSNORMAL;
11332 break;
11333 case '%':
Denis Vlasenko92e13c22008-03-25 01:17:40 +000011334 case '#': {
11335 int cc = c;
11336 subtype = c == '#' ? VSTRIMLEFT : VSTRIMRIGHT;
11337 c = pgetc();
11338 if (c == cc)
11339 subtype++;
11340 else
11341 pungetc();
11342 break;
11343 }
11344#if ENABLE_ASH_BASH_COMPAT
11345 case '/':
11346 subtype = VSREPLACE;
11347 c = pgetc();
11348 if (c == '/')
11349 subtype++; /* VSREPLACEALL */
11350 else
11351 pungetc();
11352 break;
11353#endif
Eric Andersencb57d552001-06-28 07:25:16 +000011354 }
Eric Andersenc470f442003-07-28 09:56:35 +000011355 } else {
11356 pungetc();
11357 }
11358 if (dblquote || arinest)
11359 flags |= VSQUOTE;
Denys Vlasenkocd716832009-11-28 22:14:02 +010011360 ((unsigned char *)stackblock())[typeloc] = subtype | flags;
Eric Andersenc470f442003-07-28 09:56:35 +000011361 if (subtype != VSNORMAL) {
11362 varnest++;
11363 if (dblquote || arinest) {
11364 dqvarnest++;
Eric Andersencb57d552001-06-28 07:25:16 +000011365 }
11366 }
11367 }
Eric Andersenc470f442003-07-28 09:56:35 +000011368 goto parsesub_return;
11369}
Eric Andersencb57d552001-06-28 07:25:16 +000011370
Eric Andersencb57d552001-06-28 07:25:16 +000011371/*
11372 * Called to parse command substitutions. Newstyle is set if the command
11373 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
11374 * list of commands (passed by reference), and savelen is the number of
11375 * characters on the top of the stack which must be preserved.
11376 */
Eric Andersenc470f442003-07-28 09:56:35 +000011377parsebackq: {
11378 struct nodelist **nlpp;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011379 smallint savepbq;
Eric Andersenc470f442003-07-28 09:56:35 +000011380 union node *n;
11381 char *volatile str;
11382 struct jmploc jmploc;
11383 struct jmploc *volatile savehandler;
11384 size_t savelen;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011385 smallint saveprompt = 0;
11386
Eric Andersencb57d552001-06-28 07:25:16 +000011387#ifdef __GNUC__
Eric Andersenc470f442003-07-28 09:56:35 +000011388 (void) &saveprompt;
Eric Andersencb57d552001-06-28 07:25:16 +000011389#endif
Eric Andersenc470f442003-07-28 09:56:35 +000011390 savepbq = parsebackquote;
11391 if (setjmp(jmploc.loc)) {
Denis Vlasenko60818682007-09-28 22:07:23 +000011392 free(str);
Eric Andersenc470f442003-07-28 09:56:35 +000011393 parsebackquote = 0;
Denis Vlasenko2da584f2007-02-19 22:44:05 +000011394 exception_handler = savehandler;
11395 longjmp(exception_handler->loc, 1);
Eric Andersenc470f442003-07-28 09:56:35 +000011396 }
Denis Vlasenkob012b102007-02-19 22:43:01 +000011397 INT_OFF;
Eric Andersenc470f442003-07-28 09:56:35 +000011398 str = NULL;
11399 savelen = out - (char *)stackblock();
11400 if (savelen > 0) {
11401 str = ckmalloc(savelen);
11402 memcpy(str, stackblock(), savelen);
11403 }
Denis Vlasenko2da584f2007-02-19 22:44:05 +000011404 savehandler = exception_handler;
11405 exception_handler = &jmploc;
Denis Vlasenkob012b102007-02-19 22:43:01 +000011406 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +000011407 if (oldstyle) {
11408 /* We must read until the closing backquote, giving special
11409 treatment to some slashes, and then push the string and
11410 reread it as input, interpreting it normally. */
11411 char *pout;
11412 int pc;
11413 size_t psavelen;
11414 char *pstr;
11415
11416
11417 STARTSTACKSTR(pout);
11418 for (;;) {
11419 if (needprompt) {
11420 setprompt(2);
Eric Andersenc470f442003-07-28 09:56:35 +000011421 }
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011422 pc = pgetc();
11423 switch (pc) {
Eric Andersenc470f442003-07-28 09:56:35 +000011424 case '`':
11425 goto done;
11426
11427 case '\\':
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011428 pc = pgetc();
11429 if (pc == '\n') {
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011430 g_parsefile->linno++;
Eric Andersenc470f442003-07-28 09:56:35 +000011431 if (doprompt)
11432 setprompt(2);
11433 /*
11434 * If eating a newline, avoid putting
11435 * the newline into the new character
11436 * stream (via the STPUTC after the
11437 * switch).
11438 */
11439 continue;
11440 }
11441 if (pc != '\\' && pc != '`' && pc != '$'
Denys Vlasenko76bc2d62009-11-29 01:37:46 +010011442 && (!dblquote || pc != '"')
11443 ) {
Eric Andersenc470f442003-07-28 09:56:35 +000011444 STPUTC('\\', pout);
Denys Vlasenko76bc2d62009-11-29 01:37:46 +010011445 }
Denys Vlasenkocd716832009-11-28 22:14:02 +010011446 if (pc <= 255 /* not PEOA or PEOF */) {
Eric Andersenc470f442003-07-28 09:56:35 +000011447 break;
11448 }
11449 /* fall through */
11450
11451 case PEOF:
Denys Vlasenko2ce42e92009-11-29 02:18:13 +010011452 IF_ASH_ALIAS(case PEOA:)
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011453 startlinno = g_parsefile->linno;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000011454 raise_error_syntax("EOF in backquote substitution");
Eric Andersenc470f442003-07-28 09:56:35 +000011455
11456 case '\n':
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011457 g_parsefile->linno++;
Eric Andersenc470f442003-07-28 09:56:35 +000011458 needprompt = doprompt;
11459 break;
11460
11461 default:
11462 break;
11463 }
11464 STPUTC(pc, pout);
11465 }
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011466 done:
Eric Andersenc470f442003-07-28 09:56:35 +000011467 STPUTC('\0', pout);
11468 psavelen = pout - (char *)stackblock();
11469 if (psavelen > 0) {
11470 pstr = grabstackstr(pout);
11471 setinputstring(pstr);
11472 }
11473 }
11474 nlpp = &bqlist;
11475 while (*nlpp)
11476 nlpp = &(*nlpp)->next;
Denis Vlasenko597906c2008-02-20 16:38:54 +000011477 *nlpp = stzalloc(sizeof(**nlpp));
11478 /* (*nlpp)->next = NULL; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000011479 parsebackquote = oldstyle;
11480
11481 if (oldstyle) {
11482 saveprompt = doprompt;
11483 doprompt = 0;
Eric Andersencb57d552001-06-28 07:25:16 +000011484 }
11485
Eric Andersenc470f442003-07-28 09:56:35 +000011486 n = list(2);
11487
11488 if (oldstyle)
11489 doprompt = saveprompt;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011490 else if (readtoken() != TRP)
11491 raise_error_unexpected_syntax(TRP);
Eric Andersenc470f442003-07-28 09:56:35 +000011492
11493 (*nlpp)->n = n;
11494 if (oldstyle) {
11495 /*
11496 * Start reading from old file again, ignoring any pushed back
11497 * tokens left from the backquote parsing
11498 */
11499 popfile();
11500 tokpushback = 0;
11501 }
11502 while (stackblocksize() <= savelen)
11503 growstackblock();
11504 STARTSTACKSTR(out);
11505 if (str) {
11506 memcpy(out, str, savelen);
11507 STADJUST(savelen, out);
Denis Vlasenkob012b102007-02-19 22:43:01 +000011508 INT_OFF;
11509 free(str);
Eric Andersenc470f442003-07-28 09:56:35 +000011510 str = NULL;
Denis Vlasenkob012b102007-02-19 22:43:01 +000011511 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +000011512 }
11513 parsebackquote = savepbq;
Denis Vlasenko2da584f2007-02-19 22:44:05 +000011514 exception_handler = savehandler;
Eric Andersenc470f442003-07-28 09:56:35 +000011515 if (arinest || dblquote)
11516 USTPUTC(CTLBACKQ | CTLQUOTE, out);
11517 else
11518 USTPUTC(CTLBACKQ, out);
11519 if (oldstyle)
11520 goto parsebackq_oldreturn;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000011521 goto parsebackq_newreturn;
Eric Andersenc470f442003-07-28 09:56:35 +000011522}
11523
Mike Frysinger98c52642009-04-02 10:02:37 +000011524#if ENABLE_SH_MATH_SUPPORT
Eric Andersencb57d552001-06-28 07:25:16 +000011525/*
11526 * Parse an arithmetic expansion (indicate start of one and set state)
11527 */
Eric Andersenc470f442003-07-28 09:56:35 +000011528parsearith: {
Eric Andersenc470f442003-07-28 09:56:35 +000011529 if (++arinest == 1) {
11530 prevsyntax = syntax;
11531 syntax = ARISYNTAX;
11532 USTPUTC(CTLARI, out);
11533 if (dblquote)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000011534 USTPUTC('"', out);
Eric Andersenc470f442003-07-28 09:56:35 +000011535 else
Denis Vlasenkoa624c112007-02-19 22:45:43 +000011536 USTPUTC(' ', out);
Eric Andersenc470f442003-07-28 09:56:35 +000011537 } else {
11538 /*
11539 * we collapse embedded arithmetic expansion to
11540 * parenthesis, which should be equivalent
11541 */
11542 USTPUTC('(', out);
Eric Andersencb57d552001-06-28 07:25:16 +000011543 }
Eric Andersenc470f442003-07-28 09:56:35 +000011544 goto parsearith_return;
11545}
11546#endif
Eric Andersencb57d552001-06-28 07:25:16 +000011547
Eric Andersenc470f442003-07-28 09:56:35 +000011548} /* end of readtoken */
11549
Eric Andersencb57d552001-06-28 07:25:16 +000011550/*
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011551 * Read the next input token.
11552 * If the token is a word, we set backquotelist to the list of cmds in
11553 * backquotes. We set quoteflag to true if any part of the word was
11554 * quoted.
11555 * If the token is TREDIR, then we set redirnode to a structure containing
11556 * the redirection.
11557 * In all cases, the variable startlinno is set to the number of the line
11558 * on which the token starts.
11559 *
11560 * [Change comment: here documents and internal procedures]
11561 * [Readtoken shouldn't have any arguments. Perhaps we should make the
11562 * word parsing code into a separate routine. In this case, readtoken
11563 * doesn't need to have any internal procedures, but parseword does.
11564 * We could also make parseoperator in essence the main routine, and
11565 * have parseword (readtoken1?) handle both words and redirection.]
Eric Andersencb57d552001-06-28 07:25:16 +000011566 */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011567#define NEW_xxreadtoken
11568#ifdef NEW_xxreadtoken
11569/* singles must be first! */
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011570static const char xxreadtoken_chars[7] ALIGN1 = {
Denis Vlasenko834dee72008-10-07 09:18:30 +000011571 '\n', '(', ')', /* singles */
11572 '&', '|', ';', /* doubles */
11573 0
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011574};
Eric Andersencb57d552001-06-28 07:25:16 +000011575
Denis Vlasenko834dee72008-10-07 09:18:30 +000011576#define xxreadtoken_singles 3
11577#define xxreadtoken_doubles 3
11578
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011579static const char xxreadtoken_tokens[] ALIGN1 = {
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011580 TNL, TLP, TRP, /* only single occurrence allowed */
11581 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
11582 TEOF, /* corresponds to trailing nul */
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011583 TAND, TOR, TENDCASE /* if double occurrence */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011584};
11585
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011586static int
11587xxreadtoken(void)
11588{
11589 int c;
11590
11591 if (tokpushback) {
11592 tokpushback = 0;
11593 return lasttoken;
Eric Andersencb57d552001-06-28 07:25:16 +000011594 }
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011595 if (needprompt) {
11596 setprompt(2);
11597 }
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011598 startlinno = g_parsefile->linno;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011599 for (;;) { /* until token or start of word found */
Denis Vlasenko834dee72008-10-07 09:18:30 +000011600 c = pgetc_fast();
Denis Vlasenko5e34ff22009-04-21 11:09:40 +000011601 if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011602 continue;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011603
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011604 if (c == '#') {
11605 while ((c = pgetc()) != '\n' && c != PEOF)
11606 continue;
11607 pungetc();
11608 } else if (c == '\\') {
11609 if (pgetc() != '\n') {
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011610 pungetc();
Denis Vlasenko834dee72008-10-07 09:18:30 +000011611 break; /* return readtoken1(...) */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011612 }
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011613 startlinno = ++g_parsefile->linno;
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011614 if (doprompt)
11615 setprompt(2);
11616 } else {
11617 const char *p;
11618
11619 p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
11620 if (c != PEOF) {
11621 if (c == '\n') {
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011622 g_parsefile->linno++;
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011623 needprompt = doprompt;
11624 }
11625
11626 p = strchr(xxreadtoken_chars, c);
Denis Vlasenko834dee72008-10-07 09:18:30 +000011627 if (p == NULL)
11628 break; /* return readtoken1(...) */
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011629
Denis Vlasenko834dee72008-10-07 09:18:30 +000011630 if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
11631 int cc = pgetc();
11632 if (cc == c) { /* double occurrence? */
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011633 p += xxreadtoken_doubles + 1;
11634 } else {
11635 pungetc();
Denis Vlasenko834dee72008-10-07 09:18:30 +000011636#if ENABLE_ASH_BASH_COMPAT
11637 if (c == '&' && cc == '>') /* &> */
11638 break; /* return readtoken1(...) */
11639#endif
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011640 }
11641 }
11642 }
11643 lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
11644 return lasttoken;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011645 }
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011646 } /* for (;;) */
Denis Vlasenko834dee72008-10-07 09:18:30 +000011647
11648 return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011649}
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011650#else /* old xxreadtoken */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011651#define RETURN(token) return lasttoken = token
11652static int
11653xxreadtoken(void)
11654{
11655 int c;
11656
11657 if (tokpushback) {
11658 tokpushback = 0;
11659 return lasttoken;
11660 }
11661 if (needprompt) {
11662 setprompt(2);
11663 }
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011664 startlinno = g_parsefile->linno;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011665 for (;;) { /* until token or start of word found */
Denis Vlasenko834dee72008-10-07 09:18:30 +000011666 c = pgetc_fast();
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011667 switch (c) {
11668 case ' ': case '\t':
Denys Vlasenko2ce42e92009-11-29 02:18:13 +010011669 IF_ASH_ALIAS(case PEOA:)
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011670 continue;
11671 case '#':
Denis Vlasenkof7d56652008-03-25 05:51:41 +000011672 while ((c = pgetc()) != '\n' && c != PEOF)
11673 continue;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011674 pungetc();
11675 continue;
11676 case '\\':
11677 if (pgetc() == '\n') {
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011678 startlinno = ++g_parsefile->linno;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011679 if (doprompt)
11680 setprompt(2);
11681 continue;
11682 }
11683 pungetc();
11684 goto breakloop;
11685 case '\n':
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011686 g_parsefile->linno++;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011687 needprompt = doprompt;
11688 RETURN(TNL);
11689 case PEOF:
11690 RETURN(TEOF);
11691 case '&':
11692 if (pgetc() == '&')
11693 RETURN(TAND);
11694 pungetc();
11695 RETURN(TBACKGND);
11696 case '|':
11697 if (pgetc() == '|')
11698 RETURN(TOR);
11699 pungetc();
11700 RETURN(TPIPE);
11701 case ';':
11702 if (pgetc() == ';')
11703 RETURN(TENDCASE);
11704 pungetc();
11705 RETURN(TSEMI);
11706 case '(':
11707 RETURN(TLP);
11708 case ')':
11709 RETURN(TRP);
11710 default:
11711 goto breakloop;
11712 }
11713 }
11714 breakloop:
11715 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
11716#undef RETURN
11717}
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011718#endif /* old xxreadtoken */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011719
11720static int
11721readtoken(void)
11722{
11723 int t;
11724#if DEBUG
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011725 smallint alreadyseen = tokpushback;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011726#endif
11727
11728#if ENABLE_ASH_ALIAS
11729 top:
11730#endif
11731
11732 t = xxreadtoken();
11733
11734 /*
11735 * eat newlines
11736 */
11737 if (checkkwd & CHKNL) {
11738 while (t == TNL) {
11739 parseheredoc();
11740 t = xxreadtoken();
11741 }
11742 }
11743
11744 if (t != TWORD || quoteflag) {
11745 goto out;
11746 }
11747
11748 /*
11749 * check for keywords
11750 */
11751 if (checkkwd & CHKKWD) {
11752 const char *const *pp;
11753
11754 pp = findkwd(wordtext);
11755 if (pp) {
11756 lasttoken = t = pp - tokname_array;
11757 TRACE(("keyword %s recognized\n", tokname(t)));
11758 goto out;
11759 }
11760 }
11761
11762 if (checkkwd & CHKALIAS) {
11763#if ENABLE_ASH_ALIAS
11764 struct alias *ap;
11765 ap = lookupalias(wordtext, 1);
11766 if (ap != NULL) {
11767 if (*ap->val) {
11768 pushstring(ap->val, ap);
11769 }
11770 goto top;
11771 }
11772#endif
11773 }
11774 out:
11775 checkkwd = 0;
11776#if DEBUG
11777 if (!alreadyseen)
11778 TRACE(("token %s %s\n", tokname(t), t == TWORD ? wordtext : ""));
11779 else
11780 TRACE(("reread token %s %s\n", tokname(t), t == TWORD ? wordtext : ""));
11781#endif
11782 return t;
Eric Andersencb57d552001-06-28 07:25:16 +000011783}
11784
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011785static char
11786peektoken(void)
11787{
11788 int t;
11789
11790 t = readtoken();
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011791 tokpushback = 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011792 return tokname_array[t][0];
11793}
Eric Andersencb57d552001-06-28 07:25:16 +000011794
11795/*
Denys Vlasenko86e83ec2009-07-23 22:07:07 +020011796 * Read and parse a command. Returns NODE_EOF on end of file.
11797 * (NULL is a valid parse tree indicating a blank line.)
Eric Andersencb57d552001-06-28 07:25:16 +000011798 */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011799static union node *
11800parsecmd(int interact)
Eric Andersen90898442003-08-06 11:20:52 +000011801{
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011802 int t;
Eric Andersencb57d552001-06-28 07:25:16 +000011803
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011804 tokpushback = 0;
11805 doprompt = interact;
11806 if (doprompt)
11807 setprompt(doprompt);
11808 needprompt = 0;
11809 t = readtoken();
11810 if (t == TEOF)
Denys Vlasenko86e83ec2009-07-23 22:07:07 +020011811 return NODE_EOF;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011812 if (t == TNL)
11813 return NULL;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011814 tokpushback = 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011815 return list(1);
11816}
11817
11818/*
11819 * Input any here documents.
11820 */
11821static void
11822parseheredoc(void)
11823{
11824 struct heredoc *here;
11825 union node *n;
11826
11827 here = heredoclist;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000011828 heredoclist = NULL;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011829
11830 while (here) {
11831 if (needprompt) {
11832 setprompt(2);
11833 }
11834 readtoken1(pgetc(), here->here->type == NHERE? SQSYNTAX : DQSYNTAX,
11835 here->eofmark, here->striptabs);
Denis Vlasenko597906c2008-02-20 16:38:54 +000011836 n = stzalloc(sizeof(struct narg));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011837 n->narg.type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000011838 /*n->narg.next = NULL; - stzalloc did it */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011839 n->narg.text = wordtext;
11840 n->narg.backquote = backquotelist;
11841 here->here->nhere.doc = n;
11842 here = here->next;
Eric Andersencb57d552001-06-28 07:25:16 +000011843 }
Eric Andersencb57d552001-06-28 07:25:16 +000011844}
11845
11846
11847/*
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +000011848 * called by editline -- any expansions to the prompt should be added here.
Eric Andersencb57d552001-06-28 07:25:16 +000011849 */
Denis Vlasenko131ae172007-02-18 13:00:19 +000011850#if ENABLE_ASH_EXPAND_PRMT
"Vladimir N. Oleynik"bef14d72005-09-05 13:25:11 +000011851static const char *
11852expandstr(const char *ps)
11853{
11854 union node n;
11855
Denis Vlasenko5c2b8142009-03-19 01:59:59 +000011856 /* XXX Fix (char *) cast. It _is_ a bug. ps is variable's value,
11857 * and token processing _can_ alter it (delete NULs etc). */
"Vladimir N. Oleynik"bef14d72005-09-05 13:25:11 +000011858 setinputstring((char *)ps);
Denis Vlasenko46a53062007-09-24 18:30:02 +000011859 readtoken1(pgetc(), PSSYNTAX, nullstr, 0);
"Vladimir N. Oleynik"bef14d72005-09-05 13:25:11 +000011860 popfile();
11861
11862 n.narg.type = NARG;
11863 n.narg.next = NULL;
11864 n.narg.text = wordtext;
11865 n.narg.backquote = backquotelist;
11866
11867 expandarg(&n, NULL, 0);
11868 return stackblock();
11869}
11870#endif
11871
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011872/*
11873 * Execute a command or commands contained in a string.
11874 */
11875static int
11876evalstring(char *s, int mask)
Eric Andersenc470f442003-07-28 09:56:35 +000011877{
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011878 union node *n;
11879 struct stackmark smark;
11880 int skip;
11881
11882 setinputstring(s);
11883 setstackmark(&smark);
11884
11885 skip = 0;
Denys Vlasenko86e83ec2009-07-23 22:07:07 +020011886 while ((n = parsecmd(0)) != NODE_EOF) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011887 evaltree(n, 0);
11888 popstackmark(&smark);
11889 skip = evalskip;
11890 if (skip)
11891 break;
11892 }
11893 popfile();
11894
11895 skip &= mask;
11896 evalskip = skip;
11897 return skip;
Eric Andersenc470f442003-07-28 09:56:35 +000011898}
11899
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011900/*
11901 * The eval command.
11902 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011903static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000011904evalcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011905{
11906 char *p;
11907 char *concat;
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011908
Denis Vlasenko68404f12008-03-17 09:00:54 +000011909 if (argv[1]) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011910 p = argv[1];
Denis Vlasenko68404f12008-03-17 09:00:54 +000011911 argv += 2;
11912 if (argv[0]) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011913 STARTSTACKSTR(concat);
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011914 for (;;) {
11915 concat = stack_putstr(p, concat);
Denis Vlasenko68404f12008-03-17 09:00:54 +000011916 p = *argv++;
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011917 if (p == NULL)
11918 break;
11919 STPUTC(' ', concat);
11920 }
11921 STPUTC('\0', concat);
11922 p = grabstackstr(concat);
11923 }
11924 evalstring(p, ~SKIPEVAL);
11925
11926 }
11927 return exitstatus;
11928}
11929
11930/*
Denys Vlasenko285ad152009-12-04 23:02:27 +010011931 * Read and execute commands.
11932 * "Top" is nonzero for the top level command loop;
11933 * it turns on prompting if the shell is interactive.
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011934 */
11935static int
11936cmdloop(int top)
11937{
11938 union node *n;
11939 struct stackmark smark;
11940 int inter;
11941 int numeof = 0;
11942
11943 TRACE(("cmdloop(%d) called\n", top));
11944 for (;;) {
11945 int skip;
11946
11947 setstackmark(&smark);
11948#if JOBS
Denis Vlasenkob07a4962008-06-22 13:16:23 +000011949 if (doing_jobctl)
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011950 showjobs(stderr, SHOW_CHANGED);
11951#endif
11952 inter = 0;
11953 if (iflag && top) {
11954 inter++;
11955#if ENABLE_ASH_MAIL
11956 chkmail();
11957#endif
11958 }
11959 n = parsecmd(inter);
Denys Vlasenko7cee00e2009-07-24 01:08:03 +020011960#if DEBUG
11961 if (DEBUG > 2 && debug && (n != NODE_EOF))
Denys Vlasenko883cea42009-07-11 15:31:59 +020011962 showtree(n);
Denis Vlasenko135cecb2009-04-12 00:00:57 +000011963#endif
Denys Vlasenko86e83ec2009-07-23 22:07:07 +020011964 if (n == NODE_EOF) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011965 if (!top || numeof >= 50)
11966 break;
11967 if (!stoppedjobs()) {
11968 if (!Iflag)
11969 break;
11970 out2str("\nUse \"exit\" to leave shell.\n");
11971 }
11972 numeof++;
11973 } else if (nflag == 0) {
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +000011974 /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
11975 job_warning >>= 1;
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011976 numeof = 0;
11977 evaltree(n, 0);
11978 }
11979 popstackmark(&smark);
11980 skip = evalskip;
11981
11982 if (skip) {
11983 evalskip = 0;
11984 return skip & SKIPEVAL;
11985 }
11986 }
11987 return 0;
11988}
11989
Denis Vlasenko0dec6de2007-02-23 21:10:47 +000011990/*
11991 * Take commands from a file. To be compatible we should do a path
11992 * search for the file, which is necessary to find sub-commands.
11993 */
11994static char *
11995find_dot_file(char *name)
11996{
11997 char *fullname;
11998 const char *path = pathval();
11999 struct stat statb;
12000
12001 /* don't try this for absolute or relative paths */
12002 if (strchr(name, '/'))
12003 return name;
12004
Denis Vlasenko8ad78e12009-02-15 12:40:30 +000012005 /* IIRC standards do not say whether . is to be searched.
12006 * And it is even smaller this way, making it unconditional for now:
12007 */
12008 if (1) { /* ENABLE_ASH_BASH_COMPAT */
12009 fullname = name;
12010 goto try_cur_dir;
12011 }
12012
Denys Vlasenko82a6fb32009-06-14 19:42:12 +020012013 while ((fullname = path_advance(&path, name)) != NULL) {
Denis Vlasenko8ad78e12009-02-15 12:40:30 +000012014 try_cur_dir:
Denis Vlasenko0dec6de2007-02-23 21:10:47 +000012015 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
12016 /*
12017 * Don't bother freeing here, since it will
12018 * be freed by the caller.
12019 */
12020 return fullname;
12021 }
Denys Vlasenko82a6fb32009-06-14 19:42:12 +020012022 if (fullname != name)
12023 stunalloc(fullname);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +000012024 }
12025
12026 /* not found in the PATH */
12027 ash_msg_and_raise_error("%s: not found", name);
12028 /* NOTREACHED */
12029}
12030
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012031static int FAST_FUNC
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012032dotcmd(int argc, char **argv)
12033{
12034 struct strlist *sp;
12035 volatile struct shparam saveparam;
12036 int status = 0;
12037
12038 for (sp = cmdenviron; sp; sp = sp->next)
Denis Vlasenko4222ae42007-02-25 02:37:49 +000012039 setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012040
Denis Vlasenko68404f12008-03-17 09:00:54 +000012041 if (argv[1]) { /* That's what SVR2 does */
12042 char *fullname = find_dot_file(argv[1]);
12043 argv += 2;
12044 argc -= 2;
12045 if (argc) { /* argc > 0, argv[0] != NULL */
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012046 saveparam = shellparam;
Denis Vlasenko01631112007-12-16 17:20:38 +000012047 shellparam.malloced = 0;
Denis Vlasenko68404f12008-03-17 09:00:54 +000012048 shellparam.nparam = argc;
12049 shellparam.p = argv;
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012050 };
12051
12052 setinputfile(fullname, INPUT_PUSH_FILE);
12053 commandname = fullname;
12054 cmdloop(0);
12055 popfile();
12056
Denis Vlasenko68404f12008-03-17 09:00:54 +000012057 if (argc) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012058 freeparam(&shellparam);
12059 shellparam = saveparam;
12060 };
12061 status = exitstatus;
12062 }
12063 return status;
12064}
12065
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012066static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012067exitcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012068{
12069 if (stoppedjobs())
12070 return 0;
Denis Vlasenko68404f12008-03-17 09:00:54 +000012071 if (argv[1])
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012072 exitstatus = number(argv[1]);
12073 raise_exception(EXEXIT);
12074 /* NOTREACHED */
12075}
12076
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012077/*
12078 * Read a file containing shell functions.
12079 */
12080static void
12081readcmdfile(char *name)
12082{
12083 setinputfile(name, INPUT_PUSH_FILE);
12084 cmdloop(0);
12085 popfile();
12086}
12087
12088
Denis Vlasenkocc571512007-02-23 21:10:35 +000012089/* ============ find_command inplementation */
12090
12091/*
12092 * Resolve a command name. If you change this routine, you may have to
12093 * change the shellexec routine as well.
12094 */
12095static void
12096find_command(char *name, struct cmdentry *entry, int act, const char *path)
12097{
12098 struct tblentry *cmdp;
12099 int idx;
12100 int prev;
12101 char *fullname;
12102 struct stat statb;
12103 int e;
12104 int updatetbl;
12105 struct builtincmd *bcmd;
12106
12107 /* If name contains a slash, don't use PATH or hash table */
12108 if (strchr(name, '/') != NULL) {
12109 entry->u.index = -1;
12110 if (act & DO_ABS) {
12111 while (stat(name, &statb) < 0) {
12112#ifdef SYSV
12113 if (errno == EINTR)
12114 continue;
12115#endif
12116 entry->cmdtype = CMDUNKNOWN;
12117 return;
12118 }
12119 }
12120 entry->cmdtype = CMDNORMAL;
12121 return;
12122 }
12123
Denis Vlasenkof20de5b2007-04-29 23:42:54 +000012124/* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
Denis Vlasenkocc571512007-02-23 21:10:35 +000012125
12126 updatetbl = (path == pathval());
12127 if (!updatetbl) {
12128 act |= DO_ALTPATH;
12129 if (strstr(path, "%builtin") != NULL)
12130 act |= DO_ALTBLTIN;
12131 }
12132
12133 /* If name is in the table, check answer will be ok */
12134 cmdp = cmdlookup(name, 0);
12135 if (cmdp != NULL) {
12136 int bit;
12137
12138 switch (cmdp->cmdtype) {
12139 default:
12140#if DEBUG
12141 abort();
12142#endif
12143 case CMDNORMAL:
12144 bit = DO_ALTPATH;
12145 break;
12146 case CMDFUNCTION:
12147 bit = DO_NOFUNC;
12148 break;
12149 case CMDBUILTIN:
12150 bit = DO_ALTBLTIN;
12151 break;
12152 }
12153 if (act & bit) {
12154 updatetbl = 0;
12155 cmdp = NULL;
12156 } else if (cmdp->rehash == 0)
12157 /* if not invalidated by cd, we're done */
12158 goto success;
12159 }
12160
12161 /* If %builtin not in path, check for builtin next */
12162 bcmd = find_builtin(name);
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +000012163 if (bcmd) {
12164 if (IS_BUILTIN_REGULAR(bcmd))
12165 goto builtin_success;
12166 if (act & DO_ALTPATH) {
12167 if (!(act & DO_ALTBLTIN))
12168 goto builtin_success;
12169 } else if (builtinloc <= 0) {
12170 goto builtin_success;
Denis Vlasenko8e858e22007-03-07 09:35:43 +000012171 }
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +000012172 }
Denis Vlasenkocc571512007-02-23 21:10:35 +000012173
Denis Vlasenkof20de5b2007-04-29 23:42:54 +000012174#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko7465dbc2008-04-13 02:25:53 +000012175 {
12176 int applet_no = find_applet_by_name(name);
12177 if (applet_no >= 0) {
12178 entry->cmdtype = CMDNORMAL;
12179 entry->u.index = -2 - applet_no;
12180 return;
12181 }
Denis Vlasenkof20de5b2007-04-29 23:42:54 +000012182 }
12183#endif
12184
Denis Vlasenkocc571512007-02-23 21:10:35 +000012185 /* We have to search path. */
12186 prev = -1; /* where to start */
12187 if (cmdp && cmdp->rehash) { /* doing a rehash */
12188 if (cmdp->cmdtype == CMDBUILTIN)
12189 prev = builtinloc;
12190 else
12191 prev = cmdp->param.index;
12192 }
12193
12194 e = ENOENT;
12195 idx = -1;
12196 loop:
Denys Vlasenko82a6fb32009-06-14 19:42:12 +020012197 while ((fullname = path_advance(&path, name)) != NULL) {
Denis Vlasenkocc571512007-02-23 21:10:35 +000012198 stunalloc(fullname);
Denis Vlasenkodee82b62007-07-29 14:05:27 +000012199 /* NB: code below will still use fullname
12200 * despite it being "unallocated" */
Denis Vlasenkocc571512007-02-23 21:10:35 +000012201 idx++;
12202 if (pathopt) {
12203 if (prefix(pathopt, "builtin")) {
12204 if (bcmd)
12205 goto builtin_success;
12206 continue;
Denis Vlasenko4a9ca132008-04-12 20:07:08 +000012207 }
12208 if ((act & DO_NOFUNC)
12209 || !prefix(pathopt, "func")
12210 ) { /* ignore unimplemented options */
Denis Vlasenkocc571512007-02-23 21:10:35 +000012211 continue;
12212 }
12213 }
12214 /* if rehash, don't redo absolute path names */
12215 if (fullname[0] == '/' && idx <= prev) {
12216 if (idx < prev)
12217 continue;
12218 TRACE(("searchexec \"%s\": no change\n", name));
12219 goto success;
12220 }
12221 while (stat(fullname, &statb) < 0) {
12222#ifdef SYSV
12223 if (errno == EINTR)
12224 continue;
12225#endif
12226 if (errno != ENOENT && errno != ENOTDIR)
12227 e = errno;
12228 goto loop;
12229 }
12230 e = EACCES; /* if we fail, this will be the error */
12231 if (!S_ISREG(statb.st_mode))
12232 continue;
12233 if (pathopt) { /* this is a %func directory */
12234 stalloc(strlen(fullname) + 1);
Denis Vlasenkodee82b62007-07-29 14:05:27 +000012235 /* NB: stalloc will return space pointed by fullname
12236 * (because we don't have any intervening allocations
12237 * between stunalloc above and this stalloc) */
Denis Vlasenkocc571512007-02-23 21:10:35 +000012238 readcmdfile(fullname);
12239 cmdp = cmdlookup(name, 0);
12240 if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
12241 ash_msg_and_raise_error("%s not defined in %s", name, fullname);
12242 stunalloc(fullname);
12243 goto success;
12244 }
12245 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
12246 if (!updatetbl) {
12247 entry->cmdtype = CMDNORMAL;
12248 entry->u.index = idx;
12249 return;
12250 }
12251 INT_OFF;
12252 cmdp = cmdlookup(name, 1);
12253 cmdp->cmdtype = CMDNORMAL;
12254 cmdp->param.index = idx;
12255 INT_ON;
12256 goto success;
12257 }
12258
12259 /* We failed. If there was an entry for this command, delete it */
12260 if (cmdp && updatetbl)
12261 delete_cmd_entry();
12262 if (act & DO_ERR)
12263 ash_msg("%s: %s", name, errmsg(e, "not found"));
12264 entry->cmdtype = CMDUNKNOWN;
12265 return;
12266
12267 builtin_success:
12268 if (!updatetbl) {
12269 entry->cmdtype = CMDBUILTIN;
12270 entry->u.cmd = bcmd;
12271 return;
12272 }
12273 INT_OFF;
12274 cmdp = cmdlookup(name, 1);
12275 cmdp->cmdtype = CMDBUILTIN;
12276 cmdp->param.cmd = bcmd;
12277 INT_ON;
12278 success:
12279 cmdp->rehash = 0;
12280 entry->cmdtype = cmdp->cmdtype;
12281 entry->u = cmdp->param;
12282}
12283
12284
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012285/* ============ trap.c */
Eric Andersenc470f442003-07-28 09:56:35 +000012286
Eric Andersencb57d552001-06-28 07:25:16 +000012287/*
Eric Andersencb57d552001-06-28 07:25:16 +000012288 * The trap builtin.
12289 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012290static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012291trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersencb57d552001-06-28 07:25:16 +000012292{
12293 char *action;
12294 char **ap;
Denys Vlasenko496d5bf2010-03-26 15:52:24 +010012295 int signo, exitcode;
Eric Andersencb57d552001-06-28 07:25:16 +000012296
Eric Andersenc470f442003-07-28 09:56:35 +000012297 nextopt(nullstr);
12298 ap = argptr;
12299 if (!*ap) {
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012300 for (signo = 0; signo < NSIG; signo++) {
Denys Vlasenko21d87d42009-09-25 00:06:51 +020012301 char *tr = trap_ptr[signo];
12302 if (tr) {
Denys Vlasenkoe74aaf92009-09-27 02:05:45 +020012303 /* note: bash adds "SIG", but only if invoked
12304 * as "bash". If called as "sh", or if set -o posix,
12305 * then it prints short signal names.
12306 * We are printing short names: */
12307 out1fmt("trap -- %s %s\n",
Denys Vlasenko21d87d42009-09-25 00:06:51 +020012308 single_quote(tr),
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +000012309 get_signame(signo));
Denys Vlasenko726e1a02009-09-25 02:58:20 +020012310 /* trap_ptr != trap only if we are in special-cased `trap` code.
12311 * In this case, we will exit very soon, no need to free(). */
Denys Vlasenkoe74aaf92009-09-27 02:05:45 +020012312 /* if (trap_ptr != trap && tp[0]) */
Denys Vlasenko726e1a02009-09-25 02:58:20 +020012313 /* free(tr); */
Eric Andersencb57d552001-06-28 07:25:16 +000012314 }
12315 }
Denys Vlasenko726e1a02009-09-25 02:58:20 +020012316 /*
Denys Vlasenko21d87d42009-09-25 00:06:51 +020012317 if (trap_ptr != trap) {
12318 free(trap_ptr);
12319 trap_ptr = trap;
12320 }
Denys Vlasenko726e1a02009-09-25 02:58:20 +020012321 */
Eric Andersencb57d552001-06-28 07:25:16 +000012322 return 0;
12323 }
Denys Vlasenko21d87d42009-09-25 00:06:51 +020012324
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +000012325 action = NULL;
12326 if (ap[1])
Eric Andersencb57d552001-06-28 07:25:16 +000012327 action = *ap++;
Denys Vlasenko496d5bf2010-03-26 15:52:24 +010012328 exitcode = 0;
Eric Andersencb57d552001-06-28 07:25:16 +000012329 while (*ap) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +000012330 signo = get_signum(*ap);
Denys Vlasenko496d5bf2010-03-26 15:52:24 +010012331 if (signo < 0) {
12332 /* Mimic bash message exactly */
12333 ash_msg("%s: invalid signal specification", *ap);
12334 exitcode = 1;
12335 goto next;
12336 }
Denis Vlasenkob012b102007-02-19 22:43:01 +000012337 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +000012338 if (action) {
Denis Vlasenko9f739442006-12-16 23:49:13 +000012339 if (LONE_DASH(action))
Eric Andersencb57d552001-06-28 07:25:16 +000012340 action = NULL;
12341 else
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012342 action = ckstrdup(action);
Eric Andersencb57d552001-06-28 07:25:16 +000012343 }
Denis Vlasenko60818682007-09-28 22:07:23 +000012344 free(trap[signo]);
Eric Andersencb57d552001-06-28 07:25:16 +000012345 trap[signo] = action;
12346 if (signo != 0)
12347 setsignal(signo);
Denis Vlasenkob012b102007-02-19 22:43:01 +000012348 INT_ON;
Denys Vlasenko496d5bf2010-03-26 15:52:24 +010012349 next:
Eric Andersencb57d552001-06-28 07:25:16 +000012350 ap++;
12351 }
Denys Vlasenko496d5bf2010-03-26 15:52:24 +010012352 return exitcode;
Eric Andersencb57d552001-06-28 07:25:16 +000012353}
12354
Eric Andersenc470f442003-07-28 09:56:35 +000012355
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012356/* ============ Builtins */
Eric Andersenc470f442003-07-28 09:56:35 +000012357
Denis Vlasenko8e1c7152007-01-22 07:21:38 +000012358#if !ENABLE_FEATURE_SH_EXTRA_QUIET
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012359/*
12360 * Lists available builtins
12361 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012362static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012363helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersenc470f442003-07-28 09:56:35 +000012364{
Denis Vlasenko6b06cb82008-05-15 21:30:45 +000012365 unsigned col;
12366 unsigned i;
Eric Andersenc470f442003-07-28 09:56:35 +000012367
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +020012368 out1fmt(
Denis Vlasenko34d4d892009-04-04 20:24:37 +000012369 "Built-in commands:\n"
12370 "------------------\n");
Denis Vlasenkob71c6682007-07-21 15:08:09 +000012371 for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
Eric Andersenc470f442003-07-28 09:56:35 +000012372 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
Denis Vlasenko52764022007-02-24 13:42:56 +000012373 builtintab[i].name + 1);
Eric Andersenc470f442003-07-28 09:56:35 +000012374 if (col > 60) {
12375 out1fmt("\n");
12376 col = 0;
12377 }
12378 }
Denis Vlasenko80d14be2007-04-10 23:03:30 +000012379#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko1aa7e472007-11-28 06:49:03 +000012380 {
12381 const char *a = applet_names;
12382 while (*a) {
12383 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
12384 if (col > 60) {
12385 out1fmt("\n");
12386 col = 0;
12387 }
12388 a += strlen(a) + 1;
Eric Andersenc470f442003-07-28 09:56:35 +000012389 }
12390 }
12391#endif
12392 out1fmt("\n\n");
12393 return EXIT_SUCCESS;
12394}
Denis Vlasenko131ae172007-02-18 13:00:19 +000012395#endif /* FEATURE_SH_EXTRA_QUIET */
Eric Andersenc470f442003-07-28 09:56:35 +000012396
Eric Andersencb57d552001-06-28 07:25:16 +000012397/*
Eric Andersencb57d552001-06-28 07:25:16 +000012398 * The export and readonly commands.
12399 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012400static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012401exportcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +000012402{
12403 struct var *vp;
12404 char *name;
12405 const char *p;
Eric Andersenc470f442003-07-28 09:56:35 +000012406 char **aptr;
Denis Vlasenkob7304742008-10-20 08:15:51 +000012407 int flag = argv[0][0] == 'r' ? VREADONLY : VEXPORT;
Eric Andersencb57d552001-06-28 07:25:16 +000012408
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012409 if (nextopt("p") != 'p') {
12410 aptr = argptr;
12411 name = *aptr;
12412 if (name) {
12413 do {
12414 p = strchr(name, '=');
12415 if (p != NULL) {
12416 p++;
12417 } else {
12418 vp = *findvar(hashvar(name), name);
12419 if (vp) {
12420 vp->flags |= flag;
12421 continue;
12422 }
Eric Andersencb57d552001-06-28 07:25:16 +000012423 }
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012424 setvar(name, p, flag);
12425 } while ((name = *++aptr) != NULL);
12426 return 0;
12427 }
Eric Andersencb57d552001-06-28 07:25:16 +000012428 }
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012429 showvars(argv[0], flag, 0);
Eric Andersencb57d552001-06-28 07:25:16 +000012430 return 0;
12431}
12432
Eric Andersencb57d552001-06-28 07:25:16 +000012433/*
Denis Vlasenko5651bfc2007-02-23 21:08:58 +000012434 * Delete a function if it exists.
Eric Andersencb57d552001-06-28 07:25:16 +000012435 */
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012436static void
Denis Vlasenko5651bfc2007-02-23 21:08:58 +000012437unsetfunc(const char *name)
Aaron Lehmannb6ecbdc2001-12-06 03:37:38 +000012438{
Denis Vlasenko5651bfc2007-02-23 21:08:58 +000012439 struct tblentry *cmdp;
Eric Andersencb57d552001-06-28 07:25:16 +000012440
Denis Vlasenko5651bfc2007-02-23 21:08:58 +000012441 cmdp = cmdlookup(name, 0);
12442 if (cmdp!= NULL && cmdp->cmdtype == CMDFUNCTION)
12443 delete_cmd_entry();
Eric Andersenc470f442003-07-28 09:56:35 +000012444}
12445
Eric Andersencb57d552001-06-28 07:25:16 +000012446/*
Eric Andersencb57d552001-06-28 07:25:16 +000012447 * The unset builtin command. We unset the function before we unset the
12448 * variable to allow a function to be unset when there is a readonly variable
12449 * with the same name.
12450 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012451static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012452unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersencb57d552001-06-28 07:25:16 +000012453{
12454 char **ap;
12455 int i;
Eric Andersenc470f442003-07-28 09:56:35 +000012456 int flag = 0;
Eric Andersencb57d552001-06-28 07:25:16 +000012457 int ret = 0;
12458
12459 while ((i = nextopt("vf")) != '\0') {
Eric Andersenc470f442003-07-28 09:56:35 +000012460 flag = i;
Eric Andersencb57d552001-06-28 07:25:16 +000012461 }
Eric Andersencb57d552001-06-28 07:25:16 +000012462
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012463 for (ap = argptr; *ap; ap++) {
Eric Andersenc470f442003-07-28 09:56:35 +000012464 if (flag != 'f') {
12465 i = unsetvar(*ap);
12466 ret |= i;
12467 if (!(i & 2))
12468 continue;
12469 }
12470 if (flag != 'v')
Eric Andersencb57d552001-06-28 07:25:16 +000012471 unsetfunc(*ap);
Eric Andersencb57d552001-06-28 07:25:16 +000012472 }
Eric Andersenc470f442003-07-28 09:56:35 +000012473 return ret & 1;
Eric Andersencb57d552001-06-28 07:25:16 +000012474}
12475
12476
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +000012477/* setmode.c */
Eric Andersencb57d552001-06-28 07:25:16 +000012478
Eric Andersenc470f442003-07-28 09:56:35 +000012479#include <sys/times.h>
12480
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000012481static const unsigned char timescmd_str[] ALIGN1 = {
Manuel Novoa III 4456f252003-08-13 17:48:47 +000012482 ' ', offsetof(struct tms, tms_utime),
12483 '\n', offsetof(struct tms, tms_stime),
12484 ' ', offsetof(struct tms, tms_cutime),
12485 '\n', offsetof(struct tms, tms_cstime),
12486 0
12487};
Eric Andersencb57d552001-06-28 07:25:16 +000012488
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012489static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012490timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Manuel Novoa III 4456f252003-08-13 17:48:47 +000012491{
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012492 long clk_tck, s, t;
Manuel Novoa III 4456f252003-08-13 17:48:47 +000012493 const unsigned char *p;
12494 struct tms buf;
12495
12496 clk_tck = sysconf(_SC_CLK_TCK);
Eric Andersencb57d552001-06-28 07:25:16 +000012497 times(&buf);
Manuel Novoa III 4456f252003-08-13 17:48:47 +000012498
12499 p = timescmd_str;
12500 do {
12501 t = *(clock_t *)(((char *) &buf) + p[1]);
12502 s = t / clk_tck;
12503 out1fmt("%ldm%ld.%.3lds%c",
12504 s/60, s%60,
12505 ((t - s * clk_tck) * 1000) / clk_tck,
12506 p[0]);
12507 } while (*(p += 2));
12508
Eric Andersencb57d552001-06-28 07:25:16 +000012509 return 0;
12510}
12511
Mike Frysinger98c52642009-04-02 10:02:37 +000012512#if ENABLE_SH_MATH_SUPPORT
Eric Andersenc470f442003-07-28 09:56:35 +000012513/*
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +000012514 * The let builtin. partial stolen from GNU Bash, the Bourne Again SHell.
12515 * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
Eric Andersen90898442003-08-06 11:20:52 +000012516 *
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +000012517 * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
Eric Andersenc470f442003-07-28 09:56:35 +000012518 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012519static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012520letcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersenc470f442003-07-28 09:56:35 +000012521{
Denis Vlasenko68404f12008-03-17 09:00:54 +000012522 arith_t i;
Eric Andersenc470f442003-07-28 09:56:35 +000012523
Denis Vlasenko68404f12008-03-17 09:00:54 +000012524 argv++;
12525 if (!*argv)
Denis Vlasenkob012b102007-02-19 22:43:01 +000012526 ash_msg_and_raise_error("expression expected");
Denis Vlasenko68404f12008-03-17 09:00:54 +000012527 do {
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +000012528 i = ash_arith(*argv);
Denis Vlasenko68404f12008-03-17 09:00:54 +000012529 } while (*++argv);
Eric Andersenc470f442003-07-28 09:56:35 +000012530
Denis Vlasenkod9e15f22006-11-27 16:49:55 +000012531 return !i;
Eric Andersenc470f442003-07-28 09:56:35 +000012532}
Mike Frysinger98c52642009-04-02 10:02:37 +000012533#endif /* SH_MATH_SUPPORT */
Eric Andersenc470f442003-07-28 09:56:35 +000012534
Eric Andersenc470f442003-07-28 09:56:35 +000012535
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012536/* ============ miscbltin.c
12537 *
Eric Andersenaff114c2004-04-14 17:51:38 +000012538 * Miscellaneous builtins.
Eric Andersenc470f442003-07-28 09:56:35 +000012539 */
12540
12541#undef rflag
12542
Denis Vlasenko83e5d6f2006-12-18 21:49:06 +000012543#if defined(__GLIBC__) && __GLIBC__ == 2 && __GLIBC_MINOR__ < 1
Eric Andersenc470f442003-07-28 09:56:35 +000012544typedef enum __rlimit_resource rlim_t;
12545#endif
Eric Andersen74bcd162001-07-30 21:41:37 +000012546
Eric Andersenc470f442003-07-28 09:56:35 +000012547/*
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012548 * The read builtin. Options:
12549 * -r Do not interpret '\' specially
12550 * -s Turn off echo (tty only)
12551 * -n NCHARS Read NCHARS max
12552 * -p PROMPT Display PROMPT on stderr (if input is from tty)
12553 * -t SECONDS Timeout after SECONDS (tty or pipe only)
12554 * -u FD Read from given FD instead of fd 0
Eric Andersenc470f442003-07-28 09:56:35 +000012555 * This uses unbuffered input, which may be avoidable in some cases.
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012556 * TODO: bash also has:
12557 * -a ARRAY Read into array[0],[1],etc
12558 * -d DELIM End on DELIM char, not newline
12559 * -e Use line editing (tty only)
Eric Andersenc470f442003-07-28 09:56:35 +000012560 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012561static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012562readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersenc470f442003-07-28 09:56:35 +000012563{
Denys Vlasenko73067272010-01-12 22:11:24 +010012564 char *opt_n = NULL;
12565 char *opt_p = NULL;
12566 char *opt_t = NULL;
12567 char *opt_u = NULL;
12568 int read_flags = 0;
12569 const char *r;
Eric Andersenc470f442003-07-28 09:56:35 +000012570 int i;
12571
Denys Vlasenko73067272010-01-12 22:11:24 +010012572 while ((i = nextopt("p:u:rt:n:s")) != '\0') {
Denis Vlasenkobf0a2012006-12-26 10:42:51 +000012573 switch (i) {
Paul Fox02eb9342005-09-07 16:56:02 +000012574 case 'p':
Denys Vlasenko73067272010-01-12 22:11:24 +010012575 opt_p = optionarg;
Paul Fox02eb9342005-09-07 16:56:02 +000012576 break;
Paul Fox02eb9342005-09-07 16:56:02 +000012577 case 'n':
Denys Vlasenko73067272010-01-12 22:11:24 +010012578 opt_n = optionarg;
Paul Fox02eb9342005-09-07 16:56:02 +000012579 break;
12580 case 's':
Denys Vlasenko73067272010-01-12 22:11:24 +010012581 read_flags |= BUILTIN_READ_SILENT;
Paul Fox02eb9342005-09-07 16:56:02 +000012582 break;
Paul Fox02eb9342005-09-07 16:56:02 +000012583 case 't':
Denys Vlasenko73067272010-01-12 22:11:24 +010012584 opt_t = optionarg;
Paul Fox02eb9342005-09-07 16:56:02 +000012585 break;
Paul Fox02eb9342005-09-07 16:56:02 +000012586 case 'r':
Denys Vlasenko73067272010-01-12 22:11:24 +010012587 read_flags |= BUILTIN_READ_RAW;
Paul Fox02eb9342005-09-07 16:56:02 +000012588 break;
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012589 case 'u':
Denys Vlasenko73067272010-01-12 22:11:24 +010012590 opt_u = optionarg;
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012591 break;
Paul Fox02eb9342005-09-07 16:56:02 +000012592 default:
12593 break;
12594 }
Eric Andersenc470f442003-07-28 09:56:35 +000012595 }
Paul Fox02eb9342005-09-07 16:56:02 +000012596
Denys Vlasenko03dad222010-01-12 23:29:57 +010012597 r = shell_builtin_read(setvar2,
Denys Vlasenko73067272010-01-12 22:11:24 +010012598 argptr,
12599 bltinlookup("IFS"), /* can be NULL */
12600 read_flags,
12601 opt_n,
12602 opt_p,
12603 opt_t,
12604 opt_u
12605 );
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012606
Denys Vlasenko73067272010-01-12 22:11:24 +010012607 if ((uintptr_t)r > 1)
12608 ash_msg_and_raise_error(r);
Denis Vlasenko037576d2007-10-20 18:30:38 +000012609
Denys Vlasenko73067272010-01-12 22:11:24 +010012610 return (uintptr_t)r;
Eric Andersenc470f442003-07-28 09:56:35 +000012611}
12612
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012613static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012614umaskcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersenc470f442003-07-28 09:56:35 +000012615{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000012616 static const char permuser[3] ALIGN1 = "ugo";
12617 static const char permmode[3] ALIGN1 = "rwx";
12618 static const short permmask[] ALIGN2 = {
Eric Andersenc470f442003-07-28 09:56:35 +000012619 S_IRUSR, S_IWUSR, S_IXUSR,
12620 S_IRGRP, S_IWGRP, S_IXGRP,
12621 S_IROTH, S_IWOTH, S_IXOTH
12622 };
12623
Denis Vlasenkoeb858492009-04-18 02:06:54 +000012624 /* TODO: use bb_parse_mode() instead */
12625
Eric Andersenc470f442003-07-28 09:56:35 +000012626 char *ap;
12627 mode_t mask;
12628 int i;
12629 int symbolic_mode = 0;
12630
12631 while (nextopt("S") != '\0') {
12632 symbolic_mode = 1;
12633 }
12634
Denis Vlasenkob012b102007-02-19 22:43:01 +000012635 INT_OFF;
Eric Andersenc470f442003-07-28 09:56:35 +000012636 mask = umask(0);
12637 umask(mask);
Denis Vlasenkob012b102007-02-19 22:43:01 +000012638 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +000012639
Denis Vlasenko5cedb752007-02-18 19:56:41 +000012640 ap = *argptr;
12641 if (ap == NULL) {
Eric Andersenc470f442003-07-28 09:56:35 +000012642 if (symbolic_mode) {
12643 char buf[18];
12644 char *p = buf;
12645
12646 for (i = 0; i < 3; i++) {
12647 int j;
12648
12649 *p++ = permuser[i];
12650 *p++ = '=';
12651 for (j = 0; j < 3; j++) {
12652 if ((mask & permmask[3 * i + j]) == 0) {
12653 *p++ = permmode[j];
12654 }
12655 }
12656 *p++ = ',';
12657 }
12658 *--p = 0;
12659 puts(buf);
12660 } else {
12661 out1fmt("%.4o\n", mask);
12662 }
12663 } else {
Denis Vlasenkoaa744452007-02-23 01:04:22 +000012664 if (isdigit((unsigned char) *ap)) {
Eric Andersenc470f442003-07-28 09:56:35 +000012665 mask = 0;
12666 do {
12667 if (*ap >= '8' || *ap < '0')
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +020012668 ash_msg_and_raise_error(msg_illnum, argv[1]);
Eric Andersenc470f442003-07-28 09:56:35 +000012669 mask = (mask << 3) + (*ap - '0');
12670 } while (*++ap != '\0');
12671 umask(mask);
12672 } else {
12673 mask = ~mask & 0777;
12674 if (!bb_parse_mode(ap, &mask)) {
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +000012675 ash_msg_and_raise_error("illegal mode: %s", ap);
Eric Andersenc470f442003-07-28 09:56:35 +000012676 }
12677 umask(~mask & 0777);
12678 }
12679 }
12680 return 0;
12681}
12682
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012683static int FAST_FUNC
Denys Vlasenkof3c742f2010-03-06 20:12:00 +010012684ulimitcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersenc470f442003-07-28 09:56:35 +000012685{
Denys Vlasenkof3c742f2010-03-06 20:12:00 +010012686 return shell_builtin_ulimit(argv);
Eric Andersenc470f442003-07-28 09:56:35 +000012687}
12688
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012689/* ============ main() and helpers */
12690
12691/*
12692 * Called to exit the shell.
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012693 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012694static void exitshell(void) NORETURN;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012695static void
12696exitshell(void)
12697{
12698 struct jmploc loc;
12699 char *p;
12700 int status;
12701
12702 status = exitstatus;
12703 TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
12704 if (setjmp(loc.loc)) {
Denis Vlasenko7f88e342009-03-19 03:36:18 +000012705 if (exception_type == EXEXIT)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012706/* dash bug: it just does _exit(exitstatus) here
12707 * but we have to do setjobctl(0) first!
12708 * (bug is still not fixed in dash-0.5.3 - if you run dash
12709 * under Midnight Commander, on exit from dash MC is backgrounded) */
12710 status = exitstatus;
12711 goto out;
12712 }
12713 exception_handler = &loc;
12714 p = trap[0];
12715 if (p) {
12716 trap[0] = NULL;
12717 evalstring(p, 0);
Denys Vlasenko0800e3a2009-09-24 03:09:26 +020012718 free(p);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012719 }
12720 flush_stdout_stderr();
12721 out:
12722 setjobctl(0);
12723 _exit(status);
12724 /* NOTREACHED */
12725}
12726
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012727static void
12728init(void)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012729{
12730 /* from input.c: */
Denis Vlasenko41eb3002008-11-28 03:42:31 +000012731 basepf.next_to_pgetc = basepf.buf = basebuf;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012732
12733 /* from trap.c: */
12734 signal(SIGCHLD, SIG_DFL);
Denys Vlasenko7a7b0342009-12-04 04:18:31 +010012735 /* bash re-enables SIGHUP which is SIG_IGNed on entry.
12736 * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
12737 */
12738 signal(SIGHUP, SIG_DFL);
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012739
12740 /* from var.c: */
12741 {
12742 char **envp;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012743 const char *p;
12744 struct stat st1, st2;
12745
12746 initvar();
12747 for (envp = environ; envp && *envp; envp++) {
12748 if (strchr(*envp, '=')) {
12749 setvareq(*envp, VEXPORT|VTEXTFIXED);
12750 }
12751 }
12752
Denys Vlasenko7bb346f2009-10-06 22:09:50 +020012753 setvar("PPID", utoa(getppid()), 0);
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012754
12755 p = lookupvar("PWD");
12756 if (p)
12757 if (*p != '/' || stat(p, &st1) || stat(".", &st2)
12758 || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino)
12759 p = '\0';
12760 setpwd(p, 0);
12761 }
12762}
12763
12764/*
12765 * Process the shell command line arguments.
12766 */
12767static void
Denis Vlasenko68404f12008-03-17 09:00:54 +000012768procargs(char **argv)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012769{
12770 int i;
12771 const char *xminusc;
12772 char **xargv;
12773
12774 xargv = argv;
12775 arg0 = xargv[0];
Denis Vlasenko68404f12008-03-17 09:00:54 +000012776 /* if (xargv[0]) - mmm, this is always true! */
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012777 xargv++;
12778 for (i = 0; i < NOPTS; i++)
12779 optlist[i] = 2;
12780 argptr = xargv;
Denis Vlasenko28bf6712008-02-14 15:01:47 +000012781 if (options(1)) {
12782 /* it already printed err message */
12783 raise_exception(EXERROR);
12784 }
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012785 xargv = argptr;
12786 xminusc = minusc;
12787 if (*xargv == NULL) {
12788 if (xminusc)
12789 ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
12790 sflag = 1;
12791 }
12792 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
12793 iflag = 1;
12794 if (mflag == 2)
12795 mflag = iflag;
12796 for (i = 0; i < NOPTS; i++)
12797 if (optlist[i] == 2)
12798 optlist[i] = 0;
12799#if DEBUG == 2
12800 debug = 1;
12801#endif
12802 /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
12803 if (xminusc) {
12804 minusc = *xargv++;
12805 if (*xargv)
12806 goto setarg0;
12807 } else if (!sflag) {
12808 setinputfile(*xargv, 0);
12809 setarg0:
12810 arg0 = *xargv++;
12811 commandname = arg0;
12812 }
12813
12814 shellparam.p = xargv;
12815#if ENABLE_ASH_GETOPTS
12816 shellparam.optind = 1;
12817 shellparam.optoff = -1;
12818#endif
Denis Vlasenko01631112007-12-16 17:20:38 +000012819 /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012820 while (*xargv) {
12821 shellparam.nparam++;
12822 xargv++;
12823 }
12824 optschanged();
12825}
12826
12827/*
12828 * Read /etc/profile or .profile.
12829 */
12830static void
12831read_profile(const char *name)
12832{
12833 int skip;
12834
12835 if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
12836 return;
12837 skip = cmdloop(0);
12838 popfile();
12839 if (skip)
12840 exitshell();
12841}
12842
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012843/*
12844 * This routine is called when an error or an interrupt occurs in an
12845 * interactive shell and control is returned to the main command loop.
12846 */
12847static void
12848reset(void)
12849{
12850 /* from eval.c: */
12851 evalskip = 0;
12852 loopnest = 0;
12853 /* from input.c: */
Denis Vlasenko41eb3002008-11-28 03:42:31 +000012854 g_parsefile->left_in_buffer = 0;
12855 g_parsefile->left_in_line = 0; /* clear input buffer */
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012856 popallfiles();
12857 /* from parser.c: */
12858 tokpushback = 0;
12859 checkkwd = 0;
12860 /* from redir.c: */
Denis Vlasenko34c73c42008-08-16 11:48:02 +000012861 clearredir(/*drop:*/ 0);
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012862}
12863
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012864#if PROFILE
12865static short profile_buf[16384];
12866extern int etext();
12867#endif
12868
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012869/*
12870 * Main routine. We initialize things, parse the arguments, execute
12871 * profiles if we're a login shell, and then call cmdloop to execute
12872 * commands. The setjmp call sets up the location to jump to when an
12873 * exception occurs. When an exception occurs the variable "state"
12874 * is used to figure out how far we had gotten.
12875 */
Denis Vlasenko9b49a5e2007-10-11 10:05:36 +000012876int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012877int ash_main(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012878{
Mike Frysinger98c52642009-04-02 10:02:37 +000012879 const char *shinit;
Denis Vlasenko4e12b1a2008-12-23 23:36:47 +000012880 volatile smallint state;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012881 struct jmploc jmploc;
12882 struct stackmark smark;
12883
Denis Vlasenko01631112007-12-16 17:20:38 +000012884 /* Initialize global data */
12885 INIT_G_misc();
12886 INIT_G_memstack();
12887 INIT_G_var();
Denis Vlasenkoee87ebf2007-12-21 22:18:16 +000012888#if ENABLE_ASH_ALIAS
Denis Vlasenko01631112007-12-16 17:20:38 +000012889 INIT_G_alias();
Denis Vlasenkoee87ebf2007-12-21 22:18:16 +000012890#endif
Denis Vlasenko01631112007-12-16 17:20:38 +000012891 INIT_G_cmdtable();
12892
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012893#if PROFILE
12894 monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
12895#endif
12896
12897#if ENABLE_FEATURE_EDITING
12898 line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
12899#endif
12900 state = 0;
12901 if (setjmp(jmploc.loc)) {
Denis Vlasenko7f88e342009-03-19 03:36:18 +000012902 smallint e;
Denis Vlasenko4e12b1a2008-12-23 23:36:47 +000012903 smallint s;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012904
12905 reset();
12906
Denis Vlasenko7f88e342009-03-19 03:36:18 +000012907 e = exception_type;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012908 if (e == EXERROR)
12909 exitstatus = 2;
12910 s = state;
12911 if (e == EXEXIT || s == 0 || iflag == 0 || shlvl)
12912 exitshell();
Denis Vlasenko7f88e342009-03-19 03:36:18 +000012913 if (e == EXINT)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012914 outcslow('\n', stderr);
Denis Vlasenko7f88e342009-03-19 03:36:18 +000012915
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012916 popstackmark(&smark);
12917 FORCE_INT_ON; /* enable interrupts */
12918 if (s == 1)
12919 goto state1;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000012920 if (s == 2)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012921 goto state2;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000012922 if (s == 3)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012923 goto state3;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000012924 goto state4;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012925 }
12926 exception_handler = &jmploc;
12927#if DEBUG
12928 opentrace();
Denis Vlasenko653d8e72009-03-19 21:59:35 +000012929 TRACE(("Shell args: "));
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000012930 trace_puts_args(argv);
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012931#endif
12932 rootpid = getpid();
12933
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012934 init();
12935 setstackmark(&smark);
Denis Vlasenko68404f12008-03-17 09:00:54 +000012936 procargs(argv);
12937
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012938#if ENABLE_FEATURE_EDITING_SAVEHISTORY
12939 if (iflag) {
12940 const char *hp = lookupvar("HISTFILE");
12941
12942 if (hp == NULL) {
12943 hp = lookupvar("HOME");
12944 if (hp != NULL) {
12945 char *defhp = concat_path_file(hp, ".ash_history");
12946 setvar("HISTFILE", defhp, 0);
12947 free(defhp);
12948 }
12949 }
12950 }
12951#endif
Denis Vlasenko4e12b1a2008-12-23 23:36:47 +000012952 if (/* argv[0] && */ argv[0][0] == '-')
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012953 isloginsh = 1;
12954 if (isloginsh) {
12955 state = 1;
12956 read_profile("/etc/profile");
12957 state1:
12958 state = 2;
12959 read_profile(".profile");
12960 }
12961 state2:
12962 state = 3;
12963 if (
12964#ifndef linux
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012965 getuid() == geteuid() && getgid() == getegid() &&
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012966#endif
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012967 iflag
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012968 ) {
12969 shinit = lookupvar("ENV");
12970 if (shinit != NULL && *shinit != '\0') {
12971 read_profile(shinit);
12972 }
12973 }
12974 state3:
12975 state = 4;
Denis Vlasenko5c2b8142009-03-19 01:59:59 +000012976 if (minusc) {
12977 /* evalstring pushes parsefile stack.
12978 * Ensure we don't falsely claim that 0 (stdin)
Denis Vlasenko5368ad52009-03-20 10:20:08 +000012979 * is one of stacked source fds.
12980 * Testcase: ash -c 'exec 1>&0' must not complain. */
Denis Vlasenko5c2b8142009-03-19 01:59:59 +000012981 if (!sflag)
12982 g_parsefile->fd = -1;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012983 evalstring(minusc, 0);
Denis Vlasenko5c2b8142009-03-19 01:59:59 +000012984 }
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012985
12986 if (sflag || minusc == NULL) {
Denys Vlasenko0337e032009-11-29 00:12:30 +010012987#if defined MAX_HISTORY && MAX_HISTORY > 0 && ENABLE_FEATURE_EDITING_SAVEHISTORY
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +000012988 if (iflag) {
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012989 const char *hp = lookupvar("HISTFILE");
Denis Vlasenko5c2b8142009-03-19 01:59:59 +000012990 if (hp)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012991 line_input_state->hist_file = hp;
12992 }
12993#endif
12994 state4: /* XXX ??? - why isn't this before the "if" statement */
12995 cmdloop(1);
12996 }
12997#if PROFILE
12998 monitor(0);
12999#endif
13000#ifdef GPROF
13001 {
13002 extern void _mcleanup(void);
13003 _mcleanup();
13004 }
13005#endif
13006 exitshell();
13007 /* NOTREACHED */
13008}
13009
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013010
Eric Andersendf82f612001-06-28 07:46:40 +000013011/*-
13012 * Copyright (c) 1989, 1991, 1993, 1994
Eric Andersen2870d962001-07-02 17:27:21 +000013013 * The Regents of the University of California. All rights reserved.
Eric Andersendf82f612001-06-28 07:46:40 +000013014 *
13015 * This code is derived from software contributed to Berkeley by
13016 * Kenneth Almquist.
13017 *
13018 * Redistribution and use in source and binary forms, with or without
13019 * modification, are permitted provided that the following conditions
13020 * are met:
13021 * 1. Redistributions of source code must retain the above copyright
13022 * notice, this list of conditions and the following disclaimer.
13023 * 2. Redistributions in binary form must reproduce the above copyright
13024 * notice, this list of conditions and the following disclaimer in the
13025 * documentation and/or other materials provided with the distribution.
"Vladimir N. Oleynik"ddc280e2005-12-15 12:01:49 +000013026 * 3. Neither the name of the University nor the names of its contributors
Eric Andersendf82f612001-06-28 07:46:40 +000013027 * may be used to endorse or promote products derived from this software
13028 * without specific prior written permission.
13029 *
13030 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
13031 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
13032 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
13033 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
13034 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
13035 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
13036 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
13037 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
13038 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
13039 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
13040 * SUCH DAMAGE.
13041 */