blob: fcaa7b18eb58d3d7cba5c32c0491a2aa9e76633d [file] [log] [blame]
Eric Andersendf82f612001-06-28 07:46:40 +00001/* vi: set sw=4 ts=4: */
2/*
3 * ash shell port for busybox
4 *
Denys Vlasenko73067272010-01-12 22:11:24 +01005 * This code is derived from software contributed to Berkeley by
6 * Kenneth Almquist.
7 *
8 * Original BSD copyright notice is retained at the end of this file.
9 *
Eric Andersendf82f612001-06-28 07:46:40 +000010 * Copyright (c) 1989, 1991, 1993, 1994
Eric Andersen2870d962001-07-02 17:27:21 +000011 * The Regents of the University of California. All rights reserved.
Eric Andersencb57d552001-06-28 07:25:16 +000012 *
"Vladimir N. Oleynik"ddc280e2005-12-15 12:01:49 +000013 * Copyright (c) 1997-2005 Herbert Xu <herbert@gondor.apana.org.au>
Eric Andersen81fe1232003-07-29 06:38:40 +000014 * was re-ported from NetBSD and debianized.
15 *
Bernhard Reutner-Fischer86f5c992006-01-22 22:55:11 +000016 * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
Eric Andersencb57d552001-06-28 07:25:16 +000017 */
18
Eric Andersenc470f442003-07-28 09:56:35 +000019/*
Denis Vlasenko653d8e72009-03-19 21:59:35 +000020 * The following should be set to reflect the type of system you have:
Eric Andersenc470f442003-07-28 09:56:35 +000021 * JOBS -> 1 if you have Berkeley job control, 0 otherwise.
22 * define SYSV if you are running under System V.
23 * define DEBUG=1 to compile in debugging ('set -o debug' to turn on)
24 * define DEBUG=2 to compile in and turn on debugging.
25 *
26 * When debugging is on, debugging info will be written to ./trace and
27 * a quit signal will generate a core dump.
28 */
Denis Vlasenkof1733952009-03-19 23:21:55 +000029#define DEBUG 0
Denis Vlasenko653d8e72009-03-19 21:59:35 +000030/* Tweak debug output verbosity here */
31#define DEBUG_TIME 0
32#define DEBUG_PID 1
33#define DEBUG_SIG 1
34
Eric Andersenc470f442003-07-28 09:56:35 +000035#define PROFILE 0
Denis Vlasenko0e6f6612008-02-15 15:02:15 +000036
Denis Vlasenko0e6f6612008-02-15 15:02:15 +000037#define JOBS ENABLE_ASH_JOB_CONTROL
Eric Andersenc470f442003-07-28 09:56:35 +000038
Denis Vlasenkob012b102007-02-19 22:43:01 +000039#if DEBUG
Denis Vlasenko653d8e72009-03-19 21:59:35 +000040# ifndef _GNU_SOURCE
41# define _GNU_SOURCE
42# endif
Denis Vlasenkoe26b2782008-02-12 07:40:29 +000043#endif
Denis Vlasenko0e6f6612008-02-15 15:02:15 +000044
Denis Vlasenko1aa7e472007-11-28 06:49:03 +000045#include "busybox.h" /* for applet_names */
Denis Vlasenkob012b102007-02-19 22:43:01 +000046#include <paths.h>
47#include <setjmp.h>
48#include <fnmatch.h>
Denys Vlasenko1ed2fb42010-06-18 14:09:48 +020049#include <sys/times.h>
Denys Vlasenko73067272010-01-12 22:11:24 +010050
51#include "shell_common.h"
Mike Frysinger98c52642009-04-02 10:02:37 +000052#include "math.h"
Denys Vlasenko3ea2e822009-10-09 20:59:04 +020053#if ENABLE_ASH_RANDOM_SUPPORT
54# include "random.h"
Denys Vlasenko36df0482009-10-19 16:07:28 +020055#else
56# define CLEAR_RANDOM_T(rnd) ((void)0)
Denys Vlasenko3ea2e822009-10-09 20:59:04 +020057#endif
Denis Vlasenko61befda2008-11-25 01:36:03 +000058
Denys Vlasenko14974842010-03-23 01:08:26 +010059#define SKIP_definitions 1
60#include "applet_tables.h"
61#undef SKIP_definitions
62#if NUM_APPLETS == 1
Denis Vlasenko61befda2008-11-25 01:36:03 +000063/* STANDALONE does not make sense, and won't compile */
Denys Vlasenko3ea2e822009-10-09 20:59:04 +020064# undef CONFIG_FEATURE_SH_STANDALONE
65# undef ENABLE_FEATURE_SH_STANDALONE
66# undef IF_FEATURE_SH_STANDALONE
Denys Vlasenko14974842010-03-23 01:08:26 +010067# undef IF_NOT_FEATURE_SH_STANDALONE
Denys Vlasenko3ea2e822009-10-09 20:59:04 +020068# define ENABLE_FEATURE_SH_STANDALONE 0
69# define IF_FEATURE_SH_STANDALONE(...)
70# define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
Eric Andersencb57d552001-06-28 07:25:16 +000071#endif
72
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000073#ifndef PIPE_BUF
Denis Vlasenko653d8e72009-03-19 21:59:35 +000074# define PIPE_BUF 4096 /* amount of buffering in a pipe */
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000075#endif
76
Denys Vlasenko153fcaa2010-02-21 05:17:41 +010077#if !BB_MMU
Denis Vlasenko653d8e72009-03-19 21:59:35 +000078# error "Do not even bother, ash will not run on NOMMU machine"
Denis Vlasenkob012b102007-02-19 22:43:01 +000079#endif
80
Denis Vlasenkob012b102007-02-19 22:43:01 +000081
Denis Vlasenko01631112007-12-16 17:20:38 +000082/* ============ Hash table sizes. Configurable. */
83
84#define VTABSIZE 39
85#define ATABSIZE 39
86#define CMDTABLESIZE 31 /* should be prime */
87
88
Denis Vlasenkob012b102007-02-19 22:43:01 +000089/* ============ Shell options */
90
91static const char *const optletters_optnames[] = {
92 "e" "errexit",
93 "f" "noglob",
94 "I" "ignoreeof",
95 "i" "interactive",
96 "m" "monitor",
97 "n" "noexec",
98 "s" "stdin",
99 "x" "xtrace",
100 "v" "verbose",
101 "C" "noclobber",
102 "a" "allexport",
103 "b" "notify",
104 "u" "nounset",
Denys Vlasenkoe9ac32a2009-12-05 02:01:25 +0100105 "\0" "vi"
Michael Abbott359da5e2009-12-04 23:03:29 +0100106#if ENABLE_ASH_BASH_COMPAT
Denys Vlasenkoe9ac32a2009-12-05 02:01:25 +0100107 ,"\0" "pipefail"
Michael Abbott359da5e2009-12-04 23:03:29 +0100108#endif
Denis Vlasenkob012b102007-02-19 22:43:01 +0000109#if DEBUG
Denis Vlasenko6ca409e2007-08-12 20:58:27 +0000110 ,"\0" "nolog"
111 ,"\0" "debug"
Denis Vlasenkob012b102007-02-19 22:43:01 +0000112#endif
113};
114
Denys Vlasenko285ad152009-12-04 23:02:27 +0100115#define optletters(n) optletters_optnames[n][0]
116#define optnames(n) (optletters_optnames[n] + 1)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000117
Denis Vlasenko80b8b392007-06-25 10:55:35 +0000118enum { NOPTS = ARRAY_SIZE(optletters_optnames) };
Denis Vlasenkob012b102007-02-19 22:43:01 +0000119
Eric Andersenc470f442003-07-28 09:56:35 +0000120
Denis Vlasenkob012b102007-02-19 22:43:01 +0000121/* ============ Misc data */
Eric Andersenc470f442003-07-28 09:56:35 +0000122
Denys Vlasenkoea8b2522010-06-02 12:57:26 +0200123#define msg_illnum "Illegal number: %s"
Denis Vlasenkoaa744452007-02-23 01:04:22 +0000124
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +0000125/*
Eric Andersenc470f442003-07-28 09:56:35 +0000126 * We enclose jmp_buf in a structure so that we can declare pointers to
127 * jump locations. The global variable handler contains the location to
Denis Vlasenkof1733952009-03-19 23:21:55 +0000128 * jump to when an exception occurs, and the global variable exception_type
Eric Andersenaff114c2004-04-14 17:51:38 +0000129 * contains a code identifying the exception. To implement nested
Eric Andersenc470f442003-07-28 09:56:35 +0000130 * exception handlers, the user should save the value of handler on entry
131 * to an inner scope, set handler to point to a jmploc structure for the
132 * inner scope, and restore handler on exit from the scope.
133 */
Eric Andersenc470f442003-07-28 09:56:35 +0000134struct jmploc {
135 jmp_buf loc;
136};
Denis Vlasenko01631112007-12-16 17:20:38 +0000137
138struct globals_misc {
139 /* pid of main shell */
140 int rootpid;
141 /* shell level: 0 for the main shell, 1 for its children, and so on */
142 int shlvl;
143#define rootshell (!shlvl)
144 char *minusc; /* argument to -c option */
145
146 char *curdir; // = nullstr; /* current working directory */
147 char *physdir; // = nullstr; /* physical working directory */
148
149 char *arg0; /* value of $0 */
150
151 struct jmploc *exception_handler;
Denis Vlasenko991a1da2008-02-10 19:02:53 +0000152
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200153 volatile int suppress_int; /* counter */
154 volatile /*sig_atomic_t*/ smallint pending_int; /* 1 = got SIGINT */
Denis Vlasenko991a1da2008-02-10 19:02:53 +0000155 /* last pending signal */
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200156 volatile /*sig_atomic_t*/ smallint pending_sig;
Denis Vlasenko7f88e342009-03-19 03:36:18 +0000157 smallint exception_type; /* kind of exception (0..5) */
Denis Vlasenko01631112007-12-16 17:20:38 +0000158 /* exceptions */
Eric Andersenc470f442003-07-28 09:56:35 +0000159#define EXINT 0 /* SIGINT received */
160#define EXERROR 1 /* a generic error */
161#define EXSHELLPROC 2 /* execute a shell procedure */
162#define EXEXEC 3 /* command execution failed */
163#define EXEXIT 4 /* exit the shell */
164#define EXSIG 5 /* trapped signal in wait(1) */
Eric Andersen2870d962001-07-02 17:27:21 +0000165
Denis Vlasenko01631112007-12-16 17:20:38 +0000166 smallint isloginsh;
Denis Vlasenkob07a4962008-06-22 13:16:23 +0000167 char nullstr[1]; /* zero length string */
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000168
169 char optlist[NOPTS];
170#define eflag optlist[0]
171#define fflag optlist[1]
172#define Iflag optlist[2]
173#define iflag optlist[3]
174#define mflag optlist[4]
175#define nflag optlist[5]
176#define sflag optlist[6]
177#define xflag optlist[7]
178#define vflag optlist[8]
179#define Cflag optlist[9]
180#define aflag optlist[10]
181#define bflag optlist[11]
182#define uflag optlist[12]
183#define viflag optlist[13]
Michael Abbott359da5e2009-12-04 23:03:29 +0100184#if ENABLE_ASH_BASH_COMPAT
185# define pipefail optlist[14]
186#else
187# define pipefail 0
188#endif
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000189#if DEBUG
Michael Abbott359da5e2009-12-04 23:03:29 +0100190# define nolog optlist[14 + ENABLE_ASH_BASH_COMPAT]
191# define debug optlist[15 + ENABLE_ASH_BASH_COMPAT]
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000192#endif
193
194 /* trap handler commands */
Denis Vlasenko01631112007-12-16 17:20:38 +0000195 /*
196 * Sigmode records the current value of the signal handlers for the various
197 * modes. A value of zero means that the current handler is not known.
Denis Vlasenkof8535cc2008-12-03 10:36:26 +0000198 * S_HARD_IGN indicates that the signal was ignored on entry to the shell.
Denis Vlasenko01631112007-12-16 17:20:38 +0000199 */
200 char sigmode[NSIG - 1];
Denis Vlasenkof8535cc2008-12-03 10:36:26 +0000201#define S_DFL 1 /* default signal handling (SIG_DFL) */
202#define S_CATCH 2 /* signal is caught */
203#define S_IGN 3 /* signal is ignored (SIG_IGN) */
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +0000204#define S_HARD_IGN 4 /* signal is ignored permenantly */
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +0000205
Denis Vlasenko01631112007-12-16 17:20:38 +0000206 /* indicates specified signal received */
Denis Vlasenko4b875702009-03-19 13:30:04 +0000207 uint8_t gotsig[NSIG - 1]; /* offset by 1: "signal" 0 is meaningless */
Denys Vlasenko238bf182010-05-18 15:49:07 +0200208 uint8_t may_have_traps; /* 0: definitely no traps are set, 1: some traps may be set */
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000209 char *trap[NSIG];
Denys Vlasenko21d87d42009-09-25 00:06:51 +0200210 char **trap_ptr; /* used only by "trap hack" */
Denis Vlasenko448d30e2008-06-27 00:24:11 +0000211
212 /* Rarely referenced stuff */
213#if ENABLE_ASH_RANDOM_SUPPORT
Denys Vlasenko3ea2e822009-10-09 20:59:04 +0200214 random_t random_gen;
Denis Vlasenko448d30e2008-06-27 00:24:11 +0000215#endif
216 pid_t backgndpid; /* pid of last background process */
217 smallint job_warning; /* user was warned about stopped jobs (can be 2, 1 or 0). */
Denis Vlasenko01631112007-12-16 17:20:38 +0000218};
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000219extern struct globals_misc *const ash_ptr_to_globals_misc;
220#define G_misc (*ash_ptr_to_globals_misc)
Denis Vlasenko26bc57d2008-06-27 00:29:34 +0000221#define rootpid (G_misc.rootpid )
222#define shlvl (G_misc.shlvl )
223#define minusc (G_misc.minusc )
224#define curdir (G_misc.curdir )
225#define physdir (G_misc.physdir )
226#define arg0 (G_misc.arg0 )
Denis Vlasenko01631112007-12-16 17:20:38 +0000227#define exception_handler (G_misc.exception_handler)
Denis Vlasenko7f88e342009-03-19 03:36:18 +0000228#define exception_type (G_misc.exception_type )
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200229#define suppress_int (G_misc.suppress_int )
230#define pending_int (G_misc.pending_int )
231#define pending_sig (G_misc.pending_sig )
Denis Vlasenko26bc57d2008-06-27 00:29:34 +0000232#define isloginsh (G_misc.isloginsh )
233#define nullstr (G_misc.nullstr )
234#define optlist (G_misc.optlist )
235#define sigmode (G_misc.sigmode )
236#define gotsig (G_misc.gotsig )
Denys Vlasenko238bf182010-05-18 15:49:07 +0200237#define may_have_traps (G_misc.may_have_traps )
Denis Vlasenko26bc57d2008-06-27 00:29:34 +0000238#define trap (G_misc.trap )
Denys Vlasenko21d87d42009-09-25 00:06:51 +0200239#define trap_ptr (G_misc.trap_ptr )
Denys Vlasenko3ea2e822009-10-09 20:59:04 +0200240#define random_gen (G_misc.random_gen )
Denis Vlasenko448d30e2008-06-27 00:24:11 +0000241#define backgndpid (G_misc.backgndpid )
242#define job_warning (G_misc.job_warning)
Denis Vlasenko01631112007-12-16 17:20:38 +0000243#define INIT_G_misc() do { \
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000244 (*(struct globals_misc**)&ash_ptr_to_globals_misc) = xzalloc(sizeof(G_misc)); \
245 barrier(); \
Denis Vlasenko01631112007-12-16 17:20:38 +0000246 curdir = nullstr; \
247 physdir = nullstr; \
Denys Vlasenko21d87d42009-09-25 00:06:51 +0200248 trap_ptr = trap; \
Denis Vlasenko01631112007-12-16 17:20:38 +0000249} while (0)
250
251
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000252/* ============ DEBUG */
253#if DEBUG
254static void trace_printf(const char *fmt, ...);
255static void trace_vprintf(const char *fmt, va_list va);
256# define TRACE(param) trace_printf param
257# define TRACEV(param) trace_vprintf param
Denis Vlasenko1bb3d7e2009-03-20 07:45:36 +0000258# define close(fd) do { \
259 int dfd = (fd); \
Denis Vlasenkob9e70dd2009-03-20 01:24:08 +0000260 if (close(dfd) < 0) \
Denys Vlasenko883cea42009-07-11 15:31:59 +0200261 bb_error_msg("bug on %d: closing %d(0x%x)", \
Denis Vlasenko1bb3d7e2009-03-20 07:45:36 +0000262 __LINE__, dfd, dfd); \
Denis Vlasenkob9e70dd2009-03-20 01:24:08 +0000263} while (0)
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000264#else
265# define TRACE(param)
266# define TRACEV(param)
267#endif
268
269
Denis Vlasenko559691a2008-10-05 18:39:31 +0000270/* ============ Utility functions */
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000271#define xbarrier() do { __asm__ __volatile__ ("": : :"memory"); } while (0)
272
Denis Vlasenko559691a2008-10-05 18:39:31 +0000273static int isdigit_str9(const char *str)
274{
275 int maxlen = 9 + 1; /* max 9 digits: 999999999 */
276 while (--maxlen && isdigit(*str))
277 str++;
278 return (*str == '\0');
279}
Denis Vlasenko01631112007-12-16 17:20:38 +0000280
Denys Vlasenko8837c5d2010-06-02 12:56:18 +0200281static const char *var_end(const char *var)
282{
283 while (*var)
284 if (*var++ == '=')
285 break;
286 return var;
287}
288
Denis Vlasenko559691a2008-10-05 18:39:31 +0000289
290/* ============ Interrupts / exceptions */
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +0000291/*
Eric Andersen2870d962001-07-02 17:27:21 +0000292 * These macros allow the user to suspend the handling of interrupt signals
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +0000293 * over a period of time. This is similar to SIGHOLD or to sigblock, but
Eric Andersen2870d962001-07-02 17:27:21 +0000294 * much more efficient and portable. (But hacking the kernel is so much
295 * more fun than worrying about efficiency and portability. :-))
296 */
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000297#define INT_OFF do { \
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200298 suppress_int++; \
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000299 xbarrier(); \
300} while (0)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000301
302/*
303 * Called to raise an exception. Since C doesn't include exceptions, we
304 * just do a longjmp to the exception handler. The type of exception is
Denis Vlasenko4b875702009-03-19 13:30:04 +0000305 * stored in the global variable "exception_type".
Denis Vlasenkob012b102007-02-19 22:43:01 +0000306 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +0000307static void raise_exception(int) NORETURN;
Denis Vlasenkob012b102007-02-19 22:43:01 +0000308static void
309raise_exception(int e)
310{
311#if DEBUG
Denis Vlasenko2da584f2007-02-19 22:44:05 +0000312 if (exception_handler == NULL)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000313 abort();
314#endif
315 INT_OFF;
Denis Vlasenko7f88e342009-03-19 03:36:18 +0000316 exception_type = e;
Denis Vlasenko2da584f2007-02-19 22:44:05 +0000317 longjmp(exception_handler->loc, 1);
Denis Vlasenkob012b102007-02-19 22:43:01 +0000318}
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000319#if DEBUG
320#define raise_exception(e) do { \
321 TRACE(("raising exception %d on line %d\n", (e), __LINE__)); \
322 raise_exception(e); \
323} while (0)
324#endif
Denis Vlasenkob012b102007-02-19 22:43:01 +0000325
326/*
327 * Called from trap.c when a SIGINT is received. (If the user specifies
328 * that SIGINT is to be trapped or ignored using the trap builtin, then
329 * this routine is not called.) Suppressint is nonzero when interrupts
330 * are held using the INT_OFF macro. (The test for iflag is just
331 * defensive programming.)
332 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +0000333static void raise_interrupt(void) NORETURN;
Denis Vlasenkob012b102007-02-19 22:43:01 +0000334static void
335raise_interrupt(void)
336{
Denis Vlasenko4b875702009-03-19 13:30:04 +0000337 int ex_type;
Denis Vlasenkob012b102007-02-19 22:43:01 +0000338
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200339 pending_int = 0;
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +0000340 /* Signal is not automatically unmasked after it is raised,
341 * do it ourself - unmask all signals */
Denis Vlasenko3f165fa2008-03-17 08:29:08 +0000342 sigprocmask_allsigs(SIG_UNBLOCK);
Denys Vlasenko238bf182010-05-18 15:49:07 +0200343 /* pending_sig = 0; - now done in signal_handler() */
Denis Vlasenko7c139b42007-03-21 20:17:27 +0000344
Denis Vlasenko4b875702009-03-19 13:30:04 +0000345 ex_type = EXSIG;
Denis Vlasenkob012b102007-02-19 22:43:01 +0000346 if (gotsig[SIGINT - 1] && !trap[SIGINT]) {
347 if (!(rootshell && iflag)) {
Denis Vlasenko991a1da2008-02-10 19:02:53 +0000348 /* Kill ourself with SIGINT */
Denis Vlasenkob012b102007-02-19 22:43:01 +0000349 signal(SIGINT, SIG_DFL);
350 raise(SIGINT);
351 }
Denis Vlasenko4b875702009-03-19 13:30:04 +0000352 ex_type = EXINT;
Denis Vlasenkob012b102007-02-19 22:43:01 +0000353 }
Denis Vlasenko4b875702009-03-19 13:30:04 +0000354 raise_exception(ex_type);
Denis Vlasenkob012b102007-02-19 22:43:01 +0000355 /* NOTREACHED */
356}
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000357#if DEBUG
358#define raise_interrupt() do { \
359 TRACE(("raising interrupt on line %d\n", __LINE__)); \
360 raise_interrupt(); \
361} while (0)
362#endif
Denis Vlasenkob012b102007-02-19 22:43:01 +0000363
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000364static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000365int_on(void)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000366{
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +0000367 xbarrier();
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200368 if (--suppress_int == 0 && pending_int) {
Denis Vlasenkob012b102007-02-19 22:43:01 +0000369 raise_interrupt();
370 }
371}
372#define INT_ON int_on()
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000373static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000374force_int_on(void)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000375{
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +0000376 xbarrier();
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200377 suppress_int = 0;
378 if (pending_int)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000379 raise_interrupt();
380}
381#define FORCE_INT_ON force_int_on()
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000382
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200383#define SAVE_INT(v) ((v) = suppress_int)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000384
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000385#define RESTORE_INT(v) do { \
386 xbarrier(); \
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200387 suppress_int = (v); \
388 if (suppress_int == 0 && pending_int) \
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000389 raise_interrupt(); \
390} while (0)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000391
Glenn L McGrath9fef17d2002-08-22 18:41:20 +0000392
Denis Vlasenkobc54cff2007-02-23 01:05:52 +0000393/* ============ Stdout/stderr output */
Eric Andersenc470f442003-07-28 09:56:35 +0000394
Eric Andersenc470f442003-07-28 09:56:35 +0000395static void
Denis Vlasenkob012b102007-02-19 22:43:01 +0000396outstr(const char *p, FILE *file)
Denis Vlasenkoe5570da2007-02-19 22:41:55 +0000397{
Denis Vlasenkob012b102007-02-19 22:43:01 +0000398 INT_OFF;
399 fputs(p, file);
400 INT_ON;
401}
402
403static void
404flush_stdout_stderr(void)
405{
406 INT_OFF;
Denys Vlasenko8131eea2009-11-02 14:19:51 +0100407 fflush_all();
Denis Vlasenkob012b102007-02-19 22:43:01 +0000408 INT_ON;
409}
410
411static void
412outcslow(int c, FILE *dest)
413{
414 INT_OFF;
415 putc(c, dest);
416 fflush(dest);
417 INT_ON;
418}
419
420static int out1fmt(const char *, ...) __attribute__((__format__(__printf__,1,2)));
421static int
422out1fmt(const char *fmt, ...)
423{
424 va_list ap;
425 int r;
426
427 INT_OFF;
428 va_start(ap, fmt);
429 r = vprintf(fmt, ap);
430 va_end(ap);
431 INT_ON;
432 return r;
433}
434
435static int fmtstr(char *, size_t, const char *, ...) __attribute__((__format__(__printf__,3,4)));
436static int
437fmtstr(char *outbuf, size_t length, const char *fmt, ...)
438{
439 va_list ap;
440 int ret;
441
442 va_start(ap, fmt);
443 INT_OFF;
444 ret = vsnprintf(outbuf, length, fmt, ap);
445 va_end(ap);
446 INT_ON;
447 return ret;
448}
449
450static void
451out1str(const char *p)
452{
453 outstr(p, stdout);
454}
455
456static void
457out2str(const char *p)
458{
459 outstr(p, stderr);
Denys Vlasenko8131eea2009-11-02 14:19:51 +0100460 flush_stdout_stderr();
Denis Vlasenkob012b102007-02-19 22:43:01 +0000461}
462
463
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +0000464/* ============ Parser structures */
Denis Vlasenko4d2183b2007-02-23 01:05:38 +0000465
Denis Vlasenko5651bfc2007-02-23 21:08:58 +0000466/* control characters in argument strings */
Denys Vlasenko2ce42e92009-11-29 02:18:13 +0100467#define CTL_FIRST CTLESC
Denys Vlasenkob6c84342009-08-29 20:23:20 +0200468#define CTLESC ((unsigned char)'\201') /* escape next character */
469#define CTLVAR ((unsigned char)'\202') /* variable defn */
470#define CTLENDVAR ((unsigned char)'\203')
471#define CTLBACKQ ((unsigned char)'\204')
Denis Vlasenko5651bfc2007-02-23 21:08:58 +0000472#define CTLQUOTE 01 /* ored with CTLBACKQ code if in quotes */
473/* CTLBACKQ | CTLQUOTE == '\205' */
Denys Vlasenkob6c84342009-08-29 20:23:20 +0200474#define CTLARI ((unsigned char)'\206') /* arithmetic expression */
475#define CTLENDARI ((unsigned char)'\207')
476#define CTLQUOTEMARK ((unsigned char)'\210')
Denys Vlasenko2ce42e92009-11-29 02:18:13 +0100477#define CTL_LAST CTLQUOTEMARK
Denis Vlasenko5651bfc2007-02-23 21:08:58 +0000478
479/* variable substitution byte (follows CTLVAR) */
480#define VSTYPE 0x0f /* type of variable substitution */
481#define VSNUL 0x10 /* colon--treat the empty string as unset */
482#define VSQUOTE 0x80 /* inside double quotes--suppress splitting */
483
484/* values of VSTYPE field */
Denis Vlasenko92e13c22008-03-25 01:17:40 +0000485#define VSNORMAL 0x1 /* normal variable: $var or ${var} */
486#define VSMINUS 0x2 /* ${var-text} */
487#define VSPLUS 0x3 /* ${var+text} */
488#define VSQUESTION 0x4 /* ${var?message} */
489#define VSASSIGN 0x5 /* ${var=text} */
490#define VSTRIMRIGHT 0x6 /* ${var%pattern} */
491#define VSTRIMRIGHTMAX 0x7 /* ${var%%pattern} */
492#define VSTRIMLEFT 0x8 /* ${var#pattern} */
493#define VSTRIMLEFTMAX 0x9 /* ${var##pattern} */
494#define VSLENGTH 0xa /* ${#var} */
495#if ENABLE_ASH_BASH_COMPAT
496#define VSSUBSTR 0xc /* ${var:position:length} */
497#define VSREPLACE 0xd /* ${var/pattern/replacement} */
498#define VSREPLACEALL 0xe /* ${var//pattern/replacement} */
499#endif
Denis Vlasenko5651bfc2007-02-23 21:08:58 +0000500
Denis Vlasenko6ca409e2007-08-12 20:58:27 +0000501static const char dolatstr[] ALIGN1 = {
502 CTLVAR, VSNORMAL|VSQUOTE, '@', '=', '\0'
503};
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +0000504
Denis Vlasenko559691a2008-10-05 18:39:31 +0000505#define NCMD 0
506#define NPIPE 1
507#define NREDIR 2
508#define NBACKGND 3
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000509#define NSUBSHELL 4
Denis Vlasenko559691a2008-10-05 18:39:31 +0000510#define NAND 5
511#define NOR 6
512#define NSEMI 7
513#define NIF 8
514#define NWHILE 9
515#define NUNTIL 10
516#define NFOR 11
517#define NCASE 12
518#define NCLIST 13
519#define NDEFUN 14
520#define NARG 15
521#define NTO 16
522#if ENABLE_ASH_BASH_COMPAT
523#define NTO2 17
524#endif
525#define NCLOBBER 18
526#define NFROM 19
527#define NFROMTO 20
528#define NAPPEND 21
529#define NTOFD 22
530#define NFROMFD 23
531#define NHERE 24
532#define NXHERE 25
533#define NNOT 26
Denis Vlasenko340299a2008-11-21 10:36:36 +0000534#define N_NUMBER 27
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000535
536union node;
537
538struct ncmd {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000539 smallint type; /* Nxxxx */
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000540 union node *assign;
541 union node *args;
542 union node *redirect;
543};
544
545struct npipe {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000546 smallint type;
547 smallint pipe_backgnd;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000548 struct nodelist *cmdlist;
549};
550
551struct nredir {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000552 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000553 union node *n;
554 union node *redirect;
555};
556
557struct nbinary {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000558 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000559 union node *ch1;
560 union node *ch2;
561};
562
563struct nif {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000564 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000565 union node *test;
566 union node *ifpart;
567 union node *elsepart;
568};
569
570struct nfor {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000571 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000572 union node *args;
573 union node *body;
574 char *var;
575};
576
577struct ncase {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000578 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000579 union node *expr;
580 union node *cases;
581};
582
583struct nclist {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000584 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000585 union node *next;
586 union node *pattern;
587 union node *body;
588};
589
590struct narg {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000591 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000592 union node *next;
593 char *text;
594 struct nodelist *backquote;
595};
596
Denis Vlasenko559691a2008-10-05 18:39:31 +0000597/* nfile and ndup layout must match!
598 * NTOFD (>&fdnum) uses ndup structure, but we may discover mid-flight
599 * that it is actually NTO2 (>&file), and change its type.
600 */
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000601struct nfile {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000602 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000603 union node *next;
604 int fd;
Denis Vlasenko559691a2008-10-05 18:39:31 +0000605 int _unused_dupfd;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000606 union node *fname;
607 char *expfname;
608};
609
610struct ndup {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000611 smallint type;
Denis Vlasenko559691a2008-10-05 18:39:31 +0000612 union node *next;
613 int fd;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000614 int dupfd;
615 union node *vname;
Denis Vlasenko559691a2008-10-05 18:39:31 +0000616 char *_unused_expfname;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000617};
618
619struct nhere {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000620 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000621 union node *next;
622 int fd;
623 union node *doc;
624};
625
626struct nnot {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000627 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000628 union node *com;
629};
630
631union node {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000632 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000633 struct ncmd ncmd;
634 struct npipe npipe;
635 struct nredir nredir;
636 struct nbinary nbinary;
637 struct nif nif;
638 struct nfor nfor;
639 struct ncase ncase;
640 struct nclist nclist;
641 struct narg narg;
642 struct nfile nfile;
643 struct ndup ndup;
644 struct nhere nhere;
645 struct nnot nnot;
646};
647
Denys Vlasenko86e83ec2009-07-23 22:07:07 +0200648/*
649 * NODE_EOF is returned by parsecmd when it encounters an end of file.
650 * It must be distinct from NULL.
651 */
652#define NODE_EOF ((union node *) -1L)
653
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000654struct nodelist {
655 struct nodelist *next;
656 union node *n;
657};
658
659struct funcnode {
660 int count;
661 union node n;
662};
663
Denis Vlasenko5651bfc2007-02-23 21:08:58 +0000664/*
665 * Free a parse tree.
666 */
667static void
668freefunc(struct funcnode *f)
669{
670 if (f && --f->count < 0)
671 free(f);
672}
673
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000674
675/* ============ Debugging output */
676
677#if DEBUG
678
679static FILE *tracefile;
680
681static void
682trace_printf(const char *fmt, ...)
683{
684 va_list va;
685
686 if (debug != 1)
687 return;
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000688 if (DEBUG_TIME)
689 fprintf(tracefile, "%u ", (int) time(NULL));
690 if (DEBUG_PID)
691 fprintf(tracefile, "[%u] ", (int) getpid());
692 if (DEBUG_SIG)
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200693 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000694 va_start(va, fmt);
695 vfprintf(tracefile, fmt, va);
696 va_end(va);
697}
698
699static void
700trace_vprintf(const char *fmt, va_list va)
701{
702 if (debug != 1)
703 return;
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000704 if (DEBUG_TIME)
705 fprintf(tracefile, "%u ", (int) time(NULL));
706 if (DEBUG_PID)
707 fprintf(tracefile, "[%u] ", (int) getpid());
708 if (DEBUG_SIG)
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200709 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000710 vfprintf(tracefile, fmt, va);
711}
712
713static void
714trace_puts(const char *s)
715{
716 if (debug != 1)
717 return;
718 fputs(s, tracefile);
719}
720
721static void
722trace_puts_quoted(char *s)
723{
724 char *p;
725 char c;
726
727 if (debug != 1)
728 return;
729 putc('"', tracefile);
730 for (p = s; *p; p++) {
Denys Vlasenkocd716832009-11-28 22:14:02 +0100731 switch ((unsigned char)*p) {
732 case '\n': c = 'n'; goto backslash;
733 case '\t': c = 't'; goto backslash;
734 case '\r': c = 'r'; goto backslash;
735 case '\"': c = '\"'; goto backslash;
736 case '\\': c = '\\'; goto backslash;
737 case CTLESC: c = 'e'; goto backslash;
738 case CTLVAR: c = 'v'; goto backslash;
739 case CTLVAR+CTLQUOTE: c = 'V'; goto backslash;
740 case CTLBACKQ: c = 'q'; goto backslash;
741 case CTLBACKQ+CTLQUOTE: c = 'Q'; goto backslash;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000742 backslash:
743 putc('\\', tracefile);
744 putc(c, tracefile);
745 break;
746 default:
747 if (*p >= ' ' && *p <= '~')
748 putc(*p, tracefile);
749 else {
750 putc('\\', tracefile);
Denys Vlasenkocd716832009-11-28 22:14:02 +0100751 putc((*p >> 6) & 03, tracefile);
752 putc((*p >> 3) & 07, tracefile);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000753 putc(*p & 07, tracefile);
754 }
755 break;
756 }
757 }
758 putc('"', tracefile);
759}
760
761static void
762trace_puts_args(char **ap)
763{
764 if (debug != 1)
765 return;
766 if (!*ap)
767 return;
768 while (1) {
769 trace_puts_quoted(*ap);
770 if (!*++ap) {
771 putc('\n', tracefile);
772 break;
773 }
774 putc(' ', tracefile);
775 }
776}
777
778static void
779opentrace(void)
780{
781 char s[100];
782#ifdef O_APPEND
783 int flags;
784#endif
785
786 if (debug != 1) {
787 if (tracefile)
788 fflush(tracefile);
789 /* leave open because libedit might be using it */
790 return;
791 }
792 strcpy(s, "./trace");
793 if (tracefile) {
794 if (!freopen(s, "a", tracefile)) {
795 fprintf(stderr, "Can't re-open %s\n", s);
796 debug = 0;
797 return;
798 }
799 } else {
800 tracefile = fopen(s, "a");
801 if (tracefile == NULL) {
802 fprintf(stderr, "Can't open %s\n", s);
803 debug = 0;
804 return;
805 }
806 }
807#ifdef O_APPEND
Denis Vlasenkod37f2222007-08-19 13:42:08 +0000808 flags = fcntl(fileno(tracefile), F_GETFL);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000809 if (flags >= 0)
810 fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
811#endif
812 setlinebuf(tracefile);
813 fputs("\nTracing started.\n", tracefile);
814}
815
816static void
817indent(int amount, char *pfx, FILE *fp)
818{
819 int i;
820
821 for (i = 0; i < amount; i++) {
822 if (pfx && i == amount - 1)
823 fputs(pfx, fp);
824 putc('\t', fp);
825 }
826}
827
828/* little circular references here... */
829static void shtree(union node *n, int ind, char *pfx, FILE *fp);
830
831static void
832sharg(union node *arg, FILE *fp)
833{
834 char *p;
835 struct nodelist *bqlist;
Denys Vlasenkocd716832009-11-28 22:14:02 +0100836 unsigned char subtype;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000837
838 if (arg->type != NARG) {
839 out1fmt("<node type %d>\n", arg->type);
840 abort();
841 }
842 bqlist = arg->narg.backquote;
843 for (p = arg->narg.text; *p; p++) {
Denys Vlasenkocd716832009-11-28 22:14:02 +0100844 switch ((unsigned char)*p) {
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000845 case CTLESC:
846 putc(*++p, fp);
847 break;
848 case CTLVAR:
849 putc('$', fp);
850 putc('{', fp);
851 subtype = *++p;
852 if (subtype == VSLENGTH)
853 putc('#', fp);
854
855 while (*p != '=')
856 putc(*p++, fp);
857
858 if (subtype & VSNUL)
859 putc(':', fp);
860
861 switch (subtype & VSTYPE) {
862 case VSNORMAL:
863 putc('}', fp);
864 break;
865 case VSMINUS:
866 putc('-', fp);
867 break;
868 case VSPLUS:
869 putc('+', fp);
870 break;
871 case VSQUESTION:
872 putc('?', fp);
873 break;
874 case VSASSIGN:
875 putc('=', fp);
876 break;
877 case VSTRIMLEFT:
878 putc('#', fp);
879 break;
880 case VSTRIMLEFTMAX:
881 putc('#', fp);
882 putc('#', fp);
883 break;
884 case VSTRIMRIGHT:
885 putc('%', fp);
886 break;
887 case VSTRIMRIGHTMAX:
888 putc('%', fp);
889 putc('%', fp);
890 break;
891 case VSLENGTH:
892 break;
893 default:
894 out1fmt("<subtype %d>", subtype);
895 }
896 break;
897 case CTLENDVAR:
898 putc('}', fp);
899 break;
900 case CTLBACKQ:
901 case CTLBACKQ|CTLQUOTE:
902 putc('$', fp);
903 putc('(', fp);
904 shtree(bqlist->n, -1, NULL, fp);
905 putc(')', fp);
906 break;
907 default:
908 putc(*p, fp);
909 break;
910 }
911 }
912}
913
Denys Vlasenko641dd7b2009-06-11 19:30:19 +0200914static void
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000915shcmd(union node *cmd, FILE *fp)
916{
917 union node *np;
918 int first;
919 const char *s;
920 int dftfd;
921
922 first = 1;
923 for (np = cmd->ncmd.args; np; np = np->narg.next) {
Denis Vlasenko40ba9982007-07-14 00:48:29 +0000924 if (!first)
925 putc(' ', fp);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000926 sharg(np, fp);
927 first = 0;
928 }
929 for (np = cmd->ncmd.redirect; np; np = np->nfile.next) {
Denis Vlasenko40ba9982007-07-14 00:48:29 +0000930 if (!first)
931 putc(' ', fp);
932 dftfd = 0;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000933 switch (np->nfile.type) {
Denis Vlasenko40ba9982007-07-14 00:48:29 +0000934 case NTO: s = ">>"+1; dftfd = 1; break;
935 case NCLOBBER: s = ">|"; dftfd = 1; break;
936 case NAPPEND: s = ">>"; dftfd = 1; break;
Denis Vlasenko559691a2008-10-05 18:39:31 +0000937#if ENABLE_ASH_BASH_COMPAT
938 case NTO2:
939#endif
Denis Vlasenko40ba9982007-07-14 00:48:29 +0000940 case NTOFD: s = ">&"; dftfd = 1; break;
Denis Vlasenko559691a2008-10-05 18:39:31 +0000941 case NFROM: s = "<"; break;
Denis Vlasenko40ba9982007-07-14 00:48:29 +0000942 case NFROMFD: s = "<&"; break;
943 case NFROMTO: s = "<>"; break;
944 default: s = "*error*"; break;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000945 }
946 if (np->nfile.fd != dftfd)
947 fprintf(fp, "%d", np->nfile.fd);
948 fputs(s, fp);
949 if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
950 fprintf(fp, "%d", np->ndup.dupfd);
951 } else {
952 sharg(np->nfile.fname, fp);
953 }
954 first = 0;
955 }
956}
957
958static void
959shtree(union node *n, int ind, char *pfx, FILE *fp)
960{
961 struct nodelist *lp;
962 const char *s;
963
964 if (n == NULL)
965 return;
966
967 indent(ind, pfx, fp);
Denys Vlasenko86e83ec2009-07-23 22:07:07 +0200968
969 if (n == NODE_EOF) {
970 fputs("<EOF>", fp);
971 return;
972 }
973
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000974 switch (n->type) {
975 case NSEMI:
976 s = "; ";
977 goto binop;
978 case NAND:
979 s = " && ";
980 goto binop;
981 case NOR:
982 s = " || ";
983 binop:
984 shtree(n->nbinary.ch1, ind, NULL, fp);
985 /* if (ind < 0) */
986 fputs(s, fp);
987 shtree(n->nbinary.ch2, ind, NULL, fp);
988 break;
989 case NCMD:
990 shcmd(n, fp);
991 if (ind >= 0)
992 putc('\n', fp);
993 break;
994 case NPIPE:
995 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
Denys Vlasenko7cee00e2009-07-24 01:08:03 +0200996 shtree(lp->n, 0, NULL, fp);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000997 if (lp->next)
998 fputs(" | ", fp);
999 }
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00001000 if (n->npipe.pipe_backgnd)
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00001001 fputs(" &", fp);
1002 if (ind >= 0)
1003 putc('\n', fp);
1004 break;
1005 default:
1006 fprintf(fp, "<node type %d>", n->type);
1007 if (ind >= 0)
1008 putc('\n', fp);
1009 break;
1010 }
1011}
1012
1013static void
1014showtree(union node *n)
1015{
1016 trace_puts("showtree called\n");
Denys Vlasenko883cea42009-07-11 15:31:59 +02001017 shtree(n, 1, NULL, stderr);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00001018}
1019
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00001020#endif /* DEBUG */
1021
1022
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00001023/* ============ Parser data */
1024
1025/*
Denis Vlasenkob012b102007-02-19 22:43:01 +00001026 * ash_vmsg() needs parsefile->fd, hence parsefile definition is moved up.
1027 */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001028struct strlist {
1029 struct strlist *next;
1030 char *text;
1031};
1032
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00001033struct alias;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00001034
Denis Vlasenkob012b102007-02-19 22:43:01 +00001035struct strpush {
1036 struct strpush *prev; /* preceding string on stack */
Denis Vlasenko41eb3002008-11-28 03:42:31 +00001037 char *prev_string;
1038 int prev_left_in_line;
Denis Vlasenkob012b102007-02-19 22:43:01 +00001039#if ENABLE_ASH_ALIAS
1040 struct alias *ap; /* if push was associated with an alias */
1041#endif
1042 char *string; /* remember the string since it may change */
1043};
1044
1045struct parsefile {
1046 struct parsefile *prev; /* preceding file on stack */
1047 int linno; /* current line */
Denys Vlasenko79b3d422010-06-03 04:29:08 +02001048 int pf_fd; /* file descriptor (or -1 if string) */
Denis Vlasenko41eb3002008-11-28 03:42:31 +00001049 int left_in_line; /* number of chars left in this line */
1050 int left_in_buffer; /* number of chars left in this buffer past the line */
1051 char *next_to_pgetc; /* next char in buffer */
Denis Vlasenkob012b102007-02-19 22:43:01 +00001052 char *buf; /* input buffer */
1053 struct strpush *strpush; /* for pushing strings at this level */
1054 struct strpush basestrpush; /* so pushing one is fast */
1055};
1056
Denis Vlasenko448d30e2008-06-27 00:24:11 +00001057static struct parsefile basepf; /* top level input file */
Denis Vlasenkob07a4962008-06-22 13:16:23 +00001058static struct parsefile *g_parsefile = &basepf; /* current input file */
Denis Vlasenkob012b102007-02-19 22:43:01 +00001059static int startlinno; /* line # where last token started */
1060static char *commandname; /* currently executing command */
1061static struct strlist *cmdenviron; /* environment for builtin command */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00001062static uint8_t exitstatus; /* exit status of last command */
Denis Vlasenkob012b102007-02-19 22:43:01 +00001063
1064
1065/* ============ Message printing */
1066
1067static void
1068ash_vmsg(const char *msg, va_list ap)
1069{
1070 fprintf(stderr, "%s: ", arg0);
1071 if (commandname) {
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00001072 if (strcmp(arg0, commandname))
1073 fprintf(stderr, "%s: ", commandname);
Denys Vlasenko79b3d422010-06-03 04:29:08 +02001074 if (!iflag || g_parsefile->pf_fd > 0)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00001075 fprintf(stderr, "line %d: ", startlinno);
Eric Andersenc470f442003-07-28 09:56:35 +00001076 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00001077 vfprintf(stderr, msg, ap);
1078 outcslow('\n', stderr);
Eric Andersenc470f442003-07-28 09:56:35 +00001079}
Denis Vlasenkob012b102007-02-19 22:43:01 +00001080
1081/*
1082 * Exverror is called to raise the error exception. If the second argument
1083 * is not NULL then error prints an error message using printf style
1084 * formatting. It then raises the error exception.
1085 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001086static void ash_vmsg_and_raise(int, const char *, va_list) NORETURN;
Denis Vlasenkob012b102007-02-19 22:43:01 +00001087static void
1088ash_vmsg_and_raise(int cond, const char *msg, va_list ap)
Eric Andersenc470f442003-07-28 09:56:35 +00001089{
Denis Vlasenkob012b102007-02-19 22:43:01 +00001090#if DEBUG
1091 if (msg) {
1092 TRACE(("ash_vmsg_and_raise(%d, \"", cond));
1093 TRACEV((msg, ap));
1094 TRACE(("\") pid=%d\n", getpid()));
1095 } else
1096 TRACE(("ash_vmsg_and_raise(%d, NULL) pid=%d\n", cond, getpid()));
1097 if (msg)
1098#endif
1099 ash_vmsg(msg, ap);
1100
1101 flush_stdout_stderr();
1102 raise_exception(cond);
1103 /* NOTREACHED */
Eric Andersenc470f442003-07-28 09:56:35 +00001104}
Denis Vlasenkob012b102007-02-19 22:43:01 +00001105
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001106static void ash_msg_and_raise_error(const char *, ...) NORETURN;
Denis Vlasenkob012b102007-02-19 22:43:01 +00001107static void
1108ash_msg_and_raise_error(const char *msg, ...)
1109{
1110 va_list ap;
1111
1112 va_start(ap, msg);
1113 ash_vmsg_and_raise(EXERROR, msg, ap);
1114 /* NOTREACHED */
1115 va_end(ap);
1116}
1117
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00001118static void raise_error_syntax(const char *) NORETURN;
1119static void
1120raise_error_syntax(const char *msg)
1121{
1122 ash_msg_and_raise_error("syntax error: %s", msg);
1123 /* NOTREACHED */
1124}
1125
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001126static void ash_msg_and_raise(int, const char *, ...) NORETURN;
Denis Vlasenkob012b102007-02-19 22:43:01 +00001127static void
1128ash_msg_and_raise(int cond, const char *msg, ...)
1129{
1130 va_list ap;
1131
1132 va_start(ap, msg);
1133 ash_vmsg_and_raise(cond, msg, ap);
1134 /* NOTREACHED */
1135 va_end(ap);
1136}
1137
1138/*
1139 * error/warning routines for external builtins
1140 */
1141static void
1142ash_msg(const char *fmt, ...)
1143{
1144 va_list ap;
1145
1146 va_start(ap, fmt);
1147 ash_vmsg(fmt, ap);
1148 va_end(ap);
1149}
1150
1151/*
1152 * Return a string describing an error. The returned string may be a
1153 * pointer to a static buffer that will be overwritten on the next call.
1154 * Action describes the operation that got the error.
1155 */
1156static const char *
1157errmsg(int e, const char *em)
1158{
1159 if (e == ENOENT || e == ENOTDIR) {
1160 return em;
1161 }
1162 return strerror(e);
1163}
1164
1165
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001166/* ============ Memory allocation */
1167
Denys Vlasenkoe7670ff2009-10-11 00:45:25 +02001168#if 0
1169/* I consider these wrappers nearly useless:
1170 * ok, they return you to nearest exception handler, but
1171 * how much memory do you leak in the process, making
1172 * memory starvation worse?
1173 */
1174static void *
1175ckrealloc(void * p, size_t nbytes)
1176{
1177 p = realloc(p, nbytes);
1178 if (!p)
1179 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1180 return p;
1181}
1182
1183static void *
1184ckmalloc(size_t nbytes)
1185{
1186 return ckrealloc(NULL, nbytes);
1187}
1188
1189static void *
1190ckzalloc(size_t nbytes)
1191{
1192 return memset(ckmalloc(nbytes), 0, nbytes);
1193}
1194
1195static char *
1196ckstrdup(const char *s)
1197{
1198 char *p = strdup(s);
1199 if (!p)
1200 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1201 return p;
1202}
1203#else
1204/* Using bbox equivalents. They exit if out of memory */
1205# define ckrealloc xrealloc
1206# define ckmalloc xmalloc
1207# define ckzalloc xzalloc
1208# define ckstrdup xstrdup
1209#endif
1210
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001211/*
1212 * It appears that grabstackstr() will barf with such alignments
1213 * because stalloc() will return a string allocated in a new stackblock.
1214 */
1215#define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
1216enum {
1217 /* Most machines require the value returned from malloc to be aligned
1218 * in some way. The following macro will get this right
1219 * on many machines. */
Denys Vlasenko0e5e4ea2009-10-11 00:36:20 +02001220 SHELL_SIZE = sizeof(union { int i; char *cp; double d; }) - 1,
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001221 /* Minimum size of a block */
Denis Vlasenko01631112007-12-16 17:20:38 +00001222 MINSIZE = SHELL_ALIGN(504),
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001223};
1224
1225struct stack_block {
1226 struct stack_block *prev;
1227 char space[MINSIZE];
1228};
1229
1230struct stackmark {
1231 struct stack_block *stackp;
1232 char *stacknxt;
1233 size_t stacknleft;
1234 struct stackmark *marknext;
1235};
1236
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001237
Denis Vlasenko01631112007-12-16 17:20:38 +00001238struct globals_memstack {
1239 struct stack_block *g_stackp; // = &stackbase;
1240 struct stackmark *markp;
1241 char *g_stacknxt; // = stackbase.space;
1242 char *sstrend; // = stackbase.space + MINSIZE;
1243 size_t g_stacknleft; // = MINSIZE;
1244 int herefd; // = -1;
1245 struct stack_block stackbase;
1246};
Denis Vlasenko574f2f42008-02-27 18:41:59 +00001247extern struct globals_memstack *const ash_ptr_to_globals_memstack;
1248#define G_memstack (*ash_ptr_to_globals_memstack)
Denis Vlasenko01631112007-12-16 17:20:38 +00001249#define g_stackp (G_memstack.g_stackp )
1250#define markp (G_memstack.markp )
1251#define g_stacknxt (G_memstack.g_stacknxt )
1252#define sstrend (G_memstack.sstrend )
1253#define g_stacknleft (G_memstack.g_stacknleft)
1254#define herefd (G_memstack.herefd )
1255#define stackbase (G_memstack.stackbase )
1256#define INIT_G_memstack() do { \
Denis Vlasenko574f2f42008-02-27 18:41:59 +00001257 (*(struct globals_memstack**)&ash_ptr_to_globals_memstack) = xzalloc(sizeof(G_memstack)); \
1258 barrier(); \
Denis Vlasenko01631112007-12-16 17:20:38 +00001259 g_stackp = &stackbase; \
1260 g_stacknxt = stackbase.space; \
1261 g_stacknleft = MINSIZE; \
1262 sstrend = stackbase.space + MINSIZE; \
1263 herefd = -1; \
1264} while (0)
1265
Denys Vlasenkoe7670ff2009-10-11 00:45:25 +02001266
Denis Vlasenko01631112007-12-16 17:20:38 +00001267#define stackblock() ((void *)g_stacknxt)
1268#define stackblocksize() g_stacknleft
1269
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001270/*
1271 * Parse trees for commands are allocated in lifo order, so we use a stack
1272 * to make this more efficient, and also to avoid all sorts of exception
1273 * handling code to handle interrupts in the middle of a parse.
1274 *
1275 * The size 504 was chosen because the Ultrix malloc handles that size
1276 * well.
1277 */
1278static void *
1279stalloc(size_t nbytes)
1280{
1281 char *p;
1282 size_t aligned;
1283
1284 aligned = SHELL_ALIGN(nbytes);
Denis Vlasenko01631112007-12-16 17:20:38 +00001285 if (aligned > g_stacknleft) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001286 size_t len;
1287 size_t blocksize;
1288 struct stack_block *sp;
1289
1290 blocksize = aligned;
1291 if (blocksize < MINSIZE)
1292 blocksize = MINSIZE;
1293 len = sizeof(struct stack_block) - MINSIZE + blocksize;
1294 if (len < blocksize)
1295 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1296 INT_OFF;
1297 sp = ckmalloc(len);
Denis Vlasenko01631112007-12-16 17:20:38 +00001298 sp->prev = g_stackp;
1299 g_stacknxt = sp->space;
1300 g_stacknleft = blocksize;
1301 sstrend = g_stacknxt + blocksize;
1302 g_stackp = sp;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001303 INT_ON;
1304 }
Denis Vlasenko01631112007-12-16 17:20:38 +00001305 p = g_stacknxt;
1306 g_stacknxt += aligned;
1307 g_stacknleft -= aligned;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001308 return p;
1309}
1310
Denis Vlasenko597906c2008-02-20 16:38:54 +00001311static void *
1312stzalloc(size_t nbytes)
1313{
1314 return memset(stalloc(nbytes), 0, nbytes);
1315}
1316
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001317static void
1318stunalloc(void *p)
1319{
1320#if DEBUG
Denis Vlasenko01631112007-12-16 17:20:38 +00001321 if (!p || (g_stacknxt < (char *)p) || ((char *)p < g_stackp->space)) {
Bernhard Reutner-Fischer5e25ddb2008-05-19 09:48:17 +00001322 write(STDERR_FILENO, "stunalloc\n", 10);
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001323 abort();
1324 }
1325#endif
Denis Vlasenko01631112007-12-16 17:20:38 +00001326 g_stacknleft += g_stacknxt - (char *)p;
1327 g_stacknxt = p;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001328}
1329
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001330/*
1331 * Like strdup but works with the ash stack.
1332 */
1333static char *
1334ststrdup(const char *p)
1335{
1336 size_t len = strlen(p) + 1;
1337 return memcpy(stalloc(len), p, len);
1338}
1339
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001340static void
1341setstackmark(struct stackmark *mark)
1342{
Denis Vlasenko01631112007-12-16 17:20:38 +00001343 mark->stackp = g_stackp;
1344 mark->stacknxt = g_stacknxt;
1345 mark->stacknleft = g_stacknleft;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001346 mark->marknext = markp;
1347 markp = mark;
1348}
1349
1350static void
1351popstackmark(struct stackmark *mark)
1352{
1353 struct stack_block *sp;
1354
Denis Vlasenko93ebd4f2007-03-13 20:55:36 +00001355 if (!mark->stackp)
1356 return;
1357
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001358 INT_OFF;
1359 markp = mark->marknext;
Denis Vlasenko01631112007-12-16 17:20:38 +00001360 while (g_stackp != mark->stackp) {
1361 sp = g_stackp;
1362 g_stackp = sp->prev;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001363 free(sp);
1364 }
Denis Vlasenko01631112007-12-16 17:20:38 +00001365 g_stacknxt = mark->stacknxt;
1366 g_stacknleft = mark->stacknleft;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001367 sstrend = mark->stacknxt + mark->stacknleft;
1368 INT_ON;
1369}
1370
1371/*
1372 * When the parser reads in a string, it wants to stick the string on the
1373 * stack and only adjust the stack pointer when it knows how big the
1374 * string is. Stackblock (defined in stack.h) returns a pointer to a block
1375 * of space on top of the stack and stackblocklen returns the length of
1376 * this block. Growstackblock will grow this space by at least one byte,
1377 * possibly moving it (like realloc). Grabstackblock actually allocates the
1378 * part of the block that has been used.
1379 */
1380static void
1381growstackblock(void)
1382{
1383 size_t newlen;
1384
Denis Vlasenko01631112007-12-16 17:20:38 +00001385 newlen = g_stacknleft * 2;
1386 if (newlen < g_stacknleft)
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001387 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1388 if (newlen < 128)
1389 newlen += 128;
1390
Denis Vlasenko01631112007-12-16 17:20:38 +00001391 if (g_stacknxt == g_stackp->space && g_stackp != &stackbase) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001392 struct stack_block *oldstackp;
1393 struct stackmark *xmark;
1394 struct stack_block *sp;
1395 struct stack_block *prevstackp;
1396 size_t grosslen;
1397
1398 INT_OFF;
Denis Vlasenko01631112007-12-16 17:20:38 +00001399 oldstackp = g_stackp;
1400 sp = g_stackp;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001401 prevstackp = sp->prev;
1402 grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
1403 sp = ckrealloc(sp, grosslen);
1404 sp->prev = prevstackp;
Denis Vlasenko01631112007-12-16 17:20:38 +00001405 g_stackp = sp;
1406 g_stacknxt = sp->space;
1407 g_stacknleft = newlen;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001408 sstrend = sp->space + newlen;
1409
1410 /*
1411 * Stack marks pointing to the start of the old block
1412 * must be relocated to point to the new block
1413 */
1414 xmark = markp;
1415 while (xmark != NULL && xmark->stackp == oldstackp) {
Denis Vlasenko01631112007-12-16 17:20:38 +00001416 xmark->stackp = g_stackp;
1417 xmark->stacknxt = g_stacknxt;
1418 xmark->stacknleft = g_stacknleft;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001419 xmark = xmark->marknext;
1420 }
1421 INT_ON;
1422 } else {
Denis Vlasenko01631112007-12-16 17:20:38 +00001423 char *oldspace = g_stacknxt;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00001424 size_t oldlen = g_stacknleft;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001425 char *p = stalloc(newlen);
1426
1427 /* free the space we just allocated */
Denis Vlasenko01631112007-12-16 17:20:38 +00001428 g_stacknxt = memcpy(p, oldspace, oldlen);
1429 g_stacknleft += newlen;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001430 }
1431}
1432
1433static void
1434grabstackblock(size_t len)
1435{
1436 len = SHELL_ALIGN(len);
Denis Vlasenko01631112007-12-16 17:20:38 +00001437 g_stacknxt += len;
1438 g_stacknleft -= len;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001439}
1440
1441/*
1442 * The following routines are somewhat easier to use than the above.
1443 * The user declares a variable of type STACKSTR, which may be declared
1444 * to be a register. The macro STARTSTACKSTR initializes things. Then
1445 * the user uses the macro STPUTC to add characters to the string. In
1446 * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
1447 * grown as necessary. When the user is done, she can just leave the
1448 * string there and refer to it using stackblock(). Or she can allocate
1449 * the space for it using grabstackstr(). If it is necessary to allow
1450 * someone else to use the stack temporarily and then continue to grow
1451 * the string, the user should use grabstack to allocate the space, and
1452 * then call ungrabstr(p) to return to the previous mode of operation.
1453 *
1454 * USTPUTC is like STPUTC except that it doesn't check for overflow.
1455 * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
1456 * is space for at least one character.
1457 */
1458static void *
1459growstackstr(void)
1460{
1461 size_t len = stackblocksize();
1462 if (herefd >= 0 && len >= 1024) {
1463 full_write(herefd, stackblock(), len);
1464 return stackblock();
1465 }
1466 growstackblock();
Denis Vlasenko29eb3592008-05-18 14:06:08 +00001467 return (char *)stackblock() + len;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001468}
1469
1470/*
1471 * Called from CHECKSTRSPACE.
1472 */
1473static char *
1474makestrspace(size_t newlen, char *p)
1475{
Denis Vlasenko01631112007-12-16 17:20:38 +00001476 size_t len = p - g_stacknxt;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001477 size_t size = stackblocksize();
1478
1479 for (;;) {
1480 size_t nleft;
1481
1482 size = stackblocksize();
1483 nleft = size - len;
1484 if (nleft >= newlen)
1485 break;
1486 growstackblock();
1487 }
Denis Vlasenko29eb3592008-05-18 14:06:08 +00001488 return (char *)stackblock() + len;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001489}
1490
1491static char *
1492stack_nputstr(const char *s, size_t n, char *p)
1493{
1494 p = makestrspace(n, p);
Denis Vlasenko29eb3592008-05-18 14:06:08 +00001495 p = (char *)memcpy(p, s, n) + n;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001496 return p;
1497}
1498
1499static char *
1500stack_putstr(const char *s, char *p)
1501{
1502 return stack_nputstr(s, strlen(s), p);
1503}
1504
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001505static char *
1506_STPUTC(int c, char *p)
1507{
1508 if (p == sstrend)
1509 p = growstackstr();
1510 *p++ = c;
1511 return p;
1512}
1513
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00001514#define STARTSTACKSTR(p) ((p) = stackblock())
1515#define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
Denis Vlasenko843cbd52008-06-27 00:23:18 +00001516#define CHECKSTRSPACE(n, p) do { \
1517 char *q = (p); \
1518 size_t l = (n); \
1519 size_t m = sstrend - q; \
1520 if (l > m) \
1521 (p) = makestrspace(l, q); \
1522} while (0)
Denis Vlasenkoef527f52008-06-23 01:52:30 +00001523#define USTPUTC(c, p) (*(p)++ = (c))
Denis Vlasenko843cbd52008-06-27 00:23:18 +00001524#define STACKSTRNUL(p) do { \
1525 if ((p) == sstrend) \
1526 (p) = growstackstr(); \
1527 *(p) = '\0'; \
1528} while (0)
Denis Vlasenkoef527f52008-06-23 01:52:30 +00001529#define STUNPUTC(p) (--(p))
1530#define STTOPC(p) ((p)[-1])
1531#define STADJUST(amount, p) ((p) += (amount))
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001532
1533#define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
Denis Vlasenkoef527f52008-06-23 01:52:30 +00001534#define ungrabstackstr(s, p) stunalloc(s)
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001535#define stackstrend() ((void *)sstrend)
1536
1537
1538/* ============ String helpers */
1539
1540/*
1541 * prefix -- see if pfx is a prefix of string.
1542 */
1543static char *
1544prefix(const char *string, const char *pfx)
1545{
1546 while (*pfx) {
1547 if (*pfx++ != *string++)
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00001548 return NULL;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001549 }
1550 return (char *) string;
1551}
1552
1553/*
1554 * Check for a valid number. This should be elsewhere.
1555 */
1556static int
1557is_number(const char *p)
1558{
1559 do {
1560 if (!isdigit(*p))
1561 return 0;
1562 } while (*++p != '\0');
1563 return 1;
1564}
1565
1566/*
1567 * Convert a string of digits to an integer, printing an error message on
1568 * failure.
1569 */
1570static int
1571number(const char *s)
1572{
1573 if (!is_number(s))
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02001574 ash_msg_and_raise_error(msg_illnum, s);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001575 return atoi(s);
1576}
1577
1578/*
1579 * Produce a possibly single quoted string suitable as input to the shell.
1580 * The return string is allocated on the stack.
1581 */
1582static char *
1583single_quote(const char *s)
1584{
1585 char *p;
1586
1587 STARTSTACKSTR(p);
1588
1589 do {
1590 char *q;
1591 size_t len;
1592
1593 len = strchrnul(s, '\'') - s;
1594
1595 q = p = makestrspace(len + 3, p);
1596
1597 *q++ = '\'';
Denis Vlasenko29eb3592008-05-18 14:06:08 +00001598 q = (char *)memcpy(q, s, len) + len;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001599 *q++ = '\'';
1600 s += len;
1601
1602 STADJUST(q - p, p);
1603
Denys Vlasenkocd716832009-11-28 22:14:02 +01001604 if (*s != '\'')
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001605 break;
Denys Vlasenkocd716832009-11-28 22:14:02 +01001606 len = 0;
1607 do len++; while (*++s == '\'');
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001608
1609 q = p = makestrspace(len + 3, p);
1610
1611 *q++ = '"';
Denys Vlasenkocd716832009-11-28 22:14:02 +01001612 q = (char *)memcpy(q, s - len, len) + len;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001613 *q++ = '"';
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001614
1615 STADJUST(q - p, p);
1616 } while (*s);
1617
Denys Vlasenkocd716832009-11-28 22:14:02 +01001618 USTPUTC('\0', p);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001619
1620 return stackblock();
1621}
1622
1623
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00001624/* ============ nextopt */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001625
1626static char **argptr; /* argument list for builtin commands */
1627static char *optionarg; /* set by nextopt (like getopt) */
1628static char *optptr; /* used by nextopt */
1629
1630/*
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001631 * XXX - should get rid of. Have all builtins use getopt(3).
1632 * The library getopt must have the BSD extension static variable
1633 * "optreset", otherwise it can't be used within the shell safely.
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001634 *
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001635 * Standard option processing (a la getopt) for builtin routines.
1636 * The only argument that is passed to nextopt is the option string;
1637 * the other arguments are unnecessary. It returns the character,
1638 * or '\0' on end of input.
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001639 */
1640static int
1641nextopt(const char *optstring)
1642{
1643 char *p;
1644 const char *q;
1645 char c;
1646
1647 p = optptr;
1648 if (p == NULL || *p == '\0') {
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001649 /* We ate entire "-param", take next one */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001650 p = *argptr;
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001651 if (p == NULL)
1652 return '\0';
1653 if (*p != '-')
1654 return '\0';
1655 if (*++p == '\0') /* just "-" ? */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001656 return '\0';
1657 argptr++;
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001658 if (LONE_DASH(p)) /* "--" ? */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001659 return '\0';
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001660 /* p => next "-param" */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001661 }
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001662 /* p => some option char in the middle of a "-param" */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001663 c = *p++;
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +00001664 for (q = optstring; *q != c;) {
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001665 if (*q == '\0')
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00001666 ash_msg_and_raise_error("illegal option -%c", c);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001667 if (*++q == ':')
1668 q++;
1669 }
1670 if (*++q == ':') {
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001671 if (*p == '\0') {
1672 p = *argptr++;
1673 if (p == NULL)
1674 ash_msg_and_raise_error("no arg for -%c option", c);
1675 }
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001676 optionarg = p;
1677 p = NULL;
1678 }
1679 optptr = p;
1680 return c;
1681}
1682
1683
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00001684/* ============ Shell variables */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001685
Denis Vlasenko01631112007-12-16 17:20:38 +00001686/*
1687 * The parsefile structure pointed to by the global variable parsefile
1688 * contains information about the current file being read.
1689 */
Denis Vlasenko01631112007-12-16 17:20:38 +00001690struct shparam {
1691 int nparam; /* # of positional parameters (without $0) */
1692#if ENABLE_ASH_GETOPTS
1693 int optind; /* next parameter to be processed by getopts */
1694 int optoff; /* used by getopts */
1695#endif
1696 unsigned char malloced; /* if parameter list dynamically allocated */
1697 char **p; /* parameter list */
1698};
1699
1700/*
1701 * Free the list of positional parameters.
1702 */
1703static void
1704freeparam(volatile struct shparam *param)
1705{
Denis Vlasenko01631112007-12-16 17:20:38 +00001706 if (param->malloced) {
Denis Vlasenko3177ba02008-07-13 20:39:23 +00001707 char **ap, **ap1;
1708 ap = ap1 = param->p;
1709 while (*ap)
1710 free(*ap++);
1711 free(ap1);
Denis Vlasenko01631112007-12-16 17:20:38 +00001712 }
1713}
1714
1715#if ENABLE_ASH_GETOPTS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001716static void FAST_FUNC getoptsreset(const char *value);
Denis Vlasenko01631112007-12-16 17:20:38 +00001717#endif
1718
1719struct var {
1720 struct var *next; /* next entry in hash list */
1721 int flags; /* flags are defined above */
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02001722 const char *var_text; /* name=value */
1723 void (*var_func)(const char *) FAST_FUNC; /* function to be called when */
Denis Vlasenko01631112007-12-16 17:20:38 +00001724 /* the variable gets set/unset */
1725};
1726
1727struct localvar {
1728 struct localvar *next; /* next local variable in list */
1729 struct var *vp; /* the variable that was made local */
1730 int flags; /* saved flags */
1731 const char *text; /* saved text */
1732};
1733
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001734/* flags */
1735#define VEXPORT 0x01 /* variable is exported */
1736#define VREADONLY 0x02 /* variable cannot be modified */
1737#define VSTRFIXED 0x04 /* variable struct is statically allocated */
1738#define VTEXTFIXED 0x08 /* text is statically allocated */
1739#define VSTACK 0x10 /* text is allocated on the stack */
1740#define VUNSET 0x20 /* the variable is not set */
1741#define VNOFUNC 0x40 /* don't call the callback function */
1742#define VNOSET 0x80 /* do not set variable - just readonly test */
1743#define VNOSAVE 0x100 /* when text is on the heap before setvareq */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00001744#if ENABLE_ASH_RANDOM_SUPPORT
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00001745# define VDYNAMIC 0x200 /* dynamic variable */
1746#else
1747# define VDYNAMIC 0
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001748#endif
1749
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00001750
Denis Vlasenko01631112007-12-16 17:20:38 +00001751/* Need to be before varinit_data[] */
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00001752#if ENABLE_LOCALE_SUPPORT
Denys Vlasenko2634bf32009-06-09 18:40:07 +02001753static void FAST_FUNC
Denis Vlasenkoa8915072007-02-23 21:10:06 +00001754change_lc_all(const char *value)
1755{
1756 if (value && *value != '\0')
1757 setlocale(LC_ALL, value);
1758}
Denys Vlasenko2634bf32009-06-09 18:40:07 +02001759static void FAST_FUNC
Denis Vlasenkoa8915072007-02-23 21:10:06 +00001760change_lc_ctype(const char *value)
1761{
1762 if (value && *value != '\0')
1763 setlocale(LC_CTYPE, value);
1764}
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00001765#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001766#if ENABLE_ASH_MAIL
1767static void chkmail(void);
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001768static void changemail(const char *) FAST_FUNC;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001769#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001770static void changepath(const char *) FAST_FUNC;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001771#if ENABLE_ASH_RANDOM_SUPPORT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001772static void change_random(const char *) FAST_FUNC;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001773#endif
1774
Denis Vlasenko01631112007-12-16 17:20:38 +00001775static const struct {
1776 int flags;
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02001777 const char *var_text;
1778 void (*var_func)(const char *) FAST_FUNC;
Denis Vlasenko01631112007-12-16 17:20:38 +00001779} varinit_data[] = {
Denis Vlasenko01631112007-12-16 17:20:38 +00001780 { VSTRFIXED|VTEXTFIXED , defifsvar , NULL },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001781#if ENABLE_ASH_MAIL
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02001782 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL" , changemail },
1783 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH" , changemail },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001784#endif
Denis Vlasenko01631112007-12-16 17:20:38 +00001785 { VSTRFIXED|VTEXTFIXED , bb_PATH_root_path, changepath },
1786 { VSTRFIXED|VTEXTFIXED , "PS1=$ " , NULL },
1787 { VSTRFIXED|VTEXTFIXED , "PS2=> " , NULL },
1788 { VSTRFIXED|VTEXTFIXED , "PS4=+ " , NULL },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001789#if ENABLE_ASH_GETOPTS
Denis Vlasenko01631112007-12-16 17:20:38 +00001790 { VSTRFIXED|VTEXTFIXED , "OPTIND=1" , getoptsreset },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001791#endif
1792#if ENABLE_ASH_RANDOM_SUPPORT
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02001793 { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM", change_random },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001794#endif
1795#if ENABLE_LOCALE_SUPPORT
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02001796 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL" , change_lc_all },
1797 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE" , change_lc_ctype },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001798#endif
1799#if ENABLE_FEATURE_EDITING_SAVEHISTORY
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02001800 { VSTRFIXED|VTEXTFIXED|VUNSET, "HISTFILE" , NULL },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001801#endif
1802};
1803
Denis Vlasenko0b769642008-07-24 07:54:57 +00001804struct redirtab;
Denis Vlasenko01631112007-12-16 17:20:38 +00001805
1806struct globals_var {
1807 struct shparam shellparam; /* $@ current positional parameters */
1808 struct redirtab *redirlist;
1809 int g_nullredirs;
1810 int preverrout_fd; /* save fd2 before print debug if xflag is set. */
1811 struct var *vartab[VTABSIZE];
1812 struct var varinit[ARRAY_SIZE(varinit_data)];
1813};
Denis Vlasenko574f2f42008-02-27 18:41:59 +00001814extern struct globals_var *const ash_ptr_to_globals_var;
1815#define G_var (*ash_ptr_to_globals_var)
Denis Vlasenko01631112007-12-16 17:20:38 +00001816#define shellparam (G_var.shellparam )
Denis Vlasenko0b769642008-07-24 07:54:57 +00001817//#define redirlist (G_var.redirlist )
Denis Vlasenko01631112007-12-16 17:20:38 +00001818#define g_nullredirs (G_var.g_nullredirs )
1819#define preverrout_fd (G_var.preverrout_fd)
1820#define vartab (G_var.vartab )
1821#define varinit (G_var.varinit )
1822#define INIT_G_var() do { \
Denis Vlasenko6b06cb82008-05-15 21:30:45 +00001823 unsigned i; \
Denis Vlasenko574f2f42008-02-27 18:41:59 +00001824 (*(struct globals_var**)&ash_ptr_to_globals_var) = xzalloc(sizeof(G_var)); \
1825 barrier(); \
Denis Vlasenko01631112007-12-16 17:20:38 +00001826 for (i = 0; i < ARRAY_SIZE(varinit_data); i++) { \
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02001827 varinit[i].flags = varinit_data[i].flags; \
1828 varinit[i].var_text = varinit_data[i].var_text; \
1829 varinit[i].var_func = varinit_data[i].var_func; \
Denis Vlasenko01631112007-12-16 17:20:38 +00001830 } \
1831} while (0)
1832
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001833#define vifs varinit[0]
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001834#if ENABLE_ASH_MAIL
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001835# define vmail (&vifs)[1]
1836# define vmpath (&vmail)[1]
1837# define vpath (&vmpath)[1]
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001838#else
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001839# define vpath (&vifs)[1]
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001840#endif
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001841#define vps1 (&vpath)[1]
1842#define vps2 (&vps1)[1]
1843#define vps4 (&vps2)[1]
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001844#if ENABLE_ASH_GETOPTS
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001845# define voptind (&vps4)[1]
1846# if ENABLE_ASH_RANDOM_SUPPORT
1847# define vrandom (&voptind)[1]
1848# endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001849#else
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001850# if ENABLE_ASH_RANDOM_SUPPORT
1851# define vrandom (&vps4)[1]
1852# endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001853#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001854
1855/*
1856 * The following macros access the values of the above variables.
1857 * They have to skip over the name. They return the null string
1858 * for unset variables.
1859 */
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02001860#define ifsval() (vifs.var_text + 4)
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001861#define ifsset() ((vifs.flags & VUNSET) == 0)
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001862#if ENABLE_ASH_MAIL
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02001863# define mailval() (vmail.var_text + 5)
1864# define mpathval() (vmpath.var_text + 9)
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001865# define mpathset() ((vmpath.flags & VUNSET) == 0)
1866#endif
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02001867#define pathval() (vpath.var_text + 5)
1868#define ps1val() (vps1.var_text + 4)
1869#define ps2val() (vps2.var_text + 4)
1870#define ps4val() (vps4.var_text + 4)
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001871#if ENABLE_ASH_GETOPTS
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02001872# define optindval() (voptind.var_text + 7)
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001873#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001874
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001875
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001876#define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
1877#define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
1878
Denis Vlasenko01631112007-12-16 17:20:38 +00001879#if ENABLE_ASH_GETOPTS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001880static void FAST_FUNC
Denis Vlasenko01631112007-12-16 17:20:38 +00001881getoptsreset(const char *value)
1882{
1883 shellparam.optind = number(value);
1884 shellparam.optoff = -1;
1885}
1886#endif
1887
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001888/*
1889 * Return of a legal variable name (a letter or underscore followed by zero or
1890 * more letters, underscores, and digits).
1891 */
Denys Vlasenko03dad222010-01-12 23:29:57 +01001892static char* FAST_FUNC
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001893endofname(const char *name)
1894{
1895 char *p;
1896
1897 p = (char *) name;
1898 if (!is_name(*p))
1899 return p;
1900 while (*++p) {
1901 if (!is_in_name(*p))
1902 break;
1903 }
1904 return p;
1905}
1906
1907/*
1908 * Compares two strings up to the first = or '\0'. The first
1909 * string must be terminated by '='; the second may be terminated by
1910 * either '=' or '\0'.
1911 */
1912static int
1913varcmp(const char *p, const char *q)
1914{
1915 int c, d;
1916
1917 while ((c = *p) == (d = *q)) {
1918 if (!c || c == '=')
1919 goto out;
1920 p++;
1921 q++;
1922 }
1923 if (c == '=')
Denis Vlasenko9650f362007-02-23 01:04:37 +00001924 c = '\0';
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001925 if (d == '=')
Denis Vlasenko9650f362007-02-23 01:04:37 +00001926 d = '\0';
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001927 out:
1928 return c - d;
1929}
1930
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001931/*
1932 * Find the appropriate entry in the hash table from the name.
1933 */
1934static struct var **
1935hashvar(const char *p)
1936{
1937 unsigned hashval;
1938
1939 hashval = ((unsigned char) *p) << 4;
1940 while (*p && *p != '=')
1941 hashval += (unsigned char) *p++;
1942 return &vartab[hashval % VTABSIZE];
1943}
1944
1945static int
1946vpcmp(const void *a, const void *b)
1947{
1948 return varcmp(*(const char **)a, *(const char **)b);
1949}
1950
1951/*
1952 * This routine initializes the builtin variables.
1953 */
1954static void
1955initvar(void)
1956{
1957 struct var *vp;
1958 struct var *end;
1959 struct var **vpp;
1960
1961 /*
1962 * PS1 depends on uid
1963 */
1964#if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02001965 vps1.var_text = "PS1=\\w \\$ ";
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001966#else
1967 if (!geteuid())
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02001968 vps1.var_text = "PS1=# ";
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001969#endif
1970 vp = varinit;
Denis Vlasenko80b8b392007-06-25 10:55:35 +00001971 end = vp + ARRAY_SIZE(varinit);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001972 do {
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02001973 vpp = hashvar(vp->var_text);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001974 vp->next = *vpp;
1975 *vpp = vp;
1976 } while (++vp < end);
1977}
1978
1979static struct var **
1980findvar(struct var **vpp, const char *name)
1981{
1982 for (; *vpp; vpp = &(*vpp)->next) {
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02001983 if (varcmp((*vpp)->var_text, name) == 0) {
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001984 break;
1985 }
1986 }
1987 return vpp;
1988}
1989
1990/*
1991 * Find the value of a variable. Returns NULL if not set.
1992 */
Denys Vlasenko03dad222010-01-12 23:29:57 +01001993static const char* FAST_FUNC
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001994lookupvar(const char *name)
1995{
1996 struct var *v;
1997
1998 v = *findvar(hashvar(name), name);
1999 if (v) {
Denis Vlasenko448d30e2008-06-27 00:24:11 +00002000#if ENABLE_ASH_RANDOM_SUPPORT
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002001 /*
2002 * Dynamic variables are implemented roughly the same way they are
2003 * in bash. Namely, they're "special" so long as they aren't unset.
2004 * As soon as they're unset, they're no longer dynamic, and dynamic
2005 * lookup will no longer happen at that point. -- PFM.
2006 */
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02002007 if (v->flags & VDYNAMIC)
2008 v->var_func(NULL);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002009#endif
2010 if (!(v->flags & VUNSET))
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02002011 return var_end(v->var_text);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002012 }
2013 return NULL;
2014}
2015
2016/*
2017 * Search the environment of a builtin command.
2018 */
Mike Frysinger98c52642009-04-02 10:02:37 +00002019static const char *
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002020bltinlookup(const char *name)
2021{
2022 struct strlist *sp;
2023
2024 for (sp = cmdenviron; sp; sp = sp->next) {
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02002025 if (varcmp(sp->text, name) == 0)
2026 return var_end(sp->text);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002027 }
2028 return lookupvar(name);
2029}
2030
2031/*
2032 * Same as setvar except that the variable and value are passed in
2033 * the first argument as name=value. Since the first argument will
2034 * be actually stored in the table, it should not be a string that
2035 * will go away.
2036 * Called with interrupts off.
2037 */
2038static void
2039setvareq(char *s, int flags)
2040{
2041 struct var *vp, **vpp;
2042
2043 vpp = hashvar(s);
2044 flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
2045 vp = *findvar(vpp, s);
2046 if (vp) {
2047 if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
2048 const char *n;
2049
2050 if (flags & VNOSAVE)
2051 free(s);
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02002052 n = vp->var_text;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002053 ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
2054 }
2055
2056 if (flags & VNOSET)
2057 return;
2058
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02002059 if (vp->var_func && !(flags & VNOFUNC))
2060 vp->var_func(var_end(s));
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002061
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02002062 if (!(vp->flags & (VTEXTFIXED|VSTACK)))
2063 free((char*)vp->var_text);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002064
2065 flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
2066 } else {
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02002067 /* variable s is not found */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002068 if (flags & VNOSET)
2069 return;
Denis Vlasenko597906c2008-02-20 16:38:54 +00002070 vp = ckzalloc(sizeof(*vp));
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002071 vp->next = *vpp;
Denis Vlasenko597906c2008-02-20 16:38:54 +00002072 /*vp->func = NULL; - ckzalloc did it */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002073 *vpp = vp;
2074 }
2075 if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
2076 s = ckstrdup(s);
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02002077 vp->var_text = s;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002078 vp->flags = flags;
2079}
2080
2081/*
2082 * Set the value of a variable. The flags argument is ored with the
2083 * flags of the variable. If val is NULL, the variable is unset.
2084 */
2085static void
2086setvar(const char *name, const char *val, int flags)
2087{
2088 char *p, *q;
2089 size_t namelen;
2090 char *nameeq;
2091 size_t vallen;
2092
2093 q = endofname(name);
2094 p = strchrnul(q, '=');
2095 namelen = p - name;
2096 if (!namelen || p != q)
2097 ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
2098 vallen = 0;
2099 if (val == NULL) {
2100 flags |= VUNSET;
2101 } else {
2102 vallen = strlen(val);
2103 }
2104 INT_OFF;
2105 nameeq = ckmalloc(namelen + vallen + 2);
Denis Vlasenko29eb3592008-05-18 14:06:08 +00002106 p = (char *)memcpy(nameeq, name, namelen) + namelen;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002107 if (val) {
2108 *p++ = '=';
Denis Vlasenko29eb3592008-05-18 14:06:08 +00002109 p = (char *)memcpy(p, val, vallen) + vallen;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002110 }
2111 *p = '\0';
2112 setvareq(nameeq, flags | VNOSAVE);
2113 INT_ON;
2114}
2115
Denys Vlasenko03dad222010-01-12 23:29:57 +01002116static void FAST_FUNC
2117setvar2(const char *name, const char *val)
2118{
2119 setvar(name, val, 0);
2120}
2121
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002122#if ENABLE_ASH_GETOPTS
2123/*
2124 * Safe version of setvar, returns 1 on success 0 on failure.
2125 */
2126static int
2127setvarsafe(const char *name, const char *val, int flags)
2128{
2129 int err;
2130 volatile int saveint;
2131 struct jmploc *volatile savehandler = exception_handler;
2132 struct jmploc jmploc;
2133
2134 SAVE_INT(saveint);
2135 if (setjmp(jmploc.loc))
2136 err = 1;
2137 else {
2138 exception_handler = &jmploc;
2139 setvar(name, val, flags);
2140 err = 0;
2141 }
2142 exception_handler = savehandler;
2143 RESTORE_INT(saveint);
2144 return err;
2145}
2146#endif
2147
2148/*
2149 * Unset the specified variable.
2150 */
2151static int
2152unsetvar(const char *s)
2153{
2154 struct var **vpp;
2155 struct var *vp;
2156 int retval;
2157
2158 vpp = findvar(hashvar(s), s);
2159 vp = *vpp;
2160 retval = 2;
2161 if (vp) {
2162 int flags = vp->flags;
2163
2164 retval = 1;
2165 if (flags & VREADONLY)
2166 goto out;
Denis Vlasenko448d30e2008-06-27 00:24:11 +00002167#if ENABLE_ASH_RANDOM_SUPPORT
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002168 vp->flags &= ~VDYNAMIC;
2169#endif
2170 if (flags & VUNSET)
2171 goto ok;
2172 if ((flags & VSTRFIXED) == 0) {
2173 INT_OFF;
2174 if ((flags & (VTEXTFIXED|VSTACK)) == 0)
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02002175 free((char*)vp->var_text);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002176 *vpp = vp->next;
2177 free(vp);
2178 INT_ON;
2179 } else {
2180 setvar(s, 0, 0);
2181 vp->flags &= ~VEXPORT;
2182 }
2183 ok:
2184 retval = 0;
2185 }
2186 out:
2187 return retval;
2188}
2189
2190/*
2191 * Process a linked list of variable assignments.
2192 */
2193static void
2194listsetvar(struct strlist *list_set_var, int flags)
2195{
2196 struct strlist *lp = list_set_var;
2197
2198 if (!lp)
2199 return;
2200 INT_OFF;
2201 do {
2202 setvareq(lp->text, flags);
Denis Vlasenko9650f362007-02-23 01:04:37 +00002203 lp = lp->next;
2204 } while (lp);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002205 INT_ON;
2206}
2207
2208/*
2209 * Generate a list of variables satisfying the given conditions.
2210 */
2211static char **
2212listvars(int on, int off, char ***end)
2213{
2214 struct var **vpp;
2215 struct var *vp;
2216 char **ep;
2217 int mask;
2218
2219 STARTSTACKSTR(ep);
2220 vpp = vartab;
2221 mask = on | off;
2222 do {
2223 for (vp = *vpp; vp; vp = vp->next) {
2224 if ((vp->flags & mask) == on) {
2225 if (ep == stackstrend())
2226 ep = growstackstr();
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02002227 *ep++ = (char*)vp->var_text;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002228 }
2229 }
2230 } while (++vpp < vartab + VTABSIZE);
2231 if (ep == stackstrend())
2232 ep = growstackstr();
2233 if (end)
2234 *end = ep;
2235 *ep++ = NULL;
2236 return grabstackstr(ep);
2237}
2238
2239
2240/* ============ Path search helper
2241 *
2242 * The variable path (passed by reference) should be set to the start
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02002243 * of the path before the first call; path_advance will update
2244 * this value as it proceeds. Successive calls to path_advance will return
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002245 * the possible path expansions in sequence. If an option (indicated by
2246 * a percent sign) appears in the path entry then the global variable
2247 * pathopt will be set to point to it; otherwise pathopt will be set to
2248 * NULL.
2249 */
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02002250static const char *pathopt; /* set by path_advance */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002251
2252static char *
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02002253path_advance(const char **path, const char *name)
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002254{
2255 const char *p;
2256 char *q;
2257 const char *start;
2258 size_t len;
2259
2260 if (*path == NULL)
2261 return NULL;
2262 start = *path;
Denis Vlasenkof7d56652008-03-25 05:51:41 +00002263 for (p = start; *p && *p != ':' && *p != '%'; p++)
2264 continue;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002265 len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
2266 while (stackblocksize() < len)
2267 growstackblock();
2268 q = stackblock();
2269 if (p != start) {
2270 memcpy(q, start, p - start);
2271 q += p - start;
2272 *q++ = '/';
2273 }
2274 strcpy(q, name);
2275 pathopt = NULL;
2276 if (*p == '%') {
2277 pathopt = ++p;
Denis Vlasenkof7d56652008-03-25 05:51:41 +00002278 while (*p && *p != ':')
2279 p++;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002280 }
2281 if (*p == ':')
2282 *path = p + 1;
2283 else
2284 *path = NULL;
2285 return stalloc(len);
2286}
2287
2288
2289/* ============ Prompt */
2290
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +00002291static smallint doprompt; /* if set, prompt the user */
2292static smallint needprompt; /* true if interactive and at start of line */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002293
2294#if ENABLE_FEATURE_EDITING
2295static line_input_t *line_input_state;
2296static const char *cmdedit_prompt;
2297static void
2298putprompt(const char *s)
2299{
2300 if (ENABLE_ASH_EXPAND_PRMT) {
2301 free((char*)cmdedit_prompt);
Denis Vlasenko4222ae42007-02-25 02:37:49 +00002302 cmdedit_prompt = ckstrdup(s);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002303 return;
2304 }
2305 cmdedit_prompt = s;
2306}
2307#else
2308static void
2309putprompt(const char *s)
2310{
2311 out2str(s);
2312}
2313#endif
2314
2315#if ENABLE_ASH_EXPAND_PRMT
2316/* expandstr() needs parsing machinery, so it is far away ahead... */
2317static const char *expandstr(const char *ps);
2318#else
2319#define expandstr(s) s
2320#endif
2321
2322static void
2323setprompt(int whichprompt)
2324{
2325 const char *prompt;
2326#if ENABLE_ASH_EXPAND_PRMT
2327 struct stackmark smark;
2328#endif
2329
2330 needprompt = 0;
2331
2332 switch (whichprompt) {
2333 case 1:
2334 prompt = ps1val();
2335 break;
2336 case 2:
2337 prompt = ps2val();
2338 break;
2339 default: /* 0 */
2340 prompt = nullstr;
2341 }
2342#if ENABLE_ASH_EXPAND_PRMT
2343 setstackmark(&smark);
2344 stalloc(stackblocksize());
2345#endif
2346 putprompt(expandstr(prompt));
2347#if ENABLE_ASH_EXPAND_PRMT
2348 popstackmark(&smark);
2349#endif
2350}
2351
2352
2353/* ============ The cd and pwd commands */
2354
2355#define CD_PHYSICAL 1
2356#define CD_PRINT 2
2357
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002358static int
2359cdopt(void)
2360{
2361 int flags = 0;
2362 int i, j;
2363
2364 j = 'L';
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02002365 while ((i = nextopt("LP")) != '\0') {
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002366 if (i != j) {
2367 flags ^= CD_PHYSICAL;
2368 j = i;
2369 }
2370 }
2371
2372 return flags;
2373}
2374
2375/*
2376 * Update curdir (the name of the current directory) in response to a
2377 * cd command.
2378 */
2379static const char *
2380updatepwd(const char *dir)
2381{
2382 char *new;
2383 char *p;
2384 char *cdcomppath;
2385 const char *lim;
2386
2387 cdcomppath = ststrdup(dir);
2388 STARTSTACKSTR(new);
2389 if (*dir != '/') {
2390 if (curdir == nullstr)
2391 return 0;
2392 new = stack_putstr(curdir, new);
2393 }
2394 new = makestrspace(strlen(dir) + 2, new);
Denis Vlasenko29eb3592008-05-18 14:06:08 +00002395 lim = (char *)stackblock() + 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002396 if (*dir != '/') {
2397 if (new[-1] != '/')
2398 USTPUTC('/', new);
2399 if (new > lim && *lim == '/')
2400 lim++;
2401 } else {
2402 USTPUTC('/', new);
2403 cdcomppath++;
2404 if (dir[1] == '/' && dir[2] != '/') {
2405 USTPUTC('/', new);
2406 cdcomppath++;
2407 lim++;
2408 }
2409 }
2410 p = strtok(cdcomppath, "/");
2411 while (p) {
2412 switch (*p) {
2413 case '.':
2414 if (p[1] == '.' && p[2] == '\0') {
2415 while (new > lim) {
2416 STUNPUTC(new);
2417 if (new[-1] == '/')
2418 break;
2419 }
2420 break;
Denis Vlasenko16abcd92007-04-13 23:59:52 +00002421 }
2422 if (p[1] == '\0')
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002423 break;
2424 /* fall through */
2425 default:
2426 new = stack_putstr(p, new);
2427 USTPUTC('/', new);
2428 }
2429 p = strtok(0, "/");
2430 }
2431 if (new > lim)
2432 STUNPUTC(new);
2433 *new = 0;
2434 return stackblock();
2435}
2436
2437/*
2438 * Find out what the current directory is. If we already know the current
2439 * directory, this routine returns immediately.
2440 */
2441static char *
2442getpwd(void)
2443{
Denis Vlasenko01631112007-12-16 17:20:38 +00002444 char *dir = getcwd(NULL, 0); /* huh, using glibc extension? */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002445 return dir ? dir : nullstr;
2446}
2447
2448static void
2449setpwd(const char *val, int setold)
2450{
2451 char *oldcur, *dir;
2452
2453 oldcur = dir = curdir;
2454
2455 if (setold) {
2456 setvar("OLDPWD", oldcur, VEXPORT);
2457 }
2458 INT_OFF;
2459 if (physdir != nullstr) {
2460 if (physdir != oldcur)
2461 free(physdir);
2462 physdir = nullstr;
2463 }
2464 if (oldcur == val || !val) {
2465 char *s = getpwd();
2466 physdir = s;
2467 if (!val)
2468 dir = s;
2469 } else
2470 dir = ckstrdup(val);
2471 if (oldcur != dir && oldcur != nullstr) {
2472 free(oldcur);
2473 }
2474 curdir = dir;
2475 INT_ON;
2476 setvar("PWD", dir, VEXPORT);
2477}
2478
2479static void hashcd(void);
2480
2481/*
2482 * Actually do the chdir. We also call hashcd to let the routines in exec.c
2483 * know that the current directory has changed.
2484 */
2485static int
2486docd(const char *dest, int flags)
2487{
Denys Vlasenko4b1100e2010-03-05 14:10:54 +01002488 const char *dir = NULL;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002489 int err;
2490
2491 TRACE(("docd(\"%s\", %d) called\n", dest, flags));
2492
2493 INT_OFF;
2494 if (!(flags & CD_PHYSICAL)) {
2495 dir = updatepwd(dest);
2496 if (dir)
2497 dest = dir;
2498 }
2499 err = chdir(dest);
2500 if (err)
2501 goto out;
2502 setpwd(dir, 1);
2503 hashcd();
2504 out:
2505 INT_ON;
2506 return err;
2507}
2508
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02002509static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00002510cdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002511{
2512 const char *dest;
2513 const char *path;
2514 const char *p;
2515 char c;
2516 struct stat statb;
2517 int flags;
2518
2519 flags = cdopt();
2520 dest = *argptr;
2521 if (!dest)
Denys Vlasenkoea8b2522010-06-02 12:57:26 +02002522 dest = bltinlookup("HOME");
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002523 else if (LONE_DASH(dest)) {
2524 dest = bltinlookup("OLDPWD");
2525 flags |= CD_PRINT;
2526 }
2527 if (!dest)
2528 dest = nullstr;
2529 if (*dest == '/')
2530 goto step7;
2531 if (*dest == '.') {
2532 c = dest[1];
2533 dotdot:
2534 switch (c) {
2535 case '\0':
2536 case '/':
2537 goto step6;
2538 case '.':
2539 c = dest[2];
2540 if (c != '.')
2541 goto dotdot;
2542 }
2543 }
2544 if (!*dest)
2545 dest = ".";
2546 path = bltinlookup("CDPATH");
2547 if (!path) {
2548 step6:
2549 step7:
2550 p = dest;
2551 goto docd;
2552 }
2553 do {
2554 c = *path;
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02002555 p = path_advance(&path, dest);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002556 if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
2557 if (c && c != ':')
2558 flags |= CD_PRINT;
2559 docd:
2560 if (!docd(p, flags))
2561 goto out;
2562 break;
2563 }
2564 } while (path);
2565 ash_msg_and_raise_error("can't cd to %s", dest);
2566 /* NOTREACHED */
2567 out:
2568 if (flags & CD_PRINT)
Denys Vlasenkoea8b2522010-06-02 12:57:26 +02002569 out1fmt("%s\n", curdir);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002570 return 0;
2571}
2572
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02002573static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00002574pwdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002575{
2576 int flags;
2577 const char *dir = curdir;
2578
2579 flags = cdopt();
2580 if (flags) {
2581 if (physdir == nullstr)
2582 setpwd(dir, 0);
2583 dir = physdir;
2584 }
Denys Vlasenkoea8b2522010-06-02 12:57:26 +02002585 out1fmt("%s\n", dir);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002586 return 0;
2587}
2588
Denis Vlasenko0c032a42007-02-23 01:03:40 +00002589
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00002590/* ============ ... */
Eric Andersenc470f442003-07-28 09:56:35 +00002591
Denis Vlasenko834dee72008-10-07 09:18:30 +00002592
Denys Vlasenko82dd14a2010-05-17 10:10:01 +02002593#define IBUFSIZ (ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 1024)
Eric Andersenc470f442003-07-28 09:56:35 +00002594
Eric Andersenc470f442003-07-28 09:56:35 +00002595/* Syntax classes */
Denis Vlasenko834dee72008-10-07 09:18:30 +00002596#define CWORD 0 /* character is nothing special */
2597#define CNL 1 /* newline character */
2598#define CBACK 2 /* a backslash character */
2599#define CSQUOTE 3 /* single quote */
2600#define CDQUOTE 4 /* double quote */
Eric Andersenc470f442003-07-28 09:56:35 +00002601#define CENDQUOTE 5 /* a terminating quote */
Denis Vlasenko834dee72008-10-07 09:18:30 +00002602#define CBQUOTE 6 /* backwards single quote */
2603#define CVAR 7 /* a dollar sign */
2604#define CENDVAR 8 /* a '}' character */
2605#define CLP 9 /* a left paren in arithmetic */
2606#define CRP 10 /* a right paren in arithmetic */
Eric Andersenc470f442003-07-28 09:56:35 +00002607#define CENDFILE 11 /* end of file */
Denis Vlasenko834dee72008-10-07 09:18:30 +00002608#define CCTL 12 /* like CWORD, except it must be escaped */
2609#define CSPCL 13 /* these terminate a word */
2610#define CIGN 14 /* character should be ignored */
Eric Andersenc470f442003-07-28 09:56:35 +00002611
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002612#define PEOF 256
Denis Vlasenko131ae172007-02-18 13:00:19 +00002613#if ENABLE_ASH_ALIAS
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002614# define PEOA 257
Eric Andersenc470f442003-07-28 09:56:35 +00002615#endif
2616
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002617#define USE_SIT_FUNCTION ENABLE_ASH_OPTIMIZE_FOR_SIZE
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002618
Mike Frysinger98c52642009-04-02 10:02:37 +00002619#if ENABLE_SH_MATH_SUPPORT
Denys Vlasenko76bc2d62009-11-29 01:37:46 +01002620# define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8) | (d << 12))
Eric Andersenc470f442003-07-28 09:56:35 +00002621#else
Denys Vlasenko76bc2d62009-11-29 01:37:46 +01002622# define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8))
Denys Vlasenko76bc2d62009-11-29 01:37:46 +01002623#endif
Denys Vlasenko068d3862009-11-29 01:41:11 +01002624static const uint16_t S_I_T[] = {
Denys Vlasenko76bc2d62009-11-29 01:37:46 +01002625#if ENABLE_ASH_ALIAS
2626 SIT_ITEM(CSPCL , CIGN , CIGN , CIGN ), /* 0, PEOA */
2627#endif
2628 SIT_ITEM(CSPCL , CWORD , CWORD, CWORD ), /* 1, ' ' */
2629 SIT_ITEM(CNL , CNL , CNL , CNL ), /* 2, \n */
2630 SIT_ITEM(CWORD , CCTL , CCTL , CWORD ), /* 3, !*-/:=?[]~ */
2631 SIT_ITEM(CDQUOTE , CENDQUOTE, CWORD, CWORD ), /* 4, '"' */
2632 SIT_ITEM(CVAR , CVAR , CWORD, CVAR ), /* 5, $ */
2633 SIT_ITEM(CSQUOTE , CWORD , CENDQUOTE, CWORD), /* 6, "'" */
2634 SIT_ITEM(CSPCL , CWORD , CWORD, CLP ), /* 7, ( */
2635 SIT_ITEM(CSPCL , CWORD , CWORD, CRP ), /* 8, ) */
2636 SIT_ITEM(CBACK , CBACK , CCTL , CBACK ), /* 9, \ */
2637 SIT_ITEM(CBQUOTE , CBQUOTE , CWORD, CBQUOTE), /* 10, ` */
2638 SIT_ITEM(CENDVAR , CENDVAR , CWORD, CENDVAR), /* 11, } */
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002639#if !USE_SIT_FUNCTION
Denys Vlasenko76bc2d62009-11-29 01:37:46 +01002640 SIT_ITEM(CENDFILE, CENDFILE , CENDFILE, CENDFILE),/* 12, PEOF */
2641 SIT_ITEM(CWORD , CWORD , CWORD, CWORD ), /* 13, 0-9A-Za-z */
2642 SIT_ITEM(CCTL , CCTL , CCTL , CCTL ) /* 14, CTLESC ... */
2643#endif
2644#undef SIT_ITEM
Eric Andersenc470f442003-07-28 09:56:35 +00002645};
Denys Vlasenko76bc2d62009-11-29 01:37:46 +01002646/* Constants below must match table above */
2647enum {
2648#if ENABLE_ASH_ALIAS
2649 CSPCL_CIGN_CIGN_CIGN , /* 0 */
2650#endif
2651 CSPCL_CWORD_CWORD_CWORD , /* 1 */
2652 CNL_CNL_CNL_CNL , /* 2 */
2653 CWORD_CCTL_CCTL_CWORD , /* 3 */
2654 CDQUOTE_CENDQUOTE_CWORD_CWORD , /* 4 */
2655 CVAR_CVAR_CWORD_CVAR , /* 5 */
2656 CSQUOTE_CWORD_CENDQUOTE_CWORD , /* 6 */
2657 CSPCL_CWORD_CWORD_CLP , /* 7 */
2658 CSPCL_CWORD_CWORD_CRP , /* 8 */
2659 CBACK_CBACK_CCTL_CBACK , /* 9 */
2660 CBQUOTE_CBQUOTE_CWORD_CBQUOTE , /* 10 */
2661 CENDVAR_CENDVAR_CWORD_CENDVAR , /* 11 */
2662 CENDFILE_CENDFILE_CENDFILE_CENDFILE, /* 12 */
2663 CWORD_CWORD_CWORD_CWORD , /* 13 */
2664 CCTL_CCTL_CCTL_CCTL , /* 14 */
2665};
Eric Andersen2870d962001-07-02 17:27:21 +00002666
Denys Vlasenkocd716832009-11-28 22:14:02 +01002667/* c in SIT(c, syntax) must be an *unsigned char* or PEOA or PEOF,
2668 * caller must ensure proper cast on it if c is *char_ptr!
2669 */
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002670/* Values for syntax param */
2671#define BASESYNTAX 0 /* not in quotes */
2672#define DQSYNTAX 1 /* in double quotes */
2673#define SQSYNTAX 2 /* in single quotes */
2674#define ARISYNTAX 3 /* in arithmetic */
2675#define PSSYNTAX 4 /* prompt. never passed to SIT() */
Denys Vlasenkocd716832009-11-28 22:14:02 +01002676
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002677#if USE_SIT_FUNCTION
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002678
Denis Vlasenko0c032a42007-02-23 01:03:40 +00002679static int
2680SIT(int c, int syntax)
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002681{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00002682 static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-/:;<=>?[\\]`|}~";
Denys Vlasenkocd716832009-11-28 22:14:02 +01002683# if ENABLE_ASH_ALIAS
2684 static const uint8_t syntax_index_table[] ALIGN1 = {
Eric Andersenc470f442003-07-28 09:56:35 +00002685 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
2686 7, 8, 3, 3, 3, 3, 1, 1, /* "()*-/:;<" */
2687 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
2688 11, 3 /* "}~" */
2689 };
Denys Vlasenkocd716832009-11-28 22:14:02 +01002690# else
2691 static const uint8_t syntax_index_table[] ALIGN1 = {
Eric Andersenc470f442003-07-28 09:56:35 +00002692 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
2693 6, 7, 2, 2, 2, 2, 0, 0, /* "()*-/:;<" */
2694 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
2695 10, 2 /* "}~" */
2696 };
Denys Vlasenkocd716832009-11-28 22:14:02 +01002697# endif
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002698 const char *s;
2699 int indx;
2700
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002701 if (c == PEOF)
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002702 return CENDFILE;
Denys Vlasenkocd716832009-11-28 22:14:02 +01002703# if ENABLE_ASH_ALIAS
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002704 if (c == PEOA)
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +00002705 indx = 0;
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002706 else
Denys Vlasenkocd716832009-11-28 22:14:02 +01002707# endif
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +00002708 {
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002709 /* Cast is purely for paranoia here,
2710 * just in case someone passed signed char to us */
2711 if ((unsigned char)c >= CTL_FIRST
2712 && (unsigned char)c <= CTL_LAST
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +00002713 ) {
2714 return CCTL;
2715 }
2716 s = strchrnul(spec_symbls, c);
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002717 if (*s == '\0')
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +00002718 return CWORD;
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +00002719 indx = syntax_index_table[s - spec_symbls];
2720 }
Denys Vlasenko76bc2d62009-11-29 01:37:46 +01002721 return (S_I_T[indx] >> (syntax*4)) & 0xf;
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002722}
2723
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00002724#else /* !USE_SIT_FUNCTION */
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002725
Denys Vlasenko76bc2d62009-11-29 01:37:46 +01002726static const uint8_t syntax_index_table[] = {
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00002727 /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
Denys Vlasenkocd716832009-11-28 22:14:02 +01002728 /* 0 */ CWORD_CWORD_CWORD_CWORD,
2729 /* 1 */ CWORD_CWORD_CWORD_CWORD,
2730 /* 2 */ CWORD_CWORD_CWORD_CWORD,
2731 /* 3 */ CWORD_CWORD_CWORD_CWORD,
2732 /* 4 */ CWORD_CWORD_CWORD_CWORD,
2733 /* 5 */ CWORD_CWORD_CWORD_CWORD,
2734 /* 6 */ CWORD_CWORD_CWORD_CWORD,
2735 /* 7 */ CWORD_CWORD_CWORD_CWORD,
2736 /* 8 */ CWORD_CWORD_CWORD_CWORD,
2737 /* 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
2738 /* 10 "\n" */ CNL_CNL_CNL_CNL,
2739 /* 11 */ CWORD_CWORD_CWORD_CWORD,
2740 /* 12 */ CWORD_CWORD_CWORD_CWORD,
2741 /* 13 */ CWORD_CWORD_CWORD_CWORD,
2742 /* 14 */ CWORD_CWORD_CWORD_CWORD,
2743 /* 15 */ CWORD_CWORD_CWORD_CWORD,
2744 /* 16 */ CWORD_CWORD_CWORD_CWORD,
2745 /* 17 */ CWORD_CWORD_CWORD_CWORD,
2746 /* 18 */ CWORD_CWORD_CWORD_CWORD,
2747 /* 19 */ CWORD_CWORD_CWORD_CWORD,
2748 /* 20 */ CWORD_CWORD_CWORD_CWORD,
2749 /* 21 */ CWORD_CWORD_CWORD_CWORD,
2750 /* 22 */ CWORD_CWORD_CWORD_CWORD,
2751 /* 23 */ CWORD_CWORD_CWORD_CWORD,
2752 /* 24 */ CWORD_CWORD_CWORD_CWORD,
2753 /* 25 */ CWORD_CWORD_CWORD_CWORD,
2754 /* 26 */ CWORD_CWORD_CWORD_CWORD,
2755 /* 27 */ CWORD_CWORD_CWORD_CWORD,
2756 /* 28 */ CWORD_CWORD_CWORD_CWORD,
2757 /* 29 */ CWORD_CWORD_CWORD_CWORD,
2758 /* 30 */ CWORD_CWORD_CWORD_CWORD,
2759 /* 31 */ CWORD_CWORD_CWORD_CWORD,
2760 /* 32 " " */ CSPCL_CWORD_CWORD_CWORD,
2761 /* 33 "!" */ CWORD_CCTL_CCTL_CWORD,
2762 /* 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
2763 /* 35 "#" */ CWORD_CWORD_CWORD_CWORD,
2764 /* 36 "$" */ CVAR_CVAR_CWORD_CVAR,
2765 /* 37 "%" */ CWORD_CWORD_CWORD_CWORD,
2766 /* 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
2767 /* 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
2768 /* 40 "(" */ CSPCL_CWORD_CWORD_CLP,
2769 /* 41 ")" */ CSPCL_CWORD_CWORD_CRP,
2770 /* 42 "*" */ CWORD_CCTL_CCTL_CWORD,
2771 /* 43 "+" */ CWORD_CWORD_CWORD_CWORD,
2772 /* 44 "," */ CWORD_CWORD_CWORD_CWORD,
2773 /* 45 "-" */ CWORD_CCTL_CCTL_CWORD,
2774 /* 46 "." */ CWORD_CWORD_CWORD_CWORD,
2775 /* 47 "/" */ CWORD_CCTL_CCTL_CWORD,
2776 /* 48 "0" */ CWORD_CWORD_CWORD_CWORD,
2777 /* 49 "1" */ CWORD_CWORD_CWORD_CWORD,
2778 /* 50 "2" */ CWORD_CWORD_CWORD_CWORD,
2779 /* 51 "3" */ CWORD_CWORD_CWORD_CWORD,
2780 /* 52 "4" */ CWORD_CWORD_CWORD_CWORD,
2781 /* 53 "5" */ CWORD_CWORD_CWORD_CWORD,
2782 /* 54 "6" */ CWORD_CWORD_CWORD_CWORD,
2783 /* 55 "7" */ CWORD_CWORD_CWORD_CWORD,
2784 /* 56 "8" */ CWORD_CWORD_CWORD_CWORD,
2785 /* 57 "9" */ CWORD_CWORD_CWORD_CWORD,
2786 /* 58 ":" */ CWORD_CCTL_CCTL_CWORD,
2787 /* 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
2788 /* 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
2789 /* 61 "=" */ CWORD_CCTL_CCTL_CWORD,
2790 /* 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
2791 /* 63 "?" */ CWORD_CCTL_CCTL_CWORD,
2792 /* 64 "@" */ CWORD_CWORD_CWORD_CWORD,
2793 /* 65 "A" */ CWORD_CWORD_CWORD_CWORD,
2794 /* 66 "B" */ CWORD_CWORD_CWORD_CWORD,
2795 /* 67 "C" */ CWORD_CWORD_CWORD_CWORD,
2796 /* 68 "D" */ CWORD_CWORD_CWORD_CWORD,
2797 /* 69 "E" */ CWORD_CWORD_CWORD_CWORD,
2798 /* 70 "F" */ CWORD_CWORD_CWORD_CWORD,
2799 /* 71 "G" */ CWORD_CWORD_CWORD_CWORD,
2800 /* 72 "H" */ CWORD_CWORD_CWORD_CWORD,
2801 /* 73 "I" */ CWORD_CWORD_CWORD_CWORD,
2802 /* 74 "J" */ CWORD_CWORD_CWORD_CWORD,
2803 /* 75 "K" */ CWORD_CWORD_CWORD_CWORD,
2804 /* 76 "L" */ CWORD_CWORD_CWORD_CWORD,
2805 /* 77 "M" */ CWORD_CWORD_CWORD_CWORD,
2806 /* 78 "N" */ CWORD_CWORD_CWORD_CWORD,
2807 /* 79 "O" */ CWORD_CWORD_CWORD_CWORD,
2808 /* 80 "P" */ CWORD_CWORD_CWORD_CWORD,
2809 /* 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
2810 /* 82 "R" */ CWORD_CWORD_CWORD_CWORD,
2811 /* 83 "S" */ CWORD_CWORD_CWORD_CWORD,
2812 /* 84 "T" */ CWORD_CWORD_CWORD_CWORD,
2813 /* 85 "U" */ CWORD_CWORD_CWORD_CWORD,
2814 /* 86 "V" */ CWORD_CWORD_CWORD_CWORD,
2815 /* 87 "W" */ CWORD_CWORD_CWORD_CWORD,
2816 /* 88 "X" */ CWORD_CWORD_CWORD_CWORD,
2817 /* 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
2818 /* 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
2819 /* 91 "[" */ CWORD_CCTL_CCTL_CWORD,
2820 /* 92 "\" */ CBACK_CBACK_CCTL_CBACK,
2821 /* 93 "]" */ CWORD_CCTL_CCTL_CWORD,
2822 /* 94 "^" */ CWORD_CWORD_CWORD_CWORD,
2823 /* 95 "_" */ CWORD_CWORD_CWORD_CWORD,
2824 /* 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
2825 /* 97 "a" */ CWORD_CWORD_CWORD_CWORD,
2826 /* 98 "b" */ CWORD_CWORD_CWORD_CWORD,
2827 /* 99 "c" */ CWORD_CWORD_CWORD_CWORD,
2828 /* 100 "d" */ CWORD_CWORD_CWORD_CWORD,
2829 /* 101 "e" */ CWORD_CWORD_CWORD_CWORD,
2830 /* 102 "f" */ CWORD_CWORD_CWORD_CWORD,
2831 /* 103 "g" */ CWORD_CWORD_CWORD_CWORD,
2832 /* 104 "h" */ CWORD_CWORD_CWORD_CWORD,
2833 /* 105 "i" */ CWORD_CWORD_CWORD_CWORD,
2834 /* 106 "j" */ CWORD_CWORD_CWORD_CWORD,
2835 /* 107 "k" */ CWORD_CWORD_CWORD_CWORD,
2836 /* 108 "l" */ CWORD_CWORD_CWORD_CWORD,
2837 /* 109 "m" */ CWORD_CWORD_CWORD_CWORD,
2838 /* 110 "n" */ CWORD_CWORD_CWORD_CWORD,
2839 /* 111 "o" */ CWORD_CWORD_CWORD_CWORD,
2840 /* 112 "p" */ CWORD_CWORD_CWORD_CWORD,
2841 /* 113 "q" */ CWORD_CWORD_CWORD_CWORD,
2842 /* 114 "r" */ CWORD_CWORD_CWORD_CWORD,
2843 /* 115 "s" */ CWORD_CWORD_CWORD_CWORD,
2844 /* 116 "t" */ CWORD_CWORD_CWORD_CWORD,
2845 /* 117 "u" */ CWORD_CWORD_CWORD_CWORD,
2846 /* 118 "v" */ CWORD_CWORD_CWORD_CWORD,
2847 /* 119 "w" */ CWORD_CWORD_CWORD_CWORD,
2848 /* 120 "x" */ CWORD_CWORD_CWORD_CWORD,
2849 /* 121 "y" */ CWORD_CWORD_CWORD_CWORD,
2850 /* 122 "z" */ CWORD_CWORD_CWORD_CWORD,
2851 /* 123 "{" */ CWORD_CWORD_CWORD_CWORD,
2852 /* 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
2853 /* 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
2854 /* 126 "~" */ CWORD_CCTL_CCTL_CWORD,
2855 /* 127 del */ CWORD_CWORD_CWORD_CWORD,
2856 /* 128 0x80 */ CWORD_CWORD_CWORD_CWORD,
2857 /* 129 CTLESC */ CCTL_CCTL_CCTL_CCTL,
2858 /* 130 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
2859 /* 131 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
2860 /* 132 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
2861 /* 133 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
2862 /* 134 CTLARI */ CCTL_CCTL_CCTL_CCTL,
2863 /* 135 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
2864 /* 136 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
2865 /* 137 */ CWORD_CWORD_CWORD_CWORD,
2866 /* 138 */ CWORD_CWORD_CWORD_CWORD,
2867 /* 139 */ CWORD_CWORD_CWORD_CWORD,
2868 /* 140 */ CWORD_CWORD_CWORD_CWORD,
2869 /* 141 */ CWORD_CWORD_CWORD_CWORD,
2870 /* 142 */ CWORD_CWORD_CWORD_CWORD,
2871 /* 143 */ CWORD_CWORD_CWORD_CWORD,
2872 /* 144 */ CWORD_CWORD_CWORD_CWORD,
2873 /* 145 */ CWORD_CWORD_CWORD_CWORD,
2874 /* 146 */ CWORD_CWORD_CWORD_CWORD,
2875 /* 147 */ CWORD_CWORD_CWORD_CWORD,
2876 /* 148 */ CWORD_CWORD_CWORD_CWORD,
2877 /* 149 */ CWORD_CWORD_CWORD_CWORD,
2878 /* 150 */ CWORD_CWORD_CWORD_CWORD,
2879 /* 151 */ CWORD_CWORD_CWORD_CWORD,
2880 /* 152 */ CWORD_CWORD_CWORD_CWORD,
2881 /* 153 */ CWORD_CWORD_CWORD_CWORD,
2882 /* 154 */ CWORD_CWORD_CWORD_CWORD,
2883 /* 155 */ CWORD_CWORD_CWORD_CWORD,
2884 /* 156 */ CWORD_CWORD_CWORD_CWORD,
2885 /* 157 */ CWORD_CWORD_CWORD_CWORD,
2886 /* 158 */ CWORD_CWORD_CWORD_CWORD,
2887 /* 159 */ CWORD_CWORD_CWORD_CWORD,
2888 /* 160 */ CWORD_CWORD_CWORD_CWORD,
2889 /* 161 */ CWORD_CWORD_CWORD_CWORD,
2890 /* 162 */ CWORD_CWORD_CWORD_CWORD,
2891 /* 163 */ CWORD_CWORD_CWORD_CWORD,
2892 /* 164 */ CWORD_CWORD_CWORD_CWORD,
2893 /* 165 */ CWORD_CWORD_CWORD_CWORD,
2894 /* 166 */ CWORD_CWORD_CWORD_CWORD,
2895 /* 167 */ CWORD_CWORD_CWORD_CWORD,
2896 /* 168 */ CWORD_CWORD_CWORD_CWORD,
2897 /* 169 */ CWORD_CWORD_CWORD_CWORD,
2898 /* 170 */ CWORD_CWORD_CWORD_CWORD,
2899 /* 171 */ CWORD_CWORD_CWORD_CWORD,
2900 /* 172 */ CWORD_CWORD_CWORD_CWORD,
2901 /* 173 */ CWORD_CWORD_CWORD_CWORD,
2902 /* 174 */ CWORD_CWORD_CWORD_CWORD,
2903 /* 175 */ CWORD_CWORD_CWORD_CWORD,
2904 /* 176 */ CWORD_CWORD_CWORD_CWORD,
2905 /* 177 */ CWORD_CWORD_CWORD_CWORD,
2906 /* 178 */ CWORD_CWORD_CWORD_CWORD,
2907 /* 179 */ CWORD_CWORD_CWORD_CWORD,
2908 /* 180 */ CWORD_CWORD_CWORD_CWORD,
2909 /* 181 */ CWORD_CWORD_CWORD_CWORD,
2910 /* 182 */ CWORD_CWORD_CWORD_CWORD,
2911 /* 183 */ CWORD_CWORD_CWORD_CWORD,
2912 /* 184 */ CWORD_CWORD_CWORD_CWORD,
2913 /* 185 */ CWORD_CWORD_CWORD_CWORD,
2914 /* 186 */ CWORD_CWORD_CWORD_CWORD,
2915 /* 187 */ CWORD_CWORD_CWORD_CWORD,
2916 /* 188 */ CWORD_CWORD_CWORD_CWORD,
2917 /* 189 */ CWORD_CWORD_CWORD_CWORD,
2918 /* 190 */ CWORD_CWORD_CWORD_CWORD,
2919 /* 191 */ CWORD_CWORD_CWORD_CWORD,
2920 /* 192 */ CWORD_CWORD_CWORD_CWORD,
2921 /* 193 */ CWORD_CWORD_CWORD_CWORD,
2922 /* 194 */ CWORD_CWORD_CWORD_CWORD,
2923 /* 195 */ CWORD_CWORD_CWORD_CWORD,
2924 /* 196 */ CWORD_CWORD_CWORD_CWORD,
2925 /* 197 */ CWORD_CWORD_CWORD_CWORD,
2926 /* 198 */ CWORD_CWORD_CWORD_CWORD,
2927 /* 199 */ CWORD_CWORD_CWORD_CWORD,
2928 /* 200 */ CWORD_CWORD_CWORD_CWORD,
2929 /* 201 */ CWORD_CWORD_CWORD_CWORD,
2930 /* 202 */ CWORD_CWORD_CWORD_CWORD,
2931 /* 203 */ CWORD_CWORD_CWORD_CWORD,
2932 /* 204 */ CWORD_CWORD_CWORD_CWORD,
2933 /* 205 */ CWORD_CWORD_CWORD_CWORD,
2934 /* 206 */ CWORD_CWORD_CWORD_CWORD,
2935 /* 207 */ CWORD_CWORD_CWORD_CWORD,
2936 /* 208 */ CWORD_CWORD_CWORD_CWORD,
2937 /* 209 */ CWORD_CWORD_CWORD_CWORD,
2938 /* 210 */ CWORD_CWORD_CWORD_CWORD,
2939 /* 211 */ CWORD_CWORD_CWORD_CWORD,
2940 /* 212 */ CWORD_CWORD_CWORD_CWORD,
2941 /* 213 */ CWORD_CWORD_CWORD_CWORD,
2942 /* 214 */ CWORD_CWORD_CWORD_CWORD,
2943 /* 215 */ CWORD_CWORD_CWORD_CWORD,
2944 /* 216 */ CWORD_CWORD_CWORD_CWORD,
2945 /* 217 */ CWORD_CWORD_CWORD_CWORD,
2946 /* 218 */ CWORD_CWORD_CWORD_CWORD,
2947 /* 219 */ CWORD_CWORD_CWORD_CWORD,
2948 /* 220 */ CWORD_CWORD_CWORD_CWORD,
2949 /* 221 */ CWORD_CWORD_CWORD_CWORD,
2950 /* 222 */ CWORD_CWORD_CWORD_CWORD,
2951 /* 223 */ CWORD_CWORD_CWORD_CWORD,
2952 /* 224 */ CWORD_CWORD_CWORD_CWORD,
2953 /* 225 */ CWORD_CWORD_CWORD_CWORD,
2954 /* 226 */ CWORD_CWORD_CWORD_CWORD,
2955 /* 227 */ CWORD_CWORD_CWORD_CWORD,
2956 /* 228 */ CWORD_CWORD_CWORD_CWORD,
2957 /* 229 */ CWORD_CWORD_CWORD_CWORD,
2958 /* 230 */ CWORD_CWORD_CWORD_CWORD,
2959 /* 231 */ CWORD_CWORD_CWORD_CWORD,
2960 /* 232 */ CWORD_CWORD_CWORD_CWORD,
2961 /* 233 */ CWORD_CWORD_CWORD_CWORD,
2962 /* 234 */ CWORD_CWORD_CWORD_CWORD,
2963 /* 235 */ CWORD_CWORD_CWORD_CWORD,
2964 /* 236 */ CWORD_CWORD_CWORD_CWORD,
2965 /* 237 */ CWORD_CWORD_CWORD_CWORD,
2966 /* 238 */ CWORD_CWORD_CWORD_CWORD,
2967 /* 239 */ CWORD_CWORD_CWORD_CWORD,
2968 /* 230 */ CWORD_CWORD_CWORD_CWORD,
2969 /* 241 */ CWORD_CWORD_CWORD_CWORD,
2970 /* 242 */ CWORD_CWORD_CWORD_CWORD,
2971 /* 243 */ CWORD_CWORD_CWORD_CWORD,
2972 /* 244 */ CWORD_CWORD_CWORD_CWORD,
2973 /* 245 */ CWORD_CWORD_CWORD_CWORD,
2974 /* 246 */ CWORD_CWORD_CWORD_CWORD,
2975 /* 247 */ CWORD_CWORD_CWORD_CWORD,
2976 /* 248 */ CWORD_CWORD_CWORD_CWORD,
2977 /* 249 */ CWORD_CWORD_CWORD_CWORD,
2978 /* 250 */ CWORD_CWORD_CWORD_CWORD,
2979 /* 251 */ CWORD_CWORD_CWORD_CWORD,
2980 /* 252 */ CWORD_CWORD_CWORD_CWORD,
2981 /* 253 */ CWORD_CWORD_CWORD_CWORD,
2982 /* 254 */ CWORD_CWORD_CWORD_CWORD,
2983 /* 255 */ CWORD_CWORD_CWORD_CWORD,
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002984 /* PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
Denys Vlasenkocd716832009-11-28 22:14:02 +01002985# if ENABLE_ASH_ALIAS
2986 /* PEOA */ CSPCL_CIGN_CIGN_CIGN,
2987# endif
Eric Andersen2870d962001-07-02 17:27:21 +00002988};
2989
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002990# define SIT(c, syntax) ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf)
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00002991
Denys Vlasenko76bc2d62009-11-29 01:37:46 +01002992#endif /* !USE_SIT_FUNCTION */
Eric Andersenc470f442003-07-28 09:56:35 +00002993
Eric Andersen2870d962001-07-02 17:27:21 +00002994
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00002995/* ============ Alias handling */
Denis Vlasenkofc06f292007-02-23 21:09:35 +00002996
Denis Vlasenko131ae172007-02-18 13:00:19 +00002997#if ENABLE_ASH_ALIAS
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00002998
2999#define ALIASINUSE 1
3000#define ALIASDEAD 2
3001
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00003002struct alias {
3003 struct alias *next;
3004 char *name;
3005 char *val;
3006 int flag;
3007};
3008
Denis Vlasenko01631112007-12-16 17:20:38 +00003009
3010static struct alias **atab; // [ATABSIZE];
3011#define INIT_G_alias() do { \
3012 atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
3013} while (0)
3014
Eric Andersen2870d962001-07-02 17:27:21 +00003015
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00003016static struct alias **
3017__lookupalias(const char *name) {
3018 unsigned int hashval;
3019 struct alias **app;
3020 const char *p;
3021 unsigned int ch;
3022
3023 p = name;
3024
3025 ch = (unsigned char)*p;
3026 hashval = ch << 4;
3027 while (ch) {
3028 hashval += ch;
3029 ch = (unsigned char)*++p;
3030 }
3031 app = &atab[hashval % ATABSIZE];
3032
3033 for (; *app; app = &(*app)->next) {
3034 if (strcmp(name, (*app)->name) == 0) {
3035 break;
3036 }
3037 }
3038
3039 return app;
3040}
3041
3042static struct alias *
3043lookupalias(const char *name, int check)
3044{
3045 struct alias *ap = *__lookupalias(name);
3046
3047 if (check && ap && (ap->flag & ALIASINUSE))
3048 return NULL;
3049 return ap;
3050}
3051
3052static struct alias *
3053freealias(struct alias *ap)
3054{
3055 struct alias *next;
3056
3057 if (ap->flag & ALIASINUSE) {
3058 ap->flag |= ALIASDEAD;
3059 return ap;
3060 }
3061
3062 next = ap->next;
3063 free(ap->name);
3064 free(ap->val);
3065 free(ap);
3066 return next;
3067}
Eric Andersencb57d552001-06-28 07:25:16 +00003068
Eric Andersenc470f442003-07-28 09:56:35 +00003069static void
3070setalias(const char *name, const char *val)
Eric Andersencb57d552001-06-28 07:25:16 +00003071{
3072 struct alias *ap, **app;
3073
3074 app = __lookupalias(name);
3075 ap = *app;
Denis Vlasenkob012b102007-02-19 22:43:01 +00003076 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +00003077 if (ap) {
3078 if (!(ap->flag & ALIASINUSE)) {
Denis Vlasenkob012b102007-02-19 22:43:01 +00003079 free(ap->val);
Eric Andersencb57d552001-06-28 07:25:16 +00003080 }
Denis Vlasenko0c032a42007-02-23 01:03:40 +00003081 ap->val = ckstrdup(val);
Eric Andersencb57d552001-06-28 07:25:16 +00003082 ap->flag &= ~ALIASDEAD;
3083 } else {
3084 /* not found */
Denis Vlasenko597906c2008-02-20 16:38:54 +00003085 ap = ckzalloc(sizeof(struct alias));
Denis Vlasenko0c032a42007-02-23 01:03:40 +00003086 ap->name = ckstrdup(name);
3087 ap->val = ckstrdup(val);
Denis Vlasenko597906c2008-02-20 16:38:54 +00003088 /*ap->flag = 0; - ckzalloc did it */
3089 /*ap->next = NULL;*/
Eric Andersencb57d552001-06-28 07:25:16 +00003090 *app = ap;
3091 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00003092 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00003093}
3094
Eric Andersenc470f442003-07-28 09:56:35 +00003095static int
3096unalias(const char *name)
Eric Andersen2870d962001-07-02 17:27:21 +00003097{
Eric Andersencb57d552001-06-28 07:25:16 +00003098 struct alias **app;
3099
3100 app = __lookupalias(name);
3101
3102 if (*app) {
Denis Vlasenkob012b102007-02-19 22:43:01 +00003103 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +00003104 *app = freealias(*app);
Denis Vlasenkob012b102007-02-19 22:43:01 +00003105 INT_ON;
Denis Vlasenko079f8af2006-11-27 16:49:31 +00003106 return 0;
Eric Andersencb57d552001-06-28 07:25:16 +00003107 }
3108
Denis Vlasenko079f8af2006-11-27 16:49:31 +00003109 return 1;
Eric Andersencb57d552001-06-28 07:25:16 +00003110}
3111
Eric Andersenc470f442003-07-28 09:56:35 +00003112static void
3113rmaliases(void)
Eric Andersen2870d962001-07-02 17:27:21 +00003114{
Eric Andersencb57d552001-06-28 07:25:16 +00003115 struct alias *ap, **app;
3116 int i;
3117
Denis Vlasenkob012b102007-02-19 22:43:01 +00003118 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +00003119 for (i = 0; i < ATABSIZE; i++) {
3120 app = &atab[i];
3121 for (ap = *app; ap; ap = *app) {
3122 *app = freealias(*app);
3123 if (ap == *app) {
3124 app = &ap->next;
3125 }
3126 }
3127 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00003128 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00003129}
3130
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00003131static void
3132printalias(const struct alias *ap)
3133{
3134 out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
3135}
3136
Eric Andersencb57d552001-06-28 07:25:16 +00003137/*
3138 * TODO - sort output
3139 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02003140static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00003141aliascmd(int argc UNUSED_PARAM, char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +00003142{
3143 char *n, *v;
3144 int ret = 0;
3145 struct alias *ap;
3146
Denis Vlasenko68404f12008-03-17 09:00:54 +00003147 if (!argv[1]) {
Eric Andersencb57d552001-06-28 07:25:16 +00003148 int i;
3149
Denis Vlasenko68404f12008-03-17 09:00:54 +00003150 for (i = 0; i < ATABSIZE; i++) {
Eric Andersencb57d552001-06-28 07:25:16 +00003151 for (ap = atab[i]; ap; ap = ap->next) {
3152 printalias(ap);
3153 }
Denis Vlasenko68404f12008-03-17 09:00:54 +00003154 }
Denis Vlasenko079f8af2006-11-27 16:49:31 +00003155 return 0;
Eric Andersencb57d552001-06-28 07:25:16 +00003156 }
3157 while ((n = *++argv) != NULL) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00003158 v = strchr(n+1, '=');
3159 if (v == NULL) { /* n+1: funny ksh stuff */
3160 ap = *__lookupalias(n);
3161 if (ap == NULL) {
Eric Andersenc470f442003-07-28 09:56:35 +00003162 fprintf(stderr, "%s: %s not found\n", "alias", n);
Eric Andersencb57d552001-06-28 07:25:16 +00003163 ret = 1;
3164 } else
3165 printalias(ap);
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00003166 } else {
Eric Andersencb57d552001-06-28 07:25:16 +00003167 *v++ = '\0';
3168 setalias(n, v);
3169 }
3170 }
3171
Denis Vlasenkod9e15f22006-11-27 16:49:55 +00003172 return ret;
Eric Andersencb57d552001-06-28 07:25:16 +00003173}
3174
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02003175static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00003176unaliascmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersencb57d552001-06-28 07:25:16 +00003177{
3178 int i;
3179
3180 while ((i = nextopt("a")) != '\0') {
3181 if (i == 'a') {
3182 rmaliases();
Denis Vlasenko079f8af2006-11-27 16:49:31 +00003183 return 0;
Eric Andersencb57d552001-06-28 07:25:16 +00003184 }
3185 }
3186 for (i = 0; *argptr; argptr++) {
3187 if (unalias(*argptr)) {
Eric Andersenc470f442003-07-28 09:56:35 +00003188 fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
Eric Andersencb57d552001-06-28 07:25:16 +00003189 i = 1;
3190 }
3191 }
3192
Denis Vlasenkod9e15f22006-11-27 16:49:55 +00003193 return i;
Eric Andersencb57d552001-06-28 07:25:16 +00003194}
Denis Vlasenkofc06f292007-02-23 21:09:35 +00003195
Denis Vlasenko131ae172007-02-18 13:00:19 +00003196#endif /* ASH_ALIAS */
Eric Andersencb57d552001-06-28 07:25:16 +00003197
Eric Andersenc470f442003-07-28 09:56:35 +00003198
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003199/* ============ jobs.c */
3200
3201/* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
Denys Vlasenko285ad152009-12-04 23:02:27 +01003202#define FORK_FG 0
3203#define FORK_BG 1
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003204#define FORK_NOJOB 2
3205
3206/* mode flags for showjob(s) */
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003207#define SHOW_ONLY_PGID 0x01 /* show only pgid (jobs -p) */
3208#define SHOW_PIDS 0x02 /* show individual pids, not just one line per job */
3209#define SHOW_CHANGED 0x04 /* only jobs whose state has changed */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003210
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003211/*
3212 * A job structure contains information about a job. A job is either a
3213 * single process or a set of processes contained in a pipeline. In the
3214 * latter case, pidlist will be non-NULL, and will point to a -1 terminated
3215 * array of pids.
3216 */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003217struct procstat {
Denys Vlasenko285ad152009-12-04 23:02:27 +01003218 pid_t ps_pid; /* process id */
3219 int ps_status; /* last process status from wait() */
3220 char *ps_cmd; /* text of command being run */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003221};
3222
3223struct job {
3224 struct procstat ps0; /* status of process */
3225 struct procstat *ps; /* status or processes when more than one */
3226#if JOBS
3227 int stopstatus; /* status of a stopped job */
3228#endif
3229 uint32_t
3230 nprocs: 16, /* number of processes */
3231 state: 8,
3232#define JOBRUNNING 0 /* at least one proc running */
3233#define JOBSTOPPED 1 /* all procs are stopped */
3234#define JOBDONE 2 /* all procs are completed */
3235#if JOBS
3236 sigint: 1, /* job was killed by SIGINT */
3237 jobctl: 1, /* job running under job control */
3238#endif
3239 waited: 1, /* true if this entry has been waited for */
3240 used: 1, /* true if this entry is in used */
3241 changed: 1; /* true if status has changed */
3242 struct job *prev_job; /* previous job */
3243};
3244
Denis Vlasenko68404f12008-03-17 09:00:54 +00003245static struct job *makejob(/*union node *,*/ int);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003246static int forkshell(struct job *, union node *, int);
3247static int waitforjob(struct job *);
3248
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003249#if !JOBS
Denis Vlasenkob07a4962008-06-22 13:16:23 +00003250enum { doing_jobctl = 0 };
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003251#define setjobctl(on) do {} while (0)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003252#else
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003253static smallint doing_jobctl; //references:8
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003254static void setjobctl(int);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003255#endif
3256
3257/*
Denis Vlasenko4b875702009-03-19 13:30:04 +00003258 * Ignore a signal.
3259 */
3260static void
3261ignoresig(int signo)
3262{
3263 /* Avoid unnecessary system calls. Is it already SIG_IGNed? */
3264 if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
3265 /* No, need to do it */
3266 signal(signo, SIG_IGN);
3267 }
3268 sigmode[signo - 1] = S_HARD_IGN;
3269}
3270
3271/*
Denys Vlasenko238bf182010-05-18 15:49:07 +02003272 * Only one usage site - in setsignal()
Denis Vlasenko4b875702009-03-19 13:30:04 +00003273 */
3274static void
Denys Vlasenko238bf182010-05-18 15:49:07 +02003275signal_handler(int signo)
Denis Vlasenko4b875702009-03-19 13:30:04 +00003276{
3277 gotsig[signo - 1] = 1;
3278
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02003279 if (signo == SIGINT && !trap[SIGINT]) {
3280 if (!suppress_int) {
3281 pending_sig = 0;
Denis Vlasenko4b875702009-03-19 13:30:04 +00003282 raise_interrupt(); /* does not return */
3283 }
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02003284 pending_int = 1;
Denis Vlasenko4b875702009-03-19 13:30:04 +00003285 } else {
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02003286 pending_sig = signo;
Denis Vlasenko4b875702009-03-19 13:30:04 +00003287 }
3288}
3289
3290/*
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003291 * Set the signal handler for the specified signal. The routine figures
3292 * out what it should be set to.
3293 */
3294static void
3295setsignal(int signo)
3296{
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003297 char *t;
3298 char cur_act, new_act;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003299 struct sigaction act;
3300
3301 t = trap[signo];
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003302 new_act = S_DFL;
3303 if (t != NULL) { /* trap for this sig is set */
3304 new_act = S_CATCH;
3305 if (t[0] == '\0') /* trap is "": ignore this sig */
3306 new_act = S_IGN;
3307 }
3308
3309 if (rootshell && new_act == S_DFL) {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003310 switch (signo) {
3311 case SIGINT:
3312 if (iflag || minusc || sflag == 0)
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003313 new_act = S_CATCH;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003314 break;
3315 case SIGQUIT:
3316#if DEBUG
3317 if (debug)
3318 break;
3319#endif
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003320 /* man bash:
3321 * "In all cases, bash ignores SIGQUIT. Non-builtin
3322 * commands run by bash have signal handlers
3323 * set to the values inherited by the shell
3324 * from its parent". */
3325 new_act = S_IGN;
3326 break;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003327 case SIGTERM:
3328 if (iflag)
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003329 new_act = S_IGN;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003330 break;
3331#if JOBS
3332 case SIGTSTP:
3333 case SIGTTOU:
3334 if (mflag)
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003335 new_act = S_IGN;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003336 break;
3337#endif
3338 }
3339 }
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003340//TODO: if !rootshell, we reset SIGQUIT to DFL,
3341//whereas we have to restore it to what shell got on entry
3342//from the parent. See comment above
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003343
3344 t = &sigmode[signo - 1];
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003345 cur_act = *t;
3346 if (cur_act == 0) {
3347 /* current setting is not yet known */
3348 if (sigaction(signo, NULL, &act)) {
3349 /* pretend it worked; maybe we should give a warning,
3350 * but other shells don't. We don't alter sigmode,
3351 * so we retry every time.
3352 * btw, in Linux it never fails. --vda */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003353 return;
3354 }
3355 if (act.sa_handler == SIG_IGN) {
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003356 cur_act = S_HARD_IGN;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003357 if (mflag
3358 && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
3359 ) {
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003360 cur_act = S_IGN; /* don't hard ignore these */
Denis Vlasenko991a1da2008-02-10 19:02:53 +00003361 }
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003362 }
3363 }
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003364 if (cur_act == S_HARD_IGN || cur_act == new_act)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003365 return;
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003366
Denis Vlasenko991a1da2008-02-10 19:02:53 +00003367 act.sa_handler = SIG_DFL;
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003368 switch (new_act) {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003369 case S_CATCH:
Denys Vlasenko238bf182010-05-18 15:49:07 +02003370 act.sa_handler = signal_handler;
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003371 act.sa_flags = 0; /* matters only if !DFL and !IGN */
3372 sigfillset(&act.sa_mask); /* ditto */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003373 break;
3374 case S_IGN:
3375 act.sa_handler = SIG_IGN;
3376 break;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003377 }
Denis Vlasenko8e2cfec2008-03-12 23:19:35 +00003378 sigaction_set(signo, &act);
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003379
3380 *t = new_act;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003381}
3382
3383/* mode flags for set_curjob */
3384#define CUR_DELETE 2
3385#define CUR_RUNNING 1
3386#define CUR_STOPPED 0
3387
3388/* mode flags for dowait */
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00003389#define DOWAIT_NONBLOCK WNOHANG
3390#define DOWAIT_BLOCK 0
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003391
3392#if JOBS
3393/* pgrp of shell on invocation */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003394static int initialpgrp; //references:2
3395static int ttyfd = -1; //5
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003396#endif
3397/* array of jobs */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003398static struct job *jobtab; //5
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003399/* size of array */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003400static unsigned njobs; //4
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003401/* current job */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003402static struct job *curjob; //lots
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003403/* number of presumed living untracked jobs */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003404static int jobless; //4
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003405
3406static void
3407set_curjob(struct job *jp, unsigned mode)
3408{
3409 struct job *jp1;
3410 struct job **jpp, **curp;
3411
3412 /* first remove from list */
3413 jpp = curp = &curjob;
3414 do {
3415 jp1 = *jpp;
3416 if (jp1 == jp)
3417 break;
3418 jpp = &jp1->prev_job;
3419 } while (1);
3420 *jpp = jp1->prev_job;
3421
3422 /* Then re-insert in correct position */
3423 jpp = curp;
3424 switch (mode) {
3425 default:
3426#if DEBUG
3427 abort();
3428#endif
3429 case CUR_DELETE:
3430 /* job being deleted */
3431 break;
3432 case CUR_RUNNING:
3433 /* newly created job or backgrounded job,
3434 put after all stopped jobs. */
3435 do {
3436 jp1 = *jpp;
3437#if JOBS
3438 if (!jp1 || jp1->state != JOBSTOPPED)
3439#endif
3440 break;
3441 jpp = &jp1->prev_job;
3442 } while (1);
3443 /* FALLTHROUGH */
3444#if JOBS
3445 case CUR_STOPPED:
3446#endif
3447 /* newly stopped job - becomes curjob */
3448 jp->prev_job = *jpp;
3449 *jpp = jp;
3450 break;
3451 }
3452}
3453
3454#if JOBS || DEBUG
3455static int
3456jobno(const struct job *jp)
3457{
3458 return jp - jobtab + 1;
3459}
3460#endif
3461
3462/*
3463 * Convert a job name to a job structure.
3464 */
Denis Vlasenko85c24712008-03-17 09:04:04 +00003465#if !JOBS
3466#define getjob(name, getctl) getjob(name)
3467#endif
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003468static struct job *
3469getjob(const char *name, int getctl)
3470{
3471 struct job *jp;
3472 struct job *found;
Denys Vlasenkoffc39202009-08-17 02:12:20 +02003473 const char *err_msg = "%s: no such job";
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003474 unsigned num;
3475 int c;
3476 const char *p;
3477 char *(*match)(const char *, const char *);
3478
3479 jp = curjob;
3480 p = name;
3481 if (!p)
3482 goto currentjob;
3483
3484 if (*p != '%')
3485 goto err;
3486
3487 c = *++p;
3488 if (!c)
3489 goto currentjob;
3490
3491 if (!p[1]) {
3492 if (c == '+' || c == '%') {
3493 currentjob:
3494 err_msg = "No current job";
3495 goto check;
3496 }
3497 if (c == '-') {
3498 if (jp)
3499 jp = jp->prev_job;
3500 err_msg = "No previous job";
3501 check:
3502 if (!jp)
3503 goto err;
3504 goto gotit;
3505 }
3506 }
3507
3508 if (is_number(p)) {
3509 num = atoi(p);
3510 if (num < njobs) {
3511 jp = jobtab + num - 1;
3512 if (jp->used)
3513 goto gotit;
3514 goto err;
3515 }
3516 }
3517
3518 match = prefix;
3519 if (*p == '?') {
3520 match = strstr;
3521 p++;
3522 }
3523
Denys Vlasenkoffc39202009-08-17 02:12:20 +02003524 found = NULL;
3525 while (jp) {
Denys Vlasenko285ad152009-12-04 23:02:27 +01003526 if (match(jp->ps[0].ps_cmd, p)) {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003527 if (found)
3528 goto err;
3529 found = jp;
3530 err_msg = "%s: ambiguous";
3531 }
3532 jp = jp->prev_job;
3533 }
Denys Vlasenkoffc39202009-08-17 02:12:20 +02003534 if (!found)
3535 goto err;
3536 jp = found;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003537
3538 gotit:
3539#if JOBS
3540 err_msg = "job %s not created under job control";
3541 if (getctl && jp->jobctl == 0)
3542 goto err;
3543#endif
3544 return jp;
3545 err:
3546 ash_msg_and_raise_error(err_msg, name);
3547}
3548
3549/*
3550 * Mark a job structure as unused.
3551 */
3552static void
3553freejob(struct job *jp)
3554{
3555 struct procstat *ps;
3556 int i;
3557
3558 INT_OFF;
3559 for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
Denys Vlasenko285ad152009-12-04 23:02:27 +01003560 if (ps->ps_cmd != nullstr)
3561 free(ps->ps_cmd);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003562 }
3563 if (jp->ps != &jp->ps0)
3564 free(jp->ps);
3565 jp->used = 0;
3566 set_curjob(jp, CUR_DELETE);
3567 INT_ON;
3568}
3569
3570#if JOBS
3571static void
3572xtcsetpgrp(int fd, pid_t pgrp)
3573{
3574 if (tcsetpgrp(fd, pgrp))
Bernhard Reutner-Fischera53de7f2008-07-21 13:46:54 +00003575 ash_msg_and_raise_error("can't set tty process group (%m)");
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003576}
3577
3578/*
3579 * Turn job control on and off.
3580 *
3581 * Note: This code assumes that the third arg to ioctl is a character
3582 * pointer, which is true on Berkeley systems but not System V. Since
3583 * System V doesn't have job control yet, this isn't a problem now.
3584 *
3585 * Called with interrupts off.
3586 */
3587static void
3588setjobctl(int on)
3589{
3590 int fd;
3591 int pgrp;
3592
Denis Vlasenkob07a4962008-06-22 13:16:23 +00003593 if (on == doing_jobctl || rootshell == 0)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003594 return;
3595 if (on) {
3596 int ofd;
3597 ofd = fd = open(_PATH_TTY, O_RDWR);
3598 if (fd < 0) {
3599 /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
3600 * That sometimes helps to acquire controlling tty.
3601 * Obviously, a workaround for bugs when someone
3602 * failed to provide a controlling tty to bash! :) */
Denis Vlasenkoed270a52007-11-26 05:37:07 +00003603 fd = 2;
3604 while (!isatty(fd))
3605 if (--fd < 0)
3606 goto out;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003607 }
3608 fd = fcntl(fd, F_DUPFD, 10);
Denis Vlasenkoed270a52007-11-26 05:37:07 +00003609 if (ofd >= 0)
3610 close(ofd);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003611 if (fd < 0)
3612 goto out;
Denis Vlasenkoed270a52007-11-26 05:37:07 +00003613 /* fd is a tty at this point */
Denis Vlasenko96e1b382007-09-30 23:50:48 +00003614 close_on_exec_on(fd);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003615 do { /* while we are in the background */
3616 pgrp = tcgetpgrp(fd);
3617 if (pgrp < 0) {
3618 out:
3619 ash_msg("can't access tty; job control turned off");
3620 mflag = on = 0;
3621 goto close;
3622 }
3623 if (pgrp == getpgrp())
3624 break;
3625 killpg(0, SIGTTIN);
3626 } while (1);
3627 initialpgrp = pgrp;
3628
3629 setsignal(SIGTSTP);
3630 setsignal(SIGTTOU);
3631 setsignal(SIGTTIN);
3632 pgrp = rootpid;
3633 setpgid(0, pgrp);
3634 xtcsetpgrp(fd, pgrp);
3635 } else {
3636 /* turning job control off */
3637 fd = ttyfd;
3638 pgrp = initialpgrp;
Denis Vlasenko08c8c1d2007-04-28 22:39:02 +00003639 /* was xtcsetpgrp, but this can make exiting ash
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00003640 * loop forever if pty is already deleted */
Denis Vlasenko08c8c1d2007-04-28 22:39:02 +00003641 tcsetpgrp(fd, pgrp);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003642 setpgid(0, pgrp);
3643 setsignal(SIGTSTP);
3644 setsignal(SIGTTOU);
3645 setsignal(SIGTTIN);
3646 close:
Denis Vlasenkoed270a52007-11-26 05:37:07 +00003647 if (fd >= 0)
3648 close(fd);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003649 fd = -1;
3650 }
3651 ttyfd = fd;
Denis Vlasenkob07a4962008-06-22 13:16:23 +00003652 doing_jobctl = on;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003653}
3654
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02003655static int FAST_FUNC
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003656killcmd(int argc, char **argv)
3657{
Denis Vlasenko68404f12008-03-17 09:00:54 +00003658 int i = 1;
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003659 if (argv[1] && strcmp(argv[1], "-l") != 0) {
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003660 do {
3661 if (argv[i][0] == '%') {
3662 struct job *jp = getjob(argv[i], 0);
Denys Vlasenko285ad152009-12-04 23:02:27 +01003663 unsigned pid = jp->ps[0].ps_pid;
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003664 /* Enough space for ' -NNN<nul>' */
3665 argv[i] = alloca(sizeof(int)*3 + 3);
3666 /* kill_main has matching code to expect
3667 * leading space. Needed to not confuse
3668 * negative pids with "kill -SIGNAL_NO" syntax */
3669 sprintf(argv[i], " -%u", pid);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003670 }
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003671 } while (argv[++i]);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003672 }
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003673 return kill_main(argc, argv);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003674}
3675
3676static void
Denys Vlasenko285ad152009-12-04 23:02:27 +01003677showpipe(struct job *jp /*, FILE *out*/)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003678{
Denys Vlasenko285ad152009-12-04 23:02:27 +01003679 struct procstat *ps;
3680 struct procstat *psend;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003681
Denys Vlasenko285ad152009-12-04 23:02:27 +01003682 psend = jp->ps + jp->nprocs;
3683 for (ps = jp->ps + 1; ps < psend; ps++)
3684 printf(" | %s", ps->ps_cmd);
3685 outcslow('\n', stdout);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003686 flush_stdout_stderr();
3687}
3688
3689
3690static int
3691restartjob(struct job *jp, int mode)
3692{
3693 struct procstat *ps;
3694 int i;
3695 int status;
3696 pid_t pgid;
3697
3698 INT_OFF;
3699 if (jp->state == JOBDONE)
3700 goto out;
3701 jp->state = JOBRUNNING;
Denys Vlasenko285ad152009-12-04 23:02:27 +01003702 pgid = jp->ps[0].ps_pid;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003703 if (mode == FORK_FG)
3704 xtcsetpgrp(ttyfd, pgid);
3705 killpg(pgid, SIGCONT);
3706 ps = jp->ps;
3707 i = jp->nprocs;
3708 do {
Denys Vlasenko285ad152009-12-04 23:02:27 +01003709 if (WIFSTOPPED(ps->ps_status)) {
3710 ps->ps_status = -1;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003711 }
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003712 ps++;
3713 } while (--i);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003714 out:
3715 status = (mode == FORK_FG) ? waitforjob(jp) : 0;
3716 INT_ON;
3717 return status;
3718}
3719
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02003720static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00003721fg_bgcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003722{
3723 struct job *jp;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003724 int mode;
3725 int retval;
3726
3727 mode = (**argv == 'f') ? FORK_FG : FORK_BG;
3728 nextopt(nullstr);
3729 argv = argptr;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003730 do {
3731 jp = getjob(*argv, 1);
3732 if (mode == FORK_BG) {
3733 set_curjob(jp, CUR_RUNNING);
Denys Vlasenko285ad152009-12-04 23:02:27 +01003734 printf("[%d] ", jobno(jp));
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003735 }
Denys Vlasenko285ad152009-12-04 23:02:27 +01003736 out1str(jp->ps[0].ps_cmd);
3737 showpipe(jp /*, stdout*/);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003738 retval = restartjob(jp, mode);
3739 } while (*argv && *++argv);
3740 return retval;
3741}
3742#endif
3743
3744static int
3745sprint_status(char *s, int status, int sigonly)
3746{
3747 int col;
3748 int st;
3749
3750 col = 0;
3751 if (!WIFEXITED(status)) {
3752#if JOBS
3753 if (WIFSTOPPED(status))
3754 st = WSTOPSIG(status);
3755 else
3756#endif
3757 st = WTERMSIG(status);
3758 if (sigonly) {
3759 if (st == SIGINT || st == SIGPIPE)
3760 goto out;
3761#if JOBS
3762 if (WIFSTOPPED(status))
3763 goto out;
3764#endif
3765 }
3766 st &= 0x7f;
3767 col = fmtstr(s, 32, strsignal(st));
3768 if (WCOREDUMP(status)) {
3769 col += fmtstr(s + col, 16, " (core dumped)");
3770 }
3771 } else if (!sigonly) {
3772 st = WEXITSTATUS(status);
3773 if (st)
3774 col = fmtstr(s, 16, "Done(%d)", st);
3775 else
3776 col = fmtstr(s, 16, "Done");
3777 }
3778 out:
3779 return col;
3780}
3781
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003782static int
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00003783dowait(int wait_flags, struct job *job)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003784{
3785 int pid;
3786 int status;
3787 struct job *jp;
3788 struct job *thisjob;
3789 int state;
3790
Denis Vlasenkobe54d6b2008-10-27 14:25:52 +00003791 TRACE(("dowait(0x%x) called\n", wait_flags));
3792
3793 /* Do a wait system call. If job control is compiled in, we accept
3794 * stopped processes. wait_flags may have WNOHANG, preventing blocking.
3795 * NB: _not_ safe_waitpid, we need to detect EINTR */
Denys Vlasenko285ad152009-12-04 23:02:27 +01003796 if (doing_jobctl)
3797 wait_flags |= WUNTRACED;
3798 pid = waitpid(-1, &status, wait_flags);
Denis Vlasenkob21f3792009-03-19 23:09:58 +00003799 TRACE(("wait returns pid=%d, status=0x%x, errno=%d(%s)\n",
3800 pid, status, errno, strerror(errno)));
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003801 if (pid <= 0)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003802 return pid;
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003803
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003804 INT_OFF;
3805 thisjob = NULL;
3806 for (jp = curjob; jp; jp = jp->prev_job) {
Denys Vlasenko285ad152009-12-04 23:02:27 +01003807 struct procstat *ps;
3808 struct procstat *psend;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003809 if (jp->state == JOBDONE)
3810 continue;
3811 state = JOBDONE;
Denys Vlasenko285ad152009-12-04 23:02:27 +01003812 ps = jp->ps;
3813 psend = ps + jp->nprocs;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003814 do {
Denys Vlasenko285ad152009-12-04 23:02:27 +01003815 if (ps->ps_pid == pid) {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003816 TRACE(("Job %d: changing status of proc %d "
3817 "from 0x%x to 0x%x\n",
Denys Vlasenko285ad152009-12-04 23:02:27 +01003818 jobno(jp), pid, ps->ps_status, status));
3819 ps->ps_status = status;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003820 thisjob = jp;
3821 }
Denys Vlasenko285ad152009-12-04 23:02:27 +01003822 if (ps->ps_status == -1)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003823 state = JOBRUNNING;
3824#if JOBS
3825 if (state == JOBRUNNING)
3826 continue;
Denys Vlasenko285ad152009-12-04 23:02:27 +01003827 if (WIFSTOPPED(ps->ps_status)) {
3828 jp->stopstatus = ps->ps_status;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003829 state = JOBSTOPPED;
3830 }
3831#endif
Denys Vlasenko285ad152009-12-04 23:02:27 +01003832 } while (++ps < psend);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003833 if (thisjob)
3834 goto gotjob;
3835 }
3836#if JOBS
3837 if (!WIFSTOPPED(status))
3838#endif
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003839 jobless--;
3840 goto out;
3841
3842 gotjob:
3843 if (state != JOBRUNNING) {
3844 thisjob->changed = 1;
3845
3846 if (thisjob->state != state) {
3847 TRACE(("Job %d: changing state from %d to %d\n",
3848 jobno(thisjob), thisjob->state, state));
3849 thisjob->state = state;
3850#if JOBS
3851 if (state == JOBSTOPPED) {
3852 set_curjob(thisjob, CUR_STOPPED);
3853 }
3854#endif
3855 }
3856 }
3857
3858 out:
3859 INT_ON;
3860
3861 if (thisjob && thisjob == job) {
3862 char s[48 + 1];
3863 int len;
3864
3865 len = sprint_status(s, status, 1);
3866 if (len) {
3867 s[len] = '\n';
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00003868 s[len + 1] = '\0';
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003869 out2str(s);
3870 }
3871 }
3872 return pid;
3873}
3874
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003875static int
Denys Vlasenko7c1ed9f2010-05-17 04:42:40 +02003876blocking_wait_with_raise_on_sig(void)
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003877{
Denys Vlasenko7c1ed9f2010-05-17 04:42:40 +02003878 pid_t pid = dowait(DOWAIT_BLOCK, NULL);
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02003879 if (pid <= 0 && pending_sig)
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003880 raise_exception(EXSIG);
3881 return pid;
3882}
3883
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003884#if JOBS
3885static void
3886showjob(FILE *out, struct job *jp, int mode)
3887{
3888 struct procstat *ps;
3889 struct procstat *psend;
3890 int col;
Denis Vlasenko40ba9982007-07-14 00:48:29 +00003891 int indent_col;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003892 char s[80];
3893
3894 ps = jp->ps;
3895
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003896 if (mode & SHOW_ONLY_PGID) { /* jobs -p */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003897 /* just output process (group) id of pipeline */
Denys Vlasenko285ad152009-12-04 23:02:27 +01003898 fprintf(out, "%d\n", ps->ps_pid);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003899 return;
3900 }
3901
3902 col = fmtstr(s, 16, "[%d] ", jobno(jp));
Denis Vlasenko40ba9982007-07-14 00:48:29 +00003903 indent_col = col;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003904
3905 if (jp == curjob)
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003906 s[col - 3] = '+';
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003907 else if (curjob && jp == curjob->prev_job)
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003908 s[col - 3] = '-';
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003909
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003910 if (mode & SHOW_PIDS)
Denys Vlasenko285ad152009-12-04 23:02:27 +01003911 col += fmtstr(s + col, 16, "%d ", ps->ps_pid);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003912
3913 psend = ps + jp->nprocs;
3914
3915 if (jp->state == JOBRUNNING) {
3916 strcpy(s + col, "Running");
3917 col += sizeof("Running") - 1;
3918 } else {
Denys Vlasenko285ad152009-12-04 23:02:27 +01003919 int status = psend[-1].ps_status;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003920 if (jp->state == JOBSTOPPED)
3921 status = jp->stopstatus;
3922 col += sprint_status(s + col, status, 0);
3923 }
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003924 /* By now, "[JOBID]* [maybe PID] STATUS" is printed */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003925
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003926 /* This loop either prints "<cmd1> | <cmd2> | <cmd3>" line
3927 * or prints several "PID | <cmdN>" lines,
3928 * depending on SHOW_PIDS bit.
3929 * We do not print status of individual processes
3930 * between PID and <cmdN>. bash does it, but not very well:
3931 * first line shows overall job status, not process status,
3932 * making it impossible to know 1st process status.
3933 */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003934 goto start;
Denys Vlasenko285ad152009-12-04 23:02:27 +01003935 do {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003936 /* for each process */
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003937 s[0] = '\0';
3938 col = 33;
3939 if (mode & SHOW_PIDS)
Denys Vlasenko285ad152009-12-04 23:02:27 +01003940 col = fmtstr(s, 48, "\n%*c%d ", indent_col, ' ', ps->ps_pid) - 1;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003941 start:
Denys Vlasenko285ad152009-12-04 23:02:27 +01003942 fprintf(out, "%s%*c%s%s",
3943 s,
3944 33 - col >= 0 ? 33 - col : 0, ' ',
3945 ps == jp->ps ? "" : "| ",
3946 ps->ps_cmd
3947 );
3948 } while (++ps != psend);
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003949 outcslow('\n', out);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003950
3951 jp->changed = 0;
3952
3953 if (jp->state == JOBDONE) {
3954 TRACE(("showjob: freeing job %d\n", jobno(jp)));
3955 freejob(jp);
3956 }
3957}
3958
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003959/*
3960 * Print a list of jobs. If "change" is nonzero, only print jobs whose
3961 * statuses have changed since the last call to showjobs.
3962 */
3963static void
3964showjobs(FILE *out, int mode)
3965{
3966 struct job *jp;
3967
Denys Vlasenko883cea42009-07-11 15:31:59 +02003968 TRACE(("showjobs(0x%x) called\n", mode));
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003969
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003970 /* Handle all finished jobs */
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00003971 while (dowait(DOWAIT_NONBLOCK, NULL) > 0)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003972 continue;
3973
3974 for (jp = curjob; jp; jp = jp->prev_job) {
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003975 if (!(mode & SHOW_CHANGED) || jp->changed) {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003976 showjob(out, jp, mode);
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003977 }
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003978 }
3979}
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003980
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02003981static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00003982jobscmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003983{
3984 int mode, m;
3985
3986 mode = 0;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02003987 while ((m = nextopt("lp")) != '\0') {
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003988 if (m == 'l')
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003989 mode |= SHOW_PIDS;
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003990 else
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003991 mode |= SHOW_ONLY_PGID;
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003992 }
3993
3994 argv = argptr;
3995 if (*argv) {
3996 do
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003997 showjob(stdout, getjob(*argv, 0), mode);
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003998 while (*++argv);
Denys Vlasenko285ad152009-12-04 23:02:27 +01003999 } else {
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00004000 showjobs(stdout, mode);
Denys Vlasenko285ad152009-12-04 23:02:27 +01004001 }
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00004002
4003 return 0;
4004}
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004005#endif /* JOBS */
4006
Michael Abbott359da5e2009-12-04 23:03:29 +01004007/* Called only on finished or stopped jobs (no members are running) */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004008static int
4009getstatus(struct job *job)
4010{
4011 int status;
4012 int retval;
Michael Abbott359da5e2009-12-04 23:03:29 +01004013 struct procstat *ps;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004014
Michael Abbott359da5e2009-12-04 23:03:29 +01004015 /* Fetch last member's status */
4016 ps = job->ps + job->nprocs - 1;
4017 status = ps->ps_status;
4018 if (pipefail) {
4019 /* "set -o pipefail" mode: use last _nonzero_ status */
4020 while (status == 0 && --ps >= job->ps)
4021 status = ps->ps_status;
4022 }
4023
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004024 retval = WEXITSTATUS(status);
4025 if (!WIFEXITED(status)) {
4026#if JOBS
4027 retval = WSTOPSIG(status);
4028 if (!WIFSTOPPED(status))
4029#endif
4030 {
4031 /* XXX: limits number of signals */
4032 retval = WTERMSIG(status);
4033#if JOBS
4034 if (retval == SIGINT)
4035 job->sigint = 1;
4036#endif
4037 }
4038 retval += 128;
4039 }
Denys Vlasenko883cea42009-07-11 15:31:59 +02004040 TRACE(("getstatus: job %d, nproc %d, status 0x%x, retval 0x%x\n",
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004041 jobno(job), job->nprocs, status, retval));
4042 return retval;
4043}
4044
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02004045static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00004046waitcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004047{
4048 struct job *job;
4049 int retval;
4050 struct job *jp;
4051
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02004052 if (pending_sig)
Denis Vlasenko991a1da2008-02-10 19:02:53 +00004053 raise_exception(EXSIG);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004054
4055 nextopt(nullstr);
4056 retval = 0;
4057
4058 argv = argptr;
4059 if (!*argv) {
4060 /* wait for all jobs */
4061 for (;;) {
4062 jp = curjob;
4063 while (1) {
Denis Vlasenko991a1da2008-02-10 19:02:53 +00004064 if (!jp) /* no running procs */
4065 goto ret;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004066 if (jp->state == JOBRUNNING)
4067 break;
4068 jp->waited = 1;
4069 jp = jp->prev_job;
4070 }
Denys Vlasenko7c1ed9f2010-05-17 04:42:40 +02004071 blocking_wait_with_raise_on_sig();
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004072 /* man bash:
4073 * "When bash is waiting for an asynchronous command via
4074 * the wait builtin, the reception of a signal for which a trap
4075 * has been set will cause the wait builtin to return immediately
4076 * with an exit status greater than 128, immediately after which
4077 * the trap is executed."
Denys Vlasenko7c1ed9f2010-05-17 04:42:40 +02004078 *
4079 * blocking_wait_with_raise_on_sig raises signal handlers
4080 * if it gets no pid (pid < 0). However,
4081 * if child sends us a signal *and immediately exits*,
4082 * blocking_wait_with_raise_on_sig gets pid > 0
4083 * and does not handle pending_sig. Check this case: */
4084 if (pending_sig)
4085 raise_exception(EXSIG);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004086 }
4087 }
4088
4089 retval = 127;
4090 do {
4091 if (**argv != '%') {
4092 pid_t pid = number(*argv);
4093 job = curjob;
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00004094 while (1) {
4095 if (!job)
4096 goto repeat;
Denys Vlasenko285ad152009-12-04 23:02:27 +01004097 if (job->ps[job->nprocs - 1].ps_pid == pid)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004098 break;
4099 job = job->prev_job;
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00004100 }
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004101 } else
4102 job = getjob(*argv, 0);
4103 /* loop until process terminated or stopped */
4104 while (job->state == JOBRUNNING)
Denys Vlasenko7c1ed9f2010-05-17 04:42:40 +02004105 blocking_wait_with_raise_on_sig();
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004106 job->waited = 1;
4107 retval = getstatus(job);
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004108 repeat: ;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004109 } while (*++argv);
4110
Denis Vlasenko991a1da2008-02-10 19:02:53 +00004111 ret:
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004112 return retval;
4113}
4114
4115static struct job *
4116growjobtab(void)
4117{
4118 size_t len;
4119 ptrdiff_t offset;
4120 struct job *jp, *jq;
4121
4122 len = njobs * sizeof(*jp);
4123 jq = jobtab;
4124 jp = ckrealloc(jq, len + 4 * sizeof(*jp));
4125
4126 offset = (char *)jp - (char *)jq;
4127 if (offset) {
4128 /* Relocate pointers */
4129 size_t l = len;
4130
4131 jq = (struct job *)((char *)jq + l);
4132 while (l) {
4133 l -= sizeof(*jp);
4134 jq--;
4135#define joff(p) ((struct job *)((char *)(p) + l))
4136#define jmove(p) (p) = (void *)((char *)(p) + offset)
4137 if (joff(jp)->ps == &jq->ps0)
4138 jmove(joff(jp)->ps);
4139 if (joff(jp)->prev_job)
4140 jmove(joff(jp)->prev_job);
4141 }
4142 if (curjob)
4143 jmove(curjob);
4144#undef joff
4145#undef jmove
4146 }
4147
4148 njobs += 4;
4149 jobtab = jp;
4150 jp = (struct job *)((char *)jp + len);
4151 jq = jp + 3;
4152 do {
4153 jq->used = 0;
4154 } while (--jq >= jp);
4155 return jp;
4156}
4157
4158/*
4159 * Return a new job structure.
4160 * Called with interrupts off.
4161 */
4162static struct job *
Denis Vlasenko68404f12008-03-17 09:00:54 +00004163makejob(/*union node *node,*/ int nprocs)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004164{
4165 int i;
4166 struct job *jp;
4167
4168 for (i = njobs, jp = jobtab; ; jp++) {
4169 if (--i < 0) {
4170 jp = growjobtab();
4171 break;
4172 }
4173 if (jp->used == 0)
4174 break;
4175 if (jp->state != JOBDONE || !jp->waited)
4176 continue;
4177#if JOBS
Denis Vlasenkob07a4962008-06-22 13:16:23 +00004178 if (doing_jobctl)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004179 continue;
4180#endif
4181 freejob(jp);
4182 break;
4183 }
4184 memset(jp, 0, sizeof(*jp));
4185#if JOBS
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00004186 /* jp->jobctl is a bitfield.
4187 * "jp->jobctl |= jobctl" likely to give awful code */
Denis Vlasenkob07a4962008-06-22 13:16:23 +00004188 if (doing_jobctl)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004189 jp->jobctl = 1;
4190#endif
4191 jp->prev_job = curjob;
4192 curjob = jp;
4193 jp->used = 1;
4194 jp->ps = &jp->ps0;
4195 if (nprocs > 1) {
4196 jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
4197 }
Denis Vlasenko68404f12008-03-17 09:00:54 +00004198 TRACE(("makejob(%d) returns %%%d\n", nprocs,
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004199 jobno(jp)));
4200 return jp;
4201}
4202
4203#if JOBS
4204/*
4205 * Return a string identifying a command (to be printed by the
4206 * jobs command).
4207 */
4208static char *cmdnextc;
4209
4210static void
4211cmdputs(const char *s)
4212{
Denis Vlasenko92e13c22008-03-25 01:17:40 +00004213 static const char vstype[VSTYPE + 1][3] = {
4214 "", "}", "-", "+", "?", "=",
4215 "%", "%%", "#", "##"
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00004216 IF_ASH_BASH_COMPAT(, ":", "/", "//")
Denis Vlasenko92e13c22008-03-25 01:17:40 +00004217 };
4218
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004219 const char *p, *str;
Denys Vlasenko46a14772009-12-10 21:27:13 +01004220 char cc[2];
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004221 char *nextc;
Denys Vlasenkocd716832009-11-28 22:14:02 +01004222 unsigned char c;
4223 unsigned char subtype = 0;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004224 int quoted = 0;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004225
Denys Vlasenko46a14772009-12-10 21:27:13 +01004226 cc[1] = '\0';
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004227 nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
4228 p = s;
Denys Vlasenko46a14772009-12-10 21:27:13 +01004229 while ((c = *p++) != '\0') {
Denis Vlasenkoef527f52008-06-23 01:52:30 +00004230 str = NULL;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004231 switch (c) {
4232 case CTLESC:
4233 c = *p++;
4234 break;
4235 case CTLVAR:
4236 subtype = *p++;
4237 if ((subtype & VSTYPE) == VSLENGTH)
4238 str = "${#";
4239 else
4240 str = "${";
4241 if (!(subtype & VSQUOTE) == !(quoted & 1))
4242 goto dostr;
4243 quoted ^= 1;
4244 c = '"';
4245 break;
4246 case CTLENDVAR:
4247 str = "\"}" + !(quoted & 1);
4248 quoted >>= 1;
4249 subtype = 0;
4250 goto dostr;
4251 case CTLBACKQ:
4252 str = "$(...)";
4253 goto dostr;
4254 case CTLBACKQ+CTLQUOTE:
4255 str = "\"$(...)\"";
4256 goto dostr;
Mike Frysinger98c52642009-04-02 10:02:37 +00004257#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004258 case CTLARI:
4259 str = "$((";
4260 goto dostr;
4261 case CTLENDARI:
4262 str = "))";
4263 goto dostr;
4264#endif
4265 case CTLQUOTEMARK:
4266 quoted ^= 1;
4267 c = '"';
4268 break;
4269 case '=':
4270 if (subtype == 0)
4271 break;
4272 if ((subtype & VSTYPE) != VSNORMAL)
4273 quoted <<= 1;
4274 str = vstype[subtype & VSTYPE];
4275 if (subtype & VSNUL)
4276 c = ':';
4277 else
4278 goto checkstr;
4279 break;
4280 case '\'':
4281 case '\\':
4282 case '"':
4283 case '$':
4284 /* These can only happen inside quotes */
4285 cc[0] = c;
4286 str = cc;
4287 c = '\\';
4288 break;
4289 default:
4290 break;
4291 }
4292 USTPUTC(c, nextc);
4293 checkstr:
4294 if (!str)
4295 continue;
4296 dostr:
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02004297 while ((c = *str++) != '\0') {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004298 USTPUTC(c, nextc);
4299 }
Denys Vlasenko46a14772009-12-10 21:27:13 +01004300 } /* while *p++ not NUL */
4301
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004302 if (quoted & 1) {
4303 USTPUTC('"', nextc);
4304 }
4305 *nextc = 0;
4306 cmdnextc = nextc;
4307}
4308
4309/* cmdtxt() and cmdlist() call each other */
4310static void cmdtxt(union node *n);
4311
4312static void
4313cmdlist(union node *np, int sep)
4314{
4315 for (; np; np = np->narg.next) {
4316 if (!sep)
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00004317 cmdputs(" ");
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004318 cmdtxt(np);
4319 if (sep && np->narg.next)
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00004320 cmdputs(" ");
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004321 }
4322}
4323
4324static void
4325cmdtxt(union node *n)
4326{
4327 union node *np;
4328 struct nodelist *lp;
4329 const char *p;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004330
4331 if (!n)
4332 return;
4333 switch (n->type) {
4334 default:
4335#if DEBUG
4336 abort();
4337#endif
4338 case NPIPE:
4339 lp = n->npipe.cmdlist;
4340 for (;;) {
4341 cmdtxt(lp->n);
4342 lp = lp->next;
4343 if (!lp)
4344 break;
4345 cmdputs(" | ");
4346 }
4347 break;
4348 case NSEMI:
4349 p = "; ";
4350 goto binop;
4351 case NAND:
4352 p = " && ";
4353 goto binop;
4354 case NOR:
4355 p = " || ";
4356 binop:
4357 cmdtxt(n->nbinary.ch1);
4358 cmdputs(p);
4359 n = n->nbinary.ch2;
4360 goto donode;
4361 case NREDIR:
4362 case NBACKGND:
4363 n = n->nredir.n;
4364 goto donode;
4365 case NNOT:
4366 cmdputs("!");
4367 n = n->nnot.com;
4368 donode:
4369 cmdtxt(n);
4370 break;
4371 case NIF:
4372 cmdputs("if ");
4373 cmdtxt(n->nif.test);
4374 cmdputs("; then ");
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004375 if (n->nif.elsepart) {
Denys Vlasenko7cee00e2009-07-24 01:08:03 +02004376 cmdtxt(n->nif.ifpart);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004377 cmdputs("; else ");
4378 n = n->nif.elsepart;
Denys Vlasenko7cee00e2009-07-24 01:08:03 +02004379 } else {
4380 n = n->nif.ifpart;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004381 }
4382 p = "; fi";
4383 goto dotail;
4384 case NSUBSHELL:
4385 cmdputs("(");
4386 n = n->nredir.n;
4387 p = ")";
4388 goto dotail;
4389 case NWHILE:
4390 p = "while ";
4391 goto until;
4392 case NUNTIL:
4393 p = "until ";
4394 until:
4395 cmdputs(p);
4396 cmdtxt(n->nbinary.ch1);
4397 n = n->nbinary.ch2;
4398 p = "; done";
4399 dodo:
4400 cmdputs("; do ");
4401 dotail:
4402 cmdtxt(n);
4403 goto dotail2;
4404 case NFOR:
4405 cmdputs("for ");
4406 cmdputs(n->nfor.var);
4407 cmdputs(" in ");
4408 cmdlist(n->nfor.args, 1);
4409 n = n->nfor.body;
4410 p = "; done";
4411 goto dodo;
4412 case NDEFUN:
4413 cmdputs(n->narg.text);
4414 p = "() { ... }";
4415 goto dotail2;
4416 case NCMD:
4417 cmdlist(n->ncmd.args, 1);
4418 cmdlist(n->ncmd.redirect, 0);
4419 break;
4420 case NARG:
4421 p = n->narg.text;
4422 dotail2:
4423 cmdputs(p);
4424 break;
4425 case NHERE:
4426 case NXHERE:
4427 p = "<<...";
4428 goto dotail2;
4429 case NCASE:
4430 cmdputs("case ");
4431 cmdputs(n->ncase.expr->narg.text);
4432 cmdputs(" in ");
4433 for (np = n->ncase.cases; np; np = np->nclist.next) {
4434 cmdtxt(np->nclist.pattern);
4435 cmdputs(") ");
4436 cmdtxt(np->nclist.body);
4437 cmdputs(";; ");
4438 }
4439 p = "esac";
4440 goto dotail2;
4441 case NTO:
4442 p = ">";
4443 goto redir;
4444 case NCLOBBER:
4445 p = ">|";
4446 goto redir;
4447 case NAPPEND:
4448 p = ">>";
4449 goto redir;
Denis Vlasenko559691a2008-10-05 18:39:31 +00004450#if ENABLE_ASH_BASH_COMPAT
4451 case NTO2:
4452#endif
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004453 case NTOFD:
4454 p = ">&";
4455 goto redir;
4456 case NFROM:
4457 p = "<";
4458 goto redir;
4459 case NFROMFD:
4460 p = "<&";
4461 goto redir;
4462 case NFROMTO:
4463 p = "<>";
4464 redir:
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00004465 cmdputs(utoa(n->nfile.fd));
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004466 cmdputs(p);
4467 if (n->type == NTOFD || n->type == NFROMFD) {
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00004468 cmdputs(utoa(n->ndup.dupfd));
4469 break;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004470 }
4471 n = n->nfile.fname;
4472 goto donode;
4473 }
4474}
4475
4476static char *
4477commandtext(union node *n)
4478{
4479 char *name;
4480
4481 STARTSTACKSTR(cmdnextc);
4482 cmdtxt(n);
4483 name = stackblock();
4484 TRACE(("commandtext: name %p, end %p\n\t\"%s\"\n",
4485 name, cmdnextc, cmdnextc));
4486 return ckstrdup(name);
4487}
4488#endif /* JOBS */
4489
4490/*
4491 * Fork off a subshell. If we are doing job control, give the subshell its
4492 * own process group. Jp is a job structure that the job is to be added to.
4493 * N is the command that will be evaluated by the child. Both jp and n may
4494 * be NULL. The mode parameter can be one of the following:
4495 * FORK_FG - Fork off a foreground process.
4496 * FORK_BG - Fork off a background process.
4497 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
4498 * process group even if job control is on.
4499 *
4500 * When job control is turned off, background processes have their standard
4501 * input redirected to /dev/null (except for the second and later processes
4502 * in a pipeline).
4503 *
4504 * Called with interrupts off.
4505 */
4506/*
4507 * Clear traps on a fork.
4508 */
4509static void
4510clear_traps(void)
4511{
4512 char **tp;
4513
4514 for (tp = trap; tp < &trap[NSIG]; tp++) {
Denis Vlasenko991a1da2008-02-10 19:02:53 +00004515 if (*tp && **tp) { /* trap not NULL or "" (SIG_IGN) */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004516 INT_OFF;
Denys Vlasenkoe305c282009-09-25 02:12:27 +02004517 if (trap_ptr == trap)
4518 free(*tp);
4519 /* else: it "belongs" to trap_ptr vector, don't free */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004520 *tp = NULL;
Denys Vlasenko0800e3a2009-09-24 03:09:26 +02004521 if ((tp - trap) != 0)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004522 setsignal(tp - trap);
4523 INT_ON;
4524 }
4525 }
4526}
Denis Vlasenkobdc406d2007-07-15 01:13:25 +00004527
4528/* Lives far away from here, needed for forkchild */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004529static void closescript(void);
Denis Vlasenko41770222007-10-07 18:02:52 +00004530
Denis Vlasenkobdc406d2007-07-15 01:13:25 +00004531/* Called after fork(), in child */
Denys Vlasenko21d87d42009-09-25 00:06:51 +02004532static NOINLINE void
Denys Vlasenkoe56f22a2009-07-24 00:16:59 +02004533forkchild(struct job *jp, union node *n, int mode)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004534{
4535 int oldlvl;
4536
4537 TRACE(("Child shell %d\n", getpid()));
4538 oldlvl = shlvl;
4539 shlvl++;
4540
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004541 /* man bash: "Non-builtin commands run by bash have signal handlers
4542 * set to the values inherited by the shell from its parent".
4543 * Do we do it correctly? */
4544
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004545 closescript();
Denys Vlasenko844f9902009-09-23 03:25:52 +02004546
4547 if (mode == FORK_NOJOB /* is it `xxx` ? */
4548 && n && n->type == NCMD /* is it single cmd? */
4549 /* && n->ncmd.args->type == NARG - always true? */
Denys Vlasenko74269202010-02-21 01:26:42 +01004550 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "trap") == 0
Denys Vlasenko844f9902009-09-23 03:25:52 +02004551 && n->ncmd.args->narg.next == NULL /* "trap" with no arguments */
4552 /* && n->ncmd.args->narg.backquote == NULL - do we need to check this? */
4553 ) {
4554 TRACE(("Trap hack\n"));
4555 /* Awful hack for `trap` or $(trap).
4556 *
4557 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
4558 * contains an example where "trap" is executed in a subshell:
4559 *
4560 * save_traps=$(trap)
4561 * ...
4562 * eval "$save_traps"
4563 *
4564 * Standard does not say that "trap" in subshell shall print
4565 * parent shell's traps. It only says that its output
4566 * must have suitable form, but then, in the above example
4567 * (which is not supposed to be normative), it implies that.
4568 *
4569 * bash (and probably other shell) does implement it
4570 * (traps are reset to defaults, but "trap" still shows them),
4571 * but as a result, "trap" logic is hopelessly messed up:
4572 *
4573 * # trap
4574 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
4575 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
4576 * # true | trap <--- trap is in subshell - no output (ditto)
4577 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
4578 * trap -- 'echo Ho' SIGWINCH
4579 * # echo `(trap)` <--- in subshell in subshell - output
4580 * trap -- 'echo Ho' SIGWINCH
4581 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
4582 * trap -- 'echo Ho' SIGWINCH
4583 *
4584 * The rules when to forget and when to not forget traps
4585 * get really complex and nonsensical.
4586 *
4587 * Our solution: ONLY bare $(trap) or `trap` is special.
4588 */
Denys Vlasenko8f88d852009-09-25 12:12:53 +02004589 /* Save trap handler strings for trap builtin to print */
Denys Vlasenko21d87d42009-09-25 00:06:51 +02004590 trap_ptr = memcpy(xmalloc(sizeof(trap)), trap, sizeof(trap));
Denys Vlasenko8f88d852009-09-25 12:12:53 +02004591 /* Fall through into clearing traps */
Denys Vlasenko844f9902009-09-23 03:25:52 +02004592 }
Denys Vlasenkoe305c282009-09-25 02:12:27 +02004593 clear_traps();
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004594#if JOBS
4595 /* do job control only in root shell */
Denis Vlasenkob07a4962008-06-22 13:16:23 +00004596 doing_jobctl = 0;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004597 if (mode != FORK_NOJOB && jp->jobctl && !oldlvl) {
4598 pid_t pgrp;
4599
4600 if (jp->nprocs == 0)
4601 pgrp = getpid();
4602 else
Denys Vlasenko285ad152009-12-04 23:02:27 +01004603 pgrp = jp->ps[0].ps_pid;
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004604 /* this can fail because we are doing it in the parent also */
4605 setpgid(0, pgrp);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004606 if (mode == FORK_FG)
4607 xtcsetpgrp(ttyfd, pgrp);
4608 setsignal(SIGTSTP);
4609 setsignal(SIGTTOU);
4610 } else
4611#endif
4612 if (mode == FORK_BG) {
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004613 /* man bash: "When job control is not in effect,
4614 * asynchronous commands ignore SIGINT and SIGQUIT" */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004615 ignoresig(SIGINT);
4616 ignoresig(SIGQUIT);
4617 if (jp->nprocs == 0) {
4618 close(0);
4619 if (open(bb_dev_null, O_RDONLY) != 0)
Denis Vlasenko9604e1b2009-03-03 18:47:56 +00004620 ash_msg_and_raise_error("can't open '%s'", bb_dev_null);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004621 }
4622 }
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004623 if (!oldlvl) {
4624 if (iflag) { /* why if iflag only? */
4625 setsignal(SIGINT);
4626 setsignal(SIGTERM);
4627 }
4628 /* man bash:
4629 * "In all cases, bash ignores SIGQUIT. Non-builtin
4630 * commands run by bash have signal handlers
4631 * set to the values inherited by the shell
4632 * from its parent".
4633 * Take care of the second rule: */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004634 setsignal(SIGQUIT);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004635 }
Denys Vlasenkoe56f22a2009-07-24 00:16:59 +02004636#if JOBS
Denys Vlasenko844f9902009-09-23 03:25:52 +02004637 if (n && n->type == NCMD
Denys Vlasenko74269202010-02-21 01:26:42 +01004638 && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "jobs") == 0
Denys Vlasenko844f9902009-09-23 03:25:52 +02004639 ) {
Denys Vlasenkoe56f22a2009-07-24 00:16:59 +02004640 TRACE(("Job hack\n"));
Denys Vlasenko844f9902009-09-23 03:25:52 +02004641 /* "jobs": we do not want to clear job list for it,
4642 * instead we remove only _its_ own_ job from job list.
4643 * This makes "jobs .... | cat" more useful.
4644 */
Denys Vlasenkoe56f22a2009-07-24 00:16:59 +02004645 freejob(curjob);
4646 return;
4647 }
4648#endif
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004649 for (jp = curjob; jp; jp = jp->prev_job)
4650 freejob(jp);
4651 jobless = 0;
4652}
4653
Denis Vlasenkobdc406d2007-07-15 01:13:25 +00004654/* Called after fork(), in parent */
Denis Vlasenko85c24712008-03-17 09:04:04 +00004655#if !JOBS
4656#define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
4657#endif
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004658static void
4659forkparent(struct job *jp, union node *n, int mode, pid_t pid)
4660{
4661 TRACE(("In parent shell: child = %d\n", pid));
4662 if (!jp) {
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00004663 while (jobless && dowait(DOWAIT_NONBLOCK, NULL) > 0)
4664 continue;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004665 jobless++;
4666 return;
4667 }
4668#if JOBS
4669 if (mode != FORK_NOJOB && jp->jobctl) {
4670 int pgrp;
4671
4672 if (jp->nprocs == 0)
4673 pgrp = pid;
4674 else
Denys Vlasenko285ad152009-12-04 23:02:27 +01004675 pgrp = jp->ps[0].ps_pid;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004676 /* This can fail because we are doing it in the child also */
4677 setpgid(pid, pgrp);
4678 }
4679#endif
4680 if (mode == FORK_BG) {
4681 backgndpid = pid; /* set $! */
4682 set_curjob(jp, CUR_RUNNING);
4683 }
4684 if (jp) {
4685 struct procstat *ps = &jp->ps[jp->nprocs++];
Denys Vlasenko285ad152009-12-04 23:02:27 +01004686 ps->ps_pid = pid;
4687 ps->ps_status = -1;
4688 ps->ps_cmd = nullstr;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004689#if JOBS
Denis Vlasenkob07a4962008-06-22 13:16:23 +00004690 if (doing_jobctl && n)
Denys Vlasenko285ad152009-12-04 23:02:27 +01004691 ps->ps_cmd = commandtext(n);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004692#endif
4693 }
4694}
4695
4696static int
4697forkshell(struct job *jp, union node *n, int mode)
4698{
4699 int pid;
4700
4701 TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
4702 pid = fork();
4703 if (pid < 0) {
4704 TRACE(("Fork failed, errno=%d", errno));
4705 if (jp)
4706 freejob(jp);
Denis Vlasenkofa0b56d2008-07-01 16:09:07 +00004707 ash_msg_and_raise_error("can't fork");
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004708 }
Denys Vlasenko76ace252009-10-12 15:25:01 +02004709 if (pid == 0) {
4710 CLEAR_RANDOM_T(&random_gen); /* or else $RANDOM repeats in child */
Denys Vlasenkoe56f22a2009-07-24 00:16:59 +02004711 forkchild(jp, n, mode);
Denys Vlasenko76ace252009-10-12 15:25:01 +02004712 } else {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004713 forkparent(jp, n, mode, pid);
Denys Vlasenko76ace252009-10-12 15:25:01 +02004714 }
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004715 return pid;
4716}
4717
4718/*
4719 * Wait for job to finish.
4720 *
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004721 * Under job control we have the problem that while a child process
4722 * is running interrupts generated by the user are sent to the child
4723 * but not to the shell. This means that an infinite loop started by
4724 * an interactive user may be hard to kill. With job control turned off,
4725 * an interactive user may place an interactive program inside a loop.
4726 * If the interactive program catches interrupts, the user doesn't want
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004727 * these interrupts to also abort the loop. The approach we take here
4728 * is to have the shell ignore interrupt signals while waiting for a
4729 * foreground process to terminate, and then send itself an interrupt
4730 * signal if the child process was terminated by an interrupt signal.
4731 * Unfortunately, some programs want to do a bit of cleanup and then
4732 * exit on interrupt; unless these processes terminate themselves by
4733 * sending a signal to themselves (instead of calling exit) they will
4734 * confuse this approach.
4735 *
4736 * Called with interrupts off.
4737 */
4738static int
4739waitforjob(struct job *jp)
4740{
4741 int st;
4742
4743 TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004744
4745 INT_OFF;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004746 while (jp->state == JOBRUNNING) {
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004747 /* In non-interactive shells, we _can_ get
4748 * a keyboard signal here and be EINTRed,
4749 * but we just loop back, waiting for command to complete.
4750 *
4751 * man bash:
4752 * "If bash is waiting for a command to complete and receives
4753 * a signal for which a trap has been set, the trap
4754 * will not be executed until the command completes."
4755 *
4756 * Reality is that even if trap is not set, bash
4757 * will not act on the signal until command completes.
4758 * Try this. sleep5intoff.c:
4759 * #include <signal.h>
4760 * #include <unistd.h>
4761 * int main() {
4762 * sigset_t set;
4763 * sigemptyset(&set);
4764 * sigaddset(&set, SIGINT);
4765 * sigaddset(&set, SIGQUIT);
4766 * sigprocmask(SIG_BLOCK, &set, NULL);
4767 * sleep(5);
4768 * return 0;
4769 * }
4770 * $ bash -c './sleep5intoff; echo hi'
4771 * ^C^C^C^C <--- pressing ^C once a second
4772 * $ _
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004773 * $ bash -c './sleep5intoff; echo hi'
4774 * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
4775 * $ _
4776 */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004777 dowait(DOWAIT_BLOCK, jp);
4778 }
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004779 INT_ON;
4780
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004781 st = getstatus(jp);
4782#if JOBS
4783 if (jp->jobctl) {
4784 xtcsetpgrp(ttyfd, rootpid);
4785 /*
4786 * This is truly gross.
4787 * If we're doing job control, then we did a TIOCSPGRP which
4788 * caused us (the shell) to no longer be in the controlling
4789 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
4790 * intuit from the subprocess exit status whether a SIGINT
4791 * occurred, and if so interrupt ourselves. Yuck. - mycroft
4792 */
Denis Vlasenko991a1da2008-02-10 19:02:53 +00004793 if (jp->sigint) /* TODO: do the same with all signals */
4794 raise(SIGINT); /* ... by raise(jp->sig) instead? */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004795 }
4796 if (jp->state == JOBDONE)
4797#endif
4798 freejob(jp);
4799 return st;
4800}
4801
4802/*
4803 * return 1 if there are stopped jobs, otherwise 0
4804 */
4805static int
4806stoppedjobs(void)
4807{
4808 struct job *jp;
4809 int retval;
4810
4811 retval = 0;
4812 if (job_warning)
4813 goto out;
4814 jp = curjob;
4815 if (jp && jp->state == JOBSTOPPED) {
4816 out2str("You have stopped jobs.\n");
4817 job_warning = 2;
4818 retval++;
4819 }
4820 out:
4821 return retval;
4822}
4823
4824
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004825/* ============ redir.c
4826 *
4827 * Code for dealing with input/output redirection.
4828 */
4829
4830#define EMPTY -2 /* marks an unused slot in redirtab */
Denis Vlasenko7d75a962007-11-22 08:16:57 +00004831#define CLOSED -3 /* marks a slot of previously-closed fd */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004832
4833/*
4834 * Open a file in noclobber mode.
4835 * The code was copied from bash.
4836 */
4837static int
4838noclobberopen(const char *fname)
4839{
4840 int r, fd;
4841 struct stat finfo, finfo2;
4842
4843 /*
4844 * If the file exists and is a regular file, return an error
4845 * immediately.
4846 */
4847 r = stat(fname, &finfo);
4848 if (r == 0 && S_ISREG(finfo.st_mode)) {
4849 errno = EEXIST;
4850 return -1;
4851 }
4852
4853 /*
4854 * If the file was not present (r != 0), make sure we open it
4855 * exclusively so that if it is created before we open it, our open
4856 * will fail. Make sure that we do not truncate an existing file.
4857 * Note that we don't turn on O_EXCL unless the stat failed -- if the
4858 * file was not a regular file, we leave O_EXCL off.
4859 */
4860 if (r != 0)
4861 return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
4862 fd = open(fname, O_WRONLY|O_CREAT, 0666);
4863
4864 /* If the open failed, return the file descriptor right away. */
4865 if (fd < 0)
4866 return fd;
4867
4868 /*
4869 * OK, the open succeeded, but the file may have been changed from a
4870 * non-regular file to a regular file between the stat and the open.
4871 * We are assuming that the O_EXCL open handles the case where FILENAME
4872 * did not exist and is symlinked to an existing file between the stat
4873 * and open.
4874 */
4875
4876 /*
4877 * If we can open it and fstat the file descriptor, and neither check
4878 * revealed that it was a regular file, and the file has not been
4879 * replaced, return the file descriptor.
4880 */
4881 if (fstat(fd, &finfo2) == 0 && !S_ISREG(finfo2.st_mode)
4882 && finfo.st_dev == finfo2.st_dev && finfo.st_ino == finfo2.st_ino)
4883 return fd;
4884
4885 /* The file has been replaced. badness. */
4886 close(fd);
4887 errno = EEXIST;
4888 return -1;
4889}
4890
4891/*
4892 * Handle here documents. Normally we fork off a process to write the
4893 * data to a pipe. If the document is short, we can stuff the data in
4894 * the pipe without forking.
4895 */
4896/* openhere needs this forward reference */
4897static void expandhere(union node *arg, int fd);
4898static int
4899openhere(union node *redir)
4900{
4901 int pip[2];
4902 size_t len = 0;
4903
4904 if (pipe(pip) < 0)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00004905 ash_msg_and_raise_error("pipe call failed");
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004906 if (redir->type == NHERE) {
4907 len = strlen(redir->nhere.doc->narg.text);
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00004908 if (len <= PIPE_BUF) {
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004909 full_write(pip[1], redir->nhere.doc->narg.text, len);
4910 goto out;
4911 }
4912 }
4913 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
Denis Vlasenko0b769642008-07-24 07:54:57 +00004914 /* child */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004915 close(pip[0]);
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004916 ignoresig(SIGINT); //signal(SIGINT, SIG_IGN);
4917 ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
4918 ignoresig(SIGHUP); //signal(SIGHUP, SIG_IGN);
4919 ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004920 signal(SIGPIPE, SIG_DFL);
4921 if (redir->type == NHERE)
4922 full_write(pip[1], redir->nhere.doc->narg.text, len);
Denis Vlasenko0b769642008-07-24 07:54:57 +00004923 else /* NXHERE */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004924 expandhere(redir->nhere.doc, pip[1]);
Bernhard Reutner-Fischer636a1f82008-05-19 09:29:47 +00004925 _exit(EXIT_SUCCESS);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004926 }
4927 out:
4928 close(pip[1]);
4929 return pip[0];
4930}
4931
4932static int
4933openredirect(union node *redir)
4934{
4935 char *fname;
4936 int f;
4937
4938 switch (redir->nfile.type) {
4939 case NFROM:
4940 fname = redir->nfile.expfname;
4941 f = open(fname, O_RDONLY);
4942 if (f < 0)
4943 goto eopen;
4944 break;
4945 case NFROMTO:
4946 fname = redir->nfile.expfname;
4947 f = open(fname, O_RDWR|O_CREAT|O_TRUNC, 0666);
4948 if (f < 0)
4949 goto ecreate;
4950 break;
4951 case NTO:
Denis Vlasenko559691a2008-10-05 18:39:31 +00004952#if ENABLE_ASH_BASH_COMPAT
4953 case NTO2:
4954#endif
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004955 /* Take care of noclobber mode. */
4956 if (Cflag) {
4957 fname = redir->nfile.expfname;
4958 f = noclobberopen(fname);
4959 if (f < 0)
4960 goto ecreate;
4961 break;
4962 }
4963 /* FALLTHROUGH */
4964 case NCLOBBER:
4965 fname = redir->nfile.expfname;
4966 f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
4967 if (f < 0)
4968 goto ecreate;
4969 break;
4970 case NAPPEND:
4971 fname = redir->nfile.expfname;
4972 f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
4973 if (f < 0)
4974 goto ecreate;
4975 break;
4976 default:
4977#if DEBUG
4978 abort();
4979#endif
4980 /* Fall through to eliminate warning. */
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00004981/* Our single caller does this itself */
Denis Vlasenko0b769642008-07-24 07:54:57 +00004982// case NTOFD:
4983// case NFROMFD:
4984// f = -1;
4985// break;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004986 case NHERE:
4987 case NXHERE:
4988 f = openhere(redir);
4989 break;
4990 }
4991
4992 return f;
4993 ecreate:
Bernhard Reutner-Fischera53de7f2008-07-21 13:46:54 +00004994 ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004995 eopen:
Bernhard Reutner-Fischera53de7f2008-07-21 13:46:54 +00004996 ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004997}
4998
4999/*
5000 * Copy a file descriptor to be >= to. Returns -1
5001 * if the source file descriptor is closed, EMPTY if there are no unused
5002 * file descriptors left.
5003 */
Denis Vlasenko5a867312008-07-24 19:46:38 +00005004/* 0x800..00: bit to set in "to" to request dup2 instead of fcntl(F_DUPFD).
5005 * old code was doing close(to) prior to copyfd() to achieve the same */
Denis Vlasenko22f74142008-07-24 22:34:43 +00005006enum {
5007 COPYFD_EXACT = (int)~(INT_MAX),
5008 COPYFD_RESTORE = (int)((unsigned)COPYFD_EXACT >> 1),
5009};
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005010static int
5011copyfd(int from, int to)
5012{
5013 int newfd;
5014
Denis Vlasenko5a867312008-07-24 19:46:38 +00005015 if (to & COPYFD_EXACT) {
5016 to &= ~COPYFD_EXACT;
5017 /*if (from != to)*/
5018 newfd = dup2(from, to);
5019 } else {
5020 newfd = fcntl(from, F_DUPFD, to);
5021 }
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005022 if (newfd < 0) {
5023 if (errno == EMFILE)
5024 return EMPTY;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005025 /* Happens when source fd is not open: try "echo >&99" */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005026 ash_msg_and_raise_error("%d: %m", from);
5027 }
5028 return newfd;
5029}
5030
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005031/* Struct def and variable are moved down to the first usage site */
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005032struct two_fd_t {
5033 int orig, copy;
5034};
Denis Vlasenko0b769642008-07-24 07:54:57 +00005035struct redirtab {
5036 struct redirtab *next;
Denis Vlasenko0b769642008-07-24 07:54:57 +00005037 int nullredirs;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005038 int pair_count;
Denys Vlasenko606291b2009-09-23 23:15:43 +02005039 struct two_fd_t two_fd[];
Denis Vlasenko0b769642008-07-24 07:54:57 +00005040};
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005041#define redirlist (G_var.redirlist)
Denis Vlasenko0b769642008-07-24 07:54:57 +00005042
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005043static int need_to_remember(struct redirtab *rp, int fd)
5044{
5045 int i;
5046
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005047 if (!rp) /* remembering was not requested */
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005048 return 0;
5049
5050 for (i = 0; i < rp->pair_count; i++) {
5051 if (rp->two_fd[i].orig == fd) {
5052 /* already remembered */
5053 return 0;
5054 }
5055 }
5056 return 1;
5057}
5058
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005059/* "hidden" fd is a fd used to read scripts, or a copy of such */
5060static int is_hidden_fd(struct redirtab *rp, int fd)
5061{
5062 int i;
Denis Vlasenko34c73c42008-08-16 11:48:02 +00005063 struct parsefile *pf;
5064
5065 if (fd == -1)
5066 return 0;
Denys Vlasenko08d8b3c2010-06-03 04:28:28 +02005067 /* Check open scripts' fds */
Denis Vlasenko34c73c42008-08-16 11:48:02 +00005068 pf = g_parsefile;
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005069 while (pf) {
Denys Vlasenko79b3d422010-06-03 04:29:08 +02005070 /* We skip pf_fd == 0 case because of the following case:
Denys Vlasenko08d8b3c2010-06-03 04:28:28 +02005071 * $ ash # running ash interactively
5072 * $ . ./script.sh
5073 * and in script.sh: "exec 9>&0".
Denys Vlasenko79b3d422010-06-03 04:29:08 +02005074 * Even though top-level pf_fd _is_ 0,
Denys Vlasenko08d8b3c2010-06-03 04:28:28 +02005075 * it's still ok to use it: "read" builtin uses it,
5076 * why should we cripple "exec" builtin?
5077 */
Denys Vlasenko79b3d422010-06-03 04:29:08 +02005078 if (pf->pf_fd > 0 && fd == pf->pf_fd) {
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005079 return 1;
5080 }
5081 pf = pf->prev;
5082 }
Denys Vlasenko08d8b3c2010-06-03 04:28:28 +02005083
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005084 if (!rp)
5085 return 0;
Denys Vlasenko08d8b3c2010-06-03 04:28:28 +02005086 /* Check saved fds of redirects */
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005087 fd |= COPYFD_RESTORE;
5088 for (i = 0; i < rp->pair_count; i++) {
5089 if (rp->two_fd[i].copy == fd) {
5090 return 1;
5091 }
5092 }
5093 return 0;
5094}
5095
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005096/*
5097 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
5098 * old file descriptors are stashed away so that the redirection can be
Denys Vlasenko08d8b3c2010-06-03 04:28:28 +02005099 * undone by calling popredir.
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005100 */
5101/* flags passed to redirect */
5102#define REDIR_PUSH 01 /* save previous values of file descriptors */
5103#define REDIR_SAVEFD2 03 /* set preverrout */
5104static void
5105redirect(union node *redir, int flags)
5106{
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005107 struct redirtab *sv;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005108 int sv_pos;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005109 int i;
5110 int fd;
5111 int newfd;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005112 int copied_fd2 = -1;
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005113
Denis Vlasenko01631112007-12-16 17:20:38 +00005114 g_nullredirs++;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005115 if (!redir) {
5116 return;
5117 }
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005118
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005119 sv = NULL;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005120 sv_pos = 0;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005121 INT_OFF;
5122 if (flags & REDIR_PUSH) {
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005123 union node *tmp = redir;
5124 do {
5125 sv_pos++;
Denis Vlasenko559691a2008-10-05 18:39:31 +00005126#if ENABLE_ASH_BASH_COMPAT
Chris Metcalfc3c1fb62010-01-08 13:18:06 +01005127 if (tmp->nfile.type == NTO2)
Denis Vlasenko559691a2008-10-05 18:39:31 +00005128 sv_pos++;
5129#endif
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005130 tmp = tmp->nfile.next;
5131 } while (tmp);
5132 sv = ckmalloc(sizeof(*sv) + sv_pos * sizeof(sv->two_fd[0]));
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005133 sv->next = redirlist;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005134 sv->pair_count = sv_pos;
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005135 redirlist = sv;
Denis Vlasenko01631112007-12-16 17:20:38 +00005136 sv->nullredirs = g_nullredirs - 1;
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005137 g_nullredirs = 0;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005138 while (sv_pos > 0) {
5139 sv_pos--;
5140 sv->two_fd[sv_pos].orig = sv->two_fd[sv_pos].copy = EMPTY;
5141 }
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005142 }
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005143
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005144 do {
Denys Vlasenko08d8b3c2010-06-03 04:28:28 +02005145 int right_fd = -1;
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00005146 fd = redir->nfile.fd;
Denis Vlasenko0b769642008-07-24 07:54:57 +00005147 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
Denys Vlasenko08d8b3c2010-06-03 04:28:28 +02005148 right_fd = redir->ndup.dupfd;
5149 //bb_error_msg("doing %d > %d", fd, right_fd);
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005150 /* redirect from/to same file descriptor? */
5151 if (right_fd == fd)
5152 continue;
Denys Vlasenko08d8b3c2010-06-03 04:28:28 +02005153 /* "echo >&10" and 10 is a fd opened to a sh script? */
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005154 if (is_hidden_fd(sv, right_fd)) {
5155 errno = EBADF; /* as if it is closed */
5156 ash_msg_and_raise_error("%d: %m", right_fd);
5157 }
Denis Vlasenko0b769642008-07-24 07:54:57 +00005158 newfd = -1;
5159 } else {
5160 newfd = openredirect(redir); /* always >= 0 */
5161 if (fd == newfd) {
5162 /* Descriptor wasn't open before redirect.
5163 * Mark it for close in the future */
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005164 if (need_to_remember(sv, fd)) {
Denis Vlasenko5a867312008-07-24 19:46:38 +00005165 goto remember_to_close;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005166 }
Denis Vlasenko0b769642008-07-24 07:54:57 +00005167 continue;
5168 }
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005169 }
Denis Vlasenko559691a2008-10-05 18:39:31 +00005170#if ENABLE_ASH_BASH_COMPAT
5171 redirect_more:
5172#endif
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005173 if (need_to_remember(sv, fd)) {
Denis Vlasenko0b769642008-07-24 07:54:57 +00005174 /* Copy old descriptor */
Denys Vlasenko08d8b3c2010-06-03 04:28:28 +02005175 /* Careful to not accidentally "save"
5176 * to the same fd as right side fd in N>&M */
5177 int minfd = right_fd < 10 ? 10 : right_fd + 1;
5178 i = fcntl(fd, F_DUPFD, minfd);
Denis Vlasenko5a867312008-07-24 19:46:38 +00005179/* You'd expect copy to be CLOEXECed. Currently these extra "saved" fds
5180 * are closed in popredir() in the child, preventing them from leaking
5181 * into child. (popredir() also cleans up the mess in case of failures)
5182 */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005183 if (i == -1) {
5184 i = errno;
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005185 if (i != EBADF) {
5186 /* Strange error (e.g. "too many files" EMFILE?) */
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005187 if (newfd >= 0)
5188 close(newfd);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005189 errno = i;
5190 ash_msg_and_raise_error("%d: %m", fd);
5191 /* NOTREACHED */
5192 }
Denis Vlasenko5a867312008-07-24 19:46:38 +00005193 /* EBADF: it is not open - good, remember to close it */
5194 remember_to_close:
5195 i = CLOSED;
Denis Vlasenko22f74142008-07-24 22:34:43 +00005196 } else { /* fd is open, save its copy */
5197 /* "exec fd>&-" should not close fds
5198 * which point to script file(s).
5199 * Force them to be restored afterwards */
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005200 if (is_hidden_fd(sv, fd))
5201 i |= COPYFD_RESTORE;
Denis Vlasenko22f74142008-07-24 22:34:43 +00005202 }
Denis Vlasenko5a867312008-07-24 19:46:38 +00005203 if (fd == 2)
5204 copied_fd2 = i;
5205 sv->two_fd[sv_pos].orig = fd;
5206 sv->two_fd[sv_pos].copy = i;
5207 sv_pos++;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005208 }
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005209 if (newfd < 0) {
5210 /* NTOFD/NFROMFD: copy redir->ndup.dupfd to fd */
Denis Vlasenko22f74142008-07-24 22:34:43 +00005211 if (redir->ndup.dupfd < 0) { /* "fd>&-" */
Denis Vlasenkob9e70dd2009-03-20 01:24:08 +00005212 /* Don't want to trigger debugging */
5213 if (fd != -1)
5214 close(fd);
Denis Vlasenko5a867312008-07-24 19:46:38 +00005215 } else {
5216 copyfd(redir->ndup.dupfd, fd | COPYFD_EXACT);
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005217 }
Denis Vlasenko5a867312008-07-24 19:46:38 +00005218 } else if (fd != newfd) { /* move newfd to fd */
5219 copyfd(newfd, fd | COPYFD_EXACT);
Denis Vlasenko559691a2008-10-05 18:39:31 +00005220#if ENABLE_ASH_BASH_COMPAT
5221 if (!(redir->nfile.type == NTO2 && fd == 2))
5222#endif
5223 close(newfd);
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005224 }
Denis Vlasenko559691a2008-10-05 18:39:31 +00005225#if ENABLE_ASH_BASH_COMPAT
5226 if (redir->nfile.type == NTO2 && fd == 1) {
5227 /* We already redirected it to fd 1, now copy it to 2 */
5228 newfd = 1;
5229 fd = 2;
5230 goto redirect_more;
5231 }
5232#endif
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00005233 } while ((redir = redir->nfile.next) != NULL);
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005234
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005235 INT_ON;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005236 if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
5237 preverrout_fd = copied_fd2;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005238}
5239
5240/*
5241 * Undo the effects of the last redirection.
5242 */
5243static void
Denis Vlasenko34c73c42008-08-16 11:48:02 +00005244popredir(int drop, int restore)
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005245{
5246 struct redirtab *rp;
5247 int i;
5248
Denis Vlasenko01631112007-12-16 17:20:38 +00005249 if (--g_nullredirs >= 0)
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005250 return;
5251 INT_OFF;
5252 rp = redirlist;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005253 for (i = 0; i < rp->pair_count; i++) {
5254 int fd = rp->two_fd[i].orig;
Denis Vlasenko22f74142008-07-24 22:34:43 +00005255 int copy = rp->two_fd[i].copy;
5256 if (copy == CLOSED) {
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005257 if (!drop)
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005258 close(fd);
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005259 continue;
5260 }
Denis Vlasenko22f74142008-07-24 22:34:43 +00005261 if (copy != EMPTY) {
Denis Vlasenko34c73c42008-08-16 11:48:02 +00005262 if (!drop || (restore && (copy & COPYFD_RESTORE))) {
Denis Vlasenko22f74142008-07-24 22:34:43 +00005263 copy &= ~COPYFD_RESTORE;
Denis Vlasenko5a867312008-07-24 19:46:38 +00005264 /*close(fd);*/
Denis Vlasenko22f74142008-07-24 22:34:43 +00005265 copyfd(copy, fd | COPYFD_EXACT);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005266 }
Denis Vlasenkob9e70dd2009-03-20 01:24:08 +00005267 close(copy & ~COPYFD_RESTORE);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005268 }
5269 }
5270 redirlist = rp->next;
Denis Vlasenko01631112007-12-16 17:20:38 +00005271 g_nullredirs = rp->nullredirs;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005272 free(rp);
5273 INT_ON;
5274}
5275
5276/*
5277 * Undo all redirections. Called on error or interrupt.
5278 */
5279
5280/*
5281 * Discard all saved file descriptors.
5282 */
5283static void
5284clearredir(int drop)
5285{
5286 for (;;) {
Denis Vlasenko01631112007-12-16 17:20:38 +00005287 g_nullredirs = 0;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005288 if (!redirlist)
5289 break;
Denis Vlasenko34c73c42008-08-16 11:48:02 +00005290 popredir(drop, /*restore:*/ 0);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005291 }
5292}
5293
5294static int
5295redirectsafe(union node *redir, int flags)
5296{
5297 int err;
5298 volatile int saveint;
5299 struct jmploc *volatile savehandler = exception_handler;
5300 struct jmploc jmploc;
5301
5302 SAVE_INT(saveint);
Denis Vlasenko5a867312008-07-24 19:46:38 +00005303 /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
5304 err = setjmp(jmploc.loc); // huh?? was = setjmp(jmploc.loc) * 2;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005305 if (!err) {
5306 exception_handler = &jmploc;
5307 redirect(redir, flags);
5308 }
5309 exception_handler = savehandler;
Denis Vlasenko7f88e342009-03-19 03:36:18 +00005310 if (err && exception_type != EXERROR)
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005311 longjmp(exception_handler->loc, 1);
5312 RESTORE_INT(saveint);
5313 return err;
5314}
5315
5316
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005317/* ============ Routines to expand arguments to commands
5318 *
5319 * We have to deal with backquotes, shell variables, and file metacharacters.
5320 */
5321
Mike Frysinger98c52642009-04-02 10:02:37 +00005322#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00005323static arith_t
5324ash_arith(const char *s)
5325{
5326 arith_eval_hooks_t math_hooks;
5327 arith_t result;
5328 int errcode = 0;
5329
5330 math_hooks.lookupvar = lookupvar;
Denys Vlasenko03dad222010-01-12 23:29:57 +01005331 math_hooks.setvar = setvar2;
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00005332 math_hooks.endofname = endofname;
5333
5334 INT_OFF;
5335 result = arith(s, &errcode, &math_hooks);
5336 if (errcode < 0) {
5337 if (errcode == -3)
5338 ash_msg_and_raise_error("exponent less than 0");
5339 if (errcode == -2)
5340 ash_msg_and_raise_error("divide by zero");
5341 if (errcode == -5)
5342 ash_msg_and_raise_error("expression recursion loop detected");
5343 raise_error_syntax(s);
5344 }
5345 INT_ON;
5346
5347 return result;
5348}
Denis Vlasenko448d30e2008-06-27 00:24:11 +00005349#endif
5350
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005351/*
5352 * expandarg flags
5353 */
5354#define EXP_FULL 0x1 /* perform word splitting & file globbing */
5355#define EXP_TILDE 0x2 /* do normal tilde expansion */
5356#define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
5357#define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
5358#define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
5359#define EXP_RECORD 0x20 /* need to record arguments for ifs breakup */
5360#define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
5361#define EXP_WORD 0x80 /* expand word in parameter expansion */
5362#define EXP_QWORD 0x100 /* expand word in quoted parameter expansion */
5363/*
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005364 * rmescape() flags
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005365 */
5366#define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
5367#define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
5368#define RMESCAPE_QUOTED 0x4 /* Remove CTLESC unless in quotes */
5369#define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
5370#define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
5371
5372/*
5373 * Structure specifying which parts of the string should be searched
5374 * for IFS characters.
5375 */
5376struct ifsregion {
5377 struct ifsregion *next; /* next region in list */
5378 int begoff; /* offset of start of region */
5379 int endoff; /* offset of end of region */
5380 int nulonly; /* search for nul bytes only */
5381};
5382
5383struct arglist {
5384 struct strlist *list;
5385 struct strlist **lastp;
5386};
5387
5388/* output of current string */
5389static char *expdest;
5390/* list of back quote expressions */
5391static struct nodelist *argbackq;
5392/* first struct in list of ifs regions */
5393static struct ifsregion ifsfirst;
5394/* last struct in list */
5395static struct ifsregion *ifslastp;
5396/* holds expanded arg list */
5397static struct arglist exparg;
5398
5399/*
5400 * Our own itoa().
5401 */
5402static int
5403cvtnum(arith_t num)
5404{
5405 int len;
5406
5407 expdest = makestrspace(32, expdest);
Mike Frysinger98c52642009-04-02 10:02:37 +00005408 len = fmtstr(expdest, 32, arith_t_fmt, num);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005409 STADJUST(len, expdest);
5410 return len;
5411}
5412
5413static size_t
5414esclen(const char *start, const char *p)
5415{
5416 size_t esc = 0;
5417
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005418 while (p > start && (unsigned char)*--p == CTLESC) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005419 esc++;
5420 }
5421 return esc;
5422}
5423
5424/*
5425 * Remove any CTLESC characters from a string.
5426 */
5427static char *
Denys Vlasenkob6c84342009-08-29 20:23:20 +02005428rmescapes(char *str, int flag)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005429{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00005430 static const char qchars[] ALIGN1 = { CTLESC, CTLQUOTEMARK, '\0' };
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00005431
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005432 char *p, *q, *r;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005433 unsigned inquotes;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005434 unsigned protect_against_glob;
5435 unsigned globbing;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005436
5437 p = strpbrk(str, qchars);
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005438 if (!p)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005439 return str;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005440
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005441 q = p;
5442 r = str;
5443 if (flag & RMESCAPE_ALLOC) {
5444 size_t len = p - str;
5445 size_t fulllen = len + strlen(p) + 1;
5446
5447 if (flag & RMESCAPE_GROW) {
Colin Watson3963d942010-04-26 14:21:27 +02005448 int strloc = str - (char *)stackblock();
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005449 r = makestrspace(fulllen, expdest);
Colin Watson3963d942010-04-26 14:21:27 +02005450 /* p and str may be invalidated by makestrspace */
5451 str = (char *)stackblock() + strloc;
5452 p = str + len;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005453 } else if (flag & RMESCAPE_HEAP) {
5454 r = ckmalloc(fulllen);
5455 } else {
5456 r = stalloc(fulllen);
5457 }
5458 q = r;
5459 if (len > 0) {
Denis Vlasenko29eb3592008-05-18 14:06:08 +00005460 q = (char *)memcpy(q, str, len) + len;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005461 }
5462 }
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005463
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005464 inquotes = (flag & RMESCAPE_QUOTED) ^ RMESCAPE_QUOTED;
5465 globbing = flag & RMESCAPE_GLOB;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005466 protect_against_glob = globbing;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005467 while (*p) {
Denys Vlasenkocd716832009-11-28 22:14:02 +01005468 if ((unsigned char)*p == CTLQUOTEMARK) {
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005469// TODO: if no RMESCAPE_QUOTED in flags, inquotes never becomes 0
5470// (alternates between RMESCAPE_QUOTED and ~RMESCAPE_QUOTED). Is it ok?
5471// Note: both inquotes and protect_against_glob only affect whether
5472// CTLESC,<ch> gets converted to <ch> or to \<ch>
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005473 inquotes = ~inquotes;
5474 p++;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005475 protect_against_glob = globbing;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005476 continue;
5477 }
5478 if (*p == '\\') {
5479 /* naked back slash */
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005480 protect_against_glob = 0;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005481 goto copy;
5482 }
Denys Vlasenkocd716832009-11-28 22:14:02 +01005483 if ((unsigned char)*p == CTLESC) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005484 p++;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005485 if (protect_against_glob && inquotes && *p != '/') {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005486 *q++ = '\\';
5487 }
5488 }
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005489 protect_against_glob = globbing;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005490 copy:
5491 *q++ = *p++;
5492 }
5493 *q = '\0';
5494 if (flag & RMESCAPE_GROW) {
5495 expdest = r;
5496 STADJUST(q - r + 1, expdest);
5497 }
5498 return r;
5499}
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005500#define pmatch(a, b) !fnmatch((a), (b), 0)
5501
5502/*
5503 * Prepare a pattern for a expmeta (internal glob(3)) call.
5504 *
5505 * Returns an stalloced string.
5506 */
5507static char *
5508preglob(const char *pattern, int quoted, int flag)
5509{
5510 flag |= RMESCAPE_GLOB;
5511 if (quoted) {
5512 flag |= RMESCAPE_QUOTED;
5513 }
Denys Vlasenkob6c84342009-08-29 20:23:20 +02005514 return rmescapes((char *)pattern, flag);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005515}
5516
5517/*
5518 * Put a string on the stack.
5519 */
5520static void
5521memtodest(const char *p, size_t len, int syntax, int quotes)
5522{
5523 char *q = expdest;
5524
Denys Vlasenkob6c84342009-08-29 20:23:20 +02005525 q = makestrspace(quotes ? len * 2 : len, q);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005526
5527 while (len--) {
Denys Vlasenkocd716832009-11-28 22:14:02 +01005528 unsigned char c = *p++;
5529 if (c == '\0')
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005530 continue;
Denys Vlasenkob6c84342009-08-29 20:23:20 +02005531 if (quotes) {
5532 int n = SIT(c, syntax);
5533 if (n == CCTL || n == CBACK)
5534 USTPUTC(CTLESC, q);
5535 }
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005536 USTPUTC(c, q);
5537 }
5538
5539 expdest = q;
5540}
5541
5542static void
5543strtodest(const char *p, int syntax, int quotes)
5544{
5545 memtodest(p, strlen(p), syntax, quotes);
5546}
5547
5548/*
5549 * Record the fact that we have to scan this region of the
5550 * string for IFS characters.
5551 */
5552static void
5553recordregion(int start, int end, int nulonly)
5554{
5555 struct ifsregion *ifsp;
5556
5557 if (ifslastp == NULL) {
5558 ifsp = &ifsfirst;
5559 } else {
5560 INT_OFF;
Denis Vlasenko597906c2008-02-20 16:38:54 +00005561 ifsp = ckzalloc(sizeof(*ifsp));
5562 /*ifsp->next = NULL; - ckzalloc did it */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005563 ifslastp->next = ifsp;
5564 INT_ON;
5565 }
5566 ifslastp = ifsp;
5567 ifslastp->begoff = start;
5568 ifslastp->endoff = end;
5569 ifslastp->nulonly = nulonly;
5570}
5571
5572static void
5573removerecordregions(int endoff)
5574{
5575 if (ifslastp == NULL)
5576 return;
5577
5578 if (ifsfirst.endoff > endoff) {
5579 while (ifsfirst.next != NULL) {
5580 struct ifsregion *ifsp;
5581 INT_OFF;
5582 ifsp = ifsfirst.next->next;
5583 free(ifsfirst.next);
5584 ifsfirst.next = ifsp;
5585 INT_ON;
5586 }
5587 if (ifsfirst.begoff > endoff)
5588 ifslastp = NULL;
5589 else {
5590 ifslastp = &ifsfirst;
5591 ifsfirst.endoff = endoff;
5592 }
5593 return;
5594 }
5595
5596 ifslastp = &ifsfirst;
5597 while (ifslastp->next && ifslastp->next->begoff < endoff)
5598 ifslastp=ifslastp->next;
5599 while (ifslastp->next != NULL) {
5600 struct ifsregion *ifsp;
5601 INT_OFF;
5602 ifsp = ifslastp->next->next;
5603 free(ifslastp->next);
5604 ifslastp->next = ifsp;
5605 INT_ON;
5606 }
5607 if (ifslastp->endoff > endoff)
5608 ifslastp->endoff = endoff;
5609}
5610
5611static char *
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005612exptilde(char *startp, char *p, int flags)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005613{
Denys Vlasenkocd716832009-11-28 22:14:02 +01005614 unsigned char c;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005615 char *name;
5616 struct passwd *pw;
5617 const char *home;
Denys Vlasenko1166d7b2009-09-16 16:20:31 +02005618 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005619 int startloc;
5620
5621 name = p + 1;
5622
5623 while ((c = *++p) != '\0') {
5624 switch (c) {
5625 case CTLESC:
5626 return startp;
5627 case CTLQUOTEMARK:
5628 return startp;
5629 case ':':
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005630 if (flags & EXP_VARTILDE)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005631 goto done;
5632 break;
5633 case '/':
5634 case CTLENDVAR:
5635 goto done;
5636 }
5637 }
5638 done:
5639 *p = '\0';
5640 if (*name == '\0') {
Denys Vlasenkoea8b2522010-06-02 12:57:26 +02005641 home = lookupvar("HOME");
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005642 } else {
5643 pw = getpwnam(name);
5644 if (pw == NULL)
5645 goto lose;
5646 home = pw->pw_dir;
5647 }
5648 if (!home || !*home)
5649 goto lose;
5650 *p = c;
5651 startloc = expdest - (char *)stackblock();
5652 strtodest(home, SQSYNTAX, quotes);
5653 recordregion(startloc, expdest - (char *)stackblock(), 0);
5654 return p;
5655 lose:
5656 *p = c;
5657 return startp;
5658}
5659
5660/*
5661 * Execute a command inside back quotes. If it's a builtin command, we
5662 * want to save its output in a block obtained from malloc. Otherwise
5663 * we fork off a subprocess and get the output of the command via a pipe.
5664 * Should be called with interrupts off.
5665 */
5666struct backcmd { /* result of evalbackcmd */
5667 int fd; /* file descriptor to read from */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005668 int nleft; /* number of chars in buffer */
Denis Vlasenkob07a4962008-06-22 13:16:23 +00005669 char *buf; /* buffer */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005670 struct job *jp; /* job structure for command */
5671};
5672
5673/* These forward decls are needed to use "eval" code for backticks handling: */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00005674static uint8_t back_exitstatus; /* exit status of backquoted command */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005675#define EV_EXIT 01 /* exit after evaluating tree */
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02005676static void evaltree(union node *, int);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005677
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02005678static void FAST_FUNC
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005679evalbackcmd(union node *n, struct backcmd *result)
5680{
5681 int saveherefd;
5682
5683 result->fd = -1;
5684 result->buf = NULL;
5685 result->nleft = 0;
5686 result->jp = NULL;
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00005687 if (n == NULL)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005688 goto out;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005689
5690 saveherefd = herefd;
5691 herefd = -1;
5692
5693 {
5694 int pip[2];
5695 struct job *jp;
5696
5697 if (pipe(pip) < 0)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00005698 ash_msg_and_raise_error("pipe call failed");
Denis Vlasenko68404f12008-03-17 09:00:54 +00005699 jp = makejob(/*n,*/ 1);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005700 if (forkshell(jp, n, FORK_NOJOB) == 0) {
5701 FORCE_INT_ON;
5702 close(pip[0]);
5703 if (pip[1] != 1) {
Denis Vlasenko5a867312008-07-24 19:46:38 +00005704 /*close(1);*/
5705 copyfd(pip[1], 1 | COPYFD_EXACT);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005706 close(pip[1]);
5707 }
5708 eflag = 0;
5709 evaltree(n, EV_EXIT); /* actually evaltreenr... */
5710 /* NOTREACHED */
5711 }
5712 close(pip[1]);
5713 result->fd = pip[0];
5714 result->jp = jp;
5715 }
5716 herefd = saveherefd;
5717 out:
5718 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
5719 result->fd, result->buf, result->nleft, result->jp));
5720}
5721
5722/*
5723 * Expand stuff in backwards quotes.
5724 */
5725static void
5726expbackq(union node *cmd, int quoted, int quotes)
5727{
5728 struct backcmd in;
5729 int i;
5730 char buf[128];
5731 char *p;
5732 char *dest;
5733 int startloc;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00005734 int syntax = quoted ? DQSYNTAX : BASESYNTAX;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005735 struct stackmark smark;
5736
5737 INT_OFF;
5738 setstackmark(&smark);
5739 dest = expdest;
5740 startloc = dest - (char *)stackblock();
5741 grabstackstr(dest);
5742 evalbackcmd(cmd, &in);
5743 popstackmark(&smark);
5744
5745 p = in.buf;
5746 i = in.nleft;
5747 if (i == 0)
5748 goto read;
5749 for (;;) {
5750 memtodest(p, i, syntax, quotes);
5751 read:
5752 if (in.fd < 0)
5753 break;
Denis Vlasenkoe376d452008-02-20 22:23:24 +00005754 i = nonblock_safe_read(in.fd, buf, sizeof(buf));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005755 TRACE(("expbackq: read returns %d\n", i));
5756 if (i <= 0)
5757 break;
5758 p = buf;
5759 }
5760
Denis Vlasenko60818682007-09-28 22:07:23 +00005761 free(in.buf);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005762 if (in.fd >= 0) {
5763 close(in.fd);
5764 back_exitstatus = waitforjob(in.jp);
5765 }
5766 INT_ON;
5767
5768 /* Eat all trailing newlines */
5769 dest = expdest;
5770 for (; dest > (char *)stackblock() && dest[-1] == '\n';)
5771 STUNPUTC(dest);
5772 expdest = dest;
5773
5774 if (quoted == 0)
5775 recordregion(startloc, dest - (char *)stackblock(), 0);
5776 TRACE(("evalbackq: size=%d: \"%.*s\"\n",
5777 (dest - (char *)stackblock()) - startloc,
5778 (dest - (char *)stackblock()) - startloc,
5779 stackblock() + startloc));
5780}
5781
Mike Frysinger98c52642009-04-02 10:02:37 +00005782#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005783/*
5784 * Expand arithmetic expression. Backup to start of expression,
5785 * evaluate, place result in (backed up) result, adjust string position.
5786 */
5787static void
5788expari(int quotes)
5789{
5790 char *p, *start;
5791 int begoff;
5792 int flag;
5793 int len;
5794
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00005795 /* ifsfree(); */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005796
5797 /*
5798 * This routine is slightly over-complicated for
5799 * efficiency. Next we scan backwards looking for the
5800 * start of arithmetic.
5801 */
5802 start = stackblock();
5803 p = expdest - 1;
5804 *p = '\0';
5805 p--;
5806 do {
5807 int esc;
5808
Denys Vlasenkocd716832009-11-28 22:14:02 +01005809 while ((unsigned char)*p != CTLARI) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005810 p--;
5811#if DEBUG
5812 if (p < start) {
5813 ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
5814 }
5815#endif
5816 }
5817
5818 esc = esclen(start, p);
5819 if (!(esc % 2)) {
5820 break;
5821 }
5822
5823 p -= esc + 1;
5824 } while (1);
5825
5826 begoff = p - start;
5827
5828 removerecordregions(begoff);
5829
5830 flag = p[1];
5831
5832 expdest = p;
5833
5834 if (quotes)
Denys Vlasenkob6c84342009-08-29 20:23:20 +02005835 rmescapes(p + 2, 0);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005836
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00005837 len = cvtnum(ash_arith(p + 2));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005838
5839 if (flag != '"')
5840 recordregion(begoff, begoff + len, 0);
5841}
5842#endif
5843
5844/* argstr needs it */
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005845static char *evalvar(char *p, int flags, struct strlist *var_str_list);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005846
5847/*
5848 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
5849 * characters to allow for further processing. Otherwise treat
5850 * $@ like $* since no splitting will be performed.
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00005851 *
5852 * var_str_list (can be NULL) is a list of "VAR=val" strings which take precedence
5853 * over shell varables. Needed for "A=a B=$A; echo $B" case - we use it
5854 * for correct expansion of "B=$A" word.
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005855 */
5856static void
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005857argstr(char *p, int flags, struct strlist *var_str_list)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005858{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00005859 static const char spclchars[] ALIGN1 = {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005860 '=',
5861 ':',
5862 CTLQUOTEMARK,
5863 CTLENDVAR,
5864 CTLESC,
5865 CTLVAR,
5866 CTLBACKQ,
5867 CTLBACKQ | CTLQUOTE,
Mike Frysinger98c52642009-04-02 10:02:37 +00005868#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005869 CTLENDARI,
5870#endif
Denys Vlasenkocd716832009-11-28 22:14:02 +01005871 '\0'
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005872 };
5873 const char *reject = spclchars;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005874 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR); /* do CTLESC */
5875 int breakall = flags & EXP_WORD;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005876 int inquotes;
5877 size_t length;
5878 int startloc;
5879
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005880 if (!(flags & EXP_VARTILDE)) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005881 reject += 2;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005882 } else if (flags & EXP_VARTILDE2) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005883 reject++;
5884 }
5885 inquotes = 0;
5886 length = 0;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005887 if (flags & EXP_TILDE) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005888 char *q;
5889
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005890 flags &= ~EXP_TILDE;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005891 tilde:
5892 q = p;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005893 if (*q == CTLESC && (flags & EXP_QWORD))
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005894 q++;
5895 if (*q == '~')
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005896 p = exptilde(p, q, flags);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005897 }
5898 start:
5899 startloc = expdest - (char *)stackblock();
5900 for (;;) {
Denys Vlasenkocd716832009-11-28 22:14:02 +01005901 unsigned char c;
5902
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005903 length += strcspn(p + length, reject);
Denys Vlasenkocd716832009-11-28 22:14:02 +01005904 c = p[length];
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005905 if (c) {
5906 if (!(c & 0x80)
Mike Frysinger98c52642009-04-02 10:02:37 +00005907#if ENABLE_SH_MATH_SUPPORT
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005908 || c == CTLENDARI
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005909#endif
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005910 ) {
5911 /* c == '=' || c == ':' || c == CTLENDARI */
5912 length++;
5913 }
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005914 }
5915 if (length > 0) {
5916 int newloc;
5917 expdest = stack_nputstr(p, length, expdest);
5918 newloc = expdest - (char *)stackblock();
5919 if (breakall && !inquotes && newloc > startloc) {
5920 recordregion(startloc, newloc, 0);
5921 }
5922 startloc = newloc;
5923 }
5924 p += length + 1;
5925 length = 0;
5926
5927 switch (c) {
5928 case '\0':
5929 goto breakloop;
5930 case '=':
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005931 if (flags & EXP_VARTILDE2) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005932 p--;
5933 continue;
5934 }
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005935 flags |= EXP_VARTILDE2;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005936 reject++;
5937 /* fall through */
5938 case ':':
5939 /*
5940 * sort of a hack - expand tildes in variable
5941 * assignments (after the first '=' and after ':'s).
5942 */
5943 if (*--p == '~') {
5944 goto tilde;
5945 }
5946 continue;
5947 }
5948
5949 switch (c) {
5950 case CTLENDVAR: /* ??? */
5951 goto breakloop;
5952 case CTLQUOTEMARK:
5953 /* "$@" syntax adherence hack */
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005954 if (!inquotes
5955 && memcmp(p, dolatstr, 4) == 0
5956 && ( p[4] == CTLQUOTEMARK
5957 || (p[4] == CTLENDVAR && p[5] == CTLQUOTEMARK)
5958 )
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005959 ) {
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005960 p = evalvar(p + 1, flags, /* var_str_list: */ NULL) + 1;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005961 goto start;
5962 }
5963 inquotes = !inquotes;
5964 addquote:
5965 if (quotes) {
5966 p--;
5967 length++;
5968 startloc++;
5969 }
5970 break;
5971 case CTLESC:
5972 startloc++;
5973 length++;
5974 goto addquote;
5975 case CTLVAR:
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005976 p = evalvar(p, flags, var_str_list);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005977 goto start;
5978 case CTLBACKQ:
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005979 c = '\0';
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005980 case CTLBACKQ|CTLQUOTE:
5981 expbackq(argbackq->n, c, quotes);
5982 argbackq = argbackq->next;
5983 goto start;
Mike Frysinger98c52642009-04-02 10:02:37 +00005984#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005985 case CTLENDARI:
5986 p--;
5987 expari(quotes);
5988 goto start;
5989#endif
5990 }
5991 }
5992 breakloop:
5993 ;
5994}
5995
5996static char *
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00005997scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM, char *str, int quotes,
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005998 int zero)
5999{
Denis Vlasenkoc7131c32008-04-14 01:59:53 +00006000// This commented out code was added by James Simmons <jsimmons@infradead.org>
6001// as part of a larger change when he added support for ${var/a/b}.
6002// However, it broke # and % operators:
6003//
6004//var=ababcdcd
6005// ok bad
6006//echo ${var#ab} abcdcd abcdcd
6007//echo ${var##ab} abcdcd abcdcd
6008//echo ${var#a*b} abcdcd ababcdcd (!)
6009//echo ${var##a*b} cdcd cdcd
6010//echo ${var#?} babcdcd ababcdcd (!)
6011//echo ${var##?} babcdcd babcdcd
6012//echo ${var#*} ababcdcd babcdcd (!)
6013//echo ${var##*}
6014//echo ${var%cd} ababcd ababcd
6015//echo ${var%%cd} ababcd abab (!)
6016//echo ${var%c*d} ababcd ababcd
6017//echo ${var%%c*d} abab ababcdcd (!)
6018//echo ${var%?} ababcdc ababcdc
6019//echo ${var%%?} ababcdc ababcdcd (!)
6020//echo ${var%*} ababcdcd ababcdcd
6021//echo ${var%%*}
6022//
6023// Commenting it back out helped. Remove it completely if it really
6024// is not needed.
6025
6026 char *loc, *loc2; //, *full;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006027 char c;
6028
6029 loc = startp;
6030 loc2 = rmesc;
6031 do {
Denis Vlasenkoc7131c32008-04-14 01:59:53 +00006032 int match; // = strlen(str);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006033 const char *s = loc2;
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006034
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006035 c = *loc2;
6036 if (zero) {
6037 *loc2 = '\0';
6038 s = rmesc;
6039 }
Denis Vlasenkoc7131c32008-04-14 01:59:53 +00006040 match = pmatch(str, s); // this line was deleted
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006041
Denis Vlasenkoc7131c32008-04-14 01:59:53 +00006042// // chop off end if its '*'
6043// full = strrchr(str, '*');
6044// if (full && full != str)
6045// match--;
6046//
6047// // If str starts with '*' replace with s.
6048// if ((*str == '*') && strlen(s) >= match) {
6049// full = xstrdup(s);
6050// strncpy(full+strlen(s)-match+1, str+1, match-1);
6051// } else
6052// full = xstrndup(str, match);
6053// match = strncmp(s, full, strlen(full));
6054// free(full);
6055//
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006056 *loc2 = c;
Denis Vlasenkoc7131c32008-04-14 01:59:53 +00006057 if (match) // if (!match)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006058 return loc;
Denys Vlasenkocd716832009-11-28 22:14:02 +01006059 if (quotes && (unsigned char)*loc == CTLESC)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006060 loc++;
6061 loc++;
6062 loc2++;
6063 } while (c);
6064 return 0;
6065}
6066
6067static char *
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006068scanright(char *startp, char *rmesc, char *rmescend, char *pattern, int quotes, int match_at_start)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006069{
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006070#if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6071 int try2optimize = match_at_start;
6072#endif
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006073 int esc = 0;
6074 char *loc;
6075 char *loc2;
6076
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006077 /* If we called by "${v/pattern/repl}" or "${v//pattern/repl}":
6078 * startp="escaped_value_of_v" rmesc="raw_value_of_v"
6079 * rmescend=""(ptr to NUL in rmesc) pattern="pattern" quotes=match_at_start=1
6080 * Logic:
6081 * loc starts at NUL at the end of startp, loc2 starts at the end of rmesc,
6082 * and on each iteration they go back two/one char until they reach the beginning.
6083 * We try to find a match in "raw_value_of_v", "raw_value_of_", "raw_value_of" etc.
6084 */
6085 /* TODO: document in what other circumstances we are called. */
6086
6087 for (loc = pattern - 1, loc2 = rmescend; loc >= startp; loc2--) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006088 int match;
6089 char c = *loc2;
6090 const char *s = loc2;
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006091 if (match_at_start) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006092 *loc2 = '\0';
6093 s = rmesc;
6094 }
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006095 match = pmatch(pattern, s);
6096 //bb_error_msg("pmatch(pattern:'%s',s:'%s'):%d", pattern, s, match);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006097 *loc2 = c;
6098 if (match)
6099 return loc;
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006100#if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
6101 if (try2optimize) {
6102 /* Maybe we can optimize this:
6103 * if pattern ends with unescaped *, we can avoid checking
6104 * shorter strings: if "foo*" doesnt match "raw_value_of_v",
6105 * it wont match truncated "raw_value_of_" strings too.
6106 */
6107 unsigned plen = strlen(pattern);
6108 /* Does it end with "*"? */
6109 if (plen != 0 && pattern[--plen] == '*') {
6110 /* "xxxx*" is not escaped */
6111 /* "xxx\*" is escaped */
6112 /* "xx\\*" is not escaped */
6113 /* "x\\\*" is escaped */
6114 int slashes = 0;
6115 while (plen != 0 && pattern[--plen] == '\\')
6116 slashes++;
6117 if (!(slashes & 1))
6118 break; /* ends with unescaped "*" */
6119 }
6120 try2optimize = 0;
6121 }
6122#endif
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006123 loc--;
6124 if (quotes) {
6125 if (--esc < 0) {
6126 esc = esclen(startp, loc);
6127 }
6128 if (esc % 2) {
6129 esc--;
6130 loc--;
6131 }
6132 }
6133 }
6134 return 0;
6135}
6136
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00006137static void varunset(const char *, const char *, const char *, int) NORETURN;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006138static void
6139varunset(const char *end, const char *var, const char *umsg, int varflags)
6140{
6141 const char *msg;
6142 const char *tail;
6143
6144 tail = nullstr;
6145 msg = "parameter not set";
6146 if (umsg) {
Denys Vlasenkocd716832009-11-28 22:14:02 +01006147 if ((unsigned char)*end == CTLENDVAR) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006148 if (varflags & VSNUL)
6149 tail = " or null";
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00006150 } else {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006151 msg = umsg;
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00006152 }
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006153 }
6154 ash_msg_and_raise_error("%.*s: %s%s", end - var - 1, var, msg, tail);
6155}
6156
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006157#if ENABLE_ASH_BASH_COMPAT
6158static char *
6159parse_sub_pattern(char *arg, int inquotes)
6160{
6161 char *idx, *repl = NULL;
6162 unsigned char c;
6163
Denis Vlasenko2659c632008-06-14 06:04:59 +00006164 idx = arg;
6165 while (1) {
6166 c = *arg;
6167 if (!c)
6168 break;
6169 if (c == '/') {
6170 /* Only the first '/' seen is our separator */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006171 if (!repl) {
Denis Vlasenko2659c632008-06-14 06:04:59 +00006172 repl = idx + 1;
6173 c = '\0';
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006174 }
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006175 }
Denis Vlasenko2659c632008-06-14 06:04:59 +00006176 *idx++ = c;
6177 if (!inquotes && c == '\\' && arg[1] == '\\')
6178 arg++; /* skip both \\, not just first one */
6179 arg++;
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006180 }
Denis Vlasenko29038c02008-06-14 06:14:02 +00006181 *idx = c; /* NUL */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006182
6183 return repl;
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006184}
6185#endif /* ENABLE_ASH_BASH_COMPAT */
6186
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006187static const char *
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006188subevalvar(char *p, char *str, int strloc, int subtype,
6189 int startloc, int varflags, int quotes, struct strlist *var_str_list)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006190{
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006191 struct nodelist *saveargbackq = argbackq;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006192 char *startp;
6193 char *loc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006194 char *rmesc, *rmescend;
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00006195 IF_ASH_BASH_COMPAT(char *repl = NULL;)
6196 IF_ASH_BASH_COMPAT(char null = '\0';)
6197 IF_ASH_BASH_COMPAT(int pos, len, orig_len;)
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006198 int saveherefd = herefd;
6199 int amount, workloc, resetloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006200 int zero;
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006201 char *(*scan)(char*, char*, char*, char*, int, int);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006202
6203 herefd = -1;
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006204 argstr(p, (subtype != VSASSIGN && subtype != VSQUESTION) ? EXP_CASE : 0,
6205 var_str_list);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006206 STPUTC('\0', expdest);
6207 herefd = saveherefd;
6208 argbackq = saveargbackq;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00006209 startp = (char *)stackblock() + startloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006210
6211 switch (subtype) {
6212 case VSASSIGN:
6213 setvar(str, startp, 0);
6214 amount = startp - expdest;
6215 STADJUST(amount, expdest);
6216 return startp;
6217
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006218#if ENABLE_ASH_BASH_COMPAT
6219 case VSSUBSTR:
6220 loc = str = stackblock() + strloc;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006221 /* Read POS in ${var:POS:LEN} */
6222 pos = atoi(loc); /* number(loc) errors out on "1:4" */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006223 len = str - startp - 1;
6224
6225 /* *loc != '\0', guaranteed by parser */
6226 if (quotes) {
6227 char *ptr;
6228
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006229 /* Adjust the length by the number of escapes */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006230 for (ptr = startp; ptr < (str - 1); ptr++) {
Denys Vlasenkocd716832009-11-28 22:14:02 +01006231 if ((unsigned char)*ptr == CTLESC) {
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006232 len--;
6233 ptr++;
6234 }
6235 }
6236 }
6237 orig_len = len;
6238
6239 if (*loc++ == ':') {
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006240 /* ${var::LEN} */
6241 len = number(loc);
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006242 } else {
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006243 /* Skip POS in ${var:POS:LEN} */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006244 len = orig_len;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006245 while (*loc && *loc != ':') {
6246 /* TODO?
6247 * bash complains on: var=qwe; echo ${var:1a:123}
6248 if (!isdigit(*loc))
6249 ash_msg_and_raise_error(msg_illnum, str);
6250 */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006251 loc++;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006252 }
6253 if (*loc++ == ':') {
6254 len = number(loc);
6255 }
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006256 }
6257 if (pos >= orig_len) {
6258 pos = 0;
6259 len = 0;
6260 }
6261 if (len > (orig_len - pos))
6262 len = orig_len - pos;
6263
6264 for (str = startp; pos; str++, pos--) {
Denys Vlasenkocd716832009-11-28 22:14:02 +01006265 if (quotes && (unsigned char)*str == CTLESC)
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006266 str++;
6267 }
6268 for (loc = startp; len; len--) {
Denys Vlasenkocd716832009-11-28 22:14:02 +01006269 if (quotes && (unsigned char)*str == CTLESC)
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006270 *loc++ = *str++;
6271 *loc++ = *str++;
6272 }
6273 *loc = '\0';
6274 amount = loc - expdest;
6275 STADJUST(amount, expdest);
6276 return loc;
6277#endif
6278
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006279 case VSQUESTION:
6280 varunset(p, str, startp, varflags);
6281 /* NOTREACHED */
6282 }
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006283 resetloc = expdest - (char *)stackblock();
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006284
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006285 /* We'll comeback here if we grow the stack while handling
6286 * a VSREPLACE or VSREPLACEALL, since our pointers into the
6287 * stack will need rebasing, and we'll need to remove our work
6288 * areas each time
6289 */
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00006290 IF_ASH_BASH_COMPAT(restart:)
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006291
6292 amount = expdest - ((char *)stackblock() + resetloc);
6293 STADJUST(-amount, expdest);
Denis Vlasenko29eb3592008-05-18 14:06:08 +00006294 startp = (char *)stackblock() + startloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006295
6296 rmesc = startp;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00006297 rmescend = (char *)stackblock() + strloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006298 if (quotes) {
Denys Vlasenkob6c84342009-08-29 20:23:20 +02006299 rmesc = rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006300 if (rmesc != startp) {
6301 rmescend = expdest;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00006302 startp = (char *)stackblock() + startloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006303 }
6304 }
6305 rmescend--;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00006306 str = (char *)stackblock() + strloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006307 preglob(str, varflags & VSQUOTE, 0);
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006308 workloc = expdest - (char *)stackblock();
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006309
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006310#if ENABLE_ASH_BASH_COMPAT
6311 if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006312 char *idx, *end;
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006313
Denis Vlasenkod6855d12008-09-27 14:03:25 +00006314 if (!repl) {
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006315 repl = parse_sub_pattern(str, varflags & VSQUOTE);
6316 if (!repl)
6317 repl = &null;
6318 }
6319
6320 /* If there's no pattern to match, return the expansion unmolested */
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006321 if (str[0] == '\0')
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006322 return 0;
6323
6324 len = 0;
6325 idx = startp;
6326 end = str - 1;
6327 while (idx < end) {
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006328 try_to_match:
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006329 loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
6330 if (!loc) {
6331 /* No match, advance */
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006332 char *restart_detect = stackblock();
6333 skip_matching:
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006334 STPUTC(*idx, expdest);
Denys Vlasenkocd716832009-11-28 22:14:02 +01006335 if (quotes && (unsigned char)*idx == CTLESC) {
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006336 idx++;
6337 len++;
6338 STPUTC(*idx, expdest);
6339 }
6340 if (stackblock() != restart_detect)
6341 goto restart;
6342 idx++;
6343 len++;
6344 rmesc++;
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006345 /* continue; - prone to quadratic behavior, smarter code: */
6346 if (idx >= end)
6347 break;
6348 if (str[0] == '*') {
6349 /* Pattern is "*foo". If "*foo" does not match "long_string",
6350 * it would never match "ong_string" etc, no point in trying.
6351 */
6352 goto skip_matching;
6353 }
6354 goto try_to_match;
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006355 }
6356
6357 if (subtype == VSREPLACEALL) {
6358 while (idx < loc) {
Denys Vlasenkocd716832009-11-28 22:14:02 +01006359 if (quotes && (unsigned char)*idx == CTLESC)
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006360 idx++;
6361 idx++;
6362 rmesc++;
6363 }
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00006364 } else {
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006365 idx = loc;
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00006366 }
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006367
6368 for (loc = repl; *loc; loc++) {
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006369 char *restart_detect = stackblock();
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006370 STPUTC(*loc, expdest);
6371 if (stackblock() != restart_detect)
6372 goto restart;
6373 len++;
6374 }
6375
6376 if (subtype == VSREPLACE) {
6377 while (*idx) {
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006378 char *restart_detect = stackblock();
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006379 STPUTC(*idx, expdest);
6380 if (stackblock() != restart_detect)
6381 goto restart;
6382 len++;
6383 idx++;
6384 }
6385 break;
6386 }
6387 }
6388
6389 /* We've put the replaced text into a buffer at workloc, now
6390 * move it to the right place and adjust the stack.
6391 */
6392 startp = stackblock() + startloc;
6393 STPUTC('\0', expdest);
6394 memmove(startp, stackblock() + workloc, len);
6395 startp[len++] = '\0';
6396 amount = expdest - ((char *)stackblock() + startloc + len - 1);
6397 STADJUST(-amount, expdest);
6398 return startp;
6399 }
6400#endif /* ENABLE_ASH_BASH_COMPAT */
6401
6402 subtype -= VSTRIMRIGHT;
6403#if DEBUG
6404 if (subtype < 0 || subtype > 7)
6405 abort();
6406#endif
Denys Vlasenkob76356b2010-03-13 16:19:04 +01006407 /* zero = (subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX) */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006408 zero = subtype >> 1;
6409 /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
6410 scan = (subtype & 1) ^ zero ? scanleft : scanright;
6411
6412 loc = scan(startp, rmesc, rmescend, str, quotes, zero);
6413 if (loc) {
6414 if (zero) {
6415 memmove(startp, loc, str - loc);
6416 loc = startp + (str - loc) - 1;
6417 }
6418 *loc = '\0';
6419 amount = loc - expdest;
6420 STADJUST(amount, expdest);
6421 }
6422 return loc;
6423}
6424
6425/*
6426 * Add the value of a specialized variable to the stack string.
Denys Vlasenko4d8873f2009-10-04 03:14:41 +02006427 * name parameter (examples):
6428 * ash -c 'echo $1' name:'1='
6429 * ash -c 'echo $qwe' name:'qwe='
6430 * ash -c 'echo $$' name:'$='
6431 * ash -c 'echo ${$}' name:'$='
6432 * ash -c 'echo ${$##q}' name:'$=q'
6433 * ash -c 'echo ${#$}' name:'$='
6434 * note: examples with bad shell syntax:
6435 * ash -c 'echo ${#$1}' name:'$=1'
6436 * ash -c 'echo ${#1#}' name:'1=#'
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006437 */
Denys Vlasenkoadf922e2009-10-08 14:35:37 +02006438static NOINLINE ssize_t
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006439varvalue(char *name, int varflags, int flags, struct strlist *var_str_list)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006440{
Mike Frysinger98c52642009-04-02 10:02:37 +00006441 const char *p;
Denys Vlasenko8eda4a92009-11-30 12:16:17 +01006442 int num;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006443 int i;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006444 int sepq = 0;
6445 ssize_t len = 0;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006446 int subtype = varflags & VSTYPE;
Denys Vlasenko1166d7b2009-09-16 16:20:31 +02006447 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR);
Denys Vlasenko8eda4a92009-11-30 12:16:17 +01006448 int quoted = varflags & VSQUOTE;
6449 int syntax = quoted ? DQSYNTAX : BASESYNTAX;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006450
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006451 switch (*name) {
6452 case '$':
6453 num = rootpid;
6454 goto numvar;
6455 case '?':
6456 num = exitstatus;
6457 goto numvar;
6458 case '#':
6459 num = shellparam.nparam;
6460 goto numvar;
6461 case '!':
6462 num = backgndpid;
6463 if (num == 0)
6464 return -1;
6465 numvar:
6466 len = cvtnum(num);
Denys Vlasenko4d8873f2009-10-04 03:14:41 +02006467 goto check_1char_name;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006468 case '-':
Mike Frysinger98c52642009-04-02 10:02:37 +00006469 expdest = makestrspace(NOPTS, expdest);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006470 for (i = NOPTS - 1; i >= 0; i--) {
6471 if (optlist[i]) {
Mike Frysinger98c52642009-04-02 10:02:37 +00006472 USTPUTC(optletters(i), expdest);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006473 len++;
6474 }
6475 }
Denys Vlasenko4d8873f2009-10-04 03:14:41 +02006476 check_1char_name:
6477#if 0
6478 /* handles cases similar to ${#$1} */
6479 if (name[2] != '\0')
6480 raise_error_syntax("bad substitution");
6481#endif
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006482 break;
Denys Vlasenko8eda4a92009-11-30 12:16:17 +01006483 case '@': {
6484 char **ap;
6485 int sep;
6486
6487 if (quoted && (flags & EXP_FULL)) {
6488 /* note: this is not meant as PEOF value */
6489 sep = 1 << CHAR_BIT;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006490 goto param;
Denys Vlasenko8eda4a92009-11-30 12:16:17 +01006491 }
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006492 /* fall through */
6493 case '*':
Denys Vlasenkocd716832009-11-28 22:14:02 +01006494 sep = ifsset() ? (unsigned char)(ifsval()[0]) : ' ';
Denys Vlasenko8eda4a92009-11-30 12:16:17 +01006495 i = SIT(sep, syntax);
6496 if (quotes && (i == CCTL || i == CBACK))
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006497 sepq = 1;
6498 param:
6499 ap = shellparam.p;
6500 if (!ap)
6501 return -1;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006502 while ((p = *ap++) != NULL) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006503 size_t partlen;
6504
6505 partlen = strlen(p);
6506 len += partlen;
6507
6508 if (!(subtype == VSPLUS || subtype == VSLENGTH))
6509 memtodest(p, partlen, syntax, quotes);
6510
6511 if (*ap && sep) {
6512 char *q;
6513
6514 len++;
6515 if (subtype == VSPLUS || subtype == VSLENGTH) {
6516 continue;
6517 }
6518 q = expdest;
6519 if (sepq)
6520 STPUTC(CTLESC, q);
Denys Vlasenko8eda4a92009-11-30 12:16:17 +01006521 /* note: may put NUL despite sep != 0
6522 * (see sep = 1 << CHAR_BIT above) */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006523 STPUTC(sep, q);
6524 expdest = q;
6525 }
6526 }
6527 return len;
Denys Vlasenko8eda4a92009-11-30 12:16:17 +01006528 } /* case '@' and '*' */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006529 case '0':
6530 case '1':
6531 case '2':
6532 case '3':
6533 case '4':
6534 case '5':
6535 case '6':
6536 case '7':
6537 case '8':
6538 case '9':
Denys Vlasenkoa00329c2009-08-30 20:05:10 +02006539 num = atoi(name); /* number(name) fails on ${N#str} etc */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006540 if (num < 0 || num > shellparam.nparam)
6541 return -1;
6542 p = num ? shellparam.p[num - 1] : arg0;
6543 goto value;
6544 default:
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006545 /* NB: name has form "VAR=..." */
6546
6547 /* "A=a B=$A" case: var_str_list is a list of "A=a" strings
6548 * which should be considered before we check variables. */
6549 if (var_str_list) {
6550 unsigned name_len = (strchrnul(name, '=') - name) + 1;
6551 p = NULL;
6552 do {
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00006553 char *str, *eq;
6554 str = var_str_list->text;
6555 eq = strchr(str, '=');
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006556 if (!eq) /* stop at first non-assignment */
6557 break;
6558 eq++;
Denis Vlasenko6b06cb82008-05-15 21:30:45 +00006559 if (name_len == (unsigned)(eq - str)
Denys Vlasenko8eda4a92009-11-30 12:16:17 +01006560 && strncmp(str, name, name_len) == 0
6561 ) {
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006562 p = eq;
6563 /* goto value; - WRONG! */
6564 /* think "A=1 A=2 B=$A" */
6565 }
6566 var_str_list = var_str_list->next;
6567 } while (var_str_list);
6568 if (p)
6569 goto value;
6570 }
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006571 p = lookupvar(name);
6572 value:
6573 if (!p)
6574 return -1;
6575
6576 len = strlen(p);
6577 if (!(subtype == VSPLUS || subtype == VSLENGTH))
6578 memtodest(p, len, syntax, quotes);
6579 return len;
6580 }
6581
6582 if (subtype == VSPLUS || subtype == VSLENGTH)
6583 STADJUST(-len, expdest);
6584 return len;
6585}
6586
6587/*
6588 * Expand a variable, and return a pointer to the next character in the
6589 * input string.
6590 */
6591static char *
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006592evalvar(char *p, int flags, struct strlist *var_str_list)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006593{
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006594 char varflags;
6595 char subtype;
6596 char quoted;
6597 char easy;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006598 char *var;
6599 int patloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006600 int startloc;
6601 ssize_t varlen;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006602
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006603 varflags = (unsigned char) *p++;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006604 subtype = varflags & VSTYPE;
6605 quoted = varflags & VSQUOTE;
6606 var = p;
6607 easy = (!quoted || (*var == '@' && shellparam.nparam));
6608 startloc = expdest - (char *)stackblock();
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02006609 p = strchr(p, '=') + 1; //TODO: use var_end(p)?
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006610
6611 again:
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006612 varlen = varvalue(var, varflags, flags, var_str_list);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006613 if (varflags & VSNUL)
6614 varlen--;
6615
6616 if (subtype == VSPLUS) {
6617 varlen = -1 - varlen;
6618 goto vsplus;
6619 }
6620
6621 if (subtype == VSMINUS) {
6622 vsplus:
6623 if (varlen < 0) {
6624 argstr(
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006625 p, flags | EXP_TILDE |
6626 (quoted ? EXP_QWORD : EXP_WORD),
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006627 var_str_list
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006628 );
6629 goto end;
6630 }
6631 if (easy)
6632 goto record;
6633 goto end;
6634 }
6635
6636 if (subtype == VSASSIGN || subtype == VSQUESTION) {
6637 if (varlen < 0) {
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006638 if (subevalvar(p, var, /* strloc: */ 0,
6639 subtype, startloc, varflags,
6640 /* quotes: */ 0,
6641 var_str_list)
6642 ) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006643 varflags &= ~VSNUL;
6644 /*
6645 * Remove any recorded regions beyond
6646 * start of variable
6647 */
6648 removerecordregions(startloc);
6649 goto again;
6650 }
6651 goto end;
6652 }
6653 if (easy)
6654 goto record;
6655 goto end;
6656 }
6657
6658 if (varlen < 0 && uflag)
6659 varunset(p, var, 0, 0);
6660
6661 if (subtype == VSLENGTH) {
6662 cvtnum(varlen > 0 ? varlen : 0);
6663 goto record;
6664 }
6665
6666 if (subtype == VSNORMAL) {
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006667 if (easy)
6668 goto record;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006669 goto end;
6670 }
6671
6672#if DEBUG
6673 switch (subtype) {
6674 case VSTRIMLEFT:
6675 case VSTRIMLEFTMAX:
6676 case VSTRIMRIGHT:
6677 case VSTRIMRIGHTMAX:
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006678#if ENABLE_ASH_BASH_COMPAT
6679 case VSSUBSTR:
6680 case VSREPLACE:
6681 case VSREPLACEALL:
6682#endif
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006683 break;
6684 default:
6685 abort();
6686 }
6687#endif
6688
6689 if (varlen >= 0) {
6690 /*
6691 * Terminate the string and start recording the pattern
6692 * right after it
6693 */
6694 STPUTC('\0', expdest);
6695 patloc = expdest - (char *)stackblock();
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006696 if (0 == subevalvar(p, /* str: */ NULL, patloc, subtype,
6697 startloc, varflags,
Denys Vlasenko1166d7b2009-09-16 16:20:31 +02006698//TODO: | EXP_REDIR too? All other such places do it too
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006699 /* quotes: */ flags & (EXP_FULL | EXP_CASE),
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006700 var_str_list)
6701 ) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006702 int amount = expdest - (
6703 (char *)stackblock() + patloc - 1
6704 );
6705 STADJUST(-amount, expdest);
6706 }
6707 /* Remove any recorded regions beyond start of variable */
6708 removerecordregions(startloc);
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006709 record:
6710 recordregion(startloc, expdest - (char *)stackblock(), quoted);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006711 }
6712
6713 end:
6714 if (subtype != VSNORMAL) { /* skip to end of alternative */
6715 int nesting = 1;
6716 for (;;) {
Denys Vlasenkocd716832009-11-28 22:14:02 +01006717 unsigned char c = *p++;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006718 if (c == CTLESC)
6719 p++;
6720 else if (c == CTLBACKQ || c == (CTLBACKQ|CTLQUOTE)) {
6721 if (varlen >= 0)
6722 argbackq = argbackq->next;
6723 } else if (c == CTLVAR) {
6724 if ((*p++ & VSTYPE) != VSNORMAL)
6725 nesting++;
6726 } else if (c == CTLENDVAR) {
6727 if (--nesting == 0)
6728 break;
6729 }
6730 }
6731 }
6732 return p;
6733}
6734
6735/*
6736 * Break the argument string into pieces based upon IFS and add the
6737 * strings to the argument list. The regions of the string to be
6738 * searched for IFS characters have been stored by recordregion.
6739 */
6740static void
6741ifsbreakup(char *string, struct arglist *arglist)
6742{
6743 struct ifsregion *ifsp;
6744 struct strlist *sp;
6745 char *start;
6746 char *p;
6747 char *q;
6748 const char *ifs, *realifs;
6749 int ifsspc;
6750 int nulonly;
6751
6752 start = string;
6753 if (ifslastp != NULL) {
6754 ifsspc = 0;
6755 nulonly = 0;
6756 realifs = ifsset() ? ifsval() : defifs;
6757 ifsp = &ifsfirst;
6758 do {
6759 p = string + ifsp->begoff;
6760 nulonly = ifsp->nulonly;
6761 ifs = nulonly ? nullstr : realifs;
6762 ifsspc = 0;
6763 while (p < string + ifsp->endoff) {
6764 q = p;
Denys Vlasenkocd716832009-11-28 22:14:02 +01006765 if ((unsigned char)*p == CTLESC)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006766 p++;
6767 if (!strchr(ifs, *p)) {
6768 p++;
6769 continue;
6770 }
6771 if (!nulonly)
6772 ifsspc = (strchr(defifs, *p) != NULL);
6773 /* Ignore IFS whitespace at start */
6774 if (q == start && ifsspc) {
6775 p++;
6776 start = p;
6777 continue;
6778 }
6779 *q = '\0';
Denis Vlasenko597906c2008-02-20 16:38:54 +00006780 sp = stzalloc(sizeof(*sp));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006781 sp->text = start;
6782 *arglist->lastp = sp;
6783 arglist->lastp = &sp->next;
6784 p++;
6785 if (!nulonly) {
6786 for (;;) {
6787 if (p >= string + ifsp->endoff) {
6788 break;
6789 }
6790 q = p;
Denys Vlasenkocd716832009-11-28 22:14:02 +01006791 if ((unsigned char)*p == CTLESC)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006792 p++;
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +00006793 if (strchr(ifs, *p) == NULL) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006794 p = q;
6795 break;
Denis Vlasenko597906c2008-02-20 16:38:54 +00006796 }
6797 if (strchr(defifs, *p) == NULL) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006798 if (ifsspc) {
6799 p++;
6800 ifsspc = 0;
6801 } else {
6802 p = q;
6803 break;
6804 }
6805 } else
6806 p++;
6807 }
6808 }
6809 start = p;
6810 } /* while */
6811 ifsp = ifsp->next;
6812 } while (ifsp != NULL);
6813 if (nulonly)
6814 goto add;
6815 }
6816
6817 if (!*start)
6818 return;
6819
6820 add:
Denis Vlasenko597906c2008-02-20 16:38:54 +00006821 sp = stzalloc(sizeof(*sp));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006822 sp->text = start;
6823 *arglist->lastp = sp;
6824 arglist->lastp = &sp->next;
6825}
6826
6827static void
6828ifsfree(void)
6829{
6830 struct ifsregion *p;
6831
6832 INT_OFF;
6833 p = ifsfirst.next;
6834 do {
6835 struct ifsregion *ifsp;
6836 ifsp = p->next;
6837 free(p);
6838 p = ifsp;
6839 } while (p);
6840 ifslastp = NULL;
6841 ifsfirst.next = NULL;
6842 INT_ON;
6843}
6844
6845/*
6846 * Add a file name to the list.
6847 */
6848static void
6849addfname(const char *name)
6850{
6851 struct strlist *sp;
6852
Denis Vlasenko597906c2008-02-20 16:38:54 +00006853 sp = stzalloc(sizeof(*sp));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006854 sp->text = ststrdup(name);
6855 *exparg.lastp = sp;
6856 exparg.lastp = &sp->next;
6857}
6858
6859static char *expdir;
6860
6861/*
6862 * Do metacharacter (i.e. *, ?, [...]) expansion.
6863 */
6864static void
6865expmeta(char *enddir, char *name)
6866{
6867 char *p;
6868 const char *cp;
6869 char *start;
6870 char *endname;
6871 int metaflag;
6872 struct stat statb;
6873 DIR *dirp;
6874 struct dirent *dp;
6875 int atend;
6876 int matchdot;
6877
6878 metaflag = 0;
6879 start = name;
6880 for (p = name; *p; p++) {
6881 if (*p == '*' || *p == '?')
6882 metaflag = 1;
6883 else if (*p == '[') {
6884 char *q = p + 1;
6885 if (*q == '!')
6886 q++;
6887 for (;;) {
6888 if (*q == '\\')
6889 q++;
6890 if (*q == '/' || *q == '\0')
6891 break;
6892 if (*++q == ']') {
6893 metaflag = 1;
6894 break;
6895 }
6896 }
6897 } else if (*p == '\\')
6898 p++;
6899 else if (*p == '/') {
6900 if (metaflag)
6901 goto out;
6902 start = p + 1;
6903 }
6904 }
6905 out:
6906 if (metaflag == 0) { /* we've reached the end of the file name */
6907 if (enddir != expdir)
6908 metaflag++;
6909 p = name;
6910 do {
6911 if (*p == '\\')
6912 p++;
6913 *enddir++ = *p;
6914 } while (*p++);
6915 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
6916 addfname(expdir);
6917 return;
6918 }
6919 endname = p;
6920 if (name < start) {
6921 p = name;
6922 do {
6923 if (*p == '\\')
6924 p++;
6925 *enddir++ = *p++;
6926 } while (p < start);
6927 }
6928 if (enddir == expdir) {
6929 cp = ".";
6930 } else if (enddir == expdir + 1 && *expdir == '/') {
6931 cp = "/";
6932 } else {
6933 cp = expdir;
6934 enddir[-1] = '\0';
6935 }
6936 dirp = opendir(cp);
6937 if (dirp == NULL)
6938 return;
6939 if (enddir != expdir)
6940 enddir[-1] = '/';
6941 if (*endname == 0) {
6942 atend = 1;
6943 } else {
6944 atend = 0;
6945 *endname++ = '\0';
6946 }
6947 matchdot = 0;
6948 p = start;
6949 if (*p == '\\')
6950 p++;
6951 if (*p == '.')
6952 matchdot++;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006953 while (!pending_int && (dp = readdir(dirp)) != NULL) {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00006954 if (dp->d_name[0] == '.' && !matchdot)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006955 continue;
6956 if (pmatch(start, dp->d_name)) {
6957 if (atend) {
6958 strcpy(enddir, dp->d_name);
6959 addfname(expdir);
6960 } else {
6961 for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
6962 continue;
6963 p[-1] = '/';
6964 expmeta(p, endname);
6965 }
6966 }
6967 }
6968 closedir(dirp);
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00006969 if (!atend)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006970 endname[-1] = '/';
6971}
6972
6973static struct strlist *
6974msort(struct strlist *list, int len)
6975{
6976 struct strlist *p, *q = NULL;
6977 struct strlist **lpp;
6978 int half;
6979 int n;
6980
6981 if (len <= 1)
6982 return list;
6983 half = len >> 1;
6984 p = list;
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +00006985 for (n = half; --n >= 0;) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006986 q = p;
6987 p = p->next;
6988 }
6989 q->next = NULL; /* terminate first half of list */
6990 q = msort(list, half); /* sort first half of list */
6991 p = msort(p, len - half); /* sort second half */
6992 lpp = &list;
6993 for (;;) {
6994#if ENABLE_LOCALE_SUPPORT
6995 if (strcoll(p->text, q->text) < 0)
6996#else
6997 if (strcmp(p->text, q->text) < 0)
6998#endif
6999 {
7000 *lpp = p;
7001 lpp = &p->next;
7002 p = *lpp;
7003 if (p == NULL) {
7004 *lpp = q;
7005 break;
7006 }
7007 } else {
7008 *lpp = q;
7009 lpp = &q->next;
7010 q = *lpp;
7011 if (q == NULL) {
7012 *lpp = p;
7013 break;
7014 }
7015 }
7016 }
7017 return list;
7018}
7019
7020/*
7021 * Sort the results of file name expansion. It calculates the number of
7022 * strings to sort and then calls msort (short for merge sort) to do the
7023 * work.
7024 */
7025static struct strlist *
7026expsort(struct strlist *str)
7027{
7028 int len;
7029 struct strlist *sp;
7030
7031 len = 0;
7032 for (sp = str; sp; sp = sp->next)
7033 len++;
7034 return msort(str, len);
7035}
7036
7037static void
Denis Vlasenko68404f12008-03-17 09:00:54 +00007038expandmeta(struct strlist *str /*, int flag*/)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007039{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00007040 static const char metachars[] ALIGN1 = {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007041 '*', '?', '[', 0
7042 };
7043 /* TODO - EXP_REDIR */
7044
7045 while (str) {
7046 struct strlist **savelastp;
7047 struct strlist *sp;
7048 char *p;
7049
7050 if (fflag)
7051 goto nometa;
7052 if (!strpbrk(str->text, metachars))
7053 goto nometa;
7054 savelastp = exparg.lastp;
7055
7056 INT_OFF;
7057 p = preglob(str->text, 0, RMESCAPE_ALLOC | RMESCAPE_HEAP);
7058 {
7059 int i = strlen(str->text);
7060 expdir = ckmalloc(i < 2048 ? 2048 : i); /* XXX */
7061 }
7062
7063 expmeta(expdir, p);
7064 free(expdir);
7065 if (p != str->text)
7066 free(p);
7067 INT_ON;
7068 if (exparg.lastp == savelastp) {
7069 /*
7070 * no matches
7071 */
7072 nometa:
7073 *exparg.lastp = str;
Denys Vlasenkob6c84342009-08-29 20:23:20 +02007074 rmescapes(str->text, 0);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007075 exparg.lastp = &str->next;
7076 } else {
7077 *exparg.lastp = NULL;
7078 *savelastp = sp = expsort(*savelastp);
7079 while (sp->next != NULL)
7080 sp = sp->next;
7081 exparg.lastp = &sp->next;
7082 }
7083 str = str->next;
7084 }
7085}
7086
7087/*
7088 * Perform variable substitution and command substitution on an argument,
7089 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
7090 * perform splitting and file name expansion. When arglist is NULL, perform
7091 * here document expansion.
7092 */
7093static void
7094expandarg(union node *arg, struct arglist *arglist, int flag)
7095{
7096 struct strlist *sp;
7097 char *p;
7098
7099 argbackq = arg->narg.backquote;
7100 STARTSTACKSTR(expdest);
7101 ifsfirst.next = NULL;
7102 ifslastp = NULL;
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00007103 argstr(arg->narg.text, flag,
7104 /* var_str_list: */ arglist ? arglist->list : NULL);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007105 p = _STPUTC('\0', expdest);
7106 expdest = p - 1;
7107 if (arglist == NULL) {
7108 return; /* here document expanded */
7109 }
7110 p = grabstackstr(p);
7111 exparg.lastp = &exparg.list;
7112 /*
7113 * TODO - EXP_REDIR
7114 */
7115 if (flag & EXP_FULL) {
7116 ifsbreakup(p, &exparg);
7117 *exparg.lastp = NULL;
7118 exparg.lastp = &exparg.list;
Denis Vlasenko68404f12008-03-17 09:00:54 +00007119 expandmeta(exparg.list /*, flag*/);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007120 } else {
7121 if (flag & EXP_REDIR) /*XXX - for now, just remove escapes */
Denys Vlasenkob6c84342009-08-29 20:23:20 +02007122 rmescapes(p, 0);
Denis Vlasenko597906c2008-02-20 16:38:54 +00007123 sp = stzalloc(sizeof(*sp));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007124 sp->text = p;
7125 *exparg.lastp = sp;
7126 exparg.lastp = &sp->next;
7127 }
7128 if (ifsfirst.next)
7129 ifsfree();
7130 *exparg.lastp = NULL;
7131 if (exparg.list) {
7132 *arglist->lastp = exparg.list;
7133 arglist->lastp = exparg.lastp;
7134 }
7135}
7136
7137/*
7138 * Expand shell variables and backquotes inside a here document.
7139 */
7140static void
7141expandhere(union node *arg, int fd)
7142{
7143 herefd = fd;
7144 expandarg(arg, (struct arglist *)NULL, 0);
7145 full_write(fd, stackblock(), expdest - (char *)stackblock());
7146}
7147
7148/*
7149 * Returns true if the pattern matches the string.
7150 */
7151static int
7152patmatch(char *pattern, const char *string)
7153{
7154 return pmatch(preglob(pattern, 0, 0), string);
7155}
7156
7157/*
7158 * See if a pattern matches in a case statement.
7159 */
7160static int
7161casematch(union node *pattern, char *val)
7162{
7163 struct stackmark smark;
7164 int result;
7165
7166 setstackmark(&smark);
7167 argbackq = pattern->narg.backquote;
7168 STARTSTACKSTR(expdest);
7169 ifslastp = NULL;
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00007170 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE,
7171 /* var_str_list: */ NULL);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007172 STACKSTRNUL(expdest);
7173 result = patmatch(stackblock(), val);
7174 popstackmark(&smark);
7175 return result;
7176}
7177
7178
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007179/* ============ find_command */
7180
7181struct builtincmd {
7182 const char *name;
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007183 int (*builtin)(int, char **) FAST_FUNC;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007184 /* unsigned flags; */
7185};
7186#define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
Denis Vlasenkoe26b2782008-02-12 07:40:29 +00007187/* "regular" builtins always take precedence over commands,
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007188 * regardless of PATH=....%builtin... position */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007189#define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007190#define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007191
7192struct cmdentry {
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00007193 smallint cmdtype; /* CMDxxx */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007194 union param {
7195 int index;
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00007196 /* index >= 0 for commands without path (slashes) */
7197 /* (TODO: what exactly does the value mean? PATH position?) */
7198 /* index == -1 for commands with slashes */
7199 /* index == (-2 - applet_no) for NOFORK applets */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007200 const struct builtincmd *cmd;
7201 struct funcnode *func;
7202 } u;
7203};
7204/* values of cmdtype */
7205#define CMDUNKNOWN -1 /* no entry in table for command */
7206#define CMDNORMAL 0 /* command is an executable program */
7207#define CMDFUNCTION 1 /* command is a shell function */
7208#define CMDBUILTIN 2 /* command is a shell builtin */
7209
7210/* action to find_command() */
7211#define DO_ERR 0x01 /* prints errors */
7212#define DO_ABS 0x02 /* checks absolute paths */
7213#define DO_NOFUNC 0x04 /* don't return shell functions, for command */
7214#define DO_ALTPATH 0x08 /* using alternate path */
7215#define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
7216
7217static void find_command(char *, struct cmdentry *, int, const char *);
7218
7219
7220/* ============ Hashing commands */
7221
7222/*
7223 * When commands are first encountered, they are entered in a hash table.
7224 * This ensures that a full path search will not have to be done for them
7225 * on each invocation.
7226 *
7227 * We should investigate converting to a linear search, even though that
7228 * would make the command name "hash" a misnomer.
7229 */
7230
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007231struct tblentry {
7232 struct tblentry *next; /* next entry in hash chain */
7233 union param param; /* definition of builtin function */
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00007234 smallint cmdtype; /* CMDxxx */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007235 char rehash; /* if set, cd done since entry created */
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007236 char cmdname[1]; /* name of command */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007237};
7238
Denis Vlasenko01631112007-12-16 17:20:38 +00007239static struct tblentry **cmdtable;
7240#define INIT_G_cmdtable() do { \
7241 cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
7242} while (0)
7243
7244static int builtinloc = -1; /* index in path of %builtin, or -1 */
7245
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007246
7247static void
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00007248tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) char *cmd, char **argv, char **envp)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007249{
7250 int repeated = 0;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007251
Denis Vlasenko80d14be2007-04-10 23:03:30 +00007252#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007253 if (applet_no >= 0) {
Denis Vlasenkob7304742008-10-20 08:15:51 +00007254 if (APPLET_IS_NOEXEC(applet_no)) {
7255 while (*envp)
7256 putenv(*envp++);
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007257 run_applet_no_and_exit(applet_no, argv);
Denis Vlasenkob7304742008-10-20 08:15:51 +00007258 }
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007259 /* re-exec ourselves with the new arguments */
7260 execve(bb_busybox_exec_path, argv, envp);
7261 /* If they called chroot or otherwise made the binary no longer
7262 * executable, fall through */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007263 }
7264#endif
7265
7266 repeat:
7267#ifdef SYSV
7268 do {
7269 execve(cmd, argv, envp);
7270 } while (errno == EINTR);
7271#else
7272 execve(cmd, argv, envp);
7273#endif
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007274 if (repeated) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007275 free(argv);
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007276 return;
7277 }
7278 if (errno == ENOEXEC) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007279 char **ap;
7280 char **new;
7281
7282 for (ap = argv; *ap; ap++)
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007283 continue;
7284 ap = new = ckmalloc((ap - argv + 2) * sizeof(ap[0]));
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007285 ap[1] = cmd;
Denis Vlasenkoc44ab012007-04-09 03:11:58 +00007286 ap[0] = cmd = (char *)DEFAULT_SHELL;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007287 ap += 2;
7288 argv++;
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007289 while ((*ap++ = *argv++) != NULL)
Denis Vlasenko597906c2008-02-20 16:38:54 +00007290 continue;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007291 argv = new;
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007292 repeated++;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007293 goto repeat;
7294 }
7295}
7296
7297/*
7298 * Exec a program. Never returns. If you change this routine, you may
7299 * have to change the find_command routine as well.
7300 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00007301static void shellexec(char **, const char *, int) NORETURN;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007302static void
7303shellexec(char **argv, const char *path, int idx)
7304{
7305 char *cmdname;
7306 int e;
7307 char **envp;
7308 int exerrno;
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007309#if ENABLE_FEATURE_SH_STANDALONE
7310 int applet_no = -1;
7311#endif
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007312
Denis Vlasenko34c73c42008-08-16 11:48:02 +00007313 clearredir(/*drop:*/ 1);
Denys Vlasenko1ed2fb42010-06-18 14:09:48 +02007314 envp = listvars(VEXPORT, VUNSET, /*end:*/ NULL);
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007315 if (strchr(argv[0], '/') != NULL
Denis Vlasenko80d14be2007-04-10 23:03:30 +00007316#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007317 || (applet_no = find_applet_by_name(argv[0])) >= 0
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007318#endif
7319 ) {
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00007320 tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) argv[0], argv, envp);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007321 e = errno;
7322 } else {
7323 e = ENOENT;
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02007324 while ((cmdname = path_advance(&path, argv[0])) != NULL) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007325 if (--idx < 0 && pathopt == NULL) {
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00007326 tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007327 if (errno != ENOENT && errno != ENOTDIR)
7328 e = errno;
7329 }
7330 stunalloc(cmdname);
7331 }
7332 }
7333
7334 /* Map to POSIX errors */
7335 switch (e) {
7336 case EACCES:
7337 exerrno = 126;
7338 break;
7339 case ENOENT:
7340 exerrno = 127;
7341 break;
7342 default:
7343 exerrno = 2;
7344 break;
7345 }
7346 exitstatus = exerrno;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02007347 TRACE(("shellexec failed for %s, errno %d, suppress_int %d\n",
7348 argv[0], e, suppress_int));
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007349 ash_msg_and_raise(EXEXEC, "%s: %s", argv[0], errmsg(e, "not found"));
7350 /* NOTREACHED */
7351}
7352
7353static void
7354printentry(struct tblentry *cmdp)
7355{
7356 int idx;
7357 const char *path;
7358 char *name;
7359
7360 idx = cmdp->param.index;
7361 path = pathval();
7362 do {
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02007363 name = path_advance(&path, cmdp->cmdname);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007364 stunalloc(name);
7365 } while (--idx >= 0);
7366 out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
7367}
7368
7369/*
7370 * Clear out command entries. The argument specifies the first entry in
7371 * PATH which has changed.
7372 */
7373static void
7374clearcmdentry(int firstchange)
7375{
7376 struct tblentry **tblp;
7377 struct tblentry **pp;
7378 struct tblentry *cmdp;
7379
7380 INT_OFF;
7381 for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
7382 pp = tblp;
7383 while ((cmdp = *pp) != NULL) {
7384 if ((cmdp->cmdtype == CMDNORMAL &&
7385 cmdp->param.index >= firstchange)
7386 || (cmdp->cmdtype == CMDBUILTIN &&
7387 builtinloc >= firstchange)
7388 ) {
7389 *pp = cmdp->next;
7390 free(cmdp);
7391 } else {
7392 pp = &cmdp->next;
7393 }
7394 }
7395 }
7396 INT_ON;
7397}
7398
7399/*
7400 * Locate a command in the command hash table. If "add" is nonzero,
7401 * add the command to the table if it is not already present. The
7402 * variable "lastcmdentry" is set to point to the address of the link
7403 * pointing to the entry, so that delete_cmd_entry can delete the
7404 * entry.
7405 *
7406 * Interrupts must be off if called with add != 0.
7407 */
7408static struct tblentry **lastcmdentry;
7409
7410static struct tblentry *
7411cmdlookup(const char *name, int add)
7412{
7413 unsigned int hashval;
7414 const char *p;
7415 struct tblentry *cmdp;
7416 struct tblentry **pp;
7417
7418 p = name;
7419 hashval = (unsigned char)*p << 4;
7420 while (*p)
7421 hashval += (unsigned char)*p++;
7422 hashval &= 0x7FFF;
7423 pp = &cmdtable[hashval % CMDTABLESIZE];
7424 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7425 if (strcmp(cmdp->cmdname, name) == 0)
7426 break;
7427 pp = &cmdp->next;
7428 }
7429 if (add && cmdp == NULL) {
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007430 cmdp = *pp = ckzalloc(sizeof(struct tblentry)
7431 + strlen(name)
7432 /* + 1 - already done because
7433 * tblentry::cmdname is char[1] */);
Denis Vlasenko597906c2008-02-20 16:38:54 +00007434 /*cmdp->next = NULL; - ckzalloc did it */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007435 cmdp->cmdtype = CMDUNKNOWN;
7436 strcpy(cmdp->cmdname, name);
7437 }
7438 lastcmdentry = pp;
7439 return cmdp;
7440}
7441
7442/*
7443 * Delete the command entry returned on the last lookup.
7444 */
7445static void
7446delete_cmd_entry(void)
7447{
7448 struct tblentry *cmdp;
7449
7450 INT_OFF;
7451 cmdp = *lastcmdentry;
7452 *lastcmdentry = cmdp->next;
7453 if (cmdp->cmdtype == CMDFUNCTION)
7454 freefunc(cmdp->param.func);
7455 free(cmdp);
7456 INT_ON;
7457}
7458
7459/*
7460 * Add a new command entry, replacing any existing command entry for
7461 * the same name - except special builtins.
7462 */
7463static void
7464addcmdentry(char *name, struct cmdentry *entry)
7465{
7466 struct tblentry *cmdp;
7467
7468 cmdp = cmdlookup(name, 1);
7469 if (cmdp->cmdtype == CMDFUNCTION) {
7470 freefunc(cmdp->param.func);
7471 }
7472 cmdp->cmdtype = entry->cmdtype;
7473 cmdp->param = entry->u;
7474 cmdp->rehash = 0;
7475}
7476
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007477static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00007478hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007479{
7480 struct tblentry **pp;
7481 struct tblentry *cmdp;
7482 int c;
7483 struct cmdentry entry;
7484 char *name;
7485
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007486 if (nextopt("r") != '\0') {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007487 clearcmdentry(0);
7488 return 0;
7489 }
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007490
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007491 if (*argptr == NULL) {
7492 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7493 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7494 if (cmdp->cmdtype == CMDNORMAL)
7495 printentry(cmdp);
7496 }
7497 }
7498 return 0;
7499 }
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007500
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007501 c = 0;
7502 while ((name = *argptr) != NULL) {
7503 cmdp = cmdlookup(name, 0);
7504 if (cmdp != NULL
7505 && (cmdp->cmdtype == CMDNORMAL
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007506 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
7507 ) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007508 delete_cmd_entry();
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007509 }
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007510 find_command(name, &entry, DO_ERR, pathval());
7511 if (entry.cmdtype == CMDUNKNOWN)
7512 c = 1;
7513 argptr++;
7514 }
7515 return c;
7516}
7517
7518/*
7519 * Called when a cd is done. Marks all commands so the next time they
7520 * are executed they will be rehashed.
7521 */
7522static void
7523hashcd(void)
7524{
7525 struct tblentry **pp;
7526 struct tblentry *cmdp;
7527
7528 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7529 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007530 if (cmdp->cmdtype == CMDNORMAL
7531 || (cmdp->cmdtype == CMDBUILTIN
7532 && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
7533 && builtinloc > 0)
7534 ) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007535 cmdp->rehash = 1;
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007536 }
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007537 }
7538 }
7539}
7540
7541/*
7542 * Fix command hash table when PATH changed.
7543 * Called before PATH is changed. The argument is the new value of PATH;
7544 * pathval() still returns the old value at this point.
7545 * Called with interrupts off.
7546 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007547static void FAST_FUNC
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007548changepath(const char *new)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007549{
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007550 const char *old;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007551 int firstchange;
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007552 int idx;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007553 int idx_bltin;
7554
7555 old = pathval();
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007556 firstchange = 9999; /* assume no change */
7557 idx = 0;
7558 idx_bltin = -1;
7559 for (;;) {
7560 if (*old != *new) {
7561 firstchange = idx;
7562 if ((*old == '\0' && *new == ':')
Denys Vlasenkoa0ec4f52010-05-20 12:50:42 +02007563 || (*old == ':' && *new == '\0')
7564 ) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007565 firstchange++;
Denys Vlasenkoa0ec4f52010-05-20 12:50:42 +02007566 }
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007567 old = new; /* ignore subsequent differences */
7568 }
7569 if (*new == '\0')
7570 break;
7571 if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
7572 idx_bltin = idx;
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007573 if (*new == ':')
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007574 idx++;
Denys Vlasenkoa0ec4f52010-05-20 12:50:42 +02007575 new++;
7576 old++;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007577 }
7578 if (builtinloc < 0 && idx_bltin >= 0)
7579 builtinloc = idx_bltin; /* zap builtins */
7580 if (builtinloc >= 0 && idx_bltin < 0)
7581 firstchange = 0;
7582 clearcmdentry(firstchange);
7583 builtinloc = idx_bltin;
7584}
7585
7586#define TEOF 0
7587#define TNL 1
7588#define TREDIR 2
7589#define TWORD 3
7590#define TSEMI 4
7591#define TBACKGND 5
7592#define TAND 6
7593#define TOR 7
7594#define TPIPE 8
7595#define TLP 9
7596#define TRP 10
7597#define TENDCASE 11
7598#define TENDBQUOTE 12
7599#define TNOT 13
7600#define TCASE 14
7601#define TDO 15
7602#define TDONE 16
7603#define TELIF 17
7604#define TELSE 18
7605#define TESAC 19
7606#define TFI 20
7607#define TFOR 21
7608#define TIF 22
7609#define TIN 23
7610#define TTHEN 24
7611#define TUNTIL 25
7612#define TWHILE 26
7613#define TBEGIN 27
7614#define TEND 28
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007615typedef smallint token_id_t;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007616
7617/* first char is indicating which tokens mark the end of a list */
7618static const char *const tokname_array[] = {
7619 "\1end of file",
7620 "\0newline",
7621 "\0redirection",
7622 "\0word",
7623 "\0;",
7624 "\0&",
7625 "\0&&",
7626 "\0||",
7627 "\0|",
7628 "\0(",
7629 "\1)",
7630 "\1;;",
7631 "\1`",
7632#define KWDOFFSET 13
7633 /* the following are keywords */
7634 "\0!",
7635 "\0case",
7636 "\1do",
7637 "\1done",
7638 "\1elif",
7639 "\1else",
7640 "\1esac",
7641 "\1fi",
7642 "\0for",
7643 "\0if",
7644 "\0in",
7645 "\1then",
7646 "\0until",
7647 "\0while",
7648 "\0{",
7649 "\1}",
7650};
7651
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007652/* Wrapper around strcmp for qsort/bsearch/... */
7653static int
7654pstrcmp(const void *a, const void *b)
7655{
Denis Vlasenko240a1cf2007-04-08 16:07:02 +00007656 return strcmp((char*) a, (*(char**) b) + 1);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007657}
7658
7659static const char *const *
7660findkwd(const char *s)
7661{
7662 return bsearch(s, tokname_array + KWDOFFSET,
Denis Vlasenko80b8b392007-06-25 10:55:35 +00007663 ARRAY_SIZE(tokname_array) - KWDOFFSET,
7664 sizeof(tokname_array[0]), pstrcmp);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007665}
7666
7667/*
7668 * Locate and print what a word is...
7669 */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007670static int
7671describe_command(char *command, int describe_command_verbose)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007672{
7673 struct cmdentry entry;
7674 struct tblentry *cmdp;
7675#if ENABLE_ASH_ALIAS
7676 const struct alias *ap;
7677#endif
7678 const char *path = pathval();
7679
7680 if (describe_command_verbose) {
7681 out1str(command);
7682 }
7683
7684 /* First look at the keywords */
7685 if (findkwd(command)) {
7686 out1str(describe_command_verbose ? " is a shell keyword" : command);
7687 goto out;
7688 }
7689
7690#if ENABLE_ASH_ALIAS
7691 /* Then look at the aliases */
7692 ap = lookupalias(command, 0);
7693 if (ap != NULL) {
Denis Vlasenko46846e22007-05-20 13:08:31 +00007694 if (!describe_command_verbose) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007695 out1str("alias ");
7696 printalias(ap);
7697 return 0;
7698 }
Denis Vlasenko46846e22007-05-20 13:08:31 +00007699 out1fmt(" is an alias for %s", ap->val);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007700 goto out;
7701 }
7702#endif
7703 /* Then check if it is a tracked alias */
7704 cmdp = cmdlookup(command, 0);
7705 if (cmdp != NULL) {
7706 entry.cmdtype = cmdp->cmdtype;
7707 entry.u = cmdp->param;
7708 } else {
7709 /* Finally use brute force */
7710 find_command(command, &entry, DO_ABS, path);
7711 }
7712
7713 switch (entry.cmdtype) {
7714 case CMDNORMAL: {
7715 int j = entry.u.index;
7716 char *p;
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00007717 if (j < 0) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007718 p = command;
7719 } else {
7720 do {
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02007721 p = path_advance(&path, command);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007722 stunalloc(p);
7723 } while (--j >= 0);
7724 }
7725 if (describe_command_verbose) {
7726 out1fmt(" is%s %s",
7727 (cmdp ? " a tracked alias for" : nullstr), p
7728 );
7729 } else {
7730 out1str(p);
7731 }
7732 break;
7733 }
7734
7735 case CMDFUNCTION:
7736 if (describe_command_verbose) {
7737 out1str(" is a shell function");
7738 } else {
7739 out1str(command);
7740 }
7741 break;
7742
7743 case CMDBUILTIN:
7744 if (describe_command_verbose) {
7745 out1fmt(" is a %sshell builtin",
7746 IS_BUILTIN_SPECIAL(entry.u.cmd) ?
7747 "special " : nullstr
7748 );
7749 } else {
7750 out1str(command);
7751 }
7752 break;
7753
7754 default:
7755 if (describe_command_verbose) {
7756 out1str(": not found\n");
7757 }
7758 return 127;
7759 }
7760 out:
Denys Vlasenko285ad152009-12-04 23:02:27 +01007761 out1str("\n");
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007762 return 0;
7763}
7764
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007765static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00007766typecmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007767{
Denis Vlasenko46846e22007-05-20 13:08:31 +00007768 int i = 1;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007769 int err = 0;
Denis Vlasenko46846e22007-05-20 13:08:31 +00007770 int verbose = 1;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007771
Denis Vlasenko46846e22007-05-20 13:08:31 +00007772 /* type -p ... ? (we don't bother checking for 'p') */
Denis Vlasenko1fc62382007-06-25 22:55:34 +00007773 if (argv[1] && argv[1][0] == '-') {
Denis Vlasenko46846e22007-05-20 13:08:31 +00007774 i++;
7775 verbose = 0;
7776 }
Denis Vlasenko68404f12008-03-17 09:00:54 +00007777 while (argv[i]) {
Denis Vlasenko46846e22007-05-20 13:08:31 +00007778 err |= describe_command(argv[i++], verbose);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007779 }
7780 return err;
7781}
7782
7783#if ENABLE_ASH_CMDCMD
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007784static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00007785commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007786{
7787 int c;
7788 enum {
7789 VERIFY_BRIEF = 1,
7790 VERIFY_VERBOSE = 2,
7791 } verify = 0;
7792
7793 while ((c = nextopt("pvV")) != '\0')
7794 if (c == 'V')
7795 verify |= VERIFY_VERBOSE;
7796 else if (c == 'v')
7797 verify |= VERIFY_BRIEF;
7798#if DEBUG
7799 else if (c != 'p')
7800 abort();
7801#endif
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00007802 /* Mimic bash: just "command -v" doesn't complain, it's a nop */
7803 if (verify && (*argptr != NULL)) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007804 return describe_command(*argptr, verify - VERIFY_BRIEF);
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00007805 }
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007806
7807 return 0;
7808}
7809#endif
7810
7811
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007812/* ============ eval.c */
Eric Andersencb57d552001-06-28 07:25:16 +00007813
Denis Vlasenko340299a2008-11-21 10:36:36 +00007814static int funcblocksize; /* size of structures in function */
7815static int funcstringsize; /* size of strings in node */
7816static void *funcblock; /* block to allocate function from */
7817static char *funcstring; /* block to allocate strings from */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007818
Eric Andersencb57d552001-06-28 07:25:16 +00007819/* flags in argument to evaltree */
Denis Vlasenko340299a2008-11-21 10:36:36 +00007820#define EV_EXIT 01 /* exit after evaluating tree */
7821#define EV_TESTED 02 /* exit status is checked; ignore -e flag */
Eric Andersenc470f442003-07-28 09:56:35 +00007822#define EV_BACKCMD 04 /* command executing within back quotes */
Eric Andersencb57d552001-06-28 07:25:16 +00007823
Denys Vlasenko0e5e4ea2009-10-11 00:36:20 +02007824static const uint8_t nodesize[N_NUMBER] = {
Denis Vlasenko340299a2008-11-21 10:36:36 +00007825 [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
7826 [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
7827 [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
7828 [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
7829 [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
7830 [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
7831 [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
7832 [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
7833 [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
7834 [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
7835 [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
7836 [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
7837 [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
7838 [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
7839 [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
7840 [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
7841 [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
Denis Vlasenkocc5feab2008-11-22 01:32:40 +00007842#if ENABLE_ASH_BASH_COMPAT
Denis Vlasenko340299a2008-11-21 10:36:36 +00007843 [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
Denis Vlasenkocc5feab2008-11-22 01:32:40 +00007844#endif
Denis Vlasenko340299a2008-11-21 10:36:36 +00007845 [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
7846 [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
7847 [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
7848 [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
7849 [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
7850 [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
7851 [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
7852 [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
7853 [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007854};
7855
7856static void calcsize(union node *n);
7857
7858static void
7859sizenodelist(struct nodelist *lp)
7860{
7861 while (lp) {
7862 funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
7863 calcsize(lp->n);
7864 lp = lp->next;
7865 }
7866}
7867
7868static void
7869calcsize(union node *n)
7870{
7871 if (n == NULL)
7872 return;
7873 funcblocksize += nodesize[n->type];
7874 switch (n->type) {
7875 case NCMD:
7876 calcsize(n->ncmd.redirect);
7877 calcsize(n->ncmd.args);
7878 calcsize(n->ncmd.assign);
7879 break;
7880 case NPIPE:
7881 sizenodelist(n->npipe.cmdlist);
7882 break;
7883 case NREDIR:
7884 case NBACKGND:
7885 case NSUBSHELL:
7886 calcsize(n->nredir.redirect);
7887 calcsize(n->nredir.n);
7888 break;
7889 case NAND:
7890 case NOR:
7891 case NSEMI:
7892 case NWHILE:
7893 case NUNTIL:
7894 calcsize(n->nbinary.ch2);
7895 calcsize(n->nbinary.ch1);
7896 break;
7897 case NIF:
7898 calcsize(n->nif.elsepart);
7899 calcsize(n->nif.ifpart);
7900 calcsize(n->nif.test);
7901 break;
7902 case NFOR:
7903 funcstringsize += strlen(n->nfor.var) + 1;
7904 calcsize(n->nfor.body);
7905 calcsize(n->nfor.args);
7906 break;
7907 case NCASE:
7908 calcsize(n->ncase.cases);
7909 calcsize(n->ncase.expr);
7910 break;
7911 case NCLIST:
7912 calcsize(n->nclist.body);
7913 calcsize(n->nclist.pattern);
7914 calcsize(n->nclist.next);
7915 break;
7916 case NDEFUN:
7917 case NARG:
7918 sizenodelist(n->narg.backquote);
7919 funcstringsize += strlen(n->narg.text) + 1;
7920 calcsize(n->narg.next);
7921 break;
7922 case NTO:
Denis Vlasenko559691a2008-10-05 18:39:31 +00007923#if ENABLE_ASH_BASH_COMPAT
7924 case NTO2:
7925#endif
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007926 case NCLOBBER:
7927 case NFROM:
7928 case NFROMTO:
7929 case NAPPEND:
7930 calcsize(n->nfile.fname);
7931 calcsize(n->nfile.next);
7932 break;
7933 case NTOFD:
7934 case NFROMFD:
7935 calcsize(n->ndup.vname);
7936 calcsize(n->ndup.next);
7937 break;
7938 case NHERE:
7939 case NXHERE:
7940 calcsize(n->nhere.doc);
7941 calcsize(n->nhere.next);
7942 break;
7943 case NNOT:
7944 calcsize(n->nnot.com);
7945 break;
7946 };
7947}
7948
7949static char *
7950nodeckstrdup(char *s)
7951{
7952 char *rtn = funcstring;
7953
7954 strcpy(funcstring, s);
7955 funcstring += strlen(s) + 1;
7956 return rtn;
7957}
7958
7959static union node *copynode(union node *);
7960
7961static struct nodelist *
7962copynodelist(struct nodelist *lp)
7963{
7964 struct nodelist *start;
7965 struct nodelist **lpp;
7966
7967 lpp = &start;
7968 while (lp) {
7969 *lpp = funcblock;
7970 funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
7971 (*lpp)->n = copynode(lp->n);
7972 lp = lp->next;
7973 lpp = &(*lpp)->next;
7974 }
7975 *lpp = NULL;
7976 return start;
7977}
7978
7979static union node *
7980copynode(union node *n)
7981{
7982 union node *new;
7983
7984 if (n == NULL)
7985 return NULL;
7986 new = funcblock;
7987 funcblock = (char *) funcblock + nodesize[n->type];
7988
7989 switch (n->type) {
7990 case NCMD:
7991 new->ncmd.redirect = copynode(n->ncmd.redirect);
7992 new->ncmd.args = copynode(n->ncmd.args);
7993 new->ncmd.assign = copynode(n->ncmd.assign);
7994 break;
7995 case NPIPE:
7996 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00007997 new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007998 break;
7999 case NREDIR:
8000 case NBACKGND:
8001 case NSUBSHELL:
8002 new->nredir.redirect = copynode(n->nredir.redirect);
8003 new->nredir.n = copynode(n->nredir.n);
8004 break;
8005 case NAND:
8006 case NOR:
8007 case NSEMI:
8008 case NWHILE:
8009 case NUNTIL:
8010 new->nbinary.ch2 = copynode(n->nbinary.ch2);
8011 new->nbinary.ch1 = copynode(n->nbinary.ch1);
8012 break;
8013 case NIF:
8014 new->nif.elsepart = copynode(n->nif.elsepart);
8015 new->nif.ifpart = copynode(n->nif.ifpart);
8016 new->nif.test = copynode(n->nif.test);
8017 break;
8018 case NFOR:
8019 new->nfor.var = nodeckstrdup(n->nfor.var);
8020 new->nfor.body = copynode(n->nfor.body);
8021 new->nfor.args = copynode(n->nfor.args);
8022 break;
8023 case NCASE:
8024 new->ncase.cases = copynode(n->ncase.cases);
8025 new->ncase.expr = copynode(n->ncase.expr);
8026 break;
8027 case NCLIST:
8028 new->nclist.body = copynode(n->nclist.body);
8029 new->nclist.pattern = copynode(n->nclist.pattern);
8030 new->nclist.next = copynode(n->nclist.next);
8031 break;
8032 case NDEFUN:
8033 case NARG:
8034 new->narg.backquote = copynodelist(n->narg.backquote);
8035 new->narg.text = nodeckstrdup(n->narg.text);
8036 new->narg.next = copynode(n->narg.next);
8037 break;
8038 case NTO:
Denis Vlasenko559691a2008-10-05 18:39:31 +00008039#if ENABLE_ASH_BASH_COMPAT
8040 case NTO2:
8041#endif
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008042 case NCLOBBER:
8043 case NFROM:
8044 case NFROMTO:
8045 case NAPPEND:
8046 new->nfile.fname = copynode(n->nfile.fname);
8047 new->nfile.fd = n->nfile.fd;
8048 new->nfile.next = copynode(n->nfile.next);
8049 break;
8050 case NTOFD:
8051 case NFROMFD:
8052 new->ndup.vname = copynode(n->ndup.vname);
8053 new->ndup.dupfd = n->ndup.dupfd;
8054 new->ndup.fd = n->ndup.fd;
8055 new->ndup.next = copynode(n->ndup.next);
8056 break;
8057 case NHERE:
8058 case NXHERE:
8059 new->nhere.doc = copynode(n->nhere.doc);
8060 new->nhere.fd = n->nhere.fd;
8061 new->nhere.next = copynode(n->nhere.next);
8062 break;
8063 case NNOT:
8064 new->nnot.com = copynode(n->nnot.com);
8065 break;
8066 };
8067 new->type = n->type;
8068 return new;
8069}
8070
8071/*
8072 * Make a copy of a parse tree.
8073 */
8074static struct funcnode *
8075copyfunc(union node *n)
8076{
8077 struct funcnode *f;
8078 size_t blocksize;
8079
8080 funcblocksize = offsetof(struct funcnode, n);
8081 funcstringsize = 0;
8082 calcsize(n);
8083 blocksize = funcblocksize;
8084 f = ckmalloc(blocksize + funcstringsize);
8085 funcblock = (char *) f + offsetof(struct funcnode, n);
8086 funcstring = (char *) f + blocksize;
8087 copynode(n);
8088 f->count = 0;
8089 return f;
8090}
8091
8092/*
8093 * Define a shell function.
8094 */
8095static void
8096defun(char *name, union node *func)
8097{
8098 struct cmdentry entry;
8099
8100 INT_OFF;
8101 entry.cmdtype = CMDFUNCTION;
8102 entry.u.func = copyfunc(func);
8103 addcmdentry(name, &entry);
8104 INT_ON;
8105}
8106
Denis Vlasenko4b875702009-03-19 13:30:04 +00008107/* Reasons for skipping commands (see comment on breakcmd routine) */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008108#define SKIPBREAK (1 << 0)
8109#define SKIPCONT (1 << 1)
8110#define SKIPFUNC (1 << 2)
8111#define SKIPFILE (1 << 3)
8112#define SKIPEVAL (1 << 4)
Denis Vlasenko4b875702009-03-19 13:30:04 +00008113static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008114static int skipcount; /* number of levels to skip */
8115static int funcnest; /* depth of function calls */
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +00008116static int loopnest; /* current loop nesting level */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008117
Denis Vlasenko4b875702009-03-19 13:30:04 +00008118/* Forward decl way out to parsing code - dotrap needs it */
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008119static int evalstring(char *s, int mask);
8120
Denis Vlasenko4b875702009-03-19 13:30:04 +00008121/* Called to execute a trap.
8122 * Single callsite - at the end of evaltree().
8123 * If we return non-zero, exaltree raises EXEXIT exception.
8124 *
8125 * Perhaps we should avoid entering new trap handlers
8126 * while we are executing a trap handler. [is it a TODO?]
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008127 */
8128static int
8129dotrap(void)
8130{
Denis Vlasenko4b875702009-03-19 13:30:04 +00008131 uint8_t *g;
8132 int sig;
8133 uint8_t savestatus;
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008134
8135 savestatus = exitstatus;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02008136 pending_sig = 0;
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008137 xbarrier();
8138
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008139 TRACE(("dotrap entered\n"));
Denis Vlasenko4b875702009-03-19 13:30:04 +00008140 for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
8141 int want_exexit;
8142 char *t;
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008143
Denis Vlasenko4b875702009-03-19 13:30:04 +00008144 if (*g == 0)
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008145 continue;
Denis Vlasenko4b875702009-03-19 13:30:04 +00008146 t = trap[sig];
8147 /* non-trapped SIGINT is handled separately by raise_interrupt,
8148 * don't upset it by resetting gotsig[SIGINT-1] */
8149 if (sig == SIGINT && !t)
8150 continue;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008151
8152 TRACE(("sig %d is active, will run handler '%s'\n", sig, t));
Denis Vlasenko4b875702009-03-19 13:30:04 +00008153 *g = 0;
8154 if (!t)
8155 continue;
8156 want_exexit = evalstring(t, SKIPEVAL);
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008157 exitstatus = savestatus;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008158 if (want_exexit) {
Denis Vlasenkob21f3792009-03-19 23:09:58 +00008159 TRACE(("dotrap returns %d\n", want_exexit));
Denis Vlasenko4b875702009-03-19 13:30:04 +00008160 return want_exexit;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008161 }
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008162 }
8163
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008164 TRACE(("dotrap returns 0\n"));
Denis Vlasenko991a1da2008-02-10 19:02:53 +00008165 return 0;
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008166}
8167
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00008168/* forward declarations - evaluation is fairly recursive business... */
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008169static void evalloop(union node *, int);
8170static void evalfor(union node *, int);
8171static void evalcase(union node *, int);
8172static void evalsubshell(union node *, int);
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00008173static void expredir(union node *);
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008174static void evalpipe(union node *, int);
8175static void evalcommand(union node *, int);
Eric Andersenc470f442003-07-28 09:56:35 +00008176static int evalbltin(const struct builtincmd *, int, char **);
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008177static void prehash(union node *);
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00008178
Eric Andersen62483552001-07-10 06:09:16 +00008179/*
Eric Andersenc470f442003-07-28 09:56:35 +00008180 * Evaluate a parse tree. The value is left in the global variable
8181 * exitstatus.
Eric Andersen62483552001-07-10 06:09:16 +00008182 */
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008183static void
Eric Andersenc470f442003-07-28 09:56:35 +00008184evaltree(union node *n, int flags)
Eric Andersen62483552001-07-10 06:09:16 +00008185{
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008186 struct jmploc *volatile savehandler = exception_handler;
8187 struct jmploc jmploc;
Eric Andersenc470f442003-07-28 09:56:35 +00008188 int checkexit = 0;
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008189 void (*evalfn)(union node *, int);
Eric Andersenc470f442003-07-28 09:56:35 +00008190 int status;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008191 int int_level;
8192
8193 SAVE_INT(int_level);
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008194
Eric Andersenc470f442003-07-28 09:56:35 +00008195 if (n == NULL) {
8196 TRACE(("evaltree(NULL) called\n"));
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008197 goto out1;
Eric Andersen62483552001-07-10 06:09:16 +00008198 }
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008199 TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008200
8201 exception_handler = &jmploc;
8202 {
8203 int err = setjmp(jmploc.loc);
8204 if (err) {
8205 /* if it was a signal, check for trap handlers */
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008206 if (exception_type == EXSIG) {
Denis Vlasenkob21f3792009-03-19 23:09:58 +00008207 TRACE(("exception %d (EXSIG) in evaltree, err=%d\n",
8208 exception_type, err));
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008209 goto out;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008210 }
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008211 /* continue on the way out */
Denis Vlasenkob21f3792009-03-19 23:09:58 +00008212 TRACE(("exception %d in evaltree, propagating err=%d\n",
8213 exception_type, err));
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008214 exception_handler = savehandler;
8215 longjmp(exception_handler->loc, err);
8216 }
8217 }
8218
Eric Andersenc470f442003-07-28 09:56:35 +00008219 switch (n->type) {
8220 default:
Denis Vlasenkoa7189f02006-11-17 20:29:00 +00008221#if DEBUG
Eric Andersenc470f442003-07-28 09:56:35 +00008222 out1fmt("Node type = %d\n", n->type);
Denys Vlasenko8131eea2009-11-02 14:19:51 +01008223 fflush_all();
Eric Andersenc470f442003-07-28 09:56:35 +00008224 break;
8225#endif
8226 case NNOT:
8227 evaltree(n->nnot.com, EV_TESTED);
8228 status = !exitstatus;
8229 goto setstatus;
8230 case NREDIR:
8231 expredir(n->nredir.redirect);
8232 status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
8233 if (!status) {
8234 evaltree(n->nredir.n, flags & EV_TESTED);
8235 status = exitstatus;
8236 }
Denis Vlasenko34c73c42008-08-16 11:48:02 +00008237 popredir(/*drop:*/ 0, /*restore:*/ 0 /* not sure */);
Eric Andersenc470f442003-07-28 09:56:35 +00008238 goto setstatus;
8239 case NCMD:
8240 evalfn = evalcommand;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008241 checkexit:
Eric Andersenc470f442003-07-28 09:56:35 +00008242 if (eflag && !(flags & EV_TESTED))
8243 checkexit = ~0;
8244 goto calleval;
8245 case NFOR:
8246 evalfn = evalfor;
8247 goto calleval;
8248 case NWHILE:
8249 case NUNTIL:
8250 evalfn = evalloop;
8251 goto calleval;
8252 case NSUBSHELL:
8253 case NBACKGND:
8254 evalfn = evalsubshell;
8255 goto calleval;
8256 case NPIPE:
8257 evalfn = evalpipe;
8258 goto checkexit;
8259 case NCASE:
8260 evalfn = evalcase;
8261 goto calleval;
8262 case NAND:
8263 case NOR:
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008264 case NSEMI: {
8265
Eric Andersenc470f442003-07-28 09:56:35 +00008266#if NAND + 1 != NOR
8267#error NAND + 1 != NOR
8268#endif
8269#if NOR + 1 != NSEMI
8270#error NOR + 1 != NSEMI
8271#endif
Denis Vlasenko87d5fd92008-07-26 13:48:35 +00008272 unsigned is_or = n->type - NAND;
Eric Andersenc470f442003-07-28 09:56:35 +00008273 evaltree(
8274 n->nbinary.ch1,
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008275 (flags | ((is_or >> 1) - 1)) & EV_TESTED
Eric Andersenc470f442003-07-28 09:56:35 +00008276 );
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008277 if (!exitstatus == is_or)
Eric Andersenc470f442003-07-28 09:56:35 +00008278 break;
8279 if (!evalskip) {
8280 n = n->nbinary.ch2;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008281 evaln:
Eric Andersenc470f442003-07-28 09:56:35 +00008282 evalfn = evaltree;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008283 calleval:
Eric Andersenc470f442003-07-28 09:56:35 +00008284 evalfn(n, flags);
8285 break;
8286 }
8287 break;
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008288 }
Eric Andersenc470f442003-07-28 09:56:35 +00008289 case NIF:
8290 evaltree(n->nif.test, EV_TESTED);
8291 if (evalskip)
8292 break;
8293 if (exitstatus == 0) {
8294 n = n->nif.ifpart;
8295 goto evaln;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008296 }
8297 if (n->nif.elsepart) {
Eric Andersenc470f442003-07-28 09:56:35 +00008298 n = n->nif.elsepart;
8299 goto evaln;
8300 }
8301 goto success;
8302 case NDEFUN:
8303 defun(n->narg.text, n->narg.next);
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008304 success:
Eric Andersenc470f442003-07-28 09:56:35 +00008305 status = 0;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008306 setstatus:
Eric Andersenc470f442003-07-28 09:56:35 +00008307 exitstatus = status;
8308 break;
8309 }
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008310
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008311 out:
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008312 exception_handler = savehandler;
8313 out1:
8314 if (checkexit & exitstatus)
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00008315 evalskip |= SKIPEVAL;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02008316 else if (pending_sig && dotrap())
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00008317 goto exexit;
8318
8319 if (flags & EV_EXIT) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008320 exexit:
Denis Vlasenkob012b102007-02-19 22:43:01 +00008321 raise_exception(EXEXIT);
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00008322 }
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008323
8324 RESTORE_INT(int_level);
8325 TRACE(("leaving evaltree (no interrupts)\n"));
Eric Andersen62483552001-07-10 06:09:16 +00008326}
8327
Eric Andersenc470f442003-07-28 09:56:35 +00008328#if !defined(__alpha__) || (defined(__GNUC__) && __GNUC__ >= 3)
8329static
8330#endif
8331void evaltreenr(union node *, int) __attribute__ ((alias("evaltree"),__noreturn__));
8332
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008333static void
Eric Andersenc470f442003-07-28 09:56:35 +00008334evalloop(union node *n, int flags)
Eric Andersencb57d552001-06-28 07:25:16 +00008335{
8336 int status;
8337
8338 loopnest++;
8339 status = 0;
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008340 flags &= EV_TESTED;
Eric Andersencb57d552001-06-28 07:25:16 +00008341 for (;;) {
Eric Andersenc470f442003-07-28 09:56:35 +00008342 int i;
8343
Eric Andersencb57d552001-06-28 07:25:16 +00008344 evaltree(n->nbinary.ch1, EV_TESTED);
8345 if (evalskip) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008346 skipping:
8347 if (evalskip == SKIPCONT && --skipcount <= 0) {
Eric Andersencb57d552001-06-28 07:25:16 +00008348 evalskip = 0;
8349 continue;
8350 }
8351 if (evalskip == SKIPBREAK && --skipcount <= 0)
8352 evalskip = 0;
8353 break;
8354 }
Eric Andersenc470f442003-07-28 09:56:35 +00008355 i = exitstatus;
8356 if (n->type != NWHILE)
8357 i = !i;
8358 if (i != 0)
8359 break;
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008360 evaltree(n->nbinary.ch2, flags);
Eric Andersencb57d552001-06-28 07:25:16 +00008361 status = exitstatus;
8362 if (evalskip)
8363 goto skipping;
8364 }
8365 loopnest--;
8366 exitstatus = status;
8367}
8368
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008369static void
Eric Andersenc470f442003-07-28 09:56:35 +00008370evalfor(union node *n, int flags)
Eric Andersencb57d552001-06-28 07:25:16 +00008371{
8372 struct arglist arglist;
8373 union node *argp;
8374 struct strlist *sp;
8375 struct stackmark smark;
8376
8377 setstackmark(&smark);
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00008378 arglist.list = NULL;
Eric Andersencb57d552001-06-28 07:25:16 +00008379 arglist.lastp = &arglist.list;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008380 for (argp = n->nfor.args; argp; argp = argp->narg.next) {
Eric Andersencb57d552001-06-28 07:25:16 +00008381 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE | EXP_RECORD);
Eric Andersenc470f442003-07-28 09:56:35 +00008382 /* XXX */
Eric Andersencb57d552001-06-28 07:25:16 +00008383 if (evalskip)
8384 goto out;
8385 }
8386 *arglist.lastp = NULL;
8387
8388 exitstatus = 0;
8389 loopnest++;
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008390 flags &= EV_TESTED;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008391 for (sp = arglist.list; sp; sp = sp->next) {
Eric Andersencb57d552001-06-28 07:25:16 +00008392 setvar(n->nfor.var, sp->text, 0);
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008393 evaltree(n->nfor.body, flags);
Eric Andersencb57d552001-06-28 07:25:16 +00008394 if (evalskip) {
8395 if (evalskip == SKIPCONT && --skipcount <= 0) {
8396 evalskip = 0;
8397 continue;
8398 }
8399 if (evalskip == SKIPBREAK && --skipcount <= 0)
8400 evalskip = 0;
8401 break;
8402 }
8403 }
8404 loopnest--;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008405 out:
Eric Andersencb57d552001-06-28 07:25:16 +00008406 popstackmark(&smark);
8407}
8408
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008409static void
Eric Andersenc470f442003-07-28 09:56:35 +00008410evalcase(union node *n, int flags)
Eric Andersencb57d552001-06-28 07:25:16 +00008411{
8412 union node *cp;
8413 union node *patp;
8414 struct arglist arglist;
8415 struct stackmark smark;
8416
8417 setstackmark(&smark);
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00008418 arglist.list = NULL;
Eric Andersencb57d552001-06-28 07:25:16 +00008419 arglist.lastp = &arglist.list;
Eric Andersencb57d552001-06-28 07:25:16 +00008420 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
Eric Andersenc470f442003-07-28 09:56:35 +00008421 exitstatus = 0;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008422 for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
8423 for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
Eric Andersencb57d552001-06-28 07:25:16 +00008424 if (casematch(patp, arglist.list->text)) {
8425 if (evalskip == 0) {
8426 evaltree(cp->nclist.body, flags);
8427 }
8428 goto out;
8429 }
8430 }
8431 }
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008432 out:
Eric Andersencb57d552001-06-28 07:25:16 +00008433 popstackmark(&smark);
8434}
8435
Eric Andersenc470f442003-07-28 09:56:35 +00008436/*
8437 * Kick off a subshell to evaluate a tree.
8438 */
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008439static void
Eric Andersenc470f442003-07-28 09:56:35 +00008440evalsubshell(union node *n, int flags)
8441{
8442 struct job *jp;
8443 int backgnd = (n->type == NBACKGND);
8444 int status;
8445
8446 expredir(n->nredir.redirect);
Denys Vlasenko238bf182010-05-18 15:49:07 +02008447 if (!backgnd && (flags & EV_EXIT) && !may_have_traps)
Eric Andersenc470f442003-07-28 09:56:35 +00008448 goto nofork;
Denis Vlasenkob012b102007-02-19 22:43:01 +00008449 INT_OFF;
Denis Vlasenko68404f12008-03-17 09:00:54 +00008450 jp = makejob(/*n,*/ 1);
Eric Andersenc470f442003-07-28 09:56:35 +00008451 if (forkshell(jp, n, backgnd) == 0) {
Denys Vlasenko238bf182010-05-18 15:49:07 +02008452 /* child */
Denis Vlasenkob012b102007-02-19 22:43:01 +00008453 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00008454 flags |= EV_EXIT;
8455 if (backgnd)
Denys Vlasenko238bf182010-05-18 15:49:07 +02008456 flags &= ~EV_TESTED;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00008457 nofork:
Eric Andersenc470f442003-07-28 09:56:35 +00008458 redirect(n->nredir.redirect, 0);
8459 evaltreenr(n->nredir.n, flags);
8460 /* never returns */
8461 }
8462 status = 0;
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00008463 if (!backgnd)
Eric Andersenc470f442003-07-28 09:56:35 +00008464 status = waitforjob(jp);
8465 exitstatus = status;
Denis Vlasenkob012b102007-02-19 22:43:01 +00008466 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00008467}
8468
Eric Andersenc470f442003-07-28 09:56:35 +00008469/*
8470 * Compute the names of the files in a redirection list.
8471 */
Denis Vlasenko99eb8502007-02-23 21:09:49 +00008472static void fixredir(union node *, const char *, int);
Eric Andersenc470f442003-07-28 09:56:35 +00008473static void
8474expredir(union node *n)
8475{
8476 union node *redir;
8477
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008478 for (redir = n; redir; redir = redir->nfile.next) {
Eric Andersenc470f442003-07-28 09:56:35 +00008479 struct arglist fn;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008480
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00008481 fn.list = NULL;
Eric Andersenc470f442003-07-28 09:56:35 +00008482 fn.lastp = &fn.list;
8483 switch (redir->type) {
8484 case NFROMTO:
8485 case NFROM:
8486 case NTO:
Denis Vlasenko559691a2008-10-05 18:39:31 +00008487#if ENABLE_ASH_BASH_COMPAT
8488 case NTO2:
8489#endif
Eric Andersenc470f442003-07-28 09:56:35 +00008490 case NCLOBBER:
8491 case NAPPEND:
8492 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
Denis Vlasenko559691a2008-10-05 18:39:31 +00008493#if ENABLE_ASH_BASH_COMPAT
8494 store_expfname:
8495#endif
Eric Andersenc470f442003-07-28 09:56:35 +00008496 redir->nfile.expfname = fn.list->text;
8497 break;
8498 case NFROMFD:
Denis Vlasenko559691a2008-10-05 18:39:31 +00008499 case NTOFD: /* >& */
Eric Andersenc470f442003-07-28 09:56:35 +00008500 if (redir->ndup.vname) {
8501 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008502 if (fn.list == NULL)
Denis Vlasenkob012b102007-02-19 22:43:01 +00008503 ash_msg_and_raise_error("redir error");
Denis Vlasenko559691a2008-10-05 18:39:31 +00008504#if ENABLE_ASH_BASH_COMPAT
8505//FIXME: we used expandarg with different args!
8506 if (!isdigit_str9(fn.list->text)) {
8507 /* >&file, not >&fd */
8508 if (redir->nfile.fd != 1) /* 123>&file - BAD */
8509 ash_msg_and_raise_error("redir error");
8510 redir->type = NTO2;
8511 goto store_expfname;
8512 }
8513#endif
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008514 fixredir(redir, fn.list->text, 1);
Eric Andersenc470f442003-07-28 09:56:35 +00008515 }
8516 break;
8517 }
8518 }
8519}
8520
Eric Andersencb57d552001-06-28 07:25:16 +00008521/*
Eric Andersencb57d552001-06-28 07:25:16 +00008522 * Evaluate a pipeline. All the processes in the pipeline are children
8523 * of the process creating the pipeline. (This differs from some versions
8524 * of the shell, which make the last process in a pipeline the parent
8525 * of all the rest.)
8526 */
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008527static void
Eric Andersenc470f442003-07-28 09:56:35 +00008528evalpipe(union node *n, int flags)
Eric Andersencb57d552001-06-28 07:25:16 +00008529{
8530 struct job *jp;
8531 struct nodelist *lp;
8532 int pipelen;
8533 int prevfd;
8534 int pip[2];
8535
Eric Andersenc470f442003-07-28 09:56:35 +00008536 TRACE(("evalpipe(0x%lx) called\n", (long)n));
Eric Andersencb57d552001-06-28 07:25:16 +00008537 pipelen = 0;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008538 for (lp = n->npipe.cmdlist; lp; lp = lp->next)
Eric Andersencb57d552001-06-28 07:25:16 +00008539 pipelen++;
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008540 flags |= EV_EXIT;
Denis Vlasenkob012b102007-02-19 22:43:01 +00008541 INT_OFF;
Denis Vlasenko68404f12008-03-17 09:00:54 +00008542 jp = makejob(/*n,*/ pipelen);
Eric Andersencb57d552001-06-28 07:25:16 +00008543 prevfd = -1;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008544 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008545 prehash(lp->n);
Eric Andersencb57d552001-06-28 07:25:16 +00008546 pip[1] = -1;
8547 if (lp->next) {
8548 if (pipe(pip) < 0) {
8549 close(prevfd);
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00008550 ash_msg_and_raise_error("pipe call failed");
Eric Andersencb57d552001-06-28 07:25:16 +00008551 }
8552 }
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00008553 if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
Denis Vlasenkob012b102007-02-19 22:43:01 +00008554 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00008555 if (pip[1] >= 0) {
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008556 close(pip[0]);
Eric Andersencb57d552001-06-28 07:25:16 +00008557 }
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008558 if (prevfd > 0) {
8559 dup2(prevfd, 0);
8560 close(prevfd);
8561 }
8562 if (pip[1] > 1) {
8563 dup2(pip[1], 1);
8564 close(pip[1]);
8565 }
Eric Andersenc470f442003-07-28 09:56:35 +00008566 evaltreenr(lp->n, flags);
8567 /* never returns */
Eric Andersencb57d552001-06-28 07:25:16 +00008568 }
8569 if (prevfd >= 0)
8570 close(prevfd);
8571 prevfd = pip[0];
Denis Vlasenkob9e70dd2009-03-20 01:24:08 +00008572 /* Don't want to trigger debugging */
8573 if (pip[1] != -1)
8574 close(pip[1]);
Eric Andersencb57d552001-06-28 07:25:16 +00008575 }
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00008576 if (n->npipe.pipe_backgnd == 0) {
Eric Andersencb57d552001-06-28 07:25:16 +00008577 exitstatus = waitforjob(jp);
8578 TRACE(("evalpipe: job done exit status %d\n", exitstatus));
Eric Andersencb57d552001-06-28 07:25:16 +00008579 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00008580 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00008581}
8582
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008583/*
8584 * Controls whether the shell is interactive or not.
8585 */
8586static void
8587setinteractive(int on)
8588{
Denis Vlasenkob07a4962008-06-22 13:16:23 +00008589 static smallint is_interactive;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008590
8591 if (++on == is_interactive)
8592 return;
8593 is_interactive = on;
8594 setsignal(SIGINT);
8595 setsignal(SIGQUIT);
8596 setsignal(SIGTERM);
8597#if !ENABLE_FEATURE_SH_EXTRA_QUIET
8598 if (is_interactive > 1) {
8599 /* Looks like they want an interactive shell */
Denis Vlasenkoca525b42007-06-13 12:27:17 +00008600 static smallint did_banner;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008601
Denis Vlasenkoca525b42007-06-13 12:27:17 +00008602 if (!did_banner) {
Denys Vlasenkoc34c0332009-09-29 12:25:30 +02008603 /* note: ash and hush share this string */
8604 out1fmt("\n\n%s %s\n"
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008605 "Enter 'help' for a list of built-in commands."
8606 "\n\n",
Denys Vlasenkoc34c0332009-09-29 12:25:30 +02008607 bb_banner,
8608 "built-in shell (ash)"
8609 );
Denis Vlasenkoca525b42007-06-13 12:27:17 +00008610 did_banner = 1;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008611 }
8612 }
8613#endif
8614}
8615
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008616static void
8617optschanged(void)
8618{
8619#if DEBUG
8620 opentrace();
8621#endif
8622 setinteractive(iflag);
8623 setjobctl(mflag);
Denis Vlasenkob07a4962008-06-22 13:16:23 +00008624#if ENABLE_FEATURE_EDITING_VI
8625 if (viflag)
8626 line_input_state->flags |= VI_MODE;
8627 else
8628 line_input_state->flags &= ~VI_MODE;
8629#else
8630 viflag = 0; /* forcibly keep the option off */
8631#endif
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008632}
8633
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008634static struct localvar *localvars;
8635
8636/*
8637 * Called after a function returns.
8638 * Interrupts must be off.
8639 */
8640static void
8641poplocalvars(void)
8642{
8643 struct localvar *lvp;
8644 struct var *vp;
8645
8646 while ((lvp = localvars) != NULL) {
8647 localvars = lvp->next;
8648 vp = lvp->vp;
Denys Vlasenko883cea42009-07-11 15:31:59 +02008649 TRACE(("poplocalvar %s\n", vp ? vp->text : "-"));
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008650 if (vp == NULL) { /* $- saved */
8651 memcpy(optlist, lvp->text, sizeof(optlist));
8652 free((char*)lvp->text);
8653 optschanged();
8654 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02008655 unsetvar(vp->var_text);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008656 } else {
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02008657 if (vp->var_func)
8658 vp->var_func(var_end(lvp->text));
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008659 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02008660 free((char*)vp->var_text);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008661 vp->flags = lvp->flags;
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02008662 vp->var_text = lvp->text;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008663 }
8664 free(lvp);
8665 }
8666}
8667
8668static int
8669evalfun(struct funcnode *func, int argc, char **argv, int flags)
8670{
8671 volatile struct shparam saveparam;
8672 struct localvar *volatile savelocalvars;
8673 struct jmploc *volatile savehandler;
8674 struct jmploc jmploc;
8675 int e;
8676
8677 saveparam = shellparam;
8678 savelocalvars = localvars;
8679 e = setjmp(jmploc.loc);
8680 if (e) {
8681 goto funcdone;
8682 }
8683 INT_OFF;
8684 savehandler = exception_handler;
8685 exception_handler = &jmploc;
8686 localvars = NULL;
Denis Vlasenko01631112007-12-16 17:20:38 +00008687 shellparam.malloced = 0;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008688 func->count++;
8689 funcnest++;
8690 INT_ON;
8691 shellparam.nparam = argc - 1;
8692 shellparam.p = argv + 1;
8693#if ENABLE_ASH_GETOPTS
8694 shellparam.optind = 1;
8695 shellparam.optoff = -1;
8696#endif
8697 evaltree(&func->n, flags & EV_TESTED);
Denis Vlasenko01631112007-12-16 17:20:38 +00008698 funcdone:
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008699 INT_OFF;
8700 funcnest--;
8701 freefunc(func);
8702 poplocalvars();
8703 localvars = savelocalvars;
8704 freeparam(&shellparam);
8705 shellparam = saveparam;
8706 exception_handler = savehandler;
8707 INT_ON;
8708 evalskip &= ~SKIPFUNC;
8709 return e;
8710}
8711
Denis Vlasenko131ae172007-02-18 13:00:19 +00008712#if ENABLE_ASH_CMDCMD
Denis Vlasenkoaa744452007-02-23 01:04:22 +00008713static char **
8714parse_command_args(char **argv, const char **path)
Eric Andersenc470f442003-07-28 09:56:35 +00008715{
8716 char *cp, c;
8717
8718 for (;;) {
8719 cp = *++argv;
8720 if (!cp)
8721 return 0;
8722 if (*cp++ != '-')
8723 break;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008724 c = *cp++;
8725 if (!c)
Eric Andersenc470f442003-07-28 09:56:35 +00008726 break;
8727 if (c == '-' && !*cp) {
8728 argv++;
8729 break;
8730 }
8731 do {
8732 switch (c) {
8733 case 'p':
Denis Vlasenkof5f75c52007-06-12 22:35:19 +00008734 *path = bb_default_path;
Eric Andersenc470f442003-07-28 09:56:35 +00008735 break;
8736 default:
8737 /* run 'typecmd' for other options */
8738 return 0;
8739 }
Denis Vlasenko9650f362007-02-23 01:04:37 +00008740 c = *cp++;
8741 } while (c);
Eric Andersenc470f442003-07-28 09:56:35 +00008742 }
8743 return argv;
8744}
8745#endif
8746
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008747/*
8748 * Make a variable a local variable. When a variable is made local, it's
8749 * value and flags are saved in a localvar structure. The saved values
8750 * will be restored when the shell function returns. We handle the name
8751 * "-" as a special case.
8752 */
8753static void
8754mklocal(char *name)
8755{
8756 struct localvar *lvp;
8757 struct var **vpp;
8758 struct var *vp;
8759
8760 INT_OFF;
Denis Vlasenko838ffd52008-02-21 04:32:08 +00008761 lvp = ckzalloc(sizeof(struct localvar));
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008762 if (LONE_DASH(name)) {
8763 char *p;
8764 p = ckmalloc(sizeof(optlist));
8765 lvp->text = memcpy(p, optlist, sizeof(optlist));
8766 vp = NULL;
8767 } else {
8768 char *eq;
8769
8770 vpp = hashvar(name);
8771 vp = *findvar(vpp, name);
8772 eq = strchr(name, '=');
8773 if (vp == NULL) {
8774 if (eq)
8775 setvareq(name, VSTRFIXED);
8776 else
8777 setvar(name, NULL, VSTRFIXED);
8778 vp = *vpp; /* the new variable */
8779 lvp->flags = VUNSET;
8780 } else {
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02008781 lvp->text = vp->var_text;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008782 lvp->flags = vp->flags;
8783 vp->flags |= VSTRFIXED|VTEXTFIXED;
8784 if (eq)
8785 setvareq(name, 0);
8786 }
8787 }
8788 lvp->vp = vp;
8789 lvp->next = localvars;
8790 localvars = lvp;
8791 INT_ON;
8792}
8793
8794/*
8795 * The "local" command.
8796 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008797static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008798localcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008799{
8800 char *name;
8801
8802 argv = argptr;
8803 while ((name = *argv++) != NULL) {
8804 mklocal(name);
8805 }
8806 return 0;
8807}
8808
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008809static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008810falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008811{
8812 return 1;
8813}
8814
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008815static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008816truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008817{
8818 return 0;
8819}
8820
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008821static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008822execcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008823{
Denis Vlasenko68404f12008-03-17 09:00:54 +00008824 if (argv[1]) {
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008825 iflag = 0; /* exit on error */
8826 mflag = 0;
8827 optschanged();
8828 shellexec(argv + 1, pathval(), 0);
8829 }
8830 return 0;
8831}
8832
8833/*
8834 * The return command.
8835 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008836static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008837returncmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008838{
8839 /*
8840 * If called outside a function, do what ksh does;
8841 * skip the rest of the file.
8842 */
8843 evalskip = funcnest ? SKIPFUNC : SKIPFILE;
8844 return argv[1] ? number(argv[1]) : exitstatus;
8845}
8846
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008847/* Forward declarations for builtintab[] */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008848static int breakcmd(int, char **) FAST_FUNC;
8849static int dotcmd(int, char **) FAST_FUNC;
8850static int evalcmd(int, char **) FAST_FUNC;
8851static int exitcmd(int, char **) FAST_FUNC;
8852static int exportcmd(int, char **) FAST_FUNC;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008853#if ENABLE_ASH_GETOPTS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008854static int getoptscmd(int, char **) FAST_FUNC;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008855#endif
Denis Vlasenko52764022007-02-24 13:42:56 +00008856#if !ENABLE_FEATURE_SH_EXTRA_QUIET
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008857static int helpcmd(int, char **) FAST_FUNC;
Denis Vlasenko52764022007-02-24 13:42:56 +00008858#endif
Mike Frysinger98c52642009-04-02 10:02:37 +00008859#if ENABLE_SH_MATH_SUPPORT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008860static int letcmd(int, char **) FAST_FUNC;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008861#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008862static int readcmd(int, char **) FAST_FUNC;
8863static int setcmd(int, char **) FAST_FUNC;
8864static int shiftcmd(int, char **) FAST_FUNC;
8865static int timescmd(int, char **) FAST_FUNC;
8866static int trapcmd(int, char **) FAST_FUNC;
8867static int umaskcmd(int, char **) FAST_FUNC;
8868static int unsetcmd(int, char **) FAST_FUNC;
8869static int ulimitcmd(int, char **) FAST_FUNC;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008870
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008871#define BUILTIN_NOSPEC "0"
8872#define BUILTIN_SPECIAL "1"
8873#define BUILTIN_REGULAR "2"
8874#define BUILTIN_SPEC_REG "3"
8875#define BUILTIN_ASSIGN "4"
8876#define BUILTIN_SPEC_ASSG "5"
8877#define BUILTIN_REG_ASSG "6"
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008878#define BUILTIN_SPEC_REG_ASSG "7"
8879
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008880/* Stubs for calling non-FAST_FUNC's */
Denys Vlasenko2634bf32009-06-09 18:40:07 +02008881#if ENABLE_ASH_BUILTIN_ECHO
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008882static int FAST_FUNC echocmd(int argc, char **argv) { return echo_main(argc, argv); }
Denys Vlasenko2634bf32009-06-09 18:40:07 +02008883#endif
8884#if ENABLE_ASH_BUILTIN_PRINTF
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008885static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
Denys Vlasenko2634bf32009-06-09 18:40:07 +02008886#endif
8887#if ENABLE_ASH_BUILTIN_TEST
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008888static int FAST_FUNC testcmd(int argc, char **argv) { return test_main(argc, argv); }
Denys Vlasenko2634bf32009-06-09 18:40:07 +02008889#endif
Denis Vlasenko468aea22008-04-01 14:47:57 +00008890
Denis Vlasenkof7d56652008-03-25 05:51:41 +00008891/* Keep these in proper order since it is searched via bsearch() */
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008892static const struct builtincmd builtintab[] = {
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008893 { BUILTIN_SPEC_REG "." , dotcmd },
8894 { BUILTIN_SPEC_REG ":" , truecmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008895#if ENABLE_ASH_BUILTIN_TEST
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008896 { BUILTIN_REGULAR "[" , testcmd },
Denis Vlasenko80591b02008-03-25 07:49:43 +00008897#if ENABLE_ASH_BASH_COMPAT
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008898 { BUILTIN_REGULAR "[[" , testcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008899#endif
Denis Vlasenko80591b02008-03-25 07:49:43 +00008900#endif
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008901#if ENABLE_ASH_ALIAS
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008902 { BUILTIN_REG_ASSG "alias" , aliascmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008903#endif
8904#if JOBS
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008905 { BUILTIN_REGULAR "bg" , fg_bgcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008906#endif
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008907 { BUILTIN_SPEC_REG "break" , breakcmd },
8908 { BUILTIN_REGULAR "cd" , cdcmd },
8909 { BUILTIN_NOSPEC "chdir" , cdcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008910#if ENABLE_ASH_CMDCMD
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008911 { BUILTIN_REGULAR "command" , commandcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008912#endif
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008913 { BUILTIN_SPEC_REG "continue", breakcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008914#if ENABLE_ASH_BUILTIN_ECHO
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008915 { BUILTIN_REGULAR "echo" , echocmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008916#endif
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008917 { BUILTIN_SPEC_REG "eval" , evalcmd },
8918 { BUILTIN_SPEC_REG "exec" , execcmd },
8919 { BUILTIN_SPEC_REG "exit" , exitcmd },
8920 { BUILTIN_SPEC_REG_ASSG "export" , exportcmd },
8921 { BUILTIN_REGULAR "false" , falsecmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008922#if JOBS
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008923 { BUILTIN_REGULAR "fg" , fg_bgcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008924#endif
8925#if ENABLE_ASH_GETOPTS
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008926 { BUILTIN_REGULAR "getopts" , getoptscmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008927#endif
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008928 { BUILTIN_NOSPEC "hash" , hashcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008929#if !ENABLE_FEATURE_SH_EXTRA_QUIET
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008930 { BUILTIN_NOSPEC "help" , helpcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008931#endif
8932#if JOBS
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008933 { BUILTIN_REGULAR "jobs" , jobscmd },
8934 { BUILTIN_REGULAR "kill" , killcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008935#endif
Mike Frysinger98c52642009-04-02 10:02:37 +00008936#if ENABLE_SH_MATH_SUPPORT
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008937 { BUILTIN_NOSPEC "let" , letcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008938#endif
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008939 { BUILTIN_ASSIGN "local" , localcmd },
Denis Vlasenkocd2663f2008-06-01 22:36:39 +00008940#if ENABLE_ASH_BUILTIN_PRINTF
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008941 { BUILTIN_REGULAR "printf" , printfcmd },
Denis Vlasenkocd2663f2008-06-01 22:36:39 +00008942#endif
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008943 { BUILTIN_NOSPEC "pwd" , pwdcmd },
8944 { BUILTIN_REGULAR "read" , readcmd },
8945 { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
8946 { BUILTIN_SPEC_REG "return" , returncmd },
8947 { BUILTIN_SPEC_REG "set" , setcmd },
8948 { BUILTIN_SPEC_REG "shift" , shiftcmd },
Denys Vlasenko82731b42010-05-17 17:49:52 +02008949#if ENABLE_ASH_BASH_COMPAT
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008950 { BUILTIN_SPEC_REG "source" , dotcmd },
Denys Vlasenko82731b42010-05-17 17:49:52 +02008951#endif
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008952#if ENABLE_ASH_BUILTIN_TEST
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008953 { BUILTIN_REGULAR "test" , testcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008954#endif
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008955 { BUILTIN_SPEC_REG "times" , timescmd },
8956 { BUILTIN_SPEC_REG "trap" , trapcmd },
8957 { BUILTIN_REGULAR "true" , truecmd },
8958 { BUILTIN_NOSPEC "type" , typecmd },
8959 { BUILTIN_NOSPEC "ulimit" , ulimitcmd },
8960 { BUILTIN_REGULAR "umask" , umaskcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008961#if ENABLE_ASH_ALIAS
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008962 { BUILTIN_REGULAR "unalias" , unaliascmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008963#endif
Denys Vlasenko023a08f2010-03-26 15:53:33 +01008964 { BUILTIN_SPEC_REG "unset" , unsetcmd },
8965 { BUILTIN_REGULAR "wait" , waitcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008966};
8967
Denis Vlasenko80591b02008-03-25 07:49:43 +00008968/* Should match the above table! */
8969#define COMMANDCMD (builtintab + \
8970 2 + \
8971 1 * ENABLE_ASH_BUILTIN_TEST + \
8972 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
8973 1 * ENABLE_ASH_ALIAS + \
8974 1 * ENABLE_ASH_JOB_CONTROL + \
8975 3)
8976#define EXECCMD (builtintab + \
8977 2 + \
8978 1 * ENABLE_ASH_BUILTIN_TEST + \
8979 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
8980 1 * ENABLE_ASH_ALIAS + \
8981 1 * ENABLE_ASH_JOB_CONTROL + \
8982 3 + \
8983 1 * ENABLE_ASH_CMDCMD + \
8984 1 + \
8985 ENABLE_ASH_BUILTIN_ECHO + \
8986 1)
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008987
8988/*
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008989 * Search the table of builtin commands.
8990 */
8991static struct builtincmd *
8992find_builtin(const char *name)
8993{
8994 struct builtincmd *bp;
8995
8996 bp = bsearch(
Denis Vlasenko80b8b392007-06-25 10:55:35 +00008997 name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008998 pstrcmp
8999 );
9000 return bp;
9001}
9002
9003/*
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00009004 * Execute a simple command.
9005 */
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00009006static int
9007isassignment(const char *p)
Paul Foxc3850c82005-07-20 18:23:39 +00009008{
9009 const char *q = endofname(p);
9010 if (p == q)
9011 return 0;
9012 return *q == '=';
9013}
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009014static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00009015bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00009016{
9017 /* Preserve exitstatus of a previous possible redirection
9018 * as POSIX mandates */
9019 return back_exitstatus;
9020}
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02009021static void
Eric Andersenc470f442003-07-28 09:56:35 +00009022evalcommand(union node *cmd, int flags)
9023{
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00009024 static const struct builtincmd null_bltin = {
9025 "\0\0", bltincmd /* why three NULs? */
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00009026 };
Eric Andersenc470f442003-07-28 09:56:35 +00009027 struct stackmark smark;
9028 union node *argp;
9029 struct arglist arglist;
9030 struct arglist varlist;
9031 char **argv;
9032 int argc;
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009033 const struct strlist *sp;
Eric Andersenc470f442003-07-28 09:56:35 +00009034 struct cmdentry cmdentry;
9035 struct job *jp;
9036 char *lastarg;
9037 const char *path;
9038 int spclbltin;
Eric Andersenc470f442003-07-28 09:56:35 +00009039 int status;
9040 char **nargv;
Paul Foxc3850c82005-07-20 18:23:39 +00009041 struct builtincmd *bcmd;
Denis Vlasenko34c73c42008-08-16 11:48:02 +00009042 smallint cmd_is_exec;
9043 smallint pseudovarflag = 0;
Eric Andersenc470f442003-07-28 09:56:35 +00009044
9045 /* First expand the arguments. */
9046 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
9047 setstackmark(&smark);
9048 back_exitstatus = 0;
9049
9050 cmdentry.cmdtype = CMDBUILTIN;
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00009051 cmdentry.u.cmd = &null_bltin;
Eric Andersenc470f442003-07-28 09:56:35 +00009052 varlist.lastp = &varlist.list;
9053 *varlist.lastp = NULL;
9054 arglist.lastp = &arglist.list;
9055 *arglist.lastp = NULL;
9056
9057 argc = 0;
Denis Vlasenkob012b102007-02-19 22:43:01 +00009058 if (cmd->ncmd.args) {
Paul Foxc3850c82005-07-20 18:23:39 +00009059 bcmd = find_builtin(cmd->ncmd.args->narg.text);
9060 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
9061 }
9062
Eric Andersenc470f442003-07-28 09:56:35 +00009063 for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
9064 struct strlist **spp;
9065
9066 spp = arglist.lastp;
"Vladimir N. Oleynik"bef14d72005-09-05 13:25:11 +00009067 if (pseudovarflag && isassignment(argp->narg.text))
Paul Foxc3850c82005-07-20 18:23:39 +00009068 expandarg(argp, &arglist, EXP_VARTILDE);
9069 else
9070 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
9071
Eric Andersenc470f442003-07-28 09:56:35 +00009072 for (sp = *spp; sp; sp = sp->next)
9073 argc++;
9074 }
9075
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +00009076 argv = nargv = stalloc(sizeof(char *) * (argc + 1));
Denis Vlasenko2da584f2007-02-19 22:44:05 +00009077 for (sp = arglist.list; sp; sp = sp->next) {
Eric Andersenc470f442003-07-28 09:56:35 +00009078 TRACE(("evalcommand arg: %s\n", sp->text));
9079 *nargv++ = sp->text;
9080 }
9081 *nargv = NULL;
9082
9083 lastarg = NULL;
9084 if (iflag && funcnest == 0 && argc > 0)
9085 lastarg = nargv[-1];
9086
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009087 preverrout_fd = 2;
Eric Andersenc470f442003-07-28 09:56:35 +00009088 expredir(cmd->ncmd.redirect);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009089 status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
Eric Andersenc470f442003-07-28 09:56:35 +00009090
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02009091 path = vpath.var_text;
Eric Andersenc470f442003-07-28 09:56:35 +00009092 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
9093 struct strlist **spp;
9094 char *p;
9095
9096 spp = varlist.lastp;
9097 expandarg(argp, &varlist, EXP_VARTILDE);
9098
9099 /*
9100 * Modify the command lookup path, if a PATH= assignment
9101 * is present
9102 */
9103 p = (*spp)->text;
Denys Vlasenko8837c5d2010-06-02 12:56:18 +02009104 if (varcmp(p, path) == 0)
Eric Andersenc470f442003-07-28 09:56:35 +00009105 path = p;
9106 }
9107
9108 /* Print the command if xflag is set. */
9109 if (xflag) {
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009110 int n;
9111 const char *p = " %s";
Eric Andersenc470f442003-07-28 09:56:35 +00009112
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009113 p++;
Denis Vlasenko0de37e12007-10-17 11:08:53 +00009114 fdprintf(preverrout_fd, p, expandstr(ps4val()));
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009115
9116 sp = varlist.list;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +00009117 for (n = 0; n < 2; n++) {
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009118 while (sp) {
Denis Vlasenko0de37e12007-10-17 11:08:53 +00009119 fdprintf(preverrout_fd, p, sp->text);
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009120 sp = sp->next;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +00009121 if (*p == '%') {
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009122 p--;
9123 }
9124 }
9125 sp = arglist.list;
9126 }
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00009127 safe_write(preverrout_fd, "\n", 1);
Eric Andersenc470f442003-07-28 09:56:35 +00009128 }
9129
9130 cmd_is_exec = 0;
9131 spclbltin = -1;
9132
9133 /* Now locate the command. */
9134 if (argc) {
9135 const char *oldpath;
9136 int cmd_flag = DO_ERR;
9137
9138 path += 5;
9139 oldpath = path;
9140 for (;;) {
9141 find_command(argv[0], &cmdentry, cmd_flag, path);
9142 if (cmdentry.cmdtype == CMDUNKNOWN) {
Denys Vlasenko8131eea2009-11-02 14:19:51 +01009143 flush_stdout_stderr();
Denis Vlasenko6514c5e2008-07-24 13:41:37 +00009144 status = 127;
Eric Andersenc470f442003-07-28 09:56:35 +00009145 goto bail;
9146 }
9147
9148 /* implement bltin and command here */
9149 if (cmdentry.cmdtype != CMDBUILTIN)
9150 break;
9151 if (spclbltin < 0)
9152 spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
9153 if (cmdentry.u.cmd == EXECCMD)
Denis Vlasenko34c73c42008-08-16 11:48:02 +00009154 cmd_is_exec = 1;
Denis Vlasenko131ae172007-02-18 13:00:19 +00009155#if ENABLE_ASH_CMDCMD
Eric Andersenc470f442003-07-28 09:56:35 +00009156 if (cmdentry.u.cmd == COMMANDCMD) {
Eric Andersenc470f442003-07-28 09:56:35 +00009157 path = oldpath;
9158 nargv = parse_command_args(argv, &path);
9159 if (!nargv)
9160 break;
9161 argc -= nargv - argv;
9162 argv = nargv;
9163 cmd_flag |= DO_NOFUNC;
9164 } else
9165#endif
9166 break;
9167 }
9168 }
9169
9170 if (status) {
9171 /* We have a redirection error. */
9172 if (spclbltin > 0)
Denis Vlasenkob012b102007-02-19 22:43:01 +00009173 raise_exception(EXERROR);
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009174 bail:
Eric Andersenc470f442003-07-28 09:56:35 +00009175 exitstatus = status;
9176 goto out;
9177 }
9178
9179 /* Execute the command. */
9180 switch (cmdentry.cmdtype) {
Denys Vlasenko42c4b2e2010-05-18 16:13:56 +02009181 default: {
Denis Vlasenkobe54d6b2008-10-27 14:25:52 +00009182
Denis Vlasenko9bc80d72008-04-12 20:07:53 +00009183#if ENABLE_FEATURE_SH_NOFORK
Denys Vlasenko42c4b2e2010-05-18 16:13:56 +02009184/* (1) BUG: if variables are set, we need to fork, or save/restore them
9185 * around run_nofork_applet() call.
9186 * (2) Should this check also be done in forkshell()?
9187 * (perhaps it should, so that "VAR=VAL nofork" at least avoids exec...)
9188 */
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00009189 /* find_command() encodes applet_no as (-2 - applet_no) */
9190 int applet_no = (- cmdentry.u.index - 2);
Denis Vlasenko9bc80d72008-04-12 20:07:53 +00009191 if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
Denis Vlasenko9bc80d72008-04-12 20:07:53 +00009192 listsetvar(varlist.list, VEXPORT|VSTACK);
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00009193 /* run <applet>_main() */
9194 exitstatus = run_nofork_applet(applet_no, argv);
Denis Vlasenko9bc80d72008-04-12 20:07:53 +00009195 break;
9196 }
Denis Vlasenko9bc80d72008-04-12 20:07:53 +00009197#endif
Denys Vlasenko42c4b2e2010-05-18 16:13:56 +02009198 /* Can we avoid forking off? For example, very last command
9199 * in a script or a subshell does not need forking,
9200 * we can just exec it.
9201 */
Denys Vlasenko238bf182010-05-18 15:49:07 +02009202 if (!(flags & EV_EXIT) || may_have_traps) {
Denys Vlasenko42c4b2e2010-05-18 16:13:56 +02009203 /* No, forking off a child is necessary */
Denis Vlasenkob012b102007-02-19 22:43:01 +00009204 INT_OFF;
Denis Vlasenko68404f12008-03-17 09:00:54 +00009205 jp = makejob(/*cmd,*/ 1);
Eric Andersenc470f442003-07-28 09:56:35 +00009206 if (forkshell(jp, cmd, FORK_FG) != 0) {
Denys Vlasenko238bf182010-05-18 15:49:07 +02009207 /* parent */
Eric Andersenc470f442003-07-28 09:56:35 +00009208 exitstatus = waitforjob(jp);
Denis Vlasenkob012b102007-02-19 22:43:01 +00009209 INT_ON;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00009210 TRACE(("forked child exited with %d\n", exitstatus));
Eric Andersenc470f442003-07-28 09:56:35 +00009211 break;
9212 }
Denys Vlasenko238bf182010-05-18 15:49:07 +02009213 /* child */
Denis Vlasenkob012b102007-02-19 22:43:01 +00009214 FORCE_INT_ON;
Denys Vlasenkoc7f95d22010-05-18 15:52:23 +02009215 /* fall through to exec'ing external program */
Eric Andersenc470f442003-07-28 09:56:35 +00009216 }
9217 listsetvar(varlist.list, VEXPORT|VSTACK);
9218 shellexec(argv, path, cmdentry.u.index);
9219 /* NOTREACHED */
Denys Vlasenko42c4b2e2010-05-18 16:13:56 +02009220 } /* default */
Eric Andersenc470f442003-07-28 09:56:35 +00009221 case CMDBUILTIN:
9222 cmdenviron = varlist.list;
9223 if (cmdenviron) {
9224 struct strlist *list = cmdenviron;
9225 int i = VNOSET;
9226 if (spclbltin > 0 || argc == 0) {
9227 i = 0;
9228 if (cmd_is_exec && argc > 1)
9229 i = VEXPORT;
9230 }
9231 listsetvar(list, i);
9232 }
Denis Vlasenkobe54d6b2008-10-27 14:25:52 +00009233 /* Tight loop with builtins only:
9234 * "while kill -0 $child; do true; done"
9235 * will never exit even if $child died, unless we do this
9236 * to reap the zombie and make kill detect that it's gone: */
9237 dowait(DOWAIT_NONBLOCK, NULL);
9238
Eric Andersenc470f442003-07-28 09:56:35 +00009239 if (evalbltin(cmdentry.u.cmd, argc, argv)) {
9240 int exit_status;
Denis Vlasenko7f88e342009-03-19 03:36:18 +00009241 int i = exception_type;
Eric Andersenc470f442003-07-28 09:56:35 +00009242 if (i == EXEXIT)
9243 goto raise;
Eric Andersenc470f442003-07-28 09:56:35 +00009244 exit_status = 2;
Eric Andersenc470f442003-07-28 09:56:35 +00009245 if (i == EXINT)
Denis Vlasenko991a1da2008-02-10 19:02:53 +00009246 exit_status = 128 + SIGINT;
Eric Andersenc470f442003-07-28 09:56:35 +00009247 if (i == EXSIG)
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02009248 exit_status = 128 + pending_sig;
Eric Andersenc470f442003-07-28 09:56:35 +00009249 exitstatus = exit_status;
Eric Andersenc470f442003-07-28 09:56:35 +00009250 if (i == EXINT || spclbltin > 0) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009251 raise:
Denis Vlasenko2da584f2007-02-19 22:44:05 +00009252 longjmp(exception_handler->loc, 1);
Eric Andersenc470f442003-07-28 09:56:35 +00009253 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00009254 FORCE_INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00009255 }
9256 break;
9257
9258 case CMDFUNCTION:
9259 listsetvar(varlist.list, 0);
Denis Vlasenkobe54d6b2008-10-27 14:25:52 +00009260 /* See above for the rationale */
9261 dowait(DOWAIT_NONBLOCK, NULL);
Eric Andersenc470f442003-07-28 09:56:35 +00009262 if (evalfun(cmdentry.u.func, argc, argv, flags))
9263 goto raise;
9264 break;
Denys Vlasenko42c4b2e2010-05-18 16:13:56 +02009265
9266 } /* switch */
Eric Andersenc470f442003-07-28 09:56:35 +00009267
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009268 out:
Denis Vlasenko34c73c42008-08-16 11:48:02 +00009269 popredir(/*drop:*/ cmd_is_exec, /*restore:*/ cmd_is_exec);
Denis Vlasenko6514c5e2008-07-24 13:41:37 +00009270 if (lastarg) {
Eric Andersenc470f442003-07-28 09:56:35 +00009271 /* dsl: I think this is intended to be used to support
9272 * '_' in 'vi' command mode during line editing...
9273 * However I implemented that within libedit itself.
9274 */
9275 setvar("_", lastarg, 0);
Denis Vlasenko6514c5e2008-07-24 13:41:37 +00009276 }
Eric Andersenc470f442003-07-28 09:56:35 +00009277 popstackmark(&smark);
9278}
9279
9280static int
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009281evalbltin(const struct builtincmd *cmd, int argc, char **argv)
9282{
Eric Andersenc470f442003-07-28 09:56:35 +00009283 char *volatile savecmdname;
9284 struct jmploc *volatile savehandler;
9285 struct jmploc jmploc;
9286 int i;
9287
9288 savecmdname = commandname;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009289 i = setjmp(jmploc.loc);
9290 if (i)
Eric Andersenc470f442003-07-28 09:56:35 +00009291 goto cmddone;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00009292 savehandler = exception_handler;
9293 exception_handler = &jmploc;
Eric Andersenc470f442003-07-28 09:56:35 +00009294 commandname = argv[0];
9295 argptr = argv + 1;
9296 optptr = NULL; /* initialize nextopt */
9297 exitstatus = (*cmd->builtin)(argc, argv);
Denis Vlasenkob012b102007-02-19 22:43:01 +00009298 flush_stdout_stderr();
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009299 cmddone:
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009300 exitstatus |= ferror(stdout);
Rob Landleyf296f0b2006-07-06 01:09:21 +00009301 clearerr(stdout);
Eric Andersenc470f442003-07-28 09:56:35 +00009302 commandname = savecmdname;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00009303 exception_handler = savehandler;
Eric Andersenc470f442003-07-28 09:56:35 +00009304
9305 return i;
9306}
9307
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009308static int
9309goodname(const char *p)
Glenn L McGrath16e45d72004-02-04 08:24:39 +00009310{
9311 return !*endofname(p);
9312}
9313
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009314
Glenn L McGrath50812ff2002-08-23 13:14:48 +00009315/*
9316 * Search for a command. This is called before we fork so that the
9317 * location of the command will be available in the parent as well as
Glenn L McGrath16e45d72004-02-04 08:24:39 +00009318 * the child. The check for "goodname" is an overly conservative
9319 * check that the name will not be subject to expansion.
Glenn L McGrath50812ff2002-08-23 13:14:48 +00009320 */
Eric Andersenc470f442003-07-28 09:56:35 +00009321static void
9322prehash(union node *n)
Glenn L McGrath50812ff2002-08-23 13:14:48 +00009323{
9324 struct cmdentry entry;
9325
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +00009326 if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
9327 find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
Glenn L McGrath50812ff2002-08-23 13:14:48 +00009328}
9329
Eric Andersencb57d552001-06-28 07:25:16 +00009330
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00009331/* ============ Builtin commands
9332 *
9333 * Builtin commands whose functions are closely tied to evaluation
9334 * are implemented here.
Eric Andersencb57d552001-06-28 07:25:16 +00009335 */
9336
9337/*
Eric Andersencb57d552001-06-28 07:25:16 +00009338 * Handle break and continue commands. Break, continue, and return are
9339 * all handled by setting the evalskip flag. The evaluation routines
9340 * above all check this flag, and if it is set they start skipping
9341 * commands rather than executing them. The variable skipcount is
9342 * the number of loops to break/continue, or the number of function
9343 * levels to return. (The latter is always 1.) It should probably
9344 * be an error to break out of more loops than exist, but it isn't
9345 * in the standard shell so we don't make it one here.
9346 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009347static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00009348breakcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +00009349{
Denis Vlasenko68404f12008-03-17 09:00:54 +00009350 int n = argv[1] ? number(argv[1]) : 1;
Eric Andersencb57d552001-06-28 07:25:16 +00009351
Aaron Lehmann2aef3a62001-12-31 06:03:12 +00009352 if (n <= 0)
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02009353 ash_msg_and_raise_error(msg_illnum, argv[1]);
Eric Andersencb57d552001-06-28 07:25:16 +00009354 if (n > loopnest)
9355 n = loopnest;
9356 if (n > 0) {
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00009357 evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
Eric Andersencb57d552001-06-28 07:25:16 +00009358 skipcount = n;
9359 }
9360 return 0;
9361}
9362
Eric Andersenc470f442003-07-28 09:56:35 +00009363
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009364/* ============ input.c
9365 *
Eric Andersen90898442003-08-06 11:20:52 +00009366 * This implements the input routines used by the parser.
Eric Andersencb57d552001-06-28 07:25:16 +00009367 */
Denis Vlasenko99eb8502007-02-23 21:09:49 +00009368
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009369enum {
9370 INPUT_PUSH_FILE = 1,
9371 INPUT_NOFILE_OK = 2,
9372};
Eric Andersencb57d552001-06-28 07:25:16 +00009373
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009374static smallint checkkwd;
Denis Vlasenko99eb8502007-02-23 21:09:49 +00009375/* values of checkkwd variable */
9376#define CHKALIAS 0x1
9377#define CHKKWD 0x2
9378#define CHKNL 0x4
9379
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009380/*
9381 * Push a string back onto the input at this current parsefile level.
9382 * We handle aliases this way.
9383 */
9384#if !ENABLE_ASH_ALIAS
9385#define pushstring(s, ap) pushstring(s)
9386#endif
9387static void
9388pushstring(char *s, struct alias *ap)
9389{
9390 struct strpush *sp;
9391 int len;
9392
9393 len = strlen(s);
9394 INT_OFF;
9395 if (g_parsefile->strpush) {
9396 sp = ckzalloc(sizeof(*sp));
9397 sp->prev = g_parsefile->strpush;
9398 } else {
9399 sp = &(g_parsefile->basestrpush);
9400 }
9401 g_parsefile->strpush = sp;
9402 sp->prev_string = g_parsefile->next_to_pgetc;
9403 sp->prev_left_in_line = g_parsefile->left_in_line;
9404#if ENABLE_ASH_ALIAS
9405 sp->ap = ap;
9406 if (ap) {
9407 ap->flag |= ALIASINUSE;
9408 sp->string = s;
9409 }
9410#endif
9411 g_parsefile->next_to_pgetc = s;
9412 g_parsefile->left_in_line = len;
9413 INT_ON;
9414}
9415
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009416static void
9417popstring(void)
Eric Andersenc470f442003-07-28 09:56:35 +00009418{
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009419 struct strpush *sp = g_parsefile->strpush;
Eric Andersenc470f442003-07-28 09:56:35 +00009420
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009421 INT_OFF;
Denis Vlasenko131ae172007-02-18 13:00:19 +00009422#if ENABLE_ASH_ALIAS
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009423 if (sp->ap) {
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009424 if (g_parsefile->next_to_pgetc[-1] == ' '
9425 || g_parsefile->next_to_pgetc[-1] == '\t'
9426 ) {
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009427 checkkwd |= CHKALIAS;
Glenn L McGrath28939ad2004-07-21 10:20:19 +00009428 }
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009429 if (sp->string != sp->ap->val) {
9430 free(sp->string);
9431 }
9432 sp->ap->flag &= ~ALIASINUSE;
9433 if (sp->ap->flag & ALIASDEAD) {
9434 unalias(sp->ap->name);
9435 }
Glenn L McGrath28939ad2004-07-21 10:20:19 +00009436 }
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009437#endif
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009438 g_parsefile->next_to_pgetc = sp->prev_string;
9439 g_parsefile->left_in_line = sp->prev_left_in_line;
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009440 g_parsefile->strpush = sp->prev;
9441 if (sp != &(g_parsefile->basestrpush))
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009442 free(sp);
9443 INT_ON;
9444}
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009445
Denis Vlasenkoe27dafd2008-11-28 04:01:03 +00009446//FIXME: BASH_COMPAT with "...&" does TWO pungetc():
9447//it peeks whether it is &>, and then pushes back both chars.
9448//This function needs to save last *next_to_pgetc to buf[0]
9449//to make two pungetc() reliable. Currently,
9450// pgetc (out of buf: does preadfd), pgetc, pungetc, pungetc won't work...
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009451static int
9452preadfd(void)
Eric Andersencb57d552001-06-28 07:25:16 +00009453{
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00009454 int nr;
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00009455 char *buf = g_parsefile->buf;
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00009456
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009457 g_parsefile->next_to_pgetc = buf;
Denis Vlasenko38f63192007-01-22 09:03:07 +00009458#if ENABLE_FEATURE_EDITING
Denis Vlasenko85c24712008-03-17 09:04:04 +00009459 retry:
Denys Vlasenko79b3d422010-06-03 04:29:08 +02009460 if (!iflag || g_parsefile->pf_fd != STDIN_FILENO)
9461 nr = nonblock_safe_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
Eric Andersenc470f442003-07-28 09:56:35 +00009462 else {
Denis Vlasenko38f63192007-01-22 09:03:07 +00009463#if ENABLE_FEATURE_TAB_COMPLETION
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009464 line_input_state->path_lookup = pathval();
Eric Andersen4a79c0e2004-09-08 10:01:07 +00009465#endif
Denys Vlasenko82dd14a2010-05-17 10:10:01 +02009466 nr = read_line_input(cmdedit_prompt, buf, IBUFSIZ, line_input_state);
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009467 if (nr == 0) {
9468 /* Ctrl+C pressed */
9469 if (trap[SIGINT]) {
Glenn L McGrath16e45d72004-02-04 08:24:39 +00009470 buf[0] = '\n';
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009471 buf[1] = '\0';
Glenn L McGrath16e45d72004-02-04 08:24:39 +00009472 raise(SIGINT);
9473 return 1;
9474 }
Eric Andersenc470f442003-07-28 09:56:35 +00009475 goto retry;
9476 }
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009477 if (nr < 0 && errno == 0) {
Denis Vlasenko9cb220b2007-12-09 10:03:28 +00009478 /* Ctrl+D pressed */
Eric Andersenc470f442003-07-28 09:56:35 +00009479 nr = 0;
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00009480 }
Eric Andersencb57d552001-06-28 07:25:16 +00009481 }
9482#else
Denys Vlasenko161bb8f2010-06-06 05:07:11 +02009483 nr = nonblock_safe_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
Eric Andersencb57d552001-06-28 07:25:16 +00009484#endif
9485
Denis Vlasenkoe376d452008-02-20 22:23:24 +00009486#if 0
9487/* nonblock_safe_read() handles this problem */
Eric Andersencb57d552001-06-28 07:25:16 +00009488 if (nr < 0) {
Eric Andersencb57d552001-06-28 07:25:16 +00009489 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
Denis Vlasenkod37f2222007-08-19 13:42:08 +00009490 int flags = fcntl(0, F_GETFL);
Denis Vlasenko9cb220b2007-12-09 10:03:28 +00009491 if (flags >= 0 && (flags & O_NONBLOCK)) {
9492 flags &= ~O_NONBLOCK;
Eric Andersencb57d552001-06-28 07:25:16 +00009493 if (fcntl(0, F_SETFL, flags) >= 0) {
9494 out2str("sh: turning off NDELAY mode\n");
9495 goto retry;
9496 }
9497 }
9498 }
9499 }
Denis Vlasenkoe376d452008-02-20 22:23:24 +00009500#endif
Eric Andersencb57d552001-06-28 07:25:16 +00009501 return nr;
9502}
9503
9504/*
9505 * Refill the input buffer and return the next input character:
9506 *
9507 * 1) If a string was pushed back on the input, pop it;
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009508 * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
9509 * or we are reading from a string so we can't refill the buffer,
9510 * return EOF.
Denys Vlasenko883cea42009-07-11 15:31:59 +02009511 * 3) If there is more stuff in this buffer, use it else call read to fill it.
Eric Andersencb57d552001-06-28 07:25:16 +00009512 * 4) Process input up to the next newline, deleting nul characters.
9513 */
Denis Vlasenko727752d2008-11-28 03:41:47 +00009514//#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
9515#define pgetc_debug(...) ((void)0)
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009516static int
Eric Andersenc470f442003-07-28 09:56:35 +00009517preadbuffer(void)
Eric Andersencb57d552001-06-28 07:25:16 +00009518{
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009519 char *q;
Eric Andersencb57d552001-06-28 07:25:16 +00009520 int more;
Eric Andersencb57d552001-06-28 07:25:16 +00009521
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009522 while (g_parsefile->strpush) {
Denis Vlasenko131ae172007-02-18 13:00:19 +00009523#if ENABLE_ASH_ALIAS
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009524 if (g_parsefile->left_in_line == -1
9525 && g_parsefile->strpush->ap
9526 && g_parsefile->next_to_pgetc[-1] != ' '
9527 && g_parsefile->next_to_pgetc[-1] != '\t'
Denis Vlasenko16898402008-11-25 01:34:52 +00009528 ) {
Denis Vlasenko727752d2008-11-28 03:41:47 +00009529 pgetc_debug("preadbuffer PEOA");
Eric Andersencb57d552001-06-28 07:25:16 +00009530 return PEOA;
9531 }
Eric Andersen2870d962001-07-02 17:27:21 +00009532#endif
Eric Andersencb57d552001-06-28 07:25:16 +00009533 popstring();
Denis Vlasenko727752d2008-11-28 03:41:47 +00009534 /* try "pgetc" now: */
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009535 pgetc_debug("preadbuffer internal pgetc at %d:%p'%s'",
9536 g_parsefile->left_in_line,
9537 g_parsefile->next_to_pgetc,
9538 g_parsefile->next_to_pgetc);
9539 if (--g_parsefile->left_in_line >= 0)
9540 return (unsigned char)(*g_parsefile->next_to_pgetc++);
Eric Andersencb57d552001-06-28 07:25:16 +00009541 }
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009542 /* on both branches above g_parsefile->left_in_line < 0.
Denis Vlasenko727752d2008-11-28 03:41:47 +00009543 * "pgetc" needs refilling.
9544 */
9545
Denis Vlasenkoe27dafd2008-11-28 04:01:03 +00009546 /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009547 * pungetc() may increment it a few times.
Denis Vlasenkoe27dafd2008-11-28 04:01:03 +00009548 * Assuming it won't increment it to less than -90.
Denis Vlasenko727752d2008-11-28 03:41:47 +00009549 */
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009550 if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
Denis Vlasenko727752d2008-11-28 03:41:47 +00009551 pgetc_debug("preadbuffer PEOF1");
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009552 /* even in failure keep left_in_line and next_to_pgetc
9553 * in lock step, for correct multi-layer pungetc.
9554 * left_in_line was decremented before preadbuffer(),
9555 * must inc next_to_pgetc: */
9556 g_parsefile->next_to_pgetc++;
Eric Andersencb57d552001-06-28 07:25:16 +00009557 return PEOF;
Denis Vlasenko727752d2008-11-28 03:41:47 +00009558 }
Eric Andersencb57d552001-06-28 07:25:16 +00009559
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009560 more = g_parsefile->left_in_buffer;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009561 if (more <= 0) {
Denis Vlasenko727752d2008-11-28 03:41:47 +00009562 flush_stdout_stderr();
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009563 again:
9564 more = preadfd();
9565 if (more <= 0) {
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009566 /* don't try reading again */
9567 g_parsefile->left_in_line = -99;
Denis Vlasenko727752d2008-11-28 03:41:47 +00009568 pgetc_debug("preadbuffer PEOF2");
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009569 g_parsefile->next_to_pgetc++;
Eric Andersencb57d552001-06-28 07:25:16 +00009570 return PEOF;
9571 }
9572 }
9573
Denis Vlasenko727752d2008-11-28 03:41:47 +00009574 /* Find out where's the end of line.
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009575 * Set g_parsefile->left_in_line
9576 * and g_parsefile->left_in_buffer acordingly.
Denis Vlasenko727752d2008-11-28 03:41:47 +00009577 * NUL chars are deleted.
9578 */
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009579 q = g_parsefile->next_to_pgetc;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009580 for (;;) {
Denis Vlasenko727752d2008-11-28 03:41:47 +00009581 char c;
Eric Andersencb57d552001-06-28 07:25:16 +00009582
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009583 more--;
Eric Andersenc470f442003-07-28 09:56:35 +00009584
Denis Vlasenko727752d2008-11-28 03:41:47 +00009585 c = *q;
9586 if (c == '\0') {
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009587 memmove(q, q + 1, more);
Denis Vlasenko727752d2008-11-28 03:41:47 +00009588 } else {
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009589 q++;
9590 if (c == '\n') {
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009591 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009592 break;
9593 }
Eric Andersencb57d552001-06-28 07:25:16 +00009594 }
9595
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009596 if (more <= 0) {
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009597 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9598 if (g_parsefile->left_in_line < 0)
Eric Andersencb57d552001-06-28 07:25:16 +00009599 goto again;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009600 break;
Eric Andersencb57d552001-06-28 07:25:16 +00009601 }
9602 }
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009603 g_parsefile->left_in_buffer = more;
Eric Andersencb57d552001-06-28 07:25:16 +00009604
Eric Andersencb57d552001-06-28 07:25:16 +00009605 if (vflag) {
Denis Vlasenko727752d2008-11-28 03:41:47 +00009606 char save = *q;
9607 *q = '\0';
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009608 out2str(g_parsefile->next_to_pgetc);
Denis Vlasenko727752d2008-11-28 03:41:47 +00009609 *q = save;
Eric Andersencb57d552001-06-28 07:25:16 +00009610 }
9611
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009612 pgetc_debug("preadbuffer at %d:%p'%s'",
9613 g_parsefile->left_in_line,
9614 g_parsefile->next_to_pgetc,
9615 g_parsefile->next_to_pgetc);
Denys Vlasenkocd716832009-11-28 22:14:02 +01009616 return (unsigned char)*g_parsefile->next_to_pgetc++;
Eric Andersencb57d552001-06-28 07:25:16 +00009617}
9618
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009619#define pgetc_as_macro() \
9620 (--g_parsefile->left_in_line >= 0 \
Denys Vlasenkocd716832009-11-28 22:14:02 +01009621 ? (unsigned char)*g_parsefile->next_to_pgetc++ \
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009622 : preadbuffer() \
9623 )
Denis Vlasenko727752d2008-11-28 03:41:47 +00009624
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009625static int
9626pgetc(void)
9627{
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009628 pgetc_debug("pgetc_fast at %d:%p'%s'",
9629 g_parsefile->left_in_line,
9630 g_parsefile->next_to_pgetc,
9631 g_parsefile->next_to_pgetc);
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009632 return pgetc_as_macro();
9633}
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00009634
9635#if ENABLE_ASH_OPTIMIZE_FOR_SIZE
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01009636# define pgetc_fast() pgetc()
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009637#else
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01009638# define pgetc_fast() pgetc_as_macro()
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009639#endif
9640
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009641#if ENABLE_ASH_ALIAS
9642static int
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01009643pgetc_without_PEOA(void)
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009644{
9645 int c;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009646 do {
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009647 pgetc_debug("pgetc_fast at %d:%p'%s'",
9648 g_parsefile->left_in_line,
9649 g_parsefile->next_to_pgetc,
9650 g_parsefile->next_to_pgetc);
Denis Vlasenko834dee72008-10-07 09:18:30 +00009651 c = pgetc_fast();
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009652 } while (c == PEOA);
9653 return c;
9654}
9655#else
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01009656# define pgetc_without_PEOA() pgetc()
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009657#endif
9658
9659/*
9660 * Read a line from the script.
9661 */
9662static char *
9663pfgets(char *line, int len)
9664{
9665 char *p = line;
9666 int nleft = len;
9667 int c;
9668
9669 while (--nleft > 0) {
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01009670 c = pgetc_without_PEOA();
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009671 if (c == PEOF) {
9672 if (p == line)
9673 return NULL;
9674 break;
9675 }
9676 *p++ = c;
9677 if (c == '\n')
9678 break;
9679 }
9680 *p = '\0';
9681 return line;
9682}
9683
Eric Andersenc470f442003-07-28 09:56:35 +00009684/*
9685 * Undo the last call to pgetc. Only one character may be pushed back.
9686 * PEOF may be pushed back.
9687 */
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009688static void
Eric Andersenc470f442003-07-28 09:56:35 +00009689pungetc(void)
9690{
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009691 g_parsefile->left_in_line++;
9692 g_parsefile->next_to_pgetc--;
9693 pgetc_debug("pushed back to %d:%p'%s'",
9694 g_parsefile->left_in_line,
9695 g_parsefile->next_to_pgetc,
9696 g_parsefile->next_to_pgetc);
Eric Andersencb57d552001-06-28 07:25:16 +00009697}
9698
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009699/*
9700 * To handle the "." command, a stack of input files is used. Pushfile
9701 * adds a new entry to the stack and popfile restores the previous level.
9702 */
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009703static void
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009704pushfile(void)
Eric Andersenc470f442003-07-28 09:56:35 +00009705{
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009706 struct parsefile *pf;
9707
Denis Vlasenko597906c2008-02-20 16:38:54 +00009708 pf = ckzalloc(sizeof(*pf));
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009709 pf->prev = g_parsefile;
Denys Vlasenko79b3d422010-06-03 04:29:08 +02009710 pf->pf_fd = -1;
Denis Vlasenko597906c2008-02-20 16:38:54 +00009711 /*pf->strpush = NULL; - ckzalloc did it */
9712 /*pf->basestrpush.prev = NULL;*/
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009713 g_parsefile = pf;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009714}
9715
9716static void
9717popfile(void)
9718{
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009719 struct parsefile *pf = g_parsefile;
Eric Andersenc470f442003-07-28 09:56:35 +00009720
Denis Vlasenkob012b102007-02-19 22:43:01 +00009721 INT_OFF;
Denys Vlasenko79b3d422010-06-03 04:29:08 +02009722 if (pf->pf_fd >= 0)
9723 close(pf->pf_fd);
Denis Vlasenko60818682007-09-28 22:07:23 +00009724 free(pf->buf);
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009725 while (pf->strpush)
9726 popstring();
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009727 g_parsefile = pf->prev;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009728 free(pf);
Denis Vlasenkob012b102007-02-19 22:43:01 +00009729 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00009730}
9731
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009732/*
9733 * Return to top level.
9734 */
9735static void
9736popallfiles(void)
9737{
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009738 while (g_parsefile != &basepf)
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009739 popfile();
9740}
9741
9742/*
9743 * Close the file(s) that the shell is reading commands from. Called
9744 * after a fork is done.
9745 */
9746static void
9747closescript(void)
9748{
9749 popallfiles();
Denys Vlasenko79b3d422010-06-03 04:29:08 +02009750 if (g_parsefile->pf_fd > 0) {
9751 close(g_parsefile->pf_fd);
9752 g_parsefile->pf_fd = 0;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009753 }
9754}
9755
9756/*
9757 * Like setinputfile, but takes an open file descriptor. Call this with
9758 * interrupts off.
9759 */
9760static void
9761setinputfd(int fd, int push)
9762{
Denis Vlasenko96e1b382007-09-30 23:50:48 +00009763 close_on_exec_on(fd);
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009764 if (push) {
9765 pushfile();
Denis Vlasenko727752d2008-11-28 03:41:47 +00009766 g_parsefile->buf = NULL;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009767 }
Denys Vlasenko79b3d422010-06-03 04:29:08 +02009768 g_parsefile->pf_fd = fd;
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009769 if (g_parsefile->buf == NULL)
9770 g_parsefile->buf = ckmalloc(IBUFSIZ);
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009771 g_parsefile->left_in_buffer = 0;
9772 g_parsefile->left_in_line = 0;
9773 g_parsefile->linno = 1;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009774}
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009775
Eric Andersenc470f442003-07-28 09:56:35 +00009776/*
9777 * Set the input to take input from a file. If push is set, push the
9778 * old input onto the stack first.
9779 */
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009780static int
9781setinputfile(const char *fname, int flags)
Eric Andersenc470f442003-07-28 09:56:35 +00009782{
9783 int fd;
9784 int fd2;
9785
Denis Vlasenkob012b102007-02-19 22:43:01 +00009786 INT_OFF;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009787 fd = open(fname, O_RDONLY);
9788 if (fd < 0) {
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009789 if (flags & INPUT_NOFILE_OK)
9790 goto out;
Denis Vlasenko9604e1b2009-03-03 18:47:56 +00009791 ash_msg_and_raise_error("can't open '%s'", fname);
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009792 }
Eric Andersenc470f442003-07-28 09:56:35 +00009793 if (fd < 10) {
9794 fd2 = copyfd(fd, 10);
9795 close(fd);
9796 if (fd2 < 0)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00009797 ash_msg_and_raise_error("out of file descriptors");
Eric Andersenc470f442003-07-28 09:56:35 +00009798 fd = fd2;
9799 }
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009800 setinputfd(fd, flags & INPUT_PUSH_FILE);
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009801 out:
Denis Vlasenkob012b102007-02-19 22:43:01 +00009802 INT_ON;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009803 return fd;
Eric Andersenc470f442003-07-28 09:56:35 +00009804}
9805
Eric Andersencb57d552001-06-28 07:25:16 +00009806/*
9807 * Like setinputfile, but takes input from a string.
9808 */
Eric Andersenc470f442003-07-28 09:56:35 +00009809static void
9810setinputstring(char *string)
Eric Andersen62483552001-07-10 06:09:16 +00009811{
Denis Vlasenkob012b102007-02-19 22:43:01 +00009812 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +00009813 pushfile();
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009814 g_parsefile->next_to_pgetc = string;
9815 g_parsefile->left_in_line = strlen(string);
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009816 g_parsefile->buf = NULL;
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009817 g_parsefile->linno = 1;
Denis Vlasenkob012b102007-02-19 22:43:01 +00009818 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00009819}
9820
9821
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00009822/* ============ mail.c
9823 *
9824 * Routines to check for mail.
Eric Andersencb57d552001-06-28 07:25:16 +00009825 */
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00009826
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00009827#if ENABLE_ASH_MAIL
Eric Andersencb57d552001-06-28 07:25:16 +00009828
Eric Andersencb57d552001-06-28 07:25:16 +00009829#define MAXMBOXES 10
9830
Eric Andersenc470f442003-07-28 09:56:35 +00009831/* times of mailboxes */
9832static time_t mailtime[MAXMBOXES];
9833/* Set if MAIL or MAILPATH is changed. */
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +00009834static smallint mail_var_path_changed;
Eric Andersencb57d552001-06-28 07:25:16 +00009835
Eric Andersencb57d552001-06-28 07:25:16 +00009836/*
Eric Andersenc470f442003-07-28 09:56:35 +00009837 * Print appropriate message(s) if mail has arrived.
9838 * If mail_var_path_changed is set,
9839 * then the value of MAIL has mail_var_path_changed,
9840 * so we just update the values.
Eric Andersencb57d552001-06-28 07:25:16 +00009841 */
Eric Andersenc470f442003-07-28 09:56:35 +00009842static void
9843chkmail(void)
Eric Andersencb57d552001-06-28 07:25:16 +00009844{
Eric Andersencb57d552001-06-28 07:25:16 +00009845 const char *mpath;
9846 char *p;
9847 char *q;
Eric Andersenc470f442003-07-28 09:56:35 +00009848 time_t *mtp;
Eric Andersencb57d552001-06-28 07:25:16 +00009849 struct stackmark smark;
9850 struct stat statb;
9851
Eric Andersencb57d552001-06-28 07:25:16 +00009852 setstackmark(&smark);
Eric Andersenc470f442003-07-28 09:56:35 +00009853 mpath = mpathset() ? mpathval() : mailval();
9854 for (mtp = mailtime; mtp < mailtime + MAXMBOXES; mtp++) {
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02009855 p = path_advance(&mpath, nullstr);
Eric Andersencb57d552001-06-28 07:25:16 +00009856 if (p == NULL)
9857 break;
9858 if (*p == '\0')
9859 continue;
Denis Vlasenkof7d56652008-03-25 05:51:41 +00009860 for (q = p; *q; q++)
9861 continue;
Denis Vlasenkoa7189f02006-11-17 20:29:00 +00009862#if DEBUG
Eric Andersencb57d552001-06-28 07:25:16 +00009863 if (q[-1] != '/')
9864 abort();
9865#endif
Eric Andersenc470f442003-07-28 09:56:35 +00009866 q[-1] = '\0'; /* delete trailing '/' */
9867 if (stat(p, &statb) < 0) {
9868 *mtp = 0;
9869 continue;
Eric Andersencb57d552001-06-28 07:25:16 +00009870 }
Eric Andersenc470f442003-07-28 09:56:35 +00009871 if (!mail_var_path_changed && statb.st_mtime != *mtp) {
9872 fprintf(
Denys Vlasenkoea8b2522010-06-02 12:57:26 +02009873 stderr, "%s\n",
Eric Andersenc470f442003-07-28 09:56:35 +00009874 pathopt ? pathopt : "you have mail"
9875 );
9876 }
9877 *mtp = statb.st_mtime;
Eric Andersencb57d552001-06-28 07:25:16 +00009878 }
Eric Andersenc470f442003-07-28 09:56:35 +00009879 mail_var_path_changed = 0;
Eric Andersencb57d552001-06-28 07:25:16 +00009880 popstackmark(&smark);
9881}
Eric Andersencb57d552001-06-28 07:25:16 +00009882
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009883static void FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00009884changemail(const char *val UNUSED_PARAM)
Eric Andersenc470f442003-07-28 09:56:35 +00009885{
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +00009886 mail_var_path_changed = 1;
Eric Andersenc470f442003-07-28 09:56:35 +00009887}
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00009888
Denis Vlasenko131ae172007-02-18 13:00:19 +00009889#endif /* ASH_MAIL */
Eric Andersenc470f442003-07-28 09:56:35 +00009890
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00009891
9892/* ============ ??? */
9893
Eric Andersencb57d552001-06-28 07:25:16 +00009894/*
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009895 * Set the shell parameters.
Eric Andersencb57d552001-06-28 07:25:16 +00009896 */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009897static void
9898setparam(char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +00009899{
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009900 char **newparam;
9901 char **ap;
9902 int nparam;
Eric Andersencb57d552001-06-28 07:25:16 +00009903
Denis Vlasenkof7d56652008-03-25 05:51:41 +00009904 for (nparam = 0; argv[nparam]; nparam++)
9905 continue;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009906 ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
9907 while (*argv) {
9908 *ap++ = ckstrdup(*argv++);
Eric Andersencb57d552001-06-28 07:25:16 +00009909 }
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009910 *ap = NULL;
9911 freeparam(&shellparam);
Denis Vlasenko01631112007-12-16 17:20:38 +00009912 shellparam.malloced = 1;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009913 shellparam.nparam = nparam;
9914 shellparam.p = newparam;
9915#if ENABLE_ASH_GETOPTS
9916 shellparam.optind = 1;
9917 shellparam.optoff = -1;
9918#endif
Eric Andersencb57d552001-06-28 07:25:16 +00009919}
9920
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00009921/*
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009922 * Process shell options. The global variable argptr contains a pointer
9923 * to the argument list; we advance it past the options.
Denis Vlasenko94e87bc2008-02-14 16:51:58 +00009924 *
9925 * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
9926 * For a non-interactive shell, an error condition encountered
9927 * by a special built-in ... shall cause the shell to write a diagnostic message
9928 * to standard error and exit as shown in the following table:
Denis Vlasenko56244732008-02-17 15:14:04 +00009929 * Error Special Built-In
Denis Vlasenko94e87bc2008-02-14 16:51:58 +00009930 * ...
9931 * Utility syntax error (option or operand error) Shall exit
9932 * ...
9933 * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
9934 * we see that bash does not do that (set "finishes" with error code 1 instead,
9935 * and shell continues), and people rely on this behavior!
9936 * Testcase:
9937 * set -o barfoo 2>/dev/null
9938 * echo $?
9939 *
9940 * Oh well. Let's mimic that.
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00009941 */
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009942static int
Denis Vlasenkodddfaff2008-05-06 15:30:27 +00009943plus_minus_o(char *name, int val)
Eric Andersen62483552001-07-10 06:09:16 +00009944{
9945 int i;
9946
Denis Vlasenkoa624c112007-02-19 22:45:43 +00009947 if (name) {
9948 for (i = 0; i < NOPTS; i++) {
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00009949 if (strcmp(name, optnames(i)) == 0) {
Eric Andersenc470f442003-07-28 09:56:35 +00009950 optlist[i] = val;
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009951 return 0;
Eric Andersen62483552001-07-10 06:09:16 +00009952 }
Denis Vlasenkoa624c112007-02-19 22:45:43 +00009953 }
Denis Vlasenkodddfaff2008-05-06 15:30:27 +00009954 ash_msg("illegal option %co %s", val ? '-' : '+', name);
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009955 return 1;
Eric Andersen62483552001-07-10 06:09:16 +00009956 }
Denis Vlasenko6b06cb82008-05-15 21:30:45 +00009957 for (i = 0; i < NOPTS; i++) {
Denis Vlasenkodddfaff2008-05-06 15:30:27 +00009958 if (val) {
9959 out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
9960 } else {
9961 out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
9962 }
Denis Vlasenko6b06cb82008-05-15 21:30:45 +00009963 }
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009964 return 0;
Eric Andersen62483552001-07-10 06:09:16 +00009965}
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009966static void
9967setoption(int flag, int val)
9968{
9969 int i;
9970
9971 for (i = 0; i < NOPTS; i++) {
9972 if (optletters(i) == flag) {
9973 optlist[i] = val;
9974 return;
9975 }
9976 }
Denis Vlasenkodddfaff2008-05-06 15:30:27 +00009977 ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009978 /* NOTREACHED */
9979}
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009980static int
Eric Andersenc470f442003-07-28 09:56:35 +00009981options(int cmdline)
Eric Andersencb57d552001-06-28 07:25:16 +00009982{
9983 char *p;
9984 int val;
9985 int c;
9986
9987 if (cmdline)
9988 minusc = NULL;
9989 while ((p = *argptr) != NULL) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009990 c = *p++;
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +00009991 if (c != '-' && c != '+')
9992 break;
9993 argptr++;
9994 val = 0; /* val = 0 if c == '+' */
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009995 if (c == '-') {
Eric Andersencb57d552001-06-28 07:25:16 +00009996 val = 1;
Denis Vlasenko9f739442006-12-16 23:49:13 +00009997 if (p[0] == '\0' || LONE_DASH(p)) {
Eric Andersen2870d962001-07-02 17:27:21 +00009998 if (!cmdline) {
9999 /* "-" means turn off -x and -v */
10000 if (p[0] == '\0')
10001 xflag = vflag = 0;
10002 /* "--" means reset params */
10003 else if (*argptr == NULL)
Eric Andersencb57d552001-06-28 07:25:16 +000010004 setparam(argptr);
Eric Andersen2870d962001-07-02 17:27:21 +000010005 }
Eric Andersenc470f442003-07-28 09:56:35 +000010006 break; /* "-" or "--" terminates options */
Eric Andersencb57d552001-06-28 07:25:16 +000010007 }
Eric Andersencb57d552001-06-28 07:25:16 +000010008 }
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +000010009 /* first char was + or - */
Eric Andersencb57d552001-06-28 07:25:16 +000010010 while ((c = *p++) != '\0') {
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +000010011 /* bash 3.2 indeed handles -c CMD and +c CMD the same */
Eric Andersencb57d552001-06-28 07:25:16 +000010012 if (c == 'c' && cmdline) {
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +000010013 minusc = p; /* command is after shell args */
Eric Andersencb57d552001-06-28 07:25:16 +000010014 } else if (c == 'o') {
Denis Vlasenkodddfaff2008-05-06 15:30:27 +000010015 if (plus_minus_o(*argptr, val)) {
Denis Vlasenko28bf6712008-02-14 15:01:47 +000010016 /* it already printed err message */
10017 return 1; /* error */
10018 }
Eric Andersencb57d552001-06-28 07:25:16 +000010019 if (*argptr)
10020 argptr++;
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +000010021 } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
10022 isloginsh = 1;
10023 /* bash does not accept +-login, we also won't */
10024 } else if (cmdline && val && (c == '-')) { /* long options */
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010025 if (strcmp(p, "login") == 0)
Robert Griebl64f70cc2002-05-14 23:22:06 +000010026 isloginsh = 1;
10027 break;
Eric Andersencb57d552001-06-28 07:25:16 +000010028 } else {
10029 setoption(c, val);
10030 }
10031 }
10032 }
Denis Vlasenko28bf6712008-02-14 15:01:47 +000010033 return 0;
Eric Andersencb57d552001-06-28 07:25:16 +000010034}
10035
Eric Andersencb57d552001-06-28 07:25:16 +000010036/*
Eric Andersencb57d552001-06-28 07:25:16 +000010037 * The shift builtin command.
10038 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010039static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000010040shiftcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +000010041{
10042 int n;
10043 char **ap1, **ap2;
10044
10045 n = 1;
Denis Vlasenko68404f12008-03-17 09:00:54 +000010046 if (argv[1])
Eric Andersencb57d552001-06-28 07:25:16 +000010047 n = number(argv[1]);
10048 if (n > shellparam.nparam)
Denis Vlasenkoc90e1be2008-07-30 15:35:05 +000010049 n = 0; /* bash compat, was = shellparam.nparam; */
Denis Vlasenkob012b102007-02-19 22:43:01 +000010050 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +000010051 shellparam.nparam -= n;
Denis Vlasenko2da584f2007-02-19 22:44:05 +000010052 for (ap1 = shellparam.p; --n >= 0; ap1++) {
Denis Vlasenko01631112007-12-16 17:20:38 +000010053 if (shellparam.malloced)
Denis Vlasenkob012b102007-02-19 22:43:01 +000010054 free(*ap1);
Eric Andersencb57d552001-06-28 07:25:16 +000010055 }
10056 ap2 = shellparam.p;
Denis Vlasenkof7d56652008-03-25 05:51:41 +000010057 while ((*ap2++ = *ap1++) != NULL)
10058 continue;
Denis Vlasenko131ae172007-02-18 13:00:19 +000010059#if ENABLE_ASH_GETOPTS
Eric Andersencb57d552001-06-28 07:25:16 +000010060 shellparam.optind = 1;
10061 shellparam.optoff = -1;
Eric Andersenc470f442003-07-28 09:56:35 +000010062#endif
Denis Vlasenkob012b102007-02-19 22:43:01 +000010063 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +000010064 return 0;
10065}
10066
Eric Andersencb57d552001-06-28 07:25:16 +000010067/*
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010068 * POSIX requires that 'set' (but not export or readonly) output the
10069 * variables in lexicographic order - by the locale's collating order (sigh).
10070 * Maybe we could keep them in an ordered balanced binary tree
10071 * instead of hashed lists.
10072 * For now just roll 'em through qsort for printing...
10073 */
10074static int
10075showvars(const char *sep_prefix, int on, int off)
10076{
10077 const char *sep;
10078 char **ep, **epend;
10079
10080 ep = listvars(on, off, &epend);
10081 qsort(ep, epend - ep, sizeof(char *), vpcmp);
10082
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +000010083 sep = *sep_prefix ? " " : sep_prefix;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010084
10085 for (; ep < epend; ep++) {
10086 const char *p;
10087 const char *q;
10088
10089 p = strchrnul(*ep, '=');
10090 q = nullstr;
10091 if (*p)
10092 q = single_quote(++p);
10093 out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
10094 }
10095 return 0;
10096}
10097
10098/*
Eric Andersencb57d552001-06-28 07:25:16 +000010099 * The set command builtin.
10100 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010101static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000010102setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersencb57d552001-06-28 07:25:16 +000010103{
Denis Vlasenko28bf6712008-02-14 15:01:47 +000010104 int retval;
10105
Denis Vlasenko68404f12008-03-17 09:00:54 +000010106 if (!argv[1])
Eric Andersenc470f442003-07-28 09:56:35 +000010107 return showvars(nullstr, 0, VUNSET);
Denis Vlasenkob012b102007-02-19 22:43:01 +000010108 INT_OFF;
Denis Vlasenko28bf6712008-02-14 15:01:47 +000010109 retval = 1;
10110 if (!options(0)) { /* if no parse error... */
10111 retval = 0;
10112 optschanged();
10113 if (*argptr != NULL) {
10114 setparam(argptr);
10115 }
Eric Andersencb57d552001-06-28 07:25:16 +000010116 }
Denis Vlasenkob012b102007-02-19 22:43:01 +000010117 INT_ON;
Denis Vlasenko28bf6712008-02-14 15:01:47 +000010118 return retval;
Eric Andersencb57d552001-06-28 07:25:16 +000010119}
10120
Denis Vlasenko131ae172007-02-18 13:00:19 +000010121#if ENABLE_ASH_RANDOM_SUPPORT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010122static void FAST_FUNC
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000010123change_random(const char *value)
Eric Andersenef02f822004-03-11 13:34:24 +000010124{
Denys Vlasenko3ea2e822009-10-09 20:59:04 +020010125 uint32_t t;
10126
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010127 if (value == NULL) {
Eric Andersen16767e22004-03-16 05:14:10 +000010128 /* "get", generate */
Denys Vlasenko3ea2e822009-10-09 20:59:04 +020010129 t = next_random(&random_gen);
Eric Andersen16767e22004-03-16 05:14:10 +000010130 /* set without recursion */
Denys Vlasenko8837c5d2010-06-02 12:56:18 +020010131 setvar(vrandom.var_text, utoa(t), VNOFUNC);
Eric Andersen16767e22004-03-16 05:14:10 +000010132 vrandom.flags &= ~VNOFUNC;
10133 } else {
10134 /* set/reset */
Denys Vlasenko3ea2e822009-10-09 20:59:04 +020010135 t = strtoul(value, NULL, 10);
10136 INIT_RANDOM_T(&random_gen, (t ? t : 1), t);
Eric Andersen16767e22004-03-16 05:14:10 +000010137 }
Eric Andersenef02f822004-03-11 13:34:24 +000010138}
Eric Andersen16767e22004-03-16 05:14:10 +000010139#endif
10140
Denis Vlasenko131ae172007-02-18 13:00:19 +000010141#if ENABLE_ASH_GETOPTS
Eric Andersencb57d552001-06-28 07:25:16 +000010142static int
Eric Andersenc470f442003-07-28 09:56:35 +000010143getopts(char *optstr, char *optvar, char **optfirst, int *param_optind, int *optoff)
Eric Andersencb57d552001-06-28 07:25:16 +000010144{
10145 char *p, *q;
10146 char c = '?';
10147 int done = 0;
10148 int err = 0;
Eric Andersena48b0a32003-10-22 10:56:47 +000010149 char s[12];
10150 char **optnext;
Eric Andersencb57d552001-06-28 07:25:16 +000010151
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010152 if (*param_optind < 1)
Eric Andersena48b0a32003-10-22 10:56:47 +000010153 return 1;
10154 optnext = optfirst + *param_optind - 1;
10155
Denis Vlasenko6b06cb82008-05-15 21:30:45 +000010156 if (*param_optind <= 1 || *optoff < 0 || (int)strlen(optnext[-1]) < *optoff)
Eric Andersencb57d552001-06-28 07:25:16 +000010157 p = NULL;
10158 else
Eric Andersena48b0a32003-10-22 10:56:47 +000010159 p = optnext[-1] + *optoff;
Eric Andersencb57d552001-06-28 07:25:16 +000010160 if (p == NULL || *p == '\0') {
10161 /* Current word is done, advance */
Eric Andersencb57d552001-06-28 07:25:16 +000010162 p = *optnext;
10163 if (p == NULL || *p != '-' || *++p == '\0') {
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010164 atend:
Eric Andersencb57d552001-06-28 07:25:16 +000010165 p = NULL;
10166 done = 1;
10167 goto out;
10168 }
10169 optnext++;
Denis Vlasenko9f739442006-12-16 23:49:13 +000010170 if (LONE_DASH(p)) /* check for "--" */
Eric Andersencb57d552001-06-28 07:25:16 +000010171 goto atend;
10172 }
10173
10174 c = *p++;
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +000010175 for (q = optstr; *q != c;) {
Eric Andersencb57d552001-06-28 07:25:16 +000010176 if (*q == '\0') {
10177 if (optstr[0] == ':') {
10178 s[0] = c;
10179 s[1] = '\0';
10180 err |= setvarsafe("OPTARG", s, 0);
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010181 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000010182 fprintf(stderr, "Illegal option -%c\n", c);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010183 unsetvar("OPTARG");
Eric Andersencb57d552001-06-28 07:25:16 +000010184 }
10185 c = '?';
Eric Andersenc470f442003-07-28 09:56:35 +000010186 goto out;
Eric Andersencb57d552001-06-28 07:25:16 +000010187 }
10188 if (*++q == ':')
10189 q++;
10190 }
10191
10192 if (*++q == ':') {
10193 if (*p == '\0' && (p = *optnext) == NULL) {
10194 if (optstr[0] == ':') {
10195 s[0] = c;
10196 s[1] = '\0';
10197 err |= setvarsafe("OPTARG", s, 0);
10198 c = ':';
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010199 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000010200 fprintf(stderr, "No arg for -%c option\n", c);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010201 unsetvar("OPTARG");
Eric Andersencb57d552001-06-28 07:25:16 +000010202 c = '?';
10203 }
Eric Andersenc470f442003-07-28 09:56:35 +000010204 goto out;
Eric Andersencb57d552001-06-28 07:25:16 +000010205 }
10206
10207 if (p == *optnext)
10208 optnext++;
Eric Andersenc470f442003-07-28 09:56:35 +000010209 err |= setvarsafe("OPTARG", p, 0);
Eric Andersencb57d552001-06-28 07:25:16 +000010210 p = NULL;
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010211 } else
Eric Andersenc470f442003-07-28 09:56:35 +000010212 err |= setvarsafe("OPTARG", nullstr, 0);
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010213 out:
Eric Andersencb57d552001-06-28 07:25:16 +000010214 *optoff = p ? p - *(optnext - 1) : -1;
Eric Andersenc470f442003-07-28 09:56:35 +000010215 *param_optind = optnext - optfirst + 1;
10216 fmtstr(s, sizeof(s), "%d", *param_optind);
Eric Andersencb57d552001-06-28 07:25:16 +000010217 err |= setvarsafe("OPTIND", s, VNOFUNC);
10218 s[0] = c;
10219 s[1] = '\0';
10220 err |= setvarsafe(optvar, s, 0);
10221 if (err) {
Eric Andersenc470f442003-07-28 09:56:35 +000010222 *param_optind = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010223 *optoff = -1;
Denis Vlasenkob012b102007-02-19 22:43:01 +000010224 flush_stdout_stderr();
10225 raise_exception(EXERROR);
Eric Andersencb57d552001-06-28 07:25:16 +000010226 }
10227 return done;
10228}
Eric Andersenc470f442003-07-28 09:56:35 +000010229
10230/*
10231 * The getopts builtin. Shellparam.optnext points to the next argument
10232 * to be processed. Shellparam.optptr points to the next character to
10233 * be processed in the current argument. If shellparam.optnext is NULL,
10234 * then it's the first time getopts has been called.
10235 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010236static int FAST_FUNC
Eric Andersenc470f442003-07-28 09:56:35 +000010237getoptscmd(int argc, char **argv)
10238{
10239 char **optbase;
10240
10241 if (argc < 3)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +000010242 ash_msg_and_raise_error("usage: getopts optstring var [arg]");
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010243 if (argc == 3) {
Eric Andersenc470f442003-07-28 09:56:35 +000010244 optbase = shellparam.p;
10245 if (shellparam.optind > shellparam.nparam + 1) {
10246 shellparam.optind = 1;
10247 shellparam.optoff = -1;
10248 }
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010249 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000010250 optbase = &argv[3];
10251 if (shellparam.optind > argc - 2) {
10252 shellparam.optind = 1;
10253 shellparam.optoff = -1;
10254 }
10255 }
10256
10257 return getopts(argv[1], argv[2], optbase, &shellparam.optind,
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010258 &shellparam.optoff);
Eric Andersenc470f442003-07-28 09:56:35 +000010259}
Denis Vlasenko131ae172007-02-18 13:00:19 +000010260#endif /* ASH_GETOPTS */
Eric Andersencb57d552001-06-28 07:25:16 +000010261
Eric Andersencb57d552001-06-28 07:25:16 +000010262
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010263/* ============ Shell parser */
Eric Andersencb57d552001-06-28 07:25:16 +000010264
Denis Vlasenkob07a4962008-06-22 13:16:23 +000010265struct heredoc {
10266 struct heredoc *next; /* next here document in list */
10267 union node *here; /* redirection node */
10268 char *eofmark; /* string indicating end of input */
10269 smallint striptabs; /* if set, strip leading tabs */
10270};
10271
10272static smallint tokpushback; /* last token pushed back */
10273static smallint parsebackquote; /* nonzero if we are inside backquotes */
10274static smallint quoteflag; /* set if (part of) last token was quoted */
10275static token_id_t lasttoken; /* last token read (integer id Txxx) */
10276static struct heredoc *heredoclist; /* list of here documents to read */
10277static char *wordtext; /* text of last word returned by readtoken */
10278static struct nodelist *backquotelist;
10279static union node *redirnode;
10280static struct heredoc *heredoc;
Denis Vlasenko99eb8502007-02-23 21:09:49 +000010281
Denys Vlasenkoa0ec4f52010-05-20 12:50:42 +020010282static const char *
10283tokname(char *buf, int tok)
10284{
10285 if (tok < TSEMI)
10286 return tokname_array[tok] + 1;
10287 sprintf(buf, "\"%s\"", tokname_array[tok] + 1);
10288 return buf;
10289}
10290
10291/* raise_error_unexpected_syntax:
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010292 * Called when an unexpected token is read during the parse. The argument
10293 * is the token that is expected, or -1 if more than one type of token can
10294 * occur at this point.
10295 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000010296static void raise_error_unexpected_syntax(int) NORETURN;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010297static void
10298raise_error_unexpected_syntax(int token)
10299{
10300 char msg[64];
Denys Vlasenkoa0ec4f52010-05-20 12:50:42 +020010301 char buf[16];
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010302 int l;
10303
Denys Vlasenkoa0ec4f52010-05-20 12:50:42 +020010304 l = sprintf(msg, "unexpected %s", tokname(buf, lasttoken));
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010305 if (token >= 0)
Denys Vlasenkoa0ec4f52010-05-20 12:50:42 +020010306 sprintf(msg + l, " (expecting %s)", tokname(buf, token));
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010307 raise_error_syntax(msg);
10308 /* NOTREACHED */
10309}
Eric Andersencb57d552001-06-28 07:25:16 +000010310
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010311#define EOFMARKLEN 79
Eric Andersencb57d552001-06-28 07:25:16 +000010312
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010313/* parsing is heavily cross-recursive, need these forward decls */
10314static union node *andor(void);
10315static union node *pipeline(void);
10316static union node *parse_command(void);
10317static void parseheredoc(void);
10318static char peektoken(void);
10319static int readtoken(void);
Eric Andersencb57d552001-06-28 07:25:16 +000010320
Eric Andersenc470f442003-07-28 09:56:35 +000010321static union node *
10322list(int nlflag)
Eric Andersencb57d552001-06-28 07:25:16 +000010323{
10324 union node *n1, *n2, *n3;
10325 int tok;
10326
Eric Andersenc470f442003-07-28 09:56:35 +000010327 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10328 if (nlflag == 2 && peektoken())
Eric Andersencb57d552001-06-28 07:25:16 +000010329 return NULL;
10330 n1 = NULL;
10331 for (;;) {
10332 n2 = andor();
10333 tok = readtoken();
10334 if (tok == TBACKGND) {
Eric Andersenc470f442003-07-28 09:56:35 +000010335 if (n2->type == NPIPE) {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +000010336 n2->npipe.pipe_backgnd = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010337 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000010338 if (n2->type != NREDIR) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010339 n3 = stzalloc(sizeof(struct nredir));
Eric Andersenc470f442003-07-28 09:56:35 +000010340 n3->nredir.n = n2;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010341 /*n3->nredir.redirect = NULL; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000010342 n2 = n3;
10343 }
10344 n2->type = NBACKGND;
Eric Andersencb57d552001-06-28 07:25:16 +000010345 }
10346 }
10347 if (n1 == NULL) {
10348 n1 = n2;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010349 } else {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010350 n3 = stzalloc(sizeof(struct nbinary));
Eric Andersencb57d552001-06-28 07:25:16 +000010351 n3->type = NSEMI;
10352 n3->nbinary.ch1 = n1;
10353 n3->nbinary.ch2 = n2;
10354 n1 = n3;
10355 }
10356 switch (tok) {
10357 case TBACKGND:
10358 case TSEMI:
10359 tok = readtoken();
10360 /* fall through */
10361 case TNL:
10362 if (tok == TNL) {
10363 parseheredoc();
Eric Andersenc470f442003-07-28 09:56:35 +000010364 if (nlflag == 1)
Eric Andersencb57d552001-06-28 07:25:16 +000010365 return n1;
10366 } else {
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010367 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010368 }
Eric Andersenc470f442003-07-28 09:56:35 +000010369 checkkwd = CHKNL | CHKKWD | CHKALIAS;
Manuel Novoa III 16815d42001-08-10 19:36:07 +000010370 if (peektoken())
Eric Andersencb57d552001-06-28 07:25:16 +000010371 return n1;
10372 break;
10373 case TEOF:
10374 if (heredoclist)
10375 parseheredoc();
10376 else
Eric Andersenc470f442003-07-28 09:56:35 +000010377 pungetc(); /* push back EOF on input */
Eric Andersencb57d552001-06-28 07:25:16 +000010378 return n1;
10379 default:
Eric Andersenc470f442003-07-28 09:56:35 +000010380 if (nlflag == 1)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010381 raise_error_unexpected_syntax(-1);
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010382 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010383 return n1;
10384 }
10385 }
10386}
10387
Eric Andersenc470f442003-07-28 09:56:35 +000010388static union node *
10389andor(void)
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010390{
Eric Andersencb57d552001-06-28 07:25:16 +000010391 union node *n1, *n2, *n3;
10392 int t;
10393
Eric Andersencb57d552001-06-28 07:25:16 +000010394 n1 = pipeline();
10395 for (;;) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010396 t = readtoken();
10397 if (t == TAND) {
Eric Andersencb57d552001-06-28 07:25:16 +000010398 t = NAND;
10399 } else if (t == TOR) {
10400 t = NOR;
10401 } else {
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010402 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010403 return n1;
10404 }
Eric Andersenc470f442003-07-28 09:56:35 +000010405 checkkwd = CHKNL | CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010406 n2 = pipeline();
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010407 n3 = stzalloc(sizeof(struct nbinary));
Eric Andersencb57d552001-06-28 07:25:16 +000010408 n3->type = t;
10409 n3->nbinary.ch1 = n1;
10410 n3->nbinary.ch2 = n2;
10411 n1 = n3;
10412 }
10413}
10414
Eric Andersenc470f442003-07-28 09:56:35 +000010415static union node *
10416pipeline(void)
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010417{
Eric Andersencb57d552001-06-28 07:25:16 +000010418 union node *n1, *n2, *pipenode;
10419 struct nodelist *lp, *prev;
10420 int negate;
10421
10422 negate = 0;
10423 TRACE(("pipeline: entered\n"));
10424 if (readtoken() == TNOT) {
10425 negate = !negate;
Eric Andersenc470f442003-07-28 09:56:35 +000010426 checkkwd = CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010427 } else
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010428 tokpushback = 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010429 n1 = parse_command();
Eric Andersencb57d552001-06-28 07:25:16 +000010430 if (readtoken() == TPIPE) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010431 pipenode = stzalloc(sizeof(struct npipe));
Eric Andersencb57d552001-06-28 07:25:16 +000010432 pipenode->type = NPIPE;
Denis Vlasenko2dc240c2008-07-24 06:07:50 +000010433 /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010434 lp = stzalloc(sizeof(struct nodelist));
Eric Andersencb57d552001-06-28 07:25:16 +000010435 pipenode->npipe.cmdlist = lp;
10436 lp->n = n1;
10437 do {
10438 prev = lp;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010439 lp = stzalloc(sizeof(struct nodelist));
Eric Andersenc470f442003-07-28 09:56:35 +000010440 checkkwd = CHKNL | CHKKWD | CHKALIAS;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010441 lp->n = parse_command();
Eric Andersencb57d552001-06-28 07:25:16 +000010442 prev->next = lp;
10443 } while (readtoken() == TPIPE);
10444 lp->next = NULL;
10445 n1 = pipenode;
10446 }
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010447 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010448 if (negate) {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010449 n2 = stzalloc(sizeof(struct nnot));
Eric Andersencb57d552001-06-28 07:25:16 +000010450 n2->type = NNOT;
10451 n2->nnot.com = n1;
10452 return n2;
Denis Vlasenko2da584f2007-02-19 22:44:05 +000010453 }
10454 return n1;
Eric Andersencb57d552001-06-28 07:25:16 +000010455}
10456
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010457static union node *
10458makename(void)
10459{
10460 union node *n;
10461
Denis Vlasenko597906c2008-02-20 16:38:54 +000010462 n = stzalloc(sizeof(struct narg));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010463 n->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010464 /*n->narg.next = NULL; - stzalloc did it */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010465 n->narg.text = wordtext;
10466 n->narg.backquote = backquotelist;
10467 return n;
10468}
10469
10470static void
10471fixredir(union node *n, const char *text, int err)
10472{
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000010473 int fd;
10474
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010475 TRACE(("Fix redir %s %d\n", text, err));
10476 if (!err)
10477 n->ndup.vname = NULL;
10478
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000010479 fd = bb_strtou(text, NULL, 10);
10480 if (!errno && fd >= 0)
10481 n->ndup.dupfd = fd;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010482 else if (LONE_DASH(text))
10483 n->ndup.dupfd = -1;
10484 else {
10485 if (err)
Denis Vlasenko559691a2008-10-05 18:39:31 +000010486 raise_error_syntax("bad fd number");
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010487 n->ndup.vname = makename();
10488 }
10489}
10490
10491/*
10492 * Returns true if the text contains nothing to expand (no dollar signs
10493 * or backquotes).
10494 */
10495static int
Denis Vlasenko68819d12008-12-15 11:26:36 +000010496noexpand(const char *text)
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010497{
Denys Vlasenkocd716832009-11-28 22:14:02 +010010498 unsigned char c;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010499
Denys Vlasenkocd716832009-11-28 22:14:02 +010010500 while ((c = *text++) != '\0') {
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010501 if (c == CTLQUOTEMARK)
10502 continue;
10503 if (c == CTLESC)
Denys Vlasenkocd716832009-11-28 22:14:02 +010010504 text++;
Denys Vlasenko76bc2d62009-11-29 01:37:46 +010010505 else if (SIT(c, BASESYNTAX) == CCTL)
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010506 return 0;
10507 }
10508 return 1;
10509}
10510
10511static void
10512parsefname(void)
10513{
10514 union node *n = redirnode;
10515
10516 if (readtoken() != TWORD)
10517 raise_error_unexpected_syntax(-1);
10518 if (n->type == NHERE) {
10519 struct heredoc *here = heredoc;
10520 struct heredoc *p;
10521 int i;
10522
10523 if (quoteflag == 0)
10524 n->type = NXHERE;
10525 TRACE(("Here document %d\n", n->type));
10526 if (!noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
Denis Vlasenko559691a2008-10-05 18:39:31 +000010527 raise_error_syntax("illegal eof marker for << redirection");
Denys Vlasenkob6c84342009-08-29 20:23:20 +020010528 rmescapes(wordtext, 0);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010529 here->eofmark = wordtext;
10530 here->next = NULL;
10531 if (heredoclist == NULL)
10532 heredoclist = here;
10533 else {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010534 for (p = heredoclist; p->next; p = p->next)
10535 continue;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010536 p->next = here;
10537 }
10538 } else if (n->type == NTOFD || n->type == NFROMFD) {
10539 fixredir(n, wordtext, 0);
10540 } else {
10541 n->nfile.fname = makename();
10542 }
10543}
Eric Andersencb57d552001-06-28 07:25:16 +000010544
Eric Andersenc470f442003-07-28 09:56:35 +000010545static union node *
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010546simplecmd(void)
10547{
10548 union node *args, **app;
10549 union node *n = NULL;
10550 union node *vars, **vpp;
10551 union node **rpp, *redir;
10552 int savecheckkwd;
Denis Vlasenko80591b02008-03-25 07:49:43 +000010553#if ENABLE_ASH_BASH_COMPAT
10554 smallint double_brackets_flag = 0;
10555#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010556
10557 args = NULL;
10558 app = &args;
10559 vars = NULL;
10560 vpp = &vars;
10561 redir = NULL;
10562 rpp = &redir;
10563
10564 savecheckkwd = CHKALIAS;
10565 for (;;) {
Denis Vlasenko80591b02008-03-25 07:49:43 +000010566 int t;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010567 checkkwd = savecheckkwd;
Denis Vlasenko80591b02008-03-25 07:49:43 +000010568 t = readtoken();
10569 switch (t) {
10570#if ENABLE_ASH_BASH_COMPAT
10571 case TAND: /* "&&" */
10572 case TOR: /* "||" */
10573 if (!double_brackets_flag) {
10574 tokpushback = 1;
10575 goto out;
10576 }
10577 wordtext = (char *) (t == TAND ? "-a" : "-o");
10578#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010579 case TWORD:
Denis Vlasenko597906c2008-02-20 16:38:54 +000010580 n = stzalloc(sizeof(struct narg));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010581 n->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010582 /*n->narg.next = NULL; - stzalloc did it */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010583 n->narg.text = wordtext;
Denis Vlasenko80591b02008-03-25 07:49:43 +000010584#if ENABLE_ASH_BASH_COMPAT
10585 if (strcmp("[[", wordtext) == 0)
10586 double_brackets_flag = 1;
10587 else if (strcmp("]]", wordtext) == 0)
10588 double_brackets_flag = 0;
10589#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010590 n->narg.backquote = backquotelist;
10591 if (savecheckkwd && isassignment(wordtext)) {
10592 *vpp = n;
10593 vpp = &n->narg.next;
10594 } else {
10595 *app = n;
10596 app = &n->narg.next;
10597 savecheckkwd = 0;
10598 }
10599 break;
10600 case TREDIR:
10601 *rpp = n = redirnode;
10602 rpp = &n->nfile.next;
10603 parsefname(); /* read name of redirection file */
10604 break;
10605 case TLP:
10606 if (args && app == &args->narg.next
10607 && !vars && !redir
10608 ) {
10609 struct builtincmd *bcmd;
10610 const char *name;
10611
10612 /* We have a function */
10613 if (readtoken() != TRP)
10614 raise_error_unexpected_syntax(TRP);
10615 name = n->narg.text;
10616 if (!goodname(name)
10617 || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
10618 ) {
Denis Vlasenko559691a2008-10-05 18:39:31 +000010619 raise_error_syntax("bad function name");
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010620 }
10621 n->type = NDEFUN;
10622 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10623 n->narg.next = parse_command();
10624 return n;
10625 }
10626 /* fall through */
10627 default:
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010628 tokpushback = 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010629 goto out;
10630 }
10631 }
10632 out:
10633 *app = NULL;
10634 *vpp = NULL;
10635 *rpp = NULL;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010636 n = stzalloc(sizeof(struct ncmd));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010637 n->type = NCMD;
10638 n->ncmd.args = args;
10639 n->ncmd.assign = vars;
10640 n->ncmd.redirect = redir;
10641 return n;
10642}
10643
10644static union node *
10645parse_command(void)
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010646{
Eric Andersencb57d552001-06-28 07:25:16 +000010647 union node *n1, *n2;
10648 union node *ap, **app;
10649 union node *cp, **cpp;
10650 union node *redir, **rpp;
Eric Andersenc470f442003-07-28 09:56:35 +000010651 union node **rpp2;
Eric Andersencb57d552001-06-28 07:25:16 +000010652 int t;
10653
10654 redir = NULL;
Eric Andersenc470f442003-07-28 09:56:35 +000010655 rpp2 = &redir;
Eric Andersen88cec252001-09-06 17:35:20 +000010656
Eric Andersencb57d552001-06-28 07:25:16 +000010657 switch (readtoken()) {
Eric Andersenc470f442003-07-28 09:56:35 +000010658 default:
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010659 raise_error_unexpected_syntax(-1);
Eric Andersenc470f442003-07-28 09:56:35 +000010660 /* NOTREACHED */
Eric Andersencb57d552001-06-28 07:25:16 +000010661 case TIF:
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010662 n1 = stzalloc(sizeof(struct nif));
Eric Andersencb57d552001-06-28 07:25:16 +000010663 n1->type = NIF;
10664 n1->nif.test = list(0);
10665 if (readtoken() != TTHEN)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010666 raise_error_unexpected_syntax(TTHEN);
Eric Andersencb57d552001-06-28 07:25:16 +000010667 n1->nif.ifpart = list(0);
10668 n2 = n1;
10669 while (readtoken() == TELIF) {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010670 n2->nif.elsepart = stzalloc(sizeof(struct nif));
Eric Andersencb57d552001-06-28 07:25:16 +000010671 n2 = n2->nif.elsepart;
10672 n2->type = NIF;
10673 n2->nif.test = list(0);
10674 if (readtoken() != TTHEN)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010675 raise_error_unexpected_syntax(TTHEN);
Eric Andersencb57d552001-06-28 07:25:16 +000010676 n2->nif.ifpart = list(0);
10677 }
10678 if (lasttoken == TELSE)
10679 n2->nif.elsepart = list(0);
10680 else {
10681 n2->nif.elsepart = NULL;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010682 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010683 }
Eric Andersenc470f442003-07-28 09:56:35 +000010684 t = TFI;
Eric Andersencb57d552001-06-28 07:25:16 +000010685 break;
10686 case TWHILE:
Eric Andersenc470f442003-07-28 09:56:35 +000010687 case TUNTIL: {
Eric Andersencb57d552001-06-28 07:25:16 +000010688 int got;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010689 n1 = stzalloc(sizeof(struct nbinary));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010690 n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
Eric Andersencb57d552001-06-28 07:25:16 +000010691 n1->nbinary.ch1 = list(0);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010692 got = readtoken();
10693 if (got != TDO) {
Denys Vlasenkoa0ec4f52010-05-20 12:50:42 +020010694 TRACE(("expecting DO got '%s' %s\n", tokname_array[got] + 1,
Denis Vlasenko131ae172007-02-18 13:00:19 +000010695 got == TWORD ? wordtext : ""));
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010696 raise_error_unexpected_syntax(TDO);
Eric Andersencb57d552001-06-28 07:25:16 +000010697 }
10698 n1->nbinary.ch2 = list(0);
Eric Andersenc470f442003-07-28 09:56:35 +000010699 t = TDONE;
Eric Andersencb57d552001-06-28 07:25:16 +000010700 break;
10701 }
10702 case TFOR:
Denis Vlasenko2dc240c2008-07-24 06:07:50 +000010703 if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
Denis Vlasenko559691a2008-10-05 18:39:31 +000010704 raise_error_syntax("bad for loop variable");
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010705 n1 = stzalloc(sizeof(struct nfor));
Eric Andersencb57d552001-06-28 07:25:16 +000010706 n1->type = NFOR;
10707 n1->nfor.var = wordtext;
Eric Andersenc470f442003-07-28 09:56:35 +000010708 checkkwd = CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010709 if (readtoken() == TIN) {
10710 app = &ap;
10711 while (readtoken() == TWORD) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010712 n2 = stzalloc(sizeof(struct narg));
Eric Andersencb57d552001-06-28 07:25:16 +000010713 n2->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010714 /*n2->narg.next = NULL; - stzalloc did it */
Eric Andersencb57d552001-06-28 07:25:16 +000010715 n2->narg.text = wordtext;
10716 n2->narg.backquote = backquotelist;
10717 *app = n2;
10718 app = &n2->narg.next;
10719 }
10720 *app = NULL;
10721 n1->nfor.args = ap;
10722 if (lasttoken != TNL && lasttoken != TSEMI)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010723 raise_error_unexpected_syntax(-1);
Eric Andersencb57d552001-06-28 07:25:16 +000010724 } else {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010725 n2 = stzalloc(sizeof(struct narg));
Eric Andersencb57d552001-06-28 07:25:16 +000010726 n2->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010727 /*n2->narg.next = NULL; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000010728 n2->narg.text = (char *)dolatstr;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010729 /*n2->narg.backquote = NULL;*/
Eric Andersencb57d552001-06-28 07:25:16 +000010730 n1->nfor.args = n2;
10731 /*
10732 * Newline or semicolon here is optional (but note
10733 * that the original Bourne shell only allowed NL).
10734 */
10735 if (lasttoken != TNL && lasttoken != TSEMI)
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010736 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010737 }
Eric Andersenc470f442003-07-28 09:56:35 +000010738 checkkwd = CHKNL | CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010739 if (readtoken() != TDO)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010740 raise_error_unexpected_syntax(TDO);
Eric Andersencb57d552001-06-28 07:25:16 +000010741 n1->nfor.body = list(0);
Eric Andersenc470f442003-07-28 09:56:35 +000010742 t = TDONE;
Eric Andersencb57d552001-06-28 07:25:16 +000010743 break;
10744 case TCASE:
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010745 n1 = stzalloc(sizeof(struct ncase));
Eric Andersencb57d552001-06-28 07:25:16 +000010746 n1->type = NCASE;
10747 if (readtoken() != TWORD)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010748 raise_error_unexpected_syntax(TWORD);
Denis Vlasenko597906c2008-02-20 16:38:54 +000010749 n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
Eric Andersencb57d552001-06-28 07:25:16 +000010750 n2->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010751 /*n2->narg.next = NULL; - stzalloc did it */
Eric Andersencb57d552001-06-28 07:25:16 +000010752 n2->narg.text = wordtext;
10753 n2->narg.backquote = backquotelist;
Eric Andersencb57d552001-06-28 07:25:16 +000010754 do {
Eric Andersenc470f442003-07-28 09:56:35 +000010755 checkkwd = CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010756 } while (readtoken() == TNL);
10757 if (lasttoken != TIN)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010758 raise_error_unexpected_syntax(TIN);
Eric Andersencb57d552001-06-28 07:25:16 +000010759 cpp = &n1->ncase.cases;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010760 next_case:
Eric Andersenc470f442003-07-28 09:56:35 +000010761 checkkwd = CHKNL | CHKKWD;
10762 t = readtoken();
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010763 while (t != TESAC) {
Eric Andersencb57d552001-06-28 07:25:16 +000010764 if (lasttoken == TLP)
10765 readtoken();
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010766 *cpp = cp = stzalloc(sizeof(struct nclist));
Eric Andersencb57d552001-06-28 07:25:16 +000010767 cp->type = NCLIST;
10768 app = &cp->nclist.pattern;
10769 for (;;) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010770 *app = ap = stzalloc(sizeof(struct narg));
Eric Andersencb57d552001-06-28 07:25:16 +000010771 ap->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010772 /*ap->narg.next = NULL; - stzalloc did it */
Eric Andersencb57d552001-06-28 07:25:16 +000010773 ap->narg.text = wordtext;
10774 ap->narg.backquote = backquotelist;
Eric Andersenc470f442003-07-28 09:56:35 +000010775 if (readtoken() != TPIPE)
Eric Andersencb57d552001-06-28 07:25:16 +000010776 break;
10777 app = &ap->narg.next;
10778 readtoken();
10779 }
Denis Vlasenko597906c2008-02-20 16:38:54 +000010780 //ap->narg.next = NULL;
Eric Andersencb57d552001-06-28 07:25:16 +000010781 if (lasttoken != TRP)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010782 raise_error_unexpected_syntax(TRP);
Eric Andersenc470f442003-07-28 09:56:35 +000010783 cp->nclist.body = list(2);
Eric Andersencb57d552001-06-28 07:25:16 +000010784
Eric Andersenc470f442003-07-28 09:56:35 +000010785 cpp = &cp->nclist.next;
10786
10787 checkkwd = CHKNL | CHKKWD;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010788 t = readtoken();
10789 if (t != TESAC) {
Eric Andersencb57d552001-06-28 07:25:16 +000010790 if (t != TENDCASE)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010791 raise_error_unexpected_syntax(TENDCASE);
10792 goto next_case;
Eric Andersencb57d552001-06-28 07:25:16 +000010793 }
Eric Andersenc470f442003-07-28 09:56:35 +000010794 }
Eric Andersencb57d552001-06-28 07:25:16 +000010795 *cpp = NULL;
Eric Andersenc470f442003-07-28 09:56:35 +000010796 goto redir;
Eric Andersencb57d552001-06-28 07:25:16 +000010797 case TLP:
Denis Vlasenko597906c2008-02-20 16:38:54 +000010798 n1 = stzalloc(sizeof(struct nredir));
Eric Andersencb57d552001-06-28 07:25:16 +000010799 n1->type = NSUBSHELL;
10800 n1->nredir.n = list(0);
Denis Vlasenko597906c2008-02-20 16:38:54 +000010801 /*n1->nredir.redirect = NULL; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000010802 t = TRP;
Eric Andersencb57d552001-06-28 07:25:16 +000010803 break;
10804 case TBEGIN:
10805 n1 = list(0);
Eric Andersenc470f442003-07-28 09:56:35 +000010806 t = TEND;
Eric Andersencb57d552001-06-28 07:25:16 +000010807 break;
Eric Andersencb57d552001-06-28 07:25:16 +000010808 case TWORD:
Eric Andersenc470f442003-07-28 09:56:35 +000010809 case TREDIR:
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010810 tokpushback = 1;
Eric Andersenc470f442003-07-28 09:56:35 +000010811 return simplecmd();
Eric Andersencb57d552001-06-28 07:25:16 +000010812 }
10813
Eric Andersenc470f442003-07-28 09:56:35 +000010814 if (readtoken() != t)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010815 raise_error_unexpected_syntax(t);
Eric Andersenc470f442003-07-28 09:56:35 +000010816
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010817 redir:
Eric Andersencb57d552001-06-28 07:25:16 +000010818 /* Now check for redirection which may follow command */
Eric Andersenc470f442003-07-28 09:56:35 +000010819 checkkwd = CHKKWD | CHKALIAS;
10820 rpp = rpp2;
Eric Andersencb57d552001-06-28 07:25:16 +000010821 while (readtoken() == TREDIR) {
10822 *rpp = n2 = redirnode;
10823 rpp = &n2->nfile.next;
10824 parsefname();
10825 }
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010826 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010827 *rpp = NULL;
10828 if (redir) {
10829 if (n1->type != NSUBSHELL) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010830 n2 = stzalloc(sizeof(struct nredir));
Eric Andersencb57d552001-06-28 07:25:16 +000010831 n2->type = NREDIR;
10832 n2->nredir.n = n1;
10833 n1 = n2;
10834 }
10835 n1->nredir.redirect = redir;
10836 }
Eric Andersencb57d552001-06-28 07:25:16 +000010837 return n1;
10838}
10839
Denis Vlasenkoef527f52008-06-23 01:52:30 +000010840#if ENABLE_ASH_BASH_COMPAT
10841static int decode_dollar_squote(void)
10842{
10843 static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
10844 int c, cnt;
10845 char *p;
10846 char buf[4];
10847
10848 c = pgetc();
10849 p = strchr(C_escapes, c);
10850 if (p) {
10851 buf[0] = c;
10852 p = buf;
10853 cnt = 3;
10854 if ((unsigned char)(c - '0') <= 7) { /* \ooo */
10855 do {
10856 c = pgetc();
10857 *++p = c;
10858 } while ((unsigned char)(c - '0') <= 7 && --cnt);
10859 pungetc();
10860 } else if (c == 'x') { /* \xHH */
10861 do {
10862 c = pgetc();
10863 *++p = c;
10864 } while (isxdigit(c) && --cnt);
10865 pungetc();
10866 if (cnt == 3) { /* \x but next char is "bad" */
10867 c = 'x';
10868 goto unrecognized;
10869 }
10870 } else { /* simple seq like \\ or \t */
10871 p++;
10872 }
10873 *p = '\0';
10874 p = buf;
10875 c = bb_process_escape_sequence((void*)&p);
10876 } else { /* unrecognized "\z": print both chars unless ' or " */
10877 if (c != '\'' && c != '"') {
10878 unrecognized:
10879 c |= 0x100; /* "please encode \, then me" */
10880 }
10881 }
10882 return c;
10883}
10884#endif
10885
Eric Andersencb57d552001-06-28 07:25:16 +000010886/*
10887 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
10888 * is not NULL, read a here document. In the latter case, eofmark is the
10889 * word which marks the end of the document and striptabs is true if
Denys Vlasenkocd716832009-11-28 22:14:02 +010010890 * leading tabs should be stripped from the document. The argument c
Eric Andersencb57d552001-06-28 07:25:16 +000010891 * is the first character of the input token or document.
10892 *
10893 * Because C does not have internal subroutines, I have simulated them
10894 * using goto's to implement the subroutine linkage. The following macros
10895 * will run code that appears at the end of readtoken1.
10896 */
Eric Andersen2870d962001-07-02 17:27:21 +000010897#define CHECKEND() {goto checkend; checkend_return:;}
10898#define PARSEREDIR() {goto parseredir; parseredir_return:;}
10899#define PARSESUB() {goto parsesub; parsesub_return:;}
10900#define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
10901#define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
10902#define PARSEARITH() {goto parsearith; parsearith_return:;}
Eric Andersencb57d552001-06-28 07:25:16 +000010903static int
Denys Vlasenkocd716832009-11-28 22:14:02 +010010904readtoken1(int c, int syntax, char *eofmark, int striptabs)
Manuel Novoa III 16815d42001-08-10 19:36:07 +000010905{
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010906 /* NB: syntax parameter fits into smallint */
Denys Vlasenkocd716832009-11-28 22:14:02 +010010907 /* c parameter is an unsigned char or PEOF or PEOA */
Eric Andersencb57d552001-06-28 07:25:16 +000010908 char *out;
10909 int len;
10910 char line[EOFMARKLEN + 1];
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010911 struct nodelist *bqlist;
10912 smallint quotef;
10913 smallint dblquote;
10914 smallint oldstyle;
10915 smallint prevsyntax; /* syntax before arithmetic */
Denis Vlasenko46a53062007-09-24 18:30:02 +000010916#if ENABLE_ASH_EXPAND_PRMT
10917 smallint pssyntax; /* we are expanding a prompt string */
10918#endif
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010919 int varnest; /* levels of variables expansion */
10920 int arinest; /* levels of arithmetic expansion */
10921 int parenlevel; /* levels of parens in arithmetic */
10922 int dqvarnest; /* levels of variables expansion within double quotes */
10923
Denis Vlasenko5e34ff22009-04-21 11:09:40 +000010924 IF_ASH_BASH_COMPAT(smallint bash_dollar_squote = 0;)
Denis Vlasenkoef527f52008-06-23 01:52:30 +000010925
Eric Andersencb57d552001-06-28 07:25:16 +000010926#if __GNUC__
10927 /* Avoid longjmp clobbering */
10928 (void) &out;
10929 (void) &quotef;
10930 (void) &dblquote;
10931 (void) &varnest;
10932 (void) &arinest;
10933 (void) &parenlevel;
10934 (void) &dqvarnest;
10935 (void) &oldstyle;
10936 (void) &prevsyntax;
10937 (void) &syntax;
10938#endif
Denis Vlasenko41eb3002008-11-28 03:42:31 +000010939 startlinno = g_parsefile->linno;
Eric Andersencb57d552001-06-28 07:25:16 +000010940 bqlist = NULL;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010941 quotef = 0;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010942 oldstyle = 0;
10943 prevsyntax = 0;
Denis Vlasenko46a53062007-09-24 18:30:02 +000010944#if ENABLE_ASH_EXPAND_PRMT
10945 pssyntax = (syntax == PSSYNTAX);
10946 if (pssyntax)
10947 syntax = DQSYNTAX;
10948#endif
10949 dblquote = (syntax == DQSYNTAX);
Eric Andersencb57d552001-06-28 07:25:16 +000010950 varnest = 0;
10951 arinest = 0;
10952 parenlevel = 0;
10953 dqvarnest = 0;
10954
10955 STARTSTACKSTR(out);
Denis Vlasenko176d49d2008-10-06 09:51:47 +000010956 loop:
10957 /* For each line, until end of word */
10958 {
Eric Andersenc470f442003-07-28 09:56:35 +000010959 CHECKEND(); /* set c to PEOF if at end of here document */
10960 for (;;) { /* until end of line or end of word */
10961 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
Denis Vlasenkobf0a2012006-12-26 10:42:51 +000010962 switch (SIT(c, syntax)) {
Eric Andersenc470f442003-07-28 09:56:35 +000010963 case CNL: /* '\n' */
Eric Andersencb57d552001-06-28 07:25:16 +000010964 if (syntax == BASESYNTAX)
Eric Andersenc470f442003-07-28 09:56:35 +000010965 goto endword; /* exit outer loop */
Eric Andersencb57d552001-06-28 07:25:16 +000010966 USTPUTC(c, out);
Denis Vlasenko41eb3002008-11-28 03:42:31 +000010967 g_parsefile->linno++;
Eric Andersencb57d552001-06-28 07:25:16 +000010968 if (doprompt)
10969 setprompt(2);
Eric Andersencb57d552001-06-28 07:25:16 +000010970 c = pgetc();
Eric Andersenc470f442003-07-28 09:56:35 +000010971 goto loop; /* continue outer loop */
Eric Andersencb57d552001-06-28 07:25:16 +000010972 case CWORD:
10973 USTPUTC(c, out);
10974 break;
10975 case CCTL:
Eric Andersenc470f442003-07-28 09:56:35 +000010976 if (eofmark == NULL || dblquote)
Eric Andersencb57d552001-06-28 07:25:16 +000010977 USTPUTC(CTLESC, out);
Denis Vlasenkoef527f52008-06-23 01:52:30 +000010978#if ENABLE_ASH_BASH_COMPAT
10979 if (c == '\\' && bash_dollar_squote) {
10980 c = decode_dollar_squote();
10981 if (c & 0x100) {
10982 USTPUTC('\\', out);
10983 c = (unsigned char)c;
10984 }
10985 }
10986#endif
Eric Andersencb57d552001-06-28 07:25:16 +000010987 USTPUTC(c, out);
10988 break;
Eric Andersenc470f442003-07-28 09:56:35 +000010989 case CBACK: /* backslash */
Denys Vlasenko2ce42e92009-11-29 02:18:13 +010010990 c = pgetc_without_PEOA();
Eric Andersencb57d552001-06-28 07:25:16 +000010991 if (c == PEOF) {
Eric Andersenc470f442003-07-28 09:56:35 +000010992 USTPUTC(CTLESC, out);
Eric Andersencb57d552001-06-28 07:25:16 +000010993 USTPUTC('\\', out);
10994 pungetc();
10995 } else if (c == '\n') {
10996 if (doprompt)
10997 setprompt(2);
Eric Andersencb57d552001-06-28 07:25:16 +000010998 } else {
Denis Vlasenko46a53062007-09-24 18:30:02 +000010999#if ENABLE_ASH_EXPAND_PRMT
11000 if (c == '$' && pssyntax) {
11001 USTPUTC(CTLESC, out);
11002 USTPUTC('\\', out);
11003 }
11004#endif
Denis Vlasenkoef527f52008-06-23 01:52:30 +000011005 if (dblquote && c != '\\'
11006 && c != '`' && c != '$'
11007 && (c != '"' || eofmark != NULL)
Eric Andersenc470f442003-07-28 09:56:35 +000011008 ) {
11009 USTPUTC(CTLESC, out);
Eric Andersencb57d552001-06-28 07:25:16 +000011010 USTPUTC('\\', out);
Eric Andersenc470f442003-07-28 09:56:35 +000011011 }
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000011012 if (SIT(c, SQSYNTAX) == CCTL)
Eric Andersencb57d552001-06-28 07:25:16 +000011013 USTPUTC(CTLESC, out);
Eric Andersencb57d552001-06-28 07:25:16 +000011014 USTPUTC(c, out);
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011015 quotef = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000011016 }
11017 break;
11018 case CSQUOTE:
Eric Andersencb57d552001-06-28 07:25:16 +000011019 syntax = SQSYNTAX;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011020 quotemark:
Eric Andersenc470f442003-07-28 09:56:35 +000011021 if (eofmark == NULL) {
11022 USTPUTC(CTLQUOTEMARK, out);
11023 }
Eric Andersencb57d552001-06-28 07:25:16 +000011024 break;
11025 case CDQUOTE:
Eric Andersencb57d552001-06-28 07:25:16 +000011026 syntax = DQSYNTAX;
11027 dblquote = 1;
Eric Andersenc470f442003-07-28 09:56:35 +000011028 goto quotemark;
Eric Andersencb57d552001-06-28 07:25:16 +000011029 case CENDQUOTE:
Denis Vlasenko5e34ff22009-04-21 11:09:40 +000011030 IF_ASH_BASH_COMPAT(bash_dollar_squote = 0;)
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011031 if (eofmark != NULL && arinest == 0
11032 && varnest == 0
11033 ) {
Eric Andersencb57d552001-06-28 07:25:16 +000011034 USTPUTC(c, out);
11035 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000011036 if (dqvarnest == 0) {
Eric Andersencb57d552001-06-28 07:25:16 +000011037 syntax = BASESYNTAX;
11038 dblquote = 0;
11039 }
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011040 quotef = 1;
Eric Andersenc470f442003-07-28 09:56:35 +000011041 goto quotemark;
Eric Andersencb57d552001-06-28 07:25:16 +000011042 }
11043 break;
Eric Andersenc470f442003-07-28 09:56:35 +000011044 case CVAR: /* '$' */
11045 PARSESUB(); /* parse substitution */
Eric Andersencb57d552001-06-28 07:25:16 +000011046 break;
Eric Andersenc470f442003-07-28 09:56:35 +000011047 case CENDVAR: /* '}' */
Eric Andersencb57d552001-06-28 07:25:16 +000011048 if (varnest > 0) {
11049 varnest--;
11050 if (dqvarnest > 0) {
11051 dqvarnest--;
11052 }
11053 USTPUTC(CTLENDVAR, out);
11054 } else {
11055 USTPUTC(c, out);
11056 }
11057 break;
Mike Frysinger98c52642009-04-02 10:02:37 +000011058#if ENABLE_SH_MATH_SUPPORT
Eric Andersenc470f442003-07-28 09:56:35 +000011059 case CLP: /* '(' in arithmetic */
Eric Andersencb57d552001-06-28 07:25:16 +000011060 parenlevel++;
11061 USTPUTC(c, out);
11062 break;
Eric Andersenc470f442003-07-28 09:56:35 +000011063 case CRP: /* ')' in arithmetic */
Eric Andersencb57d552001-06-28 07:25:16 +000011064 if (parenlevel > 0) {
11065 USTPUTC(c, out);
11066 --parenlevel;
11067 } else {
11068 if (pgetc() == ')') {
11069 if (--arinest == 0) {
11070 USTPUTC(CTLENDARI, out);
11071 syntax = prevsyntax;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011072 dblquote = (syntax == DQSYNTAX);
Eric Andersencb57d552001-06-28 07:25:16 +000011073 } else
11074 USTPUTC(')', out);
11075 } else {
11076 /*
11077 * unbalanced parens
11078 * (don't 2nd guess - no error)
11079 */
11080 pungetc();
11081 USTPUTC(')', out);
11082 }
11083 }
11084 break;
11085#endif
Eric Andersenc470f442003-07-28 09:56:35 +000011086 case CBQUOTE: /* '`' */
Eric Andersencb57d552001-06-28 07:25:16 +000011087 PARSEBACKQOLD();
11088 break;
Eric Andersen2870d962001-07-02 17:27:21 +000011089 case CENDFILE:
Eric Andersenc470f442003-07-28 09:56:35 +000011090 goto endword; /* exit outer loop */
Eric Andersencb57d552001-06-28 07:25:16 +000011091 case CIGN:
11092 break;
11093 default:
Denis Vlasenko834dee72008-10-07 09:18:30 +000011094 if (varnest == 0) {
11095#if ENABLE_ASH_BASH_COMPAT
11096 if (c == '&') {
11097 if (pgetc() == '>')
11098 c = 0x100 + '>'; /* flag &> */
11099 pungetc();
11100 }
11101#endif
Eric Andersenc470f442003-07-28 09:56:35 +000011102 goto endword; /* exit outer loop */
Denis Vlasenko834dee72008-10-07 09:18:30 +000011103 }
Denys Vlasenko2ce42e92009-11-29 02:18:13 +010011104 IF_ASH_ALIAS(if (c != PEOA))
Eric Andersencb57d552001-06-28 07:25:16 +000011105 USTPUTC(c, out);
Eric Andersen3102ac42001-07-06 04:26:23 +000011106
Eric Andersencb57d552001-06-28 07:25:16 +000011107 }
Denis Vlasenko834dee72008-10-07 09:18:30 +000011108 c = pgetc_fast();
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000011109 } /* for (;;) */
Eric Andersencb57d552001-06-28 07:25:16 +000011110 }
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011111 endword:
Mike Frysinger98c52642009-04-02 10:02:37 +000011112#if ENABLE_SH_MATH_SUPPORT
Eric Andersencb57d552001-06-28 07:25:16 +000011113 if (syntax == ARISYNTAX)
Denis Vlasenko559691a2008-10-05 18:39:31 +000011114 raise_error_syntax("missing '))'");
Eric Andersenc470f442003-07-28 09:56:35 +000011115#endif
Denis Vlasenko99eb8502007-02-23 21:09:49 +000011116 if (syntax != BASESYNTAX && !parsebackquote && eofmark == NULL)
Denis Vlasenko559691a2008-10-05 18:39:31 +000011117 raise_error_syntax("unterminated quoted string");
Eric Andersencb57d552001-06-28 07:25:16 +000011118 if (varnest != 0) {
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011119 startlinno = g_parsefile->linno;
Eric Andersenc470f442003-07-28 09:56:35 +000011120 /* { */
Denis Vlasenko559691a2008-10-05 18:39:31 +000011121 raise_error_syntax("missing '}'");
Eric Andersencb57d552001-06-28 07:25:16 +000011122 }
11123 USTPUTC('\0', out);
Eric Andersenc470f442003-07-28 09:56:35 +000011124 len = out - (char *)stackblock();
Eric Andersencb57d552001-06-28 07:25:16 +000011125 out = stackblock();
11126 if (eofmark == NULL) {
Denis Vlasenko5e34ff22009-04-21 11:09:40 +000011127 if ((c == '>' || c == '<' IF_ASH_BASH_COMPAT( || c == 0x100 + '>'))
Denis Vlasenko834dee72008-10-07 09:18:30 +000011128 && quotef == 0
11129 ) {
Denis Vlasenko559691a2008-10-05 18:39:31 +000011130 if (isdigit_str9(out)) {
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000011131 PARSEREDIR(); /* passed as params: out, c */
11132 lasttoken = TREDIR;
11133 return lasttoken;
11134 }
11135 /* else: non-number X seen, interpret it
11136 * as "NNNX>file" = "NNNX >file" */
Eric Andersencb57d552001-06-28 07:25:16 +000011137 }
Denis Vlasenkoef527f52008-06-23 01:52:30 +000011138 pungetc();
Eric Andersencb57d552001-06-28 07:25:16 +000011139 }
11140 quoteflag = quotef;
11141 backquotelist = bqlist;
11142 grabstackblock(len);
11143 wordtext = out;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011144 lasttoken = TWORD;
11145 return lasttoken;
Eric Andersencb57d552001-06-28 07:25:16 +000011146/* end of readtoken routine */
11147
Eric Andersencb57d552001-06-28 07:25:16 +000011148/*
11149 * Check to see whether we are at the end of the here document. When this
11150 * is called, c is set to the first character of the next input line. If
11151 * we are at the end of the here document, this routine sets the c to PEOF.
11152 */
Eric Andersenc470f442003-07-28 09:56:35 +000011153checkend: {
11154 if (eofmark) {
Denis Vlasenko131ae172007-02-18 13:00:19 +000011155#if ENABLE_ASH_ALIAS
Denys Vlasenko2ce42e92009-11-29 02:18:13 +010011156 if (c == PEOA)
11157 c = pgetc_without_PEOA();
Eric Andersenc470f442003-07-28 09:56:35 +000011158#endif
11159 if (striptabs) {
11160 while (c == '\t') {
Denys Vlasenko2ce42e92009-11-29 02:18:13 +010011161 c = pgetc_without_PEOA();
Eric Andersencb57d552001-06-28 07:25:16 +000011162 }
Eric Andersenc470f442003-07-28 09:56:35 +000011163 }
11164 if (c == *eofmark) {
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011165 if (pfgets(line, sizeof(line)) != NULL) {
Eric Andersenc470f442003-07-28 09:56:35 +000011166 char *p, *q;
Eric Andersencb57d552001-06-28 07:25:16 +000011167
Eric Andersenc470f442003-07-28 09:56:35 +000011168 p = line;
Denis Vlasenkof7d56652008-03-25 05:51:41 +000011169 for (q = eofmark + 1; *q && *p == *q; p++, q++)
11170 continue;
Eric Andersenc470f442003-07-28 09:56:35 +000011171 if (*p == '\n' && *q == '\0') {
11172 c = PEOF;
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011173 g_parsefile->linno++;
Eric Andersenc470f442003-07-28 09:56:35 +000011174 needprompt = doprompt;
11175 } else {
11176 pushstring(line, NULL);
Eric Andersencb57d552001-06-28 07:25:16 +000011177 }
11178 }
11179 }
11180 }
Eric Andersenc470f442003-07-28 09:56:35 +000011181 goto checkend_return;
11182}
Eric Andersencb57d552001-06-28 07:25:16 +000011183
Eric Andersencb57d552001-06-28 07:25:16 +000011184/*
11185 * Parse a redirection operator. The variable "out" points to a string
11186 * specifying the fd to be redirected. The variable "c" contains the
11187 * first character of the redirection operator.
11188 */
Eric Andersenc470f442003-07-28 09:56:35 +000011189parseredir: {
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000011190 /* out is already checked to be a valid number or "" */
11191 int fd = (*out == '\0' ? -1 : atoi(out));
Eric Andersenc470f442003-07-28 09:56:35 +000011192 union node *np;
Eric Andersencb57d552001-06-28 07:25:16 +000011193
Denis Vlasenko597906c2008-02-20 16:38:54 +000011194 np = stzalloc(sizeof(struct nfile));
Eric Andersenc470f442003-07-28 09:56:35 +000011195 if (c == '>') {
11196 np->nfile.fd = 1;
11197 c = pgetc();
11198 if (c == '>')
11199 np->type = NAPPEND;
11200 else if (c == '|')
11201 np->type = NCLOBBER;
11202 else if (c == '&')
11203 np->type = NTOFD;
Denis Vlasenko559691a2008-10-05 18:39:31 +000011204 /* it also can be NTO2 (>&file), but we can't figure it out yet */
Eric Andersenc470f442003-07-28 09:56:35 +000011205 else {
11206 np->type = NTO;
11207 pungetc();
Eric Andersencb57d552001-06-28 07:25:16 +000011208 }
Denis Vlasenko834dee72008-10-07 09:18:30 +000011209 }
11210#if ENABLE_ASH_BASH_COMPAT
11211 else if (c == 0x100 + '>') { /* this flags &> redirection */
11212 np->nfile.fd = 1;
11213 pgetc(); /* this is '>', no need to check */
11214 np->type = NTO2;
11215 }
11216#endif
11217 else { /* c == '<' */
Denis Vlasenko597906c2008-02-20 16:38:54 +000011218 /*np->nfile.fd = 0; - stzalloc did it */
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011219 c = pgetc();
11220 switch (c) {
Eric Andersenc470f442003-07-28 09:56:35 +000011221 case '<':
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011222 if (sizeof(struct nfile) != sizeof(struct nhere)) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000011223 np = stzalloc(sizeof(struct nhere));
11224 /*np->nfile.fd = 0; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000011225 }
11226 np->type = NHERE;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000011227 heredoc = stzalloc(sizeof(struct heredoc));
Eric Andersenc470f442003-07-28 09:56:35 +000011228 heredoc->here = np;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011229 c = pgetc();
11230 if (c == '-') {
Eric Andersenc470f442003-07-28 09:56:35 +000011231 heredoc->striptabs = 1;
11232 } else {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000011233 /*heredoc->striptabs = 0; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000011234 pungetc();
11235 }
11236 break;
11237
11238 case '&':
11239 np->type = NFROMFD;
11240 break;
11241
11242 case '>':
11243 np->type = NFROMTO;
11244 break;
11245
11246 default:
11247 np->type = NFROM;
11248 pungetc();
11249 break;
11250 }
Eric Andersencb57d552001-06-28 07:25:16 +000011251 }
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000011252 if (fd >= 0)
11253 np->nfile.fd = fd;
Eric Andersenc470f442003-07-28 09:56:35 +000011254 redirnode = np;
11255 goto parseredir_return;
11256}
Eric Andersencb57d552001-06-28 07:25:16 +000011257
Eric Andersencb57d552001-06-28 07:25:16 +000011258/*
11259 * Parse a substitution. At this point, we have read the dollar sign
11260 * and nothing else.
11261 */
Denis Vlasenkocc571512007-02-23 21:10:35 +000011262
11263/* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
11264 * (assuming ascii char codes, as the original implementation did) */
11265#define is_special(c) \
Denis Vlasenkoef527f52008-06-23 01:52:30 +000011266 (((unsigned)(c) - 33 < 32) \
11267 && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
Eric Andersenc470f442003-07-28 09:56:35 +000011268parsesub: {
Denys Vlasenkocd716832009-11-28 22:14:02 +010011269 unsigned char subtype;
Eric Andersenc470f442003-07-28 09:56:35 +000011270 int typeloc;
11271 int flags;
11272 char *p;
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011273 static const char types[] ALIGN1 = "}-+?=";
Eric Andersencb57d552001-06-28 07:25:16 +000011274
Eric Andersenc470f442003-07-28 09:56:35 +000011275 c = pgetc();
Denys Vlasenkocd716832009-11-28 22:14:02 +010011276 if (c > 255 /* PEOA or PEOF */
Denis Vlasenkoef527f52008-06-23 01:52:30 +000011277 || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
Eric Andersenc470f442003-07-28 09:56:35 +000011278 ) {
Denis Vlasenkoef527f52008-06-23 01:52:30 +000011279#if ENABLE_ASH_BASH_COMPAT
11280 if (c == '\'')
11281 bash_dollar_squote = 1;
11282 else
11283#endif
11284 USTPUTC('$', out);
Eric Andersenc470f442003-07-28 09:56:35 +000011285 pungetc();
11286 } else if (c == '(') { /* $(command) or $((arith)) */
11287 if (pgetc() == '(') {
Mike Frysinger98c52642009-04-02 10:02:37 +000011288#if ENABLE_SH_MATH_SUPPORT
Eric Andersenc470f442003-07-28 09:56:35 +000011289 PARSEARITH();
11290#else
Mike Frysinger98a6f562008-06-09 09:38:45 +000011291 raise_error_syntax("you disabled math support for $((arith)) syntax");
Eric Andersenc470f442003-07-28 09:56:35 +000011292#endif
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000011293 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000011294 pungetc();
11295 PARSEBACKQNEW();
11296 }
11297 } else {
11298 USTPUTC(CTLVAR, out);
11299 typeloc = out - (char *)stackblock();
11300 USTPUTC(VSNORMAL, out);
11301 subtype = VSNORMAL;
11302 if (c == '{') {
11303 c = pgetc();
11304 if (c == '#') {
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011305 c = pgetc();
11306 if (c == '}')
Eric Andersenc470f442003-07-28 09:56:35 +000011307 c = '#';
11308 else
11309 subtype = VSLENGTH;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011310 } else
Eric Andersenc470f442003-07-28 09:56:35 +000011311 subtype = 0;
11312 }
Denys Vlasenkocd716832009-11-28 22:14:02 +010011313 if (c <= 255 /* not PEOA or PEOF */ && is_name(c)) {
Eric Andersenc470f442003-07-28 09:56:35 +000011314 do {
11315 STPUTC(c, out);
Eric Andersencb57d552001-06-28 07:25:16 +000011316 c = pgetc();
Denys Vlasenkocd716832009-11-28 22:14:02 +010011317 } while (c <= 255 /* not PEOA or PEOF */ && is_in_name(c));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011318 } else if (isdigit(c)) {
Eric Andersenc470f442003-07-28 09:56:35 +000011319 do {
11320 STPUTC(c, out);
11321 c = pgetc();
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011322 } while (isdigit(c));
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011323 } else if (is_special(c)) {
Eric Andersenc470f442003-07-28 09:56:35 +000011324 USTPUTC(c, out);
11325 c = pgetc();
Denis Vlasenko559691a2008-10-05 18:39:31 +000011326 } else {
11327 badsub:
11328 raise_error_syntax("bad substitution");
11329 }
Cristian Ionescu-Idbohrn301f5ec2009-10-05 02:07:23 +020011330 if (c != '}' && subtype == VSLENGTH)
11331 goto badsub;
Eric Andersencb57d552001-06-28 07:25:16 +000011332
Eric Andersenc470f442003-07-28 09:56:35 +000011333 STPUTC('=', out);
11334 flags = 0;
11335 if (subtype == 0) {
11336 switch (c) {
11337 case ':':
Eric Andersenc470f442003-07-28 09:56:35 +000011338 c = pgetc();
Denis Vlasenko92e13c22008-03-25 01:17:40 +000011339#if ENABLE_ASH_BASH_COMPAT
11340 if (c == ':' || c == '$' || isdigit(c)) {
11341 pungetc();
11342 subtype = VSSUBSTR;
11343 break;
11344 }
11345#endif
11346 flags = VSNUL;
Eric Andersenc470f442003-07-28 09:56:35 +000011347 /*FALLTHROUGH*/
11348 default:
11349 p = strchr(types, c);
11350 if (p == NULL)
11351 goto badsub;
11352 subtype = p - types + VSNORMAL;
11353 break;
11354 case '%':
Denis Vlasenko92e13c22008-03-25 01:17:40 +000011355 case '#': {
11356 int cc = c;
11357 subtype = c == '#' ? VSTRIMLEFT : VSTRIMRIGHT;
11358 c = pgetc();
11359 if (c == cc)
11360 subtype++;
11361 else
11362 pungetc();
11363 break;
11364 }
11365#if ENABLE_ASH_BASH_COMPAT
11366 case '/':
11367 subtype = VSREPLACE;
11368 c = pgetc();
11369 if (c == '/')
11370 subtype++; /* VSREPLACEALL */
11371 else
11372 pungetc();
11373 break;
11374#endif
Eric Andersencb57d552001-06-28 07:25:16 +000011375 }
Eric Andersenc470f442003-07-28 09:56:35 +000011376 } else {
11377 pungetc();
11378 }
11379 if (dblquote || arinest)
11380 flags |= VSQUOTE;
Denys Vlasenkocd716832009-11-28 22:14:02 +010011381 ((unsigned char *)stackblock())[typeloc] = subtype | flags;
Eric Andersenc470f442003-07-28 09:56:35 +000011382 if (subtype != VSNORMAL) {
11383 varnest++;
11384 if (dblquote || arinest) {
11385 dqvarnest++;
Eric Andersencb57d552001-06-28 07:25:16 +000011386 }
11387 }
11388 }
Eric Andersenc470f442003-07-28 09:56:35 +000011389 goto parsesub_return;
11390}
Eric Andersencb57d552001-06-28 07:25:16 +000011391
Eric Andersencb57d552001-06-28 07:25:16 +000011392/*
11393 * Called to parse command substitutions. Newstyle is set if the command
11394 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
11395 * list of commands (passed by reference), and savelen is the number of
11396 * characters on the top of the stack which must be preserved.
11397 */
Eric Andersenc470f442003-07-28 09:56:35 +000011398parsebackq: {
11399 struct nodelist **nlpp;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011400 smallint savepbq;
Eric Andersenc470f442003-07-28 09:56:35 +000011401 union node *n;
11402 char *volatile str;
11403 struct jmploc jmploc;
11404 struct jmploc *volatile savehandler;
11405 size_t savelen;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011406 smallint saveprompt = 0;
11407
Eric Andersencb57d552001-06-28 07:25:16 +000011408#ifdef __GNUC__
Eric Andersenc470f442003-07-28 09:56:35 +000011409 (void) &saveprompt;
Eric Andersencb57d552001-06-28 07:25:16 +000011410#endif
Eric Andersenc470f442003-07-28 09:56:35 +000011411 savepbq = parsebackquote;
11412 if (setjmp(jmploc.loc)) {
Denis Vlasenko60818682007-09-28 22:07:23 +000011413 free(str);
Eric Andersenc470f442003-07-28 09:56:35 +000011414 parsebackquote = 0;
Denis Vlasenko2da584f2007-02-19 22:44:05 +000011415 exception_handler = savehandler;
11416 longjmp(exception_handler->loc, 1);
Eric Andersenc470f442003-07-28 09:56:35 +000011417 }
Denis Vlasenkob012b102007-02-19 22:43:01 +000011418 INT_OFF;
Eric Andersenc470f442003-07-28 09:56:35 +000011419 str = NULL;
11420 savelen = out - (char *)stackblock();
11421 if (savelen > 0) {
11422 str = ckmalloc(savelen);
11423 memcpy(str, stackblock(), savelen);
11424 }
Denis Vlasenko2da584f2007-02-19 22:44:05 +000011425 savehandler = exception_handler;
11426 exception_handler = &jmploc;
Denis Vlasenkob012b102007-02-19 22:43:01 +000011427 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +000011428 if (oldstyle) {
11429 /* We must read until the closing backquote, giving special
11430 treatment to some slashes, and then push the string and
11431 reread it as input, interpreting it normally. */
11432 char *pout;
11433 int pc;
11434 size_t psavelen;
11435 char *pstr;
11436
11437
11438 STARTSTACKSTR(pout);
11439 for (;;) {
11440 if (needprompt) {
11441 setprompt(2);
Eric Andersenc470f442003-07-28 09:56:35 +000011442 }
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011443 pc = pgetc();
11444 switch (pc) {
Eric Andersenc470f442003-07-28 09:56:35 +000011445 case '`':
11446 goto done;
11447
11448 case '\\':
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011449 pc = pgetc();
11450 if (pc == '\n') {
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011451 g_parsefile->linno++;
Eric Andersenc470f442003-07-28 09:56:35 +000011452 if (doprompt)
11453 setprompt(2);
11454 /*
11455 * If eating a newline, avoid putting
11456 * the newline into the new character
11457 * stream (via the STPUTC after the
11458 * switch).
11459 */
11460 continue;
11461 }
11462 if (pc != '\\' && pc != '`' && pc != '$'
Denys Vlasenko76bc2d62009-11-29 01:37:46 +010011463 && (!dblquote || pc != '"')
11464 ) {
Eric Andersenc470f442003-07-28 09:56:35 +000011465 STPUTC('\\', pout);
Denys Vlasenko76bc2d62009-11-29 01:37:46 +010011466 }
Denys Vlasenkocd716832009-11-28 22:14:02 +010011467 if (pc <= 255 /* not PEOA or PEOF */) {
Eric Andersenc470f442003-07-28 09:56:35 +000011468 break;
11469 }
11470 /* fall through */
11471
11472 case PEOF:
Denys Vlasenko2ce42e92009-11-29 02:18:13 +010011473 IF_ASH_ALIAS(case PEOA:)
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011474 startlinno = g_parsefile->linno;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000011475 raise_error_syntax("EOF in backquote substitution");
Eric Andersenc470f442003-07-28 09:56:35 +000011476
11477 case '\n':
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011478 g_parsefile->linno++;
Eric Andersenc470f442003-07-28 09:56:35 +000011479 needprompt = doprompt;
11480 break;
11481
11482 default:
11483 break;
11484 }
11485 STPUTC(pc, pout);
11486 }
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011487 done:
Eric Andersenc470f442003-07-28 09:56:35 +000011488 STPUTC('\0', pout);
11489 psavelen = pout - (char *)stackblock();
11490 if (psavelen > 0) {
11491 pstr = grabstackstr(pout);
11492 setinputstring(pstr);
11493 }
11494 }
11495 nlpp = &bqlist;
11496 while (*nlpp)
11497 nlpp = &(*nlpp)->next;
Denis Vlasenko597906c2008-02-20 16:38:54 +000011498 *nlpp = stzalloc(sizeof(**nlpp));
11499 /* (*nlpp)->next = NULL; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000011500 parsebackquote = oldstyle;
11501
11502 if (oldstyle) {
11503 saveprompt = doprompt;
11504 doprompt = 0;
Eric Andersencb57d552001-06-28 07:25:16 +000011505 }
11506
Eric Andersenc470f442003-07-28 09:56:35 +000011507 n = list(2);
11508
11509 if (oldstyle)
11510 doprompt = saveprompt;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011511 else if (readtoken() != TRP)
11512 raise_error_unexpected_syntax(TRP);
Eric Andersenc470f442003-07-28 09:56:35 +000011513
11514 (*nlpp)->n = n;
11515 if (oldstyle) {
11516 /*
11517 * Start reading from old file again, ignoring any pushed back
11518 * tokens left from the backquote parsing
11519 */
11520 popfile();
11521 tokpushback = 0;
11522 }
11523 while (stackblocksize() <= savelen)
11524 growstackblock();
11525 STARTSTACKSTR(out);
11526 if (str) {
11527 memcpy(out, str, savelen);
11528 STADJUST(savelen, out);
Denis Vlasenkob012b102007-02-19 22:43:01 +000011529 INT_OFF;
11530 free(str);
Eric Andersenc470f442003-07-28 09:56:35 +000011531 str = NULL;
Denis Vlasenkob012b102007-02-19 22:43:01 +000011532 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +000011533 }
11534 parsebackquote = savepbq;
Denis Vlasenko2da584f2007-02-19 22:44:05 +000011535 exception_handler = savehandler;
Eric Andersenc470f442003-07-28 09:56:35 +000011536 if (arinest || dblquote)
11537 USTPUTC(CTLBACKQ | CTLQUOTE, out);
11538 else
11539 USTPUTC(CTLBACKQ, out);
11540 if (oldstyle)
11541 goto parsebackq_oldreturn;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000011542 goto parsebackq_newreturn;
Eric Andersenc470f442003-07-28 09:56:35 +000011543}
11544
Mike Frysinger98c52642009-04-02 10:02:37 +000011545#if ENABLE_SH_MATH_SUPPORT
Eric Andersencb57d552001-06-28 07:25:16 +000011546/*
11547 * Parse an arithmetic expansion (indicate start of one and set state)
11548 */
Eric Andersenc470f442003-07-28 09:56:35 +000011549parsearith: {
Eric Andersenc470f442003-07-28 09:56:35 +000011550 if (++arinest == 1) {
11551 prevsyntax = syntax;
11552 syntax = ARISYNTAX;
11553 USTPUTC(CTLARI, out);
11554 if (dblquote)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000011555 USTPUTC('"', out);
Eric Andersenc470f442003-07-28 09:56:35 +000011556 else
Denis Vlasenkoa624c112007-02-19 22:45:43 +000011557 USTPUTC(' ', out);
Eric Andersenc470f442003-07-28 09:56:35 +000011558 } else {
11559 /*
11560 * we collapse embedded arithmetic expansion to
11561 * parenthesis, which should be equivalent
11562 */
11563 USTPUTC('(', out);
Eric Andersencb57d552001-06-28 07:25:16 +000011564 }
Eric Andersenc470f442003-07-28 09:56:35 +000011565 goto parsearith_return;
11566}
11567#endif
Eric Andersencb57d552001-06-28 07:25:16 +000011568
Eric Andersenc470f442003-07-28 09:56:35 +000011569} /* end of readtoken */
11570
Eric Andersencb57d552001-06-28 07:25:16 +000011571/*
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011572 * Read the next input token.
11573 * If the token is a word, we set backquotelist to the list of cmds in
11574 * backquotes. We set quoteflag to true if any part of the word was
11575 * quoted.
11576 * If the token is TREDIR, then we set redirnode to a structure containing
11577 * the redirection.
11578 * In all cases, the variable startlinno is set to the number of the line
11579 * on which the token starts.
11580 *
11581 * [Change comment: here documents and internal procedures]
11582 * [Readtoken shouldn't have any arguments. Perhaps we should make the
11583 * word parsing code into a separate routine. In this case, readtoken
11584 * doesn't need to have any internal procedures, but parseword does.
11585 * We could also make parseoperator in essence the main routine, and
11586 * have parseword (readtoken1?) handle both words and redirection.]
Eric Andersencb57d552001-06-28 07:25:16 +000011587 */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011588#define NEW_xxreadtoken
11589#ifdef NEW_xxreadtoken
11590/* singles must be first! */
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011591static const char xxreadtoken_chars[7] ALIGN1 = {
Denis Vlasenko834dee72008-10-07 09:18:30 +000011592 '\n', '(', ')', /* singles */
11593 '&', '|', ';', /* doubles */
11594 0
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011595};
Eric Andersencb57d552001-06-28 07:25:16 +000011596
Denis Vlasenko834dee72008-10-07 09:18:30 +000011597#define xxreadtoken_singles 3
11598#define xxreadtoken_doubles 3
11599
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011600static const char xxreadtoken_tokens[] ALIGN1 = {
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011601 TNL, TLP, TRP, /* only single occurrence allowed */
11602 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
11603 TEOF, /* corresponds to trailing nul */
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011604 TAND, TOR, TENDCASE /* if double occurrence */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011605};
11606
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011607static int
11608xxreadtoken(void)
11609{
11610 int c;
11611
11612 if (tokpushback) {
11613 tokpushback = 0;
11614 return lasttoken;
Eric Andersencb57d552001-06-28 07:25:16 +000011615 }
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011616 if (needprompt) {
11617 setprompt(2);
11618 }
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011619 startlinno = g_parsefile->linno;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011620 for (;;) { /* until token or start of word found */
Denis Vlasenko834dee72008-10-07 09:18:30 +000011621 c = pgetc_fast();
Denis Vlasenko5e34ff22009-04-21 11:09:40 +000011622 if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011623 continue;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011624
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011625 if (c == '#') {
11626 while ((c = pgetc()) != '\n' && c != PEOF)
11627 continue;
11628 pungetc();
11629 } else if (c == '\\') {
11630 if (pgetc() != '\n') {
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011631 pungetc();
Denis Vlasenko834dee72008-10-07 09:18:30 +000011632 break; /* return readtoken1(...) */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011633 }
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011634 startlinno = ++g_parsefile->linno;
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011635 if (doprompt)
11636 setprompt(2);
11637 } else {
11638 const char *p;
11639
11640 p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
11641 if (c != PEOF) {
11642 if (c == '\n') {
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011643 g_parsefile->linno++;
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011644 needprompt = doprompt;
11645 }
11646
11647 p = strchr(xxreadtoken_chars, c);
Denis Vlasenko834dee72008-10-07 09:18:30 +000011648 if (p == NULL)
11649 break; /* return readtoken1(...) */
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011650
Denis Vlasenko834dee72008-10-07 09:18:30 +000011651 if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
11652 int cc = pgetc();
11653 if (cc == c) { /* double occurrence? */
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011654 p += xxreadtoken_doubles + 1;
11655 } else {
11656 pungetc();
Denis Vlasenko834dee72008-10-07 09:18:30 +000011657#if ENABLE_ASH_BASH_COMPAT
11658 if (c == '&' && cc == '>') /* &> */
11659 break; /* return readtoken1(...) */
11660#endif
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011661 }
11662 }
11663 }
11664 lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
11665 return lasttoken;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011666 }
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011667 } /* for (;;) */
Denis Vlasenko834dee72008-10-07 09:18:30 +000011668
11669 return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011670}
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011671#else /* old xxreadtoken */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011672#define RETURN(token) return lasttoken = token
11673static int
11674xxreadtoken(void)
11675{
11676 int c;
11677
11678 if (tokpushback) {
11679 tokpushback = 0;
11680 return lasttoken;
11681 }
11682 if (needprompt) {
11683 setprompt(2);
11684 }
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011685 startlinno = g_parsefile->linno;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011686 for (;;) { /* until token or start of word found */
Denis Vlasenko834dee72008-10-07 09:18:30 +000011687 c = pgetc_fast();
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011688 switch (c) {
11689 case ' ': case '\t':
Denys Vlasenko2ce42e92009-11-29 02:18:13 +010011690 IF_ASH_ALIAS(case PEOA:)
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011691 continue;
11692 case '#':
Denis Vlasenkof7d56652008-03-25 05:51:41 +000011693 while ((c = pgetc()) != '\n' && c != PEOF)
11694 continue;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011695 pungetc();
11696 continue;
11697 case '\\':
11698 if (pgetc() == '\n') {
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011699 startlinno = ++g_parsefile->linno;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011700 if (doprompt)
11701 setprompt(2);
11702 continue;
11703 }
11704 pungetc();
11705 goto breakloop;
11706 case '\n':
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011707 g_parsefile->linno++;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011708 needprompt = doprompt;
11709 RETURN(TNL);
11710 case PEOF:
11711 RETURN(TEOF);
11712 case '&':
11713 if (pgetc() == '&')
11714 RETURN(TAND);
11715 pungetc();
11716 RETURN(TBACKGND);
11717 case '|':
11718 if (pgetc() == '|')
11719 RETURN(TOR);
11720 pungetc();
11721 RETURN(TPIPE);
11722 case ';':
11723 if (pgetc() == ';')
11724 RETURN(TENDCASE);
11725 pungetc();
11726 RETURN(TSEMI);
11727 case '(':
11728 RETURN(TLP);
11729 case ')':
11730 RETURN(TRP);
11731 default:
11732 goto breakloop;
11733 }
11734 }
11735 breakloop:
11736 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
11737#undef RETURN
11738}
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011739#endif /* old xxreadtoken */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011740
11741static int
11742readtoken(void)
11743{
11744 int t;
11745#if DEBUG
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011746 smallint alreadyseen = tokpushback;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011747#endif
11748
11749#if ENABLE_ASH_ALIAS
11750 top:
11751#endif
11752
11753 t = xxreadtoken();
11754
11755 /*
11756 * eat newlines
11757 */
11758 if (checkkwd & CHKNL) {
11759 while (t == TNL) {
11760 parseheredoc();
11761 t = xxreadtoken();
11762 }
11763 }
11764
11765 if (t != TWORD || quoteflag) {
11766 goto out;
11767 }
11768
11769 /*
11770 * check for keywords
11771 */
11772 if (checkkwd & CHKKWD) {
11773 const char *const *pp;
11774
11775 pp = findkwd(wordtext);
11776 if (pp) {
11777 lasttoken = t = pp - tokname_array;
Denys Vlasenkoa0ec4f52010-05-20 12:50:42 +020011778 TRACE(("keyword '%s' recognized\n", tokname_array[t] + 1));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011779 goto out;
11780 }
11781 }
11782
11783 if (checkkwd & CHKALIAS) {
11784#if ENABLE_ASH_ALIAS
11785 struct alias *ap;
11786 ap = lookupalias(wordtext, 1);
11787 if (ap != NULL) {
11788 if (*ap->val) {
11789 pushstring(ap->val, ap);
11790 }
11791 goto top;
11792 }
11793#endif
11794 }
11795 out:
11796 checkkwd = 0;
11797#if DEBUG
11798 if (!alreadyseen)
Denys Vlasenkoa0ec4f52010-05-20 12:50:42 +020011799 TRACE(("token '%s' %s\n", tokname_array[t] + 1, t == TWORD ? wordtext : ""));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011800 else
Denys Vlasenkoa0ec4f52010-05-20 12:50:42 +020011801 TRACE(("reread token '%s' %s\n", tokname_array[t] + 1, t == TWORD ? wordtext : ""));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011802#endif
11803 return t;
Eric Andersencb57d552001-06-28 07:25:16 +000011804}
11805
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011806static char
11807peektoken(void)
11808{
11809 int t;
11810
11811 t = readtoken();
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011812 tokpushback = 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011813 return tokname_array[t][0];
11814}
Eric Andersencb57d552001-06-28 07:25:16 +000011815
11816/*
Denys Vlasenko86e83ec2009-07-23 22:07:07 +020011817 * Read and parse a command. Returns NODE_EOF on end of file.
11818 * (NULL is a valid parse tree indicating a blank line.)
Eric Andersencb57d552001-06-28 07:25:16 +000011819 */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011820static union node *
11821parsecmd(int interact)
Eric Andersen90898442003-08-06 11:20:52 +000011822{
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011823 int t;
Eric Andersencb57d552001-06-28 07:25:16 +000011824
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011825 tokpushback = 0;
11826 doprompt = interact;
11827 if (doprompt)
11828 setprompt(doprompt);
11829 needprompt = 0;
11830 t = readtoken();
11831 if (t == TEOF)
Denys Vlasenko86e83ec2009-07-23 22:07:07 +020011832 return NODE_EOF;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011833 if (t == TNL)
11834 return NULL;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011835 tokpushback = 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011836 return list(1);
11837}
11838
11839/*
11840 * Input any here documents.
11841 */
11842static void
11843parseheredoc(void)
11844{
11845 struct heredoc *here;
11846 union node *n;
11847
11848 here = heredoclist;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000011849 heredoclist = NULL;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011850
11851 while (here) {
11852 if (needprompt) {
11853 setprompt(2);
11854 }
11855 readtoken1(pgetc(), here->here->type == NHERE? SQSYNTAX : DQSYNTAX,
11856 here->eofmark, here->striptabs);
Denis Vlasenko597906c2008-02-20 16:38:54 +000011857 n = stzalloc(sizeof(struct narg));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011858 n->narg.type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000011859 /*n->narg.next = NULL; - stzalloc did it */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011860 n->narg.text = wordtext;
11861 n->narg.backquote = backquotelist;
11862 here->here->nhere.doc = n;
11863 here = here->next;
Eric Andersencb57d552001-06-28 07:25:16 +000011864 }
Eric Andersencb57d552001-06-28 07:25:16 +000011865}
11866
11867
11868/*
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +000011869 * called by editline -- any expansions to the prompt should be added here.
Eric Andersencb57d552001-06-28 07:25:16 +000011870 */
Denis Vlasenko131ae172007-02-18 13:00:19 +000011871#if ENABLE_ASH_EXPAND_PRMT
"Vladimir N. Oleynik"bef14d72005-09-05 13:25:11 +000011872static const char *
11873expandstr(const char *ps)
11874{
11875 union node n;
11876
Denis Vlasenko5c2b8142009-03-19 01:59:59 +000011877 /* XXX Fix (char *) cast. It _is_ a bug. ps is variable's value,
11878 * and token processing _can_ alter it (delete NULs etc). */
"Vladimir N. Oleynik"bef14d72005-09-05 13:25:11 +000011879 setinputstring((char *)ps);
Denis Vlasenko46a53062007-09-24 18:30:02 +000011880 readtoken1(pgetc(), PSSYNTAX, nullstr, 0);
"Vladimir N. Oleynik"bef14d72005-09-05 13:25:11 +000011881 popfile();
11882
11883 n.narg.type = NARG;
11884 n.narg.next = NULL;
11885 n.narg.text = wordtext;
11886 n.narg.backquote = backquotelist;
11887
11888 expandarg(&n, NULL, 0);
11889 return stackblock();
11890}
11891#endif
11892
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011893/*
11894 * Execute a command or commands contained in a string.
11895 */
11896static int
11897evalstring(char *s, int mask)
Eric Andersenc470f442003-07-28 09:56:35 +000011898{
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011899 union node *n;
11900 struct stackmark smark;
11901 int skip;
11902
11903 setinputstring(s);
11904 setstackmark(&smark);
11905
11906 skip = 0;
Denys Vlasenko86e83ec2009-07-23 22:07:07 +020011907 while ((n = parsecmd(0)) != NODE_EOF) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011908 evaltree(n, 0);
11909 popstackmark(&smark);
11910 skip = evalskip;
11911 if (skip)
11912 break;
11913 }
11914 popfile();
11915
11916 skip &= mask;
11917 evalskip = skip;
11918 return skip;
Eric Andersenc470f442003-07-28 09:56:35 +000011919}
11920
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011921/*
11922 * The eval command.
11923 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011924static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000011925evalcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011926{
11927 char *p;
11928 char *concat;
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011929
Denis Vlasenko68404f12008-03-17 09:00:54 +000011930 if (argv[1]) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011931 p = argv[1];
Denis Vlasenko68404f12008-03-17 09:00:54 +000011932 argv += 2;
11933 if (argv[0]) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011934 STARTSTACKSTR(concat);
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011935 for (;;) {
11936 concat = stack_putstr(p, concat);
Denis Vlasenko68404f12008-03-17 09:00:54 +000011937 p = *argv++;
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011938 if (p == NULL)
11939 break;
11940 STPUTC(' ', concat);
11941 }
11942 STPUTC('\0', concat);
11943 p = grabstackstr(concat);
11944 }
11945 evalstring(p, ~SKIPEVAL);
11946
11947 }
11948 return exitstatus;
11949}
11950
11951/*
Denys Vlasenko285ad152009-12-04 23:02:27 +010011952 * Read and execute commands.
11953 * "Top" is nonzero for the top level command loop;
11954 * it turns on prompting if the shell is interactive.
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011955 */
11956static int
11957cmdloop(int top)
11958{
11959 union node *n;
11960 struct stackmark smark;
11961 int inter;
11962 int numeof = 0;
11963
11964 TRACE(("cmdloop(%d) called\n", top));
11965 for (;;) {
11966 int skip;
11967
11968 setstackmark(&smark);
11969#if JOBS
Denis Vlasenkob07a4962008-06-22 13:16:23 +000011970 if (doing_jobctl)
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011971 showjobs(stderr, SHOW_CHANGED);
11972#endif
11973 inter = 0;
11974 if (iflag && top) {
11975 inter++;
11976#if ENABLE_ASH_MAIL
11977 chkmail();
11978#endif
11979 }
11980 n = parsecmd(inter);
Denys Vlasenko7cee00e2009-07-24 01:08:03 +020011981#if DEBUG
11982 if (DEBUG > 2 && debug && (n != NODE_EOF))
Denys Vlasenko883cea42009-07-11 15:31:59 +020011983 showtree(n);
Denis Vlasenko135cecb2009-04-12 00:00:57 +000011984#endif
Denys Vlasenko86e83ec2009-07-23 22:07:07 +020011985 if (n == NODE_EOF) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011986 if (!top || numeof >= 50)
11987 break;
11988 if (!stoppedjobs()) {
11989 if (!Iflag)
11990 break;
11991 out2str("\nUse \"exit\" to leave shell.\n");
11992 }
11993 numeof++;
11994 } else if (nflag == 0) {
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +000011995 /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
11996 job_warning >>= 1;
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011997 numeof = 0;
11998 evaltree(n, 0);
11999 }
12000 popstackmark(&smark);
12001 skip = evalskip;
12002
12003 if (skip) {
12004 evalskip = 0;
12005 return skip & SKIPEVAL;
12006 }
12007 }
12008 return 0;
12009}
12010
Denis Vlasenko0dec6de2007-02-23 21:10:47 +000012011/*
12012 * Take commands from a file. To be compatible we should do a path
12013 * search for the file, which is necessary to find sub-commands.
12014 */
12015static char *
12016find_dot_file(char *name)
12017{
12018 char *fullname;
12019 const char *path = pathval();
12020 struct stat statb;
12021
12022 /* don't try this for absolute or relative paths */
12023 if (strchr(name, '/'))
12024 return name;
12025
Denis Vlasenko8ad78e12009-02-15 12:40:30 +000012026 /* IIRC standards do not say whether . is to be searched.
12027 * And it is even smaller this way, making it unconditional for now:
12028 */
12029 if (1) { /* ENABLE_ASH_BASH_COMPAT */
12030 fullname = name;
12031 goto try_cur_dir;
12032 }
12033
Denys Vlasenko82a6fb32009-06-14 19:42:12 +020012034 while ((fullname = path_advance(&path, name)) != NULL) {
Denis Vlasenko8ad78e12009-02-15 12:40:30 +000012035 try_cur_dir:
Denis Vlasenko0dec6de2007-02-23 21:10:47 +000012036 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
12037 /*
12038 * Don't bother freeing here, since it will
12039 * be freed by the caller.
12040 */
12041 return fullname;
12042 }
Denys Vlasenko82a6fb32009-06-14 19:42:12 +020012043 if (fullname != name)
12044 stunalloc(fullname);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +000012045 }
12046
12047 /* not found in the PATH */
12048 ash_msg_and_raise_error("%s: not found", name);
12049 /* NOTREACHED */
12050}
12051
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012052static int FAST_FUNC
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012053dotcmd(int argc, char **argv)
12054{
Denys Vlasenkoe66cf822010-05-18 09:12:53 +020012055 char *fullname;
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012056 struct strlist *sp;
12057 volatile struct shparam saveparam;
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012058
12059 for (sp = cmdenviron; sp; sp = sp->next)
Denis Vlasenko4222ae42007-02-25 02:37:49 +000012060 setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012061
Denys Vlasenkoe66cf822010-05-18 09:12:53 +020012062 if (!argv[1]) {
12063 /* bash says: "bash: .: filename argument required" */
12064 return 2; /* bash compat */
12065 }
12066
Denys Vlasenkocd10dc42010-05-17 17:10:46 +020012067 /* "false; . empty_file; echo $?" should print 0, not 1: */
12068 exitstatus = 0;
12069
Denys Vlasenkoe66cf822010-05-18 09:12:53 +020012070 fullname = find_dot_file(argv[1]);
Denys Vlasenkocd10dc42010-05-17 17:10:46 +020012071
Denys Vlasenkoe66cf822010-05-18 09:12:53 +020012072 argv += 2;
12073 argc -= 2;
12074 if (argc) { /* argc > 0, argv[0] != NULL */
12075 saveparam = shellparam;
12076 shellparam.malloced = 0;
12077 shellparam.nparam = argc;
12078 shellparam.p = argv;
12079 };
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012080
Denys Vlasenkoe66cf822010-05-18 09:12:53 +020012081 setinputfile(fullname, INPUT_PUSH_FILE);
12082 commandname = fullname;
12083 cmdloop(0);
12084 popfile();
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012085
Denys Vlasenkoe66cf822010-05-18 09:12:53 +020012086 if (argc) {
12087 freeparam(&shellparam);
12088 shellparam = saveparam;
12089 };
12090
Denys Vlasenkocd10dc42010-05-17 17:10:46 +020012091 return exitstatus;
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012092}
12093
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012094static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012095exitcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012096{
12097 if (stoppedjobs())
12098 return 0;
Denis Vlasenko68404f12008-03-17 09:00:54 +000012099 if (argv[1])
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012100 exitstatus = number(argv[1]);
12101 raise_exception(EXEXIT);
12102 /* NOTREACHED */
12103}
12104
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012105/*
12106 * Read a file containing shell functions.
12107 */
12108static void
12109readcmdfile(char *name)
12110{
12111 setinputfile(name, INPUT_PUSH_FILE);
12112 cmdloop(0);
12113 popfile();
12114}
12115
12116
Denis Vlasenkocc571512007-02-23 21:10:35 +000012117/* ============ find_command inplementation */
12118
12119/*
12120 * Resolve a command name. If you change this routine, you may have to
12121 * change the shellexec routine as well.
12122 */
12123static void
12124find_command(char *name, struct cmdentry *entry, int act, const char *path)
12125{
12126 struct tblentry *cmdp;
12127 int idx;
12128 int prev;
12129 char *fullname;
12130 struct stat statb;
12131 int e;
12132 int updatetbl;
12133 struct builtincmd *bcmd;
12134
12135 /* If name contains a slash, don't use PATH or hash table */
12136 if (strchr(name, '/') != NULL) {
12137 entry->u.index = -1;
12138 if (act & DO_ABS) {
12139 while (stat(name, &statb) < 0) {
12140#ifdef SYSV
12141 if (errno == EINTR)
12142 continue;
12143#endif
12144 entry->cmdtype = CMDUNKNOWN;
12145 return;
12146 }
12147 }
12148 entry->cmdtype = CMDNORMAL;
12149 return;
12150 }
12151
Denis Vlasenkof20de5b2007-04-29 23:42:54 +000012152/* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
Denis Vlasenkocc571512007-02-23 21:10:35 +000012153
12154 updatetbl = (path == pathval());
12155 if (!updatetbl) {
12156 act |= DO_ALTPATH;
12157 if (strstr(path, "%builtin") != NULL)
12158 act |= DO_ALTBLTIN;
12159 }
12160
12161 /* If name is in the table, check answer will be ok */
12162 cmdp = cmdlookup(name, 0);
12163 if (cmdp != NULL) {
12164 int bit;
12165
12166 switch (cmdp->cmdtype) {
12167 default:
12168#if DEBUG
12169 abort();
12170#endif
12171 case CMDNORMAL:
12172 bit = DO_ALTPATH;
12173 break;
12174 case CMDFUNCTION:
12175 bit = DO_NOFUNC;
12176 break;
12177 case CMDBUILTIN:
12178 bit = DO_ALTBLTIN;
12179 break;
12180 }
12181 if (act & bit) {
12182 updatetbl = 0;
12183 cmdp = NULL;
12184 } else if (cmdp->rehash == 0)
12185 /* if not invalidated by cd, we're done */
12186 goto success;
12187 }
12188
12189 /* If %builtin not in path, check for builtin next */
12190 bcmd = find_builtin(name);
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +000012191 if (bcmd) {
12192 if (IS_BUILTIN_REGULAR(bcmd))
12193 goto builtin_success;
12194 if (act & DO_ALTPATH) {
12195 if (!(act & DO_ALTBLTIN))
12196 goto builtin_success;
12197 } else if (builtinloc <= 0) {
12198 goto builtin_success;
Denis Vlasenko8e858e22007-03-07 09:35:43 +000012199 }
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +000012200 }
Denis Vlasenkocc571512007-02-23 21:10:35 +000012201
Denis Vlasenkof20de5b2007-04-29 23:42:54 +000012202#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko7465dbc2008-04-13 02:25:53 +000012203 {
12204 int applet_no = find_applet_by_name(name);
12205 if (applet_no >= 0) {
12206 entry->cmdtype = CMDNORMAL;
12207 entry->u.index = -2 - applet_no;
12208 return;
12209 }
Denis Vlasenkof20de5b2007-04-29 23:42:54 +000012210 }
12211#endif
12212
Denis Vlasenkocc571512007-02-23 21:10:35 +000012213 /* We have to search path. */
12214 prev = -1; /* where to start */
12215 if (cmdp && cmdp->rehash) { /* doing a rehash */
12216 if (cmdp->cmdtype == CMDBUILTIN)
12217 prev = builtinloc;
12218 else
12219 prev = cmdp->param.index;
12220 }
12221
12222 e = ENOENT;
12223 idx = -1;
12224 loop:
Denys Vlasenko82a6fb32009-06-14 19:42:12 +020012225 while ((fullname = path_advance(&path, name)) != NULL) {
Denis Vlasenkocc571512007-02-23 21:10:35 +000012226 stunalloc(fullname);
Denis Vlasenkodee82b62007-07-29 14:05:27 +000012227 /* NB: code below will still use fullname
12228 * despite it being "unallocated" */
Denis Vlasenkocc571512007-02-23 21:10:35 +000012229 idx++;
12230 if (pathopt) {
12231 if (prefix(pathopt, "builtin")) {
12232 if (bcmd)
12233 goto builtin_success;
12234 continue;
Denis Vlasenko4a9ca132008-04-12 20:07:08 +000012235 }
12236 if ((act & DO_NOFUNC)
12237 || !prefix(pathopt, "func")
12238 ) { /* ignore unimplemented options */
Denis Vlasenkocc571512007-02-23 21:10:35 +000012239 continue;
12240 }
12241 }
12242 /* if rehash, don't redo absolute path names */
12243 if (fullname[0] == '/' && idx <= prev) {
12244 if (idx < prev)
12245 continue;
12246 TRACE(("searchexec \"%s\": no change\n", name));
12247 goto success;
12248 }
12249 while (stat(fullname, &statb) < 0) {
12250#ifdef SYSV
12251 if (errno == EINTR)
12252 continue;
12253#endif
12254 if (errno != ENOENT && errno != ENOTDIR)
12255 e = errno;
12256 goto loop;
12257 }
12258 e = EACCES; /* if we fail, this will be the error */
12259 if (!S_ISREG(statb.st_mode))
12260 continue;
12261 if (pathopt) { /* this is a %func directory */
12262 stalloc(strlen(fullname) + 1);
Denis Vlasenkodee82b62007-07-29 14:05:27 +000012263 /* NB: stalloc will return space pointed by fullname
12264 * (because we don't have any intervening allocations
12265 * between stunalloc above and this stalloc) */
Denis Vlasenkocc571512007-02-23 21:10:35 +000012266 readcmdfile(fullname);
12267 cmdp = cmdlookup(name, 0);
12268 if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
12269 ash_msg_and_raise_error("%s not defined in %s", name, fullname);
12270 stunalloc(fullname);
12271 goto success;
12272 }
12273 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
12274 if (!updatetbl) {
12275 entry->cmdtype = CMDNORMAL;
12276 entry->u.index = idx;
12277 return;
12278 }
12279 INT_OFF;
12280 cmdp = cmdlookup(name, 1);
12281 cmdp->cmdtype = CMDNORMAL;
12282 cmdp->param.index = idx;
12283 INT_ON;
12284 goto success;
12285 }
12286
12287 /* We failed. If there was an entry for this command, delete it */
12288 if (cmdp && updatetbl)
12289 delete_cmd_entry();
12290 if (act & DO_ERR)
12291 ash_msg("%s: %s", name, errmsg(e, "not found"));
12292 entry->cmdtype = CMDUNKNOWN;
12293 return;
12294
12295 builtin_success:
12296 if (!updatetbl) {
12297 entry->cmdtype = CMDBUILTIN;
12298 entry->u.cmd = bcmd;
12299 return;
12300 }
12301 INT_OFF;
12302 cmdp = cmdlookup(name, 1);
12303 cmdp->cmdtype = CMDBUILTIN;
12304 cmdp->param.cmd = bcmd;
12305 INT_ON;
12306 success:
12307 cmdp->rehash = 0;
12308 entry->cmdtype = cmdp->cmdtype;
12309 entry->u = cmdp->param;
12310}
12311
12312
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012313/* ============ trap.c */
Eric Andersenc470f442003-07-28 09:56:35 +000012314
Eric Andersencb57d552001-06-28 07:25:16 +000012315/*
Eric Andersencb57d552001-06-28 07:25:16 +000012316 * The trap builtin.
12317 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012318static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012319trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersencb57d552001-06-28 07:25:16 +000012320{
12321 char *action;
12322 char **ap;
Denys Vlasenko496d5bf2010-03-26 15:52:24 +010012323 int signo, exitcode;
Eric Andersencb57d552001-06-28 07:25:16 +000012324
Eric Andersenc470f442003-07-28 09:56:35 +000012325 nextopt(nullstr);
12326 ap = argptr;
12327 if (!*ap) {
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012328 for (signo = 0; signo < NSIG; signo++) {
Denys Vlasenko21d87d42009-09-25 00:06:51 +020012329 char *tr = trap_ptr[signo];
12330 if (tr) {
Denys Vlasenkoe74aaf92009-09-27 02:05:45 +020012331 /* note: bash adds "SIG", but only if invoked
12332 * as "bash". If called as "sh", or if set -o posix,
12333 * then it prints short signal names.
12334 * We are printing short names: */
12335 out1fmt("trap -- %s %s\n",
Denys Vlasenko21d87d42009-09-25 00:06:51 +020012336 single_quote(tr),
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +000012337 get_signame(signo));
Denys Vlasenko726e1a02009-09-25 02:58:20 +020012338 /* trap_ptr != trap only if we are in special-cased `trap` code.
12339 * In this case, we will exit very soon, no need to free(). */
Denys Vlasenkoe74aaf92009-09-27 02:05:45 +020012340 /* if (trap_ptr != trap && tp[0]) */
Denys Vlasenko726e1a02009-09-25 02:58:20 +020012341 /* free(tr); */
Eric Andersencb57d552001-06-28 07:25:16 +000012342 }
12343 }
Denys Vlasenko726e1a02009-09-25 02:58:20 +020012344 /*
Denys Vlasenko21d87d42009-09-25 00:06:51 +020012345 if (trap_ptr != trap) {
12346 free(trap_ptr);
12347 trap_ptr = trap;
12348 }
Denys Vlasenko726e1a02009-09-25 02:58:20 +020012349 */
Eric Andersencb57d552001-06-28 07:25:16 +000012350 return 0;
12351 }
Denys Vlasenko21d87d42009-09-25 00:06:51 +020012352
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +000012353 action = NULL;
12354 if (ap[1])
Eric Andersencb57d552001-06-28 07:25:16 +000012355 action = *ap++;
Denys Vlasenko496d5bf2010-03-26 15:52:24 +010012356 exitcode = 0;
Eric Andersencb57d552001-06-28 07:25:16 +000012357 while (*ap) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +000012358 signo = get_signum(*ap);
Denys Vlasenko496d5bf2010-03-26 15:52:24 +010012359 if (signo < 0) {
12360 /* Mimic bash message exactly */
12361 ash_msg("%s: invalid signal specification", *ap);
12362 exitcode = 1;
12363 goto next;
12364 }
Denis Vlasenkob012b102007-02-19 22:43:01 +000012365 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +000012366 if (action) {
Denis Vlasenko9f739442006-12-16 23:49:13 +000012367 if (LONE_DASH(action))
Eric Andersencb57d552001-06-28 07:25:16 +000012368 action = NULL;
12369 else
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012370 action = ckstrdup(action);
Eric Andersencb57d552001-06-28 07:25:16 +000012371 }
Denis Vlasenko60818682007-09-28 22:07:23 +000012372 free(trap[signo]);
Denys Vlasenko238bf182010-05-18 15:49:07 +020012373 if (action)
12374 may_have_traps = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000012375 trap[signo] = action;
12376 if (signo != 0)
12377 setsignal(signo);
Denis Vlasenkob012b102007-02-19 22:43:01 +000012378 INT_ON;
Denys Vlasenko496d5bf2010-03-26 15:52:24 +010012379 next:
Eric Andersencb57d552001-06-28 07:25:16 +000012380 ap++;
12381 }
Denys Vlasenko496d5bf2010-03-26 15:52:24 +010012382 return exitcode;
Eric Andersencb57d552001-06-28 07:25:16 +000012383}
12384
Eric Andersenc470f442003-07-28 09:56:35 +000012385
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012386/* ============ Builtins */
Eric Andersenc470f442003-07-28 09:56:35 +000012387
Denis Vlasenko8e1c7152007-01-22 07:21:38 +000012388#if !ENABLE_FEATURE_SH_EXTRA_QUIET
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012389/*
12390 * Lists available builtins
12391 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012392static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012393helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersenc470f442003-07-28 09:56:35 +000012394{
Denis Vlasenko6b06cb82008-05-15 21:30:45 +000012395 unsigned col;
12396 unsigned i;
Eric Andersenc470f442003-07-28 09:56:35 +000012397
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +020012398 out1fmt(
Denis Vlasenko34d4d892009-04-04 20:24:37 +000012399 "Built-in commands:\n"
12400 "------------------\n");
Denis Vlasenkob71c6682007-07-21 15:08:09 +000012401 for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
Eric Andersenc470f442003-07-28 09:56:35 +000012402 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
Denis Vlasenko52764022007-02-24 13:42:56 +000012403 builtintab[i].name + 1);
Eric Andersenc470f442003-07-28 09:56:35 +000012404 if (col > 60) {
12405 out1fmt("\n");
12406 col = 0;
12407 }
12408 }
Denis Vlasenko80d14be2007-04-10 23:03:30 +000012409#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko1aa7e472007-11-28 06:49:03 +000012410 {
12411 const char *a = applet_names;
12412 while (*a) {
12413 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
12414 if (col > 60) {
12415 out1fmt("\n");
12416 col = 0;
12417 }
12418 a += strlen(a) + 1;
Eric Andersenc470f442003-07-28 09:56:35 +000012419 }
12420 }
12421#endif
12422 out1fmt("\n\n");
12423 return EXIT_SUCCESS;
12424}
Denis Vlasenko131ae172007-02-18 13:00:19 +000012425#endif /* FEATURE_SH_EXTRA_QUIET */
Eric Andersenc470f442003-07-28 09:56:35 +000012426
Eric Andersencb57d552001-06-28 07:25:16 +000012427/*
Eric Andersencb57d552001-06-28 07:25:16 +000012428 * The export and readonly commands.
12429 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012430static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012431exportcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +000012432{
12433 struct var *vp;
12434 char *name;
12435 const char *p;
Eric Andersenc470f442003-07-28 09:56:35 +000012436 char **aptr;
Denis Vlasenkob7304742008-10-20 08:15:51 +000012437 int flag = argv[0][0] == 'r' ? VREADONLY : VEXPORT;
Eric Andersencb57d552001-06-28 07:25:16 +000012438
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012439 if (nextopt("p") != 'p') {
12440 aptr = argptr;
12441 name = *aptr;
12442 if (name) {
12443 do {
12444 p = strchr(name, '=');
12445 if (p != NULL) {
12446 p++;
12447 } else {
12448 vp = *findvar(hashvar(name), name);
12449 if (vp) {
12450 vp->flags |= flag;
12451 continue;
12452 }
Eric Andersencb57d552001-06-28 07:25:16 +000012453 }
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012454 setvar(name, p, flag);
12455 } while ((name = *++aptr) != NULL);
12456 return 0;
12457 }
Eric Andersencb57d552001-06-28 07:25:16 +000012458 }
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012459 showvars(argv[0], flag, 0);
Eric Andersencb57d552001-06-28 07:25:16 +000012460 return 0;
12461}
12462
Eric Andersencb57d552001-06-28 07:25:16 +000012463/*
Denis Vlasenko5651bfc2007-02-23 21:08:58 +000012464 * Delete a function if it exists.
Eric Andersencb57d552001-06-28 07:25:16 +000012465 */
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012466static void
Denis Vlasenko5651bfc2007-02-23 21:08:58 +000012467unsetfunc(const char *name)
Aaron Lehmannb6ecbdc2001-12-06 03:37:38 +000012468{
Denis Vlasenko5651bfc2007-02-23 21:08:58 +000012469 struct tblentry *cmdp;
Eric Andersencb57d552001-06-28 07:25:16 +000012470
Denis Vlasenko5651bfc2007-02-23 21:08:58 +000012471 cmdp = cmdlookup(name, 0);
Denys Vlasenko1ed2fb42010-06-18 14:09:48 +020012472 if (cmdp != NULL && cmdp->cmdtype == CMDFUNCTION)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +000012473 delete_cmd_entry();
Eric Andersenc470f442003-07-28 09:56:35 +000012474}
12475
Eric Andersencb57d552001-06-28 07:25:16 +000012476/*
Eric Andersencb57d552001-06-28 07:25:16 +000012477 * The unset builtin command. We unset the function before we unset the
12478 * variable to allow a function to be unset when there is a readonly variable
12479 * with the same name.
12480 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012481static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012482unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersencb57d552001-06-28 07:25:16 +000012483{
12484 char **ap;
12485 int i;
Eric Andersenc470f442003-07-28 09:56:35 +000012486 int flag = 0;
Eric Andersencb57d552001-06-28 07:25:16 +000012487 int ret = 0;
12488
Denys Vlasenko1ed2fb42010-06-18 14:09:48 +020012489 while ((i = nextopt("vf")) != 0) {
Eric Andersenc470f442003-07-28 09:56:35 +000012490 flag = i;
Eric Andersencb57d552001-06-28 07:25:16 +000012491 }
Eric Andersencb57d552001-06-28 07:25:16 +000012492
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012493 for (ap = argptr; *ap; ap++) {
Eric Andersenc470f442003-07-28 09:56:35 +000012494 if (flag != 'f') {
12495 i = unsetvar(*ap);
12496 ret |= i;
12497 if (!(i & 2))
12498 continue;
12499 }
12500 if (flag != 'v')
Eric Andersencb57d552001-06-28 07:25:16 +000012501 unsetfunc(*ap);
Eric Andersencb57d552001-06-28 07:25:16 +000012502 }
Eric Andersenc470f442003-07-28 09:56:35 +000012503 return ret & 1;
Eric Andersencb57d552001-06-28 07:25:16 +000012504}
12505
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000012506static const unsigned char timescmd_str[] ALIGN1 = {
Manuel Novoa III 4456f252003-08-13 17:48:47 +000012507 ' ', offsetof(struct tms, tms_utime),
12508 '\n', offsetof(struct tms, tms_stime),
12509 ' ', offsetof(struct tms, tms_cutime),
12510 '\n', offsetof(struct tms, tms_cstime),
12511 0
12512};
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012513static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012514timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Manuel Novoa III 4456f252003-08-13 17:48:47 +000012515{
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012516 long clk_tck, s, t;
Manuel Novoa III 4456f252003-08-13 17:48:47 +000012517 const unsigned char *p;
12518 struct tms buf;
12519
12520 clk_tck = sysconf(_SC_CLK_TCK);
Eric Andersencb57d552001-06-28 07:25:16 +000012521 times(&buf);
Manuel Novoa III 4456f252003-08-13 17:48:47 +000012522
12523 p = timescmd_str;
12524 do {
12525 t = *(clock_t *)(((char *) &buf) + p[1]);
12526 s = t / clk_tck;
12527 out1fmt("%ldm%ld.%.3lds%c",
12528 s/60, s%60,
12529 ((t - s * clk_tck) * 1000) / clk_tck,
12530 p[0]);
Denys Vlasenko1ed2fb42010-06-18 14:09:48 +020012531 p += 2;
12532 } while (*p);
Manuel Novoa III 4456f252003-08-13 17:48:47 +000012533
Eric Andersencb57d552001-06-28 07:25:16 +000012534 return 0;
12535}
12536
Mike Frysinger98c52642009-04-02 10:02:37 +000012537#if ENABLE_SH_MATH_SUPPORT
Eric Andersenc470f442003-07-28 09:56:35 +000012538/*
Denys Vlasenko1ed2fb42010-06-18 14:09:48 +020012539 * The let builtin. Partially stolen from GNU Bash, the Bourne Again SHell.
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +000012540 * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
Eric Andersen90898442003-08-06 11:20:52 +000012541 *
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +000012542 * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
Eric Andersenc470f442003-07-28 09:56:35 +000012543 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012544static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012545letcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersenc470f442003-07-28 09:56:35 +000012546{
Denis Vlasenko68404f12008-03-17 09:00:54 +000012547 arith_t i;
Eric Andersenc470f442003-07-28 09:56:35 +000012548
Denis Vlasenko68404f12008-03-17 09:00:54 +000012549 argv++;
12550 if (!*argv)
Denis Vlasenkob012b102007-02-19 22:43:01 +000012551 ash_msg_and_raise_error("expression expected");
Denis Vlasenko68404f12008-03-17 09:00:54 +000012552 do {
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +000012553 i = ash_arith(*argv);
Denis Vlasenko68404f12008-03-17 09:00:54 +000012554 } while (*++argv);
Eric Andersenc470f442003-07-28 09:56:35 +000012555
Denis Vlasenkod9e15f22006-11-27 16:49:55 +000012556 return !i;
Eric Andersenc470f442003-07-28 09:56:35 +000012557}
Eric Andersenc470f442003-07-28 09:56:35 +000012558#endif
Eric Andersen74bcd162001-07-30 21:41:37 +000012559
Eric Andersenc470f442003-07-28 09:56:35 +000012560/*
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012561 * The read builtin. Options:
12562 * -r Do not interpret '\' specially
12563 * -s Turn off echo (tty only)
12564 * -n NCHARS Read NCHARS max
12565 * -p PROMPT Display PROMPT on stderr (if input is from tty)
12566 * -t SECONDS Timeout after SECONDS (tty or pipe only)
12567 * -u FD Read from given FD instead of fd 0
Eric Andersenc470f442003-07-28 09:56:35 +000012568 * This uses unbuffered input, which may be avoidable in some cases.
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012569 * TODO: bash also has:
12570 * -a ARRAY Read into array[0],[1],etc
12571 * -d DELIM End on DELIM char, not newline
12572 * -e Use line editing (tty only)
Eric Andersenc470f442003-07-28 09:56:35 +000012573 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012574static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012575readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersenc470f442003-07-28 09:56:35 +000012576{
Denys Vlasenko73067272010-01-12 22:11:24 +010012577 char *opt_n = NULL;
12578 char *opt_p = NULL;
12579 char *opt_t = NULL;
12580 char *opt_u = NULL;
12581 int read_flags = 0;
12582 const char *r;
Eric Andersenc470f442003-07-28 09:56:35 +000012583 int i;
12584
Denys Vlasenko73067272010-01-12 22:11:24 +010012585 while ((i = nextopt("p:u:rt:n:s")) != '\0') {
Denis Vlasenkobf0a2012006-12-26 10:42:51 +000012586 switch (i) {
Paul Fox02eb9342005-09-07 16:56:02 +000012587 case 'p':
Denys Vlasenko73067272010-01-12 22:11:24 +010012588 opt_p = optionarg;
Paul Fox02eb9342005-09-07 16:56:02 +000012589 break;
Paul Fox02eb9342005-09-07 16:56:02 +000012590 case 'n':
Denys Vlasenko73067272010-01-12 22:11:24 +010012591 opt_n = optionarg;
Paul Fox02eb9342005-09-07 16:56:02 +000012592 break;
12593 case 's':
Denys Vlasenko73067272010-01-12 22:11:24 +010012594 read_flags |= BUILTIN_READ_SILENT;
Paul Fox02eb9342005-09-07 16:56:02 +000012595 break;
Paul Fox02eb9342005-09-07 16:56:02 +000012596 case 't':
Denys Vlasenko73067272010-01-12 22:11:24 +010012597 opt_t = optionarg;
Paul Fox02eb9342005-09-07 16:56:02 +000012598 break;
Paul Fox02eb9342005-09-07 16:56:02 +000012599 case 'r':
Denys Vlasenko73067272010-01-12 22:11:24 +010012600 read_flags |= BUILTIN_READ_RAW;
Paul Fox02eb9342005-09-07 16:56:02 +000012601 break;
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012602 case 'u':
Denys Vlasenko73067272010-01-12 22:11:24 +010012603 opt_u = optionarg;
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012604 break;
Paul Fox02eb9342005-09-07 16:56:02 +000012605 default:
12606 break;
12607 }
Eric Andersenc470f442003-07-28 09:56:35 +000012608 }
Paul Fox02eb9342005-09-07 16:56:02 +000012609
Denys Vlasenko03dad222010-01-12 23:29:57 +010012610 r = shell_builtin_read(setvar2,
Denys Vlasenko73067272010-01-12 22:11:24 +010012611 argptr,
12612 bltinlookup("IFS"), /* can be NULL */
12613 read_flags,
12614 opt_n,
12615 opt_p,
12616 opt_t,
12617 opt_u
12618 );
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012619
Denys Vlasenko73067272010-01-12 22:11:24 +010012620 if ((uintptr_t)r > 1)
12621 ash_msg_and_raise_error(r);
Denis Vlasenko037576d2007-10-20 18:30:38 +000012622
Denys Vlasenko73067272010-01-12 22:11:24 +010012623 return (uintptr_t)r;
Eric Andersenc470f442003-07-28 09:56:35 +000012624}
12625
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012626static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012627umaskcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersenc470f442003-07-28 09:56:35 +000012628{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000012629 static const char permuser[3] ALIGN1 = "ugo";
12630 static const char permmode[3] ALIGN1 = "rwx";
12631 static const short permmask[] ALIGN2 = {
Eric Andersenc470f442003-07-28 09:56:35 +000012632 S_IRUSR, S_IWUSR, S_IXUSR,
12633 S_IRGRP, S_IWGRP, S_IXGRP,
12634 S_IROTH, S_IWOTH, S_IXOTH
12635 };
12636
Denis Vlasenkoeb858492009-04-18 02:06:54 +000012637 /* TODO: use bb_parse_mode() instead */
12638
Eric Andersenc470f442003-07-28 09:56:35 +000012639 char *ap;
12640 mode_t mask;
12641 int i;
12642 int symbolic_mode = 0;
12643
12644 while (nextopt("S") != '\0') {
12645 symbolic_mode = 1;
12646 }
12647
Denis Vlasenkob012b102007-02-19 22:43:01 +000012648 INT_OFF;
Eric Andersenc470f442003-07-28 09:56:35 +000012649 mask = umask(0);
12650 umask(mask);
Denis Vlasenkob012b102007-02-19 22:43:01 +000012651 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +000012652
Denis Vlasenko5cedb752007-02-18 19:56:41 +000012653 ap = *argptr;
12654 if (ap == NULL) {
Eric Andersenc470f442003-07-28 09:56:35 +000012655 if (symbolic_mode) {
12656 char buf[18];
12657 char *p = buf;
12658
12659 for (i = 0; i < 3; i++) {
12660 int j;
12661
12662 *p++ = permuser[i];
12663 *p++ = '=';
12664 for (j = 0; j < 3; j++) {
12665 if ((mask & permmask[3 * i + j]) == 0) {
12666 *p++ = permmode[j];
12667 }
12668 }
12669 *p++ = ',';
12670 }
12671 *--p = 0;
12672 puts(buf);
12673 } else {
12674 out1fmt("%.4o\n", mask);
12675 }
12676 } else {
Denis Vlasenkoaa744452007-02-23 01:04:22 +000012677 if (isdigit((unsigned char) *ap)) {
Eric Andersenc470f442003-07-28 09:56:35 +000012678 mask = 0;
12679 do {
12680 if (*ap >= '8' || *ap < '0')
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +020012681 ash_msg_and_raise_error(msg_illnum, argv[1]);
Eric Andersenc470f442003-07-28 09:56:35 +000012682 mask = (mask << 3) + (*ap - '0');
12683 } while (*++ap != '\0');
12684 umask(mask);
12685 } else {
12686 mask = ~mask & 0777;
12687 if (!bb_parse_mode(ap, &mask)) {
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +000012688 ash_msg_and_raise_error("illegal mode: %s", ap);
Eric Andersenc470f442003-07-28 09:56:35 +000012689 }
12690 umask(~mask & 0777);
12691 }
12692 }
12693 return 0;
12694}
12695
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012696static int FAST_FUNC
Denys Vlasenkof3c742f2010-03-06 20:12:00 +010012697ulimitcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersenc470f442003-07-28 09:56:35 +000012698{
Denys Vlasenkof3c742f2010-03-06 20:12:00 +010012699 return shell_builtin_ulimit(argv);
Eric Andersenc470f442003-07-28 09:56:35 +000012700}
12701
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012702/* ============ main() and helpers */
12703
12704/*
12705 * Called to exit the shell.
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012706 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012707static void exitshell(void) NORETURN;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012708static void
12709exitshell(void)
12710{
12711 struct jmploc loc;
12712 char *p;
12713 int status;
12714
12715 status = exitstatus;
12716 TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
12717 if (setjmp(loc.loc)) {
Denis Vlasenko7f88e342009-03-19 03:36:18 +000012718 if (exception_type == EXEXIT)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012719/* dash bug: it just does _exit(exitstatus) here
12720 * but we have to do setjobctl(0) first!
12721 * (bug is still not fixed in dash-0.5.3 - if you run dash
12722 * under Midnight Commander, on exit from dash MC is backgrounded) */
12723 status = exitstatus;
12724 goto out;
12725 }
12726 exception_handler = &loc;
12727 p = trap[0];
12728 if (p) {
12729 trap[0] = NULL;
12730 evalstring(p, 0);
Denys Vlasenko0800e3a2009-09-24 03:09:26 +020012731 free(p);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012732 }
12733 flush_stdout_stderr();
12734 out:
12735 setjobctl(0);
12736 _exit(status);
12737 /* NOTREACHED */
12738}
12739
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012740static void
12741init(void)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012742{
12743 /* from input.c: */
Denys Vlasenko82dd14a2010-05-17 10:10:01 +020012744 /* we will never free this */
12745 basepf.next_to_pgetc = basepf.buf = ckmalloc(IBUFSIZ);
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012746
12747 /* from trap.c: */
12748 signal(SIGCHLD, SIG_DFL);
Denys Vlasenko7a7b0342009-12-04 04:18:31 +010012749 /* bash re-enables SIGHUP which is SIG_IGNed on entry.
12750 * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
12751 */
12752 signal(SIGHUP, SIG_DFL);
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012753
12754 /* from var.c: */
12755 {
12756 char **envp;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012757 const char *p;
12758 struct stat st1, st2;
12759
12760 initvar();
12761 for (envp = environ; envp && *envp; envp++) {
12762 if (strchr(*envp, '=')) {
12763 setvareq(*envp, VEXPORT|VTEXTFIXED);
12764 }
12765 }
12766
Denys Vlasenko7bb346f2009-10-06 22:09:50 +020012767 setvar("PPID", utoa(getppid()), 0);
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012768
12769 p = lookupvar("PWD");
12770 if (p)
12771 if (*p != '/' || stat(p, &st1) || stat(".", &st2)
12772 || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino)
12773 p = '\0';
12774 setpwd(p, 0);
12775 }
12776}
12777
12778/*
12779 * Process the shell command line arguments.
12780 */
12781static void
Denis Vlasenko68404f12008-03-17 09:00:54 +000012782procargs(char **argv)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012783{
12784 int i;
12785 const char *xminusc;
12786 char **xargv;
12787
12788 xargv = argv;
12789 arg0 = xargv[0];
Denis Vlasenko68404f12008-03-17 09:00:54 +000012790 /* if (xargv[0]) - mmm, this is always true! */
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012791 xargv++;
12792 for (i = 0; i < NOPTS; i++)
12793 optlist[i] = 2;
12794 argptr = xargv;
Denis Vlasenko28bf6712008-02-14 15:01:47 +000012795 if (options(1)) {
12796 /* it already printed err message */
12797 raise_exception(EXERROR);
12798 }
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012799 xargv = argptr;
12800 xminusc = minusc;
12801 if (*xargv == NULL) {
12802 if (xminusc)
12803 ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
12804 sflag = 1;
12805 }
12806 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
12807 iflag = 1;
12808 if (mflag == 2)
12809 mflag = iflag;
12810 for (i = 0; i < NOPTS; i++)
12811 if (optlist[i] == 2)
12812 optlist[i] = 0;
12813#if DEBUG == 2
12814 debug = 1;
12815#endif
12816 /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
12817 if (xminusc) {
12818 minusc = *xargv++;
12819 if (*xargv)
12820 goto setarg0;
12821 } else if (!sflag) {
12822 setinputfile(*xargv, 0);
12823 setarg0:
12824 arg0 = *xargv++;
12825 commandname = arg0;
12826 }
12827
12828 shellparam.p = xargv;
12829#if ENABLE_ASH_GETOPTS
12830 shellparam.optind = 1;
12831 shellparam.optoff = -1;
12832#endif
Denis Vlasenko01631112007-12-16 17:20:38 +000012833 /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012834 while (*xargv) {
12835 shellparam.nparam++;
12836 xargv++;
12837 }
12838 optschanged();
12839}
12840
12841/*
12842 * Read /etc/profile or .profile.
12843 */
12844static void
12845read_profile(const char *name)
12846{
12847 int skip;
12848
12849 if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
12850 return;
12851 skip = cmdloop(0);
12852 popfile();
12853 if (skip)
12854 exitshell();
12855}
12856
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012857/*
12858 * This routine is called when an error or an interrupt occurs in an
12859 * interactive shell and control is returned to the main command loop.
12860 */
12861static void
12862reset(void)
12863{
12864 /* from eval.c: */
12865 evalskip = 0;
12866 loopnest = 0;
12867 /* from input.c: */
Denis Vlasenko41eb3002008-11-28 03:42:31 +000012868 g_parsefile->left_in_buffer = 0;
12869 g_parsefile->left_in_line = 0; /* clear input buffer */
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012870 popallfiles();
12871 /* from parser.c: */
12872 tokpushback = 0;
12873 checkkwd = 0;
12874 /* from redir.c: */
Denis Vlasenko34c73c42008-08-16 11:48:02 +000012875 clearredir(/*drop:*/ 0);
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012876}
12877
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012878#if PROFILE
12879static short profile_buf[16384];
12880extern int etext();
12881#endif
12882
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012883/*
12884 * Main routine. We initialize things, parse the arguments, execute
12885 * profiles if we're a login shell, and then call cmdloop to execute
12886 * commands. The setjmp call sets up the location to jump to when an
12887 * exception occurs. When an exception occurs the variable "state"
12888 * is used to figure out how far we had gotten.
12889 */
Denis Vlasenko9b49a5e2007-10-11 10:05:36 +000012890int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012891int ash_main(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012892{
Mike Frysinger98c52642009-04-02 10:02:37 +000012893 const char *shinit;
Denis Vlasenko4e12b1a2008-12-23 23:36:47 +000012894 volatile smallint state;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012895 struct jmploc jmploc;
12896 struct stackmark smark;
12897
Denis Vlasenko01631112007-12-16 17:20:38 +000012898 /* Initialize global data */
12899 INIT_G_misc();
12900 INIT_G_memstack();
12901 INIT_G_var();
Denis Vlasenkoee87ebf2007-12-21 22:18:16 +000012902#if ENABLE_ASH_ALIAS
Denis Vlasenko01631112007-12-16 17:20:38 +000012903 INIT_G_alias();
Denis Vlasenkoee87ebf2007-12-21 22:18:16 +000012904#endif
Denis Vlasenko01631112007-12-16 17:20:38 +000012905 INIT_G_cmdtable();
12906
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012907#if PROFILE
12908 monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
12909#endif
12910
12911#if ENABLE_FEATURE_EDITING
12912 line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
12913#endif
12914 state = 0;
12915 if (setjmp(jmploc.loc)) {
Denis Vlasenko7f88e342009-03-19 03:36:18 +000012916 smallint e;
Denis Vlasenko4e12b1a2008-12-23 23:36:47 +000012917 smallint s;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012918
12919 reset();
12920
Denis Vlasenko7f88e342009-03-19 03:36:18 +000012921 e = exception_type;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012922 if (e == EXERROR)
12923 exitstatus = 2;
12924 s = state;
12925 if (e == EXEXIT || s == 0 || iflag == 0 || shlvl)
12926 exitshell();
Denis Vlasenko7f88e342009-03-19 03:36:18 +000012927 if (e == EXINT)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012928 outcslow('\n', stderr);
Denis Vlasenko7f88e342009-03-19 03:36:18 +000012929
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012930 popstackmark(&smark);
12931 FORCE_INT_ON; /* enable interrupts */
12932 if (s == 1)
12933 goto state1;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000012934 if (s == 2)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012935 goto state2;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000012936 if (s == 3)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012937 goto state3;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000012938 goto state4;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012939 }
12940 exception_handler = &jmploc;
12941#if DEBUG
12942 opentrace();
Denis Vlasenko653d8e72009-03-19 21:59:35 +000012943 TRACE(("Shell args: "));
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000012944 trace_puts_args(argv);
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012945#endif
12946 rootpid = getpid();
12947
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012948 init();
12949 setstackmark(&smark);
Denis Vlasenko68404f12008-03-17 09:00:54 +000012950 procargs(argv);
12951
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012952#if ENABLE_FEATURE_EDITING_SAVEHISTORY
12953 if (iflag) {
12954 const char *hp = lookupvar("HISTFILE");
12955
12956 if (hp == NULL) {
12957 hp = lookupvar("HOME");
12958 if (hp != NULL) {
12959 char *defhp = concat_path_file(hp, ".ash_history");
12960 setvar("HISTFILE", defhp, 0);
12961 free(defhp);
12962 }
12963 }
12964 }
12965#endif
Denis Vlasenko4e12b1a2008-12-23 23:36:47 +000012966 if (/* argv[0] && */ argv[0][0] == '-')
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012967 isloginsh = 1;
12968 if (isloginsh) {
12969 state = 1;
12970 read_profile("/etc/profile");
12971 state1:
12972 state = 2;
12973 read_profile(".profile");
12974 }
12975 state2:
12976 state = 3;
12977 if (
12978#ifndef linux
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012979 getuid() == geteuid() && getgid() == getegid() &&
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012980#endif
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012981 iflag
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012982 ) {
12983 shinit = lookupvar("ENV");
12984 if (shinit != NULL && *shinit != '\0') {
12985 read_profile(shinit);
12986 }
12987 }
12988 state3:
12989 state = 4;
Denis Vlasenko5c2b8142009-03-19 01:59:59 +000012990 if (minusc) {
12991 /* evalstring pushes parsefile stack.
12992 * Ensure we don't falsely claim that 0 (stdin)
Denis Vlasenko5368ad52009-03-20 10:20:08 +000012993 * is one of stacked source fds.
12994 * Testcase: ash -c 'exec 1>&0' must not complain. */
Denys Vlasenko79b3d422010-06-03 04:29:08 +020012995 // if (!sflag) g_parsefile->pf_fd = -1;
Denys Vlasenko08d8b3c2010-06-03 04:28:28 +020012996 // ^^ not necessary since now we special-case fd 0
12997 // in is_hidden_fd() to not be considered "hidden fd"
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012998 evalstring(minusc, 0);
Denis Vlasenko5c2b8142009-03-19 01:59:59 +000012999 }
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013000
13001 if (sflag || minusc == NULL) {
Denys Vlasenko0337e032009-11-29 00:12:30 +010013002#if defined MAX_HISTORY && MAX_HISTORY > 0 && ENABLE_FEATURE_EDITING_SAVEHISTORY
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +000013003 if (iflag) {
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013004 const char *hp = lookupvar("HISTFILE");
Denis Vlasenko5c2b8142009-03-19 01:59:59 +000013005 if (hp)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013006 line_input_state->hist_file = hp;
13007 }
13008#endif
13009 state4: /* XXX ??? - why isn't this before the "if" statement */
13010 cmdloop(1);
13011 }
13012#if PROFILE
13013 monitor(0);
13014#endif
13015#ifdef GPROF
13016 {
13017 extern void _mcleanup(void);
13018 _mcleanup();
13019 }
13020#endif
13021 exitshell();
13022 /* NOTREACHED */
13023}
13024
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013025
Eric Andersendf82f612001-06-28 07:46:40 +000013026/*-
13027 * Copyright (c) 1989, 1991, 1993, 1994
Eric Andersen2870d962001-07-02 17:27:21 +000013028 * The Regents of the University of California. All rights reserved.
Eric Andersendf82f612001-06-28 07:46:40 +000013029 *
13030 * This code is derived from software contributed to Berkeley by
13031 * Kenneth Almquist.
13032 *
13033 * Redistribution and use in source and binary forms, with or without
13034 * modification, are permitted provided that the following conditions
13035 * are met:
13036 * 1. Redistributions of source code must retain the above copyright
13037 * notice, this list of conditions and the following disclaimer.
13038 * 2. Redistributions in binary form must reproduce the above copyright
13039 * notice, this list of conditions and the following disclaimer in the
13040 * documentation and/or other materials provided with the distribution.
"Vladimir N. Oleynik"ddc280e2005-12-15 12:01:49 +000013041 * 3. Neither the name of the University nor the names of its contributors
Eric Andersendf82f612001-06-28 07:46:40 +000013042 * may be used to endorse or promote products derived from this software
13043 * without specific prior written permission.
13044 *
13045 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
13046 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
13047 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
13048 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
13049 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
13050 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
13051 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
13052 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
13053 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
13054 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
13055 * SUCH DAMAGE.
13056 */