blob: 4f2fa756bdafd3701f934166810bc667e8f77f09 [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 */
Denys Vlasenko238bf182010-05-18 15:49:07 +0200211 uint8_t may_have_traps; /* 0: definitely no traps are set, 1: some traps may be set */
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000212 char *trap[NSIG];
Denys Vlasenko21d87d42009-09-25 00:06:51 +0200213 char **trap_ptr; /* used only by "trap hack" */
Denis Vlasenko448d30e2008-06-27 00:24:11 +0000214
215 /* Rarely referenced stuff */
216#if ENABLE_ASH_RANDOM_SUPPORT
Denys Vlasenko3ea2e822009-10-09 20:59:04 +0200217 random_t random_gen;
Denis Vlasenko448d30e2008-06-27 00:24:11 +0000218#endif
219 pid_t backgndpid; /* pid of last background process */
220 smallint job_warning; /* user was warned about stopped jobs (can be 2, 1 or 0). */
Denis Vlasenko01631112007-12-16 17:20:38 +0000221};
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000222extern struct globals_misc *const ash_ptr_to_globals_misc;
223#define G_misc (*ash_ptr_to_globals_misc)
Denis Vlasenko26bc57d2008-06-27 00:29:34 +0000224#define rootpid (G_misc.rootpid )
225#define shlvl (G_misc.shlvl )
226#define minusc (G_misc.minusc )
227#define curdir (G_misc.curdir )
228#define physdir (G_misc.physdir )
229#define arg0 (G_misc.arg0 )
Denis Vlasenko01631112007-12-16 17:20:38 +0000230#define exception_handler (G_misc.exception_handler)
Denis Vlasenko7f88e342009-03-19 03:36:18 +0000231#define exception_type (G_misc.exception_type )
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200232#define suppress_int (G_misc.suppress_int )
233#define pending_int (G_misc.pending_int )
234#define pending_sig (G_misc.pending_sig )
Denis Vlasenko26bc57d2008-06-27 00:29:34 +0000235#define isloginsh (G_misc.isloginsh )
236#define nullstr (G_misc.nullstr )
237#define optlist (G_misc.optlist )
238#define sigmode (G_misc.sigmode )
239#define gotsig (G_misc.gotsig )
Denys Vlasenko238bf182010-05-18 15:49:07 +0200240#define may_have_traps (G_misc.may_have_traps )
Denis Vlasenko26bc57d2008-06-27 00:29:34 +0000241#define trap (G_misc.trap )
Denys Vlasenko21d87d42009-09-25 00:06:51 +0200242#define trap_ptr (G_misc.trap_ptr )
Denys Vlasenko3ea2e822009-10-09 20:59:04 +0200243#define random_gen (G_misc.random_gen )
Denis Vlasenko448d30e2008-06-27 00:24:11 +0000244#define backgndpid (G_misc.backgndpid )
245#define job_warning (G_misc.job_warning)
Denis Vlasenko01631112007-12-16 17:20:38 +0000246#define INIT_G_misc() do { \
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000247 (*(struct globals_misc**)&ash_ptr_to_globals_misc) = xzalloc(sizeof(G_misc)); \
248 barrier(); \
Denis Vlasenko01631112007-12-16 17:20:38 +0000249 curdir = nullstr; \
250 physdir = nullstr; \
Denys Vlasenko21d87d42009-09-25 00:06:51 +0200251 trap_ptr = trap; \
Denis Vlasenko01631112007-12-16 17:20:38 +0000252} while (0)
253
254
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000255/* ============ DEBUG */
256#if DEBUG
257static void trace_printf(const char *fmt, ...);
258static void trace_vprintf(const char *fmt, va_list va);
259# define TRACE(param) trace_printf param
260# define TRACEV(param) trace_vprintf param
Denis Vlasenko1bb3d7e2009-03-20 07:45:36 +0000261# define close(fd) do { \
262 int dfd = (fd); \
Denis Vlasenkob9e70dd2009-03-20 01:24:08 +0000263 if (close(dfd) < 0) \
Denys Vlasenko883cea42009-07-11 15:31:59 +0200264 bb_error_msg("bug on %d: closing %d(0x%x)", \
Denis Vlasenko1bb3d7e2009-03-20 07:45:36 +0000265 __LINE__, dfd, dfd); \
Denis Vlasenkob9e70dd2009-03-20 01:24:08 +0000266} while (0)
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000267#else
268# define TRACE(param)
269# define TRACEV(param)
270#endif
271
272
Denis Vlasenko559691a2008-10-05 18:39:31 +0000273/* ============ Utility functions */
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000274#define xbarrier() do { __asm__ __volatile__ ("": : :"memory"); } while (0)
275
Denis Vlasenko559691a2008-10-05 18:39:31 +0000276static int isdigit_str9(const char *str)
277{
278 int maxlen = 9 + 1; /* max 9 digits: 999999999 */
279 while (--maxlen && isdigit(*str))
280 str++;
281 return (*str == '\0');
282}
Denis Vlasenko01631112007-12-16 17:20:38 +0000283
Denis Vlasenko559691a2008-10-05 18:39:31 +0000284
285/* ============ Interrupts / exceptions */
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +0000286/*
Eric Andersen2870d962001-07-02 17:27:21 +0000287 * These macros allow the user to suspend the handling of interrupt signals
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +0000288 * over a period of time. This is similar to SIGHOLD or to sigblock, but
Eric Andersen2870d962001-07-02 17:27:21 +0000289 * much more efficient and portable. (But hacking the kernel is so much
290 * more fun than worrying about efficiency and portability. :-))
291 */
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000292#define INT_OFF do { \
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200293 suppress_int++; \
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000294 xbarrier(); \
295} while (0)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000296
297/*
298 * Called to raise an exception. Since C doesn't include exceptions, we
299 * just do a longjmp to the exception handler. The type of exception is
Denis Vlasenko4b875702009-03-19 13:30:04 +0000300 * stored in the global variable "exception_type".
Denis Vlasenkob012b102007-02-19 22:43:01 +0000301 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +0000302static void raise_exception(int) NORETURN;
Denis Vlasenkob012b102007-02-19 22:43:01 +0000303static void
304raise_exception(int e)
305{
306#if DEBUG
Denis Vlasenko2da584f2007-02-19 22:44:05 +0000307 if (exception_handler == NULL)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000308 abort();
309#endif
310 INT_OFF;
Denis Vlasenko7f88e342009-03-19 03:36:18 +0000311 exception_type = e;
Denis Vlasenko2da584f2007-02-19 22:44:05 +0000312 longjmp(exception_handler->loc, 1);
Denis Vlasenkob012b102007-02-19 22:43:01 +0000313}
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000314#if DEBUG
315#define raise_exception(e) do { \
316 TRACE(("raising exception %d on line %d\n", (e), __LINE__)); \
317 raise_exception(e); \
318} while (0)
319#endif
Denis Vlasenkob012b102007-02-19 22:43:01 +0000320
321/*
322 * Called from trap.c when a SIGINT is received. (If the user specifies
323 * that SIGINT is to be trapped or ignored using the trap builtin, then
324 * this routine is not called.) Suppressint is nonzero when interrupts
325 * are held using the INT_OFF macro. (The test for iflag is just
326 * defensive programming.)
327 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +0000328static void raise_interrupt(void) NORETURN;
Denis Vlasenkob012b102007-02-19 22:43:01 +0000329static void
330raise_interrupt(void)
331{
Denis Vlasenko4b875702009-03-19 13:30:04 +0000332 int ex_type;
Denis Vlasenkob012b102007-02-19 22:43:01 +0000333
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200334 pending_int = 0;
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +0000335 /* Signal is not automatically unmasked after it is raised,
336 * do it ourself - unmask all signals */
Denis Vlasenko3f165fa2008-03-17 08:29:08 +0000337 sigprocmask_allsigs(SIG_UNBLOCK);
Denys Vlasenko238bf182010-05-18 15:49:07 +0200338 /* pending_sig = 0; - now done in signal_handler() */
Denis Vlasenko7c139b42007-03-21 20:17:27 +0000339
Denis Vlasenko4b875702009-03-19 13:30:04 +0000340 ex_type = EXSIG;
Denis Vlasenkob012b102007-02-19 22:43:01 +0000341 if (gotsig[SIGINT - 1] && !trap[SIGINT]) {
342 if (!(rootshell && iflag)) {
Denis Vlasenko991a1da2008-02-10 19:02:53 +0000343 /* Kill ourself with SIGINT */
Denis Vlasenkob012b102007-02-19 22:43:01 +0000344 signal(SIGINT, SIG_DFL);
345 raise(SIGINT);
346 }
Denis Vlasenko4b875702009-03-19 13:30:04 +0000347 ex_type = EXINT;
Denis Vlasenkob012b102007-02-19 22:43:01 +0000348 }
Denis Vlasenko4b875702009-03-19 13:30:04 +0000349 raise_exception(ex_type);
Denis Vlasenkob012b102007-02-19 22:43:01 +0000350 /* NOTREACHED */
351}
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000352#if DEBUG
353#define raise_interrupt() do { \
354 TRACE(("raising interrupt on line %d\n", __LINE__)); \
355 raise_interrupt(); \
356} while (0)
357#endif
Denis Vlasenkob012b102007-02-19 22:43:01 +0000358
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000359static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000360int_on(void)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000361{
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +0000362 xbarrier();
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200363 if (--suppress_int == 0 && pending_int) {
Denis Vlasenkob012b102007-02-19 22:43:01 +0000364 raise_interrupt();
365 }
366}
367#define INT_ON int_on()
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000368static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000369force_int_on(void)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000370{
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +0000371 xbarrier();
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200372 suppress_int = 0;
373 if (pending_int)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000374 raise_interrupt();
375}
376#define FORCE_INT_ON force_int_on()
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000377
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200378#define SAVE_INT(v) ((v) = suppress_int)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000379
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000380#define RESTORE_INT(v) do { \
381 xbarrier(); \
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200382 suppress_int = (v); \
383 if (suppress_int == 0 && pending_int) \
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000384 raise_interrupt(); \
385} while (0)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000386
Glenn L McGrath9fef17d2002-08-22 18:41:20 +0000387
Denis Vlasenkobc54cff2007-02-23 01:05:52 +0000388/* ============ Stdout/stderr output */
Eric Andersenc470f442003-07-28 09:56:35 +0000389
Eric Andersenc470f442003-07-28 09:56:35 +0000390static void
Denis Vlasenkob012b102007-02-19 22:43:01 +0000391outstr(const char *p, FILE *file)
Denis Vlasenkoe5570da2007-02-19 22:41:55 +0000392{
Denis Vlasenkob012b102007-02-19 22:43:01 +0000393 INT_OFF;
394 fputs(p, file);
395 INT_ON;
396}
397
398static void
399flush_stdout_stderr(void)
400{
401 INT_OFF;
Denys Vlasenko8131eea2009-11-02 14:19:51 +0100402 fflush_all();
Denis Vlasenkob012b102007-02-19 22:43:01 +0000403 INT_ON;
404}
405
406static void
407outcslow(int c, FILE *dest)
408{
409 INT_OFF;
410 putc(c, dest);
411 fflush(dest);
412 INT_ON;
413}
414
415static int out1fmt(const char *, ...) __attribute__((__format__(__printf__,1,2)));
416static int
417out1fmt(const char *fmt, ...)
418{
419 va_list ap;
420 int r;
421
422 INT_OFF;
423 va_start(ap, fmt);
424 r = vprintf(fmt, ap);
425 va_end(ap);
426 INT_ON;
427 return r;
428}
429
430static int fmtstr(char *, size_t, const char *, ...) __attribute__((__format__(__printf__,3,4)));
431static int
432fmtstr(char *outbuf, size_t length, const char *fmt, ...)
433{
434 va_list ap;
435 int ret;
436
437 va_start(ap, fmt);
438 INT_OFF;
439 ret = vsnprintf(outbuf, length, fmt, ap);
440 va_end(ap);
441 INT_ON;
442 return ret;
443}
444
445static void
446out1str(const char *p)
447{
448 outstr(p, stdout);
449}
450
451static void
452out2str(const char *p)
453{
454 outstr(p, stderr);
Denys Vlasenko8131eea2009-11-02 14:19:51 +0100455 flush_stdout_stderr();
Denis Vlasenkob012b102007-02-19 22:43:01 +0000456}
457
458
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +0000459/* ============ Parser structures */
Denis Vlasenko4d2183b2007-02-23 01:05:38 +0000460
Denis Vlasenko5651bfc2007-02-23 21:08:58 +0000461/* control characters in argument strings */
Denys Vlasenko2ce42e92009-11-29 02:18:13 +0100462#define CTL_FIRST CTLESC
Denys Vlasenkob6c84342009-08-29 20:23:20 +0200463#define CTLESC ((unsigned char)'\201') /* escape next character */
464#define CTLVAR ((unsigned char)'\202') /* variable defn */
465#define CTLENDVAR ((unsigned char)'\203')
466#define CTLBACKQ ((unsigned char)'\204')
Denis Vlasenko5651bfc2007-02-23 21:08:58 +0000467#define CTLQUOTE 01 /* ored with CTLBACKQ code if in quotes */
468/* CTLBACKQ | CTLQUOTE == '\205' */
Denys Vlasenkob6c84342009-08-29 20:23:20 +0200469#define CTLARI ((unsigned char)'\206') /* arithmetic expression */
470#define CTLENDARI ((unsigned char)'\207')
471#define CTLQUOTEMARK ((unsigned char)'\210')
Denys Vlasenko2ce42e92009-11-29 02:18:13 +0100472#define CTL_LAST CTLQUOTEMARK
Denis Vlasenko5651bfc2007-02-23 21:08:58 +0000473
474/* variable substitution byte (follows CTLVAR) */
475#define VSTYPE 0x0f /* type of variable substitution */
476#define VSNUL 0x10 /* colon--treat the empty string as unset */
477#define VSQUOTE 0x80 /* inside double quotes--suppress splitting */
478
479/* values of VSTYPE field */
Denis Vlasenko92e13c22008-03-25 01:17:40 +0000480#define VSNORMAL 0x1 /* normal variable: $var or ${var} */
481#define VSMINUS 0x2 /* ${var-text} */
482#define VSPLUS 0x3 /* ${var+text} */
483#define VSQUESTION 0x4 /* ${var?message} */
484#define VSASSIGN 0x5 /* ${var=text} */
485#define VSTRIMRIGHT 0x6 /* ${var%pattern} */
486#define VSTRIMRIGHTMAX 0x7 /* ${var%%pattern} */
487#define VSTRIMLEFT 0x8 /* ${var#pattern} */
488#define VSTRIMLEFTMAX 0x9 /* ${var##pattern} */
489#define VSLENGTH 0xa /* ${#var} */
490#if ENABLE_ASH_BASH_COMPAT
491#define VSSUBSTR 0xc /* ${var:position:length} */
492#define VSREPLACE 0xd /* ${var/pattern/replacement} */
493#define VSREPLACEALL 0xe /* ${var//pattern/replacement} */
494#endif
Denis Vlasenko5651bfc2007-02-23 21:08:58 +0000495
Denis Vlasenko6ca409e2007-08-12 20:58:27 +0000496static const char dolatstr[] ALIGN1 = {
497 CTLVAR, VSNORMAL|VSQUOTE, '@', '=', '\0'
498};
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +0000499
Denis Vlasenko559691a2008-10-05 18:39:31 +0000500#define NCMD 0
501#define NPIPE 1
502#define NREDIR 2
503#define NBACKGND 3
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000504#define NSUBSHELL 4
Denis Vlasenko559691a2008-10-05 18:39:31 +0000505#define NAND 5
506#define NOR 6
507#define NSEMI 7
508#define NIF 8
509#define NWHILE 9
510#define NUNTIL 10
511#define NFOR 11
512#define NCASE 12
513#define NCLIST 13
514#define NDEFUN 14
515#define NARG 15
516#define NTO 16
517#if ENABLE_ASH_BASH_COMPAT
518#define NTO2 17
519#endif
520#define NCLOBBER 18
521#define NFROM 19
522#define NFROMTO 20
523#define NAPPEND 21
524#define NTOFD 22
525#define NFROMFD 23
526#define NHERE 24
527#define NXHERE 25
528#define NNOT 26
Denis Vlasenko340299a2008-11-21 10:36:36 +0000529#define N_NUMBER 27
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000530
531union node;
532
533struct ncmd {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000534 smallint type; /* Nxxxx */
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000535 union node *assign;
536 union node *args;
537 union node *redirect;
538};
539
540struct npipe {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000541 smallint type;
542 smallint pipe_backgnd;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000543 struct nodelist *cmdlist;
544};
545
546struct nredir {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000547 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000548 union node *n;
549 union node *redirect;
550};
551
552struct nbinary {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000553 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000554 union node *ch1;
555 union node *ch2;
556};
557
558struct nif {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000559 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000560 union node *test;
561 union node *ifpart;
562 union node *elsepart;
563};
564
565struct nfor {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000566 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000567 union node *args;
568 union node *body;
569 char *var;
570};
571
572struct ncase {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000573 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000574 union node *expr;
575 union node *cases;
576};
577
578struct nclist {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000579 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000580 union node *next;
581 union node *pattern;
582 union node *body;
583};
584
585struct narg {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000586 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000587 union node *next;
588 char *text;
589 struct nodelist *backquote;
590};
591
Denis Vlasenko559691a2008-10-05 18:39:31 +0000592/* nfile and ndup layout must match!
593 * NTOFD (>&fdnum) uses ndup structure, but we may discover mid-flight
594 * that it is actually NTO2 (>&file), and change its type.
595 */
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000596struct nfile {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000597 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000598 union node *next;
599 int fd;
Denis Vlasenko559691a2008-10-05 18:39:31 +0000600 int _unused_dupfd;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000601 union node *fname;
602 char *expfname;
603};
604
605struct ndup {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000606 smallint type;
Denis Vlasenko559691a2008-10-05 18:39:31 +0000607 union node *next;
608 int fd;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000609 int dupfd;
610 union node *vname;
Denis Vlasenko559691a2008-10-05 18:39:31 +0000611 char *_unused_expfname;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000612};
613
614struct nhere {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000615 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000616 union node *next;
617 int fd;
618 union node *doc;
619};
620
621struct nnot {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000622 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000623 union node *com;
624};
625
626union node {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000627 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000628 struct ncmd ncmd;
629 struct npipe npipe;
630 struct nredir nredir;
631 struct nbinary nbinary;
632 struct nif nif;
633 struct nfor nfor;
634 struct ncase ncase;
635 struct nclist nclist;
636 struct narg narg;
637 struct nfile nfile;
638 struct ndup ndup;
639 struct nhere nhere;
640 struct nnot nnot;
641};
642
Denys Vlasenko86e83ec2009-07-23 22:07:07 +0200643/*
644 * NODE_EOF is returned by parsecmd when it encounters an end of file.
645 * It must be distinct from NULL.
646 */
647#define NODE_EOF ((union node *) -1L)
648
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000649struct nodelist {
650 struct nodelist *next;
651 union node *n;
652};
653
654struct funcnode {
655 int count;
656 union node n;
657};
658
Denis Vlasenko5651bfc2007-02-23 21:08:58 +0000659/*
660 * Free a parse tree.
661 */
662static void
663freefunc(struct funcnode *f)
664{
665 if (f && --f->count < 0)
666 free(f);
667}
668
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000669
670/* ============ Debugging output */
671
672#if DEBUG
673
674static FILE *tracefile;
675
676static void
677trace_printf(const char *fmt, ...)
678{
679 va_list va;
680
681 if (debug != 1)
682 return;
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000683 if (DEBUG_TIME)
684 fprintf(tracefile, "%u ", (int) time(NULL));
685 if (DEBUG_PID)
686 fprintf(tracefile, "[%u] ", (int) getpid());
687 if (DEBUG_SIG)
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200688 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000689 va_start(va, fmt);
690 vfprintf(tracefile, fmt, va);
691 va_end(va);
692}
693
694static void
695trace_vprintf(const char *fmt, va_list va)
696{
697 if (debug != 1)
698 return;
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000699 if (DEBUG_TIME)
700 fprintf(tracefile, "%u ", (int) time(NULL));
701 if (DEBUG_PID)
702 fprintf(tracefile, "[%u] ", (int) getpid());
703 if (DEBUG_SIG)
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200704 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000705 vfprintf(tracefile, fmt, va);
706}
707
708static void
709trace_puts(const char *s)
710{
711 if (debug != 1)
712 return;
713 fputs(s, tracefile);
714}
715
716static void
717trace_puts_quoted(char *s)
718{
719 char *p;
720 char c;
721
722 if (debug != 1)
723 return;
724 putc('"', tracefile);
725 for (p = s; *p; p++) {
Denys Vlasenkocd716832009-11-28 22:14:02 +0100726 switch ((unsigned char)*p) {
727 case '\n': c = 'n'; goto backslash;
728 case '\t': c = 't'; goto backslash;
729 case '\r': c = 'r'; goto backslash;
730 case '\"': c = '\"'; goto backslash;
731 case '\\': c = '\\'; goto backslash;
732 case CTLESC: c = 'e'; goto backslash;
733 case CTLVAR: c = 'v'; goto backslash;
734 case CTLVAR+CTLQUOTE: c = 'V'; goto backslash;
735 case CTLBACKQ: c = 'q'; goto backslash;
736 case CTLBACKQ+CTLQUOTE: c = 'Q'; goto backslash;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000737 backslash:
738 putc('\\', tracefile);
739 putc(c, tracefile);
740 break;
741 default:
742 if (*p >= ' ' && *p <= '~')
743 putc(*p, tracefile);
744 else {
745 putc('\\', tracefile);
Denys Vlasenkocd716832009-11-28 22:14:02 +0100746 putc((*p >> 6) & 03, tracefile);
747 putc((*p >> 3) & 07, tracefile);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000748 putc(*p & 07, tracefile);
749 }
750 break;
751 }
752 }
753 putc('"', tracefile);
754}
755
756static void
757trace_puts_args(char **ap)
758{
759 if (debug != 1)
760 return;
761 if (!*ap)
762 return;
763 while (1) {
764 trace_puts_quoted(*ap);
765 if (!*++ap) {
766 putc('\n', tracefile);
767 break;
768 }
769 putc(' ', tracefile);
770 }
771}
772
773static void
774opentrace(void)
775{
776 char s[100];
777#ifdef O_APPEND
778 int flags;
779#endif
780
781 if (debug != 1) {
782 if (tracefile)
783 fflush(tracefile);
784 /* leave open because libedit might be using it */
785 return;
786 }
787 strcpy(s, "./trace");
788 if (tracefile) {
789 if (!freopen(s, "a", tracefile)) {
790 fprintf(stderr, "Can't re-open %s\n", s);
791 debug = 0;
792 return;
793 }
794 } else {
795 tracefile = fopen(s, "a");
796 if (tracefile == NULL) {
797 fprintf(stderr, "Can't open %s\n", s);
798 debug = 0;
799 return;
800 }
801 }
802#ifdef O_APPEND
Denis Vlasenkod37f2222007-08-19 13:42:08 +0000803 flags = fcntl(fileno(tracefile), F_GETFL);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000804 if (flags >= 0)
805 fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
806#endif
807 setlinebuf(tracefile);
808 fputs("\nTracing started.\n", tracefile);
809}
810
811static void
812indent(int amount, char *pfx, FILE *fp)
813{
814 int i;
815
816 for (i = 0; i < amount; i++) {
817 if (pfx && i == amount - 1)
818 fputs(pfx, fp);
819 putc('\t', fp);
820 }
821}
822
823/* little circular references here... */
824static void shtree(union node *n, int ind, char *pfx, FILE *fp);
825
826static void
827sharg(union node *arg, FILE *fp)
828{
829 char *p;
830 struct nodelist *bqlist;
Denys Vlasenkocd716832009-11-28 22:14:02 +0100831 unsigned char subtype;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000832
833 if (arg->type != NARG) {
834 out1fmt("<node type %d>\n", arg->type);
835 abort();
836 }
837 bqlist = arg->narg.backquote;
838 for (p = arg->narg.text; *p; p++) {
Denys Vlasenkocd716832009-11-28 22:14:02 +0100839 switch ((unsigned char)*p) {
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000840 case CTLESC:
841 putc(*++p, fp);
842 break;
843 case CTLVAR:
844 putc('$', fp);
845 putc('{', fp);
846 subtype = *++p;
847 if (subtype == VSLENGTH)
848 putc('#', fp);
849
850 while (*p != '=')
851 putc(*p++, fp);
852
853 if (subtype & VSNUL)
854 putc(':', fp);
855
856 switch (subtype & VSTYPE) {
857 case VSNORMAL:
858 putc('}', fp);
859 break;
860 case VSMINUS:
861 putc('-', fp);
862 break;
863 case VSPLUS:
864 putc('+', fp);
865 break;
866 case VSQUESTION:
867 putc('?', fp);
868 break;
869 case VSASSIGN:
870 putc('=', fp);
871 break;
872 case VSTRIMLEFT:
873 putc('#', fp);
874 break;
875 case VSTRIMLEFTMAX:
876 putc('#', fp);
877 putc('#', fp);
878 break;
879 case VSTRIMRIGHT:
880 putc('%', fp);
881 break;
882 case VSTRIMRIGHTMAX:
883 putc('%', fp);
884 putc('%', fp);
885 break;
886 case VSLENGTH:
887 break;
888 default:
889 out1fmt("<subtype %d>", subtype);
890 }
891 break;
892 case CTLENDVAR:
893 putc('}', fp);
894 break;
895 case CTLBACKQ:
896 case CTLBACKQ|CTLQUOTE:
897 putc('$', fp);
898 putc('(', fp);
899 shtree(bqlist->n, -1, NULL, fp);
900 putc(')', fp);
901 break;
902 default:
903 putc(*p, fp);
904 break;
905 }
906 }
907}
908
Denys Vlasenko641dd7b2009-06-11 19:30:19 +0200909static void
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000910shcmd(union node *cmd, FILE *fp)
911{
912 union node *np;
913 int first;
914 const char *s;
915 int dftfd;
916
917 first = 1;
918 for (np = cmd->ncmd.args; np; np = np->narg.next) {
Denis Vlasenko40ba9982007-07-14 00:48:29 +0000919 if (!first)
920 putc(' ', fp);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000921 sharg(np, fp);
922 first = 0;
923 }
924 for (np = cmd->ncmd.redirect; np; np = np->nfile.next) {
Denis Vlasenko40ba9982007-07-14 00:48:29 +0000925 if (!first)
926 putc(' ', fp);
927 dftfd = 0;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000928 switch (np->nfile.type) {
Denis Vlasenko40ba9982007-07-14 00:48:29 +0000929 case NTO: s = ">>"+1; dftfd = 1; break;
930 case NCLOBBER: s = ">|"; dftfd = 1; break;
931 case NAPPEND: s = ">>"; dftfd = 1; break;
Denis Vlasenko559691a2008-10-05 18:39:31 +0000932#if ENABLE_ASH_BASH_COMPAT
933 case NTO2:
934#endif
Denis Vlasenko40ba9982007-07-14 00:48:29 +0000935 case NTOFD: s = ">&"; dftfd = 1; break;
Denis Vlasenko559691a2008-10-05 18:39:31 +0000936 case NFROM: s = "<"; break;
Denis Vlasenko40ba9982007-07-14 00:48:29 +0000937 case NFROMFD: s = "<&"; break;
938 case NFROMTO: s = "<>"; break;
939 default: s = "*error*"; break;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000940 }
941 if (np->nfile.fd != dftfd)
942 fprintf(fp, "%d", np->nfile.fd);
943 fputs(s, fp);
944 if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
945 fprintf(fp, "%d", np->ndup.dupfd);
946 } else {
947 sharg(np->nfile.fname, fp);
948 }
949 first = 0;
950 }
951}
952
953static void
954shtree(union node *n, int ind, char *pfx, FILE *fp)
955{
956 struct nodelist *lp;
957 const char *s;
958
959 if (n == NULL)
960 return;
961
962 indent(ind, pfx, fp);
Denys Vlasenko86e83ec2009-07-23 22:07:07 +0200963
964 if (n == NODE_EOF) {
965 fputs("<EOF>", fp);
966 return;
967 }
968
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000969 switch (n->type) {
970 case NSEMI:
971 s = "; ";
972 goto binop;
973 case NAND:
974 s = " && ";
975 goto binop;
976 case NOR:
977 s = " || ";
978 binop:
979 shtree(n->nbinary.ch1, ind, NULL, fp);
980 /* if (ind < 0) */
981 fputs(s, fp);
982 shtree(n->nbinary.ch2, ind, NULL, fp);
983 break;
984 case NCMD:
985 shcmd(n, fp);
986 if (ind >= 0)
987 putc('\n', fp);
988 break;
989 case NPIPE:
990 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
Denys Vlasenko7cee00e2009-07-24 01:08:03 +0200991 shtree(lp->n, 0, NULL, fp);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000992 if (lp->next)
993 fputs(" | ", fp);
994 }
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000995 if (n->npipe.pipe_backgnd)
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000996 fputs(" &", fp);
997 if (ind >= 0)
998 putc('\n', fp);
999 break;
1000 default:
1001 fprintf(fp, "<node type %d>", n->type);
1002 if (ind >= 0)
1003 putc('\n', fp);
1004 break;
1005 }
1006}
1007
1008static void
1009showtree(union node *n)
1010{
1011 trace_puts("showtree called\n");
Denys Vlasenko883cea42009-07-11 15:31:59 +02001012 shtree(n, 1, NULL, stderr);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00001013}
1014
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00001015#endif /* DEBUG */
1016
1017
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00001018/* ============ Parser data */
1019
1020/*
Denis Vlasenkob012b102007-02-19 22:43:01 +00001021 * ash_vmsg() needs parsefile->fd, hence parsefile definition is moved up.
1022 */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001023struct strlist {
1024 struct strlist *next;
1025 char *text;
1026};
1027
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00001028struct alias;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00001029
Denis Vlasenkob012b102007-02-19 22:43:01 +00001030struct strpush {
1031 struct strpush *prev; /* preceding string on stack */
Denis Vlasenko41eb3002008-11-28 03:42:31 +00001032 char *prev_string;
1033 int prev_left_in_line;
Denis Vlasenkob012b102007-02-19 22:43:01 +00001034#if ENABLE_ASH_ALIAS
1035 struct alias *ap; /* if push was associated with an alias */
1036#endif
1037 char *string; /* remember the string since it may change */
1038};
1039
1040struct parsefile {
1041 struct parsefile *prev; /* preceding file on stack */
1042 int linno; /* current line */
1043 int fd; /* file descriptor (or -1 if string) */
Denis Vlasenko41eb3002008-11-28 03:42:31 +00001044 int left_in_line; /* number of chars left in this line */
1045 int left_in_buffer; /* number of chars left in this buffer past the line */
1046 char *next_to_pgetc; /* next char in buffer */
Denis Vlasenkob012b102007-02-19 22:43:01 +00001047 char *buf; /* input buffer */
1048 struct strpush *strpush; /* for pushing strings at this level */
1049 struct strpush basestrpush; /* so pushing one is fast */
1050};
1051
Denis Vlasenko448d30e2008-06-27 00:24:11 +00001052static struct parsefile basepf; /* top level input file */
Denis Vlasenkob07a4962008-06-22 13:16:23 +00001053static struct parsefile *g_parsefile = &basepf; /* current input file */
Denis Vlasenkob012b102007-02-19 22:43:01 +00001054static int startlinno; /* line # where last token started */
1055static char *commandname; /* currently executing command */
1056static struct strlist *cmdenviron; /* environment for builtin command */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00001057static uint8_t exitstatus; /* exit status of last command */
Denis Vlasenkob012b102007-02-19 22:43:01 +00001058
1059
1060/* ============ Message printing */
1061
1062static void
1063ash_vmsg(const char *msg, va_list ap)
1064{
1065 fprintf(stderr, "%s: ", arg0);
1066 if (commandname) {
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00001067 if (strcmp(arg0, commandname))
1068 fprintf(stderr, "%s: ", commandname);
Denis Vlasenkob07a4962008-06-22 13:16:23 +00001069 if (!iflag || g_parsefile->fd)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00001070 fprintf(stderr, "line %d: ", startlinno);
Eric Andersenc470f442003-07-28 09:56:35 +00001071 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00001072 vfprintf(stderr, msg, ap);
1073 outcslow('\n', stderr);
Eric Andersenc470f442003-07-28 09:56:35 +00001074}
Denis Vlasenkob012b102007-02-19 22:43:01 +00001075
1076/*
1077 * Exverror is called to raise the error exception. If the second argument
1078 * is not NULL then error prints an error message using printf style
1079 * formatting. It then raises the error exception.
1080 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001081static void ash_vmsg_and_raise(int, const char *, va_list) NORETURN;
Denis Vlasenkob012b102007-02-19 22:43:01 +00001082static void
1083ash_vmsg_and_raise(int cond, const char *msg, va_list ap)
Eric Andersenc470f442003-07-28 09:56:35 +00001084{
Denis Vlasenkob012b102007-02-19 22:43:01 +00001085#if DEBUG
1086 if (msg) {
1087 TRACE(("ash_vmsg_and_raise(%d, \"", cond));
1088 TRACEV((msg, ap));
1089 TRACE(("\") pid=%d\n", getpid()));
1090 } else
1091 TRACE(("ash_vmsg_and_raise(%d, NULL) pid=%d\n", cond, getpid()));
1092 if (msg)
1093#endif
1094 ash_vmsg(msg, ap);
1095
1096 flush_stdout_stderr();
1097 raise_exception(cond);
1098 /* NOTREACHED */
Eric Andersenc470f442003-07-28 09:56:35 +00001099}
Denis Vlasenkob012b102007-02-19 22:43:01 +00001100
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001101static void ash_msg_and_raise_error(const char *, ...) NORETURN;
Denis Vlasenkob012b102007-02-19 22:43:01 +00001102static void
1103ash_msg_and_raise_error(const char *msg, ...)
1104{
1105 va_list ap;
1106
1107 va_start(ap, msg);
1108 ash_vmsg_and_raise(EXERROR, msg, ap);
1109 /* NOTREACHED */
1110 va_end(ap);
1111}
1112
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00001113static void raise_error_syntax(const char *) NORETURN;
1114static void
1115raise_error_syntax(const char *msg)
1116{
1117 ash_msg_and_raise_error("syntax error: %s", msg);
1118 /* NOTREACHED */
1119}
1120
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001121static void ash_msg_and_raise(int, const char *, ...) NORETURN;
Denis Vlasenkob012b102007-02-19 22:43:01 +00001122static void
1123ash_msg_and_raise(int cond, const char *msg, ...)
1124{
1125 va_list ap;
1126
1127 va_start(ap, msg);
1128 ash_vmsg_and_raise(cond, msg, ap);
1129 /* NOTREACHED */
1130 va_end(ap);
1131}
1132
1133/*
1134 * error/warning routines for external builtins
1135 */
1136static void
1137ash_msg(const char *fmt, ...)
1138{
1139 va_list ap;
1140
1141 va_start(ap, fmt);
1142 ash_vmsg(fmt, ap);
1143 va_end(ap);
1144}
1145
1146/*
1147 * Return a string describing an error. The returned string may be a
1148 * pointer to a static buffer that will be overwritten on the next call.
1149 * Action describes the operation that got the error.
1150 */
1151static const char *
1152errmsg(int e, const char *em)
1153{
1154 if (e == ENOENT || e == ENOTDIR) {
1155 return em;
1156 }
1157 return strerror(e);
1158}
1159
1160
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001161/* ============ Memory allocation */
1162
Denys Vlasenkoe7670ff2009-10-11 00:45:25 +02001163#if 0
1164/* I consider these wrappers nearly useless:
1165 * ok, they return you to nearest exception handler, but
1166 * how much memory do you leak in the process, making
1167 * memory starvation worse?
1168 */
1169static void *
1170ckrealloc(void * p, size_t nbytes)
1171{
1172 p = realloc(p, nbytes);
1173 if (!p)
1174 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1175 return p;
1176}
1177
1178static void *
1179ckmalloc(size_t nbytes)
1180{
1181 return ckrealloc(NULL, nbytes);
1182}
1183
1184static void *
1185ckzalloc(size_t nbytes)
1186{
1187 return memset(ckmalloc(nbytes), 0, nbytes);
1188}
1189
1190static char *
1191ckstrdup(const char *s)
1192{
1193 char *p = strdup(s);
1194 if (!p)
1195 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1196 return p;
1197}
1198#else
1199/* Using bbox equivalents. They exit if out of memory */
1200# define ckrealloc xrealloc
1201# define ckmalloc xmalloc
1202# define ckzalloc xzalloc
1203# define ckstrdup xstrdup
1204#endif
1205
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001206/*
1207 * It appears that grabstackstr() will barf with such alignments
1208 * because stalloc() will return a string allocated in a new stackblock.
1209 */
1210#define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
1211enum {
1212 /* Most machines require the value returned from malloc to be aligned
1213 * in some way. The following macro will get this right
1214 * on many machines. */
Denys Vlasenko0e5e4ea2009-10-11 00:36:20 +02001215 SHELL_SIZE = sizeof(union { int i; char *cp; double d; }) - 1,
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001216 /* Minimum size of a block */
Denis Vlasenko01631112007-12-16 17:20:38 +00001217 MINSIZE = SHELL_ALIGN(504),
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001218};
1219
1220struct stack_block {
1221 struct stack_block *prev;
1222 char space[MINSIZE];
1223};
1224
1225struct stackmark {
1226 struct stack_block *stackp;
1227 char *stacknxt;
1228 size_t stacknleft;
1229 struct stackmark *marknext;
1230};
1231
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001232
Denis Vlasenko01631112007-12-16 17:20:38 +00001233struct globals_memstack {
1234 struct stack_block *g_stackp; // = &stackbase;
1235 struct stackmark *markp;
1236 char *g_stacknxt; // = stackbase.space;
1237 char *sstrend; // = stackbase.space + MINSIZE;
1238 size_t g_stacknleft; // = MINSIZE;
1239 int herefd; // = -1;
1240 struct stack_block stackbase;
1241};
Denis Vlasenko574f2f42008-02-27 18:41:59 +00001242extern struct globals_memstack *const ash_ptr_to_globals_memstack;
1243#define G_memstack (*ash_ptr_to_globals_memstack)
Denis Vlasenko01631112007-12-16 17:20:38 +00001244#define g_stackp (G_memstack.g_stackp )
1245#define markp (G_memstack.markp )
1246#define g_stacknxt (G_memstack.g_stacknxt )
1247#define sstrend (G_memstack.sstrend )
1248#define g_stacknleft (G_memstack.g_stacknleft)
1249#define herefd (G_memstack.herefd )
1250#define stackbase (G_memstack.stackbase )
1251#define INIT_G_memstack() do { \
Denis Vlasenko574f2f42008-02-27 18:41:59 +00001252 (*(struct globals_memstack**)&ash_ptr_to_globals_memstack) = xzalloc(sizeof(G_memstack)); \
1253 barrier(); \
Denis Vlasenko01631112007-12-16 17:20:38 +00001254 g_stackp = &stackbase; \
1255 g_stacknxt = stackbase.space; \
1256 g_stacknleft = MINSIZE; \
1257 sstrend = stackbase.space + MINSIZE; \
1258 herefd = -1; \
1259} while (0)
1260
Denys Vlasenkoe7670ff2009-10-11 00:45:25 +02001261
Denis Vlasenko01631112007-12-16 17:20:38 +00001262#define stackblock() ((void *)g_stacknxt)
1263#define stackblocksize() g_stacknleft
1264
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001265/*
1266 * Parse trees for commands are allocated in lifo order, so we use a stack
1267 * to make this more efficient, and also to avoid all sorts of exception
1268 * handling code to handle interrupts in the middle of a parse.
1269 *
1270 * The size 504 was chosen because the Ultrix malloc handles that size
1271 * well.
1272 */
1273static void *
1274stalloc(size_t nbytes)
1275{
1276 char *p;
1277 size_t aligned;
1278
1279 aligned = SHELL_ALIGN(nbytes);
Denis Vlasenko01631112007-12-16 17:20:38 +00001280 if (aligned > g_stacknleft) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001281 size_t len;
1282 size_t blocksize;
1283 struct stack_block *sp;
1284
1285 blocksize = aligned;
1286 if (blocksize < MINSIZE)
1287 blocksize = MINSIZE;
1288 len = sizeof(struct stack_block) - MINSIZE + blocksize;
1289 if (len < blocksize)
1290 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1291 INT_OFF;
1292 sp = ckmalloc(len);
Denis Vlasenko01631112007-12-16 17:20:38 +00001293 sp->prev = g_stackp;
1294 g_stacknxt = sp->space;
1295 g_stacknleft = blocksize;
1296 sstrend = g_stacknxt + blocksize;
1297 g_stackp = sp;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001298 INT_ON;
1299 }
Denis Vlasenko01631112007-12-16 17:20:38 +00001300 p = g_stacknxt;
1301 g_stacknxt += aligned;
1302 g_stacknleft -= aligned;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001303 return p;
1304}
1305
Denis Vlasenko597906c2008-02-20 16:38:54 +00001306static void *
1307stzalloc(size_t nbytes)
1308{
1309 return memset(stalloc(nbytes), 0, nbytes);
1310}
1311
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001312static void
1313stunalloc(void *p)
1314{
1315#if DEBUG
Denis Vlasenko01631112007-12-16 17:20:38 +00001316 if (!p || (g_stacknxt < (char *)p) || ((char *)p < g_stackp->space)) {
Bernhard Reutner-Fischer5e25ddb2008-05-19 09:48:17 +00001317 write(STDERR_FILENO, "stunalloc\n", 10);
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001318 abort();
1319 }
1320#endif
Denis Vlasenko01631112007-12-16 17:20:38 +00001321 g_stacknleft += g_stacknxt - (char *)p;
1322 g_stacknxt = p;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001323}
1324
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001325/*
1326 * Like strdup but works with the ash stack.
1327 */
1328static char *
1329ststrdup(const char *p)
1330{
1331 size_t len = strlen(p) + 1;
1332 return memcpy(stalloc(len), p, len);
1333}
1334
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001335static void
1336setstackmark(struct stackmark *mark)
1337{
Denis Vlasenko01631112007-12-16 17:20:38 +00001338 mark->stackp = g_stackp;
1339 mark->stacknxt = g_stacknxt;
1340 mark->stacknleft = g_stacknleft;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001341 mark->marknext = markp;
1342 markp = mark;
1343}
1344
1345static void
1346popstackmark(struct stackmark *mark)
1347{
1348 struct stack_block *sp;
1349
Denis Vlasenko93ebd4f2007-03-13 20:55:36 +00001350 if (!mark->stackp)
1351 return;
1352
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001353 INT_OFF;
1354 markp = mark->marknext;
Denis Vlasenko01631112007-12-16 17:20:38 +00001355 while (g_stackp != mark->stackp) {
1356 sp = g_stackp;
1357 g_stackp = sp->prev;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001358 free(sp);
1359 }
Denis Vlasenko01631112007-12-16 17:20:38 +00001360 g_stacknxt = mark->stacknxt;
1361 g_stacknleft = mark->stacknleft;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001362 sstrend = mark->stacknxt + mark->stacknleft;
1363 INT_ON;
1364}
1365
1366/*
1367 * When the parser reads in a string, it wants to stick the string on the
1368 * stack and only adjust the stack pointer when it knows how big the
1369 * string is. Stackblock (defined in stack.h) returns a pointer to a block
1370 * of space on top of the stack and stackblocklen returns the length of
1371 * this block. Growstackblock will grow this space by at least one byte,
1372 * possibly moving it (like realloc). Grabstackblock actually allocates the
1373 * part of the block that has been used.
1374 */
1375static void
1376growstackblock(void)
1377{
1378 size_t newlen;
1379
Denis Vlasenko01631112007-12-16 17:20:38 +00001380 newlen = g_stacknleft * 2;
1381 if (newlen < g_stacknleft)
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001382 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1383 if (newlen < 128)
1384 newlen += 128;
1385
Denis Vlasenko01631112007-12-16 17:20:38 +00001386 if (g_stacknxt == g_stackp->space && g_stackp != &stackbase) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001387 struct stack_block *oldstackp;
1388 struct stackmark *xmark;
1389 struct stack_block *sp;
1390 struct stack_block *prevstackp;
1391 size_t grosslen;
1392
1393 INT_OFF;
Denis Vlasenko01631112007-12-16 17:20:38 +00001394 oldstackp = g_stackp;
1395 sp = g_stackp;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001396 prevstackp = sp->prev;
1397 grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
1398 sp = ckrealloc(sp, grosslen);
1399 sp->prev = prevstackp;
Denis Vlasenko01631112007-12-16 17:20:38 +00001400 g_stackp = sp;
1401 g_stacknxt = sp->space;
1402 g_stacknleft = newlen;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001403 sstrend = sp->space + newlen;
1404
1405 /*
1406 * Stack marks pointing to the start of the old block
1407 * must be relocated to point to the new block
1408 */
1409 xmark = markp;
1410 while (xmark != NULL && xmark->stackp == oldstackp) {
Denis Vlasenko01631112007-12-16 17:20:38 +00001411 xmark->stackp = g_stackp;
1412 xmark->stacknxt = g_stacknxt;
1413 xmark->stacknleft = g_stacknleft;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001414 xmark = xmark->marknext;
1415 }
1416 INT_ON;
1417 } else {
Denis Vlasenko01631112007-12-16 17:20:38 +00001418 char *oldspace = g_stacknxt;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00001419 size_t oldlen = g_stacknleft;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001420 char *p = stalloc(newlen);
1421
1422 /* free the space we just allocated */
Denis Vlasenko01631112007-12-16 17:20:38 +00001423 g_stacknxt = memcpy(p, oldspace, oldlen);
1424 g_stacknleft += newlen;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001425 }
1426}
1427
1428static void
1429grabstackblock(size_t len)
1430{
1431 len = SHELL_ALIGN(len);
Denis Vlasenko01631112007-12-16 17:20:38 +00001432 g_stacknxt += len;
1433 g_stacknleft -= len;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001434}
1435
1436/*
1437 * The following routines are somewhat easier to use than the above.
1438 * The user declares a variable of type STACKSTR, which may be declared
1439 * to be a register. The macro STARTSTACKSTR initializes things. Then
1440 * the user uses the macro STPUTC to add characters to the string. In
1441 * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
1442 * grown as necessary. When the user is done, she can just leave the
1443 * string there and refer to it using stackblock(). Or she can allocate
1444 * the space for it using grabstackstr(). If it is necessary to allow
1445 * someone else to use the stack temporarily and then continue to grow
1446 * the string, the user should use grabstack to allocate the space, and
1447 * then call ungrabstr(p) to return to the previous mode of operation.
1448 *
1449 * USTPUTC is like STPUTC except that it doesn't check for overflow.
1450 * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
1451 * is space for at least one character.
1452 */
1453static void *
1454growstackstr(void)
1455{
1456 size_t len = stackblocksize();
1457 if (herefd >= 0 && len >= 1024) {
1458 full_write(herefd, stackblock(), len);
1459 return stackblock();
1460 }
1461 growstackblock();
Denis Vlasenko29eb3592008-05-18 14:06:08 +00001462 return (char *)stackblock() + len;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001463}
1464
1465/*
1466 * Called from CHECKSTRSPACE.
1467 */
1468static char *
1469makestrspace(size_t newlen, char *p)
1470{
Denis Vlasenko01631112007-12-16 17:20:38 +00001471 size_t len = p - g_stacknxt;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001472 size_t size = stackblocksize();
1473
1474 for (;;) {
1475 size_t nleft;
1476
1477 size = stackblocksize();
1478 nleft = size - len;
1479 if (nleft >= newlen)
1480 break;
1481 growstackblock();
1482 }
Denis Vlasenko29eb3592008-05-18 14:06:08 +00001483 return (char *)stackblock() + len;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001484}
1485
1486static char *
1487stack_nputstr(const char *s, size_t n, char *p)
1488{
1489 p = makestrspace(n, p);
Denis Vlasenko29eb3592008-05-18 14:06:08 +00001490 p = (char *)memcpy(p, s, n) + n;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001491 return p;
1492}
1493
1494static char *
1495stack_putstr(const char *s, char *p)
1496{
1497 return stack_nputstr(s, strlen(s), p);
1498}
1499
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001500static char *
1501_STPUTC(int c, char *p)
1502{
1503 if (p == sstrend)
1504 p = growstackstr();
1505 *p++ = c;
1506 return p;
1507}
1508
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00001509#define STARTSTACKSTR(p) ((p) = stackblock())
1510#define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
Denis Vlasenko843cbd52008-06-27 00:23:18 +00001511#define CHECKSTRSPACE(n, p) do { \
1512 char *q = (p); \
1513 size_t l = (n); \
1514 size_t m = sstrend - q; \
1515 if (l > m) \
1516 (p) = makestrspace(l, q); \
1517} while (0)
Denis Vlasenkoef527f52008-06-23 01:52:30 +00001518#define USTPUTC(c, p) (*(p)++ = (c))
Denis Vlasenko843cbd52008-06-27 00:23:18 +00001519#define STACKSTRNUL(p) do { \
1520 if ((p) == sstrend) \
1521 (p) = growstackstr(); \
1522 *(p) = '\0'; \
1523} while (0)
Denis Vlasenkoef527f52008-06-23 01:52:30 +00001524#define STUNPUTC(p) (--(p))
1525#define STTOPC(p) ((p)[-1])
1526#define STADJUST(amount, p) ((p) += (amount))
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001527
1528#define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
Denis Vlasenkoef527f52008-06-23 01:52:30 +00001529#define ungrabstackstr(s, p) stunalloc(s)
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001530#define stackstrend() ((void *)sstrend)
1531
1532
1533/* ============ String helpers */
1534
1535/*
1536 * prefix -- see if pfx is a prefix of string.
1537 */
1538static char *
1539prefix(const char *string, const char *pfx)
1540{
1541 while (*pfx) {
1542 if (*pfx++ != *string++)
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00001543 return NULL;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001544 }
1545 return (char *) string;
1546}
1547
1548/*
1549 * Check for a valid number. This should be elsewhere.
1550 */
1551static int
1552is_number(const char *p)
1553{
1554 do {
1555 if (!isdigit(*p))
1556 return 0;
1557 } while (*++p != '\0');
1558 return 1;
1559}
1560
1561/*
1562 * Convert a string of digits to an integer, printing an error message on
1563 * failure.
1564 */
1565static int
1566number(const char *s)
1567{
1568 if (!is_number(s))
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02001569 ash_msg_and_raise_error(msg_illnum, s);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001570 return atoi(s);
1571}
1572
1573/*
1574 * Produce a possibly single quoted string suitable as input to the shell.
1575 * The return string is allocated on the stack.
1576 */
1577static char *
1578single_quote(const char *s)
1579{
1580 char *p;
1581
1582 STARTSTACKSTR(p);
1583
1584 do {
1585 char *q;
1586 size_t len;
1587
1588 len = strchrnul(s, '\'') - s;
1589
1590 q = p = makestrspace(len + 3, p);
1591
1592 *q++ = '\'';
Denis Vlasenko29eb3592008-05-18 14:06:08 +00001593 q = (char *)memcpy(q, s, len) + len;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001594 *q++ = '\'';
1595 s += len;
1596
1597 STADJUST(q - p, p);
1598
Denys Vlasenkocd716832009-11-28 22:14:02 +01001599 if (*s != '\'')
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001600 break;
Denys Vlasenkocd716832009-11-28 22:14:02 +01001601 len = 0;
1602 do len++; while (*++s == '\'');
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001603
1604 q = p = makestrspace(len + 3, p);
1605
1606 *q++ = '"';
Denys Vlasenkocd716832009-11-28 22:14:02 +01001607 q = (char *)memcpy(q, s - len, len) + len;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001608 *q++ = '"';
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001609
1610 STADJUST(q - p, p);
1611 } while (*s);
1612
Denys Vlasenkocd716832009-11-28 22:14:02 +01001613 USTPUTC('\0', p);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001614
1615 return stackblock();
1616}
1617
1618
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00001619/* ============ nextopt */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001620
1621static char **argptr; /* argument list for builtin commands */
1622static char *optionarg; /* set by nextopt (like getopt) */
1623static char *optptr; /* used by nextopt */
1624
1625/*
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001626 * XXX - should get rid of. Have all builtins use getopt(3).
1627 * The library getopt must have the BSD extension static variable
1628 * "optreset", otherwise it can't be used within the shell safely.
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001629 *
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001630 * Standard option processing (a la getopt) for builtin routines.
1631 * The only argument that is passed to nextopt is the option string;
1632 * the other arguments are unnecessary. It returns the character,
1633 * or '\0' on end of input.
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001634 */
1635static int
1636nextopt(const char *optstring)
1637{
1638 char *p;
1639 const char *q;
1640 char c;
1641
1642 p = optptr;
1643 if (p == NULL || *p == '\0') {
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001644 /* We ate entire "-param", take next one */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001645 p = *argptr;
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001646 if (p == NULL)
1647 return '\0';
1648 if (*p != '-')
1649 return '\0';
1650 if (*++p == '\0') /* just "-" ? */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001651 return '\0';
1652 argptr++;
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001653 if (LONE_DASH(p)) /* "--" ? */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001654 return '\0';
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001655 /* p => next "-param" */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001656 }
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001657 /* p => some option char in the middle of a "-param" */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001658 c = *p++;
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +00001659 for (q = optstring; *q != c;) {
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001660 if (*q == '\0')
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00001661 ash_msg_and_raise_error("illegal option -%c", c);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001662 if (*++q == ':')
1663 q++;
1664 }
1665 if (*++q == ':') {
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001666 if (*p == '\0') {
1667 p = *argptr++;
1668 if (p == NULL)
1669 ash_msg_and_raise_error("no arg for -%c option", c);
1670 }
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001671 optionarg = p;
1672 p = NULL;
1673 }
1674 optptr = p;
1675 return c;
1676}
1677
1678
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00001679/* ============ Shell variables */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001680
Denis Vlasenko01631112007-12-16 17:20:38 +00001681/*
1682 * The parsefile structure pointed to by the global variable parsefile
1683 * contains information about the current file being read.
1684 */
Denis Vlasenko01631112007-12-16 17:20:38 +00001685struct shparam {
1686 int nparam; /* # of positional parameters (without $0) */
1687#if ENABLE_ASH_GETOPTS
1688 int optind; /* next parameter to be processed by getopts */
1689 int optoff; /* used by getopts */
1690#endif
1691 unsigned char malloced; /* if parameter list dynamically allocated */
1692 char **p; /* parameter list */
1693};
1694
1695/*
1696 * Free the list of positional parameters.
1697 */
1698static void
1699freeparam(volatile struct shparam *param)
1700{
Denis Vlasenko01631112007-12-16 17:20:38 +00001701 if (param->malloced) {
Denis Vlasenko3177ba02008-07-13 20:39:23 +00001702 char **ap, **ap1;
1703 ap = ap1 = param->p;
1704 while (*ap)
1705 free(*ap++);
1706 free(ap1);
Denis Vlasenko01631112007-12-16 17:20:38 +00001707 }
1708}
1709
1710#if ENABLE_ASH_GETOPTS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001711static void FAST_FUNC getoptsreset(const char *value);
Denis Vlasenko01631112007-12-16 17:20:38 +00001712#endif
1713
1714struct var {
1715 struct var *next; /* next entry in hash list */
1716 int flags; /* flags are defined above */
1717 const char *text; /* name=value */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001718 void (*func)(const char *) FAST_FUNC; /* function to be called when */
Denis Vlasenko01631112007-12-16 17:20:38 +00001719 /* the variable gets set/unset */
1720};
1721
1722struct localvar {
1723 struct localvar *next; /* next local variable in list */
1724 struct var *vp; /* the variable that was made local */
1725 int flags; /* saved flags */
1726 const char *text; /* saved text */
1727};
1728
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001729/* flags */
1730#define VEXPORT 0x01 /* variable is exported */
1731#define VREADONLY 0x02 /* variable cannot be modified */
1732#define VSTRFIXED 0x04 /* variable struct is statically allocated */
1733#define VTEXTFIXED 0x08 /* text is statically allocated */
1734#define VSTACK 0x10 /* text is allocated on the stack */
1735#define VUNSET 0x20 /* the variable is not set */
1736#define VNOFUNC 0x40 /* don't call the callback function */
1737#define VNOSET 0x80 /* do not set variable - just readonly test */
1738#define VNOSAVE 0x100 /* when text is on the heap before setvareq */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00001739#if ENABLE_ASH_RANDOM_SUPPORT
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00001740# define VDYNAMIC 0x200 /* dynamic variable */
1741#else
1742# define VDYNAMIC 0
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001743#endif
1744
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00001745
Denis Vlasenko01631112007-12-16 17:20:38 +00001746/* Need to be before varinit_data[] */
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00001747#if ENABLE_LOCALE_SUPPORT
Denys Vlasenko2634bf32009-06-09 18:40:07 +02001748static void FAST_FUNC
Denis Vlasenkoa8915072007-02-23 21:10:06 +00001749change_lc_all(const char *value)
1750{
1751 if (value && *value != '\0')
1752 setlocale(LC_ALL, value);
1753}
Denys Vlasenko2634bf32009-06-09 18:40:07 +02001754static void FAST_FUNC
Denis Vlasenkoa8915072007-02-23 21:10:06 +00001755change_lc_ctype(const char *value)
1756{
1757 if (value && *value != '\0')
1758 setlocale(LC_CTYPE, value);
1759}
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00001760#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001761#if ENABLE_ASH_MAIL
1762static void chkmail(void);
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001763static void changemail(const char *) FAST_FUNC;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001764#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001765static void changepath(const char *) FAST_FUNC;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001766#if ENABLE_ASH_RANDOM_SUPPORT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001767static void change_random(const char *) FAST_FUNC;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001768#endif
1769
Denis Vlasenko01631112007-12-16 17:20:38 +00001770static const struct {
1771 int flags;
1772 const char *text;
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001773 void (*func)(const char *) FAST_FUNC;
Denis Vlasenko01631112007-12-16 17:20:38 +00001774} varinit_data[] = {
Denis Vlasenko01631112007-12-16 17:20:38 +00001775 { VSTRFIXED|VTEXTFIXED , defifsvar , NULL },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001776#if ENABLE_ASH_MAIL
Denis Vlasenko01631112007-12-16 17:20:38 +00001777 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL\0" , changemail },
1778 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH\0", changemail },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001779#endif
Denis Vlasenko01631112007-12-16 17:20:38 +00001780 { VSTRFIXED|VTEXTFIXED , bb_PATH_root_path, changepath },
1781 { VSTRFIXED|VTEXTFIXED , "PS1=$ " , NULL },
1782 { VSTRFIXED|VTEXTFIXED , "PS2=> " , NULL },
1783 { VSTRFIXED|VTEXTFIXED , "PS4=+ " , NULL },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001784#if ENABLE_ASH_GETOPTS
Denis Vlasenko01631112007-12-16 17:20:38 +00001785 { VSTRFIXED|VTEXTFIXED , "OPTIND=1" , getoptsreset },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001786#endif
1787#if ENABLE_ASH_RANDOM_SUPPORT
Denis Vlasenko01631112007-12-16 17:20:38 +00001788 { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM\0", change_random },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001789#endif
1790#if ENABLE_LOCALE_SUPPORT
Denis Vlasenko01631112007-12-16 17:20:38 +00001791 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL\0" , change_lc_all },
1792 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE\0", change_lc_ctype },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001793#endif
1794#if ENABLE_FEATURE_EDITING_SAVEHISTORY
Denis Vlasenko01631112007-12-16 17:20:38 +00001795 { VSTRFIXED|VTEXTFIXED|VUNSET, "HISTFILE\0", NULL },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001796#endif
1797};
1798
Denis Vlasenko0b769642008-07-24 07:54:57 +00001799struct redirtab;
Denis Vlasenko01631112007-12-16 17:20:38 +00001800
1801struct globals_var {
1802 struct shparam shellparam; /* $@ current positional parameters */
1803 struct redirtab *redirlist;
1804 int g_nullredirs;
1805 int preverrout_fd; /* save fd2 before print debug if xflag is set. */
1806 struct var *vartab[VTABSIZE];
1807 struct var varinit[ARRAY_SIZE(varinit_data)];
1808};
Denis Vlasenko574f2f42008-02-27 18:41:59 +00001809extern struct globals_var *const ash_ptr_to_globals_var;
1810#define G_var (*ash_ptr_to_globals_var)
Denis Vlasenko01631112007-12-16 17:20:38 +00001811#define shellparam (G_var.shellparam )
Denis Vlasenko0b769642008-07-24 07:54:57 +00001812//#define redirlist (G_var.redirlist )
Denis Vlasenko01631112007-12-16 17:20:38 +00001813#define g_nullredirs (G_var.g_nullredirs )
1814#define preverrout_fd (G_var.preverrout_fd)
1815#define vartab (G_var.vartab )
1816#define varinit (G_var.varinit )
1817#define INIT_G_var() do { \
Denis Vlasenko6b06cb82008-05-15 21:30:45 +00001818 unsigned i; \
Denis Vlasenko574f2f42008-02-27 18:41:59 +00001819 (*(struct globals_var**)&ash_ptr_to_globals_var) = xzalloc(sizeof(G_var)); \
1820 barrier(); \
Denis Vlasenko01631112007-12-16 17:20:38 +00001821 for (i = 0; i < ARRAY_SIZE(varinit_data); i++) { \
1822 varinit[i].flags = varinit_data[i].flags; \
1823 varinit[i].text = varinit_data[i].text; \
1824 varinit[i].func = varinit_data[i].func; \
1825 } \
1826} while (0)
1827
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001828#define vifs varinit[0]
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001829#if ENABLE_ASH_MAIL
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001830# define vmail (&vifs)[1]
1831# define vmpath (&vmail)[1]
1832# define vpath (&vmpath)[1]
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001833#else
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001834# define vpath (&vifs)[1]
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001835#endif
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001836#define vps1 (&vpath)[1]
1837#define vps2 (&vps1)[1]
1838#define vps4 (&vps2)[1]
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001839#if ENABLE_ASH_GETOPTS
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001840# define voptind (&vps4)[1]
1841# if ENABLE_ASH_RANDOM_SUPPORT
1842# define vrandom (&voptind)[1]
1843# endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001844#else
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001845# if ENABLE_ASH_RANDOM_SUPPORT
1846# define vrandom (&vps4)[1]
1847# endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001848#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001849
1850/*
1851 * The following macros access the values of the above variables.
1852 * They have to skip over the name. They return the null string
1853 * for unset variables.
1854 */
1855#define ifsval() (vifs.text + 4)
1856#define ifsset() ((vifs.flags & VUNSET) == 0)
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001857#if ENABLE_ASH_MAIL
1858# define mailval() (vmail.text + 5)
1859# define mpathval() (vmpath.text + 9)
1860# define mpathset() ((vmpath.flags & VUNSET) == 0)
1861#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001862#define pathval() (vpath.text + 5)
1863#define ps1val() (vps1.text + 4)
1864#define ps2val() (vps2.text + 4)
1865#define ps4val() (vps4.text + 4)
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001866#if ENABLE_ASH_GETOPTS
1867# define optindval() (voptind.text + 7)
1868#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001869
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001870
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001871#define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
1872#define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
1873
Denis Vlasenko01631112007-12-16 17:20:38 +00001874#if ENABLE_ASH_GETOPTS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001875static void FAST_FUNC
Denis Vlasenko01631112007-12-16 17:20:38 +00001876getoptsreset(const char *value)
1877{
1878 shellparam.optind = number(value);
1879 shellparam.optoff = -1;
1880}
1881#endif
1882
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001883/*
1884 * Return of a legal variable name (a letter or underscore followed by zero or
1885 * more letters, underscores, and digits).
1886 */
Denys Vlasenko03dad222010-01-12 23:29:57 +01001887static char* FAST_FUNC
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001888endofname(const char *name)
1889{
1890 char *p;
1891
1892 p = (char *) name;
1893 if (!is_name(*p))
1894 return p;
1895 while (*++p) {
1896 if (!is_in_name(*p))
1897 break;
1898 }
1899 return p;
1900}
1901
1902/*
1903 * Compares two strings up to the first = or '\0'. The first
1904 * string must be terminated by '='; the second may be terminated by
1905 * either '=' or '\0'.
1906 */
1907static int
1908varcmp(const char *p, const char *q)
1909{
1910 int c, d;
1911
1912 while ((c = *p) == (d = *q)) {
1913 if (!c || c == '=')
1914 goto out;
1915 p++;
1916 q++;
1917 }
1918 if (c == '=')
Denis Vlasenko9650f362007-02-23 01:04:37 +00001919 c = '\0';
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001920 if (d == '=')
Denis Vlasenko9650f362007-02-23 01:04:37 +00001921 d = '\0';
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001922 out:
1923 return c - d;
1924}
1925
1926static int
1927varequal(const char *a, const char *b)
1928{
1929 return !varcmp(a, b);
1930}
1931
1932/*
1933 * Find the appropriate entry in the hash table from the name.
1934 */
1935static struct var **
1936hashvar(const char *p)
1937{
1938 unsigned hashval;
1939
1940 hashval = ((unsigned char) *p) << 4;
1941 while (*p && *p != '=')
1942 hashval += (unsigned char) *p++;
1943 return &vartab[hashval % VTABSIZE];
1944}
1945
1946static int
1947vpcmp(const void *a, const void *b)
1948{
1949 return varcmp(*(const char **)a, *(const char **)b);
1950}
1951
1952/*
1953 * This routine initializes the builtin variables.
1954 */
1955static void
1956initvar(void)
1957{
1958 struct var *vp;
1959 struct var *end;
1960 struct var **vpp;
1961
1962 /*
1963 * PS1 depends on uid
1964 */
1965#if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
1966 vps1.text = "PS1=\\w \\$ ";
1967#else
1968 if (!geteuid())
1969 vps1.text = "PS1=# ";
1970#endif
1971 vp = varinit;
Denis Vlasenko80b8b392007-06-25 10:55:35 +00001972 end = vp + ARRAY_SIZE(varinit);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001973 do {
1974 vpp = hashvar(vp->text);
1975 vp->next = *vpp;
1976 *vpp = vp;
1977 } while (++vp < end);
1978}
1979
1980static struct var **
1981findvar(struct var **vpp, const char *name)
1982{
1983 for (; *vpp; vpp = &(*vpp)->next) {
1984 if (varequal((*vpp)->text, name)) {
1985 break;
1986 }
1987 }
1988 return vpp;
1989}
1990
1991/*
1992 * Find the value of a variable. Returns NULL if not set.
1993 */
Denys Vlasenko03dad222010-01-12 23:29:57 +01001994static const char* FAST_FUNC
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001995lookupvar(const char *name)
1996{
1997 struct var *v;
1998
1999 v = *findvar(hashvar(name), name);
2000 if (v) {
Denis Vlasenko448d30e2008-06-27 00:24:11 +00002001#if ENABLE_ASH_RANDOM_SUPPORT
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002002 /*
2003 * Dynamic variables are implemented roughly the same way they are
2004 * in bash. Namely, they're "special" so long as they aren't unset.
2005 * As soon as they're unset, they're no longer dynamic, and dynamic
2006 * lookup will no longer happen at that point. -- PFM.
2007 */
2008 if ((v->flags & VDYNAMIC))
2009 (*v->func)(NULL);
2010#endif
2011 if (!(v->flags & VUNSET))
2012 return strchrnul(v->text, '=') + 1;
2013 }
2014 return NULL;
2015}
2016
2017/*
2018 * Search the environment of a builtin command.
2019 */
Mike Frysinger98c52642009-04-02 10:02:37 +00002020static const char *
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002021bltinlookup(const char *name)
2022{
2023 struct strlist *sp;
2024
2025 for (sp = cmdenviron; sp; sp = sp->next) {
2026 if (varequal(sp->text, name))
2027 return strchrnul(sp->text, '=') + 1;
2028 }
2029 return lookupvar(name);
2030}
2031
2032/*
2033 * Same as setvar except that the variable and value are passed in
2034 * the first argument as name=value. Since the first argument will
2035 * be actually stored in the table, it should not be a string that
2036 * will go away.
2037 * Called with interrupts off.
2038 */
2039static void
2040setvareq(char *s, int flags)
2041{
2042 struct var *vp, **vpp;
2043
2044 vpp = hashvar(s);
2045 flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
2046 vp = *findvar(vpp, s);
2047 if (vp) {
2048 if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
2049 const char *n;
2050
2051 if (flags & VNOSAVE)
2052 free(s);
2053 n = vp->text;
2054 ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
2055 }
2056
2057 if (flags & VNOSET)
2058 return;
2059
2060 if (vp->func && (flags & VNOFUNC) == 0)
2061 (*vp->func)(strchrnul(s, '=') + 1);
2062
2063 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
2064 free((char*)vp->text);
2065
2066 flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
2067 } else {
2068 if (flags & VNOSET)
2069 return;
2070 /* not found */
Denis Vlasenko597906c2008-02-20 16:38:54 +00002071 vp = ckzalloc(sizeof(*vp));
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002072 vp->next = *vpp;
Denis Vlasenko597906c2008-02-20 16:38:54 +00002073 /*vp->func = NULL; - ckzalloc did it */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002074 *vpp = vp;
2075 }
2076 if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
2077 s = ckstrdup(s);
2078 vp->text = s;
2079 vp->flags = flags;
2080}
2081
2082/*
2083 * Set the value of a variable. The flags argument is ored with the
2084 * flags of the variable. If val is NULL, the variable is unset.
2085 */
2086static void
2087setvar(const char *name, const char *val, int flags)
2088{
2089 char *p, *q;
2090 size_t namelen;
2091 char *nameeq;
2092 size_t vallen;
2093
2094 q = endofname(name);
2095 p = strchrnul(q, '=');
2096 namelen = p - name;
2097 if (!namelen || p != q)
2098 ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
2099 vallen = 0;
2100 if (val == NULL) {
2101 flags |= VUNSET;
2102 } else {
2103 vallen = strlen(val);
2104 }
2105 INT_OFF;
2106 nameeq = ckmalloc(namelen + vallen + 2);
Denis Vlasenko29eb3592008-05-18 14:06:08 +00002107 p = (char *)memcpy(nameeq, name, namelen) + namelen;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002108 if (val) {
2109 *p++ = '=';
Denis Vlasenko29eb3592008-05-18 14:06:08 +00002110 p = (char *)memcpy(p, val, vallen) + vallen;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002111 }
2112 *p = '\0';
2113 setvareq(nameeq, flags | VNOSAVE);
2114 INT_ON;
2115}
2116
Denys Vlasenko03dad222010-01-12 23:29:57 +01002117static void FAST_FUNC
2118setvar2(const char *name, const char *val)
2119{
2120 setvar(name, val, 0);
2121}
2122
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002123#if ENABLE_ASH_GETOPTS
2124/*
2125 * Safe version of setvar, returns 1 on success 0 on failure.
2126 */
2127static int
2128setvarsafe(const char *name, const char *val, int flags)
2129{
2130 int err;
2131 volatile int saveint;
2132 struct jmploc *volatile savehandler = exception_handler;
2133 struct jmploc jmploc;
2134
2135 SAVE_INT(saveint);
2136 if (setjmp(jmploc.loc))
2137 err = 1;
2138 else {
2139 exception_handler = &jmploc;
2140 setvar(name, val, flags);
2141 err = 0;
2142 }
2143 exception_handler = savehandler;
2144 RESTORE_INT(saveint);
2145 return err;
2146}
2147#endif
2148
2149/*
2150 * Unset the specified variable.
2151 */
2152static int
2153unsetvar(const char *s)
2154{
2155 struct var **vpp;
2156 struct var *vp;
2157 int retval;
2158
2159 vpp = findvar(hashvar(s), s);
2160 vp = *vpp;
2161 retval = 2;
2162 if (vp) {
2163 int flags = vp->flags;
2164
2165 retval = 1;
2166 if (flags & VREADONLY)
2167 goto out;
Denis Vlasenko448d30e2008-06-27 00:24:11 +00002168#if ENABLE_ASH_RANDOM_SUPPORT
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002169 vp->flags &= ~VDYNAMIC;
2170#endif
2171 if (flags & VUNSET)
2172 goto ok;
2173 if ((flags & VSTRFIXED) == 0) {
2174 INT_OFF;
2175 if ((flags & (VTEXTFIXED|VSTACK)) == 0)
2176 free((char*)vp->text);
2177 *vpp = vp->next;
2178 free(vp);
2179 INT_ON;
2180 } else {
2181 setvar(s, 0, 0);
2182 vp->flags &= ~VEXPORT;
2183 }
2184 ok:
2185 retval = 0;
2186 }
2187 out:
2188 return retval;
2189}
2190
2191/*
2192 * Process a linked list of variable assignments.
2193 */
2194static void
2195listsetvar(struct strlist *list_set_var, int flags)
2196{
2197 struct strlist *lp = list_set_var;
2198
2199 if (!lp)
2200 return;
2201 INT_OFF;
2202 do {
2203 setvareq(lp->text, flags);
Denis Vlasenko9650f362007-02-23 01:04:37 +00002204 lp = lp->next;
2205 } while (lp);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002206 INT_ON;
2207}
2208
2209/*
2210 * Generate a list of variables satisfying the given conditions.
2211 */
2212static char **
2213listvars(int on, int off, char ***end)
2214{
2215 struct var **vpp;
2216 struct var *vp;
2217 char **ep;
2218 int mask;
2219
2220 STARTSTACKSTR(ep);
2221 vpp = vartab;
2222 mask = on | off;
2223 do {
2224 for (vp = *vpp; vp; vp = vp->next) {
2225 if ((vp->flags & mask) == on) {
2226 if (ep == stackstrend())
2227 ep = growstackstr();
2228 *ep++ = (char *) vp->text;
2229 }
2230 }
2231 } while (++vpp < vartab + VTABSIZE);
2232 if (ep == stackstrend())
2233 ep = growstackstr();
2234 if (end)
2235 *end = ep;
2236 *ep++ = NULL;
2237 return grabstackstr(ep);
2238}
2239
2240
2241/* ============ Path search helper
2242 *
2243 * The variable path (passed by reference) should be set to the start
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02002244 * of the path before the first call; path_advance will update
2245 * this value as it proceeds. Successive calls to path_advance will return
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002246 * the possible path expansions in sequence. If an option (indicated by
2247 * a percent sign) appears in the path entry then the global variable
2248 * pathopt will be set to point to it; otherwise pathopt will be set to
2249 * NULL.
2250 */
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02002251static const char *pathopt; /* set by path_advance */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002252
2253static char *
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02002254path_advance(const char **path, const char *name)
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002255{
2256 const char *p;
2257 char *q;
2258 const char *start;
2259 size_t len;
2260
2261 if (*path == NULL)
2262 return NULL;
2263 start = *path;
Denis Vlasenkof7d56652008-03-25 05:51:41 +00002264 for (p = start; *p && *p != ':' && *p != '%'; p++)
2265 continue;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002266 len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
2267 while (stackblocksize() < len)
2268 growstackblock();
2269 q = stackblock();
2270 if (p != start) {
2271 memcpy(q, start, p - start);
2272 q += p - start;
2273 *q++ = '/';
2274 }
2275 strcpy(q, name);
2276 pathopt = NULL;
2277 if (*p == '%') {
2278 pathopt = ++p;
Denis Vlasenkof7d56652008-03-25 05:51:41 +00002279 while (*p && *p != ':')
2280 p++;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002281 }
2282 if (*p == ':')
2283 *path = p + 1;
2284 else
2285 *path = NULL;
2286 return stalloc(len);
2287}
2288
2289
2290/* ============ Prompt */
2291
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +00002292static smallint doprompt; /* if set, prompt the user */
2293static smallint needprompt; /* true if interactive and at start of line */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002294
2295#if ENABLE_FEATURE_EDITING
2296static line_input_t *line_input_state;
2297static const char *cmdedit_prompt;
2298static void
2299putprompt(const char *s)
2300{
2301 if (ENABLE_ASH_EXPAND_PRMT) {
2302 free((char*)cmdedit_prompt);
Denis Vlasenko4222ae42007-02-25 02:37:49 +00002303 cmdedit_prompt = ckstrdup(s);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002304 return;
2305 }
2306 cmdedit_prompt = s;
2307}
2308#else
2309static void
2310putprompt(const char *s)
2311{
2312 out2str(s);
2313}
2314#endif
2315
2316#if ENABLE_ASH_EXPAND_PRMT
2317/* expandstr() needs parsing machinery, so it is far away ahead... */
2318static const char *expandstr(const char *ps);
2319#else
2320#define expandstr(s) s
2321#endif
2322
2323static void
2324setprompt(int whichprompt)
2325{
2326 const char *prompt;
2327#if ENABLE_ASH_EXPAND_PRMT
2328 struct stackmark smark;
2329#endif
2330
2331 needprompt = 0;
2332
2333 switch (whichprompt) {
2334 case 1:
2335 prompt = ps1val();
2336 break;
2337 case 2:
2338 prompt = ps2val();
2339 break;
2340 default: /* 0 */
2341 prompt = nullstr;
2342 }
2343#if ENABLE_ASH_EXPAND_PRMT
2344 setstackmark(&smark);
2345 stalloc(stackblocksize());
2346#endif
2347 putprompt(expandstr(prompt));
2348#if ENABLE_ASH_EXPAND_PRMT
2349 popstackmark(&smark);
2350#endif
2351}
2352
2353
2354/* ============ The cd and pwd commands */
2355
2356#define CD_PHYSICAL 1
2357#define CD_PRINT 2
2358
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002359static int
2360cdopt(void)
2361{
2362 int flags = 0;
2363 int i, j;
2364
2365 j = 'L';
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02002366 while ((i = nextopt("LP")) != '\0') {
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002367 if (i != j) {
2368 flags ^= CD_PHYSICAL;
2369 j = i;
2370 }
2371 }
2372
2373 return flags;
2374}
2375
2376/*
2377 * Update curdir (the name of the current directory) in response to a
2378 * cd command.
2379 */
2380static const char *
2381updatepwd(const char *dir)
2382{
2383 char *new;
2384 char *p;
2385 char *cdcomppath;
2386 const char *lim;
2387
2388 cdcomppath = ststrdup(dir);
2389 STARTSTACKSTR(new);
2390 if (*dir != '/') {
2391 if (curdir == nullstr)
2392 return 0;
2393 new = stack_putstr(curdir, new);
2394 }
2395 new = makestrspace(strlen(dir) + 2, new);
Denis Vlasenko29eb3592008-05-18 14:06:08 +00002396 lim = (char *)stackblock() + 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002397 if (*dir != '/') {
2398 if (new[-1] != '/')
2399 USTPUTC('/', new);
2400 if (new > lim && *lim == '/')
2401 lim++;
2402 } else {
2403 USTPUTC('/', new);
2404 cdcomppath++;
2405 if (dir[1] == '/' && dir[2] != '/') {
2406 USTPUTC('/', new);
2407 cdcomppath++;
2408 lim++;
2409 }
2410 }
2411 p = strtok(cdcomppath, "/");
2412 while (p) {
2413 switch (*p) {
2414 case '.':
2415 if (p[1] == '.' && p[2] == '\0') {
2416 while (new > lim) {
2417 STUNPUTC(new);
2418 if (new[-1] == '/')
2419 break;
2420 }
2421 break;
Denis Vlasenko16abcd92007-04-13 23:59:52 +00002422 }
2423 if (p[1] == '\0')
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002424 break;
2425 /* fall through */
2426 default:
2427 new = stack_putstr(p, new);
2428 USTPUTC('/', new);
2429 }
2430 p = strtok(0, "/");
2431 }
2432 if (new > lim)
2433 STUNPUTC(new);
2434 *new = 0;
2435 return stackblock();
2436}
2437
2438/*
2439 * Find out what the current directory is. If we already know the current
2440 * directory, this routine returns immediately.
2441 */
2442static char *
2443getpwd(void)
2444{
Denis Vlasenko01631112007-12-16 17:20:38 +00002445 char *dir = getcwd(NULL, 0); /* huh, using glibc extension? */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002446 return dir ? dir : nullstr;
2447}
2448
2449static void
2450setpwd(const char *val, int setold)
2451{
2452 char *oldcur, *dir;
2453
2454 oldcur = dir = curdir;
2455
2456 if (setold) {
2457 setvar("OLDPWD", oldcur, VEXPORT);
2458 }
2459 INT_OFF;
2460 if (physdir != nullstr) {
2461 if (physdir != oldcur)
2462 free(physdir);
2463 physdir = nullstr;
2464 }
2465 if (oldcur == val || !val) {
2466 char *s = getpwd();
2467 physdir = s;
2468 if (!val)
2469 dir = s;
2470 } else
2471 dir = ckstrdup(val);
2472 if (oldcur != dir && oldcur != nullstr) {
2473 free(oldcur);
2474 }
2475 curdir = dir;
2476 INT_ON;
2477 setvar("PWD", dir, VEXPORT);
2478}
2479
2480static void hashcd(void);
2481
2482/*
2483 * Actually do the chdir. We also call hashcd to let the routines in exec.c
2484 * know that the current directory has changed.
2485 */
2486static int
2487docd(const char *dest, int flags)
2488{
Denys Vlasenko4b1100e2010-03-05 14:10:54 +01002489 const char *dir = NULL;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002490 int err;
2491
2492 TRACE(("docd(\"%s\", %d) called\n", dest, flags));
2493
2494 INT_OFF;
2495 if (!(flags & CD_PHYSICAL)) {
2496 dir = updatepwd(dest);
2497 if (dir)
2498 dest = dir;
2499 }
2500 err = chdir(dest);
2501 if (err)
2502 goto out;
2503 setpwd(dir, 1);
2504 hashcd();
2505 out:
2506 INT_ON;
2507 return err;
2508}
2509
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02002510static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00002511cdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002512{
2513 const char *dest;
2514 const char *path;
2515 const char *p;
2516 char c;
2517 struct stat statb;
2518 int flags;
2519
2520 flags = cdopt();
2521 dest = *argptr;
2522 if (!dest)
2523 dest = bltinlookup(homestr);
2524 else if (LONE_DASH(dest)) {
2525 dest = bltinlookup("OLDPWD");
2526 flags |= CD_PRINT;
2527 }
2528 if (!dest)
2529 dest = nullstr;
2530 if (*dest == '/')
2531 goto step7;
2532 if (*dest == '.') {
2533 c = dest[1];
2534 dotdot:
2535 switch (c) {
2536 case '\0':
2537 case '/':
2538 goto step6;
2539 case '.':
2540 c = dest[2];
2541 if (c != '.')
2542 goto dotdot;
2543 }
2544 }
2545 if (!*dest)
2546 dest = ".";
2547 path = bltinlookup("CDPATH");
2548 if (!path) {
2549 step6:
2550 step7:
2551 p = dest;
2552 goto docd;
2553 }
2554 do {
2555 c = *path;
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02002556 p = path_advance(&path, dest);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002557 if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
2558 if (c && c != ':')
2559 flags |= CD_PRINT;
2560 docd:
2561 if (!docd(p, flags))
2562 goto out;
2563 break;
2564 }
2565 } while (path);
2566 ash_msg_and_raise_error("can't cd to %s", dest);
2567 /* NOTREACHED */
2568 out:
2569 if (flags & CD_PRINT)
2570 out1fmt(snlfmt, curdir);
2571 return 0;
2572}
2573
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02002574static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00002575pwdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002576{
2577 int flags;
2578 const char *dir = curdir;
2579
2580 flags = cdopt();
2581 if (flags) {
2582 if (physdir == nullstr)
2583 setpwd(dir, 0);
2584 dir = physdir;
2585 }
2586 out1fmt(snlfmt, dir);
2587 return 0;
2588}
2589
Denis Vlasenko0c032a42007-02-23 01:03:40 +00002590
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00002591/* ============ ... */
Eric Andersenc470f442003-07-28 09:56:35 +00002592
Denis Vlasenko834dee72008-10-07 09:18:30 +00002593
Denys Vlasenko82dd14a2010-05-17 10:10:01 +02002594#define IBUFSIZ (ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 1024)
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/*
Denys Vlasenko238bf182010-05-18 15:49:07 +02003273 * Only one usage site - in setsignal()
Denis Vlasenko4b875702009-03-19 13:30:04 +00003274 */
3275static void
Denys Vlasenko238bf182010-05-18 15:49:07 +02003276signal_handler(int signo)
Denis Vlasenko4b875702009-03-19 13:30:04 +00003277{
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:
Denys Vlasenko238bf182010-05-18 15:49:07 +02003371 act.sa_handler = signal_handler;
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);
Denys Vlasenko238bf182010-05-18 15:49:07 +02008448 if (!backgnd && (flags & EV_EXIT) && !may_have_traps)
Eric Andersenc470f442003-07-28 09:56:35 +00008449 goto nofork;
Denis Vlasenkob012b102007-02-19 22:43:01 +00008450 INT_OFF;
Denis Vlasenko68404f12008-03-17 09:00:54 +00008451 jp = makejob(/*n,*/ 1);
Eric Andersenc470f442003-07-28 09:56:35 +00008452 if (forkshell(jp, n, backgnd) == 0) {
Denys Vlasenko238bf182010-05-18 15:49:07 +02008453 /* child */
Denis Vlasenkob012b102007-02-19 22:43:01 +00008454 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00008455 flags |= EV_EXIT;
8456 if (backgnd)
Denys Vlasenko238bf182010-05-18 15:49:07 +02008457 flags &= ~EV_TESTED;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00008458 nofork:
Eric Andersenc470f442003-07-28 09:56:35 +00008459 redirect(n->nredir.redirect, 0);
8460 evaltreenr(n->nredir.n, flags);
8461 /* never returns */
8462 }
8463 status = 0;
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00008464 if (!backgnd)
Eric Andersenc470f442003-07-28 09:56:35 +00008465 status = waitforjob(jp);
8466 exitstatus = status;
Denis Vlasenkob012b102007-02-19 22:43:01 +00008467 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00008468}
8469
Eric Andersenc470f442003-07-28 09:56:35 +00008470/*
8471 * Compute the names of the files in a redirection list.
8472 */
Denis Vlasenko99eb8502007-02-23 21:09:49 +00008473static void fixredir(union node *, const char *, int);
Eric Andersenc470f442003-07-28 09:56:35 +00008474static void
8475expredir(union node *n)
8476{
8477 union node *redir;
8478
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008479 for (redir = n; redir; redir = redir->nfile.next) {
Eric Andersenc470f442003-07-28 09:56:35 +00008480 struct arglist fn;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008481
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00008482 fn.list = NULL;
Eric Andersenc470f442003-07-28 09:56:35 +00008483 fn.lastp = &fn.list;
8484 switch (redir->type) {
8485 case NFROMTO:
8486 case NFROM:
8487 case NTO:
Denis Vlasenko559691a2008-10-05 18:39:31 +00008488#if ENABLE_ASH_BASH_COMPAT
8489 case NTO2:
8490#endif
Eric Andersenc470f442003-07-28 09:56:35 +00008491 case NCLOBBER:
8492 case NAPPEND:
8493 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
Denis Vlasenko559691a2008-10-05 18:39:31 +00008494#if ENABLE_ASH_BASH_COMPAT
8495 store_expfname:
8496#endif
Eric Andersenc470f442003-07-28 09:56:35 +00008497 redir->nfile.expfname = fn.list->text;
8498 break;
8499 case NFROMFD:
Denis Vlasenko559691a2008-10-05 18:39:31 +00008500 case NTOFD: /* >& */
Eric Andersenc470f442003-07-28 09:56:35 +00008501 if (redir->ndup.vname) {
8502 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008503 if (fn.list == NULL)
Denis Vlasenkob012b102007-02-19 22:43:01 +00008504 ash_msg_and_raise_error("redir error");
Denis Vlasenko559691a2008-10-05 18:39:31 +00008505#if ENABLE_ASH_BASH_COMPAT
8506//FIXME: we used expandarg with different args!
8507 if (!isdigit_str9(fn.list->text)) {
8508 /* >&file, not >&fd */
8509 if (redir->nfile.fd != 1) /* 123>&file - BAD */
8510 ash_msg_and_raise_error("redir error");
8511 redir->type = NTO2;
8512 goto store_expfname;
8513 }
8514#endif
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008515 fixredir(redir, fn.list->text, 1);
Eric Andersenc470f442003-07-28 09:56:35 +00008516 }
8517 break;
8518 }
8519 }
8520}
8521
Eric Andersencb57d552001-06-28 07:25:16 +00008522/*
Eric Andersencb57d552001-06-28 07:25:16 +00008523 * Evaluate a pipeline. All the processes in the pipeline are children
8524 * of the process creating the pipeline. (This differs from some versions
8525 * of the shell, which make the last process in a pipeline the parent
8526 * of all the rest.)
8527 */
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008528static void
Eric Andersenc470f442003-07-28 09:56:35 +00008529evalpipe(union node *n, int flags)
Eric Andersencb57d552001-06-28 07:25:16 +00008530{
8531 struct job *jp;
8532 struct nodelist *lp;
8533 int pipelen;
8534 int prevfd;
8535 int pip[2];
8536
Eric Andersenc470f442003-07-28 09:56:35 +00008537 TRACE(("evalpipe(0x%lx) called\n", (long)n));
Eric Andersencb57d552001-06-28 07:25:16 +00008538 pipelen = 0;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008539 for (lp = n->npipe.cmdlist; lp; lp = lp->next)
Eric Andersencb57d552001-06-28 07:25:16 +00008540 pipelen++;
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008541 flags |= EV_EXIT;
Denis Vlasenkob012b102007-02-19 22:43:01 +00008542 INT_OFF;
Denis Vlasenko68404f12008-03-17 09:00:54 +00008543 jp = makejob(/*n,*/ pipelen);
Eric Andersencb57d552001-06-28 07:25:16 +00008544 prevfd = -1;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008545 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008546 prehash(lp->n);
Eric Andersencb57d552001-06-28 07:25:16 +00008547 pip[1] = -1;
8548 if (lp->next) {
8549 if (pipe(pip) < 0) {
8550 close(prevfd);
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00008551 ash_msg_and_raise_error("pipe call failed");
Eric Andersencb57d552001-06-28 07:25:16 +00008552 }
8553 }
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00008554 if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
Denis Vlasenkob012b102007-02-19 22:43:01 +00008555 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00008556 if (pip[1] >= 0) {
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008557 close(pip[0]);
Eric Andersencb57d552001-06-28 07:25:16 +00008558 }
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008559 if (prevfd > 0) {
8560 dup2(prevfd, 0);
8561 close(prevfd);
8562 }
8563 if (pip[1] > 1) {
8564 dup2(pip[1], 1);
8565 close(pip[1]);
8566 }
Eric Andersenc470f442003-07-28 09:56:35 +00008567 evaltreenr(lp->n, flags);
8568 /* never returns */
Eric Andersencb57d552001-06-28 07:25:16 +00008569 }
8570 if (prevfd >= 0)
8571 close(prevfd);
8572 prevfd = pip[0];
Denis Vlasenkob9e70dd2009-03-20 01:24:08 +00008573 /* Don't want to trigger debugging */
8574 if (pip[1] != -1)
8575 close(pip[1]);
Eric Andersencb57d552001-06-28 07:25:16 +00008576 }
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00008577 if (n->npipe.pipe_backgnd == 0) {
Eric Andersencb57d552001-06-28 07:25:16 +00008578 exitstatus = waitforjob(jp);
8579 TRACE(("evalpipe: job done exit status %d\n", exitstatus));
Eric Andersencb57d552001-06-28 07:25:16 +00008580 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00008581 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00008582}
8583
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008584/*
8585 * Controls whether the shell is interactive or not.
8586 */
8587static void
8588setinteractive(int on)
8589{
Denis Vlasenkob07a4962008-06-22 13:16:23 +00008590 static smallint is_interactive;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008591
8592 if (++on == is_interactive)
8593 return;
8594 is_interactive = on;
8595 setsignal(SIGINT);
8596 setsignal(SIGQUIT);
8597 setsignal(SIGTERM);
8598#if !ENABLE_FEATURE_SH_EXTRA_QUIET
8599 if (is_interactive > 1) {
8600 /* Looks like they want an interactive shell */
Denis Vlasenkoca525b42007-06-13 12:27:17 +00008601 static smallint did_banner;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008602
Denis Vlasenkoca525b42007-06-13 12:27:17 +00008603 if (!did_banner) {
Denys Vlasenkoc34c0332009-09-29 12:25:30 +02008604 /* note: ash and hush share this string */
8605 out1fmt("\n\n%s %s\n"
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008606 "Enter 'help' for a list of built-in commands."
8607 "\n\n",
Denys Vlasenkoc34c0332009-09-29 12:25:30 +02008608 bb_banner,
8609 "built-in shell (ash)"
8610 );
Denis Vlasenkoca525b42007-06-13 12:27:17 +00008611 did_banner = 1;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008612 }
8613 }
8614#endif
8615}
8616
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008617static void
8618optschanged(void)
8619{
8620#if DEBUG
8621 opentrace();
8622#endif
8623 setinteractive(iflag);
8624 setjobctl(mflag);
Denis Vlasenkob07a4962008-06-22 13:16:23 +00008625#if ENABLE_FEATURE_EDITING_VI
8626 if (viflag)
8627 line_input_state->flags |= VI_MODE;
8628 else
8629 line_input_state->flags &= ~VI_MODE;
8630#else
8631 viflag = 0; /* forcibly keep the option off */
8632#endif
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008633}
8634
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008635static struct localvar *localvars;
8636
8637/*
8638 * Called after a function returns.
8639 * Interrupts must be off.
8640 */
8641static void
8642poplocalvars(void)
8643{
8644 struct localvar *lvp;
8645 struct var *vp;
8646
8647 while ((lvp = localvars) != NULL) {
8648 localvars = lvp->next;
8649 vp = lvp->vp;
Denys Vlasenko883cea42009-07-11 15:31:59 +02008650 TRACE(("poplocalvar %s\n", vp ? vp->text : "-"));
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008651 if (vp == NULL) { /* $- saved */
8652 memcpy(optlist, lvp->text, sizeof(optlist));
8653 free((char*)lvp->text);
8654 optschanged();
8655 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
8656 unsetvar(vp->text);
8657 } else {
8658 if (vp->func)
8659 (*vp->func)(strchrnul(lvp->text, '=') + 1);
8660 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
8661 free((char*)vp->text);
8662 vp->flags = lvp->flags;
8663 vp->text = lvp->text;
8664 }
8665 free(lvp);
8666 }
8667}
8668
8669static int
8670evalfun(struct funcnode *func, int argc, char **argv, int flags)
8671{
8672 volatile struct shparam saveparam;
8673 struct localvar *volatile savelocalvars;
8674 struct jmploc *volatile savehandler;
8675 struct jmploc jmploc;
8676 int e;
8677
8678 saveparam = shellparam;
8679 savelocalvars = localvars;
8680 e = setjmp(jmploc.loc);
8681 if (e) {
8682 goto funcdone;
8683 }
8684 INT_OFF;
8685 savehandler = exception_handler;
8686 exception_handler = &jmploc;
8687 localvars = NULL;
Denis Vlasenko01631112007-12-16 17:20:38 +00008688 shellparam.malloced = 0;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008689 func->count++;
8690 funcnest++;
8691 INT_ON;
8692 shellparam.nparam = argc - 1;
8693 shellparam.p = argv + 1;
8694#if ENABLE_ASH_GETOPTS
8695 shellparam.optind = 1;
8696 shellparam.optoff = -1;
8697#endif
8698 evaltree(&func->n, flags & EV_TESTED);
Denis Vlasenko01631112007-12-16 17:20:38 +00008699 funcdone:
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008700 INT_OFF;
8701 funcnest--;
8702 freefunc(func);
8703 poplocalvars();
8704 localvars = savelocalvars;
8705 freeparam(&shellparam);
8706 shellparam = saveparam;
8707 exception_handler = savehandler;
8708 INT_ON;
8709 evalskip &= ~SKIPFUNC;
8710 return e;
8711}
8712
Denis Vlasenko131ae172007-02-18 13:00:19 +00008713#if ENABLE_ASH_CMDCMD
Denis Vlasenkoaa744452007-02-23 01:04:22 +00008714static char **
8715parse_command_args(char **argv, const char **path)
Eric Andersenc470f442003-07-28 09:56:35 +00008716{
8717 char *cp, c;
8718
8719 for (;;) {
8720 cp = *++argv;
8721 if (!cp)
8722 return 0;
8723 if (*cp++ != '-')
8724 break;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008725 c = *cp++;
8726 if (!c)
Eric Andersenc470f442003-07-28 09:56:35 +00008727 break;
8728 if (c == '-' && !*cp) {
8729 argv++;
8730 break;
8731 }
8732 do {
8733 switch (c) {
8734 case 'p':
Denis Vlasenkof5f75c52007-06-12 22:35:19 +00008735 *path = bb_default_path;
Eric Andersenc470f442003-07-28 09:56:35 +00008736 break;
8737 default:
8738 /* run 'typecmd' for other options */
8739 return 0;
8740 }
Denis Vlasenko9650f362007-02-23 01:04:37 +00008741 c = *cp++;
8742 } while (c);
Eric Andersenc470f442003-07-28 09:56:35 +00008743 }
8744 return argv;
8745}
8746#endif
8747
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008748/*
8749 * Make a variable a local variable. When a variable is made local, it's
8750 * value and flags are saved in a localvar structure. The saved values
8751 * will be restored when the shell function returns. We handle the name
8752 * "-" as a special case.
8753 */
8754static void
8755mklocal(char *name)
8756{
8757 struct localvar *lvp;
8758 struct var **vpp;
8759 struct var *vp;
8760
8761 INT_OFF;
Denis Vlasenko838ffd52008-02-21 04:32:08 +00008762 lvp = ckzalloc(sizeof(struct localvar));
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008763 if (LONE_DASH(name)) {
8764 char *p;
8765 p = ckmalloc(sizeof(optlist));
8766 lvp->text = memcpy(p, optlist, sizeof(optlist));
8767 vp = NULL;
8768 } else {
8769 char *eq;
8770
8771 vpp = hashvar(name);
8772 vp = *findvar(vpp, name);
8773 eq = strchr(name, '=');
8774 if (vp == NULL) {
8775 if (eq)
8776 setvareq(name, VSTRFIXED);
8777 else
8778 setvar(name, NULL, VSTRFIXED);
8779 vp = *vpp; /* the new variable */
8780 lvp->flags = VUNSET;
8781 } else {
8782 lvp->text = vp->text;
8783 lvp->flags = vp->flags;
8784 vp->flags |= VSTRFIXED|VTEXTFIXED;
8785 if (eq)
8786 setvareq(name, 0);
8787 }
8788 }
8789 lvp->vp = vp;
8790 lvp->next = localvars;
8791 localvars = lvp;
8792 INT_ON;
8793}
8794
8795/*
8796 * The "local" command.
8797 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008798static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008799localcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008800{
8801 char *name;
8802
8803 argv = argptr;
8804 while ((name = *argv++) != NULL) {
8805 mklocal(name);
8806 }
8807 return 0;
8808}
8809
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008810static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008811falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008812{
8813 return 1;
8814}
8815
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008816static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008817truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008818{
8819 return 0;
8820}
8821
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008822static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008823execcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008824{
Denis Vlasenko68404f12008-03-17 09:00:54 +00008825 if (argv[1]) {
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008826 iflag = 0; /* exit on error */
8827 mflag = 0;
8828 optschanged();
8829 shellexec(argv + 1, pathval(), 0);
8830 }
8831 return 0;
8832}
8833
8834/*
8835 * The return command.
8836 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008837static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008838returncmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008839{
8840 /*
8841 * If called outside a function, do what ksh does;
8842 * skip the rest of the file.
8843 */
8844 evalskip = funcnest ? SKIPFUNC : SKIPFILE;
8845 return argv[1] ? number(argv[1]) : exitstatus;
8846}
8847
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008848/* Forward declarations for builtintab[] */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008849static int breakcmd(int, char **) FAST_FUNC;
8850static int dotcmd(int, char **) FAST_FUNC;
8851static int evalcmd(int, char **) FAST_FUNC;
8852static int exitcmd(int, char **) FAST_FUNC;
8853static int exportcmd(int, char **) FAST_FUNC;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008854#if ENABLE_ASH_GETOPTS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008855static int getoptscmd(int, char **) FAST_FUNC;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008856#endif
Denis Vlasenko52764022007-02-24 13:42:56 +00008857#if !ENABLE_FEATURE_SH_EXTRA_QUIET
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008858static int helpcmd(int, char **) FAST_FUNC;
Denis Vlasenko52764022007-02-24 13:42:56 +00008859#endif
Mike Frysinger98c52642009-04-02 10:02:37 +00008860#if ENABLE_SH_MATH_SUPPORT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008861static int letcmd(int, char **) FAST_FUNC;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008862#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008863static int readcmd(int, char **) FAST_FUNC;
8864static int setcmd(int, char **) FAST_FUNC;
8865static int shiftcmd(int, char **) FAST_FUNC;
8866static int timescmd(int, char **) FAST_FUNC;
8867static int trapcmd(int, char **) FAST_FUNC;
8868static int umaskcmd(int, char **) FAST_FUNC;
8869static int unsetcmd(int, char **) FAST_FUNC;
8870static int ulimitcmd(int, char **) FAST_FUNC;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008871
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008872#define BUILTIN_NOSPEC "0"
8873#define BUILTIN_SPECIAL "1"
8874#define BUILTIN_REGULAR "2"
8875#define BUILTIN_SPEC_REG "3"
8876#define BUILTIN_ASSIGN "4"
8877#define BUILTIN_SPEC_ASSG "5"
8878#define BUILTIN_REG_ASSG "6"
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008879#define BUILTIN_SPEC_REG_ASSG "7"
8880
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008881/* Stubs for calling non-FAST_FUNC's */
Denys Vlasenko2634bf32009-06-09 18:40:07 +02008882#if ENABLE_ASH_BUILTIN_ECHO
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008883static int FAST_FUNC echocmd(int argc, char **argv) { return echo_main(argc, argv); }
Denys Vlasenko2634bf32009-06-09 18:40:07 +02008884#endif
8885#if ENABLE_ASH_BUILTIN_PRINTF
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008886static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
Denys Vlasenko2634bf32009-06-09 18:40:07 +02008887#endif
8888#if ENABLE_ASH_BUILTIN_TEST
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008889static int FAST_FUNC testcmd(int argc, char **argv) { return test_main(argc, argv); }
Denys Vlasenko2634bf32009-06-09 18:40:07 +02008890#endif
Denis Vlasenko468aea22008-04-01 14:47:57 +00008891
Denis Vlasenkof7d56652008-03-25 05:51:41 +00008892/* Keep these in proper order since it is searched via bsearch() */
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008893static const struct builtincmd builtintab[] = {
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008894 { BUILTIN_SPEC_REG "." , dotcmd },
8895 { BUILTIN_SPEC_REG ":" , truecmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008896#if ENABLE_ASH_BUILTIN_TEST
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008897 { BUILTIN_REGULAR "[" , testcmd },
Denis Vlasenko80591b02008-03-25 07:49:43 +00008898#if ENABLE_ASH_BASH_COMPAT
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008899 { BUILTIN_REGULAR "[[" , testcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008900#endif
Denis Vlasenko80591b02008-03-25 07:49:43 +00008901#endif
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008902#if ENABLE_ASH_ALIAS
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008903 { BUILTIN_REG_ASSG "alias" , aliascmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008904#endif
8905#if JOBS
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008906 { BUILTIN_REGULAR "bg" , fg_bgcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008907#endif
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008908 { BUILTIN_SPEC_REG "break" , breakcmd },
8909 { BUILTIN_REGULAR "cd" , cdcmd },
8910 { BUILTIN_NOSPEC "chdir" , cdcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008911#if ENABLE_ASH_CMDCMD
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008912 { BUILTIN_REGULAR "command" , commandcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008913#endif
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008914 { BUILTIN_SPEC_REG "continue", breakcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008915#if ENABLE_ASH_BUILTIN_ECHO
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008916 { BUILTIN_REGULAR "echo" , echocmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008917#endif
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008918 { BUILTIN_SPEC_REG "eval" , evalcmd },
8919 { BUILTIN_SPEC_REG "exec" , execcmd },
8920 { BUILTIN_SPEC_REG "exit" , exitcmd },
8921 { BUILTIN_SPEC_REG_ASSG "export" , exportcmd },
8922 { BUILTIN_REGULAR "false" , falsecmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008923#if JOBS
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008924 { BUILTIN_REGULAR "fg" , fg_bgcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008925#endif
8926#if ENABLE_ASH_GETOPTS
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008927 { BUILTIN_REGULAR "getopts" , getoptscmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008928#endif
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008929 { BUILTIN_NOSPEC "hash" , hashcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008930#if !ENABLE_FEATURE_SH_EXTRA_QUIET
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008931 { BUILTIN_NOSPEC "help" , helpcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008932#endif
8933#if JOBS
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008934 { BUILTIN_REGULAR "jobs" , jobscmd },
8935 { BUILTIN_REGULAR "kill" , killcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008936#endif
Mike Frysinger98c52642009-04-02 10:02:37 +00008937#if ENABLE_SH_MATH_SUPPORT
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008938 { BUILTIN_NOSPEC "let" , letcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008939#endif
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008940 { BUILTIN_ASSIGN "local" , localcmd },
Denis Vlasenkocd2663f2008-06-01 22:36:39 +00008941#if ENABLE_ASH_BUILTIN_PRINTF
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008942 { BUILTIN_REGULAR "printf" , printfcmd },
Denis Vlasenkocd2663f2008-06-01 22:36:39 +00008943#endif
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008944 { BUILTIN_NOSPEC "pwd" , pwdcmd },
8945 { BUILTIN_REGULAR "read" , readcmd },
8946 { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
8947 { BUILTIN_SPEC_REG "return" , returncmd },
8948 { BUILTIN_SPEC_REG "set" , setcmd },
8949 { BUILTIN_SPEC_REG "shift" , shiftcmd },
Denys Vlasenko82731b42010-05-17 17:49:52 +02008950#if ENABLE_ASH_BASH_COMPAT
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008951 { BUILTIN_SPEC_REG "source" , dotcmd },
Denys Vlasenko82731b42010-05-17 17:49:52 +02008952#endif
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008953#if ENABLE_ASH_BUILTIN_TEST
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008954 { BUILTIN_REGULAR "test" , testcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008955#endif
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008956 { BUILTIN_SPEC_REG "times" , timescmd },
8957 { BUILTIN_SPEC_REG "trap" , trapcmd },
8958 { BUILTIN_REGULAR "true" , truecmd },
8959 { BUILTIN_NOSPEC "type" , typecmd },
8960 { BUILTIN_NOSPEC "ulimit" , ulimitcmd },
8961 { BUILTIN_REGULAR "umask" , umaskcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008962#if ENABLE_ASH_ALIAS
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008963 { BUILTIN_REGULAR "unalias" , unaliascmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008964#endif
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008965 { BUILTIN_SPEC_REG "unset" , unsetcmd },
8966 { BUILTIN_REGULAR "wait" , waitcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008967};
8968
Denis Vlasenko80591b02008-03-25 07:49:43 +00008969/* Should match the above table! */
8970#define COMMANDCMD (builtintab + \
8971 2 + \
8972 1 * ENABLE_ASH_BUILTIN_TEST + \
8973 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
8974 1 * ENABLE_ASH_ALIAS + \
8975 1 * ENABLE_ASH_JOB_CONTROL + \
8976 3)
8977#define EXECCMD (builtintab + \
8978 2 + \
8979 1 * ENABLE_ASH_BUILTIN_TEST + \
8980 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
8981 1 * ENABLE_ASH_ALIAS + \
8982 1 * ENABLE_ASH_JOB_CONTROL + \
8983 3 + \
8984 1 * ENABLE_ASH_CMDCMD + \
8985 1 + \
8986 ENABLE_ASH_BUILTIN_ECHO + \
8987 1)
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008988
8989/*
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008990 * Search the table of builtin commands.
8991 */
8992static struct builtincmd *
8993find_builtin(const char *name)
8994{
8995 struct builtincmd *bp;
8996
8997 bp = bsearch(
Denis Vlasenko80b8b392007-06-25 10:55:35 +00008998 name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008999 pstrcmp
9000 );
9001 return bp;
9002}
9003
9004/*
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00009005 * Execute a simple command.
9006 */
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00009007static int
9008isassignment(const char *p)
Paul Foxc3850c82005-07-20 18:23:39 +00009009{
9010 const char *q = endofname(p);
9011 if (p == q)
9012 return 0;
9013 return *q == '=';
9014}
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009015static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00009016bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00009017{
9018 /* Preserve exitstatus of a previous possible redirection
9019 * as POSIX mandates */
9020 return back_exitstatus;
9021}
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02009022static void
Eric Andersenc470f442003-07-28 09:56:35 +00009023evalcommand(union node *cmd, int flags)
9024{
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00009025 static const struct builtincmd null_bltin = {
9026 "\0\0", bltincmd /* why three NULs? */
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00009027 };
Eric Andersenc470f442003-07-28 09:56:35 +00009028 struct stackmark smark;
9029 union node *argp;
9030 struct arglist arglist;
9031 struct arglist varlist;
9032 char **argv;
9033 int argc;
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009034 const struct strlist *sp;
Eric Andersenc470f442003-07-28 09:56:35 +00009035 struct cmdentry cmdentry;
9036 struct job *jp;
9037 char *lastarg;
9038 const char *path;
9039 int spclbltin;
Eric Andersenc470f442003-07-28 09:56:35 +00009040 int status;
9041 char **nargv;
Paul Foxc3850c82005-07-20 18:23:39 +00009042 struct builtincmd *bcmd;
Denis Vlasenko34c73c42008-08-16 11:48:02 +00009043 smallint cmd_is_exec;
9044 smallint pseudovarflag = 0;
Eric Andersenc470f442003-07-28 09:56:35 +00009045
9046 /* First expand the arguments. */
9047 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
9048 setstackmark(&smark);
9049 back_exitstatus = 0;
9050
9051 cmdentry.cmdtype = CMDBUILTIN;
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00009052 cmdentry.u.cmd = &null_bltin;
Eric Andersenc470f442003-07-28 09:56:35 +00009053 varlist.lastp = &varlist.list;
9054 *varlist.lastp = NULL;
9055 arglist.lastp = &arglist.list;
9056 *arglist.lastp = NULL;
9057
9058 argc = 0;
Denis Vlasenkob012b102007-02-19 22:43:01 +00009059 if (cmd->ncmd.args) {
Paul Foxc3850c82005-07-20 18:23:39 +00009060 bcmd = find_builtin(cmd->ncmd.args->narg.text);
9061 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
9062 }
9063
Eric Andersenc470f442003-07-28 09:56:35 +00009064 for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
9065 struct strlist **spp;
9066
9067 spp = arglist.lastp;
"Vladimir N. Oleynik"bef14d72005-09-05 13:25:11 +00009068 if (pseudovarflag && isassignment(argp->narg.text))
Paul Foxc3850c82005-07-20 18:23:39 +00009069 expandarg(argp, &arglist, EXP_VARTILDE);
9070 else
9071 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
9072
Eric Andersenc470f442003-07-28 09:56:35 +00009073 for (sp = *spp; sp; sp = sp->next)
9074 argc++;
9075 }
9076
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +00009077 argv = nargv = stalloc(sizeof(char *) * (argc + 1));
Denis Vlasenko2da584f2007-02-19 22:44:05 +00009078 for (sp = arglist.list; sp; sp = sp->next) {
Eric Andersenc470f442003-07-28 09:56:35 +00009079 TRACE(("evalcommand arg: %s\n", sp->text));
9080 *nargv++ = sp->text;
9081 }
9082 *nargv = NULL;
9083
9084 lastarg = NULL;
9085 if (iflag && funcnest == 0 && argc > 0)
9086 lastarg = nargv[-1];
9087
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009088 preverrout_fd = 2;
Eric Andersenc470f442003-07-28 09:56:35 +00009089 expredir(cmd->ncmd.redirect);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009090 status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
Eric Andersenc470f442003-07-28 09:56:35 +00009091
9092 path = vpath.text;
9093 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
9094 struct strlist **spp;
9095 char *p;
9096
9097 spp = varlist.lastp;
9098 expandarg(argp, &varlist, EXP_VARTILDE);
9099
9100 /*
9101 * Modify the command lookup path, if a PATH= assignment
9102 * is present
9103 */
9104 p = (*spp)->text;
9105 if (varequal(p, path))
9106 path = p;
9107 }
9108
9109 /* Print the command if xflag is set. */
9110 if (xflag) {
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009111 int n;
9112 const char *p = " %s";
Eric Andersenc470f442003-07-28 09:56:35 +00009113
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009114 p++;
Denis Vlasenko0de37e12007-10-17 11:08:53 +00009115 fdprintf(preverrout_fd, p, expandstr(ps4val()));
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009116
9117 sp = varlist.list;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +00009118 for (n = 0; n < 2; n++) {
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009119 while (sp) {
Denis Vlasenko0de37e12007-10-17 11:08:53 +00009120 fdprintf(preverrout_fd, p, sp->text);
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009121 sp = sp->next;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +00009122 if (*p == '%') {
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009123 p--;
9124 }
9125 }
9126 sp = arglist.list;
9127 }
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00009128 safe_write(preverrout_fd, "\n", 1);
Eric Andersenc470f442003-07-28 09:56:35 +00009129 }
9130
9131 cmd_is_exec = 0;
9132 spclbltin = -1;
9133
9134 /* Now locate the command. */
9135 if (argc) {
9136 const char *oldpath;
9137 int cmd_flag = DO_ERR;
9138
9139 path += 5;
9140 oldpath = path;
9141 for (;;) {
9142 find_command(argv[0], &cmdentry, cmd_flag, path);
9143 if (cmdentry.cmdtype == CMDUNKNOWN) {
Denys Vlasenko8131eea2009-11-02 14:19:51 +01009144 flush_stdout_stderr();
Denis Vlasenko6514c5e2008-07-24 13:41:37 +00009145 status = 127;
Eric Andersenc470f442003-07-28 09:56:35 +00009146 goto bail;
9147 }
9148
9149 /* implement bltin and command here */
9150 if (cmdentry.cmdtype != CMDBUILTIN)
9151 break;
9152 if (spclbltin < 0)
9153 spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
9154 if (cmdentry.u.cmd == EXECCMD)
Denis Vlasenko34c73c42008-08-16 11:48:02 +00009155 cmd_is_exec = 1;
Denis Vlasenko131ae172007-02-18 13:00:19 +00009156#if ENABLE_ASH_CMDCMD
Eric Andersenc470f442003-07-28 09:56:35 +00009157 if (cmdentry.u.cmd == COMMANDCMD) {
Eric Andersenc470f442003-07-28 09:56:35 +00009158 path = oldpath;
9159 nargv = parse_command_args(argv, &path);
9160 if (!nargv)
9161 break;
9162 argc -= nargv - argv;
9163 argv = nargv;
9164 cmd_flag |= DO_NOFUNC;
9165 } else
9166#endif
9167 break;
9168 }
9169 }
9170
9171 if (status) {
9172 /* We have a redirection error. */
9173 if (spclbltin > 0)
Denis Vlasenkob012b102007-02-19 22:43:01 +00009174 raise_exception(EXERROR);
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009175 bail:
Eric Andersenc470f442003-07-28 09:56:35 +00009176 exitstatus = status;
9177 goto out;
9178 }
9179
9180 /* Execute the command. */
9181 switch (cmdentry.cmdtype) {
9182 default:
Denis Vlasenkobe54d6b2008-10-27 14:25:52 +00009183
Denis Vlasenko9bc80d72008-04-12 20:07:53 +00009184#if ENABLE_FEATURE_SH_NOFORK
Denis Vlasenkobe54d6b2008-10-27 14:25:52 +00009185/* Hmmm... shouldn't it happen somewhere in forkshell() instead?
9186 * Why "fork off a child process if necessary" doesn't apply to NOFORK? */
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00009187 {
9188 /* find_command() encodes applet_no as (-2 - applet_no) */
9189 int applet_no = (- cmdentry.u.index - 2);
Denis Vlasenko9bc80d72008-04-12 20:07:53 +00009190 if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
Denis Vlasenko9bc80d72008-04-12 20:07:53 +00009191 listsetvar(varlist.list, VEXPORT|VSTACK);
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00009192 /* run <applet>_main() */
9193 exitstatus = run_nofork_applet(applet_no, argv);
Denis Vlasenko9bc80d72008-04-12 20:07:53 +00009194 break;
9195 }
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00009196 }
Denis Vlasenko9bc80d72008-04-12 20:07:53 +00009197#endif
Eric Andersenc470f442003-07-28 09:56:35 +00009198 /* Fork off a child process if necessary. */
Denys Vlasenko238bf182010-05-18 15:49:07 +02009199 if (!(flags & EV_EXIT) || may_have_traps) {
Denis Vlasenkob012b102007-02-19 22:43:01 +00009200 INT_OFF;
Denis Vlasenko68404f12008-03-17 09:00:54 +00009201 jp = makejob(/*cmd,*/ 1);
Eric Andersenc470f442003-07-28 09:56:35 +00009202 if (forkshell(jp, cmd, FORK_FG) != 0) {
Denys Vlasenko238bf182010-05-18 15:49:07 +02009203 /* parent */
Eric Andersenc470f442003-07-28 09:56:35 +00009204 exitstatus = waitforjob(jp);
Denis Vlasenkob012b102007-02-19 22:43:01 +00009205 INT_ON;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00009206 TRACE(("forked child exited with %d\n", exitstatus));
Eric Andersenc470f442003-07-28 09:56:35 +00009207 break;
9208 }
Denys Vlasenko238bf182010-05-18 15:49:07 +02009209 /* child */
Denis Vlasenkob012b102007-02-19 22:43:01 +00009210 FORCE_INT_ON;
Denys Vlasenko238bf182010-05-18 15:49:07 +02009211 /* fall through to exec'ing exeternal program */
Eric Andersenc470f442003-07-28 09:56:35 +00009212 }
9213 listsetvar(varlist.list, VEXPORT|VSTACK);
9214 shellexec(argv, path, cmdentry.u.index);
9215 /* NOTREACHED */
9216
9217 case CMDBUILTIN:
9218 cmdenviron = varlist.list;
9219 if (cmdenviron) {
9220 struct strlist *list = cmdenviron;
9221 int i = VNOSET;
9222 if (spclbltin > 0 || argc == 0) {
9223 i = 0;
9224 if (cmd_is_exec && argc > 1)
9225 i = VEXPORT;
9226 }
9227 listsetvar(list, i);
9228 }
Denis Vlasenkobe54d6b2008-10-27 14:25:52 +00009229 /* Tight loop with builtins only:
9230 * "while kill -0 $child; do true; done"
9231 * will never exit even if $child died, unless we do this
9232 * to reap the zombie and make kill detect that it's gone: */
9233 dowait(DOWAIT_NONBLOCK, NULL);
9234
Eric Andersenc470f442003-07-28 09:56:35 +00009235 if (evalbltin(cmdentry.u.cmd, argc, argv)) {
9236 int exit_status;
Denis Vlasenko7f88e342009-03-19 03:36:18 +00009237 int i = exception_type;
Eric Andersenc470f442003-07-28 09:56:35 +00009238 if (i == EXEXIT)
9239 goto raise;
Eric Andersenc470f442003-07-28 09:56:35 +00009240 exit_status = 2;
Eric Andersenc470f442003-07-28 09:56:35 +00009241 if (i == EXINT)
Denis Vlasenko991a1da2008-02-10 19:02:53 +00009242 exit_status = 128 + SIGINT;
Eric Andersenc470f442003-07-28 09:56:35 +00009243 if (i == EXSIG)
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02009244 exit_status = 128 + pending_sig;
Eric Andersenc470f442003-07-28 09:56:35 +00009245 exitstatus = exit_status;
Eric Andersenc470f442003-07-28 09:56:35 +00009246 if (i == EXINT || spclbltin > 0) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009247 raise:
Denis Vlasenko2da584f2007-02-19 22:44:05 +00009248 longjmp(exception_handler->loc, 1);
Eric Andersenc470f442003-07-28 09:56:35 +00009249 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00009250 FORCE_INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00009251 }
9252 break;
9253
9254 case CMDFUNCTION:
9255 listsetvar(varlist.list, 0);
Denis Vlasenkobe54d6b2008-10-27 14:25:52 +00009256 /* See above for the rationale */
9257 dowait(DOWAIT_NONBLOCK, NULL);
Eric Andersenc470f442003-07-28 09:56:35 +00009258 if (evalfun(cmdentry.u.func, argc, argv, flags))
9259 goto raise;
9260 break;
9261 }
9262
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009263 out:
Denis Vlasenko34c73c42008-08-16 11:48:02 +00009264 popredir(/*drop:*/ cmd_is_exec, /*restore:*/ cmd_is_exec);
Denis Vlasenko6514c5e2008-07-24 13:41:37 +00009265 if (lastarg) {
Eric Andersenc470f442003-07-28 09:56:35 +00009266 /* dsl: I think this is intended to be used to support
9267 * '_' in 'vi' command mode during line editing...
9268 * However I implemented that within libedit itself.
9269 */
9270 setvar("_", lastarg, 0);
Denis Vlasenko6514c5e2008-07-24 13:41:37 +00009271 }
Eric Andersenc470f442003-07-28 09:56:35 +00009272 popstackmark(&smark);
9273}
9274
9275static int
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009276evalbltin(const struct builtincmd *cmd, int argc, char **argv)
9277{
Eric Andersenc470f442003-07-28 09:56:35 +00009278 char *volatile savecmdname;
9279 struct jmploc *volatile savehandler;
9280 struct jmploc jmploc;
9281 int i;
9282
9283 savecmdname = commandname;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009284 i = setjmp(jmploc.loc);
9285 if (i)
Eric Andersenc470f442003-07-28 09:56:35 +00009286 goto cmddone;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00009287 savehandler = exception_handler;
9288 exception_handler = &jmploc;
Eric Andersenc470f442003-07-28 09:56:35 +00009289 commandname = argv[0];
9290 argptr = argv + 1;
9291 optptr = NULL; /* initialize nextopt */
9292 exitstatus = (*cmd->builtin)(argc, argv);
Denis Vlasenkob012b102007-02-19 22:43:01 +00009293 flush_stdout_stderr();
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009294 cmddone:
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009295 exitstatus |= ferror(stdout);
Rob Landleyf296f0b2006-07-06 01:09:21 +00009296 clearerr(stdout);
Eric Andersenc470f442003-07-28 09:56:35 +00009297 commandname = savecmdname;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00009298 exception_handler = savehandler;
Eric Andersenc470f442003-07-28 09:56:35 +00009299
9300 return i;
9301}
9302
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009303static int
9304goodname(const char *p)
Glenn L McGrath16e45d72004-02-04 08:24:39 +00009305{
9306 return !*endofname(p);
9307}
9308
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009309
Glenn L McGrath50812ff2002-08-23 13:14:48 +00009310/*
9311 * Search for a command. This is called before we fork so that the
9312 * location of the command will be available in the parent as well as
Glenn L McGrath16e45d72004-02-04 08:24:39 +00009313 * the child. The check for "goodname" is an overly conservative
9314 * check that the name will not be subject to expansion.
Glenn L McGrath50812ff2002-08-23 13:14:48 +00009315 */
Eric Andersenc470f442003-07-28 09:56:35 +00009316static void
9317prehash(union node *n)
Glenn L McGrath50812ff2002-08-23 13:14:48 +00009318{
9319 struct cmdentry entry;
9320
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +00009321 if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
9322 find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
Glenn L McGrath50812ff2002-08-23 13:14:48 +00009323}
9324
Eric Andersencb57d552001-06-28 07:25:16 +00009325
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00009326/* ============ Builtin commands
9327 *
9328 * Builtin commands whose functions are closely tied to evaluation
9329 * are implemented here.
Eric Andersencb57d552001-06-28 07:25:16 +00009330 */
9331
9332/*
Eric Andersencb57d552001-06-28 07:25:16 +00009333 * Handle break and continue commands. Break, continue, and return are
9334 * all handled by setting the evalskip flag. The evaluation routines
9335 * above all check this flag, and if it is set they start skipping
9336 * commands rather than executing them. The variable skipcount is
9337 * the number of loops to break/continue, or the number of function
9338 * levels to return. (The latter is always 1.) It should probably
9339 * be an error to break out of more loops than exist, but it isn't
9340 * in the standard shell so we don't make it one here.
9341 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009342static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00009343breakcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +00009344{
Denis Vlasenko68404f12008-03-17 09:00:54 +00009345 int n = argv[1] ? number(argv[1]) : 1;
Eric Andersencb57d552001-06-28 07:25:16 +00009346
Aaron Lehmann2aef3a62001-12-31 06:03:12 +00009347 if (n <= 0)
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02009348 ash_msg_and_raise_error(msg_illnum, argv[1]);
Eric Andersencb57d552001-06-28 07:25:16 +00009349 if (n > loopnest)
9350 n = loopnest;
9351 if (n > 0) {
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00009352 evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
Eric Andersencb57d552001-06-28 07:25:16 +00009353 skipcount = n;
9354 }
9355 return 0;
9356}
9357
Eric Andersenc470f442003-07-28 09:56:35 +00009358
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009359/* ============ input.c
9360 *
Eric Andersen90898442003-08-06 11:20:52 +00009361 * This implements the input routines used by the parser.
Eric Andersencb57d552001-06-28 07:25:16 +00009362 */
Denis Vlasenko99eb8502007-02-23 21:09:49 +00009363
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009364enum {
9365 INPUT_PUSH_FILE = 1,
9366 INPUT_NOFILE_OK = 2,
9367};
Eric Andersencb57d552001-06-28 07:25:16 +00009368
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009369static smallint checkkwd;
Denis Vlasenko99eb8502007-02-23 21:09:49 +00009370/* values of checkkwd variable */
9371#define CHKALIAS 0x1
9372#define CHKKWD 0x2
9373#define CHKNL 0x4
9374
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009375/*
9376 * Push a string back onto the input at this current parsefile level.
9377 * We handle aliases this way.
9378 */
9379#if !ENABLE_ASH_ALIAS
9380#define pushstring(s, ap) pushstring(s)
9381#endif
9382static void
9383pushstring(char *s, struct alias *ap)
9384{
9385 struct strpush *sp;
9386 int len;
9387
9388 len = strlen(s);
9389 INT_OFF;
9390 if (g_parsefile->strpush) {
9391 sp = ckzalloc(sizeof(*sp));
9392 sp->prev = g_parsefile->strpush;
9393 } else {
9394 sp = &(g_parsefile->basestrpush);
9395 }
9396 g_parsefile->strpush = sp;
9397 sp->prev_string = g_parsefile->next_to_pgetc;
9398 sp->prev_left_in_line = g_parsefile->left_in_line;
9399#if ENABLE_ASH_ALIAS
9400 sp->ap = ap;
9401 if (ap) {
9402 ap->flag |= ALIASINUSE;
9403 sp->string = s;
9404 }
9405#endif
9406 g_parsefile->next_to_pgetc = s;
9407 g_parsefile->left_in_line = len;
9408 INT_ON;
9409}
9410
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009411static void
9412popstring(void)
Eric Andersenc470f442003-07-28 09:56:35 +00009413{
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009414 struct strpush *sp = g_parsefile->strpush;
Eric Andersenc470f442003-07-28 09:56:35 +00009415
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009416 INT_OFF;
Denis Vlasenko131ae172007-02-18 13:00:19 +00009417#if ENABLE_ASH_ALIAS
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009418 if (sp->ap) {
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009419 if (g_parsefile->next_to_pgetc[-1] == ' '
9420 || g_parsefile->next_to_pgetc[-1] == '\t'
9421 ) {
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009422 checkkwd |= CHKALIAS;
Glenn L McGrath28939ad2004-07-21 10:20:19 +00009423 }
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009424 if (sp->string != sp->ap->val) {
9425 free(sp->string);
9426 }
9427 sp->ap->flag &= ~ALIASINUSE;
9428 if (sp->ap->flag & ALIASDEAD) {
9429 unalias(sp->ap->name);
9430 }
Glenn L McGrath28939ad2004-07-21 10:20:19 +00009431 }
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009432#endif
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009433 g_parsefile->next_to_pgetc = sp->prev_string;
9434 g_parsefile->left_in_line = sp->prev_left_in_line;
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009435 g_parsefile->strpush = sp->prev;
9436 if (sp != &(g_parsefile->basestrpush))
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009437 free(sp);
9438 INT_ON;
9439}
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009440
Denis Vlasenkoe27dafd2008-11-28 04:01:03 +00009441//FIXME: BASH_COMPAT with "...&" does TWO pungetc():
9442//it peeks whether it is &>, and then pushes back both chars.
9443//This function needs to save last *next_to_pgetc to buf[0]
9444//to make two pungetc() reliable. Currently,
9445// pgetc (out of buf: does preadfd), pgetc, pungetc, pungetc won't work...
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009446static int
9447preadfd(void)
Eric Andersencb57d552001-06-28 07:25:16 +00009448{
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00009449 int nr;
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00009450 char *buf = g_parsefile->buf;
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00009451
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009452 g_parsefile->next_to_pgetc = buf;
Denis Vlasenko38f63192007-01-22 09:03:07 +00009453#if ENABLE_FEATURE_EDITING
Denis Vlasenko85c24712008-03-17 09:04:04 +00009454 retry:
Denis Vlasenko727752d2008-11-28 03:41:47 +00009455 if (!iflag || g_parsefile->fd != STDIN_FILENO)
Denys Vlasenko82dd14a2010-05-17 10:10:01 +02009456 nr = nonblock_safe_read(g_parsefile->fd, buf, IBUFSIZ - 1);
Eric Andersenc470f442003-07-28 09:56:35 +00009457 else {
Denis Vlasenko38f63192007-01-22 09:03:07 +00009458#if ENABLE_FEATURE_TAB_COMPLETION
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009459 line_input_state->path_lookup = pathval();
Eric Andersen4a79c0e2004-09-08 10:01:07 +00009460#endif
Denys Vlasenko82dd14a2010-05-17 10:10:01 +02009461 nr = read_line_input(cmdedit_prompt, buf, IBUFSIZ, line_input_state);
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009462 if (nr == 0) {
9463 /* Ctrl+C pressed */
9464 if (trap[SIGINT]) {
Glenn L McGrath16e45d72004-02-04 08:24:39 +00009465 buf[0] = '\n';
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009466 buf[1] = '\0';
Glenn L McGrath16e45d72004-02-04 08:24:39 +00009467 raise(SIGINT);
9468 return 1;
9469 }
Eric Andersenc470f442003-07-28 09:56:35 +00009470 goto retry;
9471 }
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009472 if (nr < 0 && errno == 0) {
Denis Vlasenko9cb220b2007-12-09 10:03:28 +00009473 /* Ctrl+D pressed */
Eric Andersenc470f442003-07-28 09:56:35 +00009474 nr = 0;
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00009475 }
Eric Andersencb57d552001-06-28 07:25:16 +00009476 }
9477#else
Denys Vlasenko82dd14a2010-05-17 10:10:01 +02009478 nr = nonblock_safe_read(g_parsefile->fd, buf, IBUFSIZ - 1);
Eric Andersencb57d552001-06-28 07:25:16 +00009479#endif
9480
Denis Vlasenkoe376d452008-02-20 22:23:24 +00009481#if 0
9482/* nonblock_safe_read() handles this problem */
Eric Andersencb57d552001-06-28 07:25:16 +00009483 if (nr < 0) {
Eric Andersencb57d552001-06-28 07:25:16 +00009484 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
Denis Vlasenkod37f2222007-08-19 13:42:08 +00009485 int flags = fcntl(0, F_GETFL);
Denis Vlasenko9cb220b2007-12-09 10:03:28 +00009486 if (flags >= 0 && (flags & O_NONBLOCK)) {
9487 flags &= ~O_NONBLOCK;
Eric Andersencb57d552001-06-28 07:25:16 +00009488 if (fcntl(0, F_SETFL, flags) >= 0) {
9489 out2str("sh: turning off NDELAY mode\n");
9490 goto retry;
9491 }
9492 }
9493 }
9494 }
Denis Vlasenkoe376d452008-02-20 22:23:24 +00009495#endif
Eric Andersencb57d552001-06-28 07:25:16 +00009496 return nr;
9497}
9498
9499/*
9500 * Refill the input buffer and return the next input character:
9501 *
9502 * 1) If a string was pushed back on the input, pop it;
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009503 * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
9504 * or we are reading from a string so we can't refill the buffer,
9505 * return EOF.
Denys Vlasenko883cea42009-07-11 15:31:59 +02009506 * 3) If there is more stuff in this buffer, use it else call read to fill it.
Eric Andersencb57d552001-06-28 07:25:16 +00009507 * 4) Process input up to the next newline, deleting nul characters.
9508 */
Denis Vlasenko727752d2008-11-28 03:41:47 +00009509//#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
9510#define pgetc_debug(...) ((void)0)
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009511static int
Eric Andersenc470f442003-07-28 09:56:35 +00009512preadbuffer(void)
Eric Andersencb57d552001-06-28 07:25:16 +00009513{
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009514 char *q;
Eric Andersencb57d552001-06-28 07:25:16 +00009515 int more;
Eric Andersencb57d552001-06-28 07:25:16 +00009516
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009517 while (g_parsefile->strpush) {
Denis Vlasenko131ae172007-02-18 13:00:19 +00009518#if ENABLE_ASH_ALIAS
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009519 if (g_parsefile->left_in_line == -1
9520 && g_parsefile->strpush->ap
9521 && g_parsefile->next_to_pgetc[-1] != ' '
9522 && g_parsefile->next_to_pgetc[-1] != '\t'
Denis Vlasenko16898402008-11-25 01:34:52 +00009523 ) {
Denis Vlasenko727752d2008-11-28 03:41:47 +00009524 pgetc_debug("preadbuffer PEOA");
Eric Andersencb57d552001-06-28 07:25:16 +00009525 return PEOA;
9526 }
Eric Andersen2870d962001-07-02 17:27:21 +00009527#endif
Eric Andersencb57d552001-06-28 07:25:16 +00009528 popstring();
Denis Vlasenko727752d2008-11-28 03:41:47 +00009529 /* try "pgetc" now: */
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009530 pgetc_debug("preadbuffer internal pgetc at %d:%p'%s'",
9531 g_parsefile->left_in_line,
9532 g_parsefile->next_to_pgetc,
9533 g_parsefile->next_to_pgetc);
9534 if (--g_parsefile->left_in_line >= 0)
9535 return (unsigned char)(*g_parsefile->next_to_pgetc++);
Eric Andersencb57d552001-06-28 07:25:16 +00009536 }
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009537 /* on both branches above g_parsefile->left_in_line < 0.
Denis Vlasenko727752d2008-11-28 03:41:47 +00009538 * "pgetc" needs refilling.
9539 */
9540
Denis Vlasenkoe27dafd2008-11-28 04:01:03 +00009541 /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009542 * pungetc() may increment it a few times.
Denis Vlasenkoe27dafd2008-11-28 04:01:03 +00009543 * Assuming it won't increment it to less than -90.
Denis Vlasenko727752d2008-11-28 03:41:47 +00009544 */
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009545 if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
Denis Vlasenko727752d2008-11-28 03:41:47 +00009546 pgetc_debug("preadbuffer PEOF1");
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009547 /* even in failure keep left_in_line and next_to_pgetc
9548 * in lock step, for correct multi-layer pungetc.
9549 * left_in_line was decremented before preadbuffer(),
9550 * must inc next_to_pgetc: */
9551 g_parsefile->next_to_pgetc++;
Eric Andersencb57d552001-06-28 07:25:16 +00009552 return PEOF;
Denis Vlasenko727752d2008-11-28 03:41:47 +00009553 }
Eric Andersencb57d552001-06-28 07:25:16 +00009554
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009555 more = g_parsefile->left_in_buffer;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009556 if (more <= 0) {
Denis Vlasenko727752d2008-11-28 03:41:47 +00009557 flush_stdout_stderr();
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009558 again:
9559 more = preadfd();
9560 if (more <= 0) {
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009561 /* don't try reading again */
9562 g_parsefile->left_in_line = -99;
Denis Vlasenko727752d2008-11-28 03:41:47 +00009563 pgetc_debug("preadbuffer PEOF2");
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009564 g_parsefile->next_to_pgetc++;
Eric Andersencb57d552001-06-28 07:25:16 +00009565 return PEOF;
9566 }
9567 }
9568
Denis Vlasenko727752d2008-11-28 03:41:47 +00009569 /* Find out where's the end of line.
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009570 * Set g_parsefile->left_in_line
9571 * and g_parsefile->left_in_buffer acordingly.
Denis Vlasenko727752d2008-11-28 03:41:47 +00009572 * NUL chars are deleted.
9573 */
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009574 q = g_parsefile->next_to_pgetc;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009575 for (;;) {
Denis Vlasenko727752d2008-11-28 03:41:47 +00009576 char c;
Eric Andersencb57d552001-06-28 07:25:16 +00009577
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009578 more--;
Eric Andersenc470f442003-07-28 09:56:35 +00009579
Denis Vlasenko727752d2008-11-28 03:41:47 +00009580 c = *q;
9581 if (c == '\0') {
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009582 memmove(q, q + 1, more);
Denis Vlasenko727752d2008-11-28 03:41:47 +00009583 } else {
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009584 q++;
9585 if (c == '\n') {
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009586 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009587 break;
9588 }
Eric Andersencb57d552001-06-28 07:25:16 +00009589 }
9590
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009591 if (more <= 0) {
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009592 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9593 if (g_parsefile->left_in_line < 0)
Eric Andersencb57d552001-06-28 07:25:16 +00009594 goto again;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009595 break;
Eric Andersencb57d552001-06-28 07:25:16 +00009596 }
9597 }
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009598 g_parsefile->left_in_buffer = more;
Eric Andersencb57d552001-06-28 07:25:16 +00009599
Eric Andersencb57d552001-06-28 07:25:16 +00009600 if (vflag) {
Denis Vlasenko727752d2008-11-28 03:41:47 +00009601 char save = *q;
9602 *q = '\0';
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009603 out2str(g_parsefile->next_to_pgetc);
Denis Vlasenko727752d2008-11-28 03:41:47 +00009604 *q = save;
Eric Andersencb57d552001-06-28 07:25:16 +00009605 }
9606
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009607 pgetc_debug("preadbuffer at %d:%p'%s'",
9608 g_parsefile->left_in_line,
9609 g_parsefile->next_to_pgetc,
9610 g_parsefile->next_to_pgetc);
Denys Vlasenkocd716832009-11-28 22:14:02 +01009611 return (unsigned char)*g_parsefile->next_to_pgetc++;
Eric Andersencb57d552001-06-28 07:25:16 +00009612}
9613
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009614#define pgetc_as_macro() \
9615 (--g_parsefile->left_in_line >= 0 \
Denys Vlasenkocd716832009-11-28 22:14:02 +01009616 ? (unsigned char)*g_parsefile->next_to_pgetc++ \
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009617 : preadbuffer() \
9618 )
Denis Vlasenko727752d2008-11-28 03:41:47 +00009619
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009620static int
9621pgetc(void)
9622{
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009623 pgetc_debug("pgetc_fast at %d:%p'%s'",
9624 g_parsefile->left_in_line,
9625 g_parsefile->next_to_pgetc,
9626 g_parsefile->next_to_pgetc);
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009627 return pgetc_as_macro();
9628}
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00009629
9630#if ENABLE_ASH_OPTIMIZE_FOR_SIZE
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01009631# define pgetc_fast() pgetc()
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009632#else
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01009633# define pgetc_fast() pgetc_as_macro()
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009634#endif
9635
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009636#if ENABLE_ASH_ALIAS
9637static int
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01009638pgetc_without_PEOA(void)
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009639{
9640 int c;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009641 do {
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009642 pgetc_debug("pgetc_fast at %d:%p'%s'",
9643 g_parsefile->left_in_line,
9644 g_parsefile->next_to_pgetc,
9645 g_parsefile->next_to_pgetc);
Denis Vlasenko834dee72008-10-07 09:18:30 +00009646 c = pgetc_fast();
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009647 } while (c == PEOA);
9648 return c;
9649}
9650#else
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01009651# define pgetc_without_PEOA() pgetc()
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009652#endif
9653
9654/*
9655 * Read a line from the script.
9656 */
9657static char *
9658pfgets(char *line, int len)
9659{
9660 char *p = line;
9661 int nleft = len;
9662 int c;
9663
9664 while (--nleft > 0) {
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01009665 c = pgetc_without_PEOA();
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009666 if (c == PEOF) {
9667 if (p == line)
9668 return NULL;
9669 break;
9670 }
9671 *p++ = c;
9672 if (c == '\n')
9673 break;
9674 }
9675 *p = '\0';
9676 return line;
9677}
9678
Eric Andersenc470f442003-07-28 09:56:35 +00009679/*
9680 * Undo the last call to pgetc. Only one character may be pushed back.
9681 * PEOF may be pushed back.
9682 */
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009683static void
Eric Andersenc470f442003-07-28 09:56:35 +00009684pungetc(void)
9685{
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009686 g_parsefile->left_in_line++;
9687 g_parsefile->next_to_pgetc--;
9688 pgetc_debug("pushed back to %d:%p'%s'",
9689 g_parsefile->left_in_line,
9690 g_parsefile->next_to_pgetc,
9691 g_parsefile->next_to_pgetc);
Eric Andersencb57d552001-06-28 07:25:16 +00009692}
9693
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009694/*
9695 * To handle the "." command, a stack of input files is used. Pushfile
9696 * adds a new entry to the stack and popfile restores the previous level.
9697 */
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009698static void
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009699pushfile(void)
Eric Andersenc470f442003-07-28 09:56:35 +00009700{
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009701 struct parsefile *pf;
9702
Denis Vlasenko597906c2008-02-20 16:38:54 +00009703 pf = ckzalloc(sizeof(*pf));
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009704 pf->prev = g_parsefile;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009705 pf->fd = -1;
Denis Vlasenko597906c2008-02-20 16:38:54 +00009706 /*pf->strpush = NULL; - ckzalloc did it */
9707 /*pf->basestrpush.prev = NULL;*/
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009708 g_parsefile = pf;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009709}
9710
9711static void
9712popfile(void)
9713{
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009714 struct parsefile *pf = g_parsefile;
Eric Andersenc470f442003-07-28 09:56:35 +00009715
Denis Vlasenkob012b102007-02-19 22:43:01 +00009716 INT_OFF;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009717 if (pf->fd >= 0)
9718 close(pf->fd);
Denis Vlasenko60818682007-09-28 22:07:23 +00009719 free(pf->buf);
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009720 while (pf->strpush)
9721 popstring();
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009722 g_parsefile = pf->prev;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009723 free(pf);
Denis Vlasenkob012b102007-02-19 22:43:01 +00009724 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00009725}
9726
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009727/*
9728 * Return to top level.
9729 */
9730static void
9731popallfiles(void)
9732{
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009733 while (g_parsefile != &basepf)
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009734 popfile();
9735}
9736
9737/*
9738 * Close the file(s) that the shell is reading commands from. Called
9739 * after a fork is done.
9740 */
9741static void
9742closescript(void)
9743{
9744 popallfiles();
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009745 if (g_parsefile->fd > 0) {
9746 close(g_parsefile->fd);
9747 g_parsefile->fd = 0;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009748 }
9749}
9750
9751/*
9752 * Like setinputfile, but takes an open file descriptor. Call this with
9753 * interrupts off.
9754 */
9755static void
9756setinputfd(int fd, int push)
9757{
Denis Vlasenko96e1b382007-09-30 23:50:48 +00009758 close_on_exec_on(fd);
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009759 if (push) {
9760 pushfile();
Denis Vlasenko727752d2008-11-28 03:41:47 +00009761 g_parsefile->buf = NULL;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009762 }
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009763 g_parsefile->fd = fd;
9764 if (g_parsefile->buf == NULL)
9765 g_parsefile->buf = ckmalloc(IBUFSIZ);
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009766 g_parsefile->left_in_buffer = 0;
9767 g_parsefile->left_in_line = 0;
9768 g_parsefile->linno = 1;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009769}
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009770
Eric Andersenc470f442003-07-28 09:56:35 +00009771/*
9772 * Set the input to take input from a file. If push is set, push the
9773 * old input onto the stack first.
9774 */
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009775static int
9776setinputfile(const char *fname, int flags)
Eric Andersenc470f442003-07-28 09:56:35 +00009777{
9778 int fd;
9779 int fd2;
9780
Denis Vlasenkob012b102007-02-19 22:43:01 +00009781 INT_OFF;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009782 fd = open(fname, O_RDONLY);
9783 if (fd < 0) {
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009784 if (flags & INPUT_NOFILE_OK)
9785 goto out;
Denis Vlasenko9604e1b2009-03-03 18:47:56 +00009786 ash_msg_and_raise_error("can't open '%s'", fname);
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009787 }
Eric Andersenc470f442003-07-28 09:56:35 +00009788 if (fd < 10) {
9789 fd2 = copyfd(fd, 10);
9790 close(fd);
9791 if (fd2 < 0)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00009792 ash_msg_and_raise_error("out of file descriptors");
Eric Andersenc470f442003-07-28 09:56:35 +00009793 fd = fd2;
9794 }
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009795 setinputfd(fd, flags & INPUT_PUSH_FILE);
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009796 out:
Denis Vlasenkob012b102007-02-19 22:43:01 +00009797 INT_ON;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009798 return fd;
Eric Andersenc470f442003-07-28 09:56:35 +00009799}
9800
Eric Andersencb57d552001-06-28 07:25:16 +00009801/*
9802 * Like setinputfile, but takes input from a string.
9803 */
Eric Andersenc470f442003-07-28 09:56:35 +00009804static void
9805setinputstring(char *string)
Eric Andersen62483552001-07-10 06:09:16 +00009806{
Denis Vlasenkob012b102007-02-19 22:43:01 +00009807 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +00009808 pushfile();
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009809 g_parsefile->next_to_pgetc = string;
9810 g_parsefile->left_in_line = strlen(string);
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009811 g_parsefile->buf = NULL;
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009812 g_parsefile->linno = 1;
Denis Vlasenkob012b102007-02-19 22:43:01 +00009813 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00009814}
9815
9816
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00009817/* ============ mail.c
9818 *
9819 * Routines to check for mail.
Eric Andersencb57d552001-06-28 07:25:16 +00009820 */
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00009821
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00009822#if ENABLE_ASH_MAIL
Eric Andersencb57d552001-06-28 07:25:16 +00009823
Eric Andersencb57d552001-06-28 07:25:16 +00009824#define MAXMBOXES 10
9825
Eric Andersenc470f442003-07-28 09:56:35 +00009826/* times of mailboxes */
9827static time_t mailtime[MAXMBOXES];
9828/* Set if MAIL or MAILPATH is changed. */
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +00009829static smallint mail_var_path_changed;
Eric Andersencb57d552001-06-28 07:25:16 +00009830
Eric Andersencb57d552001-06-28 07:25:16 +00009831/*
Eric Andersenc470f442003-07-28 09:56:35 +00009832 * Print appropriate message(s) if mail has arrived.
9833 * If mail_var_path_changed is set,
9834 * then the value of MAIL has mail_var_path_changed,
9835 * so we just update the values.
Eric Andersencb57d552001-06-28 07:25:16 +00009836 */
Eric Andersenc470f442003-07-28 09:56:35 +00009837static void
9838chkmail(void)
Eric Andersencb57d552001-06-28 07:25:16 +00009839{
Eric Andersencb57d552001-06-28 07:25:16 +00009840 const char *mpath;
9841 char *p;
9842 char *q;
Eric Andersenc470f442003-07-28 09:56:35 +00009843 time_t *mtp;
Eric Andersencb57d552001-06-28 07:25:16 +00009844 struct stackmark smark;
9845 struct stat statb;
9846
Eric Andersencb57d552001-06-28 07:25:16 +00009847 setstackmark(&smark);
Eric Andersenc470f442003-07-28 09:56:35 +00009848 mpath = mpathset() ? mpathval() : mailval();
9849 for (mtp = mailtime; mtp < mailtime + MAXMBOXES; mtp++) {
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02009850 p = path_advance(&mpath, nullstr);
Eric Andersencb57d552001-06-28 07:25:16 +00009851 if (p == NULL)
9852 break;
9853 if (*p == '\0')
9854 continue;
Denis Vlasenkof7d56652008-03-25 05:51:41 +00009855 for (q = p; *q; q++)
9856 continue;
Denis Vlasenkoa7189f02006-11-17 20:29:00 +00009857#if DEBUG
Eric Andersencb57d552001-06-28 07:25:16 +00009858 if (q[-1] != '/')
9859 abort();
9860#endif
Eric Andersenc470f442003-07-28 09:56:35 +00009861 q[-1] = '\0'; /* delete trailing '/' */
9862 if (stat(p, &statb) < 0) {
9863 *mtp = 0;
9864 continue;
Eric Andersencb57d552001-06-28 07:25:16 +00009865 }
Eric Andersenc470f442003-07-28 09:56:35 +00009866 if (!mail_var_path_changed && statb.st_mtime != *mtp) {
9867 fprintf(
9868 stderr, snlfmt,
9869 pathopt ? pathopt : "you have mail"
9870 );
9871 }
9872 *mtp = statb.st_mtime;
Eric Andersencb57d552001-06-28 07:25:16 +00009873 }
Eric Andersenc470f442003-07-28 09:56:35 +00009874 mail_var_path_changed = 0;
Eric Andersencb57d552001-06-28 07:25:16 +00009875 popstackmark(&smark);
9876}
Eric Andersencb57d552001-06-28 07:25:16 +00009877
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009878static void FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00009879changemail(const char *val UNUSED_PARAM)
Eric Andersenc470f442003-07-28 09:56:35 +00009880{
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +00009881 mail_var_path_changed = 1;
Eric Andersenc470f442003-07-28 09:56:35 +00009882}
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00009883
Denis Vlasenko131ae172007-02-18 13:00:19 +00009884#endif /* ASH_MAIL */
Eric Andersenc470f442003-07-28 09:56:35 +00009885
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00009886
9887/* ============ ??? */
9888
Eric Andersencb57d552001-06-28 07:25:16 +00009889/*
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009890 * Set the shell parameters.
Eric Andersencb57d552001-06-28 07:25:16 +00009891 */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009892static void
9893setparam(char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +00009894{
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009895 char **newparam;
9896 char **ap;
9897 int nparam;
Eric Andersencb57d552001-06-28 07:25:16 +00009898
Denis Vlasenkof7d56652008-03-25 05:51:41 +00009899 for (nparam = 0; argv[nparam]; nparam++)
9900 continue;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009901 ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
9902 while (*argv) {
9903 *ap++ = ckstrdup(*argv++);
Eric Andersencb57d552001-06-28 07:25:16 +00009904 }
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009905 *ap = NULL;
9906 freeparam(&shellparam);
Denis Vlasenko01631112007-12-16 17:20:38 +00009907 shellparam.malloced = 1;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009908 shellparam.nparam = nparam;
9909 shellparam.p = newparam;
9910#if ENABLE_ASH_GETOPTS
9911 shellparam.optind = 1;
9912 shellparam.optoff = -1;
9913#endif
Eric Andersencb57d552001-06-28 07:25:16 +00009914}
9915
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00009916/*
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009917 * Process shell options. The global variable argptr contains a pointer
9918 * to the argument list; we advance it past the options.
Denis Vlasenko94e87bc2008-02-14 16:51:58 +00009919 *
9920 * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
9921 * For a non-interactive shell, an error condition encountered
9922 * by a special built-in ... shall cause the shell to write a diagnostic message
9923 * to standard error and exit as shown in the following table:
Denis Vlasenko56244732008-02-17 15:14:04 +00009924 * Error Special Built-In
Denis Vlasenko94e87bc2008-02-14 16:51:58 +00009925 * ...
9926 * Utility syntax error (option or operand error) Shall exit
9927 * ...
9928 * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
9929 * we see that bash does not do that (set "finishes" with error code 1 instead,
9930 * and shell continues), and people rely on this behavior!
9931 * Testcase:
9932 * set -o barfoo 2>/dev/null
9933 * echo $?
9934 *
9935 * Oh well. Let's mimic that.
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00009936 */
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009937static int
Denis Vlasenkodddfaff2008-05-06 15:30:27 +00009938plus_minus_o(char *name, int val)
Eric Andersen62483552001-07-10 06:09:16 +00009939{
9940 int i;
9941
Denis Vlasenkoa624c112007-02-19 22:45:43 +00009942 if (name) {
9943 for (i = 0; i < NOPTS; i++) {
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00009944 if (strcmp(name, optnames(i)) == 0) {
Eric Andersenc470f442003-07-28 09:56:35 +00009945 optlist[i] = val;
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009946 return 0;
Eric Andersen62483552001-07-10 06:09:16 +00009947 }
Denis Vlasenkoa624c112007-02-19 22:45:43 +00009948 }
Denis Vlasenkodddfaff2008-05-06 15:30:27 +00009949 ash_msg("illegal option %co %s", val ? '-' : '+', name);
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009950 return 1;
Eric Andersen62483552001-07-10 06:09:16 +00009951 }
Denis Vlasenko6b06cb82008-05-15 21:30:45 +00009952 for (i = 0; i < NOPTS; i++) {
Denis Vlasenkodddfaff2008-05-06 15:30:27 +00009953 if (val) {
9954 out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
9955 } else {
9956 out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
9957 }
Denis Vlasenko6b06cb82008-05-15 21:30:45 +00009958 }
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009959 return 0;
Eric Andersen62483552001-07-10 06:09:16 +00009960}
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009961static void
9962setoption(int flag, int val)
9963{
9964 int i;
9965
9966 for (i = 0; i < NOPTS; i++) {
9967 if (optletters(i) == flag) {
9968 optlist[i] = val;
9969 return;
9970 }
9971 }
Denis Vlasenkodddfaff2008-05-06 15:30:27 +00009972 ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009973 /* NOTREACHED */
9974}
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009975static int
Eric Andersenc470f442003-07-28 09:56:35 +00009976options(int cmdline)
Eric Andersencb57d552001-06-28 07:25:16 +00009977{
9978 char *p;
9979 int val;
9980 int c;
9981
9982 if (cmdline)
9983 minusc = NULL;
9984 while ((p = *argptr) != NULL) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009985 c = *p++;
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +00009986 if (c != '-' && c != '+')
9987 break;
9988 argptr++;
9989 val = 0; /* val = 0 if c == '+' */
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009990 if (c == '-') {
Eric Andersencb57d552001-06-28 07:25:16 +00009991 val = 1;
Denis Vlasenko9f739442006-12-16 23:49:13 +00009992 if (p[0] == '\0' || LONE_DASH(p)) {
Eric Andersen2870d962001-07-02 17:27:21 +00009993 if (!cmdline) {
9994 /* "-" means turn off -x and -v */
9995 if (p[0] == '\0')
9996 xflag = vflag = 0;
9997 /* "--" means reset params */
9998 else if (*argptr == NULL)
Eric Andersencb57d552001-06-28 07:25:16 +00009999 setparam(argptr);
Eric Andersen2870d962001-07-02 17:27:21 +000010000 }
Eric Andersenc470f442003-07-28 09:56:35 +000010001 break; /* "-" or "--" terminates options */
Eric Andersencb57d552001-06-28 07:25:16 +000010002 }
Eric Andersencb57d552001-06-28 07:25:16 +000010003 }
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +000010004 /* first char was + or - */
Eric Andersencb57d552001-06-28 07:25:16 +000010005 while ((c = *p++) != '\0') {
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +000010006 /* bash 3.2 indeed handles -c CMD and +c CMD the same */
Eric Andersencb57d552001-06-28 07:25:16 +000010007 if (c == 'c' && cmdline) {
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +000010008 minusc = p; /* command is after shell args */
Eric Andersencb57d552001-06-28 07:25:16 +000010009 } else if (c == 'o') {
Denis Vlasenkodddfaff2008-05-06 15:30:27 +000010010 if (plus_minus_o(*argptr, val)) {
Denis Vlasenko28bf6712008-02-14 15:01:47 +000010011 /* it already printed err message */
10012 return 1; /* error */
10013 }
Eric Andersencb57d552001-06-28 07:25:16 +000010014 if (*argptr)
10015 argptr++;
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +000010016 } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
10017 isloginsh = 1;
10018 /* bash does not accept +-login, we also won't */
10019 } else if (cmdline && val && (c == '-')) { /* long options */
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010020 if (strcmp(p, "login") == 0)
Robert Griebl64f70cc2002-05-14 23:22:06 +000010021 isloginsh = 1;
10022 break;
Eric Andersencb57d552001-06-28 07:25:16 +000010023 } else {
10024 setoption(c, val);
10025 }
10026 }
10027 }
Denis Vlasenko28bf6712008-02-14 15:01:47 +000010028 return 0;
Eric Andersencb57d552001-06-28 07:25:16 +000010029}
10030
Eric Andersencb57d552001-06-28 07:25:16 +000010031/*
Eric Andersencb57d552001-06-28 07:25:16 +000010032 * The shift builtin command.
10033 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010034static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000010035shiftcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +000010036{
10037 int n;
10038 char **ap1, **ap2;
10039
10040 n = 1;
Denis Vlasenko68404f12008-03-17 09:00:54 +000010041 if (argv[1])
Eric Andersencb57d552001-06-28 07:25:16 +000010042 n = number(argv[1]);
10043 if (n > shellparam.nparam)
Denis Vlasenkoc90e1be2008-07-30 15:35:05 +000010044 n = 0; /* bash compat, was = shellparam.nparam; */
Denis Vlasenkob012b102007-02-19 22:43:01 +000010045 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +000010046 shellparam.nparam -= n;
Denis Vlasenko2da584f2007-02-19 22:44:05 +000010047 for (ap1 = shellparam.p; --n >= 0; ap1++) {
Denis Vlasenko01631112007-12-16 17:20:38 +000010048 if (shellparam.malloced)
Denis Vlasenkob012b102007-02-19 22:43:01 +000010049 free(*ap1);
Eric Andersencb57d552001-06-28 07:25:16 +000010050 }
10051 ap2 = shellparam.p;
Denis Vlasenkof7d56652008-03-25 05:51:41 +000010052 while ((*ap2++ = *ap1++) != NULL)
10053 continue;
Denis Vlasenko131ae172007-02-18 13:00:19 +000010054#if ENABLE_ASH_GETOPTS
Eric Andersencb57d552001-06-28 07:25:16 +000010055 shellparam.optind = 1;
10056 shellparam.optoff = -1;
Eric Andersenc470f442003-07-28 09:56:35 +000010057#endif
Denis Vlasenkob012b102007-02-19 22:43:01 +000010058 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +000010059 return 0;
10060}
10061
Eric Andersencb57d552001-06-28 07:25:16 +000010062/*
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010063 * POSIX requires that 'set' (but not export or readonly) output the
10064 * variables in lexicographic order - by the locale's collating order (sigh).
10065 * Maybe we could keep them in an ordered balanced binary tree
10066 * instead of hashed lists.
10067 * For now just roll 'em through qsort for printing...
10068 */
10069static int
10070showvars(const char *sep_prefix, int on, int off)
10071{
10072 const char *sep;
10073 char **ep, **epend;
10074
10075 ep = listvars(on, off, &epend);
10076 qsort(ep, epend - ep, sizeof(char *), vpcmp);
10077
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +000010078 sep = *sep_prefix ? " " : sep_prefix;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010079
10080 for (; ep < epend; ep++) {
10081 const char *p;
10082 const char *q;
10083
10084 p = strchrnul(*ep, '=');
10085 q = nullstr;
10086 if (*p)
10087 q = single_quote(++p);
10088 out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
10089 }
10090 return 0;
10091}
10092
10093/*
Eric Andersencb57d552001-06-28 07:25:16 +000010094 * The set command builtin.
10095 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010096static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000010097setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersencb57d552001-06-28 07:25:16 +000010098{
Denis Vlasenko28bf6712008-02-14 15:01:47 +000010099 int retval;
10100
Denis Vlasenko68404f12008-03-17 09:00:54 +000010101 if (!argv[1])
Eric Andersenc470f442003-07-28 09:56:35 +000010102 return showvars(nullstr, 0, VUNSET);
Denis Vlasenkob012b102007-02-19 22:43:01 +000010103 INT_OFF;
Denis Vlasenko28bf6712008-02-14 15:01:47 +000010104 retval = 1;
10105 if (!options(0)) { /* if no parse error... */
10106 retval = 0;
10107 optschanged();
10108 if (*argptr != NULL) {
10109 setparam(argptr);
10110 }
Eric Andersencb57d552001-06-28 07:25:16 +000010111 }
Denis Vlasenkob012b102007-02-19 22:43:01 +000010112 INT_ON;
Denis Vlasenko28bf6712008-02-14 15:01:47 +000010113 return retval;
Eric Andersencb57d552001-06-28 07:25:16 +000010114}
10115
Denis Vlasenko131ae172007-02-18 13:00:19 +000010116#if ENABLE_ASH_RANDOM_SUPPORT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010117static void FAST_FUNC
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000010118change_random(const char *value)
Eric Andersenef02f822004-03-11 13:34:24 +000010119{
Denys Vlasenko3ea2e822009-10-09 20:59:04 +020010120 uint32_t t;
10121
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010122 if (value == NULL) {
Eric Andersen16767e22004-03-16 05:14:10 +000010123 /* "get", generate */
Denys Vlasenko3ea2e822009-10-09 20:59:04 +020010124 t = next_random(&random_gen);
Eric Andersen16767e22004-03-16 05:14:10 +000010125 /* set without recursion */
Denis Vlasenko448d30e2008-06-27 00:24:11 +000010126 setvar(vrandom.text, utoa(t), VNOFUNC);
Eric Andersen16767e22004-03-16 05:14:10 +000010127 vrandom.flags &= ~VNOFUNC;
10128 } else {
10129 /* set/reset */
Denys Vlasenko3ea2e822009-10-09 20:59:04 +020010130 t = strtoul(value, NULL, 10);
10131 INIT_RANDOM_T(&random_gen, (t ? t : 1), t);
Eric Andersen16767e22004-03-16 05:14:10 +000010132 }
Eric Andersenef02f822004-03-11 13:34:24 +000010133}
Eric Andersen16767e22004-03-16 05:14:10 +000010134#endif
10135
Denis Vlasenko131ae172007-02-18 13:00:19 +000010136#if ENABLE_ASH_GETOPTS
Eric Andersencb57d552001-06-28 07:25:16 +000010137static int
Eric Andersenc470f442003-07-28 09:56:35 +000010138getopts(char *optstr, char *optvar, char **optfirst, int *param_optind, int *optoff)
Eric Andersencb57d552001-06-28 07:25:16 +000010139{
10140 char *p, *q;
10141 char c = '?';
10142 int done = 0;
10143 int err = 0;
Eric Andersena48b0a32003-10-22 10:56:47 +000010144 char s[12];
10145 char **optnext;
Eric Andersencb57d552001-06-28 07:25:16 +000010146
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010147 if (*param_optind < 1)
Eric Andersena48b0a32003-10-22 10:56:47 +000010148 return 1;
10149 optnext = optfirst + *param_optind - 1;
10150
Denis Vlasenko6b06cb82008-05-15 21:30:45 +000010151 if (*param_optind <= 1 || *optoff < 0 || (int)strlen(optnext[-1]) < *optoff)
Eric Andersencb57d552001-06-28 07:25:16 +000010152 p = NULL;
10153 else
Eric Andersena48b0a32003-10-22 10:56:47 +000010154 p = optnext[-1] + *optoff;
Eric Andersencb57d552001-06-28 07:25:16 +000010155 if (p == NULL || *p == '\0') {
10156 /* Current word is done, advance */
Eric Andersencb57d552001-06-28 07:25:16 +000010157 p = *optnext;
10158 if (p == NULL || *p != '-' || *++p == '\0') {
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010159 atend:
Eric Andersencb57d552001-06-28 07:25:16 +000010160 p = NULL;
10161 done = 1;
10162 goto out;
10163 }
10164 optnext++;
Denis Vlasenko9f739442006-12-16 23:49:13 +000010165 if (LONE_DASH(p)) /* check for "--" */
Eric Andersencb57d552001-06-28 07:25:16 +000010166 goto atend;
10167 }
10168
10169 c = *p++;
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +000010170 for (q = optstr; *q != c;) {
Eric Andersencb57d552001-06-28 07:25:16 +000010171 if (*q == '\0') {
10172 if (optstr[0] == ':') {
10173 s[0] = c;
10174 s[1] = '\0';
10175 err |= setvarsafe("OPTARG", s, 0);
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010176 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000010177 fprintf(stderr, "Illegal option -%c\n", c);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010178 unsetvar("OPTARG");
Eric Andersencb57d552001-06-28 07:25:16 +000010179 }
10180 c = '?';
Eric Andersenc470f442003-07-28 09:56:35 +000010181 goto out;
Eric Andersencb57d552001-06-28 07:25:16 +000010182 }
10183 if (*++q == ':')
10184 q++;
10185 }
10186
10187 if (*++q == ':') {
10188 if (*p == '\0' && (p = *optnext) == NULL) {
10189 if (optstr[0] == ':') {
10190 s[0] = c;
10191 s[1] = '\0';
10192 err |= setvarsafe("OPTARG", s, 0);
10193 c = ':';
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010194 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000010195 fprintf(stderr, "No arg for -%c option\n", c);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010196 unsetvar("OPTARG");
Eric Andersencb57d552001-06-28 07:25:16 +000010197 c = '?';
10198 }
Eric Andersenc470f442003-07-28 09:56:35 +000010199 goto out;
Eric Andersencb57d552001-06-28 07:25:16 +000010200 }
10201
10202 if (p == *optnext)
10203 optnext++;
Eric Andersenc470f442003-07-28 09:56:35 +000010204 err |= setvarsafe("OPTARG", p, 0);
Eric Andersencb57d552001-06-28 07:25:16 +000010205 p = NULL;
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010206 } else
Eric Andersenc470f442003-07-28 09:56:35 +000010207 err |= setvarsafe("OPTARG", nullstr, 0);
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010208 out:
Eric Andersencb57d552001-06-28 07:25:16 +000010209 *optoff = p ? p - *(optnext - 1) : -1;
Eric Andersenc470f442003-07-28 09:56:35 +000010210 *param_optind = optnext - optfirst + 1;
10211 fmtstr(s, sizeof(s), "%d", *param_optind);
Eric Andersencb57d552001-06-28 07:25:16 +000010212 err |= setvarsafe("OPTIND", s, VNOFUNC);
10213 s[0] = c;
10214 s[1] = '\0';
10215 err |= setvarsafe(optvar, s, 0);
10216 if (err) {
Eric Andersenc470f442003-07-28 09:56:35 +000010217 *param_optind = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010218 *optoff = -1;
Denis Vlasenkob012b102007-02-19 22:43:01 +000010219 flush_stdout_stderr();
10220 raise_exception(EXERROR);
Eric Andersencb57d552001-06-28 07:25:16 +000010221 }
10222 return done;
10223}
Eric Andersenc470f442003-07-28 09:56:35 +000010224
10225/*
10226 * The getopts builtin. Shellparam.optnext points to the next argument
10227 * to be processed. Shellparam.optptr points to the next character to
10228 * be processed in the current argument. If shellparam.optnext is NULL,
10229 * then it's the first time getopts has been called.
10230 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010231static int FAST_FUNC
Eric Andersenc470f442003-07-28 09:56:35 +000010232getoptscmd(int argc, char **argv)
10233{
10234 char **optbase;
10235
10236 if (argc < 3)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +000010237 ash_msg_and_raise_error("usage: getopts optstring var [arg]");
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010238 if (argc == 3) {
Eric Andersenc470f442003-07-28 09:56:35 +000010239 optbase = shellparam.p;
10240 if (shellparam.optind > shellparam.nparam + 1) {
10241 shellparam.optind = 1;
10242 shellparam.optoff = -1;
10243 }
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010244 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000010245 optbase = &argv[3];
10246 if (shellparam.optind > argc - 2) {
10247 shellparam.optind = 1;
10248 shellparam.optoff = -1;
10249 }
10250 }
10251
10252 return getopts(argv[1], argv[2], optbase, &shellparam.optind,
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010253 &shellparam.optoff);
Eric Andersenc470f442003-07-28 09:56:35 +000010254}
Denis Vlasenko131ae172007-02-18 13:00:19 +000010255#endif /* ASH_GETOPTS */
Eric Andersencb57d552001-06-28 07:25:16 +000010256
Eric Andersencb57d552001-06-28 07:25:16 +000010257
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010258/* ============ Shell parser */
Eric Andersencb57d552001-06-28 07:25:16 +000010259
Denis Vlasenkob07a4962008-06-22 13:16:23 +000010260struct heredoc {
10261 struct heredoc *next; /* next here document in list */
10262 union node *here; /* redirection node */
10263 char *eofmark; /* string indicating end of input */
10264 smallint striptabs; /* if set, strip leading tabs */
10265};
10266
10267static smallint tokpushback; /* last token pushed back */
10268static smallint parsebackquote; /* nonzero if we are inside backquotes */
10269static smallint quoteflag; /* set if (part of) last token was quoted */
10270static token_id_t lasttoken; /* last token read (integer id Txxx) */
10271static struct heredoc *heredoclist; /* list of here documents to read */
10272static char *wordtext; /* text of last word returned by readtoken */
10273static struct nodelist *backquotelist;
10274static union node *redirnode;
10275static struct heredoc *heredoc;
Denis Vlasenko99eb8502007-02-23 21:09:49 +000010276
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010277/*
10278 * Called when an unexpected token is read during the parse. The argument
10279 * is the token that is expected, or -1 if more than one type of token can
10280 * occur at this point.
10281 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000010282static void raise_error_unexpected_syntax(int) NORETURN;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010283static void
10284raise_error_unexpected_syntax(int token)
10285{
10286 char msg[64];
10287 int l;
10288
Denis Vlasenko7b2294e2008-11-28 03:50:46 +000010289 l = sprintf(msg, "unexpected %s", tokname(lasttoken));
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010290 if (token >= 0)
10291 sprintf(msg + l, " (expecting %s)", tokname(token));
10292 raise_error_syntax(msg);
10293 /* NOTREACHED */
10294}
Eric Andersencb57d552001-06-28 07:25:16 +000010295
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010296#define EOFMARKLEN 79
Eric Andersencb57d552001-06-28 07:25:16 +000010297
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010298/* parsing is heavily cross-recursive, need these forward decls */
10299static union node *andor(void);
10300static union node *pipeline(void);
10301static union node *parse_command(void);
10302static void parseheredoc(void);
10303static char peektoken(void);
10304static int readtoken(void);
Eric Andersencb57d552001-06-28 07:25:16 +000010305
Eric Andersenc470f442003-07-28 09:56:35 +000010306static union node *
10307list(int nlflag)
Eric Andersencb57d552001-06-28 07:25:16 +000010308{
10309 union node *n1, *n2, *n3;
10310 int tok;
10311
Eric Andersenc470f442003-07-28 09:56:35 +000010312 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10313 if (nlflag == 2 && peektoken())
Eric Andersencb57d552001-06-28 07:25:16 +000010314 return NULL;
10315 n1 = NULL;
10316 for (;;) {
10317 n2 = andor();
10318 tok = readtoken();
10319 if (tok == TBACKGND) {
Eric Andersenc470f442003-07-28 09:56:35 +000010320 if (n2->type == NPIPE) {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +000010321 n2->npipe.pipe_backgnd = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010322 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000010323 if (n2->type != NREDIR) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010324 n3 = stzalloc(sizeof(struct nredir));
Eric Andersenc470f442003-07-28 09:56:35 +000010325 n3->nredir.n = n2;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010326 /*n3->nredir.redirect = NULL; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000010327 n2 = n3;
10328 }
10329 n2->type = NBACKGND;
Eric Andersencb57d552001-06-28 07:25:16 +000010330 }
10331 }
10332 if (n1 == NULL) {
10333 n1 = n2;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010334 } else {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010335 n3 = stzalloc(sizeof(struct nbinary));
Eric Andersencb57d552001-06-28 07:25:16 +000010336 n3->type = NSEMI;
10337 n3->nbinary.ch1 = n1;
10338 n3->nbinary.ch2 = n2;
10339 n1 = n3;
10340 }
10341 switch (tok) {
10342 case TBACKGND:
10343 case TSEMI:
10344 tok = readtoken();
10345 /* fall through */
10346 case TNL:
10347 if (tok == TNL) {
10348 parseheredoc();
Eric Andersenc470f442003-07-28 09:56:35 +000010349 if (nlflag == 1)
Eric Andersencb57d552001-06-28 07:25:16 +000010350 return n1;
10351 } else {
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010352 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010353 }
Eric Andersenc470f442003-07-28 09:56:35 +000010354 checkkwd = CHKNL | CHKKWD | CHKALIAS;
Manuel Novoa III 16815d42001-08-10 19:36:07 +000010355 if (peektoken())
Eric Andersencb57d552001-06-28 07:25:16 +000010356 return n1;
10357 break;
10358 case TEOF:
10359 if (heredoclist)
10360 parseheredoc();
10361 else
Eric Andersenc470f442003-07-28 09:56:35 +000010362 pungetc(); /* push back EOF on input */
Eric Andersencb57d552001-06-28 07:25:16 +000010363 return n1;
10364 default:
Eric Andersenc470f442003-07-28 09:56:35 +000010365 if (nlflag == 1)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010366 raise_error_unexpected_syntax(-1);
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010367 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010368 return n1;
10369 }
10370 }
10371}
10372
Eric Andersenc470f442003-07-28 09:56:35 +000010373static union node *
10374andor(void)
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010375{
Eric Andersencb57d552001-06-28 07:25:16 +000010376 union node *n1, *n2, *n3;
10377 int t;
10378
Eric Andersencb57d552001-06-28 07:25:16 +000010379 n1 = pipeline();
10380 for (;;) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010381 t = readtoken();
10382 if (t == TAND) {
Eric Andersencb57d552001-06-28 07:25:16 +000010383 t = NAND;
10384 } else if (t == TOR) {
10385 t = NOR;
10386 } else {
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010387 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010388 return n1;
10389 }
Eric Andersenc470f442003-07-28 09:56:35 +000010390 checkkwd = CHKNL | CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010391 n2 = pipeline();
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010392 n3 = stzalloc(sizeof(struct nbinary));
Eric Andersencb57d552001-06-28 07:25:16 +000010393 n3->type = t;
10394 n3->nbinary.ch1 = n1;
10395 n3->nbinary.ch2 = n2;
10396 n1 = n3;
10397 }
10398}
10399
Eric Andersenc470f442003-07-28 09:56:35 +000010400static union node *
10401pipeline(void)
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010402{
Eric Andersencb57d552001-06-28 07:25:16 +000010403 union node *n1, *n2, *pipenode;
10404 struct nodelist *lp, *prev;
10405 int negate;
10406
10407 negate = 0;
10408 TRACE(("pipeline: entered\n"));
10409 if (readtoken() == TNOT) {
10410 negate = !negate;
Eric Andersenc470f442003-07-28 09:56:35 +000010411 checkkwd = CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010412 } else
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010413 tokpushback = 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010414 n1 = parse_command();
Eric Andersencb57d552001-06-28 07:25:16 +000010415 if (readtoken() == TPIPE) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010416 pipenode = stzalloc(sizeof(struct npipe));
Eric Andersencb57d552001-06-28 07:25:16 +000010417 pipenode->type = NPIPE;
Denis Vlasenko2dc240c2008-07-24 06:07:50 +000010418 /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010419 lp = stzalloc(sizeof(struct nodelist));
Eric Andersencb57d552001-06-28 07:25:16 +000010420 pipenode->npipe.cmdlist = lp;
10421 lp->n = n1;
10422 do {
10423 prev = lp;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010424 lp = stzalloc(sizeof(struct nodelist));
Eric Andersenc470f442003-07-28 09:56:35 +000010425 checkkwd = CHKNL | CHKKWD | CHKALIAS;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010426 lp->n = parse_command();
Eric Andersencb57d552001-06-28 07:25:16 +000010427 prev->next = lp;
10428 } while (readtoken() == TPIPE);
10429 lp->next = NULL;
10430 n1 = pipenode;
10431 }
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010432 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010433 if (negate) {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010434 n2 = stzalloc(sizeof(struct nnot));
Eric Andersencb57d552001-06-28 07:25:16 +000010435 n2->type = NNOT;
10436 n2->nnot.com = n1;
10437 return n2;
Denis Vlasenko2da584f2007-02-19 22:44:05 +000010438 }
10439 return n1;
Eric Andersencb57d552001-06-28 07:25:16 +000010440}
10441
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010442static union node *
10443makename(void)
10444{
10445 union node *n;
10446
Denis Vlasenko597906c2008-02-20 16:38:54 +000010447 n = stzalloc(sizeof(struct narg));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010448 n->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010449 /*n->narg.next = NULL; - stzalloc did it */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010450 n->narg.text = wordtext;
10451 n->narg.backquote = backquotelist;
10452 return n;
10453}
10454
10455static void
10456fixredir(union node *n, const char *text, int err)
10457{
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000010458 int fd;
10459
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010460 TRACE(("Fix redir %s %d\n", text, err));
10461 if (!err)
10462 n->ndup.vname = NULL;
10463
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000010464 fd = bb_strtou(text, NULL, 10);
10465 if (!errno && fd >= 0)
10466 n->ndup.dupfd = fd;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010467 else if (LONE_DASH(text))
10468 n->ndup.dupfd = -1;
10469 else {
10470 if (err)
Denis Vlasenko559691a2008-10-05 18:39:31 +000010471 raise_error_syntax("bad fd number");
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010472 n->ndup.vname = makename();
10473 }
10474}
10475
10476/*
10477 * Returns true if the text contains nothing to expand (no dollar signs
10478 * or backquotes).
10479 */
10480static int
Denis Vlasenko68819d12008-12-15 11:26:36 +000010481noexpand(const char *text)
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010482{
Denys Vlasenkocd716832009-11-28 22:14:02 +010010483 unsigned char c;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010484
Denys Vlasenkocd716832009-11-28 22:14:02 +010010485 while ((c = *text++) != '\0') {
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010486 if (c == CTLQUOTEMARK)
10487 continue;
10488 if (c == CTLESC)
Denys Vlasenkocd716832009-11-28 22:14:02 +010010489 text++;
Denys Vlasenko76bc2d62009-11-29 01:37:46 +010010490 else if (SIT(c, BASESYNTAX) == CCTL)
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010491 return 0;
10492 }
10493 return 1;
10494}
10495
10496static void
10497parsefname(void)
10498{
10499 union node *n = redirnode;
10500
10501 if (readtoken() != TWORD)
10502 raise_error_unexpected_syntax(-1);
10503 if (n->type == NHERE) {
10504 struct heredoc *here = heredoc;
10505 struct heredoc *p;
10506 int i;
10507
10508 if (quoteflag == 0)
10509 n->type = NXHERE;
10510 TRACE(("Here document %d\n", n->type));
10511 if (!noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
Denis Vlasenko559691a2008-10-05 18:39:31 +000010512 raise_error_syntax("illegal eof marker for << redirection");
Denys Vlasenkob6c84342009-08-29 20:23:20 +020010513 rmescapes(wordtext, 0);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010514 here->eofmark = wordtext;
10515 here->next = NULL;
10516 if (heredoclist == NULL)
10517 heredoclist = here;
10518 else {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010519 for (p = heredoclist; p->next; p = p->next)
10520 continue;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010521 p->next = here;
10522 }
10523 } else if (n->type == NTOFD || n->type == NFROMFD) {
10524 fixredir(n, wordtext, 0);
10525 } else {
10526 n->nfile.fname = makename();
10527 }
10528}
Eric Andersencb57d552001-06-28 07:25:16 +000010529
Eric Andersenc470f442003-07-28 09:56:35 +000010530static union node *
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010531simplecmd(void)
10532{
10533 union node *args, **app;
10534 union node *n = NULL;
10535 union node *vars, **vpp;
10536 union node **rpp, *redir;
10537 int savecheckkwd;
Denis Vlasenko80591b02008-03-25 07:49:43 +000010538#if ENABLE_ASH_BASH_COMPAT
10539 smallint double_brackets_flag = 0;
10540#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010541
10542 args = NULL;
10543 app = &args;
10544 vars = NULL;
10545 vpp = &vars;
10546 redir = NULL;
10547 rpp = &redir;
10548
10549 savecheckkwd = CHKALIAS;
10550 for (;;) {
Denis Vlasenko80591b02008-03-25 07:49:43 +000010551 int t;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010552 checkkwd = savecheckkwd;
Denis Vlasenko80591b02008-03-25 07:49:43 +000010553 t = readtoken();
10554 switch (t) {
10555#if ENABLE_ASH_BASH_COMPAT
10556 case TAND: /* "&&" */
10557 case TOR: /* "||" */
10558 if (!double_brackets_flag) {
10559 tokpushback = 1;
10560 goto out;
10561 }
10562 wordtext = (char *) (t == TAND ? "-a" : "-o");
10563#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010564 case TWORD:
Denis Vlasenko597906c2008-02-20 16:38:54 +000010565 n = stzalloc(sizeof(struct narg));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010566 n->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010567 /*n->narg.next = NULL; - stzalloc did it */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010568 n->narg.text = wordtext;
Denis Vlasenko80591b02008-03-25 07:49:43 +000010569#if ENABLE_ASH_BASH_COMPAT
10570 if (strcmp("[[", wordtext) == 0)
10571 double_brackets_flag = 1;
10572 else if (strcmp("]]", wordtext) == 0)
10573 double_brackets_flag = 0;
10574#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010575 n->narg.backquote = backquotelist;
10576 if (savecheckkwd && isassignment(wordtext)) {
10577 *vpp = n;
10578 vpp = &n->narg.next;
10579 } else {
10580 *app = n;
10581 app = &n->narg.next;
10582 savecheckkwd = 0;
10583 }
10584 break;
10585 case TREDIR:
10586 *rpp = n = redirnode;
10587 rpp = &n->nfile.next;
10588 parsefname(); /* read name of redirection file */
10589 break;
10590 case TLP:
10591 if (args && app == &args->narg.next
10592 && !vars && !redir
10593 ) {
10594 struct builtincmd *bcmd;
10595 const char *name;
10596
10597 /* We have a function */
10598 if (readtoken() != TRP)
10599 raise_error_unexpected_syntax(TRP);
10600 name = n->narg.text;
10601 if (!goodname(name)
10602 || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
10603 ) {
Denis Vlasenko559691a2008-10-05 18:39:31 +000010604 raise_error_syntax("bad function name");
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010605 }
10606 n->type = NDEFUN;
10607 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10608 n->narg.next = parse_command();
10609 return n;
10610 }
10611 /* fall through */
10612 default:
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010613 tokpushback = 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010614 goto out;
10615 }
10616 }
10617 out:
10618 *app = NULL;
10619 *vpp = NULL;
10620 *rpp = NULL;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010621 n = stzalloc(sizeof(struct ncmd));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010622 n->type = NCMD;
10623 n->ncmd.args = args;
10624 n->ncmd.assign = vars;
10625 n->ncmd.redirect = redir;
10626 return n;
10627}
10628
10629static union node *
10630parse_command(void)
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010631{
Eric Andersencb57d552001-06-28 07:25:16 +000010632 union node *n1, *n2;
10633 union node *ap, **app;
10634 union node *cp, **cpp;
10635 union node *redir, **rpp;
Eric Andersenc470f442003-07-28 09:56:35 +000010636 union node **rpp2;
Eric Andersencb57d552001-06-28 07:25:16 +000010637 int t;
10638
10639 redir = NULL;
Eric Andersenc470f442003-07-28 09:56:35 +000010640 rpp2 = &redir;
Eric Andersen88cec252001-09-06 17:35:20 +000010641
Eric Andersencb57d552001-06-28 07:25:16 +000010642 switch (readtoken()) {
Eric Andersenc470f442003-07-28 09:56:35 +000010643 default:
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010644 raise_error_unexpected_syntax(-1);
Eric Andersenc470f442003-07-28 09:56:35 +000010645 /* NOTREACHED */
Eric Andersencb57d552001-06-28 07:25:16 +000010646 case TIF:
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010647 n1 = stzalloc(sizeof(struct nif));
Eric Andersencb57d552001-06-28 07:25:16 +000010648 n1->type = NIF;
10649 n1->nif.test = list(0);
10650 if (readtoken() != TTHEN)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010651 raise_error_unexpected_syntax(TTHEN);
Eric Andersencb57d552001-06-28 07:25:16 +000010652 n1->nif.ifpart = list(0);
10653 n2 = n1;
10654 while (readtoken() == TELIF) {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010655 n2->nif.elsepart = stzalloc(sizeof(struct nif));
Eric Andersencb57d552001-06-28 07:25:16 +000010656 n2 = n2->nif.elsepart;
10657 n2->type = NIF;
10658 n2->nif.test = list(0);
10659 if (readtoken() != TTHEN)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010660 raise_error_unexpected_syntax(TTHEN);
Eric Andersencb57d552001-06-28 07:25:16 +000010661 n2->nif.ifpart = list(0);
10662 }
10663 if (lasttoken == TELSE)
10664 n2->nif.elsepart = list(0);
10665 else {
10666 n2->nif.elsepart = NULL;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010667 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010668 }
Eric Andersenc470f442003-07-28 09:56:35 +000010669 t = TFI;
Eric Andersencb57d552001-06-28 07:25:16 +000010670 break;
10671 case TWHILE:
Eric Andersenc470f442003-07-28 09:56:35 +000010672 case TUNTIL: {
Eric Andersencb57d552001-06-28 07:25:16 +000010673 int got;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010674 n1 = stzalloc(sizeof(struct nbinary));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010675 n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
Eric Andersencb57d552001-06-28 07:25:16 +000010676 n1->nbinary.ch1 = list(0);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010677 got = readtoken();
10678 if (got != TDO) {
Denis Vlasenko131ae172007-02-18 13:00:19 +000010679 TRACE(("expecting DO got %s %s\n", tokname(got),
10680 got == TWORD ? wordtext : ""));
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010681 raise_error_unexpected_syntax(TDO);
Eric Andersencb57d552001-06-28 07:25:16 +000010682 }
10683 n1->nbinary.ch2 = list(0);
Eric Andersenc470f442003-07-28 09:56:35 +000010684 t = TDONE;
Eric Andersencb57d552001-06-28 07:25:16 +000010685 break;
10686 }
10687 case TFOR:
Denis Vlasenko2dc240c2008-07-24 06:07:50 +000010688 if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
Denis Vlasenko559691a2008-10-05 18:39:31 +000010689 raise_error_syntax("bad for loop variable");
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010690 n1 = stzalloc(sizeof(struct nfor));
Eric Andersencb57d552001-06-28 07:25:16 +000010691 n1->type = NFOR;
10692 n1->nfor.var = wordtext;
Eric Andersenc470f442003-07-28 09:56:35 +000010693 checkkwd = CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010694 if (readtoken() == TIN) {
10695 app = &ap;
10696 while (readtoken() == TWORD) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010697 n2 = stzalloc(sizeof(struct narg));
Eric Andersencb57d552001-06-28 07:25:16 +000010698 n2->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010699 /*n2->narg.next = NULL; - stzalloc did it */
Eric Andersencb57d552001-06-28 07:25:16 +000010700 n2->narg.text = wordtext;
10701 n2->narg.backquote = backquotelist;
10702 *app = n2;
10703 app = &n2->narg.next;
10704 }
10705 *app = NULL;
10706 n1->nfor.args = ap;
10707 if (lasttoken != TNL && lasttoken != TSEMI)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010708 raise_error_unexpected_syntax(-1);
Eric Andersencb57d552001-06-28 07:25:16 +000010709 } else {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010710 n2 = stzalloc(sizeof(struct narg));
Eric Andersencb57d552001-06-28 07:25:16 +000010711 n2->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010712 /*n2->narg.next = NULL; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000010713 n2->narg.text = (char *)dolatstr;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010714 /*n2->narg.backquote = NULL;*/
Eric Andersencb57d552001-06-28 07:25:16 +000010715 n1->nfor.args = n2;
10716 /*
10717 * Newline or semicolon here is optional (but note
10718 * that the original Bourne shell only allowed NL).
10719 */
10720 if (lasttoken != TNL && lasttoken != TSEMI)
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010721 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010722 }
Eric Andersenc470f442003-07-28 09:56:35 +000010723 checkkwd = CHKNL | CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010724 if (readtoken() != TDO)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010725 raise_error_unexpected_syntax(TDO);
Eric Andersencb57d552001-06-28 07:25:16 +000010726 n1->nfor.body = list(0);
Eric Andersenc470f442003-07-28 09:56:35 +000010727 t = TDONE;
Eric Andersencb57d552001-06-28 07:25:16 +000010728 break;
10729 case TCASE:
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010730 n1 = stzalloc(sizeof(struct ncase));
Eric Andersencb57d552001-06-28 07:25:16 +000010731 n1->type = NCASE;
10732 if (readtoken() != TWORD)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010733 raise_error_unexpected_syntax(TWORD);
Denis Vlasenko597906c2008-02-20 16:38:54 +000010734 n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
Eric Andersencb57d552001-06-28 07:25:16 +000010735 n2->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010736 /*n2->narg.next = NULL; - stzalloc did it */
Eric Andersencb57d552001-06-28 07:25:16 +000010737 n2->narg.text = wordtext;
10738 n2->narg.backquote = backquotelist;
Eric Andersencb57d552001-06-28 07:25:16 +000010739 do {
Eric Andersenc470f442003-07-28 09:56:35 +000010740 checkkwd = CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010741 } while (readtoken() == TNL);
10742 if (lasttoken != TIN)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010743 raise_error_unexpected_syntax(TIN);
Eric Andersencb57d552001-06-28 07:25:16 +000010744 cpp = &n1->ncase.cases;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010745 next_case:
Eric Andersenc470f442003-07-28 09:56:35 +000010746 checkkwd = CHKNL | CHKKWD;
10747 t = readtoken();
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010748 while (t != TESAC) {
Eric Andersencb57d552001-06-28 07:25:16 +000010749 if (lasttoken == TLP)
10750 readtoken();
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010751 *cpp = cp = stzalloc(sizeof(struct nclist));
Eric Andersencb57d552001-06-28 07:25:16 +000010752 cp->type = NCLIST;
10753 app = &cp->nclist.pattern;
10754 for (;;) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010755 *app = ap = stzalloc(sizeof(struct narg));
Eric Andersencb57d552001-06-28 07:25:16 +000010756 ap->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010757 /*ap->narg.next = NULL; - stzalloc did it */
Eric Andersencb57d552001-06-28 07:25:16 +000010758 ap->narg.text = wordtext;
10759 ap->narg.backquote = backquotelist;
Eric Andersenc470f442003-07-28 09:56:35 +000010760 if (readtoken() != TPIPE)
Eric Andersencb57d552001-06-28 07:25:16 +000010761 break;
10762 app = &ap->narg.next;
10763 readtoken();
10764 }
Denis Vlasenko597906c2008-02-20 16:38:54 +000010765 //ap->narg.next = NULL;
Eric Andersencb57d552001-06-28 07:25:16 +000010766 if (lasttoken != TRP)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010767 raise_error_unexpected_syntax(TRP);
Eric Andersenc470f442003-07-28 09:56:35 +000010768 cp->nclist.body = list(2);
Eric Andersencb57d552001-06-28 07:25:16 +000010769
Eric Andersenc470f442003-07-28 09:56:35 +000010770 cpp = &cp->nclist.next;
10771
10772 checkkwd = CHKNL | CHKKWD;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010773 t = readtoken();
10774 if (t != TESAC) {
Eric Andersencb57d552001-06-28 07:25:16 +000010775 if (t != TENDCASE)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010776 raise_error_unexpected_syntax(TENDCASE);
10777 goto next_case;
Eric Andersencb57d552001-06-28 07:25:16 +000010778 }
Eric Andersenc470f442003-07-28 09:56:35 +000010779 }
Eric Andersencb57d552001-06-28 07:25:16 +000010780 *cpp = NULL;
Eric Andersenc470f442003-07-28 09:56:35 +000010781 goto redir;
Eric Andersencb57d552001-06-28 07:25:16 +000010782 case TLP:
Denis Vlasenko597906c2008-02-20 16:38:54 +000010783 n1 = stzalloc(sizeof(struct nredir));
Eric Andersencb57d552001-06-28 07:25:16 +000010784 n1->type = NSUBSHELL;
10785 n1->nredir.n = list(0);
Denis Vlasenko597906c2008-02-20 16:38:54 +000010786 /*n1->nredir.redirect = NULL; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000010787 t = TRP;
Eric Andersencb57d552001-06-28 07:25:16 +000010788 break;
10789 case TBEGIN:
10790 n1 = list(0);
Eric Andersenc470f442003-07-28 09:56:35 +000010791 t = TEND;
Eric Andersencb57d552001-06-28 07:25:16 +000010792 break;
Eric Andersencb57d552001-06-28 07:25:16 +000010793 case TWORD:
Eric Andersenc470f442003-07-28 09:56:35 +000010794 case TREDIR:
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010795 tokpushback = 1;
Eric Andersenc470f442003-07-28 09:56:35 +000010796 return simplecmd();
Eric Andersencb57d552001-06-28 07:25:16 +000010797 }
10798
Eric Andersenc470f442003-07-28 09:56:35 +000010799 if (readtoken() != t)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010800 raise_error_unexpected_syntax(t);
Eric Andersenc470f442003-07-28 09:56:35 +000010801
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010802 redir:
Eric Andersencb57d552001-06-28 07:25:16 +000010803 /* Now check for redirection which may follow command */
Eric Andersenc470f442003-07-28 09:56:35 +000010804 checkkwd = CHKKWD | CHKALIAS;
10805 rpp = rpp2;
Eric Andersencb57d552001-06-28 07:25:16 +000010806 while (readtoken() == TREDIR) {
10807 *rpp = n2 = redirnode;
10808 rpp = &n2->nfile.next;
10809 parsefname();
10810 }
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010811 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010812 *rpp = NULL;
10813 if (redir) {
10814 if (n1->type != NSUBSHELL) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010815 n2 = stzalloc(sizeof(struct nredir));
Eric Andersencb57d552001-06-28 07:25:16 +000010816 n2->type = NREDIR;
10817 n2->nredir.n = n1;
10818 n1 = n2;
10819 }
10820 n1->nredir.redirect = redir;
10821 }
Eric Andersencb57d552001-06-28 07:25:16 +000010822 return n1;
10823}
10824
Denis Vlasenkoef527f52008-06-23 01:52:30 +000010825#if ENABLE_ASH_BASH_COMPAT
10826static int decode_dollar_squote(void)
10827{
10828 static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
10829 int c, cnt;
10830 char *p;
10831 char buf[4];
10832
10833 c = pgetc();
10834 p = strchr(C_escapes, c);
10835 if (p) {
10836 buf[0] = c;
10837 p = buf;
10838 cnt = 3;
10839 if ((unsigned char)(c - '0') <= 7) { /* \ooo */
10840 do {
10841 c = pgetc();
10842 *++p = c;
10843 } while ((unsigned char)(c - '0') <= 7 && --cnt);
10844 pungetc();
10845 } else if (c == 'x') { /* \xHH */
10846 do {
10847 c = pgetc();
10848 *++p = c;
10849 } while (isxdigit(c) && --cnt);
10850 pungetc();
10851 if (cnt == 3) { /* \x but next char is "bad" */
10852 c = 'x';
10853 goto unrecognized;
10854 }
10855 } else { /* simple seq like \\ or \t */
10856 p++;
10857 }
10858 *p = '\0';
10859 p = buf;
10860 c = bb_process_escape_sequence((void*)&p);
10861 } else { /* unrecognized "\z": print both chars unless ' or " */
10862 if (c != '\'' && c != '"') {
10863 unrecognized:
10864 c |= 0x100; /* "please encode \, then me" */
10865 }
10866 }
10867 return c;
10868}
10869#endif
10870
Eric Andersencb57d552001-06-28 07:25:16 +000010871/*
10872 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
10873 * is not NULL, read a here document. In the latter case, eofmark is the
10874 * word which marks the end of the document and striptabs is true if
Denys Vlasenkocd716832009-11-28 22:14:02 +010010875 * leading tabs should be stripped from the document. The argument c
Eric Andersencb57d552001-06-28 07:25:16 +000010876 * is the first character of the input token or document.
10877 *
10878 * Because C does not have internal subroutines, I have simulated them
10879 * using goto's to implement the subroutine linkage. The following macros
10880 * will run code that appears at the end of readtoken1.
10881 */
Eric Andersen2870d962001-07-02 17:27:21 +000010882#define CHECKEND() {goto checkend; checkend_return:;}
10883#define PARSEREDIR() {goto parseredir; parseredir_return:;}
10884#define PARSESUB() {goto parsesub; parsesub_return:;}
10885#define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
10886#define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
10887#define PARSEARITH() {goto parsearith; parsearith_return:;}
Eric Andersencb57d552001-06-28 07:25:16 +000010888static int
Denys Vlasenkocd716832009-11-28 22:14:02 +010010889readtoken1(int c, int syntax, char *eofmark, int striptabs)
Manuel Novoa III 16815d42001-08-10 19:36:07 +000010890{
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010891 /* NB: syntax parameter fits into smallint */
Denys Vlasenkocd716832009-11-28 22:14:02 +010010892 /* c parameter is an unsigned char or PEOF or PEOA */
Eric Andersencb57d552001-06-28 07:25:16 +000010893 char *out;
10894 int len;
10895 char line[EOFMARKLEN + 1];
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010896 struct nodelist *bqlist;
10897 smallint quotef;
10898 smallint dblquote;
10899 smallint oldstyle;
10900 smallint prevsyntax; /* syntax before arithmetic */
Denis Vlasenko46a53062007-09-24 18:30:02 +000010901#if ENABLE_ASH_EXPAND_PRMT
10902 smallint pssyntax; /* we are expanding a prompt string */
10903#endif
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010904 int varnest; /* levels of variables expansion */
10905 int arinest; /* levels of arithmetic expansion */
10906 int parenlevel; /* levels of parens in arithmetic */
10907 int dqvarnest; /* levels of variables expansion within double quotes */
10908
Denis Vlasenko5e34ff22009-04-21 11:09:40 +000010909 IF_ASH_BASH_COMPAT(smallint bash_dollar_squote = 0;)
Denis Vlasenkoef527f52008-06-23 01:52:30 +000010910
Eric Andersencb57d552001-06-28 07:25:16 +000010911#if __GNUC__
10912 /* Avoid longjmp clobbering */
10913 (void) &out;
10914 (void) &quotef;
10915 (void) &dblquote;
10916 (void) &varnest;
10917 (void) &arinest;
10918 (void) &parenlevel;
10919 (void) &dqvarnest;
10920 (void) &oldstyle;
10921 (void) &prevsyntax;
10922 (void) &syntax;
10923#endif
Denis Vlasenko41eb3002008-11-28 03:42:31 +000010924 startlinno = g_parsefile->linno;
Eric Andersencb57d552001-06-28 07:25:16 +000010925 bqlist = NULL;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010926 quotef = 0;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010927 oldstyle = 0;
10928 prevsyntax = 0;
Denis Vlasenko46a53062007-09-24 18:30:02 +000010929#if ENABLE_ASH_EXPAND_PRMT
10930 pssyntax = (syntax == PSSYNTAX);
10931 if (pssyntax)
10932 syntax = DQSYNTAX;
10933#endif
10934 dblquote = (syntax == DQSYNTAX);
Eric Andersencb57d552001-06-28 07:25:16 +000010935 varnest = 0;
10936 arinest = 0;
10937 parenlevel = 0;
10938 dqvarnest = 0;
10939
10940 STARTSTACKSTR(out);
Denis Vlasenko176d49d2008-10-06 09:51:47 +000010941 loop:
10942 /* For each line, until end of word */
10943 {
Eric Andersenc470f442003-07-28 09:56:35 +000010944 CHECKEND(); /* set c to PEOF if at end of here document */
10945 for (;;) { /* until end of line or end of word */
10946 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
Denis Vlasenkobf0a2012006-12-26 10:42:51 +000010947 switch (SIT(c, syntax)) {
Eric Andersenc470f442003-07-28 09:56:35 +000010948 case CNL: /* '\n' */
Eric Andersencb57d552001-06-28 07:25:16 +000010949 if (syntax == BASESYNTAX)
Eric Andersenc470f442003-07-28 09:56:35 +000010950 goto endword; /* exit outer loop */
Eric Andersencb57d552001-06-28 07:25:16 +000010951 USTPUTC(c, out);
Denis Vlasenko41eb3002008-11-28 03:42:31 +000010952 g_parsefile->linno++;
Eric Andersencb57d552001-06-28 07:25:16 +000010953 if (doprompt)
10954 setprompt(2);
Eric Andersencb57d552001-06-28 07:25:16 +000010955 c = pgetc();
Eric Andersenc470f442003-07-28 09:56:35 +000010956 goto loop; /* continue outer loop */
Eric Andersencb57d552001-06-28 07:25:16 +000010957 case CWORD:
10958 USTPUTC(c, out);
10959 break;
10960 case CCTL:
Eric Andersenc470f442003-07-28 09:56:35 +000010961 if (eofmark == NULL || dblquote)
Eric Andersencb57d552001-06-28 07:25:16 +000010962 USTPUTC(CTLESC, out);
Denis Vlasenkoef527f52008-06-23 01:52:30 +000010963#if ENABLE_ASH_BASH_COMPAT
10964 if (c == '\\' && bash_dollar_squote) {
10965 c = decode_dollar_squote();
10966 if (c & 0x100) {
10967 USTPUTC('\\', out);
10968 c = (unsigned char)c;
10969 }
10970 }
10971#endif
Eric Andersencb57d552001-06-28 07:25:16 +000010972 USTPUTC(c, out);
10973 break;
Eric Andersenc470f442003-07-28 09:56:35 +000010974 case CBACK: /* backslash */
Denys Vlasenko2ce42e92009-11-29 02:18:13 +010010975 c = pgetc_without_PEOA();
Eric Andersencb57d552001-06-28 07:25:16 +000010976 if (c == PEOF) {
Eric Andersenc470f442003-07-28 09:56:35 +000010977 USTPUTC(CTLESC, out);
Eric Andersencb57d552001-06-28 07:25:16 +000010978 USTPUTC('\\', out);
10979 pungetc();
10980 } else if (c == '\n') {
10981 if (doprompt)
10982 setprompt(2);
Eric Andersencb57d552001-06-28 07:25:16 +000010983 } else {
Denis Vlasenko46a53062007-09-24 18:30:02 +000010984#if ENABLE_ASH_EXPAND_PRMT
10985 if (c == '$' && pssyntax) {
10986 USTPUTC(CTLESC, out);
10987 USTPUTC('\\', out);
10988 }
10989#endif
Denis Vlasenkoef527f52008-06-23 01:52:30 +000010990 if (dblquote && c != '\\'
10991 && c != '`' && c != '$'
10992 && (c != '"' || eofmark != NULL)
Eric Andersenc470f442003-07-28 09:56:35 +000010993 ) {
10994 USTPUTC(CTLESC, out);
Eric Andersencb57d552001-06-28 07:25:16 +000010995 USTPUTC('\\', out);
Eric Andersenc470f442003-07-28 09:56:35 +000010996 }
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010997 if (SIT(c, SQSYNTAX) == CCTL)
Eric Andersencb57d552001-06-28 07:25:16 +000010998 USTPUTC(CTLESC, out);
Eric Andersencb57d552001-06-28 07:25:16 +000010999 USTPUTC(c, out);
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011000 quotef = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000011001 }
11002 break;
11003 case CSQUOTE:
Eric Andersencb57d552001-06-28 07:25:16 +000011004 syntax = SQSYNTAX;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011005 quotemark:
Eric Andersenc470f442003-07-28 09:56:35 +000011006 if (eofmark == NULL) {
11007 USTPUTC(CTLQUOTEMARK, out);
11008 }
Eric Andersencb57d552001-06-28 07:25:16 +000011009 break;
11010 case CDQUOTE:
Eric Andersencb57d552001-06-28 07:25:16 +000011011 syntax = DQSYNTAX;
11012 dblquote = 1;
Eric Andersenc470f442003-07-28 09:56:35 +000011013 goto quotemark;
Eric Andersencb57d552001-06-28 07:25:16 +000011014 case CENDQUOTE:
Denis Vlasenko5e34ff22009-04-21 11:09:40 +000011015 IF_ASH_BASH_COMPAT(bash_dollar_squote = 0;)
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011016 if (eofmark != NULL && arinest == 0
11017 && varnest == 0
11018 ) {
Eric Andersencb57d552001-06-28 07:25:16 +000011019 USTPUTC(c, out);
11020 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000011021 if (dqvarnest == 0) {
Eric Andersencb57d552001-06-28 07:25:16 +000011022 syntax = BASESYNTAX;
11023 dblquote = 0;
11024 }
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011025 quotef = 1;
Eric Andersenc470f442003-07-28 09:56:35 +000011026 goto quotemark;
Eric Andersencb57d552001-06-28 07:25:16 +000011027 }
11028 break;
Eric Andersenc470f442003-07-28 09:56:35 +000011029 case CVAR: /* '$' */
11030 PARSESUB(); /* parse substitution */
Eric Andersencb57d552001-06-28 07:25:16 +000011031 break;
Eric Andersenc470f442003-07-28 09:56:35 +000011032 case CENDVAR: /* '}' */
Eric Andersencb57d552001-06-28 07:25:16 +000011033 if (varnest > 0) {
11034 varnest--;
11035 if (dqvarnest > 0) {
11036 dqvarnest--;
11037 }
11038 USTPUTC(CTLENDVAR, out);
11039 } else {
11040 USTPUTC(c, out);
11041 }
11042 break;
Mike Frysinger98c52642009-04-02 10:02:37 +000011043#if ENABLE_SH_MATH_SUPPORT
Eric Andersenc470f442003-07-28 09:56:35 +000011044 case CLP: /* '(' in arithmetic */
Eric Andersencb57d552001-06-28 07:25:16 +000011045 parenlevel++;
11046 USTPUTC(c, out);
11047 break;
Eric Andersenc470f442003-07-28 09:56:35 +000011048 case CRP: /* ')' in arithmetic */
Eric Andersencb57d552001-06-28 07:25:16 +000011049 if (parenlevel > 0) {
11050 USTPUTC(c, out);
11051 --parenlevel;
11052 } else {
11053 if (pgetc() == ')') {
11054 if (--arinest == 0) {
11055 USTPUTC(CTLENDARI, out);
11056 syntax = prevsyntax;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011057 dblquote = (syntax == DQSYNTAX);
Eric Andersencb57d552001-06-28 07:25:16 +000011058 } else
11059 USTPUTC(')', out);
11060 } else {
11061 /*
11062 * unbalanced parens
11063 * (don't 2nd guess - no error)
11064 */
11065 pungetc();
11066 USTPUTC(')', out);
11067 }
11068 }
11069 break;
11070#endif
Eric Andersenc470f442003-07-28 09:56:35 +000011071 case CBQUOTE: /* '`' */
Eric Andersencb57d552001-06-28 07:25:16 +000011072 PARSEBACKQOLD();
11073 break;
Eric Andersen2870d962001-07-02 17:27:21 +000011074 case CENDFILE:
Eric Andersenc470f442003-07-28 09:56:35 +000011075 goto endword; /* exit outer loop */
Eric Andersencb57d552001-06-28 07:25:16 +000011076 case CIGN:
11077 break;
11078 default:
Denis Vlasenko834dee72008-10-07 09:18:30 +000011079 if (varnest == 0) {
11080#if ENABLE_ASH_BASH_COMPAT
11081 if (c == '&') {
11082 if (pgetc() == '>')
11083 c = 0x100 + '>'; /* flag &> */
11084 pungetc();
11085 }
11086#endif
Eric Andersenc470f442003-07-28 09:56:35 +000011087 goto endword; /* exit outer loop */
Denis Vlasenko834dee72008-10-07 09:18:30 +000011088 }
Denys Vlasenko2ce42e92009-11-29 02:18:13 +010011089 IF_ASH_ALIAS(if (c != PEOA))
Eric Andersencb57d552001-06-28 07:25:16 +000011090 USTPUTC(c, out);
Eric Andersen3102ac42001-07-06 04:26:23 +000011091
Eric Andersencb57d552001-06-28 07:25:16 +000011092 }
Denis Vlasenko834dee72008-10-07 09:18:30 +000011093 c = pgetc_fast();
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000011094 } /* for (;;) */
Eric Andersencb57d552001-06-28 07:25:16 +000011095 }
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011096 endword:
Mike Frysinger98c52642009-04-02 10:02:37 +000011097#if ENABLE_SH_MATH_SUPPORT
Eric Andersencb57d552001-06-28 07:25:16 +000011098 if (syntax == ARISYNTAX)
Denis Vlasenko559691a2008-10-05 18:39:31 +000011099 raise_error_syntax("missing '))'");
Eric Andersenc470f442003-07-28 09:56:35 +000011100#endif
Denis Vlasenko99eb8502007-02-23 21:09:49 +000011101 if (syntax != BASESYNTAX && !parsebackquote && eofmark == NULL)
Denis Vlasenko559691a2008-10-05 18:39:31 +000011102 raise_error_syntax("unterminated quoted string");
Eric Andersencb57d552001-06-28 07:25:16 +000011103 if (varnest != 0) {
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011104 startlinno = g_parsefile->linno;
Eric Andersenc470f442003-07-28 09:56:35 +000011105 /* { */
Denis Vlasenko559691a2008-10-05 18:39:31 +000011106 raise_error_syntax("missing '}'");
Eric Andersencb57d552001-06-28 07:25:16 +000011107 }
11108 USTPUTC('\0', out);
Eric Andersenc470f442003-07-28 09:56:35 +000011109 len = out - (char *)stackblock();
Eric Andersencb57d552001-06-28 07:25:16 +000011110 out = stackblock();
11111 if (eofmark == NULL) {
Denis Vlasenko5e34ff22009-04-21 11:09:40 +000011112 if ((c == '>' || c == '<' IF_ASH_BASH_COMPAT( || c == 0x100 + '>'))
Denis Vlasenko834dee72008-10-07 09:18:30 +000011113 && quotef == 0
11114 ) {
Denis Vlasenko559691a2008-10-05 18:39:31 +000011115 if (isdigit_str9(out)) {
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000011116 PARSEREDIR(); /* passed as params: out, c */
11117 lasttoken = TREDIR;
11118 return lasttoken;
11119 }
11120 /* else: non-number X seen, interpret it
11121 * as "NNNX>file" = "NNNX >file" */
Eric Andersencb57d552001-06-28 07:25:16 +000011122 }
Denis Vlasenkoef527f52008-06-23 01:52:30 +000011123 pungetc();
Eric Andersencb57d552001-06-28 07:25:16 +000011124 }
11125 quoteflag = quotef;
11126 backquotelist = bqlist;
11127 grabstackblock(len);
11128 wordtext = out;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011129 lasttoken = TWORD;
11130 return lasttoken;
Eric Andersencb57d552001-06-28 07:25:16 +000011131/* end of readtoken routine */
11132
Eric Andersencb57d552001-06-28 07:25:16 +000011133/*
11134 * Check to see whether we are at the end of the here document. When this
11135 * is called, c is set to the first character of the next input line. If
11136 * we are at the end of the here document, this routine sets the c to PEOF.
11137 */
Eric Andersenc470f442003-07-28 09:56:35 +000011138checkend: {
11139 if (eofmark) {
Denis Vlasenko131ae172007-02-18 13:00:19 +000011140#if ENABLE_ASH_ALIAS
Denys Vlasenko2ce42e92009-11-29 02:18:13 +010011141 if (c == PEOA)
11142 c = pgetc_without_PEOA();
Eric Andersenc470f442003-07-28 09:56:35 +000011143#endif
11144 if (striptabs) {
11145 while (c == '\t') {
Denys Vlasenko2ce42e92009-11-29 02:18:13 +010011146 c = pgetc_without_PEOA();
Eric Andersencb57d552001-06-28 07:25:16 +000011147 }
Eric Andersenc470f442003-07-28 09:56:35 +000011148 }
11149 if (c == *eofmark) {
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011150 if (pfgets(line, sizeof(line)) != NULL) {
Eric Andersenc470f442003-07-28 09:56:35 +000011151 char *p, *q;
Eric Andersencb57d552001-06-28 07:25:16 +000011152
Eric Andersenc470f442003-07-28 09:56:35 +000011153 p = line;
Denis Vlasenkof7d56652008-03-25 05:51:41 +000011154 for (q = eofmark + 1; *q && *p == *q; p++, q++)
11155 continue;
Eric Andersenc470f442003-07-28 09:56:35 +000011156 if (*p == '\n' && *q == '\0') {
11157 c = PEOF;
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011158 g_parsefile->linno++;
Eric Andersenc470f442003-07-28 09:56:35 +000011159 needprompt = doprompt;
11160 } else {
11161 pushstring(line, NULL);
Eric Andersencb57d552001-06-28 07:25:16 +000011162 }
11163 }
11164 }
11165 }
Eric Andersenc470f442003-07-28 09:56:35 +000011166 goto checkend_return;
11167}
Eric Andersencb57d552001-06-28 07:25:16 +000011168
Eric Andersencb57d552001-06-28 07:25:16 +000011169/*
11170 * Parse a redirection operator. The variable "out" points to a string
11171 * specifying the fd to be redirected. The variable "c" contains the
11172 * first character of the redirection operator.
11173 */
Eric Andersenc470f442003-07-28 09:56:35 +000011174parseredir: {
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000011175 /* out is already checked to be a valid number or "" */
11176 int fd = (*out == '\0' ? -1 : atoi(out));
Eric Andersenc470f442003-07-28 09:56:35 +000011177 union node *np;
Eric Andersencb57d552001-06-28 07:25:16 +000011178
Denis Vlasenko597906c2008-02-20 16:38:54 +000011179 np = stzalloc(sizeof(struct nfile));
Eric Andersenc470f442003-07-28 09:56:35 +000011180 if (c == '>') {
11181 np->nfile.fd = 1;
11182 c = pgetc();
11183 if (c == '>')
11184 np->type = NAPPEND;
11185 else if (c == '|')
11186 np->type = NCLOBBER;
11187 else if (c == '&')
11188 np->type = NTOFD;
Denis Vlasenko559691a2008-10-05 18:39:31 +000011189 /* it also can be NTO2 (>&file), but we can't figure it out yet */
Eric Andersenc470f442003-07-28 09:56:35 +000011190 else {
11191 np->type = NTO;
11192 pungetc();
Eric Andersencb57d552001-06-28 07:25:16 +000011193 }
Denis Vlasenko834dee72008-10-07 09:18:30 +000011194 }
11195#if ENABLE_ASH_BASH_COMPAT
11196 else if (c == 0x100 + '>') { /* this flags &> redirection */
11197 np->nfile.fd = 1;
11198 pgetc(); /* this is '>', no need to check */
11199 np->type = NTO2;
11200 }
11201#endif
11202 else { /* c == '<' */
Denis Vlasenko597906c2008-02-20 16:38:54 +000011203 /*np->nfile.fd = 0; - stzalloc did it */
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011204 c = pgetc();
11205 switch (c) {
Eric Andersenc470f442003-07-28 09:56:35 +000011206 case '<':
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011207 if (sizeof(struct nfile) != sizeof(struct nhere)) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000011208 np = stzalloc(sizeof(struct nhere));
11209 /*np->nfile.fd = 0; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000011210 }
11211 np->type = NHERE;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000011212 heredoc = stzalloc(sizeof(struct heredoc));
Eric Andersenc470f442003-07-28 09:56:35 +000011213 heredoc->here = np;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011214 c = pgetc();
11215 if (c == '-') {
Eric Andersenc470f442003-07-28 09:56:35 +000011216 heredoc->striptabs = 1;
11217 } else {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000011218 /*heredoc->striptabs = 0; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000011219 pungetc();
11220 }
11221 break;
11222
11223 case '&':
11224 np->type = NFROMFD;
11225 break;
11226
11227 case '>':
11228 np->type = NFROMTO;
11229 break;
11230
11231 default:
11232 np->type = NFROM;
11233 pungetc();
11234 break;
11235 }
Eric Andersencb57d552001-06-28 07:25:16 +000011236 }
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000011237 if (fd >= 0)
11238 np->nfile.fd = fd;
Eric Andersenc470f442003-07-28 09:56:35 +000011239 redirnode = np;
11240 goto parseredir_return;
11241}
Eric Andersencb57d552001-06-28 07:25:16 +000011242
Eric Andersencb57d552001-06-28 07:25:16 +000011243/*
11244 * Parse a substitution. At this point, we have read the dollar sign
11245 * and nothing else.
11246 */
Denis Vlasenkocc571512007-02-23 21:10:35 +000011247
11248/* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
11249 * (assuming ascii char codes, as the original implementation did) */
11250#define is_special(c) \
Denis Vlasenkoef527f52008-06-23 01:52:30 +000011251 (((unsigned)(c) - 33 < 32) \
11252 && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
Eric Andersenc470f442003-07-28 09:56:35 +000011253parsesub: {
Denys Vlasenkocd716832009-11-28 22:14:02 +010011254 unsigned char subtype;
Eric Andersenc470f442003-07-28 09:56:35 +000011255 int typeloc;
11256 int flags;
11257 char *p;
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011258 static const char types[] ALIGN1 = "}-+?=";
Eric Andersencb57d552001-06-28 07:25:16 +000011259
Eric Andersenc470f442003-07-28 09:56:35 +000011260 c = pgetc();
Denys Vlasenkocd716832009-11-28 22:14:02 +010011261 if (c > 255 /* PEOA or PEOF */
Denis Vlasenkoef527f52008-06-23 01:52:30 +000011262 || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
Eric Andersenc470f442003-07-28 09:56:35 +000011263 ) {
Denis Vlasenkoef527f52008-06-23 01:52:30 +000011264#if ENABLE_ASH_BASH_COMPAT
11265 if (c == '\'')
11266 bash_dollar_squote = 1;
11267 else
11268#endif
11269 USTPUTC('$', out);
Eric Andersenc470f442003-07-28 09:56:35 +000011270 pungetc();
11271 } else if (c == '(') { /* $(command) or $((arith)) */
11272 if (pgetc() == '(') {
Mike Frysinger98c52642009-04-02 10:02:37 +000011273#if ENABLE_SH_MATH_SUPPORT
Eric Andersenc470f442003-07-28 09:56:35 +000011274 PARSEARITH();
11275#else
Mike Frysinger98a6f562008-06-09 09:38:45 +000011276 raise_error_syntax("you disabled math support for $((arith)) syntax");
Eric Andersenc470f442003-07-28 09:56:35 +000011277#endif
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000011278 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000011279 pungetc();
11280 PARSEBACKQNEW();
11281 }
11282 } else {
11283 USTPUTC(CTLVAR, out);
11284 typeloc = out - (char *)stackblock();
11285 USTPUTC(VSNORMAL, out);
11286 subtype = VSNORMAL;
11287 if (c == '{') {
11288 c = pgetc();
11289 if (c == '#') {
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011290 c = pgetc();
11291 if (c == '}')
Eric Andersenc470f442003-07-28 09:56:35 +000011292 c = '#';
11293 else
11294 subtype = VSLENGTH;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011295 } else
Eric Andersenc470f442003-07-28 09:56:35 +000011296 subtype = 0;
11297 }
Denys Vlasenkocd716832009-11-28 22:14:02 +010011298 if (c <= 255 /* not PEOA or PEOF */ && is_name(c)) {
Eric Andersenc470f442003-07-28 09:56:35 +000011299 do {
11300 STPUTC(c, out);
Eric Andersencb57d552001-06-28 07:25:16 +000011301 c = pgetc();
Denys Vlasenkocd716832009-11-28 22:14:02 +010011302 } while (c <= 255 /* not PEOA or PEOF */ && is_in_name(c));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011303 } else if (isdigit(c)) {
Eric Andersenc470f442003-07-28 09:56:35 +000011304 do {
11305 STPUTC(c, out);
11306 c = pgetc();
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011307 } while (isdigit(c));
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011308 } else if (is_special(c)) {
Eric Andersenc470f442003-07-28 09:56:35 +000011309 USTPUTC(c, out);
11310 c = pgetc();
Denis Vlasenko559691a2008-10-05 18:39:31 +000011311 } else {
11312 badsub:
11313 raise_error_syntax("bad substitution");
11314 }
Cristian Ionescu-Idbohrn301f5ec2009-10-05 02:07:23 +020011315 if (c != '}' && subtype == VSLENGTH)
11316 goto badsub;
Eric Andersencb57d552001-06-28 07:25:16 +000011317
Eric Andersenc470f442003-07-28 09:56:35 +000011318 STPUTC('=', out);
11319 flags = 0;
11320 if (subtype == 0) {
11321 switch (c) {
11322 case ':':
Eric Andersenc470f442003-07-28 09:56:35 +000011323 c = pgetc();
Denis Vlasenko92e13c22008-03-25 01:17:40 +000011324#if ENABLE_ASH_BASH_COMPAT
11325 if (c == ':' || c == '$' || isdigit(c)) {
11326 pungetc();
11327 subtype = VSSUBSTR;
11328 break;
11329 }
11330#endif
11331 flags = VSNUL;
Eric Andersenc470f442003-07-28 09:56:35 +000011332 /*FALLTHROUGH*/
11333 default:
11334 p = strchr(types, c);
11335 if (p == NULL)
11336 goto badsub;
11337 subtype = p - types + VSNORMAL;
11338 break;
11339 case '%':
Denis Vlasenko92e13c22008-03-25 01:17:40 +000011340 case '#': {
11341 int cc = c;
11342 subtype = c == '#' ? VSTRIMLEFT : VSTRIMRIGHT;
11343 c = pgetc();
11344 if (c == cc)
11345 subtype++;
11346 else
11347 pungetc();
11348 break;
11349 }
11350#if ENABLE_ASH_BASH_COMPAT
11351 case '/':
11352 subtype = VSREPLACE;
11353 c = pgetc();
11354 if (c == '/')
11355 subtype++; /* VSREPLACEALL */
11356 else
11357 pungetc();
11358 break;
11359#endif
Eric Andersencb57d552001-06-28 07:25:16 +000011360 }
Eric Andersenc470f442003-07-28 09:56:35 +000011361 } else {
11362 pungetc();
11363 }
11364 if (dblquote || arinest)
11365 flags |= VSQUOTE;
Denys Vlasenkocd716832009-11-28 22:14:02 +010011366 ((unsigned char *)stackblock())[typeloc] = subtype | flags;
Eric Andersenc470f442003-07-28 09:56:35 +000011367 if (subtype != VSNORMAL) {
11368 varnest++;
11369 if (dblquote || arinest) {
11370 dqvarnest++;
Eric Andersencb57d552001-06-28 07:25:16 +000011371 }
11372 }
11373 }
Eric Andersenc470f442003-07-28 09:56:35 +000011374 goto parsesub_return;
11375}
Eric Andersencb57d552001-06-28 07:25:16 +000011376
Eric Andersencb57d552001-06-28 07:25:16 +000011377/*
11378 * Called to parse command substitutions. Newstyle is set if the command
11379 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
11380 * list of commands (passed by reference), and savelen is the number of
11381 * characters on the top of the stack which must be preserved.
11382 */
Eric Andersenc470f442003-07-28 09:56:35 +000011383parsebackq: {
11384 struct nodelist **nlpp;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011385 smallint savepbq;
Eric Andersenc470f442003-07-28 09:56:35 +000011386 union node *n;
11387 char *volatile str;
11388 struct jmploc jmploc;
11389 struct jmploc *volatile savehandler;
11390 size_t savelen;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011391 smallint saveprompt = 0;
11392
Eric Andersencb57d552001-06-28 07:25:16 +000011393#ifdef __GNUC__
Eric Andersenc470f442003-07-28 09:56:35 +000011394 (void) &saveprompt;
Eric Andersencb57d552001-06-28 07:25:16 +000011395#endif
Eric Andersenc470f442003-07-28 09:56:35 +000011396 savepbq = parsebackquote;
11397 if (setjmp(jmploc.loc)) {
Denis Vlasenko60818682007-09-28 22:07:23 +000011398 free(str);
Eric Andersenc470f442003-07-28 09:56:35 +000011399 parsebackquote = 0;
Denis Vlasenko2da584f2007-02-19 22:44:05 +000011400 exception_handler = savehandler;
11401 longjmp(exception_handler->loc, 1);
Eric Andersenc470f442003-07-28 09:56:35 +000011402 }
Denis Vlasenkob012b102007-02-19 22:43:01 +000011403 INT_OFF;
Eric Andersenc470f442003-07-28 09:56:35 +000011404 str = NULL;
11405 savelen = out - (char *)stackblock();
11406 if (savelen > 0) {
11407 str = ckmalloc(savelen);
11408 memcpy(str, stackblock(), savelen);
11409 }
Denis Vlasenko2da584f2007-02-19 22:44:05 +000011410 savehandler = exception_handler;
11411 exception_handler = &jmploc;
Denis Vlasenkob012b102007-02-19 22:43:01 +000011412 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +000011413 if (oldstyle) {
11414 /* We must read until the closing backquote, giving special
11415 treatment to some slashes, and then push the string and
11416 reread it as input, interpreting it normally. */
11417 char *pout;
11418 int pc;
11419 size_t psavelen;
11420 char *pstr;
11421
11422
11423 STARTSTACKSTR(pout);
11424 for (;;) {
11425 if (needprompt) {
11426 setprompt(2);
Eric Andersenc470f442003-07-28 09:56:35 +000011427 }
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011428 pc = pgetc();
11429 switch (pc) {
Eric Andersenc470f442003-07-28 09:56:35 +000011430 case '`':
11431 goto done;
11432
11433 case '\\':
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011434 pc = pgetc();
11435 if (pc == '\n') {
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011436 g_parsefile->linno++;
Eric Andersenc470f442003-07-28 09:56:35 +000011437 if (doprompt)
11438 setprompt(2);
11439 /*
11440 * If eating a newline, avoid putting
11441 * the newline into the new character
11442 * stream (via the STPUTC after the
11443 * switch).
11444 */
11445 continue;
11446 }
11447 if (pc != '\\' && pc != '`' && pc != '$'
Denys Vlasenko76bc2d62009-11-29 01:37:46 +010011448 && (!dblquote || pc != '"')
11449 ) {
Eric Andersenc470f442003-07-28 09:56:35 +000011450 STPUTC('\\', pout);
Denys Vlasenko76bc2d62009-11-29 01:37:46 +010011451 }
Denys Vlasenkocd716832009-11-28 22:14:02 +010011452 if (pc <= 255 /* not PEOA or PEOF */) {
Eric Andersenc470f442003-07-28 09:56:35 +000011453 break;
11454 }
11455 /* fall through */
11456
11457 case PEOF:
Denys Vlasenko2ce42e92009-11-29 02:18:13 +010011458 IF_ASH_ALIAS(case PEOA:)
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011459 startlinno = g_parsefile->linno;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000011460 raise_error_syntax("EOF in backquote substitution");
Eric Andersenc470f442003-07-28 09:56:35 +000011461
11462 case '\n':
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011463 g_parsefile->linno++;
Eric Andersenc470f442003-07-28 09:56:35 +000011464 needprompt = doprompt;
11465 break;
11466
11467 default:
11468 break;
11469 }
11470 STPUTC(pc, pout);
11471 }
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011472 done:
Eric Andersenc470f442003-07-28 09:56:35 +000011473 STPUTC('\0', pout);
11474 psavelen = pout - (char *)stackblock();
11475 if (psavelen > 0) {
11476 pstr = grabstackstr(pout);
11477 setinputstring(pstr);
11478 }
11479 }
11480 nlpp = &bqlist;
11481 while (*nlpp)
11482 nlpp = &(*nlpp)->next;
Denis Vlasenko597906c2008-02-20 16:38:54 +000011483 *nlpp = stzalloc(sizeof(**nlpp));
11484 /* (*nlpp)->next = NULL; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000011485 parsebackquote = oldstyle;
11486
11487 if (oldstyle) {
11488 saveprompt = doprompt;
11489 doprompt = 0;
Eric Andersencb57d552001-06-28 07:25:16 +000011490 }
11491
Eric Andersenc470f442003-07-28 09:56:35 +000011492 n = list(2);
11493
11494 if (oldstyle)
11495 doprompt = saveprompt;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011496 else if (readtoken() != TRP)
11497 raise_error_unexpected_syntax(TRP);
Eric Andersenc470f442003-07-28 09:56:35 +000011498
11499 (*nlpp)->n = n;
11500 if (oldstyle) {
11501 /*
11502 * Start reading from old file again, ignoring any pushed back
11503 * tokens left from the backquote parsing
11504 */
11505 popfile();
11506 tokpushback = 0;
11507 }
11508 while (stackblocksize() <= savelen)
11509 growstackblock();
11510 STARTSTACKSTR(out);
11511 if (str) {
11512 memcpy(out, str, savelen);
11513 STADJUST(savelen, out);
Denis Vlasenkob012b102007-02-19 22:43:01 +000011514 INT_OFF;
11515 free(str);
Eric Andersenc470f442003-07-28 09:56:35 +000011516 str = NULL;
Denis Vlasenkob012b102007-02-19 22:43:01 +000011517 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +000011518 }
11519 parsebackquote = savepbq;
Denis Vlasenko2da584f2007-02-19 22:44:05 +000011520 exception_handler = savehandler;
Eric Andersenc470f442003-07-28 09:56:35 +000011521 if (arinest || dblquote)
11522 USTPUTC(CTLBACKQ | CTLQUOTE, out);
11523 else
11524 USTPUTC(CTLBACKQ, out);
11525 if (oldstyle)
11526 goto parsebackq_oldreturn;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000011527 goto parsebackq_newreturn;
Eric Andersenc470f442003-07-28 09:56:35 +000011528}
11529
Mike Frysinger98c52642009-04-02 10:02:37 +000011530#if ENABLE_SH_MATH_SUPPORT
Eric Andersencb57d552001-06-28 07:25:16 +000011531/*
11532 * Parse an arithmetic expansion (indicate start of one and set state)
11533 */
Eric Andersenc470f442003-07-28 09:56:35 +000011534parsearith: {
Eric Andersenc470f442003-07-28 09:56:35 +000011535 if (++arinest == 1) {
11536 prevsyntax = syntax;
11537 syntax = ARISYNTAX;
11538 USTPUTC(CTLARI, out);
11539 if (dblquote)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000011540 USTPUTC('"', out);
Eric Andersenc470f442003-07-28 09:56:35 +000011541 else
Denis Vlasenkoa624c112007-02-19 22:45:43 +000011542 USTPUTC(' ', out);
Eric Andersenc470f442003-07-28 09:56:35 +000011543 } else {
11544 /*
11545 * we collapse embedded arithmetic expansion to
11546 * parenthesis, which should be equivalent
11547 */
11548 USTPUTC('(', out);
Eric Andersencb57d552001-06-28 07:25:16 +000011549 }
Eric Andersenc470f442003-07-28 09:56:35 +000011550 goto parsearith_return;
11551}
11552#endif
Eric Andersencb57d552001-06-28 07:25:16 +000011553
Eric Andersenc470f442003-07-28 09:56:35 +000011554} /* end of readtoken */
11555
Eric Andersencb57d552001-06-28 07:25:16 +000011556/*
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011557 * Read the next input token.
11558 * If the token is a word, we set backquotelist to the list of cmds in
11559 * backquotes. We set quoteflag to true if any part of the word was
11560 * quoted.
11561 * If the token is TREDIR, then we set redirnode to a structure containing
11562 * the redirection.
11563 * In all cases, the variable startlinno is set to the number of the line
11564 * on which the token starts.
11565 *
11566 * [Change comment: here documents and internal procedures]
11567 * [Readtoken shouldn't have any arguments. Perhaps we should make the
11568 * word parsing code into a separate routine. In this case, readtoken
11569 * doesn't need to have any internal procedures, but parseword does.
11570 * We could also make parseoperator in essence the main routine, and
11571 * have parseword (readtoken1?) handle both words and redirection.]
Eric Andersencb57d552001-06-28 07:25:16 +000011572 */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011573#define NEW_xxreadtoken
11574#ifdef NEW_xxreadtoken
11575/* singles must be first! */
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011576static const char xxreadtoken_chars[7] ALIGN1 = {
Denis Vlasenko834dee72008-10-07 09:18:30 +000011577 '\n', '(', ')', /* singles */
11578 '&', '|', ';', /* doubles */
11579 0
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011580};
Eric Andersencb57d552001-06-28 07:25:16 +000011581
Denis Vlasenko834dee72008-10-07 09:18:30 +000011582#define xxreadtoken_singles 3
11583#define xxreadtoken_doubles 3
11584
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011585static const char xxreadtoken_tokens[] ALIGN1 = {
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011586 TNL, TLP, TRP, /* only single occurrence allowed */
11587 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
11588 TEOF, /* corresponds to trailing nul */
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011589 TAND, TOR, TENDCASE /* if double occurrence */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011590};
11591
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011592static int
11593xxreadtoken(void)
11594{
11595 int c;
11596
11597 if (tokpushback) {
11598 tokpushback = 0;
11599 return lasttoken;
Eric Andersencb57d552001-06-28 07:25:16 +000011600 }
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011601 if (needprompt) {
11602 setprompt(2);
11603 }
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011604 startlinno = g_parsefile->linno;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011605 for (;;) { /* until token or start of word found */
Denis Vlasenko834dee72008-10-07 09:18:30 +000011606 c = pgetc_fast();
Denis Vlasenko5e34ff22009-04-21 11:09:40 +000011607 if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011608 continue;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011609
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011610 if (c == '#') {
11611 while ((c = pgetc()) != '\n' && c != PEOF)
11612 continue;
11613 pungetc();
11614 } else if (c == '\\') {
11615 if (pgetc() != '\n') {
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011616 pungetc();
Denis Vlasenko834dee72008-10-07 09:18:30 +000011617 break; /* return readtoken1(...) */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011618 }
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011619 startlinno = ++g_parsefile->linno;
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011620 if (doprompt)
11621 setprompt(2);
11622 } else {
11623 const char *p;
11624
11625 p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
11626 if (c != PEOF) {
11627 if (c == '\n') {
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011628 g_parsefile->linno++;
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011629 needprompt = doprompt;
11630 }
11631
11632 p = strchr(xxreadtoken_chars, c);
Denis Vlasenko834dee72008-10-07 09:18:30 +000011633 if (p == NULL)
11634 break; /* return readtoken1(...) */
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011635
Denis Vlasenko834dee72008-10-07 09:18:30 +000011636 if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
11637 int cc = pgetc();
11638 if (cc == c) { /* double occurrence? */
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011639 p += xxreadtoken_doubles + 1;
11640 } else {
11641 pungetc();
Denis Vlasenko834dee72008-10-07 09:18:30 +000011642#if ENABLE_ASH_BASH_COMPAT
11643 if (c == '&' && cc == '>') /* &> */
11644 break; /* return readtoken1(...) */
11645#endif
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011646 }
11647 }
11648 }
11649 lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
11650 return lasttoken;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011651 }
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011652 } /* for (;;) */
Denis Vlasenko834dee72008-10-07 09:18:30 +000011653
11654 return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011655}
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011656#else /* old xxreadtoken */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011657#define RETURN(token) return lasttoken = token
11658static int
11659xxreadtoken(void)
11660{
11661 int c;
11662
11663 if (tokpushback) {
11664 tokpushback = 0;
11665 return lasttoken;
11666 }
11667 if (needprompt) {
11668 setprompt(2);
11669 }
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011670 startlinno = g_parsefile->linno;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011671 for (;;) { /* until token or start of word found */
Denis Vlasenko834dee72008-10-07 09:18:30 +000011672 c = pgetc_fast();
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011673 switch (c) {
11674 case ' ': case '\t':
Denys Vlasenko2ce42e92009-11-29 02:18:13 +010011675 IF_ASH_ALIAS(case PEOA:)
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011676 continue;
11677 case '#':
Denis Vlasenkof7d56652008-03-25 05:51:41 +000011678 while ((c = pgetc()) != '\n' && c != PEOF)
11679 continue;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011680 pungetc();
11681 continue;
11682 case '\\':
11683 if (pgetc() == '\n') {
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011684 startlinno = ++g_parsefile->linno;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011685 if (doprompt)
11686 setprompt(2);
11687 continue;
11688 }
11689 pungetc();
11690 goto breakloop;
11691 case '\n':
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011692 g_parsefile->linno++;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011693 needprompt = doprompt;
11694 RETURN(TNL);
11695 case PEOF:
11696 RETURN(TEOF);
11697 case '&':
11698 if (pgetc() == '&')
11699 RETURN(TAND);
11700 pungetc();
11701 RETURN(TBACKGND);
11702 case '|':
11703 if (pgetc() == '|')
11704 RETURN(TOR);
11705 pungetc();
11706 RETURN(TPIPE);
11707 case ';':
11708 if (pgetc() == ';')
11709 RETURN(TENDCASE);
11710 pungetc();
11711 RETURN(TSEMI);
11712 case '(':
11713 RETURN(TLP);
11714 case ')':
11715 RETURN(TRP);
11716 default:
11717 goto breakloop;
11718 }
11719 }
11720 breakloop:
11721 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
11722#undef RETURN
11723}
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011724#endif /* old xxreadtoken */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011725
11726static int
11727readtoken(void)
11728{
11729 int t;
11730#if DEBUG
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011731 smallint alreadyseen = tokpushback;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011732#endif
11733
11734#if ENABLE_ASH_ALIAS
11735 top:
11736#endif
11737
11738 t = xxreadtoken();
11739
11740 /*
11741 * eat newlines
11742 */
11743 if (checkkwd & CHKNL) {
11744 while (t == TNL) {
11745 parseheredoc();
11746 t = xxreadtoken();
11747 }
11748 }
11749
11750 if (t != TWORD || quoteflag) {
11751 goto out;
11752 }
11753
11754 /*
11755 * check for keywords
11756 */
11757 if (checkkwd & CHKKWD) {
11758 const char *const *pp;
11759
11760 pp = findkwd(wordtext);
11761 if (pp) {
11762 lasttoken = t = pp - tokname_array;
11763 TRACE(("keyword %s recognized\n", tokname(t)));
11764 goto out;
11765 }
11766 }
11767
11768 if (checkkwd & CHKALIAS) {
11769#if ENABLE_ASH_ALIAS
11770 struct alias *ap;
11771 ap = lookupalias(wordtext, 1);
11772 if (ap != NULL) {
11773 if (*ap->val) {
11774 pushstring(ap->val, ap);
11775 }
11776 goto top;
11777 }
11778#endif
11779 }
11780 out:
11781 checkkwd = 0;
11782#if DEBUG
11783 if (!alreadyseen)
11784 TRACE(("token %s %s\n", tokname(t), t == TWORD ? wordtext : ""));
11785 else
11786 TRACE(("reread token %s %s\n", tokname(t), t == TWORD ? wordtext : ""));
11787#endif
11788 return t;
Eric Andersencb57d552001-06-28 07:25:16 +000011789}
11790
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011791static char
11792peektoken(void)
11793{
11794 int t;
11795
11796 t = readtoken();
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011797 tokpushback = 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011798 return tokname_array[t][0];
11799}
Eric Andersencb57d552001-06-28 07:25:16 +000011800
11801/*
Denys Vlasenko86e83ec2009-07-23 22:07:07 +020011802 * Read and parse a command. Returns NODE_EOF on end of file.
11803 * (NULL is a valid parse tree indicating a blank line.)
Eric Andersencb57d552001-06-28 07:25:16 +000011804 */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011805static union node *
11806parsecmd(int interact)
Eric Andersen90898442003-08-06 11:20:52 +000011807{
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011808 int t;
Eric Andersencb57d552001-06-28 07:25:16 +000011809
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011810 tokpushback = 0;
11811 doprompt = interact;
11812 if (doprompt)
11813 setprompt(doprompt);
11814 needprompt = 0;
11815 t = readtoken();
11816 if (t == TEOF)
Denys Vlasenko86e83ec2009-07-23 22:07:07 +020011817 return NODE_EOF;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011818 if (t == TNL)
11819 return NULL;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011820 tokpushback = 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011821 return list(1);
11822}
11823
11824/*
11825 * Input any here documents.
11826 */
11827static void
11828parseheredoc(void)
11829{
11830 struct heredoc *here;
11831 union node *n;
11832
11833 here = heredoclist;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000011834 heredoclist = NULL;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011835
11836 while (here) {
11837 if (needprompt) {
11838 setprompt(2);
11839 }
11840 readtoken1(pgetc(), here->here->type == NHERE? SQSYNTAX : DQSYNTAX,
11841 here->eofmark, here->striptabs);
Denis Vlasenko597906c2008-02-20 16:38:54 +000011842 n = stzalloc(sizeof(struct narg));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011843 n->narg.type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000011844 /*n->narg.next = NULL; - stzalloc did it */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011845 n->narg.text = wordtext;
11846 n->narg.backquote = backquotelist;
11847 here->here->nhere.doc = n;
11848 here = here->next;
Eric Andersencb57d552001-06-28 07:25:16 +000011849 }
Eric Andersencb57d552001-06-28 07:25:16 +000011850}
11851
11852
11853/*
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +000011854 * called by editline -- any expansions to the prompt should be added here.
Eric Andersencb57d552001-06-28 07:25:16 +000011855 */
Denis Vlasenko131ae172007-02-18 13:00:19 +000011856#if ENABLE_ASH_EXPAND_PRMT
"Vladimir N. Oleynik"bef14d72005-09-05 13:25:11 +000011857static const char *
11858expandstr(const char *ps)
11859{
11860 union node n;
11861
Denis Vlasenko5c2b8142009-03-19 01:59:59 +000011862 /* XXX Fix (char *) cast. It _is_ a bug. ps is variable's value,
11863 * and token processing _can_ alter it (delete NULs etc). */
"Vladimir N. Oleynik"bef14d72005-09-05 13:25:11 +000011864 setinputstring((char *)ps);
Denis Vlasenko46a53062007-09-24 18:30:02 +000011865 readtoken1(pgetc(), PSSYNTAX, nullstr, 0);
"Vladimir N. Oleynik"bef14d72005-09-05 13:25:11 +000011866 popfile();
11867
11868 n.narg.type = NARG;
11869 n.narg.next = NULL;
11870 n.narg.text = wordtext;
11871 n.narg.backquote = backquotelist;
11872
11873 expandarg(&n, NULL, 0);
11874 return stackblock();
11875}
11876#endif
11877
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011878/*
11879 * Execute a command or commands contained in a string.
11880 */
11881static int
11882evalstring(char *s, int mask)
Eric Andersenc470f442003-07-28 09:56:35 +000011883{
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011884 union node *n;
11885 struct stackmark smark;
11886 int skip;
11887
11888 setinputstring(s);
11889 setstackmark(&smark);
11890
11891 skip = 0;
Denys Vlasenko86e83ec2009-07-23 22:07:07 +020011892 while ((n = parsecmd(0)) != NODE_EOF) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011893 evaltree(n, 0);
11894 popstackmark(&smark);
11895 skip = evalskip;
11896 if (skip)
11897 break;
11898 }
11899 popfile();
11900
11901 skip &= mask;
11902 evalskip = skip;
11903 return skip;
Eric Andersenc470f442003-07-28 09:56:35 +000011904}
11905
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011906/*
11907 * The eval command.
11908 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011909static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000011910evalcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011911{
11912 char *p;
11913 char *concat;
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011914
Denis Vlasenko68404f12008-03-17 09:00:54 +000011915 if (argv[1]) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011916 p = argv[1];
Denis Vlasenko68404f12008-03-17 09:00:54 +000011917 argv += 2;
11918 if (argv[0]) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011919 STARTSTACKSTR(concat);
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011920 for (;;) {
11921 concat = stack_putstr(p, concat);
Denis Vlasenko68404f12008-03-17 09:00:54 +000011922 p = *argv++;
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011923 if (p == NULL)
11924 break;
11925 STPUTC(' ', concat);
11926 }
11927 STPUTC('\0', concat);
11928 p = grabstackstr(concat);
11929 }
11930 evalstring(p, ~SKIPEVAL);
11931
11932 }
11933 return exitstatus;
11934}
11935
11936/*
Denys Vlasenko285ad152009-12-04 23:02:27 +010011937 * Read and execute commands.
11938 * "Top" is nonzero for the top level command loop;
11939 * it turns on prompting if the shell is interactive.
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011940 */
11941static int
11942cmdloop(int top)
11943{
11944 union node *n;
11945 struct stackmark smark;
11946 int inter;
11947 int numeof = 0;
11948
11949 TRACE(("cmdloop(%d) called\n", top));
11950 for (;;) {
11951 int skip;
11952
11953 setstackmark(&smark);
11954#if JOBS
Denis Vlasenkob07a4962008-06-22 13:16:23 +000011955 if (doing_jobctl)
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011956 showjobs(stderr, SHOW_CHANGED);
11957#endif
11958 inter = 0;
11959 if (iflag && top) {
11960 inter++;
11961#if ENABLE_ASH_MAIL
11962 chkmail();
11963#endif
11964 }
11965 n = parsecmd(inter);
Denys Vlasenko7cee00e2009-07-24 01:08:03 +020011966#if DEBUG
11967 if (DEBUG > 2 && debug && (n != NODE_EOF))
Denys Vlasenko883cea42009-07-11 15:31:59 +020011968 showtree(n);
Denis Vlasenko135cecb2009-04-12 00:00:57 +000011969#endif
Denys Vlasenko86e83ec2009-07-23 22:07:07 +020011970 if (n == NODE_EOF) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011971 if (!top || numeof >= 50)
11972 break;
11973 if (!stoppedjobs()) {
11974 if (!Iflag)
11975 break;
11976 out2str("\nUse \"exit\" to leave shell.\n");
11977 }
11978 numeof++;
11979 } else if (nflag == 0) {
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +000011980 /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
11981 job_warning >>= 1;
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011982 numeof = 0;
11983 evaltree(n, 0);
11984 }
11985 popstackmark(&smark);
11986 skip = evalskip;
11987
11988 if (skip) {
11989 evalskip = 0;
11990 return skip & SKIPEVAL;
11991 }
11992 }
11993 return 0;
11994}
11995
Denis Vlasenko0dec6de2007-02-23 21:10:47 +000011996/*
11997 * Take commands from a file. To be compatible we should do a path
11998 * search for the file, which is necessary to find sub-commands.
11999 */
12000static char *
12001find_dot_file(char *name)
12002{
12003 char *fullname;
12004 const char *path = pathval();
12005 struct stat statb;
12006
12007 /* don't try this for absolute or relative paths */
12008 if (strchr(name, '/'))
12009 return name;
12010
Denis Vlasenko8ad78e12009-02-15 12:40:30 +000012011 /* IIRC standards do not say whether . is to be searched.
12012 * And it is even smaller this way, making it unconditional for now:
12013 */
12014 if (1) { /* ENABLE_ASH_BASH_COMPAT */
12015 fullname = name;
12016 goto try_cur_dir;
12017 }
12018
Denys Vlasenko82a6fb32009-06-14 19:42:12 +020012019 while ((fullname = path_advance(&path, name)) != NULL) {
Denis Vlasenko8ad78e12009-02-15 12:40:30 +000012020 try_cur_dir:
Denis Vlasenko0dec6de2007-02-23 21:10:47 +000012021 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
12022 /*
12023 * Don't bother freeing here, since it will
12024 * be freed by the caller.
12025 */
12026 return fullname;
12027 }
Denys Vlasenko82a6fb32009-06-14 19:42:12 +020012028 if (fullname != name)
12029 stunalloc(fullname);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +000012030 }
12031
12032 /* not found in the PATH */
12033 ash_msg_and_raise_error("%s: not found", name);
12034 /* NOTREACHED */
12035}
12036
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012037static int FAST_FUNC
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012038dotcmd(int argc, char **argv)
12039{
Denys Vlasenkoe66cf822010-05-18 09:12:53 +020012040 char *fullname;
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012041 struct strlist *sp;
12042 volatile struct shparam saveparam;
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012043
12044 for (sp = cmdenviron; sp; sp = sp->next)
Denis Vlasenko4222ae42007-02-25 02:37:49 +000012045 setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012046
Denys Vlasenkoe66cf822010-05-18 09:12:53 +020012047 if (!argv[1]) {
12048 /* bash says: "bash: .: filename argument required" */
12049 return 2; /* bash compat */
12050 }
12051
Denys Vlasenkocd10dc42010-05-17 17:10:46 +020012052 /* "false; . empty_file; echo $?" should print 0, not 1: */
12053 exitstatus = 0;
12054
Denys Vlasenkoe66cf822010-05-18 09:12:53 +020012055 fullname = find_dot_file(argv[1]);
Denys Vlasenkocd10dc42010-05-17 17:10:46 +020012056
Denys Vlasenkoe66cf822010-05-18 09:12:53 +020012057 argv += 2;
12058 argc -= 2;
12059 if (argc) { /* argc > 0, argv[0] != NULL */
12060 saveparam = shellparam;
12061 shellparam.malloced = 0;
12062 shellparam.nparam = argc;
12063 shellparam.p = argv;
12064 };
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012065
Denys Vlasenkoe66cf822010-05-18 09:12:53 +020012066 setinputfile(fullname, INPUT_PUSH_FILE);
12067 commandname = fullname;
12068 cmdloop(0);
12069 popfile();
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012070
Denys Vlasenkoe66cf822010-05-18 09:12:53 +020012071 if (argc) {
12072 freeparam(&shellparam);
12073 shellparam = saveparam;
12074 };
12075
Denys Vlasenkocd10dc42010-05-17 17:10:46 +020012076 return exitstatus;
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012077}
12078
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012079static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012080exitcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012081{
12082 if (stoppedjobs())
12083 return 0;
Denis Vlasenko68404f12008-03-17 09:00:54 +000012084 if (argv[1])
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012085 exitstatus = number(argv[1]);
12086 raise_exception(EXEXIT);
12087 /* NOTREACHED */
12088}
12089
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012090/*
12091 * Read a file containing shell functions.
12092 */
12093static void
12094readcmdfile(char *name)
12095{
12096 setinputfile(name, INPUT_PUSH_FILE);
12097 cmdloop(0);
12098 popfile();
12099}
12100
12101
Denis Vlasenkocc571512007-02-23 21:10:35 +000012102/* ============ find_command inplementation */
12103
12104/*
12105 * Resolve a command name. If you change this routine, you may have to
12106 * change the shellexec routine as well.
12107 */
12108static void
12109find_command(char *name, struct cmdentry *entry, int act, const char *path)
12110{
12111 struct tblentry *cmdp;
12112 int idx;
12113 int prev;
12114 char *fullname;
12115 struct stat statb;
12116 int e;
12117 int updatetbl;
12118 struct builtincmd *bcmd;
12119
12120 /* If name contains a slash, don't use PATH or hash table */
12121 if (strchr(name, '/') != NULL) {
12122 entry->u.index = -1;
12123 if (act & DO_ABS) {
12124 while (stat(name, &statb) < 0) {
12125#ifdef SYSV
12126 if (errno == EINTR)
12127 continue;
12128#endif
12129 entry->cmdtype = CMDUNKNOWN;
12130 return;
12131 }
12132 }
12133 entry->cmdtype = CMDNORMAL;
12134 return;
12135 }
12136
Denis Vlasenkof20de5b2007-04-29 23:42:54 +000012137/* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
Denis Vlasenkocc571512007-02-23 21:10:35 +000012138
12139 updatetbl = (path == pathval());
12140 if (!updatetbl) {
12141 act |= DO_ALTPATH;
12142 if (strstr(path, "%builtin") != NULL)
12143 act |= DO_ALTBLTIN;
12144 }
12145
12146 /* If name is in the table, check answer will be ok */
12147 cmdp = cmdlookup(name, 0);
12148 if (cmdp != NULL) {
12149 int bit;
12150
12151 switch (cmdp->cmdtype) {
12152 default:
12153#if DEBUG
12154 abort();
12155#endif
12156 case CMDNORMAL:
12157 bit = DO_ALTPATH;
12158 break;
12159 case CMDFUNCTION:
12160 bit = DO_NOFUNC;
12161 break;
12162 case CMDBUILTIN:
12163 bit = DO_ALTBLTIN;
12164 break;
12165 }
12166 if (act & bit) {
12167 updatetbl = 0;
12168 cmdp = NULL;
12169 } else if (cmdp->rehash == 0)
12170 /* if not invalidated by cd, we're done */
12171 goto success;
12172 }
12173
12174 /* If %builtin not in path, check for builtin next */
12175 bcmd = find_builtin(name);
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +000012176 if (bcmd) {
12177 if (IS_BUILTIN_REGULAR(bcmd))
12178 goto builtin_success;
12179 if (act & DO_ALTPATH) {
12180 if (!(act & DO_ALTBLTIN))
12181 goto builtin_success;
12182 } else if (builtinloc <= 0) {
12183 goto builtin_success;
Denis Vlasenko8e858e22007-03-07 09:35:43 +000012184 }
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +000012185 }
Denis Vlasenkocc571512007-02-23 21:10:35 +000012186
Denis Vlasenkof20de5b2007-04-29 23:42:54 +000012187#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko7465dbc2008-04-13 02:25:53 +000012188 {
12189 int applet_no = find_applet_by_name(name);
12190 if (applet_no >= 0) {
12191 entry->cmdtype = CMDNORMAL;
12192 entry->u.index = -2 - applet_no;
12193 return;
12194 }
Denis Vlasenkof20de5b2007-04-29 23:42:54 +000012195 }
12196#endif
12197
Denis Vlasenkocc571512007-02-23 21:10:35 +000012198 /* We have to search path. */
12199 prev = -1; /* where to start */
12200 if (cmdp && cmdp->rehash) { /* doing a rehash */
12201 if (cmdp->cmdtype == CMDBUILTIN)
12202 prev = builtinloc;
12203 else
12204 prev = cmdp->param.index;
12205 }
12206
12207 e = ENOENT;
12208 idx = -1;
12209 loop:
Denys Vlasenko82a6fb32009-06-14 19:42:12 +020012210 while ((fullname = path_advance(&path, name)) != NULL) {
Denis Vlasenkocc571512007-02-23 21:10:35 +000012211 stunalloc(fullname);
Denis Vlasenkodee82b62007-07-29 14:05:27 +000012212 /* NB: code below will still use fullname
12213 * despite it being "unallocated" */
Denis Vlasenkocc571512007-02-23 21:10:35 +000012214 idx++;
12215 if (pathopt) {
12216 if (prefix(pathopt, "builtin")) {
12217 if (bcmd)
12218 goto builtin_success;
12219 continue;
Denis Vlasenko4a9ca132008-04-12 20:07:08 +000012220 }
12221 if ((act & DO_NOFUNC)
12222 || !prefix(pathopt, "func")
12223 ) { /* ignore unimplemented options */
Denis Vlasenkocc571512007-02-23 21:10:35 +000012224 continue;
12225 }
12226 }
12227 /* if rehash, don't redo absolute path names */
12228 if (fullname[0] == '/' && idx <= prev) {
12229 if (idx < prev)
12230 continue;
12231 TRACE(("searchexec \"%s\": no change\n", name));
12232 goto success;
12233 }
12234 while (stat(fullname, &statb) < 0) {
12235#ifdef SYSV
12236 if (errno == EINTR)
12237 continue;
12238#endif
12239 if (errno != ENOENT && errno != ENOTDIR)
12240 e = errno;
12241 goto loop;
12242 }
12243 e = EACCES; /* if we fail, this will be the error */
12244 if (!S_ISREG(statb.st_mode))
12245 continue;
12246 if (pathopt) { /* this is a %func directory */
12247 stalloc(strlen(fullname) + 1);
Denis Vlasenkodee82b62007-07-29 14:05:27 +000012248 /* NB: stalloc will return space pointed by fullname
12249 * (because we don't have any intervening allocations
12250 * between stunalloc above and this stalloc) */
Denis Vlasenkocc571512007-02-23 21:10:35 +000012251 readcmdfile(fullname);
12252 cmdp = cmdlookup(name, 0);
12253 if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
12254 ash_msg_and_raise_error("%s not defined in %s", name, fullname);
12255 stunalloc(fullname);
12256 goto success;
12257 }
12258 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
12259 if (!updatetbl) {
12260 entry->cmdtype = CMDNORMAL;
12261 entry->u.index = idx;
12262 return;
12263 }
12264 INT_OFF;
12265 cmdp = cmdlookup(name, 1);
12266 cmdp->cmdtype = CMDNORMAL;
12267 cmdp->param.index = idx;
12268 INT_ON;
12269 goto success;
12270 }
12271
12272 /* We failed. If there was an entry for this command, delete it */
12273 if (cmdp && updatetbl)
12274 delete_cmd_entry();
12275 if (act & DO_ERR)
12276 ash_msg("%s: %s", name, errmsg(e, "not found"));
12277 entry->cmdtype = CMDUNKNOWN;
12278 return;
12279
12280 builtin_success:
12281 if (!updatetbl) {
12282 entry->cmdtype = CMDBUILTIN;
12283 entry->u.cmd = bcmd;
12284 return;
12285 }
12286 INT_OFF;
12287 cmdp = cmdlookup(name, 1);
12288 cmdp->cmdtype = CMDBUILTIN;
12289 cmdp->param.cmd = bcmd;
12290 INT_ON;
12291 success:
12292 cmdp->rehash = 0;
12293 entry->cmdtype = cmdp->cmdtype;
12294 entry->u = cmdp->param;
12295}
12296
12297
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012298/* ============ trap.c */
Eric Andersenc470f442003-07-28 09:56:35 +000012299
Eric Andersencb57d552001-06-28 07:25:16 +000012300/*
Eric Andersencb57d552001-06-28 07:25:16 +000012301 * The trap builtin.
12302 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012303static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012304trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersencb57d552001-06-28 07:25:16 +000012305{
12306 char *action;
12307 char **ap;
Denys Vlasenko496d5bf2010-03-26 15:52:24 +010012308 int signo, exitcode;
Eric Andersencb57d552001-06-28 07:25:16 +000012309
Eric Andersenc470f442003-07-28 09:56:35 +000012310 nextopt(nullstr);
12311 ap = argptr;
12312 if (!*ap) {
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012313 for (signo = 0; signo < NSIG; signo++) {
Denys Vlasenko21d87d42009-09-25 00:06:51 +020012314 char *tr = trap_ptr[signo];
12315 if (tr) {
Denys Vlasenkoe74aaf92009-09-27 02:05:45 +020012316 /* note: bash adds "SIG", but only if invoked
12317 * as "bash". If called as "sh", or if set -o posix,
12318 * then it prints short signal names.
12319 * We are printing short names: */
12320 out1fmt("trap -- %s %s\n",
Denys Vlasenko21d87d42009-09-25 00:06:51 +020012321 single_quote(tr),
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +000012322 get_signame(signo));
Denys Vlasenko726e1a02009-09-25 02:58:20 +020012323 /* trap_ptr != trap only if we are in special-cased `trap` code.
12324 * In this case, we will exit very soon, no need to free(). */
Denys Vlasenkoe74aaf92009-09-27 02:05:45 +020012325 /* if (trap_ptr != trap && tp[0]) */
Denys Vlasenko726e1a02009-09-25 02:58:20 +020012326 /* free(tr); */
Eric Andersencb57d552001-06-28 07:25:16 +000012327 }
12328 }
Denys Vlasenko726e1a02009-09-25 02:58:20 +020012329 /*
Denys Vlasenko21d87d42009-09-25 00:06:51 +020012330 if (trap_ptr != trap) {
12331 free(trap_ptr);
12332 trap_ptr = trap;
12333 }
Denys Vlasenko726e1a02009-09-25 02:58:20 +020012334 */
Eric Andersencb57d552001-06-28 07:25:16 +000012335 return 0;
12336 }
Denys Vlasenko21d87d42009-09-25 00:06:51 +020012337
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +000012338 action = NULL;
12339 if (ap[1])
Eric Andersencb57d552001-06-28 07:25:16 +000012340 action = *ap++;
Denys Vlasenko496d5bf2010-03-26 15:52:24 +010012341 exitcode = 0;
Eric Andersencb57d552001-06-28 07:25:16 +000012342 while (*ap) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +000012343 signo = get_signum(*ap);
Denys Vlasenko496d5bf2010-03-26 15:52:24 +010012344 if (signo < 0) {
12345 /* Mimic bash message exactly */
12346 ash_msg("%s: invalid signal specification", *ap);
12347 exitcode = 1;
12348 goto next;
12349 }
Denis Vlasenkob012b102007-02-19 22:43:01 +000012350 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +000012351 if (action) {
Denis Vlasenko9f739442006-12-16 23:49:13 +000012352 if (LONE_DASH(action))
Eric Andersencb57d552001-06-28 07:25:16 +000012353 action = NULL;
12354 else
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012355 action = ckstrdup(action);
Eric Andersencb57d552001-06-28 07:25:16 +000012356 }
Denis Vlasenko60818682007-09-28 22:07:23 +000012357 free(trap[signo]);
Denys Vlasenko238bf182010-05-18 15:49:07 +020012358 if (action)
12359 may_have_traps = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000012360 trap[signo] = action;
12361 if (signo != 0)
12362 setsignal(signo);
Denis Vlasenkob012b102007-02-19 22:43:01 +000012363 INT_ON;
Denys Vlasenko496d5bf2010-03-26 15:52:24 +010012364 next:
Eric Andersencb57d552001-06-28 07:25:16 +000012365 ap++;
12366 }
Denys Vlasenko496d5bf2010-03-26 15:52:24 +010012367 return exitcode;
Eric Andersencb57d552001-06-28 07:25:16 +000012368}
12369
Eric Andersenc470f442003-07-28 09:56:35 +000012370
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012371/* ============ Builtins */
Eric Andersenc470f442003-07-28 09:56:35 +000012372
Denis Vlasenko8e1c7152007-01-22 07:21:38 +000012373#if !ENABLE_FEATURE_SH_EXTRA_QUIET
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012374/*
12375 * Lists available builtins
12376 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012377static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012378helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersenc470f442003-07-28 09:56:35 +000012379{
Denis Vlasenko6b06cb82008-05-15 21:30:45 +000012380 unsigned col;
12381 unsigned i;
Eric Andersenc470f442003-07-28 09:56:35 +000012382
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +020012383 out1fmt(
Denis Vlasenko34d4d892009-04-04 20:24:37 +000012384 "Built-in commands:\n"
12385 "------------------\n");
Denis Vlasenkob71c6682007-07-21 15:08:09 +000012386 for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
Eric Andersenc470f442003-07-28 09:56:35 +000012387 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
Denis Vlasenko52764022007-02-24 13:42:56 +000012388 builtintab[i].name + 1);
Eric Andersenc470f442003-07-28 09:56:35 +000012389 if (col > 60) {
12390 out1fmt("\n");
12391 col = 0;
12392 }
12393 }
Denis Vlasenko80d14be2007-04-10 23:03:30 +000012394#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko1aa7e472007-11-28 06:49:03 +000012395 {
12396 const char *a = applet_names;
12397 while (*a) {
12398 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
12399 if (col > 60) {
12400 out1fmt("\n");
12401 col = 0;
12402 }
12403 a += strlen(a) + 1;
Eric Andersenc470f442003-07-28 09:56:35 +000012404 }
12405 }
12406#endif
12407 out1fmt("\n\n");
12408 return EXIT_SUCCESS;
12409}
Denis Vlasenko131ae172007-02-18 13:00:19 +000012410#endif /* FEATURE_SH_EXTRA_QUIET */
Eric Andersenc470f442003-07-28 09:56:35 +000012411
Eric Andersencb57d552001-06-28 07:25:16 +000012412/*
Eric Andersencb57d552001-06-28 07:25:16 +000012413 * The export and readonly commands.
12414 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012415static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012416exportcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +000012417{
12418 struct var *vp;
12419 char *name;
12420 const char *p;
Eric Andersenc470f442003-07-28 09:56:35 +000012421 char **aptr;
Denis Vlasenkob7304742008-10-20 08:15:51 +000012422 int flag = argv[0][0] == 'r' ? VREADONLY : VEXPORT;
Eric Andersencb57d552001-06-28 07:25:16 +000012423
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012424 if (nextopt("p") != 'p') {
12425 aptr = argptr;
12426 name = *aptr;
12427 if (name) {
12428 do {
12429 p = strchr(name, '=');
12430 if (p != NULL) {
12431 p++;
12432 } else {
12433 vp = *findvar(hashvar(name), name);
12434 if (vp) {
12435 vp->flags |= flag;
12436 continue;
12437 }
Eric Andersencb57d552001-06-28 07:25:16 +000012438 }
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012439 setvar(name, p, flag);
12440 } while ((name = *++aptr) != NULL);
12441 return 0;
12442 }
Eric Andersencb57d552001-06-28 07:25:16 +000012443 }
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012444 showvars(argv[0], flag, 0);
Eric Andersencb57d552001-06-28 07:25:16 +000012445 return 0;
12446}
12447
Eric Andersencb57d552001-06-28 07:25:16 +000012448/*
Denis Vlasenko5651bfc2007-02-23 21:08:58 +000012449 * Delete a function if it exists.
Eric Andersencb57d552001-06-28 07:25:16 +000012450 */
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012451static void
Denis Vlasenko5651bfc2007-02-23 21:08:58 +000012452unsetfunc(const char *name)
Aaron Lehmannb6ecbdc2001-12-06 03:37:38 +000012453{
Denis Vlasenko5651bfc2007-02-23 21:08:58 +000012454 struct tblentry *cmdp;
Eric Andersencb57d552001-06-28 07:25:16 +000012455
Denis Vlasenko5651bfc2007-02-23 21:08:58 +000012456 cmdp = cmdlookup(name, 0);
12457 if (cmdp!= NULL && cmdp->cmdtype == CMDFUNCTION)
12458 delete_cmd_entry();
Eric Andersenc470f442003-07-28 09:56:35 +000012459}
12460
Eric Andersencb57d552001-06-28 07:25:16 +000012461/*
Eric Andersencb57d552001-06-28 07:25:16 +000012462 * The unset builtin command. We unset the function before we unset the
12463 * variable to allow a function to be unset when there is a readonly variable
12464 * with the same name.
12465 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012466static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012467unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersencb57d552001-06-28 07:25:16 +000012468{
12469 char **ap;
12470 int i;
Eric Andersenc470f442003-07-28 09:56:35 +000012471 int flag = 0;
Eric Andersencb57d552001-06-28 07:25:16 +000012472 int ret = 0;
12473
12474 while ((i = nextopt("vf")) != '\0') {
Eric Andersenc470f442003-07-28 09:56:35 +000012475 flag = i;
Eric Andersencb57d552001-06-28 07:25:16 +000012476 }
Eric Andersencb57d552001-06-28 07:25:16 +000012477
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012478 for (ap = argptr; *ap; ap++) {
Eric Andersenc470f442003-07-28 09:56:35 +000012479 if (flag != 'f') {
12480 i = unsetvar(*ap);
12481 ret |= i;
12482 if (!(i & 2))
12483 continue;
12484 }
12485 if (flag != 'v')
Eric Andersencb57d552001-06-28 07:25:16 +000012486 unsetfunc(*ap);
Eric Andersencb57d552001-06-28 07:25:16 +000012487 }
Eric Andersenc470f442003-07-28 09:56:35 +000012488 return ret & 1;
Eric Andersencb57d552001-06-28 07:25:16 +000012489}
12490
12491
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +000012492/* setmode.c */
Eric Andersencb57d552001-06-28 07:25:16 +000012493
Eric Andersenc470f442003-07-28 09:56:35 +000012494#include <sys/times.h>
12495
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000012496static const unsigned char timescmd_str[] ALIGN1 = {
Manuel Novoa III 4456f252003-08-13 17:48:47 +000012497 ' ', offsetof(struct tms, tms_utime),
12498 '\n', offsetof(struct tms, tms_stime),
12499 ' ', offsetof(struct tms, tms_cutime),
12500 '\n', offsetof(struct tms, tms_cstime),
12501 0
12502};
Eric Andersencb57d552001-06-28 07:25:16 +000012503
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012504static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012505timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Manuel Novoa III 4456f252003-08-13 17:48:47 +000012506{
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012507 long clk_tck, s, t;
Manuel Novoa III 4456f252003-08-13 17:48:47 +000012508 const unsigned char *p;
12509 struct tms buf;
12510
12511 clk_tck = sysconf(_SC_CLK_TCK);
Eric Andersencb57d552001-06-28 07:25:16 +000012512 times(&buf);
Manuel Novoa III 4456f252003-08-13 17:48:47 +000012513
12514 p = timescmd_str;
12515 do {
12516 t = *(clock_t *)(((char *) &buf) + p[1]);
12517 s = t / clk_tck;
12518 out1fmt("%ldm%ld.%.3lds%c",
12519 s/60, s%60,
12520 ((t - s * clk_tck) * 1000) / clk_tck,
12521 p[0]);
12522 } while (*(p += 2));
12523
Eric Andersencb57d552001-06-28 07:25:16 +000012524 return 0;
12525}
12526
Mike Frysinger98c52642009-04-02 10:02:37 +000012527#if ENABLE_SH_MATH_SUPPORT
Eric Andersenc470f442003-07-28 09:56:35 +000012528/*
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +000012529 * The let builtin. partial stolen from GNU Bash, the Bourne Again SHell.
12530 * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
Eric Andersen90898442003-08-06 11:20:52 +000012531 *
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +000012532 * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
Eric Andersenc470f442003-07-28 09:56:35 +000012533 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012534static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012535letcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersenc470f442003-07-28 09:56:35 +000012536{
Denis Vlasenko68404f12008-03-17 09:00:54 +000012537 arith_t i;
Eric Andersenc470f442003-07-28 09:56:35 +000012538
Denis Vlasenko68404f12008-03-17 09:00:54 +000012539 argv++;
12540 if (!*argv)
Denis Vlasenkob012b102007-02-19 22:43:01 +000012541 ash_msg_and_raise_error("expression expected");
Denis Vlasenko68404f12008-03-17 09:00:54 +000012542 do {
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +000012543 i = ash_arith(*argv);
Denis Vlasenko68404f12008-03-17 09:00:54 +000012544 } while (*++argv);
Eric Andersenc470f442003-07-28 09:56:35 +000012545
Denis Vlasenkod9e15f22006-11-27 16:49:55 +000012546 return !i;
Eric Andersenc470f442003-07-28 09:56:35 +000012547}
Mike Frysinger98c52642009-04-02 10:02:37 +000012548#endif /* SH_MATH_SUPPORT */
Eric Andersenc470f442003-07-28 09:56:35 +000012549
Eric Andersenc470f442003-07-28 09:56:35 +000012550
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012551/* ============ miscbltin.c
12552 *
Eric Andersenaff114c2004-04-14 17:51:38 +000012553 * Miscellaneous builtins.
Eric Andersenc470f442003-07-28 09:56:35 +000012554 */
12555
12556#undef rflag
12557
Denis Vlasenko83e5d6f2006-12-18 21:49:06 +000012558#if defined(__GLIBC__) && __GLIBC__ == 2 && __GLIBC_MINOR__ < 1
Eric Andersenc470f442003-07-28 09:56:35 +000012559typedef enum __rlimit_resource rlim_t;
12560#endif
Eric Andersen74bcd162001-07-30 21:41:37 +000012561
Eric Andersenc470f442003-07-28 09:56:35 +000012562/*
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012563 * The read builtin. Options:
12564 * -r Do not interpret '\' specially
12565 * -s Turn off echo (tty only)
12566 * -n NCHARS Read NCHARS max
12567 * -p PROMPT Display PROMPT on stderr (if input is from tty)
12568 * -t SECONDS Timeout after SECONDS (tty or pipe only)
12569 * -u FD Read from given FD instead of fd 0
Eric Andersenc470f442003-07-28 09:56:35 +000012570 * This uses unbuffered input, which may be avoidable in some cases.
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012571 * TODO: bash also has:
12572 * -a ARRAY Read into array[0],[1],etc
12573 * -d DELIM End on DELIM char, not newline
12574 * -e Use line editing (tty only)
Eric Andersenc470f442003-07-28 09:56:35 +000012575 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012576static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012577readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersenc470f442003-07-28 09:56:35 +000012578{
Denys Vlasenko73067272010-01-12 22:11:24 +010012579 char *opt_n = NULL;
12580 char *opt_p = NULL;
12581 char *opt_t = NULL;
12582 char *opt_u = NULL;
12583 int read_flags = 0;
12584 const char *r;
Eric Andersenc470f442003-07-28 09:56:35 +000012585 int i;
12586
Denys Vlasenko73067272010-01-12 22:11:24 +010012587 while ((i = nextopt("p:u:rt:n:s")) != '\0') {
Denis Vlasenkobf0a2012006-12-26 10:42:51 +000012588 switch (i) {
Paul Fox02eb9342005-09-07 16:56:02 +000012589 case 'p':
Denys Vlasenko73067272010-01-12 22:11:24 +010012590 opt_p = optionarg;
Paul Fox02eb9342005-09-07 16:56:02 +000012591 break;
Paul Fox02eb9342005-09-07 16:56:02 +000012592 case 'n':
Denys Vlasenko73067272010-01-12 22:11:24 +010012593 opt_n = optionarg;
Paul Fox02eb9342005-09-07 16:56:02 +000012594 break;
12595 case 's':
Denys Vlasenko73067272010-01-12 22:11:24 +010012596 read_flags |= BUILTIN_READ_SILENT;
Paul Fox02eb9342005-09-07 16:56:02 +000012597 break;
Paul Fox02eb9342005-09-07 16:56:02 +000012598 case 't':
Denys Vlasenko73067272010-01-12 22:11:24 +010012599 opt_t = optionarg;
Paul Fox02eb9342005-09-07 16:56:02 +000012600 break;
Paul Fox02eb9342005-09-07 16:56:02 +000012601 case 'r':
Denys Vlasenko73067272010-01-12 22:11:24 +010012602 read_flags |= BUILTIN_READ_RAW;
Paul Fox02eb9342005-09-07 16:56:02 +000012603 break;
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012604 case 'u':
Denys Vlasenko73067272010-01-12 22:11:24 +010012605 opt_u = optionarg;
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012606 break;
Paul Fox02eb9342005-09-07 16:56:02 +000012607 default:
12608 break;
12609 }
Eric Andersenc470f442003-07-28 09:56:35 +000012610 }
Paul Fox02eb9342005-09-07 16:56:02 +000012611
Denys Vlasenko03dad222010-01-12 23:29:57 +010012612 r = shell_builtin_read(setvar2,
Denys Vlasenko73067272010-01-12 22:11:24 +010012613 argptr,
12614 bltinlookup("IFS"), /* can be NULL */
12615 read_flags,
12616 opt_n,
12617 opt_p,
12618 opt_t,
12619 opt_u
12620 );
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012621
Denys Vlasenko73067272010-01-12 22:11:24 +010012622 if ((uintptr_t)r > 1)
12623 ash_msg_and_raise_error(r);
Denis Vlasenko037576d2007-10-20 18:30:38 +000012624
Denys Vlasenko73067272010-01-12 22:11:24 +010012625 return (uintptr_t)r;
Eric Andersenc470f442003-07-28 09:56:35 +000012626}
12627
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012628static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012629umaskcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersenc470f442003-07-28 09:56:35 +000012630{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000012631 static const char permuser[3] ALIGN1 = "ugo";
12632 static const char permmode[3] ALIGN1 = "rwx";
12633 static const short permmask[] ALIGN2 = {
Eric Andersenc470f442003-07-28 09:56:35 +000012634 S_IRUSR, S_IWUSR, S_IXUSR,
12635 S_IRGRP, S_IWGRP, S_IXGRP,
12636 S_IROTH, S_IWOTH, S_IXOTH
12637 };
12638
Denis Vlasenkoeb858492009-04-18 02:06:54 +000012639 /* TODO: use bb_parse_mode() instead */
12640
Eric Andersenc470f442003-07-28 09:56:35 +000012641 char *ap;
12642 mode_t mask;
12643 int i;
12644 int symbolic_mode = 0;
12645
12646 while (nextopt("S") != '\0') {
12647 symbolic_mode = 1;
12648 }
12649
Denis Vlasenkob012b102007-02-19 22:43:01 +000012650 INT_OFF;
Eric Andersenc470f442003-07-28 09:56:35 +000012651 mask = umask(0);
12652 umask(mask);
Denis Vlasenkob012b102007-02-19 22:43:01 +000012653 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +000012654
Denis Vlasenko5cedb752007-02-18 19:56:41 +000012655 ap = *argptr;
12656 if (ap == NULL) {
Eric Andersenc470f442003-07-28 09:56:35 +000012657 if (symbolic_mode) {
12658 char buf[18];
12659 char *p = buf;
12660
12661 for (i = 0; i < 3; i++) {
12662 int j;
12663
12664 *p++ = permuser[i];
12665 *p++ = '=';
12666 for (j = 0; j < 3; j++) {
12667 if ((mask & permmask[3 * i + j]) == 0) {
12668 *p++ = permmode[j];
12669 }
12670 }
12671 *p++ = ',';
12672 }
12673 *--p = 0;
12674 puts(buf);
12675 } else {
12676 out1fmt("%.4o\n", mask);
12677 }
12678 } else {
Denis Vlasenkoaa744452007-02-23 01:04:22 +000012679 if (isdigit((unsigned char) *ap)) {
Eric Andersenc470f442003-07-28 09:56:35 +000012680 mask = 0;
12681 do {
12682 if (*ap >= '8' || *ap < '0')
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +020012683 ash_msg_and_raise_error(msg_illnum, argv[1]);
Eric Andersenc470f442003-07-28 09:56:35 +000012684 mask = (mask << 3) + (*ap - '0');
12685 } while (*++ap != '\0');
12686 umask(mask);
12687 } else {
12688 mask = ~mask & 0777;
12689 if (!bb_parse_mode(ap, &mask)) {
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +000012690 ash_msg_and_raise_error("illegal mode: %s", ap);
Eric Andersenc470f442003-07-28 09:56:35 +000012691 }
12692 umask(~mask & 0777);
12693 }
12694 }
12695 return 0;
12696}
12697
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012698static int FAST_FUNC
Denys Vlasenkof3c742f2010-03-06 20:12:00 +010012699ulimitcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersenc470f442003-07-28 09:56:35 +000012700{
Denys Vlasenkof3c742f2010-03-06 20:12:00 +010012701 return shell_builtin_ulimit(argv);
Eric Andersenc470f442003-07-28 09:56:35 +000012702}
12703
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012704/* ============ main() and helpers */
12705
12706/*
12707 * Called to exit the shell.
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012708 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012709static void exitshell(void) NORETURN;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012710static void
12711exitshell(void)
12712{
12713 struct jmploc loc;
12714 char *p;
12715 int status;
12716
12717 status = exitstatus;
12718 TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
12719 if (setjmp(loc.loc)) {
Denis Vlasenko7f88e342009-03-19 03:36:18 +000012720 if (exception_type == EXEXIT)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012721/* dash bug: it just does _exit(exitstatus) here
12722 * but we have to do setjobctl(0) first!
12723 * (bug is still not fixed in dash-0.5.3 - if you run dash
12724 * under Midnight Commander, on exit from dash MC is backgrounded) */
12725 status = exitstatus;
12726 goto out;
12727 }
12728 exception_handler = &loc;
12729 p = trap[0];
12730 if (p) {
12731 trap[0] = NULL;
12732 evalstring(p, 0);
Denys Vlasenko0800e3a2009-09-24 03:09:26 +020012733 free(p);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012734 }
12735 flush_stdout_stderr();
12736 out:
12737 setjobctl(0);
12738 _exit(status);
12739 /* NOTREACHED */
12740}
12741
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012742static void
12743init(void)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012744{
12745 /* from input.c: */
Denys Vlasenko82dd14a2010-05-17 10:10:01 +020012746 /* we will never free this */
12747 basepf.next_to_pgetc = basepf.buf = ckmalloc(IBUFSIZ);
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012748
12749 /* from trap.c: */
12750 signal(SIGCHLD, SIG_DFL);
Denys Vlasenko7a7b0342009-12-04 04:18:31 +010012751 /* bash re-enables SIGHUP which is SIG_IGNed on entry.
12752 * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
12753 */
12754 signal(SIGHUP, SIG_DFL);
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012755
12756 /* from var.c: */
12757 {
12758 char **envp;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012759 const char *p;
12760 struct stat st1, st2;
12761
12762 initvar();
12763 for (envp = environ; envp && *envp; envp++) {
12764 if (strchr(*envp, '=')) {
12765 setvareq(*envp, VEXPORT|VTEXTFIXED);
12766 }
12767 }
12768
Denys Vlasenko7bb346f2009-10-06 22:09:50 +020012769 setvar("PPID", utoa(getppid()), 0);
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012770
12771 p = lookupvar("PWD");
12772 if (p)
12773 if (*p != '/' || stat(p, &st1) || stat(".", &st2)
12774 || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino)
12775 p = '\0';
12776 setpwd(p, 0);
12777 }
12778}
12779
12780/*
12781 * Process the shell command line arguments.
12782 */
12783static void
Denis Vlasenko68404f12008-03-17 09:00:54 +000012784procargs(char **argv)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012785{
12786 int i;
12787 const char *xminusc;
12788 char **xargv;
12789
12790 xargv = argv;
12791 arg0 = xargv[0];
Denis Vlasenko68404f12008-03-17 09:00:54 +000012792 /* if (xargv[0]) - mmm, this is always true! */
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012793 xargv++;
12794 for (i = 0; i < NOPTS; i++)
12795 optlist[i] = 2;
12796 argptr = xargv;
Denis Vlasenko28bf6712008-02-14 15:01:47 +000012797 if (options(1)) {
12798 /* it already printed err message */
12799 raise_exception(EXERROR);
12800 }
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012801 xargv = argptr;
12802 xminusc = minusc;
12803 if (*xargv == NULL) {
12804 if (xminusc)
12805 ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
12806 sflag = 1;
12807 }
12808 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
12809 iflag = 1;
12810 if (mflag == 2)
12811 mflag = iflag;
12812 for (i = 0; i < NOPTS; i++)
12813 if (optlist[i] == 2)
12814 optlist[i] = 0;
12815#if DEBUG == 2
12816 debug = 1;
12817#endif
12818 /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
12819 if (xminusc) {
12820 minusc = *xargv++;
12821 if (*xargv)
12822 goto setarg0;
12823 } else if (!sflag) {
12824 setinputfile(*xargv, 0);
12825 setarg0:
12826 arg0 = *xargv++;
12827 commandname = arg0;
12828 }
12829
12830 shellparam.p = xargv;
12831#if ENABLE_ASH_GETOPTS
12832 shellparam.optind = 1;
12833 shellparam.optoff = -1;
12834#endif
Denis Vlasenko01631112007-12-16 17:20:38 +000012835 /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012836 while (*xargv) {
12837 shellparam.nparam++;
12838 xargv++;
12839 }
12840 optschanged();
12841}
12842
12843/*
12844 * Read /etc/profile or .profile.
12845 */
12846static void
12847read_profile(const char *name)
12848{
12849 int skip;
12850
12851 if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
12852 return;
12853 skip = cmdloop(0);
12854 popfile();
12855 if (skip)
12856 exitshell();
12857}
12858
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012859/*
12860 * This routine is called when an error or an interrupt occurs in an
12861 * interactive shell and control is returned to the main command loop.
12862 */
12863static void
12864reset(void)
12865{
12866 /* from eval.c: */
12867 evalskip = 0;
12868 loopnest = 0;
12869 /* from input.c: */
Denis Vlasenko41eb3002008-11-28 03:42:31 +000012870 g_parsefile->left_in_buffer = 0;
12871 g_parsefile->left_in_line = 0; /* clear input buffer */
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012872 popallfiles();
12873 /* from parser.c: */
12874 tokpushback = 0;
12875 checkkwd = 0;
12876 /* from redir.c: */
Denis Vlasenko34c73c42008-08-16 11:48:02 +000012877 clearredir(/*drop:*/ 0);
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012878}
12879
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012880#if PROFILE
12881static short profile_buf[16384];
12882extern int etext();
12883#endif
12884
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012885/*
12886 * Main routine. We initialize things, parse the arguments, execute
12887 * profiles if we're a login shell, and then call cmdloop to execute
12888 * commands. The setjmp call sets up the location to jump to when an
12889 * exception occurs. When an exception occurs the variable "state"
12890 * is used to figure out how far we had gotten.
12891 */
Denis Vlasenko9b49a5e2007-10-11 10:05:36 +000012892int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012893int ash_main(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012894{
Mike Frysinger98c52642009-04-02 10:02:37 +000012895 const char *shinit;
Denis Vlasenko4e12b1a2008-12-23 23:36:47 +000012896 volatile smallint state;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012897 struct jmploc jmploc;
12898 struct stackmark smark;
12899
Denis Vlasenko01631112007-12-16 17:20:38 +000012900 /* Initialize global data */
12901 INIT_G_misc();
12902 INIT_G_memstack();
12903 INIT_G_var();
Denis Vlasenkoee87ebf2007-12-21 22:18:16 +000012904#if ENABLE_ASH_ALIAS
Denis Vlasenko01631112007-12-16 17:20:38 +000012905 INIT_G_alias();
Denis Vlasenkoee87ebf2007-12-21 22:18:16 +000012906#endif
Denis Vlasenko01631112007-12-16 17:20:38 +000012907 INIT_G_cmdtable();
12908
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012909#if PROFILE
12910 monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
12911#endif
12912
12913#if ENABLE_FEATURE_EDITING
12914 line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
12915#endif
12916 state = 0;
12917 if (setjmp(jmploc.loc)) {
Denis Vlasenko7f88e342009-03-19 03:36:18 +000012918 smallint e;
Denis Vlasenko4e12b1a2008-12-23 23:36:47 +000012919 smallint s;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012920
12921 reset();
12922
Denis Vlasenko7f88e342009-03-19 03:36:18 +000012923 e = exception_type;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012924 if (e == EXERROR)
12925 exitstatus = 2;
12926 s = state;
12927 if (e == EXEXIT || s == 0 || iflag == 0 || shlvl)
12928 exitshell();
Denis Vlasenko7f88e342009-03-19 03:36:18 +000012929 if (e == EXINT)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012930 outcslow('\n', stderr);
Denis Vlasenko7f88e342009-03-19 03:36:18 +000012931
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012932 popstackmark(&smark);
12933 FORCE_INT_ON; /* enable interrupts */
12934 if (s == 1)
12935 goto state1;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000012936 if (s == 2)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012937 goto state2;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000012938 if (s == 3)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012939 goto state3;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000012940 goto state4;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012941 }
12942 exception_handler = &jmploc;
12943#if DEBUG
12944 opentrace();
Denis Vlasenko653d8e72009-03-19 21:59:35 +000012945 TRACE(("Shell args: "));
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000012946 trace_puts_args(argv);
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012947#endif
12948 rootpid = getpid();
12949
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012950 init();
12951 setstackmark(&smark);
Denis Vlasenko68404f12008-03-17 09:00:54 +000012952 procargs(argv);
12953
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012954#if ENABLE_FEATURE_EDITING_SAVEHISTORY
12955 if (iflag) {
12956 const char *hp = lookupvar("HISTFILE");
12957
12958 if (hp == NULL) {
12959 hp = lookupvar("HOME");
12960 if (hp != NULL) {
12961 char *defhp = concat_path_file(hp, ".ash_history");
12962 setvar("HISTFILE", defhp, 0);
12963 free(defhp);
12964 }
12965 }
12966 }
12967#endif
Denis Vlasenko4e12b1a2008-12-23 23:36:47 +000012968 if (/* argv[0] && */ argv[0][0] == '-')
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012969 isloginsh = 1;
12970 if (isloginsh) {
12971 state = 1;
12972 read_profile("/etc/profile");
12973 state1:
12974 state = 2;
12975 read_profile(".profile");
12976 }
12977 state2:
12978 state = 3;
12979 if (
12980#ifndef linux
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012981 getuid() == geteuid() && getgid() == getegid() &&
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012982#endif
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012983 iflag
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012984 ) {
12985 shinit = lookupvar("ENV");
12986 if (shinit != NULL && *shinit != '\0') {
12987 read_profile(shinit);
12988 }
12989 }
12990 state3:
12991 state = 4;
Denis Vlasenko5c2b8142009-03-19 01:59:59 +000012992 if (minusc) {
12993 /* evalstring pushes parsefile stack.
12994 * Ensure we don't falsely claim that 0 (stdin)
Denis Vlasenko5368ad52009-03-20 10:20:08 +000012995 * is one of stacked source fds.
12996 * Testcase: ash -c 'exec 1>&0' must not complain. */
Denis Vlasenko5c2b8142009-03-19 01:59:59 +000012997 if (!sflag)
12998 g_parsefile->fd = -1;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012999 evalstring(minusc, 0);
Denis Vlasenko5c2b8142009-03-19 01:59:59 +000013000 }
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013001
13002 if (sflag || minusc == NULL) {
Denys Vlasenko0337e032009-11-29 00:12:30 +010013003#if defined MAX_HISTORY && MAX_HISTORY > 0 && ENABLE_FEATURE_EDITING_SAVEHISTORY
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +000013004 if (iflag) {
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013005 const char *hp = lookupvar("HISTFILE");
Denis Vlasenko5c2b8142009-03-19 01:59:59 +000013006 if (hp)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013007 line_input_state->hist_file = hp;
13008 }
13009#endif
13010 state4: /* XXX ??? - why isn't this before the "if" statement */
13011 cmdloop(1);
13012 }
13013#if PROFILE
13014 monitor(0);
13015#endif
13016#ifdef GPROF
13017 {
13018 extern void _mcleanup(void);
13019 _mcleanup();
13020 }
13021#endif
13022 exitshell();
13023 /* NOTREACHED */
13024}
13025
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013026
Eric Andersendf82f612001-06-28 07:46:40 +000013027/*-
13028 * Copyright (c) 1989, 1991, 1993, 1994
Eric Andersen2870d962001-07-02 17:27:21 +000013029 * The Regents of the University of California. All rights reserved.
Eric Andersendf82f612001-06-28 07:46:40 +000013030 *
13031 * This code is derived from software contributed to Berkeley by
13032 * Kenneth Almquist.
13033 *
13034 * Redistribution and use in source and binary forms, with or without
13035 * modification, are permitted provided that the following conditions
13036 * are met:
13037 * 1. Redistributions of source code must retain the above copyright
13038 * notice, this list of conditions and the following disclaimer.
13039 * 2. Redistributions in binary form must reproduce the above copyright
13040 * notice, this list of conditions and the following disclaimer in the
13041 * documentation and/or other materials provided with the distribution.
"Vladimir N. Oleynik"ddc280e2005-12-15 12:01:49 +000013042 * 3. Neither the name of the University nor the names of its contributors
Eric Andersendf82f612001-06-28 07:46:40 +000013043 * may be used to endorse or promote products derived from this software
13044 * without specific prior written permission.
13045 *
13046 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
13047 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
13048 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
13049 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
13050 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
13051 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
13052 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
13053 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
13054 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
13055 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
13056 * SUCH DAMAGE.
13057 */