blob: f581b5bdf63bc415d44c6f83be8afa218fa0e1e6 [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 Vlasenko1aa7e472007-11-28 06:49:03 +000039#include "busybox.h" /* for applet_names */
Denis Vlasenkob012b102007-02-19 22:43:01 +000040#include <paths.h>
41#include <setjmp.h>
42#include <fnmatch.h>
Denys Vlasenko1ed2fb42010-06-18 14:09:48 +020043#include <sys/times.h>
Denys Vlasenko73067272010-01-12 22:11:24 +010044
45#include "shell_common.h"
Mike Frysinger98c52642009-04-02 10:02:37 +000046#include "math.h"
Denys Vlasenko3ea2e822009-10-09 20:59:04 +020047#if ENABLE_ASH_RANDOM_SUPPORT
48# include "random.h"
Denys Vlasenko36df0482009-10-19 16:07:28 +020049#else
50# define CLEAR_RANDOM_T(rnd) ((void)0)
Denys Vlasenko3ea2e822009-10-09 20:59:04 +020051#endif
Denis Vlasenko61befda2008-11-25 01:36:03 +000052
Denys Vlasenko14974842010-03-23 01:08:26 +010053#define SKIP_definitions 1
54#include "applet_tables.h"
55#undef SKIP_definitions
56#if NUM_APPLETS == 1
Denis Vlasenko61befda2008-11-25 01:36:03 +000057/* STANDALONE does not make sense, and won't compile */
Denys Vlasenko3ea2e822009-10-09 20:59:04 +020058# undef CONFIG_FEATURE_SH_STANDALONE
59# undef ENABLE_FEATURE_SH_STANDALONE
60# undef IF_FEATURE_SH_STANDALONE
Denys Vlasenko14974842010-03-23 01:08:26 +010061# undef IF_NOT_FEATURE_SH_STANDALONE
Denys Vlasenko3ea2e822009-10-09 20:59:04 +020062# define ENABLE_FEATURE_SH_STANDALONE 0
63# define IF_FEATURE_SH_STANDALONE(...)
64# define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
Eric Andersencb57d552001-06-28 07:25:16 +000065#endif
66
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000067#ifndef PIPE_BUF
Denis Vlasenko653d8e72009-03-19 21:59:35 +000068# define PIPE_BUF 4096 /* amount of buffering in a pipe */
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000069#endif
70
Denys Vlasenko153fcaa2010-02-21 05:17:41 +010071#if !BB_MMU
Denis Vlasenko653d8e72009-03-19 21:59:35 +000072# error "Do not even bother, ash will not run on NOMMU machine"
Denis Vlasenkob012b102007-02-19 22:43:01 +000073#endif
74
Denis Vlasenkob012b102007-02-19 22:43:01 +000075
Denis Vlasenko01631112007-12-16 17:20:38 +000076/* ============ Hash table sizes. Configurable. */
77
78#define VTABSIZE 39
79#define ATABSIZE 39
80#define CMDTABLESIZE 31 /* should be prime */
81
82
Denis Vlasenkob012b102007-02-19 22:43:01 +000083/* ============ Shell options */
84
85static const char *const optletters_optnames[] = {
86 "e" "errexit",
87 "f" "noglob",
88 "I" "ignoreeof",
89 "i" "interactive",
90 "m" "monitor",
91 "n" "noexec",
92 "s" "stdin",
93 "x" "xtrace",
94 "v" "verbose",
95 "C" "noclobber",
96 "a" "allexport",
97 "b" "notify",
98 "u" "nounset",
Denys Vlasenkoe9ac32a2009-12-05 02:01:25 +010099 "\0" "vi"
Michael Abbott359da5e2009-12-04 23:03:29 +0100100#if ENABLE_ASH_BASH_COMPAT
Denys Vlasenkoe9ac32a2009-12-05 02:01:25 +0100101 ,"\0" "pipefail"
Michael Abbott359da5e2009-12-04 23:03:29 +0100102#endif
Denis Vlasenkob012b102007-02-19 22:43:01 +0000103#if DEBUG
Denis Vlasenko6ca409e2007-08-12 20:58:27 +0000104 ,"\0" "nolog"
105 ,"\0" "debug"
Denis Vlasenkob012b102007-02-19 22:43:01 +0000106#endif
107};
108
Denys Vlasenko285ad152009-12-04 23:02:27 +0100109#define optletters(n) optletters_optnames[n][0]
110#define optnames(n) (optletters_optnames[n] + 1)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000111
Denis Vlasenko80b8b392007-06-25 10:55:35 +0000112enum { NOPTS = ARRAY_SIZE(optletters_optnames) };
Denis Vlasenkob012b102007-02-19 22:43:01 +0000113
Eric Andersenc470f442003-07-28 09:56:35 +0000114
Denis Vlasenkob012b102007-02-19 22:43:01 +0000115/* ============ Misc data */
Eric Andersenc470f442003-07-28 09:56:35 +0000116
Denys Vlasenkoea8b2522010-06-02 12:57:26 +0200117#define msg_illnum "Illegal number: %s"
Denis Vlasenkoaa744452007-02-23 01:04:22 +0000118
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +0000119/*
Eric Andersenc470f442003-07-28 09:56:35 +0000120 * We enclose jmp_buf in a structure so that we can declare pointers to
121 * jump locations. The global variable handler contains the location to
Denis Vlasenkof1733952009-03-19 23:21:55 +0000122 * jump to when an exception occurs, and the global variable exception_type
Eric Andersenaff114c2004-04-14 17:51:38 +0000123 * contains a code identifying the exception. To implement nested
Eric Andersenc470f442003-07-28 09:56:35 +0000124 * exception handlers, the user should save the value of handler on entry
125 * to an inner scope, set handler to point to a jmploc structure for the
126 * inner scope, and restore handler on exit from the scope.
127 */
Eric Andersenc470f442003-07-28 09:56:35 +0000128struct jmploc {
129 jmp_buf loc;
130};
Denis Vlasenko01631112007-12-16 17:20:38 +0000131
132struct globals_misc {
133 /* pid of main shell */
134 int rootpid;
135 /* shell level: 0 for the main shell, 1 for its children, and so on */
136 int shlvl;
137#define rootshell (!shlvl)
138 char *minusc; /* argument to -c option */
139
140 char *curdir; // = nullstr; /* current working directory */
141 char *physdir; // = nullstr; /* physical working directory */
142
143 char *arg0; /* value of $0 */
144
145 struct jmploc *exception_handler;
Denis Vlasenko991a1da2008-02-10 19:02:53 +0000146
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200147 volatile int suppress_int; /* counter */
148 volatile /*sig_atomic_t*/ smallint pending_int; /* 1 = got SIGINT */
Denis Vlasenko991a1da2008-02-10 19:02:53 +0000149 /* last pending signal */
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200150 volatile /*sig_atomic_t*/ smallint pending_sig;
Denis Vlasenko7f88e342009-03-19 03:36:18 +0000151 smallint exception_type; /* kind of exception (0..5) */
Denis Vlasenko01631112007-12-16 17:20:38 +0000152 /* exceptions */
Eric Andersenc470f442003-07-28 09:56:35 +0000153#define EXINT 0 /* SIGINT received */
154#define EXERROR 1 /* a generic error */
155#define EXSHELLPROC 2 /* execute a shell procedure */
156#define EXEXEC 3 /* command execution failed */
157#define EXEXIT 4 /* exit the shell */
158#define EXSIG 5 /* trapped signal in wait(1) */
Eric Andersen2870d962001-07-02 17:27:21 +0000159
Denis Vlasenko01631112007-12-16 17:20:38 +0000160 smallint isloginsh;
Denis Vlasenkob07a4962008-06-22 13:16:23 +0000161 char nullstr[1]; /* zero length string */
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000162
163 char optlist[NOPTS];
164#define eflag optlist[0]
165#define fflag optlist[1]
166#define Iflag optlist[2]
167#define iflag optlist[3]
168#define mflag optlist[4]
169#define nflag optlist[5]
170#define sflag optlist[6]
171#define xflag optlist[7]
172#define vflag optlist[8]
173#define Cflag optlist[9]
174#define aflag optlist[10]
175#define bflag optlist[11]
176#define uflag optlist[12]
177#define viflag optlist[13]
Michael Abbott359da5e2009-12-04 23:03:29 +0100178#if ENABLE_ASH_BASH_COMPAT
179# define pipefail optlist[14]
180#else
181# define pipefail 0
182#endif
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000183#if DEBUG
Michael Abbott359da5e2009-12-04 23:03:29 +0100184# define nolog optlist[14 + ENABLE_ASH_BASH_COMPAT]
185# define debug optlist[15 + ENABLE_ASH_BASH_COMPAT]
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000186#endif
187
188 /* trap handler commands */
Denis Vlasenko01631112007-12-16 17:20:38 +0000189 /*
190 * Sigmode records the current value of the signal handlers for the various
191 * modes. A value of zero means that the current handler is not known.
Denis Vlasenkof8535cc2008-12-03 10:36:26 +0000192 * S_HARD_IGN indicates that the signal was ignored on entry to the shell.
Denis Vlasenko01631112007-12-16 17:20:38 +0000193 */
194 char sigmode[NSIG - 1];
Denis Vlasenkof8535cc2008-12-03 10:36:26 +0000195#define S_DFL 1 /* default signal handling (SIG_DFL) */
196#define S_CATCH 2 /* signal is caught */
197#define S_IGN 3 /* signal is ignored (SIG_IGN) */
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +0000198#define S_HARD_IGN 4 /* signal is ignored permenantly */
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +0000199
Denis Vlasenko01631112007-12-16 17:20:38 +0000200 /* indicates specified signal received */
Denis Vlasenko4b875702009-03-19 13:30:04 +0000201 uint8_t gotsig[NSIG - 1]; /* offset by 1: "signal" 0 is meaningless */
Denys Vlasenko238bf182010-05-18 15:49:07 +0200202 uint8_t may_have_traps; /* 0: definitely no traps are set, 1: some traps may be set */
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000203 char *trap[NSIG];
Denys Vlasenko21d87d42009-09-25 00:06:51 +0200204 char **trap_ptr; /* used only by "trap hack" */
Denis Vlasenko448d30e2008-06-27 00:24:11 +0000205
206 /* Rarely referenced stuff */
207#if ENABLE_ASH_RANDOM_SUPPORT
Denys Vlasenko3ea2e822009-10-09 20:59:04 +0200208 random_t random_gen;
Denis Vlasenko448d30e2008-06-27 00:24:11 +0000209#endif
210 pid_t backgndpid; /* pid of last background process */
211 smallint job_warning; /* user was warned about stopped jobs (can be 2, 1 or 0). */
Denis Vlasenko01631112007-12-16 17:20:38 +0000212};
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000213extern struct globals_misc *const ash_ptr_to_globals_misc;
214#define G_misc (*ash_ptr_to_globals_misc)
Denis Vlasenko26bc57d2008-06-27 00:29:34 +0000215#define rootpid (G_misc.rootpid )
216#define shlvl (G_misc.shlvl )
217#define minusc (G_misc.minusc )
218#define curdir (G_misc.curdir )
219#define physdir (G_misc.physdir )
220#define arg0 (G_misc.arg0 )
Denis Vlasenko01631112007-12-16 17:20:38 +0000221#define exception_handler (G_misc.exception_handler)
Denis Vlasenko7f88e342009-03-19 03:36:18 +0000222#define exception_type (G_misc.exception_type )
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200223#define suppress_int (G_misc.suppress_int )
224#define pending_int (G_misc.pending_int )
225#define pending_sig (G_misc.pending_sig )
Denis Vlasenko26bc57d2008-06-27 00:29:34 +0000226#define isloginsh (G_misc.isloginsh )
227#define nullstr (G_misc.nullstr )
228#define optlist (G_misc.optlist )
229#define sigmode (G_misc.sigmode )
230#define gotsig (G_misc.gotsig )
Denys Vlasenko238bf182010-05-18 15:49:07 +0200231#define may_have_traps (G_misc.may_have_traps )
Denis Vlasenko26bc57d2008-06-27 00:29:34 +0000232#define trap (G_misc.trap )
Denys Vlasenko21d87d42009-09-25 00:06:51 +0200233#define trap_ptr (G_misc.trap_ptr )
Denys Vlasenko3ea2e822009-10-09 20:59:04 +0200234#define random_gen (G_misc.random_gen )
Denis Vlasenko448d30e2008-06-27 00:24:11 +0000235#define backgndpid (G_misc.backgndpid )
236#define job_warning (G_misc.job_warning)
Denis Vlasenko01631112007-12-16 17:20:38 +0000237#define INIT_G_misc() do { \
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000238 (*(struct globals_misc**)&ash_ptr_to_globals_misc) = xzalloc(sizeof(G_misc)); \
239 barrier(); \
Denis Vlasenko01631112007-12-16 17:20:38 +0000240 curdir = nullstr; \
241 physdir = nullstr; \
Denys Vlasenko21d87d42009-09-25 00:06:51 +0200242 trap_ptr = trap; \
Denis Vlasenko01631112007-12-16 17:20:38 +0000243} while (0)
244
245
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000246/* ============ DEBUG */
247#if DEBUG
248static void trace_printf(const char *fmt, ...);
249static void trace_vprintf(const char *fmt, va_list va);
250# define TRACE(param) trace_printf param
251# define TRACEV(param) trace_vprintf param
Denis Vlasenko1bb3d7e2009-03-20 07:45:36 +0000252# define close(fd) do { \
253 int dfd = (fd); \
Denis Vlasenkob9e70dd2009-03-20 01:24:08 +0000254 if (close(dfd) < 0) \
Denys Vlasenko883cea42009-07-11 15:31:59 +0200255 bb_error_msg("bug on %d: closing %d(0x%x)", \
Denis Vlasenko1bb3d7e2009-03-20 07:45:36 +0000256 __LINE__, dfd, dfd); \
Denis Vlasenkob9e70dd2009-03-20 01:24:08 +0000257} while (0)
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000258#else
259# define TRACE(param)
260# define TRACEV(param)
261#endif
262
263
Denis Vlasenko559691a2008-10-05 18:39:31 +0000264/* ============ Utility functions */
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000265#define xbarrier() do { __asm__ __volatile__ ("": : :"memory"); } while (0)
266
Denis Vlasenko559691a2008-10-05 18:39:31 +0000267static int isdigit_str9(const char *str)
268{
269 int maxlen = 9 + 1; /* max 9 digits: 999999999 */
270 while (--maxlen && isdigit(*str))
271 str++;
272 return (*str == '\0');
273}
Denis Vlasenko01631112007-12-16 17:20:38 +0000274
Denys Vlasenko8837c5d2010-06-02 12:56:18 +0200275static const char *var_end(const char *var)
276{
277 while (*var)
278 if (*var++ == '=')
279 break;
280 return var;
281}
282
Denis Vlasenko559691a2008-10-05 18:39:31 +0000283
284/* ============ Interrupts / exceptions */
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +0000285/*
Eric Andersen2870d962001-07-02 17:27:21 +0000286 * These macros allow the user to suspend the handling of interrupt signals
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +0000287 * over a period of time. This is similar to SIGHOLD or to sigblock, but
Eric Andersen2870d962001-07-02 17:27:21 +0000288 * much more efficient and portable. (But hacking the kernel is so much
289 * more fun than worrying about efficiency and portability. :-))
290 */
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000291#define INT_OFF do { \
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200292 suppress_int++; \
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000293 xbarrier(); \
294} while (0)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000295
296/*
297 * Called to raise an exception. Since C doesn't include exceptions, we
298 * just do a longjmp to the exception handler. The type of exception is
Denis Vlasenko4b875702009-03-19 13:30:04 +0000299 * stored in the global variable "exception_type".
Denis Vlasenkob012b102007-02-19 22:43:01 +0000300 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +0000301static void raise_exception(int) NORETURN;
Denis Vlasenkob012b102007-02-19 22:43:01 +0000302static void
303raise_exception(int e)
304{
305#if DEBUG
Denis Vlasenko2da584f2007-02-19 22:44:05 +0000306 if (exception_handler == NULL)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000307 abort();
308#endif
309 INT_OFF;
Denis Vlasenko7f88e342009-03-19 03:36:18 +0000310 exception_type = e;
Denis Vlasenko2da584f2007-02-19 22:44:05 +0000311 longjmp(exception_handler->loc, 1);
Denis Vlasenkob012b102007-02-19 22:43:01 +0000312}
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000313#if DEBUG
314#define raise_exception(e) do { \
315 TRACE(("raising exception %d on line %d\n", (e), __LINE__)); \
316 raise_exception(e); \
317} while (0)
318#endif
Denis Vlasenkob012b102007-02-19 22:43:01 +0000319
320/*
321 * Called from trap.c when a SIGINT is received. (If the user specifies
322 * that SIGINT is to be trapped or ignored using the trap builtin, then
323 * this routine is not called.) Suppressint is nonzero when interrupts
324 * are held using the INT_OFF macro. (The test for iflag is just
325 * defensive programming.)
326 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +0000327static void raise_interrupt(void) NORETURN;
Denis Vlasenkob012b102007-02-19 22:43:01 +0000328static void
329raise_interrupt(void)
330{
Denis Vlasenko4b875702009-03-19 13:30:04 +0000331 int ex_type;
Denis Vlasenkob012b102007-02-19 22:43:01 +0000332
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200333 pending_int = 0;
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +0000334 /* Signal is not automatically unmasked after it is raised,
335 * do it ourself - unmask all signals */
Denis Vlasenko3f165fa2008-03-17 08:29:08 +0000336 sigprocmask_allsigs(SIG_UNBLOCK);
Denys Vlasenko238bf182010-05-18 15:49:07 +0200337 /* pending_sig = 0; - now done in signal_handler() */
Denis Vlasenko7c139b42007-03-21 20:17:27 +0000338
Denis Vlasenko4b875702009-03-19 13:30:04 +0000339 ex_type = EXSIG;
Denis Vlasenkob012b102007-02-19 22:43:01 +0000340 if (gotsig[SIGINT - 1] && !trap[SIGINT]) {
341 if (!(rootshell && iflag)) {
Denis Vlasenko991a1da2008-02-10 19:02:53 +0000342 /* Kill ourself with SIGINT */
Denis Vlasenkob012b102007-02-19 22:43:01 +0000343 signal(SIGINT, SIG_DFL);
344 raise(SIGINT);
345 }
Denis Vlasenko4b875702009-03-19 13:30:04 +0000346 ex_type = EXINT;
Denis Vlasenkob012b102007-02-19 22:43:01 +0000347 }
Denis Vlasenko4b875702009-03-19 13:30:04 +0000348 raise_exception(ex_type);
Denis Vlasenkob012b102007-02-19 22:43:01 +0000349 /* NOTREACHED */
350}
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000351#if DEBUG
352#define raise_interrupt() do { \
353 TRACE(("raising interrupt on line %d\n", __LINE__)); \
354 raise_interrupt(); \
355} while (0)
356#endif
Denis Vlasenkob012b102007-02-19 22:43:01 +0000357
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000358static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000359int_on(void)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000360{
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +0000361 xbarrier();
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200362 if (--suppress_int == 0 && pending_int) {
Denis Vlasenkob012b102007-02-19 22:43:01 +0000363 raise_interrupt();
364 }
365}
366#define INT_ON int_on()
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000367static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000368force_int_on(void)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000369{
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +0000370 xbarrier();
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200371 suppress_int = 0;
372 if (pending_int)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000373 raise_interrupt();
374}
375#define FORCE_INT_ON force_int_on()
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000376
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200377#define SAVE_INT(v) ((v) = suppress_int)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000378
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000379#define RESTORE_INT(v) do { \
380 xbarrier(); \
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200381 suppress_int = (v); \
382 if (suppress_int == 0 && pending_int) \
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000383 raise_interrupt(); \
384} while (0)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000385
Glenn L McGrath9fef17d2002-08-22 18:41:20 +0000386
Denis Vlasenkobc54cff2007-02-23 01:05:52 +0000387/* ============ Stdout/stderr output */
Eric Andersenc470f442003-07-28 09:56:35 +0000388
Eric Andersenc470f442003-07-28 09:56:35 +0000389static void
Denis Vlasenkob012b102007-02-19 22:43:01 +0000390outstr(const char *p, FILE *file)
Denis Vlasenkoe5570da2007-02-19 22:41:55 +0000391{
Denis Vlasenkob012b102007-02-19 22:43:01 +0000392 INT_OFF;
393 fputs(p, file);
394 INT_ON;
395}
396
397static void
398flush_stdout_stderr(void)
399{
400 INT_OFF;
Denys Vlasenko8131eea2009-11-02 14:19:51 +0100401 fflush_all();
Denis Vlasenkob012b102007-02-19 22:43:01 +0000402 INT_ON;
403}
404
405static void
406outcslow(int c, FILE *dest)
407{
408 INT_OFF;
409 putc(c, dest);
410 fflush(dest);
411 INT_ON;
412}
413
414static int out1fmt(const char *, ...) __attribute__((__format__(__printf__,1,2)));
415static int
416out1fmt(const char *fmt, ...)
417{
418 va_list ap;
419 int r;
420
421 INT_OFF;
422 va_start(ap, fmt);
423 r = vprintf(fmt, ap);
424 va_end(ap);
425 INT_ON;
426 return r;
427}
428
429static int fmtstr(char *, size_t, const char *, ...) __attribute__((__format__(__printf__,3,4)));
430static int
431fmtstr(char *outbuf, size_t length, const char *fmt, ...)
432{
433 va_list ap;
434 int ret;
435
436 va_start(ap, fmt);
437 INT_OFF;
438 ret = vsnprintf(outbuf, length, fmt, ap);
439 va_end(ap);
440 INT_ON;
441 return ret;
442}
443
444static void
445out1str(const char *p)
446{
447 outstr(p, stdout);
448}
449
450static void
451out2str(const char *p)
452{
453 outstr(p, stderr);
Denys Vlasenko8131eea2009-11-02 14:19:51 +0100454 flush_stdout_stderr();
Denis Vlasenkob012b102007-02-19 22:43:01 +0000455}
456
457
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +0000458/* ============ Parser structures */
Denis Vlasenko4d2183b2007-02-23 01:05:38 +0000459
Denis Vlasenko5651bfc2007-02-23 21:08:58 +0000460/* control characters in argument strings */
Denys Vlasenko2ce42e92009-11-29 02:18:13 +0100461#define CTL_FIRST CTLESC
Denys Vlasenkob6c84342009-08-29 20:23:20 +0200462#define CTLESC ((unsigned char)'\201') /* escape next character */
463#define CTLVAR ((unsigned char)'\202') /* variable defn */
464#define CTLENDVAR ((unsigned char)'\203')
465#define CTLBACKQ ((unsigned char)'\204')
Denis Vlasenko5651bfc2007-02-23 21:08:58 +0000466#define CTLQUOTE 01 /* ored with CTLBACKQ code if in quotes */
467/* CTLBACKQ | CTLQUOTE == '\205' */
Denys Vlasenkob6c84342009-08-29 20:23:20 +0200468#define CTLARI ((unsigned char)'\206') /* arithmetic expression */
469#define CTLENDARI ((unsigned char)'\207')
470#define CTLQUOTEMARK ((unsigned char)'\210')
Denys Vlasenko2ce42e92009-11-29 02:18:13 +0100471#define CTL_LAST CTLQUOTEMARK
Denis Vlasenko5651bfc2007-02-23 21:08:58 +0000472
473/* variable substitution byte (follows CTLVAR) */
474#define VSTYPE 0x0f /* type of variable substitution */
475#define VSNUL 0x10 /* colon--treat the empty string as unset */
476#define VSQUOTE 0x80 /* inside double quotes--suppress splitting */
477
478/* values of VSTYPE field */
Denis Vlasenko92e13c22008-03-25 01:17:40 +0000479#define VSNORMAL 0x1 /* normal variable: $var or ${var} */
480#define VSMINUS 0x2 /* ${var-text} */
481#define VSPLUS 0x3 /* ${var+text} */
482#define VSQUESTION 0x4 /* ${var?message} */
483#define VSASSIGN 0x5 /* ${var=text} */
484#define VSTRIMRIGHT 0x6 /* ${var%pattern} */
485#define VSTRIMRIGHTMAX 0x7 /* ${var%%pattern} */
486#define VSTRIMLEFT 0x8 /* ${var#pattern} */
487#define VSTRIMLEFTMAX 0x9 /* ${var##pattern} */
488#define VSLENGTH 0xa /* ${#var} */
489#if ENABLE_ASH_BASH_COMPAT
490#define VSSUBSTR 0xc /* ${var:position:length} */
491#define VSREPLACE 0xd /* ${var/pattern/replacement} */
492#define VSREPLACEALL 0xe /* ${var//pattern/replacement} */
493#endif
Denis Vlasenko5651bfc2007-02-23 21:08:58 +0000494
Denis Vlasenko6ca409e2007-08-12 20:58:27 +0000495static const char dolatstr[] ALIGN1 = {
496 CTLVAR, VSNORMAL|VSQUOTE, '@', '=', '\0'
497};
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +0000498
Denis Vlasenko559691a2008-10-05 18:39:31 +0000499#define NCMD 0
500#define NPIPE 1
501#define NREDIR 2
502#define NBACKGND 3
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000503#define NSUBSHELL 4
Denis Vlasenko559691a2008-10-05 18:39:31 +0000504#define NAND 5
505#define NOR 6
506#define NSEMI 7
507#define NIF 8
508#define NWHILE 9
509#define NUNTIL 10
510#define NFOR 11
511#define NCASE 12
512#define NCLIST 13
513#define NDEFUN 14
514#define NARG 15
515#define NTO 16
516#if ENABLE_ASH_BASH_COMPAT
517#define NTO2 17
518#endif
519#define NCLOBBER 18
520#define NFROM 19
521#define NFROMTO 20
522#define NAPPEND 21
523#define NTOFD 22
524#define NFROMFD 23
525#define NHERE 24
526#define NXHERE 25
527#define NNOT 26
Denis Vlasenko340299a2008-11-21 10:36:36 +0000528#define N_NUMBER 27
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000529
530union node;
531
532struct ncmd {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000533 smallint type; /* Nxxxx */
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000534 union node *assign;
535 union node *args;
536 union node *redirect;
537};
538
539struct npipe {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000540 smallint type;
541 smallint pipe_backgnd;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000542 struct nodelist *cmdlist;
543};
544
545struct nredir {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000546 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000547 union node *n;
548 union node *redirect;
549};
550
551struct nbinary {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000552 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000553 union node *ch1;
554 union node *ch2;
555};
556
557struct nif {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000558 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000559 union node *test;
560 union node *ifpart;
561 union node *elsepart;
562};
563
564struct nfor {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000565 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000566 union node *args;
567 union node *body;
568 char *var;
569};
570
571struct ncase {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000572 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000573 union node *expr;
574 union node *cases;
575};
576
577struct nclist {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000578 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000579 union node *next;
580 union node *pattern;
581 union node *body;
582};
583
584struct narg {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000585 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000586 union node *next;
587 char *text;
588 struct nodelist *backquote;
589};
590
Denis Vlasenko559691a2008-10-05 18:39:31 +0000591/* nfile and ndup layout must match!
592 * NTOFD (>&fdnum) uses ndup structure, but we may discover mid-flight
593 * that it is actually NTO2 (>&file), and change its type.
594 */
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000595struct nfile {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000596 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000597 union node *next;
598 int fd;
Denis Vlasenko559691a2008-10-05 18:39:31 +0000599 int _unused_dupfd;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000600 union node *fname;
601 char *expfname;
602};
603
604struct ndup {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000605 smallint type;
Denis Vlasenko559691a2008-10-05 18:39:31 +0000606 union node *next;
607 int fd;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000608 int dupfd;
609 union node *vname;
Denis Vlasenko559691a2008-10-05 18:39:31 +0000610 char *_unused_expfname;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000611};
612
613struct nhere {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000614 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000615 union node *next;
616 int fd;
617 union node *doc;
618};
619
620struct nnot {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000621 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000622 union node *com;
623};
624
625union node {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000626 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000627 struct ncmd ncmd;
628 struct npipe npipe;
629 struct nredir nredir;
630 struct nbinary nbinary;
631 struct nif nif;
632 struct nfor nfor;
633 struct ncase ncase;
634 struct nclist nclist;
635 struct narg narg;
636 struct nfile nfile;
637 struct ndup ndup;
638 struct nhere nhere;
639 struct nnot nnot;
640};
641
Denys Vlasenko86e83ec2009-07-23 22:07:07 +0200642/*
643 * NODE_EOF is returned by parsecmd when it encounters an end of file.
644 * It must be distinct from NULL.
645 */
646#define NODE_EOF ((union node *) -1L)
647
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000648struct nodelist {
649 struct nodelist *next;
650 union node *n;
651};
652
653struct funcnode {
654 int count;
655 union node n;
656};
657
Denis Vlasenko5651bfc2007-02-23 21:08:58 +0000658/*
659 * Free a parse tree.
660 */
661static void
662freefunc(struct funcnode *f)
663{
664 if (f && --f->count < 0)
665 free(f);
666}
667
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000668
669/* ============ Debugging output */
670
671#if DEBUG
672
673static FILE *tracefile;
674
675static void
676trace_printf(const char *fmt, ...)
677{
678 va_list va;
679
680 if (debug != 1)
681 return;
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000682 if (DEBUG_TIME)
683 fprintf(tracefile, "%u ", (int) time(NULL));
684 if (DEBUG_PID)
685 fprintf(tracefile, "[%u] ", (int) getpid());
686 if (DEBUG_SIG)
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200687 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000688 va_start(va, fmt);
689 vfprintf(tracefile, fmt, va);
690 va_end(va);
691}
692
693static void
694trace_vprintf(const char *fmt, va_list va)
695{
696 if (debug != 1)
697 return;
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000698 if (DEBUG_TIME)
699 fprintf(tracefile, "%u ", (int) time(NULL));
700 if (DEBUG_PID)
701 fprintf(tracefile, "[%u] ", (int) getpid());
702 if (DEBUG_SIG)
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200703 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000704 vfprintf(tracefile, fmt, va);
705}
706
707static void
708trace_puts(const char *s)
709{
710 if (debug != 1)
711 return;
712 fputs(s, tracefile);
713}
714
715static void
716trace_puts_quoted(char *s)
717{
718 char *p;
719 char c;
720
721 if (debug != 1)
722 return;
723 putc('"', tracefile);
724 for (p = s; *p; p++) {
Denys Vlasenkocd716832009-11-28 22:14:02 +0100725 switch ((unsigned char)*p) {
726 case '\n': c = 'n'; goto backslash;
727 case '\t': c = 't'; goto backslash;
728 case '\r': c = 'r'; goto backslash;
729 case '\"': c = '\"'; goto backslash;
730 case '\\': c = '\\'; goto backslash;
731 case CTLESC: c = 'e'; goto backslash;
732 case CTLVAR: c = 'v'; goto backslash;
733 case CTLVAR+CTLQUOTE: c = 'V'; goto backslash;
734 case CTLBACKQ: c = 'q'; goto backslash;
735 case CTLBACKQ+CTLQUOTE: c = 'Q'; goto backslash;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000736 backslash:
737 putc('\\', tracefile);
738 putc(c, tracefile);
739 break;
740 default:
741 if (*p >= ' ' && *p <= '~')
742 putc(*p, tracefile);
743 else {
744 putc('\\', tracefile);
Denys Vlasenkocd716832009-11-28 22:14:02 +0100745 putc((*p >> 6) & 03, tracefile);
746 putc((*p >> 3) & 07, tracefile);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000747 putc(*p & 07, tracefile);
748 }
749 break;
750 }
751 }
752 putc('"', tracefile);
753}
754
755static void
756trace_puts_args(char **ap)
757{
758 if (debug != 1)
759 return;
760 if (!*ap)
761 return;
762 while (1) {
763 trace_puts_quoted(*ap);
764 if (!*++ap) {
765 putc('\n', tracefile);
766 break;
767 }
768 putc(' ', tracefile);
769 }
770}
771
772static void
773opentrace(void)
774{
775 char s[100];
776#ifdef O_APPEND
777 int flags;
778#endif
779
780 if (debug != 1) {
781 if (tracefile)
782 fflush(tracefile);
783 /* leave open because libedit might be using it */
784 return;
785 }
786 strcpy(s, "./trace");
787 if (tracefile) {
788 if (!freopen(s, "a", tracefile)) {
789 fprintf(stderr, "Can't re-open %s\n", s);
790 debug = 0;
791 return;
792 }
793 } else {
794 tracefile = fopen(s, "a");
795 if (tracefile == NULL) {
796 fprintf(stderr, "Can't open %s\n", s);
797 debug = 0;
798 return;
799 }
800 }
801#ifdef O_APPEND
Denis Vlasenkod37f2222007-08-19 13:42:08 +0000802 flags = fcntl(fileno(tracefile), F_GETFL);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000803 if (flags >= 0)
804 fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
805#endif
806 setlinebuf(tracefile);
807 fputs("\nTracing started.\n", tracefile);
808}
809
810static void
811indent(int amount, char *pfx, FILE *fp)
812{
813 int i;
814
815 for (i = 0; i < amount; i++) {
816 if (pfx && i == amount - 1)
817 fputs(pfx, fp);
818 putc('\t', fp);
819 }
820}
821
822/* little circular references here... */
823static void shtree(union node *n, int ind, char *pfx, FILE *fp);
824
825static void
826sharg(union node *arg, FILE *fp)
827{
828 char *p;
829 struct nodelist *bqlist;
Denys Vlasenkocd716832009-11-28 22:14:02 +0100830 unsigned char subtype;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000831
832 if (arg->type != NARG) {
833 out1fmt("<node type %d>\n", arg->type);
834 abort();
835 }
836 bqlist = arg->narg.backquote;
837 for (p = arg->narg.text; *p; p++) {
Denys Vlasenkocd716832009-11-28 22:14:02 +0100838 switch ((unsigned char)*p) {
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000839 case CTLESC:
840 putc(*++p, fp);
841 break;
842 case CTLVAR:
843 putc('$', fp);
844 putc('{', fp);
845 subtype = *++p;
846 if (subtype == VSLENGTH)
847 putc('#', fp);
848
849 while (*p != '=')
850 putc(*p++, fp);
851
852 if (subtype & VSNUL)
853 putc(':', fp);
854
855 switch (subtype & VSTYPE) {
856 case VSNORMAL:
857 putc('}', fp);
858 break;
859 case VSMINUS:
860 putc('-', fp);
861 break;
862 case VSPLUS:
863 putc('+', fp);
864 break;
865 case VSQUESTION:
866 putc('?', fp);
867 break;
868 case VSASSIGN:
869 putc('=', fp);
870 break;
871 case VSTRIMLEFT:
872 putc('#', fp);
873 break;
874 case VSTRIMLEFTMAX:
875 putc('#', fp);
876 putc('#', fp);
877 break;
878 case VSTRIMRIGHT:
879 putc('%', fp);
880 break;
881 case VSTRIMRIGHTMAX:
882 putc('%', fp);
883 putc('%', fp);
884 break;
885 case VSLENGTH:
886 break;
887 default:
888 out1fmt("<subtype %d>", subtype);
889 }
890 break;
891 case CTLENDVAR:
892 putc('}', fp);
893 break;
894 case CTLBACKQ:
895 case CTLBACKQ|CTLQUOTE:
896 putc('$', fp);
897 putc('(', fp);
898 shtree(bqlist->n, -1, NULL, fp);
899 putc(')', fp);
900 break;
901 default:
902 putc(*p, fp);
903 break;
904 }
905 }
906}
907
Denys Vlasenko641dd7b2009-06-11 19:30:19 +0200908static void
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000909shcmd(union node *cmd, FILE *fp)
910{
911 union node *np;
912 int first;
913 const char *s;
914 int dftfd;
915
916 first = 1;
917 for (np = cmd->ncmd.args; np; np = np->narg.next) {
Denis Vlasenko40ba9982007-07-14 00:48:29 +0000918 if (!first)
919 putc(' ', fp);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000920 sharg(np, fp);
921 first = 0;
922 }
923 for (np = cmd->ncmd.redirect; np; np = np->nfile.next) {
Denis Vlasenko40ba9982007-07-14 00:48:29 +0000924 if (!first)
925 putc(' ', fp);
926 dftfd = 0;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000927 switch (np->nfile.type) {
Denis Vlasenko40ba9982007-07-14 00:48:29 +0000928 case NTO: s = ">>"+1; dftfd = 1; break;
929 case NCLOBBER: s = ">|"; dftfd = 1; break;
930 case NAPPEND: s = ">>"; dftfd = 1; break;
Denis Vlasenko559691a2008-10-05 18:39:31 +0000931#if ENABLE_ASH_BASH_COMPAT
932 case NTO2:
933#endif
Denis Vlasenko40ba9982007-07-14 00:48:29 +0000934 case NTOFD: s = ">&"; dftfd = 1; break;
Denis Vlasenko559691a2008-10-05 18:39:31 +0000935 case NFROM: s = "<"; break;
Denis Vlasenko40ba9982007-07-14 00:48:29 +0000936 case NFROMFD: s = "<&"; break;
937 case NFROMTO: s = "<>"; break;
938 default: s = "*error*"; break;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000939 }
940 if (np->nfile.fd != dftfd)
941 fprintf(fp, "%d", np->nfile.fd);
942 fputs(s, fp);
943 if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
944 fprintf(fp, "%d", np->ndup.dupfd);
945 } else {
946 sharg(np->nfile.fname, fp);
947 }
948 first = 0;
949 }
950}
951
952static void
953shtree(union node *n, int ind, char *pfx, FILE *fp)
954{
955 struct nodelist *lp;
956 const char *s;
957
958 if (n == NULL)
959 return;
960
961 indent(ind, pfx, fp);
Denys Vlasenko86e83ec2009-07-23 22:07:07 +0200962
963 if (n == NODE_EOF) {
964 fputs("<EOF>", fp);
965 return;
966 }
967
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000968 switch (n->type) {
969 case NSEMI:
970 s = "; ";
971 goto binop;
972 case NAND:
973 s = " && ";
974 goto binop;
975 case NOR:
976 s = " || ";
977 binop:
978 shtree(n->nbinary.ch1, ind, NULL, fp);
979 /* if (ind < 0) */
980 fputs(s, fp);
981 shtree(n->nbinary.ch2, ind, NULL, fp);
982 break;
983 case NCMD:
984 shcmd(n, fp);
985 if (ind >= 0)
986 putc('\n', fp);
987 break;
988 case NPIPE:
989 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
Denys Vlasenko7cee00e2009-07-24 01:08:03 +0200990 shtree(lp->n, 0, NULL, fp);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000991 if (lp->next)
992 fputs(" | ", fp);
993 }
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000994 if (n->npipe.pipe_backgnd)
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000995 fputs(" &", fp);
996 if (ind >= 0)
997 putc('\n', fp);
998 break;
999 default:
1000 fprintf(fp, "<node type %d>", n->type);
1001 if (ind >= 0)
1002 putc('\n', fp);
1003 break;
1004 }
1005}
1006
1007static void
1008showtree(union node *n)
1009{
1010 trace_puts("showtree called\n");
Denys Vlasenko883cea42009-07-11 15:31:59 +02001011 shtree(n, 1, NULL, stderr);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00001012}
1013
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00001014#endif /* DEBUG */
1015
1016
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00001017/* ============ Parser data */
1018
1019/*
Denis Vlasenkob012b102007-02-19 22:43:01 +00001020 * ash_vmsg() needs parsefile->fd, hence parsefile definition is moved up.
1021 */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001022struct strlist {
1023 struct strlist *next;
1024 char *text;
1025};
1026
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00001027struct alias;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00001028
Denis Vlasenkob012b102007-02-19 22:43:01 +00001029struct strpush {
1030 struct strpush *prev; /* preceding string on stack */
Denis Vlasenko41eb3002008-11-28 03:42:31 +00001031 char *prev_string;
1032 int prev_left_in_line;
Denis Vlasenkob012b102007-02-19 22:43:01 +00001033#if ENABLE_ASH_ALIAS
1034 struct alias *ap; /* if push was associated with an alias */
1035#endif
1036 char *string; /* remember the string since it may change */
1037};
1038
1039struct parsefile {
1040 struct parsefile *prev; /* preceding file on stack */
1041 int linno; /* current line */
Denys Vlasenko79b3d422010-06-03 04:29:08 +02001042 int pf_fd; /* file descriptor (or -1 if string) */
Denis Vlasenko41eb3002008-11-28 03:42:31 +00001043 int left_in_line; /* number of chars left in this line */
1044 int left_in_buffer; /* number of chars left in this buffer past the line */
1045 char *next_to_pgetc; /* next char in buffer */
Denis Vlasenkob012b102007-02-19 22:43:01 +00001046 char *buf; /* input buffer */
1047 struct strpush *strpush; /* for pushing strings at this level */
1048 struct strpush basestrpush; /* so pushing one is fast */
1049};
1050
Denis Vlasenko448d30e2008-06-27 00:24:11 +00001051static struct parsefile basepf; /* top level input file */
Denis Vlasenkob07a4962008-06-22 13:16:23 +00001052static struct parsefile *g_parsefile = &basepf; /* current input file */
Denis Vlasenkob012b102007-02-19 22:43:01 +00001053static int startlinno; /* line # where last token started */
1054static char *commandname; /* currently executing command */
1055static struct strlist *cmdenviron; /* environment for builtin command */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00001056static uint8_t exitstatus; /* exit status of last command */
Denis Vlasenkob012b102007-02-19 22:43:01 +00001057
1058
1059/* ============ Message printing */
1060
1061static void
1062ash_vmsg(const char *msg, va_list ap)
1063{
1064 fprintf(stderr, "%s: ", arg0);
1065 if (commandname) {
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00001066 if (strcmp(arg0, commandname))
1067 fprintf(stderr, "%s: ", commandname);
Denys Vlasenko79b3d422010-06-03 04:29:08 +02001068 if (!iflag || g_parsefile->pf_fd > 0)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00001069 fprintf(stderr, "line %d: ", startlinno);
Eric Andersenc470f442003-07-28 09:56:35 +00001070 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00001071 vfprintf(stderr, msg, ap);
1072 outcslow('\n', stderr);
Eric Andersenc470f442003-07-28 09:56:35 +00001073}
Denis Vlasenkob012b102007-02-19 22:43:01 +00001074
1075/*
1076 * Exverror is called to raise the error exception. If the second argument
1077 * is not NULL then error prints an error message using printf style
1078 * formatting. It then raises the error exception.
1079 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001080static void ash_vmsg_and_raise(int, const char *, va_list) NORETURN;
Denis Vlasenkob012b102007-02-19 22:43:01 +00001081static void
1082ash_vmsg_and_raise(int cond, const char *msg, va_list ap)
Eric Andersenc470f442003-07-28 09:56:35 +00001083{
Denis Vlasenkob012b102007-02-19 22:43:01 +00001084#if DEBUG
1085 if (msg) {
1086 TRACE(("ash_vmsg_and_raise(%d, \"", cond));
1087 TRACEV((msg, ap));
1088 TRACE(("\") pid=%d\n", getpid()));
1089 } else
1090 TRACE(("ash_vmsg_and_raise(%d, NULL) pid=%d\n", cond, getpid()));
1091 if (msg)
1092#endif
1093 ash_vmsg(msg, ap);
1094
1095 flush_stdout_stderr();
1096 raise_exception(cond);
1097 /* NOTREACHED */
Eric Andersenc470f442003-07-28 09:56:35 +00001098}
Denis Vlasenkob012b102007-02-19 22:43:01 +00001099
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001100static void ash_msg_and_raise_error(const char *, ...) NORETURN;
Denis Vlasenkob012b102007-02-19 22:43:01 +00001101static void
1102ash_msg_and_raise_error(const char *msg, ...)
1103{
1104 va_list ap;
1105
1106 va_start(ap, msg);
1107 ash_vmsg_and_raise(EXERROR, msg, ap);
1108 /* NOTREACHED */
1109 va_end(ap);
1110}
1111
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00001112static void raise_error_syntax(const char *) NORETURN;
1113static void
1114raise_error_syntax(const char *msg)
1115{
1116 ash_msg_and_raise_error("syntax error: %s", msg);
1117 /* NOTREACHED */
1118}
1119
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001120static void ash_msg_and_raise(int, const char *, ...) NORETURN;
Denis Vlasenkob012b102007-02-19 22:43:01 +00001121static void
1122ash_msg_and_raise(int cond, const char *msg, ...)
1123{
1124 va_list ap;
1125
1126 va_start(ap, msg);
1127 ash_vmsg_and_raise(cond, msg, ap);
1128 /* NOTREACHED */
1129 va_end(ap);
1130}
1131
1132/*
1133 * error/warning routines for external builtins
1134 */
1135static void
1136ash_msg(const char *fmt, ...)
1137{
1138 va_list ap;
1139
1140 va_start(ap, fmt);
1141 ash_vmsg(fmt, ap);
1142 va_end(ap);
1143}
1144
1145/*
1146 * Return a string describing an error. The returned string may be a
1147 * pointer to a static buffer that will be overwritten on the next call.
1148 * Action describes the operation that got the error.
1149 */
1150static const char *
1151errmsg(int e, const char *em)
1152{
1153 if (e == ENOENT || e == ENOTDIR) {
1154 return em;
1155 }
1156 return strerror(e);
1157}
1158
1159
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001160/* ============ Memory allocation */
1161
Denys Vlasenkoe7670ff2009-10-11 00:45:25 +02001162#if 0
1163/* I consider these wrappers nearly useless:
1164 * ok, they return you to nearest exception handler, but
1165 * how much memory do you leak in the process, making
1166 * memory starvation worse?
1167 */
1168static void *
1169ckrealloc(void * p, size_t nbytes)
1170{
1171 p = realloc(p, nbytes);
1172 if (!p)
1173 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1174 return p;
1175}
1176
1177static void *
1178ckmalloc(size_t nbytes)
1179{
1180 return ckrealloc(NULL, nbytes);
1181}
1182
1183static void *
1184ckzalloc(size_t nbytes)
1185{
1186 return memset(ckmalloc(nbytes), 0, nbytes);
1187}
1188
1189static char *
1190ckstrdup(const char *s)
1191{
1192 char *p = strdup(s);
1193 if (!p)
1194 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1195 return p;
1196}
1197#else
1198/* Using bbox equivalents. They exit if out of memory */
1199# define ckrealloc xrealloc
1200# define ckmalloc xmalloc
1201# define ckzalloc xzalloc
1202# define ckstrdup xstrdup
1203#endif
1204
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001205/*
1206 * It appears that grabstackstr() will barf with such alignments
1207 * because stalloc() will return a string allocated in a new stackblock.
1208 */
1209#define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
1210enum {
1211 /* Most machines require the value returned from malloc to be aligned
1212 * in some way. The following macro will get this right
1213 * on many machines. */
Denys Vlasenko0e5e4ea2009-10-11 00:36:20 +02001214 SHELL_SIZE = sizeof(union { int i; char *cp; double d; }) - 1,
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001215 /* Minimum size of a block */
Denis Vlasenko01631112007-12-16 17:20:38 +00001216 MINSIZE = SHELL_ALIGN(504),
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001217};
1218
1219struct stack_block {
1220 struct stack_block *prev;
1221 char space[MINSIZE];
1222};
1223
1224struct stackmark {
1225 struct stack_block *stackp;
1226 char *stacknxt;
1227 size_t stacknleft;
1228 struct stackmark *marknext;
1229};
1230
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001231
Denis Vlasenko01631112007-12-16 17:20:38 +00001232struct globals_memstack {
1233 struct stack_block *g_stackp; // = &stackbase;
1234 struct stackmark *markp;
1235 char *g_stacknxt; // = stackbase.space;
1236 char *sstrend; // = stackbase.space + MINSIZE;
1237 size_t g_stacknleft; // = MINSIZE;
1238 int herefd; // = -1;
1239 struct stack_block stackbase;
1240};
Denis Vlasenko574f2f42008-02-27 18:41:59 +00001241extern struct globals_memstack *const ash_ptr_to_globals_memstack;
1242#define G_memstack (*ash_ptr_to_globals_memstack)
Denis Vlasenko01631112007-12-16 17:20:38 +00001243#define g_stackp (G_memstack.g_stackp )
1244#define markp (G_memstack.markp )
1245#define g_stacknxt (G_memstack.g_stacknxt )
1246#define sstrend (G_memstack.sstrend )
1247#define g_stacknleft (G_memstack.g_stacknleft)
1248#define herefd (G_memstack.herefd )
1249#define stackbase (G_memstack.stackbase )
1250#define INIT_G_memstack() do { \
Denis Vlasenko574f2f42008-02-27 18:41:59 +00001251 (*(struct globals_memstack**)&ash_ptr_to_globals_memstack) = xzalloc(sizeof(G_memstack)); \
1252 barrier(); \
Denis Vlasenko01631112007-12-16 17:20:38 +00001253 g_stackp = &stackbase; \
1254 g_stacknxt = stackbase.space; \
1255 g_stacknleft = MINSIZE; \
1256 sstrend = stackbase.space + MINSIZE; \
1257 herefd = -1; \
1258} while (0)
1259
Denys Vlasenkoe7670ff2009-10-11 00:45:25 +02001260
Denis Vlasenko01631112007-12-16 17:20:38 +00001261#define stackblock() ((void *)g_stacknxt)
1262#define stackblocksize() g_stacknleft
1263
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001264/*
1265 * Parse trees for commands are allocated in lifo order, so we use a stack
1266 * to make this more efficient, and also to avoid all sorts of exception
1267 * handling code to handle interrupts in the middle of a parse.
1268 *
1269 * The size 504 was chosen because the Ultrix malloc handles that size
1270 * well.
1271 */
1272static void *
1273stalloc(size_t nbytes)
1274{
1275 char *p;
1276 size_t aligned;
1277
1278 aligned = SHELL_ALIGN(nbytes);
Denis Vlasenko01631112007-12-16 17:20:38 +00001279 if (aligned > g_stacknleft) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001280 size_t len;
1281 size_t blocksize;
1282 struct stack_block *sp;
1283
1284 blocksize = aligned;
1285 if (blocksize < MINSIZE)
1286 blocksize = MINSIZE;
1287 len = sizeof(struct stack_block) - MINSIZE + blocksize;
1288 if (len < blocksize)
1289 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1290 INT_OFF;
1291 sp = ckmalloc(len);
Denis Vlasenko01631112007-12-16 17:20:38 +00001292 sp->prev = g_stackp;
1293 g_stacknxt = sp->space;
1294 g_stacknleft = blocksize;
1295 sstrend = g_stacknxt + blocksize;
1296 g_stackp = sp;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001297 INT_ON;
1298 }
Denis Vlasenko01631112007-12-16 17:20:38 +00001299 p = g_stacknxt;
1300 g_stacknxt += aligned;
1301 g_stacknleft -= aligned;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001302 return p;
1303}
1304
Denis Vlasenko597906c2008-02-20 16:38:54 +00001305static void *
1306stzalloc(size_t nbytes)
1307{
1308 return memset(stalloc(nbytes), 0, nbytes);
1309}
1310
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001311static void
1312stunalloc(void *p)
1313{
1314#if DEBUG
Denis Vlasenko01631112007-12-16 17:20:38 +00001315 if (!p || (g_stacknxt < (char *)p) || ((char *)p < g_stackp->space)) {
Bernhard Reutner-Fischer5e25ddb2008-05-19 09:48:17 +00001316 write(STDERR_FILENO, "stunalloc\n", 10);
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001317 abort();
1318 }
1319#endif
Denis Vlasenko01631112007-12-16 17:20:38 +00001320 g_stacknleft += g_stacknxt - (char *)p;
1321 g_stacknxt = p;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001322}
1323
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001324/*
1325 * Like strdup but works with the ash stack.
1326 */
1327static char *
1328ststrdup(const char *p)
1329{
1330 size_t len = strlen(p) + 1;
1331 return memcpy(stalloc(len), p, len);
1332}
1333
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001334static void
1335setstackmark(struct stackmark *mark)
1336{
Denis Vlasenko01631112007-12-16 17:20:38 +00001337 mark->stackp = g_stackp;
1338 mark->stacknxt = g_stacknxt;
1339 mark->stacknleft = g_stacknleft;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001340 mark->marknext = markp;
1341 markp = mark;
1342}
1343
1344static void
1345popstackmark(struct stackmark *mark)
1346{
1347 struct stack_block *sp;
1348
Denis Vlasenko93ebd4f2007-03-13 20:55:36 +00001349 if (!mark->stackp)
1350 return;
1351
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001352 INT_OFF;
1353 markp = mark->marknext;
Denis Vlasenko01631112007-12-16 17:20:38 +00001354 while (g_stackp != mark->stackp) {
1355 sp = g_stackp;
1356 g_stackp = sp->prev;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001357 free(sp);
1358 }
Denis Vlasenko01631112007-12-16 17:20:38 +00001359 g_stacknxt = mark->stacknxt;
1360 g_stacknleft = mark->stacknleft;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001361 sstrend = mark->stacknxt + mark->stacknleft;
1362 INT_ON;
1363}
1364
1365/*
1366 * When the parser reads in a string, it wants to stick the string on the
1367 * stack and only adjust the stack pointer when it knows how big the
1368 * string is. Stackblock (defined in stack.h) returns a pointer to a block
1369 * of space on top of the stack and stackblocklen returns the length of
1370 * this block. Growstackblock will grow this space by at least one byte,
1371 * possibly moving it (like realloc). Grabstackblock actually allocates the
1372 * part of the block that has been used.
1373 */
1374static void
1375growstackblock(void)
1376{
1377 size_t newlen;
1378
Denis Vlasenko01631112007-12-16 17:20:38 +00001379 newlen = g_stacknleft * 2;
1380 if (newlen < g_stacknleft)
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001381 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1382 if (newlen < 128)
1383 newlen += 128;
1384
Denis Vlasenko01631112007-12-16 17:20:38 +00001385 if (g_stacknxt == g_stackp->space && g_stackp != &stackbase) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001386 struct stack_block *oldstackp;
1387 struct stackmark *xmark;
1388 struct stack_block *sp;
1389 struct stack_block *prevstackp;
1390 size_t grosslen;
1391
1392 INT_OFF;
Denis Vlasenko01631112007-12-16 17:20:38 +00001393 oldstackp = g_stackp;
1394 sp = g_stackp;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001395 prevstackp = sp->prev;
1396 grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
1397 sp = ckrealloc(sp, grosslen);
1398 sp->prev = prevstackp;
Denis Vlasenko01631112007-12-16 17:20:38 +00001399 g_stackp = sp;
1400 g_stacknxt = sp->space;
1401 g_stacknleft = newlen;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001402 sstrend = sp->space + newlen;
1403
1404 /*
1405 * Stack marks pointing to the start of the old block
1406 * must be relocated to point to the new block
1407 */
1408 xmark = markp;
1409 while (xmark != NULL && xmark->stackp == oldstackp) {
Denis Vlasenko01631112007-12-16 17:20:38 +00001410 xmark->stackp = g_stackp;
1411 xmark->stacknxt = g_stacknxt;
1412 xmark->stacknleft = g_stacknleft;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001413 xmark = xmark->marknext;
1414 }
1415 INT_ON;
1416 } else {
Denis Vlasenko01631112007-12-16 17:20:38 +00001417 char *oldspace = g_stacknxt;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00001418 size_t oldlen = g_stacknleft;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001419 char *p = stalloc(newlen);
1420
1421 /* free the space we just allocated */
Denis Vlasenko01631112007-12-16 17:20:38 +00001422 g_stacknxt = memcpy(p, oldspace, oldlen);
1423 g_stacknleft += newlen;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001424 }
1425}
1426
1427static void
1428grabstackblock(size_t len)
1429{
1430 len = SHELL_ALIGN(len);
Denis Vlasenko01631112007-12-16 17:20:38 +00001431 g_stacknxt += len;
1432 g_stacknleft -= len;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001433}
1434
1435/*
1436 * The following routines are somewhat easier to use than the above.
1437 * The user declares a variable of type STACKSTR, which may be declared
1438 * to be a register. The macro STARTSTACKSTR initializes things. Then
1439 * the user uses the macro STPUTC to add characters to the string. In
1440 * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
1441 * grown as necessary. When the user is done, she can just leave the
1442 * string there and refer to it using stackblock(). Or she can allocate
1443 * the space for it using grabstackstr(). If it is necessary to allow
1444 * someone else to use the stack temporarily and then continue to grow
1445 * the string, the user should use grabstack to allocate the space, and
1446 * then call ungrabstr(p) to return to the previous mode of operation.
1447 *
1448 * USTPUTC is like STPUTC except that it doesn't check for overflow.
1449 * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
1450 * is space for at least one character.
1451 */
1452static void *
1453growstackstr(void)
1454{
1455 size_t len = stackblocksize();
1456 if (herefd >= 0 && len >= 1024) {
1457 full_write(herefd, stackblock(), len);
1458 return stackblock();
1459 }
1460 growstackblock();
Denis Vlasenko29eb3592008-05-18 14:06:08 +00001461 return (char *)stackblock() + len;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001462}
1463
1464/*
1465 * Called from CHECKSTRSPACE.
1466 */
1467static char *
1468makestrspace(size_t newlen, char *p)
1469{
Denis Vlasenko01631112007-12-16 17:20:38 +00001470 size_t len = p - g_stacknxt;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001471 size_t size = stackblocksize();
1472
1473 for (;;) {
1474 size_t nleft;
1475
1476 size = stackblocksize();
1477 nleft = size - len;
1478 if (nleft >= newlen)
1479 break;
1480 growstackblock();
1481 }
Denis Vlasenko29eb3592008-05-18 14:06:08 +00001482 return (char *)stackblock() + len;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001483}
1484
1485static char *
1486stack_nputstr(const char *s, size_t n, char *p)
1487{
1488 p = makestrspace(n, p);
Denis Vlasenko29eb3592008-05-18 14:06:08 +00001489 p = (char *)memcpy(p, s, n) + n;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001490 return p;
1491}
1492
1493static char *
1494stack_putstr(const char *s, char *p)
1495{
1496 return stack_nputstr(s, strlen(s), p);
1497}
1498
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001499static char *
1500_STPUTC(int c, char *p)
1501{
1502 if (p == sstrend)
1503 p = growstackstr();
1504 *p++ = c;
1505 return p;
1506}
1507
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00001508#define STARTSTACKSTR(p) ((p) = stackblock())
1509#define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
Denis Vlasenko843cbd52008-06-27 00:23:18 +00001510#define CHECKSTRSPACE(n, p) do { \
1511 char *q = (p); \
1512 size_t l = (n); \
1513 size_t m = sstrend - q; \
1514 if (l > m) \
1515 (p) = makestrspace(l, q); \
1516} while (0)
Denis Vlasenkoef527f52008-06-23 01:52:30 +00001517#define USTPUTC(c, p) (*(p)++ = (c))
Denis Vlasenko843cbd52008-06-27 00:23:18 +00001518#define STACKSTRNUL(p) do { \
1519 if ((p) == sstrend) \
1520 (p) = growstackstr(); \
1521 *(p) = '\0'; \
1522} while (0)
Denis Vlasenkoef527f52008-06-23 01:52:30 +00001523#define STUNPUTC(p) (--(p))
1524#define STTOPC(p) ((p)[-1])
1525#define STADJUST(amount, p) ((p) += (amount))
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001526
1527#define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
Denis Vlasenkoef527f52008-06-23 01:52:30 +00001528#define ungrabstackstr(s, p) stunalloc(s)
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001529#define stackstrend() ((void *)sstrend)
1530
1531
1532/* ============ String helpers */
1533
1534/*
1535 * prefix -- see if pfx is a prefix of string.
1536 */
1537static char *
1538prefix(const char *string, const char *pfx)
1539{
1540 while (*pfx) {
1541 if (*pfx++ != *string++)
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00001542 return NULL;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001543 }
1544 return (char *) string;
1545}
1546
1547/*
1548 * Check for a valid number. This should be elsewhere.
1549 */
1550static int
1551is_number(const char *p)
1552{
1553 do {
1554 if (!isdigit(*p))
1555 return 0;
1556 } while (*++p != '\0');
1557 return 1;
1558}
1559
1560/*
1561 * Convert a string of digits to an integer, printing an error message on
1562 * failure.
1563 */
1564static int
1565number(const char *s)
1566{
1567 if (!is_number(s))
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02001568 ash_msg_and_raise_error(msg_illnum, s);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001569 return atoi(s);
1570}
1571
1572/*
1573 * Produce a possibly single quoted string suitable as input to the shell.
1574 * The return string is allocated on the stack.
1575 */
1576static char *
1577single_quote(const char *s)
1578{
1579 char *p;
1580
1581 STARTSTACKSTR(p);
1582
1583 do {
1584 char *q;
1585 size_t len;
1586
1587 len = strchrnul(s, '\'') - s;
1588
1589 q = p = makestrspace(len + 3, p);
1590
1591 *q++ = '\'';
Denis Vlasenko29eb3592008-05-18 14:06:08 +00001592 q = (char *)memcpy(q, s, len) + len;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001593 *q++ = '\'';
1594 s += len;
1595
1596 STADJUST(q - p, p);
1597
Denys Vlasenkocd716832009-11-28 22:14:02 +01001598 if (*s != '\'')
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001599 break;
Denys Vlasenkocd716832009-11-28 22:14:02 +01001600 len = 0;
1601 do len++; while (*++s == '\'');
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001602
1603 q = p = makestrspace(len + 3, p);
1604
1605 *q++ = '"';
Denys Vlasenkocd716832009-11-28 22:14:02 +01001606 q = (char *)memcpy(q, s - len, len) + len;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001607 *q++ = '"';
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001608
1609 STADJUST(q - p, p);
1610 } while (*s);
1611
Denys Vlasenkocd716832009-11-28 22:14:02 +01001612 USTPUTC('\0', p);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001613
1614 return stackblock();
1615}
1616
1617
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00001618/* ============ nextopt */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001619
1620static char **argptr; /* argument list for builtin commands */
1621static char *optionarg; /* set by nextopt (like getopt) */
1622static char *optptr; /* used by nextopt */
1623
1624/*
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001625 * XXX - should get rid of. Have all builtins use getopt(3).
1626 * The library getopt must have the BSD extension static variable
1627 * "optreset", otherwise it can't be used within the shell safely.
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001628 *
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001629 * Standard option processing (a la getopt) for builtin routines.
1630 * The only argument that is passed to nextopt is the option string;
1631 * the other arguments are unnecessary. It returns the character,
1632 * or '\0' on end of input.
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001633 */
1634static int
1635nextopt(const char *optstring)
1636{
1637 char *p;
1638 const char *q;
1639 char c;
1640
1641 p = optptr;
1642 if (p == NULL || *p == '\0') {
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001643 /* We ate entire "-param", take next one */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001644 p = *argptr;
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001645 if (p == NULL)
1646 return '\0';
1647 if (*p != '-')
1648 return '\0';
1649 if (*++p == '\0') /* just "-" ? */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001650 return '\0';
1651 argptr++;
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001652 if (LONE_DASH(p)) /* "--" ? */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001653 return '\0';
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001654 /* p => next "-param" */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001655 }
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001656 /* p => some option char in the middle of a "-param" */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001657 c = *p++;
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +00001658 for (q = optstring; *q != c;) {
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001659 if (*q == '\0')
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00001660 ash_msg_and_raise_error("illegal option -%c", c);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001661 if (*++q == ':')
1662 q++;
1663 }
1664 if (*++q == ':') {
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001665 if (*p == '\0') {
1666 p = *argptr++;
1667 if (p == NULL)
1668 ash_msg_and_raise_error("no arg for -%c option", c);
1669 }
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001670 optionarg = p;
1671 p = NULL;
1672 }
1673 optptr = p;
1674 return c;
1675}
1676
1677
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00001678/* ============ Shell variables */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001679
Denis Vlasenko01631112007-12-16 17:20:38 +00001680/*
1681 * The parsefile structure pointed to by the global variable parsefile
1682 * contains information about the current file being read.
1683 */
Denis Vlasenko01631112007-12-16 17:20:38 +00001684struct shparam {
1685 int nparam; /* # of positional parameters (without $0) */
1686#if ENABLE_ASH_GETOPTS
1687 int optind; /* next parameter to be processed by getopts */
1688 int optoff; /* used by getopts */
1689#endif
1690 unsigned char malloced; /* if parameter list dynamically allocated */
1691 char **p; /* parameter list */
1692};
1693
1694/*
1695 * Free the list of positional parameters.
1696 */
1697static void
1698freeparam(volatile struct shparam *param)
1699{
Denis Vlasenko01631112007-12-16 17:20:38 +00001700 if (param->malloced) {
Denis Vlasenko3177ba02008-07-13 20:39:23 +00001701 char **ap, **ap1;
1702 ap = ap1 = param->p;
1703 while (*ap)
1704 free(*ap++);
1705 free(ap1);
Denis Vlasenko01631112007-12-16 17:20:38 +00001706 }
1707}
1708
1709#if ENABLE_ASH_GETOPTS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001710static void FAST_FUNC getoptsreset(const char *value);
Denis Vlasenko01631112007-12-16 17:20:38 +00001711#endif
1712
1713struct var {
1714 struct var *next; /* next entry in hash list */
1715 int flags; /* flags are defined above */
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02001716 const char *var_text; /* name=value */
1717 void (*var_func)(const char *) FAST_FUNC; /* function to be called when */
Denis Vlasenko01631112007-12-16 17:20:38 +00001718 /* the variable gets set/unset */
1719};
1720
1721struct localvar {
1722 struct localvar *next; /* next local variable in list */
1723 struct var *vp; /* the variable that was made local */
1724 int flags; /* saved flags */
1725 const char *text; /* saved text */
1726};
1727
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001728/* flags */
1729#define VEXPORT 0x01 /* variable is exported */
1730#define VREADONLY 0x02 /* variable cannot be modified */
1731#define VSTRFIXED 0x04 /* variable struct is statically allocated */
1732#define VTEXTFIXED 0x08 /* text is statically allocated */
1733#define VSTACK 0x10 /* text is allocated on the stack */
1734#define VUNSET 0x20 /* the variable is not set */
1735#define VNOFUNC 0x40 /* don't call the callback function */
1736#define VNOSET 0x80 /* do not set variable - just readonly test */
1737#define VNOSAVE 0x100 /* when text is on the heap before setvareq */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00001738#if ENABLE_ASH_RANDOM_SUPPORT
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00001739# define VDYNAMIC 0x200 /* dynamic variable */
1740#else
1741# define VDYNAMIC 0
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001742#endif
1743
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00001744
Denis Vlasenko01631112007-12-16 17:20:38 +00001745/* Need to be before varinit_data[] */
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00001746#if ENABLE_LOCALE_SUPPORT
Denys Vlasenko2634bf32009-06-09 18:40:07 +02001747static void FAST_FUNC
Denis Vlasenkoa8915072007-02-23 21:10:06 +00001748change_lc_all(const char *value)
1749{
1750 if (value && *value != '\0')
1751 setlocale(LC_ALL, value);
1752}
Denys Vlasenko2634bf32009-06-09 18:40:07 +02001753static void FAST_FUNC
Denis Vlasenkoa8915072007-02-23 21:10:06 +00001754change_lc_ctype(const char *value)
1755{
1756 if (value && *value != '\0')
1757 setlocale(LC_CTYPE, value);
1758}
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00001759#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001760#if ENABLE_ASH_MAIL
1761static void chkmail(void);
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001762static void changemail(const char *) FAST_FUNC;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001763#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001764static void changepath(const char *) FAST_FUNC;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001765#if ENABLE_ASH_RANDOM_SUPPORT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001766static void change_random(const char *) FAST_FUNC;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001767#endif
1768
Denis Vlasenko01631112007-12-16 17:20:38 +00001769static const struct {
1770 int flags;
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02001771 const char *var_text;
1772 void (*var_func)(const char *) FAST_FUNC;
Denis Vlasenko01631112007-12-16 17:20:38 +00001773} varinit_data[] = {
Denis Vlasenko01631112007-12-16 17:20:38 +00001774 { VSTRFIXED|VTEXTFIXED , defifsvar , NULL },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001775#if ENABLE_ASH_MAIL
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02001776 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL" , changemail },
1777 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH" , changemail },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001778#endif
Denis Vlasenko01631112007-12-16 17:20:38 +00001779 { VSTRFIXED|VTEXTFIXED , bb_PATH_root_path, changepath },
1780 { VSTRFIXED|VTEXTFIXED , "PS1=$ " , NULL },
1781 { VSTRFIXED|VTEXTFIXED , "PS2=> " , NULL },
1782 { VSTRFIXED|VTEXTFIXED , "PS4=+ " , NULL },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001783#if ENABLE_ASH_GETOPTS
Denis Vlasenko01631112007-12-16 17:20:38 +00001784 { VSTRFIXED|VTEXTFIXED , "OPTIND=1" , getoptsreset },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001785#endif
1786#if ENABLE_ASH_RANDOM_SUPPORT
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02001787 { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM", change_random },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001788#endif
1789#if ENABLE_LOCALE_SUPPORT
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02001790 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL" , change_lc_all },
1791 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE" , change_lc_ctype },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001792#endif
1793#if ENABLE_FEATURE_EDITING_SAVEHISTORY
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02001794 { VSTRFIXED|VTEXTFIXED|VUNSET, "HISTFILE" , NULL },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001795#endif
1796};
1797
Denis Vlasenko0b769642008-07-24 07:54:57 +00001798struct redirtab;
Denis Vlasenko01631112007-12-16 17:20:38 +00001799
1800struct globals_var {
1801 struct shparam shellparam; /* $@ current positional parameters */
1802 struct redirtab *redirlist;
1803 int g_nullredirs;
1804 int preverrout_fd; /* save fd2 before print debug if xflag is set. */
1805 struct var *vartab[VTABSIZE];
1806 struct var varinit[ARRAY_SIZE(varinit_data)];
1807};
Denis Vlasenko574f2f42008-02-27 18:41:59 +00001808extern struct globals_var *const ash_ptr_to_globals_var;
1809#define G_var (*ash_ptr_to_globals_var)
Denis Vlasenko01631112007-12-16 17:20:38 +00001810#define shellparam (G_var.shellparam )
Denis Vlasenko0b769642008-07-24 07:54:57 +00001811//#define redirlist (G_var.redirlist )
Denis Vlasenko01631112007-12-16 17:20:38 +00001812#define g_nullredirs (G_var.g_nullredirs )
1813#define preverrout_fd (G_var.preverrout_fd)
1814#define vartab (G_var.vartab )
1815#define varinit (G_var.varinit )
1816#define INIT_G_var() do { \
Denis Vlasenko6b06cb82008-05-15 21:30:45 +00001817 unsigned i; \
Denis Vlasenko574f2f42008-02-27 18:41:59 +00001818 (*(struct globals_var**)&ash_ptr_to_globals_var) = xzalloc(sizeof(G_var)); \
1819 barrier(); \
Denis Vlasenko01631112007-12-16 17:20:38 +00001820 for (i = 0; i < ARRAY_SIZE(varinit_data); i++) { \
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02001821 varinit[i].flags = varinit_data[i].flags; \
1822 varinit[i].var_text = varinit_data[i].var_text; \
1823 varinit[i].var_func = varinit_data[i].var_func; \
Denis Vlasenko01631112007-12-16 17:20:38 +00001824 } \
1825} while (0)
1826
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001827#define vifs varinit[0]
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001828#if ENABLE_ASH_MAIL
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001829# define vmail (&vifs)[1]
1830# define vmpath (&vmail)[1]
1831# define vpath (&vmpath)[1]
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001832#else
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001833# define vpath (&vifs)[1]
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001834#endif
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001835#define vps1 (&vpath)[1]
1836#define vps2 (&vps1)[1]
1837#define vps4 (&vps2)[1]
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001838#if ENABLE_ASH_GETOPTS
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001839# define voptind (&vps4)[1]
1840# if ENABLE_ASH_RANDOM_SUPPORT
1841# define vrandom (&voptind)[1]
1842# endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001843#else
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001844# if ENABLE_ASH_RANDOM_SUPPORT
1845# define vrandom (&vps4)[1]
1846# endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001847#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001848
1849/*
1850 * The following macros access the values of the above variables.
1851 * They have to skip over the name. They return the null string
1852 * for unset variables.
1853 */
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02001854#define ifsval() (vifs.var_text + 4)
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001855#define ifsset() ((vifs.flags & VUNSET) == 0)
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001856#if ENABLE_ASH_MAIL
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02001857# define mailval() (vmail.var_text + 5)
1858# define mpathval() (vmpath.var_text + 9)
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001859# define mpathset() ((vmpath.flags & VUNSET) == 0)
1860#endif
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02001861#define pathval() (vpath.var_text + 5)
1862#define ps1val() (vps1.var_text + 4)
1863#define ps2val() (vps2.var_text + 4)
1864#define ps4val() (vps4.var_text + 4)
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001865#if ENABLE_ASH_GETOPTS
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02001866# define optindval() (voptind.var_text + 7)
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001867#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001868
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001869
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001870#define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
1871#define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
1872
Denis Vlasenko01631112007-12-16 17:20:38 +00001873#if ENABLE_ASH_GETOPTS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001874static void FAST_FUNC
Denis Vlasenko01631112007-12-16 17:20:38 +00001875getoptsreset(const char *value)
1876{
1877 shellparam.optind = number(value);
1878 shellparam.optoff = -1;
1879}
1880#endif
1881
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001882/*
1883 * Return of a legal variable name (a letter or underscore followed by zero or
1884 * more letters, underscores, and digits).
1885 */
Denys Vlasenko03dad222010-01-12 23:29:57 +01001886static char* FAST_FUNC
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001887endofname(const char *name)
1888{
1889 char *p;
1890
1891 p = (char *) name;
1892 if (!is_name(*p))
1893 return p;
1894 while (*++p) {
1895 if (!is_in_name(*p))
1896 break;
1897 }
1898 return p;
1899}
1900
1901/*
1902 * Compares two strings up to the first = or '\0'. The first
1903 * string must be terminated by '='; the second may be terminated by
1904 * either '=' or '\0'.
1905 */
1906static int
1907varcmp(const char *p, const char *q)
1908{
1909 int c, d;
1910
1911 while ((c = *p) == (d = *q)) {
1912 if (!c || c == '=')
1913 goto out;
1914 p++;
1915 q++;
1916 }
1917 if (c == '=')
Denis Vlasenko9650f362007-02-23 01:04:37 +00001918 c = '\0';
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001919 if (d == '=')
Denis Vlasenko9650f362007-02-23 01:04:37 +00001920 d = '\0';
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001921 out:
1922 return c - d;
1923}
1924
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001925/*
1926 * Find the appropriate entry in the hash table from the name.
1927 */
1928static struct var **
1929hashvar(const char *p)
1930{
1931 unsigned hashval;
1932
1933 hashval = ((unsigned char) *p) << 4;
1934 while (*p && *p != '=')
1935 hashval += (unsigned char) *p++;
1936 return &vartab[hashval % VTABSIZE];
1937}
1938
1939static int
1940vpcmp(const void *a, const void *b)
1941{
1942 return varcmp(*(const char **)a, *(const char **)b);
1943}
1944
1945/*
1946 * This routine initializes the builtin variables.
1947 */
1948static void
1949initvar(void)
1950{
1951 struct var *vp;
1952 struct var *end;
1953 struct var **vpp;
1954
1955 /*
1956 * PS1 depends on uid
1957 */
1958#if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02001959 vps1.var_text = "PS1=\\w \\$ ";
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001960#else
1961 if (!geteuid())
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02001962 vps1.var_text = "PS1=# ";
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001963#endif
1964 vp = varinit;
Denis Vlasenko80b8b392007-06-25 10:55:35 +00001965 end = vp + ARRAY_SIZE(varinit);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001966 do {
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02001967 vpp = hashvar(vp->var_text);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001968 vp->next = *vpp;
1969 *vpp = vp;
1970 } while (++vp < end);
1971}
1972
1973static struct var **
1974findvar(struct var **vpp, const char *name)
1975{
1976 for (; *vpp; vpp = &(*vpp)->next) {
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02001977 if (varcmp((*vpp)->var_text, name) == 0) {
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001978 break;
1979 }
1980 }
1981 return vpp;
1982}
1983
1984/*
1985 * Find the value of a variable. Returns NULL if not set.
1986 */
Denys Vlasenko03dad222010-01-12 23:29:57 +01001987static const char* FAST_FUNC
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001988lookupvar(const char *name)
1989{
1990 struct var *v;
1991
1992 v = *findvar(hashvar(name), name);
1993 if (v) {
Denis Vlasenko448d30e2008-06-27 00:24:11 +00001994#if ENABLE_ASH_RANDOM_SUPPORT
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001995 /*
1996 * Dynamic variables are implemented roughly the same way they are
1997 * in bash. Namely, they're "special" so long as they aren't unset.
1998 * As soon as they're unset, they're no longer dynamic, and dynamic
1999 * lookup will no longer happen at that point. -- PFM.
2000 */
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02002001 if (v->flags & VDYNAMIC)
2002 v->var_func(NULL);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002003#endif
2004 if (!(v->flags & VUNSET))
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02002005 return var_end(v->var_text);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002006 }
2007 return NULL;
2008}
2009
2010/*
2011 * Search the environment of a builtin command.
2012 */
Mike Frysinger98c52642009-04-02 10:02:37 +00002013static const char *
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002014bltinlookup(const char *name)
2015{
2016 struct strlist *sp;
2017
2018 for (sp = cmdenviron; sp; sp = sp->next) {
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02002019 if (varcmp(sp->text, name) == 0)
2020 return var_end(sp->text);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002021 }
2022 return lookupvar(name);
2023}
2024
2025/*
2026 * Same as setvar except that the variable and value are passed in
2027 * the first argument as name=value. Since the first argument will
2028 * be actually stored in the table, it should not be a string that
2029 * will go away.
2030 * Called with interrupts off.
2031 */
2032static void
2033setvareq(char *s, int flags)
2034{
2035 struct var *vp, **vpp;
2036
2037 vpp = hashvar(s);
2038 flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
2039 vp = *findvar(vpp, s);
2040 if (vp) {
2041 if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
2042 const char *n;
2043
2044 if (flags & VNOSAVE)
2045 free(s);
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02002046 n = vp->var_text;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002047 ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
2048 }
2049
2050 if (flags & VNOSET)
2051 return;
2052
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02002053 if (vp->var_func && !(flags & VNOFUNC))
2054 vp->var_func(var_end(s));
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002055
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02002056 if (!(vp->flags & (VTEXTFIXED|VSTACK)))
2057 free((char*)vp->var_text);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002058
2059 flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
2060 } else {
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02002061 /* variable s is not found */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002062 if (flags & VNOSET)
2063 return;
Denis Vlasenko597906c2008-02-20 16:38:54 +00002064 vp = ckzalloc(sizeof(*vp));
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002065 vp->next = *vpp;
Denis Vlasenko597906c2008-02-20 16:38:54 +00002066 /*vp->func = NULL; - ckzalloc did it */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002067 *vpp = vp;
2068 }
2069 if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
2070 s = ckstrdup(s);
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02002071 vp->var_text = s;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002072 vp->flags = flags;
2073}
2074
2075/*
2076 * Set the value of a variable. The flags argument is ored with the
2077 * flags of the variable. If val is NULL, the variable is unset.
2078 */
2079static void
2080setvar(const char *name, const char *val, int flags)
2081{
2082 char *p, *q;
2083 size_t namelen;
2084 char *nameeq;
2085 size_t vallen;
2086
2087 q = endofname(name);
2088 p = strchrnul(q, '=');
2089 namelen = p - name;
2090 if (!namelen || p != q)
2091 ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
2092 vallen = 0;
2093 if (val == NULL) {
2094 flags |= VUNSET;
2095 } else {
2096 vallen = strlen(val);
2097 }
2098 INT_OFF;
2099 nameeq = ckmalloc(namelen + vallen + 2);
Denis Vlasenko29eb3592008-05-18 14:06:08 +00002100 p = (char *)memcpy(nameeq, name, namelen) + namelen;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002101 if (val) {
2102 *p++ = '=';
Denis Vlasenko29eb3592008-05-18 14:06:08 +00002103 p = (char *)memcpy(p, val, vallen) + vallen;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002104 }
2105 *p = '\0';
2106 setvareq(nameeq, flags | VNOSAVE);
2107 INT_ON;
2108}
2109
Denys Vlasenko03dad222010-01-12 23:29:57 +01002110static void FAST_FUNC
2111setvar2(const char *name, const char *val)
2112{
2113 setvar(name, val, 0);
2114}
2115
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002116#if ENABLE_ASH_GETOPTS
2117/*
2118 * Safe version of setvar, returns 1 on success 0 on failure.
2119 */
2120static int
2121setvarsafe(const char *name, const char *val, int flags)
2122{
2123 int err;
2124 volatile int saveint;
2125 struct jmploc *volatile savehandler = exception_handler;
2126 struct jmploc jmploc;
2127
2128 SAVE_INT(saveint);
2129 if (setjmp(jmploc.loc))
2130 err = 1;
2131 else {
2132 exception_handler = &jmploc;
2133 setvar(name, val, flags);
2134 err = 0;
2135 }
2136 exception_handler = savehandler;
2137 RESTORE_INT(saveint);
2138 return err;
2139}
2140#endif
2141
2142/*
2143 * Unset the specified variable.
2144 */
2145static int
2146unsetvar(const char *s)
2147{
2148 struct var **vpp;
2149 struct var *vp;
2150 int retval;
2151
2152 vpp = findvar(hashvar(s), s);
2153 vp = *vpp;
2154 retval = 2;
2155 if (vp) {
2156 int flags = vp->flags;
2157
2158 retval = 1;
2159 if (flags & VREADONLY)
2160 goto out;
Denis Vlasenko448d30e2008-06-27 00:24:11 +00002161#if ENABLE_ASH_RANDOM_SUPPORT
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002162 vp->flags &= ~VDYNAMIC;
2163#endif
2164 if (flags & VUNSET)
2165 goto ok;
2166 if ((flags & VSTRFIXED) == 0) {
2167 INT_OFF;
2168 if ((flags & (VTEXTFIXED|VSTACK)) == 0)
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02002169 free((char*)vp->var_text);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002170 *vpp = vp->next;
2171 free(vp);
2172 INT_ON;
2173 } else {
2174 setvar(s, 0, 0);
2175 vp->flags &= ~VEXPORT;
2176 }
2177 ok:
2178 retval = 0;
2179 }
2180 out:
2181 return retval;
2182}
2183
2184/*
2185 * Process a linked list of variable assignments.
2186 */
2187static void
2188listsetvar(struct strlist *list_set_var, int flags)
2189{
2190 struct strlist *lp = list_set_var;
2191
2192 if (!lp)
2193 return;
2194 INT_OFF;
2195 do {
2196 setvareq(lp->text, flags);
Denis Vlasenko9650f362007-02-23 01:04:37 +00002197 lp = lp->next;
2198 } while (lp);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002199 INT_ON;
2200}
2201
2202/*
2203 * Generate a list of variables satisfying the given conditions.
2204 */
2205static char **
2206listvars(int on, int off, char ***end)
2207{
2208 struct var **vpp;
2209 struct var *vp;
2210 char **ep;
2211 int mask;
2212
2213 STARTSTACKSTR(ep);
2214 vpp = vartab;
2215 mask = on | off;
2216 do {
2217 for (vp = *vpp; vp; vp = vp->next) {
2218 if ((vp->flags & mask) == on) {
2219 if (ep == stackstrend())
2220 ep = growstackstr();
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02002221 *ep++ = (char*)vp->var_text;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002222 }
2223 }
2224 } while (++vpp < vartab + VTABSIZE);
2225 if (ep == stackstrend())
2226 ep = growstackstr();
2227 if (end)
2228 *end = ep;
2229 *ep++ = NULL;
2230 return grabstackstr(ep);
2231}
2232
2233
2234/* ============ Path search helper
2235 *
2236 * The variable path (passed by reference) should be set to the start
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02002237 * of the path before the first call; path_advance will update
2238 * this value as it proceeds. Successive calls to path_advance will return
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002239 * the possible path expansions in sequence. If an option (indicated by
2240 * a percent sign) appears in the path entry then the global variable
2241 * pathopt will be set to point to it; otherwise pathopt will be set to
2242 * NULL.
2243 */
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02002244static const char *pathopt; /* set by path_advance */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002245
2246static char *
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02002247path_advance(const char **path, const char *name)
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002248{
2249 const char *p;
2250 char *q;
2251 const char *start;
2252 size_t len;
2253
2254 if (*path == NULL)
2255 return NULL;
2256 start = *path;
Denis Vlasenkof7d56652008-03-25 05:51:41 +00002257 for (p = start; *p && *p != ':' && *p != '%'; p++)
2258 continue;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002259 len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
2260 while (stackblocksize() < len)
2261 growstackblock();
2262 q = stackblock();
2263 if (p != start) {
2264 memcpy(q, start, p - start);
2265 q += p - start;
2266 *q++ = '/';
2267 }
2268 strcpy(q, name);
2269 pathopt = NULL;
2270 if (*p == '%') {
2271 pathopt = ++p;
Denis Vlasenkof7d56652008-03-25 05:51:41 +00002272 while (*p && *p != ':')
2273 p++;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002274 }
2275 if (*p == ':')
2276 *path = p + 1;
2277 else
2278 *path = NULL;
2279 return stalloc(len);
2280}
2281
2282
2283/* ============ Prompt */
2284
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +00002285static smallint doprompt; /* if set, prompt the user */
2286static smallint needprompt; /* true if interactive and at start of line */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002287
2288#if ENABLE_FEATURE_EDITING
2289static line_input_t *line_input_state;
2290static const char *cmdedit_prompt;
2291static void
2292putprompt(const char *s)
2293{
2294 if (ENABLE_ASH_EXPAND_PRMT) {
2295 free((char*)cmdedit_prompt);
Denis Vlasenko4222ae42007-02-25 02:37:49 +00002296 cmdedit_prompt = ckstrdup(s);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002297 return;
2298 }
2299 cmdedit_prompt = s;
2300}
2301#else
2302static void
2303putprompt(const char *s)
2304{
2305 out2str(s);
2306}
2307#endif
2308
2309#if ENABLE_ASH_EXPAND_PRMT
2310/* expandstr() needs parsing machinery, so it is far away ahead... */
2311static const char *expandstr(const char *ps);
2312#else
2313#define expandstr(s) s
2314#endif
2315
2316static void
2317setprompt(int whichprompt)
2318{
2319 const char *prompt;
2320#if ENABLE_ASH_EXPAND_PRMT
2321 struct stackmark smark;
2322#endif
2323
2324 needprompt = 0;
2325
2326 switch (whichprompt) {
2327 case 1:
2328 prompt = ps1val();
2329 break;
2330 case 2:
2331 prompt = ps2val();
2332 break;
2333 default: /* 0 */
2334 prompt = nullstr;
2335 }
2336#if ENABLE_ASH_EXPAND_PRMT
2337 setstackmark(&smark);
2338 stalloc(stackblocksize());
2339#endif
2340 putprompt(expandstr(prompt));
2341#if ENABLE_ASH_EXPAND_PRMT
2342 popstackmark(&smark);
2343#endif
2344}
2345
2346
2347/* ============ The cd and pwd commands */
2348
2349#define CD_PHYSICAL 1
2350#define CD_PRINT 2
2351
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002352static int
2353cdopt(void)
2354{
2355 int flags = 0;
2356 int i, j;
2357
2358 j = 'L';
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02002359 while ((i = nextopt("LP")) != '\0') {
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002360 if (i != j) {
2361 flags ^= CD_PHYSICAL;
2362 j = i;
2363 }
2364 }
2365
2366 return flags;
2367}
2368
2369/*
2370 * Update curdir (the name of the current directory) in response to a
2371 * cd command.
2372 */
2373static const char *
2374updatepwd(const char *dir)
2375{
2376 char *new;
2377 char *p;
2378 char *cdcomppath;
2379 const char *lim;
2380
2381 cdcomppath = ststrdup(dir);
2382 STARTSTACKSTR(new);
2383 if (*dir != '/') {
2384 if (curdir == nullstr)
2385 return 0;
2386 new = stack_putstr(curdir, new);
2387 }
2388 new = makestrspace(strlen(dir) + 2, new);
Denis Vlasenko29eb3592008-05-18 14:06:08 +00002389 lim = (char *)stackblock() + 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002390 if (*dir != '/') {
2391 if (new[-1] != '/')
2392 USTPUTC('/', new);
2393 if (new > lim && *lim == '/')
2394 lim++;
2395 } else {
2396 USTPUTC('/', new);
2397 cdcomppath++;
2398 if (dir[1] == '/' && dir[2] != '/') {
2399 USTPUTC('/', new);
2400 cdcomppath++;
2401 lim++;
2402 }
2403 }
2404 p = strtok(cdcomppath, "/");
2405 while (p) {
2406 switch (*p) {
2407 case '.':
2408 if (p[1] == '.' && p[2] == '\0') {
2409 while (new > lim) {
2410 STUNPUTC(new);
2411 if (new[-1] == '/')
2412 break;
2413 }
2414 break;
Denis Vlasenko16abcd92007-04-13 23:59:52 +00002415 }
2416 if (p[1] == '\0')
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002417 break;
2418 /* fall through */
2419 default:
2420 new = stack_putstr(p, new);
2421 USTPUTC('/', new);
2422 }
2423 p = strtok(0, "/");
2424 }
2425 if (new > lim)
2426 STUNPUTC(new);
2427 *new = 0;
2428 return stackblock();
2429}
2430
2431/*
2432 * Find out what the current directory is. If we already know the current
2433 * directory, this routine returns immediately.
2434 */
2435static char *
2436getpwd(void)
2437{
Denis Vlasenko01631112007-12-16 17:20:38 +00002438 char *dir = getcwd(NULL, 0); /* huh, using glibc extension? */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002439 return dir ? dir : nullstr;
2440}
2441
2442static void
2443setpwd(const char *val, int setold)
2444{
2445 char *oldcur, *dir;
2446
2447 oldcur = dir = curdir;
2448
2449 if (setold) {
2450 setvar("OLDPWD", oldcur, VEXPORT);
2451 }
2452 INT_OFF;
2453 if (physdir != nullstr) {
2454 if (physdir != oldcur)
2455 free(physdir);
2456 physdir = nullstr;
2457 }
2458 if (oldcur == val || !val) {
2459 char *s = getpwd();
2460 physdir = s;
2461 if (!val)
2462 dir = s;
2463 } else
2464 dir = ckstrdup(val);
2465 if (oldcur != dir && oldcur != nullstr) {
2466 free(oldcur);
2467 }
2468 curdir = dir;
2469 INT_ON;
2470 setvar("PWD", dir, VEXPORT);
2471}
2472
2473static void hashcd(void);
2474
2475/*
2476 * Actually do the chdir. We also call hashcd to let the routines in exec.c
2477 * know that the current directory has changed.
2478 */
2479static int
2480docd(const char *dest, int flags)
2481{
Denys Vlasenko4b1100e2010-03-05 14:10:54 +01002482 const char *dir = NULL;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002483 int err;
2484
2485 TRACE(("docd(\"%s\", %d) called\n", dest, flags));
2486
2487 INT_OFF;
2488 if (!(flags & CD_PHYSICAL)) {
2489 dir = updatepwd(dest);
2490 if (dir)
2491 dest = dir;
2492 }
2493 err = chdir(dest);
2494 if (err)
2495 goto out;
2496 setpwd(dir, 1);
2497 hashcd();
2498 out:
2499 INT_ON;
2500 return err;
2501}
2502
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02002503static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00002504cdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002505{
2506 const char *dest;
2507 const char *path;
2508 const char *p;
2509 char c;
2510 struct stat statb;
2511 int flags;
2512
2513 flags = cdopt();
2514 dest = *argptr;
2515 if (!dest)
Denys Vlasenkoea8b2522010-06-02 12:57:26 +02002516 dest = bltinlookup("HOME");
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002517 else if (LONE_DASH(dest)) {
2518 dest = bltinlookup("OLDPWD");
2519 flags |= CD_PRINT;
2520 }
2521 if (!dest)
2522 dest = nullstr;
2523 if (*dest == '/')
2524 goto step7;
2525 if (*dest == '.') {
2526 c = dest[1];
2527 dotdot:
2528 switch (c) {
2529 case '\0':
2530 case '/':
2531 goto step6;
2532 case '.':
2533 c = dest[2];
2534 if (c != '.')
2535 goto dotdot;
2536 }
2537 }
2538 if (!*dest)
2539 dest = ".";
2540 path = bltinlookup("CDPATH");
2541 if (!path) {
2542 step6:
2543 step7:
2544 p = dest;
2545 goto docd;
2546 }
2547 do {
2548 c = *path;
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02002549 p = path_advance(&path, dest);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002550 if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
2551 if (c && c != ':')
2552 flags |= CD_PRINT;
2553 docd:
2554 if (!docd(p, flags))
2555 goto out;
2556 break;
2557 }
2558 } while (path);
2559 ash_msg_and_raise_error("can't cd to %s", dest);
2560 /* NOTREACHED */
2561 out:
2562 if (flags & CD_PRINT)
Denys Vlasenkoea8b2522010-06-02 12:57:26 +02002563 out1fmt("%s\n", curdir);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002564 return 0;
2565}
2566
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02002567static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00002568pwdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002569{
2570 int flags;
2571 const char *dir = curdir;
2572
2573 flags = cdopt();
2574 if (flags) {
2575 if (physdir == nullstr)
2576 setpwd(dir, 0);
2577 dir = physdir;
2578 }
Denys Vlasenkoea8b2522010-06-02 12:57:26 +02002579 out1fmt("%s\n", dir);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002580 return 0;
2581}
2582
Denis Vlasenko0c032a42007-02-23 01:03:40 +00002583
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00002584/* ============ ... */
Eric Andersenc470f442003-07-28 09:56:35 +00002585
Denis Vlasenko834dee72008-10-07 09:18:30 +00002586
Denys Vlasenko82dd14a2010-05-17 10:10:01 +02002587#define IBUFSIZ (ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 1024)
Eric Andersenc470f442003-07-28 09:56:35 +00002588
Eric Andersenc470f442003-07-28 09:56:35 +00002589/* Syntax classes */
Denis Vlasenko834dee72008-10-07 09:18:30 +00002590#define CWORD 0 /* character is nothing special */
2591#define CNL 1 /* newline character */
2592#define CBACK 2 /* a backslash character */
2593#define CSQUOTE 3 /* single quote */
2594#define CDQUOTE 4 /* double quote */
Eric Andersenc470f442003-07-28 09:56:35 +00002595#define CENDQUOTE 5 /* a terminating quote */
Denis Vlasenko834dee72008-10-07 09:18:30 +00002596#define CBQUOTE 6 /* backwards single quote */
2597#define CVAR 7 /* a dollar sign */
2598#define CENDVAR 8 /* a '}' character */
2599#define CLP 9 /* a left paren in arithmetic */
2600#define CRP 10 /* a right paren in arithmetic */
Eric Andersenc470f442003-07-28 09:56:35 +00002601#define CENDFILE 11 /* end of file */
Denis Vlasenko834dee72008-10-07 09:18:30 +00002602#define CCTL 12 /* like CWORD, except it must be escaped */
2603#define CSPCL 13 /* these terminate a word */
2604#define CIGN 14 /* character should be ignored */
Eric Andersenc470f442003-07-28 09:56:35 +00002605
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002606#define PEOF 256
Denis Vlasenko131ae172007-02-18 13:00:19 +00002607#if ENABLE_ASH_ALIAS
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002608# define PEOA 257
Eric Andersenc470f442003-07-28 09:56:35 +00002609#endif
2610
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002611#define USE_SIT_FUNCTION ENABLE_ASH_OPTIMIZE_FOR_SIZE
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002612
Mike Frysinger98c52642009-04-02 10:02:37 +00002613#if ENABLE_SH_MATH_SUPPORT
Denys Vlasenko76bc2d62009-11-29 01:37:46 +01002614# define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8) | (d << 12))
Eric Andersenc470f442003-07-28 09:56:35 +00002615#else
Denys Vlasenko76bc2d62009-11-29 01:37:46 +01002616# define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8))
Denys Vlasenko76bc2d62009-11-29 01:37:46 +01002617#endif
Denys Vlasenko068d3862009-11-29 01:41:11 +01002618static const uint16_t S_I_T[] = {
Denys Vlasenko76bc2d62009-11-29 01:37:46 +01002619#if ENABLE_ASH_ALIAS
2620 SIT_ITEM(CSPCL , CIGN , CIGN , CIGN ), /* 0, PEOA */
2621#endif
2622 SIT_ITEM(CSPCL , CWORD , CWORD, CWORD ), /* 1, ' ' */
2623 SIT_ITEM(CNL , CNL , CNL , CNL ), /* 2, \n */
2624 SIT_ITEM(CWORD , CCTL , CCTL , CWORD ), /* 3, !*-/:=?[]~ */
2625 SIT_ITEM(CDQUOTE , CENDQUOTE, CWORD, CWORD ), /* 4, '"' */
2626 SIT_ITEM(CVAR , CVAR , CWORD, CVAR ), /* 5, $ */
2627 SIT_ITEM(CSQUOTE , CWORD , CENDQUOTE, CWORD), /* 6, "'" */
2628 SIT_ITEM(CSPCL , CWORD , CWORD, CLP ), /* 7, ( */
2629 SIT_ITEM(CSPCL , CWORD , CWORD, CRP ), /* 8, ) */
2630 SIT_ITEM(CBACK , CBACK , CCTL , CBACK ), /* 9, \ */
2631 SIT_ITEM(CBQUOTE , CBQUOTE , CWORD, CBQUOTE), /* 10, ` */
2632 SIT_ITEM(CENDVAR , CENDVAR , CWORD, CENDVAR), /* 11, } */
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002633#if !USE_SIT_FUNCTION
Denys Vlasenko76bc2d62009-11-29 01:37:46 +01002634 SIT_ITEM(CENDFILE, CENDFILE , CENDFILE, CENDFILE),/* 12, PEOF */
2635 SIT_ITEM(CWORD , CWORD , CWORD, CWORD ), /* 13, 0-9A-Za-z */
2636 SIT_ITEM(CCTL , CCTL , CCTL , CCTL ) /* 14, CTLESC ... */
2637#endif
2638#undef SIT_ITEM
Eric Andersenc470f442003-07-28 09:56:35 +00002639};
Denys Vlasenko76bc2d62009-11-29 01:37:46 +01002640/* Constants below must match table above */
2641enum {
2642#if ENABLE_ASH_ALIAS
2643 CSPCL_CIGN_CIGN_CIGN , /* 0 */
2644#endif
2645 CSPCL_CWORD_CWORD_CWORD , /* 1 */
2646 CNL_CNL_CNL_CNL , /* 2 */
2647 CWORD_CCTL_CCTL_CWORD , /* 3 */
2648 CDQUOTE_CENDQUOTE_CWORD_CWORD , /* 4 */
2649 CVAR_CVAR_CWORD_CVAR , /* 5 */
2650 CSQUOTE_CWORD_CENDQUOTE_CWORD , /* 6 */
2651 CSPCL_CWORD_CWORD_CLP , /* 7 */
2652 CSPCL_CWORD_CWORD_CRP , /* 8 */
2653 CBACK_CBACK_CCTL_CBACK , /* 9 */
2654 CBQUOTE_CBQUOTE_CWORD_CBQUOTE , /* 10 */
2655 CENDVAR_CENDVAR_CWORD_CENDVAR , /* 11 */
2656 CENDFILE_CENDFILE_CENDFILE_CENDFILE, /* 12 */
2657 CWORD_CWORD_CWORD_CWORD , /* 13 */
2658 CCTL_CCTL_CCTL_CCTL , /* 14 */
2659};
Eric Andersen2870d962001-07-02 17:27:21 +00002660
Denys Vlasenkocd716832009-11-28 22:14:02 +01002661/* c in SIT(c, syntax) must be an *unsigned char* or PEOA or PEOF,
2662 * caller must ensure proper cast on it if c is *char_ptr!
2663 */
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002664/* Values for syntax param */
2665#define BASESYNTAX 0 /* not in quotes */
2666#define DQSYNTAX 1 /* in double quotes */
2667#define SQSYNTAX 2 /* in single quotes */
2668#define ARISYNTAX 3 /* in arithmetic */
2669#define PSSYNTAX 4 /* prompt. never passed to SIT() */
Denys Vlasenkocd716832009-11-28 22:14:02 +01002670
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002671#if USE_SIT_FUNCTION
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002672
Denis Vlasenko0c032a42007-02-23 01:03:40 +00002673static int
2674SIT(int c, int syntax)
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002675{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00002676 static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-/:;<=>?[\\]`|}~";
Denys Vlasenkocd716832009-11-28 22:14:02 +01002677# if ENABLE_ASH_ALIAS
2678 static const uint8_t syntax_index_table[] ALIGN1 = {
Eric Andersenc470f442003-07-28 09:56:35 +00002679 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
2680 7, 8, 3, 3, 3, 3, 1, 1, /* "()*-/:;<" */
2681 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
2682 11, 3 /* "}~" */
2683 };
Denys Vlasenkocd716832009-11-28 22:14:02 +01002684# else
2685 static const uint8_t syntax_index_table[] ALIGN1 = {
Eric Andersenc470f442003-07-28 09:56:35 +00002686 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
2687 6, 7, 2, 2, 2, 2, 0, 0, /* "()*-/:;<" */
2688 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
2689 10, 2 /* "}~" */
2690 };
Denys Vlasenkocd716832009-11-28 22:14:02 +01002691# endif
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002692 const char *s;
2693 int indx;
2694
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002695 if (c == PEOF)
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002696 return CENDFILE;
Denys Vlasenkocd716832009-11-28 22:14:02 +01002697# if ENABLE_ASH_ALIAS
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002698 if (c == PEOA)
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +00002699 indx = 0;
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002700 else
Denys Vlasenkocd716832009-11-28 22:14:02 +01002701# endif
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +00002702 {
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002703 /* Cast is purely for paranoia here,
2704 * just in case someone passed signed char to us */
2705 if ((unsigned char)c >= CTL_FIRST
2706 && (unsigned char)c <= CTL_LAST
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +00002707 ) {
2708 return CCTL;
2709 }
2710 s = strchrnul(spec_symbls, c);
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002711 if (*s == '\0')
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +00002712 return CWORD;
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +00002713 indx = syntax_index_table[s - spec_symbls];
2714 }
Denys Vlasenko76bc2d62009-11-29 01:37:46 +01002715 return (S_I_T[indx] >> (syntax*4)) & 0xf;
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002716}
2717
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00002718#else /* !USE_SIT_FUNCTION */
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002719
Denys Vlasenko76bc2d62009-11-29 01:37:46 +01002720static const uint8_t syntax_index_table[] = {
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00002721 /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
Denys Vlasenkocd716832009-11-28 22:14:02 +01002722 /* 0 */ CWORD_CWORD_CWORD_CWORD,
2723 /* 1 */ CWORD_CWORD_CWORD_CWORD,
2724 /* 2 */ CWORD_CWORD_CWORD_CWORD,
2725 /* 3 */ CWORD_CWORD_CWORD_CWORD,
2726 /* 4 */ CWORD_CWORD_CWORD_CWORD,
2727 /* 5 */ CWORD_CWORD_CWORD_CWORD,
2728 /* 6 */ CWORD_CWORD_CWORD_CWORD,
2729 /* 7 */ CWORD_CWORD_CWORD_CWORD,
2730 /* 8 */ CWORD_CWORD_CWORD_CWORD,
2731 /* 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
2732 /* 10 "\n" */ CNL_CNL_CNL_CNL,
2733 /* 11 */ CWORD_CWORD_CWORD_CWORD,
2734 /* 12 */ CWORD_CWORD_CWORD_CWORD,
2735 /* 13 */ CWORD_CWORD_CWORD_CWORD,
2736 /* 14 */ CWORD_CWORD_CWORD_CWORD,
2737 /* 15 */ CWORD_CWORD_CWORD_CWORD,
2738 /* 16 */ CWORD_CWORD_CWORD_CWORD,
2739 /* 17 */ CWORD_CWORD_CWORD_CWORD,
2740 /* 18 */ CWORD_CWORD_CWORD_CWORD,
2741 /* 19 */ CWORD_CWORD_CWORD_CWORD,
2742 /* 20 */ CWORD_CWORD_CWORD_CWORD,
2743 /* 21 */ CWORD_CWORD_CWORD_CWORD,
2744 /* 22 */ CWORD_CWORD_CWORD_CWORD,
2745 /* 23 */ CWORD_CWORD_CWORD_CWORD,
2746 /* 24 */ CWORD_CWORD_CWORD_CWORD,
2747 /* 25 */ CWORD_CWORD_CWORD_CWORD,
2748 /* 26 */ CWORD_CWORD_CWORD_CWORD,
2749 /* 27 */ CWORD_CWORD_CWORD_CWORD,
2750 /* 28 */ CWORD_CWORD_CWORD_CWORD,
2751 /* 29 */ CWORD_CWORD_CWORD_CWORD,
2752 /* 30 */ CWORD_CWORD_CWORD_CWORD,
2753 /* 31 */ CWORD_CWORD_CWORD_CWORD,
2754 /* 32 " " */ CSPCL_CWORD_CWORD_CWORD,
2755 /* 33 "!" */ CWORD_CCTL_CCTL_CWORD,
2756 /* 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
2757 /* 35 "#" */ CWORD_CWORD_CWORD_CWORD,
2758 /* 36 "$" */ CVAR_CVAR_CWORD_CVAR,
2759 /* 37 "%" */ CWORD_CWORD_CWORD_CWORD,
2760 /* 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
2761 /* 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
2762 /* 40 "(" */ CSPCL_CWORD_CWORD_CLP,
2763 /* 41 ")" */ CSPCL_CWORD_CWORD_CRP,
2764 /* 42 "*" */ CWORD_CCTL_CCTL_CWORD,
2765 /* 43 "+" */ CWORD_CWORD_CWORD_CWORD,
2766 /* 44 "," */ CWORD_CWORD_CWORD_CWORD,
2767 /* 45 "-" */ CWORD_CCTL_CCTL_CWORD,
2768 /* 46 "." */ CWORD_CWORD_CWORD_CWORD,
2769 /* 47 "/" */ CWORD_CCTL_CCTL_CWORD,
2770 /* 48 "0" */ CWORD_CWORD_CWORD_CWORD,
2771 /* 49 "1" */ CWORD_CWORD_CWORD_CWORD,
2772 /* 50 "2" */ CWORD_CWORD_CWORD_CWORD,
2773 /* 51 "3" */ CWORD_CWORD_CWORD_CWORD,
2774 /* 52 "4" */ CWORD_CWORD_CWORD_CWORD,
2775 /* 53 "5" */ CWORD_CWORD_CWORD_CWORD,
2776 /* 54 "6" */ CWORD_CWORD_CWORD_CWORD,
2777 /* 55 "7" */ CWORD_CWORD_CWORD_CWORD,
2778 /* 56 "8" */ CWORD_CWORD_CWORD_CWORD,
2779 /* 57 "9" */ CWORD_CWORD_CWORD_CWORD,
2780 /* 58 ":" */ CWORD_CCTL_CCTL_CWORD,
2781 /* 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
2782 /* 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
2783 /* 61 "=" */ CWORD_CCTL_CCTL_CWORD,
2784 /* 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
2785 /* 63 "?" */ CWORD_CCTL_CCTL_CWORD,
2786 /* 64 "@" */ CWORD_CWORD_CWORD_CWORD,
2787 /* 65 "A" */ CWORD_CWORD_CWORD_CWORD,
2788 /* 66 "B" */ CWORD_CWORD_CWORD_CWORD,
2789 /* 67 "C" */ CWORD_CWORD_CWORD_CWORD,
2790 /* 68 "D" */ CWORD_CWORD_CWORD_CWORD,
2791 /* 69 "E" */ CWORD_CWORD_CWORD_CWORD,
2792 /* 70 "F" */ CWORD_CWORD_CWORD_CWORD,
2793 /* 71 "G" */ CWORD_CWORD_CWORD_CWORD,
2794 /* 72 "H" */ CWORD_CWORD_CWORD_CWORD,
2795 /* 73 "I" */ CWORD_CWORD_CWORD_CWORD,
2796 /* 74 "J" */ CWORD_CWORD_CWORD_CWORD,
2797 /* 75 "K" */ CWORD_CWORD_CWORD_CWORD,
2798 /* 76 "L" */ CWORD_CWORD_CWORD_CWORD,
2799 /* 77 "M" */ CWORD_CWORD_CWORD_CWORD,
2800 /* 78 "N" */ CWORD_CWORD_CWORD_CWORD,
2801 /* 79 "O" */ CWORD_CWORD_CWORD_CWORD,
2802 /* 80 "P" */ CWORD_CWORD_CWORD_CWORD,
2803 /* 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
2804 /* 82 "R" */ CWORD_CWORD_CWORD_CWORD,
2805 /* 83 "S" */ CWORD_CWORD_CWORD_CWORD,
2806 /* 84 "T" */ CWORD_CWORD_CWORD_CWORD,
2807 /* 85 "U" */ CWORD_CWORD_CWORD_CWORD,
2808 /* 86 "V" */ CWORD_CWORD_CWORD_CWORD,
2809 /* 87 "W" */ CWORD_CWORD_CWORD_CWORD,
2810 /* 88 "X" */ CWORD_CWORD_CWORD_CWORD,
2811 /* 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
2812 /* 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
2813 /* 91 "[" */ CWORD_CCTL_CCTL_CWORD,
2814 /* 92 "\" */ CBACK_CBACK_CCTL_CBACK,
2815 /* 93 "]" */ CWORD_CCTL_CCTL_CWORD,
2816 /* 94 "^" */ CWORD_CWORD_CWORD_CWORD,
2817 /* 95 "_" */ CWORD_CWORD_CWORD_CWORD,
2818 /* 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
2819 /* 97 "a" */ CWORD_CWORD_CWORD_CWORD,
2820 /* 98 "b" */ CWORD_CWORD_CWORD_CWORD,
2821 /* 99 "c" */ CWORD_CWORD_CWORD_CWORD,
2822 /* 100 "d" */ CWORD_CWORD_CWORD_CWORD,
2823 /* 101 "e" */ CWORD_CWORD_CWORD_CWORD,
2824 /* 102 "f" */ CWORD_CWORD_CWORD_CWORD,
2825 /* 103 "g" */ CWORD_CWORD_CWORD_CWORD,
2826 /* 104 "h" */ CWORD_CWORD_CWORD_CWORD,
2827 /* 105 "i" */ CWORD_CWORD_CWORD_CWORD,
2828 /* 106 "j" */ CWORD_CWORD_CWORD_CWORD,
2829 /* 107 "k" */ CWORD_CWORD_CWORD_CWORD,
2830 /* 108 "l" */ CWORD_CWORD_CWORD_CWORD,
2831 /* 109 "m" */ CWORD_CWORD_CWORD_CWORD,
2832 /* 110 "n" */ CWORD_CWORD_CWORD_CWORD,
2833 /* 111 "o" */ CWORD_CWORD_CWORD_CWORD,
2834 /* 112 "p" */ CWORD_CWORD_CWORD_CWORD,
2835 /* 113 "q" */ CWORD_CWORD_CWORD_CWORD,
2836 /* 114 "r" */ CWORD_CWORD_CWORD_CWORD,
2837 /* 115 "s" */ CWORD_CWORD_CWORD_CWORD,
2838 /* 116 "t" */ CWORD_CWORD_CWORD_CWORD,
2839 /* 117 "u" */ CWORD_CWORD_CWORD_CWORD,
2840 /* 118 "v" */ CWORD_CWORD_CWORD_CWORD,
2841 /* 119 "w" */ CWORD_CWORD_CWORD_CWORD,
2842 /* 120 "x" */ CWORD_CWORD_CWORD_CWORD,
2843 /* 121 "y" */ CWORD_CWORD_CWORD_CWORD,
2844 /* 122 "z" */ CWORD_CWORD_CWORD_CWORD,
2845 /* 123 "{" */ CWORD_CWORD_CWORD_CWORD,
2846 /* 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
2847 /* 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
2848 /* 126 "~" */ CWORD_CCTL_CCTL_CWORD,
2849 /* 127 del */ CWORD_CWORD_CWORD_CWORD,
2850 /* 128 0x80 */ CWORD_CWORD_CWORD_CWORD,
2851 /* 129 CTLESC */ CCTL_CCTL_CCTL_CCTL,
2852 /* 130 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
2853 /* 131 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
2854 /* 132 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
2855 /* 133 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
2856 /* 134 CTLARI */ CCTL_CCTL_CCTL_CCTL,
2857 /* 135 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
2858 /* 136 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
2859 /* 137 */ CWORD_CWORD_CWORD_CWORD,
2860 /* 138 */ CWORD_CWORD_CWORD_CWORD,
2861 /* 139 */ CWORD_CWORD_CWORD_CWORD,
2862 /* 140 */ CWORD_CWORD_CWORD_CWORD,
2863 /* 141 */ CWORD_CWORD_CWORD_CWORD,
2864 /* 142 */ CWORD_CWORD_CWORD_CWORD,
2865 /* 143 */ CWORD_CWORD_CWORD_CWORD,
2866 /* 144 */ CWORD_CWORD_CWORD_CWORD,
2867 /* 145 */ CWORD_CWORD_CWORD_CWORD,
2868 /* 146 */ CWORD_CWORD_CWORD_CWORD,
2869 /* 147 */ CWORD_CWORD_CWORD_CWORD,
2870 /* 148 */ CWORD_CWORD_CWORD_CWORD,
2871 /* 149 */ CWORD_CWORD_CWORD_CWORD,
2872 /* 150 */ CWORD_CWORD_CWORD_CWORD,
2873 /* 151 */ CWORD_CWORD_CWORD_CWORD,
2874 /* 152 */ CWORD_CWORD_CWORD_CWORD,
2875 /* 153 */ CWORD_CWORD_CWORD_CWORD,
2876 /* 154 */ CWORD_CWORD_CWORD_CWORD,
2877 /* 155 */ CWORD_CWORD_CWORD_CWORD,
2878 /* 156 */ CWORD_CWORD_CWORD_CWORD,
2879 /* 157 */ CWORD_CWORD_CWORD_CWORD,
2880 /* 158 */ CWORD_CWORD_CWORD_CWORD,
2881 /* 159 */ CWORD_CWORD_CWORD_CWORD,
2882 /* 160 */ CWORD_CWORD_CWORD_CWORD,
2883 /* 161 */ CWORD_CWORD_CWORD_CWORD,
2884 /* 162 */ CWORD_CWORD_CWORD_CWORD,
2885 /* 163 */ CWORD_CWORD_CWORD_CWORD,
2886 /* 164 */ CWORD_CWORD_CWORD_CWORD,
2887 /* 165 */ CWORD_CWORD_CWORD_CWORD,
2888 /* 166 */ CWORD_CWORD_CWORD_CWORD,
2889 /* 167 */ CWORD_CWORD_CWORD_CWORD,
2890 /* 168 */ CWORD_CWORD_CWORD_CWORD,
2891 /* 169 */ CWORD_CWORD_CWORD_CWORD,
2892 /* 170 */ CWORD_CWORD_CWORD_CWORD,
2893 /* 171 */ CWORD_CWORD_CWORD_CWORD,
2894 /* 172 */ CWORD_CWORD_CWORD_CWORD,
2895 /* 173 */ CWORD_CWORD_CWORD_CWORD,
2896 /* 174 */ CWORD_CWORD_CWORD_CWORD,
2897 /* 175 */ CWORD_CWORD_CWORD_CWORD,
2898 /* 176 */ CWORD_CWORD_CWORD_CWORD,
2899 /* 177 */ CWORD_CWORD_CWORD_CWORD,
2900 /* 178 */ CWORD_CWORD_CWORD_CWORD,
2901 /* 179 */ CWORD_CWORD_CWORD_CWORD,
2902 /* 180 */ CWORD_CWORD_CWORD_CWORD,
2903 /* 181 */ CWORD_CWORD_CWORD_CWORD,
2904 /* 182 */ CWORD_CWORD_CWORD_CWORD,
2905 /* 183 */ CWORD_CWORD_CWORD_CWORD,
2906 /* 184 */ CWORD_CWORD_CWORD_CWORD,
2907 /* 185 */ CWORD_CWORD_CWORD_CWORD,
2908 /* 186 */ CWORD_CWORD_CWORD_CWORD,
2909 /* 187 */ CWORD_CWORD_CWORD_CWORD,
2910 /* 188 */ CWORD_CWORD_CWORD_CWORD,
2911 /* 189 */ CWORD_CWORD_CWORD_CWORD,
2912 /* 190 */ CWORD_CWORD_CWORD_CWORD,
2913 /* 191 */ CWORD_CWORD_CWORD_CWORD,
2914 /* 192 */ CWORD_CWORD_CWORD_CWORD,
2915 /* 193 */ CWORD_CWORD_CWORD_CWORD,
2916 /* 194 */ CWORD_CWORD_CWORD_CWORD,
2917 /* 195 */ CWORD_CWORD_CWORD_CWORD,
2918 /* 196 */ CWORD_CWORD_CWORD_CWORD,
2919 /* 197 */ CWORD_CWORD_CWORD_CWORD,
2920 /* 198 */ CWORD_CWORD_CWORD_CWORD,
2921 /* 199 */ CWORD_CWORD_CWORD_CWORD,
2922 /* 200 */ CWORD_CWORD_CWORD_CWORD,
2923 /* 201 */ CWORD_CWORD_CWORD_CWORD,
2924 /* 202 */ CWORD_CWORD_CWORD_CWORD,
2925 /* 203 */ CWORD_CWORD_CWORD_CWORD,
2926 /* 204 */ CWORD_CWORD_CWORD_CWORD,
2927 /* 205 */ CWORD_CWORD_CWORD_CWORD,
2928 /* 206 */ CWORD_CWORD_CWORD_CWORD,
2929 /* 207 */ CWORD_CWORD_CWORD_CWORD,
2930 /* 208 */ CWORD_CWORD_CWORD_CWORD,
2931 /* 209 */ CWORD_CWORD_CWORD_CWORD,
2932 /* 210 */ CWORD_CWORD_CWORD_CWORD,
2933 /* 211 */ CWORD_CWORD_CWORD_CWORD,
2934 /* 212 */ CWORD_CWORD_CWORD_CWORD,
2935 /* 213 */ CWORD_CWORD_CWORD_CWORD,
2936 /* 214 */ CWORD_CWORD_CWORD_CWORD,
2937 /* 215 */ CWORD_CWORD_CWORD_CWORD,
2938 /* 216 */ CWORD_CWORD_CWORD_CWORD,
2939 /* 217 */ CWORD_CWORD_CWORD_CWORD,
2940 /* 218 */ CWORD_CWORD_CWORD_CWORD,
2941 /* 219 */ CWORD_CWORD_CWORD_CWORD,
2942 /* 220 */ CWORD_CWORD_CWORD_CWORD,
2943 /* 221 */ CWORD_CWORD_CWORD_CWORD,
2944 /* 222 */ CWORD_CWORD_CWORD_CWORD,
2945 /* 223 */ CWORD_CWORD_CWORD_CWORD,
2946 /* 224 */ CWORD_CWORD_CWORD_CWORD,
2947 /* 225 */ CWORD_CWORD_CWORD_CWORD,
2948 /* 226 */ CWORD_CWORD_CWORD_CWORD,
2949 /* 227 */ CWORD_CWORD_CWORD_CWORD,
2950 /* 228 */ CWORD_CWORD_CWORD_CWORD,
2951 /* 229 */ CWORD_CWORD_CWORD_CWORD,
2952 /* 230 */ CWORD_CWORD_CWORD_CWORD,
2953 /* 231 */ CWORD_CWORD_CWORD_CWORD,
2954 /* 232 */ CWORD_CWORD_CWORD_CWORD,
2955 /* 233 */ CWORD_CWORD_CWORD_CWORD,
2956 /* 234 */ CWORD_CWORD_CWORD_CWORD,
2957 /* 235 */ CWORD_CWORD_CWORD_CWORD,
2958 /* 236 */ CWORD_CWORD_CWORD_CWORD,
2959 /* 237 */ CWORD_CWORD_CWORD_CWORD,
2960 /* 238 */ CWORD_CWORD_CWORD_CWORD,
2961 /* 239 */ CWORD_CWORD_CWORD_CWORD,
2962 /* 230 */ CWORD_CWORD_CWORD_CWORD,
2963 /* 241 */ CWORD_CWORD_CWORD_CWORD,
2964 /* 242 */ CWORD_CWORD_CWORD_CWORD,
2965 /* 243 */ CWORD_CWORD_CWORD_CWORD,
2966 /* 244 */ CWORD_CWORD_CWORD_CWORD,
2967 /* 245 */ CWORD_CWORD_CWORD_CWORD,
2968 /* 246 */ CWORD_CWORD_CWORD_CWORD,
2969 /* 247 */ CWORD_CWORD_CWORD_CWORD,
2970 /* 248 */ CWORD_CWORD_CWORD_CWORD,
2971 /* 249 */ CWORD_CWORD_CWORD_CWORD,
2972 /* 250 */ CWORD_CWORD_CWORD_CWORD,
2973 /* 251 */ CWORD_CWORD_CWORD_CWORD,
2974 /* 252 */ CWORD_CWORD_CWORD_CWORD,
2975 /* 253 */ CWORD_CWORD_CWORD_CWORD,
2976 /* 254 */ CWORD_CWORD_CWORD_CWORD,
2977 /* 255 */ CWORD_CWORD_CWORD_CWORD,
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002978 /* PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
Denys Vlasenkocd716832009-11-28 22:14:02 +01002979# if ENABLE_ASH_ALIAS
2980 /* PEOA */ CSPCL_CIGN_CIGN_CIGN,
2981# endif
Eric Andersen2870d962001-07-02 17:27:21 +00002982};
2983
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002984# define SIT(c, syntax) ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf)
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00002985
Denys Vlasenko76bc2d62009-11-29 01:37:46 +01002986#endif /* !USE_SIT_FUNCTION */
Eric Andersenc470f442003-07-28 09:56:35 +00002987
Eric Andersen2870d962001-07-02 17:27:21 +00002988
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00002989/* ============ Alias handling */
Denis Vlasenkofc06f292007-02-23 21:09:35 +00002990
Denis Vlasenko131ae172007-02-18 13:00:19 +00002991#if ENABLE_ASH_ALIAS
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00002992
2993#define ALIASINUSE 1
2994#define ALIASDEAD 2
2995
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00002996struct alias {
2997 struct alias *next;
2998 char *name;
2999 char *val;
3000 int flag;
3001};
3002
Denis Vlasenko01631112007-12-16 17:20:38 +00003003
3004static struct alias **atab; // [ATABSIZE];
3005#define INIT_G_alias() do { \
3006 atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
3007} while (0)
3008
Eric Andersen2870d962001-07-02 17:27:21 +00003009
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00003010static struct alias **
3011__lookupalias(const char *name) {
3012 unsigned int hashval;
3013 struct alias **app;
3014 const char *p;
3015 unsigned int ch;
3016
3017 p = name;
3018
3019 ch = (unsigned char)*p;
3020 hashval = ch << 4;
3021 while (ch) {
3022 hashval += ch;
3023 ch = (unsigned char)*++p;
3024 }
3025 app = &atab[hashval % ATABSIZE];
3026
3027 for (; *app; app = &(*app)->next) {
3028 if (strcmp(name, (*app)->name) == 0) {
3029 break;
3030 }
3031 }
3032
3033 return app;
3034}
3035
3036static struct alias *
3037lookupalias(const char *name, int check)
3038{
3039 struct alias *ap = *__lookupalias(name);
3040
3041 if (check && ap && (ap->flag & ALIASINUSE))
3042 return NULL;
3043 return ap;
3044}
3045
3046static struct alias *
3047freealias(struct alias *ap)
3048{
3049 struct alias *next;
3050
3051 if (ap->flag & ALIASINUSE) {
3052 ap->flag |= ALIASDEAD;
3053 return ap;
3054 }
3055
3056 next = ap->next;
3057 free(ap->name);
3058 free(ap->val);
3059 free(ap);
3060 return next;
3061}
Eric Andersencb57d552001-06-28 07:25:16 +00003062
Eric Andersenc470f442003-07-28 09:56:35 +00003063static void
3064setalias(const char *name, const char *val)
Eric Andersencb57d552001-06-28 07:25:16 +00003065{
3066 struct alias *ap, **app;
3067
3068 app = __lookupalias(name);
3069 ap = *app;
Denis Vlasenkob012b102007-02-19 22:43:01 +00003070 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +00003071 if (ap) {
3072 if (!(ap->flag & ALIASINUSE)) {
Denis Vlasenkob012b102007-02-19 22:43:01 +00003073 free(ap->val);
Eric Andersencb57d552001-06-28 07:25:16 +00003074 }
Denis Vlasenko0c032a42007-02-23 01:03:40 +00003075 ap->val = ckstrdup(val);
Eric Andersencb57d552001-06-28 07:25:16 +00003076 ap->flag &= ~ALIASDEAD;
3077 } else {
3078 /* not found */
Denis Vlasenko597906c2008-02-20 16:38:54 +00003079 ap = ckzalloc(sizeof(struct alias));
Denis Vlasenko0c032a42007-02-23 01:03:40 +00003080 ap->name = ckstrdup(name);
3081 ap->val = ckstrdup(val);
Denis Vlasenko597906c2008-02-20 16:38:54 +00003082 /*ap->flag = 0; - ckzalloc did it */
3083 /*ap->next = NULL;*/
Eric Andersencb57d552001-06-28 07:25:16 +00003084 *app = ap;
3085 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00003086 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00003087}
3088
Eric Andersenc470f442003-07-28 09:56:35 +00003089static int
3090unalias(const char *name)
Eric Andersen2870d962001-07-02 17:27:21 +00003091{
Eric Andersencb57d552001-06-28 07:25:16 +00003092 struct alias **app;
3093
3094 app = __lookupalias(name);
3095
3096 if (*app) {
Denis Vlasenkob012b102007-02-19 22:43:01 +00003097 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +00003098 *app = freealias(*app);
Denis Vlasenkob012b102007-02-19 22:43:01 +00003099 INT_ON;
Denis Vlasenko079f8af2006-11-27 16:49:31 +00003100 return 0;
Eric Andersencb57d552001-06-28 07:25:16 +00003101 }
3102
Denis Vlasenko079f8af2006-11-27 16:49:31 +00003103 return 1;
Eric Andersencb57d552001-06-28 07:25:16 +00003104}
3105
Eric Andersenc470f442003-07-28 09:56:35 +00003106static void
3107rmaliases(void)
Eric Andersen2870d962001-07-02 17:27:21 +00003108{
Eric Andersencb57d552001-06-28 07:25:16 +00003109 struct alias *ap, **app;
3110 int i;
3111
Denis Vlasenkob012b102007-02-19 22:43:01 +00003112 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +00003113 for (i = 0; i < ATABSIZE; i++) {
3114 app = &atab[i];
3115 for (ap = *app; ap; ap = *app) {
3116 *app = freealias(*app);
3117 if (ap == *app) {
3118 app = &ap->next;
3119 }
3120 }
3121 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00003122 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00003123}
3124
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00003125static void
3126printalias(const struct alias *ap)
3127{
3128 out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
3129}
3130
Eric Andersencb57d552001-06-28 07:25:16 +00003131/*
3132 * TODO - sort output
3133 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02003134static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00003135aliascmd(int argc UNUSED_PARAM, char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +00003136{
3137 char *n, *v;
3138 int ret = 0;
3139 struct alias *ap;
3140
Denis Vlasenko68404f12008-03-17 09:00:54 +00003141 if (!argv[1]) {
Eric Andersencb57d552001-06-28 07:25:16 +00003142 int i;
3143
Denis Vlasenko68404f12008-03-17 09:00:54 +00003144 for (i = 0; i < ATABSIZE; i++) {
Eric Andersencb57d552001-06-28 07:25:16 +00003145 for (ap = atab[i]; ap; ap = ap->next) {
3146 printalias(ap);
3147 }
Denis Vlasenko68404f12008-03-17 09:00:54 +00003148 }
Denis Vlasenko079f8af2006-11-27 16:49:31 +00003149 return 0;
Eric Andersencb57d552001-06-28 07:25:16 +00003150 }
3151 while ((n = *++argv) != NULL) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00003152 v = strchr(n+1, '=');
3153 if (v == NULL) { /* n+1: funny ksh stuff */
3154 ap = *__lookupalias(n);
3155 if (ap == NULL) {
Eric Andersenc470f442003-07-28 09:56:35 +00003156 fprintf(stderr, "%s: %s not found\n", "alias", n);
Eric Andersencb57d552001-06-28 07:25:16 +00003157 ret = 1;
3158 } else
3159 printalias(ap);
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00003160 } else {
Eric Andersencb57d552001-06-28 07:25:16 +00003161 *v++ = '\0';
3162 setalias(n, v);
3163 }
3164 }
3165
Denis Vlasenkod9e15f22006-11-27 16:49:55 +00003166 return ret;
Eric Andersencb57d552001-06-28 07:25:16 +00003167}
3168
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02003169static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00003170unaliascmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersencb57d552001-06-28 07:25:16 +00003171{
3172 int i;
3173
3174 while ((i = nextopt("a")) != '\0') {
3175 if (i == 'a') {
3176 rmaliases();
Denis Vlasenko079f8af2006-11-27 16:49:31 +00003177 return 0;
Eric Andersencb57d552001-06-28 07:25:16 +00003178 }
3179 }
3180 for (i = 0; *argptr; argptr++) {
3181 if (unalias(*argptr)) {
Eric Andersenc470f442003-07-28 09:56:35 +00003182 fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
Eric Andersencb57d552001-06-28 07:25:16 +00003183 i = 1;
3184 }
3185 }
3186
Denis Vlasenkod9e15f22006-11-27 16:49:55 +00003187 return i;
Eric Andersencb57d552001-06-28 07:25:16 +00003188}
Denis Vlasenkofc06f292007-02-23 21:09:35 +00003189
Denis Vlasenko131ae172007-02-18 13:00:19 +00003190#endif /* ASH_ALIAS */
Eric Andersencb57d552001-06-28 07:25:16 +00003191
Eric Andersenc470f442003-07-28 09:56:35 +00003192
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003193/* ============ jobs.c */
3194
3195/* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
Denys Vlasenko285ad152009-12-04 23:02:27 +01003196#define FORK_FG 0
3197#define FORK_BG 1
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003198#define FORK_NOJOB 2
3199
3200/* mode flags for showjob(s) */
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003201#define SHOW_ONLY_PGID 0x01 /* show only pgid (jobs -p) */
3202#define SHOW_PIDS 0x02 /* show individual pids, not just one line per job */
3203#define SHOW_CHANGED 0x04 /* only jobs whose state has changed */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003204
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003205/*
3206 * A job structure contains information about a job. A job is either a
3207 * single process or a set of processes contained in a pipeline. In the
3208 * latter case, pidlist will be non-NULL, and will point to a -1 terminated
3209 * array of pids.
3210 */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003211struct procstat {
Denys Vlasenko285ad152009-12-04 23:02:27 +01003212 pid_t ps_pid; /* process id */
3213 int ps_status; /* last process status from wait() */
3214 char *ps_cmd; /* text of command being run */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003215};
3216
3217struct job {
3218 struct procstat ps0; /* status of process */
3219 struct procstat *ps; /* status or processes when more than one */
3220#if JOBS
3221 int stopstatus; /* status of a stopped job */
3222#endif
3223 uint32_t
3224 nprocs: 16, /* number of processes */
3225 state: 8,
3226#define JOBRUNNING 0 /* at least one proc running */
3227#define JOBSTOPPED 1 /* all procs are stopped */
3228#define JOBDONE 2 /* all procs are completed */
3229#if JOBS
3230 sigint: 1, /* job was killed by SIGINT */
3231 jobctl: 1, /* job running under job control */
3232#endif
3233 waited: 1, /* true if this entry has been waited for */
3234 used: 1, /* true if this entry is in used */
3235 changed: 1; /* true if status has changed */
3236 struct job *prev_job; /* previous job */
3237};
3238
Denis Vlasenko68404f12008-03-17 09:00:54 +00003239static struct job *makejob(/*union node *,*/ int);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003240static int forkshell(struct job *, union node *, int);
3241static int waitforjob(struct job *);
3242
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003243#if !JOBS
Denis Vlasenkob07a4962008-06-22 13:16:23 +00003244enum { doing_jobctl = 0 };
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003245#define setjobctl(on) do {} while (0)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003246#else
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003247static smallint doing_jobctl; //references:8
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003248static void setjobctl(int);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003249#endif
3250
3251/*
Denis Vlasenko4b875702009-03-19 13:30:04 +00003252 * Ignore a signal.
3253 */
3254static void
3255ignoresig(int signo)
3256{
3257 /* Avoid unnecessary system calls. Is it already SIG_IGNed? */
3258 if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
3259 /* No, need to do it */
3260 signal(signo, SIG_IGN);
3261 }
3262 sigmode[signo - 1] = S_HARD_IGN;
3263}
3264
3265/*
Denys Vlasenko238bf182010-05-18 15:49:07 +02003266 * Only one usage site - in setsignal()
Denis Vlasenko4b875702009-03-19 13:30:04 +00003267 */
3268static void
Denys Vlasenko238bf182010-05-18 15:49:07 +02003269signal_handler(int signo)
Denis Vlasenko4b875702009-03-19 13:30:04 +00003270{
3271 gotsig[signo - 1] = 1;
3272
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02003273 if (signo == SIGINT && !trap[SIGINT]) {
3274 if (!suppress_int) {
3275 pending_sig = 0;
Denis Vlasenko4b875702009-03-19 13:30:04 +00003276 raise_interrupt(); /* does not return */
3277 }
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02003278 pending_int = 1;
Denis Vlasenko4b875702009-03-19 13:30:04 +00003279 } else {
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02003280 pending_sig = signo;
Denis Vlasenko4b875702009-03-19 13:30:04 +00003281 }
3282}
3283
3284/*
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003285 * Set the signal handler for the specified signal. The routine figures
3286 * out what it should be set to.
3287 */
3288static void
3289setsignal(int signo)
3290{
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003291 char *t;
3292 char cur_act, new_act;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003293 struct sigaction act;
3294
3295 t = trap[signo];
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003296 new_act = S_DFL;
3297 if (t != NULL) { /* trap for this sig is set */
3298 new_act = S_CATCH;
3299 if (t[0] == '\0') /* trap is "": ignore this sig */
3300 new_act = S_IGN;
3301 }
3302
3303 if (rootshell && new_act == S_DFL) {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003304 switch (signo) {
3305 case SIGINT:
3306 if (iflag || minusc || sflag == 0)
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003307 new_act = S_CATCH;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003308 break;
3309 case SIGQUIT:
3310#if DEBUG
3311 if (debug)
3312 break;
3313#endif
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003314 /* man bash:
3315 * "In all cases, bash ignores SIGQUIT. Non-builtin
3316 * commands run by bash have signal handlers
3317 * set to the values inherited by the shell
3318 * from its parent". */
3319 new_act = S_IGN;
3320 break;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003321 case SIGTERM:
3322 if (iflag)
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003323 new_act = S_IGN;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003324 break;
3325#if JOBS
3326 case SIGTSTP:
3327 case SIGTTOU:
3328 if (mflag)
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003329 new_act = S_IGN;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003330 break;
3331#endif
3332 }
3333 }
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003334//TODO: if !rootshell, we reset SIGQUIT to DFL,
3335//whereas we have to restore it to what shell got on entry
3336//from the parent. See comment above
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003337
3338 t = &sigmode[signo - 1];
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003339 cur_act = *t;
3340 if (cur_act == 0) {
3341 /* current setting is not yet known */
3342 if (sigaction(signo, NULL, &act)) {
3343 /* pretend it worked; maybe we should give a warning,
3344 * but other shells don't. We don't alter sigmode,
3345 * so we retry every time.
3346 * btw, in Linux it never fails. --vda */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003347 return;
3348 }
3349 if (act.sa_handler == SIG_IGN) {
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003350 cur_act = S_HARD_IGN;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003351 if (mflag
3352 && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
3353 ) {
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003354 cur_act = S_IGN; /* don't hard ignore these */
Denis Vlasenko991a1da2008-02-10 19:02:53 +00003355 }
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003356 }
3357 }
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003358 if (cur_act == S_HARD_IGN || cur_act == new_act)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003359 return;
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003360
Denis Vlasenko991a1da2008-02-10 19:02:53 +00003361 act.sa_handler = SIG_DFL;
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003362 switch (new_act) {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003363 case S_CATCH:
Denys Vlasenko238bf182010-05-18 15:49:07 +02003364 act.sa_handler = signal_handler;
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003365 act.sa_flags = 0; /* matters only if !DFL and !IGN */
3366 sigfillset(&act.sa_mask); /* ditto */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003367 break;
3368 case S_IGN:
3369 act.sa_handler = SIG_IGN;
3370 break;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003371 }
Denis Vlasenko8e2cfec2008-03-12 23:19:35 +00003372 sigaction_set(signo, &act);
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003373
3374 *t = new_act;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003375}
3376
3377/* mode flags for set_curjob */
3378#define CUR_DELETE 2
3379#define CUR_RUNNING 1
3380#define CUR_STOPPED 0
3381
3382/* mode flags for dowait */
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00003383#define DOWAIT_NONBLOCK WNOHANG
3384#define DOWAIT_BLOCK 0
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003385
3386#if JOBS
3387/* pgrp of shell on invocation */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003388static int initialpgrp; //references:2
3389static int ttyfd = -1; //5
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003390#endif
3391/* array of jobs */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003392static struct job *jobtab; //5
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003393/* size of array */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003394static unsigned njobs; //4
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003395/* current job */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003396static struct job *curjob; //lots
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003397/* number of presumed living untracked jobs */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003398static int jobless; //4
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003399
3400static void
3401set_curjob(struct job *jp, unsigned mode)
3402{
3403 struct job *jp1;
3404 struct job **jpp, **curp;
3405
3406 /* first remove from list */
3407 jpp = curp = &curjob;
3408 do {
3409 jp1 = *jpp;
3410 if (jp1 == jp)
3411 break;
3412 jpp = &jp1->prev_job;
3413 } while (1);
3414 *jpp = jp1->prev_job;
3415
3416 /* Then re-insert in correct position */
3417 jpp = curp;
3418 switch (mode) {
3419 default:
3420#if DEBUG
3421 abort();
3422#endif
3423 case CUR_DELETE:
3424 /* job being deleted */
3425 break;
3426 case CUR_RUNNING:
3427 /* newly created job or backgrounded job,
3428 put after all stopped jobs. */
3429 do {
3430 jp1 = *jpp;
3431#if JOBS
3432 if (!jp1 || jp1->state != JOBSTOPPED)
3433#endif
3434 break;
3435 jpp = &jp1->prev_job;
3436 } while (1);
3437 /* FALLTHROUGH */
3438#if JOBS
3439 case CUR_STOPPED:
3440#endif
3441 /* newly stopped job - becomes curjob */
3442 jp->prev_job = *jpp;
3443 *jpp = jp;
3444 break;
3445 }
3446}
3447
3448#if JOBS || DEBUG
3449static int
3450jobno(const struct job *jp)
3451{
3452 return jp - jobtab + 1;
3453}
3454#endif
3455
3456/*
3457 * Convert a job name to a job structure.
3458 */
Denis Vlasenko85c24712008-03-17 09:04:04 +00003459#if !JOBS
3460#define getjob(name, getctl) getjob(name)
3461#endif
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003462static struct job *
3463getjob(const char *name, int getctl)
3464{
3465 struct job *jp;
3466 struct job *found;
Denys Vlasenkoffc39202009-08-17 02:12:20 +02003467 const char *err_msg = "%s: no such job";
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003468 unsigned num;
3469 int c;
3470 const char *p;
3471 char *(*match)(const char *, const char *);
3472
3473 jp = curjob;
3474 p = name;
3475 if (!p)
3476 goto currentjob;
3477
3478 if (*p != '%')
3479 goto err;
3480
3481 c = *++p;
3482 if (!c)
3483 goto currentjob;
3484
3485 if (!p[1]) {
3486 if (c == '+' || c == '%') {
3487 currentjob:
3488 err_msg = "No current job";
3489 goto check;
3490 }
3491 if (c == '-') {
3492 if (jp)
3493 jp = jp->prev_job;
3494 err_msg = "No previous job";
3495 check:
3496 if (!jp)
3497 goto err;
3498 goto gotit;
3499 }
3500 }
3501
3502 if (is_number(p)) {
3503 num = atoi(p);
3504 if (num < njobs) {
3505 jp = jobtab + num - 1;
3506 if (jp->used)
3507 goto gotit;
3508 goto err;
3509 }
3510 }
3511
3512 match = prefix;
3513 if (*p == '?') {
3514 match = strstr;
3515 p++;
3516 }
3517
Denys Vlasenkoffc39202009-08-17 02:12:20 +02003518 found = NULL;
3519 while (jp) {
Denys Vlasenko285ad152009-12-04 23:02:27 +01003520 if (match(jp->ps[0].ps_cmd, p)) {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003521 if (found)
3522 goto err;
3523 found = jp;
3524 err_msg = "%s: ambiguous";
3525 }
3526 jp = jp->prev_job;
3527 }
Denys Vlasenkoffc39202009-08-17 02:12:20 +02003528 if (!found)
3529 goto err;
3530 jp = found;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003531
3532 gotit:
3533#if JOBS
3534 err_msg = "job %s not created under job control";
3535 if (getctl && jp->jobctl == 0)
3536 goto err;
3537#endif
3538 return jp;
3539 err:
3540 ash_msg_and_raise_error(err_msg, name);
3541}
3542
3543/*
3544 * Mark a job structure as unused.
3545 */
3546static void
3547freejob(struct job *jp)
3548{
3549 struct procstat *ps;
3550 int i;
3551
3552 INT_OFF;
3553 for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
Denys Vlasenko285ad152009-12-04 23:02:27 +01003554 if (ps->ps_cmd != nullstr)
3555 free(ps->ps_cmd);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003556 }
3557 if (jp->ps != &jp->ps0)
3558 free(jp->ps);
3559 jp->used = 0;
3560 set_curjob(jp, CUR_DELETE);
3561 INT_ON;
3562}
3563
3564#if JOBS
3565static void
3566xtcsetpgrp(int fd, pid_t pgrp)
3567{
3568 if (tcsetpgrp(fd, pgrp))
Bernhard Reutner-Fischera53de7f2008-07-21 13:46:54 +00003569 ash_msg_and_raise_error("can't set tty process group (%m)");
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003570}
3571
3572/*
3573 * Turn job control on and off.
3574 *
3575 * Note: This code assumes that the third arg to ioctl is a character
3576 * pointer, which is true on Berkeley systems but not System V. Since
3577 * System V doesn't have job control yet, this isn't a problem now.
3578 *
3579 * Called with interrupts off.
3580 */
3581static void
3582setjobctl(int on)
3583{
3584 int fd;
3585 int pgrp;
3586
Denis Vlasenkob07a4962008-06-22 13:16:23 +00003587 if (on == doing_jobctl || rootshell == 0)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003588 return;
3589 if (on) {
3590 int ofd;
3591 ofd = fd = open(_PATH_TTY, O_RDWR);
3592 if (fd < 0) {
3593 /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
3594 * That sometimes helps to acquire controlling tty.
3595 * Obviously, a workaround for bugs when someone
3596 * failed to provide a controlling tty to bash! :) */
Denis Vlasenkoed270a52007-11-26 05:37:07 +00003597 fd = 2;
3598 while (!isatty(fd))
3599 if (--fd < 0)
3600 goto out;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003601 }
3602 fd = fcntl(fd, F_DUPFD, 10);
Denis Vlasenkoed270a52007-11-26 05:37:07 +00003603 if (ofd >= 0)
3604 close(ofd);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003605 if (fd < 0)
3606 goto out;
Denis Vlasenkoed270a52007-11-26 05:37:07 +00003607 /* fd is a tty at this point */
Denis Vlasenko96e1b382007-09-30 23:50:48 +00003608 close_on_exec_on(fd);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003609 do { /* while we are in the background */
3610 pgrp = tcgetpgrp(fd);
3611 if (pgrp < 0) {
3612 out:
3613 ash_msg("can't access tty; job control turned off");
3614 mflag = on = 0;
3615 goto close;
3616 }
3617 if (pgrp == getpgrp())
3618 break;
3619 killpg(0, SIGTTIN);
3620 } while (1);
3621 initialpgrp = pgrp;
3622
3623 setsignal(SIGTSTP);
3624 setsignal(SIGTTOU);
3625 setsignal(SIGTTIN);
3626 pgrp = rootpid;
3627 setpgid(0, pgrp);
3628 xtcsetpgrp(fd, pgrp);
3629 } else {
3630 /* turning job control off */
3631 fd = ttyfd;
3632 pgrp = initialpgrp;
Denis Vlasenko08c8c1d2007-04-28 22:39:02 +00003633 /* was xtcsetpgrp, but this can make exiting ash
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00003634 * loop forever if pty is already deleted */
Denis Vlasenko08c8c1d2007-04-28 22:39:02 +00003635 tcsetpgrp(fd, pgrp);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003636 setpgid(0, pgrp);
3637 setsignal(SIGTSTP);
3638 setsignal(SIGTTOU);
3639 setsignal(SIGTTIN);
3640 close:
Denis Vlasenkoed270a52007-11-26 05:37:07 +00003641 if (fd >= 0)
3642 close(fd);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003643 fd = -1;
3644 }
3645 ttyfd = fd;
Denis Vlasenkob07a4962008-06-22 13:16:23 +00003646 doing_jobctl = on;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003647}
3648
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02003649static int FAST_FUNC
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003650killcmd(int argc, char **argv)
3651{
Denis Vlasenko68404f12008-03-17 09:00:54 +00003652 int i = 1;
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003653 if (argv[1] && strcmp(argv[1], "-l") != 0) {
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003654 do {
3655 if (argv[i][0] == '%') {
3656 struct job *jp = getjob(argv[i], 0);
Denys Vlasenko285ad152009-12-04 23:02:27 +01003657 unsigned pid = jp->ps[0].ps_pid;
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003658 /* Enough space for ' -NNN<nul>' */
3659 argv[i] = alloca(sizeof(int)*3 + 3);
3660 /* kill_main has matching code to expect
3661 * leading space. Needed to not confuse
3662 * negative pids with "kill -SIGNAL_NO" syntax */
3663 sprintf(argv[i], " -%u", pid);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003664 }
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003665 } while (argv[++i]);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003666 }
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003667 return kill_main(argc, argv);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003668}
3669
3670static void
Denys Vlasenko285ad152009-12-04 23:02:27 +01003671showpipe(struct job *jp /*, FILE *out*/)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003672{
Denys Vlasenko285ad152009-12-04 23:02:27 +01003673 struct procstat *ps;
3674 struct procstat *psend;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003675
Denys Vlasenko285ad152009-12-04 23:02:27 +01003676 psend = jp->ps + jp->nprocs;
3677 for (ps = jp->ps + 1; ps < psend; ps++)
3678 printf(" | %s", ps->ps_cmd);
3679 outcslow('\n', stdout);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003680 flush_stdout_stderr();
3681}
3682
3683
3684static int
3685restartjob(struct job *jp, int mode)
3686{
3687 struct procstat *ps;
3688 int i;
3689 int status;
3690 pid_t pgid;
3691
3692 INT_OFF;
3693 if (jp->state == JOBDONE)
3694 goto out;
3695 jp->state = JOBRUNNING;
Denys Vlasenko285ad152009-12-04 23:02:27 +01003696 pgid = jp->ps[0].ps_pid;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003697 if (mode == FORK_FG)
3698 xtcsetpgrp(ttyfd, pgid);
3699 killpg(pgid, SIGCONT);
3700 ps = jp->ps;
3701 i = jp->nprocs;
3702 do {
Denys Vlasenko285ad152009-12-04 23:02:27 +01003703 if (WIFSTOPPED(ps->ps_status)) {
3704 ps->ps_status = -1;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003705 }
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003706 ps++;
3707 } while (--i);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003708 out:
3709 status = (mode == FORK_FG) ? waitforjob(jp) : 0;
3710 INT_ON;
3711 return status;
3712}
3713
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02003714static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00003715fg_bgcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003716{
3717 struct job *jp;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003718 int mode;
3719 int retval;
3720
3721 mode = (**argv == 'f') ? FORK_FG : FORK_BG;
3722 nextopt(nullstr);
3723 argv = argptr;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003724 do {
3725 jp = getjob(*argv, 1);
3726 if (mode == FORK_BG) {
3727 set_curjob(jp, CUR_RUNNING);
Denys Vlasenko285ad152009-12-04 23:02:27 +01003728 printf("[%d] ", jobno(jp));
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003729 }
Denys Vlasenko285ad152009-12-04 23:02:27 +01003730 out1str(jp->ps[0].ps_cmd);
3731 showpipe(jp /*, stdout*/);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003732 retval = restartjob(jp, mode);
3733 } while (*argv && *++argv);
3734 return retval;
3735}
3736#endif
3737
3738static int
3739sprint_status(char *s, int status, int sigonly)
3740{
3741 int col;
3742 int st;
3743
3744 col = 0;
3745 if (!WIFEXITED(status)) {
3746#if JOBS
3747 if (WIFSTOPPED(status))
3748 st = WSTOPSIG(status);
3749 else
3750#endif
3751 st = WTERMSIG(status);
3752 if (sigonly) {
3753 if (st == SIGINT || st == SIGPIPE)
3754 goto out;
3755#if JOBS
3756 if (WIFSTOPPED(status))
3757 goto out;
3758#endif
3759 }
3760 st &= 0x7f;
3761 col = fmtstr(s, 32, strsignal(st));
3762 if (WCOREDUMP(status)) {
3763 col += fmtstr(s + col, 16, " (core dumped)");
3764 }
3765 } else if (!sigonly) {
3766 st = WEXITSTATUS(status);
3767 if (st)
3768 col = fmtstr(s, 16, "Done(%d)", st);
3769 else
3770 col = fmtstr(s, 16, "Done");
3771 }
3772 out:
3773 return col;
3774}
3775
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003776static int
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00003777dowait(int wait_flags, struct job *job)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003778{
3779 int pid;
3780 int status;
3781 struct job *jp;
3782 struct job *thisjob;
3783 int state;
3784
Denis Vlasenkobe54d6b2008-10-27 14:25:52 +00003785 TRACE(("dowait(0x%x) called\n", wait_flags));
3786
3787 /* Do a wait system call. If job control is compiled in, we accept
3788 * stopped processes. wait_flags may have WNOHANG, preventing blocking.
3789 * NB: _not_ safe_waitpid, we need to detect EINTR */
Denys Vlasenko285ad152009-12-04 23:02:27 +01003790 if (doing_jobctl)
3791 wait_flags |= WUNTRACED;
3792 pid = waitpid(-1, &status, wait_flags);
Denis Vlasenkob21f3792009-03-19 23:09:58 +00003793 TRACE(("wait returns pid=%d, status=0x%x, errno=%d(%s)\n",
3794 pid, status, errno, strerror(errno)));
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003795 if (pid <= 0)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003796 return pid;
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003797
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003798 INT_OFF;
3799 thisjob = NULL;
3800 for (jp = curjob; jp; jp = jp->prev_job) {
Denys Vlasenko285ad152009-12-04 23:02:27 +01003801 struct procstat *ps;
3802 struct procstat *psend;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003803 if (jp->state == JOBDONE)
3804 continue;
3805 state = JOBDONE;
Denys Vlasenko285ad152009-12-04 23:02:27 +01003806 ps = jp->ps;
3807 psend = ps + jp->nprocs;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003808 do {
Denys Vlasenko285ad152009-12-04 23:02:27 +01003809 if (ps->ps_pid == pid) {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003810 TRACE(("Job %d: changing status of proc %d "
3811 "from 0x%x to 0x%x\n",
Denys Vlasenko285ad152009-12-04 23:02:27 +01003812 jobno(jp), pid, ps->ps_status, status));
3813 ps->ps_status = status;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003814 thisjob = jp;
3815 }
Denys Vlasenko285ad152009-12-04 23:02:27 +01003816 if (ps->ps_status == -1)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003817 state = JOBRUNNING;
3818#if JOBS
3819 if (state == JOBRUNNING)
3820 continue;
Denys Vlasenko285ad152009-12-04 23:02:27 +01003821 if (WIFSTOPPED(ps->ps_status)) {
3822 jp->stopstatus = ps->ps_status;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003823 state = JOBSTOPPED;
3824 }
3825#endif
Denys Vlasenko285ad152009-12-04 23:02:27 +01003826 } while (++ps < psend);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003827 if (thisjob)
3828 goto gotjob;
3829 }
3830#if JOBS
3831 if (!WIFSTOPPED(status))
3832#endif
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003833 jobless--;
3834 goto out;
3835
3836 gotjob:
3837 if (state != JOBRUNNING) {
3838 thisjob->changed = 1;
3839
3840 if (thisjob->state != state) {
3841 TRACE(("Job %d: changing state from %d to %d\n",
3842 jobno(thisjob), thisjob->state, state));
3843 thisjob->state = state;
3844#if JOBS
3845 if (state == JOBSTOPPED) {
3846 set_curjob(thisjob, CUR_STOPPED);
3847 }
3848#endif
3849 }
3850 }
3851
3852 out:
3853 INT_ON;
3854
3855 if (thisjob && thisjob == job) {
3856 char s[48 + 1];
3857 int len;
3858
3859 len = sprint_status(s, status, 1);
3860 if (len) {
3861 s[len] = '\n';
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00003862 s[len + 1] = '\0';
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003863 out2str(s);
3864 }
3865 }
3866 return pid;
3867}
3868
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003869static int
Denys Vlasenko7c1ed9f2010-05-17 04:42:40 +02003870blocking_wait_with_raise_on_sig(void)
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003871{
Denys Vlasenko7c1ed9f2010-05-17 04:42:40 +02003872 pid_t pid = dowait(DOWAIT_BLOCK, NULL);
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02003873 if (pid <= 0 && pending_sig)
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003874 raise_exception(EXSIG);
3875 return pid;
3876}
3877
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003878#if JOBS
3879static void
3880showjob(FILE *out, struct job *jp, int mode)
3881{
3882 struct procstat *ps;
3883 struct procstat *psend;
3884 int col;
Denis Vlasenko40ba9982007-07-14 00:48:29 +00003885 int indent_col;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003886 char s[80];
3887
3888 ps = jp->ps;
3889
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003890 if (mode & SHOW_ONLY_PGID) { /* jobs -p */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003891 /* just output process (group) id of pipeline */
Denys Vlasenko285ad152009-12-04 23:02:27 +01003892 fprintf(out, "%d\n", ps->ps_pid);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003893 return;
3894 }
3895
3896 col = fmtstr(s, 16, "[%d] ", jobno(jp));
Denis Vlasenko40ba9982007-07-14 00:48:29 +00003897 indent_col = col;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003898
3899 if (jp == curjob)
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003900 s[col - 3] = '+';
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003901 else if (curjob && jp == curjob->prev_job)
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003902 s[col - 3] = '-';
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003903
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003904 if (mode & SHOW_PIDS)
Denys Vlasenko285ad152009-12-04 23:02:27 +01003905 col += fmtstr(s + col, 16, "%d ", ps->ps_pid);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003906
3907 psend = ps + jp->nprocs;
3908
3909 if (jp->state == JOBRUNNING) {
3910 strcpy(s + col, "Running");
3911 col += sizeof("Running") - 1;
3912 } else {
Denys Vlasenko285ad152009-12-04 23:02:27 +01003913 int status = psend[-1].ps_status;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003914 if (jp->state == JOBSTOPPED)
3915 status = jp->stopstatus;
3916 col += sprint_status(s + col, status, 0);
3917 }
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003918 /* By now, "[JOBID]* [maybe PID] STATUS" is printed */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003919
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003920 /* This loop either prints "<cmd1> | <cmd2> | <cmd3>" line
3921 * or prints several "PID | <cmdN>" lines,
3922 * depending on SHOW_PIDS bit.
3923 * We do not print status of individual processes
3924 * between PID and <cmdN>. bash does it, but not very well:
3925 * first line shows overall job status, not process status,
3926 * making it impossible to know 1st process status.
3927 */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003928 goto start;
Denys Vlasenko285ad152009-12-04 23:02:27 +01003929 do {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003930 /* for each process */
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003931 s[0] = '\0';
3932 col = 33;
3933 if (mode & SHOW_PIDS)
Denys Vlasenko285ad152009-12-04 23:02:27 +01003934 col = fmtstr(s, 48, "\n%*c%d ", indent_col, ' ', ps->ps_pid) - 1;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003935 start:
Denys Vlasenko285ad152009-12-04 23:02:27 +01003936 fprintf(out, "%s%*c%s%s",
3937 s,
3938 33 - col >= 0 ? 33 - col : 0, ' ',
3939 ps == jp->ps ? "" : "| ",
3940 ps->ps_cmd
3941 );
3942 } while (++ps != psend);
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003943 outcslow('\n', out);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003944
3945 jp->changed = 0;
3946
3947 if (jp->state == JOBDONE) {
3948 TRACE(("showjob: freeing job %d\n", jobno(jp)));
3949 freejob(jp);
3950 }
3951}
3952
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003953/*
3954 * Print a list of jobs. If "change" is nonzero, only print jobs whose
3955 * statuses have changed since the last call to showjobs.
3956 */
3957static void
3958showjobs(FILE *out, int mode)
3959{
3960 struct job *jp;
3961
Denys Vlasenko883cea42009-07-11 15:31:59 +02003962 TRACE(("showjobs(0x%x) called\n", mode));
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003963
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003964 /* Handle all finished jobs */
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00003965 while (dowait(DOWAIT_NONBLOCK, NULL) > 0)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003966 continue;
3967
3968 for (jp = curjob; jp; jp = jp->prev_job) {
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003969 if (!(mode & SHOW_CHANGED) || jp->changed) {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003970 showjob(out, jp, mode);
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003971 }
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003972 }
3973}
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003974
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02003975static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00003976jobscmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003977{
3978 int mode, m;
3979
3980 mode = 0;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02003981 while ((m = nextopt("lp")) != '\0') {
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003982 if (m == 'l')
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003983 mode |= SHOW_PIDS;
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003984 else
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003985 mode |= SHOW_ONLY_PGID;
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003986 }
3987
3988 argv = argptr;
3989 if (*argv) {
3990 do
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003991 showjob(stdout, getjob(*argv, 0), mode);
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003992 while (*++argv);
Denys Vlasenko285ad152009-12-04 23:02:27 +01003993 } else {
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003994 showjobs(stdout, mode);
Denys Vlasenko285ad152009-12-04 23:02:27 +01003995 }
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003996
3997 return 0;
3998}
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003999#endif /* JOBS */
4000
Michael Abbott359da5e2009-12-04 23:03:29 +01004001/* Called only on finished or stopped jobs (no members are running) */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004002static int
4003getstatus(struct job *job)
4004{
4005 int status;
4006 int retval;
Michael Abbott359da5e2009-12-04 23:03:29 +01004007 struct procstat *ps;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004008
Michael Abbott359da5e2009-12-04 23:03:29 +01004009 /* Fetch last member's status */
4010 ps = job->ps + job->nprocs - 1;
4011 status = ps->ps_status;
4012 if (pipefail) {
4013 /* "set -o pipefail" mode: use last _nonzero_ status */
4014 while (status == 0 && --ps >= job->ps)
4015 status = ps->ps_status;
4016 }
4017
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004018 retval = WEXITSTATUS(status);
4019 if (!WIFEXITED(status)) {
4020#if JOBS
4021 retval = WSTOPSIG(status);
4022 if (!WIFSTOPPED(status))
4023#endif
4024 {
4025 /* XXX: limits number of signals */
4026 retval = WTERMSIG(status);
4027#if JOBS
4028 if (retval == SIGINT)
4029 job->sigint = 1;
4030#endif
4031 }
4032 retval += 128;
4033 }
Denys Vlasenko883cea42009-07-11 15:31:59 +02004034 TRACE(("getstatus: job %d, nproc %d, status 0x%x, retval 0x%x\n",
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004035 jobno(job), job->nprocs, status, retval));
4036 return retval;
4037}
4038
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02004039static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00004040waitcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004041{
4042 struct job *job;
4043 int retval;
4044 struct job *jp;
4045
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02004046 if (pending_sig)
Denis Vlasenko991a1da2008-02-10 19:02:53 +00004047 raise_exception(EXSIG);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004048
4049 nextopt(nullstr);
4050 retval = 0;
4051
4052 argv = argptr;
4053 if (!*argv) {
4054 /* wait for all jobs */
4055 for (;;) {
4056 jp = curjob;
4057 while (1) {
Denis Vlasenko991a1da2008-02-10 19:02:53 +00004058 if (!jp) /* no running procs */
4059 goto ret;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004060 if (jp->state == JOBRUNNING)
4061 break;
4062 jp->waited = 1;
4063 jp = jp->prev_job;
4064 }
Denys Vlasenko7c1ed9f2010-05-17 04:42:40 +02004065 blocking_wait_with_raise_on_sig();
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004066 /* man bash:
4067 * "When bash is waiting for an asynchronous command via
4068 * the wait builtin, the reception of a signal for which a trap
4069 * has been set will cause the wait builtin to return immediately
4070 * with an exit status greater than 128, immediately after which
4071 * the trap is executed."
Denys Vlasenko7c1ed9f2010-05-17 04:42:40 +02004072 *
4073 * blocking_wait_with_raise_on_sig raises signal handlers
4074 * if it gets no pid (pid < 0). However,
4075 * if child sends us a signal *and immediately exits*,
4076 * blocking_wait_with_raise_on_sig gets pid > 0
4077 * and does not handle pending_sig. Check this case: */
4078 if (pending_sig)
4079 raise_exception(EXSIG);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004080 }
4081 }
4082
4083 retval = 127;
4084 do {
4085 if (**argv != '%') {
4086 pid_t pid = number(*argv);
4087 job = curjob;
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00004088 while (1) {
4089 if (!job)
4090 goto repeat;
Denys Vlasenko285ad152009-12-04 23:02:27 +01004091 if (job->ps[job->nprocs - 1].ps_pid == pid)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004092 break;
4093 job = job->prev_job;
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00004094 }
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004095 } else
4096 job = getjob(*argv, 0);
4097 /* loop until process terminated or stopped */
4098 while (job->state == JOBRUNNING)
Denys Vlasenko7c1ed9f2010-05-17 04:42:40 +02004099 blocking_wait_with_raise_on_sig();
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004100 job->waited = 1;
4101 retval = getstatus(job);
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004102 repeat: ;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004103 } while (*++argv);
4104
Denis Vlasenko991a1da2008-02-10 19:02:53 +00004105 ret:
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004106 return retval;
4107}
4108
4109static struct job *
4110growjobtab(void)
4111{
4112 size_t len;
4113 ptrdiff_t offset;
4114 struct job *jp, *jq;
4115
4116 len = njobs * sizeof(*jp);
4117 jq = jobtab;
4118 jp = ckrealloc(jq, len + 4 * sizeof(*jp));
4119
4120 offset = (char *)jp - (char *)jq;
4121 if (offset) {
4122 /* Relocate pointers */
4123 size_t l = len;
4124
4125 jq = (struct job *)((char *)jq + l);
4126 while (l) {
4127 l -= sizeof(*jp);
4128 jq--;
4129#define joff(p) ((struct job *)((char *)(p) + l))
4130#define jmove(p) (p) = (void *)((char *)(p) + offset)
4131 if (joff(jp)->ps == &jq->ps0)
4132 jmove(joff(jp)->ps);
4133 if (joff(jp)->prev_job)
4134 jmove(joff(jp)->prev_job);
4135 }
4136 if (curjob)
4137 jmove(curjob);
4138#undef joff
4139#undef jmove
4140 }
4141
4142 njobs += 4;
4143 jobtab = jp;
4144 jp = (struct job *)((char *)jp + len);
4145 jq = jp + 3;
4146 do {
4147 jq->used = 0;
4148 } while (--jq >= jp);
4149 return jp;
4150}
4151
4152/*
4153 * Return a new job structure.
4154 * Called with interrupts off.
4155 */
4156static struct job *
Denis Vlasenko68404f12008-03-17 09:00:54 +00004157makejob(/*union node *node,*/ int nprocs)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004158{
4159 int i;
4160 struct job *jp;
4161
4162 for (i = njobs, jp = jobtab; ; jp++) {
4163 if (--i < 0) {
4164 jp = growjobtab();
4165 break;
4166 }
4167 if (jp->used == 0)
4168 break;
4169 if (jp->state != JOBDONE || !jp->waited)
4170 continue;
4171#if JOBS
Denis Vlasenkob07a4962008-06-22 13:16:23 +00004172 if (doing_jobctl)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004173 continue;
4174#endif
4175 freejob(jp);
4176 break;
4177 }
4178 memset(jp, 0, sizeof(*jp));
4179#if JOBS
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00004180 /* jp->jobctl is a bitfield.
4181 * "jp->jobctl |= jobctl" likely to give awful code */
Denis Vlasenkob07a4962008-06-22 13:16:23 +00004182 if (doing_jobctl)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004183 jp->jobctl = 1;
4184#endif
4185 jp->prev_job = curjob;
4186 curjob = jp;
4187 jp->used = 1;
4188 jp->ps = &jp->ps0;
4189 if (nprocs > 1) {
4190 jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
4191 }
Denis Vlasenko68404f12008-03-17 09:00:54 +00004192 TRACE(("makejob(%d) returns %%%d\n", nprocs,
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004193 jobno(jp)));
4194 return jp;
4195}
4196
4197#if JOBS
4198/*
4199 * Return a string identifying a command (to be printed by the
4200 * jobs command).
4201 */
4202static char *cmdnextc;
4203
4204static void
4205cmdputs(const char *s)
4206{
Denis Vlasenko92e13c22008-03-25 01:17:40 +00004207 static const char vstype[VSTYPE + 1][3] = {
4208 "", "}", "-", "+", "?", "=",
4209 "%", "%%", "#", "##"
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00004210 IF_ASH_BASH_COMPAT(, ":", "/", "//")
Denis Vlasenko92e13c22008-03-25 01:17:40 +00004211 };
4212
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004213 const char *p, *str;
Denys Vlasenko46a14772009-12-10 21:27:13 +01004214 char cc[2];
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004215 char *nextc;
Denys Vlasenkocd716832009-11-28 22:14:02 +01004216 unsigned char c;
4217 unsigned char subtype = 0;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004218 int quoted = 0;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004219
Denys Vlasenko46a14772009-12-10 21:27:13 +01004220 cc[1] = '\0';
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004221 nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
4222 p = s;
Denys Vlasenko46a14772009-12-10 21:27:13 +01004223 while ((c = *p++) != '\0') {
Denis Vlasenkoef527f52008-06-23 01:52:30 +00004224 str = NULL;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004225 switch (c) {
4226 case CTLESC:
4227 c = *p++;
4228 break;
4229 case CTLVAR:
4230 subtype = *p++;
4231 if ((subtype & VSTYPE) == VSLENGTH)
4232 str = "${#";
4233 else
4234 str = "${";
4235 if (!(subtype & VSQUOTE) == !(quoted & 1))
4236 goto dostr;
4237 quoted ^= 1;
4238 c = '"';
4239 break;
4240 case CTLENDVAR:
4241 str = "\"}" + !(quoted & 1);
4242 quoted >>= 1;
4243 subtype = 0;
4244 goto dostr;
4245 case CTLBACKQ:
4246 str = "$(...)";
4247 goto dostr;
4248 case CTLBACKQ+CTLQUOTE:
4249 str = "\"$(...)\"";
4250 goto dostr;
Mike Frysinger98c52642009-04-02 10:02:37 +00004251#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004252 case CTLARI:
4253 str = "$((";
4254 goto dostr;
4255 case CTLENDARI:
4256 str = "))";
4257 goto dostr;
4258#endif
4259 case CTLQUOTEMARK:
4260 quoted ^= 1;
4261 c = '"';
4262 break;
4263 case '=':
4264 if (subtype == 0)
4265 break;
4266 if ((subtype & VSTYPE) != VSNORMAL)
4267 quoted <<= 1;
4268 str = vstype[subtype & VSTYPE];
4269 if (subtype & VSNUL)
4270 c = ':';
4271 else
4272 goto checkstr;
4273 break;
4274 case '\'':
4275 case '\\':
4276 case '"':
4277 case '$':
4278 /* These can only happen inside quotes */
4279 cc[0] = c;
4280 str = cc;
4281 c = '\\';
4282 break;
4283 default:
4284 break;
4285 }
4286 USTPUTC(c, nextc);
4287 checkstr:
4288 if (!str)
4289 continue;
4290 dostr:
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02004291 while ((c = *str++) != '\0') {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004292 USTPUTC(c, nextc);
4293 }
Denys Vlasenko46a14772009-12-10 21:27:13 +01004294 } /* while *p++ not NUL */
4295
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004296 if (quoted & 1) {
4297 USTPUTC('"', nextc);
4298 }
4299 *nextc = 0;
4300 cmdnextc = nextc;
4301}
4302
4303/* cmdtxt() and cmdlist() call each other */
4304static void cmdtxt(union node *n);
4305
4306static void
4307cmdlist(union node *np, int sep)
4308{
4309 for (; np; np = np->narg.next) {
4310 if (!sep)
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00004311 cmdputs(" ");
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004312 cmdtxt(np);
4313 if (sep && np->narg.next)
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00004314 cmdputs(" ");
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004315 }
4316}
4317
4318static void
4319cmdtxt(union node *n)
4320{
4321 union node *np;
4322 struct nodelist *lp;
4323 const char *p;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004324
4325 if (!n)
4326 return;
4327 switch (n->type) {
4328 default:
4329#if DEBUG
4330 abort();
4331#endif
4332 case NPIPE:
4333 lp = n->npipe.cmdlist;
4334 for (;;) {
4335 cmdtxt(lp->n);
4336 lp = lp->next;
4337 if (!lp)
4338 break;
4339 cmdputs(" | ");
4340 }
4341 break;
4342 case NSEMI:
4343 p = "; ";
4344 goto binop;
4345 case NAND:
4346 p = " && ";
4347 goto binop;
4348 case NOR:
4349 p = " || ";
4350 binop:
4351 cmdtxt(n->nbinary.ch1);
4352 cmdputs(p);
4353 n = n->nbinary.ch2;
4354 goto donode;
4355 case NREDIR:
4356 case NBACKGND:
4357 n = n->nredir.n;
4358 goto donode;
4359 case NNOT:
4360 cmdputs("!");
4361 n = n->nnot.com;
4362 donode:
4363 cmdtxt(n);
4364 break;
4365 case NIF:
4366 cmdputs("if ");
4367 cmdtxt(n->nif.test);
4368 cmdputs("; then ");
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004369 if (n->nif.elsepart) {
Denys Vlasenko7cee00e2009-07-24 01:08:03 +02004370 cmdtxt(n->nif.ifpart);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004371 cmdputs("; else ");
4372 n = n->nif.elsepart;
Denys Vlasenko7cee00e2009-07-24 01:08:03 +02004373 } else {
4374 n = n->nif.ifpart;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004375 }
4376 p = "; fi";
4377 goto dotail;
4378 case NSUBSHELL:
4379 cmdputs("(");
4380 n = n->nredir.n;
4381 p = ")";
4382 goto dotail;
4383 case NWHILE:
4384 p = "while ";
4385 goto until;
4386 case NUNTIL:
4387 p = "until ";
4388 until:
4389 cmdputs(p);
4390 cmdtxt(n->nbinary.ch1);
4391 n = n->nbinary.ch2;
4392 p = "; done";
4393 dodo:
4394 cmdputs("; do ");
4395 dotail:
4396 cmdtxt(n);
4397 goto dotail2;
4398 case NFOR:
4399 cmdputs("for ");
4400 cmdputs(n->nfor.var);
4401 cmdputs(" in ");
4402 cmdlist(n->nfor.args, 1);
4403 n = n->nfor.body;
4404 p = "; done";
4405 goto dodo;
4406 case NDEFUN:
4407 cmdputs(n->narg.text);
4408 p = "() { ... }";
4409 goto dotail2;
4410 case NCMD:
4411 cmdlist(n->ncmd.args, 1);
4412 cmdlist(n->ncmd.redirect, 0);
4413 break;
4414 case NARG:
4415 p = n->narg.text;
4416 dotail2:
4417 cmdputs(p);
4418 break;
4419 case NHERE:
4420 case NXHERE:
4421 p = "<<...";
4422 goto dotail2;
4423 case NCASE:
4424 cmdputs("case ");
4425 cmdputs(n->ncase.expr->narg.text);
4426 cmdputs(" in ");
4427 for (np = n->ncase.cases; np; np = np->nclist.next) {
4428 cmdtxt(np->nclist.pattern);
4429 cmdputs(") ");
4430 cmdtxt(np->nclist.body);
4431 cmdputs(";; ");
4432 }
4433 p = "esac";
4434 goto dotail2;
4435 case NTO:
4436 p = ">";
4437 goto redir;
4438 case NCLOBBER:
4439 p = ">|";
4440 goto redir;
4441 case NAPPEND:
4442 p = ">>";
4443 goto redir;
Denis Vlasenko559691a2008-10-05 18:39:31 +00004444#if ENABLE_ASH_BASH_COMPAT
4445 case NTO2:
4446#endif
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004447 case NTOFD:
4448 p = ">&";
4449 goto redir;
4450 case NFROM:
4451 p = "<";
4452 goto redir;
4453 case NFROMFD:
4454 p = "<&";
4455 goto redir;
4456 case NFROMTO:
4457 p = "<>";
4458 redir:
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00004459 cmdputs(utoa(n->nfile.fd));
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004460 cmdputs(p);
4461 if (n->type == NTOFD || n->type == NFROMFD) {
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00004462 cmdputs(utoa(n->ndup.dupfd));
4463 break;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004464 }
4465 n = n->nfile.fname;
4466 goto donode;
4467 }
4468}
4469
4470static char *
4471commandtext(union node *n)
4472{
4473 char *name;
4474
4475 STARTSTACKSTR(cmdnextc);
4476 cmdtxt(n);
4477 name = stackblock();
4478 TRACE(("commandtext: name %p, end %p\n\t\"%s\"\n",
4479 name, cmdnextc, cmdnextc));
4480 return ckstrdup(name);
4481}
4482#endif /* JOBS */
4483
4484/*
4485 * Fork off a subshell. If we are doing job control, give the subshell its
4486 * own process group. Jp is a job structure that the job is to be added to.
4487 * N is the command that will be evaluated by the child. Both jp and n may
4488 * be NULL. The mode parameter can be one of the following:
4489 * FORK_FG - Fork off a foreground process.
4490 * FORK_BG - Fork off a background process.
4491 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
4492 * process group even if job control is on.
4493 *
4494 * When job control is turned off, background processes have their standard
4495 * input redirected to /dev/null (except for the second and later processes
4496 * in a pipeline).
4497 *
4498 * Called with interrupts off.
4499 */
4500/*
4501 * Clear traps on a fork.
4502 */
4503static void
4504clear_traps(void)
4505{
4506 char **tp;
4507
4508 for (tp = trap; tp < &trap[NSIG]; tp++) {
Denis Vlasenko991a1da2008-02-10 19:02:53 +00004509 if (*tp && **tp) { /* trap not NULL or "" (SIG_IGN) */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004510 INT_OFF;
Denys Vlasenkoe305c282009-09-25 02:12:27 +02004511 if (trap_ptr == trap)
4512 free(*tp);
4513 /* else: it "belongs" to trap_ptr vector, don't free */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004514 *tp = NULL;
Denys Vlasenko0800e3a2009-09-24 03:09:26 +02004515 if ((tp - trap) != 0)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004516 setsignal(tp - trap);
4517 INT_ON;
4518 }
4519 }
4520}
Denis Vlasenkobdc406d2007-07-15 01:13:25 +00004521
4522/* Lives far away from here, needed for forkchild */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004523static void closescript(void);
Denis Vlasenko41770222007-10-07 18:02:52 +00004524
Denis Vlasenkobdc406d2007-07-15 01:13:25 +00004525/* Called after fork(), in child */
Denys Vlasenko21d87d42009-09-25 00:06:51 +02004526static NOINLINE void
Denys Vlasenkoe56f22a2009-07-24 00:16:59 +02004527forkchild(struct job *jp, union node *n, int mode)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004528{
4529 int oldlvl;
4530
4531 TRACE(("Child shell %d\n", getpid()));
4532 oldlvl = shlvl;
4533 shlvl++;
4534
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004535 /* man bash: "Non-builtin commands run by bash have signal handlers
4536 * set to the values inherited by the shell from its parent".
4537 * Do we do it correctly? */
4538
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004539 closescript();
Denys Vlasenko844f9902009-09-23 03:25:52 +02004540
4541 if (mode == FORK_NOJOB /* is it `xxx` ? */
4542 && n && n->type == NCMD /* is it single cmd? */
4543 /* && n->ncmd.args->type == NARG - always true? */
Denys Vlasenko74269202010-02-21 01:26:42 +01004544 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "trap") == 0
Denys Vlasenko844f9902009-09-23 03:25:52 +02004545 && n->ncmd.args->narg.next == NULL /* "trap" with no arguments */
4546 /* && n->ncmd.args->narg.backquote == NULL - do we need to check this? */
4547 ) {
4548 TRACE(("Trap hack\n"));
4549 /* Awful hack for `trap` or $(trap).
4550 *
4551 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
4552 * contains an example where "trap" is executed in a subshell:
4553 *
4554 * save_traps=$(trap)
4555 * ...
4556 * eval "$save_traps"
4557 *
4558 * Standard does not say that "trap" in subshell shall print
4559 * parent shell's traps. It only says that its output
4560 * must have suitable form, but then, in the above example
4561 * (which is not supposed to be normative), it implies that.
4562 *
4563 * bash (and probably other shell) does implement it
4564 * (traps are reset to defaults, but "trap" still shows them),
4565 * but as a result, "trap" logic is hopelessly messed up:
4566 *
4567 * # trap
4568 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
4569 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
4570 * # true | trap <--- trap is in subshell - no output (ditto)
4571 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
4572 * trap -- 'echo Ho' SIGWINCH
4573 * # echo `(trap)` <--- in subshell in subshell - output
4574 * trap -- 'echo Ho' SIGWINCH
4575 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
4576 * trap -- 'echo Ho' SIGWINCH
4577 *
4578 * The rules when to forget and when to not forget traps
4579 * get really complex and nonsensical.
4580 *
4581 * Our solution: ONLY bare $(trap) or `trap` is special.
4582 */
Denys Vlasenko8f88d852009-09-25 12:12:53 +02004583 /* Save trap handler strings for trap builtin to print */
Denys Vlasenko21d87d42009-09-25 00:06:51 +02004584 trap_ptr = memcpy(xmalloc(sizeof(trap)), trap, sizeof(trap));
Denys Vlasenko8f88d852009-09-25 12:12:53 +02004585 /* Fall through into clearing traps */
Denys Vlasenko844f9902009-09-23 03:25:52 +02004586 }
Denys Vlasenkoe305c282009-09-25 02:12:27 +02004587 clear_traps();
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004588#if JOBS
4589 /* do job control only in root shell */
Denis Vlasenkob07a4962008-06-22 13:16:23 +00004590 doing_jobctl = 0;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004591 if (mode != FORK_NOJOB && jp->jobctl && !oldlvl) {
4592 pid_t pgrp;
4593
4594 if (jp->nprocs == 0)
4595 pgrp = getpid();
4596 else
Denys Vlasenko285ad152009-12-04 23:02:27 +01004597 pgrp = jp->ps[0].ps_pid;
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004598 /* this can fail because we are doing it in the parent also */
4599 setpgid(0, pgrp);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004600 if (mode == FORK_FG)
4601 xtcsetpgrp(ttyfd, pgrp);
4602 setsignal(SIGTSTP);
4603 setsignal(SIGTTOU);
4604 } else
4605#endif
4606 if (mode == FORK_BG) {
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004607 /* man bash: "When job control is not in effect,
4608 * asynchronous commands ignore SIGINT and SIGQUIT" */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004609 ignoresig(SIGINT);
4610 ignoresig(SIGQUIT);
4611 if (jp->nprocs == 0) {
4612 close(0);
4613 if (open(bb_dev_null, O_RDONLY) != 0)
Denis Vlasenko9604e1b2009-03-03 18:47:56 +00004614 ash_msg_and_raise_error("can't open '%s'", bb_dev_null);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004615 }
4616 }
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004617 if (!oldlvl) {
4618 if (iflag) { /* why if iflag only? */
4619 setsignal(SIGINT);
4620 setsignal(SIGTERM);
4621 }
4622 /* man bash:
4623 * "In all cases, bash ignores SIGQUIT. Non-builtin
4624 * commands run by bash have signal handlers
4625 * set to the values inherited by the shell
4626 * from its parent".
4627 * Take care of the second rule: */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004628 setsignal(SIGQUIT);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004629 }
Denys Vlasenkoe56f22a2009-07-24 00:16:59 +02004630#if JOBS
Denys Vlasenko844f9902009-09-23 03:25:52 +02004631 if (n && n->type == NCMD
Denys Vlasenko74269202010-02-21 01:26:42 +01004632 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "jobs") == 0
Denys Vlasenko844f9902009-09-23 03:25:52 +02004633 ) {
Denys Vlasenkoe56f22a2009-07-24 00:16:59 +02004634 TRACE(("Job hack\n"));
Denys Vlasenko844f9902009-09-23 03:25:52 +02004635 /* "jobs": we do not want to clear job list for it,
4636 * instead we remove only _its_ own_ job from job list.
4637 * This makes "jobs .... | cat" more useful.
4638 */
Denys Vlasenkoe56f22a2009-07-24 00:16:59 +02004639 freejob(curjob);
4640 return;
4641 }
4642#endif
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004643 for (jp = curjob; jp; jp = jp->prev_job)
4644 freejob(jp);
4645 jobless = 0;
4646}
4647
Denis Vlasenkobdc406d2007-07-15 01:13:25 +00004648/* Called after fork(), in parent */
Denis Vlasenko85c24712008-03-17 09:04:04 +00004649#if !JOBS
4650#define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
4651#endif
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004652static void
4653forkparent(struct job *jp, union node *n, int mode, pid_t pid)
4654{
4655 TRACE(("In parent shell: child = %d\n", pid));
4656 if (!jp) {
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00004657 while (jobless && dowait(DOWAIT_NONBLOCK, NULL) > 0)
4658 continue;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004659 jobless++;
4660 return;
4661 }
4662#if JOBS
4663 if (mode != FORK_NOJOB && jp->jobctl) {
4664 int pgrp;
4665
4666 if (jp->nprocs == 0)
4667 pgrp = pid;
4668 else
Denys Vlasenko285ad152009-12-04 23:02:27 +01004669 pgrp = jp->ps[0].ps_pid;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004670 /* This can fail because we are doing it in the child also */
4671 setpgid(pid, pgrp);
4672 }
4673#endif
4674 if (mode == FORK_BG) {
4675 backgndpid = pid; /* set $! */
4676 set_curjob(jp, CUR_RUNNING);
4677 }
4678 if (jp) {
4679 struct procstat *ps = &jp->ps[jp->nprocs++];
Denys Vlasenko285ad152009-12-04 23:02:27 +01004680 ps->ps_pid = pid;
4681 ps->ps_status = -1;
4682 ps->ps_cmd = nullstr;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004683#if JOBS
Denis Vlasenkob07a4962008-06-22 13:16:23 +00004684 if (doing_jobctl && n)
Denys Vlasenko285ad152009-12-04 23:02:27 +01004685 ps->ps_cmd = commandtext(n);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004686#endif
4687 }
4688}
4689
4690static int
4691forkshell(struct job *jp, union node *n, int mode)
4692{
4693 int pid;
4694
4695 TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
4696 pid = fork();
4697 if (pid < 0) {
4698 TRACE(("Fork failed, errno=%d", errno));
4699 if (jp)
4700 freejob(jp);
Denis Vlasenkofa0b56d2008-07-01 16:09:07 +00004701 ash_msg_and_raise_error("can't fork");
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004702 }
Denys Vlasenko76ace252009-10-12 15:25:01 +02004703 if (pid == 0) {
4704 CLEAR_RANDOM_T(&random_gen); /* or else $RANDOM repeats in child */
Denys Vlasenkoe56f22a2009-07-24 00:16:59 +02004705 forkchild(jp, n, mode);
Denys Vlasenko76ace252009-10-12 15:25:01 +02004706 } else {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004707 forkparent(jp, n, mode, pid);
Denys Vlasenko76ace252009-10-12 15:25:01 +02004708 }
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004709 return pid;
4710}
4711
4712/*
4713 * Wait for job to finish.
4714 *
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004715 * Under job control we have the problem that while a child process
4716 * is running interrupts generated by the user are sent to the child
4717 * but not to the shell. This means that an infinite loop started by
4718 * an interactive user may be hard to kill. With job control turned off,
4719 * an interactive user may place an interactive program inside a loop.
4720 * If the interactive program catches interrupts, the user doesn't want
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004721 * these interrupts to also abort the loop. The approach we take here
4722 * is to have the shell ignore interrupt signals while waiting for a
4723 * foreground process to terminate, and then send itself an interrupt
4724 * signal if the child process was terminated by an interrupt signal.
4725 * Unfortunately, some programs want to do a bit of cleanup and then
4726 * exit on interrupt; unless these processes terminate themselves by
4727 * sending a signal to themselves (instead of calling exit) they will
4728 * confuse this approach.
4729 *
4730 * Called with interrupts off.
4731 */
4732static int
4733waitforjob(struct job *jp)
4734{
4735 int st;
4736
4737 TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004738
4739 INT_OFF;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004740 while (jp->state == JOBRUNNING) {
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004741 /* In non-interactive shells, we _can_ get
4742 * a keyboard signal here and be EINTRed,
4743 * but we just loop back, waiting for command to complete.
4744 *
4745 * man bash:
4746 * "If bash is waiting for a command to complete and receives
4747 * a signal for which a trap has been set, the trap
4748 * will not be executed until the command completes."
4749 *
4750 * Reality is that even if trap is not set, bash
4751 * will not act on the signal until command completes.
4752 * Try this. sleep5intoff.c:
4753 * #include <signal.h>
4754 * #include <unistd.h>
4755 * int main() {
4756 * sigset_t set;
4757 * sigemptyset(&set);
4758 * sigaddset(&set, SIGINT);
4759 * sigaddset(&set, SIGQUIT);
4760 * sigprocmask(SIG_BLOCK, &set, NULL);
4761 * sleep(5);
4762 * return 0;
4763 * }
4764 * $ bash -c './sleep5intoff; echo hi'
4765 * ^C^C^C^C <--- pressing ^C once a second
4766 * $ _
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004767 * $ bash -c './sleep5intoff; echo hi'
4768 * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
4769 * $ _
4770 */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004771 dowait(DOWAIT_BLOCK, jp);
4772 }
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004773 INT_ON;
4774
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004775 st = getstatus(jp);
4776#if JOBS
4777 if (jp->jobctl) {
4778 xtcsetpgrp(ttyfd, rootpid);
4779 /*
4780 * This is truly gross.
4781 * If we're doing job control, then we did a TIOCSPGRP which
4782 * caused us (the shell) to no longer be in the controlling
4783 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
4784 * intuit from the subprocess exit status whether a SIGINT
4785 * occurred, and if so interrupt ourselves. Yuck. - mycroft
4786 */
Denis Vlasenko991a1da2008-02-10 19:02:53 +00004787 if (jp->sigint) /* TODO: do the same with all signals */
4788 raise(SIGINT); /* ... by raise(jp->sig) instead? */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004789 }
4790 if (jp->state == JOBDONE)
4791#endif
4792 freejob(jp);
4793 return st;
4794}
4795
4796/*
4797 * return 1 if there are stopped jobs, otherwise 0
4798 */
4799static int
4800stoppedjobs(void)
4801{
4802 struct job *jp;
4803 int retval;
4804
4805 retval = 0;
4806 if (job_warning)
4807 goto out;
4808 jp = curjob;
4809 if (jp && jp->state == JOBSTOPPED) {
4810 out2str("You have stopped jobs.\n");
4811 job_warning = 2;
4812 retval++;
4813 }
4814 out:
4815 return retval;
4816}
4817
4818
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004819/* ============ redir.c
4820 *
4821 * Code for dealing with input/output redirection.
4822 */
4823
4824#define EMPTY -2 /* marks an unused slot in redirtab */
Denis Vlasenko7d75a962007-11-22 08:16:57 +00004825#define CLOSED -3 /* marks a slot of previously-closed fd */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004826
4827/*
4828 * Open a file in noclobber mode.
4829 * The code was copied from bash.
4830 */
4831static int
4832noclobberopen(const char *fname)
4833{
4834 int r, fd;
4835 struct stat finfo, finfo2;
4836
4837 /*
4838 * If the file exists and is a regular file, return an error
4839 * immediately.
4840 */
4841 r = stat(fname, &finfo);
4842 if (r == 0 && S_ISREG(finfo.st_mode)) {
4843 errno = EEXIST;
4844 return -1;
4845 }
4846
4847 /*
4848 * If the file was not present (r != 0), make sure we open it
4849 * exclusively so that if it is created before we open it, our open
4850 * will fail. Make sure that we do not truncate an existing file.
4851 * Note that we don't turn on O_EXCL unless the stat failed -- if the
4852 * file was not a regular file, we leave O_EXCL off.
4853 */
4854 if (r != 0)
4855 return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
4856 fd = open(fname, O_WRONLY|O_CREAT, 0666);
4857
4858 /* If the open failed, return the file descriptor right away. */
4859 if (fd < 0)
4860 return fd;
4861
4862 /*
4863 * OK, the open succeeded, but the file may have been changed from a
4864 * non-regular file to a regular file between the stat and the open.
4865 * We are assuming that the O_EXCL open handles the case where FILENAME
4866 * did not exist and is symlinked to an existing file between the stat
4867 * and open.
4868 */
4869
4870 /*
4871 * If we can open it and fstat the file descriptor, and neither check
4872 * revealed that it was a regular file, and the file has not been
4873 * replaced, return the file descriptor.
4874 */
4875 if (fstat(fd, &finfo2) == 0 && !S_ISREG(finfo2.st_mode)
4876 && finfo.st_dev == finfo2.st_dev && finfo.st_ino == finfo2.st_ino)
4877 return fd;
4878
4879 /* The file has been replaced. badness. */
4880 close(fd);
4881 errno = EEXIST;
4882 return -1;
4883}
4884
4885/*
4886 * Handle here documents. Normally we fork off a process to write the
4887 * data to a pipe. If the document is short, we can stuff the data in
4888 * the pipe without forking.
4889 */
4890/* openhere needs this forward reference */
4891static void expandhere(union node *arg, int fd);
4892static int
4893openhere(union node *redir)
4894{
4895 int pip[2];
4896 size_t len = 0;
4897
4898 if (pipe(pip) < 0)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00004899 ash_msg_and_raise_error("pipe call failed");
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004900 if (redir->type == NHERE) {
4901 len = strlen(redir->nhere.doc->narg.text);
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00004902 if (len <= PIPE_BUF) {
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004903 full_write(pip[1], redir->nhere.doc->narg.text, len);
4904 goto out;
4905 }
4906 }
4907 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
Denis Vlasenko0b769642008-07-24 07:54:57 +00004908 /* child */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004909 close(pip[0]);
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004910 ignoresig(SIGINT); //signal(SIGINT, SIG_IGN);
4911 ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
4912 ignoresig(SIGHUP); //signal(SIGHUP, SIG_IGN);
4913 ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004914 signal(SIGPIPE, SIG_DFL);
4915 if (redir->type == NHERE)
4916 full_write(pip[1], redir->nhere.doc->narg.text, len);
Denis Vlasenko0b769642008-07-24 07:54:57 +00004917 else /* NXHERE */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004918 expandhere(redir->nhere.doc, pip[1]);
Bernhard Reutner-Fischer636a1f82008-05-19 09:29:47 +00004919 _exit(EXIT_SUCCESS);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004920 }
4921 out:
4922 close(pip[1]);
4923 return pip[0];
4924}
4925
4926static int
4927openredirect(union node *redir)
4928{
4929 char *fname;
4930 int f;
4931
4932 switch (redir->nfile.type) {
4933 case NFROM:
4934 fname = redir->nfile.expfname;
4935 f = open(fname, O_RDONLY);
4936 if (f < 0)
4937 goto eopen;
4938 break;
4939 case NFROMTO:
4940 fname = redir->nfile.expfname;
4941 f = open(fname, O_RDWR|O_CREAT|O_TRUNC, 0666);
4942 if (f < 0)
4943 goto ecreate;
4944 break;
4945 case NTO:
Denis Vlasenko559691a2008-10-05 18:39:31 +00004946#if ENABLE_ASH_BASH_COMPAT
4947 case NTO2:
4948#endif
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004949 /* Take care of noclobber mode. */
4950 if (Cflag) {
4951 fname = redir->nfile.expfname;
4952 f = noclobberopen(fname);
4953 if (f < 0)
4954 goto ecreate;
4955 break;
4956 }
4957 /* FALLTHROUGH */
4958 case NCLOBBER:
4959 fname = redir->nfile.expfname;
4960 f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
4961 if (f < 0)
4962 goto ecreate;
4963 break;
4964 case NAPPEND:
4965 fname = redir->nfile.expfname;
4966 f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
4967 if (f < 0)
4968 goto ecreate;
4969 break;
4970 default:
4971#if DEBUG
4972 abort();
4973#endif
4974 /* Fall through to eliminate warning. */
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00004975/* Our single caller does this itself */
Denis Vlasenko0b769642008-07-24 07:54:57 +00004976// case NTOFD:
4977// case NFROMFD:
4978// f = -1;
4979// break;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004980 case NHERE:
4981 case NXHERE:
4982 f = openhere(redir);
4983 break;
4984 }
4985
4986 return f;
4987 ecreate:
Bernhard Reutner-Fischera53de7f2008-07-21 13:46:54 +00004988 ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004989 eopen:
Bernhard Reutner-Fischera53de7f2008-07-21 13:46:54 +00004990 ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004991}
4992
4993/*
4994 * Copy a file descriptor to be >= to. Returns -1
4995 * if the source file descriptor is closed, EMPTY if there are no unused
4996 * file descriptors left.
4997 */
Denis Vlasenko5a867312008-07-24 19:46:38 +00004998/* 0x800..00: bit to set in "to" to request dup2 instead of fcntl(F_DUPFD).
4999 * old code was doing close(to) prior to copyfd() to achieve the same */
Denis Vlasenko22f74142008-07-24 22:34:43 +00005000enum {
5001 COPYFD_EXACT = (int)~(INT_MAX),
5002 COPYFD_RESTORE = (int)((unsigned)COPYFD_EXACT >> 1),
5003};
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005004static int
5005copyfd(int from, int to)
5006{
5007 int newfd;
5008
Denis Vlasenko5a867312008-07-24 19:46:38 +00005009 if (to & COPYFD_EXACT) {
5010 to &= ~COPYFD_EXACT;
5011 /*if (from != to)*/
5012 newfd = dup2(from, to);
5013 } else {
5014 newfd = fcntl(from, F_DUPFD, to);
5015 }
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005016 if (newfd < 0) {
5017 if (errno == EMFILE)
5018 return EMPTY;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005019 /* Happens when source fd is not open: try "echo >&99" */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005020 ash_msg_and_raise_error("%d: %m", from);
5021 }
5022 return newfd;
5023}
5024
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005025/* Struct def and variable are moved down to the first usage site */
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005026struct two_fd_t {
5027 int orig, copy;
5028};
Denis Vlasenko0b769642008-07-24 07:54:57 +00005029struct redirtab {
5030 struct redirtab *next;
Denis Vlasenko0b769642008-07-24 07:54:57 +00005031 int nullredirs;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005032 int pair_count;
Denys Vlasenko606291b2009-09-23 23:15:43 +02005033 struct two_fd_t two_fd[];
Denis Vlasenko0b769642008-07-24 07:54:57 +00005034};
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005035#define redirlist (G_var.redirlist)
Denis Vlasenko0b769642008-07-24 07:54:57 +00005036
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005037static int need_to_remember(struct redirtab *rp, int fd)
5038{
5039 int i;
5040
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005041 if (!rp) /* remembering was not requested */
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005042 return 0;
5043
5044 for (i = 0; i < rp->pair_count; i++) {
5045 if (rp->two_fd[i].orig == fd) {
5046 /* already remembered */
5047 return 0;
5048 }
5049 }
5050 return 1;
5051}
5052
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005053/* "hidden" fd is a fd used to read scripts, or a copy of such */
5054static int is_hidden_fd(struct redirtab *rp, int fd)
5055{
5056 int i;
Denis Vlasenko34c73c42008-08-16 11:48:02 +00005057 struct parsefile *pf;
5058
5059 if (fd == -1)
5060 return 0;
Denys Vlasenko08d8b3c2010-06-03 04:28:28 +02005061 /* Check open scripts' fds */
Denis Vlasenko34c73c42008-08-16 11:48:02 +00005062 pf = g_parsefile;
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005063 while (pf) {
Denys Vlasenko79b3d422010-06-03 04:29:08 +02005064 /* We skip pf_fd == 0 case because of the following case:
Denys Vlasenko08d8b3c2010-06-03 04:28:28 +02005065 * $ ash # running ash interactively
5066 * $ . ./script.sh
5067 * and in script.sh: "exec 9>&0".
Denys Vlasenko79b3d422010-06-03 04:29:08 +02005068 * Even though top-level pf_fd _is_ 0,
Denys Vlasenko08d8b3c2010-06-03 04:28:28 +02005069 * it's still ok to use it: "read" builtin uses it,
5070 * why should we cripple "exec" builtin?
5071 */
Denys Vlasenko79b3d422010-06-03 04:29:08 +02005072 if (pf->pf_fd > 0 && fd == pf->pf_fd) {
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005073 return 1;
5074 }
5075 pf = pf->prev;
5076 }
Denys Vlasenko08d8b3c2010-06-03 04:28:28 +02005077
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005078 if (!rp)
5079 return 0;
Denys Vlasenko08d8b3c2010-06-03 04:28:28 +02005080 /* Check saved fds of redirects */
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005081 fd |= COPYFD_RESTORE;
5082 for (i = 0; i < rp->pair_count; i++) {
5083 if (rp->two_fd[i].copy == fd) {
5084 return 1;
5085 }
5086 }
5087 return 0;
5088}
5089
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005090/*
5091 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
5092 * old file descriptors are stashed away so that the redirection can be
Denys Vlasenko08d8b3c2010-06-03 04:28:28 +02005093 * undone by calling popredir.
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005094 */
5095/* flags passed to redirect */
5096#define REDIR_PUSH 01 /* save previous values of file descriptors */
5097#define REDIR_SAVEFD2 03 /* set preverrout */
5098static void
5099redirect(union node *redir, int flags)
5100{
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005101 struct redirtab *sv;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005102 int sv_pos;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005103 int i;
5104 int fd;
5105 int newfd;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005106 int copied_fd2 = -1;
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005107
Denis Vlasenko01631112007-12-16 17:20:38 +00005108 g_nullredirs++;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005109 if (!redir) {
5110 return;
5111 }
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005112
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005113 sv = NULL;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005114 sv_pos = 0;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005115 INT_OFF;
5116 if (flags & REDIR_PUSH) {
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005117 union node *tmp = redir;
5118 do {
5119 sv_pos++;
Denis Vlasenko559691a2008-10-05 18:39:31 +00005120#if ENABLE_ASH_BASH_COMPAT
Chris Metcalfc3c1fb62010-01-08 13:18:06 +01005121 if (tmp->nfile.type == NTO2)
Denis Vlasenko559691a2008-10-05 18:39:31 +00005122 sv_pos++;
5123#endif
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005124 tmp = tmp->nfile.next;
5125 } while (tmp);
5126 sv = ckmalloc(sizeof(*sv) + sv_pos * sizeof(sv->two_fd[0]));
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005127 sv->next = redirlist;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005128 sv->pair_count = sv_pos;
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005129 redirlist = sv;
Denis Vlasenko01631112007-12-16 17:20:38 +00005130 sv->nullredirs = g_nullredirs - 1;
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005131 g_nullredirs = 0;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005132 while (sv_pos > 0) {
5133 sv_pos--;
5134 sv->two_fd[sv_pos].orig = sv->two_fd[sv_pos].copy = EMPTY;
5135 }
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005136 }
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005137
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005138 do {
Denys Vlasenko08d8b3c2010-06-03 04:28:28 +02005139 int right_fd = -1;
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00005140 fd = redir->nfile.fd;
Denis Vlasenko0b769642008-07-24 07:54:57 +00005141 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
Denys Vlasenko08d8b3c2010-06-03 04:28:28 +02005142 right_fd = redir->ndup.dupfd;
5143 //bb_error_msg("doing %d > %d", fd, right_fd);
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005144 /* redirect from/to same file descriptor? */
5145 if (right_fd == fd)
5146 continue;
Denys Vlasenko08d8b3c2010-06-03 04:28:28 +02005147 /* "echo >&10" and 10 is a fd opened to a sh script? */
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005148 if (is_hidden_fd(sv, right_fd)) {
5149 errno = EBADF; /* as if it is closed */
5150 ash_msg_and_raise_error("%d: %m", right_fd);
5151 }
Denis Vlasenko0b769642008-07-24 07:54:57 +00005152 newfd = -1;
5153 } else {
5154 newfd = openredirect(redir); /* always >= 0 */
5155 if (fd == newfd) {
5156 /* Descriptor wasn't open before redirect.
5157 * Mark it for close in the future */
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005158 if (need_to_remember(sv, fd)) {
Denis Vlasenko5a867312008-07-24 19:46:38 +00005159 goto remember_to_close;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005160 }
Denis Vlasenko0b769642008-07-24 07:54:57 +00005161 continue;
5162 }
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005163 }
Denis Vlasenko559691a2008-10-05 18:39:31 +00005164#if ENABLE_ASH_BASH_COMPAT
5165 redirect_more:
5166#endif
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005167 if (need_to_remember(sv, fd)) {
Denis Vlasenko0b769642008-07-24 07:54:57 +00005168 /* Copy old descriptor */
Denys Vlasenko08d8b3c2010-06-03 04:28:28 +02005169 /* Careful to not accidentally "save"
5170 * to the same fd as right side fd in N>&M */
5171 int minfd = right_fd < 10 ? 10 : right_fd + 1;
5172 i = fcntl(fd, F_DUPFD, minfd);
Denis Vlasenko5a867312008-07-24 19:46:38 +00005173/* You'd expect copy to be CLOEXECed. Currently these extra "saved" fds
5174 * are closed in popredir() in the child, preventing them from leaking
5175 * into child. (popredir() also cleans up the mess in case of failures)
5176 */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005177 if (i == -1) {
5178 i = errno;
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005179 if (i != EBADF) {
5180 /* Strange error (e.g. "too many files" EMFILE?) */
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005181 if (newfd >= 0)
5182 close(newfd);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005183 errno = i;
5184 ash_msg_and_raise_error("%d: %m", fd);
5185 /* NOTREACHED */
5186 }
Denis Vlasenko5a867312008-07-24 19:46:38 +00005187 /* EBADF: it is not open - good, remember to close it */
5188 remember_to_close:
5189 i = CLOSED;
Denis Vlasenko22f74142008-07-24 22:34:43 +00005190 } else { /* fd is open, save its copy */
5191 /* "exec fd>&-" should not close fds
5192 * which point to script file(s).
5193 * Force them to be restored afterwards */
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005194 if (is_hidden_fd(sv, fd))
5195 i |= COPYFD_RESTORE;
Denis Vlasenko22f74142008-07-24 22:34:43 +00005196 }
Denis Vlasenko5a867312008-07-24 19:46:38 +00005197 if (fd == 2)
5198 copied_fd2 = i;
5199 sv->two_fd[sv_pos].orig = fd;
5200 sv->two_fd[sv_pos].copy = i;
5201 sv_pos++;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005202 }
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005203 if (newfd < 0) {
5204 /* NTOFD/NFROMFD: copy redir->ndup.dupfd to fd */
Denis Vlasenko22f74142008-07-24 22:34:43 +00005205 if (redir->ndup.dupfd < 0) { /* "fd>&-" */
Denis Vlasenkob9e70dd2009-03-20 01:24:08 +00005206 /* Don't want to trigger debugging */
5207 if (fd != -1)
5208 close(fd);
Denis Vlasenko5a867312008-07-24 19:46:38 +00005209 } else {
5210 copyfd(redir->ndup.dupfd, fd | COPYFD_EXACT);
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005211 }
Denis Vlasenko5a867312008-07-24 19:46:38 +00005212 } else if (fd != newfd) { /* move newfd to fd */
5213 copyfd(newfd, fd | COPYFD_EXACT);
Denis Vlasenko559691a2008-10-05 18:39:31 +00005214#if ENABLE_ASH_BASH_COMPAT
5215 if (!(redir->nfile.type == NTO2 && fd == 2))
5216#endif
5217 close(newfd);
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005218 }
Denis Vlasenko559691a2008-10-05 18:39:31 +00005219#if ENABLE_ASH_BASH_COMPAT
5220 if (redir->nfile.type == NTO2 && fd == 1) {
5221 /* We already redirected it to fd 1, now copy it to 2 */
5222 newfd = 1;
5223 fd = 2;
5224 goto redirect_more;
5225 }
5226#endif
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00005227 } while ((redir = redir->nfile.next) != NULL);
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005228
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005229 INT_ON;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005230 if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
5231 preverrout_fd = copied_fd2;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005232}
5233
5234/*
5235 * Undo the effects of the last redirection.
5236 */
5237static void
Denis Vlasenko34c73c42008-08-16 11:48:02 +00005238popredir(int drop, int restore)
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005239{
5240 struct redirtab *rp;
5241 int i;
5242
Denis Vlasenko01631112007-12-16 17:20:38 +00005243 if (--g_nullredirs >= 0)
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005244 return;
5245 INT_OFF;
5246 rp = redirlist;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005247 for (i = 0; i < rp->pair_count; i++) {
5248 int fd = rp->two_fd[i].orig;
Denis Vlasenko22f74142008-07-24 22:34:43 +00005249 int copy = rp->two_fd[i].copy;
5250 if (copy == CLOSED) {
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005251 if (!drop)
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005252 close(fd);
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005253 continue;
5254 }
Denis Vlasenko22f74142008-07-24 22:34:43 +00005255 if (copy != EMPTY) {
Denis Vlasenko34c73c42008-08-16 11:48:02 +00005256 if (!drop || (restore && (copy & COPYFD_RESTORE))) {
Denis Vlasenko22f74142008-07-24 22:34:43 +00005257 copy &= ~COPYFD_RESTORE;
Denis Vlasenko5a867312008-07-24 19:46:38 +00005258 /*close(fd);*/
Denis Vlasenko22f74142008-07-24 22:34:43 +00005259 copyfd(copy, fd | COPYFD_EXACT);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005260 }
Denis Vlasenkob9e70dd2009-03-20 01:24:08 +00005261 close(copy & ~COPYFD_RESTORE);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005262 }
5263 }
5264 redirlist = rp->next;
Denis Vlasenko01631112007-12-16 17:20:38 +00005265 g_nullredirs = rp->nullredirs;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005266 free(rp);
5267 INT_ON;
5268}
5269
5270/*
5271 * Undo all redirections. Called on error or interrupt.
5272 */
5273
5274/*
5275 * Discard all saved file descriptors.
5276 */
5277static void
5278clearredir(int drop)
5279{
5280 for (;;) {
Denis Vlasenko01631112007-12-16 17:20:38 +00005281 g_nullredirs = 0;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005282 if (!redirlist)
5283 break;
Denis Vlasenko34c73c42008-08-16 11:48:02 +00005284 popredir(drop, /*restore:*/ 0);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005285 }
5286}
5287
5288static int
5289redirectsafe(union node *redir, int flags)
5290{
5291 int err;
5292 volatile int saveint;
5293 struct jmploc *volatile savehandler = exception_handler;
5294 struct jmploc jmploc;
5295
5296 SAVE_INT(saveint);
Denis Vlasenko5a867312008-07-24 19:46:38 +00005297 /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
5298 err = setjmp(jmploc.loc); // huh?? was = setjmp(jmploc.loc) * 2;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005299 if (!err) {
5300 exception_handler = &jmploc;
5301 redirect(redir, flags);
5302 }
5303 exception_handler = savehandler;
Denis Vlasenko7f88e342009-03-19 03:36:18 +00005304 if (err && exception_type != EXERROR)
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005305 longjmp(exception_handler->loc, 1);
5306 RESTORE_INT(saveint);
5307 return err;
5308}
5309
5310
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005311/* ============ Routines to expand arguments to commands
5312 *
5313 * We have to deal with backquotes, shell variables, and file metacharacters.
5314 */
5315
Mike Frysinger98c52642009-04-02 10:02:37 +00005316#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00005317static arith_t
5318ash_arith(const char *s)
5319{
5320 arith_eval_hooks_t math_hooks;
5321 arith_t result;
5322 int errcode = 0;
5323
5324 math_hooks.lookupvar = lookupvar;
Denys Vlasenko03dad222010-01-12 23:29:57 +01005325 math_hooks.setvar = setvar2;
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00005326 math_hooks.endofname = endofname;
5327
5328 INT_OFF;
5329 result = arith(s, &errcode, &math_hooks);
5330 if (errcode < 0) {
5331 if (errcode == -3)
5332 ash_msg_and_raise_error("exponent less than 0");
5333 if (errcode == -2)
5334 ash_msg_and_raise_error("divide by zero");
5335 if (errcode == -5)
5336 ash_msg_and_raise_error("expression recursion loop detected");
5337 raise_error_syntax(s);
5338 }
5339 INT_ON;
5340
5341 return result;
5342}
Denis Vlasenko448d30e2008-06-27 00:24:11 +00005343#endif
5344
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005345/*
5346 * expandarg flags
5347 */
5348#define EXP_FULL 0x1 /* perform word splitting & file globbing */
5349#define EXP_TILDE 0x2 /* do normal tilde expansion */
5350#define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
5351#define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
5352#define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
5353#define EXP_RECORD 0x20 /* need to record arguments for ifs breakup */
5354#define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
5355#define EXP_WORD 0x80 /* expand word in parameter expansion */
5356#define EXP_QWORD 0x100 /* expand word in quoted parameter expansion */
5357/*
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005358 * rmescape() flags
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005359 */
5360#define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
5361#define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
5362#define RMESCAPE_QUOTED 0x4 /* Remove CTLESC unless in quotes */
5363#define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
5364#define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
5365
5366/*
5367 * Structure specifying which parts of the string should be searched
5368 * for IFS characters.
5369 */
5370struct ifsregion {
5371 struct ifsregion *next; /* next region in list */
5372 int begoff; /* offset of start of region */
5373 int endoff; /* offset of end of region */
5374 int nulonly; /* search for nul bytes only */
5375};
5376
5377struct arglist {
5378 struct strlist *list;
5379 struct strlist **lastp;
5380};
5381
5382/* output of current string */
5383static char *expdest;
5384/* list of back quote expressions */
5385static struct nodelist *argbackq;
5386/* first struct in list of ifs regions */
5387static struct ifsregion ifsfirst;
5388/* last struct in list */
5389static struct ifsregion *ifslastp;
5390/* holds expanded arg list */
5391static struct arglist exparg;
5392
5393/*
5394 * Our own itoa().
5395 */
5396static int
5397cvtnum(arith_t num)
5398{
5399 int len;
5400
5401 expdest = makestrspace(32, expdest);
Mike Frysinger98c52642009-04-02 10:02:37 +00005402 len = fmtstr(expdest, 32, arith_t_fmt, num);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005403 STADJUST(len, expdest);
5404 return len;
5405}
5406
5407static size_t
5408esclen(const char *start, const char *p)
5409{
5410 size_t esc = 0;
5411
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005412 while (p > start && (unsigned char)*--p == CTLESC) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005413 esc++;
5414 }
5415 return esc;
5416}
5417
5418/*
5419 * Remove any CTLESC characters from a string.
5420 */
5421static char *
Denys Vlasenkob6c84342009-08-29 20:23:20 +02005422rmescapes(char *str, int flag)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005423{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00005424 static const char qchars[] ALIGN1 = { CTLESC, CTLQUOTEMARK, '\0' };
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00005425
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005426 char *p, *q, *r;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005427 unsigned inquotes;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005428 unsigned protect_against_glob;
5429 unsigned globbing;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005430
5431 p = strpbrk(str, qchars);
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005432 if (!p)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005433 return str;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005434
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005435 q = p;
5436 r = str;
5437 if (flag & RMESCAPE_ALLOC) {
5438 size_t len = p - str;
5439 size_t fulllen = len + strlen(p) + 1;
5440
5441 if (flag & RMESCAPE_GROW) {
Colin Watson3963d942010-04-26 14:21:27 +02005442 int strloc = str - (char *)stackblock();
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005443 r = makestrspace(fulllen, expdest);
Colin Watson3963d942010-04-26 14:21:27 +02005444 /* p and str may be invalidated by makestrspace */
5445 str = (char *)stackblock() + strloc;
5446 p = str + len;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005447 } else if (flag & RMESCAPE_HEAP) {
5448 r = ckmalloc(fulllen);
5449 } else {
5450 r = stalloc(fulllen);
5451 }
5452 q = r;
5453 if (len > 0) {
Denis Vlasenko29eb3592008-05-18 14:06:08 +00005454 q = (char *)memcpy(q, str, len) + len;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005455 }
5456 }
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005457
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005458 inquotes = (flag & RMESCAPE_QUOTED) ^ RMESCAPE_QUOTED;
5459 globbing = flag & RMESCAPE_GLOB;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005460 protect_against_glob = globbing;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005461 while (*p) {
Denys Vlasenkocd716832009-11-28 22:14:02 +01005462 if ((unsigned char)*p == CTLQUOTEMARK) {
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005463// TODO: if no RMESCAPE_QUOTED in flags, inquotes never becomes 0
5464// (alternates between RMESCAPE_QUOTED and ~RMESCAPE_QUOTED). Is it ok?
5465// Note: both inquotes and protect_against_glob only affect whether
5466// CTLESC,<ch> gets converted to <ch> or to \<ch>
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005467 inquotes = ~inquotes;
5468 p++;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005469 protect_against_glob = globbing;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005470 continue;
5471 }
5472 if (*p == '\\') {
5473 /* naked back slash */
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005474 protect_against_glob = 0;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005475 goto copy;
5476 }
Denys Vlasenkocd716832009-11-28 22:14:02 +01005477 if ((unsigned char)*p == CTLESC) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005478 p++;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005479 if (protect_against_glob && inquotes && *p != '/') {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005480 *q++ = '\\';
5481 }
5482 }
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005483 protect_against_glob = globbing;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005484 copy:
5485 *q++ = *p++;
5486 }
5487 *q = '\0';
5488 if (flag & RMESCAPE_GROW) {
5489 expdest = r;
5490 STADJUST(q - r + 1, expdest);
5491 }
5492 return r;
5493}
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005494#define pmatch(a, b) !fnmatch((a), (b), 0)
5495
5496/*
5497 * Prepare a pattern for a expmeta (internal glob(3)) call.
5498 *
5499 * Returns an stalloced string.
5500 */
5501static char *
5502preglob(const char *pattern, int quoted, int flag)
5503{
5504 flag |= RMESCAPE_GLOB;
5505 if (quoted) {
5506 flag |= RMESCAPE_QUOTED;
5507 }
Denys Vlasenkob6c84342009-08-29 20:23:20 +02005508 return rmescapes((char *)pattern, flag);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005509}
5510
5511/*
5512 * Put a string on the stack.
5513 */
5514static void
5515memtodest(const char *p, size_t len, int syntax, int quotes)
5516{
5517 char *q = expdest;
5518
Denys Vlasenkob6c84342009-08-29 20:23:20 +02005519 q = makestrspace(quotes ? len * 2 : len, q);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005520
5521 while (len--) {
Denys Vlasenkocd716832009-11-28 22:14:02 +01005522 unsigned char c = *p++;
5523 if (c == '\0')
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005524 continue;
Denys Vlasenkob6c84342009-08-29 20:23:20 +02005525 if (quotes) {
5526 int n = SIT(c, syntax);
5527 if (n == CCTL || n == CBACK)
5528 USTPUTC(CTLESC, q);
5529 }
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005530 USTPUTC(c, q);
5531 }
5532
5533 expdest = q;
5534}
5535
5536static void
5537strtodest(const char *p, int syntax, int quotes)
5538{
5539 memtodest(p, strlen(p), syntax, quotes);
5540}
5541
5542/*
5543 * Record the fact that we have to scan this region of the
5544 * string for IFS characters.
5545 */
5546static void
5547recordregion(int start, int end, int nulonly)
5548{
5549 struct ifsregion *ifsp;
5550
5551 if (ifslastp == NULL) {
5552 ifsp = &ifsfirst;
5553 } else {
5554 INT_OFF;
Denis Vlasenko597906c2008-02-20 16:38:54 +00005555 ifsp = ckzalloc(sizeof(*ifsp));
5556 /*ifsp->next = NULL; - ckzalloc did it */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005557 ifslastp->next = ifsp;
5558 INT_ON;
5559 }
5560 ifslastp = ifsp;
5561 ifslastp->begoff = start;
5562 ifslastp->endoff = end;
5563 ifslastp->nulonly = nulonly;
5564}
5565
5566static void
5567removerecordregions(int endoff)
5568{
5569 if (ifslastp == NULL)
5570 return;
5571
5572 if (ifsfirst.endoff > endoff) {
5573 while (ifsfirst.next != NULL) {
5574 struct ifsregion *ifsp;
5575 INT_OFF;
5576 ifsp = ifsfirst.next->next;
5577 free(ifsfirst.next);
5578 ifsfirst.next = ifsp;
5579 INT_ON;
5580 }
5581 if (ifsfirst.begoff > endoff)
5582 ifslastp = NULL;
5583 else {
5584 ifslastp = &ifsfirst;
5585 ifsfirst.endoff = endoff;
5586 }
5587 return;
5588 }
5589
5590 ifslastp = &ifsfirst;
5591 while (ifslastp->next && ifslastp->next->begoff < endoff)
5592 ifslastp=ifslastp->next;
5593 while (ifslastp->next != NULL) {
5594 struct ifsregion *ifsp;
5595 INT_OFF;
5596 ifsp = ifslastp->next->next;
5597 free(ifslastp->next);
5598 ifslastp->next = ifsp;
5599 INT_ON;
5600 }
5601 if (ifslastp->endoff > endoff)
5602 ifslastp->endoff = endoff;
5603}
5604
5605static char *
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005606exptilde(char *startp, char *p, int flags)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005607{
Denys Vlasenkocd716832009-11-28 22:14:02 +01005608 unsigned char c;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005609 char *name;
5610 struct passwd *pw;
5611 const char *home;
Denys Vlasenko1166d7b2009-09-16 16:20:31 +02005612 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005613 int startloc;
5614
5615 name = p + 1;
5616
5617 while ((c = *++p) != '\0') {
5618 switch (c) {
5619 case CTLESC:
5620 return startp;
5621 case CTLQUOTEMARK:
5622 return startp;
5623 case ':':
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005624 if (flags & EXP_VARTILDE)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005625 goto done;
5626 break;
5627 case '/':
5628 case CTLENDVAR:
5629 goto done;
5630 }
5631 }
5632 done:
5633 *p = '\0';
5634 if (*name == '\0') {
Denys Vlasenkoea8b2522010-06-02 12:57:26 +02005635 home = lookupvar("HOME");
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005636 } else {
5637 pw = getpwnam(name);
5638 if (pw == NULL)
5639 goto lose;
5640 home = pw->pw_dir;
5641 }
5642 if (!home || !*home)
5643 goto lose;
5644 *p = c;
5645 startloc = expdest - (char *)stackblock();
5646 strtodest(home, SQSYNTAX, quotes);
5647 recordregion(startloc, expdest - (char *)stackblock(), 0);
5648 return p;
5649 lose:
5650 *p = c;
5651 return startp;
5652}
5653
5654/*
5655 * Execute a command inside back quotes. If it's a builtin command, we
5656 * want to save its output in a block obtained from malloc. Otherwise
5657 * we fork off a subprocess and get the output of the command via a pipe.
5658 * Should be called with interrupts off.
5659 */
5660struct backcmd { /* result of evalbackcmd */
5661 int fd; /* file descriptor to read from */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005662 int nleft; /* number of chars in buffer */
Denis Vlasenkob07a4962008-06-22 13:16:23 +00005663 char *buf; /* buffer */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005664 struct job *jp; /* job structure for command */
5665};
5666
5667/* These forward decls are needed to use "eval" code for backticks handling: */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00005668static uint8_t back_exitstatus; /* exit status of backquoted command */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005669#define EV_EXIT 01 /* exit after evaluating tree */
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02005670static void evaltree(union node *, int);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005671
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02005672static void FAST_FUNC
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005673evalbackcmd(union node *n, struct backcmd *result)
5674{
5675 int saveherefd;
5676
5677 result->fd = -1;
5678 result->buf = NULL;
5679 result->nleft = 0;
5680 result->jp = NULL;
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00005681 if (n == NULL)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005682 goto out;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005683
5684 saveherefd = herefd;
5685 herefd = -1;
5686
5687 {
5688 int pip[2];
5689 struct job *jp;
5690
5691 if (pipe(pip) < 0)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00005692 ash_msg_and_raise_error("pipe call failed");
Denis Vlasenko68404f12008-03-17 09:00:54 +00005693 jp = makejob(/*n,*/ 1);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005694 if (forkshell(jp, n, FORK_NOJOB) == 0) {
5695 FORCE_INT_ON;
5696 close(pip[0]);
5697 if (pip[1] != 1) {
Denis Vlasenko5a867312008-07-24 19:46:38 +00005698 /*close(1);*/
5699 copyfd(pip[1], 1 | COPYFD_EXACT);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005700 close(pip[1]);
5701 }
5702 eflag = 0;
5703 evaltree(n, EV_EXIT); /* actually evaltreenr... */
5704 /* NOTREACHED */
5705 }
5706 close(pip[1]);
5707 result->fd = pip[0];
5708 result->jp = jp;
5709 }
5710 herefd = saveherefd;
5711 out:
5712 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
5713 result->fd, result->buf, result->nleft, result->jp));
5714}
5715
5716/*
5717 * Expand stuff in backwards quotes.
5718 */
5719static void
5720expbackq(union node *cmd, int quoted, int quotes)
5721{
5722 struct backcmd in;
5723 int i;
5724 char buf[128];
5725 char *p;
5726 char *dest;
5727 int startloc;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00005728 int syntax = quoted ? DQSYNTAX : BASESYNTAX;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005729 struct stackmark smark;
5730
5731 INT_OFF;
5732 setstackmark(&smark);
5733 dest = expdest;
5734 startloc = dest - (char *)stackblock();
5735 grabstackstr(dest);
5736 evalbackcmd(cmd, &in);
5737 popstackmark(&smark);
5738
5739 p = in.buf;
5740 i = in.nleft;
5741 if (i == 0)
5742 goto read;
5743 for (;;) {
5744 memtodest(p, i, syntax, quotes);
5745 read:
5746 if (in.fd < 0)
5747 break;
Denis Vlasenkoe376d452008-02-20 22:23:24 +00005748 i = nonblock_safe_read(in.fd, buf, sizeof(buf));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005749 TRACE(("expbackq: read returns %d\n", i));
5750 if (i <= 0)
5751 break;
5752 p = buf;
5753 }
5754
Denis Vlasenko60818682007-09-28 22:07:23 +00005755 free(in.buf);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005756 if (in.fd >= 0) {
5757 close(in.fd);
5758 back_exitstatus = waitforjob(in.jp);
5759 }
5760 INT_ON;
5761
5762 /* Eat all trailing newlines */
5763 dest = expdest;
5764 for (; dest > (char *)stackblock() && dest[-1] == '\n';)
5765 STUNPUTC(dest);
5766 expdest = dest;
5767
5768 if (quoted == 0)
5769 recordregion(startloc, dest - (char *)stackblock(), 0);
5770 TRACE(("evalbackq: size=%d: \"%.*s\"\n",
5771 (dest - (char *)stackblock()) - startloc,
5772 (dest - (char *)stackblock()) - startloc,
5773 stackblock() + startloc));
5774}
5775
Mike Frysinger98c52642009-04-02 10:02:37 +00005776#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005777/*
5778 * Expand arithmetic expression. Backup to start of expression,
5779 * evaluate, place result in (backed up) result, adjust string position.
5780 */
5781static void
5782expari(int quotes)
5783{
5784 char *p, *start;
5785 int begoff;
5786 int flag;
5787 int len;
5788
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00005789 /* ifsfree(); */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005790
5791 /*
5792 * This routine is slightly over-complicated for
5793 * efficiency. Next we scan backwards looking for the
5794 * start of arithmetic.
5795 */
5796 start = stackblock();
5797 p = expdest - 1;
5798 *p = '\0';
5799 p--;
5800 do {
5801 int esc;
5802
Denys Vlasenkocd716832009-11-28 22:14:02 +01005803 while ((unsigned char)*p != CTLARI) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005804 p--;
5805#if DEBUG
5806 if (p < start) {
5807 ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
5808 }
5809#endif
5810 }
5811
5812 esc = esclen(start, p);
5813 if (!(esc % 2)) {
5814 break;
5815 }
5816
5817 p -= esc + 1;
5818 } while (1);
5819
5820 begoff = p - start;
5821
5822 removerecordregions(begoff);
5823
5824 flag = p[1];
5825
5826 expdest = p;
5827
5828 if (quotes)
Denys Vlasenkob6c84342009-08-29 20:23:20 +02005829 rmescapes(p + 2, 0);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005830
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00005831 len = cvtnum(ash_arith(p + 2));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005832
5833 if (flag != '"')
5834 recordregion(begoff, begoff + len, 0);
5835}
5836#endif
5837
5838/* argstr needs it */
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005839static char *evalvar(char *p, int flags, struct strlist *var_str_list);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005840
5841/*
5842 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
5843 * characters to allow for further processing. Otherwise treat
5844 * $@ like $* since no splitting will be performed.
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00005845 *
5846 * var_str_list (can be NULL) is a list of "VAR=val" strings which take precedence
5847 * over shell varables. Needed for "A=a B=$A; echo $B" case - we use it
5848 * for correct expansion of "B=$A" word.
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005849 */
5850static void
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005851argstr(char *p, int flags, struct strlist *var_str_list)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005852{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00005853 static const char spclchars[] ALIGN1 = {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005854 '=',
5855 ':',
5856 CTLQUOTEMARK,
5857 CTLENDVAR,
5858 CTLESC,
5859 CTLVAR,
5860 CTLBACKQ,
5861 CTLBACKQ | CTLQUOTE,
Mike Frysinger98c52642009-04-02 10:02:37 +00005862#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005863 CTLENDARI,
5864#endif
Denys Vlasenkocd716832009-11-28 22:14:02 +01005865 '\0'
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005866 };
5867 const char *reject = spclchars;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005868 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR); /* do CTLESC */
5869 int breakall = flags & EXP_WORD;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005870 int inquotes;
5871 size_t length;
5872 int startloc;
5873
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005874 if (!(flags & EXP_VARTILDE)) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005875 reject += 2;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005876 } else if (flags & EXP_VARTILDE2) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005877 reject++;
5878 }
5879 inquotes = 0;
5880 length = 0;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005881 if (flags & EXP_TILDE) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005882 char *q;
5883
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005884 flags &= ~EXP_TILDE;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005885 tilde:
5886 q = p;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005887 if (*q == CTLESC && (flags & EXP_QWORD))
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005888 q++;
5889 if (*q == '~')
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005890 p = exptilde(p, q, flags);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005891 }
5892 start:
5893 startloc = expdest - (char *)stackblock();
5894 for (;;) {
Denys Vlasenkocd716832009-11-28 22:14:02 +01005895 unsigned char c;
5896
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005897 length += strcspn(p + length, reject);
Denys Vlasenkocd716832009-11-28 22:14:02 +01005898 c = p[length];
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005899 if (c) {
5900 if (!(c & 0x80)
Mike Frysinger98c52642009-04-02 10:02:37 +00005901#if ENABLE_SH_MATH_SUPPORT
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005902 || c == CTLENDARI
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005903#endif
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005904 ) {
5905 /* c == '=' || c == ':' || c == CTLENDARI */
5906 length++;
5907 }
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005908 }
5909 if (length > 0) {
5910 int newloc;
5911 expdest = stack_nputstr(p, length, expdest);
5912 newloc = expdest - (char *)stackblock();
5913 if (breakall && !inquotes && newloc > startloc) {
5914 recordregion(startloc, newloc, 0);
5915 }
5916 startloc = newloc;
5917 }
5918 p += length + 1;
5919 length = 0;
5920
5921 switch (c) {
5922 case '\0':
5923 goto breakloop;
5924 case '=':
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005925 if (flags & EXP_VARTILDE2) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005926 p--;
5927 continue;
5928 }
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005929 flags |= EXP_VARTILDE2;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005930 reject++;
5931 /* fall through */
5932 case ':':
5933 /*
5934 * sort of a hack - expand tildes in variable
5935 * assignments (after the first '=' and after ':'s).
5936 */
5937 if (*--p == '~') {
5938 goto tilde;
5939 }
5940 continue;
5941 }
5942
5943 switch (c) {
5944 case CTLENDVAR: /* ??? */
5945 goto breakloop;
5946 case CTLQUOTEMARK:
5947 /* "$@" syntax adherence hack */
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005948 if (!inquotes
5949 && memcmp(p, dolatstr, 4) == 0
5950 && ( p[4] == CTLQUOTEMARK
5951 || (p[4] == CTLENDVAR && p[5] == CTLQUOTEMARK)
5952 )
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005953 ) {
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005954 p = evalvar(p + 1, flags, /* var_str_list: */ NULL) + 1;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005955 goto start;
5956 }
5957 inquotes = !inquotes;
5958 addquote:
5959 if (quotes) {
5960 p--;
5961 length++;
5962 startloc++;
5963 }
5964 break;
5965 case CTLESC:
5966 startloc++;
5967 length++;
5968 goto addquote;
5969 case CTLVAR:
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005970 p = evalvar(p, flags, var_str_list);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005971 goto start;
5972 case CTLBACKQ:
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005973 c = '\0';
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005974 case CTLBACKQ|CTLQUOTE:
5975 expbackq(argbackq->n, c, quotes);
5976 argbackq = argbackq->next;
5977 goto start;
Mike Frysinger98c52642009-04-02 10:02:37 +00005978#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005979 case CTLENDARI:
5980 p--;
5981 expari(quotes);
5982 goto start;
5983#endif
5984 }
5985 }
5986 breakloop:
5987 ;
5988}
5989
5990static char *
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00005991scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM, char *str, int quotes,
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005992 int zero)
5993{
Denis Vlasenkoc7131c32008-04-14 01:59:53 +00005994// This commented out code was added by James Simmons <jsimmons@infradead.org>
5995// as part of a larger change when he added support for ${var/a/b}.
5996// However, it broke # and % operators:
5997//
5998//var=ababcdcd
5999// ok bad
6000//echo ${var#ab} abcdcd abcdcd
6001//echo ${var##ab} abcdcd abcdcd
6002//echo ${var#a*b} abcdcd ababcdcd (!)
6003//echo ${var##a*b} cdcd cdcd
6004//echo ${var#?} babcdcd ababcdcd (!)
6005//echo ${var##?} babcdcd babcdcd
6006//echo ${var#*} ababcdcd babcdcd (!)
6007//echo ${var##*}
6008//echo ${var%cd} ababcd ababcd
6009//echo ${var%%cd} ababcd abab (!)
6010//echo ${var%c*d} ababcd ababcd
6011//echo ${var%%c*d} abab ababcdcd (!)
6012//echo ${var%?} ababcdc ababcdc
6013//echo ${var%%?} ababcdc ababcdcd (!)
6014//echo ${var%*} ababcdcd ababcdcd
6015//echo ${var%%*}
6016//
6017// Commenting it back out helped. Remove it completely if it really
6018// is not needed.
6019
6020 char *loc, *loc2; //, *full;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006021 char c;
6022
6023 loc = startp;
6024 loc2 = rmesc;
6025 do {
Denis Vlasenkoc7131c32008-04-14 01:59:53 +00006026 int match; // = strlen(str);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006027 const char *s = loc2;
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006028
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006029 c = *loc2;
6030 if (zero) {
6031 *loc2 = '\0';
6032 s = rmesc;
6033 }
Denis Vlasenkoc7131c32008-04-14 01:59:53 +00006034 match = pmatch(str, s); // this line was deleted
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006035
Denis Vlasenkoc7131c32008-04-14 01:59:53 +00006036// // chop off end if its '*'
6037// full = strrchr(str, '*');
6038// if (full && full != str)
6039// match--;
6040//
6041// // If str starts with '*' replace with s.
6042// if ((*str == '*') && strlen(s) >= match) {
6043// full = xstrdup(s);
6044// strncpy(full+strlen(s)-match+1, str+1, match-1);
6045// } else
6046// full = xstrndup(str, match);
6047// match = strncmp(s, full, strlen(full));
6048// free(full);
6049//
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006050 *loc2 = c;
Denis Vlasenkoc7131c32008-04-14 01:59:53 +00006051 if (match) // if (!match)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006052 return loc;
Denys Vlasenkocd716832009-11-28 22:14:02 +01006053 if (quotes && (unsigned char)*loc == CTLESC)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006054 loc++;
6055 loc++;
6056 loc2++;
6057 } while (c);
6058 return 0;
6059}
6060
6061static char *
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006062scanright(char *startp, char *rmesc, char *rmescend, char *pattern, int quotes, int match_at_start)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006063{
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006064#if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6065 int try2optimize = match_at_start;
6066#endif
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006067 int esc = 0;
6068 char *loc;
6069 char *loc2;
6070
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006071 /* If we called by "${v/pattern/repl}" or "${v//pattern/repl}":
6072 * startp="escaped_value_of_v" rmesc="raw_value_of_v"
6073 * rmescend=""(ptr to NUL in rmesc) pattern="pattern" quotes=match_at_start=1
6074 * Logic:
6075 * loc starts at NUL at the end of startp, loc2 starts at the end of rmesc,
6076 * and on each iteration they go back two/one char until they reach the beginning.
6077 * We try to find a match in "raw_value_of_v", "raw_value_of_", "raw_value_of" etc.
6078 */
6079 /* TODO: document in what other circumstances we are called. */
6080
6081 for (loc = pattern - 1, loc2 = rmescend; loc >= startp; loc2--) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006082 int match;
6083 char c = *loc2;
6084 const char *s = loc2;
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006085 if (match_at_start) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006086 *loc2 = '\0';
6087 s = rmesc;
6088 }
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006089 match = pmatch(pattern, s);
6090 //bb_error_msg("pmatch(pattern:'%s',s:'%s'):%d", pattern, s, match);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006091 *loc2 = c;
6092 if (match)
6093 return loc;
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006094#if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6095 if (try2optimize) {
6096 /* Maybe we can optimize this:
6097 * if pattern ends with unescaped *, we can avoid checking
6098 * shorter strings: if "foo*" doesnt match "raw_value_of_v",
6099 * it wont match truncated "raw_value_of_" strings too.
6100 */
6101 unsigned plen = strlen(pattern);
6102 /* Does it end with "*"? */
6103 if (plen != 0 && pattern[--plen] == '*') {
6104 /* "xxxx*" is not escaped */
6105 /* "xxx\*" is escaped */
6106 /* "xx\\*" is not escaped */
6107 /* "x\\\*" is escaped */
6108 int slashes = 0;
6109 while (plen != 0 && pattern[--plen] == '\\')
6110 slashes++;
6111 if (!(slashes & 1))
6112 break; /* ends with unescaped "*" */
6113 }
6114 try2optimize = 0;
6115 }
6116#endif
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006117 loc--;
6118 if (quotes) {
6119 if (--esc < 0) {
6120 esc = esclen(startp, loc);
6121 }
6122 if (esc % 2) {
6123 esc--;
6124 loc--;
6125 }
6126 }
6127 }
6128 return 0;
6129}
6130
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00006131static void varunset(const char *, const char *, const char *, int) NORETURN;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006132static void
6133varunset(const char *end, const char *var, const char *umsg, int varflags)
6134{
6135 const char *msg;
6136 const char *tail;
6137
6138 tail = nullstr;
6139 msg = "parameter not set";
6140 if (umsg) {
Denys Vlasenkocd716832009-11-28 22:14:02 +01006141 if ((unsigned char)*end == CTLENDVAR) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006142 if (varflags & VSNUL)
6143 tail = " or null";
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00006144 } else {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006145 msg = umsg;
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00006146 }
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006147 }
6148 ash_msg_and_raise_error("%.*s: %s%s", end - var - 1, var, msg, tail);
6149}
6150
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006151#if ENABLE_ASH_BASH_COMPAT
6152static char *
6153parse_sub_pattern(char *arg, int inquotes)
6154{
6155 char *idx, *repl = NULL;
6156 unsigned char c;
6157
Denis Vlasenko2659c632008-06-14 06:04:59 +00006158 idx = arg;
6159 while (1) {
6160 c = *arg;
6161 if (!c)
6162 break;
6163 if (c == '/') {
6164 /* Only the first '/' seen is our separator */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006165 if (!repl) {
Denis Vlasenko2659c632008-06-14 06:04:59 +00006166 repl = idx + 1;
6167 c = '\0';
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006168 }
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006169 }
Denis Vlasenko2659c632008-06-14 06:04:59 +00006170 *idx++ = c;
6171 if (!inquotes && c == '\\' && arg[1] == '\\')
6172 arg++; /* skip both \\, not just first one */
6173 arg++;
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006174 }
Denis Vlasenko29038c02008-06-14 06:14:02 +00006175 *idx = c; /* NUL */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006176
6177 return repl;
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006178}
6179#endif /* ENABLE_ASH_BASH_COMPAT */
6180
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006181static const char *
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006182subevalvar(char *p, char *str, int strloc, int subtype,
6183 int startloc, int varflags, int quotes, struct strlist *var_str_list)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006184{
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006185 struct nodelist *saveargbackq = argbackq;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006186 char *startp;
6187 char *loc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006188 char *rmesc, *rmescend;
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00006189 IF_ASH_BASH_COMPAT(char *repl = NULL;)
6190 IF_ASH_BASH_COMPAT(char null = '\0';)
6191 IF_ASH_BASH_COMPAT(int pos, len, orig_len;)
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006192 int saveherefd = herefd;
6193 int amount, workloc, resetloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006194 int zero;
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006195 char *(*scan)(char*, char*, char*, char*, int, int);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006196
6197 herefd = -1;
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006198 argstr(p, (subtype != VSASSIGN && subtype != VSQUESTION) ? EXP_CASE : 0,
6199 var_str_list);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006200 STPUTC('\0', expdest);
6201 herefd = saveherefd;
6202 argbackq = saveargbackq;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00006203 startp = (char *)stackblock() + startloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006204
6205 switch (subtype) {
6206 case VSASSIGN:
6207 setvar(str, startp, 0);
6208 amount = startp - expdest;
6209 STADJUST(amount, expdest);
6210 return startp;
6211
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006212#if ENABLE_ASH_BASH_COMPAT
6213 case VSSUBSTR:
6214 loc = str = stackblock() + strloc;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006215 /* Read POS in ${var:POS:LEN} */
6216 pos = atoi(loc); /* number(loc) errors out on "1:4" */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006217 len = str - startp - 1;
6218
6219 /* *loc != '\0', guaranteed by parser */
6220 if (quotes) {
6221 char *ptr;
6222
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006223 /* Adjust the length by the number of escapes */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006224 for (ptr = startp; ptr < (str - 1); ptr++) {
Denys Vlasenkocd716832009-11-28 22:14:02 +01006225 if ((unsigned char)*ptr == CTLESC) {
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006226 len--;
6227 ptr++;
6228 }
6229 }
6230 }
6231 orig_len = len;
6232
6233 if (*loc++ == ':') {
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006234 /* ${var::LEN} */
6235 len = number(loc);
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006236 } else {
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006237 /* Skip POS in ${var:POS:LEN} */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006238 len = orig_len;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006239 while (*loc && *loc != ':') {
6240 /* TODO?
6241 * bash complains on: var=qwe; echo ${var:1a:123}
6242 if (!isdigit(*loc))
6243 ash_msg_and_raise_error(msg_illnum, str);
6244 */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006245 loc++;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006246 }
6247 if (*loc++ == ':') {
6248 len = number(loc);
6249 }
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006250 }
6251 if (pos >= orig_len) {
6252 pos = 0;
6253 len = 0;
6254 }
6255 if (len > (orig_len - pos))
6256 len = orig_len - pos;
6257
6258 for (str = startp; pos; str++, pos--) {
Denys Vlasenkocd716832009-11-28 22:14:02 +01006259 if (quotes && (unsigned char)*str == CTLESC)
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006260 str++;
6261 }
6262 for (loc = startp; len; len--) {
Denys Vlasenkocd716832009-11-28 22:14:02 +01006263 if (quotes && (unsigned char)*str == CTLESC)
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006264 *loc++ = *str++;
6265 *loc++ = *str++;
6266 }
6267 *loc = '\0';
6268 amount = loc - expdest;
6269 STADJUST(amount, expdest);
6270 return loc;
6271#endif
6272
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006273 case VSQUESTION:
6274 varunset(p, str, startp, varflags);
6275 /* NOTREACHED */
6276 }
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006277 resetloc = expdest - (char *)stackblock();
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006278
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006279 /* We'll comeback here if we grow the stack while handling
6280 * a VSREPLACE or VSREPLACEALL, since our pointers into the
6281 * stack will need rebasing, and we'll need to remove our work
6282 * areas each time
6283 */
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00006284 IF_ASH_BASH_COMPAT(restart:)
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006285
6286 amount = expdest - ((char *)stackblock() + resetloc);
6287 STADJUST(-amount, expdest);
Denis Vlasenko29eb3592008-05-18 14:06:08 +00006288 startp = (char *)stackblock() + startloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006289
6290 rmesc = startp;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00006291 rmescend = (char *)stackblock() + strloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006292 if (quotes) {
Denys Vlasenkob6c84342009-08-29 20:23:20 +02006293 rmesc = rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006294 if (rmesc != startp) {
6295 rmescend = expdest;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00006296 startp = (char *)stackblock() + startloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006297 }
6298 }
6299 rmescend--;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00006300 str = (char *)stackblock() + strloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006301 preglob(str, varflags & VSQUOTE, 0);
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006302 workloc = expdest - (char *)stackblock();
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006303
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006304#if ENABLE_ASH_BASH_COMPAT
6305 if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006306 char *idx, *end;
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006307
Denis Vlasenkod6855d12008-09-27 14:03:25 +00006308 if (!repl) {
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006309 repl = parse_sub_pattern(str, varflags & VSQUOTE);
6310 if (!repl)
6311 repl = &null;
6312 }
6313
6314 /* If there's no pattern to match, return the expansion unmolested */
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006315 if (str[0] == '\0')
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006316 return 0;
6317
6318 len = 0;
6319 idx = startp;
6320 end = str - 1;
6321 while (idx < end) {
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006322 try_to_match:
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006323 loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
6324 if (!loc) {
6325 /* No match, advance */
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006326 char *restart_detect = stackblock();
6327 skip_matching:
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006328 STPUTC(*idx, expdest);
Denys Vlasenkocd716832009-11-28 22:14:02 +01006329 if (quotes && (unsigned char)*idx == CTLESC) {
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006330 idx++;
6331 len++;
6332 STPUTC(*idx, expdest);
6333 }
6334 if (stackblock() != restart_detect)
6335 goto restart;
6336 idx++;
6337 len++;
6338 rmesc++;
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006339 /* continue; - prone to quadratic behavior, smarter code: */
6340 if (idx >= end)
6341 break;
6342 if (str[0] == '*') {
6343 /* Pattern is "*foo". If "*foo" does not match "long_string",
6344 * it would never match "ong_string" etc, no point in trying.
6345 */
6346 goto skip_matching;
6347 }
6348 goto try_to_match;
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006349 }
6350
6351 if (subtype == VSREPLACEALL) {
6352 while (idx < loc) {
Denys Vlasenkocd716832009-11-28 22:14:02 +01006353 if (quotes && (unsigned char)*idx == CTLESC)
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006354 idx++;
6355 idx++;
6356 rmesc++;
6357 }
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00006358 } else {
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006359 idx = loc;
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00006360 }
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006361
6362 for (loc = repl; *loc; loc++) {
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006363 char *restart_detect = stackblock();
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006364 STPUTC(*loc, expdest);
6365 if (stackblock() != restart_detect)
6366 goto restart;
6367 len++;
6368 }
6369
6370 if (subtype == VSREPLACE) {
6371 while (*idx) {
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006372 char *restart_detect = stackblock();
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006373 STPUTC(*idx, expdest);
6374 if (stackblock() != restart_detect)
6375 goto restart;
6376 len++;
6377 idx++;
6378 }
6379 break;
6380 }
6381 }
6382
6383 /* We've put the replaced text into a buffer at workloc, now
6384 * move it to the right place and adjust the stack.
6385 */
6386 startp = stackblock() + startloc;
6387 STPUTC('\0', expdest);
6388 memmove(startp, stackblock() + workloc, len);
6389 startp[len++] = '\0';
6390 amount = expdest - ((char *)stackblock() + startloc + len - 1);
6391 STADJUST(-amount, expdest);
6392 return startp;
6393 }
6394#endif /* ENABLE_ASH_BASH_COMPAT */
6395
6396 subtype -= VSTRIMRIGHT;
6397#if DEBUG
6398 if (subtype < 0 || subtype > 7)
6399 abort();
6400#endif
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006401 /* zero = (subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX) */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006402 zero = subtype >> 1;
6403 /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
6404 scan = (subtype & 1) ^ zero ? scanleft : scanright;
6405
6406 loc = scan(startp, rmesc, rmescend, str, quotes, zero);
6407 if (loc) {
6408 if (zero) {
6409 memmove(startp, loc, str - loc);
6410 loc = startp + (str - loc) - 1;
6411 }
6412 *loc = '\0';
6413 amount = loc - expdest;
6414 STADJUST(amount, expdest);
6415 }
6416 return loc;
6417}
6418
6419/*
6420 * Add the value of a specialized variable to the stack string.
Denys Vlasenko4d8873f2009-10-04 03:14:41 +02006421 * name parameter (examples):
6422 * ash -c 'echo $1' name:'1='
6423 * ash -c 'echo $qwe' name:'qwe='
6424 * ash -c 'echo $$' name:'$='
6425 * ash -c 'echo ${$}' name:'$='
6426 * ash -c 'echo ${$##q}' name:'$=q'
6427 * ash -c 'echo ${#$}' name:'$='
6428 * note: examples with bad shell syntax:
6429 * ash -c 'echo ${#$1}' name:'$=1'
6430 * ash -c 'echo ${#1#}' name:'1=#'
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006431 */
Denys Vlasenkoadf922e2009-10-08 14:35:37 +02006432static NOINLINE ssize_t
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006433varvalue(char *name, int varflags, int flags, struct strlist *var_str_list)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006434{
Mike Frysinger98c52642009-04-02 10:02:37 +00006435 const char *p;
Denys Vlasenko8eda4a92009-11-30 12:16:17 +01006436 int num;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006437 int i;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006438 int sepq = 0;
6439 ssize_t len = 0;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006440 int subtype = varflags & VSTYPE;
Denys Vlasenko1166d7b2009-09-16 16:20:31 +02006441 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR);
Denys Vlasenko8eda4a92009-11-30 12:16:17 +01006442 int quoted = varflags & VSQUOTE;
6443 int syntax = quoted ? DQSYNTAX : BASESYNTAX;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006444
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006445 switch (*name) {
6446 case '$':
6447 num = rootpid;
6448 goto numvar;
6449 case '?':
6450 num = exitstatus;
6451 goto numvar;
6452 case '#':
6453 num = shellparam.nparam;
6454 goto numvar;
6455 case '!':
6456 num = backgndpid;
6457 if (num == 0)
6458 return -1;
6459 numvar:
6460 len = cvtnum(num);
Denys Vlasenko4d8873f2009-10-04 03:14:41 +02006461 goto check_1char_name;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006462 case '-':
Mike Frysinger98c52642009-04-02 10:02:37 +00006463 expdest = makestrspace(NOPTS, expdest);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006464 for (i = NOPTS - 1; i >= 0; i--) {
6465 if (optlist[i]) {
Mike Frysinger98c52642009-04-02 10:02:37 +00006466 USTPUTC(optletters(i), expdest);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006467 len++;
6468 }
6469 }
Denys Vlasenko4d8873f2009-10-04 03:14:41 +02006470 check_1char_name:
6471#if 0
6472 /* handles cases similar to ${#$1} */
6473 if (name[2] != '\0')
6474 raise_error_syntax("bad substitution");
6475#endif
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006476 break;
Denys Vlasenko8eda4a92009-11-30 12:16:17 +01006477 case '@': {
6478 char **ap;
6479 int sep;
6480
6481 if (quoted && (flags & EXP_FULL)) {
6482 /* note: this is not meant as PEOF value */
6483 sep = 1 << CHAR_BIT;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006484 goto param;
Denys Vlasenko8eda4a92009-11-30 12:16:17 +01006485 }
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006486 /* fall through */
6487 case '*':
Denys Vlasenkocd716832009-11-28 22:14:02 +01006488 sep = ifsset() ? (unsigned char)(ifsval()[0]) : ' ';
Denys Vlasenko8eda4a92009-11-30 12:16:17 +01006489 i = SIT(sep, syntax);
6490 if (quotes && (i == CCTL || i == CBACK))
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006491 sepq = 1;
6492 param:
6493 ap = shellparam.p;
6494 if (!ap)
6495 return -1;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006496 while ((p = *ap++) != NULL) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006497 size_t partlen;
6498
6499 partlen = strlen(p);
6500 len += partlen;
6501
6502 if (!(subtype == VSPLUS || subtype == VSLENGTH))
6503 memtodest(p, partlen, syntax, quotes);
6504
6505 if (*ap && sep) {
6506 char *q;
6507
6508 len++;
6509 if (subtype == VSPLUS || subtype == VSLENGTH) {
6510 continue;
6511 }
6512 q = expdest;
6513 if (sepq)
6514 STPUTC(CTLESC, q);
Denys Vlasenko8eda4a92009-11-30 12:16:17 +01006515 /* note: may put NUL despite sep != 0
6516 * (see sep = 1 << CHAR_BIT above) */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006517 STPUTC(sep, q);
6518 expdest = q;
6519 }
6520 }
6521 return len;
Denys Vlasenko8eda4a92009-11-30 12:16:17 +01006522 } /* case '@' and '*' */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006523 case '0':
6524 case '1':
6525 case '2':
6526 case '3':
6527 case '4':
6528 case '5':
6529 case '6':
6530 case '7':
6531 case '8':
6532 case '9':
Denys Vlasenkoa00329c2009-08-30 20:05:10 +02006533 num = atoi(name); /* number(name) fails on ${N#str} etc */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006534 if (num < 0 || num > shellparam.nparam)
6535 return -1;
6536 p = num ? shellparam.p[num - 1] : arg0;
6537 goto value;
6538 default:
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006539 /* NB: name has form "VAR=..." */
6540
6541 /* "A=a B=$A" case: var_str_list is a list of "A=a" strings
6542 * which should be considered before we check variables. */
6543 if (var_str_list) {
6544 unsigned name_len = (strchrnul(name, '=') - name) + 1;
6545 p = NULL;
6546 do {
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00006547 char *str, *eq;
6548 str = var_str_list->text;
6549 eq = strchr(str, '=');
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006550 if (!eq) /* stop at first non-assignment */
6551 break;
6552 eq++;
Denis Vlasenko6b06cb82008-05-15 21:30:45 +00006553 if (name_len == (unsigned)(eq - str)
Denys Vlasenko8eda4a92009-11-30 12:16:17 +01006554 && strncmp(str, name, name_len) == 0
6555 ) {
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006556 p = eq;
6557 /* goto value; - WRONG! */
6558 /* think "A=1 A=2 B=$A" */
6559 }
6560 var_str_list = var_str_list->next;
6561 } while (var_str_list);
6562 if (p)
6563 goto value;
6564 }
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006565 p = lookupvar(name);
6566 value:
6567 if (!p)
6568 return -1;
6569
6570 len = strlen(p);
6571 if (!(subtype == VSPLUS || subtype == VSLENGTH))
6572 memtodest(p, len, syntax, quotes);
6573 return len;
6574 }
6575
6576 if (subtype == VSPLUS || subtype == VSLENGTH)
6577 STADJUST(-len, expdest);
6578 return len;
6579}
6580
6581/*
6582 * Expand a variable, and return a pointer to the next character in the
6583 * input string.
6584 */
6585static char *
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006586evalvar(char *p, int flags, struct strlist *var_str_list)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006587{
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006588 char varflags;
6589 char subtype;
6590 char quoted;
6591 char easy;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006592 char *var;
6593 int patloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006594 int startloc;
6595 ssize_t varlen;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006596
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006597 varflags = (unsigned char) *p++;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006598 subtype = varflags & VSTYPE;
6599 quoted = varflags & VSQUOTE;
6600 var = p;
6601 easy = (!quoted || (*var == '@' && shellparam.nparam));
6602 startloc = expdest - (char *)stackblock();
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02006603 p = strchr(p, '=') + 1; //TODO: use var_end(p)?
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006604
6605 again:
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006606 varlen = varvalue(var, varflags, flags, var_str_list);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006607 if (varflags & VSNUL)
6608 varlen--;
6609
6610 if (subtype == VSPLUS) {
6611 varlen = -1 - varlen;
6612 goto vsplus;
6613 }
6614
6615 if (subtype == VSMINUS) {
6616 vsplus:
6617 if (varlen < 0) {
6618 argstr(
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006619 p, flags | EXP_TILDE |
6620 (quoted ? EXP_QWORD : EXP_WORD),
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006621 var_str_list
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006622 );
6623 goto end;
6624 }
6625 if (easy)
6626 goto record;
6627 goto end;
6628 }
6629
6630 if (subtype == VSASSIGN || subtype == VSQUESTION) {
6631 if (varlen < 0) {
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006632 if (subevalvar(p, var, /* strloc: */ 0,
6633 subtype, startloc, varflags,
6634 /* quotes: */ 0,
6635 var_str_list)
6636 ) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006637 varflags &= ~VSNUL;
6638 /*
6639 * Remove any recorded regions beyond
6640 * start of variable
6641 */
6642 removerecordregions(startloc);
6643 goto again;
6644 }
6645 goto end;
6646 }
6647 if (easy)
6648 goto record;
6649 goto end;
6650 }
6651
6652 if (varlen < 0 && uflag)
6653 varunset(p, var, 0, 0);
6654
6655 if (subtype == VSLENGTH) {
6656 cvtnum(varlen > 0 ? varlen : 0);
6657 goto record;
6658 }
6659
6660 if (subtype == VSNORMAL) {
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006661 if (easy)
6662 goto record;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006663 goto end;
6664 }
6665
6666#if DEBUG
6667 switch (subtype) {
6668 case VSTRIMLEFT:
6669 case VSTRIMLEFTMAX:
6670 case VSTRIMRIGHT:
6671 case VSTRIMRIGHTMAX:
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006672#if ENABLE_ASH_BASH_COMPAT
6673 case VSSUBSTR:
6674 case VSREPLACE:
6675 case VSREPLACEALL:
6676#endif
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006677 break;
6678 default:
6679 abort();
6680 }
6681#endif
6682
6683 if (varlen >= 0) {
6684 /*
6685 * Terminate the string and start recording the pattern
6686 * right after it
6687 */
6688 STPUTC('\0', expdest);
6689 patloc = expdest - (char *)stackblock();
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006690 if (0 == subevalvar(p, /* str: */ NULL, patloc, subtype,
6691 startloc, varflags,
Denys Vlasenko1166d7b2009-09-16 16:20:31 +02006692//TODO: | EXP_REDIR too? All other such places do it too
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006693 /* quotes: */ flags & (EXP_FULL | EXP_CASE),
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006694 var_str_list)
6695 ) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006696 int amount = expdest - (
6697 (char *)stackblock() + patloc - 1
6698 );
6699 STADJUST(-amount, expdest);
6700 }
6701 /* Remove any recorded regions beyond start of variable */
6702 removerecordregions(startloc);
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006703 record:
6704 recordregion(startloc, expdest - (char *)stackblock(), quoted);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006705 }
6706
6707 end:
6708 if (subtype != VSNORMAL) { /* skip to end of alternative */
6709 int nesting = 1;
6710 for (;;) {
Denys Vlasenkocd716832009-11-28 22:14:02 +01006711 unsigned char c = *p++;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006712 if (c == CTLESC)
6713 p++;
6714 else if (c == CTLBACKQ || c == (CTLBACKQ|CTLQUOTE)) {
6715 if (varlen >= 0)
6716 argbackq = argbackq->next;
6717 } else if (c == CTLVAR) {
6718 if ((*p++ & VSTYPE) != VSNORMAL)
6719 nesting++;
6720 } else if (c == CTLENDVAR) {
6721 if (--nesting == 0)
6722 break;
6723 }
6724 }
6725 }
6726 return p;
6727}
6728
6729/*
6730 * Break the argument string into pieces based upon IFS and add the
6731 * strings to the argument list. The regions of the string to be
6732 * searched for IFS characters have been stored by recordregion.
6733 */
6734static void
6735ifsbreakup(char *string, struct arglist *arglist)
6736{
6737 struct ifsregion *ifsp;
6738 struct strlist *sp;
6739 char *start;
6740 char *p;
6741 char *q;
6742 const char *ifs, *realifs;
6743 int ifsspc;
6744 int nulonly;
6745
6746 start = string;
6747 if (ifslastp != NULL) {
6748 ifsspc = 0;
6749 nulonly = 0;
6750 realifs = ifsset() ? ifsval() : defifs;
6751 ifsp = &ifsfirst;
6752 do {
6753 p = string + ifsp->begoff;
6754 nulonly = ifsp->nulonly;
6755 ifs = nulonly ? nullstr : realifs;
6756 ifsspc = 0;
6757 while (p < string + ifsp->endoff) {
6758 q = p;
Denys Vlasenkocd716832009-11-28 22:14:02 +01006759 if ((unsigned char)*p == CTLESC)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006760 p++;
6761 if (!strchr(ifs, *p)) {
6762 p++;
6763 continue;
6764 }
6765 if (!nulonly)
6766 ifsspc = (strchr(defifs, *p) != NULL);
6767 /* Ignore IFS whitespace at start */
6768 if (q == start && ifsspc) {
6769 p++;
6770 start = p;
6771 continue;
6772 }
6773 *q = '\0';
Denis Vlasenko597906c2008-02-20 16:38:54 +00006774 sp = stzalloc(sizeof(*sp));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006775 sp->text = start;
6776 *arglist->lastp = sp;
6777 arglist->lastp = &sp->next;
6778 p++;
6779 if (!nulonly) {
6780 for (;;) {
6781 if (p >= string + ifsp->endoff) {
6782 break;
6783 }
6784 q = p;
Denys Vlasenkocd716832009-11-28 22:14:02 +01006785 if ((unsigned char)*p == CTLESC)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006786 p++;
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +00006787 if (strchr(ifs, *p) == NULL) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006788 p = q;
6789 break;
Denis Vlasenko597906c2008-02-20 16:38:54 +00006790 }
6791 if (strchr(defifs, *p) == NULL) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006792 if (ifsspc) {
6793 p++;
6794 ifsspc = 0;
6795 } else {
6796 p = q;
6797 break;
6798 }
6799 } else
6800 p++;
6801 }
6802 }
6803 start = p;
6804 } /* while */
6805 ifsp = ifsp->next;
6806 } while (ifsp != NULL);
6807 if (nulonly)
6808 goto add;
6809 }
6810
6811 if (!*start)
6812 return;
6813
6814 add:
Denis Vlasenko597906c2008-02-20 16:38:54 +00006815 sp = stzalloc(sizeof(*sp));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006816 sp->text = start;
6817 *arglist->lastp = sp;
6818 arglist->lastp = &sp->next;
6819}
6820
6821static void
6822ifsfree(void)
6823{
6824 struct ifsregion *p;
6825
6826 INT_OFF;
6827 p = ifsfirst.next;
6828 do {
6829 struct ifsregion *ifsp;
6830 ifsp = p->next;
6831 free(p);
6832 p = ifsp;
6833 } while (p);
6834 ifslastp = NULL;
6835 ifsfirst.next = NULL;
6836 INT_ON;
6837}
6838
6839/*
6840 * Add a file name to the list.
6841 */
6842static void
6843addfname(const char *name)
6844{
6845 struct strlist *sp;
6846
Denis Vlasenko597906c2008-02-20 16:38:54 +00006847 sp = stzalloc(sizeof(*sp));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006848 sp->text = ststrdup(name);
6849 *exparg.lastp = sp;
6850 exparg.lastp = &sp->next;
6851}
6852
6853static char *expdir;
6854
6855/*
6856 * Do metacharacter (i.e. *, ?, [...]) expansion.
6857 */
6858static void
6859expmeta(char *enddir, char *name)
6860{
6861 char *p;
6862 const char *cp;
6863 char *start;
6864 char *endname;
6865 int metaflag;
6866 struct stat statb;
6867 DIR *dirp;
6868 struct dirent *dp;
6869 int atend;
6870 int matchdot;
6871
6872 metaflag = 0;
6873 start = name;
6874 for (p = name; *p; p++) {
6875 if (*p == '*' || *p == '?')
6876 metaflag = 1;
6877 else if (*p == '[') {
6878 char *q = p + 1;
6879 if (*q == '!')
6880 q++;
6881 for (;;) {
6882 if (*q == '\\')
6883 q++;
6884 if (*q == '/' || *q == '\0')
6885 break;
6886 if (*++q == ']') {
6887 metaflag = 1;
6888 break;
6889 }
6890 }
6891 } else if (*p == '\\')
6892 p++;
6893 else if (*p == '/') {
6894 if (metaflag)
6895 goto out;
6896 start = p + 1;
6897 }
6898 }
6899 out:
6900 if (metaflag == 0) { /* we've reached the end of the file name */
6901 if (enddir != expdir)
6902 metaflag++;
6903 p = name;
6904 do {
6905 if (*p == '\\')
6906 p++;
6907 *enddir++ = *p;
6908 } while (*p++);
6909 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
6910 addfname(expdir);
6911 return;
6912 }
6913 endname = p;
6914 if (name < start) {
6915 p = name;
6916 do {
6917 if (*p == '\\')
6918 p++;
6919 *enddir++ = *p++;
6920 } while (p < start);
6921 }
6922 if (enddir == expdir) {
6923 cp = ".";
6924 } else if (enddir == expdir + 1 && *expdir == '/') {
6925 cp = "/";
6926 } else {
6927 cp = expdir;
6928 enddir[-1] = '\0';
6929 }
6930 dirp = opendir(cp);
6931 if (dirp == NULL)
6932 return;
6933 if (enddir != expdir)
6934 enddir[-1] = '/';
6935 if (*endname == 0) {
6936 atend = 1;
6937 } else {
6938 atend = 0;
6939 *endname++ = '\0';
6940 }
6941 matchdot = 0;
6942 p = start;
6943 if (*p == '\\')
6944 p++;
6945 if (*p == '.')
6946 matchdot++;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006947 while (!pending_int && (dp = readdir(dirp)) != NULL) {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00006948 if (dp->d_name[0] == '.' && !matchdot)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006949 continue;
6950 if (pmatch(start, dp->d_name)) {
6951 if (atend) {
6952 strcpy(enddir, dp->d_name);
6953 addfname(expdir);
6954 } else {
6955 for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
6956 continue;
6957 p[-1] = '/';
6958 expmeta(p, endname);
6959 }
6960 }
6961 }
6962 closedir(dirp);
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00006963 if (!atend)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006964 endname[-1] = '/';
6965}
6966
6967static struct strlist *
6968msort(struct strlist *list, int len)
6969{
6970 struct strlist *p, *q = NULL;
6971 struct strlist **lpp;
6972 int half;
6973 int n;
6974
6975 if (len <= 1)
6976 return list;
6977 half = len >> 1;
6978 p = list;
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +00006979 for (n = half; --n >= 0;) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006980 q = p;
6981 p = p->next;
6982 }
6983 q->next = NULL; /* terminate first half of list */
6984 q = msort(list, half); /* sort first half of list */
6985 p = msort(p, len - half); /* sort second half */
6986 lpp = &list;
6987 for (;;) {
6988#if ENABLE_LOCALE_SUPPORT
6989 if (strcoll(p->text, q->text) < 0)
6990#else
6991 if (strcmp(p->text, q->text) < 0)
6992#endif
6993 {
6994 *lpp = p;
6995 lpp = &p->next;
6996 p = *lpp;
6997 if (p == NULL) {
6998 *lpp = q;
6999 break;
7000 }
7001 } else {
7002 *lpp = q;
7003 lpp = &q->next;
7004 q = *lpp;
7005 if (q == NULL) {
7006 *lpp = p;
7007 break;
7008 }
7009 }
7010 }
7011 return list;
7012}
7013
7014/*
7015 * Sort the results of file name expansion. It calculates the number of
7016 * strings to sort and then calls msort (short for merge sort) to do the
7017 * work.
7018 */
7019static struct strlist *
7020expsort(struct strlist *str)
7021{
7022 int len;
7023 struct strlist *sp;
7024
7025 len = 0;
7026 for (sp = str; sp; sp = sp->next)
7027 len++;
7028 return msort(str, len);
7029}
7030
7031static void
Denis Vlasenko68404f12008-03-17 09:00:54 +00007032expandmeta(struct strlist *str /*, int flag*/)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007033{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00007034 static const char metachars[] ALIGN1 = {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007035 '*', '?', '[', 0
7036 };
7037 /* TODO - EXP_REDIR */
7038
7039 while (str) {
7040 struct strlist **savelastp;
7041 struct strlist *sp;
7042 char *p;
7043
7044 if (fflag)
7045 goto nometa;
7046 if (!strpbrk(str->text, metachars))
7047 goto nometa;
7048 savelastp = exparg.lastp;
7049
7050 INT_OFF;
7051 p = preglob(str->text, 0, RMESCAPE_ALLOC | RMESCAPE_HEAP);
7052 {
7053 int i = strlen(str->text);
7054 expdir = ckmalloc(i < 2048 ? 2048 : i); /* XXX */
7055 }
7056
7057 expmeta(expdir, p);
7058 free(expdir);
7059 if (p != str->text)
7060 free(p);
7061 INT_ON;
7062 if (exparg.lastp == savelastp) {
7063 /*
7064 * no matches
7065 */
7066 nometa:
7067 *exparg.lastp = str;
Denys Vlasenkob6c84342009-08-29 20:23:20 +02007068 rmescapes(str->text, 0);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007069 exparg.lastp = &str->next;
7070 } else {
7071 *exparg.lastp = NULL;
7072 *savelastp = sp = expsort(*savelastp);
7073 while (sp->next != NULL)
7074 sp = sp->next;
7075 exparg.lastp = &sp->next;
7076 }
7077 str = str->next;
7078 }
7079}
7080
7081/*
7082 * Perform variable substitution and command substitution on an argument,
7083 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
7084 * perform splitting and file name expansion. When arglist is NULL, perform
7085 * here document expansion.
7086 */
7087static void
7088expandarg(union node *arg, struct arglist *arglist, int flag)
7089{
7090 struct strlist *sp;
7091 char *p;
7092
7093 argbackq = arg->narg.backquote;
7094 STARTSTACKSTR(expdest);
7095 ifsfirst.next = NULL;
7096 ifslastp = NULL;
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00007097 argstr(arg->narg.text, flag,
7098 /* var_str_list: */ arglist ? arglist->list : NULL);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007099 p = _STPUTC('\0', expdest);
7100 expdest = p - 1;
7101 if (arglist == NULL) {
7102 return; /* here document expanded */
7103 }
7104 p = grabstackstr(p);
7105 exparg.lastp = &exparg.list;
7106 /*
7107 * TODO - EXP_REDIR
7108 */
7109 if (flag & EXP_FULL) {
7110 ifsbreakup(p, &exparg);
7111 *exparg.lastp = NULL;
7112 exparg.lastp = &exparg.list;
Denis Vlasenko68404f12008-03-17 09:00:54 +00007113 expandmeta(exparg.list /*, flag*/);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007114 } else {
7115 if (flag & EXP_REDIR) /*XXX - for now, just remove escapes */
Denys Vlasenkob6c84342009-08-29 20:23:20 +02007116 rmescapes(p, 0);
Denis Vlasenko597906c2008-02-20 16:38:54 +00007117 sp = stzalloc(sizeof(*sp));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007118 sp->text = p;
7119 *exparg.lastp = sp;
7120 exparg.lastp = &sp->next;
7121 }
7122 if (ifsfirst.next)
7123 ifsfree();
7124 *exparg.lastp = NULL;
7125 if (exparg.list) {
7126 *arglist->lastp = exparg.list;
7127 arglist->lastp = exparg.lastp;
7128 }
7129}
7130
7131/*
7132 * Expand shell variables and backquotes inside a here document.
7133 */
7134static void
7135expandhere(union node *arg, int fd)
7136{
7137 herefd = fd;
7138 expandarg(arg, (struct arglist *)NULL, 0);
7139 full_write(fd, stackblock(), expdest - (char *)stackblock());
7140}
7141
7142/*
7143 * Returns true if the pattern matches the string.
7144 */
7145static int
7146patmatch(char *pattern, const char *string)
7147{
7148 return pmatch(preglob(pattern, 0, 0), string);
7149}
7150
7151/*
7152 * See if a pattern matches in a case statement.
7153 */
7154static int
7155casematch(union node *pattern, char *val)
7156{
7157 struct stackmark smark;
7158 int result;
7159
7160 setstackmark(&smark);
7161 argbackq = pattern->narg.backquote;
7162 STARTSTACKSTR(expdest);
7163 ifslastp = NULL;
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00007164 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE,
7165 /* var_str_list: */ NULL);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007166 STACKSTRNUL(expdest);
7167 result = patmatch(stackblock(), val);
7168 popstackmark(&smark);
7169 return result;
7170}
7171
7172
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007173/* ============ find_command */
7174
7175struct builtincmd {
7176 const char *name;
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007177 int (*builtin)(int, char **) FAST_FUNC;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007178 /* unsigned flags; */
7179};
7180#define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
Denis Vlasenkoe26b2782008-02-12 07:40:29 +00007181/* "regular" builtins always take precedence over commands,
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007182 * regardless of PATH=....%builtin... position */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007183#define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007184#define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007185
7186struct cmdentry {
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00007187 smallint cmdtype; /* CMDxxx */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007188 union param {
7189 int index;
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00007190 /* index >= 0 for commands without path (slashes) */
7191 /* (TODO: what exactly does the value mean? PATH position?) */
7192 /* index == -1 for commands with slashes */
7193 /* index == (-2 - applet_no) for NOFORK applets */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007194 const struct builtincmd *cmd;
7195 struct funcnode *func;
7196 } u;
7197};
7198/* values of cmdtype */
7199#define CMDUNKNOWN -1 /* no entry in table for command */
7200#define CMDNORMAL 0 /* command is an executable program */
7201#define CMDFUNCTION 1 /* command is a shell function */
7202#define CMDBUILTIN 2 /* command is a shell builtin */
7203
7204/* action to find_command() */
7205#define DO_ERR 0x01 /* prints errors */
7206#define DO_ABS 0x02 /* checks absolute paths */
7207#define DO_NOFUNC 0x04 /* don't return shell functions, for command */
7208#define DO_ALTPATH 0x08 /* using alternate path */
7209#define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
7210
7211static void find_command(char *, struct cmdentry *, int, const char *);
7212
7213
7214/* ============ Hashing commands */
7215
7216/*
7217 * When commands are first encountered, they are entered in a hash table.
7218 * This ensures that a full path search will not have to be done for them
7219 * on each invocation.
7220 *
7221 * We should investigate converting to a linear search, even though that
7222 * would make the command name "hash" a misnomer.
7223 */
7224
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007225struct tblentry {
7226 struct tblentry *next; /* next entry in hash chain */
7227 union param param; /* definition of builtin function */
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00007228 smallint cmdtype; /* CMDxxx */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007229 char rehash; /* if set, cd done since entry created */
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007230 char cmdname[1]; /* name of command */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007231};
7232
Denis Vlasenko01631112007-12-16 17:20:38 +00007233static struct tblentry **cmdtable;
7234#define INIT_G_cmdtable() do { \
7235 cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
7236} while (0)
7237
7238static int builtinloc = -1; /* index in path of %builtin, or -1 */
7239
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007240
7241static void
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00007242tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) char *cmd, char **argv, char **envp)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007243{
7244 int repeated = 0;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007245
Denis Vlasenko80d14be2007-04-10 23:03:30 +00007246#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007247 if (applet_no >= 0) {
Denis Vlasenkob7304742008-10-20 08:15:51 +00007248 if (APPLET_IS_NOEXEC(applet_no)) {
Denys Vlasenko7df28bb2010-06-18 14:23:47 +02007249 clearenv();
Denis Vlasenkob7304742008-10-20 08:15:51 +00007250 while (*envp)
7251 putenv(*envp++);
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007252 run_applet_no_and_exit(applet_no, argv);
Denis Vlasenkob7304742008-10-20 08:15:51 +00007253 }
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007254 /* re-exec ourselves with the new arguments */
7255 execve(bb_busybox_exec_path, argv, envp);
7256 /* If they called chroot or otherwise made the binary no longer
7257 * executable, fall through */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007258 }
7259#endif
7260
7261 repeat:
7262#ifdef SYSV
7263 do {
7264 execve(cmd, argv, envp);
7265 } while (errno == EINTR);
7266#else
7267 execve(cmd, argv, envp);
7268#endif
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007269 if (repeated) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007270 free(argv);
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007271 return;
7272 }
7273 if (errno == ENOEXEC) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007274 char **ap;
7275 char **new;
7276
7277 for (ap = argv; *ap; ap++)
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007278 continue;
7279 ap = new = ckmalloc((ap - argv + 2) * sizeof(ap[0]));
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007280 ap[1] = cmd;
Denis Vlasenkoc44ab012007-04-09 03:11:58 +00007281 ap[0] = cmd = (char *)DEFAULT_SHELL;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007282 ap += 2;
7283 argv++;
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007284 while ((*ap++ = *argv++) != NULL)
Denis Vlasenko597906c2008-02-20 16:38:54 +00007285 continue;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007286 argv = new;
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007287 repeated++;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007288 goto repeat;
7289 }
7290}
7291
7292/*
7293 * Exec a program. Never returns. If you change this routine, you may
7294 * have to change the find_command routine as well.
7295 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00007296static void shellexec(char **, const char *, int) NORETURN;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007297static void
7298shellexec(char **argv, const char *path, int idx)
7299{
7300 char *cmdname;
7301 int e;
7302 char **envp;
7303 int exerrno;
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007304#if ENABLE_FEATURE_SH_STANDALONE
7305 int applet_no = -1;
7306#endif
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007307
Denis Vlasenko34c73c42008-08-16 11:48:02 +00007308 clearredir(/*drop:*/ 1);
Denys Vlasenko1ed2fb42010-06-18 14:09:48 +02007309 envp = listvars(VEXPORT, VUNSET, /*end:*/ NULL);
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007310 if (strchr(argv[0], '/') != NULL
Denis Vlasenko80d14be2007-04-10 23:03:30 +00007311#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007312 || (applet_no = find_applet_by_name(argv[0])) >= 0
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007313#endif
7314 ) {
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00007315 tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) argv[0], argv, envp);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007316 e = errno;
7317 } else {
7318 e = ENOENT;
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02007319 while ((cmdname = path_advance(&path, argv[0])) != NULL) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007320 if (--idx < 0 && pathopt == NULL) {
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00007321 tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007322 if (errno != ENOENT && errno != ENOTDIR)
7323 e = errno;
7324 }
7325 stunalloc(cmdname);
7326 }
7327 }
7328
7329 /* Map to POSIX errors */
7330 switch (e) {
7331 case EACCES:
7332 exerrno = 126;
7333 break;
7334 case ENOENT:
7335 exerrno = 127;
7336 break;
7337 default:
7338 exerrno = 2;
7339 break;
7340 }
7341 exitstatus = exerrno;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02007342 TRACE(("shellexec failed for %s, errno %d, suppress_int %d\n",
7343 argv[0], e, suppress_int));
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007344 ash_msg_and_raise(EXEXEC, "%s: %s", argv[0], errmsg(e, "not found"));
7345 /* NOTREACHED */
7346}
7347
7348static void
7349printentry(struct tblentry *cmdp)
7350{
7351 int idx;
7352 const char *path;
7353 char *name;
7354
7355 idx = cmdp->param.index;
7356 path = pathval();
7357 do {
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02007358 name = path_advance(&path, cmdp->cmdname);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007359 stunalloc(name);
7360 } while (--idx >= 0);
7361 out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
7362}
7363
7364/*
7365 * Clear out command entries. The argument specifies the first entry in
7366 * PATH which has changed.
7367 */
7368static void
7369clearcmdentry(int firstchange)
7370{
7371 struct tblentry **tblp;
7372 struct tblentry **pp;
7373 struct tblentry *cmdp;
7374
7375 INT_OFF;
7376 for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
7377 pp = tblp;
7378 while ((cmdp = *pp) != NULL) {
7379 if ((cmdp->cmdtype == CMDNORMAL &&
7380 cmdp->param.index >= firstchange)
7381 || (cmdp->cmdtype == CMDBUILTIN &&
7382 builtinloc >= firstchange)
7383 ) {
7384 *pp = cmdp->next;
7385 free(cmdp);
7386 } else {
7387 pp = &cmdp->next;
7388 }
7389 }
7390 }
7391 INT_ON;
7392}
7393
7394/*
7395 * Locate a command in the command hash table. If "add" is nonzero,
7396 * add the command to the table if it is not already present. The
7397 * variable "lastcmdentry" is set to point to the address of the link
7398 * pointing to the entry, so that delete_cmd_entry can delete the
7399 * entry.
7400 *
7401 * Interrupts must be off if called with add != 0.
7402 */
7403static struct tblentry **lastcmdentry;
7404
7405static struct tblentry *
7406cmdlookup(const char *name, int add)
7407{
7408 unsigned int hashval;
7409 const char *p;
7410 struct tblentry *cmdp;
7411 struct tblentry **pp;
7412
7413 p = name;
7414 hashval = (unsigned char)*p << 4;
7415 while (*p)
7416 hashval += (unsigned char)*p++;
7417 hashval &= 0x7FFF;
7418 pp = &cmdtable[hashval % CMDTABLESIZE];
7419 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7420 if (strcmp(cmdp->cmdname, name) == 0)
7421 break;
7422 pp = &cmdp->next;
7423 }
7424 if (add && cmdp == NULL) {
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007425 cmdp = *pp = ckzalloc(sizeof(struct tblentry)
7426 + strlen(name)
7427 /* + 1 - already done because
7428 * tblentry::cmdname is char[1] */);
Denis Vlasenko597906c2008-02-20 16:38:54 +00007429 /*cmdp->next = NULL; - ckzalloc did it */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007430 cmdp->cmdtype = CMDUNKNOWN;
7431 strcpy(cmdp->cmdname, name);
7432 }
7433 lastcmdentry = pp;
7434 return cmdp;
7435}
7436
7437/*
7438 * Delete the command entry returned on the last lookup.
7439 */
7440static void
7441delete_cmd_entry(void)
7442{
7443 struct tblentry *cmdp;
7444
7445 INT_OFF;
7446 cmdp = *lastcmdentry;
7447 *lastcmdentry = cmdp->next;
7448 if (cmdp->cmdtype == CMDFUNCTION)
7449 freefunc(cmdp->param.func);
7450 free(cmdp);
7451 INT_ON;
7452}
7453
7454/*
7455 * Add a new command entry, replacing any existing command entry for
7456 * the same name - except special builtins.
7457 */
7458static void
7459addcmdentry(char *name, struct cmdentry *entry)
7460{
7461 struct tblentry *cmdp;
7462
7463 cmdp = cmdlookup(name, 1);
7464 if (cmdp->cmdtype == CMDFUNCTION) {
7465 freefunc(cmdp->param.func);
7466 }
7467 cmdp->cmdtype = entry->cmdtype;
7468 cmdp->param = entry->u;
7469 cmdp->rehash = 0;
7470}
7471
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007472static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00007473hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007474{
7475 struct tblentry **pp;
7476 struct tblentry *cmdp;
7477 int c;
7478 struct cmdentry entry;
7479 char *name;
7480
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007481 if (nextopt("r") != '\0') {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007482 clearcmdentry(0);
7483 return 0;
7484 }
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007485
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007486 if (*argptr == NULL) {
7487 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7488 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7489 if (cmdp->cmdtype == CMDNORMAL)
7490 printentry(cmdp);
7491 }
7492 }
7493 return 0;
7494 }
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007495
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007496 c = 0;
7497 while ((name = *argptr) != NULL) {
7498 cmdp = cmdlookup(name, 0);
7499 if (cmdp != NULL
7500 && (cmdp->cmdtype == CMDNORMAL
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007501 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
7502 ) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007503 delete_cmd_entry();
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007504 }
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007505 find_command(name, &entry, DO_ERR, pathval());
7506 if (entry.cmdtype == CMDUNKNOWN)
7507 c = 1;
7508 argptr++;
7509 }
7510 return c;
7511}
7512
7513/*
7514 * Called when a cd is done. Marks all commands so the next time they
7515 * are executed they will be rehashed.
7516 */
7517static void
7518hashcd(void)
7519{
7520 struct tblentry **pp;
7521 struct tblentry *cmdp;
7522
7523 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7524 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007525 if (cmdp->cmdtype == CMDNORMAL
7526 || (cmdp->cmdtype == CMDBUILTIN
7527 && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
7528 && builtinloc > 0)
7529 ) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007530 cmdp->rehash = 1;
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007531 }
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007532 }
7533 }
7534}
7535
7536/*
7537 * Fix command hash table when PATH changed.
7538 * Called before PATH is changed. The argument is the new value of PATH;
7539 * pathval() still returns the old value at this point.
7540 * Called with interrupts off.
7541 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007542static void FAST_FUNC
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007543changepath(const char *new)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007544{
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007545 const char *old;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007546 int firstchange;
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007547 int idx;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007548 int idx_bltin;
7549
7550 old = pathval();
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007551 firstchange = 9999; /* assume no change */
7552 idx = 0;
7553 idx_bltin = -1;
7554 for (;;) {
7555 if (*old != *new) {
7556 firstchange = idx;
7557 if ((*old == '\0' && *new == ':')
Denys Vlasenkoa0ec4f52010-05-20 12:50:42 +02007558 || (*old == ':' && *new == '\0')
7559 ) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007560 firstchange++;
Denys Vlasenkoa0ec4f52010-05-20 12:50:42 +02007561 }
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007562 old = new; /* ignore subsequent differences */
7563 }
7564 if (*new == '\0')
7565 break;
7566 if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
7567 idx_bltin = idx;
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007568 if (*new == ':')
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007569 idx++;
Denys Vlasenkoa0ec4f52010-05-20 12:50:42 +02007570 new++;
7571 old++;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007572 }
7573 if (builtinloc < 0 && idx_bltin >= 0)
7574 builtinloc = idx_bltin; /* zap builtins */
7575 if (builtinloc >= 0 && idx_bltin < 0)
7576 firstchange = 0;
7577 clearcmdentry(firstchange);
7578 builtinloc = idx_bltin;
7579}
7580
7581#define TEOF 0
7582#define TNL 1
7583#define TREDIR 2
7584#define TWORD 3
7585#define TSEMI 4
7586#define TBACKGND 5
7587#define TAND 6
7588#define TOR 7
7589#define TPIPE 8
7590#define TLP 9
7591#define TRP 10
7592#define TENDCASE 11
7593#define TENDBQUOTE 12
7594#define TNOT 13
7595#define TCASE 14
7596#define TDO 15
7597#define TDONE 16
7598#define TELIF 17
7599#define TELSE 18
7600#define TESAC 19
7601#define TFI 20
7602#define TFOR 21
7603#define TIF 22
7604#define TIN 23
7605#define TTHEN 24
7606#define TUNTIL 25
7607#define TWHILE 26
7608#define TBEGIN 27
7609#define TEND 28
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007610typedef smallint token_id_t;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007611
7612/* first char is indicating which tokens mark the end of a list */
7613static const char *const tokname_array[] = {
7614 "\1end of file",
7615 "\0newline",
7616 "\0redirection",
7617 "\0word",
7618 "\0;",
7619 "\0&",
7620 "\0&&",
7621 "\0||",
7622 "\0|",
7623 "\0(",
7624 "\1)",
7625 "\1;;",
7626 "\1`",
7627#define KWDOFFSET 13
7628 /* the following are keywords */
7629 "\0!",
7630 "\0case",
7631 "\1do",
7632 "\1done",
7633 "\1elif",
7634 "\1else",
7635 "\1esac",
7636 "\1fi",
7637 "\0for",
7638 "\0if",
7639 "\0in",
7640 "\1then",
7641 "\0until",
7642 "\0while",
7643 "\0{",
7644 "\1}",
7645};
7646
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007647/* Wrapper around strcmp for qsort/bsearch/... */
7648static int
7649pstrcmp(const void *a, const void *b)
7650{
Denis Vlasenko240a1cf2007-04-08 16:07:02 +00007651 return strcmp((char*) a, (*(char**) b) + 1);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007652}
7653
7654static const char *const *
7655findkwd(const char *s)
7656{
7657 return bsearch(s, tokname_array + KWDOFFSET,
Denis Vlasenko80b8b392007-06-25 10:55:35 +00007658 ARRAY_SIZE(tokname_array) - KWDOFFSET,
7659 sizeof(tokname_array[0]), pstrcmp);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007660}
7661
7662/*
7663 * Locate and print what a word is...
7664 */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007665static int
7666describe_command(char *command, int describe_command_verbose)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007667{
7668 struct cmdentry entry;
7669 struct tblentry *cmdp;
7670#if ENABLE_ASH_ALIAS
7671 const struct alias *ap;
7672#endif
7673 const char *path = pathval();
7674
7675 if (describe_command_verbose) {
7676 out1str(command);
7677 }
7678
7679 /* First look at the keywords */
7680 if (findkwd(command)) {
7681 out1str(describe_command_verbose ? " is a shell keyword" : command);
7682 goto out;
7683 }
7684
7685#if ENABLE_ASH_ALIAS
7686 /* Then look at the aliases */
7687 ap = lookupalias(command, 0);
7688 if (ap != NULL) {
Denis Vlasenko46846e22007-05-20 13:08:31 +00007689 if (!describe_command_verbose) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007690 out1str("alias ");
7691 printalias(ap);
7692 return 0;
7693 }
Denis Vlasenko46846e22007-05-20 13:08:31 +00007694 out1fmt(" is an alias for %s", ap->val);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007695 goto out;
7696 }
7697#endif
7698 /* Then check if it is a tracked alias */
7699 cmdp = cmdlookup(command, 0);
7700 if (cmdp != NULL) {
7701 entry.cmdtype = cmdp->cmdtype;
7702 entry.u = cmdp->param;
7703 } else {
7704 /* Finally use brute force */
7705 find_command(command, &entry, DO_ABS, path);
7706 }
7707
7708 switch (entry.cmdtype) {
7709 case CMDNORMAL: {
7710 int j = entry.u.index;
7711 char *p;
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00007712 if (j < 0) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007713 p = command;
7714 } else {
7715 do {
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02007716 p = path_advance(&path, command);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007717 stunalloc(p);
7718 } while (--j >= 0);
7719 }
7720 if (describe_command_verbose) {
7721 out1fmt(" is%s %s",
7722 (cmdp ? " a tracked alias for" : nullstr), p
7723 );
7724 } else {
7725 out1str(p);
7726 }
7727 break;
7728 }
7729
7730 case CMDFUNCTION:
7731 if (describe_command_verbose) {
7732 out1str(" is a shell function");
7733 } else {
7734 out1str(command);
7735 }
7736 break;
7737
7738 case CMDBUILTIN:
7739 if (describe_command_verbose) {
7740 out1fmt(" is a %sshell builtin",
7741 IS_BUILTIN_SPECIAL(entry.u.cmd) ?
7742 "special " : nullstr
7743 );
7744 } else {
7745 out1str(command);
7746 }
7747 break;
7748
7749 default:
7750 if (describe_command_verbose) {
7751 out1str(": not found\n");
7752 }
7753 return 127;
7754 }
7755 out:
Denys Vlasenko285ad152009-12-04 23:02:27 +01007756 out1str("\n");
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007757 return 0;
7758}
7759
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007760static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00007761typecmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007762{
Denis Vlasenko46846e22007-05-20 13:08:31 +00007763 int i = 1;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007764 int err = 0;
Denis Vlasenko46846e22007-05-20 13:08:31 +00007765 int verbose = 1;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007766
Denis Vlasenko46846e22007-05-20 13:08:31 +00007767 /* type -p ... ? (we don't bother checking for 'p') */
Denis Vlasenko1fc62382007-06-25 22:55:34 +00007768 if (argv[1] && argv[1][0] == '-') {
Denis Vlasenko46846e22007-05-20 13:08:31 +00007769 i++;
7770 verbose = 0;
7771 }
Denis Vlasenko68404f12008-03-17 09:00:54 +00007772 while (argv[i]) {
Denis Vlasenko46846e22007-05-20 13:08:31 +00007773 err |= describe_command(argv[i++], verbose);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007774 }
7775 return err;
7776}
7777
7778#if ENABLE_ASH_CMDCMD
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007779static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00007780commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007781{
7782 int c;
7783 enum {
7784 VERIFY_BRIEF = 1,
7785 VERIFY_VERBOSE = 2,
7786 } verify = 0;
7787
7788 while ((c = nextopt("pvV")) != '\0')
7789 if (c == 'V')
7790 verify |= VERIFY_VERBOSE;
7791 else if (c == 'v')
7792 verify |= VERIFY_BRIEF;
7793#if DEBUG
7794 else if (c != 'p')
7795 abort();
7796#endif
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00007797 /* Mimic bash: just "command -v" doesn't complain, it's a nop */
7798 if (verify && (*argptr != NULL)) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007799 return describe_command(*argptr, verify - VERIFY_BRIEF);
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00007800 }
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007801
7802 return 0;
7803}
7804#endif
7805
7806
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007807/* ============ eval.c */
Eric Andersencb57d552001-06-28 07:25:16 +00007808
Denis Vlasenko340299a2008-11-21 10:36:36 +00007809static int funcblocksize; /* size of structures in function */
7810static int funcstringsize; /* size of strings in node */
7811static void *funcblock; /* block to allocate function from */
7812static char *funcstring; /* block to allocate strings from */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007813
Eric Andersencb57d552001-06-28 07:25:16 +00007814/* flags in argument to evaltree */
Denis Vlasenko340299a2008-11-21 10:36:36 +00007815#define EV_EXIT 01 /* exit after evaluating tree */
7816#define EV_TESTED 02 /* exit status is checked; ignore -e flag */
Eric Andersenc470f442003-07-28 09:56:35 +00007817#define EV_BACKCMD 04 /* command executing within back quotes */
Eric Andersencb57d552001-06-28 07:25:16 +00007818
Denys Vlasenko0e5e4ea2009-10-11 00:36:20 +02007819static const uint8_t nodesize[N_NUMBER] = {
Denis Vlasenko340299a2008-11-21 10:36:36 +00007820 [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
7821 [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
7822 [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
7823 [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
7824 [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
7825 [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
7826 [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
7827 [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
7828 [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
7829 [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
7830 [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
7831 [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
7832 [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
7833 [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
7834 [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
7835 [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
7836 [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
Denis Vlasenkocc5feab2008-11-22 01:32:40 +00007837#if ENABLE_ASH_BASH_COMPAT
Denis Vlasenko340299a2008-11-21 10:36:36 +00007838 [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
Denis Vlasenkocc5feab2008-11-22 01:32:40 +00007839#endif
Denis Vlasenko340299a2008-11-21 10:36:36 +00007840 [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
7841 [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
7842 [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
7843 [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
7844 [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
7845 [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
7846 [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
7847 [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
7848 [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007849};
7850
7851static void calcsize(union node *n);
7852
7853static void
7854sizenodelist(struct nodelist *lp)
7855{
7856 while (lp) {
7857 funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
7858 calcsize(lp->n);
7859 lp = lp->next;
7860 }
7861}
7862
7863static void
7864calcsize(union node *n)
7865{
7866 if (n == NULL)
7867 return;
7868 funcblocksize += nodesize[n->type];
7869 switch (n->type) {
7870 case NCMD:
7871 calcsize(n->ncmd.redirect);
7872 calcsize(n->ncmd.args);
7873 calcsize(n->ncmd.assign);
7874 break;
7875 case NPIPE:
7876 sizenodelist(n->npipe.cmdlist);
7877 break;
7878 case NREDIR:
7879 case NBACKGND:
7880 case NSUBSHELL:
7881 calcsize(n->nredir.redirect);
7882 calcsize(n->nredir.n);
7883 break;
7884 case NAND:
7885 case NOR:
7886 case NSEMI:
7887 case NWHILE:
7888 case NUNTIL:
7889 calcsize(n->nbinary.ch2);
7890 calcsize(n->nbinary.ch1);
7891 break;
7892 case NIF:
7893 calcsize(n->nif.elsepart);
7894 calcsize(n->nif.ifpart);
7895 calcsize(n->nif.test);
7896 break;
7897 case NFOR:
7898 funcstringsize += strlen(n->nfor.var) + 1;
7899 calcsize(n->nfor.body);
7900 calcsize(n->nfor.args);
7901 break;
7902 case NCASE:
7903 calcsize(n->ncase.cases);
7904 calcsize(n->ncase.expr);
7905 break;
7906 case NCLIST:
7907 calcsize(n->nclist.body);
7908 calcsize(n->nclist.pattern);
7909 calcsize(n->nclist.next);
7910 break;
7911 case NDEFUN:
7912 case NARG:
7913 sizenodelist(n->narg.backquote);
7914 funcstringsize += strlen(n->narg.text) + 1;
7915 calcsize(n->narg.next);
7916 break;
7917 case NTO:
Denis Vlasenko559691a2008-10-05 18:39:31 +00007918#if ENABLE_ASH_BASH_COMPAT
7919 case NTO2:
7920#endif
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007921 case NCLOBBER:
7922 case NFROM:
7923 case NFROMTO:
7924 case NAPPEND:
7925 calcsize(n->nfile.fname);
7926 calcsize(n->nfile.next);
7927 break;
7928 case NTOFD:
7929 case NFROMFD:
7930 calcsize(n->ndup.vname);
7931 calcsize(n->ndup.next);
7932 break;
7933 case NHERE:
7934 case NXHERE:
7935 calcsize(n->nhere.doc);
7936 calcsize(n->nhere.next);
7937 break;
7938 case NNOT:
7939 calcsize(n->nnot.com);
7940 break;
7941 };
7942}
7943
7944static char *
7945nodeckstrdup(char *s)
7946{
7947 char *rtn = funcstring;
7948
7949 strcpy(funcstring, s);
7950 funcstring += strlen(s) + 1;
7951 return rtn;
7952}
7953
7954static union node *copynode(union node *);
7955
7956static struct nodelist *
7957copynodelist(struct nodelist *lp)
7958{
7959 struct nodelist *start;
7960 struct nodelist **lpp;
7961
7962 lpp = &start;
7963 while (lp) {
7964 *lpp = funcblock;
7965 funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
7966 (*lpp)->n = copynode(lp->n);
7967 lp = lp->next;
7968 lpp = &(*lpp)->next;
7969 }
7970 *lpp = NULL;
7971 return start;
7972}
7973
7974static union node *
7975copynode(union node *n)
7976{
7977 union node *new;
7978
7979 if (n == NULL)
7980 return NULL;
7981 new = funcblock;
7982 funcblock = (char *) funcblock + nodesize[n->type];
7983
7984 switch (n->type) {
7985 case NCMD:
7986 new->ncmd.redirect = copynode(n->ncmd.redirect);
7987 new->ncmd.args = copynode(n->ncmd.args);
7988 new->ncmd.assign = copynode(n->ncmd.assign);
7989 break;
7990 case NPIPE:
7991 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00007992 new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007993 break;
7994 case NREDIR:
7995 case NBACKGND:
7996 case NSUBSHELL:
7997 new->nredir.redirect = copynode(n->nredir.redirect);
7998 new->nredir.n = copynode(n->nredir.n);
7999 break;
8000 case NAND:
8001 case NOR:
8002 case NSEMI:
8003 case NWHILE:
8004 case NUNTIL:
8005 new->nbinary.ch2 = copynode(n->nbinary.ch2);
8006 new->nbinary.ch1 = copynode(n->nbinary.ch1);
8007 break;
8008 case NIF:
8009 new->nif.elsepart = copynode(n->nif.elsepart);
8010 new->nif.ifpart = copynode(n->nif.ifpart);
8011 new->nif.test = copynode(n->nif.test);
8012 break;
8013 case NFOR:
8014 new->nfor.var = nodeckstrdup(n->nfor.var);
8015 new->nfor.body = copynode(n->nfor.body);
8016 new->nfor.args = copynode(n->nfor.args);
8017 break;
8018 case NCASE:
8019 new->ncase.cases = copynode(n->ncase.cases);
8020 new->ncase.expr = copynode(n->ncase.expr);
8021 break;
8022 case NCLIST:
8023 new->nclist.body = copynode(n->nclist.body);
8024 new->nclist.pattern = copynode(n->nclist.pattern);
8025 new->nclist.next = copynode(n->nclist.next);
8026 break;
8027 case NDEFUN:
8028 case NARG:
8029 new->narg.backquote = copynodelist(n->narg.backquote);
8030 new->narg.text = nodeckstrdup(n->narg.text);
8031 new->narg.next = copynode(n->narg.next);
8032 break;
8033 case NTO:
Denis Vlasenko559691a2008-10-05 18:39:31 +00008034#if ENABLE_ASH_BASH_COMPAT
8035 case NTO2:
8036#endif
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008037 case NCLOBBER:
8038 case NFROM:
8039 case NFROMTO:
8040 case NAPPEND:
8041 new->nfile.fname = copynode(n->nfile.fname);
8042 new->nfile.fd = n->nfile.fd;
8043 new->nfile.next = copynode(n->nfile.next);
8044 break;
8045 case NTOFD:
8046 case NFROMFD:
8047 new->ndup.vname = copynode(n->ndup.vname);
8048 new->ndup.dupfd = n->ndup.dupfd;
8049 new->ndup.fd = n->ndup.fd;
8050 new->ndup.next = copynode(n->ndup.next);
8051 break;
8052 case NHERE:
8053 case NXHERE:
8054 new->nhere.doc = copynode(n->nhere.doc);
8055 new->nhere.fd = n->nhere.fd;
8056 new->nhere.next = copynode(n->nhere.next);
8057 break;
8058 case NNOT:
8059 new->nnot.com = copynode(n->nnot.com);
8060 break;
8061 };
8062 new->type = n->type;
8063 return new;
8064}
8065
8066/*
8067 * Make a copy of a parse tree.
8068 */
8069static struct funcnode *
8070copyfunc(union node *n)
8071{
8072 struct funcnode *f;
8073 size_t blocksize;
8074
8075 funcblocksize = offsetof(struct funcnode, n);
8076 funcstringsize = 0;
8077 calcsize(n);
8078 blocksize = funcblocksize;
8079 f = ckmalloc(blocksize + funcstringsize);
8080 funcblock = (char *) f + offsetof(struct funcnode, n);
8081 funcstring = (char *) f + blocksize;
8082 copynode(n);
8083 f->count = 0;
8084 return f;
8085}
8086
8087/*
8088 * Define a shell function.
8089 */
8090static void
8091defun(char *name, union node *func)
8092{
8093 struct cmdentry entry;
8094
8095 INT_OFF;
8096 entry.cmdtype = CMDFUNCTION;
8097 entry.u.func = copyfunc(func);
8098 addcmdentry(name, &entry);
8099 INT_ON;
8100}
8101
Denis Vlasenko4b875702009-03-19 13:30:04 +00008102/* Reasons for skipping commands (see comment on breakcmd routine) */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008103#define SKIPBREAK (1 << 0)
8104#define SKIPCONT (1 << 1)
8105#define SKIPFUNC (1 << 2)
8106#define SKIPFILE (1 << 3)
8107#define SKIPEVAL (1 << 4)
Denis Vlasenko4b875702009-03-19 13:30:04 +00008108static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008109static int skipcount; /* number of levels to skip */
8110static int funcnest; /* depth of function calls */
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +00008111static int loopnest; /* current loop nesting level */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008112
Denis Vlasenko4b875702009-03-19 13:30:04 +00008113/* Forward decl way out to parsing code - dotrap needs it */
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008114static int evalstring(char *s, int mask);
8115
Denis Vlasenko4b875702009-03-19 13:30:04 +00008116/* Called to execute a trap.
8117 * Single callsite - at the end of evaltree().
8118 * If we return non-zero, exaltree raises EXEXIT exception.
8119 *
8120 * Perhaps we should avoid entering new trap handlers
8121 * while we are executing a trap handler. [is it a TODO?]
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008122 */
8123static int
8124dotrap(void)
8125{
Denis Vlasenko4b875702009-03-19 13:30:04 +00008126 uint8_t *g;
8127 int sig;
8128 uint8_t savestatus;
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008129
8130 savestatus = exitstatus;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02008131 pending_sig = 0;
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008132 xbarrier();
8133
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008134 TRACE(("dotrap entered\n"));
Denis Vlasenko4b875702009-03-19 13:30:04 +00008135 for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
8136 int want_exexit;
8137 char *t;
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008138
Denis Vlasenko4b875702009-03-19 13:30:04 +00008139 if (*g == 0)
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008140 continue;
Denis Vlasenko4b875702009-03-19 13:30:04 +00008141 t = trap[sig];
8142 /* non-trapped SIGINT is handled separately by raise_interrupt,
8143 * don't upset it by resetting gotsig[SIGINT-1] */
8144 if (sig == SIGINT && !t)
8145 continue;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008146
8147 TRACE(("sig %d is active, will run handler '%s'\n", sig, t));
Denis Vlasenko4b875702009-03-19 13:30:04 +00008148 *g = 0;
8149 if (!t)
8150 continue;
8151 want_exexit = evalstring(t, SKIPEVAL);
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008152 exitstatus = savestatus;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008153 if (want_exexit) {
Denis Vlasenkob21f3792009-03-19 23:09:58 +00008154 TRACE(("dotrap returns %d\n", want_exexit));
Denis Vlasenko4b875702009-03-19 13:30:04 +00008155 return want_exexit;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008156 }
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008157 }
8158
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008159 TRACE(("dotrap returns 0\n"));
Denis Vlasenko991a1da2008-02-10 19:02:53 +00008160 return 0;
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008161}
8162
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00008163/* forward declarations - evaluation is fairly recursive business... */
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008164static void evalloop(union node *, int);
8165static void evalfor(union node *, int);
8166static void evalcase(union node *, int);
8167static void evalsubshell(union node *, int);
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00008168static void expredir(union node *);
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008169static void evalpipe(union node *, int);
8170static void evalcommand(union node *, int);
Eric Andersenc470f442003-07-28 09:56:35 +00008171static int evalbltin(const struct builtincmd *, int, char **);
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008172static void prehash(union node *);
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00008173
Eric Andersen62483552001-07-10 06:09:16 +00008174/*
Eric Andersenc470f442003-07-28 09:56:35 +00008175 * Evaluate a parse tree. The value is left in the global variable
8176 * exitstatus.
Eric Andersen62483552001-07-10 06:09:16 +00008177 */
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008178static void
Eric Andersenc470f442003-07-28 09:56:35 +00008179evaltree(union node *n, int flags)
Eric Andersen62483552001-07-10 06:09:16 +00008180{
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008181 struct jmploc *volatile savehandler = exception_handler;
8182 struct jmploc jmploc;
Eric Andersenc470f442003-07-28 09:56:35 +00008183 int checkexit = 0;
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008184 void (*evalfn)(union node *, int);
Eric Andersenc470f442003-07-28 09:56:35 +00008185 int status;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008186 int int_level;
8187
8188 SAVE_INT(int_level);
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008189
Eric Andersenc470f442003-07-28 09:56:35 +00008190 if (n == NULL) {
8191 TRACE(("evaltree(NULL) called\n"));
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008192 goto out1;
Eric Andersen62483552001-07-10 06:09:16 +00008193 }
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008194 TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008195
8196 exception_handler = &jmploc;
8197 {
8198 int err = setjmp(jmploc.loc);
8199 if (err) {
8200 /* if it was a signal, check for trap handlers */
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008201 if (exception_type == EXSIG) {
Denis Vlasenkob21f3792009-03-19 23:09:58 +00008202 TRACE(("exception %d (EXSIG) in evaltree, err=%d\n",
8203 exception_type, err));
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008204 goto out;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008205 }
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008206 /* continue on the way out */
Denis Vlasenkob21f3792009-03-19 23:09:58 +00008207 TRACE(("exception %d in evaltree, propagating err=%d\n",
8208 exception_type, err));
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008209 exception_handler = savehandler;
8210 longjmp(exception_handler->loc, err);
8211 }
8212 }
8213
Eric Andersenc470f442003-07-28 09:56:35 +00008214 switch (n->type) {
8215 default:
Denis Vlasenkoa7189f02006-11-17 20:29:00 +00008216#if DEBUG
Eric Andersenc470f442003-07-28 09:56:35 +00008217 out1fmt("Node type = %d\n", n->type);
Denys Vlasenko8131eea2009-11-02 14:19:51 +01008218 fflush_all();
Eric Andersenc470f442003-07-28 09:56:35 +00008219 break;
8220#endif
8221 case NNOT:
8222 evaltree(n->nnot.com, EV_TESTED);
8223 status = !exitstatus;
8224 goto setstatus;
8225 case NREDIR:
8226 expredir(n->nredir.redirect);
8227 status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
8228 if (!status) {
8229 evaltree(n->nredir.n, flags & EV_TESTED);
8230 status = exitstatus;
8231 }
Denis Vlasenko34c73c42008-08-16 11:48:02 +00008232 popredir(/*drop:*/ 0, /*restore:*/ 0 /* not sure */);
Eric Andersenc470f442003-07-28 09:56:35 +00008233 goto setstatus;
8234 case NCMD:
8235 evalfn = evalcommand;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008236 checkexit:
Eric Andersenc470f442003-07-28 09:56:35 +00008237 if (eflag && !(flags & EV_TESTED))
8238 checkexit = ~0;
8239 goto calleval;
8240 case NFOR:
8241 evalfn = evalfor;
8242 goto calleval;
8243 case NWHILE:
8244 case NUNTIL:
8245 evalfn = evalloop;
8246 goto calleval;
8247 case NSUBSHELL:
8248 case NBACKGND:
8249 evalfn = evalsubshell;
8250 goto calleval;
8251 case NPIPE:
8252 evalfn = evalpipe;
8253 goto checkexit;
8254 case NCASE:
8255 evalfn = evalcase;
8256 goto calleval;
8257 case NAND:
8258 case NOR:
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008259 case NSEMI: {
8260
Eric Andersenc470f442003-07-28 09:56:35 +00008261#if NAND + 1 != NOR
8262#error NAND + 1 != NOR
8263#endif
8264#if NOR + 1 != NSEMI
8265#error NOR + 1 != NSEMI
8266#endif
Denis Vlasenko87d5fd92008-07-26 13:48:35 +00008267 unsigned is_or = n->type - NAND;
Eric Andersenc470f442003-07-28 09:56:35 +00008268 evaltree(
8269 n->nbinary.ch1,
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008270 (flags | ((is_or >> 1) - 1)) & EV_TESTED
Eric Andersenc470f442003-07-28 09:56:35 +00008271 );
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008272 if (!exitstatus == is_or)
Eric Andersenc470f442003-07-28 09:56:35 +00008273 break;
8274 if (!evalskip) {
8275 n = n->nbinary.ch2;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008276 evaln:
Eric Andersenc470f442003-07-28 09:56:35 +00008277 evalfn = evaltree;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008278 calleval:
Eric Andersenc470f442003-07-28 09:56:35 +00008279 evalfn(n, flags);
8280 break;
8281 }
8282 break;
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008283 }
Eric Andersenc470f442003-07-28 09:56:35 +00008284 case NIF:
8285 evaltree(n->nif.test, EV_TESTED);
8286 if (evalskip)
8287 break;
8288 if (exitstatus == 0) {
8289 n = n->nif.ifpart;
8290 goto evaln;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008291 }
8292 if (n->nif.elsepart) {
Eric Andersenc470f442003-07-28 09:56:35 +00008293 n = n->nif.elsepart;
8294 goto evaln;
8295 }
8296 goto success;
8297 case NDEFUN:
8298 defun(n->narg.text, n->narg.next);
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008299 success:
Eric Andersenc470f442003-07-28 09:56:35 +00008300 status = 0;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008301 setstatus:
Eric Andersenc470f442003-07-28 09:56:35 +00008302 exitstatus = status;
8303 break;
8304 }
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008305
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008306 out:
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008307 exception_handler = savehandler;
8308 out1:
8309 if (checkexit & exitstatus)
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00008310 evalskip |= SKIPEVAL;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02008311 else if (pending_sig && dotrap())
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00008312 goto exexit;
8313
8314 if (flags & EV_EXIT) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008315 exexit:
Denis Vlasenkob012b102007-02-19 22:43:01 +00008316 raise_exception(EXEXIT);
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00008317 }
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008318
8319 RESTORE_INT(int_level);
8320 TRACE(("leaving evaltree (no interrupts)\n"));
Eric Andersen62483552001-07-10 06:09:16 +00008321}
8322
Eric Andersenc470f442003-07-28 09:56:35 +00008323#if !defined(__alpha__) || (defined(__GNUC__) && __GNUC__ >= 3)
8324static
8325#endif
8326void evaltreenr(union node *, int) __attribute__ ((alias("evaltree"),__noreturn__));
8327
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008328static void
Eric Andersenc470f442003-07-28 09:56:35 +00008329evalloop(union node *n, int flags)
Eric Andersencb57d552001-06-28 07:25:16 +00008330{
8331 int status;
8332
8333 loopnest++;
8334 status = 0;
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008335 flags &= EV_TESTED;
Eric Andersencb57d552001-06-28 07:25:16 +00008336 for (;;) {
Eric Andersenc470f442003-07-28 09:56:35 +00008337 int i;
8338
Eric Andersencb57d552001-06-28 07:25:16 +00008339 evaltree(n->nbinary.ch1, EV_TESTED);
8340 if (evalskip) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008341 skipping:
8342 if (evalskip == SKIPCONT && --skipcount <= 0) {
Eric Andersencb57d552001-06-28 07:25:16 +00008343 evalskip = 0;
8344 continue;
8345 }
8346 if (evalskip == SKIPBREAK && --skipcount <= 0)
8347 evalskip = 0;
8348 break;
8349 }
Eric Andersenc470f442003-07-28 09:56:35 +00008350 i = exitstatus;
8351 if (n->type != NWHILE)
8352 i = !i;
8353 if (i != 0)
8354 break;
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008355 evaltree(n->nbinary.ch2, flags);
Eric Andersencb57d552001-06-28 07:25:16 +00008356 status = exitstatus;
8357 if (evalskip)
8358 goto skipping;
8359 }
8360 loopnest--;
8361 exitstatus = status;
8362}
8363
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008364static void
Eric Andersenc470f442003-07-28 09:56:35 +00008365evalfor(union node *n, int flags)
Eric Andersencb57d552001-06-28 07:25:16 +00008366{
8367 struct arglist arglist;
8368 union node *argp;
8369 struct strlist *sp;
8370 struct stackmark smark;
8371
8372 setstackmark(&smark);
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00008373 arglist.list = NULL;
Eric Andersencb57d552001-06-28 07:25:16 +00008374 arglist.lastp = &arglist.list;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008375 for (argp = n->nfor.args; argp; argp = argp->narg.next) {
Eric Andersencb57d552001-06-28 07:25:16 +00008376 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE | EXP_RECORD);
Eric Andersenc470f442003-07-28 09:56:35 +00008377 /* XXX */
Eric Andersencb57d552001-06-28 07:25:16 +00008378 if (evalskip)
8379 goto out;
8380 }
8381 *arglist.lastp = NULL;
8382
8383 exitstatus = 0;
8384 loopnest++;
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008385 flags &= EV_TESTED;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008386 for (sp = arglist.list; sp; sp = sp->next) {
Eric Andersencb57d552001-06-28 07:25:16 +00008387 setvar(n->nfor.var, sp->text, 0);
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008388 evaltree(n->nfor.body, flags);
Eric Andersencb57d552001-06-28 07:25:16 +00008389 if (evalskip) {
8390 if (evalskip == SKIPCONT && --skipcount <= 0) {
8391 evalskip = 0;
8392 continue;
8393 }
8394 if (evalskip == SKIPBREAK && --skipcount <= 0)
8395 evalskip = 0;
8396 break;
8397 }
8398 }
8399 loopnest--;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008400 out:
Eric Andersencb57d552001-06-28 07:25:16 +00008401 popstackmark(&smark);
8402}
8403
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008404static void
Eric Andersenc470f442003-07-28 09:56:35 +00008405evalcase(union node *n, int flags)
Eric Andersencb57d552001-06-28 07:25:16 +00008406{
8407 union node *cp;
8408 union node *patp;
8409 struct arglist arglist;
8410 struct stackmark smark;
8411
8412 setstackmark(&smark);
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00008413 arglist.list = NULL;
Eric Andersencb57d552001-06-28 07:25:16 +00008414 arglist.lastp = &arglist.list;
Eric Andersencb57d552001-06-28 07:25:16 +00008415 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
Eric Andersenc470f442003-07-28 09:56:35 +00008416 exitstatus = 0;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008417 for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
8418 for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
Eric Andersencb57d552001-06-28 07:25:16 +00008419 if (casematch(patp, arglist.list->text)) {
8420 if (evalskip == 0) {
8421 evaltree(cp->nclist.body, flags);
8422 }
8423 goto out;
8424 }
8425 }
8426 }
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008427 out:
Eric Andersencb57d552001-06-28 07:25:16 +00008428 popstackmark(&smark);
8429}
8430
Eric Andersenc470f442003-07-28 09:56:35 +00008431/*
8432 * Kick off a subshell to evaluate a tree.
8433 */
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008434static void
Eric Andersenc470f442003-07-28 09:56:35 +00008435evalsubshell(union node *n, int flags)
8436{
8437 struct job *jp;
8438 int backgnd = (n->type == NBACKGND);
8439 int status;
8440
8441 expredir(n->nredir.redirect);
Denys Vlasenko238bf182010-05-18 15:49:07 +02008442 if (!backgnd && (flags & EV_EXIT) && !may_have_traps)
Eric Andersenc470f442003-07-28 09:56:35 +00008443 goto nofork;
Denis Vlasenkob012b102007-02-19 22:43:01 +00008444 INT_OFF;
Denis Vlasenko68404f12008-03-17 09:00:54 +00008445 jp = makejob(/*n,*/ 1);
Eric Andersenc470f442003-07-28 09:56:35 +00008446 if (forkshell(jp, n, backgnd) == 0) {
Denys Vlasenko238bf182010-05-18 15:49:07 +02008447 /* child */
Denis Vlasenkob012b102007-02-19 22:43:01 +00008448 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00008449 flags |= EV_EXIT;
8450 if (backgnd)
Denys Vlasenko238bf182010-05-18 15:49:07 +02008451 flags &= ~EV_TESTED;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00008452 nofork:
Eric Andersenc470f442003-07-28 09:56:35 +00008453 redirect(n->nredir.redirect, 0);
8454 evaltreenr(n->nredir.n, flags);
8455 /* never returns */
8456 }
8457 status = 0;
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00008458 if (!backgnd)
Eric Andersenc470f442003-07-28 09:56:35 +00008459 status = waitforjob(jp);
8460 exitstatus = status;
Denis Vlasenkob012b102007-02-19 22:43:01 +00008461 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00008462}
8463
Eric Andersenc470f442003-07-28 09:56:35 +00008464/*
8465 * Compute the names of the files in a redirection list.
8466 */
Denis Vlasenko99eb8502007-02-23 21:09:49 +00008467static void fixredir(union node *, const char *, int);
Eric Andersenc470f442003-07-28 09:56:35 +00008468static void
8469expredir(union node *n)
8470{
8471 union node *redir;
8472
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008473 for (redir = n; redir; redir = redir->nfile.next) {
Eric Andersenc470f442003-07-28 09:56:35 +00008474 struct arglist fn;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008475
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00008476 fn.list = NULL;
Eric Andersenc470f442003-07-28 09:56:35 +00008477 fn.lastp = &fn.list;
8478 switch (redir->type) {
8479 case NFROMTO:
8480 case NFROM:
8481 case NTO:
Denis Vlasenko559691a2008-10-05 18:39:31 +00008482#if ENABLE_ASH_BASH_COMPAT
8483 case NTO2:
8484#endif
Eric Andersenc470f442003-07-28 09:56:35 +00008485 case NCLOBBER:
8486 case NAPPEND:
8487 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
Denis Vlasenko559691a2008-10-05 18:39:31 +00008488#if ENABLE_ASH_BASH_COMPAT
8489 store_expfname:
8490#endif
Eric Andersenc470f442003-07-28 09:56:35 +00008491 redir->nfile.expfname = fn.list->text;
8492 break;
8493 case NFROMFD:
Denis Vlasenko559691a2008-10-05 18:39:31 +00008494 case NTOFD: /* >& */
Eric Andersenc470f442003-07-28 09:56:35 +00008495 if (redir->ndup.vname) {
8496 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008497 if (fn.list == NULL)
Denis Vlasenkob012b102007-02-19 22:43:01 +00008498 ash_msg_and_raise_error("redir error");
Denis Vlasenko559691a2008-10-05 18:39:31 +00008499#if ENABLE_ASH_BASH_COMPAT
8500//FIXME: we used expandarg with different args!
8501 if (!isdigit_str9(fn.list->text)) {
8502 /* >&file, not >&fd */
8503 if (redir->nfile.fd != 1) /* 123>&file - BAD */
8504 ash_msg_and_raise_error("redir error");
8505 redir->type = NTO2;
8506 goto store_expfname;
8507 }
8508#endif
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008509 fixredir(redir, fn.list->text, 1);
Eric Andersenc470f442003-07-28 09:56:35 +00008510 }
8511 break;
8512 }
8513 }
8514}
8515
Eric Andersencb57d552001-06-28 07:25:16 +00008516/*
Eric Andersencb57d552001-06-28 07:25:16 +00008517 * Evaluate a pipeline. All the processes in the pipeline are children
8518 * of the process creating the pipeline. (This differs from some versions
8519 * of the shell, which make the last process in a pipeline the parent
8520 * of all the rest.)
8521 */
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008522static void
Eric Andersenc470f442003-07-28 09:56:35 +00008523evalpipe(union node *n, int flags)
Eric Andersencb57d552001-06-28 07:25:16 +00008524{
8525 struct job *jp;
8526 struct nodelist *lp;
8527 int pipelen;
8528 int prevfd;
8529 int pip[2];
8530
Eric Andersenc470f442003-07-28 09:56:35 +00008531 TRACE(("evalpipe(0x%lx) called\n", (long)n));
Eric Andersencb57d552001-06-28 07:25:16 +00008532 pipelen = 0;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008533 for (lp = n->npipe.cmdlist; lp; lp = lp->next)
Eric Andersencb57d552001-06-28 07:25:16 +00008534 pipelen++;
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008535 flags |= EV_EXIT;
Denis Vlasenkob012b102007-02-19 22:43:01 +00008536 INT_OFF;
Denis Vlasenko68404f12008-03-17 09:00:54 +00008537 jp = makejob(/*n,*/ pipelen);
Eric Andersencb57d552001-06-28 07:25:16 +00008538 prevfd = -1;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008539 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008540 prehash(lp->n);
Eric Andersencb57d552001-06-28 07:25:16 +00008541 pip[1] = -1;
8542 if (lp->next) {
8543 if (pipe(pip) < 0) {
8544 close(prevfd);
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00008545 ash_msg_and_raise_error("pipe call failed");
Eric Andersencb57d552001-06-28 07:25:16 +00008546 }
8547 }
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00008548 if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
Denis Vlasenkob012b102007-02-19 22:43:01 +00008549 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00008550 if (pip[1] >= 0) {
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008551 close(pip[0]);
Eric Andersencb57d552001-06-28 07:25:16 +00008552 }
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008553 if (prevfd > 0) {
8554 dup2(prevfd, 0);
8555 close(prevfd);
8556 }
8557 if (pip[1] > 1) {
8558 dup2(pip[1], 1);
8559 close(pip[1]);
8560 }
Eric Andersenc470f442003-07-28 09:56:35 +00008561 evaltreenr(lp->n, flags);
8562 /* never returns */
Eric Andersencb57d552001-06-28 07:25:16 +00008563 }
8564 if (prevfd >= 0)
8565 close(prevfd);
8566 prevfd = pip[0];
Denis Vlasenkob9e70dd2009-03-20 01:24:08 +00008567 /* Don't want to trigger debugging */
8568 if (pip[1] != -1)
8569 close(pip[1]);
Eric Andersencb57d552001-06-28 07:25:16 +00008570 }
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00008571 if (n->npipe.pipe_backgnd == 0) {
Eric Andersencb57d552001-06-28 07:25:16 +00008572 exitstatus = waitforjob(jp);
8573 TRACE(("evalpipe: job done exit status %d\n", exitstatus));
Eric Andersencb57d552001-06-28 07:25:16 +00008574 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00008575 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00008576}
8577
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008578/*
8579 * Controls whether the shell is interactive or not.
8580 */
8581static void
8582setinteractive(int on)
8583{
Denis Vlasenkob07a4962008-06-22 13:16:23 +00008584 static smallint is_interactive;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008585
8586 if (++on == is_interactive)
8587 return;
8588 is_interactive = on;
8589 setsignal(SIGINT);
8590 setsignal(SIGQUIT);
8591 setsignal(SIGTERM);
8592#if !ENABLE_FEATURE_SH_EXTRA_QUIET
8593 if (is_interactive > 1) {
8594 /* Looks like they want an interactive shell */
Denis Vlasenkoca525b42007-06-13 12:27:17 +00008595 static smallint did_banner;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008596
Denis Vlasenkoca525b42007-06-13 12:27:17 +00008597 if (!did_banner) {
Denys Vlasenkoc34c0332009-09-29 12:25:30 +02008598 /* note: ash and hush share this string */
8599 out1fmt("\n\n%s %s\n"
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008600 "Enter 'help' for a list of built-in commands."
8601 "\n\n",
Denys Vlasenkoc34c0332009-09-29 12:25:30 +02008602 bb_banner,
8603 "built-in shell (ash)"
8604 );
Denis Vlasenkoca525b42007-06-13 12:27:17 +00008605 did_banner = 1;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008606 }
8607 }
8608#endif
8609}
8610
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008611static void
8612optschanged(void)
8613{
8614#if DEBUG
8615 opentrace();
8616#endif
8617 setinteractive(iflag);
8618 setjobctl(mflag);
Denis Vlasenkob07a4962008-06-22 13:16:23 +00008619#if ENABLE_FEATURE_EDITING_VI
8620 if (viflag)
8621 line_input_state->flags |= VI_MODE;
8622 else
8623 line_input_state->flags &= ~VI_MODE;
8624#else
8625 viflag = 0; /* forcibly keep the option off */
8626#endif
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008627}
8628
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008629static struct localvar *localvars;
8630
8631/*
8632 * Called after a function returns.
8633 * Interrupts must be off.
8634 */
8635static void
8636poplocalvars(void)
8637{
8638 struct localvar *lvp;
8639 struct var *vp;
8640
8641 while ((lvp = localvars) != NULL) {
8642 localvars = lvp->next;
8643 vp = lvp->vp;
Denys Vlasenko883cea42009-07-11 15:31:59 +02008644 TRACE(("poplocalvar %s\n", vp ? vp->text : "-"));
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008645 if (vp == NULL) { /* $- saved */
8646 memcpy(optlist, lvp->text, sizeof(optlist));
8647 free((char*)lvp->text);
8648 optschanged();
8649 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02008650 unsetvar(vp->var_text);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008651 } else {
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02008652 if (vp->var_func)
8653 vp->var_func(var_end(lvp->text));
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008654 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02008655 free((char*)vp->var_text);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008656 vp->flags = lvp->flags;
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02008657 vp->var_text = lvp->text;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008658 }
8659 free(lvp);
8660 }
8661}
8662
8663static int
8664evalfun(struct funcnode *func, int argc, char **argv, int flags)
8665{
8666 volatile struct shparam saveparam;
8667 struct localvar *volatile savelocalvars;
8668 struct jmploc *volatile savehandler;
8669 struct jmploc jmploc;
8670 int e;
8671
8672 saveparam = shellparam;
8673 savelocalvars = localvars;
8674 e = setjmp(jmploc.loc);
8675 if (e) {
8676 goto funcdone;
8677 }
8678 INT_OFF;
8679 savehandler = exception_handler;
8680 exception_handler = &jmploc;
8681 localvars = NULL;
Denis Vlasenko01631112007-12-16 17:20:38 +00008682 shellparam.malloced = 0;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008683 func->count++;
8684 funcnest++;
8685 INT_ON;
8686 shellparam.nparam = argc - 1;
8687 shellparam.p = argv + 1;
8688#if ENABLE_ASH_GETOPTS
8689 shellparam.optind = 1;
8690 shellparam.optoff = -1;
8691#endif
8692 evaltree(&func->n, flags & EV_TESTED);
Denis Vlasenko01631112007-12-16 17:20:38 +00008693 funcdone:
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008694 INT_OFF;
8695 funcnest--;
8696 freefunc(func);
8697 poplocalvars();
8698 localvars = savelocalvars;
8699 freeparam(&shellparam);
8700 shellparam = saveparam;
8701 exception_handler = savehandler;
8702 INT_ON;
8703 evalskip &= ~SKIPFUNC;
8704 return e;
8705}
8706
Denis Vlasenko131ae172007-02-18 13:00:19 +00008707#if ENABLE_ASH_CMDCMD
Denis Vlasenkoaa744452007-02-23 01:04:22 +00008708static char **
8709parse_command_args(char **argv, const char **path)
Eric Andersenc470f442003-07-28 09:56:35 +00008710{
8711 char *cp, c;
8712
8713 for (;;) {
8714 cp = *++argv;
8715 if (!cp)
8716 return 0;
8717 if (*cp++ != '-')
8718 break;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008719 c = *cp++;
8720 if (!c)
Eric Andersenc470f442003-07-28 09:56:35 +00008721 break;
8722 if (c == '-' && !*cp) {
8723 argv++;
8724 break;
8725 }
8726 do {
8727 switch (c) {
8728 case 'p':
Denis Vlasenkof5f75c52007-06-12 22:35:19 +00008729 *path = bb_default_path;
Eric Andersenc470f442003-07-28 09:56:35 +00008730 break;
8731 default:
8732 /* run 'typecmd' for other options */
8733 return 0;
8734 }
Denis Vlasenko9650f362007-02-23 01:04:37 +00008735 c = *cp++;
8736 } while (c);
Eric Andersenc470f442003-07-28 09:56:35 +00008737 }
8738 return argv;
8739}
8740#endif
8741
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008742/*
8743 * Make a variable a local variable. When a variable is made local, it's
8744 * value and flags are saved in a localvar structure. The saved values
8745 * will be restored when the shell function returns. We handle the name
8746 * "-" as a special case.
8747 */
8748static void
8749mklocal(char *name)
8750{
8751 struct localvar *lvp;
8752 struct var **vpp;
8753 struct var *vp;
8754
8755 INT_OFF;
Denis Vlasenko838ffd52008-02-21 04:32:08 +00008756 lvp = ckzalloc(sizeof(struct localvar));
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008757 if (LONE_DASH(name)) {
8758 char *p;
8759 p = ckmalloc(sizeof(optlist));
8760 lvp->text = memcpy(p, optlist, sizeof(optlist));
8761 vp = NULL;
8762 } else {
8763 char *eq;
8764
8765 vpp = hashvar(name);
8766 vp = *findvar(vpp, name);
8767 eq = strchr(name, '=');
8768 if (vp == NULL) {
8769 if (eq)
8770 setvareq(name, VSTRFIXED);
8771 else
8772 setvar(name, NULL, VSTRFIXED);
8773 vp = *vpp; /* the new variable */
8774 lvp->flags = VUNSET;
8775 } else {
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02008776 lvp->text = vp->var_text;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008777 lvp->flags = vp->flags;
8778 vp->flags |= VSTRFIXED|VTEXTFIXED;
8779 if (eq)
8780 setvareq(name, 0);
8781 }
8782 }
8783 lvp->vp = vp;
8784 lvp->next = localvars;
8785 localvars = lvp;
8786 INT_ON;
8787}
8788
8789/*
8790 * The "local" command.
8791 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008792static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008793localcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008794{
8795 char *name;
8796
8797 argv = argptr;
8798 while ((name = *argv++) != NULL) {
8799 mklocal(name);
8800 }
8801 return 0;
8802}
8803
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008804static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008805falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008806{
8807 return 1;
8808}
8809
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008810static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008811truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008812{
8813 return 0;
8814}
8815
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008816static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008817execcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008818{
Denis Vlasenko68404f12008-03-17 09:00:54 +00008819 if (argv[1]) {
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008820 iflag = 0; /* exit on error */
8821 mflag = 0;
8822 optschanged();
8823 shellexec(argv + 1, pathval(), 0);
8824 }
8825 return 0;
8826}
8827
8828/*
8829 * The return command.
8830 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008831static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008832returncmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008833{
8834 /*
8835 * If called outside a function, do what ksh does;
8836 * skip the rest of the file.
8837 */
8838 evalskip = funcnest ? SKIPFUNC : SKIPFILE;
8839 return argv[1] ? number(argv[1]) : exitstatus;
8840}
8841
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008842/* Forward declarations for builtintab[] */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008843static int breakcmd(int, char **) FAST_FUNC;
8844static int dotcmd(int, char **) FAST_FUNC;
8845static int evalcmd(int, char **) FAST_FUNC;
8846static int exitcmd(int, char **) FAST_FUNC;
8847static int exportcmd(int, char **) FAST_FUNC;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008848#if ENABLE_ASH_GETOPTS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008849static int getoptscmd(int, char **) FAST_FUNC;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008850#endif
Denis Vlasenko52764022007-02-24 13:42:56 +00008851#if !ENABLE_FEATURE_SH_EXTRA_QUIET
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008852static int helpcmd(int, char **) FAST_FUNC;
Denis Vlasenko52764022007-02-24 13:42:56 +00008853#endif
Mike Frysinger98c52642009-04-02 10:02:37 +00008854#if ENABLE_SH_MATH_SUPPORT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008855static int letcmd(int, char **) FAST_FUNC;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008856#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008857static int readcmd(int, char **) FAST_FUNC;
8858static int setcmd(int, char **) FAST_FUNC;
8859static int shiftcmd(int, char **) FAST_FUNC;
8860static int timescmd(int, char **) FAST_FUNC;
8861static int trapcmd(int, char **) FAST_FUNC;
8862static int umaskcmd(int, char **) FAST_FUNC;
8863static int unsetcmd(int, char **) FAST_FUNC;
8864static int ulimitcmd(int, char **) FAST_FUNC;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008865
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008866#define BUILTIN_NOSPEC "0"
8867#define BUILTIN_SPECIAL "1"
8868#define BUILTIN_REGULAR "2"
8869#define BUILTIN_SPEC_REG "3"
8870#define BUILTIN_ASSIGN "4"
8871#define BUILTIN_SPEC_ASSG "5"
8872#define BUILTIN_REG_ASSG "6"
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008873#define BUILTIN_SPEC_REG_ASSG "7"
8874
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008875/* Stubs for calling non-FAST_FUNC's */
Denys Vlasenko2634bf32009-06-09 18:40:07 +02008876#if ENABLE_ASH_BUILTIN_ECHO
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008877static int FAST_FUNC echocmd(int argc, char **argv) { return echo_main(argc, argv); }
Denys Vlasenko2634bf32009-06-09 18:40:07 +02008878#endif
8879#if ENABLE_ASH_BUILTIN_PRINTF
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008880static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
Denys Vlasenko2634bf32009-06-09 18:40:07 +02008881#endif
8882#if ENABLE_ASH_BUILTIN_TEST
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008883static int FAST_FUNC testcmd(int argc, char **argv) { return test_main(argc, argv); }
Denys Vlasenko2634bf32009-06-09 18:40:07 +02008884#endif
Denis Vlasenko468aea22008-04-01 14:47:57 +00008885
Denis Vlasenkof7d56652008-03-25 05:51:41 +00008886/* Keep these in proper order since it is searched via bsearch() */
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008887static const struct builtincmd builtintab[] = {
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008888 { BUILTIN_SPEC_REG "." , dotcmd },
8889 { BUILTIN_SPEC_REG ":" , truecmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008890#if ENABLE_ASH_BUILTIN_TEST
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008891 { BUILTIN_REGULAR "[" , testcmd },
Denis Vlasenko80591b02008-03-25 07:49:43 +00008892#if ENABLE_ASH_BASH_COMPAT
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008893 { BUILTIN_REGULAR "[[" , testcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008894#endif
Denis Vlasenko80591b02008-03-25 07:49:43 +00008895#endif
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008896#if ENABLE_ASH_ALIAS
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008897 { BUILTIN_REG_ASSG "alias" , aliascmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008898#endif
8899#if JOBS
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008900 { BUILTIN_REGULAR "bg" , fg_bgcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008901#endif
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008902 { BUILTIN_SPEC_REG "break" , breakcmd },
8903 { BUILTIN_REGULAR "cd" , cdcmd },
8904 { BUILTIN_NOSPEC "chdir" , cdcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008905#if ENABLE_ASH_CMDCMD
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008906 { BUILTIN_REGULAR "command" , commandcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008907#endif
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008908 { BUILTIN_SPEC_REG "continue", breakcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008909#if ENABLE_ASH_BUILTIN_ECHO
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008910 { BUILTIN_REGULAR "echo" , echocmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008911#endif
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008912 { BUILTIN_SPEC_REG "eval" , evalcmd },
8913 { BUILTIN_SPEC_REG "exec" , execcmd },
8914 { BUILTIN_SPEC_REG "exit" , exitcmd },
8915 { BUILTIN_SPEC_REG_ASSG "export" , exportcmd },
8916 { BUILTIN_REGULAR "false" , falsecmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008917#if JOBS
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008918 { BUILTIN_REGULAR "fg" , fg_bgcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008919#endif
8920#if ENABLE_ASH_GETOPTS
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008921 { BUILTIN_REGULAR "getopts" , getoptscmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008922#endif
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008923 { BUILTIN_NOSPEC "hash" , hashcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008924#if !ENABLE_FEATURE_SH_EXTRA_QUIET
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008925 { BUILTIN_NOSPEC "help" , helpcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008926#endif
8927#if JOBS
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008928 { BUILTIN_REGULAR "jobs" , jobscmd },
8929 { BUILTIN_REGULAR "kill" , killcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008930#endif
Mike Frysinger98c52642009-04-02 10:02:37 +00008931#if ENABLE_SH_MATH_SUPPORT
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008932 { BUILTIN_NOSPEC "let" , letcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008933#endif
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008934 { BUILTIN_ASSIGN "local" , localcmd },
Denis Vlasenkocd2663f2008-06-01 22:36:39 +00008935#if ENABLE_ASH_BUILTIN_PRINTF
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008936 { BUILTIN_REGULAR "printf" , printfcmd },
Denis Vlasenkocd2663f2008-06-01 22:36:39 +00008937#endif
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008938 { BUILTIN_NOSPEC "pwd" , pwdcmd },
8939 { BUILTIN_REGULAR "read" , readcmd },
8940 { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
8941 { BUILTIN_SPEC_REG "return" , returncmd },
8942 { BUILTIN_SPEC_REG "set" , setcmd },
8943 { BUILTIN_SPEC_REG "shift" , shiftcmd },
Denys Vlasenko82731b42010-05-17 17:49:52 +02008944#if ENABLE_ASH_BASH_COMPAT
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008945 { BUILTIN_SPEC_REG "source" , dotcmd },
Denys Vlasenko82731b42010-05-17 17:49:52 +02008946#endif
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008947#if ENABLE_ASH_BUILTIN_TEST
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008948 { BUILTIN_REGULAR "test" , testcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008949#endif
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008950 { BUILTIN_SPEC_REG "times" , timescmd },
8951 { BUILTIN_SPEC_REG "trap" , trapcmd },
8952 { BUILTIN_REGULAR "true" , truecmd },
8953 { BUILTIN_NOSPEC "type" , typecmd },
8954 { BUILTIN_NOSPEC "ulimit" , ulimitcmd },
8955 { BUILTIN_REGULAR "umask" , umaskcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008956#if ENABLE_ASH_ALIAS
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008957 { BUILTIN_REGULAR "unalias" , unaliascmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008958#endif
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008959 { BUILTIN_SPEC_REG "unset" , unsetcmd },
8960 { BUILTIN_REGULAR "wait" , waitcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008961};
8962
Denis Vlasenko80591b02008-03-25 07:49:43 +00008963/* Should match the above table! */
8964#define COMMANDCMD (builtintab + \
8965 2 + \
8966 1 * ENABLE_ASH_BUILTIN_TEST + \
8967 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
8968 1 * ENABLE_ASH_ALIAS + \
8969 1 * ENABLE_ASH_JOB_CONTROL + \
8970 3)
8971#define EXECCMD (builtintab + \
8972 2 + \
8973 1 * ENABLE_ASH_BUILTIN_TEST + \
8974 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
8975 1 * ENABLE_ASH_ALIAS + \
8976 1 * ENABLE_ASH_JOB_CONTROL + \
8977 3 + \
8978 1 * ENABLE_ASH_CMDCMD + \
8979 1 + \
8980 ENABLE_ASH_BUILTIN_ECHO + \
8981 1)
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008982
8983/*
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008984 * Search the table of builtin commands.
8985 */
8986static struct builtincmd *
8987find_builtin(const char *name)
8988{
8989 struct builtincmd *bp;
8990
8991 bp = bsearch(
Denis Vlasenko80b8b392007-06-25 10:55:35 +00008992 name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008993 pstrcmp
8994 );
8995 return bp;
8996}
8997
8998/*
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008999 * Execute a simple command.
9000 */
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00009001static int
9002isassignment(const char *p)
Paul Foxc3850c82005-07-20 18:23:39 +00009003{
9004 const char *q = endofname(p);
9005 if (p == q)
9006 return 0;
9007 return *q == '=';
9008}
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009009static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00009010bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00009011{
9012 /* Preserve exitstatus of a previous possible redirection
9013 * as POSIX mandates */
9014 return back_exitstatus;
9015}
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02009016static void
Eric Andersenc470f442003-07-28 09:56:35 +00009017evalcommand(union node *cmd, int flags)
9018{
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00009019 static const struct builtincmd null_bltin = {
9020 "\0\0", bltincmd /* why three NULs? */
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00009021 };
Eric Andersenc470f442003-07-28 09:56:35 +00009022 struct stackmark smark;
9023 union node *argp;
9024 struct arglist arglist;
9025 struct arglist varlist;
9026 char **argv;
9027 int argc;
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009028 const struct strlist *sp;
Eric Andersenc470f442003-07-28 09:56:35 +00009029 struct cmdentry cmdentry;
9030 struct job *jp;
9031 char *lastarg;
9032 const char *path;
9033 int spclbltin;
Eric Andersenc470f442003-07-28 09:56:35 +00009034 int status;
9035 char **nargv;
Paul Foxc3850c82005-07-20 18:23:39 +00009036 struct builtincmd *bcmd;
Denis Vlasenko34c73c42008-08-16 11:48:02 +00009037 smallint cmd_is_exec;
9038 smallint pseudovarflag = 0;
Eric Andersenc470f442003-07-28 09:56:35 +00009039
9040 /* First expand the arguments. */
9041 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
9042 setstackmark(&smark);
9043 back_exitstatus = 0;
9044
9045 cmdentry.cmdtype = CMDBUILTIN;
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00009046 cmdentry.u.cmd = &null_bltin;
Eric Andersenc470f442003-07-28 09:56:35 +00009047 varlist.lastp = &varlist.list;
9048 *varlist.lastp = NULL;
9049 arglist.lastp = &arglist.list;
9050 *arglist.lastp = NULL;
9051
9052 argc = 0;
Denis Vlasenkob012b102007-02-19 22:43:01 +00009053 if (cmd->ncmd.args) {
Paul Foxc3850c82005-07-20 18:23:39 +00009054 bcmd = find_builtin(cmd->ncmd.args->narg.text);
9055 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
9056 }
9057
Eric Andersenc470f442003-07-28 09:56:35 +00009058 for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
9059 struct strlist **spp;
9060
9061 spp = arglist.lastp;
"Vladimir N. Oleynik"bef14d72005-09-05 13:25:11 +00009062 if (pseudovarflag && isassignment(argp->narg.text))
Paul Foxc3850c82005-07-20 18:23:39 +00009063 expandarg(argp, &arglist, EXP_VARTILDE);
9064 else
9065 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
9066
Eric Andersenc470f442003-07-28 09:56:35 +00009067 for (sp = *spp; sp; sp = sp->next)
9068 argc++;
9069 }
9070
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +00009071 argv = nargv = stalloc(sizeof(char *) * (argc + 1));
Denis Vlasenko2da584f2007-02-19 22:44:05 +00009072 for (sp = arglist.list; sp; sp = sp->next) {
Eric Andersenc470f442003-07-28 09:56:35 +00009073 TRACE(("evalcommand arg: %s\n", sp->text));
9074 *nargv++ = sp->text;
9075 }
9076 *nargv = NULL;
9077
9078 lastarg = NULL;
9079 if (iflag && funcnest == 0 && argc > 0)
9080 lastarg = nargv[-1];
9081
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009082 preverrout_fd = 2;
Eric Andersenc470f442003-07-28 09:56:35 +00009083 expredir(cmd->ncmd.redirect);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009084 status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
Eric Andersenc470f442003-07-28 09:56:35 +00009085
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02009086 path = vpath.var_text;
Eric Andersenc470f442003-07-28 09:56:35 +00009087 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
9088 struct strlist **spp;
9089 char *p;
9090
9091 spp = varlist.lastp;
9092 expandarg(argp, &varlist, EXP_VARTILDE);
9093
9094 /*
9095 * Modify the command lookup path, if a PATH= assignment
9096 * is present
9097 */
9098 p = (*spp)->text;
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02009099 if (varcmp(p, path) == 0)
Eric Andersenc470f442003-07-28 09:56:35 +00009100 path = p;
9101 }
9102
9103 /* Print the command if xflag is set. */
9104 if (xflag) {
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009105 int n;
9106 const char *p = " %s";
Eric Andersenc470f442003-07-28 09:56:35 +00009107
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009108 p++;
Denis Vlasenko0de37e12007-10-17 11:08:53 +00009109 fdprintf(preverrout_fd, p, expandstr(ps4val()));
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009110
9111 sp = varlist.list;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +00009112 for (n = 0; n < 2; n++) {
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009113 while (sp) {
Denis Vlasenko0de37e12007-10-17 11:08:53 +00009114 fdprintf(preverrout_fd, p, sp->text);
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009115 sp = sp->next;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +00009116 if (*p == '%') {
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009117 p--;
9118 }
9119 }
9120 sp = arglist.list;
9121 }
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00009122 safe_write(preverrout_fd, "\n", 1);
Eric Andersenc470f442003-07-28 09:56:35 +00009123 }
9124
9125 cmd_is_exec = 0;
9126 spclbltin = -1;
9127
9128 /* Now locate the command. */
9129 if (argc) {
9130 const char *oldpath;
9131 int cmd_flag = DO_ERR;
9132
9133 path += 5;
9134 oldpath = path;
9135 for (;;) {
9136 find_command(argv[0], &cmdentry, cmd_flag, path);
9137 if (cmdentry.cmdtype == CMDUNKNOWN) {
Denys Vlasenko8131eea2009-11-02 14:19:51 +01009138 flush_stdout_stderr();
Denis Vlasenko6514c5e2008-07-24 13:41:37 +00009139 status = 127;
Eric Andersenc470f442003-07-28 09:56:35 +00009140 goto bail;
9141 }
9142
9143 /* implement bltin and command here */
9144 if (cmdentry.cmdtype != CMDBUILTIN)
9145 break;
9146 if (spclbltin < 0)
9147 spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
9148 if (cmdentry.u.cmd == EXECCMD)
Denis Vlasenko34c73c42008-08-16 11:48:02 +00009149 cmd_is_exec = 1;
Denis Vlasenko131ae172007-02-18 13:00:19 +00009150#if ENABLE_ASH_CMDCMD
Eric Andersenc470f442003-07-28 09:56:35 +00009151 if (cmdentry.u.cmd == COMMANDCMD) {
Eric Andersenc470f442003-07-28 09:56:35 +00009152 path = oldpath;
9153 nargv = parse_command_args(argv, &path);
9154 if (!nargv)
9155 break;
9156 argc -= nargv - argv;
9157 argv = nargv;
9158 cmd_flag |= DO_NOFUNC;
9159 } else
9160#endif
9161 break;
9162 }
9163 }
9164
9165 if (status) {
9166 /* We have a redirection error. */
9167 if (spclbltin > 0)
Denis Vlasenkob012b102007-02-19 22:43:01 +00009168 raise_exception(EXERROR);
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009169 bail:
Eric Andersenc470f442003-07-28 09:56:35 +00009170 exitstatus = status;
9171 goto out;
9172 }
9173
9174 /* Execute the command. */
9175 switch (cmdentry.cmdtype) {
Denys Vlasenko42c4b2e2010-05-18 16:13:56 +02009176 default: {
Denis Vlasenkobe54d6b2008-10-27 14:25:52 +00009177
Denis Vlasenko9bc80d72008-04-12 20:07:53 +00009178#if ENABLE_FEATURE_SH_NOFORK
Denys Vlasenko42c4b2e2010-05-18 16:13:56 +02009179/* (1) BUG: if variables are set, we need to fork, or save/restore them
9180 * around run_nofork_applet() call.
9181 * (2) Should this check also be done in forkshell()?
9182 * (perhaps it should, so that "VAR=VAL nofork" at least avoids exec...)
9183 */
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00009184 /* find_command() encodes applet_no as (-2 - applet_no) */
9185 int applet_no = (- cmdentry.u.index - 2);
Denis Vlasenko9bc80d72008-04-12 20:07:53 +00009186 if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
Denis Vlasenko9bc80d72008-04-12 20:07:53 +00009187 listsetvar(varlist.list, VEXPORT|VSTACK);
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00009188 /* run <applet>_main() */
9189 exitstatus = run_nofork_applet(applet_no, argv);
Denis Vlasenko9bc80d72008-04-12 20:07:53 +00009190 break;
9191 }
Denis Vlasenko9bc80d72008-04-12 20:07:53 +00009192#endif
Denys Vlasenko42c4b2e2010-05-18 16:13:56 +02009193 /* Can we avoid forking off? For example, very last command
9194 * in a script or a subshell does not need forking,
9195 * we can just exec it.
9196 */
Denys Vlasenko238bf182010-05-18 15:49:07 +02009197 if (!(flags & EV_EXIT) || may_have_traps) {
Denys Vlasenko42c4b2e2010-05-18 16:13:56 +02009198 /* No, forking off a child is necessary */
Denis Vlasenkob012b102007-02-19 22:43:01 +00009199 INT_OFF;
Denis Vlasenko68404f12008-03-17 09:00:54 +00009200 jp = makejob(/*cmd,*/ 1);
Eric Andersenc470f442003-07-28 09:56:35 +00009201 if (forkshell(jp, cmd, FORK_FG) != 0) {
Denys Vlasenko238bf182010-05-18 15:49:07 +02009202 /* parent */
Eric Andersenc470f442003-07-28 09:56:35 +00009203 exitstatus = waitforjob(jp);
Denis Vlasenkob012b102007-02-19 22:43:01 +00009204 INT_ON;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00009205 TRACE(("forked child exited with %d\n", exitstatus));
Eric Andersenc470f442003-07-28 09:56:35 +00009206 break;
9207 }
Denys Vlasenko238bf182010-05-18 15:49:07 +02009208 /* child */
Denis Vlasenkob012b102007-02-19 22:43:01 +00009209 FORCE_INT_ON;
Denys Vlasenkoc7f95d22010-05-18 15:52:23 +02009210 /* fall through to exec'ing external program */
Eric Andersenc470f442003-07-28 09:56:35 +00009211 }
9212 listsetvar(varlist.list, VEXPORT|VSTACK);
9213 shellexec(argv, path, cmdentry.u.index);
9214 /* NOTREACHED */
Denys Vlasenko42c4b2e2010-05-18 16:13:56 +02009215 } /* default */
Eric Andersenc470f442003-07-28 09:56:35 +00009216 case CMDBUILTIN:
9217 cmdenviron = varlist.list;
9218 if (cmdenviron) {
9219 struct strlist *list = cmdenviron;
9220 int i = VNOSET;
9221 if (spclbltin > 0 || argc == 0) {
9222 i = 0;
9223 if (cmd_is_exec && argc > 1)
9224 i = VEXPORT;
9225 }
9226 listsetvar(list, i);
9227 }
Denis Vlasenkobe54d6b2008-10-27 14:25:52 +00009228 /* Tight loop with builtins only:
9229 * "while kill -0 $child; do true; done"
9230 * will never exit even if $child died, unless we do this
9231 * to reap the zombie and make kill detect that it's gone: */
9232 dowait(DOWAIT_NONBLOCK, NULL);
9233
Eric Andersenc470f442003-07-28 09:56:35 +00009234 if (evalbltin(cmdentry.u.cmd, argc, argv)) {
9235 int exit_status;
Denis Vlasenko7f88e342009-03-19 03:36:18 +00009236 int i = exception_type;
Eric Andersenc470f442003-07-28 09:56:35 +00009237 if (i == EXEXIT)
9238 goto raise;
Eric Andersenc470f442003-07-28 09:56:35 +00009239 exit_status = 2;
Eric Andersenc470f442003-07-28 09:56:35 +00009240 if (i == EXINT)
Denis Vlasenko991a1da2008-02-10 19:02:53 +00009241 exit_status = 128 + SIGINT;
Eric Andersenc470f442003-07-28 09:56:35 +00009242 if (i == EXSIG)
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02009243 exit_status = 128 + pending_sig;
Eric Andersenc470f442003-07-28 09:56:35 +00009244 exitstatus = exit_status;
Eric Andersenc470f442003-07-28 09:56:35 +00009245 if (i == EXINT || spclbltin > 0) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009246 raise:
Denis Vlasenko2da584f2007-02-19 22:44:05 +00009247 longjmp(exception_handler->loc, 1);
Eric Andersenc470f442003-07-28 09:56:35 +00009248 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00009249 FORCE_INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00009250 }
9251 break;
9252
9253 case CMDFUNCTION:
9254 listsetvar(varlist.list, 0);
Denis Vlasenkobe54d6b2008-10-27 14:25:52 +00009255 /* See above for the rationale */
9256 dowait(DOWAIT_NONBLOCK, NULL);
Eric Andersenc470f442003-07-28 09:56:35 +00009257 if (evalfun(cmdentry.u.func, argc, argv, flags))
9258 goto raise;
9259 break;
Denys Vlasenko42c4b2e2010-05-18 16:13:56 +02009260
9261 } /* switch */
Eric Andersenc470f442003-07-28 09:56:35 +00009262
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:
Denys Vlasenko79b3d422010-06-03 04:29:08 +02009455 if (!iflag || g_parsefile->pf_fd != STDIN_FILENO)
9456 nr = nonblock_safe_read(g_parsefile->pf_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 Vlasenko161bb8f2010-06-06 05:07:11 +02009478 nr = nonblock_safe_read(g_parsefile->pf_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;
Denys Vlasenko79b3d422010-06-03 04:29:08 +02009705 pf->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;
Denys Vlasenko79b3d422010-06-03 04:29:08 +02009717 if (pf->pf_fd >= 0)
9718 close(pf->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();
Denys Vlasenko79b3d422010-06-03 04:29:08 +02009745 if (g_parsefile->pf_fd > 0) {
9746 close(g_parsefile->pf_fd);
9747 g_parsefile->pf_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 }
Denys Vlasenko79b3d422010-06-03 04:29:08 +02009763 g_parsefile->pf_fd = fd;
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009764 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(
Denys Vlasenkoea8b2522010-06-02 12:57:26 +02009868 stderr, "%s\n",
Eric Andersenc470f442003-07-28 09:56:35 +00009869 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 */
Denys Vlasenko8837c5d2010-06-02 12:56:18 +020010126 setvar(vrandom.var_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
Denys Vlasenkoa0ec4f52010-05-20 12:50:42 +020010277static const char *
10278tokname(char *buf, int tok)
10279{
10280 if (tok < TSEMI)
10281 return tokname_array[tok] + 1;
10282 sprintf(buf, "\"%s\"", tokname_array[tok] + 1);
10283 return buf;
10284}
10285
10286/* raise_error_unexpected_syntax:
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010287 * Called when an unexpected token is read during the parse. The argument
10288 * is the token that is expected, or -1 if more than one type of token can
10289 * occur at this point.
10290 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000010291static void raise_error_unexpected_syntax(int) NORETURN;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010292static void
10293raise_error_unexpected_syntax(int token)
10294{
10295 char msg[64];
Denys Vlasenkoa0ec4f52010-05-20 12:50:42 +020010296 char buf[16];
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010297 int l;
10298
Denys Vlasenkoa0ec4f52010-05-20 12:50:42 +020010299 l = sprintf(msg, "unexpected %s", tokname(buf, lasttoken));
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010300 if (token >= 0)
Denys Vlasenkoa0ec4f52010-05-20 12:50:42 +020010301 sprintf(msg + l, " (expecting %s)", tokname(buf, token));
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010302 raise_error_syntax(msg);
10303 /* NOTREACHED */
10304}
Eric Andersencb57d552001-06-28 07:25:16 +000010305
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010306#define EOFMARKLEN 79
Eric Andersencb57d552001-06-28 07:25:16 +000010307
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010308/* parsing is heavily cross-recursive, need these forward decls */
10309static union node *andor(void);
10310static union node *pipeline(void);
10311static union node *parse_command(void);
10312static void parseheredoc(void);
10313static char peektoken(void);
10314static int readtoken(void);
Eric Andersencb57d552001-06-28 07:25:16 +000010315
Eric Andersenc470f442003-07-28 09:56:35 +000010316static union node *
10317list(int nlflag)
Eric Andersencb57d552001-06-28 07:25:16 +000010318{
10319 union node *n1, *n2, *n3;
10320 int tok;
10321
Eric Andersenc470f442003-07-28 09:56:35 +000010322 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10323 if (nlflag == 2 && peektoken())
Eric Andersencb57d552001-06-28 07:25:16 +000010324 return NULL;
10325 n1 = NULL;
10326 for (;;) {
10327 n2 = andor();
10328 tok = readtoken();
10329 if (tok == TBACKGND) {
Eric Andersenc470f442003-07-28 09:56:35 +000010330 if (n2->type == NPIPE) {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +000010331 n2->npipe.pipe_backgnd = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010332 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000010333 if (n2->type != NREDIR) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010334 n3 = stzalloc(sizeof(struct nredir));
Eric Andersenc470f442003-07-28 09:56:35 +000010335 n3->nredir.n = n2;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010336 /*n3->nredir.redirect = NULL; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000010337 n2 = n3;
10338 }
10339 n2->type = NBACKGND;
Eric Andersencb57d552001-06-28 07:25:16 +000010340 }
10341 }
10342 if (n1 == NULL) {
10343 n1 = n2;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010344 } else {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010345 n3 = stzalloc(sizeof(struct nbinary));
Eric Andersencb57d552001-06-28 07:25:16 +000010346 n3->type = NSEMI;
10347 n3->nbinary.ch1 = n1;
10348 n3->nbinary.ch2 = n2;
10349 n1 = n3;
10350 }
10351 switch (tok) {
10352 case TBACKGND:
10353 case TSEMI:
10354 tok = readtoken();
10355 /* fall through */
10356 case TNL:
10357 if (tok == TNL) {
10358 parseheredoc();
Eric Andersenc470f442003-07-28 09:56:35 +000010359 if (nlflag == 1)
Eric Andersencb57d552001-06-28 07:25:16 +000010360 return n1;
10361 } else {
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010362 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010363 }
Eric Andersenc470f442003-07-28 09:56:35 +000010364 checkkwd = CHKNL | CHKKWD | CHKALIAS;
Manuel Novoa III 16815d42001-08-10 19:36:07 +000010365 if (peektoken())
Eric Andersencb57d552001-06-28 07:25:16 +000010366 return n1;
10367 break;
10368 case TEOF:
10369 if (heredoclist)
10370 parseheredoc();
10371 else
Eric Andersenc470f442003-07-28 09:56:35 +000010372 pungetc(); /* push back EOF on input */
Eric Andersencb57d552001-06-28 07:25:16 +000010373 return n1;
10374 default:
Eric Andersenc470f442003-07-28 09:56:35 +000010375 if (nlflag == 1)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010376 raise_error_unexpected_syntax(-1);
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010377 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010378 return n1;
10379 }
10380 }
10381}
10382
Eric Andersenc470f442003-07-28 09:56:35 +000010383static union node *
10384andor(void)
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010385{
Eric Andersencb57d552001-06-28 07:25:16 +000010386 union node *n1, *n2, *n3;
10387 int t;
10388
Eric Andersencb57d552001-06-28 07:25:16 +000010389 n1 = pipeline();
10390 for (;;) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010391 t = readtoken();
10392 if (t == TAND) {
Eric Andersencb57d552001-06-28 07:25:16 +000010393 t = NAND;
10394 } else if (t == TOR) {
10395 t = NOR;
10396 } else {
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010397 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010398 return n1;
10399 }
Eric Andersenc470f442003-07-28 09:56:35 +000010400 checkkwd = CHKNL | CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010401 n2 = pipeline();
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010402 n3 = stzalloc(sizeof(struct nbinary));
Eric Andersencb57d552001-06-28 07:25:16 +000010403 n3->type = t;
10404 n3->nbinary.ch1 = n1;
10405 n3->nbinary.ch2 = n2;
10406 n1 = n3;
10407 }
10408}
10409
Eric Andersenc470f442003-07-28 09:56:35 +000010410static union node *
10411pipeline(void)
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010412{
Eric Andersencb57d552001-06-28 07:25:16 +000010413 union node *n1, *n2, *pipenode;
10414 struct nodelist *lp, *prev;
10415 int negate;
10416
10417 negate = 0;
10418 TRACE(("pipeline: entered\n"));
10419 if (readtoken() == TNOT) {
10420 negate = !negate;
Eric Andersenc470f442003-07-28 09:56:35 +000010421 checkkwd = CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010422 } else
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010423 tokpushback = 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010424 n1 = parse_command();
Eric Andersencb57d552001-06-28 07:25:16 +000010425 if (readtoken() == TPIPE) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010426 pipenode = stzalloc(sizeof(struct npipe));
Eric Andersencb57d552001-06-28 07:25:16 +000010427 pipenode->type = NPIPE;
Denis Vlasenko2dc240c2008-07-24 06:07:50 +000010428 /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010429 lp = stzalloc(sizeof(struct nodelist));
Eric Andersencb57d552001-06-28 07:25:16 +000010430 pipenode->npipe.cmdlist = lp;
10431 lp->n = n1;
10432 do {
10433 prev = lp;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010434 lp = stzalloc(sizeof(struct nodelist));
Eric Andersenc470f442003-07-28 09:56:35 +000010435 checkkwd = CHKNL | CHKKWD | CHKALIAS;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010436 lp->n = parse_command();
Eric Andersencb57d552001-06-28 07:25:16 +000010437 prev->next = lp;
10438 } while (readtoken() == TPIPE);
10439 lp->next = NULL;
10440 n1 = pipenode;
10441 }
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010442 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010443 if (negate) {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010444 n2 = stzalloc(sizeof(struct nnot));
Eric Andersencb57d552001-06-28 07:25:16 +000010445 n2->type = NNOT;
10446 n2->nnot.com = n1;
10447 return n2;
Denis Vlasenko2da584f2007-02-19 22:44:05 +000010448 }
10449 return n1;
Eric Andersencb57d552001-06-28 07:25:16 +000010450}
10451
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010452static union node *
10453makename(void)
10454{
10455 union node *n;
10456
Denis Vlasenko597906c2008-02-20 16:38:54 +000010457 n = stzalloc(sizeof(struct narg));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010458 n->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010459 /*n->narg.next = NULL; - stzalloc did it */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010460 n->narg.text = wordtext;
10461 n->narg.backquote = backquotelist;
10462 return n;
10463}
10464
10465static void
10466fixredir(union node *n, const char *text, int err)
10467{
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000010468 int fd;
10469
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010470 TRACE(("Fix redir %s %d\n", text, err));
10471 if (!err)
10472 n->ndup.vname = NULL;
10473
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000010474 fd = bb_strtou(text, NULL, 10);
10475 if (!errno && fd >= 0)
10476 n->ndup.dupfd = fd;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010477 else if (LONE_DASH(text))
10478 n->ndup.dupfd = -1;
10479 else {
10480 if (err)
Denis Vlasenko559691a2008-10-05 18:39:31 +000010481 raise_error_syntax("bad fd number");
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010482 n->ndup.vname = makename();
10483 }
10484}
10485
10486/*
10487 * Returns true if the text contains nothing to expand (no dollar signs
10488 * or backquotes).
10489 */
10490static int
Denis Vlasenko68819d12008-12-15 11:26:36 +000010491noexpand(const char *text)
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010492{
Denys Vlasenkocd716832009-11-28 22:14:02 +010010493 unsigned char c;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010494
Denys Vlasenkocd716832009-11-28 22:14:02 +010010495 while ((c = *text++) != '\0') {
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010496 if (c == CTLQUOTEMARK)
10497 continue;
10498 if (c == CTLESC)
Denys Vlasenkocd716832009-11-28 22:14:02 +010010499 text++;
Denys Vlasenko76bc2d62009-11-29 01:37:46 +010010500 else if (SIT(c, BASESYNTAX) == CCTL)
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010501 return 0;
10502 }
10503 return 1;
10504}
10505
10506static void
10507parsefname(void)
10508{
10509 union node *n = redirnode;
10510
10511 if (readtoken() != TWORD)
10512 raise_error_unexpected_syntax(-1);
10513 if (n->type == NHERE) {
10514 struct heredoc *here = heredoc;
10515 struct heredoc *p;
10516 int i;
10517
10518 if (quoteflag == 0)
10519 n->type = NXHERE;
10520 TRACE(("Here document %d\n", n->type));
10521 if (!noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
Denis Vlasenko559691a2008-10-05 18:39:31 +000010522 raise_error_syntax("illegal eof marker for << redirection");
Denys Vlasenkob6c84342009-08-29 20:23:20 +020010523 rmescapes(wordtext, 0);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010524 here->eofmark = wordtext;
10525 here->next = NULL;
10526 if (heredoclist == NULL)
10527 heredoclist = here;
10528 else {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010529 for (p = heredoclist; p->next; p = p->next)
10530 continue;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010531 p->next = here;
10532 }
10533 } else if (n->type == NTOFD || n->type == NFROMFD) {
10534 fixredir(n, wordtext, 0);
10535 } else {
10536 n->nfile.fname = makename();
10537 }
10538}
Eric Andersencb57d552001-06-28 07:25:16 +000010539
Eric Andersenc470f442003-07-28 09:56:35 +000010540static union node *
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010541simplecmd(void)
10542{
10543 union node *args, **app;
10544 union node *n = NULL;
10545 union node *vars, **vpp;
10546 union node **rpp, *redir;
10547 int savecheckkwd;
Denis Vlasenko80591b02008-03-25 07:49:43 +000010548#if ENABLE_ASH_BASH_COMPAT
10549 smallint double_brackets_flag = 0;
10550#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010551
10552 args = NULL;
10553 app = &args;
10554 vars = NULL;
10555 vpp = &vars;
10556 redir = NULL;
10557 rpp = &redir;
10558
10559 savecheckkwd = CHKALIAS;
10560 for (;;) {
Denis Vlasenko80591b02008-03-25 07:49:43 +000010561 int t;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010562 checkkwd = savecheckkwd;
Denis Vlasenko80591b02008-03-25 07:49:43 +000010563 t = readtoken();
10564 switch (t) {
10565#if ENABLE_ASH_BASH_COMPAT
10566 case TAND: /* "&&" */
10567 case TOR: /* "||" */
10568 if (!double_brackets_flag) {
10569 tokpushback = 1;
10570 goto out;
10571 }
10572 wordtext = (char *) (t == TAND ? "-a" : "-o");
10573#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010574 case TWORD:
Denis Vlasenko597906c2008-02-20 16:38:54 +000010575 n = stzalloc(sizeof(struct narg));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010576 n->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010577 /*n->narg.next = NULL; - stzalloc did it */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010578 n->narg.text = wordtext;
Denis Vlasenko80591b02008-03-25 07:49:43 +000010579#if ENABLE_ASH_BASH_COMPAT
10580 if (strcmp("[[", wordtext) == 0)
10581 double_brackets_flag = 1;
10582 else if (strcmp("]]", wordtext) == 0)
10583 double_brackets_flag = 0;
10584#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010585 n->narg.backquote = backquotelist;
10586 if (savecheckkwd && isassignment(wordtext)) {
10587 *vpp = n;
10588 vpp = &n->narg.next;
10589 } else {
10590 *app = n;
10591 app = &n->narg.next;
10592 savecheckkwd = 0;
10593 }
10594 break;
10595 case TREDIR:
10596 *rpp = n = redirnode;
10597 rpp = &n->nfile.next;
10598 parsefname(); /* read name of redirection file */
10599 break;
10600 case TLP:
10601 if (args && app == &args->narg.next
10602 && !vars && !redir
10603 ) {
10604 struct builtincmd *bcmd;
10605 const char *name;
10606
10607 /* We have a function */
10608 if (readtoken() != TRP)
10609 raise_error_unexpected_syntax(TRP);
10610 name = n->narg.text;
10611 if (!goodname(name)
10612 || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
10613 ) {
Denis Vlasenko559691a2008-10-05 18:39:31 +000010614 raise_error_syntax("bad function name");
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010615 }
10616 n->type = NDEFUN;
10617 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10618 n->narg.next = parse_command();
10619 return n;
10620 }
10621 /* fall through */
10622 default:
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010623 tokpushback = 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010624 goto out;
10625 }
10626 }
10627 out:
10628 *app = NULL;
10629 *vpp = NULL;
10630 *rpp = NULL;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010631 n = stzalloc(sizeof(struct ncmd));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010632 n->type = NCMD;
10633 n->ncmd.args = args;
10634 n->ncmd.assign = vars;
10635 n->ncmd.redirect = redir;
10636 return n;
10637}
10638
10639static union node *
10640parse_command(void)
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010641{
Eric Andersencb57d552001-06-28 07:25:16 +000010642 union node *n1, *n2;
10643 union node *ap, **app;
10644 union node *cp, **cpp;
10645 union node *redir, **rpp;
Eric Andersenc470f442003-07-28 09:56:35 +000010646 union node **rpp2;
Eric Andersencb57d552001-06-28 07:25:16 +000010647 int t;
10648
10649 redir = NULL;
Eric Andersenc470f442003-07-28 09:56:35 +000010650 rpp2 = &redir;
Eric Andersen88cec252001-09-06 17:35:20 +000010651
Eric Andersencb57d552001-06-28 07:25:16 +000010652 switch (readtoken()) {
Eric Andersenc470f442003-07-28 09:56:35 +000010653 default:
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010654 raise_error_unexpected_syntax(-1);
Eric Andersenc470f442003-07-28 09:56:35 +000010655 /* NOTREACHED */
Eric Andersencb57d552001-06-28 07:25:16 +000010656 case TIF:
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010657 n1 = stzalloc(sizeof(struct nif));
Eric Andersencb57d552001-06-28 07:25:16 +000010658 n1->type = NIF;
10659 n1->nif.test = list(0);
10660 if (readtoken() != TTHEN)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010661 raise_error_unexpected_syntax(TTHEN);
Eric Andersencb57d552001-06-28 07:25:16 +000010662 n1->nif.ifpart = list(0);
10663 n2 = n1;
10664 while (readtoken() == TELIF) {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010665 n2->nif.elsepart = stzalloc(sizeof(struct nif));
Eric Andersencb57d552001-06-28 07:25:16 +000010666 n2 = n2->nif.elsepart;
10667 n2->type = NIF;
10668 n2->nif.test = list(0);
10669 if (readtoken() != TTHEN)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010670 raise_error_unexpected_syntax(TTHEN);
Eric Andersencb57d552001-06-28 07:25:16 +000010671 n2->nif.ifpart = list(0);
10672 }
10673 if (lasttoken == TELSE)
10674 n2->nif.elsepart = list(0);
10675 else {
10676 n2->nif.elsepart = NULL;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010677 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010678 }
Eric Andersenc470f442003-07-28 09:56:35 +000010679 t = TFI;
Eric Andersencb57d552001-06-28 07:25:16 +000010680 break;
10681 case TWHILE:
Eric Andersenc470f442003-07-28 09:56:35 +000010682 case TUNTIL: {
Eric Andersencb57d552001-06-28 07:25:16 +000010683 int got;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010684 n1 = stzalloc(sizeof(struct nbinary));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010685 n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
Eric Andersencb57d552001-06-28 07:25:16 +000010686 n1->nbinary.ch1 = list(0);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010687 got = readtoken();
10688 if (got != TDO) {
Denys Vlasenkoa0ec4f52010-05-20 12:50:42 +020010689 TRACE(("expecting DO got '%s' %s\n", tokname_array[got] + 1,
Denis Vlasenko131ae172007-02-18 13:00:19 +000010690 got == TWORD ? wordtext : ""));
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010691 raise_error_unexpected_syntax(TDO);
Eric Andersencb57d552001-06-28 07:25:16 +000010692 }
10693 n1->nbinary.ch2 = list(0);
Eric Andersenc470f442003-07-28 09:56:35 +000010694 t = TDONE;
Eric Andersencb57d552001-06-28 07:25:16 +000010695 break;
10696 }
10697 case TFOR:
Denis Vlasenko2dc240c2008-07-24 06:07:50 +000010698 if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
Denis Vlasenko559691a2008-10-05 18:39:31 +000010699 raise_error_syntax("bad for loop variable");
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010700 n1 = stzalloc(sizeof(struct nfor));
Eric Andersencb57d552001-06-28 07:25:16 +000010701 n1->type = NFOR;
10702 n1->nfor.var = wordtext;
Eric Andersenc470f442003-07-28 09:56:35 +000010703 checkkwd = CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010704 if (readtoken() == TIN) {
10705 app = &ap;
10706 while (readtoken() == TWORD) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010707 n2 = stzalloc(sizeof(struct narg));
Eric Andersencb57d552001-06-28 07:25:16 +000010708 n2->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010709 /*n2->narg.next = NULL; - stzalloc did it */
Eric Andersencb57d552001-06-28 07:25:16 +000010710 n2->narg.text = wordtext;
10711 n2->narg.backquote = backquotelist;
10712 *app = n2;
10713 app = &n2->narg.next;
10714 }
10715 *app = NULL;
10716 n1->nfor.args = ap;
10717 if (lasttoken != TNL && lasttoken != TSEMI)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010718 raise_error_unexpected_syntax(-1);
Eric Andersencb57d552001-06-28 07:25:16 +000010719 } else {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010720 n2 = stzalloc(sizeof(struct narg));
Eric Andersencb57d552001-06-28 07:25:16 +000010721 n2->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010722 /*n2->narg.next = NULL; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000010723 n2->narg.text = (char *)dolatstr;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010724 /*n2->narg.backquote = NULL;*/
Eric Andersencb57d552001-06-28 07:25:16 +000010725 n1->nfor.args = n2;
10726 /*
10727 * Newline or semicolon here is optional (but note
10728 * that the original Bourne shell only allowed NL).
10729 */
10730 if (lasttoken != TNL && lasttoken != TSEMI)
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010731 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010732 }
Eric Andersenc470f442003-07-28 09:56:35 +000010733 checkkwd = CHKNL | CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010734 if (readtoken() != TDO)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010735 raise_error_unexpected_syntax(TDO);
Eric Andersencb57d552001-06-28 07:25:16 +000010736 n1->nfor.body = list(0);
Eric Andersenc470f442003-07-28 09:56:35 +000010737 t = TDONE;
Eric Andersencb57d552001-06-28 07:25:16 +000010738 break;
10739 case TCASE:
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010740 n1 = stzalloc(sizeof(struct ncase));
Eric Andersencb57d552001-06-28 07:25:16 +000010741 n1->type = NCASE;
10742 if (readtoken() != TWORD)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010743 raise_error_unexpected_syntax(TWORD);
Denis Vlasenko597906c2008-02-20 16:38:54 +000010744 n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
Eric Andersencb57d552001-06-28 07:25:16 +000010745 n2->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010746 /*n2->narg.next = NULL; - stzalloc did it */
Eric Andersencb57d552001-06-28 07:25:16 +000010747 n2->narg.text = wordtext;
10748 n2->narg.backquote = backquotelist;
Eric Andersencb57d552001-06-28 07:25:16 +000010749 do {
Eric Andersenc470f442003-07-28 09:56:35 +000010750 checkkwd = CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010751 } while (readtoken() == TNL);
10752 if (lasttoken != TIN)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010753 raise_error_unexpected_syntax(TIN);
Eric Andersencb57d552001-06-28 07:25:16 +000010754 cpp = &n1->ncase.cases;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010755 next_case:
Eric Andersenc470f442003-07-28 09:56:35 +000010756 checkkwd = CHKNL | CHKKWD;
10757 t = readtoken();
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010758 while (t != TESAC) {
Eric Andersencb57d552001-06-28 07:25:16 +000010759 if (lasttoken == TLP)
10760 readtoken();
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010761 *cpp = cp = stzalloc(sizeof(struct nclist));
Eric Andersencb57d552001-06-28 07:25:16 +000010762 cp->type = NCLIST;
10763 app = &cp->nclist.pattern;
10764 for (;;) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010765 *app = ap = stzalloc(sizeof(struct narg));
Eric Andersencb57d552001-06-28 07:25:16 +000010766 ap->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010767 /*ap->narg.next = NULL; - stzalloc did it */
Eric Andersencb57d552001-06-28 07:25:16 +000010768 ap->narg.text = wordtext;
10769 ap->narg.backquote = backquotelist;
Eric Andersenc470f442003-07-28 09:56:35 +000010770 if (readtoken() != TPIPE)
Eric Andersencb57d552001-06-28 07:25:16 +000010771 break;
10772 app = &ap->narg.next;
10773 readtoken();
10774 }
Denis Vlasenko597906c2008-02-20 16:38:54 +000010775 //ap->narg.next = NULL;
Eric Andersencb57d552001-06-28 07:25:16 +000010776 if (lasttoken != TRP)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010777 raise_error_unexpected_syntax(TRP);
Eric Andersenc470f442003-07-28 09:56:35 +000010778 cp->nclist.body = list(2);
Eric Andersencb57d552001-06-28 07:25:16 +000010779
Eric Andersenc470f442003-07-28 09:56:35 +000010780 cpp = &cp->nclist.next;
10781
10782 checkkwd = CHKNL | CHKKWD;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010783 t = readtoken();
10784 if (t != TESAC) {
Eric Andersencb57d552001-06-28 07:25:16 +000010785 if (t != TENDCASE)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010786 raise_error_unexpected_syntax(TENDCASE);
10787 goto next_case;
Eric Andersencb57d552001-06-28 07:25:16 +000010788 }
Eric Andersenc470f442003-07-28 09:56:35 +000010789 }
Eric Andersencb57d552001-06-28 07:25:16 +000010790 *cpp = NULL;
Eric Andersenc470f442003-07-28 09:56:35 +000010791 goto redir;
Eric Andersencb57d552001-06-28 07:25:16 +000010792 case TLP:
Denis Vlasenko597906c2008-02-20 16:38:54 +000010793 n1 = stzalloc(sizeof(struct nredir));
Eric Andersencb57d552001-06-28 07:25:16 +000010794 n1->type = NSUBSHELL;
10795 n1->nredir.n = list(0);
Denis Vlasenko597906c2008-02-20 16:38:54 +000010796 /*n1->nredir.redirect = NULL; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000010797 t = TRP;
Eric Andersencb57d552001-06-28 07:25:16 +000010798 break;
10799 case TBEGIN:
10800 n1 = list(0);
Eric Andersenc470f442003-07-28 09:56:35 +000010801 t = TEND;
Eric Andersencb57d552001-06-28 07:25:16 +000010802 break;
Eric Andersencb57d552001-06-28 07:25:16 +000010803 case TWORD:
Eric Andersenc470f442003-07-28 09:56:35 +000010804 case TREDIR:
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010805 tokpushback = 1;
Eric Andersenc470f442003-07-28 09:56:35 +000010806 return simplecmd();
Eric Andersencb57d552001-06-28 07:25:16 +000010807 }
10808
Eric Andersenc470f442003-07-28 09:56:35 +000010809 if (readtoken() != t)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010810 raise_error_unexpected_syntax(t);
Eric Andersenc470f442003-07-28 09:56:35 +000010811
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010812 redir:
Eric Andersencb57d552001-06-28 07:25:16 +000010813 /* Now check for redirection which may follow command */
Eric Andersenc470f442003-07-28 09:56:35 +000010814 checkkwd = CHKKWD | CHKALIAS;
10815 rpp = rpp2;
Eric Andersencb57d552001-06-28 07:25:16 +000010816 while (readtoken() == TREDIR) {
10817 *rpp = n2 = redirnode;
10818 rpp = &n2->nfile.next;
10819 parsefname();
10820 }
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010821 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010822 *rpp = NULL;
10823 if (redir) {
10824 if (n1->type != NSUBSHELL) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010825 n2 = stzalloc(sizeof(struct nredir));
Eric Andersencb57d552001-06-28 07:25:16 +000010826 n2->type = NREDIR;
10827 n2->nredir.n = n1;
10828 n1 = n2;
10829 }
10830 n1->nredir.redirect = redir;
10831 }
Eric Andersencb57d552001-06-28 07:25:16 +000010832 return n1;
10833}
10834
Denis Vlasenkoef527f52008-06-23 01:52:30 +000010835#if ENABLE_ASH_BASH_COMPAT
10836static int decode_dollar_squote(void)
10837{
10838 static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
10839 int c, cnt;
10840 char *p;
10841 char buf[4];
10842
10843 c = pgetc();
10844 p = strchr(C_escapes, c);
10845 if (p) {
10846 buf[0] = c;
10847 p = buf;
10848 cnt = 3;
10849 if ((unsigned char)(c - '0') <= 7) { /* \ooo */
10850 do {
10851 c = pgetc();
10852 *++p = c;
10853 } while ((unsigned char)(c - '0') <= 7 && --cnt);
10854 pungetc();
10855 } else if (c == 'x') { /* \xHH */
10856 do {
10857 c = pgetc();
10858 *++p = c;
10859 } while (isxdigit(c) && --cnt);
10860 pungetc();
10861 if (cnt == 3) { /* \x but next char is "bad" */
10862 c = 'x';
10863 goto unrecognized;
10864 }
10865 } else { /* simple seq like \\ or \t */
10866 p++;
10867 }
10868 *p = '\0';
10869 p = buf;
10870 c = bb_process_escape_sequence((void*)&p);
10871 } else { /* unrecognized "\z": print both chars unless ' or " */
10872 if (c != '\'' && c != '"') {
10873 unrecognized:
10874 c |= 0x100; /* "please encode \, then me" */
10875 }
10876 }
10877 return c;
10878}
10879#endif
10880
Eric Andersencb57d552001-06-28 07:25:16 +000010881/*
10882 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
10883 * is not NULL, read a here document. In the latter case, eofmark is the
10884 * word which marks the end of the document and striptabs is true if
Denys Vlasenkocd716832009-11-28 22:14:02 +010010885 * leading tabs should be stripped from the document. The argument c
Eric Andersencb57d552001-06-28 07:25:16 +000010886 * is the first character of the input token or document.
10887 *
10888 * Because C does not have internal subroutines, I have simulated them
10889 * using goto's to implement the subroutine linkage. The following macros
10890 * will run code that appears at the end of readtoken1.
10891 */
Eric Andersen2870d962001-07-02 17:27:21 +000010892#define CHECKEND() {goto checkend; checkend_return:;}
10893#define PARSEREDIR() {goto parseredir; parseredir_return:;}
10894#define PARSESUB() {goto parsesub; parsesub_return:;}
10895#define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
10896#define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
10897#define PARSEARITH() {goto parsearith; parsearith_return:;}
Eric Andersencb57d552001-06-28 07:25:16 +000010898static int
Denys Vlasenkocd716832009-11-28 22:14:02 +010010899readtoken1(int c, int syntax, char *eofmark, int striptabs)
Manuel Novoa III 16815d42001-08-10 19:36:07 +000010900{
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010901 /* NB: syntax parameter fits into smallint */
Denys Vlasenkocd716832009-11-28 22:14:02 +010010902 /* c parameter is an unsigned char or PEOF or PEOA */
Eric Andersencb57d552001-06-28 07:25:16 +000010903 char *out;
10904 int len;
10905 char line[EOFMARKLEN + 1];
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010906 struct nodelist *bqlist;
10907 smallint quotef;
10908 smallint dblquote;
10909 smallint oldstyle;
10910 smallint prevsyntax; /* syntax before arithmetic */
Denis Vlasenko46a53062007-09-24 18:30:02 +000010911#if ENABLE_ASH_EXPAND_PRMT
10912 smallint pssyntax; /* we are expanding a prompt string */
10913#endif
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010914 int varnest; /* levels of variables expansion */
10915 int arinest; /* levels of arithmetic expansion */
10916 int parenlevel; /* levels of parens in arithmetic */
10917 int dqvarnest; /* levels of variables expansion within double quotes */
10918
Denis Vlasenko5e34ff22009-04-21 11:09:40 +000010919 IF_ASH_BASH_COMPAT(smallint bash_dollar_squote = 0;)
Denis Vlasenkoef527f52008-06-23 01:52:30 +000010920
Eric Andersencb57d552001-06-28 07:25:16 +000010921#if __GNUC__
10922 /* Avoid longjmp clobbering */
10923 (void) &out;
10924 (void) &quotef;
10925 (void) &dblquote;
10926 (void) &varnest;
10927 (void) &arinest;
10928 (void) &parenlevel;
10929 (void) &dqvarnest;
10930 (void) &oldstyle;
10931 (void) &prevsyntax;
10932 (void) &syntax;
10933#endif
Denis Vlasenko41eb3002008-11-28 03:42:31 +000010934 startlinno = g_parsefile->linno;
Eric Andersencb57d552001-06-28 07:25:16 +000010935 bqlist = NULL;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010936 quotef = 0;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010937 oldstyle = 0;
10938 prevsyntax = 0;
Denis Vlasenko46a53062007-09-24 18:30:02 +000010939#if ENABLE_ASH_EXPAND_PRMT
10940 pssyntax = (syntax == PSSYNTAX);
10941 if (pssyntax)
10942 syntax = DQSYNTAX;
10943#endif
10944 dblquote = (syntax == DQSYNTAX);
Eric Andersencb57d552001-06-28 07:25:16 +000010945 varnest = 0;
10946 arinest = 0;
10947 parenlevel = 0;
10948 dqvarnest = 0;
10949
10950 STARTSTACKSTR(out);
Denis Vlasenko176d49d2008-10-06 09:51:47 +000010951 loop:
10952 /* For each line, until end of word */
10953 {
Eric Andersenc470f442003-07-28 09:56:35 +000010954 CHECKEND(); /* set c to PEOF if at end of here document */
10955 for (;;) { /* until end of line or end of word */
10956 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
Denis Vlasenkobf0a2012006-12-26 10:42:51 +000010957 switch (SIT(c, syntax)) {
Eric Andersenc470f442003-07-28 09:56:35 +000010958 case CNL: /* '\n' */
Eric Andersencb57d552001-06-28 07:25:16 +000010959 if (syntax == BASESYNTAX)
Eric Andersenc470f442003-07-28 09:56:35 +000010960 goto endword; /* exit outer loop */
Eric Andersencb57d552001-06-28 07:25:16 +000010961 USTPUTC(c, out);
Denis Vlasenko41eb3002008-11-28 03:42:31 +000010962 g_parsefile->linno++;
Eric Andersencb57d552001-06-28 07:25:16 +000010963 if (doprompt)
10964 setprompt(2);
Eric Andersencb57d552001-06-28 07:25:16 +000010965 c = pgetc();
Eric Andersenc470f442003-07-28 09:56:35 +000010966 goto loop; /* continue outer loop */
Eric Andersencb57d552001-06-28 07:25:16 +000010967 case CWORD:
10968 USTPUTC(c, out);
10969 break;
10970 case CCTL:
Eric Andersenc470f442003-07-28 09:56:35 +000010971 if (eofmark == NULL || dblquote)
Eric Andersencb57d552001-06-28 07:25:16 +000010972 USTPUTC(CTLESC, out);
Denis Vlasenkoef527f52008-06-23 01:52:30 +000010973#if ENABLE_ASH_BASH_COMPAT
10974 if (c == '\\' && bash_dollar_squote) {
10975 c = decode_dollar_squote();
10976 if (c & 0x100) {
10977 USTPUTC('\\', out);
10978 c = (unsigned char)c;
10979 }
10980 }
10981#endif
Eric Andersencb57d552001-06-28 07:25:16 +000010982 USTPUTC(c, out);
10983 break;
Eric Andersenc470f442003-07-28 09:56:35 +000010984 case CBACK: /* backslash */
Denys Vlasenko2ce42e92009-11-29 02:18:13 +010010985 c = pgetc_without_PEOA();
Eric Andersencb57d552001-06-28 07:25:16 +000010986 if (c == PEOF) {
Eric Andersenc470f442003-07-28 09:56:35 +000010987 USTPUTC(CTLESC, out);
Eric Andersencb57d552001-06-28 07:25:16 +000010988 USTPUTC('\\', out);
10989 pungetc();
10990 } else if (c == '\n') {
10991 if (doprompt)
10992 setprompt(2);
Eric Andersencb57d552001-06-28 07:25:16 +000010993 } else {
Denis Vlasenko46a53062007-09-24 18:30:02 +000010994#if ENABLE_ASH_EXPAND_PRMT
10995 if (c == '$' && pssyntax) {
10996 USTPUTC(CTLESC, out);
10997 USTPUTC('\\', out);
10998 }
10999#endif
Denis Vlasenkoef527f52008-06-23 01:52:30 +000011000 if (dblquote && c != '\\'
11001 && c != '`' && c != '$'
11002 && (c != '"' || eofmark != NULL)
Eric Andersenc470f442003-07-28 09:56:35 +000011003 ) {
11004 USTPUTC(CTLESC, out);
Eric Andersencb57d552001-06-28 07:25:16 +000011005 USTPUTC('\\', out);
Eric Andersenc470f442003-07-28 09:56:35 +000011006 }
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000011007 if (SIT(c, SQSYNTAX) == CCTL)
Eric Andersencb57d552001-06-28 07:25:16 +000011008 USTPUTC(CTLESC, out);
Eric Andersencb57d552001-06-28 07:25:16 +000011009 USTPUTC(c, out);
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011010 quotef = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000011011 }
11012 break;
11013 case CSQUOTE:
Eric Andersencb57d552001-06-28 07:25:16 +000011014 syntax = SQSYNTAX;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011015 quotemark:
Eric Andersenc470f442003-07-28 09:56:35 +000011016 if (eofmark == NULL) {
11017 USTPUTC(CTLQUOTEMARK, out);
11018 }
Eric Andersencb57d552001-06-28 07:25:16 +000011019 break;
11020 case CDQUOTE:
Eric Andersencb57d552001-06-28 07:25:16 +000011021 syntax = DQSYNTAX;
11022 dblquote = 1;
Eric Andersenc470f442003-07-28 09:56:35 +000011023 goto quotemark;
Eric Andersencb57d552001-06-28 07:25:16 +000011024 case CENDQUOTE:
Denis Vlasenko5e34ff22009-04-21 11:09:40 +000011025 IF_ASH_BASH_COMPAT(bash_dollar_squote = 0;)
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011026 if (eofmark != NULL && arinest == 0
11027 && varnest == 0
11028 ) {
Eric Andersencb57d552001-06-28 07:25:16 +000011029 USTPUTC(c, out);
11030 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000011031 if (dqvarnest == 0) {
Eric Andersencb57d552001-06-28 07:25:16 +000011032 syntax = BASESYNTAX;
11033 dblquote = 0;
11034 }
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011035 quotef = 1;
Eric Andersenc470f442003-07-28 09:56:35 +000011036 goto quotemark;
Eric Andersencb57d552001-06-28 07:25:16 +000011037 }
11038 break;
Eric Andersenc470f442003-07-28 09:56:35 +000011039 case CVAR: /* '$' */
11040 PARSESUB(); /* parse substitution */
Eric Andersencb57d552001-06-28 07:25:16 +000011041 break;
Eric Andersenc470f442003-07-28 09:56:35 +000011042 case CENDVAR: /* '}' */
Eric Andersencb57d552001-06-28 07:25:16 +000011043 if (varnest > 0) {
11044 varnest--;
11045 if (dqvarnest > 0) {
11046 dqvarnest--;
11047 }
11048 USTPUTC(CTLENDVAR, out);
11049 } else {
11050 USTPUTC(c, out);
11051 }
11052 break;
Mike Frysinger98c52642009-04-02 10:02:37 +000011053#if ENABLE_SH_MATH_SUPPORT
Eric Andersenc470f442003-07-28 09:56:35 +000011054 case CLP: /* '(' in arithmetic */
Eric Andersencb57d552001-06-28 07:25:16 +000011055 parenlevel++;
11056 USTPUTC(c, out);
11057 break;
Eric Andersenc470f442003-07-28 09:56:35 +000011058 case CRP: /* ')' in arithmetic */
Eric Andersencb57d552001-06-28 07:25:16 +000011059 if (parenlevel > 0) {
11060 USTPUTC(c, out);
11061 --parenlevel;
11062 } else {
11063 if (pgetc() == ')') {
11064 if (--arinest == 0) {
11065 USTPUTC(CTLENDARI, out);
11066 syntax = prevsyntax;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011067 dblquote = (syntax == DQSYNTAX);
Eric Andersencb57d552001-06-28 07:25:16 +000011068 } else
11069 USTPUTC(')', out);
11070 } else {
11071 /*
11072 * unbalanced parens
11073 * (don't 2nd guess - no error)
11074 */
11075 pungetc();
11076 USTPUTC(')', out);
11077 }
11078 }
11079 break;
11080#endif
Eric Andersenc470f442003-07-28 09:56:35 +000011081 case CBQUOTE: /* '`' */
Eric Andersencb57d552001-06-28 07:25:16 +000011082 PARSEBACKQOLD();
11083 break;
Eric Andersen2870d962001-07-02 17:27:21 +000011084 case CENDFILE:
Eric Andersenc470f442003-07-28 09:56:35 +000011085 goto endword; /* exit outer loop */
Eric Andersencb57d552001-06-28 07:25:16 +000011086 case CIGN:
11087 break;
11088 default:
Denis Vlasenko834dee72008-10-07 09:18:30 +000011089 if (varnest == 0) {
11090#if ENABLE_ASH_BASH_COMPAT
11091 if (c == '&') {
11092 if (pgetc() == '>')
11093 c = 0x100 + '>'; /* flag &> */
11094 pungetc();
11095 }
11096#endif
Eric Andersenc470f442003-07-28 09:56:35 +000011097 goto endword; /* exit outer loop */
Denis Vlasenko834dee72008-10-07 09:18:30 +000011098 }
Denys Vlasenko2ce42e92009-11-29 02:18:13 +010011099 IF_ASH_ALIAS(if (c != PEOA))
Eric Andersencb57d552001-06-28 07:25:16 +000011100 USTPUTC(c, out);
Eric Andersen3102ac42001-07-06 04:26:23 +000011101
Eric Andersencb57d552001-06-28 07:25:16 +000011102 }
Denis Vlasenko834dee72008-10-07 09:18:30 +000011103 c = pgetc_fast();
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000011104 } /* for (;;) */
Eric Andersencb57d552001-06-28 07:25:16 +000011105 }
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011106 endword:
Mike Frysinger98c52642009-04-02 10:02:37 +000011107#if ENABLE_SH_MATH_SUPPORT
Eric Andersencb57d552001-06-28 07:25:16 +000011108 if (syntax == ARISYNTAX)
Denis Vlasenko559691a2008-10-05 18:39:31 +000011109 raise_error_syntax("missing '))'");
Eric Andersenc470f442003-07-28 09:56:35 +000011110#endif
Denis Vlasenko99eb8502007-02-23 21:09:49 +000011111 if (syntax != BASESYNTAX && !parsebackquote && eofmark == NULL)
Denis Vlasenko559691a2008-10-05 18:39:31 +000011112 raise_error_syntax("unterminated quoted string");
Eric Andersencb57d552001-06-28 07:25:16 +000011113 if (varnest != 0) {
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011114 startlinno = g_parsefile->linno;
Eric Andersenc470f442003-07-28 09:56:35 +000011115 /* { */
Denis Vlasenko559691a2008-10-05 18:39:31 +000011116 raise_error_syntax("missing '}'");
Eric Andersencb57d552001-06-28 07:25:16 +000011117 }
11118 USTPUTC('\0', out);
Eric Andersenc470f442003-07-28 09:56:35 +000011119 len = out - (char *)stackblock();
Eric Andersencb57d552001-06-28 07:25:16 +000011120 out = stackblock();
11121 if (eofmark == NULL) {
Denis Vlasenko5e34ff22009-04-21 11:09:40 +000011122 if ((c == '>' || c == '<' IF_ASH_BASH_COMPAT( || c == 0x100 + '>'))
Denis Vlasenko834dee72008-10-07 09:18:30 +000011123 && quotef == 0
11124 ) {
Denis Vlasenko559691a2008-10-05 18:39:31 +000011125 if (isdigit_str9(out)) {
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000011126 PARSEREDIR(); /* passed as params: out, c */
11127 lasttoken = TREDIR;
11128 return lasttoken;
11129 }
11130 /* else: non-number X seen, interpret it
11131 * as "NNNX>file" = "NNNX >file" */
Eric Andersencb57d552001-06-28 07:25:16 +000011132 }
Denis Vlasenkoef527f52008-06-23 01:52:30 +000011133 pungetc();
Eric Andersencb57d552001-06-28 07:25:16 +000011134 }
11135 quoteflag = quotef;
11136 backquotelist = bqlist;
11137 grabstackblock(len);
11138 wordtext = out;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011139 lasttoken = TWORD;
11140 return lasttoken;
Eric Andersencb57d552001-06-28 07:25:16 +000011141/* end of readtoken routine */
11142
Eric Andersencb57d552001-06-28 07:25:16 +000011143/*
11144 * Check to see whether we are at the end of the here document. When this
11145 * is called, c is set to the first character of the next input line. If
11146 * we are at the end of the here document, this routine sets the c to PEOF.
11147 */
Eric Andersenc470f442003-07-28 09:56:35 +000011148checkend: {
11149 if (eofmark) {
Denis Vlasenko131ae172007-02-18 13:00:19 +000011150#if ENABLE_ASH_ALIAS
Denys Vlasenko2ce42e92009-11-29 02:18:13 +010011151 if (c == PEOA)
11152 c = pgetc_without_PEOA();
Eric Andersenc470f442003-07-28 09:56:35 +000011153#endif
11154 if (striptabs) {
11155 while (c == '\t') {
Denys Vlasenko2ce42e92009-11-29 02:18:13 +010011156 c = pgetc_without_PEOA();
Eric Andersencb57d552001-06-28 07:25:16 +000011157 }
Eric Andersenc470f442003-07-28 09:56:35 +000011158 }
11159 if (c == *eofmark) {
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011160 if (pfgets(line, sizeof(line)) != NULL) {
Eric Andersenc470f442003-07-28 09:56:35 +000011161 char *p, *q;
Eric Andersencb57d552001-06-28 07:25:16 +000011162
Eric Andersenc470f442003-07-28 09:56:35 +000011163 p = line;
Denis Vlasenkof7d56652008-03-25 05:51:41 +000011164 for (q = eofmark + 1; *q && *p == *q; p++, q++)
11165 continue;
Eric Andersenc470f442003-07-28 09:56:35 +000011166 if (*p == '\n' && *q == '\0') {
11167 c = PEOF;
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011168 g_parsefile->linno++;
Eric Andersenc470f442003-07-28 09:56:35 +000011169 needprompt = doprompt;
11170 } else {
11171 pushstring(line, NULL);
Eric Andersencb57d552001-06-28 07:25:16 +000011172 }
11173 }
11174 }
11175 }
Eric Andersenc470f442003-07-28 09:56:35 +000011176 goto checkend_return;
11177}
Eric Andersencb57d552001-06-28 07:25:16 +000011178
Eric Andersencb57d552001-06-28 07:25:16 +000011179/*
11180 * Parse a redirection operator. The variable "out" points to a string
11181 * specifying the fd to be redirected. The variable "c" contains the
11182 * first character of the redirection operator.
11183 */
Eric Andersenc470f442003-07-28 09:56:35 +000011184parseredir: {
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000011185 /* out is already checked to be a valid number or "" */
11186 int fd = (*out == '\0' ? -1 : atoi(out));
Eric Andersenc470f442003-07-28 09:56:35 +000011187 union node *np;
Eric Andersencb57d552001-06-28 07:25:16 +000011188
Denis Vlasenko597906c2008-02-20 16:38:54 +000011189 np = stzalloc(sizeof(struct nfile));
Eric Andersenc470f442003-07-28 09:56:35 +000011190 if (c == '>') {
11191 np->nfile.fd = 1;
11192 c = pgetc();
11193 if (c == '>')
11194 np->type = NAPPEND;
11195 else if (c == '|')
11196 np->type = NCLOBBER;
11197 else if (c == '&')
11198 np->type = NTOFD;
Denis Vlasenko559691a2008-10-05 18:39:31 +000011199 /* it also can be NTO2 (>&file), but we can't figure it out yet */
Eric Andersenc470f442003-07-28 09:56:35 +000011200 else {
11201 np->type = NTO;
11202 pungetc();
Eric Andersencb57d552001-06-28 07:25:16 +000011203 }
Denis Vlasenko834dee72008-10-07 09:18:30 +000011204 }
11205#if ENABLE_ASH_BASH_COMPAT
11206 else if (c == 0x100 + '>') { /* this flags &> redirection */
11207 np->nfile.fd = 1;
11208 pgetc(); /* this is '>', no need to check */
11209 np->type = NTO2;
11210 }
11211#endif
11212 else { /* c == '<' */
Denis Vlasenko597906c2008-02-20 16:38:54 +000011213 /*np->nfile.fd = 0; - stzalloc did it */
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011214 c = pgetc();
11215 switch (c) {
Eric Andersenc470f442003-07-28 09:56:35 +000011216 case '<':
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011217 if (sizeof(struct nfile) != sizeof(struct nhere)) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000011218 np = stzalloc(sizeof(struct nhere));
11219 /*np->nfile.fd = 0; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000011220 }
11221 np->type = NHERE;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000011222 heredoc = stzalloc(sizeof(struct heredoc));
Eric Andersenc470f442003-07-28 09:56:35 +000011223 heredoc->here = np;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011224 c = pgetc();
11225 if (c == '-') {
Eric Andersenc470f442003-07-28 09:56:35 +000011226 heredoc->striptabs = 1;
11227 } else {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000011228 /*heredoc->striptabs = 0; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000011229 pungetc();
11230 }
11231 break;
11232
11233 case '&':
11234 np->type = NFROMFD;
11235 break;
11236
11237 case '>':
11238 np->type = NFROMTO;
11239 break;
11240
11241 default:
11242 np->type = NFROM;
11243 pungetc();
11244 break;
11245 }
Eric Andersencb57d552001-06-28 07:25:16 +000011246 }
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000011247 if (fd >= 0)
11248 np->nfile.fd = fd;
Eric Andersenc470f442003-07-28 09:56:35 +000011249 redirnode = np;
11250 goto parseredir_return;
11251}
Eric Andersencb57d552001-06-28 07:25:16 +000011252
Eric Andersencb57d552001-06-28 07:25:16 +000011253/*
11254 * Parse a substitution. At this point, we have read the dollar sign
11255 * and nothing else.
11256 */
Denis Vlasenkocc571512007-02-23 21:10:35 +000011257
11258/* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
11259 * (assuming ascii char codes, as the original implementation did) */
11260#define is_special(c) \
Denis Vlasenkoef527f52008-06-23 01:52:30 +000011261 (((unsigned)(c) - 33 < 32) \
11262 && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
Eric Andersenc470f442003-07-28 09:56:35 +000011263parsesub: {
Denys Vlasenkocd716832009-11-28 22:14:02 +010011264 unsigned char subtype;
Eric Andersenc470f442003-07-28 09:56:35 +000011265 int typeloc;
11266 int flags;
11267 char *p;
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011268 static const char types[] ALIGN1 = "}-+?=";
Eric Andersencb57d552001-06-28 07:25:16 +000011269
Eric Andersenc470f442003-07-28 09:56:35 +000011270 c = pgetc();
Denys Vlasenkocd716832009-11-28 22:14:02 +010011271 if (c > 255 /* PEOA or PEOF */
Denis Vlasenkoef527f52008-06-23 01:52:30 +000011272 || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
Eric Andersenc470f442003-07-28 09:56:35 +000011273 ) {
Denis Vlasenkoef527f52008-06-23 01:52:30 +000011274#if ENABLE_ASH_BASH_COMPAT
11275 if (c == '\'')
11276 bash_dollar_squote = 1;
11277 else
11278#endif
11279 USTPUTC('$', out);
Eric Andersenc470f442003-07-28 09:56:35 +000011280 pungetc();
11281 } else if (c == '(') { /* $(command) or $((arith)) */
11282 if (pgetc() == '(') {
Mike Frysinger98c52642009-04-02 10:02:37 +000011283#if ENABLE_SH_MATH_SUPPORT
Eric Andersenc470f442003-07-28 09:56:35 +000011284 PARSEARITH();
11285#else
Mike Frysinger98a6f562008-06-09 09:38:45 +000011286 raise_error_syntax("you disabled math support for $((arith)) syntax");
Eric Andersenc470f442003-07-28 09:56:35 +000011287#endif
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000011288 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000011289 pungetc();
11290 PARSEBACKQNEW();
11291 }
11292 } else {
11293 USTPUTC(CTLVAR, out);
11294 typeloc = out - (char *)stackblock();
11295 USTPUTC(VSNORMAL, out);
11296 subtype = VSNORMAL;
11297 if (c == '{') {
11298 c = pgetc();
11299 if (c == '#') {
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011300 c = pgetc();
11301 if (c == '}')
Eric Andersenc470f442003-07-28 09:56:35 +000011302 c = '#';
11303 else
11304 subtype = VSLENGTH;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011305 } else
Eric Andersenc470f442003-07-28 09:56:35 +000011306 subtype = 0;
11307 }
Denys Vlasenkocd716832009-11-28 22:14:02 +010011308 if (c <= 255 /* not PEOA or PEOF */ && is_name(c)) {
Eric Andersenc470f442003-07-28 09:56:35 +000011309 do {
11310 STPUTC(c, out);
Eric Andersencb57d552001-06-28 07:25:16 +000011311 c = pgetc();
Denys Vlasenkocd716832009-11-28 22:14:02 +010011312 } while (c <= 255 /* not PEOA or PEOF */ && is_in_name(c));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011313 } else if (isdigit(c)) {
Eric Andersenc470f442003-07-28 09:56:35 +000011314 do {
11315 STPUTC(c, out);
11316 c = pgetc();
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011317 } while (isdigit(c));
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011318 } else if (is_special(c)) {
Eric Andersenc470f442003-07-28 09:56:35 +000011319 USTPUTC(c, out);
11320 c = pgetc();
Denis Vlasenko559691a2008-10-05 18:39:31 +000011321 } else {
11322 badsub:
11323 raise_error_syntax("bad substitution");
11324 }
Cristian Ionescu-Idbohrn301f5ec2009-10-05 02:07:23 +020011325 if (c != '}' && subtype == VSLENGTH)
11326 goto badsub;
Eric Andersencb57d552001-06-28 07:25:16 +000011327
Eric Andersenc470f442003-07-28 09:56:35 +000011328 STPUTC('=', out);
11329 flags = 0;
11330 if (subtype == 0) {
11331 switch (c) {
11332 case ':':
Eric Andersenc470f442003-07-28 09:56:35 +000011333 c = pgetc();
Denis Vlasenko92e13c22008-03-25 01:17:40 +000011334#if ENABLE_ASH_BASH_COMPAT
11335 if (c == ':' || c == '$' || isdigit(c)) {
11336 pungetc();
11337 subtype = VSSUBSTR;
11338 break;
11339 }
11340#endif
11341 flags = VSNUL;
Eric Andersenc470f442003-07-28 09:56:35 +000011342 /*FALLTHROUGH*/
11343 default:
11344 p = strchr(types, c);
11345 if (p == NULL)
11346 goto badsub;
11347 subtype = p - types + VSNORMAL;
11348 break;
11349 case '%':
Denis Vlasenko92e13c22008-03-25 01:17:40 +000011350 case '#': {
11351 int cc = c;
11352 subtype = c == '#' ? VSTRIMLEFT : VSTRIMRIGHT;
11353 c = pgetc();
11354 if (c == cc)
11355 subtype++;
11356 else
11357 pungetc();
11358 break;
11359 }
11360#if ENABLE_ASH_BASH_COMPAT
11361 case '/':
11362 subtype = VSREPLACE;
11363 c = pgetc();
11364 if (c == '/')
11365 subtype++; /* VSREPLACEALL */
11366 else
11367 pungetc();
11368 break;
11369#endif
Eric Andersencb57d552001-06-28 07:25:16 +000011370 }
Eric Andersenc470f442003-07-28 09:56:35 +000011371 } else {
11372 pungetc();
11373 }
11374 if (dblquote || arinest)
11375 flags |= VSQUOTE;
Denys Vlasenkocd716832009-11-28 22:14:02 +010011376 ((unsigned char *)stackblock())[typeloc] = subtype | flags;
Eric Andersenc470f442003-07-28 09:56:35 +000011377 if (subtype != VSNORMAL) {
11378 varnest++;
11379 if (dblquote || arinest) {
11380 dqvarnest++;
Eric Andersencb57d552001-06-28 07:25:16 +000011381 }
11382 }
11383 }
Eric Andersenc470f442003-07-28 09:56:35 +000011384 goto parsesub_return;
11385}
Eric Andersencb57d552001-06-28 07:25:16 +000011386
Eric Andersencb57d552001-06-28 07:25:16 +000011387/*
11388 * Called to parse command substitutions. Newstyle is set if the command
11389 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
11390 * list of commands (passed by reference), and savelen is the number of
11391 * characters on the top of the stack which must be preserved.
11392 */
Eric Andersenc470f442003-07-28 09:56:35 +000011393parsebackq: {
11394 struct nodelist **nlpp;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011395 smallint savepbq;
Eric Andersenc470f442003-07-28 09:56:35 +000011396 union node *n;
11397 char *volatile str;
11398 struct jmploc jmploc;
11399 struct jmploc *volatile savehandler;
11400 size_t savelen;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011401 smallint saveprompt = 0;
11402
Eric Andersencb57d552001-06-28 07:25:16 +000011403#ifdef __GNUC__
Eric Andersenc470f442003-07-28 09:56:35 +000011404 (void) &saveprompt;
Eric Andersencb57d552001-06-28 07:25:16 +000011405#endif
Eric Andersenc470f442003-07-28 09:56:35 +000011406 savepbq = parsebackquote;
11407 if (setjmp(jmploc.loc)) {
Denis Vlasenko60818682007-09-28 22:07:23 +000011408 free(str);
Eric Andersenc470f442003-07-28 09:56:35 +000011409 parsebackquote = 0;
Denis Vlasenko2da584f2007-02-19 22:44:05 +000011410 exception_handler = savehandler;
11411 longjmp(exception_handler->loc, 1);
Eric Andersenc470f442003-07-28 09:56:35 +000011412 }
Denis Vlasenkob012b102007-02-19 22:43:01 +000011413 INT_OFF;
Eric Andersenc470f442003-07-28 09:56:35 +000011414 str = NULL;
11415 savelen = out - (char *)stackblock();
11416 if (savelen > 0) {
11417 str = ckmalloc(savelen);
11418 memcpy(str, stackblock(), savelen);
11419 }
Denis Vlasenko2da584f2007-02-19 22:44:05 +000011420 savehandler = exception_handler;
11421 exception_handler = &jmploc;
Denis Vlasenkob012b102007-02-19 22:43:01 +000011422 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +000011423 if (oldstyle) {
11424 /* We must read until the closing backquote, giving special
11425 treatment to some slashes, and then push the string and
11426 reread it as input, interpreting it normally. */
11427 char *pout;
11428 int pc;
11429 size_t psavelen;
11430 char *pstr;
11431
11432
11433 STARTSTACKSTR(pout);
11434 for (;;) {
11435 if (needprompt) {
11436 setprompt(2);
Eric Andersenc470f442003-07-28 09:56:35 +000011437 }
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011438 pc = pgetc();
11439 switch (pc) {
Eric Andersenc470f442003-07-28 09:56:35 +000011440 case '`':
11441 goto done;
11442
11443 case '\\':
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011444 pc = pgetc();
11445 if (pc == '\n') {
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011446 g_parsefile->linno++;
Eric Andersenc470f442003-07-28 09:56:35 +000011447 if (doprompt)
11448 setprompt(2);
11449 /*
11450 * If eating a newline, avoid putting
11451 * the newline into the new character
11452 * stream (via the STPUTC after the
11453 * switch).
11454 */
11455 continue;
11456 }
11457 if (pc != '\\' && pc != '`' && pc != '$'
Denys Vlasenko76bc2d62009-11-29 01:37:46 +010011458 && (!dblquote || pc != '"')
11459 ) {
Eric Andersenc470f442003-07-28 09:56:35 +000011460 STPUTC('\\', pout);
Denys Vlasenko76bc2d62009-11-29 01:37:46 +010011461 }
Denys Vlasenkocd716832009-11-28 22:14:02 +010011462 if (pc <= 255 /* not PEOA or PEOF */) {
Eric Andersenc470f442003-07-28 09:56:35 +000011463 break;
11464 }
11465 /* fall through */
11466
11467 case PEOF:
Denys Vlasenko2ce42e92009-11-29 02:18:13 +010011468 IF_ASH_ALIAS(case PEOA:)
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011469 startlinno = g_parsefile->linno;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000011470 raise_error_syntax("EOF in backquote substitution");
Eric Andersenc470f442003-07-28 09:56:35 +000011471
11472 case '\n':
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011473 g_parsefile->linno++;
Eric Andersenc470f442003-07-28 09:56:35 +000011474 needprompt = doprompt;
11475 break;
11476
11477 default:
11478 break;
11479 }
11480 STPUTC(pc, pout);
11481 }
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011482 done:
Eric Andersenc470f442003-07-28 09:56:35 +000011483 STPUTC('\0', pout);
11484 psavelen = pout - (char *)stackblock();
11485 if (psavelen > 0) {
11486 pstr = grabstackstr(pout);
11487 setinputstring(pstr);
11488 }
11489 }
11490 nlpp = &bqlist;
11491 while (*nlpp)
11492 nlpp = &(*nlpp)->next;
Denis Vlasenko597906c2008-02-20 16:38:54 +000011493 *nlpp = stzalloc(sizeof(**nlpp));
11494 /* (*nlpp)->next = NULL; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000011495 parsebackquote = oldstyle;
11496
11497 if (oldstyle) {
11498 saveprompt = doprompt;
11499 doprompt = 0;
Eric Andersencb57d552001-06-28 07:25:16 +000011500 }
11501
Eric Andersenc470f442003-07-28 09:56:35 +000011502 n = list(2);
11503
11504 if (oldstyle)
11505 doprompt = saveprompt;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011506 else if (readtoken() != TRP)
11507 raise_error_unexpected_syntax(TRP);
Eric Andersenc470f442003-07-28 09:56:35 +000011508
11509 (*nlpp)->n = n;
11510 if (oldstyle) {
11511 /*
11512 * Start reading from old file again, ignoring any pushed back
11513 * tokens left from the backquote parsing
11514 */
11515 popfile();
11516 tokpushback = 0;
11517 }
11518 while (stackblocksize() <= savelen)
11519 growstackblock();
11520 STARTSTACKSTR(out);
11521 if (str) {
11522 memcpy(out, str, savelen);
11523 STADJUST(savelen, out);
Denis Vlasenkob012b102007-02-19 22:43:01 +000011524 INT_OFF;
11525 free(str);
Eric Andersenc470f442003-07-28 09:56:35 +000011526 str = NULL;
Denis Vlasenkob012b102007-02-19 22:43:01 +000011527 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +000011528 }
11529 parsebackquote = savepbq;
Denis Vlasenko2da584f2007-02-19 22:44:05 +000011530 exception_handler = savehandler;
Eric Andersenc470f442003-07-28 09:56:35 +000011531 if (arinest || dblquote)
11532 USTPUTC(CTLBACKQ | CTLQUOTE, out);
11533 else
11534 USTPUTC(CTLBACKQ, out);
11535 if (oldstyle)
11536 goto parsebackq_oldreturn;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000011537 goto parsebackq_newreturn;
Eric Andersenc470f442003-07-28 09:56:35 +000011538}
11539
Mike Frysinger98c52642009-04-02 10:02:37 +000011540#if ENABLE_SH_MATH_SUPPORT
Eric Andersencb57d552001-06-28 07:25:16 +000011541/*
11542 * Parse an arithmetic expansion (indicate start of one and set state)
11543 */
Eric Andersenc470f442003-07-28 09:56:35 +000011544parsearith: {
Eric Andersenc470f442003-07-28 09:56:35 +000011545 if (++arinest == 1) {
11546 prevsyntax = syntax;
11547 syntax = ARISYNTAX;
11548 USTPUTC(CTLARI, out);
11549 if (dblquote)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000011550 USTPUTC('"', out);
Eric Andersenc470f442003-07-28 09:56:35 +000011551 else
Denis Vlasenkoa624c112007-02-19 22:45:43 +000011552 USTPUTC(' ', out);
Eric Andersenc470f442003-07-28 09:56:35 +000011553 } else {
11554 /*
11555 * we collapse embedded arithmetic expansion to
11556 * parenthesis, which should be equivalent
11557 */
11558 USTPUTC('(', out);
Eric Andersencb57d552001-06-28 07:25:16 +000011559 }
Eric Andersenc470f442003-07-28 09:56:35 +000011560 goto parsearith_return;
11561}
11562#endif
Eric Andersencb57d552001-06-28 07:25:16 +000011563
Eric Andersenc470f442003-07-28 09:56:35 +000011564} /* end of readtoken */
11565
Eric Andersencb57d552001-06-28 07:25:16 +000011566/*
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011567 * Read the next input token.
11568 * If the token is a word, we set backquotelist to the list of cmds in
11569 * backquotes. We set quoteflag to true if any part of the word was
11570 * quoted.
11571 * If the token is TREDIR, then we set redirnode to a structure containing
11572 * the redirection.
11573 * In all cases, the variable startlinno is set to the number of the line
11574 * on which the token starts.
11575 *
11576 * [Change comment: here documents and internal procedures]
11577 * [Readtoken shouldn't have any arguments. Perhaps we should make the
11578 * word parsing code into a separate routine. In this case, readtoken
11579 * doesn't need to have any internal procedures, but parseword does.
11580 * We could also make parseoperator in essence the main routine, and
11581 * have parseword (readtoken1?) handle both words and redirection.]
Eric Andersencb57d552001-06-28 07:25:16 +000011582 */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011583#define NEW_xxreadtoken
11584#ifdef NEW_xxreadtoken
11585/* singles must be first! */
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011586static const char xxreadtoken_chars[7] ALIGN1 = {
Denis Vlasenko834dee72008-10-07 09:18:30 +000011587 '\n', '(', ')', /* singles */
11588 '&', '|', ';', /* doubles */
11589 0
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011590};
Eric Andersencb57d552001-06-28 07:25:16 +000011591
Denis Vlasenko834dee72008-10-07 09:18:30 +000011592#define xxreadtoken_singles 3
11593#define xxreadtoken_doubles 3
11594
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011595static const char xxreadtoken_tokens[] ALIGN1 = {
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011596 TNL, TLP, TRP, /* only single occurrence allowed */
11597 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
11598 TEOF, /* corresponds to trailing nul */
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011599 TAND, TOR, TENDCASE /* if double occurrence */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011600};
11601
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011602static int
11603xxreadtoken(void)
11604{
11605 int c;
11606
11607 if (tokpushback) {
11608 tokpushback = 0;
11609 return lasttoken;
Eric Andersencb57d552001-06-28 07:25:16 +000011610 }
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011611 if (needprompt) {
11612 setprompt(2);
11613 }
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011614 startlinno = g_parsefile->linno;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011615 for (;;) { /* until token or start of word found */
Denis Vlasenko834dee72008-10-07 09:18:30 +000011616 c = pgetc_fast();
Denis Vlasenko5e34ff22009-04-21 11:09:40 +000011617 if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011618 continue;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011619
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011620 if (c == '#') {
11621 while ((c = pgetc()) != '\n' && c != PEOF)
11622 continue;
11623 pungetc();
11624 } else if (c == '\\') {
11625 if (pgetc() != '\n') {
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011626 pungetc();
Denis Vlasenko834dee72008-10-07 09:18:30 +000011627 break; /* return readtoken1(...) */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011628 }
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011629 startlinno = ++g_parsefile->linno;
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011630 if (doprompt)
11631 setprompt(2);
11632 } else {
11633 const char *p;
11634
11635 p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
11636 if (c != PEOF) {
11637 if (c == '\n') {
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011638 g_parsefile->linno++;
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011639 needprompt = doprompt;
11640 }
11641
11642 p = strchr(xxreadtoken_chars, c);
Denis Vlasenko834dee72008-10-07 09:18:30 +000011643 if (p == NULL)
11644 break; /* return readtoken1(...) */
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011645
Denis Vlasenko834dee72008-10-07 09:18:30 +000011646 if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
11647 int cc = pgetc();
11648 if (cc == c) { /* double occurrence? */
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011649 p += xxreadtoken_doubles + 1;
11650 } else {
11651 pungetc();
Denis Vlasenko834dee72008-10-07 09:18:30 +000011652#if ENABLE_ASH_BASH_COMPAT
11653 if (c == '&' && cc == '>') /* &> */
11654 break; /* return readtoken1(...) */
11655#endif
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011656 }
11657 }
11658 }
11659 lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
11660 return lasttoken;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011661 }
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011662 } /* for (;;) */
Denis Vlasenko834dee72008-10-07 09:18:30 +000011663
11664 return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011665}
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011666#else /* old xxreadtoken */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011667#define RETURN(token) return lasttoken = token
11668static int
11669xxreadtoken(void)
11670{
11671 int c;
11672
11673 if (tokpushback) {
11674 tokpushback = 0;
11675 return lasttoken;
11676 }
11677 if (needprompt) {
11678 setprompt(2);
11679 }
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011680 startlinno = g_parsefile->linno;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011681 for (;;) { /* until token or start of word found */
Denis Vlasenko834dee72008-10-07 09:18:30 +000011682 c = pgetc_fast();
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011683 switch (c) {
11684 case ' ': case '\t':
Denys Vlasenko2ce42e92009-11-29 02:18:13 +010011685 IF_ASH_ALIAS(case PEOA:)
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011686 continue;
11687 case '#':
Denis Vlasenkof7d56652008-03-25 05:51:41 +000011688 while ((c = pgetc()) != '\n' && c != PEOF)
11689 continue;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011690 pungetc();
11691 continue;
11692 case '\\':
11693 if (pgetc() == '\n') {
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011694 startlinno = ++g_parsefile->linno;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011695 if (doprompt)
11696 setprompt(2);
11697 continue;
11698 }
11699 pungetc();
11700 goto breakloop;
11701 case '\n':
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011702 g_parsefile->linno++;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011703 needprompt = doprompt;
11704 RETURN(TNL);
11705 case PEOF:
11706 RETURN(TEOF);
11707 case '&':
11708 if (pgetc() == '&')
11709 RETURN(TAND);
11710 pungetc();
11711 RETURN(TBACKGND);
11712 case '|':
11713 if (pgetc() == '|')
11714 RETURN(TOR);
11715 pungetc();
11716 RETURN(TPIPE);
11717 case ';':
11718 if (pgetc() == ';')
11719 RETURN(TENDCASE);
11720 pungetc();
11721 RETURN(TSEMI);
11722 case '(':
11723 RETURN(TLP);
11724 case ')':
11725 RETURN(TRP);
11726 default:
11727 goto breakloop;
11728 }
11729 }
11730 breakloop:
11731 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
11732#undef RETURN
11733}
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011734#endif /* old xxreadtoken */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011735
11736static int
11737readtoken(void)
11738{
11739 int t;
11740#if DEBUG
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011741 smallint alreadyseen = tokpushback;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011742#endif
11743
11744#if ENABLE_ASH_ALIAS
11745 top:
11746#endif
11747
11748 t = xxreadtoken();
11749
11750 /*
11751 * eat newlines
11752 */
11753 if (checkkwd & CHKNL) {
11754 while (t == TNL) {
11755 parseheredoc();
11756 t = xxreadtoken();
11757 }
11758 }
11759
11760 if (t != TWORD || quoteflag) {
11761 goto out;
11762 }
11763
11764 /*
11765 * check for keywords
11766 */
11767 if (checkkwd & CHKKWD) {
11768 const char *const *pp;
11769
11770 pp = findkwd(wordtext);
11771 if (pp) {
11772 lasttoken = t = pp - tokname_array;
Denys Vlasenkoa0ec4f52010-05-20 12:50:42 +020011773 TRACE(("keyword '%s' recognized\n", tokname_array[t] + 1));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011774 goto out;
11775 }
11776 }
11777
11778 if (checkkwd & CHKALIAS) {
11779#if ENABLE_ASH_ALIAS
11780 struct alias *ap;
11781 ap = lookupalias(wordtext, 1);
11782 if (ap != NULL) {
11783 if (*ap->val) {
11784 pushstring(ap->val, ap);
11785 }
11786 goto top;
11787 }
11788#endif
11789 }
11790 out:
11791 checkkwd = 0;
11792#if DEBUG
11793 if (!alreadyseen)
Denys Vlasenkoa0ec4f52010-05-20 12:50:42 +020011794 TRACE(("token '%s' %s\n", tokname_array[t] + 1, t == TWORD ? wordtext : ""));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011795 else
Denys Vlasenkoa0ec4f52010-05-20 12:50:42 +020011796 TRACE(("reread token '%s' %s\n", tokname_array[t] + 1, t == TWORD ? wordtext : ""));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011797#endif
11798 return t;
Eric Andersencb57d552001-06-28 07:25:16 +000011799}
11800
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011801static char
11802peektoken(void)
11803{
11804 int t;
11805
11806 t = readtoken();
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011807 tokpushback = 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011808 return tokname_array[t][0];
11809}
Eric Andersencb57d552001-06-28 07:25:16 +000011810
11811/*
Denys Vlasenko86e83ec2009-07-23 22:07:07 +020011812 * Read and parse a command. Returns NODE_EOF on end of file.
11813 * (NULL is a valid parse tree indicating a blank line.)
Eric Andersencb57d552001-06-28 07:25:16 +000011814 */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011815static union node *
11816parsecmd(int interact)
Eric Andersen90898442003-08-06 11:20:52 +000011817{
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011818 int t;
Eric Andersencb57d552001-06-28 07:25:16 +000011819
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011820 tokpushback = 0;
11821 doprompt = interact;
11822 if (doprompt)
11823 setprompt(doprompt);
11824 needprompt = 0;
11825 t = readtoken();
11826 if (t == TEOF)
Denys Vlasenko86e83ec2009-07-23 22:07:07 +020011827 return NODE_EOF;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011828 if (t == TNL)
11829 return NULL;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011830 tokpushback = 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011831 return list(1);
11832}
11833
11834/*
11835 * Input any here documents.
11836 */
11837static void
11838parseheredoc(void)
11839{
11840 struct heredoc *here;
11841 union node *n;
11842
11843 here = heredoclist;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000011844 heredoclist = NULL;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011845
11846 while (here) {
11847 if (needprompt) {
11848 setprompt(2);
11849 }
11850 readtoken1(pgetc(), here->here->type == NHERE? SQSYNTAX : DQSYNTAX,
11851 here->eofmark, here->striptabs);
Denis Vlasenko597906c2008-02-20 16:38:54 +000011852 n = stzalloc(sizeof(struct narg));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011853 n->narg.type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000011854 /*n->narg.next = NULL; - stzalloc did it */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011855 n->narg.text = wordtext;
11856 n->narg.backquote = backquotelist;
11857 here->here->nhere.doc = n;
11858 here = here->next;
Eric Andersencb57d552001-06-28 07:25:16 +000011859 }
Eric Andersencb57d552001-06-28 07:25:16 +000011860}
11861
11862
11863/*
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +000011864 * called by editline -- any expansions to the prompt should be added here.
Eric Andersencb57d552001-06-28 07:25:16 +000011865 */
Denis Vlasenko131ae172007-02-18 13:00:19 +000011866#if ENABLE_ASH_EXPAND_PRMT
"Vladimir N. Oleynik"bef14d72005-09-05 13:25:11 +000011867static const char *
11868expandstr(const char *ps)
11869{
11870 union node n;
11871
Denis Vlasenko5c2b8142009-03-19 01:59:59 +000011872 /* XXX Fix (char *) cast. It _is_ a bug. ps is variable's value,
11873 * and token processing _can_ alter it (delete NULs etc). */
"Vladimir N. Oleynik"bef14d72005-09-05 13:25:11 +000011874 setinputstring((char *)ps);
Denis Vlasenko46a53062007-09-24 18:30:02 +000011875 readtoken1(pgetc(), PSSYNTAX, nullstr, 0);
"Vladimir N. Oleynik"bef14d72005-09-05 13:25:11 +000011876 popfile();
11877
11878 n.narg.type = NARG;
11879 n.narg.next = NULL;
11880 n.narg.text = wordtext;
11881 n.narg.backquote = backquotelist;
11882
11883 expandarg(&n, NULL, 0);
11884 return stackblock();
11885}
11886#endif
11887
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011888/*
11889 * Execute a command or commands contained in a string.
11890 */
11891static int
11892evalstring(char *s, int mask)
Eric Andersenc470f442003-07-28 09:56:35 +000011893{
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011894 union node *n;
11895 struct stackmark smark;
11896 int skip;
11897
11898 setinputstring(s);
11899 setstackmark(&smark);
11900
11901 skip = 0;
Denys Vlasenko86e83ec2009-07-23 22:07:07 +020011902 while ((n = parsecmd(0)) != NODE_EOF) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011903 evaltree(n, 0);
11904 popstackmark(&smark);
11905 skip = evalskip;
11906 if (skip)
11907 break;
11908 }
11909 popfile();
11910
11911 skip &= mask;
11912 evalskip = skip;
11913 return skip;
Eric Andersenc470f442003-07-28 09:56:35 +000011914}
11915
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011916/*
11917 * The eval command.
11918 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011919static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000011920evalcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011921{
11922 char *p;
11923 char *concat;
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011924
Denis Vlasenko68404f12008-03-17 09:00:54 +000011925 if (argv[1]) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011926 p = argv[1];
Denis Vlasenko68404f12008-03-17 09:00:54 +000011927 argv += 2;
11928 if (argv[0]) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011929 STARTSTACKSTR(concat);
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011930 for (;;) {
11931 concat = stack_putstr(p, concat);
Denis Vlasenko68404f12008-03-17 09:00:54 +000011932 p = *argv++;
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011933 if (p == NULL)
11934 break;
11935 STPUTC(' ', concat);
11936 }
11937 STPUTC('\0', concat);
11938 p = grabstackstr(concat);
11939 }
11940 evalstring(p, ~SKIPEVAL);
11941
11942 }
11943 return exitstatus;
11944}
11945
11946/*
Denys Vlasenko285ad152009-12-04 23:02:27 +010011947 * Read and execute commands.
11948 * "Top" is nonzero for the top level command loop;
11949 * it turns on prompting if the shell is interactive.
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011950 */
11951static int
11952cmdloop(int top)
11953{
11954 union node *n;
11955 struct stackmark smark;
11956 int inter;
11957 int numeof = 0;
11958
11959 TRACE(("cmdloop(%d) called\n", top));
11960 for (;;) {
11961 int skip;
11962
11963 setstackmark(&smark);
11964#if JOBS
Denis Vlasenkob07a4962008-06-22 13:16:23 +000011965 if (doing_jobctl)
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011966 showjobs(stderr, SHOW_CHANGED);
11967#endif
11968 inter = 0;
11969 if (iflag && top) {
11970 inter++;
11971#if ENABLE_ASH_MAIL
11972 chkmail();
11973#endif
11974 }
11975 n = parsecmd(inter);
Denys Vlasenko7cee00e2009-07-24 01:08:03 +020011976#if DEBUG
11977 if (DEBUG > 2 && debug && (n != NODE_EOF))
Denys Vlasenko883cea42009-07-11 15:31:59 +020011978 showtree(n);
Denis Vlasenko135cecb2009-04-12 00:00:57 +000011979#endif
Denys Vlasenko86e83ec2009-07-23 22:07:07 +020011980 if (n == NODE_EOF) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011981 if (!top || numeof >= 50)
11982 break;
11983 if (!stoppedjobs()) {
11984 if (!Iflag)
11985 break;
11986 out2str("\nUse \"exit\" to leave shell.\n");
11987 }
11988 numeof++;
11989 } else if (nflag == 0) {
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +000011990 /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
11991 job_warning >>= 1;
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011992 numeof = 0;
11993 evaltree(n, 0);
11994 }
11995 popstackmark(&smark);
11996 skip = evalskip;
11997
11998 if (skip) {
11999 evalskip = 0;
12000 return skip & SKIPEVAL;
12001 }
12002 }
12003 return 0;
12004}
12005
Denis Vlasenko0dec6de2007-02-23 21:10:47 +000012006/*
12007 * Take commands from a file. To be compatible we should do a path
12008 * search for the file, which is necessary to find sub-commands.
12009 */
12010static char *
12011find_dot_file(char *name)
12012{
12013 char *fullname;
12014 const char *path = pathval();
12015 struct stat statb;
12016
12017 /* don't try this for absolute or relative paths */
12018 if (strchr(name, '/'))
12019 return name;
12020
Denis Vlasenko8ad78e12009-02-15 12:40:30 +000012021 /* IIRC standards do not say whether . is to be searched.
12022 * And it is even smaller this way, making it unconditional for now:
12023 */
12024 if (1) { /* ENABLE_ASH_BASH_COMPAT */
12025 fullname = name;
12026 goto try_cur_dir;
12027 }
12028
Denys Vlasenko82a6fb32009-06-14 19:42:12 +020012029 while ((fullname = path_advance(&path, name)) != NULL) {
Denis Vlasenko8ad78e12009-02-15 12:40:30 +000012030 try_cur_dir:
Denis Vlasenko0dec6de2007-02-23 21:10:47 +000012031 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
12032 /*
12033 * Don't bother freeing here, since it will
12034 * be freed by the caller.
12035 */
12036 return fullname;
12037 }
Denys Vlasenko82a6fb32009-06-14 19:42:12 +020012038 if (fullname != name)
12039 stunalloc(fullname);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +000012040 }
12041
12042 /* not found in the PATH */
12043 ash_msg_and_raise_error("%s: not found", name);
12044 /* NOTREACHED */
12045}
12046
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012047static int FAST_FUNC
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012048dotcmd(int argc, char **argv)
12049{
Denys Vlasenkoe66cf822010-05-18 09:12:53 +020012050 char *fullname;
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012051 struct strlist *sp;
12052 volatile struct shparam saveparam;
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012053
12054 for (sp = cmdenviron; sp; sp = sp->next)
Denis Vlasenko4222ae42007-02-25 02:37:49 +000012055 setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012056
Denys Vlasenkoe66cf822010-05-18 09:12:53 +020012057 if (!argv[1]) {
12058 /* bash says: "bash: .: filename argument required" */
12059 return 2; /* bash compat */
12060 }
12061
Denys Vlasenkocd10dc42010-05-17 17:10:46 +020012062 /* "false; . empty_file; echo $?" should print 0, not 1: */
12063 exitstatus = 0;
12064
Denys Vlasenkoe66cf822010-05-18 09:12:53 +020012065 fullname = find_dot_file(argv[1]);
Denys Vlasenkocd10dc42010-05-17 17:10:46 +020012066
Denys Vlasenkoe66cf822010-05-18 09:12:53 +020012067 argv += 2;
12068 argc -= 2;
12069 if (argc) { /* argc > 0, argv[0] != NULL */
12070 saveparam = shellparam;
12071 shellparam.malloced = 0;
12072 shellparam.nparam = argc;
12073 shellparam.p = argv;
12074 };
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012075
Denys Vlasenkoe66cf822010-05-18 09:12:53 +020012076 setinputfile(fullname, INPUT_PUSH_FILE);
12077 commandname = fullname;
12078 cmdloop(0);
12079 popfile();
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012080
Denys Vlasenkoe66cf822010-05-18 09:12:53 +020012081 if (argc) {
12082 freeparam(&shellparam);
12083 shellparam = saveparam;
12084 };
12085
Denys Vlasenkocd10dc42010-05-17 17:10:46 +020012086 return exitstatus;
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012087}
12088
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012089static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012090exitcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012091{
12092 if (stoppedjobs())
12093 return 0;
Denis Vlasenko68404f12008-03-17 09:00:54 +000012094 if (argv[1])
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012095 exitstatus = number(argv[1]);
12096 raise_exception(EXEXIT);
12097 /* NOTREACHED */
12098}
12099
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012100/*
12101 * Read a file containing shell functions.
12102 */
12103static void
12104readcmdfile(char *name)
12105{
12106 setinputfile(name, INPUT_PUSH_FILE);
12107 cmdloop(0);
12108 popfile();
12109}
12110
12111
Denis Vlasenkocc571512007-02-23 21:10:35 +000012112/* ============ find_command inplementation */
12113
12114/*
12115 * Resolve a command name. If you change this routine, you may have to
12116 * change the shellexec routine as well.
12117 */
12118static void
12119find_command(char *name, struct cmdentry *entry, int act, const char *path)
12120{
12121 struct tblentry *cmdp;
12122 int idx;
12123 int prev;
12124 char *fullname;
12125 struct stat statb;
12126 int e;
12127 int updatetbl;
12128 struct builtincmd *bcmd;
12129
12130 /* If name contains a slash, don't use PATH or hash table */
12131 if (strchr(name, '/') != NULL) {
12132 entry->u.index = -1;
12133 if (act & DO_ABS) {
12134 while (stat(name, &statb) < 0) {
12135#ifdef SYSV
12136 if (errno == EINTR)
12137 continue;
12138#endif
12139 entry->cmdtype = CMDUNKNOWN;
12140 return;
12141 }
12142 }
12143 entry->cmdtype = CMDNORMAL;
12144 return;
12145 }
12146
Denis Vlasenkof20de5b2007-04-29 23:42:54 +000012147/* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
Denis Vlasenkocc571512007-02-23 21:10:35 +000012148
12149 updatetbl = (path == pathval());
12150 if (!updatetbl) {
12151 act |= DO_ALTPATH;
12152 if (strstr(path, "%builtin") != NULL)
12153 act |= DO_ALTBLTIN;
12154 }
12155
12156 /* If name is in the table, check answer will be ok */
12157 cmdp = cmdlookup(name, 0);
12158 if (cmdp != NULL) {
12159 int bit;
12160
12161 switch (cmdp->cmdtype) {
12162 default:
12163#if DEBUG
12164 abort();
12165#endif
12166 case CMDNORMAL:
12167 bit = DO_ALTPATH;
12168 break;
12169 case CMDFUNCTION:
12170 bit = DO_NOFUNC;
12171 break;
12172 case CMDBUILTIN:
12173 bit = DO_ALTBLTIN;
12174 break;
12175 }
12176 if (act & bit) {
12177 updatetbl = 0;
12178 cmdp = NULL;
12179 } else if (cmdp->rehash == 0)
12180 /* if not invalidated by cd, we're done */
12181 goto success;
12182 }
12183
12184 /* If %builtin not in path, check for builtin next */
12185 bcmd = find_builtin(name);
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +000012186 if (bcmd) {
12187 if (IS_BUILTIN_REGULAR(bcmd))
12188 goto builtin_success;
12189 if (act & DO_ALTPATH) {
12190 if (!(act & DO_ALTBLTIN))
12191 goto builtin_success;
12192 } else if (builtinloc <= 0) {
12193 goto builtin_success;
Denis Vlasenko8e858e22007-03-07 09:35:43 +000012194 }
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +000012195 }
Denis Vlasenkocc571512007-02-23 21:10:35 +000012196
Denis Vlasenkof20de5b2007-04-29 23:42:54 +000012197#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko7465dbc2008-04-13 02:25:53 +000012198 {
12199 int applet_no = find_applet_by_name(name);
12200 if (applet_no >= 0) {
12201 entry->cmdtype = CMDNORMAL;
12202 entry->u.index = -2 - applet_no;
12203 return;
12204 }
Denis Vlasenkof20de5b2007-04-29 23:42:54 +000012205 }
12206#endif
12207
Denis Vlasenkocc571512007-02-23 21:10:35 +000012208 /* We have to search path. */
12209 prev = -1; /* where to start */
12210 if (cmdp && cmdp->rehash) { /* doing a rehash */
12211 if (cmdp->cmdtype == CMDBUILTIN)
12212 prev = builtinloc;
12213 else
12214 prev = cmdp->param.index;
12215 }
12216
12217 e = ENOENT;
12218 idx = -1;
12219 loop:
Denys Vlasenko82a6fb32009-06-14 19:42:12 +020012220 while ((fullname = path_advance(&path, name)) != NULL) {
Denis Vlasenkocc571512007-02-23 21:10:35 +000012221 stunalloc(fullname);
Denis Vlasenkodee82b62007-07-29 14:05:27 +000012222 /* NB: code below will still use fullname
12223 * despite it being "unallocated" */
Denis Vlasenkocc571512007-02-23 21:10:35 +000012224 idx++;
12225 if (pathopt) {
12226 if (prefix(pathopt, "builtin")) {
12227 if (bcmd)
12228 goto builtin_success;
12229 continue;
Denis Vlasenko4a9ca132008-04-12 20:07:08 +000012230 }
12231 if ((act & DO_NOFUNC)
12232 || !prefix(pathopt, "func")
12233 ) { /* ignore unimplemented options */
Denis Vlasenkocc571512007-02-23 21:10:35 +000012234 continue;
12235 }
12236 }
12237 /* if rehash, don't redo absolute path names */
12238 if (fullname[0] == '/' && idx <= prev) {
12239 if (idx < prev)
12240 continue;
12241 TRACE(("searchexec \"%s\": no change\n", name));
12242 goto success;
12243 }
12244 while (stat(fullname, &statb) < 0) {
12245#ifdef SYSV
12246 if (errno == EINTR)
12247 continue;
12248#endif
12249 if (errno != ENOENT && errno != ENOTDIR)
12250 e = errno;
12251 goto loop;
12252 }
12253 e = EACCES; /* if we fail, this will be the error */
12254 if (!S_ISREG(statb.st_mode))
12255 continue;
12256 if (pathopt) { /* this is a %func directory */
12257 stalloc(strlen(fullname) + 1);
Denis Vlasenkodee82b62007-07-29 14:05:27 +000012258 /* NB: stalloc will return space pointed by fullname
12259 * (because we don't have any intervening allocations
12260 * between stunalloc above and this stalloc) */
Denis Vlasenkocc571512007-02-23 21:10:35 +000012261 readcmdfile(fullname);
12262 cmdp = cmdlookup(name, 0);
12263 if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
12264 ash_msg_and_raise_error("%s not defined in %s", name, fullname);
12265 stunalloc(fullname);
12266 goto success;
12267 }
12268 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
12269 if (!updatetbl) {
12270 entry->cmdtype = CMDNORMAL;
12271 entry->u.index = idx;
12272 return;
12273 }
12274 INT_OFF;
12275 cmdp = cmdlookup(name, 1);
12276 cmdp->cmdtype = CMDNORMAL;
12277 cmdp->param.index = idx;
12278 INT_ON;
12279 goto success;
12280 }
12281
12282 /* We failed. If there was an entry for this command, delete it */
12283 if (cmdp && updatetbl)
12284 delete_cmd_entry();
12285 if (act & DO_ERR)
12286 ash_msg("%s: %s", name, errmsg(e, "not found"));
12287 entry->cmdtype = CMDUNKNOWN;
12288 return;
12289
12290 builtin_success:
12291 if (!updatetbl) {
12292 entry->cmdtype = CMDBUILTIN;
12293 entry->u.cmd = bcmd;
12294 return;
12295 }
12296 INT_OFF;
12297 cmdp = cmdlookup(name, 1);
12298 cmdp->cmdtype = CMDBUILTIN;
12299 cmdp->param.cmd = bcmd;
12300 INT_ON;
12301 success:
12302 cmdp->rehash = 0;
12303 entry->cmdtype = cmdp->cmdtype;
12304 entry->u = cmdp->param;
12305}
12306
12307
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012308/* ============ trap.c */
Eric Andersenc470f442003-07-28 09:56:35 +000012309
Eric Andersencb57d552001-06-28 07:25:16 +000012310/*
Eric Andersencb57d552001-06-28 07:25:16 +000012311 * The trap builtin.
12312 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012313static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012314trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersencb57d552001-06-28 07:25:16 +000012315{
12316 char *action;
12317 char **ap;
Denys Vlasenko496d5bf2010-03-26 15:52:24 +010012318 int signo, exitcode;
Eric Andersencb57d552001-06-28 07:25:16 +000012319
Eric Andersenc470f442003-07-28 09:56:35 +000012320 nextopt(nullstr);
12321 ap = argptr;
12322 if (!*ap) {
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012323 for (signo = 0; signo < NSIG; signo++) {
Denys Vlasenko21d87d42009-09-25 00:06:51 +020012324 char *tr = trap_ptr[signo];
12325 if (tr) {
Denys Vlasenkoe74aaf92009-09-27 02:05:45 +020012326 /* note: bash adds "SIG", but only if invoked
12327 * as "bash". If called as "sh", or if set -o posix,
12328 * then it prints short signal names.
12329 * We are printing short names: */
12330 out1fmt("trap -- %s %s\n",
Denys Vlasenko21d87d42009-09-25 00:06:51 +020012331 single_quote(tr),
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +000012332 get_signame(signo));
Denys Vlasenko726e1a02009-09-25 02:58:20 +020012333 /* trap_ptr != trap only if we are in special-cased `trap` code.
12334 * In this case, we will exit very soon, no need to free(). */
Denys Vlasenkoe74aaf92009-09-27 02:05:45 +020012335 /* if (trap_ptr != trap && tp[0]) */
Denys Vlasenko726e1a02009-09-25 02:58:20 +020012336 /* free(tr); */
Eric Andersencb57d552001-06-28 07:25:16 +000012337 }
12338 }
Denys Vlasenko726e1a02009-09-25 02:58:20 +020012339 /*
Denys Vlasenko21d87d42009-09-25 00:06:51 +020012340 if (trap_ptr != trap) {
12341 free(trap_ptr);
12342 trap_ptr = trap;
12343 }
Denys Vlasenko726e1a02009-09-25 02:58:20 +020012344 */
Eric Andersencb57d552001-06-28 07:25:16 +000012345 return 0;
12346 }
Denys Vlasenko21d87d42009-09-25 00:06:51 +020012347
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +000012348 action = NULL;
12349 if (ap[1])
Eric Andersencb57d552001-06-28 07:25:16 +000012350 action = *ap++;
Denys Vlasenko496d5bf2010-03-26 15:52:24 +010012351 exitcode = 0;
Eric Andersencb57d552001-06-28 07:25:16 +000012352 while (*ap) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +000012353 signo = get_signum(*ap);
Denys Vlasenko496d5bf2010-03-26 15:52:24 +010012354 if (signo < 0) {
12355 /* Mimic bash message exactly */
12356 ash_msg("%s: invalid signal specification", *ap);
12357 exitcode = 1;
12358 goto next;
12359 }
Denis Vlasenkob012b102007-02-19 22:43:01 +000012360 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +000012361 if (action) {
Denis Vlasenko9f739442006-12-16 23:49:13 +000012362 if (LONE_DASH(action))
Eric Andersencb57d552001-06-28 07:25:16 +000012363 action = NULL;
12364 else
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012365 action = ckstrdup(action);
Eric Andersencb57d552001-06-28 07:25:16 +000012366 }
Denis Vlasenko60818682007-09-28 22:07:23 +000012367 free(trap[signo]);
Denys Vlasenko238bf182010-05-18 15:49:07 +020012368 if (action)
12369 may_have_traps = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000012370 trap[signo] = action;
12371 if (signo != 0)
12372 setsignal(signo);
Denis Vlasenkob012b102007-02-19 22:43:01 +000012373 INT_ON;
Denys Vlasenko496d5bf2010-03-26 15:52:24 +010012374 next:
Eric Andersencb57d552001-06-28 07:25:16 +000012375 ap++;
12376 }
Denys Vlasenko496d5bf2010-03-26 15:52:24 +010012377 return exitcode;
Eric Andersencb57d552001-06-28 07:25:16 +000012378}
12379
Eric Andersenc470f442003-07-28 09:56:35 +000012380
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012381/* ============ Builtins */
Eric Andersenc470f442003-07-28 09:56:35 +000012382
Denis Vlasenko8e1c7152007-01-22 07:21:38 +000012383#if !ENABLE_FEATURE_SH_EXTRA_QUIET
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012384/*
12385 * Lists available builtins
12386 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012387static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012388helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersenc470f442003-07-28 09:56:35 +000012389{
Denis Vlasenko6b06cb82008-05-15 21:30:45 +000012390 unsigned col;
12391 unsigned i;
Eric Andersenc470f442003-07-28 09:56:35 +000012392
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +020012393 out1fmt(
Denis Vlasenko34d4d892009-04-04 20:24:37 +000012394 "Built-in commands:\n"
12395 "------------------\n");
Denis Vlasenkob71c6682007-07-21 15:08:09 +000012396 for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
Eric Andersenc470f442003-07-28 09:56:35 +000012397 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
Denis Vlasenko52764022007-02-24 13:42:56 +000012398 builtintab[i].name + 1);
Eric Andersenc470f442003-07-28 09:56:35 +000012399 if (col > 60) {
12400 out1fmt("\n");
12401 col = 0;
12402 }
12403 }
Denis Vlasenko80d14be2007-04-10 23:03:30 +000012404#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko1aa7e472007-11-28 06:49:03 +000012405 {
12406 const char *a = applet_names;
12407 while (*a) {
12408 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
12409 if (col > 60) {
12410 out1fmt("\n");
12411 col = 0;
12412 }
12413 a += strlen(a) + 1;
Eric Andersenc470f442003-07-28 09:56:35 +000012414 }
12415 }
12416#endif
12417 out1fmt("\n\n");
12418 return EXIT_SUCCESS;
12419}
Denis Vlasenko131ae172007-02-18 13:00:19 +000012420#endif /* FEATURE_SH_EXTRA_QUIET */
Eric Andersenc470f442003-07-28 09:56:35 +000012421
Eric Andersencb57d552001-06-28 07:25:16 +000012422/*
Eric Andersencb57d552001-06-28 07:25:16 +000012423 * The export and readonly commands.
12424 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012425static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012426exportcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +000012427{
12428 struct var *vp;
12429 char *name;
12430 const char *p;
Eric Andersenc470f442003-07-28 09:56:35 +000012431 char **aptr;
Denis Vlasenkob7304742008-10-20 08:15:51 +000012432 int flag = argv[0][0] == 'r' ? VREADONLY : VEXPORT;
Eric Andersencb57d552001-06-28 07:25:16 +000012433
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012434 if (nextopt("p") != 'p') {
12435 aptr = argptr;
12436 name = *aptr;
12437 if (name) {
12438 do {
12439 p = strchr(name, '=');
12440 if (p != NULL) {
12441 p++;
12442 } else {
12443 vp = *findvar(hashvar(name), name);
12444 if (vp) {
12445 vp->flags |= flag;
12446 continue;
12447 }
Eric Andersencb57d552001-06-28 07:25:16 +000012448 }
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012449 setvar(name, p, flag);
12450 } while ((name = *++aptr) != NULL);
12451 return 0;
12452 }
Eric Andersencb57d552001-06-28 07:25:16 +000012453 }
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012454 showvars(argv[0], flag, 0);
Eric Andersencb57d552001-06-28 07:25:16 +000012455 return 0;
12456}
12457
Eric Andersencb57d552001-06-28 07:25:16 +000012458/*
Denis Vlasenko5651bfc2007-02-23 21:08:58 +000012459 * Delete a function if it exists.
Eric Andersencb57d552001-06-28 07:25:16 +000012460 */
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012461static void
Denis Vlasenko5651bfc2007-02-23 21:08:58 +000012462unsetfunc(const char *name)
Aaron Lehmannb6ecbdc2001-12-06 03:37:38 +000012463{
Denis Vlasenko5651bfc2007-02-23 21:08:58 +000012464 struct tblentry *cmdp;
Eric Andersencb57d552001-06-28 07:25:16 +000012465
Denis Vlasenko5651bfc2007-02-23 21:08:58 +000012466 cmdp = cmdlookup(name, 0);
Denys Vlasenko1ed2fb42010-06-18 14:09:48 +020012467 if (cmdp != NULL && cmdp->cmdtype == CMDFUNCTION)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +000012468 delete_cmd_entry();
Eric Andersenc470f442003-07-28 09:56:35 +000012469}
12470
Eric Andersencb57d552001-06-28 07:25:16 +000012471/*
Eric Andersencb57d552001-06-28 07:25:16 +000012472 * The unset builtin command. We unset the function before we unset the
12473 * variable to allow a function to be unset when there is a readonly variable
12474 * with the same name.
12475 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012476static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012477unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersencb57d552001-06-28 07:25:16 +000012478{
12479 char **ap;
12480 int i;
Eric Andersenc470f442003-07-28 09:56:35 +000012481 int flag = 0;
Eric Andersencb57d552001-06-28 07:25:16 +000012482 int ret = 0;
12483
Denys Vlasenko1ed2fb42010-06-18 14:09:48 +020012484 while ((i = nextopt("vf")) != 0) {
Eric Andersenc470f442003-07-28 09:56:35 +000012485 flag = i;
Eric Andersencb57d552001-06-28 07:25:16 +000012486 }
Eric Andersencb57d552001-06-28 07:25:16 +000012487
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012488 for (ap = argptr; *ap; ap++) {
Eric Andersenc470f442003-07-28 09:56:35 +000012489 if (flag != 'f') {
12490 i = unsetvar(*ap);
12491 ret |= i;
12492 if (!(i & 2))
12493 continue;
12494 }
12495 if (flag != 'v')
Eric Andersencb57d552001-06-28 07:25:16 +000012496 unsetfunc(*ap);
Eric Andersencb57d552001-06-28 07:25:16 +000012497 }
Eric Andersenc470f442003-07-28 09:56:35 +000012498 return ret & 1;
Eric Andersencb57d552001-06-28 07:25:16 +000012499}
12500
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000012501static const unsigned char timescmd_str[] ALIGN1 = {
Manuel Novoa III 4456f252003-08-13 17:48:47 +000012502 ' ', offsetof(struct tms, tms_utime),
12503 '\n', offsetof(struct tms, tms_stime),
12504 ' ', offsetof(struct tms, tms_cutime),
12505 '\n', offsetof(struct tms, tms_cstime),
12506 0
12507};
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012508static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012509timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Manuel Novoa III 4456f252003-08-13 17:48:47 +000012510{
Denys Vlasenko8cd9f342010-06-18 15:36:48 +020012511 unsigned long clk_tck, s, t;
Manuel Novoa III 4456f252003-08-13 17:48:47 +000012512 const unsigned char *p;
12513 struct tms buf;
12514
12515 clk_tck = sysconf(_SC_CLK_TCK);
Eric Andersencb57d552001-06-28 07:25:16 +000012516 times(&buf);
Manuel Novoa III 4456f252003-08-13 17:48:47 +000012517
12518 p = timescmd_str;
12519 do {
12520 t = *(clock_t *)(((char *) &buf) + p[1]);
12521 s = t / clk_tck;
Denys Vlasenko8cd9f342010-06-18 15:36:48 +020012522 t = t % clk_tck;
12523 out1fmt("%lum%lu.%03lus%c",
12524 s / 60, s % 60,
12525 (t * 1000) / clk_tck,
Manuel Novoa III 4456f252003-08-13 17:48:47 +000012526 p[0]);
Denys Vlasenko1ed2fb42010-06-18 14:09:48 +020012527 p += 2;
12528 } while (*p);
Manuel Novoa III 4456f252003-08-13 17:48:47 +000012529
Eric Andersencb57d552001-06-28 07:25:16 +000012530 return 0;
12531}
12532
Mike Frysinger98c52642009-04-02 10:02:37 +000012533#if ENABLE_SH_MATH_SUPPORT
Eric Andersenc470f442003-07-28 09:56:35 +000012534/*
Denys Vlasenko1ed2fb42010-06-18 14:09:48 +020012535 * The let builtin. Partially stolen from GNU Bash, the Bourne Again SHell.
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +000012536 * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
Eric Andersen90898442003-08-06 11:20:52 +000012537 *
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +000012538 * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
Eric Andersenc470f442003-07-28 09:56:35 +000012539 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012540static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012541letcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersenc470f442003-07-28 09:56:35 +000012542{
Denis Vlasenko68404f12008-03-17 09:00:54 +000012543 arith_t i;
Eric Andersenc470f442003-07-28 09:56:35 +000012544
Denis Vlasenko68404f12008-03-17 09:00:54 +000012545 argv++;
12546 if (!*argv)
Denis Vlasenkob012b102007-02-19 22:43:01 +000012547 ash_msg_and_raise_error("expression expected");
Denis Vlasenko68404f12008-03-17 09:00:54 +000012548 do {
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +000012549 i = ash_arith(*argv);
Denis Vlasenko68404f12008-03-17 09:00:54 +000012550 } while (*++argv);
Eric Andersenc470f442003-07-28 09:56:35 +000012551
Denis Vlasenkod9e15f22006-11-27 16:49:55 +000012552 return !i;
Eric Andersenc470f442003-07-28 09:56:35 +000012553}
Eric Andersenc470f442003-07-28 09:56:35 +000012554#endif
Eric Andersen74bcd162001-07-30 21:41:37 +000012555
Eric Andersenc470f442003-07-28 09:56:35 +000012556/*
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012557 * The read builtin. Options:
12558 * -r Do not interpret '\' specially
12559 * -s Turn off echo (tty only)
12560 * -n NCHARS Read NCHARS max
12561 * -p PROMPT Display PROMPT on stderr (if input is from tty)
12562 * -t SECONDS Timeout after SECONDS (tty or pipe only)
12563 * -u FD Read from given FD instead of fd 0
Eric Andersenc470f442003-07-28 09:56:35 +000012564 * This uses unbuffered input, which may be avoidable in some cases.
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012565 * TODO: bash also has:
12566 * -a ARRAY Read into array[0],[1],etc
12567 * -d DELIM End on DELIM char, not newline
12568 * -e Use line editing (tty only)
Eric Andersenc470f442003-07-28 09:56:35 +000012569 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012570static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012571readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersenc470f442003-07-28 09:56:35 +000012572{
Denys Vlasenko73067272010-01-12 22:11:24 +010012573 char *opt_n = NULL;
12574 char *opt_p = NULL;
12575 char *opt_t = NULL;
12576 char *opt_u = NULL;
12577 int read_flags = 0;
12578 const char *r;
Eric Andersenc470f442003-07-28 09:56:35 +000012579 int i;
12580
Denys Vlasenko73067272010-01-12 22:11:24 +010012581 while ((i = nextopt("p:u:rt:n:s")) != '\0') {
Denis Vlasenkobf0a2012006-12-26 10:42:51 +000012582 switch (i) {
Paul Fox02eb9342005-09-07 16:56:02 +000012583 case 'p':
Denys Vlasenko73067272010-01-12 22:11:24 +010012584 opt_p = optionarg;
Paul Fox02eb9342005-09-07 16:56:02 +000012585 break;
Paul Fox02eb9342005-09-07 16:56:02 +000012586 case 'n':
Denys Vlasenko73067272010-01-12 22:11:24 +010012587 opt_n = optionarg;
Paul Fox02eb9342005-09-07 16:56:02 +000012588 break;
12589 case 's':
Denys Vlasenko73067272010-01-12 22:11:24 +010012590 read_flags |= BUILTIN_READ_SILENT;
Paul Fox02eb9342005-09-07 16:56:02 +000012591 break;
Paul Fox02eb9342005-09-07 16:56:02 +000012592 case 't':
Denys Vlasenko73067272010-01-12 22:11:24 +010012593 opt_t = optionarg;
Paul Fox02eb9342005-09-07 16:56:02 +000012594 break;
Paul Fox02eb9342005-09-07 16:56:02 +000012595 case 'r':
Denys Vlasenko73067272010-01-12 22:11:24 +010012596 read_flags |= BUILTIN_READ_RAW;
Paul Fox02eb9342005-09-07 16:56:02 +000012597 break;
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012598 case 'u':
Denys Vlasenko73067272010-01-12 22:11:24 +010012599 opt_u = optionarg;
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012600 break;
Paul Fox02eb9342005-09-07 16:56:02 +000012601 default:
12602 break;
12603 }
Eric Andersenc470f442003-07-28 09:56:35 +000012604 }
Paul Fox02eb9342005-09-07 16:56:02 +000012605
Denys Vlasenko03dad222010-01-12 23:29:57 +010012606 r = shell_builtin_read(setvar2,
Denys Vlasenko73067272010-01-12 22:11:24 +010012607 argptr,
12608 bltinlookup("IFS"), /* can be NULL */
12609 read_flags,
12610 opt_n,
12611 opt_p,
12612 opt_t,
12613 opt_u
12614 );
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012615
Denys Vlasenko73067272010-01-12 22:11:24 +010012616 if ((uintptr_t)r > 1)
12617 ash_msg_and_raise_error(r);
Denis Vlasenko037576d2007-10-20 18:30:38 +000012618
Denys Vlasenko73067272010-01-12 22:11:24 +010012619 return (uintptr_t)r;
Eric Andersenc470f442003-07-28 09:56:35 +000012620}
12621
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012622static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012623umaskcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersenc470f442003-07-28 09:56:35 +000012624{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000012625 static const char permuser[3] ALIGN1 = "ugo";
12626 static const char permmode[3] ALIGN1 = "rwx";
12627 static const short permmask[] ALIGN2 = {
Eric Andersenc470f442003-07-28 09:56:35 +000012628 S_IRUSR, S_IWUSR, S_IXUSR,
12629 S_IRGRP, S_IWGRP, S_IXGRP,
12630 S_IROTH, S_IWOTH, S_IXOTH
12631 };
12632
Denis Vlasenkoeb858492009-04-18 02:06:54 +000012633 /* TODO: use bb_parse_mode() instead */
12634
Eric Andersenc470f442003-07-28 09:56:35 +000012635 char *ap;
12636 mode_t mask;
12637 int i;
12638 int symbolic_mode = 0;
12639
12640 while (nextopt("S") != '\0') {
12641 symbolic_mode = 1;
12642 }
12643
Denis Vlasenkob012b102007-02-19 22:43:01 +000012644 INT_OFF;
Eric Andersenc470f442003-07-28 09:56:35 +000012645 mask = umask(0);
12646 umask(mask);
Denis Vlasenkob012b102007-02-19 22:43:01 +000012647 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +000012648
Denis Vlasenko5cedb752007-02-18 19:56:41 +000012649 ap = *argptr;
12650 if (ap == NULL) {
Eric Andersenc470f442003-07-28 09:56:35 +000012651 if (symbolic_mode) {
12652 char buf[18];
12653 char *p = buf;
12654
12655 for (i = 0; i < 3; i++) {
12656 int j;
12657
12658 *p++ = permuser[i];
12659 *p++ = '=';
12660 for (j = 0; j < 3; j++) {
12661 if ((mask & permmask[3 * i + j]) == 0) {
12662 *p++ = permmode[j];
12663 }
12664 }
12665 *p++ = ',';
12666 }
12667 *--p = 0;
12668 puts(buf);
12669 } else {
12670 out1fmt("%.4o\n", mask);
12671 }
12672 } else {
Denis Vlasenkoaa744452007-02-23 01:04:22 +000012673 if (isdigit((unsigned char) *ap)) {
Eric Andersenc470f442003-07-28 09:56:35 +000012674 mask = 0;
12675 do {
12676 if (*ap >= '8' || *ap < '0')
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +020012677 ash_msg_and_raise_error(msg_illnum, argv[1]);
Eric Andersenc470f442003-07-28 09:56:35 +000012678 mask = (mask << 3) + (*ap - '0');
12679 } while (*++ap != '\0');
12680 umask(mask);
12681 } else {
12682 mask = ~mask & 0777;
12683 if (!bb_parse_mode(ap, &mask)) {
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +000012684 ash_msg_and_raise_error("illegal mode: %s", ap);
Eric Andersenc470f442003-07-28 09:56:35 +000012685 }
12686 umask(~mask & 0777);
12687 }
12688 }
12689 return 0;
12690}
12691
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012692static int FAST_FUNC
Denys Vlasenkof3c742f2010-03-06 20:12:00 +010012693ulimitcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersenc470f442003-07-28 09:56:35 +000012694{
Denys Vlasenkof3c742f2010-03-06 20:12:00 +010012695 return shell_builtin_ulimit(argv);
Eric Andersenc470f442003-07-28 09:56:35 +000012696}
12697
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012698/* ============ main() and helpers */
12699
12700/*
12701 * Called to exit the shell.
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012702 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012703static void exitshell(void) NORETURN;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012704static void
12705exitshell(void)
12706{
12707 struct jmploc loc;
12708 char *p;
12709 int status;
12710
12711 status = exitstatus;
12712 TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
12713 if (setjmp(loc.loc)) {
Denis Vlasenko7f88e342009-03-19 03:36:18 +000012714 if (exception_type == EXEXIT)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012715/* dash bug: it just does _exit(exitstatus) here
12716 * but we have to do setjobctl(0) first!
12717 * (bug is still not fixed in dash-0.5.3 - if you run dash
12718 * under Midnight Commander, on exit from dash MC is backgrounded) */
12719 status = exitstatus;
12720 goto out;
12721 }
12722 exception_handler = &loc;
12723 p = trap[0];
12724 if (p) {
12725 trap[0] = NULL;
12726 evalstring(p, 0);
Denys Vlasenko0800e3a2009-09-24 03:09:26 +020012727 free(p);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012728 }
12729 flush_stdout_stderr();
12730 out:
12731 setjobctl(0);
12732 _exit(status);
12733 /* NOTREACHED */
12734}
12735
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012736static void
12737init(void)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012738{
12739 /* from input.c: */
Denys Vlasenko82dd14a2010-05-17 10:10:01 +020012740 /* we will never free this */
12741 basepf.next_to_pgetc = basepf.buf = ckmalloc(IBUFSIZ);
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012742
12743 /* from trap.c: */
12744 signal(SIGCHLD, SIG_DFL);
Denys Vlasenko7a7b0342009-12-04 04:18:31 +010012745 /* bash re-enables SIGHUP which is SIG_IGNed on entry.
12746 * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
12747 */
12748 signal(SIGHUP, SIG_DFL);
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012749
12750 /* from var.c: */
12751 {
12752 char **envp;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012753 const char *p;
12754 struct stat st1, st2;
12755
12756 initvar();
12757 for (envp = environ; envp && *envp; envp++) {
12758 if (strchr(*envp, '=')) {
12759 setvareq(*envp, VEXPORT|VTEXTFIXED);
12760 }
12761 }
12762
Denys Vlasenko7bb346f2009-10-06 22:09:50 +020012763 setvar("PPID", utoa(getppid()), 0);
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012764
12765 p = lookupvar("PWD");
12766 if (p)
12767 if (*p != '/' || stat(p, &st1) || stat(".", &st2)
12768 || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino)
12769 p = '\0';
12770 setpwd(p, 0);
12771 }
12772}
12773
12774/*
12775 * Process the shell command line arguments.
12776 */
12777static void
Denis Vlasenko68404f12008-03-17 09:00:54 +000012778procargs(char **argv)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012779{
12780 int i;
12781 const char *xminusc;
12782 char **xargv;
12783
12784 xargv = argv;
12785 arg0 = xargv[0];
Denis Vlasenko68404f12008-03-17 09:00:54 +000012786 /* if (xargv[0]) - mmm, this is always true! */
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012787 xargv++;
12788 for (i = 0; i < NOPTS; i++)
12789 optlist[i] = 2;
12790 argptr = xargv;
Denis Vlasenko28bf6712008-02-14 15:01:47 +000012791 if (options(1)) {
12792 /* it already printed err message */
12793 raise_exception(EXERROR);
12794 }
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012795 xargv = argptr;
12796 xminusc = minusc;
12797 if (*xargv == NULL) {
12798 if (xminusc)
12799 ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
12800 sflag = 1;
12801 }
12802 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
12803 iflag = 1;
12804 if (mflag == 2)
12805 mflag = iflag;
12806 for (i = 0; i < NOPTS; i++)
12807 if (optlist[i] == 2)
12808 optlist[i] = 0;
12809#if DEBUG == 2
12810 debug = 1;
12811#endif
12812 /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
12813 if (xminusc) {
12814 minusc = *xargv++;
12815 if (*xargv)
12816 goto setarg0;
12817 } else if (!sflag) {
12818 setinputfile(*xargv, 0);
12819 setarg0:
12820 arg0 = *xargv++;
12821 commandname = arg0;
12822 }
12823
12824 shellparam.p = xargv;
12825#if ENABLE_ASH_GETOPTS
12826 shellparam.optind = 1;
12827 shellparam.optoff = -1;
12828#endif
Denis Vlasenko01631112007-12-16 17:20:38 +000012829 /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012830 while (*xargv) {
12831 shellparam.nparam++;
12832 xargv++;
12833 }
12834 optschanged();
12835}
12836
12837/*
12838 * Read /etc/profile or .profile.
12839 */
12840static void
12841read_profile(const char *name)
12842{
12843 int skip;
12844
12845 if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
12846 return;
12847 skip = cmdloop(0);
12848 popfile();
12849 if (skip)
12850 exitshell();
12851}
12852
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012853/*
12854 * This routine is called when an error or an interrupt occurs in an
12855 * interactive shell and control is returned to the main command loop.
12856 */
12857static void
12858reset(void)
12859{
12860 /* from eval.c: */
12861 evalskip = 0;
12862 loopnest = 0;
12863 /* from input.c: */
Denis Vlasenko41eb3002008-11-28 03:42:31 +000012864 g_parsefile->left_in_buffer = 0;
12865 g_parsefile->left_in_line = 0; /* clear input buffer */
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012866 popallfiles();
12867 /* from parser.c: */
12868 tokpushback = 0;
12869 checkkwd = 0;
12870 /* from redir.c: */
Denis Vlasenko34c73c42008-08-16 11:48:02 +000012871 clearredir(/*drop:*/ 0);
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012872}
12873
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012874#if PROFILE
12875static short profile_buf[16384];
12876extern int etext();
12877#endif
12878
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012879/*
12880 * Main routine. We initialize things, parse the arguments, execute
12881 * profiles if we're a login shell, and then call cmdloop to execute
12882 * commands. The setjmp call sets up the location to jump to when an
12883 * exception occurs. When an exception occurs the variable "state"
12884 * is used to figure out how far we had gotten.
12885 */
Denis Vlasenko9b49a5e2007-10-11 10:05:36 +000012886int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012887int ash_main(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012888{
Mike Frysinger98c52642009-04-02 10:02:37 +000012889 const char *shinit;
Denis Vlasenko4e12b1a2008-12-23 23:36:47 +000012890 volatile smallint state;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012891 struct jmploc jmploc;
12892 struct stackmark smark;
12893
Denis Vlasenko01631112007-12-16 17:20:38 +000012894 /* Initialize global data */
12895 INIT_G_misc();
12896 INIT_G_memstack();
12897 INIT_G_var();
Denis Vlasenkoee87ebf2007-12-21 22:18:16 +000012898#if ENABLE_ASH_ALIAS
Denis Vlasenko01631112007-12-16 17:20:38 +000012899 INIT_G_alias();
Denis Vlasenkoee87ebf2007-12-21 22:18:16 +000012900#endif
Denis Vlasenko01631112007-12-16 17:20:38 +000012901 INIT_G_cmdtable();
12902
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012903#if PROFILE
12904 monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
12905#endif
12906
12907#if ENABLE_FEATURE_EDITING
12908 line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
12909#endif
12910 state = 0;
12911 if (setjmp(jmploc.loc)) {
Denis Vlasenko7f88e342009-03-19 03:36:18 +000012912 smallint e;
Denis Vlasenko4e12b1a2008-12-23 23:36:47 +000012913 smallint s;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012914
12915 reset();
12916
Denis Vlasenko7f88e342009-03-19 03:36:18 +000012917 e = exception_type;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012918 if (e == EXERROR)
12919 exitstatus = 2;
12920 s = state;
12921 if (e == EXEXIT || s == 0 || iflag == 0 || shlvl)
12922 exitshell();
Denis Vlasenko7f88e342009-03-19 03:36:18 +000012923 if (e == EXINT)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012924 outcslow('\n', stderr);
Denis Vlasenko7f88e342009-03-19 03:36:18 +000012925
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012926 popstackmark(&smark);
12927 FORCE_INT_ON; /* enable interrupts */
12928 if (s == 1)
12929 goto state1;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000012930 if (s == 2)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012931 goto state2;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000012932 if (s == 3)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012933 goto state3;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000012934 goto state4;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012935 }
12936 exception_handler = &jmploc;
12937#if DEBUG
12938 opentrace();
Denis Vlasenko653d8e72009-03-19 21:59:35 +000012939 TRACE(("Shell args: "));
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000012940 trace_puts_args(argv);
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012941#endif
12942 rootpid = getpid();
12943
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012944 init();
12945 setstackmark(&smark);
Denis Vlasenko68404f12008-03-17 09:00:54 +000012946 procargs(argv);
12947
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012948#if ENABLE_FEATURE_EDITING_SAVEHISTORY
12949 if (iflag) {
12950 const char *hp = lookupvar("HISTFILE");
12951
12952 if (hp == NULL) {
12953 hp = lookupvar("HOME");
12954 if (hp != NULL) {
12955 char *defhp = concat_path_file(hp, ".ash_history");
12956 setvar("HISTFILE", defhp, 0);
12957 free(defhp);
12958 }
12959 }
12960 }
12961#endif
Denis Vlasenko4e12b1a2008-12-23 23:36:47 +000012962 if (/* argv[0] && */ argv[0][0] == '-')
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012963 isloginsh = 1;
12964 if (isloginsh) {
12965 state = 1;
12966 read_profile("/etc/profile");
12967 state1:
12968 state = 2;
12969 read_profile(".profile");
12970 }
12971 state2:
12972 state = 3;
12973 if (
12974#ifndef linux
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012975 getuid() == geteuid() && getgid() == getegid() &&
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012976#endif
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012977 iflag
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012978 ) {
12979 shinit = lookupvar("ENV");
12980 if (shinit != NULL && *shinit != '\0') {
12981 read_profile(shinit);
12982 }
12983 }
12984 state3:
12985 state = 4;
Denis Vlasenko5c2b8142009-03-19 01:59:59 +000012986 if (minusc) {
12987 /* evalstring pushes parsefile stack.
12988 * Ensure we don't falsely claim that 0 (stdin)
Denis Vlasenko5368ad52009-03-20 10:20:08 +000012989 * is one of stacked source fds.
12990 * Testcase: ash -c 'exec 1>&0' must not complain. */
Denys Vlasenko79b3d422010-06-03 04:29:08 +020012991 // if (!sflag) g_parsefile->pf_fd = -1;
Denys Vlasenko08d8b3c2010-06-03 04:28:28 +020012992 // ^^ not necessary since now we special-case fd 0
12993 // in is_hidden_fd() to not be considered "hidden fd"
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012994 evalstring(minusc, 0);
Denis Vlasenko5c2b8142009-03-19 01:59:59 +000012995 }
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012996
12997 if (sflag || minusc == NULL) {
Denys Vlasenko0337e032009-11-29 00:12:30 +010012998#if defined MAX_HISTORY && MAX_HISTORY > 0 && ENABLE_FEATURE_EDITING_SAVEHISTORY
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +000012999 if (iflag) {
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013000 const char *hp = lookupvar("HISTFILE");
Denis Vlasenko5c2b8142009-03-19 01:59:59 +000013001 if (hp)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013002 line_input_state->hist_file = hp;
13003 }
13004#endif
13005 state4: /* XXX ??? - why isn't this before the "if" statement */
13006 cmdloop(1);
13007 }
13008#if PROFILE
13009 monitor(0);
13010#endif
13011#ifdef GPROF
13012 {
13013 extern void _mcleanup(void);
13014 _mcleanup();
13015 }
13016#endif
13017 exitshell();
13018 /* NOTREACHED */
13019}
13020
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013021
Eric Andersendf82f612001-06-28 07:46:40 +000013022/*-
13023 * Copyright (c) 1989, 1991, 1993, 1994
Eric Andersen2870d962001-07-02 17:27:21 +000013024 * The Regents of the University of California. All rights reserved.
Eric Andersendf82f612001-06-28 07:46:40 +000013025 *
13026 * This code is derived from software contributed to Berkeley by
13027 * Kenneth Almquist.
13028 *
13029 * Redistribution and use in source and binary forms, with or without
13030 * modification, are permitted provided that the following conditions
13031 * are met:
13032 * 1. Redistributions of source code must retain the above copyright
13033 * notice, this list of conditions and the following disclaimer.
13034 * 2. Redistributions in binary form must reproduce the above copyright
13035 * notice, this list of conditions and the following disclaimer in the
13036 * documentation and/or other materials provided with the distribution.
"Vladimir N. Oleynik"ddc280e2005-12-15 12:01:49 +000013037 * 3. Neither the name of the University nor the names of its contributors
Eric Andersendf82f612001-06-28 07:46:40 +000013038 * may be used to endorse or promote products derived from this software
13039 * without specific prior written permission.
13040 *
13041 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
13042 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
13043 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
13044 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
13045 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
13046 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
13047 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
13048 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
13049 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
13050 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
13051 * SUCH DAMAGE.
13052 */