blob: d81dbd3f5c1985de192cd48c69721a80d01e353e [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 *
5 * Copyright (c) 1989, 1991, 1993, 1994
Eric Andersen2870d962001-07-02 17:27:21 +00006 * The Regents of the University of California. All rights reserved.
Eric Andersencb57d552001-06-28 07:25:16 +00007 *
"Vladimir N. Oleynik"ddc280e2005-12-15 12:01:49 +00008 * Copyright (c) 1997-2005 Herbert Xu <herbert@gondor.apana.org.au>
Eric Andersen81fe1232003-07-29 06:38:40 +00009 * was re-ported from NetBSD and debianized.
10 *
Eric Andersencb57d552001-06-28 07:25:16 +000011 * This code is derived from software contributed to Berkeley by
12 * Kenneth Almquist.
13 *
Bernhard Reutner-Fischer86f5c992006-01-22 22:55:11 +000014 * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
Eric Andersendf82f612001-06-28 07:46:40 +000015 *
Eric Andersen81fe1232003-07-29 06:38:40 +000016 * Original BSD copyright notice is retained at the end of this file.
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
37#define IFS_BROKEN
38
39#define JOBS ENABLE_ASH_JOB_CONTROL
Eric Andersenc470f442003-07-28 09:56:35 +000040
Denis Vlasenkob012b102007-02-19 22:43:01 +000041#if DEBUG
Denis Vlasenko653d8e72009-03-19 21:59:35 +000042# ifndef _GNU_SOURCE
43# define _GNU_SOURCE
44# endif
Denis Vlasenkoe26b2782008-02-12 07:40:29 +000045#endif
Denis Vlasenko0e6f6612008-02-15 15:02:15 +000046
Denis Vlasenko1aa7e472007-11-28 06:49:03 +000047#include "busybox.h" /* for applet_names */
Denis Vlasenko61befda2008-11-25 01:36:03 +000048//TODO: pull in some .h and find out do we have SINGLE_APPLET_MAIN?
49//#include "applet_tables.h" doesn't work
Denis Vlasenkob012b102007-02-19 22:43:01 +000050#include <paths.h>
51#include <setjmp.h>
52#include <fnmatch.h>
Mike Frysinger98c52642009-04-02 10:02:37 +000053#include "math.h"
Denys Vlasenko3ea2e822009-10-09 20:59:04 +020054#if ENABLE_ASH_RANDOM_SUPPORT
55# include "random.h"
56#endif
Denis Vlasenko61befda2008-11-25 01:36:03 +000057
58#if defined SINGLE_APPLET_MAIN
59/* STANDALONE does not make sense, and won't compile */
Denys Vlasenko3ea2e822009-10-09 20:59:04 +020060# undef CONFIG_FEATURE_SH_STANDALONE
61# undef ENABLE_FEATURE_SH_STANDALONE
62# undef IF_FEATURE_SH_STANDALONE
63# undef IF_NOT_FEATURE_SH_STANDALONE(...)
64# define ENABLE_FEATURE_SH_STANDALONE 0
65# define IF_FEATURE_SH_STANDALONE(...)
66# define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
Eric Andersencb57d552001-06-28 07:25:16 +000067#endif
68
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000069#ifndef PIPE_BUF
Denis Vlasenko653d8e72009-03-19 21:59:35 +000070# define PIPE_BUF 4096 /* amount of buffering in a pipe */
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000071#endif
72
Denis Vlasenkob012b102007-02-19 22:43:01 +000073#if defined(__uClinux__)
Denis Vlasenko653d8e72009-03-19 21:59:35 +000074# error "Do not even bother, ash will not run on NOMMU machine"
Denis Vlasenkob012b102007-02-19 22:43:01 +000075#endif
76
Denis Vlasenkob012b102007-02-19 22:43:01 +000077
Denis Vlasenko01631112007-12-16 17:20:38 +000078/* ============ Hash table sizes. Configurable. */
79
80#define VTABSIZE 39
81#define ATABSIZE 39
82#define CMDTABLESIZE 31 /* should be prime */
83
84
Denis Vlasenkob012b102007-02-19 22:43:01 +000085/* ============ Shell options */
86
87static const char *const optletters_optnames[] = {
88 "e" "errexit",
89 "f" "noglob",
90 "I" "ignoreeof",
91 "i" "interactive",
92 "m" "monitor",
93 "n" "noexec",
94 "s" "stdin",
95 "x" "xtrace",
96 "v" "verbose",
97 "C" "noclobber",
98 "a" "allexport",
99 "b" "notify",
100 "u" "nounset",
Denis Vlasenko6ca409e2007-08-12 20:58:27 +0000101 "\0" "vi"
Denis Vlasenkob012b102007-02-19 22:43:01 +0000102#if DEBUG
Denis Vlasenko6ca409e2007-08-12 20:58:27 +0000103 ,"\0" "nolog"
104 ,"\0" "debug"
Denis Vlasenkob012b102007-02-19 22:43:01 +0000105#endif
106};
107
108#define optletters(n) optletters_optnames[(n)][0]
109#define optnames(n) (&optletters_optnames[(n)][1])
110
Denis Vlasenko80b8b392007-06-25 10:55:35 +0000111enum { NOPTS = ARRAY_SIZE(optletters_optnames) };
Denis Vlasenkob012b102007-02-19 22:43:01 +0000112
Eric Andersenc470f442003-07-28 09:56:35 +0000113
Denis Vlasenkob012b102007-02-19 22:43:01 +0000114/* ============ Misc data */
Eric Andersenc470f442003-07-28 09:56:35 +0000115
Denis Vlasenko6ca409e2007-08-12 20:58:27 +0000116static const char homestr[] ALIGN1 = "HOME";
117static const char snlfmt[] ALIGN1 = "%s\n";
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200118static const char msg_illnum[] ALIGN1 = "Illegal number: %s";
Denis Vlasenkoaa744452007-02-23 01:04:22 +0000119
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +0000120/*
Eric Andersenc470f442003-07-28 09:56:35 +0000121 * We enclose jmp_buf in a structure so that we can declare pointers to
122 * jump locations. The global variable handler contains the location to
Denis Vlasenkof1733952009-03-19 23:21:55 +0000123 * jump to when an exception occurs, and the global variable exception_type
Eric Andersenaff114c2004-04-14 17:51:38 +0000124 * contains a code identifying the exception. To implement nested
Eric Andersenc470f442003-07-28 09:56:35 +0000125 * exception handlers, the user should save the value of handler on entry
126 * to an inner scope, set handler to point to a jmploc structure for the
127 * inner scope, and restore handler on exit from the scope.
128 */
Eric Andersenc470f442003-07-28 09:56:35 +0000129struct jmploc {
130 jmp_buf loc;
131};
Denis Vlasenko01631112007-12-16 17:20:38 +0000132
133struct globals_misc {
134 /* pid of main shell */
135 int rootpid;
136 /* shell level: 0 for the main shell, 1 for its children, and so on */
137 int shlvl;
138#define rootshell (!shlvl)
139 char *minusc; /* argument to -c option */
140
141 char *curdir; // = nullstr; /* current working directory */
142 char *physdir; // = nullstr; /* physical working directory */
143
144 char *arg0; /* value of $0 */
145
146 struct jmploc *exception_handler;
Denis Vlasenko991a1da2008-02-10 19:02:53 +0000147
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200148 volatile int suppress_int; /* counter */
149 volatile /*sig_atomic_t*/ smallint pending_int; /* 1 = got SIGINT */
Denis Vlasenko991a1da2008-02-10 19:02:53 +0000150 /* last pending signal */
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200151 volatile /*sig_atomic_t*/ smallint pending_sig;
Denis Vlasenko7f88e342009-03-19 03:36:18 +0000152 smallint exception_type; /* kind of exception (0..5) */
Denis Vlasenko01631112007-12-16 17:20:38 +0000153 /* exceptions */
Eric Andersenc470f442003-07-28 09:56:35 +0000154#define EXINT 0 /* SIGINT received */
155#define EXERROR 1 /* a generic error */
156#define EXSHELLPROC 2 /* execute a shell procedure */
157#define EXEXEC 3 /* command execution failed */
158#define EXEXIT 4 /* exit the shell */
159#define EXSIG 5 /* trapped signal in wait(1) */
Eric Andersen2870d962001-07-02 17:27:21 +0000160
Denis Vlasenko01631112007-12-16 17:20:38 +0000161 smallint isloginsh;
Denis Vlasenkob07a4962008-06-22 13:16:23 +0000162 char nullstr[1]; /* zero length string */
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000163
164 char optlist[NOPTS];
165#define eflag optlist[0]
166#define fflag optlist[1]
167#define Iflag optlist[2]
168#define iflag optlist[3]
169#define mflag optlist[4]
170#define nflag optlist[5]
171#define sflag optlist[6]
172#define xflag optlist[7]
173#define vflag optlist[8]
174#define Cflag optlist[9]
175#define aflag optlist[10]
176#define bflag optlist[11]
177#define uflag optlist[12]
178#define viflag optlist[13]
179#if DEBUG
180#define nolog optlist[14]
181#define debug optlist[15]
182#endif
183
184 /* trap handler commands */
Denis Vlasenko01631112007-12-16 17:20:38 +0000185 /*
186 * Sigmode records the current value of the signal handlers for the various
187 * modes. A value of zero means that the current handler is not known.
Denis Vlasenkof8535cc2008-12-03 10:36:26 +0000188 * S_HARD_IGN indicates that the signal was ignored on entry to the shell.
Denis Vlasenko01631112007-12-16 17:20:38 +0000189 */
190 char sigmode[NSIG - 1];
Denis Vlasenkof8535cc2008-12-03 10:36:26 +0000191#define S_DFL 1 /* default signal handling (SIG_DFL) */
192#define S_CATCH 2 /* signal is caught */
193#define S_IGN 3 /* signal is ignored (SIG_IGN) */
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +0000194#define S_HARD_IGN 4 /* signal is ignored permenantly */
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +0000195
Denis Vlasenko01631112007-12-16 17:20:38 +0000196 /* indicates specified signal received */
Denis Vlasenko4b875702009-03-19 13:30:04 +0000197 uint8_t gotsig[NSIG - 1]; /* offset by 1: "signal" 0 is meaningless */
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000198 char *trap[NSIG];
Denys Vlasenko21d87d42009-09-25 00:06:51 +0200199 char **trap_ptr; /* used only by "trap hack" */
Denis Vlasenko448d30e2008-06-27 00:24:11 +0000200
201 /* Rarely referenced stuff */
202#if ENABLE_ASH_RANDOM_SUPPORT
Denys Vlasenko3ea2e822009-10-09 20:59:04 +0200203 random_t random_gen;
Denis Vlasenko448d30e2008-06-27 00:24:11 +0000204#endif
205 pid_t backgndpid; /* pid of last background process */
206 smallint job_warning; /* user was warned about stopped jobs (can be 2, 1 or 0). */
Denis Vlasenko01631112007-12-16 17:20:38 +0000207};
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000208extern struct globals_misc *const ash_ptr_to_globals_misc;
209#define G_misc (*ash_ptr_to_globals_misc)
Denis Vlasenko26bc57d2008-06-27 00:29:34 +0000210#define rootpid (G_misc.rootpid )
211#define shlvl (G_misc.shlvl )
212#define minusc (G_misc.minusc )
213#define curdir (G_misc.curdir )
214#define physdir (G_misc.physdir )
215#define arg0 (G_misc.arg0 )
Denis Vlasenko01631112007-12-16 17:20:38 +0000216#define exception_handler (G_misc.exception_handler)
Denis Vlasenko7f88e342009-03-19 03:36:18 +0000217#define exception_type (G_misc.exception_type )
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200218#define suppress_int (G_misc.suppress_int )
219#define pending_int (G_misc.pending_int )
220#define pending_sig (G_misc.pending_sig )
Denis Vlasenko26bc57d2008-06-27 00:29:34 +0000221#define isloginsh (G_misc.isloginsh )
222#define nullstr (G_misc.nullstr )
223#define optlist (G_misc.optlist )
224#define sigmode (G_misc.sigmode )
225#define gotsig (G_misc.gotsig )
226#define trap (G_misc.trap )
Denys Vlasenko21d87d42009-09-25 00:06:51 +0200227#define trap_ptr (G_misc.trap_ptr )
Denys Vlasenko3ea2e822009-10-09 20:59:04 +0200228#define random_gen (G_misc.random_gen )
Denis Vlasenko448d30e2008-06-27 00:24:11 +0000229#define backgndpid (G_misc.backgndpid )
230#define job_warning (G_misc.job_warning)
Denis Vlasenko01631112007-12-16 17:20:38 +0000231#define INIT_G_misc() do { \
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000232 (*(struct globals_misc**)&ash_ptr_to_globals_misc) = xzalloc(sizeof(G_misc)); \
233 barrier(); \
Denis Vlasenko01631112007-12-16 17:20:38 +0000234 curdir = nullstr; \
235 physdir = nullstr; \
Denys Vlasenko21d87d42009-09-25 00:06:51 +0200236 trap_ptr = trap; \
Denis Vlasenko01631112007-12-16 17:20:38 +0000237} while (0)
238
239
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000240/* ============ DEBUG */
241#if DEBUG
242static void trace_printf(const char *fmt, ...);
243static void trace_vprintf(const char *fmt, va_list va);
244# define TRACE(param) trace_printf param
245# define TRACEV(param) trace_vprintf param
Denis Vlasenko1bb3d7e2009-03-20 07:45:36 +0000246# define close(fd) do { \
247 int dfd = (fd); \
Denis Vlasenkob9e70dd2009-03-20 01:24:08 +0000248 if (close(dfd) < 0) \
Denys Vlasenko883cea42009-07-11 15:31:59 +0200249 bb_error_msg("bug on %d: closing %d(0x%x)", \
Denis Vlasenko1bb3d7e2009-03-20 07:45:36 +0000250 __LINE__, dfd, dfd); \
Denis Vlasenkob9e70dd2009-03-20 01:24:08 +0000251} while (0)
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000252#else
253# define TRACE(param)
254# define TRACEV(param)
255#endif
256
257
Denis Vlasenko559691a2008-10-05 18:39:31 +0000258/* ============ Utility functions */
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000259#define xbarrier() do { __asm__ __volatile__ ("": : :"memory"); } while (0)
260
Denys Vlasenko7cee00e2009-07-24 01:08:03 +0200261/* C99 says: "char" declaration may be signed or unsigned by default */
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000262#define signed_char2int(sc) ((int)(signed char)(sc))
263
Denis Vlasenko559691a2008-10-05 18:39:31 +0000264static int isdigit_str9(const char *str)
265{
266 int maxlen = 9 + 1; /* max 9 digits: 999999999 */
267 while (--maxlen && isdigit(*str))
268 str++;
269 return (*str == '\0');
270}
Denis Vlasenko01631112007-12-16 17:20:38 +0000271
Denis Vlasenko559691a2008-10-05 18:39:31 +0000272
273/* ============ Interrupts / exceptions */
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +0000274/*
Eric Andersen2870d962001-07-02 17:27:21 +0000275 * These macros allow the user to suspend the handling of interrupt signals
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +0000276 * over a period of time. This is similar to SIGHOLD or to sigblock, but
Eric Andersen2870d962001-07-02 17:27:21 +0000277 * much more efficient and portable. (But hacking the kernel is so much
278 * more fun than worrying about efficiency and portability. :-))
279 */
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000280#define INT_OFF do { \
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200281 suppress_int++; \
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000282 xbarrier(); \
283} while (0)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000284
285/*
286 * Called to raise an exception. Since C doesn't include exceptions, we
287 * just do a longjmp to the exception handler. The type of exception is
Denis Vlasenko4b875702009-03-19 13:30:04 +0000288 * stored in the global variable "exception_type".
Denis Vlasenkob012b102007-02-19 22:43:01 +0000289 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +0000290static void raise_exception(int) NORETURN;
Denis Vlasenkob012b102007-02-19 22:43:01 +0000291static void
292raise_exception(int e)
293{
294#if DEBUG
Denis Vlasenko2da584f2007-02-19 22:44:05 +0000295 if (exception_handler == NULL)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000296 abort();
297#endif
298 INT_OFF;
Denis Vlasenko7f88e342009-03-19 03:36:18 +0000299 exception_type = e;
Denis Vlasenko2da584f2007-02-19 22:44:05 +0000300 longjmp(exception_handler->loc, 1);
Denis Vlasenkob012b102007-02-19 22:43:01 +0000301}
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000302#if DEBUG
303#define raise_exception(e) do { \
304 TRACE(("raising exception %d on line %d\n", (e), __LINE__)); \
305 raise_exception(e); \
306} while (0)
307#endif
Denis Vlasenkob012b102007-02-19 22:43:01 +0000308
309/*
310 * Called from trap.c when a SIGINT is received. (If the user specifies
311 * that SIGINT is to be trapped or ignored using the trap builtin, then
312 * this routine is not called.) Suppressint is nonzero when interrupts
313 * are held using the INT_OFF macro. (The test for iflag is just
314 * defensive programming.)
315 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +0000316static void raise_interrupt(void) NORETURN;
Denis Vlasenkob012b102007-02-19 22:43:01 +0000317static void
318raise_interrupt(void)
319{
Denis Vlasenko4b875702009-03-19 13:30:04 +0000320 int ex_type;
Denis Vlasenkob012b102007-02-19 22:43:01 +0000321
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200322 pending_int = 0;
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +0000323 /* Signal is not automatically unmasked after it is raised,
324 * do it ourself - unmask all signals */
Denis Vlasenko3f165fa2008-03-17 08:29:08 +0000325 sigprocmask_allsigs(SIG_UNBLOCK);
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200326 /* pending_sig = 0; - now done in onsig() */
Denis Vlasenko7c139b42007-03-21 20:17:27 +0000327
Denis Vlasenko4b875702009-03-19 13:30:04 +0000328 ex_type = EXSIG;
Denis Vlasenkob012b102007-02-19 22:43:01 +0000329 if (gotsig[SIGINT - 1] && !trap[SIGINT]) {
330 if (!(rootshell && iflag)) {
Denis Vlasenko991a1da2008-02-10 19:02:53 +0000331 /* Kill ourself with SIGINT */
Denis Vlasenkob012b102007-02-19 22:43:01 +0000332 signal(SIGINT, SIG_DFL);
333 raise(SIGINT);
334 }
Denis Vlasenko4b875702009-03-19 13:30:04 +0000335 ex_type = EXINT;
Denis Vlasenkob012b102007-02-19 22:43:01 +0000336 }
Denis Vlasenko4b875702009-03-19 13:30:04 +0000337 raise_exception(ex_type);
Denis Vlasenkob012b102007-02-19 22:43:01 +0000338 /* NOTREACHED */
339}
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000340#if DEBUG
341#define raise_interrupt() do { \
342 TRACE(("raising interrupt on line %d\n", __LINE__)); \
343 raise_interrupt(); \
344} while (0)
345#endif
Denis Vlasenkob012b102007-02-19 22:43:01 +0000346
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000347static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000348int_on(void)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000349{
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +0000350 xbarrier();
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200351 if (--suppress_int == 0 && pending_int) {
Denis Vlasenkob012b102007-02-19 22:43:01 +0000352 raise_interrupt();
353 }
354}
355#define INT_ON int_on()
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000356static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000357force_int_on(void)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000358{
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +0000359 xbarrier();
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200360 suppress_int = 0;
361 if (pending_int)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000362 raise_interrupt();
363}
364#define FORCE_INT_ON force_int_on()
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000365
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200366#define SAVE_INT(v) ((v) = suppress_int)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000367
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000368#define RESTORE_INT(v) do { \
369 xbarrier(); \
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200370 suppress_int = (v); \
371 if (suppress_int == 0 && pending_int) \
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000372 raise_interrupt(); \
373} while (0)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000374
Glenn L McGrath9fef17d2002-08-22 18:41:20 +0000375
Denis Vlasenkobc54cff2007-02-23 01:05:52 +0000376/* ============ Stdout/stderr output */
Eric Andersenc470f442003-07-28 09:56:35 +0000377
Eric Andersenc470f442003-07-28 09:56:35 +0000378static void
Denis Vlasenkob012b102007-02-19 22:43:01 +0000379outstr(const char *p, FILE *file)
Denis Vlasenkoe5570da2007-02-19 22:41:55 +0000380{
Denis Vlasenkob012b102007-02-19 22:43:01 +0000381 INT_OFF;
382 fputs(p, file);
383 INT_ON;
384}
385
386static void
387flush_stdout_stderr(void)
388{
389 INT_OFF;
390 fflush(stdout);
391 fflush(stderr);
392 INT_ON;
393}
394
395static void
396flush_stderr(void)
397{
398 INT_OFF;
399 fflush(stderr);
400 INT_ON;
401}
402
403static void
404outcslow(int c, FILE *dest)
405{
406 INT_OFF;
407 putc(c, dest);
408 fflush(dest);
409 INT_ON;
410}
411
412static int out1fmt(const char *, ...) __attribute__((__format__(__printf__,1,2)));
413static int
414out1fmt(const char *fmt, ...)
415{
416 va_list ap;
417 int r;
418
419 INT_OFF;
420 va_start(ap, fmt);
421 r = vprintf(fmt, ap);
422 va_end(ap);
423 INT_ON;
424 return r;
425}
426
427static int fmtstr(char *, size_t, const char *, ...) __attribute__((__format__(__printf__,3,4)));
428static int
429fmtstr(char *outbuf, size_t length, const char *fmt, ...)
430{
431 va_list ap;
432 int ret;
433
434 va_start(ap, fmt);
435 INT_OFF;
436 ret = vsnprintf(outbuf, length, fmt, ap);
437 va_end(ap);
438 INT_ON;
439 return ret;
440}
441
442static void
443out1str(const char *p)
444{
445 outstr(p, stdout);
446}
447
448static void
449out2str(const char *p)
450{
451 outstr(p, stderr);
452 flush_stderr();
453}
454
455
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +0000456/* ============ Parser structures */
Denis Vlasenko4d2183b2007-02-23 01:05:38 +0000457
Denis Vlasenko5651bfc2007-02-23 21:08:58 +0000458/* control characters in argument strings */
Denys Vlasenkob6c84342009-08-29 20:23:20 +0200459#define CTLESC ((unsigned char)'\201') /* escape next character */
460#define CTLVAR ((unsigned char)'\202') /* variable defn */
461#define CTLENDVAR ((unsigned char)'\203')
462#define CTLBACKQ ((unsigned char)'\204')
Denis Vlasenko5651bfc2007-02-23 21:08:58 +0000463#define CTLQUOTE 01 /* ored with CTLBACKQ code if in quotes */
464/* CTLBACKQ | CTLQUOTE == '\205' */
Denys Vlasenkob6c84342009-08-29 20:23:20 +0200465#define CTLARI ((unsigned char)'\206') /* arithmetic expression */
466#define CTLENDARI ((unsigned char)'\207')
467#define CTLQUOTEMARK ((unsigned char)'\210')
Denis Vlasenko5651bfc2007-02-23 21:08:58 +0000468
469/* variable substitution byte (follows CTLVAR) */
470#define VSTYPE 0x0f /* type of variable substitution */
471#define VSNUL 0x10 /* colon--treat the empty string as unset */
472#define VSQUOTE 0x80 /* inside double quotes--suppress splitting */
473
474/* values of VSTYPE field */
Denis Vlasenko92e13c22008-03-25 01:17:40 +0000475#define VSNORMAL 0x1 /* normal variable: $var or ${var} */
476#define VSMINUS 0x2 /* ${var-text} */
477#define VSPLUS 0x3 /* ${var+text} */
478#define VSQUESTION 0x4 /* ${var?message} */
479#define VSASSIGN 0x5 /* ${var=text} */
480#define VSTRIMRIGHT 0x6 /* ${var%pattern} */
481#define VSTRIMRIGHTMAX 0x7 /* ${var%%pattern} */
482#define VSTRIMLEFT 0x8 /* ${var#pattern} */
483#define VSTRIMLEFTMAX 0x9 /* ${var##pattern} */
484#define VSLENGTH 0xa /* ${#var} */
485#if ENABLE_ASH_BASH_COMPAT
486#define VSSUBSTR 0xc /* ${var:position:length} */
487#define VSREPLACE 0xd /* ${var/pattern/replacement} */
488#define VSREPLACEALL 0xe /* ${var//pattern/replacement} */
489#endif
Denis Vlasenko5651bfc2007-02-23 21:08:58 +0000490
Denis Vlasenko6ca409e2007-08-12 20:58:27 +0000491static const char dolatstr[] ALIGN1 = {
492 CTLVAR, VSNORMAL|VSQUOTE, '@', '=', '\0'
493};
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +0000494
Denis Vlasenko559691a2008-10-05 18:39:31 +0000495#define NCMD 0
496#define NPIPE 1
497#define NREDIR 2
498#define NBACKGND 3
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000499#define NSUBSHELL 4
Denis Vlasenko559691a2008-10-05 18:39:31 +0000500#define NAND 5
501#define NOR 6
502#define NSEMI 7
503#define NIF 8
504#define NWHILE 9
505#define NUNTIL 10
506#define NFOR 11
507#define NCASE 12
508#define NCLIST 13
509#define NDEFUN 14
510#define NARG 15
511#define NTO 16
512#if ENABLE_ASH_BASH_COMPAT
513#define NTO2 17
514#endif
515#define NCLOBBER 18
516#define NFROM 19
517#define NFROMTO 20
518#define NAPPEND 21
519#define NTOFD 22
520#define NFROMFD 23
521#define NHERE 24
522#define NXHERE 25
523#define NNOT 26
Denis Vlasenko340299a2008-11-21 10:36:36 +0000524#define N_NUMBER 27
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000525
526union node;
527
528struct ncmd {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000529 smallint type; /* Nxxxx */
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000530 union node *assign;
531 union node *args;
532 union node *redirect;
533};
534
535struct npipe {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000536 smallint type;
537 smallint pipe_backgnd;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000538 struct nodelist *cmdlist;
539};
540
541struct nredir {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000542 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000543 union node *n;
544 union node *redirect;
545};
546
547struct nbinary {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000548 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000549 union node *ch1;
550 union node *ch2;
551};
552
553struct nif {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000554 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000555 union node *test;
556 union node *ifpart;
557 union node *elsepart;
558};
559
560struct nfor {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000561 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000562 union node *args;
563 union node *body;
564 char *var;
565};
566
567struct ncase {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000568 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000569 union node *expr;
570 union node *cases;
571};
572
573struct nclist {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000574 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000575 union node *next;
576 union node *pattern;
577 union node *body;
578};
579
580struct narg {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000581 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000582 union node *next;
583 char *text;
584 struct nodelist *backquote;
585};
586
Denis Vlasenko559691a2008-10-05 18:39:31 +0000587/* nfile and ndup layout must match!
588 * NTOFD (>&fdnum) uses ndup structure, but we may discover mid-flight
589 * that it is actually NTO2 (>&file), and change its type.
590 */
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000591struct nfile {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000592 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000593 union node *next;
594 int fd;
Denis Vlasenko559691a2008-10-05 18:39:31 +0000595 int _unused_dupfd;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000596 union node *fname;
597 char *expfname;
598};
599
600struct ndup {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000601 smallint type;
Denis Vlasenko559691a2008-10-05 18:39:31 +0000602 union node *next;
603 int fd;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000604 int dupfd;
605 union node *vname;
Denis Vlasenko559691a2008-10-05 18:39:31 +0000606 char *_unused_expfname;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000607};
608
609struct nhere {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000610 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000611 union node *next;
612 int fd;
613 union node *doc;
614};
615
616struct nnot {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000617 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000618 union node *com;
619};
620
621union node {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000622 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000623 struct ncmd ncmd;
624 struct npipe npipe;
625 struct nredir nredir;
626 struct nbinary nbinary;
627 struct nif nif;
628 struct nfor nfor;
629 struct ncase ncase;
630 struct nclist nclist;
631 struct narg narg;
632 struct nfile nfile;
633 struct ndup ndup;
634 struct nhere nhere;
635 struct nnot nnot;
636};
637
Denys Vlasenko86e83ec2009-07-23 22:07:07 +0200638/*
639 * NODE_EOF is returned by parsecmd when it encounters an end of file.
640 * It must be distinct from NULL.
641 */
642#define NODE_EOF ((union node *) -1L)
643
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000644struct nodelist {
645 struct nodelist *next;
646 union node *n;
647};
648
649struct funcnode {
650 int count;
651 union node n;
652};
653
Denis Vlasenko5651bfc2007-02-23 21:08:58 +0000654/*
655 * Free a parse tree.
656 */
657static void
658freefunc(struct funcnode *f)
659{
660 if (f && --f->count < 0)
661 free(f);
662}
663
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000664
665/* ============ Debugging output */
666
667#if DEBUG
668
669static FILE *tracefile;
670
671static void
672trace_printf(const char *fmt, ...)
673{
674 va_list va;
675
676 if (debug != 1)
677 return;
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000678 if (DEBUG_TIME)
679 fprintf(tracefile, "%u ", (int) time(NULL));
680 if (DEBUG_PID)
681 fprintf(tracefile, "[%u] ", (int) getpid());
682 if (DEBUG_SIG)
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200683 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000684 va_start(va, fmt);
685 vfprintf(tracefile, fmt, va);
686 va_end(va);
687}
688
689static void
690trace_vprintf(const char *fmt, va_list va)
691{
692 if (debug != 1)
693 return;
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000694 if (DEBUG_TIME)
695 fprintf(tracefile, "%u ", (int) time(NULL));
696 if (DEBUG_PID)
697 fprintf(tracefile, "[%u] ", (int) getpid());
698 if (DEBUG_SIG)
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200699 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000700 vfprintf(tracefile, fmt, va);
701}
702
703static void
704trace_puts(const char *s)
705{
706 if (debug != 1)
707 return;
708 fputs(s, tracefile);
709}
710
711static void
712trace_puts_quoted(char *s)
713{
714 char *p;
715 char c;
716
717 if (debug != 1)
718 return;
719 putc('"', tracefile);
720 for (p = s; *p; p++) {
721 switch (*p) {
722 case '\n': c = 'n'; goto backslash;
723 case '\t': c = 't'; goto backslash;
724 case '\r': c = 'r'; goto backslash;
725 case '"': c = '"'; goto backslash;
726 case '\\': c = '\\'; goto backslash;
727 case CTLESC: c = 'e'; goto backslash;
728 case CTLVAR: c = 'v'; goto backslash;
729 case CTLVAR+CTLQUOTE: c = 'V'; goto backslash;
730 case CTLBACKQ: c = 'q'; goto backslash;
731 case CTLBACKQ+CTLQUOTE: c = 'Q'; goto backslash;
732 backslash:
733 putc('\\', tracefile);
734 putc(c, tracefile);
735 break;
736 default:
737 if (*p >= ' ' && *p <= '~')
738 putc(*p, tracefile);
739 else {
740 putc('\\', tracefile);
741 putc(*p >> 6 & 03, tracefile);
742 putc(*p >> 3 & 07, tracefile);
743 putc(*p & 07, tracefile);
744 }
745 break;
746 }
747 }
748 putc('"', tracefile);
749}
750
751static void
752trace_puts_args(char **ap)
753{
754 if (debug != 1)
755 return;
756 if (!*ap)
757 return;
758 while (1) {
759 trace_puts_quoted(*ap);
760 if (!*++ap) {
761 putc('\n', tracefile);
762 break;
763 }
764 putc(' ', tracefile);
765 }
766}
767
768static void
769opentrace(void)
770{
771 char s[100];
772#ifdef O_APPEND
773 int flags;
774#endif
775
776 if (debug != 1) {
777 if (tracefile)
778 fflush(tracefile);
779 /* leave open because libedit might be using it */
780 return;
781 }
782 strcpy(s, "./trace");
783 if (tracefile) {
784 if (!freopen(s, "a", tracefile)) {
785 fprintf(stderr, "Can't re-open %s\n", s);
786 debug = 0;
787 return;
788 }
789 } else {
790 tracefile = fopen(s, "a");
791 if (tracefile == NULL) {
792 fprintf(stderr, "Can't open %s\n", s);
793 debug = 0;
794 return;
795 }
796 }
797#ifdef O_APPEND
Denis Vlasenkod37f2222007-08-19 13:42:08 +0000798 flags = fcntl(fileno(tracefile), F_GETFL);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000799 if (flags >= 0)
800 fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
801#endif
802 setlinebuf(tracefile);
803 fputs("\nTracing started.\n", tracefile);
804}
805
806static void
807indent(int amount, char *pfx, FILE *fp)
808{
809 int i;
810
811 for (i = 0; i < amount; i++) {
812 if (pfx && i == amount - 1)
813 fputs(pfx, fp);
814 putc('\t', fp);
815 }
816}
817
818/* little circular references here... */
819static void shtree(union node *n, int ind, char *pfx, FILE *fp);
820
821static void
822sharg(union node *arg, FILE *fp)
823{
824 char *p;
825 struct nodelist *bqlist;
826 int subtype;
827
828 if (arg->type != NARG) {
829 out1fmt("<node type %d>\n", arg->type);
830 abort();
831 }
832 bqlist = arg->narg.backquote;
833 for (p = arg->narg.text; *p; p++) {
834 switch (*p) {
835 case CTLESC:
836 putc(*++p, fp);
837 break;
838 case CTLVAR:
839 putc('$', fp);
840 putc('{', fp);
841 subtype = *++p;
842 if (subtype == VSLENGTH)
843 putc('#', fp);
844
845 while (*p != '=')
846 putc(*p++, fp);
847
848 if (subtype & VSNUL)
849 putc(':', fp);
850
851 switch (subtype & VSTYPE) {
852 case VSNORMAL:
853 putc('}', fp);
854 break;
855 case VSMINUS:
856 putc('-', fp);
857 break;
858 case VSPLUS:
859 putc('+', fp);
860 break;
861 case VSQUESTION:
862 putc('?', fp);
863 break;
864 case VSASSIGN:
865 putc('=', fp);
866 break;
867 case VSTRIMLEFT:
868 putc('#', fp);
869 break;
870 case VSTRIMLEFTMAX:
871 putc('#', fp);
872 putc('#', fp);
873 break;
874 case VSTRIMRIGHT:
875 putc('%', fp);
876 break;
877 case VSTRIMRIGHTMAX:
878 putc('%', fp);
879 putc('%', fp);
880 break;
881 case VSLENGTH:
882 break;
883 default:
884 out1fmt("<subtype %d>", subtype);
885 }
886 break;
887 case CTLENDVAR:
888 putc('}', fp);
889 break;
890 case CTLBACKQ:
891 case CTLBACKQ|CTLQUOTE:
892 putc('$', fp);
893 putc('(', fp);
894 shtree(bqlist->n, -1, NULL, fp);
895 putc(')', fp);
896 break;
897 default:
898 putc(*p, fp);
899 break;
900 }
901 }
902}
903
Denys Vlasenko641dd7b2009-06-11 19:30:19 +0200904static void
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000905shcmd(union node *cmd, FILE *fp)
906{
907 union node *np;
908 int first;
909 const char *s;
910 int dftfd;
911
912 first = 1;
913 for (np = cmd->ncmd.args; np; np = np->narg.next) {
Denis Vlasenko40ba9982007-07-14 00:48:29 +0000914 if (!first)
915 putc(' ', fp);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000916 sharg(np, fp);
917 first = 0;
918 }
919 for (np = cmd->ncmd.redirect; np; np = np->nfile.next) {
Denis Vlasenko40ba9982007-07-14 00:48:29 +0000920 if (!first)
921 putc(' ', fp);
922 dftfd = 0;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000923 switch (np->nfile.type) {
Denis Vlasenko40ba9982007-07-14 00:48:29 +0000924 case NTO: s = ">>"+1; dftfd = 1; break;
925 case NCLOBBER: s = ">|"; dftfd = 1; break;
926 case NAPPEND: s = ">>"; dftfd = 1; break;
Denis Vlasenko559691a2008-10-05 18:39:31 +0000927#if ENABLE_ASH_BASH_COMPAT
928 case NTO2:
929#endif
Denis Vlasenko40ba9982007-07-14 00:48:29 +0000930 case NTOFD: s = ">&"; dftfd = 1; break;
Denis Vlasenko559691a2008-10-05 18:39:31 +0000931 case NFROM: s = "<"; break;
Denis Vlasenko40ba9982007-07-14 00:48:29 +0000932 case NFROMFD: s = "<&"; break;
933 case NFROMTO: s = "<>"; break;
934 default: s = "*error*"; break;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000935 }
936 if (np->nfile.fd != dftfd)
937 fprintf(fp, "%d", np->nfile.fd);
938 fputs(s, fp);
939 if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
940 fprintf(fp, "%d", np->ndup.dupfd);
941 } else {
942 sharg(np->nfile.fname, fp);
943 }
944 first = 0;
945 }
946}
947
948static void
949shtree(union node *n, int ind, char *pfx, FILE *fp)
950{
951 struct nodelist *lp;
952 const char *s;
953
954 if (n == NULL)
955 return;
956
957 indent(ind, pfx, fp);
Denys Vlasenko86e83ec2009-07-23 22:07:07 +0200958
959 if (n == NODE_EOF) {
960 fputs("<EOF>", fp);
961 return;
962 }
963
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000964 switch (n->type) {
965 case NSEMI:
966 s = "; ";
967 goto binop;
968 case NAND:
969 s = " && ";
970 goto binop;
971 case NOR:
972 s = " || ";
973 binop:
974 shtree(n->nbinary.ch1, ind, NULL, fp);
975 /* if (ind < 0) */
976 fputs(s, fp);
977 shtree(n->nbinary.ch2, ind, NULL, fp);
978 break;
979 case NCMD:
980 shcmd(n, fp);
981 if (ind >= 0)
982 putc('\n', fp);
983 break;
984 case NPIPE:
985 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
Denys Vlasenko7cee00e2009-07-24 01:08:03 +0200986 shtree(lp->n, 0, NULL, fp);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000987 if (lp->next)
988 fputs(" | ", fp);
989 }
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000990 if (n->npipe.pipe_backgnd)
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000991 fputs(" &", fp);
992 if (ind >= 0)
993 putc('\n', fp);
994 break;
995 default:
996 fprintf(fp, "<node type %d>", n->type);
997 if (ind >= 0)
998 putc('\n', fp);
999 break;
1000 }
1001}
1002
1003static void
1004showtree(union node *n)
1005{
1006 trace_puts("showtree called\n");
Denys Vlasenko883cea42009-07-11 15:31:59 +02001007 shtree(n, 1, NULL, stderr);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00001008}
1009
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00001010#endif /* DEBUG */
1011
1012
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00001013/* ============ Parser data */
1014
1015/*
Denis Vlasenkob012b102007-02-19 22:43:01 +00001016 * ash_vmsg() needs parsefile->fd, hence parsefile definition is moved up.
1017 */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001018struct strlist {
1019 struct strlist *next;
1020 char *text;
1021};
1022
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00001023struct alias;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00001024
Denis Vlasenkob012b102007-02-19 22:43:01 +00001025struct strpush {
1026 struct strpush *prev; /* preceding string on stack */
Denis Vlasenko41eb3002008-11-28 03:42:31 +00001027 char *prev_string;
1028 int prev_left_in_line;
Denis Vlasenkob012b102007-02-19 22:43:01 +00001029#if ENABLE_ASH_ALIAS
1030 struct alias *ap; /* if push was associated with an alias */
1031#endif
1032 char *string; /* remember the string since it may change */
1033};
1034
1035struct parsefile {
1036 struct parsefile *prev; /* preceding file on stack */
1037 int linno; /* current line */
1038 int fd; /* file descriptor (or -1 if string) */
Denis Vlasenko41eb3002008-11-28 03:42:31 +00001039 int left_in_line; /* number of chars left in this line */
1040 int left_in_buffer; /* number of chars left in this buffer past the line */
1041 char *next_to_pgetc; /* next char in buffer */
Denis Vlasenkob012b102007-02-19 22:43:01 +00001042 char *buf; /* input buffer */
1043 struct strpush *strpush; /* for pushing strings at this level */
1044 struct strpush basestrpush; /* so pushing one is fast */
1045};
1046
Denis Vlasenko448d30e2008-06-27 00:24:11 +00001047static struct parsefile basepf; /* top level input file */
Denis Vlasenkob07a4962008-06-22 13:16:23 +00001048static struct parsefile *g_parsefile = &basepf; /* current input file */
Denis Vlasenkob012b102007-02-19 22:43:01 +00001049static int startlinno; /* line # where last token started */
1050static char *commandname; /* currently executing command */
1051static struct strlist *cmdenviron; /* environment for builtin command */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00001052static uint8_t exitstatus; /* exit status of last command */
Denis Vlasenkob012b102007-02-19 22:43:01 +00001053
1054
1055/* ============ Message printing */
1056
1057static void
1058ash_vmsg(const char *msg, va_list ap)
1059{
1060 fprintf(stderr, "%s: ", arg0);
1061 if (commandname) {
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00001062 if (strcmp(arg0, commandname))
1063 fprintf(stderr, "%s: ", commandname);
Denis Vlasenkob07a4962008-06-22 13:16:23 +00001064 if (!iflag || g_parsefile->fd)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00001065 fprintf(stderr, "line %d: ", startlinno);
Eric Andersenc470f442003-07-28 09:56:35 +00001066 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00001067 vfprintf(stderr, msg, ap);
1068 outcslow('\n', stderr);
Eric Andersenc470f442003-07-28 09:56:35 +00001069}
Denis Vlasenkob012b102007-02-19 22:43:01 +00001070
1071/*
1072 * Exverror is called to raise the error exception. If the second argument
1073 * is not NULL then error prints an error message using printf style
1074 * formatting. It then raises the error exception.
1075 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001076static void ash_vmsg_and_raise(int, const char *, va_list) NORETURN;
Denis Vlasenkob012b102007-02-19 22:43:01 +00001077static void
1078ash_vmsg_and_raise(int cond, const char *msg, va_list ap)
Eric Andersenc470f442003-07-28 09:56:35 +00001079{
Denis Vlasenkob012b102007-02-19 22:43:01 +00001080#if DEBUG
1081 if (msg) {
1082 TRACE(("ash_vmsg_and_raise(%d, \"", cond));
1083 TRACEV((msg, ap));
1084 TRACE(("\") pid=%d\n", getpid()));
1085 } else
1086 TRACE(("ash_vmsg_and_raise(%d, NULL) pid=%d\n", cond, getpid()));
1087 if (msg)
1088#endif
1089 ash_vmsg(msg, ap);
1090
1091 flush_stdout_stderr();
1092 raise_exception(cond);
1093 /* NOTREACHED */
Eric Andersenc470f442003-07-28 09:56:35 +00001094}
Denis Vlasenkob012b102007-02-19 22:43:01 +00001095
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001096static void ash_msg_and_raise_error(const char *, ...) NORETURN;
Denis Vlasenkob012b102007-02-19 22:43:01 +00001097static void
1098ash_msg_and_raise_error(const char *msg, ...)
1099{
1100 va_list ap;
1101
1102 va_start(ap, msg);
1103 ash_vmsg_and_raise(EXERROR, msg, ap);
1104 /* NOTREACHED */
1105 va_end(ap);
1106}
1107
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00001108static void raise_error_syntax(const char *) NORETURN;
1109static void
1110raise_error_syntax(const char *msg)
1111{
1112 ash_msg_and_raise_error("syntax error: %s", msg);
1113 /* NOTREACHED */
1114}
1115
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001116static void ash_msg_and_raise(int, const char *, ...) NORETURN;
Denis Vlasenkob012b102007-02-19 22:43:01 +00001117static void
1118ash_msg_and_raise(int cond, const char *msg, ...)
1119{
1120 va_list ap;
1121
1122 va_start(ap, msg);
1123 ash_vmsg_and_raise(cond, msg, ap);
1124 /* NOTREACHED */
1125 va_end(ap);
1126}
1127
1128/*
1129 * error/warning routines for external builtins
1130 */
1131static void
1132ash_msg(const char *fmt, ...)
1133{
1134 va_list ap;
1135
1136 va_start(ap, fmt);
1137 ash_vmsg(fmt, ap);
1138 va_end(ap);
1139}
1140
1141/*
1142 * Return a string describing an error. The returned string may be a
1143 * pointer to a static buffer that will be overwritten on the next call.
1144 * Action describes the operation that got the error.
1145 */
1146static const char *
1147errmsg(int e, const char *em)
1148{
1149 if (e == ENOENT || e == ENOTDIR) {
1150 return em;
1151 }
1152 return strerror(e);
1153}
1154
1155
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001156/* ============ Memory allocation */
1157
Denys Vlasenkoe7670ff2009-10-11 00:45:25 +02001158#if 0
1159/* I consider these wrappers nearly useless:
1160 * ok, they return you to nearest exception handler, but
1161 * how much memory do you leak in the process, making
1162 * memory starvation worse?
1163 */
1164static void *
1165ckrealloc(void * p, size_t nbytes)
1166{
1167 p = realloc(p, nbytes);
1168 if (!p)
1169 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1170 return p;
1171}
1172
1173static void *
1174ckmalloc(size_t nbytes)
1175{
1176 return ckrealloc(NULL, nbytes);
1177}
1178
1179static void *
1180ckzalloc(size_t nbytes)
1181{
1182 return memset(ckmalloc(nbytes), 0, nbytes);
1183}
1184
1185static char *
1186ckstrdup(const char *s)
1187{
1188 char *p = strdup(s);
1189 if (!p)
1190 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1191 return p;
1192}
1193#else
1194/* Using bbox equivalents. They exit if out of memory */
1195# define ckrealloc xrealloc
1196# define ckmalloc xmalloc
1197# define ckzalloc xzalloc
1198# define ckstrdup xstrdup
1199#endif
1200
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001201/*
1202 * It appears that grabstackstr() will barf with such alignments
1203 * because stalloc() will return a string allocated in a new stackblock.
1204 */
1205#define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
1206enum {
1207 /* Most machines require the value returned from malloc to be aligned
1208 * in some way. The following macro will get this right
1209 * on many machines. */
Denys Vlasenko0e5e4ea2009-10-11 00:36:20 +02001210 SHELL_SIZE = sizeof(union { int i; char *cp; double d; }) - 1,
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001211 /* Minimum size of a block */
Denis Vlasenko01631112007-12-16 17:20:38 +00001212 MINSIZE = SHELL_ALIGN(504),
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001213};
1214
1215struct stack_block {
1216 struct stack_block *prev;
1217 char space[MINSIZE];
1218};
1219
1220struct stackmark {
1221 struct stack_block *stackp;
1222 char *stacknxt;
1223 size_t stacknleft;
1224 struct stackmark *marknext;
1225};
1226
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001227
Denis Vlasenko01631112007-12-16 17:20:38 +00001228struct globals_memstack {
1229 struct stack_block *g_stackp; // = &stackbase;
1230 struct stackmark *markp;
1231 char *g_stacknxt; // = stackbase.space;
1232 char *sstrend; // = stackbase.space + MINSIZE;
1233 size_t g_stacknleft; // = MINSIZE;
1234 int herefd; // = -1;
1235 struct stack_block stackbase;
1236};
Denis Vlasenko574f2f42008-02-27 18:41:59 +00001237extern struct globals_memstack *const ash_ptr_to_globals_memstack;
1238#define G_memstack (*ash_ptr_to_globals_memstack)
Denis Vlasenko01631112007-12-16 17:20:38 +00001239#define g_stackp (G_memstack.g_stackp )
1240#define markp (G_memstack.markp )
1241#define g_stacknxt (G_memstack.g_stacknxt )
1242#define sstrend (G_memstack.sstrend )
1243#define g_stacknleft (G_memstack.g_stacknleft)
1244#define herefd (G_memstack.herefd )
1245#define stackbase (G_memstack.stackbase )
1246#define INIT_G_memstack() do { \
Denis Vlasenko574f2f42008-02-27 18:41:59 +00001247 (*(struct globals_memstack**)&ash_ptr_to_globals_memstack) = xzalloc(sizeof(G_memstack)); \
1248 barrier(); \
Denis Vlasenko01631112007-12-16 17:20:38 +00001249 g_stackp = &stackbase; \
1250 g_stacknxt = stackbase.space; \
1251 g_stacknleft = MINSIZE; \
1252 sstrend = stackbase.space + MINSIZE; \
1253 herefd = -1; \
1254} while (0)
1255
Denys Vlasenkoe7670ff2009-10-11 00:45:25 +02001256
Denis Vlasenko01631112007-12-16 17:20:38 +00001257#define stackblock() ((void *)g_stacknxt)
1258#define stackblocksize() g_stacknleft
1259
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001260/*
1261 * Parse trees for commands are allocated in lifo order, so we use a stack
1262 * to make this more efficient, and also to avoid all sorts of exception
1263 * handling code to handle interrupts in the middle of a parse.
1264 *
1265 * The size 504 was chosen because the Ultrix malloc handles that size
1266 * well.
1267 */
1268static void *
1269stalloc(size_t nbytes)
1270{
1271 char *p;
1272 size_t aligned;
1273
1274 aligned = SHELL_ALIGN(nbytes);
Denis Vlasenko01631112007-12-16 17:20:38 +00001275 if (aligned > g_stacknleft) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001276 size_t len;
1277 size_t blocksize;
1278 struct stack_block *sp;
1279
1280 blocksize = aligned;
1281 if (blocksize < MINSIZE)
1282 blocksize = MINSIZE;
1283 len = sizeof(struct stack_block) - MINSIZE + blocksize;
1284 if (len < blocksize)
1285 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1286 INT_OFF;
1287 sp = ckmalloc(len);
Denis Vlasenko01631112007-12-16 17:20:38 +00001288 sp->prev = g_stackp;
1289 g_stacknxt = sp->space;
1290 g_stacknleft = blocksize;
1291 sstrend = g_stacknxt + blocksize;
1292 g_stackp = sp;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001293 INT_ON;
1294 }
Denis Vlasenko01631112007-12-16 17:20:38 +00001295 p = g_stacknxt;
1296 g_stacknxt += aligned;
1297 g_stacknleft -= aligned;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001298 return p;
1299}
1300
Denis Vlasenko597906c2008-02-20 16:38:54 +00001301static void *
1302stzalloc(size_t nbytes)
1303{
1304 return memset(stalloc(nbytes), 0, nbytes);
1305}
1306
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001307static void
1308stunalloc(void *p)
1309{
1310#if DEBUG
Denis Vlasenko01631112007-12-16 17:20:38 +00001311 if (!p || (g_stacknxt < (char *)p) || ((char *)p < g_stackp->space)) {
Bernhard Reutner-Fischer5e25ddb2008-05-19 09:48:17 +00001312 write(STDERR_FILENO, "stunalloc\n", 10);
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001313 abort();
1314 }
1315#endif
Denis Vlasenko01631112007-12-16 17:20:38 +00001316 g_stacknleft += g_stacknxt - (char *)p;
1317 g_stacknxt = p;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001318}
1319
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001320/*
1321 * Like strdup but works with the ash stack.
1322 */
1323static char *
1324ststrdup(const char *p)
1325{
1326 size_t len = strlen(p) + 1;
1327 return memcpy(stalloc(len), p, len);
1328}
1329
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001330static void
1331setstackmark(struct stackmark *mark)
1332{
Denis Vlasenko01631112007-12-16 17:20:38 +00001333 mark->stackp = g_stackp;
1334 mark->stacknxt = g_stacknxt;
1335 mark->stacknleft = g_stacknleft;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001336 mark->marknext = markp;
1337 markp = mark;
1338}
1339
1340static void
1341popstackmark(struct stackmark *mark)
1342{
1343 struct stack_block *sp;
1344
Denis Vlasenko93ebd4f2007-03-13 20:55:36 +00001345 if (!mark->stackp)
1346 return;
1347
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001348 INT_OFF;
1349 markp = mark->marknext;
Denis Vlasenko01631112007-12-16 17:20:38 +00001350 while (g_stackp != mark->stackp) {
1351 sp = g_stackp;
1352 g_stackp = sp->prev;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001353 free(sp);
1354 }
Denis Vlasenko01631112007-12-16 17:20:38 +00001355 g_stacknxt = mark->stacknxt;
1356 g_stacknleft = mark->stacknleft;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001357 sstrend = mark->stacknxt + mark->stacknleft;
1358 INT_ON;
1359}
1360
1361/*
1362 * When the parser reads in a string, it wants to stick the string on the
1363 * stack and only adjust the stack pointer when it knows how big the
1364 * string is. Stackblock (defined in stack.h) returns a pointer to a block
1365 * of space on top of the stack and stackblocklen returns the length of
1366 * this block. Growstackblock will grow this space by at least one byte,
1367 * possibly moving it (like realloc). Grabstackblock actually allocates the
1368 * part of the block that has been used.
1369 */
1370static void
1371growstackblock(void)
1372{
1373 size_t newlen;
1374
Denis Vlasenko01631112007-12-16 17:20:38 +00001375 newlen = g_stacknleft * 2;
1376 if (newlen < g_stacknleft)
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001377 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1378 if (newlen < 128)
1379 newlen += 128;
1380
Denis Vlasenko01631112007-12-16 17:20:38 +00001381 if (g_stacknxt == g_stackp->space && g_stackp != &stackbase) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001382 struct stack_block *oldstackp;
1383 struct stackmark *xmark;
1384 struct stack_block *sp;
1385 struct stack_block *prevstackp;
1386 size_t grosslen;
1387
1388 INT_OFF;
Denis Vlasenko01631112007-12-16 17:20:38 +00001389 oldstackp = g_stackp;
1390 sp = g_stackp;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001391 prevstackp = sp->prev;
1392 grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
1393 sp = ckrealloc(sp, grosslen);
1394 sp->prev = prevstackp;
Denis Vlasenko01631112007-12-16 17:20:38 +00001395 g_stackp = sp;
1396 g_stacknxt = sp->space;
1397 g_stacknleft = newlen;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001398 sstrend = sp->space + newlen;
1399
1400 /*
1401 * Stack marks pointing to the start of the old block
1402 * must be relocated to point to the new block
1403 */
1404 xmark = markp;
1405 while (xmark != NULL && xmark->stackp == oldstackp) {
Denis Vlasenko01631112007-12-16 17:20:38 +00001406 xmark->stackp = g_stackp;
1407 xmark->stacknxt = g_stacknxt;
1408 xmark->stacknleft = g_stacknleft;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001409 xmark = xmark->marknext;
1410 }
1411 INT_ON;
1412 } else {
Denis Vlasenko01631112007-12-16 17:20:38 +00001413 char *oldspace = g_stacknxt;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00001414 size_t oldlen = g_stacknleft;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001415 char *p = stalloc(newlen);
1416
1417 /* free the space we just allocated */
Denis Vlasenko01631112007-12-16 17:20:38 +00001418 g_stacknxt = memcpy(p, oldspace, oldlen);
1419 g_stacknleft += newlen;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001420 }
1421}
1422
1423static void
1424grabstackblock(size_t len)
1425{
1426 len = SHELL_ALIGN(len);
Denis Vlasenko01631112007-12-16 17:20:38 +00001427 g_stacknxt += len;
1428 g_stacknleft -= len;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001429}
1430
1431/*
1432 * The following routines are somewhat easier to use than the above.
1433 * The user declares a variable of type STACKSTR, which may be declared
1434 * to be a register. The macro STARTSTACKSTR initializes things. Then
1435 * the user uses the macro STPUTC to add characters to the string. In
1436 * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
1437 * grown as necessary. When the user is done, she can just leave the
1438 * string there and refer to it using stackblock(). Or she can allocate
1439 * the space for it using grabstackstr(). If it is necessary to allow
1440 * someone else to use the stack temporarily and then continue to grow
1441 * the string, the user should use grabstack to allocate the space, and
1442 * then call ungrabstr(p) to return to the previous mode of operation.
1443 *
1444 * USTPUTC is like STPUTC except that it doesn't check for overflow.
1445 * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
1446 * is space for at least one character.
1447 */
1448static void *
1449growstackstr(void)
1450{
1451 size_t len = stackblocksize();
1452 if (herefd >= 0 && len >= 1024) {
1453 full_write(herefd, stackblock(), len);
1454 return stackblock();
1455 }
1456 growstackblock();
Denis Vlasenko29eb3592008-05-18 14:06:08 +00001457 return (char *)stackblock() + len;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001458}
1459
1460/*
1461 * Called from CHECKSTRSPACE.
1462 */
1463static char *
1464makestrspace(size_t newlen, char *p)
1465{
Denis Vlasenko01631112007-12-16 17:20:38 +00001466 size_t len = p - g_stacknxt;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001467 size_t size = stackblocksize();
1468
1469 for (;;) {
1470 size_t nleft;
1471
1472 size = stackblocksize();
1473 nleft = size - len;
1474 if (nleft >= newlen)
1475 break;
1476 growstackblock();
1477 }
Denis Vlasenko29eb3592008-05-18 14:06:08 +00001478 return (char *)stackblock() + len;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001479}
1480
1481static char *
1482stack_nputstr(const char *s, size_t n, char *p)
1483{
1484 p = makestrspace(n, p);
Denis Vlasenko29eb3592008-05-18 14:06:08 +00001485 p = (char *)memcpy(p, s, n) + n;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001486 return p;
1487}
1488
1489static char *
1490stack_putstr(const char *s, char *p)
1491{
1492 return stack_nputstr(s, strlen(s), p);
1493}
1494
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001495static char *
1496_STPUTC(int c, char *p)
1497{
1498 if (p == sstrend)
1499 p = growstackstr();
1500 *p++ = c;
1501 return p;
1502}
1503
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00001504#define STARTSTACKSTR(p) ((p) = stackblock())
1505#define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
Denis Vlasenko843cbd52008-06-27 00:23:18 +00001506#define CHECKSTRSPACE(n, p) do { \
1507 char *q = (p); \
1508 size_t l = (n); \
1509 size_t m = sstrend - q; \
1510 if (l > m) \
1511 (p) = makestrspace(l, q); \
1512} while (0)
Denis Vlasenkoef527f52008-06-23 01:52:30 +00001513#define USTPUTC(c, p) (*(p)++ = (c))
Denis Vlasenko843cbd52008-06-27 00:23:18 +00001514#define STACKSTRNUL(p) do { \
1515 if ((p) == sstrend) \
1516 (p) = growstackstr(); \
1517 *(p) = '\0'; \
1518} while (0)
Denis Vlasenkoef527f52008-06-23 01:52:30 +00001519#define STUNPUTC(p) (--(p))
1520#define STTOPC(p) ((p)[-1])
1521#define STADJUST(amount, p) ((p) += (amount))
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001522
1523#define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
Denis Vlasenkoef527f52008-06-23 01:52:30 +00001524#define ungrabstackstr(s, p) stunalloc(s)
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001525#define stackstrend() ((void *)sstrend)
1526
1527
1528/* ============ String helpers */
1529
1530/*
1531 * prefix -- see if pfx is a prefix of string.
1532 */
1533static char *
1534prefix(const char *string, const char *pfx)
1535{
1536 while (*pfx) {
1537 if (*pfx++ != *string++)
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00001538 return NULL;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001539 }
1540 return (char *) string;
1541}
1542
1543/*
1544 * Check for a valid number. This should be elsewhere.
1545 */
1546static int
1547is_number(const char *p)
1548{
1549 do {
1550 if (!isdigit(*p))
1551 return 0;
1552 } while (*++p != '\0');
1553 return 1;
1554}
1555
1556/*
1557 * Convert a string of digits to an integer, printing an error message on
1558 * failure.
1559 */
1560static int
1561number(const char *s)
1562{
1563 if (!is_number(s))
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02001564 ash_msg_and_raise_error(msg_illnum, s);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001565 return atoi(s);
1566}
1567
1568/*
1569 * Produce a possibly single quoted string suitable as input to the shell.
1570 * The return string is allocated on the stack.
1571 */
1572static char *
1573single_quote(const char *s)
1574{
1575 char *p;
1576
1577 STARTSTACKSTR(p);
1578
1579 do {
1580 char *q;
1581 size_t len;
1582
1583 len = strchrnul(s, '\'') - s;
1584
1585 q = p = makestrspace(len + 3, p);
1586
1587 *q++ = '\'';
Denis Vlasenko29eb3592008-05-18 14:06:08 +00001588 q = (char *)memcpy(q, s, len) + len;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001589 *q++ = '\'';
1590 s += len;
1591
1592 STADJUST(q - p, p);
1593
1594 len = strspn(s, "'");
1595 if (!len)
1596 break;
1597
1598 q = p = makestrspace(len + 3, p);
1599
1600 *q++ = '"';
Denis Vlasenko29eb3592008-05-18 14:06:08 +00001601 q = (char *)memcpy(q, s, len) + len;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001602 *q++ = '"';
1603 s += len;
1604
1605 STADJUST(q - p, p);
1606 } while (*s);
1607
1608 USTPUTC(0, p);
1609
1610 return stackblock();
1611}
1612
1613
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00001614/* ============ nextopt */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001615
1616static char **argptr; /* argument list for builtin commands */
1617static char *optionarg; /* set by nextopt (like getopt) */
1618static char *optptr; /* used by nextopt */
1619
1620/*
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001621 * XXX - should get rid of. Have all builtins use getopt(3).
1622 * The library getopt must have the BSD extension static variable
1623 * "optreset", otherwise it can't be used within the shell safely.
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001624 *
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001625 * Standard option processing (a la getopt) for builtin routines.
1626 * The only argument that is passed to nextopt is the option string;
1627 * the other arguments are unnecessary. It returns the character,
1628 * or '\0' on end of input.
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001629 */
1630static int
1631nextopt(const char *optstring)
1632{
1633 char *p;
1634 const char *q;
1635 char c;
1636
1637 p = optptr;
1638 if (p == NULL || *p == '\0') {
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001639 /* We ate entire "-param", take next one */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001640 p = *argptr;
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001641 if (p == NULL)
1642 return '\0';
1643 if (*p != '-')
1644 return '\0';
1645 if (*++p == '\0') /* just "-" ? */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001646 return '\0';
1647 argptr++;
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001648 if (LONE_DASH(p)) /* "--" ? */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001649 return '\0';
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001650 /* p => next "-param" */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001651 }
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001652 /* p => some option char in the middle of a "-param" */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001653 c = *p++;
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +00001654 for (q = optstring; *q != c;) {
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001655 if (*q == '\0')
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00001656 ash_msg_and_raise_error("illegal option -%c", c);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001657 if (*++q == ':')
1658 q++;
1659 }
1660 if (*++q == ':') {
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001661 if (*p == '\0') {
1662 p = *argptr++;
1663 if (p == NULL)
1664 ash_msg_and_raise_error("no arg for -%c option", c);
1665 }
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001666 optionarg = p;
1667 p = NULL;
1668 }
1669 optptr = p;
1670 return c;
1671}
1672
1673
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00001674/* ============ Shell variables */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001675
Denis Vlasenko01631112007-12-16 17:20:38 +00001676/*
1677 * The parsefile structure pointed to by the global variable parsefile
1678 * contains information about the current file being read.
1679 */
Denis Vlasenko01631112007-12-16 17:20:38 +00001680struct shparam {
1681 int nparam; /* # of positional parameters (without $0) */
1682#if ENABLE_ASH_GETOPTS
1683 int optind; /* next parameter to be processed by getopts */
1684 int optoff; /* used by getopts */
1685#endif
1686 unsigned char malloced; /* if parameter list dynamically allocated */
1687 char **p; /* parameter list */
1688};
1689
1690/*
1691 * Free the list of positional parameters.
1692 */
1693static void
1694freeparam(volatile struct shparam *param)
1695{
Denis Vlasenko01631112007-12-16 17:20:38 +00001696 if (param->malloced) {
Denis Vlasenko3177ba02008-07-13 20:39:23 +00001697 char **ap, **ap1;
1698 ap = ap1 = param->p;
1699 while (*ap)
1700 free(*ap++);
1701 free(ap1);
Denis Vlasenko01631112007-12-16 17:20:38 +00001702 }
1703}
1704
1705#if ENABLE_ASH_GETOPTS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001706static void FAST_FUNC getoptsreset(const char *value);
Denis Vlasenko01631112007-12-16 17:20:38 +00001707#endif
1708
1709struct var {
1710 struct var *next; /* next entry in hash list */
1711 int flags; /* flags are defined above */
1712 const char *text; /* name=value */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001713 void (*func)(const char *) FAST_FUNC; /* function to be called when */
Denis Vlasenko01631112007-12-16 17:20:38 +00001714 /* the variable gets set/unset */
1715};
1716
1717struct localvar {
1718 struct localvar *next; /* next local variable in list */
1719 struct var *vp; /* the variable that was made local */
1720 int flags; /* saved flags */
1721 const char *text; /* saved text */
1722};
1723
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001724/* flags */
1725#define VEXPORT 0x01 /* variable is exported */
1726#define VREADONLY 0x02 /* variable cannot be modified */
1727#define VSTRFIXED 0x04 /* variable struct is statically allocated */
1728#define VTEXTFIXED 0x08 /* text is statically allocated */
1729#define VSTACK 0x10 /* text is allocated on the stack */
1730#define VUNSET 0x20 /* the variable is not set */
1731#define VNOFUNC 0x40 /* don't call the callback function */
1732#define VNOSET 0x80 /* do not set variable - just readonly test */
1733#define VNOSAVE 0x100 /* when text is on the heap before setvareq */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00001734#if ENABLE_ASH_RANDOM_SUPPORT
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00001735# define VDYNAMIC 0x200 /* dynamic variable */
1736#else
1737# define VDYNAMIC 0
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001738#endif
1739
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001740#ifdef IFS_BROKEN
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00001741static const char defifsvar[] ALIGN1 = "IFS= \t\n";
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001742#define defifs (defifsvar + 4)
1743#else
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00001744static const char defifs[] ALIGN1 = " \t\n";
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001745#endif
1746
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00001747
Denis Vlasenko01631112007-12-16 17:20:38 +00001748/* Need to be before varinit_data[] */
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00001749#if ENABLE_LOCALE_SUPPORT
Denys Vlasenko2634bf32009-06-09 18:40:07 +02001750static void FAST_FUNC
Denis Vlasenkoa8915072007-02-23 21:10:06 +00001751change_lc_all(const char *value)
1752{
1753 if (value && *value != '\0')
1754 setlocale(LC_ALL, value);
1755}
Denys Vlasenko2634bf32009-06-09 18:40:07 +02001756static void FAST_FUNC
Denis Vlasenkoa8915072007-02-23 21:10:06 +00001757change_lc_ctype(const char *value)
1758{
1759 if (value && *value != '\0')
1760 setlocale(LC_CTYPE, value);
1761}
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00001762#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001763#if ENABLE_ASH_MAIL
1764static void chkmail(void);
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001765static void changemail(const char *) FAST_FUNC;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001766#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001767static void changepath(const char *) FAST_FUNC;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001768#if ENABLE_ASH_RANDOM_SUPPORT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001769static void change_random(const char *) FAST_FUNC;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001770#endif
1771
Denis Vlasenko01631112007-12-16 17:20:38 +00001772static const struct {
1773 int flags;
1774 const char *text;
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001775 void (*func)(const char *) FAST_FUNC;
Denis Vlasenko01631112007-12-16 17:20:38 +00001776} varinit_data[] = {
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001777#ifdef IFS_BROKEN
Denis Vlasenko01631112007-12-16 17:20:38 +00001778 { VSTRFIXED|VTEXTFIXED , defifsvar , NULL },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001779#else
Denis Vlasenko01631112007-12-16 17:20:38 +00001780 { VSTRFIXED|VTEXTFIXED|VUNSET, "IFS\0" , NULL },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001781#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001782#if ENABLE_ASH_MAIL
Denis Vlasenko01631112007-12-16 17:20:38 +00001783 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL\0" , changemail },
1784 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH\0", changemail },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001785#endif
Denis Vlasenko01631112007-12-16 17:20:38 +00001786 { VSTRFIXED|VTEXTFIXED , bb_PATH_root_path, changepath },
1787 { VSTRFIXED|VTEXTFIXED , "PS1=$ " , NULL },
1788 { VSTRFIXED|VTEXTFIXED , "PS2=> " , NULL },
1789 { VSTRFIXED|VTEXTFIXED , "PS4=+ " , NULL },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001790#if ENABLE_ASH_GETOPTS
Denis Vlasenko01631112007-12-16 17:20:38 +00001791 { VSTRFIXED|VTEXTFIXED , "OPTIND=1" , getoptsreset },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001792#endif
1793#if ENABLE_ASH_RANDOM_SUPPORT
Denis Vlasenko01631112007-12-16 17:20:38 +00001794 { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM\0", change_random },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001795#endif
1796#if ENABLE_LOCALE_SUPPORT
Denis Vlasenko01631112007-12-16 17:20:38 +00001797 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL\0" , change_lc_all },
1798 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE\0", change_lc_ctype },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001799#endif
1800#if ENABLE_FEATURE_EDITING_SAVEHISTORY
Denis Vlasenko01631112007-12-16 17:20:38 +00001801 { VSTRFIXED|VTEXTFIXED|VUNSET, "HISTFILE\0", NULL },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001802#endif
1803};
1804
Denis Vlasenko0b769642008-07-24 07:54:57 +00001805struct redirtab;
Denis Vlasenko01631112007-12-16 17:20:38 +00001806
1807struct globals_var {
1808 struct shparam shellparam; /* $@ current positional parameters */
1809 struct redirtab *redirlist;
1810 int g_nullredirs;
1811 int preverrout_fd; /* save fd2 before print debug if xflag is set. */
1812 struct var *vartab[VTABSIZE];
1813 struct var varinit[ARRAY_SIZE(varinit_data)];
1814};
Denis Vlasenko574f2f42008-02-27 18:41:59 +00001815extern struct globals_var *const ash_ptr_to_globals_var;
1816#define G_var (*ash_ptr_to_globals_var)
Denis Vlasenko01631112007-12-16 17:20:38 +00001817#define shellparam (G_var.shellparam )
Denis Vlasenko0b769642008-07-24 07:54:57 +00001818//#define redirlist (G_var.redirlist )
Denis Vlasenko01631112007-12-16 17:20:38 +00001819#define g_nullredirs (G_var.g_nullredirs )
1820#define preverrout_fd (G_var.preverrout_fd)
1821#define vartab (G_var.vartab )
1822#define varinit (G_var.varinit )
1823#define INIT_G_var() do { \
Denis Vlasenko6b06cb82008-05-15 21:30:45 +00001824 unsigned i; \
Denis Vlasenko574f2f42008-02-27 18:41:59 +00001825 (*(struct globals_var**)&ash_ptr_to_globals_var) = xzalloc(sizeof(G_var)); \
1826 barrier(); \
Denis Vlasenko01631112007-12-16 17:20:38 +00001827 for (i = 0; i < ARRAY_SIZE(varinit_data); i++) { \
1828 varinit[i].flags = varinit_data[i].flags; \
1829 varinit[i].text = varinit_data[i].text; \
1830 varinit[i].func = varinit_data[i].func; \
1831 } \
1832} while (0)
1833
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001834#define vifs varinit[0]
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001835#if ENABLE_ASH_MAIL
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001836# define vmail (&vifs)[1]
1837# define vmpath (&vmail)[1]
1838# define vpath (&vmpath)[1]
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001839#else
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001840# define vpath (&vifs)[1]
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001841#endif
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001842#define vps1 (&vpath)[1]
1843#define vps2 (&vps1)[1]
1844#define vps4 (&vps2)[1]
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001845#if ENABLE_ASH_GETOPTS
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001846# define voptind (&vps4)[1]
1847# if ENABLE_ASH_RANDOM_SUPPORT
1848# define vrandom (&voptind)[1]
1849# endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001850#else
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001851# if ENABLE_ASH_RANDOM_SUPPORT
1852# define vrandom (&vps4)[1]
1853# endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001854#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001855
1856/*
1857 * The following macros access the values of the above variables.
1858 * They have to skip over the name. They return the null string
1859 * for unset variables.
1860 */
1861#define ifsval() (vifs.text + 4)
1862#define ifsset() ((vifs.flags & VUNSET) == 0)
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001863#if ENABLE_ASH_MAIL
1864# define mailval() (vmail.text + 5)
1865# define mpathval() (vmpath.text + 9)
1866# define mpathset() ((vmpath.flags & VUNSET) == 0)
1867#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001868#define pathval() (vpath.text + 5)
1869#define ps1val() (vps1.text + 4)
1870#define ps2val() (vps2.text + 4)
1871#define ps4val() (vps4.text + 4)
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001872#if ENABLE_ASH_GETOPTS
1873# define optindval() (voptind.text + 7)
1874#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001875
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001876
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001877#define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
1878#define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
1879
Denis Vlasenko01631112007-12-16 17:20:38 +00001880#if ENABLE_ASH_GETOPTS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001881static void FAST_FUNC
Denis Vlasenko01631112007-12-16 17:20:38 +00001882getoptsreset(const char *value)
1883{
1884 shellparam.optind = number(value);
1885 shellparam.optoff = -1;
1886}
1887#endif
1888
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001889/*
1890 * Return of a legal variable name (a letter or underscore followed by zero or
1891 * more letters, underscores, and digits).
1892 */
1893static char *
1894endofname(const char *name)
1895{
1896 char *p;
1897
1898 p = (char *) name;
1899 if (!is_name(*p))
1900 return p;
1901 while (*++p) {
1902 if (!is_in_name(*p))
1903 break;
1904 }
1905 return p;
1906}
1907
1908/*
1909 * Compares two strings up to the first = or '\0'. The first
1910 * string must be terminated by '='; the second may be terminated by
1911 * either '=' or '\0'.
1912 */
1913static int
1914varcmp(const char *p, const char *q)
1915{
1916 int c, d;
1917
1918 while ((c = *p) == (d = *q)) {
1919 if (!c || c == '=')
1920 goto out;
1921 p++;
1922 q++;
1923 }
1924 if (c == '=')
Denis Vlasenko9650f362007-02-23 01:04:37 +00001925 c = '\0';
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001926 if (d == '=')
Denis Vlasenko9650f362007-02-23 01:04:37 +00001927 d = '\0';
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001928 out:
1929 return c - d;
1930}
1931
1932static int
1933varequal(const char *a, const char *b)
1934{
1935 return !varcmp(a, b);
1936}
1937
1938/*
1939 * Find the appropriate entry in the hash table from the name.
1940 */
1941static struct var **
1942hashvar(const char *p)
1943{
1944 unsigned hashval;
1945
1946 hashval = ((unsigned char) *p) << 4;
1947 while (*p && *p != '=')
1948 hashval += (unsigned char) *p++;
1949 return &vartab[hashval % VTABSIZE];
1950}
1951
1952static int
1953vpcmp(const void *a, const void *b)
1954{
1955 return varcmp(*(const char **)a, *(const char **)b);
1956}
1957
1958/*
1959 * This routine initializes the builtin variables.
1960 */
1961static void
1962initvar(void)
1963{
1964 struct var *vp;
1965 struct var *end;
1966 struct var **vpp;
1967
1968 /*
1969 * PS1 depends on uid
1970 */
1971#if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
1972 vps1.text = "PS1=\\w \\$ ";
1973#else
1974 if (!geteuid())
1975 vps1.text = "PS1=# ";
1976#endif
1977 vp = varinit;
Denis Vlasenko80b8b392007-06-25 10:55:35 +00001978 end = vp + ARRAY_SIZE(varinit);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001979 do {
1980 vpp = hashvar(vp->text);
1981 vp->next = *vpp;
1982 *vpp = vp;
1983 } while (++vp < end);
1984}
1985
1986static struct var **
1987findvar(struct var **vpp, const char *name)
1988{
1989 for (; *vpp; vpp = &(*vpp)->next) {
1990 if (varequal((*vpp)->text, name)) {
1991 break;
1992 }
1993 }
1994 return vpp;
1995}
1996
1997/*
1998 * Find the value of a variable. Returns NULL if not set.
1999 */
Mike Frysinger98c52642009-04-02 10:02:37 +00002000static const char *
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002001lookupvar(const char *name)
2002{
2003 struct var *v;
2004
2005 v = *findvar(hashvar(name), name);
2006 if (v) {
Denis Vlasenko448d30e2008-06-27 00:24:11 +00002007#if ENABLE_ASH_RANDOM_SUPPORT
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002008 /*
2009 * Dynamic variables are implemented roughly the same way they are
2010 * in bash. Namely, they're "special" so long as they aren't unset.
2011 * As soon as they're unset, they're no longer dynamic, and dynamic
2012 * lookup will no longer happen at that point. -- PFM.
2013 */
2014 if ((v->flags & VDYNAMIC))
2015 (*v->func)(NULL);
2016#endif
2017 if (!(v->flags & VUNSET))
2018 return strchrnul(v->text, '=') + 1;
2019 }
2020 return NULL;
2021}
2022
2023/*
2024 * Search the environment of a builtin command.
2025 */
Mike Frysinger98c52642009-04-02 10:02:37 +00002026static const char *
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002027bltinlookup(const char *name)
2028{
2029 struct strlist *sp;
2030
2031 for (sp = cmdenviron; sp; sp = sp->next) {
2032 if (varequal(sp->text, name))
2033 return strchrnul(sp->text, '=') + 1;
2034 }
2035 return lookupvar(name);
2036}
2037
2038/*
2039 * Same as setvar except that the variable and value are passed in
2040 * the first argument as name=value. Since the first argument will
2041 * be actually stored in the table, it should not be a string that
2042 * will go away.
2043 * Called with interrupts off.
2044 */
2045static void
2046setvareq(char *s, int flags)
2047{
2048 struct var *vp, **vpp;
2049
2050 vpp = hashvar(s);
2051 flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
2052 vp = *findvar(vpp, s);
2053 if (vp) {
2054 if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
2055 const char *n;
2056
2057 if (flags & VNOSAVE)
2058 free(s);
2059 n = vp->text;
2060 ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
2061 }
2062
2063 if (flags & VNOSET)
2064 return;
2065
2066 if (vp->func && (flags & VNOFUNC) == 0)
2067 (*vp->func)(strchrnul(s, '=') + 1);
2068
2069 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
2070 free((char*)vp->text);
2071
2072 flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
2073 } else {
2074 if (flags & VNOSET)
2075 return;
2076 /* not found */
Denis Vlasenko597906c2008-02-20 16:38:54 +00002077 vp = ckzalloc(sizeof(*vp));
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002078 vp->next = *vpp;
Denis Vlasenko597906c2008-02-20 16:38:54 +00002079 /*vp->func = NULL; - ckzalloc did it */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002080 *vpp = vp;
2081 }
2082 if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
2083 s = ckstrdup(s);
2084 vp->text = s;
2085 vp->flags = flags;
2086}
2087
2088/*
2089 * Set the value of a variable. The flags argument is ored with the
2090 * flags of the variable. If val is NULL, the variable is unset.
2091 */
2092static void
2093setvar(const char *name, const char *val, int flags)
2094{
2095 char *p, *q;
2096 size_t namelen;
2097 char *nameeq;
2098 size_t vallen;
2099
2100 q = endofname(name);
2101 p = strchrnul(q, '=');
2102 namelen = p - name;
2103 if (!namelen || p != q)
2104 ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
2105 vallen = 0;
2106 if (val == NULL) {
2107 flags |= VUNSET;
2108 } else {
2109 vallen = strlen(val);
2110 }
2111 INT_OFF;
2112 nameeq = ckmalloc(namelen + vallen + 2);
Denis Vlasenko29eb3592008-05-18 14:06:08 +00002113 p = (char *)memcpy(nameeq, name, namelen) + namelen;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002114 if (val) {
2115 *p++ = '=';
Denis Vlasenko29eb3592008-05-18 14:06:08 +00002116 p = (char *)memcpy(p, val, vallen) + vallen;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002117 }
2118 *p = '\0';
2119 setvareq(nameeq, flags | VNOSAVE);
2120 INT_ON;
2121}
2122
2123#if ENABLE_ASH_GETOPTS
2124/*
2125 * Safe version of setvar, returns 1 on success 0 on failure.
2126 */
2127static int
2128setvarsafe(const char *name, const char *val, int flags)
2129{
2130 int err;
2131 volatile int saveint;
2132 struct jmploc *volatile savehandler = exception_handler;
2133 struct jmploc jmploc;
2134
2135 SAVE_INT(saveint);
2136 if (setjmp(jmploc.loc))
2137 err = 1;
2138 else {
2139 exception_handler = &jmploc;
2140 setvar(name, val, flags);
2141 err = 0;
2142 }
2143 exception_handler = savehandler;
2144 RESTORE_INT(saveint);
2145 return err;
2146}
2147#endif
2148
2149/*
2150 * Unset the specified variable.
2151 */
2152static int
2153unsetvar(const char *s)
2154{
2155 struct var **vpp;
2156 struct var *vp;
2157 int retval;
2158
2159 vpp = findvar(hashvar(s), s);
2160 vp = *vpp;
2161 retval = 2;
2162 if (vp) {
2163 int flags = vp->flags;
2164
2165 retval = 1;
2166 if (flags & VREADONLY)
2167 goto out;
Denis Vlasenko448d30e2008-06-27 00:24:11 +00002168#if ENABLE_ASH_RANDOM_SUPPORT
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002169 vp->flags &= ~VDYNAMIC;
2170#endif
2171 if (flags & VUNSET)
2172 goto ok;
2173 if ((flags & VSTRFIXED) == 0) {
2174 INT_OFF;
2175 if ((flags & (VTEXTFIXED|VSTACK)) == 0)
2176 free((char*)vp->text);
2177 *vpp = vp->next;
2178 free(vp);
2179 INT_ON;
2180 } else {
2181 setvar(s, 0, 0);
2182 vp->flags &= ~VEXPORT;
2183 }
2184 ok:
2185 retval = 0;
2186 }
2187 out:
2188 return retval;
2189}
2190
2191/*
2192 * Process a linked list of variable assignments.
2193 */
2194static void
2195listsetvar(struct strlist *list_set_var, int flags)
2196{
2197 struct strlist *lp = list_set_var;
2198
2199 if (!lp)
2200 return;
2201 INT_OFF;
2202 do {
2203 setvareq(lp->text, flags);
Denis Vlasenko9650f362007-02-23 01:04:37 +00002204 lp = lp->next;
2205 } while (lp);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002206 INT_ON;
2207}
2208
2209/*
2210 * Generate a list of variables satisfying the given conditions.
2211 */
2212static char **
2213listvars(int on, int off, char ***end)
2214{
2215 struct var **vpp;
2216 struct var *vp;
2217 char **ep;
2218 int mask;
2219
2220 STARTSTACKSTR(ep);
2221 vpp = vartab;
2222 mask = on | off;
2223 do {
2224 for (vp = *vpp; vp; vp = vp->next) {
2225 if ((vp->flags & mask) == on) {
2226 if (ep == stackstrend())
2227 ep = growstackstr();
2228 *ep++ = (char *) vp->text;
2229 }
2230 }
2231 } while (++vpp < vartab + VTABSIZE);
2232 if (ep == stackstrend())
2233 ep = growstackstr();
2234 if (end)
2235 *end = ep;
2236 *ep++ = NULL;
2237 return grabstackstr(ep);
2238}
2239
2240
2241/* ============ Path search helper
2242 *
2243 * The variable path (passed by reference) should be set to the start
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02002244 * of the path before the first call; path_advance will update
2245 * this value as it proceeds. Successive calls to path_advance will return
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002246 * the possible path expansions in sequence. If an option (indicated by
2247 * a percent sign) appears in the path entry then the global variable
2248 * pathopt will be set to point to it; otherwise pathopt will be set to
2249 * NULL.
2250 */
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02002251static const char *pathopt; /* set by path_advance */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002252
2253static char *
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02002254path_advance(const char **path, const char *name)
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002255{
2256 const char *p;
2257 char *q;
2258 const char *start;
2259 size_t len;
2260
2261 if (*path == NULL)
2262 return NULL;
2263 start = *path;
Denis Vlasenkof7d56652008-03-25 05:51:41 +00002264 for (p = start; *p && *p != ':' && *p != '%'; p++)
2265 continue;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002266 len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
2267 while (stackblocksize() < len)
2268 growstackblock();
2269 q = stackblock();
2270 if (p != start) {
2271 memcpy(q, start, p - start);
2272 q += p - start;
2273 *q++ = '/';
2274 }
2275 strcpy(q, name);
2276 pathopt = NULL;
2277 if (*p == '%') {
2278 pathopt = ++p;
Denis Vlasenkof7d56652008-03-25 05:51:41 +00002279 while (*p && *p != ':')
2280 p++;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002281 }
2282 if (*p == ':')
2283 *path = p + 1;
2284 else
2285 *path = NULL;
2286 return stalloc(len);
2287}
2288
2289
2290/* ============ Prompt */
2291
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +00002292static smallint doprompt; /* if set, prompt the user */
2293static smallint needprompt; /* true if interactive and at start of line */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002294
2295#if ENABLE_FEATURE_EDITING
2296static line_input_t *line_input_state;
2297static const char *cmdedit_prompt;
2298static void
2299putprompt(const char *s)
2300{
2301 if (ENABLE_ASH_EXPAND_PRMT) {
2302 free((char*)cmdedit_prompt);
Denis Vlasenko4222ae42007-02-25 02:37:49 +00002303 cmdedit_prompt = ckstrdup(s);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002304 return;
2305 }
2306 cmdedit_prompt = s;
2307}
2308#else
2309static void
2310putprompt(const char *s)
2311{
2312 out2str(s);
2313}
2314#endif
2315
2316#if ENABLE_ASH_EXPAND_PRMT
2317/* expandstr() needs parsing machinery, so it is far away ahead... */
2318static const char *expandstr(const char *ps);
2319#else
2320#define expandstr(s) s
2321#endif
2322
2323static void
2324setprompt(int whichprompt)
2325{
2326 const char *prompt;
2327#if ENABLE_ASH_EXPAND_PRMT
2328 struct stackmark smark;
2329#endif
2330
2331 needprompt = 0;
2332
2333 switch (whichprompt) {
2334 case 1:
2335 prompt = ps1val();
2336 break;
2337 case 2:
2338 prompt = ps2val();
2339 break;
2340 default: /* 0 */
2341 prompt = nullstr;
2342 }
2343#if ENABLE_ASH_EXPAND_PRMT
2344 setstackmark(&smark);
2345 stalloc(stackblocksize());
2346#endif
2347 putprompt(expandstr(prompt));
2348#if ENABLE_ASH_EXPAND_PRMT
2349 popstackmark(&smark);
2350#endif
2351}
2352
2353
2354/* ============ The cd and pwd commands */
2355
2356#define CD_PHYSICAL 1
2357#define CD_PRINT 2
2358
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002359static int
2360cdopt(void)
2361{
2362 int flags = 0;
2363 int i, j;
2364
2365 j = 'L';
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02002366 while ((i = nextopt("LP")) != '\0') {
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002367 if (i != j) {
2368 flags ^= CD_PHYSICAL;
2369 j = i;
2370 }
2371 }
2372
2373 return flags;
2374}
2375
2376/*
2377 * Update curdir (the name of the current directory) in response to a
2378 * cd command.
2379 */
2380static const char *
2381updatepwd(const char *dir)
2382{
2383 char *new;
2384 char *p;
2385 char *cdcomppath;
2386 const char *lim;
2387
2388 cdcomppath = ststrdup(dir);
2389 STARTSTACKSTR(new);
2390 if (*dir != '/') {
2391 if (curdir == nullstr)
2392 return 0;
2393 new = stack_putstr(curdir, new);
2394 }
2395 new = makestrspace(strlen(dir) + 2, new);
Denis Vlasenko29eb3592008-05-18 14:06:08 +00002396 lim = (char *)stackblock() + 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002397 if (*dir != '/') {
2398 if (new[-1] != '/')
2399 USTPUTC('/', new);
2400 if (new > lim && *lim == '/')
2401 lim++;
2402 } else {
2403 USTPUTC('/', new);
2404 cdcomppath++;
2405 if (dir[1] == '/' && dir[2] != '/') {
2406 USTPUTC('/', new);
2407 cdcomppath++;
2408 lim++;
2409 }
2410 }
2411 p = strtok(cdcomppath, "/");
2412 while (p) {
2413 switch (*p) {
2414 case '.':
2415 if (p[1] == '.' && p[2] == '\0') {
2416 while (new > lim) {
2417 STUNPUTC(new);
2418 if (new[-1] == '/')
2419 break;
2420 }
2421 break;
Denis Vlasenko16abcd92007-04-13 23:59:52 +00002422 }
2423 if (p[1] == '\0')
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002424 break;
2425 /* fall through */
2426 default:
2427 new = stack_putstr(p, new);
2428 USTPUTC('/', new);
2429 }
2430 p = strtok(0, "/");
2431 }
2432 if (new > lim)
2433 STUNPUTC(new);
2434 *new = 0;
2435 return stackblock();
2436}
2437
2438/*
2439 * Find out what the current directory is. If we already know the current
2440 * directory, this routine returns immediately.
2441 */
2442static char *
2443getpwd(void)
2444{
Denis Vlasenko01631112007-12-16 17:20:38 +00002445 char *dir = getcwd(NULL, 0); /* huh, using glibc extension? */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002446 return dir ? dir : nullstr;
2447}
2448
2449static void
2450setpwd(const char *val, int setold)
2451{
2452 char *oldcur, *dir;
2453
2454 oldcur = dir = curdir;
2455
2456 if (setold) {
2457 setvar("OLDPWD", oldcur, VEXPORT);
2458 }
2459 INT_OFF;
2460 if (physdir != nullstr) {
2461 if (physdir != oldcur)
2462 free(physdir);
2463 physdir = nullstr;
2464 }
2465 if (oldcur == val || !val) {
2466 char *s = getpwd();
2467 physdir = s;
2468 if (!val)
2469 dir = s;
2470 } else
2471 dir = ckstrdup(val);
2472 if (oldcur != dir && oldcur != nullstr) {
2473 free(oldcur);
2474 }
2475 curdir = dir;
2476 INT_ON;
2477 setvar("PWD", dir, VEXPORT);
2478}
2479
2480static void hashcd(void);
2481
2482/*
2483 * Actually do the chdir. We also call hashcd to let the routines in exec.c
2484 * know that the current directory has changed.
2485 */
2486static int
2487docd(const char *dest, int flags)
2488{
2489 const char *dir = 0;
2490 int err;
2491
2492 TRACE(("docd(\"%s\", %d) called\n", dest, flags));
2493
2494 INT_OFF;
2495 if (!(flags & CD_PHYSICAL)) {
2496 dir = updatepwd(dest);
2497 if (dir)
2498 dest = dir;
2499 }
2500 err = chdir(dest);
2501 if (err)
2502 goto out;
2503 setpwd(dir, 1);
2504 hashcd();
2505 out:
2506 INT_ON;
2507 return err;
2508}
2509
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02002510static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00002511cdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002512{
2513 const char *dest;
2514 const char *path;
2515 const char *p;
2516 char c;
2517 struct stat statb;
2518 int flags;
2519
2520 flags = cdopt();
2521 dest = *argptr;
2522 if (!dest)
2523 dest = bltinlookup(homestr);
2524 else if (LONE_DASH(dest)) {
2525 dest = bltinlookup("OLDPWD");
2526 flags |= CD_PRINT;
2527 }
2528 if (!dest)
2529 dest = nullstr;
2530 if (*dest == '/')
2531 goto step7;
2532 if (*dest == '.') {
2533 c = dest[1];
2534 dotdot:
2535 switch (c) {
2536 case '\0':
2537 case '/':
2538 goto step6;
2539 case '.':
2540 c = dest[2];
2541 if (c != '.')
2542 goto dotdot;
2543 }
2544 }
2545 if (!*dest)
2546 dest = ".";
2547 path = bltinlookup("CDPATH");
2548 if (!path) {
2549 step6:
2550 step7:
2551 p = dest;
2552 goto docd;
2553 }
2554 do {
2555 c = *path;
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02002556 p = path_advance(&path, dest);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002557 if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
2558 if (c && c != ':')
2559 flags |= CD_PRINT;
2560 docd:
2561 if (!docd(p, flags))
2562 goto out;
2563 break;
2564 }
2565 } while (path);
2566 ash_msg_and_raise_error("can't cd to %s", dest);
2567 /* NOTREACHED */
2568 out:
2569 if (flags & CD_PRINT)
2570 out1fmt(snlfmt, curdir);
2571 return 0;
2572}
2573
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02002574static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00002575pwdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002576{
2577 int flags;
2578 const char *dir = curdir;
2579
2580 flags = cdopt();
2581 if (flags) {
2582 if (physdir == nullstr)
2583 setpwd(dir, 0);
2584 dir = physdir;
2585 }
2586 out1fmt(snlfmt, dir);
2587 return 0;
2588}
2589
Denis Vlasenko0c032a42007-02-23 01:03:40 +00002590
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00002591/* ============ ... */
Eric Andersenc470f442003-07-28 09:56:35 +00002592
Denis Vlasenko834dee72008-10-07 09:18:30 +00002593
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +00002594#define IBUFSIZ COMMON_BUFSIZE
Denis Vlasenko834dee72008-10-07 09:18:30 +00002595/* buffer for top level input file */
2596#define basebuf bb_common_bufsiz1
Eric Andersenc470f442003-07-28 09:56:35 +00002597
Eric Andersenc470f442003-07-28 09:56:35 +00002598/* Syntax classes */
Denis Vlasenko834dee72008-10-07 09:18:30 +00002599#define CWORD 0 /* character is nothing special */
2600#define CNL 1 /* newline character */
2601#define CBACK 2 /* a backslash character */
2602#define CSQUOTE 3 /* single quote */
2603#define CDQUOTE 4 /* double quote */
Eric Andersenc470f442003-07-28 09:56:35 +00002604#define CENDQUOTE 5 /* a terminating quote */
Denis Vlasenko834dee72008-10-07 09:18:30 +00002605#define CBQUOTE 6 /* backwards single quote */
2606#define CVAR 7 /* a dollar sign */
2607#define CENDVAR 8 /* a '}' character */
2608#define CLP 9 /* a left paren in arithmetic */
2609#define CRP 10 /* a right paren in arithmetic */
Eric Andersenc470f442003-07-28 09:56:35 +00002610#define CENDFILE 11 /* end of file */
Denis Vlasenko834dee72008-10-07 09:18:30 +00002611#define CCTL 12 /* like CWORD, except it must be escaped */
2612#define CSPCL 13 /* these terminate a word */
2613#define CIGN 14 /* character should be ignored */
Eric Andersenc470f442003-07-28 09:56:35 +00002614
Denis Vlasenko131ae172007-02-18 13:00:19 +00002615#if ENABLE_ASH_ALIAS
Denis Vlasenko834dee72008-10-07 09:18:30 +00002616#define SYNBASE 130
2617#define PEOF -130
2618#define PEOA -129
Eric Andersenc470f442003-07-28 09:56:35 +00002619#define PEOA_OR_PEOF PEOA
2620#else
Denis Vlasenko834dee72008-10-07 09:18:30 +00002621#define SYNBASE 129
2622#define PEOF -129
Eric Andersenc470f442003-07-28 09:56:35 +00002623#define PEOA_OR_PEOF PEOF
2624#endif
2625
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00002626/* number syntax index */
2627#define BASESYNTAX 0 /* not in quotes */
2628#define DQSYNTAX 1 /* in double quotes */
2629#define SQSYNTAX 2 /* in single quotes */
2630#define ARISYNTAX 3 /* in arithmetic */
Denis Vlasenko46a53062007-09-24 18:30:02 +00002631#define PSSYNTAX 4 /* prompt */
Eric Andersenc470f442003-07-28 09:56:35 +00002632
Denis Vlasenko131ae172007-02-18 13:00:19 +00002633#if ENABLE_ASH_OPTIMIZE_FOR_SIZE
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002634#define USE_SIT_FUNCTION
2635#endif
2636
Mike Frysinger98c52642009-04-02 10:02:37 +00002637#if ENABLE_SH_MATH_SUPPORT
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002638static const char S_I_T[][4] = {
Denis Vlasenko131ae172007-02-18 13:00:19 +00002639#if ENABLE_ASH_ALIAS
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00002640 { CSPCL, CIGN, CIGN, CIGN }, /* 0, PEOA */
Eric Andersenc470f442003-07-28 09:56:35 +00002641#endif
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00002642 { CSPCL, CWORD, CWORD, CWORD }, /* 1, ' ' */
2643 { CNL, CNL, CNL, CNL }, /* 2, \n */
2644 { CWORD, CCTL, CCTL, CWORD }, /* 3, !*-/:=?[]~ */
2645 { CDQUOTE, CENDQUOTE, CWORD, CWORD }, /* 4, '"' */
2646 { CVAR, CVAR, CWORD, CVAR }, /* 5, $ */
2647 { CSQUOTE, CWORD, CENDQUOTE, CWORD }, /* 6, "'" */
2648 { CSPCL, CWORD, CWORD, CLP }, /* 7, ( */
2649 { CSPCL, CWORD, CWORD, CRP }, /* 8, ) */
2650 { CBACK, CBACK, CCTL, CBACK }, /* 9, \ */
2651 { CBQUOTE, CBQUOTE, CWORD, CBQUOTE }, /* 10, ` */
2652 { CENDVAR, CENDVAR, CWORD, CENDVAR }, /* 11, } */
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002653#ifndef USE_SIT_FUNCTION
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00002654 { CENDFILE, CENDFILE, CENDFILE, CENDFILE }, /* 12, PEOF */
2655 { CWORD, CWORD, CWORD, CWORD }, /* 13, 0-9A-Za-z */
2656 { CCTL, CCTL, CCTL, CCTL } /* 14, CTLESC ... */
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002657#endif
Eric Andersen2870d962001-07-02 17:27:21 +00002658};
Eric Andersenc470f442003-07-28 09:56:35 +00002659#else
2660static const char S_I_T[][3] = {
Denis Vlasenko131ae172007-02-18 13:00:19 +00002661#if ENABLE_ASH_ALIAS
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00002662 { CSPCL, CIGN, CIGN }, /* 0, PEOA */
Eric Andersenc470f442003-07-28 09:56:35 +00002663#endif
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00002664 { CSPCL, CWORD, CWORD }, /* 1, ' ' */
2665 { CNL, CNL, CNL }, /* 2, \n */
2666 { CWORD, CCTL, CCTL }, /* 3, !*-/:=?[]~ */
2667 { CDQUOTE, CENDQUOTE, CWORD }, /* 4, '"' */
2668 { CVAR, CVAR, CWORD }, /* 5, $ */
2669 { CSQUOTE, CWORD, CENDQUOTE }, /* 6, "'" */
2670 { CSPCL, CWORD, CWORD }, /* 7, ( */
2671 { CSPCL, CWORD, CWORD }, /* 8, ) */
2672 { CBACK, CBACK, CCTL }, /* 9, \ */
2673 { CBQUOTE, CBQUOTE, CWORD }, /* 10, ` */
2674 { CENDVAR, CENDVAR, CWORD }, /* 11, } */
Eric Andersenc470f442003-07-28 09:56:35 +00002675#ifndef USE_SIT_FUNCTION
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00002676 { CENDFILE, CENDFILE, CENDFILE }, /* 12, PEOF */
2677 { CWORD, CWORD, CWORD }, /* 13, 0-9A-Za-z */
2678 { CCTL, CCTL, CCTL } /* 14, CTLESC ... */
Eric Andersenc470f442003-07-28 09:56:35 +00002679#endif
2680};
Mike Frysinger98c52642009-04-02 10:02:37 +00002681#endif /* SH_MATH_SUPPORT */
Eric Andersen2870d962001-07-02 17:27:21 +00002682
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002683#ifdef USE_SIT_FUNCTION
2684
Denis Vlasenko0c032a42007-02-23 01:03:40 +00002685static int
2686SIT(int c, int syntax)
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002687{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00002688 static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-/:;<=>?[\\]`|}~";
Denis Vlasenko131ae172007-02-18 13:00:19 +00002689#if ENABLE_ASH_ALIAS
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00002690 static const char syntax_index_table[] ALIGN1 = {
Eric Andersenc470f442003-07-28 09:56:35 +00002691 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
2692 7, 8, 3, 3, 3, 3, 1, 1, /* "()*-/:;<" */
2693 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
2694 11, 3 /* "}~" */
2695 };
2696#else
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00002697 static const char syntax_index_table[] ALIGN1 = {
Eric Andersenc470f442003-07-28 09:56:35 +00002698 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
2699 6, 7, 2, 2, 2, 2, 0, 0, /* "()*-/:;<" */
2700 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
2701 10, 2 /* "}~" */
2702 };
2703#endif
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002704 const char *s;
2705 int indx;
2706
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +00002707 if (c == PEOF) { /* 2^8+2 */
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002708 return CENDFILE;
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002709 }
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +00002710#if ENABLE_ASH_ALIAS
2711 if (c == PEOA) { /* 2^8+1 */
2712 indx = 0;
2713 } else
2714#endif
2715 {
Denys Vlasenkob0d63382009-09-16 16:18:32 +02002716 if ((unsigned char)c >= CTLESC
2717 && (unsigned char)c <= CTLQUOTEMARK
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +00002718 ) {
2719 return CCTL;
2720 }
2721 s = strchrnul(spec_symbls, c);
2722 if (*s == '\0') {
2723 return CWORD;
2724 }
2725 indx = syntax_index_table[s - spec_symbls];
2726 }
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002727 return S_I_T[indx][syntax];
2728}
2729
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00002730#else /* !USE_SIT_FUNCTION */
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002731
Denis Vlasenko131ae172007-02-18 13:00:19 +00002732#if ENABLE_ASH_ALIAS
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00002733#define CSPCL_CIGN_CIGN_CIGN 0
2734#define CSPCL_CWORD_CWORD_CWORD 1
2735#define CNL_CNL_CNL_CNL 2
2736#define CWORD_CCTL_CCTL_CWORD 3
2737#define CDQUOTE_CENDQUOTE_CWORD_CWORD 4
2738#define CVAR_CVAR_CWORD_CVAR 5
2739#define CSQUOTE_CWORD_CENDQUOTE_CWORD 6
2740#define CSPCL_CWORD_CWORD_CLP 7
2741#define CSPCL_CWORD_CWORD_CRP 8
2742#define CBACK_CBACK_CCTL_CBACK 9
2743#define CBQUOTE_CBQUOTE_CWORD_CBQUOTE 10
2744#define CENDVAR_CENDVAR_CWORD_CENDVAR 11
2745#define CENDFILE_CENDFILE_CENDFILE_CENDFILE 12
2746#define CWORD_CWORD_CWORD_CWORD 13
2747#define CCTL_CCTL_CCTL_CCTL 14
Eric Andersenc470f442003-07-28 09:56:35 +00002748#else
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00002749#define CSPCL_CWORD_CWORD_CWORD 0
2750#define CNL_CNL_CNL_CNL 1
2751#define CWORD_CCTL_CCTL_CWORD 2
2752#define CDQUOTE_CENDQUOTE_CWORD_CWORD 3
2753#define CVAR_CVAR_CWORD_CVAR 4
2754#define CSQUOTE_CWORD_CENDQUOTE_CWORD 5
2755#define CSPCL_CWORD_CWORD_CLP 6
2756#define CSPCL_CWORD_CWORD_CRP 7
2757#define CBACK_CBACK_CCTL_CBACK 8
2758#define CBQUOTE_CBQUOTE_CWORD_CBQUOTE 9
2759#define CENDVAR_CENDVAR_CWORD_CENDVAR 10
2760#define CENDFILE_CENDFILE_CENDFILE_CENDFILE 11
2761#define CWORD_CWORD_CWORD_CWORD 12
2762#define CCTL_CCTL_CCTL_CCTL 13
Eric Andersenc470f442003-07-28 09:56:35 +00002763#endif
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002764
2765static const char syntax_index_table[258] = {
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00002766 /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
Eric Andersenc470f442003-07-28 09:56:35 +00002767 /* 0 PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
Denis Vlasenko131ae172007-02-18 13:00:19 +00002768#if ENABLE_ASH_ALIAS
Eric Andersenc470f442003-07-28 09:56:35 +00002769 /* 1 PEOA */ CSPCL_CIGN_CIGN_CIGN,
2770#endif
2771 /* 2 -128 0x80 */ CWORD_CWORD_CWORD_CWORD,
2772 /* 3 -127 CTLESC */ CCTL_CCTL_CCTL_CCTL,
2773 /* 4 -126 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
2774 /* 5 -125 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
2775 /* 6 -124 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
2776 /* 7 -123 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
2777 /* 8 -122 CTLARI */ CCTL_CCTL_CCTL_CCTL,
2778 /* 9 -121 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
2779 /* 10 -120 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00002780 /* 11 -119 */ CWORD_CWORD_CWORD_CWORD,
2781 /* 12 -118 */ CWORD_CWORD_CWORD_CWORD,
2782 /* 13 -117 */ CWORD_CWORD_CWORD_CWORD,
2783 /* 14 -116 */ CWORD_CWORD_CWORD_CWORD,
2784 /* 15 -115 */ CWORD_CWORD_CWORD_CWORD,
2785 /* 16 -114 */ CWORD_CWORD_CWORD_CWORD,
2786 /* 17 -113 */ CWORD_CWORD_CWORD_CWORD,
2787 /* 18 -112 */ CWORD_CWORD_CWORD_CWORD,
2788 /* 19 -111 */ CWORD_CWORD_CWORD_CWORD,
2789 /* 20 -110 */ CWORD_CWORD_CWORD_CWORD,
2790 /* 21 -109 */ CWORD_CWORD_CWORD_CWORD,
2791 /* 22 -108 */ CWORD_CWORD_CWORD_CWORD,
2792 /* 23 -107 */ CWORD_CWORD_CWORD_CWORD,
2793 /* 24 -106 */ CWORD_CWORD_CWORD_CWORD,
2794 /* 25 -105 */ CWORD_CWORD_CWORD_CWORD,
2795 /* 26 -104 */ CWORD_CWORD_CWORD_CWORD,
2796 /* 27 -103 */ CWORD_CWORD_CWORD_CWORD,
2797 /* 28 -102 */ CWORD_CWORD_CWORD_CWORD,
2798 /* 29 -101 */ CWORD_CWORD_CWORD_CWORD,
2799 /* 30 -100 */ CWORD_CWORD_CWORD_CWORD,
2800 /* 31 -99 */ CWORD_CWORD_CWORD_CWORD,
2801 /* 32 -98 */ CWORD_CWORD_CWORD_CWORD,
2802 /* 33 -97 */ CWORD_CWORD_CWORD_CWORD,
2803 /* 34 -96 */ CWORD_CWORD_CWORD_CWORD,
2804 /* 35 -95 */ CWORD_CWORD_CWORD_CWORD,
2805 /* 36 -94 */ CWORD_CWORD_CWORD_CWORD,
2806 /* 37 -93 */ CWORD_CWORD_CWORD_CWORD,
2807 /* 38 -92 */ CWORD_CWORD_CWORD_CWORD,
2808 /* 39 -91 */ CWORD_CWORD_CWORD_CWORD,
2809 /* 40 -90 */ CWORD_CWORD_CWORD_CWORD,
2810 /* 41 -89 */ CWORD_CWORD_CWORD_CWORD,
2811 /* 42 -88 */ CWORD_CWORD_CWORD_CWORD,
2812 /* 43 -87 */ CWORD_CWORD_CWORD_CWORD,
2813 /* 44 -86 */ CWORD_CWORD_CWORD_CWORD,
2814 /* 45 -85 */ CWORD_CWORD_CWORD_CWORD,
2815 /* 46 -84 */ CWORD_CWORD_CWORD_CWORD,
2816 /* 47 -83 */ CWORD_CWORD_CWORD_CWORD,
2817 /* 48 -82 */ CWORD_CWORD_CWORD_CWORD,
2818 /* 49 -81 */ CWORD_CWORD_CWORD_CWORD,
2819 /* 50 -80 */ CWORD_CWORD_CWORD_CWORD,
2820 /* 51 -79 */ CWORD_CWORD_CWORD_CWORD,
2821 /* 52 -78 */ CWORD_CWORD_CWORD_CWORD,
2822 /* 53 -77 */ CWORD_CWORD_CWORD_CWORD,
2823 /* 54 -76 */ CWORD_CWORD_CWORD_CWORD,
2824 /* 55 -75 */ CWORD_CWORD_CWORD_CWORD,
2825 /* 56 -74 */ CWORD_CWORD_CWORD_CWORD,
2826 /* 57 -73 */ CWORD_CWORD_CWORD_CWORD,
2827 /* 58 -72 */ CWORD_CWORD_CWORD_CWORD,
2828 /* 59 -71 */ CWORD_CWORD_CWORD_CWORD,
2829 /* 60 -70 */ CWORD_CWORD_CWORD_CWORD,
2830 /* 61 -69 */ CWORD_CWORD_CWORD_CWORD,
2831 /* 62 -68 */ CWORD_CWORD_CWORD_CWORD,
2832 /* 63 -67 */ CWORD_CWORD_CWORD_CWORD,
2833 /* 64 -66 */ CWORD_CWORD_CWORD_CWORD,
2834 /* 65 -65 */ CWORD_CWORD_CWORD_CWORD,
2835 /* 66 -64 */ CWORD_CWORD_CWORD_CWORD,
2836 /* 67 -63 */ CWORD_CWORD_CWORD_CWORD,
2837 /* 68 -62 */ CWORD_CWORD_CWORD_CWORD,
2838 /* 69 -61 */ CWORD_CWORD_CWORD_CWORD,
2839 /* 70 -60 */ CWORD_CWORD_CWORD_CWORD,
2840 /* 71 -59 */ CWORD_CWORD_CWORD_CWORD,
2841 /* 72 -58 */ CWORD_CWORD_CWORD_CWORD,
2842 /* 73 -57 */ CWORD_CWORD_CWORD_CWORD,
2843 /* 74 -56 */ CWORD_CWORD_CWORD_CWORD,
2844 /* 75 -55 */ CWORD_CWORD_CWORD_CWORD,
2845 /* 76 -54 */ CWORD_CWORD_CWORD_CWORD,
2846 /* 77 -53 */ CWORD_CWORD_CWORD_CWORD,
2847 /* 78 -52 */ CWORD_CWORD_CWORD_CWORD,
2848 /* 79 -51 */ CWORD_CWORD_CWORD_CWORD,
2849 /* 80 -50 */ CWORD_CWORD_CWORD_CWORD,
2850 /* 81 -49 */ CWORD_CWORD_CWORD_CWORD,
2851 /* 82 -48 */ CWORD_CWORD_CWORD_CWORD,
2852 /* 83 -47 */ CWORD_CWORD_CWORD_CWORD,
2853 /* 84 -46 */ CWORD_CWORD_CWORD_CWORD,
2854 /* 85 -45 */ CWORD_CWORD_CWORD_CWORD,
2855 /* 86 -44 */ CWORD_CWORD_CWORD_CWORD,
2856 /* 87 -43 */ CWORD_CWORD_CWORD_CWORD,
2857 /* 88 -42 */ CWORD_CWORD_CWORD_CWORD,
2858 /* 89 -41 */ CWORD_CWORD_CWORD_CWORD,
2859 /* 90 -40 */ CWORD_CWORD_CWORD_CWORD,
2860 /* 91 -39 */ CWORD_CWORD_CWORD_CWORD,
2861 /* 92 -38 */ CWORD_CWORD_CWORD_CWORD,
2862 /* 93 -37 */ CWORD_CWORD_CWORD_CWORD,
2863 /* 94 -36 */ CWORD_CWORD_CWORD_CWORD,
2864 /* 95 -35 */ CWORD_CWORD_CWORD_CWORD,
2865 /* 96 -34 */ CWORD_CWORD_CWORD_CWORD,
2866 /* 97 -33 */ CWORD_CWORD_CWORD_CWORD,
2867 /* 98 -32 */ CWORD_CWORD_CWORD_CWORD,
2868 /* 99 -31 */ CWORD_CWORD_CWORD_CWORD,
2869 /* 100 -30 */ CWORD_CWORD_CWORD_CWORD,
2870 /* 101 -29 */ CWORD_CWORD_CWORD_CWORD,
2871 /* 102 -28 */ CWORD_CWORD_CWORD_CWORD,
2872 /* 103 -27 */ CWORD_CWORD_CWORD_CWORD,
2873 /* 104 -26 */ CWORD_CWORD_CWORD_CWORD,
2874 /* 105 -25 */ CWORD_CWORD_CWORD_CWORD,
2875 /* 106 -24 */ CWORD_CWORD_CWORD_CWORD,
2876 /* 107 -23 */ CWORD_CWORD_CWORD_CWORD,
2877 /* 108 -22 */ CWORD_CWORD_CWORD_CWORD,
2878 /* 109 -21 */ CWORD_CWORD_CWORD_CWORD,
2879 /* 110 -20 */ CWORD_CWORD_CWORD_CWORD,
2880 /* 111 -19 */ CWORD_CWORD_CWORD_CWORD,
2881 /* 112 -18 */ CWORD_CWORD_CWORD_CWORD,
2882 /* 113 -17 */ CWORD_CWORD_CWORD_CWORD,
2883 /* 114 -16 */ CWORD_CWORD_CWORD_CWORD,
2884 /* 115 -15 */ CWORD_CWORD_CWORD_CWORD,
2885 /* 116 -14 */ CWORD_CWORD_CWORD_CWORD,
2886 /* 117 -13 */ CWORD_CWORD_CWORD_CWORD,
2887 /* 118 -12 */ CWORD_CWORD_CWORD_CWORD,
2888 /* 119 -11 */ CWORD_CWORD_CWORD_CWORD,
2889 /* 120 -10 */ CWORD_CWORD_CWORD_CWORD,
2890 /* 121 -9 */ CWORD_CWORD_CWORD_CWORD,
2891 /* 122 -8 */ CWORD_CWORD_CWORD_CWORD,
2892 /* 123 -7 */ CWORD_CWORD_CWORD_CWORD,
2893 /* 124 -6 */ CWORD_CWORD_CWORD_CWORD,
2894 /* 125 -5 */ CWORD_CWORD_CWORD_CWORD,
2895 /* 126 -4 */ CWORD_CWORD_CWORD_CWORD,
2896 /* 127 -3 */ CWORD_CWORD_CWORD_CWORD,
2897 /* 128 -2 */ CWORD_CWORD_CWORD_CWORD,
2898 /* 129 -1 */ CWORD_CWORD_CWORD_CWORD,
2899 /* 130 0 */ CWORD_CWORD_CWORD_CWORD,
2900 /* 131 1 */ CWORD_CWORD_CWORD_CWORD,
2901 /* 132 2 */ CWORD_CWORD_CWORD_CWORD,
2902 /* 133 3 */ CWORD_CWORD_CWORD_CWORD,
2903 /* 134 4 */ CWORD_CWORD_CWORD_CWORD,
2904 /* 135 5 */ CWORD_CWORD_CWORD_CWORD,
2905 /* 136 6 */ CWORD_CWORD_CWORD_CWORD,
2906 /* 137 7 */ CWORD_CWORD_CWORD_CWORD,
2907 /* 138 8 */ CWORD_CWORD_CWORD_CWORD,
2908 /* 139 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
2909 /* 140 10 "\n" */ CNL_CNL_CNL_CNL,
2910 /* 141 11 */ CWORD_CWORD_CWORD_CWORD,
2911 /* 142 12 */ CWORD_CWORD_CWORD_CWORD,
2912 /* 143 13 */ CWORD_CWORD_CWORD_CWORD,
2913 /* 144 14 */ CWORD_CWORD_CWORD_CWORD,
2914 /* 145 15 */ CWORD_CWORD_CWORD_CWORD,
2915 /* 146 16 */ CWORD_CWORD_CWORD_CWORD,
2916 /* 147 17 */ CWORD_CWORD_CWORD_CWORD,
2917 /* 148 18 */ CWORD_CWORD_CWORD_CWORD,
2918 /* 149 19 */ CWORD_CWORD_CWORD_CWORD,
2919 /* 150 20 */ CWORD_CWORD_CWORD_CWORD,
2920 /* 151 21 */ CWORD_CWORD_CWORD_CWORD,
2921 /* 152 22 */ CWORD_CWORD_CWORD_CWORD,
2922 /* 153 23 */ CWORD_CWORD_CWORD_CWORD,
2923 /* 154 24 */ CWORD_CWORD_CWORD_CWORD,
2924 /* 155 25 */ CWORD_CWORD_CWORD_CWORD,
2925 /* 156 26 */ CWORD_CWORD_CWORD_CWORD,
2926 /* 157 27 */ CWORD_CWORD_CWORD_CWORD,
2927 /* 158 28 */ CWORD_CWORD_CWORD_CWORD,
2928 /* 159 29 */ CWORD_CWORD_CWORD_CWORD,
2929 /* 160 30 */ CWORD_CWORD_CWORD_CWORD,
2930 /* 161 31 */ CWORD_CWORD_CWORD_CWORD,
2931 /* 162 32 " " */ CSPCL_CWORD_CWORD_CWORD,
2932 /* 163 33 "!" */ CWORD_CCTL_CCTL_CWORD,
Eric Andersenc470f442003-07-28 09:56:35 +00002933 /* 164 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00002934 /* 165 35 "#" */ CWORD_CWORD_CWORD_CWORD,
2935 /* 166 36 "$" */ CVAR_CVAR_CWORD_CVAR,
2936 /* 167 37 "%" */ CWORD_CWORD_CWORD_CWORD,
2937 /* 168 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
Eric Andersenc470f442003-07-28 09:56:35 +00002938 /* 169 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00002939 /* 170 40 "(" */ CSPCL_CWORD_CWORD_CLP,
2940 /* 171 41 ")" */ CSPCL_CWORD_CWORD_CRP,
2941 /* 172 42 "*" */ CWORD_CCTL_CCTL_CWORD,
2942 /* 173 43 "+" */ CWORD_CWORD_CWORD_CWORD,
2943 /* 174 44 "," */ CWORD_CWORD_CWORD_CWORD,
2944 /* 175 45 "-" */ CWORD_CCTL_CCTL_CWORD,
2945 /* 176 46 "." */ CWORD_CWORD_CWORD_CWORD,
2946 /* 177 47 "/" */ CWORD_CCTL_CCTL_CWORD,
2947 /* 178 48 "0" */ CWORD_CWORD_CWORD_CWORD,
2948 /* 179 49 "1" */ CWORD_CWORD_CWORD_CWORD,
2949 /* 180 50 "2" */ CWORD_CWORD_CWORD_CWORD,
2950 /* 181 51 "3" */ CWORD_CWORD_CWORD_CWORD,
2951 /* 182 52 "4" */ CWORD_CWORD_CWORD_CWORD,
2952 /* 183 53 "5" */ CWORD_CWORD_CWORD_CWORD,
2953 /* 184 54 "6" */ CWORD_CWORD_CWORD_CWORD,
2954 /* 185 55 "7" */ CWORD_CWORD_CWORD_CWORD,
2955 /* 186 56 "8" */ CWORD_CWORD_CWORD_CWORD,
2956 /* 187 57 "9" */ CWORD_CWORD_CWORD_CWORD,
2957 /* 188 58 ":" */ CWORD_CCTL_CCTL_CWORD,
2958 /* 189 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
2959 /* 190 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
2960 /* 191 61 "=" */ CWORD_CCTL_CCTL_CWORD,
2961 /* 192 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
2962 /* 193 63 "?" */ CWORD_CCTL_CCTL_CWORD,
2963 /* 194 64 "@" */ CWORD_CWORD_CWORD_CWORD,
2964 /* 195 65 "A" */ CWORD_CWORD_CWORD_CWORD,
2965 /* 196 66 "B" */ CWORD_CWORD_CWORD_CWORD,
2966 /* 197 67 "C" */ CWORD_CWORD_CWORD_CWORD,
2967 /* 198 68 "D" */ CWORD_CWORD_CWORD_CWORD,
2968 /* 199 69 "E" */ CWORD_CWORD_CWORD_CWORD,
2969 /* 200 70 "F" */ CWORD_CWORD_CWORD_CWORD,
2970 /* 201 71 "G" */ CWORD_CWORD_CWORD_CWORD,
2971 /* 202 72 "H" */ CWORD_CWORD_CWORD_CWORD,
2972 /* 203 73 "I" */ CWORD_CWORD_CWORD_CWORD,
2973 /* 204 74 "J" */ CWORD_CWORD_CWORD_CWORD,
2974 /* 205 75 "K" */ CWORD_CWORD_CWORD_CWORD,
2975 /* 206 76 "L" */ CWORD_CWORD_CWORD_CWORD,
2976 /* 207 77 "M" */ CWORD_CWORD_CWORD_CWORD,
2977 /* 208 78 "N" */ CWORD_CWORD_CWORD_CWORD,
2978 /* 209 79 "O" */ CWORD_CWORD_CWORD_CWORD,
2979 /* 210 80 "P" */ CWORD_CWORD_CWORD_CWORD,
2980 /* 211 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
2981 /* 212 82 "R" */ CWORD_CWORD_CWORD_CWORD,
2982 /* 213 83 "S" */ CWORD_CWORD_CWORD_CWORD,
2983 /* 214 84 "T" */ CWORD_CWORD_CWORD_CWORD,
2984 /* 215 85 "U" */ CWORD_CWORD_CWORD_CWORD,
2985 /* 216 86 "V" */ CWORD_CWORD_CWORD_CWORD,
2986 /* 217 87 "W" */ CWORD_CWORD_CWORD_CWORD,
2987 /* 218 88 "X" */ CWORD_CWORD_CWORD_CWORD,
2988 /* 219 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
2989 /* 220 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
2990 /* 221 91 "[" */ CWORD_CCTL_CCTL_CWORD,
2991 /* 222 92 "\" */ CBACK_CBACK_CCTL_CBACK,
2992 /* 223 93 "]" */ CWORD_CCTL_CCTL_CWORD,
2993 /* 224 94 "^" */ CWORD_CWORD_CWORD_CWORD,
2994 /* 225 95 "_" */ CWORD_CWORD_CWORD_CWORD,
2995 /* 226 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
2996 /* 227 97 "a" */ CWORD_CWORD_CWORD_CWORD,
2997 /* 228 98 "b" */ CWORD_CWORD_CWORD_CWORD,
2998 /* 229 99 "c" */ CWORD_CWORD_CWORD_CWORD,
2999 /* 230 100 "d" */ CWORD_CWORD_CWORD_CWORD,
3000 /* 231 101 "e" */ CWORD_CWORD_CWORD_CWORD,
3001 /* 232 102 "f" */ CWORD_CWORD_CWORD_CWORD,
3002 /* 233 103 "g" */ CWORD_CWORD_CWORD_CWORD,
3003 /* 234 104 "h" */ CWORD_CWORD_CWORD_CWORD,
3004 /* 235 105 "i" */ CWORD_CWORD_CWORD_CWORD,
3005 /* 236 106 "j" */ CWORD_CWORD_CWORD_CWORD,
3006 /* 237 107 "k" */ CWORD_CWORD_CWORD_CWORD,
3007 /* 238 108 "l" */ CWORD_CWORD_CWORD_CWORD,
3008 /* 239 109 "m" */ CWORD_CWORD_CWORD_CWORD,
3009 /* 240 110 "n" */ CWORD_CWORD_CWORD_CWORD,
3010 /* 241 111 "o" */ CWORD_CWORD_CWORD_CWORD,
3011 /* 242 112 "p" */ CWORD_CWORD_CWORD_CWORD,
3012 /* 243 113 "q" */ CWORD_CWORD_CWORD_CWORD,
3013 /* 244 114 "r" */ CWORD_CWORD_CWORD_CWORD,
3014 /* 245 115 "s" */ CWORD_CWORD_CWORD_CWORD,
3015 /* 246 116 "t" */ CWORD_CWORD_CWORD_CWORD,
3016 /* 247 117 "u" */ CWORD_CWORD_CWORD_CWORD,
3017 /* 248 118 "v" */ CWORD_CWORD_CWORD_CWORD,
3018 /* 249 119 "w" */ CWORD_CWORD_CWORD_CWORD,
3019 /* 250 120 "x" */ CWORD_CWORD_CWORD_CWORD,
3020 /* 251 121 "y" */ CWORD_CWORD_CWORD_CWORD,
3021 /* 252 122 "z" */ CWORD_CWORD_CWORD_CWORD,
3022 /* 253 123 "{" */ CWORD_CWORD_CWORD_CWORD,
3023 /* 254 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
3024 /* 255 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
3025 /* 256 126 "~" */ CWORD_CCTL_CCTL_CWORD,
3026 /* 257 127 */ CWORD_CWORD_CWORD_CWORD,
Eric Andersen2870d962001-07-02 17:27:21 +00003027};
3028
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +00003029#define SIT(c, syntax) (S_I_T[(int)syntax_index_table[(int)(c) + SYNBASE]][syntax])
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00003030
"Vladimir N. Oleynik"fdb871c2006-01-25 11:53:47 +00003031#endif /* USE_SIT_FUNCTION */
Eric Andersenc470f442003-07-28 09:56:35 +00003032
Eric Andersen2870d962001-07-02 17:27:21 +00003033
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00003034/* ============ Alias handling */
Denis Vlasenkofc06f292007-02-23 21:09:35 +00003035
Denis Vlasenko131ae172007-02-18 13:00:19 +00003036#if ENABLE_ASH_ALIAS
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00003037
3038#define ALIASINUSE 1
3039#define ALIASDEAD 2
3040
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00003041struct alias {
3042 struct alias *next;
3043 char *name;
3044 char *val;
3045 int flag;
3046};
3047
Denis Vlasenko01631112007-12-16 17:20:38 +00003048
3049static struct alias **atab; // [ATABSIZE];
3050#define INIT_G_alias() do { \
3051 atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
3052} while (0)
3053
Eric Andersen2870d962001-07-02 17:27:21 +00003054
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00003055static struct alias **
3056__lookupalias(const char *name) {
3057 unsigned int hashval;
3058 struct alias **app;
3059 const char *p;
3060 unsigned int ch;
3061
3062 p = name;
3063
3064 ch = (unsigned char)*p;
3065 hashval = ch << 4;
3066 while (ch) {
3067 hashval += ch;
3068 ch = (unsigned char)*++p;
3069 }
3070 app = &atab[hashval % ATABSIZE];
3071
3072 for (; *app; app = &(*app)->next) {
3073 if (strcmp(name, (*app)->name) == 0) {
3074 break;
3075 }
3076 }
3077
3078 return app;
3079}
3080
3081static struct alias *
3082lookupalias(const char *name, int check)
3083{
3084 struct alias *ap = *__lookupalias(name);
3085
3086 if (check && ap && (ap->flag & ALIASINUSE))
3087 return NULL;
3088 return ap;
3089}
3090
3091static struct alias *
3092freealias(struct alias *ap)
3093{
3094 struct alias *next;
3095
3096 if (ap->flag & ALIASINUSE) {
3097 ap->flag |= ALIASDEAD;
3098 return ap;
3099 }
3100
3101 next = ap->next;
3102 free(ap->name);
3103 free(ap->val);
3104 free(ap);
3105 return next;
3106}
Eric Andersencb57d552001-06-28 07:25:16 +00003107
Eric Andersenc470f442003-07-28 09:56:35 +00003108static void
3109setalias(const char *name, const char *val)
Eric Andersencb57d552001-06-28 07:25:16 +00003110{
3111 struct alias *ap, **app;
3112
3113 app = __lookupalias(name);
3114 ap = *app;
Denis Vlasenkob012b102007-02-19 22:43:01 +00003115 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +00003116 if (ap) {
3117 if (!(ap->flag & ALIASINUSE)) {
Denis Vlasenkob012b102007-02-19 22:43:01 +00003118 free(ap->val);
Eric Andersencb57d552001-06-28 07:25:16 +00003119 }
Denis Vlasenko0c032a42007-02-23 01:03:40 +00003120 ap->val = ckstrdup(val);
Eric Andersencb57d552001-06-28 07:25:16 +00003121 ap->flag &= ~ALIASDEAD;
3122 } else {
3123 /* not found */
Denis Vlasenko597906c2008-02-20 16:38:54 +00003124 ap = ckzalloc(sizeof(struct alias));
Denis Vlasenko0c032a42007-02-23 01:03:40 +00003125 ap->name = ckstrdup(name);
3126 ap->val = ckstrdup(val);
Denis Vlasenko597906c2008-02-20 16:38:54 +00003127 /*ap->flag = 0; - ckzalloc did it */
3128 /*ap->next = NULL;*/
Eric Andersencb57d552001-06-28 07:25:16 +00003129 *app = ap;
3130 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00003131 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00003132}
3133
Eric Andersenc470f442003-07-28 09:56:35 +00003134static int
3135unalias(const char *name)
Eric Andersen2870d962001-07-02 17:27:21 +00003136{
Eric Andersencb57d552001-06-28 07:25:16 +00003137 struct alias **app;
3138
3139 app = __lookupalias(name);
3140
3141 if (*app) {
Denis Vlasenkob012b102007-02-19 22:43:01 +00003142 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +00003143 *app = freealias(*app);
Denis Vlasenkob012b102007-02-19 22:43:01 +00003144 INT_ON;
Denis Vlasenko079f8af2006-11-27 16:49:31 +00003145 return 0;
Eric Andersencb57d552001-06-28 07:25:16 +00003146 }
3147
Denis Vlasenko079f8af2006-11-27 16:49:31 +00003148 return 1;
Eric Andersencb57d552001-06-28 07:25:16 +00003149}
3150
Eric Andersenc470f442003-07-28 09:56:35 +00003151static void
3152rmaliases(void)
Eric Andersen2870d962001-07-02 17:27:21 +00003153{
Eric Andersencb57d552001-06-28 07:25:16 +00003154 struct alias *ap, **app;
3155 int i;
3156
Denis Vlasenkob012b102007-02-19 22:43:01 +00003157 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +00003158 for (i = 0; i < ATABSIZE; i++) {
3159 app = &atab[i];
3160 for (ap = *app; ap; ap = *app) {
3161 *app = freealias(*app);
3162 if (ap == *app) {
3163 app = &ap->next;
3164 }
3165 }
3166 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00003167 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00003168}
3169
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00003170static void
3171printalias(const struct alias *ap)
3172{
3173 out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
3174}
3175
Eric Andersencb57d552001-06-28 07:25:16 +00003176/*
3177 * TODO - sort output
3178 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02003179static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00003180aliascmd(int argc UNUSED_PARAM, char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +00003181{
3182 char *n, *v;
3183 int ret = 0;
3184 struct alias *ap;
3185
Denis Vlasenko68404f12008-03-17 09:00:54 +00003186 if (!argv[1]) {
Eric Andersencb57d552001-06-28 07:25:16 +00003187 int i;
3188
Denis Vlasenko68404f12008-03-17 09:00:54 +00003189 for (i = 0; i < ATABSIZE; i++) {
Eric Andersencb57d552001-06-28 07:25:16 +00003190 for (ap = atab[i]; ap; ap = ap->next) {
3191 printalias(ap);
3192 }
Denis Vlasenko68404f12008-03-17 09:00:54 +00003193 }
Denis Vlasenko079f8af2006-11-27 16:49:31 +00003194 return 0;
Eric Andersencb57d552001-06-28 07:25:16 +00003195 }
3196 while ((n = *++argv) != NULL) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00003197 v = strchr(n+1, '=');
3198 if (v == NULL) { /* n+1: funny ksh stuff */
3199 ap = *__lookupalias(n);
3200 if (ap == NULL) {
Eric Andersenc470f442003-07-28 09:56:35 +00003201 fprintf(stderr, "%s: %s not found\n", "alias", n);
Eric Andersencb57d552001-06-28 07:25:16 +00003202 ret = 1;
3203 } else
3204 printalias(ap);
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00003205 } else {
Eric Andersencb57d552001-06-28 07:25:16 +00003206 *v++ = '\0';
3207 setalias(n, v);
3208 }
3209 }
3210
Denis Vlasenkod9e15f22006-11-27 16:49:55 +00003211 return ret;
Eric Andersencb57d552001-06-28 07:25:16 +00003212}
3213
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02003214static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00003215unaliascmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersencb57d552001-06-28 07:25:16 +00003216{
3217 int i;
3218
3219 while ((i = nextopt("a")) != '\0') {
3220 if (i == 'a') {
3221 rmaliases();
Denis Vlasenko079f8af2006-11-27 16:49:31 +00003222 return 0;
Eric Andersencb57d552001-06-28 07:25:16 +00003223 }
3224 }
3225 for (i = 0; *argptr; argptr++) {
3226 if (unalias(*argptr)) {
Eric Andersenc470f442003-07-28 09:56:35 +00003227 fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
Eric Andersencb57d552001-06-28 07:25:16 +00003228 i = 1;
3229 }
3230 }
3231
Denis Vlasenkod9e15f22006-11-27 16:49:55 +00003232 return i;
Eric Andersencb57d552001-06-28 07:25:16 +00003233}
Denis Vlasenkofc06f292007-02-23 21:09:35 +00003234
Denis Vlasenko131ae172007-02-18 13:00:19 +00003235#endif /* ASH_ALIAS */
Eric Andersencb57d552001-06-28 07:25:16 +00003236
Eric Andersenc470f442003-07-28 09:56:35 +00003237
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003238/* ============ jobs.c */
3239
3240/* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
3241#define FORK_FG 0
3242#define FORK_BG 1
3243#define FORK_NOJOB 2
3244
3245/* mode flags for showjob(s) */
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003246#define SHOW_ONLY_PGID 0x01 /* show only pgid (jobs -p) */
3247#define SHOW_PIDS 0x02 /* show individual pids, not just one line per job */
3248#define SHOW_CHANGED 0x04 /* only jobs whose state has changed */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003249
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003250/*
3251 * A job structure contains information about a job. A job is either a
3252 * single process or a set of processes contained in a pipeline. In the
3253 * latter case, pidlist will be non-NULL, and will point to a -1 terminated
3254 * array of pids.
3255 */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003256struct procstat {
3257 pid_t pid; /* process id */
3258 int status; /* last process status from wait() */
3259 char *cmd; /* text of command being run */
3260};
3261
3262struct job {
3263 struct procstat ps0; /* status of process */
3264 struct procstat *ps; /* status or processes when more than one */
3265#if JOBS
3266 int stopstatus; /* status of a stopped job */
3267#endif
3268 uint32_t
3269 nprocs: 16, /* number of processes */
3270 state: 8,
3271#define JOBRUNNING 0 /* at least one proc running */
3272#define JOBSTOPPED 1 /* all procs are stopped */
3273#define JOBDONE 2 /* all procs are completed */
3274#if JOBS
3275 sigint: 1, /* job was killed by SIGINT */
3276 jobctl: 1, /* job running under job control */
3277#endif
3278 waited: 1, /* true if this entry has been waited for */
3279 used: 1, /* true if this entry is in used */
3280 changed: 1; /* true if status has changed */
3281 struct job *prev_job; /* previous job */
3282};
3283
Denis Vlasenko68404f12008-03-17 09:00:54 +00003284static struct job *makejob(/*union node *,*/ int);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003285static int forkshell(struct job *, union node *, int);
3286static int waitforjob(struct job *);
3287
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003288#if !JOBS
Denis Vlasenkob07a4962008-06-22 13:16:23 +00003289enum { doing_jobctl = 0 };
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003290#define setjobctl(on) do {} while (0)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003291#else
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003292static smallint doing_jobctl; //references:8
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003293static void setjobctl(int);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003294#endif
3295
3296/*
Denis Vlasenko4b875702009-03-19 13:30:04 +00003297 * Ignore a signal.
3298 */
3299static void
3300ignoresig(int signo)
3301{
3302 /* Avoid unnecessary system calls. Is it already SIG_IGNed? */
3303 if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
3304 /* No, need to do it */
3305 signal(signo, SIG_IGN);
3306 }
3307 sigmode[signo - 1] = S_HARD_IGN;
3308}
3309
3310/*
3311 * Signal handler. Only one usage site - in setsignal()
3312 */
3313static void
3314onsig(int signo)
3315{
3316 gotsig[signo - 1] = 1;
3317
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02003318 if (signo == SIGINT && !trap[SIGINT]) {
3319 if (!suppress_int) {
3320 pending_sig = 0;
Denis Vlasenko4b875702009-03-19 13:30:04 +00003321 raise_interrupt(); /* does not return */
3322 }
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02003323 pending_int = 1;
Denis Vlasenko4b875702009-03-19 13:30:04 +00003324 } else {
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02003325 pending_sig = signo;
Denis Vlasenko4b875702009-03-19 13:30:04 +00003326 }
3327}
3328
3329/*
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003330 * Set the signal handler for the specified signal. The routine figures
3331 * out what it should be set to.
3332 */
3333static void
3334setsignal(int signo)
3335{
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003336 char *t;
3337 char cur_act, new_act;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003338 struct sigaction act;
3339
3340 t = trap[signo];
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003341 new_act = S_DFL;
3342 if (t != NULL) { /* trap for this sig is set */
3343 new_act = S_CATCH;
3344 if (t[0] == '\0') /* trap is "": ignore this sig */
3345 new_act = S_IGN;
3346 }
3347
3348 if (rootshell && new_act == S_DFL) {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003349 switch (signo) {
3350 case SIGINT:
3351 if (iflag || minusc || sflag == 0)
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003352 new_act = S_CATCH;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003353 break;
3354 case SIGQUIT:
3355#if DEBUG
3356 if (debug)
3357 break;
3358#endif
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003359 /* man bash:
3360 * "In all cases, bash ignores SIGQUIT. Non-builtin
3361 * commands run by bash have signal handlers
3362 * set to the values inherited by the shell
3363 * from its parent". */
3364 new_act = S_IGN;
3365 break;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003366 case SIGTERM:
3367 if (iflag)
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003368 new_act = S_IGN;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003369 break;
3370#if JOBS
3371 case SIGTSTP:
3372 case SIGTTOU:
3373 if (mflag)
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003374 new_act = S_IGN;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003375 break;
3376#endif
3377 }
3378 }
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003379//TODO: if !rootshell, we reset SIGQUIT to DFL,
3380//whereas we have to restore it to what shell got on entry
3381//from the parent. See comment above
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003382
3383 t = &sigmode[signo - 1];
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003384 cur_act = *t;
3385 if (cur_act == 0) {
3386 /* current setting is not yet known */
3387 if (sigaction(signo, NULL, &act)) {
3388 /* pretend it worked; maybe we should give a warning,
3389 * but other shells don't. We don't alter sigmode,
3390 * so we retry every time.
3391 * btw, in Linux it never fails. --vda */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003392 return;
3393 }
3394 if (act.sa_handler == SIG_IGN) {
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003395 cur_act = S_HARD_IGN;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003396 if (mflag
3397 && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
3398 ) {
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003399 cur_act = S_IGN; /* don't hard ignore these */
Denis Vlasenko991a1da2008-02-10 19:02:53 +00003400 }
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003401 }
3402 }
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003403 if (cur_act == S_HARD_IGN || cur_act == new_act)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003404 return;
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003405
Denis Vlasenko991a1da2008-02-10 19:02:53 +00003406 act.sa_handler = SIG_DFL;
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003407 switch (new_act) {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003408 case S_CATCH:
3409 act.sa_handler = onsig;
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003410 act.sa_flags = 0; /* matters only if !DFL and !IGN */
3411 sigfillset(&act.sa_mask); /* ditto */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003412 break;
3413 case S_IGN:
3414 act.sa_handler = SIG_IGN;
3415 break;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003416 }
Denis Vlasenko8e2cfec2008-03-12 23:19:35 +00003417 sigaction_set(signo, &act);
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003418
3419 *t = new_act;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003420}
3421
3422/* mode flags for set_curjob */
3423#define CUR_DELETE 2
3424#define CUR_RUNNING 1
3425#define CUR_STOPPED 0
3426
3427/* mode flags for dowait */
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00003428#define DOWAIT_NONBLOCK WNOHANG
3429#define DOWAIT_BLOCK 0
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003430
3431#if JOBS
3432/* pgrp of shell on invocation */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003433static int initialpgrp; //references:2
3434static int ttyfd = -1; //5
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003435#endif
3436/* array of jobs */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003437static struct job *jobtab; //5
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003438/* size of array */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003439static unsigned njobs; //4
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003440/* current job */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003441static struct job *curjob; //lots
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003442/* number of presumed living untracked jobs */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003443static int jobless; //4
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003444
3445static void
3446set_curjob(struct job *jp, unsigned mode)
3447{
3448 struct job *jp1;
3449 struct job **jpp, **curp;
3450
3451 /* first remove from list */
3452 jpp = curp = &curjob;
3453 do {
3454 jp1 = *jpp;
3455 if (jp1 == jp)
3456 break;
3457 jpp = &jp1->prev_job;
3458 } while (1);
3459 *jpp = jp1->prev_job;
3460
3461 /* Then re-insert in correct position */
3462 jpp = curp;
3463 switch (mode) {
3464 default:
3465#if DEBUG
3466 abort();
3467#endif
3468 case CUR_DELETE:
3469 /* job being deleted */
3470 break;
3471 case CUR_RUNNING:
3472 /* newly created job or backgrounded job,
3473 put after all stopped jobs. */
3474 do {
3475 jp1 = *jpp;
3476#if JOBS
3477 if (!jp1 || jp1->state != JOBSTOPPED)
3478#endif
3479 break;
3480 jpp = &jp1->prev_job;
3481 } while (1);
3482 /* FALLTHROUGH */
3483#if JOBS
3484 case CUR_STOPPED:
3485#endif
3486 /* newly stopped job - becomes curjob */
3487 jp->prev_job = *jpp;
3488 *jpp = jp;
3489 break;
3490 }
3491}
3492
3493#if JOBS || DEBUG
3494static int
3495jobno(const struct job *jp)
3496{
3497 return jp - jobtab + 1;
3498}
3499#endif
3500
3501/*
3502 * Convert a job name to a job structure.
3503 */
Denis Vlasenko85c24712008-03-17 09:04:04 +00003504#if !JOBS
3505#define getjob(name, getctl) getjob(name)
3506#endif
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003507static struct job *
3508getjob(const char *name, int getctl)
3509{
3510 struct job *jp;
3511 struct job *found;
Denys Vlasenkoffc39202009-08-17 02:12:20 +02003512 const char *err_msg = "%s: no such job";
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003513 unsigned num;
3514 int c;
3515 const char *p;
3516 char *(*match)(const char *, const char *);
3517
3518 jp = curjob;
3519 p = name;
3520 if (!p)
3521 goto currentjob;
3522
3523 if (*p != '%')
3524 goto err;
3525
3526 c = *++p;
3527 if (!c)
3528 goto currentjob;
3529
3530 if (!p[1]) {
3531 if (c == '+' || c == '%') {
3532 currentjob:
3533 err_msg = "No current job";
3534 goto check;
3535 }
3536 if (c == '-') {
3537 if (jp)
3538 jp = jp->prev_job;
3539 err_msg = "No previous job";
3540 check:
3541 if (!jp)
3542 goto err;
3543 goto gotit;
3544 }
3545 }
3546
3547 if (is_number(p)) {
3548 num = atoi(p);
3549 if (num < njobs) {
3550 jp = jobtab + num - 1;
3551 if (jp->used)
3552 goto gotit;
3553 goto err;
3554 }
3555 }
3556
3557 match = prefix;
3558 if (*p == '?') {
3559 match = strstr;
3560 p++;
3561 }
3562
Denys Vlasenkoffc39202009-08-17 02:12:20 +02003563 found = NULL;
3564 while (jp) {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003565 if (match(jp->ps[0].cmd, p)) {
3566 if (found)
3567 goto err;
3568 found = jp;
3569 err_msg = "%s: ambiguous";
3570 }
3571 jp = jp->prev_job;
3572 }
Denys Vlasenkoffc39202009-08-17 02:12:20 +02003573 if (!found)
3574 goto err;
3575 jp = found;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003576
3577 gotit:
3578#if JOBS
3579 err_msg = "job %s not created under job control";
3580 if (getctl && jp->jobctl == 0)
3581 goto err;
3582#endif
3583 return jp;
3584 err:
3585 ash_msg_and_raise_error(err_msg, name);
3586}
3587
3588/*
3589 * Mark a job structure as unused.
3590 */
3591static void
3592freejob(struct job *jp)
3593{
3594 struct procstat *ps;
3595 int i;
3596
3597 INT_OFF;
3598 for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
3599 if (ps->cmd != nullstr)
3600 free(ps->cmd);
3601 }
3602 if (jp->ps != &jp->ps0)
3603 free(jp->ps);
3604 jp->used = 0;
3605 set_curjob(jp, CUR_DELETE);
3606 INT_ON;
3607}
3608
3609#if JOBS
3610static void
3611xtcsetpgrp(int fd, pid_t pgrp)
3612{
3613 if (tcsetpgrp(fd, pgrp))
Bernhard Reutner-Fischera53de7f2008-07-21 13:46:54 +00003614 ash_msg_and_raise_error("can't set tty process group (%m)");
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003615}
3616
3617/*
3618 * Turn job control on and off.
3619 *
3620 * Note: This code assumes that the third arg to ioctl is a character
3621 * pointer, which is true on Berkeley systems but not System V. Since
3622 * System V doesn't have job control yet, this isn't a problem now.
3623 *
3624 * Called with interrupts off.
3625 */
3626static void
3627setjobctl(int on)
3628{
3629 int fd;
3630 int pgrp;
3631
Denis Vlasenkob07a4962008-06-22 13:16:23 +00003632 if (on == doing_jobctl || rootshell == 0)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003633 return;
3634 if (on) {
3635 int ofd;
3636 ofd = fd = open(_PATH_TTY, O_RDWR);
3637 if (fd < 0) {
3638 /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
3639 * That sometimes helps to acquire controlling tty.
3640 * Obviously, a workaround for bugs when someone
3641 * failed to provide a controlling tty to bash! :) */
Denis Vlasenkoed270a52007-11-26 05:37:07 +00003642 fd = 2;
3643 while (!isatty(fd))
3644 if (--fd < 0)
3645 goto out;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003646 }
3647 fd = fcntl(fd, F_DUPFD, 10);
Denis Vlasenkoed270a52007-11-26 05:37:07 +00003648 if (ofd >= 0)
3649 close(ofd);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003650 if (fd < 0)
3651 goto out;
Denis Vlasenkoed270a52007-11-26 05:37:07 +00003652 /* fd is a tty at this point */
Denis Vlasenko96e1b382007-09-30 23:50:48 +00003653 close_on_exec_on(fd);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003654 do { /* while we are in the background */
3655 pgrp = tcgetpgrp(fd);
3656 if (pgrp < 0) {
3657 out:
3658 ash_msg("can't access tty; job control turned off");
3659 mflag = on = 0;
3660 goto close;
3661 }
3662 if (pgrp == getpgrp())
3663 break;
3664 killpg(0, SIGTTIN);
3665 } while (1);
3666 initialpgrp = pgrp;
3667
3668 setsignal(SIGTSTP);
3669 setsignal(SIGTTOU);
3670 setsignal(SIGTTIN);
3671 pgrp = rootpid;
3672 setpgid(0, pgrp);
3673 xtcsetpgrp(fd, pgrp);
3674 } else {
3675 /* turning job control off */
3676 fd = ttyfd;
3677 pgrp = initialpgrp;
Denis Vlasenko08c8c1d2007-04-28 22:39:02 +00003678 /* was xtcsetpgrp, but this can make exiting ash
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00003679 * loop forever if pty is already deleted */
Denis Vlasenko08c8c1d2007-04-28 22:39:02 +00003680 tcsetpgrp(fd, pgrp);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003681 setpgid(0, pgrp);
3682 setsignal(SIGTSTP);
3683 setsignal(SIGTTOU);
3684 setsignal(SIGTTIN);
3685 close:
Denis Vlasenkoed270a52007-11-26 05:37:07 +00003686 if (fd >= 0)
3687 close(fd);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003688 fd = -1;
3689 }
3690 ttyfd = fd;
Denis Vlasenkob07a4962008-06-22 13:16:23 +00003691 doing_jobctl = on;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003692}
3693
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02003694static int FAST_FUNC
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003695killcmd(int argc, char **argv)
3696{
Denis Vlasenko68404f12008-03-17 09:00:54 +00003697 int i = 1;
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003698 if (argv[1] && strcmp(argv[1], "-l") != 0) {
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003699 do {
3700 if (argv[i][0] == '%') {
3701 struct job *jp = getjob(argv[i], 0);
3702 unsigned pid = jp->ps[0].pid;
3703 /* Enough space for ' -NNN<nul>' */
3704 argv[i] = alloca(sizeof(int)*3 + 3);
3705 /* kill_main has matching code to expect
3706 * leading space. Needed to not confuse
3707 * negative pids with "kill -SIGNAL_NO" syntax */
3708 sprintf(argv[i], " -%u", pid);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003709 }
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003710 } while (argv[++i]);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003711 }
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003712 return kill_main(argc, argv);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003713}
3714
3715static void
3716showpipe(struct job *jp, FILE *out)
3717{
3718 struct procstat *sp;
3719 struct procstat *spend;
3720
3721 spend = jp->ps + jp->nprocs;
3722 for (sp = jp->ps + 1; sp < spend; sp++)
3723 fprintf(out, " | %s", sp->cmd);
3724 outcslow('\n', out);
3725 flush_stdout_stderr();
3726}
3727
3728
3729static int
3730restartjob(struct job *jp, int mode)
3731{
3732 struct procstat *ps;
3733 int i;
3734 int status;
3735 pid_t pgid;
3736
3737 INT_OFF;
3738 if (jp->state == JOBDONE)
3739 goto out;
3740 jp->state = JOBRUNNING;
3741 pgid = jp->ps->pid;
3742 if (mode == FORK_FG)
3743 xtcsetpgrp(ttyfd, pgid);
3744 killpg(pgid, SIGCONT);
3745 ps = jp->ps;
3746 i = jp->nprocs;
3747 do {
3748 if (WIFSTOPPED(ps->status)) {
3749 ps->status = -1;
3750 }
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003751 ps++;
3752 } while (--i);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003753 out:
3754 status = (mode == FORK_FG) ? waitforjob(jp) : 0;
3755 INT_ON;
3756 return status;
3757}
3758
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02003759static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00003760fg_bgcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003761{
3762 struct job *jp;
3763 FILE *out;
3764 int mode;
3765 int retval;
3766
3767 mode = (**argv == 'f') ? FORK_FG : FORK_BG;
3768 nextopt(nullstr);
3769 argv = argptr;
3770 out = stdout;
3771 do {
3772 jp = getjob(*argv, 1);
3773 if (mode == FORK_BG) {
3774 set_curjob(jp, CUR_RUNNING);
3775 fprintf(out, "[%d] ", jobno(jp));
3776 }
3777 outstr(jp->ps->cmd, out);
3778 showpipe(jp, out);
3779 retval = restartjob(jp, mode);
3780 } while (*argv && *++argv);
3781 return retval;
3782}
3783#endif
3784
3785static int
3786sprint_status(char *s, int status, int sigonly)
3787{
3788 int col;
3789 int st;
3790
3791 col = 0;
3792 if (!WIFEXITED(status)) {
3793#if JOBS
3794 if (WIFSTOPPED(status))
3795 st = WSTOPSIG(status);
3796 else
3797#endif
3798 st = WTERMSIG(status);
3799 if (sigonly) {
3800 if (st == SIGINT || st == SIGPIPE)
3801 goto out;
3802#if JOBS
3803 if (WIFSTOPPED(status))
3804 goto out;
3805#endif
3806 }
3807 st &= 0x7f;
3808 col = fmtstr(s, 32, strsignal(st));
3809 if (WCOREDUMP(status)) {
3810 col += fmtstr(s + col, 16, " (core dumped)");
3811 }
3812 } else if (!sigonly) {
3813 st = WEXITSTATUS(status);
3814 if (st)
3815 col = fmtstr(s, 16, "Done(%d)", st);
3816 else
3817 col = fmtstr(s, 16, "Done");
3818 }
3819 out:
3820 return col;
3821}
3822
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003823static int
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00003824dowait(int wait_flags, struct job *job)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003825{
3826 int pid;
3827 int status;
3828 struct job *jp;
3829 struct job *thisjob;
3830 int state;
3831
Denis Vlasenkobe54d6b2008-10-27 14:25:52 +00003832 TRACE(("dowait(0x%x) called\n", wait_flags));
3833
3834 /* Do a wait system call. If job control is compiled in, we accept
3835 * stopped processes. wait_flags may have WNOHANG, preventing blocking.
3836 * NB: _not_ safe_waitpid, we need to detect EINTR */
3837 pid = waitpid(-1, &status,
3838 (doing_jobctl ? (wait_flags | WUNTRACED) : wait_flags));
Denis Vlasenkob21f3792009-03-19 23:09:58 +00003839 TRACE(("wait returns pid=%d, status=0x%x, errno=%d(%s)\n",
3840 pid, status, errno, strerror(errno)));
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003841 if (pid <= 0)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003842 return pid;
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003843
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003844 INT_OFF;
3845 thisjob = NULL;
3846 for (jp = curjob; jp; jp = jp->prev_job) {
3847 struct procstat *sp;
3848 struct procstat *spend;
3849 if (jp->state == JOBDONE)
3850 continue;
3851 state = JOBDONE;
3852 spend = jp->ps + jp->nprocs;
3853 sp = jp->ps;
3854 do {
3855 if (sp->pid == pid) {
3856 TRACE(("Job %d: changing status of proc %d "
3857 "from 0x%x to 0x%x\n",
3858 jobno(jp), pid, sp->status, status));
3859 sp->status = status;
3860 thisjob = jp;
3861 }
3862 if (sp->status == -1)
3863 state = JOBRUNNING;
3864#if JOBS
3865 if (state == JOBRUNNING)
3866 continue;
3867 if (WIFSTOPPED(sp->status)) {
3868 jp->stopstatus = sp->status;
3869 state = JOBSTOPPED;
3870 }
3871#endif
3872 } while (++sp < spend);
3873 if (thisjob)
3874 goto gotjob;
3875 }
3876#if JOBS
3877 if (!WIFSTOPPED(status))
3878#endif
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003879 jobless--;
3880 goto out;
3881
3882 gotjob:
3883 if (state != JOBRUNNING) {
3884 thisjob->changed = 1;
3885
3886 if (thisjob->state != state) {
3887 TRACE(("Job %d: changing state from %d to %d\n",
3888 jobno(thisjob), thisjob->state, state));
3889 thisjob->state = state;
3890#if JOBS
3891 if (state == JOBSTOPPED) {
3892 set_curjob(thisjob, CUR_STOPPED);
3893 }
3894#endif
3895 }
3896 }
3897
3898 out:
3899 INT_ON;
3900
3901 if (thisjob && thisjob == job) {
3902 char s[48 + 1];
3903 int len;
3904
3905 len = sprint_status(s, status, 1);
3906 if (len) {
3907 s[len] = '\n';
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00003908 s[len + 1] = '\0';
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003909 out2str(s);
3910 }
3911 }
3912 return pid;
3913}
3914
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003915static int
3916blocking_wait_with_raise_on_sig(struct job *job)
3917{
3918 pid_t pid = dowait(DOWAIT_BLOCK, job);
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02003919 if (pid <= 0 && pending_sig)
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003920 raise_exception(EXSIG);
3921 return pid;
3922}
3923
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003924#if JOBS
3925static void
3926showjob(FILE *out, struct job *jp, int mode)
3927{
3928 struct procstat *ps;
3929 struct procstat *psend;
3930 int col;
Denis Vlasenko40ba9982007-07-14 00:48:29 +00003931 int indent_col;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003932 char s[80];
3933
3934 ps = jp->ps;
3935
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003936 if (mode & SHOW_ONLY_PGID) { /* jobs -p */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003937 /* just output process (group) id of pipeline */
3938 fprintf(out, "%d\n", ps->pid);
3939 return;
3940 }
3941
3942 col = fmtstr(s, 16, "[%d] ", jobno(jp));
Denis Vlasenko40ba9982007-07-14 00:48:29 +00003943 indent_col = col;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003944
3945 if (jp == curjob)
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003946 s[col - 3] = '+';
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003947 else if (curjob && jp == curjob->prev_job)
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003948 s[col - 3] = '-';
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003949
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003950 if (mode & SHOW_PIDS)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003951 col += fmtstr(s + col, 16, "%d ", ps->pid);
3952
3953 psend = ps + jp->nprocs;
3954
3955 if (jp->state == JOBRUNNING) {
3956 strcpy(s + col, "Running");
3957 col += sizeof("Running") - 1;
3958 } else {
3959 int status = psend[-1].status;
3960 if (jp->state == JOBSTOPPED)
3961 status = jp->stopstatus;
3962 col += sprint_status(s + col, status, 0);
3963 }
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003964 /* By now, "[JOBID]* [maybe PID] STATUS" is printed */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003965
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003966 /* This loop either prints "<cmd1> | <cmd2> | <cmd3>" line
3967 * or prints several "PID | <cmdN>" lines,
3968 * depending on SHOW_PIDS bit.
3969 * We do not print status of individual processes
3970 * between PID and <cmdN>. bash does it, but not very well:
3971 * first line shows overall job status, not process status,
3972 * making it impossible to know 1st process status.
3973 */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003974 goto start;
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003975 while (1) {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003976 /* for each process */
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003977 s[0] = '\0';
3978 col = 33;
3979 if (mode & SHOW_PIDS)
3980 col = fmtstr(s, 48, "\n%*c%d ", indent_col, ' ', ps->pid) - 1;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003981 start:
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003982 fprintf(out, "%s%*c", s, 33 - col >= 0 ? 33 - col : 0, ' ');
3983 if (ps != jp->ps)
3984 fprintf(out, "| ");
3985 fprintf(out, "%s", ps->cmd);
3986 if (++ps == psend)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003987 break;
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003988 }
3989 outcslow('\n', out);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003990
3991 jp->changed = 0;
3992
3993 if (jp->state == JOBDONE) {
3994 TRACE(("showjob: freeing job %d\n", jobno(jp)));
3995 freejob(jp);
3996 }
3997}
3998
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003999/*
4000 * Print a list of jobs. If "change" is nonzero, only print jobs whose
4001 * statuses have changed since the last call to showjobs.
4002 */
4003static void
4004showjobs(FILE *out, int mode)
4005{
4006 struct job *jp;
4007
Denys Vlasenko883cea42009-07-11 15:31:59 +02004008 TRACE(("showjobs(0x%x) called\n", mode));
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004009
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004010 /* Handle all finished jobs */
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00004011 while (dowait(DOWAIT_NONBLOCK, NULL) > 0)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004012 continue;
4013
4014 for (jp = curjob; jp; jp = jp->prev_job) {
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00004015 if (!(mode & SHOW_CHANGED) || jp->changed) {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004016 showjob(out, jp, mode);
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00004017 }
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004018 }
4019}
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00004020
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02004021static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00004022jobscmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00004023{
4024 int mode, m;
4025
4026 mode = 0;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02004027 while ((m = nextopt("lp")) != '\0') {
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00004028 if (m == 'l')
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02004029 mode |= SHOW_PIDS;
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00004030 else
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02004031 mode |= SHOW_ONLY_PGID;
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00004032 }
4033
4034 argv = argptr;
4035 if (*argv) {
4036 do
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02004037 showjob(stdout, getjob(*argv, 0), mode);
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00004038 while (*++argv);
4039 } else
4040 showjobs(stdout, mode);
4041
4042 return 0;
4043}
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004044#endif /* JOBS */
4045
4046static int
4047getstatus(struct job *job)
4048{
4049 int status;
4050 int retval;
4051
4052 status = job->ps[job->nprocs - 1].status;
4053 retval = WEXITSTATUS(status);
4054 if (!WIFEXITED(status)) {
4055#if JOBS
4056 retval = WSTOPSIG(status);
4057 if (!WIFSTOPPED(status))
4058#endif
4059 {
4060 /* XXX: limits number of signals */
4061 retval = WTERMSIG(status);
4062#if JOBS
4063 if (retval == SIGINT)
4064 job->sigint = 1;
4065#endif
4066 }
4067 retval += 128;
4068 }
Denys Vlasenko883cea42009-07-11 15:31:59 +02004069 TRACE(("getstatus: job %d, nproc %d, status 0x%x, retval 0x%x\n",
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004070 jobno(job), job->nprocs, status, retval));
4071 return retval;
4072}
4073
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02004074static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00004075waitcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004076{
4077 struct job *job;
4078 int retval;
4079 struct job *jp;
4080
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02004081 if (pending_sig)
Denis Vlasenko991a1da2008-02-10 19:02:53 +00004082 raise_exception(EXSIG);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004083
4084 nextopt(nullstr);
4085 retval = 0;
4086
4087 argv = argptr;
4088 if (!*argv) {
4089 /* wait for all jobs */
4090 for (;;) {
4091 jp = curjob;
4092 while (1) {
Denis Vlasenko991a1da2008-02-10 19:02:53 +00004093 if (!jp) /* no running procs */
4094 goto ret;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004095 if (jp->state == JOBRUNNING)
4096 break;
4097 jp->waited = 1;
4098 jp = jp->prev_job;
4099 }
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004100 /* man bash:
4101 * "When bash is waiting for an asynchronous command via
4102 * the wait builtin, the reception of a signal for which a trap
4103 * has been set will cause the wait builtin to return immediately
4104 * with an exit status greater than 128, immediately after which
4105 * the trap is executed."
4106 * Do we do it that way? */
4107 blocking_wait_with_raise_on_sig(NULL);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004108 }
4109 }
4110
4111 retval = 127;
4112 do {
4113 if (**argv != '%') {
4114 pid_t pid = number(*argv);
4115 job = curjob;
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00004116 while (1) {
4117 if (!job)
4118 goto repeat;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004119 if (job->ps[job->nprocs - 1].pid == pid)
4120 break;
4121 job = job->prev_job;
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00004122 }
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004123 } else
4124 job = getjob(*argv, 0);
4125 /* loop until process terminated or stopped */
4126 while (job->state == JOBRUNNING)
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004127 blocking_wait_with_raise_on_sig(NULL);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004128 job->waited = 1;
4129 retval = getstatus(job);
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004130 repeat: ;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004131 } while (*++argv);
4132
Denis Vlasenko991a1da2008-02-10 19:02:53 +00004133 ret:
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004134 return retval;
4135}
4136
4137static struct job *
4138growjobtab(void)
4139{
4140 size_t len;
4141 ptrdiff_t offset;
4142 struct job *jp, *jq;
4143
4144 len = njobs * sizeof(*jp);
4145 jq = jobtab;
4146 jp = ckrealloc(jq, len + 4 * sizeof(*jp));
4147
4148 offset = (char *)jp - (char *)jq;
4149 if (offset) {
4150 /* Relocate pointers */
4151 size_t l = len;
4152
4153 jq = (struct job *)((char *)jq + l);
4154 while (l) {
4155 l -= sizeof(*jp);
4156 jq--;
4157#define joff(p) ((struct job *)((char *)(p) + l))
4158#define jmove(p) (p) = (void *)((char *)(p) + offset)
4159 if (joff(jp)->ps == &jq->ps0)
4160 jmove(joff(jp)->ps);
4161 if (joff(jp)->prev_job)
4162 jmove(joff(jp)->prev_job);
4163 }
4164 if (curjob)
4165 jmove(curjob);
4166#undef joff
4167#undef jmove
4168 }
4169
4170 njobs += 4;
4171 jobtab = jp;
4172 jp = (struct job *)((char *)jp + len);
4173 jq = jp + 3;
4174 do {
4175 jq->used = 0;
4176 } while (--jq >= jp);
4177 return jp;
4178}
4179
4180/*
4181 * Return a new job structure.
4182 * Called with interrupts off.
4183 */
4184static struct job *
Denis Vlasenko68404f12008-03-17 09:00:54 +00004185makejob(/*union node *node,*/ int nprocs)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004186{
4187 int i;
4188 struct job *jp;
4189
4190 for (i = njobs, jp = jobtab; ; jp++) {
4191 if (--i < 0) {
4192 jp = growjobtab();
4193 break;
4194 }
4195 if (jp->used == 0)
4196 break;
4197 if (jp->state != JOBDONE || !jp->waited)
4198 continue;
4199#if JOBS
Denis Vlasenkob07a4962008-06-22 13:16:23 +00004200 if (doing_jobctl)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004201 continue;
4202#endif
4203 freejob(jp);
4204 break;
4205 }
4206 memset(jp, 0, sizeof(*jp));
4207#if JOBS
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00004208 /* jp->jobctl is a bitfield.
4209 * "jp->jobctl |= jobctl" likely to give awful code */
Denis Vlasenkob07a4962008-06-22 13:16:23 +00004210 if (doing_jobctl)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004211 jp->jobctl = 1;
4212#endif
4213 jp->prev_job = curjob;
4214 curjob = jp;
4215 jp->used = 1;
4216 jp->ps = &jp->ps0;
4217 if (nprocs > 1) {
4218 jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
4219 }
Denis Vlasenko68404f12008-03-17 09:00:54 +00004220 TRACE(("makejob(%d) returns %%%d\n", nprocs,
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004221 jobno(jp)));
4222 return jp;
4223}
4224
4225#if JOBS
4226/*
4227 * Return a string identifying a command (to be printed by the
4228 * jobs command).
4229 */
4230static char *cmdnextc;
4231
4232static void
4233cmdputs(const char *s)
4234{
Denis Vlasenko92e13c22008-03-25 01:17:40 +00004235 static const char vstype[VSTYPE + 1][3] = {
4236 "", "}", "-", "+", "?", "=",
4237 "%", "%%", "#", "##"
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00004238 IF_ASH_BASH_COMPAT(, ":", "/", "//")
Denis Vlasenko92e13c22008-03-25 01:17:40 +00004239 };
4240
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004241 const char *p, *str;
4242 char c, cc[2] = " ";
4243 char *nextc;
4244 int subtype = 0;
4245 int quoted = 0;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004246
4247 nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
4248 p = s;
4249 while ((c = *p++) != 0) {
Denis Vlasenkoef527f52008-06-23 01:52:30 +00004250 str = NULL;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004251 switch (c) {
4252 case CTLESC:
4253 c = *p++;
4254 break;
4255 case CTLVAR:
4256 subtype = *p++;
4257 if ((subtype & VSTYPE) == VSLENGTH)
4258 str = "${#";
4259 else
4260 str = "${";
4261 if (!(subtype & VSQUOTE) == !(quoted & 1))
4262 goto dostr;
4263 quoted ^= 1;
4264 c = '"';
4265 break;
4266 case CTLENDVAR:
4267 str = "\"}" + !(quoted & 1);
4268 quoted >>= 1;
4269 subtype = 0;
4270 goto dostr;
4271 case CTLBACKQ:
4272 str = "$(...)";
4273 goto dostr;
4274 case CTLBACKQ+CTLQUOTE:
4275 str = "\"$(...)\"";
4276 goto dostr;
Mike Frysinger98c52642009-04-02 10:02:37 +00004277#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004278 case CTLARI:
4279 str = "$((";
4280 goto dostr;
4281 case CTLENDARI:
4282 str = "))";
4283 goto dostr;
4284#endif
4285 case CTLQUOTEMARK:
4286 quoted ^= 1;
4287 c = '"';
4288 break;
4289 case '=':
4290 if (subtype == 0)
4291 break;
4292 if ((subtype & VSTYPE) != VSNORMAL)
4293 quoted <<= 1;
4294 str = vstype[subtype & VSTYPE];
4295 if (subtype & VSNUL)
4296 c = ':';
4297 else
4298 goto checkstr;
4299 break;
4300 case '\'':
4301 case '\\':
4302 case '"':
4303 case '$':
4304 /* These can only happen inside quotes */
4305 cc[0] = c;
4306 str = cc;
4307 c = '\\';
4308 break;
4309 default:
4310 break;
4311 }
4312 USTPUTC(c, nextc);
4313 checkstr:
4314 if (!str)
4315 continue;
4316 dostr:
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02004317 while ((c = *str++) != '\0') {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004318 USTPUTC(c, nextc);
4319 }
4320 }
4321 if (quoted & 1) {
4322 USTPUTC('"', nextc);
4323 }
4324 *nextc = 0;
4325 cmdnextc = nextc;
4326}
4327
4328/* cmdtxt() and cmdlist() call each other */
4329static void cmdtxt(union node *n);
4330
4331static void
4332cmdlist(union node *np, int sep)
4333{
4334 for (; np; np = np->narg.next) {
4335 if (!sep)
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00004336 cmdputs(" ");
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004337 cmdtxt(np);
4338 if (sep && np->narg.next)
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00004339 cmdputs(" ");
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004340 }
4341}
4342
4343static void
4344cmdtxt(union node *n)
4345{
4346 union node *np;
4347 struct nodelist *lp;
4348 const char *p;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004349
4350 if (!n)
4351 return;
4352 switch (n->type) {
4353 default:
4354#if DEBUG
4355 abort();
4356#endif
4357 case NPIPE:
4358 lp = n->npipe.cmdlist;
4359 for (;;) {
4360 cmdtxt(lp->n);
4361 lp = lp->next;
4362 if (!lp)
4363 break;
4364 cmdputs(" | ");
4365 }
4366 break;
4367 case NSEMI:
4368 p = "; ";
4369 goto binop;
4370 case NAND:
4371 p = " && ";
4372 goto binop;
4373 case NOR:
4374 p = " || ";
4375 binop:
4376 cmdtxt(n->nbinary.ch1);
4377 cmdputs(p);
4378 n = n->nbinary.ch2;
4379 goto donode;
4380 case NREDIR:
4381 case NBACKGND:
4382 n = n->nredir.n;
4383 goto donode;
4384 case NNOT:
4385 cmdputs("!");
4386 n = n->nnot.com;
4387 donode:
4388 cmdtxt(n);
4389 break;
4390 case NIF:
4391 cmdputs("if ");
4392 cmdtxt(n->nif.test);
4393 cmdputs("; then ");
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004394 if (n->nif.elsepart) {
Denys Vlasenko7cee00e2009-07-24 01:08:03 +02004395 cmdtxt(n->nif.ifpart);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004396 cmdputs("; else ");
4397 n = n->nif.elsepart;
Denys Vlasenko7cee00e2009-07-24 01:08:03 +02004398 } else {
4399 n = n->nif.ifpart;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004400 }
4401 p = "; fi";
4402 goto dotail;
4403 case NSUBSHELL:
4404 cmdputs("(");
4405 n = n->nredir.n;
4406 p = ")";
4407 goto dotail;
4408 case NWHILE:
4409 p = "while ";
4410 goto until;
4411 case NUNTIL:
4412 p = "until ";
4413 until:
4414 cmdputs(p);
4415 cmdtxt(n->nbinary.ch1);
4416 n = n->nbinary.ch2;
4417 p = "; done";
4418 dodo:
4419 cmdputs("; do ");
4420 dotail:
4421 cmdtxt(n);
4422 goto dotail2;
4423 case NFOR:
4424 cmdputs("for ");
4425 cmdputs(n->nfor.var);
4426 cmdputs(" in ");
4427 cmdlist(n->nfor.args, 1);
4428 n = n->nfor.body;
4429 p = "; done";
4430 goto dodo;
4431 case NDEFUN:
4432 cmdputs(n->narg.text);
4433 p = "() { ... }";
4434 goto dotail2;
4435 case NCMD:
4436 cmdlist(n->ncmd.args, 1);
4437 cmdlist(n->ncmd.redirect, 0);
4438 break;
4439 case NARG:
4440 p = n->narg.text;
4441 dotail2:
4442 cmdputs(p);
4443 break;
4444 case NHERE:
4445 case NXHERE:
4446 p = "<<...";
4447 goto dotail2;
4448 case NCASE:
4449 cmdputs("case ");
4450 cmdputs(n->ncase.expr->narg.text);
4451 cmdputs(" in ");
4452 for (np = n->ncase.cases; np; np = np->nclist.next) {
4453 cmdtxt(np->nclist.pattern);
4454 cmdputs(") ");
4455 cmdtxt(np->nclist.body);
4456 cmdputs(";; ");
4457 }
4458 p = "esac";
4459 goto dotail2;
4460 case NTO:
4461 p = ">";
4462 goto redir;
4463 case NCLOBBER:
4464 p = ">|";
4465 goto redir;
4466 case NAPPEND:
4467 p = ">>";
4468 goto redir;
Denis Vlasenko559691a2008-10-05 18:39:31 +00004469#if ENABLE_ASH_BASH_COMPAT
4470 case NTO2:
4471#endif
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004472 case NTOFD:
4473 p = ">&";
4474 goto redir;
4475 case NFROM:
4476 p = "<";
4477 goto redir;
4478 case NFROMFD:
4479 p = "<&";
4480 goto redir;
4481 case NFROMTO:
4482 p = "<>";
4483 redir:
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00004484 cmdputs(utoa(n->nfile.fd));
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004485 cmdputs(p);
4486 if (n->type == NTOFD || n->type == NFROMFD) {
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00004487 cmdputs(utoa(n->ndup.dupfd));
4488 break;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004489 }
4490 n = n->nfile.fname;
4491 goto donode;
4492 }
4493}
4494
4495static char *
4496commandtext(union node *n)
4497{
4498 char *name;
4499
4500 STARTSTACKSTR(cmdnextc);
4501 cmdtxt(n);
4502 name = stackblock();
4503 TRACE(("commandtext: name %p, end %p\n\t\"%s\"\n",
4504 name, cmdnextc, cmdnextc));
4505 return ckstrdup(name);
4506}
4507#endif /* JOBS */
4508
4509/*
4510 * Fork off a subshell. If we are doing job control, give the subshell its
4511 * own process group. Jp is a job structure that the job is to be added to.
4512 * N is the command that will be evaluated by the child. Both jp and n may
4513 * be NULL. The mode parameter can be one of the following:
4514 * FORK_FG - Fork off a foreground process.
4515 * FORK_BG - Fork off a background process.
4516 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
4517 * process group even if job control is on.
4518 *
4519 * When job control is turned off, background processes have their standard
4520 * input redirected to /dev/null (except for the second and later processes
4521 * in a pipeline).
4522 *
4523 * Called with interrupts off.
4524 */
4525/*
4526 * Clear traps on a fork.
4527 */
4528static void
4529clear_traps(void)
4530{
4531 char **tp;
4532
4533 for (tp = trap; tp < &trap[NSIG]; tp++) {
Denis Vlasenko991a1da2008-02-10 19:02:53 +00004534 if (*tp && **tp) { /* trap not NULL or "" (SIG_IGN) */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004535 INT_OFF;
Denys Vlasenkoe305c282009-09-25 02:12:27 +02004536 if (trap_ptr == trap)
4537 free(*tp);
4538 /* else: it "belongs" to trap_ptr vector, don't free */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004539 *tp = NULL;
Denys Vlasenko0800e3a2009-09-24 03:09:26 +02004540 if ((tp - trap) != 0)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004541 setsignal(tp - trap);
4542 INT_ON;
4543 }
4544 }
4545}
Denis Vlasenkobdc406d2007-07-15 01:13:25 +00004546
4547/* Lives far away from here, needed for forkchild */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004548static void closescript(void);
Denis Vlasenko41770222007-10-07 18:02:52 +00004549
Denis Vlasenkobdc406d2007-07-15 01:13:25 +00004550/* Called after fork(), in child */
Denys Vlasenko21d87d42009-09-25 00:06:51 +02004551static NOINLINE void
Denys Vlasenkoe56f22a2009-07-24 00:16:59 +02004552forkchild(struct job *jp, union node *n, int mode)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004553{
4554 int oldlvl;
4555
4556 TRACE(("Child shell %d\n", getpid()));
4557 oldlvl = shlvl;
4558 shlvl++;
4559
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004560 /* man bash: "Non-builtin commands run by bash have signal handlers
4561 * set to the values inherited by the shell from its parent".
4562 * Do we do it correctly? */
4563
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004564 closescript();
Denys Vlasenko844f9902009-09-23 03:25:52 +02004565
4566 if (mode == FORK_NOJOB /* is it `xxx` ? */
4567 && n && n->type == NCMD /* is it single cmd? */
4568 /* && n->ncmd.args->type == NARG - always true? */
4569 && strcmp(n->ncmd.args->narg.text, "trap") == 0
4570 && n->ncmd.args->narg.next == NULL /* "trap" with no arguments */
4571 /* && n->ncmd.args->narg.backquote == NULL - do we need to check this? */
4572 ) {
4573 TRACE(("Trap hack\n"));
4574 /* Awful hack for `trap` or $(trap).
4575 *
4576 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
4577 * contains an example where "trap" is executed in a subshell:
4578 *
4579 * save_traps=$(trap)
4580 * ...
4581 * eval "$save_traps"
4582 *
4583 * Standard does not say that "trap" in subshell shall print
4584 * parent shell's traps. It only says that its output
4585 * must have suitable form, but then, in the above example
4586 * (which is not supposed to be normative), it implies that.
4587 *
4588 * bash (and probably other shell) does implement it
4589 * (traps are reset to defaults, but "trap" still shows them),
4590 * but as a result, "trap" logic is hopelessly messed up:
4591 *
4592 * # trap
4593 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
4594 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
4595 * # true | trap <--- trap is in subshell - no output (ditto)
4596 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
4597 * trap -- 'echo Ho' SIGWINCH
4598 * # echo `(trap)` <--- in subshell in subshell - output
4599 * trap -- 'echo Ho' SIGWINCH
4600 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
4601 * trap -- 'echo Ho' SIGWINCH
4602 *
4603 * The rules when to forget and when to not forget traps
4604 * get really complex and nonsensical.
4605 *
4606 * Our solution: ONLY bare $(trap) or `trap` is special.
4607 */
Denys Vlasenko8f88d852009-09-25 12:12:53 +02004608 /* Save trap handler strings for trap builtin to print */
Denys Vlasenko21d87d42009-09-25 00:06:51 +02004609 trap_ptr = memcpy(xmalloc(sizeof(trap)), trap, sizeof(trap));
Denys Vlasenko8f88d852009-09-25 12:12:53 +02004610 /* Fall through into clearing traps */
Denys Vlasenko844f9902009-09-23 03:25:52 +02004611 }
Denys Vlasenkoe305c282009-09-25 02:12:27 +02004612 clear_traps();
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004613#if JOBS
4614 /* do job control only in root shell */
Denis Vlasenkob07a4962008-06-22 13:16:23 +00004615 doing_jobctl = 0;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004616 if (mode != FORK_NOJOB && jp->jobctl && !oldlvl) {
4617 pid_t pgrp;
4618
4619 if (jp->nprocs == 0)
4620 pgrp = getpid();
4621 else
4622 pgrp = jp->ps[0].pid;
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004623 /* this can fail because we are doing it in the parent also */
4624 setpgid(0, pgrp);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004625 if (mode == FORK_FG)
4626 xtcsetpgrp(ttyfd, pgrp);
4627 setsignal(SIGTSTP);
4628 setsignal(SIGTTOU);
4629 } else
4630#endif
4631 if (mode == FORK_BG) {
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004632 /* man bash: "When job control is not in effect,
4633 * asynchronous commands ignore SIGINT and SIGQUIT" */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004634 ignoresig(SIGINT);
4635 ignoresig(SIGQUIT);
4636 if (jp->nprocs == 0) {
4637 close(0);
4638 if (open(bb_dev_null, O_RDONLY) != 0)
Denis Vlasenko9604e1b2009-03-03 18:47:56 +00004639 ash_msg_and_raise_error("can't open '%s'", bb_dev_null);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004640 }
4641 }
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004642 if (!oldlvl) {
4643 if (iflag) { /* why if iflag only? */
4644 setsignal(SIGINT);
4645 setsignal(SIGTERM);
4646 }
4647 /* man bash:
4648 * "In all cases, bash ignores SIGQUIT. Non-builtin
4649 * commands run by bash have signal handlers
4650 * set to the values inherited by the shell
4651 * from its parent".
4652 * Take care of the second rule: */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004653 setsignal(SIGQUIT);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004654 }
Denys Vlasenkoe56f22a2009-07-24 00:16:59 +02004655#if JOBS
Denys Vlasenko844f9902009-09-23 03:25:52 +02004656 if (n && n->type == NCMD
4657 && strcmp(n->ncmd.args->narg.text, "jobs") == 0
4658 ) {
Denys Vlasenkoe56f22a2009-07-24 00:16:59 +02004659 TRACE(("Job hack\n"));
Denys Vlasenko844f9902009-09-23 03:25:52 +02004660 /* "jobs": we do not want to clear job list for it,
4661 * instead we remove only _its_ own_ job from job list.
4662 * This makes "jobs .... | cat" more useful.
4663 */
Denys Vlasenkoe56f22a2009-07-24 00:16:59 +02004664 freejob(curjob);
4665 return;
4666 }
4667#endif
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004668 for (jp = curjob; jp; jp = jp->prev_job)
4669 freejob(jp);
4670 jobless = 0;
4671}
4672
Denis Vlasenkobdc406d2007-07-15 01:13:25 +00004673/* Called after fork(), in parent */
Denis Vlasenko85c24712008-03-17 09:04:04 +00004674#if !JOBS
4675#define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
4676#endif
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004677static void
4678forkparent(struct job *jp, union node *n, int mode, pid_t pid)
4679{
4680 TRACE(("In parent shell: child = %d\n", pid));
4681 if (!jp) {
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00004682 while (jobless && dowait(DOWAIT_NONBLOCK, NULL) > 0)
4683 continue;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004684 jobless++;
4685 return;
4686 }
4687#if JOBS
4688 if (mode != FORK_NOJOB && jp->jobctl) {
4689 int pgrp;
4690
4691 if (jp->nprocs == 0)
4692 pgrp = pid;
4693 else
4694 pgrp = jp->ps[0].pid;
4695 /* This can fail because we are doing it in the child also */
4696 setpgid(pid, pgrp);
4697 }
4698#endif
4699 if (mode == FORK_BG) {
4700 backgndpid = pid; /* set $! */
4701 set_curjob(jp, CUR_RUNNING);
4702 }
4703 if (jp) {
4704 struct procstat *ps = &jp->ps[jp->nprocs++];
4705 ps->pid = pid;
4706 ps->status = -1;
4707 ps->cmd = nullstr;
4708#if JOBS
Denis Vlasenkob07a4962008-06-22 13:16:23 +00004709 if (doing_jobctl && n)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004710 ps->cmd = commandtext(n);
4711#endif
4712 }
4713}
4714
4715static int
4716forkshell(struct job *jp, union node *n, int mode)
4717{
4718 int pid;
4719
4720 TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
4721 pid = fork();
4722 if (pid < 0) {
4723 TRACE(("Fork failed, errno=%d", errno));
4724 if (jp)
4725 freejob(jp);
Denis Vlasenkofa0b56d2008-07-01 16:09:07 +00004726 ash_msg_and_raise_error("can't fork");
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004727 }
Denys Vlasenko76ace252009-10-12 15:25:01 +02004728 if (pid == 0) {
4729 CLEAR_RANDOM_T(&random_gen); /* or else $RANDOM repeats in child */
Denys Vlasenkoe56f22a2009-07-24 00:16:59 +02004730 forkchild(jp, n, mode);
Denys Vlasenko76ace252009-10-12 15:25:01 +02004731 } else {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004732 forkparent(jp, n, mode, pid);
Denys Vlasenko76ace252009-10-12 15:25:01 +02004733 }
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004734 return pid;
4735}
4736
4737/*
4738 * Wait for job to finish.
4739 *
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004740 * Under job control we have the problem that while a child process
4741 * is running interrupts generated by the user are sent to the child
4742 * but not to the shell. This means that an infinite loop started by
4743 * an interactive user may be hard to kill. With job control turned off,
4744 * an interactive user may place an interactive program inside a loop.
4745 * If the interactive program catches interrupts, the user doesn't want
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004746 * these interrupts to also abort the loop. The approach we take here
4747 * is to have the shell ignore interrupt signals while waiting for a
4748 * foreground process to terminate, and then send itself an interrupt
4749 * signal if the child process was terminated by an interrupt signal.
4750 * Unfortunately, some programs want to do a bit of cleanup and then
4751 * exit on interrupt; unless these processes terminate themselves by
4752 * sending a signal to themselves (instead of calling exit) they will
4753 * confuse this approach.
4754 *
4755 * Called with interrupts off.
4756 */
4757static int
4758waitforjob(struct job *jp)
4759{
4760 int st;
4761
4762 TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004763
4764 INT_OFF;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004765 while (jp->state == JOBRUNNING) {
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004766 /* In non-interactive shells, we _can_ get
4767 * a keyboard signal here and be EINTRed,
4768 * but we just loop back, waiting for command to complete.
4769 *
4770 * man bash:
4771 * "If bash is waiting for a command to complete and receives
4772 * a signal for which a trap has been set, the trap
4773 * will not be executed until the command completes."
4774 *
4775 * Reality is that even if trap is not set, bash
4776 * will not act on the signal until command completes.
4777 * Try this. sleep5intoff.c:
4778 * #include <signal.h>
4779 * #include <unistd.h>
4780 * int main() {
4781 * sigset_t set;
4782 * sigemptyset(&set);
4783 * sigaddset(&set, SIGINT);
4784 * sigaddset(&set, SIGQUIT);
4785 * sigprocmask(SIG_BLOCK, &set, NULL);
4786 * sleep(5);
4787 * return 0;
4788 * }
4789 * $ bash -c './sleep5intoff; echo hi'
4790 * ^C^C^C^C <--- pressing ^C once a second
4791 * $ _
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004792 * $ bash -c './sleep5intoff; echo hi'
4793 * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
4794 * $ _
4795 */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004796 dowait(DOWAIT_BLOCK, jp);
4797 }
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004798 INT_ON;
4799
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004800 st = getstatus(jp);
4801#if JOBS
4802 if (jp->jobctl) {
4803 xtcsetpgrp(ttyfd, rootpid);
4804 /*
4805 * This is truly gross.
4806 * If we're doing job control, then we did a TIOCSPGRP which
4807 * caused us (the shell) to no longer be in the controlling
4808 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
4809 * intuit from the subprocess exit status whether a SIGINT
4810 * occurred, and if so interrupt ourselves. Yuck. - mycroft
4811 */
Denis Vlasenko991a1da2008-02-10 19:02:53 +00004812 if (jp->sigint) /* TODO: do the same with all signals */
4813 raise(SIGINT); /* ... by raise(jp->sig) instead? */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004814 }
4815 if (jp->state == JOBDONE)
4816#endif
4817 freejob(jp);
4818 return st;
4819}
4820
4821/*
4822 * return 1 if there are stopped jobs, otherwise 0
4823 */
4824static int
4825stoppedjobs(void)
4826{
4827 struct job *jp;
4828 int retval;
4829
4830 retval = 0;
4831 if (job_warning)
4832 goto out;
4833 jp = curjob;
4834 if (jp && jp->state == JOBSTOPPED) {
4835 out2str("You have stopped jobs.\n");
4836 job_warning = 2;
4837 retval++;
4838 }
4839 out:
4840 return retval;
4841}
4842
4843
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004844/* ============ redir.c
4845 *
4846 * Code for dealing with input/output redirection.
4847 */
4848
4849#define EMPTY -2 /* marks an unused slot in redirtab */
Denis Vlasenko7d75a962007-11-22 08:16:57 +00004850#define CLOSED -3 /* marks a slot of previously-closed fd */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004851
4852/*
4853 * Open a file in noclobber mode.
4854 * The code was copied from bash.
4855 */
4856static int
4857noclobberopen(const char *fname)
4858{
4859 int r, fd;
4860 struct stat finfo, finfo2;
4861
4862 /*
4863 * If the file exists and is a regular file, return an error
4864 * immediately.
4865 */
4866 r = stat(fname, &finfo);
4867 if (r == 0 && S_ISREG(finfo.st_mode)) {
4868 errno = EEXIST;
4869 return -1;
4870 }
4871
4872 /*
4873 * If the file was not present (r != 0), make sure we open it
4874 * exclusively so that if it is created before we open it, our open
4875 * will fail. Make sure that we do not truncate an existing file.
4876 * Note that we don't turn on O_EXCL unless the stat failed -- if the
4877 * file was not a regular file, we leave O_EXCL off.
4878 */
4879 if (r != 0)
4880 return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
4881 fd = open(fname, O_WRONLY|O_CREAT, 0666);
4882
4883 /* If the open failed, return the file descriptor right away. */
4884 if (fd < 0)
4885 return fd;
4886
4887 /*
4888 * OK, the open succeeded, but the file may have been changed from a
4889 * non-regular file to a regular file between the stat and the open.
4890 * We are assuming that the O_EXCL open handles the case where FILENAME
4891 * did not exist and is symlinked to an existing file between the stat
4892 * and open.
4893 */
4894
4895 /*
4896 * If we can open it and fstat the file descriptor, and neither check
4897 * revealed that it was a regular file, and the file has not been
4898 * replaced, return the file descriptor.
4899 */
4900 if (fstat(fd, &finfo2) == 0 && !S_ISREG(finfo2.st_mode)
4901 && finfo.st_dev == finfo2.st_dev && finfo.st_ino == finfo2.st_ino)
4902 return fd;
4903
4904 /* The file has been replaced. badness. */
4905 close(fd);
4906 errno = EEXIST;
4907 return -1;
4908}
4909
4910/*
4911 * Handle here documents. Normally we fork off a process to write the
4912 * data to a pipe. If the document is short, we can stuff the data in
4913 * the pipe without forking.
4914 */
4915/* openhere needs this forward reference */
4916static void expandhere(union node *arg, int fd);
4917static int
4918openhere(union node *redir)
4919{
4920 int pip[2];
4921 size_t len = 0;
4922
4923 if (pipe(pip) < 0)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00004924 ash_msg_and_raise_error("pipe call failed");
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004925 if (redir->type == NHERE) {
4926 len = strlen(redir->nhere.doc->narg.text);
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00004927 if (len <= PIPE_BUF) {
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004928 full_write(pip[1], redir->nhere.doc->narg.text, len);
4929 goto out;
4930 }
4931 }
4932 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
Denis Vlasenko0b769642008-07-24 07:54:57 +00004933 /* child */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004934 close(pip[0]);
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004935 ignoresig(SIGINT); //signal(SIGINT, SIG_IGN);
4936 ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
4937 ignoresig(SIGHUP); //signal(SIGHUP, SIG_IGN);
4938 ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004939 signal(SIGPIPE, SIG_DFL);
4940 if (redir->type == NHERE)
4941 full_write(pip[1], redir->nhere.doc->narg.text, len);
Denis Vlasenko0b769642008-07-24 07:54:57 +00004942 else /* NXHERE */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004943 expandhere(redir->nhere.doc, pip[1]);
Bernhard Reutner-Fischer636a1f82008-05-19 09:29:47 +00004944 _exit(EXIT_SUCCESS);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004945 }
4946 out:
4947 close(pip[1]);
4948 return pip[0];
4949}
4950
4951static int
4952openredirect(union node *redir)
4953{
4954 char *fname;
4955 int f;
4956
4957 switch (redir->nfile.type) {
4958 case NFROM:
4959 fname = redir->nfile.expfname;
4960 f = open(fname, O_RDONLY);
4961 if (f < 0)
4962 goto eopen;
4963 break;
4964 case NFROMTO:
4965 fname = redir->nfile.expfname;
4966 f = open(fname, O_RDWR|O_CREAT|O_TRUNC, 0666);
4967 if (f < 0)
4968 goto ecreate;
4969 break;
4970 case NTO:
Denis Vlasenko559691a2008-10-05 18:39:31 +00004971#if ENABLE_ASH_BASH_COMPAT
4972 case NTO2:
4973#endif
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004974 /* Take care of noclobber mode. */
4975 if (Cflag) {
4976 fname = redir->nfile.expfname;
4977 f = noclobberopen(fname);
4978 if (f < 0)
4979 goto ecreate;
4980 break;
4981 }
4982 /* FALLTHROUGH */
4983 case NCLOBBER:
4984 fname = redir->nfile.expfname;
4985 f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
4986 if (f < 0)
4987 goto ecreate;
4988 break;
4989 case NAPPEND:
4990 fname = redir->nfile.expfname;
4991 f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
4992 if (f < 0)
4993 goto ecreate;
4994 break;
4995 default:
4996#if DEBUG
4997 abort();
4998#endif
4999 /* Fall through to eliminate warning. */
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005000/* Our single caller does this itself */
Denis Vlasenko0b769642008-07-24 07:54:57 +00005001// case NTOFD:
5002// case NFROMFD:
5003// f = -1;
5004// break;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005005 case NHERE:
5006 case NXHERE:
5007 f = openhere(redir);
5008 break;
5009 }
5010
5011 return f;
5012 ecreate:
Bernhard Reutner-Fischera53de7f2008-07-21 13:46:54 +00005013 ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005014 eopen:
Bernhard Reutner-Fischera53de7f2008-07-21 13:46:54 +00005015 ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005016}
5017
5018/*
5019 * Copy a file descriptor to be >= to. Returns -1
5020 * if the source file descriptor is closed, EMPTY if there are no unused
5021 * file descriptors left.
5022 */
Denis Vlasenko5a867312008-07-24 19:46:38 +00005023/* 0x800..00: bit to set in "to" to request dup2 instead of fcntl(F_DUPFD).
5024 * old code was doing close(to) prior to copyfd() to achieve the same */
Denis Vlasenko22f74142008-07-24 22:34:43 +00005025enum {
5026 COPYFD_EXACT = (int)~(INT_MAX),
5027 COPYFD_RESTORE = (int)((unsigned)COPYFD_EXACT >> 1),
5028};
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005029static int
5030copyfd(int from, int to)
5031{
5032 int newfd;
5033
Denis Vlasenko5a867312008-07-24 19:46:38 +00005034 if (to & COPYFD_EXACT) {
5035 to &= ~COPYFD_EXACT;
5036 /*if (from != to)*/
5037 newfd = dup2(from, to);
5038 } else {
5039 newfd = fcntl(from, F_DUPFD, to);
5040 }
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005041 if (newfd < 0) {
5042 if (errno == EMFILE)
5043 return EMPTY;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005044 /* Happens when source fd is not open: try "echo >&99" */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005045 ash_msg_and_raise_error("%d: %m", from);
5046 }
5047 return newfd;
5048}
5049
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005050/* Struct def and variable are moved down to the first usage site */
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005051struct two_fd_t {
5052 int orig, copy;
5053};
Denis Vlasenko0b769642008-07-24 07:54:57 +00005054struct redirtab {
5055 struct redirtab *next;
Denis Vlasenko0b769642008-07-24 07:54:57 +00005056 int nullredirs;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005057 int pair_count;
Denys Vlasenko606291b2009-09-23 23:15:43 +02005058 struct two_fd_t two_fd[];
Denis Vlasenko0b769642008-07-24 07:54:57 +00005059};
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005060#define redirlist (G_var.redirlist)
Denis Vlasenko0b769642008-07-24 07:54:57 +00005061
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005062static int need_to_remember(struct redirtab *rp, int fd)
5063{
5064 int i;
5065
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005066 if (!rp) /* remembering was not requested */
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005067 return 0;
5068
5069 for (i = 0; i < rp->pair_count; i++) {
5070 if (rp->two_fd[i].orig == fd) {
5071 /* already remembered */
5072 return 0;
5073 }
5074 }
5075 return 1;
5076}
5077
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005078/* "hidden" fd is a fd used to read scripts, or a copy of such */
5079static int is_hidden_fd(struct redirtab *rp, int fd)
5080{
5081 int i;
Denis Vlasenko34c73c42008-08-16 11:48:02 +00005082 struct parsefile *pf;
5083
5084 if (fd == -1)
5085 return 0;
5086 pf = g_parsefile;
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005087 while (pf) {
5088 if (fd == pf->fd) {
5089 return 1;
5090 }
5091 pf = pf->prev;
5092 }
5093 if (!rp)
5094 return 0;
5095 fd |= COPYFD_RESTORE;
5096 for (i = 0; i < rp->pair_count; i++) {
5097 if (rp->two_fd[i].copy == fd) {
5098 return 1;
5099 }
5100 }
5101 return 0;
5102}
5103
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005104/*
5105 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
5106 * old file descriptors are stashed away so that the redirection can be
5107 * undone by calling popredir. If the REDIR_BACKQ flag is set, then the
5108 * standard output, and the standard error if it becomes a duplicate of
5109 * stdout, is saved in memory.
5110 */
5111/* flags passed to redirect */
5112#define REDIR_PUSH 01 /* save previous values of file descriptors */
5113#define REDIR_SAVEFD2 03 /* set preverrout */
5114static void
5115redirect(union node *redir, int flags)
5116{
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005117 struct redirtab *sv;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005118 int sv_pos;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005119 int i;
5120 int fd;
5121 int newfd;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005122 int copied_fd2 = -1;
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005123
Denis Vlasenko01631112007-12-16 17:20:38 +00005124 g_nullredirs++;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005125 if (!redir) {
5126 return;
5127 }
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005128
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005129 sv = NULL;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005130 sv_pos = 0;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005131 INT_OFF;
5132 if (flags & REDIR_PUSH) {
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005133 union node *tmp = redir;
5134 do {
5135 sv_pos++;
Denis Vlasenko559691a2008-10-05 18:39:31 +00005136#if ENABLE_ASH_BASH_COMPAT
5137 if (redir->nfile.type == NTO2)
5138 sv_pos++;
5139#endif
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005140 tmp = tmp->nfile.next;
5141 } while (tmp);
5142 sv = ckmalloc(sizeof(*sv) + sv_pos * sizeof(sv->two_fd[0]));
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005143 sv->next = redirlist;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005144 sv->pair_count = sv_pos;
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005145 redirlist = sv;
Denis Vlasenko01631112007-12-16 17:20:38 +00005146 sv->nullredirs = g_nullredirs - 1;
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005147 g_nullredirs = 0;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005148 while (sv_pos > 0) {
5149 sv_pos--;
5150 sv->two_fd[sv_pos].orig = sv->two_fd[sv_pos].copy = EMPTY;
5151 }
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005152 }
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005153
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005154 do {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00005155 fd = redir->nfile.fd;
Denis Vlasenko0b769642008-07-24 07:54:57 +00005156 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005157 int right_fd = redir->ndup.dupfd;
5158 /* redirect from/to same file descriptor? */
5159 if (right_fd == fd)
5160 continue;
5161 /* echo >&10 and 10 is a fd opened to the sh script? */
5162 if (is_hidden_fd(sv, right_fd)) {
5163 errno = EBADF; /* as if it is closed */
5164 ash_msg_and_raise_error("%d: %m", right_fd);
5165 }
Denis Vlasenko0b769642008-07-24 07:54:57 +00005166 newfd = -1;
5167 } else {
5168 newfd = openredirect(redir); /* always >= 0 */
5169 if (fd == newfd) {
5170 /* Descriptor wasn't open before redirect.
5171 * Mark it for close in the future */
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005172 if (need_to_remember(sv, fd)) {
Denis Vlasenko5a867312008-07-24 19:46:38 +00005173 goto remember_to_close;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005174 }
Denis Vlasenko0b769642008-07-24 07:54:57 +00005175 continue;
5176 }
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005177 }
Denis Vlasenko559691a2008-10-05 18:39:31 +00005178#if ENABLE_ASH_BASH_COMPAT
5179 redirect_more:
5180#endif
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005181 if (need_to_remember(sv, fd)) {
Denis Vlasenko0b769642008-07-24 07:54:57 +00005182 /* Copy old descriptor */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005183 i = fcntl(fd, F_DUPFD, 10);
Denis Vlasenko5a867312008-07-24 19:46:38 +00005184/* You'd expect copy to be CLOEXECed. Currently these extra "saved" fds
5185 * are closed in popredir() in the child, preventing them from leaking
5186 * into child. (popredir() also cleans up the mess in case of failures)
5187 */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005188 if (i == -1) {
5189 i = errno;
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005190 if (i != EBADF) {
5191 /* Strange error (e.g. "too many files" EMFILE?) */
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005192 if (newfd >= 0)
5193 close(newfd);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005194 errno = i;
5195 ash_msg_and_raise_error("%d: %m", fd);
5196 /* NOTREACHED */
5197 }
Denis Vlasenko5a867312008-07-24 19:46:38 +00005198 /* EBADF: it is not open - good, remember to close it */
5199 remember_to_close:
5200 i = CLOSED;
Denis Vlasenko22f74142008-07-24 22:34:43 +00005201 } else { /* fd is open, save its copy */
5202 /* "exec fd>&-" should not close fds
5203 * which point to script file(s).
5204 * Force them to be restored afterwards */
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005205 if (is_hidden_fd(sv, fd))
5206 i |= COPYFD_RESTORE;
Denis Vlasenko22f74142008-07-24 22:34:43 +00005207 }
Denis Vlasenko5a867312008-07-24 19:46:38 +00005208 if (fd == 2)
5209 copied_fd2 = i;
5210 sv->two_fd[sv_pos].orig = fd;
5211 sv->two_fd[sv_pos].copy = i;
5212 sv_pos++;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005213 }
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005214 if (newfd < 0) {
5215 /* NTOFD/NFROMFD: copy redir->ndup.dupfd to fd */
Denis Vlasenko22f74142008-07-24 22:34:43 +00005216 if (redir->ndup.dupfd < 0) { /* "fd>&-" */
Denis Vlasenkob9e70dd2009-03-20 01:24:08 +00005217 /* Don't want to trigger debugging */
5218 if (fd != -1)
5219 close(fd);
Denis Vlasenko5a867312008-07-24 19:46:38 +00005220 } else {
5221 copyfd(redir->ndup.dupfd, fd | COPYFD_EXACT);
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005222 }
Denis Vlasenko5a867312008-07-24 19:46:38 +00005223 } else if (fd != newfd) { /* move newfd to fd */
5224 copyfd(newfd, fd | COPYFD_EXACT);
Denis Vlasenko559691a2008-10-05 18:39:31 +00005225#if ENABLE_ASH_BASH_COMPAT
5226 if (!(redir->nfile.type == NTO2 && fd == 2))
5227#endif
5228 close(newfd);
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005229 }
Denis Vlasenko559691a2008-10-05 18:39:31 +00005230#if ENABLE_ASH_BASH_COMPAT
5231 if (redir->nfile.type == NTO2 && fd == 1) {
5232 /* We already redirected it to fd 1, now copy it to 2 */
5233 newfd = 1;
5234 fd = 2;
5235 goto redirect_more;
5236 }
5237#endif
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00005238 } while ((redir = redir->nfile.next) != NULL);
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005239
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005240 INT_ON;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005241 if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
5242 preverrout_fd = copied_fd2;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005243}
5244
5245/*
5246 * Undo the effects of the last redirection.
5247 */
5248static void
Denis Vlasenko34c73c42008-08-16 11:48:02 +00005249popredir(int drop, int restore)
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005250{
5251 struct redirtab *rp;
5252 int i;
5253
Denis Vlasenko01631112007-12-16 17:20:38 +00005254 if (--g_nullredirs >= 0)
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005255 return;
5256 INT_OFF;
5257 rp = redirlist;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005258 for (i = 0; i < rp->pair_count; i++) {
5259 int fd = rp->two_fd[i].orig;
Denis Vlasenko22f74142008-07-24 22:34:43 +00005260 int copy = rp->two_fd[i].copy;
5261 if (copy == CLOSED) {
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005262 if (!drop)
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005263 close(fd);
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005264 continue;
5265 }
Denis Vlasenko22f74142008-07-24 22:34:43 +00005266 if (copy != EMPTY) {
Denis Vlasenko34c73c42008-08-16 11:48:02 +00005267 if (!drop || (restore && (copy & COPYFD_RESTORE))) {
Denis Vlasenko22f74142008-07-24 22:34:43 +00005268 copy &= ~COPYFD_RESTORE;
Denis Vlasenko5a867312008-07-24 19:46:38 +00005269 /*close(fd);*/
Denis Vlasenko22f74142008-07-24 22:34:43 +00005270 copyfd(copy, fd | COPYFD_EXACT);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005271 }
Denis Vlasenkob9e70dd2009-03-20 01:24:08 +00005272 close(copy & ~COPYFD_RESTORE);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005273 }
5274 }
5275 redirlist = rp->next;
Denis Vlasenko01631112007-12-16 17:20:38 +00005276 g_nullredirs = rp->nullredirs;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005277 free(rp);
5278 INT_ON;
5279}
5280
5281/*
5282 * Undo all redirections. Called on error or interrupt.
5283 */
5284
5285/*
5286 * Discard all saved file descriptors.
5287 */
5288static void
5289clearredir(int drop)
5290{
5291 for (;;) {
Denis Vlasenko01631112007-12-16 17:20:38 +00005292 g_nullredirs = 0;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005293 if (!redirlist)
5294 break;
Denis Vlasenko34c73c42008-08-16 11:48:02 +00005295 popredir(drop, /*restore:*/ 0);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005296 }
5297}
5298
5299static int
5300redirectsafe(union node *redir, int flags)
5301{
5302 int err;
5303 volatile int saveint;
5304 struct jmploc *volatile savehandler = exception_handler;
5305 struct jmploc jmploc;
5306
5307 SAVE_INT(saveint);
Denis Vlasenko5a867312008-07-24 19:46:38 +00005308 /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
5309 err = setjmp(jmploc.loc); // huh?? was = setjmp(jmploc.loc) * 2;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005310 if (!err) {
5311 exception_handler = &jmploc;
5312 redirect(redir, flags);
5313 }
5314 exception_handler = savehandler;
Denis Vlasenko7f88e342009-03-19 03:36:18 +00005315 if (err && exception_type != EXERROR)
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005316 longjmp(exception_handler->loc, 1);
5317 RESTORE_INT(saveint);
5318 return err;
5319}
5320
5321
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005322/* ============ Routines to expand arguments to commands
5323 *
5324 * We have to deal with backquotes, shell variables, and file metacharacters.
5325 */
5326
Mike Frysinger98c52642009-04-02 10:02:37 +00005327#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00005328static arith_t
5329ash_arith(const char *s)
5330{
5331 arith_eval_hooks_t math_hooks;
5332 arith_t result;
5333 int errcode = 0;
5334
5335 math_hooks.lookupvar = lookupvar;
5336 math_hooks.setvar = setvar;
5337 math_hooks.endofname = endofname;
5338
5339 INT_OFF;
5340 result = arith(s, &errcode, &math_hooks);
5341 if (errcode < 0) {
5342 if (errcode == -3)
5343 ash_msg_and_raise_error("exponent less than 0");
5344 if (errcode == -2)
5345 ash_msg_and_raise_error("divide by zero");
5346 if (errcode == -5)
5347 ash_msg_and_raise_error("expression recursion loop detected");
5348 raise_error_syntax(s);
5349 }
5350 INT_ON;
5351
5352 return result;
5353}
Denis Vlasenko448d30e2008-06-27 00:24:11 +00005354#endif
5355
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005356/*
5357 * expandarg flags
5358 */
5359#define EXP_FULL 0x1 /* perform word splitting & file globbing */
5360#define EXP_TILDE 0x2 /* do normal tilde expansion */
5361#define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
5362#define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
5363#define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
5364#define EXP_RECORD 0x20 /* need to record arguments for ifs breakup */
5365#define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
5366#define EXP_WORD 0x80 /* expand word in parameter expansion */
5367#define EXP_QWORD 0x100 /* expand word in quoted parameter expansion */
5368/*
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005369 * rmescape() flags
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005370 */
5371#define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
5372#define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
5373#define RMESCAPE_QUOTED 0x4 /* Remove CTLESC unless in quotes */
5374#define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
5375#define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
5376
5377/*
5378 * Structure specifying which parts of the string should be searched
5379 * for IFS characters.
5380 */
5381struct ifsregion {
5382 struct ifsregion *next; /* next region in list */
5383 int begoff; /* offset of start of region */
5384 int endoff; /* offset of end of region */
5385 int nulonly; /* search for nul bytes only */
5386};
5387
5388struct arglist {
5389 struct strlist *list;
5390 struct strlist **lastp;
5391};
5392
5393/* output of current string */
5394static char *expdest;
5395/* list of back quote expressions */
5396static struct nodelist *argbackq;
5397/* first struct in list of ifs regions */
5398static struct ifsregion ifsfirst;
5399/* last struct in list */
5400static struct ifsregion *ifslastp;
5401/* holds expanded arg list */
5402static struct arglist exparg;
5403
5404/*
5405 * Our own itoa().
5406 */
5407static int
5408cvtnum(arith_t num)
5409{
5410 int len;
5411
5412 expdest = makestrspace(32, expdest);
Mike Frysinger98c52642009-04-02 10:02:37 +00005413 len = fmtstr(expdest, 32, arith_t_fmt, num);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005414 STADJUST(len, expdest);
5415 return len;
5416}
5417
5418static size_t
5419esclen(const char *start, const char *p)
5420{
5421 size_t esc = 0;
5422
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005423 while (p > start && (unsigned char)*--p == CTLESC) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005424 esc++;
5425 }
5426 return esc;
5427}
5428
5429/*
5430 * Remove any CTLESC characters from a string.
5431 */
5432static char *
Denys Vlasenkob6c84342009-08-29 20:23:20 +02005433rmescapes(char *str, int flag)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005434{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00005435 static const char qchars[] ALIGN1 = { CTLESC, CTLQUOTEMARK, '\0' };
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00005436
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005437 char *p, *q, *r;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005438 unsigned inquotes;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005439 unsigned protect_against_glob;
5440 unsigned globbing;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005441
5442 p = strpbrk(str, qchars);
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005443 if (!p)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005444 return str;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005445
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005446 q = p;
5447 r = str;
5448 if (flag & RMESCAPE_ALLOC) {
5449 size_t len = p - str;
5450 size_t fulllen = len + strlen(p) + 1;
5451
5452 if (flag & RMESCAPE_GROW) {
5453 r = makestrspace(fulllen, expdest);
5454 } else if (flag & RMESCAPE_HEAP) {
5455 r = ckmalloc(fulllen);
5456 } else {
5457 r = stalloc(fulllen);
5458 }
5459 q = r;
5460 if (len > 0) {
Denis Vlasenko29eb3592008-05-18 14:06:08 +00005461 q = (char *)memcpy(q, str, len) + len;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005462 }
5463 }
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005464
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005465 inquotes = (flag & RMESCAPE_QUOTED) ^ RMESCAPE_QUOTED;
5466 globbing = flag & RMESCAPE_GLOB;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005467 protect_against_glob = globbing;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005468 while (*p) {
5469 if (*p == CTLQUOTEMARK) {
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005470// TODO: if no RMESCAPE_QUOTED in flags, inquotes never becomes 0
5471// (alternates between RMESCAPE_QUOTED and ~RMESCAPE_QUOTED). Is it ok?
5472// Note: both inquotes and protect_against_glob only affect whether
5473// CTLESC,<ch> gets converted to <ch> or to \<ch>
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005474 inquotes = ~inquotes;
5475 p++;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005476 protect_against_glob = globbing;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005477 continue;
5478 }
5479 if (*p == '\\') {
5480 /* naked back slash */
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005481 protect_against_glob = 0;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005482 goto copy;
5483 }
5484 if (*p == CTLESC) {
5485 p++;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005486 if (protect_against_glob && inquotes && *p != '/') {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005487 *q++ = '\\';
5488 }
5489 }
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005490 protect_against_glob = globbing;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005491 copy:
5492 *q++ = *p++;
5493 }
5494 *q = '\0';
5495 if (flag & RMESCAPE_GROW) {
5496 expdest = r;
5497 STADJUST(q - r + 1, expdest);
5498 }
5499 return r;
5500}
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005501#define pmatch(a, b) !fnmatch((a), (b), 0)
5502
5503/*
5504 * Prepare a pattern for a expmeta (internal glob(3)) call.
5505 *
5506 * Returns an stalloced string.
5507 */
5508static char *
5509preglob(const char *pattern, int quoted, int flag)
5510{
5511 flag |= RMESCAPE_GLOB;
5512 if (quoted) {
5513 flag |= RMESCAPE_QUOTED;
5514 }
Denys Vlasenkob6c84342009-08-29 20:23:20 +02005515 return rmescapes((char *)pattern, flag);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005516}
5517
5518/*
5519 * Put a string on the stack.
5520 */
5521static void
5522memtodest(const char *p, size_t len, int syntax, int quotes)
5523{
5524 char *q = expdest;
5525
Denys Vlasenkob6c84342009-08-29 20:23:20 +02005526 q = makestrspace(quotes ? len * 2 : len, q);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005527
5528 while (len--) {
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00005529 int c = signed_char2int(*p++);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005530 if (!c)
5531 continue;
Denys Vlasenkob6c84342009-08-29 20:23:20 +02005532 if (quotes) {
5533 int n = SIT(c, syntax);
5534 if (n == CCTL || n == CBACK)
5535 USTPUTC(CTLESC, q);
5536 }
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005537 USTPUTC(c, q);
5538 }
5539
5540 expdest = q;
5541}
5542
5543static void
5544strtodest(const char *p, int syntax, int quotes)
5545{
5546 memtodest(p, strlen(p), syntax, quotes);
5547}
5548
5549/*
5550 * Record the fact that we have to scan this region of the
5551 * string for IFS characters.
5552 */
5553static void
5554recordregion(int start, int end, int nulonly)
5555{
5556 struct ifsregion *ifsp;
5557
5558 if (ifslastp == NULL) {
5559 ifsp = &ifsfirst;
5560 } else {
5561 INT_OFF;
Denis Vlasenko597906c2008-02-20 16:38:54 +00005562 ifsp = ckzalloc(sizeof(*ifsp));
5563 /*ifsp->next = NULL; - ckzalloc did it */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005564 ifslastp->next = ifsp;
5565 INT_ON;
5566 }
5567 ifslastp = ifsp;
5568 ifslastp->begoff = start;
5569 ifslastp->endoff = end;
5570 ifslastp->nulonly = nulonly;
5571}
5572
5573static void
5574removerecordregions(int endoff)
5575{
5576 if (ifslastp == NULL)
5577 return;
5578
5579 if (ifsfirst.endoff > endoff) {
5580 while (ifsfirst.next != NULL) {
5581 struct ifsregion *ifsp;
5582 INT_OFF;
5583 ifsp = ifsfirst.next->next;
5584 free(ifsfirst.next);
5585 ifsfirst.next = ifsp;
5586 INT_ON;
5587 }
5588 if (ifsfirst.begoff > endoff)
5589 ifslastp = NULL;
5590 else {
5591 ifslastp = &ifsfirst;
5592 ifsfirst.endoff = endoff;
5593 }
5594 return;
5595 }
5596
5597 ifslastp = &ifsfirst;
5598 while (ifslastp->next && ifslastp->next->begoff < endoff)
5599 ifslastp=ifslastp->next;
5600 while (ifslastp->next != NULL) {
5601 struct ifsregion *ifsp;
5602 INT_OFF;
5603 ifsp = ifslastp->next->next;
5604 free(ifslastp->next);
5605 ifslastp->next = ifsp;
5606 INT_ON;
5607 }
5608 if (ifslastp->endoff > endoff)
5609 ifslastp->endoff = endoff;
5610}
5611
5612static char *
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005613exptilde(char *startp, char *p, int flags)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005614{
5615 char c;
5616 char *name;
5617 struct passwd *pw;
5618 const char *home;
Denys Vlasenko1166d7b2009-09-16 16:20:31 +02005619 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005620 int startloc;
5621
5622 name = p + 1;
5623
5624 while ((c = *++p) != '\0') {
5625 switch (c) {
5626 case CTLESC:
5627 return startp;
5628 case CTLQUOTEMARK:
5629 return startp;
5630 case ':':
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005631 if (flags & EXP_VARTILDE)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005632 goto done;
5633 break;
5634 case '/':
5635 case CTLENDVAR:
5636 goto done;
5637 }
5638 }
5639 done:
5640 *p = '\0';
5641 if (*name == '\0') {
5642 home = lookupvar(homestr);
5643 } else {
5644 pw = getpwnam(name);
5645 if (pw == NULL)
5646 goto lose;
5647 home = pw->pw_dir;
5648 }
5649 if (!home || !*home)
5650 goto lose;
5651 *p = c;
5652 startloc = expdest - (char *)stackblock();
5653 strtodest(home, SQSYNTAX, quotes);
5654 recordregion(startloc, expdest - (char *)stackblock(), 0);
5655 return p;
5656 lose:
5657 *p = c;
5658 return startp;
5659}
5660
5661/*
5662 * Execute a command inside back quotes. If it's a builtin command, we
5663 * want to save its output in a block obtained from malloc. Otherwise
5664 * we fork off a subprocess and get the output of the command via a pipe.
5665 * Should be called with interrupts off.
5666 */
5667struct backcmd { /* result of evalbackcmd */
5668 int fd; /* file descriptor to read from */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005669 int nleft; /* number of chars in buffer */
Denis Vlasenkob07a4962008-06-22 13:16:23 +00005670 char *buf; /* buffer */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005671 struct job *jp; /* job structure for command */
5672};
5673
5674/* These forward decls are needed to use "eval" code for backticks handling: */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00005675static uint8_t back_exitstatus; /* exit status of backquoted command */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005676#define EV_EXIT 01 /* exit after evaluating tree */
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02005677static void evaltree(union node *, int);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005678
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02005679static void FAST_FUNC
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005680evalbackcmd(union node *n, struct backcmd *result)
5681{
5682 int saveherefd;
5683
5684 result->fd = -1;
5685 result->buf = NULL;
5686 result->nleft = 0;
5687 result->jp = NULL;
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00005688 if (n == NULL)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005689 goto out;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005690
5691 saveherefd = herefd;
5692 herefd = -1;
5693
5694 {
5695 int pip[2];
5696 struct job *jp;
5697
5698 if (pipe(pip) < 0)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00005699 ash_msg_and_raise_error("pipe call failed");
Denis Vlasenko68404f12008-03-17 09:00:54 +00005700 jp = makejob(/*n,*/ 1);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005701 if (forkshell(jp, n, FORK_NOJOB) == 0) {
5702 FORCE_INT_ON;
5703 close(pip[0]);
5704 if (pip[1] != 1) {
Denis Vlasenko5a867312008-07-24 19:46:38 +00005705 /*close(1);*/
5706 copyfd(pip[1], 1 | COPYFD_EXACT);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005707 close(pip[1]);
5708 }
5709 eflag = 0;
5710 evaltree(n, EV_EXIT); /* actually evaltreenr... */
5711 /* NOTREACHED */
5712 }
5713 close(pip[1]);
5714 result->fd = pip[0];
5715 result->jp = jp;
5716 }
5717 herefd = saveherefd;
5718 out:
5719 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
5720 result->fd, result->buf, result->nleft, result->jp));
5721}
5722
5723/*
5724 * Expand stuff in backwards quotes.
5725 */
5726static void
5727expbackq(union node *cmd, int quoted, int quotes)
5728{
5729 struct backcmd in;
5730 int i;
5731 char buf[128];
5732 char *p;
5733 char *dest;
5734 int startloc;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00005735 int syntax = quoted ? DQSYNTAX : BASESYNTAX;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005736 struct stackmark smark;
5737
5738 INT_OFF;
5739 setstackmark(&smark);
5740 dest = expdest;
5741 startloc = dest - (char *)stackblock();
5742 grabstackstr(dest);
5743 evalbackcmd(cmd, &in);
5744 popstackmark(&smark);
5745
5746 p = in.buf;
5747 i = in.nleft;
5748 if (i == 0)
5749 goto read;
5750 for (;;) {
5751 memtodest(p, i, syntax, quotes);
5752 read:
5753 if (in.fd < 0)
5754 break;
Denis Vlasenkoe376d452008-02-20 22:23:24 +00005755 i = nonblock_safe_read(in.fd, buf, sizeof(buf));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005756 TRACE(("expbackq: read returns %d\n", i));
5757 if (i <= 0)
5758 break;
5759 p = buf;
5760 }
5761
Denis Vlasenko60818682007-09-28 22:07:23 +00005762 free(in.buf);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005763 if (in.fd >= 0) {
5764 close(in.fd);
5765 back_exitstatus = waitforjob(in.jp);
5766 }
5767 INT_ON;
5768
5769 /* Eat all trailing newlines */
5770 dest = expdest;
5771 for (; dest > (char *)stackblock() && dest[-1] == '\n';)
5772 STUNPUTC(dest);
5773 expdest = dest;
5774
5775 if (quoted == 0)
5776 recordregion(startloc, dest - (char *)stackblock(), 0);
5777 TRACE(("evalbackq: size=%d: \"%.*s\"\n",
5778 (dest - (char *)stackblock()) - startloc,
5779 (dest - (char *)stackblock()) - startloc,
5780 stackblock() + startloc));
5781}
5782
Mike Frysinger98c52642009-04-02 10:02:37 +00005783#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005784/*
5785 * Expand arithmetic expression. Backup to start of expression,
5786 * evaluate, place result in (backed up) result, adjust string position.
5787 */
5788static void
5789expari(int quotes)
5790{
5791 char *p, *start;
5792 int begoff;
5793 int flag;
5794 int len;
5795
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00005796 /* ifsfree(); */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005797
5798 /*
5799 * This routine is slightly over-complicated for
5800 * efficiency. Next we scan backwards looking for the
5801 * start of arithmetic.
5802 */
5803 start = stackblock();
5804 p = expdest - 1;
5805 *p = '\0';
5806 p--;
5807 do {
5808 int esc;
5809
5810 while (*p != CTLARI) {
5811 p--;
5812#if DEBUG
5813 if (p < start) {
5814 ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
5815 }
5816#endif
5817 }
5818
5819 esc = esclen(start, p);
5820 if (!(esc % 2)) {
5821 break;
5822 }
5823
5824 p -= esc + 1;
5825 } while (1);
5826
5827 begoff = p - start;
5828
5829 removerecordregions(begoff);
5830
5831 flag = p[1];
5832
5833 expdest = p;
5834
5835 if (quotes)
Denys Vlasenkob6c84342009-08-29 20:23:20 +02005836 rmescapes(p + 2, 0);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005837
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00005838 len = cvtnum(ash_arith(p + 2));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005839
5840 if (flag != '"')
5841 recordregion(begoff, begoff + len, 0);
5842}
5843#endif
5844
5845/* argstr needs it */
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005846static char *evalvar(char *p, int flags, struct strlist *var_str_list);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005847
5848/*
5849 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
5850 * characters to allow for further processing. Otherwise treat
5851 * $@ like $* since no splitting will be performed.
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00005852 *
5853 * var_str_list (can be NULL) is a list of "VAR=val" strings which take precedence
5854 * over shell varables. Needed for "A=a B=$A; echo $B" case - we use it
5855 * for correct expansion of "B=$A" word.
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005856 */
5857static void
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005858argstr(char *p, int flags, struct strlist *var_str_list)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005859{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00005860 static const char spclchars[] ALIGN1 = {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005861 '=',
5862 ':',
5863 CTLQUOTEMARK,
5864 CTLENDVAR,
5865 CTLESC,
5866 CTLVAR,
5867 CTLBACKQ,
5868 CTLBACKQ | CTLQUOTE,
Mike Frysinger98c52642009-04-02 10:02:37 +00005869#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005870 CTLENDARI,
5871#endif
5872 0
5873 };
5874 const char *reject = spclchars;
5875 int c;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005876 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR); /* do CTLESC */
5877 int breakall = flags & EXP_WORD;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005878 int inquotes;
5879 size_t length;
5880 int startloc;
5881
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005882 if (!(flags & EXP_VARTILDE)) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005883 reject += 2;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005884 } else if (flags & EXP_VARTILDE2) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005885 reject++;
5886 }
5887 inquotes = 0;
5888 length = 0;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005889 if (flags & EXP_TILDE) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005890 char *q;
5891
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005892 flags &= ~EXP_TILDE;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005893 tilde:
5894 q = p;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005895 if (*q == CTLESC && (flags & EXP_QWORD))
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005896 q++;
5897 if (*q == '~')
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005898 p = exptilde(p, q, flags);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005899 }
5900 start:
5901 startloc = expdest - (char *)stackblock();
5902 for (;;) {
5903 length += strcspn(p + length, reject);
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005904 c = (unsigned char) p[length];
5905 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;
6059 if (quotes && *loc == CTLESC)
6060 loc++;
6061 loc++;
6062 loc2++;
6063 } while (c);
6064 return 0;
6065}
6066
6067static char *
6068scanright(char *startp, char *rmesc, char *rmescend, char *str, int quotes,
6069 int zero)
6070{
6071 int esc = 0;
6072 char *loc;
6073 char *loc2;
6074
6075 for (loc = str - 1, loc2 = rmescend; loc >= startp; loc2--) {
6076 int match;
6077 char c = *loc2;
6078 const char *s = loc2;
6079 if (zero) {
6080 *loc2 = '\0';
6081 s = rmesc;
6082 }
6083 match = pmatch(str, s);
6084 *loc2 = c;
6085 if (match)
6086 return loc;
6087 loc--;
6088 if (quotes) {
6089 if (--esc < 0) {
6090 esc = esclen(startp, loc);
6091 }
6092 if (esc % 2) {
6093 esc--;
6094 loc--;
6095 }
6096 }
6097 }
6098 return 0;
6099}
6100
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00006101static void varunset(const char *, const char *, const char *, int) NORETURN;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006102static void
6103varunset(const char *end, const char *var, const char *umsg, int varflags)
6104{
6105 const char *msg;
6106 const char *tail;
6107
6108 tail = nullstr;
6109 msg = "parameter not set";
6110 if (umsg) {
6111 if (*end == CTLENDVAR) {
6112 if (varflags & VSNUL)
6113 tail = " or null";
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00006114 } else {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006115 msg = umsg;
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00006116 }
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006117 }
6118 ash_msg_and_raise_error("%.*s: %s%s", end - var - 1, var, msg, tail);
6119}
6120
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006121#if ENABLE_ASH_BASH_COMPAT
6122static char *
6123parse_sub_pattern(char *arg, int inquotes)
6124{
6125 char *idx, *repl = NULL;
6126 unsigned char c;
6127
Denis Vlasenko2659c632008-06-14 06:04:59 +00006128 idx = arg;
6129 while (1) {
6130 c = *arg;
6131 if (!c)
6132 break;
6133 if (c == '/') {
6134 /* Only the first '/' seen is our separator */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006135 if (!repl) {
Denis Vlasenko2659c632008-06-14 06:04:59 +00006136 repl = idx + 1;
6137 c = '\0';
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006138 }
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006139 }
Denis Vlasenko2659c632008-06-14 06:04:59 +00006140 *idx++ = c;
6141 if (!inquotes && c == '\\' && arg[1] == '\\')
6142 arg++; /* skip both \\, not just first one */
6143 arg++;
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006144 }
Denis Vlasenko29038c02008-06-14 06:14:02 +00006145 *idx = c; /* NUL */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006146
6147 return repl;
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006148}
6149#endif /* ENABLE_ASH_BASH_COMPAT */
6150
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006151static const char *
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006152subevalvar(char *p, char *str, int strloc, int subtype,
6153 int startloc, int varflags, int quotes, struct strlist *var_str_list)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006154{
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006155 struct nodelist *saveargbackq = argbackq;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006156 char *startp;
6157 char *loc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006158 char *rmesc, *rmescend;
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00006159 IF_ASH_BASH_COMPAT(char *repl = NULL;)
6160 IF_ASH_BASH_COMPAT(char null = '\0';)
6161 IF_ASH_BASH_COMPAT(int pos, len, orig_len;)
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006162 int saveherefd = herefd;
6163 int amount, workloc, resetloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006164 int zero;
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006165 char *(*scan)(char*, char*, char*, char*, int, int);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006166
6167 herefd = -1;
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006168 argstr(p, (subtype != VSASSIGN && subtype != VSQUESTION) ? EXP_CASE : 0,
6169 var_str_list);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006170 STPUTC('\0', expdest);
6171 herefd = saveherefd;
6172 argbackq = saveargbackq;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00006173 startp = (char *)stackblock() + startloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006174
6175 switch (subtype) {
6176 case VSASSIGN:
6177 setvar(str, startp, 0);
6178 amount = startp - expdest;
6179 STADJUST(amount, expdest);
6180 return startp;
6181
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006182#if ENABLE_ASH_BASH_COMPAT
6183 case VSSUBSTR:
6184 loc = str = stackblock() + strloc;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006185 /* Read POS in ${var:POS:LEN} */
6186 pos = atoi(loc); /* number(loc) errors out on "1:4" */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006187 len = str - startp - 1;
6188
6189 /* *loc != '\0', guaranteed by parser */
6190 if (quotes) {
6191 char *ptr;
6192
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006193 /* Adjust the length by the number of escapes */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006194 for (ptr = startp; ptr < (str - 1); ptr++) {
Denis Vlasenkod6855d12008-09-27 14:03:25 +00006195 if (*ptr == CTLESC) {
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006196 len--;
6197 ptr++;
6198 }
6199 }
6200 }
6201 orig_len = len;
6202
6203 if (*loc++ == ':') {
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006204 /* ${var::LEN} */
6205 len = number(loc);
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006206 } else {
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006207 /* Skip POS in ${var:POS:LEN} */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006208 len = orig_len;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006209 while (*loc && *loc != ':') {
6210 /* TODO?
6211 * bash complains on: var=qwe; echo ${var:1a:123}
6212 if (!isdigit(*loc))
6213 ash_msg_and_raise_error(msg_illnum, str);
6214 */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006215 loc++;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006216 }
6217 if (*loc++ == ':') {
6218 len = number(loc);
6219 }
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006220 }
6221 if (pos >= orig_len) {
6222 pos = 0;
6223 len = 0;
6224 }
6225 if (len > (orig_len - pos))
6226 len = orig_len - pos;
6227
6228 for (str = startp; pos; str++, pos--) {
6229 if (quotes && *str == CTLESC)
6230 str++;
6231 }
6232 for (loc = startp; len; len--) {
6233 if (quotes && *str == CTLESC)
6234 *loc++ = *str++;
6235 *loc++ = *str++;
6236 }
6237 *loc = '\0';
6238 amount = loc - expdest;
6239 STADJUST(amount, expdest);
6240 return loc;
6241#endif
6242
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006243 case VSQUESTION:
6244 varunset(p, str, startp, varflags);
6245 /* NOTREACHED */
6246 }
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006247 resetloc = expdest - (char *)stackblock();
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006248
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006249 /* We'll comeback here if we grow the stack while handling
6250 * a VSREPLACE or VSREPLACEALL, since our pointers into the
6251 * stack will need rebasing, and we'll need to remove our work
6252 * areas each time
6253 */
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00006254 IF_ASH_BASH_COMPAT(restart:)
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006255
6256 amount = expdest - ((char *)stackblock() + resetloc);
6257 STADJUST(-amount, expdest);
Denis Vlasenko29eb3592008-05-18 14:06:08 +00006258 startp = (char *)stackblock() + startloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006259
6260 rmesc = startp;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00006261 rmescend = (char *)stackblock() + strloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006262 if (quotes) {
Denys Vlasenkob6c84342009-08-29 20:23:20 +02006263 rmesc = rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006264 if (rmesc != startp) {
6265 rmescend = expdest;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00006266 startp = (char *)stackblock() + startloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006267 }
6268 }
6269 rmescend--;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00006270 str = (char *)stackblock() + strloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006271 preglob(str, varflags & VSQUOTE, 0);
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006272 workloc = expdest - (char *)stackblock();
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006273
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006274#if ENABLE_ASH_BASH_COMPAT
6275 if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
6276 char *idx, *end, *restart_detect;
6277
Denis Vlasenkod6855d12008-09-27 14:03:25 +00006278 if (!repl) {
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006279 repl = parse_sub_pattern(str, varflags & VSQUOTE);
6280 if (!repl)
6281 repl = &null;
6282 }
6283
6284 /* If there's no pattern to match, return the expansion unmolested */
6285 if (*str == '\0')
6286 return 0;
6287
6288 len = 0;
6289 idx = startp;
6290 end = str - 1;
6291 while (idx < end) {
6292 loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
6293 if (!loc) {
6294 /* No match, advance */
6295 restart_detect = stackblock();
6296 STPUTC(*idx, expdest);
6297 if (quotes && *idx == CTLESC) {
6298 idx++;
6299 len++;
6300 STPUTC(*idx, expdest);
6301 }
6302 if (stackblock() != restart_detect)
6303 goto restart;
6304 idx++;
6305 len++;
6306 rmesc++;
6307 continue;
6308 }
6309
6310 if (subtype == VSREPLACEALL) {
6311 while (idx < loc) {
6312 if (quotes && *idx == CTLESC)
6313 idx++;
6314 idx++;
6315 rmesc++;
6316 }
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00006317 } else {
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006318 idx = loc;
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00006319 }
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006320
6321 for (loc = repl; *loc; loc++) {
6322 restart_detect = stackblock();
6323 STPUTC(*loc, expdest);
6324 if (stackblock() != restart_detect)
6325 goto restart;
6326 len++;
6327 }
6328
6329 if (subtype == VSREPLACE) {
6330 while (*idx) {
6331 restart_detect = stackblock();
6332 STPUTC(*idx, expdest);
6333 if (stackblock() != restart_detect)
6334 goto restart;
6335 len++;
6336 idx++;
6337 }
6338 break;
6339 }
6340 }
6341
6342 /* We've put the replaced text into a buffer at workloc, now
6343 * move it to the right place and adjust the stack.
6344 */
6345 startp = stackblock() + startloc;
6346 STPUTC('\0', expdest);
6347 memmove(startp, stackblock() + workloc, len);
6348 startp[len++] = '\0';
6349 amount = expdest - ((char *)stackblock() + startloc + len - 1);
6350 STADJUST(-amount, expdest);
6351 return startp;
6352 }
6353#endif /* ENABLE_ASH_BASH_COMPAT */
6354
6355 subtype -= VSTRIMRIGHT;
6356#if DEBUG
6357 if (subtype < 0 || subtype > 7)
6358 abort();
6359#endif
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006360 /* zero = subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX */
6361 zero = subtype >> 1;
6362 /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
6363 scan = (subtype & 1) ^ zero ? scanleft : scanright;
6364
6365 loc = scan(startp, rmesc, rmescend, str, quotes, zero);
6366 if (loc) {
6367 if (zero) {
6368 memmove(startp, loc, str - loc);
6369 loc = startp + (str - loc) - 1;
6370 }
6371 *loc = '\0';
6372 amount = loc - expdest;
6373 STADJUST(amount, expdest);
6374 }
6375 return loc;
6376}
6377
6378/*
6379 * Add the value of a specialized variable to the stack string.
Denys Vlasenko4d8873f2009-10-04 03:14:41 +02006380 * name parameter (examples):
6381 * ash -c 'echo $1' name:'1='
6382 * ash -c 'echo $qwe' name:'qwe='
6383 * ash -c 'echo $$' name:'$='
6384 * ash -c 'echo ${$}' name:'$='
6385 * ash -c 'echo ${$##q}' name:'$=q'
6386 * ash -c 'echo ${#$}' name:'$='
6387 * note: examples with bad shell syntax:
6388 * ash -c 'echo ${#$1}' name:'$=1'
6389 * ash -c 'echo ${#1#}' name:'1=#'
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006390 */
Denys Vlasenkoadf922e2009-10-08 14:35:37 +02006391static NOINLINE ssize_t
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006392varvalue(char *name, int varflags, int flags, struct strlist *var_str_list)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006393{
6394 int num;
Mike Frysinger98c52642009-04-02 10:02:37 +00006395 const char *p;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006396 int i;
6397 int sep = 0;
6398 int sepq = 0;
6399 ssize_t len = 0;
6400 char **ap;
6401 int syntax;
6402 int quoted = varflags & VSQUOTE;
6403 int subtype = varflags & VSTYPE;
Denys Vlasenko1166d7b2009-09-16 16:20:31 +02006404 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006405
6406 if (quoted && (flags & EXP_FULL))
6407 sep = 1 << CHAR_BIT;
6408
6409 syntax = quoted ? DQSYNTAX : BASESYNTAX;
6410 switch (*name) {
6411 case '$':
6412 num = rootpid;
6413 goto numvar;
6414 case '?':
6415 num = exitstatus;
6416 goto numvar;
6417 case '#':
6418 num = shellparam.nparam;
6419 goto numvar;
6420 case '!':
6421 num = backgndpid;
6422 if (num == 0)
6423 return -1;
6424 numvar:
6425 len = cvtnum(num);
Denys Vlasenko4d8873f2009-10-04 03:14:41 +02006426 goto check_1char_name;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006427 case '-':
Mike Frysinger98c52642009-04-02 10:02:37 +00006428 expdest = makestrspace(NOPTS, expdest);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006429 for (i = NOPTS - 1; i >= 0; i--) {
6430 if (optlist[i]) {
Mike Frysinger98c52642009-04-02 10:02:37 +00006431 USTPUTC(optletters(i), expdest);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006432 len++;
6433 }
6434 }
Denys Vlasenko4d8873f2009-10-04 03:14:41 +02006435 check_1char_name:
6436#if 0
6437 /* handles cases similar to ${#$1} */
6438 if (name[2] != '\0')
6439 raise_error_syntax("bad substitution");
6440#endif
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006441 break;
6442 case '@':
6443 if (sep)
6444 goto param;
6445 /* fall through */
6446 case '*':
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00006447 sep = ifsset() ? signed_char2int(ifsval()[0]) : ' ';
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006448 if (quotes && (SIT(sep, syntax) == CCTL || SIT(sep, syntax) == CBACK))
6449 sepq = 1;
6450 param:
6451 ap = shellparam.p;
6452 if (!ap)
6453 return -1;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006454 while ((p = *ap++) != NULL) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006455 size_t partlen;
6456
6457 partlen = strlen(p);
6458 len += partlen;
6459
6460 if (!(subtype == VSPLUS || subtype == VSLENGTH))
6461 memtodest(p, partlen, syntax, quotes);
6462
6463 if (*ap && sep) {
6464 char *q;
6465
6466 len++;
6467 if (subtype == VSPLUS || subtype == VSLENGTH) {
6468 continue;
6469 }
6470 q = expdest;
6471 if (sepq)
6472 STPUTC(CTLESC, q);
6473 STPUTC(sep, q);
6474 expdest = q;
6475 }
6476 }
6477 return len;
6478 case '0':
6479 case '1':
6480 case '2':
6481 case '3':
6482 case '4':
6483 case '5':
6484 case '6':
6485 case '7':
6486 case '8':
6487 case '9':
Denys Vlasenkoa00329c2009-08-30 20:05:10 +02006488 num = atoi(name); /* number(name) fails on ${N#str} etc */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006489 if (num < 0 || num > shellparam.nparam)
6490 return -1;
6491 p = num ? shellparam.p[num - 1] : arg0;
6492 goto value;
6493 default:
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006494 /* NB: name has form "VAR=..." */
6495
6496 /* "A=a B=$A" case: var_str_list is a list of "A=a" strings
6497 * which should be considered before we check variables. */
6498 if (var_str_list) {
6499 unsigned name_len = (strchrnul(name, '=') - name) + 1;
6500 p = NULL;
6501 do {
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00006502 char *str, *eq;
6503 str = var_str_list->text;
6504 eq = strchr(str, '=');
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006505 if (!eq) /* stop at first non-assignment */
6506 break;
6507 eq++;
Denis Vlasenko6b06cb82008-05-15 21:30:45 +00006508 if (name_len == (unsigned)(eq - str)
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006509 && strncmp(str, name, name_len) == 0) {
6510 p = eq;
6511 /* goto value; - WRONG! */
6512 /* think "A=1 A=2 B=$A" */
6513 }
6514 var_str_list = var_str_list->next;
6515 } while (var_str_list);
6516 if (p)
6517 goto value;
6518 }
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006519 p = lookupvar(name);
6520 value:
6521 if (!p)
6522 return -1;
6523
6524 len = strlen(p);
6525 if (!(subtype == VSPLUS || subtype == VSLENGTH))
6526 memtodest(p, len, syntax, quotes);
6527 return len;
6528 }
6529
6530 if (subtype == VSPLUS || subtype == VSLENGTH)
6531 STADJUST(-len, expdest);
6532 return len;
6533}
6534
6535/*
6536 * Expand a variable, and return a pointer to the next character in the
6537 * input string.
6538 */
6539static char *
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006540evalvar(char *p, int flags, struct strlist *var_str_list)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006541{
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006542 char varflags;
6543 char subtype;
6544 char quoted;
6545 char easy;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006546 char *var;
6547 int patloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006548 int startloc;
6549 ssize_t varlen;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006550
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006551 varflags = (unsigned char) *p++;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006552 subtype = varflags & VSTYPE;
6553 quoted = varflags & VSQUOTE;
6554 var = p;
6555 easy = (!quoted || (*var == '@' && shellparam.nparam));
6556 startloc = expdest - (char *)stackblock();
6557 p = strchr(p, '=') + 1;
6558
6559 again:
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006560 varlen = varvalue(var, varflags, flags, var_str_list);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006561 if (varflags & VSNUL)
6562 varlen--;
6563
6564 if (subtype == VSPLUS) {
6565 varlen = -1 - varlen;
6566 goto vsplus;
6567 }
6568
6569 if (subtype == VSMINUS) {
6570 vsplus:
6571 if (varlen < 0) {
6572 argstr(
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006573 p, flags | EXP_TILDE |
6574 (quoted ? EXP_QWORD : EXP_WORD),
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006575 var_str_list
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006576 );
6577 goto end;
6578 }
6579 if (easy)
6580 goto record;
6581 goto end;
6582 }
6583
6584 if (subtype == VSASSIGN || subtype == VSQUESTION) {
6585 if (varlen < 0) {
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006586 if (subevalvar(p, var, /* strloc: */ 0,
6587 subtype, startloc, varflags,
6588 /* quotes: */ 0,
6589 var_str_list)
6590 ) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006591 varflags &= ~VSNUL;
6592 /*
6593 * Remove any recorded regions beyond
6594 * start of variable
6595 */
6596 removerecordregions(startloc);
6597 goto again;
6598 }
6599 goto end;
6600 }
6601 if (easy)
6602 goto record;
6603 goto end;
6604 }
6605
6606 if (varlen < 0 && uflag)
6607 varunset(p, var, 0, 0);
6608
6609 if (subtype == VSLENGTH) {
6610 cvtnum(varlen > 0 ? varlen : 0);
6611 goto record;
6612 }
6613
6614 if (subtype == VSNORMAL) {
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006615 if (easy)
6616 goto record;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006617 goto end;
6618 }
6619
6620#if DEBUG
6621 switch (subtype) {
6622 case VSTRIMLEFT:
6623 case VSTRIMLEFTMAX:
6624 case VSTRIMRIGHT:
6625 case VSTRIMRIGHTMAX:
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006626#if ENABLE_ASH_BASH_COMPAT
6627 case VSSUBSTR:
6628 case VSREPLACE:
6629 case VSREPLACEALL:
6630#endif
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006631 break;
6632 default:
6633 abort();
6634 }
6635#endif
6636
6637 if (varlen >= 0) {
6638 /*
6639 * Terminate the string and start recording the pattern
6640 * right after it
6641 */
6642 STPUTC('\0', expdest);
6643 patloc = expdest - (char *)stackblock();
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006644 if (0 == subevalvar(p, /* str: */ NULL, patloc, subtype,
6645 startloc, varflags,
Denys Vlasenko1166d7b2009-09-16 16:20:31 +02006646//TODO: | EXP_REDIR too? All other such places do it too
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006647 /* quotes: */ flags & (EXP_FULL | EXP_CASE),
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006648 var_str_list)
6649 ) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006650 int amount = expdest - (
6651 (char *)stackblock() + patloc - 1
6652 );
6653 STADJUST(-amount, expdest);
6654 }
6655 /* Remove any recorded regions beyond start of variable */
6656 removerecordregions(startloc);
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006657 record:
6658 recordregion(startloc, expdest - (char *)stackblock(), quoted);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006659 }
6660
6661 end:
6662 if (subtype != VSNORMAL) { /* skip to end of alternative */
6663 int nesting = 1;
6664 for (;;) {
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006665 char c = *p++;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006666 if (c == CTLESC)
6667 p++;
6668 else if (c == CTLBACKQ || c == (CTLBACKQ|CTLQUOTE)) {
6669 if (varlen >= 0)
6670 argbackq = argbackq->next;
6671 } else if (c == CTLVAR) {
6672 if ((*p++ & VSTYPE) != VSNORMAL)
6673 nesting++;
6674 } else if (c == CTLENDVAR) {
6675 if (--nesting == 0)
6676 break;
6677 }
6678 }
6679 }
6680 return p;
6681}
6682
6683/*
6684 * Break the argument string into pieces based upon IFS and add the
6685 * strings to the argument list. The regions of the string to be
6686 * searched for IFS characters have been stored by recordregion.
6687 */
6688static void
6689ifsbreakup(char *string, struct arglist *arglist)
6690{
6691 struct ifsregion *ifsp;
6692 struct strlist *sp;
6693 char *start;
6694 char *p;
6695 char *q;
6696 const char *ifs, *realifs;
6697 int ifsspc;
6698 int nulonly;
6699
6700 start = string;
6701 if (ifslastp != NULL) {
6702 ifsspc = 0;
6703 nulonly = 0;
6704 realifs = ifsset() ? ifsval() : defifs;
6705 ifsp = &ifsfirst;
6706 do {
6707 p = string + ifsp->begoff;
6708 nulonly = ifsp->nulonly;
6709 ifs = nulonly ? nullstr : realifs;
6710 ifsspc = 0;
6711 while (p < string + ifsp->endoff) {
6712 q = p;
6713 if (*p == CTLESC)
6714 p++;
6715 if (!strchr(ifs, *p)) {
6716 p++;
6717 continue;
6718 }
6719 if (!nulonly)
6720 ifsspc = (strchr(defifs, *p) != NULL);
6721 /* Ignore IFS whitespace at start */
6722 if (q == start && ifsspc) {
6723 p++;
6724 start = p;
6725 continue;
6726 }
6727 *q = '\0';
Denis Vlasenko597906c2008-02-20 16:38:54 +00006728 sp = stzalloc(sizeof(*sp));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006729 sp->text = start;
6730 *arglist->lastp = sp;
6731 arglist->lastp = &sp->next;
6732 p++;
6733 if (!nulonly) {
6734 for (;;) {
6735 if (p >= string + ifsp->endoff) {
6736 break;
6737 }
6738 q = p;
6739 if (*p == CTLESC)
6740 p++;
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +00006741 if (strchr(ifs, *p) == NULL) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006742 p = q;
6743 break;
Denis Vlasenko597906c2008-02-20 16:38:54 +00006744 }
6745 if (strchr(defifs, *p) == NULL) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006746 if (ifsspc) {
6747 p++;
6748 ifsspc = 0;
6749 } else {
6750 p = q;
6751 break;
6752 }
6753 } else
6754 p++;
6755 }
6756 }
6757 start = p;
6758 } /* while */
6759 ifsp = ifsp->next;
6760 } while (ifsp != NULL);
6761 if (nulonly)
6762 goto add;
6763 }
6764
6765 if (!*start)
6766 return;
6767
6768 add:
Denis Vlasenko597906c2008-02-20 16:38:54 +00006769 sp = stzalloc(sizeof(*sp));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006770 sp->text = start;
6771 *arglist->lastp = sp;
6772 arglist->lastp = &sp->next;
6773}
6774
6775static void
6776ifsfree(void)
6777{
6778 struct ifsregion *p;
6779
6780 INT_OFF;
6781 p = ifsfirst.next;
6782 do {
6783 struct ifsregion *ifsp;
6784 ifsp = p->next;
6785 free(p);
6786 p = ifsp;
6787 } while (p);
6788 ifslastp = NULL;
6789 ifsfirst.next = NULL;
6790 INT_ON;
6791}
6792
6793/*
6794 * Add a file name to the list.
6795 */
6796static void
6797addfname(const char *name)
6798{
6799 struct strlist *sp;
6800
Denis Vlasenko597906c2008-02-20 16:38:54 +00006801 sp = stzalloc(sizeof(*sp));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006802 sp->text = ststrdup(name);
6803 *exparg.lastp = sp;
6804 exparg.lastp = &sp->next;
6805}
6806
6807static char *expdir;
6808
6809/*
6810 * Do metacharacter (i.e. *, ?, [...]) expansion.
6811 */
6812static void
6813expmeta(char *enddir, char *name)
6814{
6815 char *p;
6816 const char *cp;
6817 char *start;
6818 char *endname;
6819 int metaflag;
6820 struct stat statb;
6821 DIR *dirp;
6822 struct dirent *dp;
6823 int atend;
6824 int matchdot;
6825
6826 metaflag = 0;
6827 start = name;
6828 for (p = name; *p; p++) {
6829 if (*p == '*' || *p == '?')
6830 metaflag = 1;
6831 else if (*p == '[') {
6832 char *q = p + 1;
6833 if (*q == '!')
6834 q++;
6835 for (;;) {
6836 if (*q == '\\')
6837 q++;
6838 if (*q == '/' || *q == '\0')
6839 break;
6840 if (*++q == ']') {
6841 metaflag = 1;
6842 break;
6843 }
6844 }
6845 } else if (*p == '\\')
6846 p++;
6847 else if (*p == '/') {
6848 if (metaflag)
6849 goto out;
6850 start = p + 1;
6851 }
6852 }
6853 out:
6854 if (metaflag == 0) { /* we've reached the end of the file name */
6855 if (enddir != expdir)
6856 metaflag++;
6857 p = name;
6858 do {
6859 if (*p == '\\')
6860 p++;
6861 *enddir++ = *p;
6862 } while (*p++);
6863 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
6864 addfname(expdir);
6865 return;
6866 }
6867 endname = p;
6868 if (name < start) {
6869 p = name;
6870 do {
6871 if (*p == '\\')
6872 p++;
6873 *enddir++ = *p++;
6874 } while (p < start);
6875 }
6876 if (enddir == expdir) {
6877 cp = ".";
6878 } else if (enddir == expdir + 1 && *expdir == '/') {
6879 cp = "/";
6880 } else {
6881 cp = expdir;
6882 enddir[-1] = '\0';
6883 }
6884 dirp = opendir(cp);
6885 if (dirp == NULL)
6886 return;
6887 if (enddir != expdir)
6888 enddir[-1] = '/';
6889 if (*endname == 0) {
6890 atend = 1;
6891 } else {
6892 atend = 0;
6893 *endname++ = '\0';
6894 }
6895 matchdot = 0;
6896 p = start;
6897 if (*p == '\\')
6898 p++;
6899 if (*p == '.')
6900 matchdot++;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006901 while (!pending_int && (dp = readdir(dirp)) != NULL) {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00006902 if (dp->d_name[0] == '.' && !matchdot)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006903 continue;
6904 if (pmatch(start, dp->d_name)) {
6905 if (atend) {
6906 strcpy(enddir, dp->d_name);
6907 addfname(expdir);
6908 } else {
6909 for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
6910 continue;
6911 p[-1] = '/';
6912 expmeta(p, endname);
6913 }
6914 }
6915 }
6916 closedir(dirp);
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00006917 if (!atend)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006918 endname[-1] = '/';
6919}
6920
6921static struct strlist *
6922msort(struct strlist *list, int len)
6923{
6924 struct strlist *p, *q = NULL;
6925 struct strlist **lpp;
6926 int half;
6927 int n;
6928
6929 if (len <= 1)
6930 return list;
6931 half = len >> 1;
6932 p = list;
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +00006933 for (n = half; --n >= 0;) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006934 q = p;
6935 p = p->next;
6936 }
6937 q->next = NULL; /* terminate first half of list */
6938 q = msort(list, half); /* sort first half of list */
6939 p = msort(p, len - half); /* sort second half */
6940 lpp = &list;
6941 for (;;) {
6942#if ENABLE_LOCALE_SUPPORT
6943 if (strcoll(p->text, q->text) < 0)
6944#else
6945 if (strcmp(p->text, q->text) < 0)
6946#endif
6947 {
6948 *lpp = p;
6949 lpp = &p->next;
6950 p = *lpp;
6951 if (p == NULL) {
6952 *lpp = q;
6953 break;
6954 }
6955 } else {
6956 *lpp = q;
6957 lpp = &q->next;
6958 q = *lpp;
6959 if (q == NULL) {
6960 *lpp = p;
6961 break;
6962 }
6963 }
6964 }
6965 return list;
6966}
6967
6968/*
6969 * Sort the results of file name expansion. It calculates the number of
6970 * strings to sort and then calls msort (short for merge sort) to do the
6971 * work.
6972 */
6973static struct strlist *
6974expsort(struct strlist *str)
6975{
6976 int len;
6977 struct strlist *sp;
6978
6979 len = 0;
6980 for (sp = str; sp; sp = sp->next)
6981 len++;
6982 return msort(str, len);
6983}
6984
6985static void
Denis Vlasenko68404f12008-03-17 09:00:54 +00006986expandmeta(struct strlist *str /*, int flag*/)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006987{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00006988 static const char metachars[] ALIGN1 = {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006989 '*', '?', '[', 0
6990 };
6991 /* TODO - EXP_REDIR */
6992
6993 while (str) {
6994 struct strlist **savelastp;
6995 struct strlist *sp;
6996 char *p;
6997
6998 if (fflag)
6999 goto nometa;
7000 if (!strpbrk(str->text, metachars))
7001 goto nometa;
7002 savelastp = exparg.lastp;
7003
7004 INT_OFF;
7005 p = preglob(str->text, 0, RMESCAPE_ALLOC | RMESCAPE_HEAP);
7006 {
7007 int i = strlen(str->text);
7008 expdir = ckmalloc(i < 2048 ? 2048 : i); /* XXX */
7009 }
7010
7011 expmeta(expdir, p);
7012 free(expdir);
7013 if (p != str->text)
7014 free(p);
7015 INT_ON;
7016 if (exparg.lastp == savelastp) {
7017 /*
7018 * no matches
7019 */
7020 nometa:
7021 *exparg.lastp = str;
Denys Vlasenkob6c84342009-08-29 20:23:20 +02007022 rmescapes(str->text, 0);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007023 exparg.lastp = &str->next;
7024 } else {
7025 *exparg.lastp = NULL;
7026 *savelastp = sp = expsort(*savelastp);
7027 while (sp->next != NULL)
7028 sp = sp->next;
7029 exparg.lastp = &sp->next;
7030 }
7031 str = str->next;
7032 }
7033}
7034
7035/*
7036 * Perform variable substitution and command substitution on an argument,
7037 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
7038 * perform splitting and file name expansion. When arglist is NULL, perform
7039 * here document expansion.
7040 */
7041static void
7042expandarg(union node *arg, struct arglist *arglist, int flag)
7043{
7044 struct strlist *sp;
7045 char *p;
7046
7047 argbackq = arg->narg.backquote;
7048 STARTSTACKSTR(expdest);
7049 ifsfirst.next = NULL;
7050 ifslastp = NULL;
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00007051 argstr(arg->narg.text, flag,
7052 /* var_str_list: */ arglist ? arglist->list : NULL);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007053 p = _STPUTC('\0', expdest);
7054 expdest = p - 1;
7055 if (arglist == NULL) {
7056 return; /* here document expanded */
7057 }
7058 p = grabstackstr(p);
7059 exparg.lastp = &exparg.list;
7060 /*
7061 * TODO - EXP_REDIR
7062 */
7063 if (flag & EXP_FULL) {
7064 ifsbreakup(p, &exparg);
7065 *exparg.lastp = NULL;
7066 exparg.lastp = &exparg.list;
Denis Vlasenko68404f12008-03-17 09:00:54 +00007067 expandmeta(exparg.list /*, flag*/);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007068 } else {
7069 if (flag & EXP_REDIR) /*XXX - for now, just remove escapes */
Denys Vlasenkob6c84342009-08-29 20:23:20 +02007070 rmescapes(p, 0);
Denis Vlasenko597906c2008-02-20 16:38:54 +00007071 sp = stzalloc(sizeof(*sp));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007072 sp->text = p;
7073 *exparg.lastp = sp;
7074 exparg.lastp = &sp->next;
7075 }
7076 if (ifsfirst.next)
7077 ifsfree();
7078 *exparg.lastp = NULL;
7079 if (exparg.list) {
7080 *arglist->lastp = exparg.list;
7081 arglist->lastp = exparg.lastp;
7082 }
7083}
7084
7085/*
7086 * Expand shell variables and backquotes inside a here document.
7087 */
7088static void
7089expandhere(union node *arg, int fd)
7090{
7091 herefd = fd;
7092 expandarg(arg, (struct arglist *)NULL, 0);
7093 full_write(fd, stackblock(), expdest - (char *)stackblock());
7094}
7095
7096/*
7097 * Returns true if the pattern matches the string.
7098 */
7099static int
7100patmatch(char *pattern, const char *string)
7101{
7102 return pmatch(preglob(pattern, 0, 0), string);
7103}
7104
7105/*
7106 * See if a pattern matches in a case statement.
7107 */
7108static int
7109casematch(union node *pattern, char *val)
7110{
7111 struct stackmark smark;
7112 int result;
7113
7114 setstackmark(&smark);
7115 argbackq = pattern->narg.backquote;
7116 STARTSTACKSTR(expdest);
7117 ifslastp = NULL;
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00007118 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE,
7119 /* var_str_list: */ NULL);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007120 STACKSTRNUL(expdest);
7121 result = patmatch(stackblock(), val);
7122 popstackmark(&smark);
7123 return result;
7124}
7125
7126
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007127/* ============ find_command */
7128
7129struct builtincmd {
7130 const char *name;
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007131 int (*builtin)(int, char **) FAST_FUNC;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007132 /* unsigned flags; */
7133};
7134#define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
Denis Vlasenkoe26b2782008-02-12 07:40:29 +00007135/* "regular" builtins always take precedence over commands,
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007136 * regardless of PATH=....%builtin... position */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007137#define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007138#define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007139
7140struct cmdentry {
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00007141 smallint cmdtype; /* CMDxxx */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007142 union param {
7143 int index;
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00007144 /* index >= 0 for commands without path (slashes) */
7145 /* (TODO: what exactly does the value mean? PATH position?) */
7146 /* index == -1 for commands with slashes */
7147 /* index == (-2 - applet_no) for NOFORK applets */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007148 const struct builtincmd *cmd;
7149 struct funcnode *func;
7150 } u;
7151};
7152/* values of cmdtype */
7153#define CMDUNKNOWN -1 /* no entry in table for command */
7154#define CMDNORMAL 0 /* command is an executable program */
7155#define CMDFUNCTION 1 /* command is a shell function */
7156#define CMDBUILTIN 2 /* command is a shell builtin */
7157
7158/* action to find_command() */
7159#define DO_ERR 0x01 /* prints errors */
7160#define DO_ABS 0x02 /* checks absolute paths */
7161#define DO_NOFUNC 0x04 /* don't return shell functions, for command */
7162#define DO_ALTPATH 0x08 /* using alternate path */
7163#define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
7164
7165static void find_command(char *, struct cmdentry *, int, const char *);
7166
7167
7168/* ============ Hashing commands */
7169
7170/*
7171 * When commands are first encountered, they are entered in a hash table.
7172 * This ensures that a full path search will not have to be done for them
7173 * on each invocation.
7174 *
7175 * We should investigate converting to a linear search, even though that
7176 * would make the command name "hash" a misnomer.
7177 */
7178
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007179struct tblentry {
7180 struct tblentry *next; /* next entry in hash chain */
7181 union param param; /* definition of builtin function */
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00007182 smallint cmdtype; /* CMDxxx */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007183 char rehash; /* if set, cd done since entry created */
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007184 char cmdname[1]; /* name of command */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007185};
7186
Denis Vlasenko01631112007-12-16 17:20:38 +00007187static struct tblentry **cmdtable;
7188#define INIT_G_cmdtable() do { \
7189 cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
7190} while (0)
7191
7192static int builtinloc = -1; /* index in path of %builtin, or -1 */
7193
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007194
7195static void
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00007196tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) char *cmd, char **argv, char **envp)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007197{
7198 int repeated = 0;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007199
Denis Vlasenko80d14be2007-04-10 23:03:30 +00007200#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007201 if (applet_no >= 0) {
Denis Vlasenkob7304742008-10-20 08:15:51 +00007202 if (APPLET_IS_NOEXEC(applet_no)) {
7203 while (*envp)
7204 putenv(*envp++);
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007205 run_applet_no_and_exit(applet_no, argv);
Denis Vlasenkob7304742008-10-20 08:15:51 +00007206 }
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007207 /* re-exec ourselves with the new arguments */
7208 execve(bb_busybox_exec_path, argv, envp);
7209 /* If they called chroot or otherwise made the binary no longer
7210 * executable, fall through */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007211 }
7212#endif
7213
7214 repeat:
7215#ifdef SYSV
7216 do {
7217 execve(cmd, argv, envp);
7218 } while (errno == EINTR);
7219#else
7220 execve(cmd, argv, envp);
7221#endif
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007222 if (repeated) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007223 free(argv);
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007224 return;
7225 }
7226 if (errno == ENOEXEC) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007227 char **ap;
7228 char **new;
7229
7230 for (ap = argv; *ap; ap++)
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007231 continue;
7232 ap = new = ckmalloc((ap - argv + 2) * sizeof(ap[0]));
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007233 ap[1] = cmd;
Denis Vlasenkoc44ab012007-04-09 03:11:58 +00007234 ap[0] = cmd = (char *)DEFAULT_SHELL;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007235 ap += 2;
7236 argv++;
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007237 while ((*ap++ = *argv++) != NULL)
Denis Vlasenko597906c2008-02-20 16:38:54 +00007238 continue;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007239 argv = new;
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007240 repeated++;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007241 goto repeat;
7242 }
7243}
7244
7245/*
7246 * Exec a program. Never returns. If you change this routine, you may
7247 * have to change the find_command routine as well.
7248 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00007249static void shellexec(char **, const char *, int) NORETURN;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007250static void
7251shellexec(char **argv, const char *path, int idx)
7252{
7253 char *cmdname;
7254 int e;
7255 char **envp;
7256 int exerrno;
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007257#if ENABLE_FEATURE_SH_STANDALONE
7258 int applet_no = -1;
7259#endif
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007260
Denis Vlasenko34c73c42008-08-16 11:48:02 +00007261 clearredir(/*drop:*/ 1);
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007262 envp = listvars(VEXPORT, VUNSET, 0);
7263 if (strchr(argv[0], '/') != NULL
Denis Vlasenko80d14be2007-04-10 23:03:30 +00007264#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007265 || (applet_no = find_applet_by_name(argv[0])) >= 0
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007266#endif
7267 ) {
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00007268 tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) argv[0], argv, envp);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007269 e = errno;
7270 } else {
7271 e = ENOENT;
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02007272 while ((cmdname = path_advance(&path, argv[0])) != NULL) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007273 if (--idx < 0 && pathopt == NULL) {
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00007274 tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007275 if (errno != ENOENT && errno != ENOTDIR)
7276 e = errno;
7277 }
7278 stunalloc(cmdname);
7279 }
7280 }
7281
7282 /* Map to POSIX errors */
7283 switch (e) {
7284 case EACCES:
7285 exerrno = 126;
7286 break;
7287 case ENOENT:
7288 exerrno = 127;
7289 break;
7290 default:
7291 exerrno = 2;
7292 break;
7293 }
7294 exitstatus = exerrno;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02007295 TRACE(("shellexec failed for %s, errno %d, suppress_int %d\n",
7296 argv[0], e, suppress_int));
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007297 ash_msg_and_raise(EXEXEC, "%s: %s", argv[0], errmsg(e, "not found"));
7298 /* NOTREACHED */
7299}
7300
7301static void
7302printentry(struct tblentry *cmdp)
7303{
7304 int idx;
7305 const char *path;
7306 char *name;
7307
7308 idx = cmdp->param.index;
7309 path = pathval();
7310 do {
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02007311 name = path_advance(&path, cmdp->cmdname);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007312 stunalloc(name);
7313 } while (--idx >= 0);
7314 out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
7315}
7316
7317/*
7318 * Clear out command entries. The argument specifies the first entry in
7319 * PATH which has changed.
7320 */
7321static void
7322clearcmdentry(int firstchange)
7323{
7324 struct tblentry **tblp;
7325 struct tblentry **pp;
7326 struct tblentry *cmdp;
7327
7328 INT_OFF;
7329 for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
7330 pp = tblp;
7331 while ((cmdp = *pp) != NULL) {
7332 if ((cmdp->cmdtype == CMDNORMAL &&
7333 cmdp->param.index >= firstchange)
7334 || (cmdp->cmdtype == CMDBUILTIN &&
7335 builtinloc >= firstchange)
7336 ) {
7337 *pp = cmdp->next;
7338 free(cmdp);
7339 } else {
7340 pp = &cmdp->next;
7341 }
7342 }
7343 }
7344 INT_ON;
7345}
7346
7347/*
7348 * Locate a command in the command hash table. If "add" is nonzero,
7349 * add the command to the table if it is not already present. The
7350 * variable "lastcmdentry" is set to point to the address of the link
7351 * pointing to the entry, so that delete_cmd_entry can delete the
7352 * entry.
7353 *
7354 * Interrupts must be off if called with add != 0.
7355 */
7356static struct tblentry **lastcmdentry;
7357
7358static struct tblentry *
7359cmdlookup(const char *name, int add)
7360{
7361 unsigned int hashval;
7362 const char *p;
7363 struct tblentry *cmdp;
7364 struct tblentry **pp;
7365
7366 p = name;
7367 hashval = (unsigned char)*p << 4;
7368 while (*p)
7369 hashval += (unsigned char)*p++;
7370 hashval &= 0x7FFF;
7371 pp = &cmdtable[hashval % CMDTABLESIZE];
7372 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7373 if (strcmp(cmdp->cmdname, name) == 0)
7374 break;
7375 pp = &cmdp->next;
7376 }
7377 if (add && cmdp == NULL) {
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007378 cmdp = *pp = ckzalloc(sizeof(struct tblentry)
7379 + strlen(name)
7380 /* + 1 - already done because
7381 * tblentry::cmdname is char[1] */);
Denis Vlasenko597906c2008-02-20 16:38:54 +00007382 /*cmdp->next = NULL; - ckzalloc did it */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007383 cmdp->cmdtype = CMDUNKNOWN;
7384 strcpy(cmdp->cmdname, name);
7385 }
7386 lastcmdentry = pp;
7387 return cmdp;
7388}
7389
7390/*
7391 * Delete the command entry returned on the last lookup.
7392 */
7393static void
7394delete_cmd_entry(void)
7395{
7396 struct tblentry *cmdp;
7397
7398 INT_OFF;
7399 cmdp = *lastcmdentry;
7400 *lastcmdentry = cmdp->next;
7401 if (cmdp->cmdtype == CMDFUNCTION)
7402 freefunc(cmdp->param.func);
7403 free(cmdp);
7404 INT_ON;
7405}
7406
7407/*
7408 * Add a new command entry, replacing any existing command entry for
7409 * the same name - except special builtins.
7410 */
7411static void
7412addcmdentry(char *name, struct cmdentry *entry)
7413{
7414 struct tblentry *cmdp;
7415
7416 cmdp = cmdlookup(name, 1);
7417 if (cmdp->cmdtype == CMDFUNCTION) {
7418 freefunc(cmdp->param.func);
7419 }
7420 cmdp->cmdtype = entry->cmdtype;
7421 cmdp->param = entry->u;
7422 cmdp->rehash = 0;
7423}
7424
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007425static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00007426hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007427{
7428 struct tblentry **pp;
7429 struct tblentry *cmdp;
7430 int c;
7431 struct cmdentry entry;
7432 char *name;
7433
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007434 if (nextopt("r") != '\0') {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007435 clearcmdentry(0);
7436 return 0;
7437 }
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007438
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007439 if (*argptr == NULL) {
7440 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7441 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7442 if (cmdp->cmdtype == CMDNORMAL)
7443 printentry(cmdp);
7444 }
7445 }
7446 return 0;
7447 }
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007448
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007449 c = 0;
7450 while ((name = *argptr) != NULL) {
7451 cmdp = cmdlookup(name, 0);
7452 if (cmdp != NULL
7453 && (cmdp->cmdtype == CMDNORMAL
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007454 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
7455 ) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007456 delete_cmd_entry();
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007457 }
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007458 find_command(name, &entry, DO_ERR, pathval());
7459 if (entry.cmdtype == CMDUNKNOWN)
7460 c = 1;
7461 argptr++;
7462 }
7463 return c;
7464}
7465
7466/*
7467 * Called when a cd is done. Marks all commands so the next time they
7468 * are executed they will be rehashed.
7469 */
7470static void
7471hashcd(void)
7472{
7473 struct tblentry **pp;
7474 struct tblentry *cmdp;
7475
7476 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7477 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007478 if (cmdp->cmdtype == CMDNORMAL
7479 || (cmdp->cmdtype == CMDBUILTIN
7480 && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
7481 && builtinloc > 0)
7482 ) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007483 cmdp->rehash = 1;
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007484 }
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007485 }
7486 }
7487}
7488
7489/*
7490 * Fix command hash table when PATH changed.
7491 * Called before PATH is changed. The argument is the new value of PATH;
7492 * pathval() still returns the old value at this point.
7493 * Called with interrupts off.
7494 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007495static void FAST_FUNC
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007496changepath(const char *new)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007497{
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007498 const char *old;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007499 int firstchange;
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007500 int idx;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007501 int idx_bltin;
7502
7503 old = pathval();
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007504 firstchange = 9999; /* assume no change */
7505 idx = 0;
7506 idx_bltin = -1;
7507 for (;;) {
7508 if (*old != *new) {
7509 firstchange = idx;
7510 if ((*old == '\0' && *new == ':')
7511 || (*old == ':' && *new == '\0'))
7512 firstchange++;
7513 old = new; /* ignore subsequent differences */
7514 }
7515 if (*new == '\0')
7516 break;
7517 if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
7518 idx_bltin = idx;
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007519 if (*new == ':')
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007520 idx++;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007521 new++, old++;
7522 }
7523 if (builtinloc < 0 && idx_bltin >= 0)
7524 builtinloc = idx_bltin; /* zap builtins */
7525 if (builtinloc >= 0 && idx_bltin < 0)
7526 firstchange = 0;
7527 clearcmdentry(firstchange);
7528 builtinloc = idx_bltin;
7529}
7530
7531#define TEOF 0
7532#define TNL 1
7533#define TREDIR 2
7534#define TWORD 3
7535#define TSEMI 4
7536#define TBACKGND 5
7537#define TAND 6
7538#define TOR 7
7539#define TPIPE 8
7540#define TLP 9
7541#define TRP 10
7542#define TENDCASE 11
7543#define TENDBQUOTE 12
7544#define TNOT 13
7545#define TCASE 14
7546#define TDO 15
7547#define TDONE 16
7548#define TELIF 17
7549#define TELSE 18
7550#define TESAC 19
7551#define TFI 20
7552#define TFOR 21
7553#define TIF 22
7554#define TIN 23
7555#define TTHEN 24
7556#define TUNTIL 25
7557#define TWHILE 26
7558#define TBEGIN 27
7559#define TEND 28
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007560typedef smallint token_id_t;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007561
7562/* first char is indicating which tokens mark the end of a list */
7563static const char *const tokname_array[] = {
7564 "\1end of file",
7565 "\0newline",
7566 "\0redirection",
7567 "\0word",
7568 "\0;",
7569 "\0&",
7570 "\0&&",
7571 "\0||",
7572 "\0|",
7573 "\0(",
7574 "\1)",
7575 "\1;;",
7576 "\1`",
7577#define KWDOFFSET 13
7578 /* the following are keywords */
7579 "\0!",
7580 "\0case",
7581 "\1do",
7582 "\1done",
7583 "\1elif",
7584 "\1else",
7585 "\1esac",
7586 "\1fi",
7587 "\0for",
7588 "\0if",
7589 "\0in",
7590 "\1then",
7591 "\0until",
7592 "\0while",
7593 "\0{",
7594 "\1}",
7595};
7596
7597static const char *
7598tokname(int tok)
7599{
7600 static char buf[16];
7601
Denis Vlasenko240a1cf2007-04-08 16:07:02 +00007602//try this:
7603//if (tok < TSEMI) return tokname_array[tok] + 1;
7604//sprintf(buf, "\"%s\"", tokname_array[tok] + 1);
7605//return buf;
7606
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007607 if (tok >= TSEMI)
7608 buf[0] = '"';
7609 sprintf(buf + (tok >= TSEMI), "%s%c",
7610 tokname_array[tok] + 1, (tok >= TSEMI ? '"' : 0));
7611 return buf;
7612}
7613
7614/* Wrapper around strcmp for qsort/bsearch/... */
7615static int
7616pstrcmp(const void *a, const void *b)
7617{
Denis Vlasenko240a1cf2007-04-08 16:07:02 +00007618 return strcmp((char*) a, (*(char**) b) + 1);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007619}
7620
7621static const char *const *
7622findkwd(const char *s)
7623{
7624 return bsearch(s, tokname_array + KWDOFFSET,
Denis Vlasenko80b8b392007-06-25 10:55:35 +00007625 ARRAY_SIZE(tokname_array) - KWDOFFSET,
7626 sizeof(tokname_array[0]), pstrcmp);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007627}
7628
7629/*
7630 * Locate and print what a word is...
7631 */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007632static int
7633describe_command(char *command, int describe_command_verbose)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007634{
7635 struct cmdentry entry;
7636 struct tblentry *cmdp;
7637#if ENABLE_ASH_ALIAS
7638 const struct alias *ap;
7639#endif
7640 const char *path = pathval();
7641
7642 if (describe_command_verbose) {
7643 out1str(command);
7644 }
7645
7646 /* First look at the keywords */
7647 if (findkwd(command)) {
7648 out1str(describe_command_verbose ? " is a shell keyword" : command);
7649 goto out;
7650 }
7651
7652#if ENABLE_ASH_ALIAS
7653 /* Then look at the aliases */
7654 ap = lookupalias(command, 0);
7655 if (ap != NULL) {
Denis Vlasenko46846e22007-05-20 13:08:31 +00007656 if (!describe_command_verbose) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007657 out1str("alias ");
7658 printalias(ap);
7659 return 0;
7660 }
Denis Vlasenko46846e22007-05-20 13:08:31 +00007661 out1fmt(" is an alias for %s", ap->val);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007662 goto out;
7663 }
7664#endif
7665 /* Then check if it is a tracked alias */
7666 cmdp = cmdlookup(command, 0);
7667 if (cmdp != NULL) {
7668 entry.cmdtype = cmdp->cmdtype;
7669 entry.u = cmdp->param;
7670 } else {
7671 /* Finally use brute force */
7672 find_command(command, &entry, DO_ABS, path);
7673 }
7674
7675 switch (entry.cmdtype) {
7676 case CMDNORMAL: {
7677 int j = entry.u.index;
7678 char *p;
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00007679 if (j < 0) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007680 p = command;
7681 } else {
7682 do {
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02007683 p = path_advance(&path, command);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007684 stunalloc(p);
7685 } while (--j >= 0);
7686 }
7687 if (describe_command_verbose) {
7688 out1fmt(" is%s %s",
7689 (cmdp ? " a tracked alias for" : nullstr), p
7690 );
7691 } else {
7692 out1str(p);
7693 }
7694 break;
7695 }
7696
7697 case CMDFUNCTION:
7698 if (describe_command_verbose) {
7699 out1str(" is a shell function");
7700 } else {
7701 out1str(command);
7702 }
7703 break;
7704
7705 case CMDBUILTIN:
7706 if (describe_command_verbose) {
7707 out1fmt(" is a %sshell builtin",
7708 IS_BUILTIN_SPECIAL(entry.u.cmd) ?
7709 "special " : nullstr
7710 );
7711 } else {
7712 out1str(command);
7713 }
7714 break;
7715
7716 default:
7717 if (describe_command_verbose) {
7718 out1str(": not found\n");
7719 }
7720 return 127;
7721 }
7722 out:
7723 outstr("\n", stdout);
7724 return 0;
7725}
7726
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007727static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00007728typecmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007729{
Denis Vlasenko46846e22007-05-20 13:08:31 +00007730 int i = 1;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007731 int err = 0;
Denis Vlasenko46846e22007-05-20 13:08:31 +00007732 int verbose = 1;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007733
Denis Vlasenko46846e22007-05-20 13:08:31 +00007734 /* type -p ... ? (we don't bother checking for 'p') */
Denis Vlasenko1fc62382007-06-25 22:55:34 +00007735 if (argv[1] && argv[1][0] == '-') {
Denis Vlasenko46846e22007-05-20 13:08:31 +00007736 i++;
7737 verbose = 0;
7738 }
Denis Vlasenko68404f12008-03-17 09:00:54 +00007739 while (argv[i]) {
Denis Vlasenko46846e22007-05-20 13:08:31 +00007740 err |= describe_command(argv[i++], verbose);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007741 }
7742 return err;
7743}
7744
7745#if ENABLE_ASH_CMDCMD
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007746static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00007747commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007748{
7749 int c;
7750 enum {
7751 VERIFY_BRIEF = 1,
7752 VERIFY_VERBOSE = 2,
7753 } verify = 0;
7754
7755 while ((c = nextopt("pvV")) != '\0')
7756 if (c == 'V')
7757 verify |= VERIFY_VERBOSE;
7758 else if (c == 'v')
7759 verify |= VERIFY_BRIEF;
7760#if DEBUG
7761 else if (c != 'p')
7762 abort();
7763#endif
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00007764 /* Mimic bash: just "command -v" doesn't complain, it's a nop */
7765 if (verify && (*argptr != NULL)) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007766 return describe_command(*argptr, verify - VERIFY_BRIEF);
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00007767 }
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007768
7769 return 0;
7770}
7771#endif
7772
7773
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007774/* ============ eval.c */
Eric Andersencb57d552001-06-28 07:25:16 +00007775
Denis Vlasenko340299a2008-11-21 10:36:36 +00007776static int funcblocksize; /* size of structures in function */
7777static int funcstringsize; /* size of strings in node */
7778static void *funcblock; /* block to allocate function from */
7779static char *funcstring; /* block to allocate strings from */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007780
Eric Andersencb57d552001-06-28 07:25:16 +00007781/* flags in argument to evaltree */
Denis Vlasenko340299a2008-11-21 10:36:36 +00007782#define EV_EXIT 01 /* exit after evaluating tree */
7783#define EV_TESTED 02 /* exit status is checked; ignore -e flag */
Eric Andersenc470f442003-07-28 09:56:35 +00007784#define EV_BACKCMD 04 /* command executing within back quotes */
Eric Andersencb57d552001-06-28 07:25:16 +00007785
Denys Vlasenko0e5e4ea2009-10-11 00:36:20 +02007786static const uint8_t nodesize[N_NUMBER] = {
Denis Vlasenko340299a2008-11-21 10:36:36 +00007787 [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
7788 [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
7789 [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
7790 [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
7791 [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
7792 [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
7793 [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
7794 [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
7795 [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
7796 [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
7797 [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
7798 [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
7799 [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
7800 [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
7801 [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
7802 [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
7803 [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
Denis Vlasenkocc5feab2008-11-22 01:32:40 +00007804#if ENABLE_ASH_BASH_COMPAT
Denis Vlasenko340299a2008-11-21 10:36:36 +00007805 [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
Denis Vlasenkocc5feab2008-11-22 01:32:40 +00007806#endif
Denis Vlasenko340299a2008-11-21 10:36:36 +00007807 [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
7808 [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
7809 [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
7810 [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
7811 [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
7812 [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
7813 [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
7814 [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
7815 [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007816};
7817
7818static void calcsize(union node *n);
7819
7820static void
7821sizenodelist(struct nodelist *lp)
7822{
7823 while (lp) {
7824 funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
7825 calcsize(lp->n);
7826 lp = lp->next;
7827 }
7828}
7829
7830static void
7831calcsize(union node *n)
7832{
7833 if (n == NULL)
7834 return;
7835 funcblocksize += nodesize[n->type];
7836 switch (n->type) {
7837 case NCMD:
7838 calcsize(n->ncmd.redirect);
7839 calcsize(n->ncmd.args);
7840 calcsize(n->ncmd.assign);
7841 break;
7842 case NPIPE:
7843 sizenodelist(n->npipe.cmdlist);
7844 break;
7845 case NREDIR:
7846 case NBACKGND:
7847 case NSUBSHELL:
7848 calcsize(n->nredir.redirect);
7849 calcsize(n->nredir.n);
7850 break;
7851 case NAND:
7852 case NOR:
7853 case NSEMI:
7854 case NWHILE:
7855 case NUNTIL:
7856 calcsize(n->nbinary.ch2);
7857 calcsize(n->nbinary.ch1);
7858 break;
7859 case NIF:
7860 calcsize(n->nif.elsepart);
7861 calcsize(n->nif.ifpart);
7862 calcsize(n->nif.test);
7863 break;
7864 case NFOR:
7865 funcstringsize += strlen(n->nfor.var) + 1;
7866 calcsize(n->nfor.body);
7867 calcsize(n->nfor.args);
7868 break;
7869 case NCASE:
7870 calcsize(n->ncase.cases);
7871 calcsize(n->ncase.expr);
7872 break;
7873 case NCLIST:
7874 calcsize(n->nclist.body);
7875 calcsize(n->nclist.pattern);
7876 calcsize(n->nclist.next);
7877 break;
7878 case NDEFUN:
7879 case NARG:
7880 sizenodelist(n->narg.backquote);
7881 funcstringsize += strlen(n->narg.text) + 1;
7882 calcsize(n->narg.next);
7883 break;
7884 case NTO:
Denis Vlasenko559691a2008-10-05 18:39:31 +00007885#if ENABLE_ASH_BASH_COMPAT
7886 case NTO2:
7887#endif
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007888 case NCLOBBER:
7889 case NFROM:
7890 case NFROMTO:
7891 case NAPPEND:
7892 calcsize(n->nfile.fname);
7893 calcsize(n->nfile.next);
7894 break;
7895 case NTOFD:
7896 case NFROMFD:
7897 calcsize(n->ndup.vname);
7898 calcsize(n->ndup.next);
7899 break;
7900 case NHERE:
7901 case NXHERE:
7902 calcsize(n->nhere.doc);
7903 calcsize(n->nhere.next);
7904 break;
7905 case NNOT:
7906 calcsize(n->nnot.com);
7907 break;
7908 };
7909}
7910
7911static char *
7912nodeckstrdup(char *s)
7913{
7914 char *rtn = funcstring;
7915
7916 strcpy(funcstring, s);
7917 funcstring += strlen(s) + 1;
7918 return rtn;
7919}
7920
7921static union node *copynode(union node *);
7922
7923static struct nodelist *
7924copynodelist(struct nodelist *lp)
7925{
7926 struct nodelist *start;
7927 struct nodelist **lpp;
7928
7929 lpp = &start;
7930 while (lp) {
7931 *lpp = funcblock;
7932 funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
7933 (*lpp)->n = copynode(lp->n);
7934 lp = lp->next;
7935 lpp = &(*lpp)->next;
7936 }
7937 *lpp = NULL;
7938 return start;
7939}
7940
7941static union node *
7942copynode(union node *n)
7943{
7944 union node *new;
7945
7946 if (n == NULL)
7947 return NULL;
7948 new = funcblock;
7949 funcblock = (char *) funcblock + nodesize[n->type];
7950
7951 switch (n->type) {
7952 case NCMD:
7953 new->ncmd.redirect = copynode(n->ncmd.redirect);
7954 new->ncmd.args = copynode(n->ncmd.args);
7955 new->ncmd.assign = copynode(n->ncmd.assign);
7956 break;
7957 case NPIPE:
7958 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00007959 new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007960 break;
7961 case NREDIR:
7962 case NBACKGND:
7963 case NSUBSHELL:
7964 new->nredir.redirect = copynode(n->nredir.redirect);
7965 new->nredir.n = copynode(n->nredir.n);
7966 break;
7967 case NAND:
7968 case NOR:
7969 case NSEMI:
7970 case NWHILE:
7971 case NUNTIL:
7972 new->nbinary.ch2 = copynode(n->nbinary.ch2);
7973 new->nbinary.ch1 = copynode(n->nbinary.ch1);
7974 break;
7975 case NIF:
7976 new->nif.elsepart = copynode(n->nif.elsepart);
7977 new->nif.ifpart = copynode(n->nif.ifpart);
7978 new->nif.test = copynode(n->nif.test);
7979 break;
7980 case NFOR:
7981 new->nfor.var = nodeckstrdup(n->nfor.var);
7982 new->nfor.body = copynode(n->nfor.body);
7983 new->nfor.args = copynode(n->nfor.args);
7984 break;
7985 case NCASE:
7986 new->ncase.cases = copynode(n->ncase.cases);
7987 new->ncase.expr = copynode(n->ncase.expr);
7988 break;
7989 case NCLIST:
7990 new->nclist.body = copynode(n->nclist.body);
7991 new->nclist.pattern = copynode(n->nclist.pattern);
7992 new->nclist.next = copynode(n->nclist.next);
7993 break;
7994 case NDEFUN:
7995 case NARG:
7996 new->narg.backquote = copynodelist(n->narg.backquote);
7997 new->narg.text = nodeckstrdup(n->narg.text);
7998 new->narg.next = copynode(n->narg.next);
7999 break;
8000 case NTO:
Denis Vlasenko559691a2008-10-05 18:39:31 +00008001#if ENABLE_ASH_BASH_COMPAT
8002 case NTO2:
8003#endif
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008004 case NCLOBBER:
8005 case NFROM:
8006 case NFROMTO:
8007 case NAPPEND:
8008 new->nfile.fname = copynode(n->nfile.fname);
8009 new->nfile.fd = n->nfile.fd;
8010 new->nfile.next = copynode(n->nfile.next);
8011 break;
8012 case NTOFD:
8013 case NFROMFD:
8014 new->ndup.vname = copynode(n->ndup.vname);
8015 new->ndup.dupfd = n->ndup.dupfd;
8016 new->ndup.fd = n->ndup.fd;
8017 new->ndup.next = copynode(n->ndup.next);
8018 break;
8019 case NHERE:
8020 case NXHERE:
8021 new->nhere.doc = copynode(n->nhere.doc);
8022 new->nhere.fd = n->nhere.fd;
8023 new->nhere.next = copynode(n->nhere.next);
8024 break;
8025 case NNOT:
8026 new->nnot.com = copynode(n->nnot.com);
8027 break;
8028 };
8029 new->type = n->type;
8030 return new;
8031}
8032
8033/*
8034 * Make a copy of a parse tree.
8035 */
8036static struct funcnode *
8037copyfunc(union node *n)
8038{
8039 struct funcnode *f;
8040 size_t blocksize;
8041
8042 funcblocksize = offsetof(struct funcnode, n);
8043 funcstringsize = 0;
8044 calcsize(n);
8045 blocksize = funcblocksize;
8046 f = ckmalloc(blocksize + funcstringsize);
8047 funcblock = (char *) f + offsetof(struct funcnode, n);
8048 funcstring = (char *) f + blocksize;
8049 copynode(n);
8050 f->count = 0;
8051 return f;
8052}
8053
8054/*
8055 * Define a shell function.
8056 */
8057static void
8058defun(char *name, union node *func)
8059{
8060 struct cmdentry entry;
8061
8062 INT_OFF;
8063 entry.cmdtype = CMDFUNCTION;
8064 entry.u.func = copyfunc(func);
8065 addcmdentry(name, &entry);
8066 INT_ON;
8067}
8068
Denis Vlasenko4b875702009-03-19 13:30:04 +00008069/* Reasons for skipping commands (see comment on breakcmd routine) */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008070#define SKIPBREAK (1 << 0)
8071#define SKIPCONT (1 << 1)
8072#define SKIPFUNC (1 << 2)
8073#define SKIPFILE (1 << 3)
8074#define SKIPEVAL (1 << 4)
Denis Vlasenko4b875702009-03-19 13:30:04 +00008075static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008076static int skipcount; /* number of levels to skip */
8077static int funcnest; /* depth of function calls */
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +00008078static int loopnest; /* current loop nesting level */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008079
Denis Vlasenko4b875702009-03-19 13:30:04 +00008080/* Forward decl way out to parsing code - dotrap needs it */
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008081static int evalstring(char *s, int mask);
8082
Denis Vlasenko4b875702009-03-19 13:30:04 +00008083/* Called to execute a trap.
8084 * Single callsite - at the end of evaltree().
8085 * If we return non-zero, exaltree raises EXEXIT exception.
8086 *
8087 * Perhaps we should avoid entering new trap handlers
8088 * while we are executing a trap handler. [is it a TODO?]
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008089 */
8090static int
8091dotrap(void)
8092{
Denis Vlasenko4b875702009-03-19 13:30:04 +00008093 uint8_t *g;
8094 int sig;
8095 uint8_t savestatus;
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008096
8097 savestatus = exitstatus;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02008098 pending_sig = 0;
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008099 xbarrier();
8100
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008101 TRACE(("dotrap entered\n"));
Denis Vlasenko4b875702009-03-19 13:30:04 +00008102 for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
8103 int want_exexit;
8104 char *t;
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008105
Denis Vlasenko4b875702009-03-19 13:30:04 +00008106 if (*g == 0)
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008107 continue;
Denis Vlasenko4b875702009-03-19 13:30:04 +00008108 t = trap[sig];
8109 /* non-trapped SIGINT is handled separately by raise_interrupt,
8110 * don't upset it by resetting gotsig[SIGINT-1] */
8111 if (sig == SIGINT && !t)
8112 continue;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008113
8114 TRACE(("sig %d is active, will run handler '%s'\n", sig, t));
Denis Vlasenko4b875702009-03-19 13:30:04 +00008115 *g = 0;
8116 if (!t)
8117 continue;
8118 want_exexit = evalstring(t, SKIPEVAL);
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008119 exitstatus = savestatus;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008120 if (want_exexit) {
Denis Vlasenkob21f3792009-03-19 23:09:58 +00008121 TRACE(("dotrap returns %d\n", want_exexit));
Denis Vlasenko4b875702009-03-19 13:30:04 +00008122 return want_exexit;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008123 }
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008124 }
8125
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008126 TRACE(("dotrap returns 0\n"));
Denis Vlasenko991a1da2008-02-10 19:02:53 +00008127 return 0;
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008128}
8129
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00008130/* forward declarations - evaluation is fairly recursive business... */
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008131static void evalloop(union node *, int);
8132static void evalfor(union node *, int);
8133static void evalcase(union node *, int);
8134static void evalsubshell(union node *, int);
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00008135static void expredir(union node *);
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008136static void evalpipe(union node *, int);
8137static void evalcommand(union node *, int);
Eric Andersenc470f442003-07-28 09:56:35 +00008138static int evalbltin(const struct builtincmd *, int, char **);
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008139static void prehash(union node *);
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00008140
Eric Andersen62483552001-07-10 06:09:16 +00008141/*
Eric Andersenc470f442003-07-28 09:56:35 +00008142 * Evaluate a parse tree. The value is left in the global variable
8143 * exitstatus.
Eric Andersen62483552001-07-10 06:09:16 +00008144 */
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008145static void
Eric Andersenc470f442003-07-28 09:56:35 +00008146evaltree(union node *n, int flags)
Eric Andersen62483552001-07-10 06:09:16 +00008147{
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008148 struct jmploc *volatile savehandler = exception_handler;
8149 struct jmploc jmploc;
Eric Andersenc470f442003-07-28 09:56:35 +00008150 int checkexit = 0;
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008151 void (*evalfn)(union node *, int);
Eric Andersenc470f442003-07-28 09:56:35 +00008152 int status;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008153 int int_level;
8154
8155 SAVE_INT(int_level);
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008156
Eric Andersenc470f442003-07-28 09:56:35 +00008157 if (n == NULL) {
8158 TRACE(("evaltree(NULL) called\n"));
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008159 goto out1;
Eric Andersen62483552001-07-10 06:09:16 +00008160 }
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008161 TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008162
8163 exception_handler = &jmploc;
8164 {
8165 int err = setjmp(jmploc.loc);
8166 if (err) {
8167 /* if it was a signal, check for trap handlers */
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008168 if (exception_type == EXSIG) {
Denis Vlasenkob21f3792009-03-19 23:09:58 +00008169 TRACE(("exception %d (EXSIG) in evaltree, err=%d\n",
8170 exception_type, err));
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008171 goto out;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008172 }
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008173 /* continue on the way out */
Denis Vlasenkob21f3792009-03-19 23:09:58 +00008174 TRACE(("exception %d in evaltree, propagating err=%d\n",
8175 exception_type, err));
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008176 exception_handler = savehandler;
8177 longjmp(exception_handler->loc, err);
8178 }
8179 }
8180
Eric Andersenc470f442003-07-28 09:56:35 +00008181 switch (n->type) {
8182 default:
Denis Vlasenkoa7189f02006-11-17 20:29:00 +00008183#if DEBUG
Eric Andersenc470f442003-07-28 09:56:35 +00008184 out1fmt("Node type = %d\n", n->type);
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00008185 fflush(stdout);
Eric Andersenc470f442003-07-28 09:56:35 +00008186 break;
8187#endif
8188 case NNOT:
8189 evaltree(n->nnot.com, EV_TESTED);
8190 status = !exitstatus;
8191 goto setstatus;
8192 case NREDIR:
8193 expredir(n->nredir.redirect);
8194 status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
8195 if (!status) {
8196 evaltree(n->nredir.n, flags & EV_TESTED);
8197 status = exitstatus;
8198 }
Denis Vlasenko34c73c42008-08-16 11:48:02 +00008199 popredir(/*drop:*/ 0, /*restore:*/ 0 /* not sure */);
Eric Andersenc470f442003-07-28 09:56:35 +00008200 goto setstatus;
8201 case NCMD:
8202 evalfn = evalcommand;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008203 checkexit:
Eric Andersenc470f442003-07-28 09:56:35 +00008204 if (eflag && !(flags & EV_TESTED))
8205 checkexit = ~0;
8206 goto calleval;
8207 case NFOR:
8208 evalfn = evalfor;
8209 goto calleval;
8210 case NWHILE:
8211 case NUNTIL:
8212 evalfn = evalloop;
8213 goto calleval;
8214 case NSUBSHELL:
8215 case NBACKGND:
8216 evalfn = evalsubshell;
8217 goto calleval;
8218 case NPIPE:
8219 evalfn = evalpipe;
8220 goto checkexit;
8221 case NCASE:
8222 evalfn = evalcase;
8223 goto calleval;
8224 case NAND:
8225 case NOR:
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008226 case NSEMI: {
8227
Eric Andersenc470f442003-07-28 09:56:35 +00008228#if NAND + 1 != NOR
8229#error NAND + 1 != NOR
8230#endif
8231#if NOR + 1 != NSEMI
8232#error NOR + 1 != NSEMI
8233#endif
Denis Vlasenko87d5fd92008-07-26 13:48:35 +00008234 unsigned is_or = n->type - NAND;
Eric Andersenc470f442003-07-28 09:56:35 +00008235 evaltree(
8236 n->nbinary.ch1,
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008237 (flags | ((is_or >> 1) - 1)) & EV_TESTED
Eric Andersenc470f442003-07-28 09:56:35 +00008238 );
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008239 if (!exitstatus == is_or)
Eric Andersenc470f442003-07-28 09:56:35 +00008240 break;
8241 if (!evalskip) {
8242 n = n->nbinary.ch2;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008243 evaln:
Eric Andersenc470f442003-07-28 09:56:35 +00008244 evalfn = evaltree;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008245 calleval:
Eric Andersenc470f442003-07-28 09:56:35 +00008246 evalfn(n, flags);
8247 break;
8248 }
8249 break;
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008250 }
Eric Andersenc470f442003-07-28 09:56:35 +00008251 case NIF:
8252 evaltree(n->nif.test, EV_TESTED);
8253 if (evalskip)
8254 break;
8255 if (exitstatus == 0) {
8256 n = n->nif.ifpart;
8257 goto evaln;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008258 }
8259 if (n->nif.elsepart) {
Eric Andersenc470f442003-07-28 09:56:35 +00008260 n = n->nif.elsepart;
8261 goto evaln;
8262 }
8263 goto success;
8264 case NDEFUN:
8265 defun(n->narg.text, n->narg.next);
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008266 success:
Eric Andersenc470f442003-07-28 09:56:35 +00008267 status = 0;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008268 setstatus:
Eric Andersenc470f442003-07-28 09:56:35 +00008269 exitstatus = status;
8270 break;
8271 }
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008272
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008273 out:
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008274 exception_handler = savehandler;
8275 out1:
8276 if (checkexit & exitstatus)
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00008277 evalskip |= SKIPEVAL;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02008278 else if (pending_sig && dotrap())
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00008279 goto exexit;
8280
8281 if (flags & EV_EXIT) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008282 exexit:
Denis Vlasenkob012b102007-02-19 22:43:01 +00008283 raise_exception(EXEXIT);
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00008284 }
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008285
8286 RESTORE_INT(int_level);
8287 TRACE(("leaving evaltree (no interrupts)\n"));
Eric Andersen62483552001-07-10 06:09:16 +00008288}
8289
Eric Andersenc470f442003-07-28 09:56:35 +00008290#if !defined(__alpha__) || (defined(__GNUC__) && __GNUC__ >= 3)
8291static
8292#endif
8293void evaltreenr(union node *, int) __attribute__ ((alias("evaltree"),__noreturn__));
8294
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008295static void
Eric Andersenc470f442003-07-28 09:56:35 +00008296evalloop(union node *n, int flags)
Eric Andersencb57d552001-06-28 07:25:16 +00008297{
8298 int status;
8299
8300 loopnest++;
8301 status = 0;
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008302 flags &= EV_TESTED;
Eric Andersencb57d552001-06-28 07:25:16 +00008303 for (;;) {
Eric Andersenc470f442003-07-28 09:56:35 +00008304 int i;
8305
Eric Andersencb57d552001-06-28 07:25:16 +00008306 evaltree(n->nbinary.ch1, EV_TESTED);
8307 if (evalskip) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008308 skipping:
8309 if (evalskip == SKIPCONT && --skipcount <= 0) {
Eric Andersencb57d552001-06-28 07:25:16 +00008310 evalskip = 0;
8311 continue;
8312 }
8313 if (evalskip == SKIPBREAK && --skipcount <= 0)
8314 evalskip = 0;
8315 break;
8316 }
Eric Andersenc470f442003-07-28 09:56:35 +00008317 i = exitstatus;
8318 if (n->type != NWHILE)
8319 i = !i;
8320 if (i != 0)
8321 break;
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008322 evaltree(n->nbinary.ch2, flags);
Eric Andersencb57d552001-06-28 07:25:16 +00008323 status = exitstatus;
8324 if (evalskip)
8325 goto skipping;
8326 }
8327 loopnest--;
8328 exitstatus = status;
8329}
8330
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008331static void
Eric Andersenc470f442003-07-28 09:56:35 +00008332evalfor(union node *n, int flags)
Eric Andersencb57d552001-06-28 07:25:16 +00008333{
8334 struct arglist arglist;
8335 union node *argp;
8336 struct strlist *sp;
8337 struct stackmark smark;
8338
8339 setstackmark(&smark);
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00008340 arglist.list = NULL;
Eric Andersencb57d552001-06-28 07:25:16 +00008341 arglist.lastp = &arglist.list;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008342 for (argp = n->nfor.args; argp; argp = argp->narg.next) {
Eric Andersencb57d552001-06-28 07:25:16 +00008343 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE | EXP_RECORD);
Eric Andersenc470f442003-07-28 09:56:35 +00008344 /* XXX */
Eric Andersencb57d552001-06-28 07:25:16 +00008345 if (evalskip)
8346 goto out;
8347 }
8348 *arglist.lastp = NULL;
8349
8350 exitstatus = 0;
8351 loopnest++;
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008352 flags &= EV_TESTED;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008353 for (sp = arglist.list; sp; sp = sp->next) {
Eric Andersencb57d552001-06-28 07:25:16 +00008354 setvar(n->nfor.var, sp->text, 0);
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008355 evaltree(n->nfor.body, flags);
Eric Andersencb57d552001-06-28 07:25:16 +00008356 if (evalskip) {
8357 if (evalskip == SKIPCONT && --skipcount <= 0) {
8358 evalskip = 0;
8359 continue;
8360 }
8361 if (evalskip == SKIPBREAK && --skipcount <= 0)
8362 evalskip = 0;
8363 break;
8364 }
8365 }
8366 loopnest--;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008367 out:
Eric Andersencb57d552001-06-28 07:25:16 +00008368 popstackmark(&smark);
8369}
8370
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008371static void
Eric Andersenc470f442003-07-28 09:56:35 +00008372evalcase(union node *n, int flags)
Eric Andersencb57d552001-06-28 07:25:16 +00008373{
8374 union node *cp;
8375 union node *patp;
8376 struct arglist arglist;
8377 struct stackmark smark;
8378
8379 setstackmark(&smark);
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00008380 arglist.list = NULL;
Eric Andersencb57d552001-06-28 07:25:16 +00008381 arglist.lastp = &arglist.list;
Eric Andersencb57d552001-06-28 07:25:16 +00008382 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
Eric Andersenc470f442003-07-28 09:56:35 +00008383 exitstatus = 0;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008384 for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
8385 for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
Eric Andersencb57d552001-06-28 07:25:16 +00008386 if (casematch(patp, arglist.list->text)) {
8387 if (evalskip == 0) {
8388 evaltree(cp->nclist.body, flags);
8389 }
8390 goto out;
8391 }
8392 }
8393 }
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008394 out:
Eric Andersencb57d552001-06-28 07:25:16 +00008395 popstackmark(&smark);
8396}
8397
Eric Andersenc470f442003-07-28 09:56:35 +00008398/*
8399 * Kick off a subshell to evaluate a tree.
8400 */
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008401static void
Eric Andersenc470f442003-07-28 09:56:35 +00008402evalsubshell(union node *n, int flags)
8403{
8404 struct job *jp;
8405 int backgnd = (n->type == NBACKGND);
8406 int status;
8407
8408 expredir(n->nredir.redirect);
8409 if (!backgnd && flags & EV_EXIT && !trap[0])
8410 goto nofork;
Denis Vlasenkob012b102007-02-19 22:43:01 +00008411 INT_OFF;
Denis Vlasenko68404f12008-03-17 09:00:54 +00008412 jp = makejob(/*n,*/ 1);
Eric Andersenc470f442003-07-28 09:56:35 +00008413 if (forkshell(jp, n, backgnd) == 0) {
Denis Vlasenkob012b102007-02-19 22:43:01 +00008414 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00008415 flags |= EV_EXIT;
8416 if (backgnd)
8417 flags &=~ EV_TESTED;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00008418 nofork:
Eric Andersenc470f442003-07-28 09:56:35 +00008419 redirect(n->nredir.redirect, 0);
8420 evaltreenr(n->nredir.n, flags);
8421 /* never returns */
8422 }
8423 status = 0;
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00008424 if (!backgnd)
Eric Andersenc470f442003-07-28 09:56:35 +00008425 status = waitforjob(jp);
8426 exitstatus = status;
Denis Vlasenkob012b102007-02-19 22:43:01 +00008427 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00008428}
8429
Eric Andersenc470f442003-07-28 09:56:35 +00008430/*
8431 * Compute the names of the files in a redirection list.
8432 */
Denis Vlasenko99eb8502007-02-23 21:09:49 +00008433static void fixredir(union node *, const char *, int);
Eric Andersenc470f442003-07-28 09:56:35 +00008434static void
8435expredir(union node *n)
8436{
8437 union node *redir;
8438
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008439 for (redir = n; redir; redir = redir->nfile.next) {
Eric Andersenc470f442003-07-28 09:56:35 +00008440 struct arglist fn;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008441
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00008442 fn.list = NULL;
Eric Andersenc470f442003-07-28 09:56:35 +00008443 fn.lastp = &fn.list;
8444 switch (redir->type) {
8445 case NFROMTO:
8446 case NFROM:
8447 case NTO:
Denis Vlasenko559691a2008-10-05 18:39:31 +00008448#if ENABLE_ASH_BASH_COMPAT
8449 case NTO2:
8450#endif
Eric Andersenc470f442003-07-28 09:56:35 +00008451 case NCLOBBER:
8452 case NAPPEND:
8453 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
Denis Vlasenko559691a2008-10-05 18:39:31 +00008454#if ENABLE_ASH_BASH_COMPAT
8455 store_expfname:
8456#endif
Eric Andersenc470f442003-07-28 09:56:35 +00008457 redir->nfile.expfname = fn.list->text;
8458 break;
8459 case NFROMFD:
Denis Vlasenko559691a2008-10-05 18:39:31 +00008460 case NTOFD: /* >& */
Eric Andersenc470f442003-07-28 09:56:35 +00008461 if (redir->ndup.vname) {
8462 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008463 if (fn.list == NULL)
Denis Vlasenkob012b102007-02-19 22:43:01 +00008464 ash_msg_and_raise_error("redir error");
Denis Vlasenko559691a2008-10-05 18:39:31 +00008465#if ENABLE_ASH_BASH_COMPAT
8466//FIXME: we used expandarg with different args!
8467 if (!isdigit_str9(fn.list->text)) {
8468 /* >&file, not >&fd */
8469 if (redir->nfile.fd != 1) /* 123>&file - BAD */
8470 ash_msg_and_raise_error("redir error");
8471 redir->type = NTO2;
8472 goto store_expfname;
8473 }
8474#endif
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008475 fixredir(redir, fn.list->text, 1);
Eric Andersenc470f442003-07-28 09:56:35 +00008476 }
8477 break;
8478 }
8479 }
8480}
8481
Eric Andersencb57d552001-06-28 07:25:16 +00008482/*
Eric Andersencb57d552001-06-28 07:25:16 +00008483 * Evaluate a pipeline. All the processes in the pipeline are children
8484 * of the process creating the pipeline. (This differs from some versions
8485 * of the shell, which make the last process in a pipeline the parent
8486 * of all the rest.)
8487 */
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008488static void
Eric Andersenc470f442003-07-28 09:56:35 +00008489evalpipe(union node *n, int flags)
Eric Andersencb57d552001-06-28 07:25:16 +00008490{
8491 struct job *jp;
8492 struct nodelist *lp;
8493 int pipelen;
8494 int prevfd;
8495 int pip[2];
8496
Eric Andersenc470f442003-07-28 09:56:35 +00008497 TRACE(("evalpipe(0x%lx) called\n", (long)n));
Eric Andersencb57d552001-06-28 07:25:16 +00008498 pipelen = 0;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008499 for (lp = n->npipe.cmdlist; lp; lp = lp->next)
Eric Andersencb57d552001-06-28 07:25:16 +00008500 pipelen++;
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008501 flags |= EV_EXIT;
Denis Vlasenkob012b102007-02-19 22:43:01 +00008502 INT_OFF;
Denis Vlasenko68404f12008-03-17 09:00:54 +00008503 jp = makejob(/*n,*/ pipelen);
Eric Andersencb57d552001-06-28 07:25:16 +00008504 prevfd = -1;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008505 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008506 prehash(lp->n);
Eric Andersencb57d552001-06-28 07:25:16 +00008507 pip[1] = -1;
8508 if (lp->next) {
8509 if (pipe(pip) < 0) {
8510 close(prevfd);
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00008511 ash_msg_and_raise_error("pipe call failed");
Eric Andersencb57d552001-06-28 07:25:16 +00008512 }
8513 }
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00008514 if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
Denis Vlasenkob012b102007-02-19 22:43:01 +00008515 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00008516 if (pip[1] >= 0) {
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008517 close(pip[0]);
Eric Andersencb57d552001-06-28 07:25:16 +00008518 }
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008519 if (prevfd > 0) {
8520 dup2(prevfd, 0);
8521 close(prevfd);
8522 }
8523 if (pip[1] > 1) {
8524 dup2(pip[1], 1);
8525 close(pip[1]);
8526 }
Eric Andersenc470f442003-07-28 09:56:35 +00008527 evaltreenr(lp->n, flags);
8528 /* never returns */
Eric Andersencb57d552001-06-28 07:25:16 +00008529 }
8530 if (prevfd >= 0)
8531 close(prevfd);
8532 prevfd = pip[0];
Denis Vlasenkob9e70dd2009-03-20 01:24:08 +00008533 /* Don't want to trigger debugging */
8534 if (pip[1] != -1)
8535 close(pip[1]);
Eric Andersencb57d552001-06-28 07:25:16 +00008536 }
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00008537 if (n->npipe.pipe_backgnd == 0) {
Eric Andersencb57d552001-06-28 07:25:16 +00008538 exitstatus = waitforjob(jp);
8539 TRACE(("evalpipe: job done exit status %d\n", exitstatus));
Eric Andersencb57d552001-06-28 07:25:16 +00008540 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00008541 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00008542}
8543
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008544/*
8545 * Controls whether the shell is interactive or not.
8546 */
8547static void
8548setinteractive(int on)
8549{
Denis Vlasenkob07a4962008-06-22 13:16:23 +00008550 static smallint is_interactive;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008551
8552 if (++on == is_interactive)
8553 return;
8554 is_interactive = on;
8555 setsignal(SIGINT);
8556 setsignal(SIGQUIT);
8557 setsignal(SIGTERM);
8558#if !ENABLE_FEATURE_SH_EXTRA_QUIET
8559 if (is_interactive > 1) {
8560 /* Looks like they want an interactive shell */
Denis Vlasenkoca525b42007-06-13 12:27:17 +00008561 static smallint did_banner;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008562
Denis Vlasenkoca525b42007-06-13 12:27:17 +00008563 if (!did_banner) {
Denys Vlasenkoc34c0332009-09-29 12:25:30 +02008564 /* note: ash and hush share this string */
8565 out1fmt("\n\n%s %s\n"
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008566 "Enter 'help' for a list of built-in commands."
8567 "\n\n",
Denys Vlasenkoc34c0332009-09-29 12:25:30 +02008568 bb_banner,
8569 "built-in shell (ash)"
8570 );
Denis Vlasenkoca525b42007-06-13 12:27:17 +00008571 did_banner = 1;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008572 }
8573 }
8574#endif
8575}
8576
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008577static void
8578optschanged(void)
8579{
8580#if DEBUG
8581 opentrace();
8582#endif
8583 setinteractive(iflag);
8584 setjobctl(mflag);
Denis Vlasenkob07a4962008-06-22 13:16:23 +00008585#if ENABLE_FEATURE_EDITING_VI
8586 if (viflag)
8587 line_input_state->flags |= VI_MODE;
8588 else
8589 line_input_state->flags &= ~VI_MODE;
8590#else
8591 viflag = 0; /* forcibly keep the option off */
8592#endif
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008593}
8594
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008595static struct localvar *localvars;
8596
8597/*
8598 * Called after a function returns.
8599 * Interrupts must be off.
8600 */
8601static void
8602poplocalvars(void)
8603{
8604 struct localvar *lvp;
8605 struct var *vp;
8606
8607 while ((lvp = localvars) != NULL) {
8608 localvars = lvp->next;
8609 vp = lvp->vp;
Denys Vlasenko883cea42009-07-11 15:31:59 +02008610 TRACE(("poplocalvar %s\n", vp ? vp->text : "-"));
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008611 if (vp == NULL) { /* $- saved */
8612 memcpy(optlist, lvp->text, sizeof(optlist));
8613 free((char*)lvp->text);
8614 optschanged();
8615 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
8616 unsetvar(vp->text);
8617 } else {
8618 if (vp->func)
8619 (*vp->func)(strchrnul(lvp->text, '=') + 1);
8620 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
8621 free((char*)vp->text);
8622 vp->flags = lvp->flags;
8623 vp->text = lvp->text;
8624 }
8625 free(lvp);
8626 }
8627}
8628
8629static int
8630evalfun(struct funcnode *func, int argc, char **argv, int flags)
8631{
8632 volatile struct shparam saveparam;
8633 struct localvar *volatile savelocalvars;
8634 struct jmploc *volatile savehandler;
8635 struct jmploc jmploc;
8636 int e;
8637
8638 saveparam = shellparam;
8639 savelocalvars = localvars;
8640 e = setjmp(jmploc.loc);
8641 if (e) {
8642 goto funcdone;
8643 }
8644 INT_OFF;
8645 savehandler = exception_handler;
8646 exception_handler = &jmploc;
8647 localvars = NULL;
Denis Vlasenko01631112007-12-16 17:20:38 +00008648 shellparam.malloced = 0;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008649 func->count++;
8650 funcnest++;
8651 INT_ON;
8652 shellparam.nparam = argc - 1;
8653 shellparam.p = argv + 1;
8654#if ENABLE_ASH_GETOPTS
8655 shellparam.optind = 1;
8656 shellparam.optoff = -1;
8657#endif
8658 evaltree(&func->n, flags & EV_TESTED);
Denis Vlasenko01631112007-12-16 17:20:38 +00008659 funcdone:
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008660 INT_OFF;
8661 funcnest--;
8662 freefunc(func);
8663 poplocalvars();
8664 localvars = savelocalvars;
8665 freeparam(&shellparam);
8666 shellparam = saveparam;
8667 exception_handler = savehandler;
8668 INT_ON;
8669 evalskip &= ~SKIPFUNC;
8670 return e;
8671}
8672
Denis Vlasenko131ae172007-02-18 13:00:19 +00008673#if ENABLE_ASH_CMDCMD
Denis Vlasenkoaa744452007-02-23 01:04:22 +00008674static char **
8675parse_command_args(char **argv, const char **path)
Eric Andersenc470f442003-07-28 09:56:35 +00008676{
8677 char *cp, c;
8678
8679 for (;;) {
8680 cp = *++argv;
8681 if (!cp)
8682 return 0;
8683 if (*cp++ != '-')
8684 break;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008685 c = *cp++;
8686 if (!c)
Eric Andersenc470f442003-07-28 09:56:35 +00008687 break;
8688 if (c == '-' && !*cp) {
8689 argv++;
8690 break;
8691 }
8692 do {
8693 switch (c) {
8694 case 'p':
Denis Vlasenkof5f75c52007-06-12 22:35:19 +00008695 *path = bb_default_path;
Eric Andersenc470f442003-07-28 09:56:35 +00008696 break;
8697 default:
8698 /* run 'typecmd' for other options */
8699 return 0;
8700 }
Denis Vlasenko9650f362007-02-23 01:04:37 +00008701 c = *cp++;
8702 } while (c);
Eric Andersenc470f442003-07-28 09:56:35 +00008703 }
8704 return argv;
8705}
8706#endif
8707
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008708/*
8709 * Make a variable a local variable. When a variable is made local, it's
8710 * value and flags are saved in a localvar structure. The saved values
8711 * will be restored when the shell function returns. We handle the name
8712 * "-" as a special case.
8713 */
8714static void
8715mklocal(char *name)
8716{
8717 struct localvar *lvp;
8718 struct var **vpp;
8719 struct var *vp;
8720
8721 INT_OFF;
Denis Vlasenko838ffd52008-02-21 04:32:08 +00008722 lvp = ckzalloc(sizeof(struct localvar));
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008723 if (LONE_DASH(name)) {
8724 char *p;
8725 p = ckmalloc(sizeof(optlist));
8726 lvp->text = memcpy(p, optlist, sizeof(optlist));
8727 vp = NULL;
8728 } else {
8729 char *eq;
8730
8731 vpp = hashvar(name);
8732 vp = *findvar(vpp, name);
8733 eq = strchr(name, '=');
8734 if (vp == NULL) {
8735 if (eq)
8736 setvareq(name, VSTRFIXED);
8737 else
8738 setvar(name, NULL, VSTRFIXED);
8739 vp = *vpp; /* the new variable */
8740 lvp->flags = VUNSET;
8741 } else {
8742 lvp->text = vp->text;
8743 lvp->flags = vp->flags;
8744 vp->flags |= VSTRFIXED|VTEXTFIXED;
8745 if (eq)
8746 setvareq(name, 0);
8747 }
8748 }
8749 lvp->vp = vp;
8750 lvp->next = localvars;
8751 localvars = lvp;
8752 INT_ON;
8753}
8754
8755/*
8756 * The "local" command.
8757 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008758static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008759localcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008760{
8761 char *name;
8762
8763 argv = argptr;
8764 while ((name = *argv++) != NULL) {
8765 mklocal(name);
8766 }
8767 return 0;
8768}
8769
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008770static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008771falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008772{
8773 return 1;
8774}
8775
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008776static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008777truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008778{
8779 return 0;
8780}
8781
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008782static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008783execcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008784{
Denis Vlasenko68404f12008-03-17 09:00:54 +00008785 if (argv[1]) {
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008786 iflag = 0; /* exit on error */
8787 mflag = 0;
8788 optschanged();
8789 shellexec(argv + 1, pathval(), 0);
8790 }
8791 return 0;
8792}
8793
8794/*
8795 * The return command.
8796 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008797static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008798returncmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008799{
8800 /*
8801 * If called outside a function, do what ksh does;
8802 * skip the rest of the file.
8803 */
8804 evalskip = funcnest ? SKIPFUNC : SKIPFILE;
8805 return argv[1] ? number(argv[1]) : exitstatus;
8806}
8807
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008808/* Forward declarations for builtintab[] */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008809static int breakcmd(int, char **) FAST_FUNC;
8810static int dotcmd(int, char **) FAST_FUNC;
8811static int evalcmd(int, char **) FAST_FUNC;
8812static int exitcmd(int, char **) FAST_FUNC;
8813static int exportcmd(int, char **) FAST_FUNC;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008814#if ENABLE_ASH_GETOPTS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008815static int getoptscmd(int, char **) FAST_FUNC;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008816#endif
Denis Vlasenko52764022007-02-24 13:42:56 +00008817#if !ENABLE_FEATURE_SH_EXTRA_QUIET
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008818static int helpcmd(int, char **) FAST_FUNC;
Denis Vlasenko52764022007-02-24 13:42:56 +00008819#endif
Mike Frysinger98c52642009-04-02 10:02:37 +00008820#if ENABLE_SH_MATH_SUPPORT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008821static int letcmd(int, char **) FAST_FUNC;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008822#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008823static int readcmd(int, char **) FAST_FUNC;
8824static int setcmd(int, char **) FAST_FUNC;
8825static int shiftcmd(int, char **) FAST_FUNC;
8826static int timescmd(int, char **) FAST_FUNC;
8827static int trapcmd(int, char **) FAST_FUNC;
8828static int umaskcmd(int, char **) FAST_FUNC;
8829static int unsetcmd(int, char **) FAST_FUNC;
8830static int ulimitcmd(int, char **) FAST_FUNC;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008831
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008832#define BUILTIN_NOSPEC "0"
8833#define BUILTIN_SPECIAL "1"
8834#define BUILTIN_REGULAR "2"
8835#define BUILTIN_SPEC_REG "3"
8836#define BUILTIN_ASSIGN "4"
8837#define BUILTIN_SPEC_ASSG "5"
8838#define BUILTIN_REG_ASSG "6"
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008839#define BUILTIN_SPEC_REG_ASSG "7"
8840
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008841/* Stubs for calling non-FAST_FUNC's */
Denys Vlasenko2634bf32009-06-09 18:40:07 +02008842#if ENABLE_ASH_BUILTIN_ECHO
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008843static int FAST_FUNC echocmd(int argc, char **argv) { return echo_main(argc, argv); }
Denys Vlasenko2634bf32009-06-09 18:40:07 +02008844#endif
8845#if ENABLE_ASH_BUILTIN_PRINTF
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008846static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
Denys Vlasenko2634bf32009-06-09 18:40:07 +02008847#endif
8848#if ENABLE_ASH_BUILTIN_TEST
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008849static int FAST_FUNC testcmd(int argc, char **argv) { return test_main(argc, argv); }
Denys Vlasenko2634bf32009-06-09 18:40:07 +02008850#endif
Denis Vlasenko468aea22008-04-01 14:47:57 +00008851
Denis Vlasenkof7d56652008-03-25 05:51:41 +00008852/* Keep these in proper order since it is searched via bsearch() */
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008853static const struct builtincmd builtintab[] = {
8854 { BUILTIN_SPEC_REG ".", dotcmd },
8855 { BUILTIN_SPEC_REG ":", truecmd },
8856#if ENABLE_ASH_BUILTIN_TEST
Denis Vlasenkocd2663f2008-06-01 22:36:39 +00008857 { BUILTIN_REGULAR "[", testcmd },
Denis Vlasenko80591b02008-03-25 07:49:43 +00008858#if ENABLE_ASH_BASH_COMPAT
Denis Vlasenkocd2663f2008-06-01 22:36:39 +00008859 { BUILTIN_REGULAR "[[", testcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008860#endif
Denis Vlasenko80591b02008-03-25 07:49:43 +00008861#endif
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008862#if ENABLE_ASH_ALIAS
8863 { BUILTIN_REG_ASSG "alias", aliascmd },
8864#endif
8865#if JOBS
8866 { BUILTIN_REGULAR "bg", fg_bgcmd },
8867#endif
8868 { BUILTIN_SPEC_REG "break", breakcmd },
8869 { BUILTIN_REGULAR "cd", cdcmd },
8870 { BUILTIN_NOSPEC "chdir", cdcmd },
8871#if ENABLE_ASH_CMDCMD
8872 { BUILTIN_REGULAR "command", commandcmd },
8873#endif
8874 { BUILTIN_SPEC_REG "continue", breakcmd },
8875#if ENABLE_ASH_BUILTIN_ECHO
8876 { BUILTIN_REGULAR "echo", echocmd },
8877#endif
8878 { BUILTIN_SPEC_REG "eval", evalcmd },
8879 { BUILTIN_SPEC_REG "exec", execcmd },
8880 { BUILTIN_SPEC_REG "exit", exitcmd },
8881 { BUILTIN_SPEC_REG_ASSG "export", exportcmd },
8882 { BUILTIN_REGULAR "false", falsecmd },
8883#if JOBS
8884 { BUILTIN_REGULAR "fg", fg_bgcmd },
8885#endif
8886#if ENABLE_ASH_GETOPTS
8887 { BUILTIN_REGULAR "getopts", getoptscmd },
8888#endif
8889 { BUILTIN_NOSPEC "hash", hashcmd },
8890#if !ENABLE_FEATURE_SH_EXTRA_QUIET
8891 { BUILTIN_NOSPEC "help", helpcmd },
8892#endif
8893#if JOBS
8894 { BUILTIN_REGULAR "jobs", jobscmd },
8895 { BUILTIN_REGULAR "kill", killcmd },
8896#endif
Mike Frysinger98c52642009-04-02 10:02:37 +00008897#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008898 { BUILTIN_NOSPEC "let", letcmd },
8899#endif
8900 { BUILTIN_ASSIGN "local", localcmd },
Denis Vlasenkocd2663f2008-06-01 22:36:39 +00008901#if ENABLE_ASH_BUILTIN_PRINTF
8902 { BUILTIN_REGULAR "printf", printfcmd },
8903#endif
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008904 { BUILTIN_NOSPEC "pwd", pwdcmd },
8905 { BUILTIN_REGULAR "read", readcmd },
8906 { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
8907 { BUILTIN_SPEC_REG "return", returncmd },
8908 { BUILTIN_SPEC_REG "set", setcmd },
8909 { BUILTIN_SPEC_REG "shift", shiftcmd },
8910 { BUILTIN_SPEC_REG "source", dotcmd },
8911#if ENABLE_ASH_BUILTIN_TEST
Denis Vlasenkocd2663f2008-06-01 22:36:39 +00008912 { BUILTIN_REGULAR "test", testcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008913#endif
8914 { BUILTIN_SPEC_REG "times", timescmd },
8915 { BUILTIN_SPEC_REG "trap", trapcmd },
8916 { BUILTIN_REGULAR "true", truecmd },
8917 { BUILTIN_NOSPEC "type", typecmd },
8918 { BUILTIN_NOSPEC "ulimit", ulimitcmd },
8919 { BUILTIN_REGULAR "umask", umaskcmd },
8920#if ENABLE_ASH_ALIAS
8921 { BUILTIN_REGULAR "unalias", unaliascmd },
8922#endif
8923 { BUILTIN_SPEC_REG "unset", unsetcmd },
8924 { BUILTIN_REGULAR "wait", waitcmd },
8925};
8926
Denis Vlasenko80591b02008-03-25 07:49:43 +00008927/* Should match the above table! */
8928#define COMMANDCMD (builtintab + \
8929 2 + \
8930 1 * ENABLE_ASH_BUILTIN_TEST + \
8931 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
8932 1 * ENABLE_ASH_ALIAS + \
8933 1 * ENABLE_ASH_JOB_CONTROL + \
8934 3)
8935#define EXECCMD (builtintab + \
8936 2 + \
8937 1 * ENABLE_ASH_BUILTIN_TEST + \
8938 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
8939 1 * ENABLE_ASH_ALIAS + \
8940 1 * ENABLE_ASH_JOB_CONTROL + \
8941 3 + \
8942 1 * ENABLE_ASH_CMDCMD + \
8943 1 + \
8944 ENABLE_ASH_BUILTIN_ECHO + \
8945 1)
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008946
8947/*
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008948 * Search the table of builtin commands.
8949 */
8950static struct builtincmd *
8951find_builtin(const char *name)
8952{
8953 struct builtincmd *bp;
8954
8955 bp = bsearch(
Denis Vlasenko80b8b392007-06-25 10:55:35 +00008956 name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008957 pstrcmp
8958 );
8959 return bp;
8960}
8961
8962/*
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008963 * Execute a simple command.
8964 */
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008965static int
8966isassignment(const char *p)
Paul Foxc3850c82005-07-20 18:23:39 +00008967{
8968 const char *q = endofname(p);
8969 if (p == q)
8970 return 0;
8971 return *q == '=';
8972}
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008973static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008974bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008975{
8976 /* Preserve exitstatus of a previous possible redirection
8977 * as POSIX mandates */
8978 return back_exitstatus;
8979}
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008980static void
Eric Andersenc470f442003-07-28 09:56:35 +00008981evalcommand(union node *cmd, int flags)
8982{
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00008983 static const struct builtincmd null_bltin = {
8984 "\0\0", bltincmd /* why three NULs? */
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008985 };
Eric Andersenc470f442003-07-28 09:56:35 +00008986 struct stackmark smark;
8987 union node *argp;
8988 struct arglist arglist;
8989 struct arglist varlist;
8990 char **argv;
8991 int argc;
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00008992 const struct strlist *sp;
Eric Andersenc470f442003-07-28 09:56:35 +00008993 struct cmdentry cmdentry;
8994 struct job *jp;
8995 char *lastarg;
8996 const char *path;
8997 int spclbltin;
Eric Andersenc470f442003-07-28 09:56:35 +00008998 int status;
8999 char **nargv;
Paul Foxc3850c82005-07-20 18:23:39 +00009000 struct builtincmd *bcmd;
Denis Vlasenko34c73c42008-08-16 11:48:02 +00009001 smallint cmd_is_exec;
9002 smallint pseudovarflag = 0;
Eric Andersenc470f442003-07-28 09:56:35 +00009003
9004 /* First expand the arguments. */
9005 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
9006 setstackmark(&smark);
9007 back_exitstatus = 0;
9008
9009 cmdentry.cmdtype = CMDBUILTIN;
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00009010 cmdentry.u.cmd = &null_bltin;
Eric Andersenc470f442003-07-28 09:56:35 +00009011 varlist.lastp = &varlist.list;
9012 *varlist.lastp = NULL;
9013 arglist.lastp = &arglist.list;
9014 *arglist.lastp = NULL;
9015
9016 argc = 0;
Denis Vlasenkob012b102007-02-19 22:43:01 +00009017 if (cmd->ncmd.args) {
Paul Foxc3850c82005-07-20 18:23:39 +00009018 bcmd = find_builtin(cmd->ncmd.args->narg.text);
9019 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
9020 }
9021
Eric Andersenc470f442003-07-28 09:56:35 +00009022 for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
9023 struct strlist **spp;
9024
9025 spp = arglist.lastp;
"Vladimir N. Oleynik"bef14d72005-09-05 13:25:11 +00009026 if (pseudovarflag && isassignment(argp->narg.text))
Paul Foxc3850c82005-07-20 18:23:39 +00009027 expandarg(argp, &arglist, EXP_VARTILDE);
9028 else
9029 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
9030
Eric Andersenc470f442003-07-28 09:56:35 +00009031 for (sp = *spp; sp; sp = sp->next)
9032 argc++;
9033 }
9034
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +00009035 argv = nargv = stalloc(sizeof(char *) * (argc + 1));
Denis Vlasenko2da584f2007-02-19 22:44:05 +00009036 for (sp = arglist.list; sp; sp = sp->next) {
Eric Andersenc470f442003-07-28 09:56:35 +00009037 TRACE(("evalcommand arg: %s\n", sp->text));
9038 *nargv++ = sp->text;
9039 }
9040 *nargv = NULL;
9041
9042 lastarg = NULL;
9043 if (iflag && funcnest == 0 && argc > 0)
9044 lastarg = nargv[-1];
9045
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009046 preverrout_fd = 2;
Eric Andersenc470f442003-07-28 09:56:35 +00009047 expredir(cmd->ncmd.redirect);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009048 status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
Eric Andersenc470f442003-07-28 09:56:35 +00009049
9050 path = vpath.text;
9051 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
9052 struct strlist **spp;
9053 char *p;
9054
9055 spp = varlist.lastp;
9056 expandarg(argp, &varlist, EXP_VARTILDE);
9057
9058 /*
9059 * Modify the command lookup path, if a PATH= assignment
9060 * is present
9061 */
9062 p = (*spp)->text;
9063 if (varequal(p, path))
9064 path = p;
9065 }
9066
9067 /* Print the command if xflag is set. */
9068 if (xflag) {
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009069 int n;
9070 const char *p = " %s";
Eric Andersenc470f442003-07-28 09:56:35 +00009071
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009072 p++;
Denis Vlasenko0de37e12007-10-17 11:08:53 +00009073 fdprintf(preverrout_fd, p, expandstr(ps4val()));
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009074
9075 sp = varlist.list;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +00009076 for (n = 0; n < 2; n++) {
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009077 while (sp) {
Denis Vlasenko0de37e12007-10-17 11:08:53 +00009078 fdprintf(preverrout_fd, p, sp->text);
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009079 sp = sp->next;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +00009080 if (*p == '%') {
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009081 p--;
9082 }
9083 }
9084 sp = arglist.list;
9085 }
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00009086 safe_write(preverrout_fd, "\n", 1);
Eric Andersenc470f442003-07-28 09:56:35 +00009087 }
9088
9089 cmd_is_exec = 0;
9090 spclbltin = -1;
9091
9092 /* Now locate the command. */
9093 if (argc) {
9094 const char *oldpath;
9095 int cmd_flag = DO_ERR;
9096
9097 path += 5;
9098 oldpath = path;
9099 for (;;) {
9100 find_command(argv[0], &cmdentry, cmd_flag, path);
9101 if (cmdentry.cmdtype == CMDUNKNOWN) {
Denis Vlasenkob012b102007-02-19 22:43:01 +00009102 flush_stderr();
Denis Vlasenko6514c5e2008-07-24 13:41:37 +00009103 status = 127;
Eric Andersenc470f442003-07-28 09:56:35 +00009104 goto bail;
9105 }
9106
9107 /* implement bltin and command here */
9108 if (cmdentry.cmdtype != CMDBUILTIN)
9109 break;
9110 if (spclbltin < 0)
9111 spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
9112 if (cmdentry.u.cmd == EXECCMD)
Denis Vlasenko34c73c42008-08-16 11:48:02 +00009113 cmd_is_exec = 1;
Denis Vlasenko131ae172007-02-18 13:00:19 +00009114#if ENABLE_ASH_CMDCMD
Eric Andersenc470f442003-07-28 09:56:35 +00009115 if (cmdentry.u.cmd == COMMANDCMD) {
Eric Andersenc470f442003-07-28 09:56:35 +00009116 path = oldpath;
9117 nargv = parse_command_args(argv, &path);
9118 if (!nargv)
9119 break;
9120 argc -= nargv - argv;
9121 argv = nargv;
9122 cmd_flag |= DO_NOFUNC;
9123 } else
9124#endif
9125 break;
9126 }
9127 }
9128
9129 if (status) {
9130 /* We have a redirection error. */
9131 if (spclbltin > 0)
Denis Vlasenkob012b102007-02-19 22:43:01 +00009132 raise_exception(EXERROR);
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009133 bail:
Eric Andersenc470f442003-07-28 09:56:35 +00009134 exitstatus = status;
9135 goto out;
9136 }
9137
9138 /* Execute the command. */
9139 switch (cmdentry.cmdtype) {
9140 default:
Denis Vlasenkobe54d6b2008-10-27 14:25:52 +00009141
Denis Vlasenko9bc80d72008-04-12 20:07:53 +00009142#if ENABLE_FEATURE_SH_NOFORK
Denis Vlasenkobe54d6b2008-10-27 14:25:52 +00009143/* Hmmm... shouldn't it happen somewhere in forkshell() instead?
9144 * Why "fork off a child process if necessary" doesn't apply to NOFORK? */
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00009145 {
9146 /* find_command() encodes applet_no as (-2 - applet_no) */
9147 int applet_no = (- cmdentry.u.index - 2);
Denis Vlasenko9bc80d72008-04-12 20:07:53 +00009148 if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
Denis Vlasenko9bc80d72008-04-12 20:07:53 +00009149 listsetvar(varlist.list, VEXPORT|VSTACK);
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00009150 /* run <applet>_main() */
9151 exitstatus = run_nofork_applet(applet_no, argv);
Denis Vlasenko9bc80d72008-04-12 20:07:53 +00009152 break;
9153 }
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00009154 }
Denis Vlasenko9bc80d72008-04-12 20:07:53 +00009155#endif
Eric Andersenc470f442003-07-28 09:56:35 +00009156 /* Fork off a child process if necessary. */
9157 if (!(flags & EV_EXIT) || trap[0]) {
Denis Vlasenkob012b102007-02-19 22:43:01 +00009158 INT_OFF;
Denis Vlasenko68404f12008-03-17 09:00:54 +00009159 jp = makejob(/*cmd,*/ 1);
Eric Andersenc470f442003-07-28 09:56:35 +00009160 if (forkshell(jp, cmd, FORK_FG) != 0) {
9161 exitstatus = waitforjob(jp);
Denis Vlasenkob012b102007-02-19 22:43:01 +00009162 INT_ON;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00009163 TRACE(("forked child exited with %d\n", exitstatus));
Eric Andersenc470f442003-07-28 09:56:35 +00009164 break;
9165 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00009166 FORCE_INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00009167 }
9168 listsetvar(varlist.list, VEXPORT|VSTACK);
9169 shellexec(argv, path, cmdentry.u.index);
9170 /* NOTREACHED */
9171
9172 case CMDBUILTIN:
9173 cmdenviron = varlist.list;
9174 if (cmdenviron) {
9175 struct strlist *list = cmdenviron;
9176 int i = VNOSET;
9177 if (spclbltin > 0 || argc == 0) {
9178 i = 0;
9179 if (cmd_is_exec && argc > 1)
9180 i = VEXPORT;
9181 }
9182 listsetvar(list, i);
9183 }
Denis Vlasenkobe54d6b2008-10-27 14:25:52 +00009184 /* Tight loop with builtins only:
9185 * "while kill -0 $child; do true; done"
9186 * will never exit even if $child died, unless we do this
9187 * to reap the zombie and make kill detect that it's gone: */
9188 dowait(DOWAIT_NONBLOCK, NULL);
9189
Eric Andersenc470f442003-07-28 09:56:35 +00009190 if (evalbltin(cmdentry.u.cmd, argc, argv)) {
9191 int exit_status;
Denis Vlasenko7f88e342009-03-19 03:36:18 +00009192 int i = exception_type;
Eric Andersenc470f442003-07-28 09:56:35 +00009193 if (i == EXEXIT)
9194 goto raise;
Eric Andersenc470f442003-07-28 09:56:35 +00009195 exit_status = 2;
Eric Andersenc470f442003-07-28 09:56:35 +00009196 if (i == EXINT)
Denis Vlasenko991a1da2008-02-10 19:02:53 +00009197 exit_status = 128 + SIGINT;
Eric Andersenc470f442003-07-28 09:56:35 +00009198 if (i == EXSIG)
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02009199 exit_status = 128 + pending_sig;
Eric Andersenc470f442003-07-28 09:56:35 +00009200 exitstatus = exit_status;
Eric Andersenc470f442003-07-28 09:56:35 +00009201 if (i == EXINT || spclbltin > 0) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009202 raise:
Denis Vlasenko2da584f2007-02-19 22:44:05 +00009203 longjmp(exception_handler->loc, 1);
Eric Andersenc470f442003-07-28 09:56:35 +00009204 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00009205 FORCE_INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00009206 }
9207 break;
9208
9209 case CMDFUNCTION:
9210 listsetvar(varlist.list, 0);
Denis Vlasenkobe54d6b2008-10-27 14:25:52 +00009211 /* See above for the rationale */
9212 dowait(DOWAIT_NONBLOCK, NULL);
Eric Andersenc470f442003-07-28 09:56:35 +00009213 if (evalfun(cmdentry.u.func, argc, argv, flags))
9214 goto raise;
9215 break;
9216 }
9217
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009218 out:
Denis Vlasenko34c73c42008-08-16 11:48:02 +00009219 popredir(/*drop:*/ cmd_is_exec, /*restore:*/ cmd_is_exec);
Denis Vlasenko6514c5e2008-07-24 13:41:37 +00009220 if (lastarg) {
Eric Andersenc470f442003-07-28 09:56:35 +00009221 /* dsl: I think this is intended to be used to support
9222 * '_' in 'vi' command mode during line editing...
9223 * However I implemented that within libedit itself.
9224 */
9225 setvar("_", lastarg, 0);
Denis Vlasenko6514c5e2008-07-24 13:41:37 +00009226 }
Eric Andersenc470f442003-07-28 09:56:35 +00009227 popstackmark(&smark);
9228}
9229
9230static int
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009231evalbltin(const struct builtincmd *cmd, int argc, char **argv)
9232{
Eric Andersenc470f442003-07-28 09:56:35 +00009233 char *volatile savecmdname;
9234 struct jmploc *volatile savehandler;
9235 struct jmploc jmploc;
9236 int i;
9237
9238 savecmdname = commandname;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009239 i = setjmp(jmploc.loc);
9240 if (i)
Eric Andersenc470f442003-07-28 09:56:35 +00009241 goto cmddone;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00009242 savehandler = exception_handler;
9243 exception_handler = &jmploc;
Eric Andersenc470f442003-07-28 09:56:35 +00009244 commandname = argv[0];
9245 argptr = argv + 1;
9246 optptr = NULL; /* initialize nextopt */
9247 exitstatus = (*cmd->builtin)(argc, argv);
Denis Vlasenkob012b102007-02-19 22:43:01 +00009248 flush_stdout_stderr();
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009249 cmddone:
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009250 exitstatus |= ferror(stdout);
Rob Landleyf296f0b2006-07-06 01:09:21 +00009251 clearerr(stdout);
Eric Andersenc470f442003-07-28 09:56:35 +00009252 commandname = savecmdname;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00009253 exception_handler = savehandler;
Eric Andersenc470f442003-07-28 09:56:35 +00009254
9255 return i;
9256}
9257
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009258static int
9259goodname(const char *p)
Glenn L McGrath16e45d72004-02-04 08:24:39 +00009260{
9261 return !*endofname(p);
9262}
9263
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009264
Glenn L McGrath50812ff2002-08-23 13:14:48 +00009265/*
9266 * Search for a command. This is called before we fork so that the
9267 * location of the command will be available in the parent as well as
Glenn L McGrath16e45d72004-02-04 08:24:39 +00009268 * the child. The check for "goodname" is an overly conservative
9269 * check that the name will not be subject to expansion.
Glenn L McGrath50812ff2002-08-23 13:14:48 +00009270 */
Eric Andersenc470f442003-07-28 09:56:35 +00009271static void
9272prehash(union node *n)
Glenn L McGrath50812ff2002-08-23 13:14:48 +00009273{
9274 struct cmdentry entry;
9275
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +00009276 if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
9277 find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
Glenn L McGrath50812ff2002-08-23 13:14:48 +00009278}
9279
Eric Andersencb57d552001-06-28 07:25:16 +00009280
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00009281/* ============ Builtin commands
9282 *
9283 * Builtin commands whose functions are closely tied to evaluation
9284 * are implemented here.
Eric Andersencb57d552001-06-28 07:25:16 +00009285 */
9286
9287/*
Eric Andersencb57d552001-06-28 07:25:16 +00009288 * Handle break and continue commands. Break, continue, and return are
9289 * all handled by setting the evalskip flag. The evaluation routines
9290 * above all check this flag, and if it is set they start skipping
9291 * commands rather than executing them. The variable skipcount is
9292 * the number of loops to break/continue, or the number of function
9293 * levels to return. (The latter is always 1.) It should probably
9294 * be an error to break out of more loops than exist, but it isn't
9295 * in the standard shell so we don't make it one here.
9296 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009297static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00009298breakcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +00009299{
Denis Vlasenko68404f12008-03-17 09:00:54 +00009300 int n = argv[1] ? number(argv[1]) : 1;
Eric Andersencb57d552001-06-28 07:25:16 +00009301
Aaron Lehmann2aef3a62001-12-31 06:03:12 +00009302 if (n <= 0)
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02009303 ash_msg_and_raise_error(msg_illnum, argv[1]);
Eric Andersencb57d552001-06-28 07:25:16 +00009304 if (n > loopnest)
9305 n = loopnest;
9306 if (n > 0) {
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00009307 evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
Eric Andersencb57d552001-06-28 07:25:16 +00009308 skipcount = n;
9309 }
9310 return 0;
9311}
9312
Eric Andersenc470f442003-07-28 09:56:35 +00009313
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009314/* ============ input.c
9315 *
Eric Andersen90898442003-08-06 11:20:52 +00009316 * This implements the input routines used by the parser.
Eric Andersencb57d552001-06-28 07:25:16 +00009317 */
Denis Vlasenko99eb8502007-02-23 21:09:49 +00009318
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009319enum {
9320 INPUT_PUSH_FILE = 1,
9321 INPUT_NOFILE_OK = 2,
9322};
Eric Andersencb57d552001-06-28 07:25:16 +00009323
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009324static smallint checkkwd;
Denis Vlasenko99eb8502007-02-23 21:09:49 +00009325/* values of checkkwd variable */
9326#define CHKALIAS 0x1
9327#define CHKKWD 0x2
9328#define CHKNL 0x4
9329
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009330/*
9331 * Push a string back onto the input at this current parsefile level.
9332 * We handle aliases this way.
9333 */
9334#if !ENABLE_ASH_ALIAS
9335#define pushstring(s, ap) pushstring(s)
9336#endif
9337static void
9338pushstring(char *s, struct alias *ap)
9339{
9340 struct strpush *sp;
9341 int len;
9342
9343 len = strlen(s);
9344 INT_OFF;
9345 if (g_parsefile->strpush) {
9346 sp = ckzalloc(sizeof(*sp));
9347 sp->prev = g_parsefile->strpush;
9348 } else {
9349 sp = &(g_parsefile->basestrpush);
9350 }
9351 g_parsefile->strpush = sp;
9352 sp->prev_string = g_parsefile->next_to_pgetc;
9353 sp->prev_left_in_line = g_parsefile->left_in_line;
9354#if ENABLE_ASH_ALIAS
9355 sp->ap = ap;
9356 if (ap) {
9357 ap->flag |= ALIASINUSE;
9358 sp->string = s;
9359 }
9360#endif
9361 g_parsefile->next_to_pgetc = s;
9362 g_parsefile->left_in_line = len;
9363 INT_ON;
9364}
9365
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009366static void
9367popstring(void)
Eric Andersenc470f442003-07-28 09:56:35 +00009368{
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009369 struct strpush *sp = g_parsefile->strpush;
Eric Andersenc470f442003-07-28 09:56:35 +00009370
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009371 INT_OFF;
Denis Vlasenko131ae172007-02-18 13:00:19 +00009372#if ENABLE_ASH_ALIAS
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009373 if (sp->ap) {
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009374 if (g_parsefile->next_to_pgetc[-1] == ' '
9375 || g_parsefile->next_to_pgetc[-1] == '\t'
9376 ) {
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009377 checkkwd |= CHKALIAS;
Glenn L McGrath28939ad2004-07-21 10:20:19 +00009378 }
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009379 if (sp->string != sp->ap->val) {
9380 free(sp->string);
9381 }
9382 sp->ap->flag &= ~ALIASINUSE;
9383 if (sp->ap->flag & ALIASDEAD) {
9384 unalias(sp->ap->name);
9385 }
Glenn L McGrath28939ad2004-07-21 10:20:19 +00009386 }
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009387#endif
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009388 g_parsefile->next_to_pgetc = sp->prev_string;
9389 g_parsefile->left_in_line = sp->prev_left_in_line;
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009390 g_parsefile->strpush = sp->prev;
9391 if (sp != &(g_parsefile->basestrpush))
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009392 free(sp);
9393 INT_ON;
9394}
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009395
Denis Vlasenkoe27dafd2008-11-28 04:01:03 +00009396//FIXME: BASH_COMPAT with "...&" does TWO pungetc():
9397//it peeks whether it is &>, and then pushes back both chars.
9398//This function needs to save last *next_to_pgetc to buf[0]
9399//to make two pungetc() reliable. Currently,
9400// pgetc (out of buf: does preadfd), pgetc, pungetc, pungetc won't work...
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009401static int
9402preadfd(void)
Eric Andersencb57d552001-06-28 07:25:16 +00009403{
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00009404 int nr;
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00009405 char *buf = g_parsefile->buf;
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00009406
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009407 g_parsefile->next_to_pgetc = buf;
Denis Vlasenko38f63192007-01-22 09:03:07 +00009408#if ENABLE_FEATURE_EDITING
Denis Vlasenko85c24712008-03-17 09:04:04 +00009409 retry:
Denis Vlasenko727752d2008-11-28 03:41:47 +00009410 if (!iflag || g_parsefile->fd != STDIN_FILENO)
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009411 nr = nonblock_safe_read(g_parsefile->fd, buf, BUFSIZ - 1);
Eric Andersenc470f442003-07-28 09:56:35 +00009412 else {
Denis Vlasenko38f63192007-01-22 09:03:07 +00009413#if ENABLE_FEATURE_TAB_COMPLETION
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009414 line_input_state->path_lookup = pathval();
Eric Andersen4a79c0e2004-09-08 10:01:07 +00009415#endif
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009416 nr = read_line_input(cmdedit_prompt, buf, BUFSIZ, line_input_state);
9417 if (nr == 0) {
9418 /* Ctrl+C pressed */
9419 if (trap[SIGINT]) {
Glenn L McGrath16e45d72004-02-04 08:24:39 +00009420 buf[0] = '\n';
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009421 buf[1] = '\0';
Glenn L McGrath16e45d72004-02-04 08:24:39 +00009422 raise(SIGINT);
9423 return 1;
9424 }
Eric Andersenc470f442003-07-28 09:56:35 +00009425 goto retry;
9426 }
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009427 if (nr < 0 && errno == 0) {
Denis Vlasenko9cb220b2007-12-09 10:03:28 +00009428 /* Ctrl+D pressed */
Eric Andersenc470f442003-07-28 09:56:35 +00009429 nr = 0;
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00009430 }
Eric Andersencb57d552001-06-28 07:25:16 +00009431 }
9432#else
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +00009433 nr = nonblock_safe_read(g_parsefile->fd, buf, BUFSIZ - 1);
Eric Andersencb57d552001-06-28 07:25:16 +00009434#endif
9435
Denis Vlasenkoe376d452008-02-20 22:23:24 +00009436#if 0
9437/* nonblock_safe_read() handles this problem */
Eric Andersencb57d552001-06-28 07:25:16 +00009438 if (nr < 0) {
Eric Andersencb57d552001-06-28 07:25:16 +00009439 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
Denis Vlasenkod37f2222007-08-19 13:42:08 +00009440 int flags = fcntl(0, F_GETFL);
Denis Vlasenko9cb220b2007-12-09 10:03:28 +00009441 if (flags >= 0 && (flags & O_NONBLOCK)) {
9442 flags &= ~O_NONBLOCK;
Eric Andersencb57d552001-06-28 07:25:16 +00009443 if (fcntl(0, F_SETFL, flags) >= 0) {
9444 out2str("sh: turning off NDELAY mode\n");
9445 goto retry;
9446 }
9447 }
9448 }
9449 }
Denis Vlasenkoe376d452008-02-20 22:23:24 +00009450#endif
Eric Andersencb57d552001-06-28 07:25:16 +00009451 return nr;
9452}
9453
9454/*
9455 * Refill the input buffer and return the next input character:
9456 *
9457 * 1) If a string was pushed back on the input, pop it;
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009458 * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
9459 * or we are reading from a string so we can't refill the buffer,
9460 * return EOF.
Denys Vlasenko883cea42009-07-11 15:31:59 +02009461 * 3) If there is more stuff in this buffer, use it else call read to fill it.
Eric Andersencb57d552001-06-28 07:25:16 +00009462 * 4) Process input up to the next newline, deleting nul characters.
9463 */
Denis Vlasenko727752d2008-11-28 03:41:47 +00009464//#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
9465#define pgetc_debug(...) ((void)0)
Denis Vlasenko68819d12008-12-15 11:26:36 +00009466/*
9467 * NB: due to SIT(c) internals (syntax_index_table[] vector),
9468 * pgetc() and related functions must return chars SIGN-EXTENDED into ints,
9469 * not zero-extended. Seems fragile to me. Affects only !USE_SIT_FUNCTION case,
9470 * so we can fix it by ditching !USE_SIT_FUNCTION if Unicode requires that.
9471 */
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009472static int
Eric Andersenc470f442003-07-28 09:56:35 +00009473preadbuffer(void)
Eric Andersencb57d552001-06-28 07:25:16 +00009474{
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009475 char *q;
Eric Andersencb57d552001-06-28 07:25:16 +00009476 int more;
Eric Andersencb57d552001-06-28 07:25:16 +00009477
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009478 while (g_parsefile->strpush) {
Denis Vlasenko131ae172007-02-18 13:00:19 +00009479#if ENABLE_ASH_ALIAS
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009480 if (g_parsefile->left_in_line == -1
9481 && g_parsefile->strpush->ap
9482 && g_parsefile->next_to_pgetc[-1] != ' '
9483 && g_parsefile->next_to_pgetc[-1] != '\t'
Denis Vlasenko16898402008-11-25 01:34:52 +00009484 ) {
Denis Vlasenko727752d2008-11-28 03:41:47 +00009485 pgetc_debug("preadbuffer PEOA");
Eric Andersencb57d552001-06-28 07:25:16 +00009486 return PEOA;
9487 }
Eric Andersen2870d962001-07-02 17:27:21 +00009488#endif
Eric Andersencb57d552001-06-28 07:25:16 +00009489 popstring();
Denis Vlasenko727752d2008-11-28 03:41:47 +00009490 /* try "pgetc" now: */
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009491 pgetc_debug("preadbuffer internal pgetc at %d:%p'%s'",
9492 g_parsefile->left_in_line,
9493 g_parsefile->next_to_pgetc,
9494 g_parsefile->next_to_pgetc);
9495 if (--g_parsefile->left_in_line >= 0)
9496 return (unsigned char)(*g_parsefile->next_to_pgetc++);
Eric Andersencb57d552001-06-28 07:25:16 +00009497 }
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009498 /* on both branches above g_parsefile->left_in_line < 0.
Denis Vlasenko727752d2008-11-28 03:41:47 +00009499 * "pgetc" needs refilling.
9500 */
9501
Denis Vlasenkoe27dafd2008-11-28 04:01:03 +00009502 /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009503 * pungetc() may increment it a few times.
Denis Vlasenkoe27dafd2008-11-28 04:01:03 +00009504 * Assuming it won't increment it to less than -90.
Denis Vlasenko727752d2008-11-28 03:41:47 +00009505 */
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009506 if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
Denis Vlasenko727752d2008-11-28 03:41:47 +00009507 pgetc_debug("preadbuffer PEOF1");
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009508 /* even in failure keep left_in_line and next_to_pgetc
9509 * in lock step, for correct multi-layer pungetc.
9510 * left_in_line was decremented before preadbuffer(),
9511 * must inc next_to_pgetc: */
9512 g_parsefile->next_to_pgetc++;
Eric Andersencb57d552001-06-28 07:25:16 +00009513 return PEOF;
Denis Vlasenko727752d2008-11-28 03:41:47 +00009514 }
Eric Andersencb57d552001-06-28 07:25:16 +00009515
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009516 more = g_parsefile->left_in_buffer;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009517 if (more <= 0) {
Denis Vlasenko727752d2008-11-28 03:41:47 +00009518 flush_stdout_stderr();
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009519 again:
9520 more = preadfd();
9521 if (more <= 0) {
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009522 /* don't try reading again */
9523 g_parsefile->left_in_line = -99;
Denis Vlasenko727752d2008-11-28 03:41:47 +00009524 pgetc_debug("preadbuffer PEOF2");
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009525 g_parsefile->next_to_pgetc++;
Eric Andersencb57d552001-06-28 07:25:16 +00009526 return PEOF;
9527 }
9528 }
9529
Denis Vlasenko727752d2008-11-28 03:41:47 +00009530 /* Find out where's the end of line.
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009531 * Set g_parsefile->left_in_line
9532 * and g_parsefile->left_in_buffer acordingly.
Denis Vlasenko727752d2008-11-28 03:41:47 +00009533 * NUL chars are deleted.
9534 */
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009535 q = g_parsefile->next_to_pgetc;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009536 for (;;) {
Denis Vlasenko727752d2008-11-28 03:41:47 +00009537 char c;
Eric Andersencb57d552001-06-28 07:25:16 +00009538
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009539 more--;
Eric Andersenc470f442003-07-28 09:56:35 +00009540
Denis Vlasenko727752d2008-11-28 03:41:47 +00009541 c = *q;
9542 if (c == '\0') {
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009543 memmove(q, q + 1, more);
Denis Vlasenko727752d2008-11-28 03:41:47 +00009544 } else {
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009545 q++;
9546 if (c == '\n') {
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009547 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009548 break;
9549 }
Eric Andersencb57d552001-06-28 07:25:16 +00009550 }
9551
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009552 if (more <= 0) {
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009553 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9554 if (g_parsefile->left_in_line < 0)
Eric Andersencb57d552001-06-28 07:25:16 +00009555 goto again;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009556 break;
Eric Andersencb57d552001-06-28 07:25:16 +00009557 }
9558 }
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009559 g_parsefile->left_in_buffer = more;
Eric Andersencb57d552001-06-28 07:25:16 +00009560
Eric Andersencb57d552001-06-28 07:25:16 +00009561 if (vflag) {
Denis Vlasenko727752d2008-11-28 03:41:47 +00009562 char save = *q;
9563 *q = '\0';
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009564 out2str(g_parsefile->next_to_pgetc);
Denis Vlasenko727752d2008-11-28 03:41:47 +00009565 *q = save;
Eric Andersencb57d552001-06-28 07:25:16 +00009566 }
9567
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009568 pgetc_debug("preadbuffer at %d:%p'%s'",
9569 g_parsefile->left_in_line,
9570 g_parsefile->next_to_pgetc,
9571 g_parsefile->next_to_pgetc);
Denis Vlasenko68819d12008-12-15 11:26:36 +00009572 return signed_char2int(*g_parsefile->next_to_pgetc++);
Eric Andersencb57d552001-06-28 07:25:16 +00009573}
9574
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009575#define pgetc_as_macro() \
9576 (--g_parsefile->left_in_line >= 0 \
Denis Vlasenko68819d12008-12-15 11:26:36 +00009577 ? signed_char2int(*g_parsefile->next_to_pgetc++) \
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009578 : preadbuffer() \
9579 )
Denis Vlasenko727752d2008-11-28 03:41:47 +00009580
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009581static int
9582pgetc(void)
9583{
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009584 pgetc_debug("pgetc_fast at %d:%p'%s'",
9585 g_parsefile->left_in_line,
9586 g_parsefile->next_to_pgetc,
9587 g_parsefile->next_to_pgetc);
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009588 return pgetc_as_macro();
9589}
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00009590
9591#if ENABLE_ASH_OPTIMIZE_FOR_SIZE
Denis Vlasenko834dee72008-10-07 09:18:30 +00009592#define pgetc_fast() pgetc()
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009593#else
Denis Vlasenko834dee72008-10-07 09:18:30 +00009594#define pgetc_fast() pgetc_as_macro()
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009595#endif
9596
9597/*
9598 * Same as pgetc(), but ignores PEOA.
9599 */
9600#if ENABLE_ASH_ALIAS
9601static int
9602pgetc2(void)
9603{
9604 int c;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009605 do {
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009606 pgetc_debug("pgetc_fast at %d:%p'%s'",
9607 g_parsefile->left_in_line,
9608 g_parsefile->next_to_pgetc,
9609 g_parsefile->next_to_pgetc);
Denis Vlasenko834dee72008-10-07 09:18:30 +00009610 c = pgetc_fast();
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009611 } while (c == PEOA);
9612 return c;
9613}
9614#else
Denis Vlasenko834dee72008-10-07 09:18:30 +00009615#define pgetc2() pgetc()
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009616#endif
9617
9618/*
9619 * Read a line from the script.
9620 */
9621static char *
9622pfgets(char *line, int len)
9623{
9624 char *p = line;
9625 int nleft = len;
9626 int c;
9627
9628 while (--nleft > 0) {
9629 c = pgetc2();
9630 if (c == PEOF) {
9631 if (p == line)
9632 return NULL;
9633 break;
9634 }
9635 *p++ = c;
9636 if (c == '\n')
9637 break;
9638 }
9639 *p = '\0';
9640 return line;
9641}
9642
Eric Andersenc470f442003-07-28 09:56:35 +00009643/*
9644 * Undo the last call to pgetc. Only one character may be pushed back.
9645 * PEOF may be pushed back.
9646 */
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009647static void
Eric Andersenc470f442003-07-28 09:56:35 +00009648pungetc(void)
9649{
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009650 g_parsefile->left_in_line++;
9651 g_parsefile->next_to_pgetc--;
9652 pgetc_debug("pushed back to %d:%p'%s'",
9653 g_parsefile->left_in_line,
9654 g_parsefile->next_to_pgetc,
9655 g_parsefile->next_to_pgetc);
Eric Andersencb57d552001-06-28 07:25:16 +00009656}
9657
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009658/*
9659 * To handle the "." command, a stack of input files is used. Pushfile
9660 * adds a new entry to the stack and popfile restores the previous level.
9661 */
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009662static void
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009663pushfile(void)
Eric Andersenc470f442003-07-28 09:56:35 +00009664{
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009665 struct parsefile *pf;
9666
Denis Vlasenko597906c2008-02-20 16:38:54 +00009667 pf = ckzalloc(sizeof(*pf));
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009668 pf->prev = g_parsefile;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009669 pf->fd = -1;
Denis Vlasenko597906c2008-02-20 16:38:54 +00009670 /*pf->strpush = NULL; - ckzalloc did it */
9671 /*pf->basestrpush.prev = NULL;*/
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009672 g_parsefile = pf;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009673}
9674
9675static void
9676popfile(void)
9677{
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009678 struct parsefile *pf = g_parsefile;
Eric Andersenc470f442003-07-28 09:56:35 +00009679
Denis Vlasenkob012b102007-02-19 22:43:01 +00009680 INT_OFF;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009681 if (pf->fd >= 0)
9682 close(pf->fd);
Denis Vlasenko60818682007-09-28 22:07:23 +00009683 free(pf->buf);
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009684 while (pf->strpush)
9685 popstring();
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009686 g_parsefile = pf->prev;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009687 free(pf);
Denis Vlasenkob012b102007-02-19 22:43:01 +00009688 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00009689}
9690
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009691/*
9692 * Return to top level.
9693 */
9694static void
9695popallfiles(void)
9696{
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009697 while (g_parsefile != &basepf)
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009698 popfile();
9699}
9700
9701/*
9702 * Close the file(s) that the shell is reading commands from. Called
9703 * after a fork is done.
9704 */
9705static void
9706closescript(void)
9707{
9708 popallfiles();
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009709 if (g_parsefile->fd > 0) {
9710 close(g_parsefile->fd);
9711 g_parsefile->fd = 0;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009712 }
9713}
9714
9715/*
9716 * Like setinputfile, but takes an open file descriptor. Call this with
9717 * interrupts off.
9718 */
9719static void
9720setinputfd(int fd, int push)
9721{
Denis Vlasenko96e1b382007-09-30 23:50:48 +00009722 close_on_exec_on(fd);
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009723 if (push) {
9724 pushfile();
Denis Vlasenko727752d2008-11-28 03:41:47 +00009725 g_parsefile->buf = NULL;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009726 }
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009727 g_parsefile->fd = fd;
9728 if (g_parsefile->buf == NULL)
9729 g_parsefile->buf = ckmalloc(IBUFSIZ);
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009730 g_parsefile->left_in_buffer = 0;
9731 g_parsefile->left_in_line = 0;
9732 g_parsefile->linno = 1;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009733}
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009734
Eric Andersenc470f442003-07-28 09:56:35 +00009735/*
9736 * Set the input to take input from a file. If push is set, push the
9737 * old input onto the stack first.
9738 */
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009739static int
9740setinputfile(const char *fname, int flags)
Eric Andersenc470f442003-07-28 09:56:35 +00009741{
9742 int fd;
9743 int fd2;
9744
Denis Vlasenkob012b102007-02-19 22:43:01 +00009745 INT_OFF;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009746 fd = open(fname, O_RDONLY);
9747 if (fd < 0) {
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009748 if (flags & INPUT_NOFILE_OK)
9749 goto out;
Denis Vlasenko9604e1b2009-03-03 18:47:56 +00009750 ash_msg_and_raise_error("can't open '%s'", fname);
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009751 }
Eric Andersenc470f442003-07-28 09:56:35 +00009752 if (fd < 10) {
9753 fd2 = copyfd(fd, 10);
9754 close(fd);
9755 if (fd2 < 0)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00009756 ash_msg_and_raise_error("out of file descriptors");
Eric Andersenc470f442003-07-28 09:56:35 +00009757 fd = fd2;
9758 }
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009759 setinputfd(fd, flags & INPUT_PUSH_FILE);
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009760 out:
Denis Vlasenkob012b102007-02-19 22:43:01 +00009761 INT_ON;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009762 return fd;
Eric Andersenc470f442003-07-28 09:56:35 +00009763}
9764
Eric Andersencb57d552001-06-28 07:25:16 +00009765/*
9766 * Like setinputfile, but takes input from a string.
9767 */
Eric Andersenc470f442003-07-28 09:56:35 +00009768static void
9769setinputstring(char *string)
Eric Andersen62483552001-07-10 06:09:16 +00009770{
Denis Vlasenkob012b102007-02-19 22:43:01 +00009771 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +00009772 pushfile();
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009773 g_parsefile->next_to_pgetc = string;
9774 g_parsefile->left_in_line = strlen(string);
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009775 g_parsefile->buf = NULL;
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009776 g_parsefile->linno = 1;
Denis Vlasenkob012b102007-02-19 22:43:01 +00009777 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00009778}
9779
9780
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00009781/* ============ mail.c
9782 *
9783 * Routines to check for mail.
Eric Andersencb57d552001-06-28 07:25:16 +00009784 */
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00009785
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00009786#if ENABLE_ASH_MAIL
Eric Andersencb57d552001-06-28 07:25:16 +00009787
Eric Andersencb57d552001-06-28 07:25:16 +00009788#define MAXMBOXES 10
9789
Eric Andersenc470f442003-07-28 09:56:35 +00009790/* times of mailboxes */
9791static time_t mailtime[MAXMBOXES];
9792/* Set if MAIL or MAILPATH is changed. */
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +00009793static smallint mail_var_path_changed;
Eric Andersencb57d552001-06-28 07:25:16 +00009794
Eric Andersencb57d552001-06-28 07:25:16 +00009795/*
Eric Andersenc470f442003-07-28 09:56:35 +00009796 * Print appropriate message(s) if mail has arrived.
9797 * If mail_var_path_changed is set,
9798 * then the value of MAIL has mail_var_path_changed,
9799 * so we just update the values.
Eric Andersencb57d552001-06-28 07:25:16 +00009800 */
Eric Andersenc470f442003-07-28 09:56:35 +00009801static void
9802chkmail(void)
Eric Andersencb57d552001-06-28 07:25:16 +00009803{
Eric Andersencb57d552001-06-28 07:25:16 +00009804 const char *mpath;
9805 char *p;
9806 char *q;
Eric Andersenc470f442003-07-28 09:56:35 +00009807 time_t *mtp;
Eric Andersencb57d552001-06-28 07:25:16 +00009808 struct stackmark smark;
9809 struct stat statb;
9810
Eric Andersencb57d552001-06-28 07:25:16 +00009811 setstackmark(&smark);
Eric Andersenc470f442003-07-28 09:56:35 +00009812 mpath = mpathset() ? mpathval() : mailval();
9813 for (mtp = mailtime; mtp < mailtime + MAXMBOXES; mtp++) {
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02009814 p = path_advance(&mpath, nullstr);
Eric Andersencb57d552001-06-28 07:25:16 +00009815 if (p == NULL)
9816 break;
9817 if (*p == '\0')
9818 continue;
Denis Vlasenkof7d56652008-03-25 05:51:41 +00009819 for (q = p; *q; q++)
9820 continue;
Denis Vlasenkoa7189f02006-11-17 20:29:00 +00009821#if DEBUG
Eric Andersencb57d552001-06-28 07:25:16 +00009822 if (q[-1] != '/')
9823 abort();
9824#endif
Eric Andersenc470f442003-07-28 09:56:35 +00009825 q[-1] = '\0'; /* delete trailing '/' */
9826 if (stat(p, &statb) < 0) {
9827 *mtp = 0;
9828 continue;
Eric Andersencb57d552001-06-28 07:25:16 +00009829 }
Eric Andersenc470f442003-07-28 09:56:35 +00009830 if (!mail_var_path_changed && statb.st_mtime != *mtp) {
9831 fprintf(
9832 stderr, snlfmt,
9833 pathopt ? pathopt : "you have mail"
9834 );
9835 }
9836 *mtp = statb.st_mtime;
Eric Andersencb57d552001-06-28 07:25:16 +00009837 }
Eric Andersenc470f442003-07-28 09:56:35 +00009838 mail_var_path_changed = 0;
Eric Andersencb57d552001-06-28 07:25:16 +00009839 popstackmark(&smark);
9840}
Eric Andersencb57d552001-06-28 07:25:16 +00009841
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009842static void FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00009843changemail(const char *val UNUSED_PARAM)
Eric Andersenc470f442003-07-28 09:56:35 +00009844{
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +00009845 mail_var_path_changed = 1;
Eric Andersenc470f442003-07-28 09:56:35 +00009846}
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00009847
Denis Vlasenko131ae172007-02-18 13:00:19 +00009848#endif /* ASH_MAIL */
Eric Andersenc470f442003-07-28 09:56:35 +00009849
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00009850
9851/* ============ ??? */
9852
Eric Andersencb57d552001-06-28 07:25:16 +00009853/*
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009854 * Set the shell parameters.
Eric Andersencb57d552001-06-28 07:25:16 +00009855 */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009856static void
9857setparam(char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +00009858{
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009859 char **newparam;
9860 char **ap;
9861 int nparam;
Eric Andersencb57d552001-06-28 07:25:16 +00009862
Denis Vlasenkof7d56652008-03-25 05:51:41 +00009863 for (nparam = 0; argv[nparam]; nparam++)
9864 continue;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009865 ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
9866 while (*argv) {
9867 *ap++ = ckstrdup(*argv++);
Eric Andersencb57d552001-06-28 07:25:16 +00009868 }
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009869 *ap = NULL;
9870 freeparam(&shellparam);
Denis Vlasenko01631112007-12-16 17:20:38 +00009871 shellparam.malloced = 1;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009872 shellparam.nparam = nparam;
9873 shellparam.p = newparam;
9874#if ENABLE_ASH_GETOPTS
9875 shellparam.optind = 1;
9876 shellparam.optoff = -1;
9877#endif
Eric Andersencb57d552001-06-28 07:25:16 +00009878}
9879
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00009880/*
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009881 * Process shell options. The global variable argptr contains a pointer
9882 * to the argument list; we advance it past the options.
Denis Vlasenko94e87bc2008-02-14 16:51:58 +00009883 *
9884 * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
9885 * For a non-interactive shell, an error condition encountered
9886 * by a special built-in ... shall cause the shell to write a diagnostic message
9887 * to standard error and exit as shown in the following table:
Denis Vlasenko56244732008-02-17 15:14:04 +00009888 * Error Special Built-In
Denis Vlasenko94e87bc2008-02-14 16:51:58 +00009889 * ...
9890 * Utility syntax error (option or operand error) Shall exit
9891 * ...
9892 * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
9893 * we see that bash does not do that (set "finishes" with error code 1 instead,
9894 * and shell continues), and people rely on this behavior!
9895 * Testcase:
9896 * set -o barfoo 2>/dev/null
9897 * echo $?
9898 *
9899 * Oh well. Let's mimic that.
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00009900 */
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009901static int
Denis Vlasenkodddfaff2008-05-06 15:30:27 +00009902plus_minus_o(char *name, int val)
Eric Andersen62483552001-07-10 06:09:16 +00009903{
9904 int i;
9905
Denis Vlasenkoa624c112007-02-19 22:45:43 +00009906 if (name) {
9907 for (i = 0; i < NOPTS; i++) {
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00009908 if (strcmp(name, optnames(i)) == 0) {
Eric Andersenc470f442003-07-28 09:56:35 +00009909 optlist[i] = val;
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009910 return 0;
Eric Andersen62483552001-07-10 06:09:16 +00009911 }
Denis Vlasenkoa624c112007-02-19 22:45:43 +00009912 }
Denis Vlasenkodddfaff2008-05-06 15:30:27 +00009913 ash_msg("illegal option %co %s", val ? '-' : '+', name);
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009914 return 1;
Eric Andersen62483552001-07-10 06:09:16 +00009915 }
Denis Vlasenko6b06cb82008-05-15 21:30:45 +00009916 for (i = 0; i < NOPTS; i++) {
Denis Vlasenkodddfaff2008-05-06 15:30:27 +00009917 if (val) {
9918 out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
9919 } else {
9920 out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
9921 }
Denis Vlasenko6b06cb82008-05-15 21:30:45 +00009922 }
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009923 return 0;
Eric Andersen62483552001-07-10 06:09:16 +00009924}
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009925static void
9926setoption(int flag, int val)
9927{
9928 int i;
9929
9930 for (i = 0; i < NOPTS; i++) {
9931 if (optletters(i) == flag) {
9932 optlist[i] = val;
9933 return;
9934 }
9935 }
Denis Vlasenkodddfaff2008-05-06 15:30:27 +00009936 ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009937 /* NOTREACHED */
9938}
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009939static int
Eric Andersenc470f442003-07-28 09:56:35 +00009940options(int cmdline)
Eric Andersencb57d552001-06-28 07:25:16 +00009941{
9942 char *p;
9943 int val;
9944 int c;
9945
9946 if (cmdline)
9947 minusc = NULL;
9948 while ((p = *argptr) != NULL) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009949 c = *p++;
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +00009950 if (c != '-' && c != '+')
9951 break;
9952 argptr++;
9953 val = 0; /* val = 0 if c == '+' */
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009954 if (c == '-') {
Eric Andersencb57d552001-06-28 07:25:16 +00009955 val = 1;
Denis Vlasenko9f739442006-12-16 23:49:13 +00009956 if (p[0] == '\0' || LONE_DASH(p)) {
Eric Andersen2870d962001-07-02 17:27:21 +00009957 if (!cmdline) {
9958 /* "-" means turn off -x and -v */
9959 if (p[0] == '\0')
9960 xflag = vflag = 0;
9961 /* "--" means reset params */
9962 else if (*argptr == NULL)
Eric Andersencb57d552001-06-28 07:25:16 +00009963 setparam(argptr);
Eric Andersen2870d962001-07-02 17:27:21 +00009964 }
Eric Andersenc470f442003-07-28 09:56:35 +00009965 break; /* "-" or "--" terminates options */
Eric Andersencb57d552001-06-28 07:25:16 +00009966 }
Eric Andersencb57d552001-06-28 07:25:16 +00009967 }
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +00009968 /* first char was + or - */
Eric Andersencb57d552001-06-28 07:25:16 +00009969 while ((c = *p++) != '\0') {
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +00009970 /* bash 3.2 indeed handles -c CMD and +c CMD the same */
Eric Andersencb57d552001-06-28 07:25:16 +00009971 if (c == 'c' && cmdline) {
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +00009972 minusc = p; /* command is after shell args */
Eric Andersencb57d552001-06-28 07:25:16 +00009973 } else if (c == 'o') {
Denis Vlasenkodddfaff2008-05-06 15:30:27 +00009974 if (plus_minus_o(*argptr, val)) {
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009975 /* it already printed err message */
9976 return 1; /* error */
9977 }
Eric Andersencb57d552001-06-28 07:25:16 +00009978 if (*argptr)
9979 argptr++;
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +00009980 } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
9981 isloginsh = 1;
9982 /* bash does not accept +-login, we also won't */
9983 } else if (cmdline && val && (c == '-')) { /* long options */
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00009984 if (strcmp(p, "login") == 0)
Robert Griebl64f70cc2002-05-14 23:22:06 +00009985 isloginsh = 1;
9986 break;
Eric Andersencb57d552001-06-28 07:25:16 +00009987 } else {
9988 setoption(c, val);
9989 }
9990 }
9991 }
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009992 return 0;
Eric Andersencb57d552001-06-28 07:25:16 +00009993}
9994
Eric Andersencb57d552001-06-28 07:25:16 +00009995/*
Eric Andersencb57d552001-06-28 07:25:16 +00009996 * The shift builtin command.
9997 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009998static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00009999shiftcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +000010000{
10001 int n;
10002 char **ap1, **ap2;
10003
10004 n = 1;
Denis Vlasenko68404f12008-03-17 09:00:54 +000010005 if (argv[1])
Eric Andersencb57d552001-06-28 07:25:16 +000010006 n = number(argv[1]);
10007 if (n > shellparam.nparam)
Denis Vlasenkoc90e1be2008-07-30 15:35:05 +000010008 n = 0; /* bash compat, was = shellparam.nparam; */
Denis Vlasenkob012b102007-02-19 22:43:01 +000010009 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +000010010 shellparam.nparam -= n;
Denis Vlasenko2da584f2007-02-19 22:44:05 +000010011 for (ap1 = shellparam.p; --n >= 0; ap1++) {
Denis Vlasenko01631112007-12-16 17:20:38 +000010012 if (shellparam.malloced)
Denis Vlasenkob012b102007-02-19 22:43:01 +000010013 free(*ap1);
Eric Andersencb57d552001-06-28 07:25:16 +000010014 }
10015 ap2 = shellparam.p;
Denis Vlasenkof7d56652008-03-25 05:51:41 +000010016 while ((*ap2++ = *ap1++) != NULL)
10017 continue;
Denis Vlasenko131ae172007-02-18 13:00:19 +000010018#if ENABLE_ASH_GETOPTS
Eric Andersencb57d552001-06-28 07:25:16 +000010019 shellparam.optind = 1;
10020 shellparam.optoff = -1;
Eric Andersenc470f442003-07-28 09:56:35 +000010021#endif
Denis Vlasenkob012b102007-02-19 22:43:01 +000010022 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +000010023 return 0;
10024}
10025
Eric Andersencb57d552001-06-28 07:25:16 +000010026/*
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010027 * POSIX requires that 'set' (but not export or readonly) output the
10028 * variables in lexicographic order - by the locale's collating order (sigh).
10029 * Maybe we could keep them in an ordered balanced binary tree
10030 * instead of hashed lists.
10031 * For now just roll 'em through qsort for printing...
10032 */
10033static int
10034showvars(const char *sep_prefix, int on, int off)
10035{
10036 const char *sep;
10037 char **ep, **epend;
10038
10039 ep = listvars(on, off, &epend);
10040 qsort(ep, epend - ep, sizeof(char *), vpcmp);
10041
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +000010042 sep = *sep_prefix ? " " : sep_prefix;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010043
10044 for (; ep < epend; ep++) {
10045 const char *p;
10046 const char *q;
10047
10048 p = strchrnul(*ep, '=');
10049 q = nullstr;
10050 if (*p)
10051 q = single_quote(++p);
10052 out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
10053 }
10054 return 0;
10055}
10056
10057/*
Eric Andersencb57d552001-06-28 07:25:16 +000010058 * The set command builtin.
10059 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010060static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000010061setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersencb57d552001-06-28 07:25:16 +000010062{
Denis Vlasenko28bf6712008-02-14 15:01:47 +000010063 int retval;
10064
Denis Vlasenko68404f12008-03-17 09:00:54 +000010065 if (!argv[1])
Eric Andersenc470f442003-07-28 09:56:35 +000010066 return showvars(nullstr, 0, VUNSET);
Denis Vlasenkob012b102007-02-19 22:43:01 +000010067 INT_OFF;
Denis Vlasenko28bf6712008-02-14 15:01:47 +000010068 retval = 1;
10069 if (!options(0)) { /* if no parse error... */
10070 retval = 0;
10071 optschanged();
10072 if (*argptr != NULL) {
10073 setparam(argptr);
10074 }
Eric Andersencb57d552001-06-28 07:25:16 +000010075 }
Denis Vlasenkob012b102007-02-19 22:43:01 +000010076 INT_ON;
Denis Vlasenko28bf6712008-02-14 15:01:47 +000010077 return retval;
Eric Andersencb57d552001-06-28 07:25:16 +000010078}
10079
Denis Vlasenko131ae172007-02-18 13:00:19 +000010080#if ENABLE_ASH_RANDOM_SUPPORT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010081static void FAST_FUNC
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000010082change_random(const char *value)
Eric Andersenef02f822004-03-11 13:34:24 +000010083{
Denys Vlasenko3ea2e822009-10-09 20:59:04 +020010084 uint32_t t;
10085
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010086 if (value == NULL) {
Eric Andersen16767e22004-03-16 05:14:10 +000010087 /* "get", generate */
Denys Vlasenko3ea2e822009-10-09 20:59:04 +020010088 t = next_random(&random_gen);
Eric Andersen16767e22004-03-16 05:14:10 +000010089 /* set without recursion */
Denis Vlasenko448d30e2008-06-27 00:24:11 +000010090 setvar(vrandom.text, utoa(t), VNOFUNC);
Eric Andersen16767e22004-03-16 05:14:10 +000010091 vrandom.flags &= ~VNOFUNC;
10092 } else {
10093 /* set/reset */
Denys Vlasenko3ea2e822009-10-09 20:59:04 +020010094 t = strtoul(value, NULL, 10);
10095 INIT_RANDOM_T(&random_gen, (t ? t : 1), t);
Eric Andersen16767e22004-03-16 05:14:10 +000010096 }
Eric Andersenef02f822004-03-11 13:34:24 +000010097}
Eric Andersen16767e22004-03-16 05:14:10 +000010098#endif
10099
Denis Vlasenko131ae172007-02-18 13:00:19 +000010100#if ENABLE_ASH_GETOPTS
Eric Andersencb57d552001-06-28 07:25:16 +000010101static int
Eric Andersenc470f442003-07-28 09:56:35 +000010102getopts(char *optstr, char *optvar, char **optfirst, int *param_optind, int *optoff)
Eric Andersencb57d552001-06-28 07:25:16 +000010103{
10104 char *p, *q;
10105 char c = '?';
10106 int done = 0;
10107 int err = 0;
Eric Andersena48b0a32003-10-22 10:56:47 +000010108 char s[12];
10109 char **optnext;
Eric Andersencb57d552001-06-28 07:25:16 +000010110
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010111 if (*param_optind < 1)
Eric Andersena48b0a32003-10-22 10:56:47 +000010112 return 1;
10113 optnext = optfirst + *param_optind - 1;
10114
Denis Vlasenko6b06cb82008-05-15 21:30:45 +000010115 if (*param_optind <= 1 || *optoff < 0 || (int)strlen(optnext[-1]) < *optoff)
Eric Andersencb57d552001-06-28 07:25:16 +000010116 p = NULL;
10117 else
Eric Andersena48b0a32003-10-22 10:56:47 +000010118 p = optnext[-1] + *optoff;
Eric Andersencb57d552001-06-28 07:25:16 +000010119 if (p == NULL || *p == '\0') {
10120 /* Current word is done, advance */
Eric Andersencb57d552001-06-28 07:25:16 +000010121 p = *optnext;
10122 if (p == NULL || *p != '-' || *++p == '\0') {
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010123 atend:
Eric Andersencb57d552001-06-28 07:25:16 +000010124 p = NULL;
10125 done = 1;
10126 goto out;
10127 }
10128 optnext++;
Denis Vlasenko9f739442006-12-16 23:49:13 +000010129 if (LONE_DASH(p)) /* check for "--" */
Eric Andersencb57d552001-06-28 07:25:16 +000010130 goto atend;
10131 }
10132
10133 c = *p++;
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +000010134 for (q = optstr; *q != c;) {
Eric Andersencb57d552001-06-28 07:25:16 +000010135 if (*q == '\0') {
10136 if (optstr[0] == ':') {
10137 s[0] = c;
10138 s[1] = '\0';
10139 err |= setvarsafe("OPTARG", s, 0);
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010140 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000010141 fprintf(stderr, "Illegal option -%c\n", c);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010142 unsetvar("OPTARG");
Eric Andersencb57d552001-06-28 07:25:16 +000010143 }
10144 c = '?';
Eric Andersenc470f442003-07-28 09:56:35 +000010145 goto out;
Eric Andersencb57d552001-06-28 07:25:16 +000010146 }
10147 if (*++q == ':')
10148 q++;
10149 }
10150
10151 if (*++q == ':') {
10152 if (*p == '\0' && (p = *optnext) == NULL) {
10153 if (optstr[0] == ':') {
10154 s[0] = c;
10155 s[1] = '\0';
10156 err |= setvarsafe("OPTARG", s, 0);
10157 c = ':';
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010158 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000010159 fprintf(stderr, "No arg for -%c option\n", c);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010160 unsetvar("OPTARG");
Eric Andersencb57d552001-06-28 07:25:16 +000010161 c = '?';
10162 }
Eric Andersenc470f442003-07-28 09:56:35 +000010163 goto out;
Eric Andersencb57d552001-06-28 07:25:16 +000010164 }
10165
10166 if (p == *optnext)
10167 optnext++;
Eric Andersenc470f442003-07-28 09:56:35 +000010168 err |= setvarsafe("OPTARG", p, 0);
Eric Andersencb57d552001-06-28 07:25:16 +000010169 p = NULL;
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010170 } else
Eric Andersenc470f442003-07-28 09:56:35 +000010171 err |= setvarsafe("OPTARG", nullstr, 0);
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010172 out:
Eric Andersencb57d552001-06-28 07:25:16 +000010173 *optoff = p ? p - *(optnext - 1) : -1;
Eric Andersenc470f442003-07-28 09:56:35 +000010174 *param_optind = optnext - optfirst + 1;
10175 fmtstr(s, sizeof(s), "%d", *param_optind);
Eric Andersencb57d552001-06-28 07:25:16 +000010176 err |= setvarsafe("OPTIND", s, VNOFUNC);
10177 s[0] = c;
10178 s[1] = '\0';
10179 err |= setvarsafe(optvar, s, 0);
10180 if (err) {
Eric Andersenc470f442003-07-28 09:56:35 +000010181 *param_optind = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010182 *optoff = -1;
Denis Vlasenkob012b102007-02-19 22:43:01 +000010183 flush_stdout_stderr();
10184 raise_exception(EXERROR);
Eric Andersencb57d552001-06-28 07:25:16 +000010185 }
10186 return done;
10187}
Eric Andersenc470f442003-07-28 09:56:35 +000010188
10189/*
10190 * The getopts builtin. Shellparam.optnext points to the next argument
10191 * to be processed. Shellparam.optptr points to the next character to
10192 * be processed in the current argument. If shellparam.optnext is NULL,
10193 * then it's the first time getopts has been called.
10194 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010195static int FAST_FUNC
Eric Andersenc470f442003-07-28 09:56:35 +000010196getoptscmd(int argc, char **argv)
10197{
10198 char **optbase;
10199
10200 if (argc < 3)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +000010201 ash_msg_and_raise_error("usage: getopts optstring var [arg]");
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010202 if (argc == 3) {
Eric Andersenc470f442003-07-28 09:56:35 +000010203 optbase = shellparam.p;
10204 if (shellparam.optind > shellparam.nparam + 1) {
10205 shellparam.optind = 1;
10206 shellparam.optoff = -1;
10207 }
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010208 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000010209 optbase = &argv[3];
10210 if (shellparam.optind > argc - 2) {
10211 shellparam.optind = 1;
10212 shellparam.optoff = -1;
10213 }
10214 }
10215
10216 return getopts(argv[1], argv[2], optbase, &shellparam.optind,
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010217 &shellparam.optoff);
Eric Andersenc470f442003-07-28 09:56:35 +000010218}
Denis Vlasenko131ae172007-02-18 13:00:19 +000010219#endif /* ASH_GETOPTS */
Eric Andersencb57d552001-06-28 07:25:16 +000010220
Eric Andersencb57d552001-06-28 07:25:16 +000010221
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010222/* ============ Shell parser */
Eric Andersencb57d552001-06-28 07:25:16 +000010223
Denis Vlasenkob07a4962008-06-22 13:16:23 +000010224struct heredoc {
10225 struct heredoc *next; /* next here document in list */
10226 union node *here; /* redirection node */
10227 char *eofmark; /* string indicating end of input */
10228 smallint striptabs; /* if set, strip leading tabs */
10229};
10230
10231static smallint tokpushback; /* last token pushed back */
10232static smallint parsebackquote; /* nonzero if we are inside backquotes */
10233static smallint quoteflag; /* set if (part of) last token was quoted */
10234static token_id_t lasttoken; /* last token read (integer id Txxx) */
10235static struct heredoc *heredoclist; /* list of here documents to read */
10236static char *wordtext; /* text of last word returned by readtoken */
10237static struct nodelist *backquotelist;
10238static union node *redirnode;
10239static struct heredoc *heredoc;
Denis Vlasenko99eb8502007-02-23 21:09:49 +000010240
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010241/*
10242 * Called when an unexpected token is read during the parse. The argument
10243 * is the token that is expected, or -1 if more than one type of token can
10244 * occur at this point.
10245 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000010246static void raise_error_unexpected_syntax(int) NORETURN;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010247static void
10248raise_error_unexpected_syntax(int token)
10249{
10250 char msg[64];
10251 int l;
10252
Denis Vlasenko7b2294e2008-11-28 03:50:46 +000010253 l = sprintf(msg, "unexpected %s", tokname(lasttoken));
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010254 if (token >= 0)
10255 sprintf(msg + l, " (expecting %s)", tokname(token));
10256 raise_error_syntax(msg);
10257 /* NOTREACHED */
10258}
Eric Andersencb57d552001-06-28 07:25:16 +000010259
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010260#define EOFMARKLEN 79
Eric Andersencb57d552001-06-28 07:25:16 +000010261
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010262/* parsing is heavily cross-recursive, need these forward decls */
10263static union node *andor(void);
10264static union node *pipeline(void);
10265static union node *parse_command(void);
10266static void parseheredoc(void);
10267static char peektoken(void);
10268static int readtoken(void);
Eric Andersencb57d552001-06-28 07:25:16 +000010269
Eric Andersenc470f442003-07-28 09:56:35 +000010270static union node *
10271list(int nlflag)
Eric Andersencb57d552001-06-28 07:25:16 +000010272{
10273 union node *n1, *n2, *n3;
10274 int tok;
10275
Eric Andersenc470f442003-07-28 09:56:35 +000010276 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10277 if (nlflag == 2 && peektoken())
Eric Andersencb57d552001-06-28 07:25:16 +000010278 return NULL;
10279 n1 = NULL;
10280 for (;;) {
10281 n2 = andor();
10282 tok = readtoken();
10283 if (tok == TBACKGND) {
Eric Andersenc470f442003-07-28 09:56:35 +000010284 if (n2->type == NPIPE) {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +000010285 n2->npipe.pipe_backgnd = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010286 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000010287 if (n2->type != NREDIR) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010288 n3 = stzalloc(sizeof(struct nredir));
Eric Andersenc470f442003-07-28 09:56:35 +000010289 n3->nredir.n = n2;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010290 /*n3->nredir.redirect = NULL; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000010291 n2 = n3;
10292 }
10293 n2->type = NBACKGND;
Eric Andersencb57d552001-06-28 07:25:16 +000010294 }
10295 }
10296 if (n1 == NULL) {
10297 n1 = n2;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010298 } else {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010299 n3 = stzalloc(sizeof(struct nbinary));
Eric Andersencb57d552001-06-28 07:25:16 +000010300 n3->type = NSEMI;
10301 n3->nbinary.ch1 = n1;
10302 n3->nbinary.ch2 = n2;
10303 n1 = n3;
10304 }
10305 switch (tok) {
10306 case TBACKGND:
10307 case TSEMI:
10308 tok = readtoken();
10309 /* fall through */
10310 case TNL:
10311 if (tok == TNL) {
10312 parseheredoc();
Eric Andersenc470f442003-07-28 09:56:35 +000010313 if (nlflag == 1)
Eric Andersencb57d552001-06-28 07:25:16 +000010314 return n1;
10315 } else {
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010316 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010317 }
Eric Andersenc470f442003-07-28 09:56:35 +000010318 checkkwd = CHKNL | CHKKWD | CHKALIAS;
Manuel Novoa III 16815d42001-08-10 19:36:07 +000010319 if (peektoken())
Eric Andersencb57d552001-06-28 07:25:16 +000010320 return n1;
10321 break;
10322 case TEOF:
10323 if (heredoclist)
10324 parseheredoc();
10325 else
Eric Andersenc470f442003-07-28 09:56:35 +000010326 pungetc(); /* push back EOF on input */
Eric Andersencb57d552001-06-28 07:25:16 +000010327 return n1;
10328 default:
Eric Andersenc470f442003-07-28 09:56:35 +000010329 if (nlflag == 1)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010330 raise_error_unexpected_syntax(-1);
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010331 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010332 return n1;
10333 }
10334 }
10335}
10336
Eric Andersenc470f442003-07-28 09:56:35 +000010337static union node *
10338andor(void)
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010339{
Eric Andersencb57d552001-06-28 07:25:16 +000010340 union node *n1, *n2, *n3;
10341 int t;
10342
Eric Andersencb57d552001-06-28 07:25:16 +000010343 n1 = pipeline();
10344 for (;;) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010345 t = readtoken();
10346 if (t == TAND) {
Eric Andersencb57d552001-06-28 07:25:16 +000010347 t = NAND;
10348 } else if (t == TOR) {
10349 t = NOR;
10350 } else {
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010351 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010352 return n1;
10353 }
Eric Andersenc470f442003-07-28 09:56:35 +000010354 checkkwd = CHKNL | CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010355 n2 = pipeline();
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010356 n3 = stzalloc(sizeof(struct nbinary));
Eric Andersencb57d552001-06-28 07:25:16 +000010357 n3->type = t;
10358 n3->nbinary.ch1 = n1;
10359 n3->nbinary.ch2 = n2;
10360 n1 = n3;
10361 }
10362}
10363
Eric Andersenc470f442003-07-28 09:56:35 +000010364static union node *
10365pipeline(void)
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010366{
Eric Andersencb57d552001-06-28 07:25:16 +000010367 union node *n1, *n2, *pipenode;
10368 struct nodelist *lp, *prev;
10369 int negate;
10370
10371 negate = 0;
10372 TRACE(("pipeline: entered\n"));
10373 if (readtoken() == TNOT) {
10374 negate = !negate;
Eric Andersenc470f442003-07-28 09:56:35 +000010375 checkkwd = CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010376 } else
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010377 tokpushback = 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010378 n1 = parse_command();
Eric Andersencb57d552001-06-28 07:25:16 +000010379 if (readtoken() == TPIPE) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010380 pipenode = stzalloc(sizeof(struct npipe));
Eric Andersencb57d552001-06-28 07:25:16 +000010381 pipenode->type = NPIPE;
Denis Vlasenko2dc240c2008-07-24 06:07:50 +000010382 /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010383 lp = stzalloc(sizeof(struct nodelist));
Eric Andersencb57d552001-06-28 07:25:16 +000010384 pipenode->npipe.cmdlist = lp;
10385 lp->n = n1;
10386 do {
10387 prev = lp;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010388 lp = stzalloc(sizeof(struct nodelist));
Eric Andersenc470f442003-07-28 09:56:35 +000010389 checkkwd = CHKNL | CHKKWD | CHKALIAS;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010390 lp->n = parse_command();
Eric Andersencb57d552001-06-28 07:25:16 +000010391 prev->next = lp;
10392 } while (readtoken() == TPIPE);
10393 lp->next = NULL;
10394 n1 = pipenode;
10395 }
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010396 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010397 if (negate) {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010398 n2 = stzalloc(sizeof(struct nnot));
Eric Andersencb57d552001-06-28 07:25:16 +000010399 n2->type = NNOT;
10400 n2->nnot.com = n1;
10401 return n2;
Denis Vlasenko2da584f2007-02-19 22:44:05 +000010402 }
10403 return n1;
Eric Andersencb57d552001-06-28 07:25:16 +000010404}
10405
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010406static union node *
10407makename(void)
10408{
10409 union node *n;
10410
Denis Vlasenko597906c2008-02-20 16:38:54 +000010411 n = stzalloc(sizeof(struct narg));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010412 n->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010413 /*n->narg.next = NULL; - stzalloc did it */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010414 n->narg.text = wordtext;
10415 n->narg.backquote = backquotelist;
10416 return n;
10417}
10418
10419static void
10420fixredir(union node *n, const char *text, int err)
10421{
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000010422 int fd;
10423
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010424 TRACE(("Fix redir %s %d\n", text, err));
10425 if (!err)
10426 n->ndup.vname = NULL;
10427
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000010428 fd = bb_strtou(text, NULL, 10);
10429 if (!errno && fd >= 0)
10430 n->ndup.dupfd = fd;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010431 else if (LONE_DASH(text))
10432 n->ndup.dupfd = -1;
10433 else {
10434 if (err)
Denis Vlasenko559691a2008-10-05 18:39:31 +000010435 raise_error_syntax("bad fd number");
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010436 n->ndup.vname = makename();
10437 }
10438}
10439
10440/*
10441 * Returns true if the text contains nothing to expand (no dollar signs
10442 * or backquotes).
10443 */
10444static int
Denis Vlasenko68819d12008-12-15 11:26:36 +000010445noexpand(const char *text)
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010446{
Denis Vlasenko68819d12008-12-15 11:26:36 +000010447 const char *p;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010448 char c;
10449
10450 p = text;
10451 while ((c = *p++) != '\0') {
10452 if (c == CTLQUOTEMARK)
10453 continue;
10454 if (c == CTLESC)
10455 p++;
Denis Vlasenko68819d12008-12-15 11:26:36 +000010456 else if (SIT((signed char)c, BASESYNTAX) == CCTL)
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010457 return 0;
10458 }
10459 return 1;
10460}
10461
10462static void
10463parsefname(void)
10464{
10465 union node *n = redirnode;
10466
10467 if (readtoken() != TWORD)
10468 raise_error_unexpected_syntax(-1);
10469 if (n->type == NHERE) {
10470 struct heredoc *here = heredoc;
10471 struct heredoc *p;
10472 int i;
10473
10474 if (quoteflag == 0)
10475 n->type = NXHERE;
10476 TRACE(("Here document %d\n", n->type));
10477 if (!noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
Denis Vlasenko559691a2008-10-05 18:39:31 +000010478 raise_error_syntax("illegal eof marker for << redirection");
Denys Vlasenkob6c84342009-08-29 20:23:20 +020010479 rmescapes(wordtext, 0);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010480 here->eofmark = wordtext;
10481 here->next = NULL;
10482 if (heredoclist == NULL)
10483 heredoclist = here;
10484 else {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010485 for (p = heredoclist; p->next; p = p->next)
10486 continue;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010487 p->next = here;
10488 }
10489 } else if (n->type == NTOFD || n->type == NFROMFD) {
10490 fixredir(n, wordtext, 0);
10491 } else {
10492 n->nfile.fname = makename();
10493 }
10494}
Eric Andersencb57d552001-06-28 07:25:16 +000010495
Eric Andersenc470f442003-07-28 09:56:35 +000010496static union node *
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010497simplecmd(void)
10498{
10499 union node *args, **app;
10500 union node *n = NULL;
10501 union node *vars, **vpp;
10502 union node **rpp, *redir;
10503 int savecheckkwd;
Denis Vlasenko80591b02008-03-25 07:49:43 +000010504#if ENABLE_ASH_BASH_COMPAT
10505 smallint double_brackets_flag = 0;
10506#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010507
10508 args = NULL;
10509 app = &args;
10510 vars = NULL;
10511 vpp = &vars;
10512 redir = NULL;
10513 rpp = &redir;
10514
10515 savecheckkwd = CHKALIAS;
10516 for (;;) {
Denis Vlasenko80591b02008-03-25 07:49:43 +000010517 int t;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010518 checkkwd = savecheckkwd;
Denis Vlasenko80591b02008-03-25 07:49:43 +000010519 t = readtoken();
10520 switch (t) {
10521#if ENABLE_ASH_BASH_COMPAT
10522 case TAND: /* "&&" */
10523 case TOR: /* "||" */
10524 if (!double_brackets_flag) {
10525 tokpushback = 1;
10526 goto out;
10527 }
10528 wordtext = (char *) (t == TAND ? "-a" : "-o");
10529#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010530 case TWORD:
Denis Vlasenko597906c2008-02-20 16:38:54 +000010531 n = stzalloc(sizeof(struct narg));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010532 n->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010533 /*n->narg.next = NULL; - stzalloc did it */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010534 n->narg.text = wordtext;
Denis Vlasenko80591b02008-03-25 07:49:43 +000010535#if ENABLE_ASH_BASH_COMPAT
10536 if (strcmp("[[", wordtext) == 0)
10537 double_brackets_flag = 1;
10538 else if (strcmp("]]", wordtext) == 0)
10539 double_brackets_flag = 0;
10540#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010541 n->narg.backquote = backquotelist;
10542 if (savecheckkwd && isassignment(wordtext)) {
10543 *vpp = n;
10544 vpp = &n->narg.next;
10545 } else {
10546 *app = n;
10547 app = &n->narg.next;
10548 savecheckkwd = 0;
10549 }
10550 break;
10551 case TREDIR:
10552 *rpp = n = redirnode;
10553 rpp = &n->nfile.next;
10554 parsefname(); /* read name of redirection file */
10555 break;
10556 case TLP:
10557 if (args && app == &args->narg.next
10558 && !vars && !redir
10559 ) {
10560 struct builtincmd *bcmd;
10561 const char *name;
10562
10563 /* We have a function */
10564 if (readtoken() != TRP)
10565 raise_error_unexpected_syntax(TRP);
10566 name = n->narg.text;
10567 if (!goodname(name)
10568 || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
10569 ) {
Denis Vlasenko559691a2008-10-05 18:39:31 +000010570 raise_error_syntax("bad function name");
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010571 }
10572 n->type = NDEFUN;
10573 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10574 n->narg.next = parse_command();
10575 return n;
10576 }
10577 /* fall through */
10578 default:
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010579 tokpushback = 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010580 goto out;
10581 }
10582 }
10583 out:
10584 *app = NULL;
10585 *vpp = NULL;
10586 *rpp = NULL;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010587 n = stzalloc(sizeof(struct ncmd));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010588 n->type = NCMD;
10589 n->ncmd.args = args;
10590 n->ncmd.assign = vars;
10591 n->ncmd.redirect = redir;
10592 return n;
10593}
10594
10595static union node *
10596parse_command(void)
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010597{
Eric Andersencb57d552001-06-28 07:25:16 +000010598 union node *n1, *n2;
10599 union node *ap, **app;
10600 union node *cp, **cpp;
10601 union node *redir, **rpp;
Eric Andersenc470f442003-07-28 09:56:35 +000010602 union node **rpp2;
Eric Andersencb57d552001-06-28 07:25:16 +000010603 int t;
10604
10605 redir = NULL;
Eric Andersenc470f442003-07-28 09:56:35 +000010606 rpp2 = &redir;
Eric Andersen88cec252001-09-06 17:35:20 +000010607
Eric Andersencb57d552001-06-28 07:25:16 +000010608 switch (readtoken()) {
Eric Andersenc470f442003-07-28 09:56:35 +000010609 default:
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010610 raise_error_unexpected_syntax(-1);
Eric Andersenc470f442003-07-28 09:56:35 +000010611 /* NOTREACHED */
Eric Andersencb57d552001-06-28 07:25:16 +000010612 case TIF:
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010613 n1 = stzalloc(sizeof(struct nif));
Eric Andersencb57d552001-06-28 07:25:16 +000010614 n1->type = NIF;
10615 n1->nif.test = list(0);
10616 if (readtoken() != TTHEN)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010617 raise_error_unexpected_syntax(TTHEN);
Eric Andersencb57d552001-06-28 07:25:16 +000010618 n1->nif.ifpart = list(0);
10619 n2 = n1;
10620 while (readtoken() == TELIF) {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010621 n2->nif.elsepart = stzalloc(sizeof(struct nif));
Eric Andersencb57d552001-06-28 07:25:16 +000010622 n2 = n2->nif.elsepart;
10623 n2->type = NIF;
10624 n2->nif.test = list(0);
10625 if (readtoken() != TTHEN)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010626 raise_error_unexpected_syntax(TTHEN);
Eric Andersencb57d552001-06-28 07:25:16 +000010627 n2->nif.ifpart = list(0);
10628 }
10629 if (lasttoken == TELSE)
10630 n2->nif.elsepart = list(0);
10631 else {
10632 n2->nif.elsepart = NULL;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010633 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010634 }
Eric Andersenc470f442003-07-28 09:56:35 +000010635 t = TFI;
Eric Andersencb57d552001-06-28 07:25:16 +000010636 break;
10637 case TWHILE:
Eric Andersenc470f442003-07-28 09:56:35 +000010638 case TUNTIL: {
Eric Andersencb57d552001-06-28 07:25:16 +000010639 int got;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010640 n1 = stzalloc(sizeof(struct nbinary));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010641 n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
Eric Andersencb57d552001-06-28 07:25:16 +000010642 n1->nbinary.ch1 = list(0);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010643 got = readtoken();
10644 if (got != TDO) {
Denis Vlasenko131ae172007-02-18 13:00:19 +000010645 TRACE(("expecting DO got %s %s\n", tokname(got),
10646 got == TWORD ? wordtext : ""));
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010647 raise_error_unexpected_syntax(TDO);
Eric Andersencb57d552001-06-28 07:25:16 +000010648 }
10649 n1->nbinary.ch2 = list(0);
Eric Andersenc470f442003-07-28 09:56:35 +000010650 t = TDONE;
Eric Andersencb57d552001-06-28 07:25:16 +000010651 break;
10652 }
10653 case TFOR:
Denis Vlasenko2dc240c2008-07-24 06:07:50 +000010654 if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
Denis Vlasenko559691a2008-10-05 18:39:31 +000010655 raise_error_syntax("bad for loop variable");
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010656 n1 = stzalloc(sizeof(struct nfor));
Eric Andersencb57d552001-06-28 07:25:16 +000010657 n1->type = NFOR;
10658 n1->nfor.var = wordtext;
Eric Andersenc470f442003-07-28 09:56:35 +000010659 checkkwd = CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010660 if (readtoken() == TIN) {
10661 app = &ap;
10662 while (readtoken() == TWORD) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010663 n2 = stzalloc(sizeof(struct narg));
Eric Andersencb57d552001-06-28 07:25:16 +000010664 n2->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010665 /*n2->narg.next = NULL; - stzalloc did it */
Eric Andersencb57d552001-06-28 07:25:16 +000010666 n2->narg.text = wordtext;
10667 n2->narg.backquote = backquotelist;
10668 *app = n2;
10669 app = &n2->narg.next;
10670 }
10671 *app = NULL;
10672 n1->nfor.args = ap;
10673 if (lasttoken != TNL && lasttoken != TSEMI)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010674 raise_error_unexpected_syntax(-1);
Eric Andersencb57d552001-06-28 07:25:16 +000010675 } else {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010676 n2 = stzalloc(sizeof(struct narg));
Eric Andersencb57d552001-06-28 07:25:16 +000010677 n2->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010678 /*n2->narg.next = NULL; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000010679 n2->narg.text = (char *)dolatstr;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010680 /*n2->narg.backquote = NULL;*/
Eric Andersencb57d552001-06-28 07:25:16 +000010681 n1->nfor.args = n2;
10682 /*
10683 * Newline or semicolon here is optional (but note
10684 * that the original Bourne shell only allowed NL).
10685 */
10686 if (lasttoken != TNL && lasttoken != TSEMI)
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010687 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010688 }
Eric Andersenc470f442003-07-28 09:56:35 +000010689 checkkwd = CHKNL | CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010690 if (readtoken() != TDO)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010691 raise_error_unexpected_syntax(TDO);
Eric Andersencb57d552001-06-28 07:25:16 +000010692 n1->nfor.body = list(0);
Eric Andersenc470f442003-07-28 09:56:35 +000010693 t = TDONE;
Eric Andersencb57d552001-06-28 07:25:16 +000010694 break;
10695 case TCASE:
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010696 n1 = stzalloc(sizeof(struct ncase));
Eric Andersencb57d552001-06-28 07:25:16 +000010697 n1->type = NCASE;
10698 if (readtoken() != TWORD)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010699 raise_error_unexpected_syntax(TWORD);
Denis Vlasenko597906c2008-02-20 16:38:54 +000010700 n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
Eric Andersencb57d552001-06-28 07:25:16 +000010701 n2->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010702 /*n2->narg.next = NULL; - stzalloc did it */
Eric Andersencb57d552001-06-28 07:25:16 +000010703 n2->narg.text = wordtext;
10704 n2->narg.backquote = backquotelist;
Eric Andersencb57d552001-06-28 07:25:16 +000010705 do {
Eric Andersenc470f442003-07-28 09:56:35 +000010706 checkkwd = CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010707 } while (readtoken() == TNL);
10708 if (lasttoken != TIN)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010709 raise_error_unexpected_syntax(TIN);
Eric Andersencb57d552001-06-28 07:25:16 +000010710 cpp = &n1->ncase.cases;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010711 next_case:
Eric Andersenc470f442003-07-28 09:56:35 +000010712 checkkwd = CHKNL | CHKKWD;
10713 t = readtoken();
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010714 while (t != TESAC) {
Eric Andersencb57d552001-06-28 07:25:16 +000010715 if (lasttoken == TLP)
10716 readtoken();
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010717 *cpp = cp = stzalloc(sizeof(struct nclist));
Eric Andersencb57d552001-06-28 07:25:16 +000010718 cp->type = NCLIST;
10719 app = &cp->nclist.pattern;
10720 for (;;) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010721 *app = ap = stzalloc(sizeof(struct narg));
Eric Andersencb57d552001-06-28 07:25:16 +000010722 ap->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010723 /*ap->narg.next = NULL; - stzalloc did it */
Eric Andersencb57d552001-06-28 07:25:16 +000010724 ap->narg.text = wordtext;
10725 ap->narg.backquote = backquotelist;
Eric Andersenc470f442003-07-28 09:56:35 +000010726 if (readtoken() != TPIPE)
Eric Andersencb57d552001-06-28 07:25:16 +000010727 break;
10728 app = &ap->narg.next;
10729 readtoken();
10730 }
Denis Vlasenko597906c2008-02-20 16:38:54 +000010731 //ap->narg.next = NULL;
Eric Andersencb57d552001-06-28 07:25:16 +000010732 if (lasttoken != TRP)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010733 raise_error_unexpected_syntax(TRP);
Eric Andersenc470f442003-07-28 09:56:35 +000010734 cp->nclist.body = list(2);
Eric Andersencb57d552001-06-28 07:25:16 +000010735
Eric Andersenc470f442003-07-28 09:56:35 +000010736 cpp = &cp->nclist.next;
10737
10738 checkkwd = CHKNL | CHKKWD;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010739 t = readtoken();
10740 if (t != TESAC) {
Eric Andersencb57d552001-06-28 07:25:16 +000010741 if (t != TENDCASE)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010742 raise_error_unexpected_syntax(TENDCASE);
10743 goto next_case;
Eric Andersencb57d552001-06-28 07:25:16 +000010744 }
Eric Andersenc470f442003-07-28 09:56:35 +000010745 }
Eric Andersencb57d552001-06-28 07:25:16 +000010746 *cpp = NULL;
Eric Andersenc470f442003-07-28 09:56:35 +000010747 goto redir;
Eric Andersencb57d552001-06-28 07:25:16 +000010748 case TLP:
Denis Vlasenko597906c2008-02-20 16:38:54 +000010749 n1 = stzalloc(sizeof(struct nredir));
Eric Andersencb57d552001-06-28 07:25:16 +000010750 n1->type = NSUBSHELL;
10751 n1->nredir.n = list(0);
Denis Vlasenko597906c2008-02-20 16:38:54 +000010752 /*n1->nredir.redirect = NULL; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000010753 t = TRP;
Eric Andersencb57d552001-06-28 07:25:16 +000010754 break;
10755 case TBEGIN:
10756 n1 = list(0);
Eric Andersenc470f442003-07-28 09:56:35 +000010757 t = TEND;
Eric Andersencb57d552001-06-28 07:25:16 +000010758 break;
Eric Andersencb57d552001-06-28 07:25:16 +000010759 case TWORD:
Eric Andersenc470f442003-07-28 09:56:35 +000010760 case TREDIR:
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010761 tokpushback = 1;
Eric Andersenc470f442003-07-28 09:56:35 +000010762 return simplecmd();
Eric Andersencb57d552001-06-28 07:25:16 +000010763 }
10764
Eric Andersenc470f442003-07-28 09:56:35 +000010765 if (readtoken() != t)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010766 raise_error_unexpected_syntax(t);
Eric Andersenc470f442003-07-28 09:56:35 +000010767
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010768 redir:
Eric Andersencb57d552001-06-28 07:25:16 +000010769 /* Now check for redirection which may follow command */
Eric Andersenc470f442003-07-28 09:56:35 +000010770 checkkwd = CHKKWD | CHKALIAS;
10771 rpp = rpp2;
Eric Andersencb57d552001-06-28 07:25:16 +000010772 while (readtoken() == TREDIR) {
10773 *rpp = n2 = redirnode;
10774 rpp = &n2->nfile.next;
10775 parsefname();
10776 }
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010777 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010778 *rpp = NULL;
10779 if (redir) {
10780 if (n1->type != NSUBSHELL) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010781 n2 = stzalloc(sizeof(struct nredir));
Eric Andersencb57d552001-06-28 07:25:16 +000010782 n2->type = NREDIR;
10783 n2->nredir.n = n1;
10784 n1 = n2;
10785 }
10786 n1->nredir.redirect = redir;
10787 }
Eric Andersencb57d552001-06-28 07:25:16 +000010788 return n1;
10789}
10790
Denis Vlasenkoef527f52008-06-23 01:52:30 +000010791#if ENABLE_ASH_BASH_COMPAT
10792static int decode_dollar_squote(void)
10793{
10794 static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
10795 int c, cnt;
10796 char *p;
10797 char buf[4];
10798
10799 c = pgetc();
10800 p = strchr(C_escapes, c);
10801 if (p) {
10802 buf[0] = c;
10803 p = buf;
10804 cnt = 3;
10805 if ((unsigned char)(c - '0') <= 7) { /* \ooo */
10806 do {
10807 c = pgetc();
10808 *++p = c;
10809 } while ((unsigned char)(c - '0') <= 7 && --cnt);
10810 pungetc();
10811 } else if (c == 'x') { /* \xHH */
10812 do {
10813 c = pgetc();
10814 *++p = c;
10815 } while (isxdigit(c) && --cnt);
10816 pungetc();
10817 if (cnt == 3) { /* \x but next char is "bad" */
10818 c = 'x';
10819 goto unrecognized;
10820 }
10821 } else { /* simple seq like \\ or \t */
10822 p++;
10823 }
10824 *p = '\0';
10825 p = buf;
10826 c = bb_process_escape_sequence((void*)&p);
10827 } else { /* unrecognized "\z": print both chars unless ' or " */
10828 if (c != '\'' && c != '"') {
10829 unrecognized:
10830 c |= 0x100; /* "please encode \, then me" */
10831 }
10832 }
10833 return c;
10834}
10835#endif
10836
Eric Andersencb57d552001-06-28 07:25:16 +000010837/*
10838 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
10839 * is not NULL, read a here document. In the latter case, eofmark is the
10840 * word which marks the end of the document and striptabs is true if
10841 * leading tabs should be stripped from the document. The argument firstc
10842 * is the first character of the input token or document.
10843 *
10844 * Because C does not have internal subroutines, I have simulated them
10845 * using goto's to implement the subroutine linkage. The following macros
10846 * will run code that appears at the end of readtoken1.
10847 */
Eric Andersen2870d962001-07-02 17:27:21 +000010848#define CHECKEND() {goto checkend; checkend_return:;}
10849#define PARSEREDIR() {goto parseredir; parseredir_return:;}
10850#define PARSESUB() {goto parsesub; parsesub_return:;}
10851#define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
10852#define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
10853#define PARSEARITH() {goto parsearith; parsearith_return:;}
Eric Andersencb57d552001-06-28 07:25:16 +000010854static int
Eric Andersenc470f442003-07-28 09:56:35 +000010855readtoken1(int firstc, int syntax, char *eofmark, int striptabs)
Manuel Novoa III 16815d42001-08-10 19:36:07 +000010856{
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010857 /* NB: syntax parameter fits into smallint */
Eric Andersencb57d552001-06-28 07:25:16 +000010858 int c = firstc;
10859 char *out;
10860 int len;
10861 char line[EOFMARKLEN + 1];
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010862 struct nodelist *bqlist;
10863 smallint quotef;
10864 smallint dblquote;
10865 smallint oldstyle;
10866 smallint prevsyntax; /* syntax before arithmetic */
Denis Vlasenko46a53062007-09-24 18:30:02 +000010867#if ENABLE_ASH_EXPAND_PRMT
10868 smallint pssyntax; /* we are expanding a prompt string */
10869#endif
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010870 int varnest; /* levels of variables expansion */
10871 int arinest; /* levels of arithmetic expansion */
10872 int parenlevel; /* levels of parens in arithmetic */
10873 int dqvarnest; /* levels of variables expansion within double quotes */
10874
Denis Vlasenko5e34ff22009-04-21 11:09:40 +000010875 IF_ASH_BASH_COMPAT(smallint bash_dollar_squote = 0;)
Denis Vlasenkoef527f52008-06-23 01:52:30 +000010876
Eric Andersencb57d552001-06-28 07:25:16 +000010877#if __GNUC__
10878 /* Avoid longjmp clobbering */
10879 (void) &out;
10880 (void) &quotef;
10881 (void) &dblquote;
10882 (void) &varnest;
10883 (void) &arinest;
10884 (void) &parenlevel;
10885 (void) &dqvarnest;
10886 (void) &oldstyle;
10887 (void) &prevsyntax;
10888 (void) &syntax;
10889#endif
Denis Vlasenko41eb3002008-11-28 03:42:31 +000010890 startlinno = g_parsefile->linno;
Eric Andersencb57d552001-06-28 07:25:16 +000010891 bqlist = NULL;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010892 quotef = 0;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010893 oldstyle = 0;
10894 prevsyntax = 0;
Denis Vlasenko46a53062007-09-24 18:30:02 +000010895#if ENABLE_ASH_EXPAND_PRMT
10896 pssyntax = (syntax == PSSYNTAX);
10897 if (pssyntax)
10898 syntax = DQSYNTAX;
10899#endif
10900 dblquote = (syntax == DQSYNTAX);
Eric Andersencb57d552001-06-28 07:25:16 +000010901 varnest = 0;
10902 arinest = 0;
10903 parenlevel = 0;
10904 dqvarnest = 0;
10905
10906 STARTSTACKSTR(out);
Denis Vlasenko176d49d2008-10-06 09:51:47 +000010907 loop:
10908 /* For each line, until end of word */
10909 {
Eric Andersenc470f442003-07-28 09:56:35 +000010910 CHECKEND(); /* set c to PEOF if at end of here document */
10911 for (;;) { /* until end of line or end of word */
10912 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
Denis Vlasenkobf0a2012006-12-26 10:42:51 +000010913 switch (SIT(c, syntax)) {
Eric Andersenc470f442003-07-28 09:56:35 +000010914 case CNL: /* '\n' */
Eric Andersencb57d552001-06-28 07:25:16 +000010915 if (syntax == BASESYNTAX)
Eric Andersenc470f442003-07-28 09:56:35 +000010916 goto endword; /* exit outer loop */
Eric Andersencb57d552001-06-28 07:25:16 +000010917 USTPUTC(c, out);
Denis Vlasenko41eb3002008-11-28 03:42:31 +000010918 g_parsefile->linno++;
Eric Andersencb57d552001-06-28 07:25:16 +000010919 if (doprompt)
10920 setprompt(2);
Eric Andersencb57d552001-06-28 07:25:16 +000010921 c = pgetc();
Eric Andersenc470f442003-07-28 09:56:35 +000010922 goto loop; /* continue outer loop */
Eric Andersencb57d552001-06-28 07:25:16 +000010923 case CWORD:
10924 USTPUTC(c, out);
10925 break;
10926 case CCTL:
Eric Andersenc470f442003-07-28 09:56:35 +000010927 if (eofmark == NULL || dblquote)
Eric Andersencb57d552001-06-28 07:25:16 +000010928 USTPUTC(CTLESC, out);
Denis Vlasenkoef527f52008-06-23 01:52:30 +000010929#if ENABLE_ASH_BASH_COMPAT
10930 if (c == '\\' && bash_dollar_squote) {
10931 c = decode_dollar_squote();
10932 if (c & 0x100) {
10933 USTPUTC('\\', out);
10934 c = (unsigned char)c;
10935 }
10936 }
10937#endif
Eric Andersencb57d552001-06-28 07:25:16 +000010938 USTPUTC(c, out);
10939 break;
Eric Andersenc470f442003-07-28 09:56:35 +000010940 case CBACK: /* backslash */
Eric Andersencb57d552001-06-28 07:25:16 +000010941 c = pgetc2();
10942 if (c == PEOF) {
Eric Andersenc470f442003-07-28 09:56:35 +000010943 USTPUTC(CTLESC, out);
Eric Andersencb57d552001-06-28 07:25:16 +000010944 USTPUTC('\\', out);
10945 pungetc();
10946 } else if (c == '\n') {
10947 if (doprompt)
10948 setprompt(2);
Eric Andersencb57d552001-06-28 07:25:16 +000010949 } else {
Denis Vlasenko46a53062007-09-24 18:30:02 +000010950#if ENABLE_ASH_EXPAND_PRMT
10951 if (c == '$' && pssyntax) {
10952 USTPUTC(CTLESC, out);
10953 USTPUTC('\\', out);
10954 }
10955#endif
Denis Vlasenkoef527f52008-06-23 01:52:30 +000010956 if (dblquote && c != '\\'
10957 && c != '`' && c != '$'
10958 && (c != '"' || eofmark != NULL)
Eric Andersenc470f442003-07-28 09:56:35 +000010959 ) {
10960 USTPUTC(CTLESC, out);
Eric Andersencb57d552001-06-28 07:25:16 +000010961 USTPUTC('\\', out);
Eric Andersenc470f442003-07-28 09:56:35 +000010962 }
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010963 if (SIT(c, SQSYNTAX) == CCTL)
Eric Andersencb57d552001-06-28 07:25:16 +000010964 USTPUTC(CTLESC, out);
Eric Andersencb57d552001-06-28 07:25:16 +000010965 USTPUTC(c, out);
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010966 quotef = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010967 }
10968 break;
10969 case CSQUOTE:
Eric Andersencb57d552001-06-28 07:25:16 +000010970 syntax = SQSYNTAX;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010971 quotemark:
Eric Andersenc470f442003-07-28 09:56:35 +000010972 if (eofmark == NULL) {
10973 USTPUTC(CTLQUOTEMARK, out);
10974 }
Eric Andersencb57d552001-06-28 07:25:16 +000010975 break;
10976 case CDQUOTE:
Eric Andersencb57d552001-06-28 07:25:16 +000010977 syntax = DQSYNTAX;
10978 dblquote = 1;
Eric Andersenc470f442003-07-28 09:56:35 +000010979 goto quotemark;
Eric Andersencb57d552001-06-28 07:25:16 +000010980 case CENDQUOTE:
Denis Vlasenko5e34ff22009-04-21 11:09:40 +000010981 IF_ASH_BASH_COMPAT(bash_dollar_squote = 0;)
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010982 if (eofmark != NULL && arinest == 0
10983 && varnest == 0
10984 ) {
Eric Andersencb57d552001-06-28 07:25:16 +000010985 USTPUTC(c, out);
10986 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000010987 if (dqvarnest == 0) {
Eric Andersencb57d552001-06-28 07:25:16 +000010988 syntax = BASESYNTAX;
10989 dblquote = 0;
10990 }
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010991 quotef = 1;
Eric Andersenc470f442003-07-28 09:56:35 +000010992 goto quotemark;
Eric Andersencb57d552001-06-28 07:25:16 +000010993 }
10994 break;
Eric Andersenc470f442003-07-28 09:56:35 +000010995 case CVAR: /* '$' */
10996 PARSESUB(); /* parse substitution */
Eric Andersencb57d552001-06-28 07:25:16 +000010997 break;
Eric Andersenc470f442003-07-28 09:56:35 +000010998 case CENDVAR: /* '}' */
Eric Andersencb57d552001-06-28 07:25:16 +000010999 if (varnest > 0) {
11000 varnest--;
11001 if (dqvarnest > 0) {
11002 dqvarnest--;
11003 }
11004 USTPUTC(CTLENDVAR, out);
11005 } else {
11006 USTPUTC(c, out);
11007 }
11008 break;
Mike Frysinger98c52642009-04-02 10:02:37 +000011009#if ENABLE_SH_MATH_SUPPORT
Eric Andersenc470f442003-07-28 09:56:35 +000011010 case CLP: /* '(' in arithmetic */
Eric Andersencb57d552001-06-28 07:25:16 +000011011 parenlevel++;
11012 USTPUTC(c, out);
11013 break;
Eric Andersenc470f442003-07-28 09:56:35 +000011014 case CRP: /* ')' in arithmetic */
Eric Andersencb57d552001-06-28 07:25:16 +000011015 if (parenlevel > 0) {
11016 USTPUTC(c, out);
11017 --parenlevel;
11018 } else {
11019 if (pgetc() == ')') {
11020 if (--arinest == 0) {
11021 USTPUTC(CTLENDARI, out);
11022 syntax = prevsyntax;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011023 dblquote = (syntax == DQSYNTAX);
Eric Andersencb57d552001-06-28 07:25:16 +000011024 } else
11025 USTPUTC(')', out);
11026 } else {
11027 /*
11028 * unbalanced parens
11029 * (don't 2nd guess - no error)
11030 */
11031 pungetc();
11032 USTPUTC(')', out);
11033 }
11034 }
11035 break;
11036#endif
Eric Andersenc470f442003-07-28 09:56:35 +000011037 case CBQUOTE: /* '`' */
Eric Andersencb57d552001-06-28 07:25:16 +000011038 PARSEBACKQOLD();
11039 break;
Eric Andersen2870d962001-07-02 17:27:21 +000011040 case CENDFILE:
Eric Andersenc470f442003-07-28 09:56:35 +000011041 goto endword; /* exit outer loop */
Eric Andersencb57d552001-06-28 07:25:16 +000011042 case CIGN:
11043 break;
11044 default:
Denis Vlasenko834dee72008-10-07 09:18:30 +000011045 if (varnest == 0) {
11046#if ENABLE_ASH_BASH_COMPAT
11047 if (c == '&') {
11048 if (pgetc() == '>')
11049 c = 0x100 + '>'; /* flag &> */
11050 pungetc();
11051 }
11052#endif
Eric Andersenc470f442003-07-28 09:56:35 +000011053 goto endword; /* exit outer loop */
Denis Vlasenko834dee72008-10-07 09:18:30 +000011054 }
Denis Vlasenko131ae172007-02-18 13:00:19 +000011055#if ENABLE_ASH_ALIAS
Eric Andersen3102ac42001-07-06 04:26:23 +000011056 if (c != PEOA)
11057#endif
Eric Andersencb57d552001-06-28 07:25:16 +000011058 USTPUTC(c, out);
Eric Andersen3102ac42001-07-06 04:26:23 +000011059
Eric Andersencb57d552001-06-28 07:25:16 +000011060 }
Denis Vlasenko834dee72008-10-07 09:18:30 +000011061 c = pgetc_fast();
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000011062 } /* for (;;) */
Eric Andersencb57d552001-06-28 07:25:16 +000011063 }
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011064 endword:
Mike Frysinger98c52642009-04-02 10:02:37 +000011065#if ENABLE_SH_MATH_SUPPORT
Eric Andersencb57d552001-06-28 07:25:16 +000011066 if (syntax == ARISYNTAX)
Denis Vlasenko559691a2008-10-05 18:39:31 +000011067 raise_error_syntax("missing '))'");
Eric Andersenc470f442003-07-28 09:56:35 +000011068#endif
Denis Vlasenko99eb8502007-02-23 21:09:49 +000011069 if (syntax != BASESYNTAX && !parsebackquote && eofmark == NULL)
Denis Vlasenko559691a2008-10-05 18:39:31 +000011070 raise_error_syntax("unterminated quoted string");
Eric Andersencb57d552001-06-28 07:25:16 +000011071 if (varnest != 0) {
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011072 startlinno = g_parsefile->linno;
Eric Andersenc470f442003-07-28 09:56:35 +000011073 /* { */
Denis Vlasenko559691a2008-10-05 18:39:31 +000011074 raise_error_syntax("missing '}'");
Eric Andersencb57d552001-06-28 07:25:16 +000011075 }
11076 USTPUTC('\0', out);
Eric Andersenc470f442003-07-28 09:56:35 +000011077 len = out - (char *)stackblock();
Eric Andersencb57d552001-06-28 07:25:16 +000011078 out = stackblock();
11079 if (eofmark == NULL) {
Denis Vlasenko5e34ff22009-04-21 11:09:40 +000011080 if ((c == '>' || c == '<' IF_ASH_BASH_COMPAT( || c == 0x100 + '>'))
Denis Vlasenko834dee72008-10-07 09:18:30 +000011081 && quotef == 0
11082 ) {
Denis Vlasenko559691a2008-10-05 18:39:31 +000011083 if (isdigit_str9(out)) {
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000011084 PARSEREDIR(); /* passed as params: out, c */
11085 lasttoken = TREDIR;
11086 return lasttoken;
11087 }
11088 /* else: non-number X seen, interpret it
11089 * as "NNNX>file" = "NNNX >file" */
Eric Andersencb57d552001-06-28 07:25:16 +000011090 }
Denis Vlasenkoef527f52008-06-23 01:52:30 +000011091 pungetc();
Eric Andersencb57d552001-06-28 07:25:16 +000011092 }
11093 quoteflag = quotef;
11094 backquotelist = bqlist;
11095 grabstackblock(len);
11096 wordtext = out;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011097 lasttoken = TWORD;
11098 return lasttoken;
Eric Andersencb57d552001-06-28 07:25:16 +000011099/* end of readtoken routine */
11100
Eric Andersencb57d552001-06-28 07:25:16 +000011101/*
11102 * Check to see whether we are at the end of the here document. When this
11103 * is called, c is set to the first character of the next input line. If
11104 * we are at the end of the here document, this routine sets the c to PEOF.
11105 */
Eric Andersenc470f442003-07-28 09:56:35 +000011106checkend: {
11107 if (eofmark) {
Denis Vlasenko131ae172007-02-18 13:00:19 +000011108#if ENABLE_ASH_ALIAS
Eric Andersenc470f442003-07-28 09:56:35 +000011109 if (c == PEOA) {
11110 c = pgetc2();
11111 }
11112#endif
11113 if (striptabs) {
11114 while (c == '\t') {
Eric Andersencb57d552001-06-28 07:25:16 +000011115 c = pgetc2();
11116 }
Eric Andersenc470f442003-07-28 09:56:35 +000011117 }
11118 if (c == *eofmark) {
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011119 if (pfgets(line, sizeof(line)) != NULL) {
Eric Andersenc470f442003-07-28 09:56:35 +000011120 char *p, *q;
Eric Andersencb57d552001-06-28 07:25:16 +000011121
Eric Andersenc470f442003-07-28 09:56:35 +000011122 p = line;
Denis Vlasenkof7d56652008-03-25 05:51:41 +000011123 for (q = eofmark + 1; *q && *p == *q; p++, q++)
11124 continue;
Eric Andersenc470f442003-07-28 09:56:35 +000011125 if (*p == '\n' && *q == '\0') {
11126 c = PEOF;
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011127 g_parsefile->linno++;
Eric Andersenc470f442003-07-28 09:56:35 +000011128 needprompt = doprompt;
11129 } else {
11130 pushstring(line, NULL);
Eric Andersencb57d552001-06-28 07:25:16 +000011131 }
11132 }
11133 }
11134 }
Eric Andersenc470f442003-07-28 09:56:35 +000011135 goto checkend_return;
11136}
Eric Andersencb57d552001-06-28 07:25:16 +000011137
Eric Andersencb57d552001-06-28 07:25:16 +000011138/*
11139 * Parse a redirection operator. The variable "out" points to a string
11140 * specifying the fd to be redirected. The variable "c" contains the
11141 * first character of the redirection operator.
11142 */
Eric Andersenc470f442003-07-28 09:56:35 +000011143parseredir: {
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000011144 /* out is already checked to be a valid number or "" */
11145 int fd = (*out == '\0' ? -1 : atoi(out));
Eric Andersenc470f442003-07-28 09:56:35 +000011146 union node *np;
Eric Andersencb57d552001-06-28 07:25:16 +000011147
Denis Vlasenko597906c2008-02-20 16:38:54 +000011148 np = stzalloc(sizeof(struct nfile));
Eric Andersenc470f442003-07-28 09:56:35 +000011149 if (c == '>') {
11150 np->nfile.fd = 1;
11151 c = pgetc();
11152 if (c == '>')
11153 np->type = NAPPEND;
11154 else if (c == '|')
11155 np->type = NCLOBBER;
11156 else if (c == '&')
11157 np->type = NTOFD;
Denis Vlasenko559691a2008-10-05 18:39:31 +000011158 /* it also can be NTO2 (>&file), but we can't figure it out yet */
Eric Andersenc470f442003-07-28 09:56:35 +000011159 else {
11160 np->type = NTO;
11161 pungetc();
Eric Andersencb57d552001-06-28 07:25:16 +000011162 }
Denis Vlasenko834dee72008-10-07 09:18:30 +000011163 }
11164#if ENABLE_ASH_BASH_COMPAT
11165 else if (c == 0x100 + '>') { /* this flags &> redirection */
11166 np->nfile.fd = 1;
11167 pgetc(); /* this is '>', no need to check */
11168 np->type = NTO2;
11169 }
11170#endif
11171 else { /* c == '<' */
Denis Vlasenko597906c2008-02-20 16:38:54 +000011172 /*np->nfile.fd = 0; - stzalloc did it */
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011173 c = pgetc();
11174 switch (c) {
Eric Andersenc470f442003-07-28 09:56:35 +000011175 case '<':
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011176 if (sizeof(struct nfile) != sizeof(struct nhere)) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000011177 np = stzalloc(sizeof(struct nhere));
11178 /*np->nfile.fd = 0; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000011179 }
11180 np->type = NHERE;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000011181 heredoc = stzalloc(sizeof(struct heredoc));
Eric Andersenc470f442003-07-28 09:56:35 +000011182 heredoc->here = np;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011183 c = pgetc();
11184 if (c == '-') {
Eric Andersenc470f442003-07-28 09:56:35 +000011185 heredoc->striptabs = 1;
11186 } else {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000011187 /*heredoc->striptabs = 0; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000011188 pungetc();
11189 }
11190 break;
11191
11192 case '&':
11193 np->type = NFROMFD;
11194 break;
11195
11196 case '>':
11197 np->type = NFROMTO;
11198 break;
11199
11200 default:
11201 np->type = NFROM;
11202 pungetc();
11203 break;
11204 }
Eric Andersencb57d552001-06-28 07:25:16 +000011205 }
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000011206 if (fd >= 0)
11207 np->nfile.fd = fd;
Eric Andersenc470f442003-07-28 09:56:35 +000011208 redirnode = np;
11209 goto parseredir_return;
11210}
Eric Andersencb57d552001-06-28 07:25:16 +000011211
Eric Andersencb57d552001-06-28 07:25:16 +000011212/*
11213 * Parse a substitution. At this point, we have read the dollar sign
11214 * and nothing else.
11215 */
Denis Vlasenkocc571512007-02-23 21:10:35 +000011216
11217/* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
11218 * (assuming ascii char codes, as the original implementation did) */
11219#define is_special(c) \
Denis Vlasenkoef527f52008-06-23 01:52:30 +000011220 (((unsigned)(c) - 33 < 32) \
11221 && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
Eric Andersenc470f442003-07-28 09:56:35 +000011222parsesub: {
11223 int subtype;
11224 int typeloc;
11225 int flags;
11226 char *p;
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011227 static const char types[] ALIGN1 = "}-+?=";
Eric Andersencb57d552001-06-28 07:25:16 +000011228
Eric Andersenc470f442003-07-28 09:56:35 +000011229 c = pgetc();
Denis Vlasenkoef527f52008-06-23 01:52:30 +000011230 if (c <= PEOA_OR_PEOF
11231 || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
Eric Andersenc470f442003-07-28 09:56:35 +000011232 ) {
Denis Vlasenkoef527f52008-06-23 01:52:30 +000011233#if ENABLE_ASH_BASH_COMPAT
11234 if (c == '\'')
11235 bash_dollar_squote = 1;
11236 else
11237#endif
11238 USTPUTC('$', out);
Eric Andersenc470f442003-07-28 09:56:35 +000011239 pungetc();
11240 } else if (c == '(') { /* $(command) or $((arith)) */
11241 if (pgetc() == '(') {
Mike Frysinger98c52642009-04-02 10:02:37 +000011242#if ENABLE_SH_MATH_SUPPORT
Eric Andersenc470f442003-07-28 09:56:35 +000011243 PARSEARITH();
11244#else
Mike Frysinger98a6f562008-06-09 09:38:45 +000011245 raise_error_syntax("you disabled math support for $((arith)) syntax");
Eric Andersenc470f442003-07-28 09:56:35 +000011246#endif
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000011247 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000011248 pungetc();
11249 PARSEBACKQNEW();
11250 }
11251 } else {
11252 USTPUTC(CTLVAR, out);
11253 typeloc = out - (char *)stackblock();
11254 USTPUTC(VSNORMAL, out);
11255 subtype = VSNORMAL;
11256 if (c == '{') {
11257 c = pgetc();
11258 if (c == '#') {
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011259 c = pgetc();
11260 if (c == '}')
Eric Andersenc470f442003-07-28 09:56:35 +000011261 c = '#';
11262 else
11263 subtype = VSLENGTH;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011264 } else
Eric Andersenc470f442003-07-28 09:56:35 +000011265 subtype = 0;
11266 }
11267 if (c > PEOA_OR_PEOF && is_name(c)) {
11268 do {
11269 STPUTC(c, out);
Eric Andersencb57d552001-06-28 07:25:16 +000011270 c = pgetc();
Eric Andersenc470f442003-07-28 09:56:35 +000011271 } while (c > PEOA_OR_PEOF && is_in_name(c));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011272 } else if (isdigit(c)) {
Eric Andersenc470f442003-07-28 09:56:35 +000011273 do {
11274 STPUTC(c, out);
11275 c = pgetc();
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011276 } while (isdigit(c));
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011277 } else if (is_special(c)) {
Eric Andersenc470f442003-07-28 09:56:35 +000011278 USTPUTC(c, out);
11279 c = pgetc();
Denis Vlasenko559691a2008-10-05 18:39:31 +000011280 } else {
11281 badsub:
11282 raise_error_syntax("bad substitution");
11283 }
Cristian Ionescu-Idbohrn301f5ec2009-10-05 02:07:23 +020011284 if (c != '}' && subtype == VSLENGTH)
11285 goto badsub;
Eric Andersencb57d552001-06-28 07:25:16 +000011286
Eric Andersenc470f442003-07-28 09:56:35 +000011287 STPUTC('=', out);
11288 flags = 0;
11289 if (subtype == 0) {
11290 switch (c) {
11291 case ':':
Eric Andersenc470f442003-07-28 09:56:35 +000011292 c = pgetc();
Denis Vlasenko92e13c22008-03-25 01:17:40 +000011293#if ENABLE_ASH_BASH_COMPAT
11294 if (c == ':' || c == '$' || isdigit(c)) {
11295 pungetc();
11296 subtype = VSSUBSTR;
11297 break;
11298 }
11299#endif
11300 flags = VSNUL;
Eric Andersenc470f442003-07-28 09:56:35 +000011301 /*FALLTHROUGH*/
11302 default:
11303 p = strchr(types, c);
11304 if (p == NULL)
11305 goto badsub;
11306 subtype = p - types + VSNORMAL;
11307 break;
11308 case '%':
Denis Vlasenko92e13c22008-03-25 01:17:40 +000011309 case '#': {
11310 int cc = c;
11311 subtype = c == '#' ? VSTRIMLEFT : VSTRIMRIGHT;
11312 c = pgetc();
11313 if (c == cc)
11314 subtype++;
11315 else
11316 pungetc();
11317 break;
11318 }
11319#if ENABLE_ASH_BASH_COMPAT
11320 case '/':
11321 subtype = VSREPLACE;
11322 c = pgetc();
11323 if (c == '/')
11324 subtype++; /* VSREPLACEALL */
11325 else
11326 pungetc();
11327 break;
11328#endif
Eric Andersencb57d552001-06-28 07:25:16 +000011329 }
Eric Andersenc470f442003-07-28 09:56:35 +000011330 } else {
11331 pungetc();
11332 }
11333 if (dblquote || arinest)
11334 flags |= VSQUOTE;
11335 *((char *)stackblock() + typeloc) = subtype | flags;
11336 if (subtype != VSNORMAL) {
11337 varnest++;
11338 if (dblquote || arinest) {
11339 dqvarnest++;
Eric Andersencb57d552001-06-28 07:25:16 +000011340 }
11341 }
11342 }
Eric Andersenc470f442003-07-28 09:56:35 +000011343 goto parsesub_return;
11344}
Eric Andersencb57d552001-06-28 07:25:16 +000011345
Eric Andersencb57d552001-06-28 07:25:16 +000011346/*
11347 * Called to parse command substitutions. Newstyle is set if the command
11348 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
11349 * list of commands (passed by reference), and savelen is the number of
11350 * characters on the top of the stack which must be preserved.
11351 */
Eric Andersenc470f442003-07-28 09:56:35 +000011352parsebackq: {
11353 struct nodelist **nlpp;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011354 smallint savepbq;
Eric Andersenc470f442003-07-28 09:56:35 +000011355 union node *n;
11356 char *volatile str;
11357 struct jmploc jmploc;
11358 struct jmploc *volatile savehandler;
11359 size_t savelen;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011360 smallint saveprompt = 0;
11361
Eric Andersencb57d552001-06-28 07:25:16 +000011362#ifdef __GNUC__
Eric Andersenc470f442003-07-28 09:56:35 +000011363 (void) &saveprompt;
Eric Andersencb57d552001-06-28 07:25:16 +000011364#endif
Eric Andersenc470f442003-07-28 09:56:35 +000011365 savepbq = parsebackquote;
11366 if (setjmp(jmploc.loc)) {
Denis Vlasenko60818682007-09-28 22:07:23 +000011367 free(str);
Eric Andersenc470f442003-07-28 09:56:35 +000011368 parsebackquote = 0;
Denis Vlasenko2da584f2007-02-19 22:44:05 +000011369 exception_handler = savehandler;
11370 longjmp(exception_handler->loc, 1);
Eric Andersenc470f442003-07-28 09:56:35 +000011371 }
Denis Vlasenkob012b102007-02-19 22:43:01 +000011372 INT_OFF;
Eric Andersenc470f442003-07-28 09:56:35 +000011373 str = NULL;
11374 savelen = out - (char *)stackblock();
11375 if (savelen > 0) {
11376 str = ckmalloc(savelen);
11377 memcpy(str, stackblock(), savelen);
11378 }
Denis Vlasenko2da584f2007-02-19 22:44:05 +000011379 savehandler = exception_handler;
11380 exception_handler = &jmploc;
Denis Vlasenkob012b102007-02-19 22:43:01 +000011381 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +000011382 if (oldstyle) {
11383 /* We must read until the closing backquote, giving special
11384 treatment to some slashes, and then push the string and
11385 reread it as input, interpreting it normally. */
11386 char *pout;
11387 int pc;
11388 size_t psavelen;
11389 char *pstr;
11390
11391
11392 STARTSTACKSTR(pout);
11393 for (;;) {
11394 if (needprompt) {
11395 setprompt(2);
Eric Andersenc470f442003-07-28 09:56:35 +000011396 }
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011397 pc = pgetc();
11398 switch (pc) {
Eric Andersenc470f442003-07-28 09:56:35 +000011399 case '`':
11400 goto done;
11401
11402 case '\\':
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011403 pc = pgetc();
11404 if (pc == '\n') {
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011405 g_parsefile->linno++;
Eric Andersenc470f442003-07-28 09:56:35 +000011406 if (doprompt)
11407 setprompt(2);
11408 /*
11409 * If eating a newline, avoid putting
11410 * the newline into the new character
11411 * stream (via the STPUTC after the
11412 * switch).
11413 */
11414 continue;
11415 }
11416 if (pc != '\\' && pc != '`' && pc != '$'
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011417 && (!dblquote || pc != '"'))
Eric Andersenc470f442003-07-28 09:56:35 +000011418 STPUTC('\\', pout);
11419 if (pc > PEOA_OR_PEOF) {
11420 break;
11421 }
11422 /* fall through */
11423
11424 case PEOF:
Denis Vlasenko131ae172007-02-18 13:00:19 +000011425#if ENABLE_ASH_ALIAS
Eric Andersenc470f442003-07-28 09:56:35 +000011426 case PEOA:
11427#endif
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011428 startlinno = g_parsefile->linno;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000011429 raise_error_syntax("EOF in backquote substitution");
Eric Andersenc470f442003-07-28 09:56:35 +000011430
11431 case '\n':
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011432 g_parsefile->linno++;
Eric Andersenc470f442003-07-28 09:56:35 +000011433 needprompt = doprompt;
11434 break;
11435
11436 default:
11437 break;
11438 }
11439 STPUTC(pc, pout);
11440 }
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011441 done:
Eric Andersenc470f442003-07-28 09:56:35 +000011442 STPUTC('\0', pout);
11443 psavelen = pout - (char *)stackblock();
11444 if (psavelen > 0) {
11445 pstr = grabstackstr(pout);
11446 setinputstring(pstr);
11447 }
11448 }
11449 nlpp = &bqlist;
11450 while (*nlpp)
11451 nlpp = &(*nlpp)->next;
Denis Vlasenko597906c2008-02-20 16:38:54 +000011452 *nlpp = stzalloc(sizeof(**nlpp));
11453 /* (*nlpp)->next = NULL; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000011454 parsebackquote = oldstyle;
11455
11456 if (oldstyle) {
11457 saveprompt = doprompt;
11458 doprompt = 0;
Eric Andersencb57d552001-06-28 07:25:16 +000011459 }
11460
Eric Andersenc470f442003-07-28 09:56:35 +000011461 n = list(2);
11462
11463 if (oldstyle)
11464 doprompt = saveprompt;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011465 else if (readtoken() != TRP)
11466 raise_error_unexpected_syntax(TRP);
Eric Andersenc470f442003-07-28 09:56:35 +000011467
11468 (*nlpp)->n = n;
11469 if (oldstyle) {
11470 /*
11471 * Start reading from old file again, ignoring any pushed back
11472 * tokens left from the backquote parsing
11473 */
11474 popfile();
11475 tokpushback = 0;
11476 }
11477 while (stackblocksize() <= savelen)
11478 growstackblock();
11479 STARTSTACKSTR(out);
11480 if (str) {
11481 memcpy(out, str, savelen);
11482 STADJUST(savelen, out);
Denis Vlasenkob012b102007-02-19 22:43:01 +000011483 INT_OFF;
11484 free(str);
Eric Andersenc470f442003-07-28 09:56:35 +000011485 str = NULL;
Denis Vlasenkob012b102007-02-19 22:43:01 +000011486 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +000011487 }
11488 parsebackquote = savepbq;
Denis Vlasenko2da584f2007-02-19 22:44:05 +000011489 exception_handler = savehandler;
Eric Andersenc470f442003-07-28 09:56:35 +000011490 if (arinest || dblquote)
11491 USTPUTC(CTLBACKQ | CTLQUOTE, out);
11492 else
11493 USTPUTC(CTLBACKQ, out);
11494 if (oldstyle)
11495 goto parsebackq_oldreturn;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000011496 goto parsebackq_newreturn;
Eric Andersenc470f442003-07-28 09:56:35 +000011497}
11498
Mike Frysinger98c52642009-04-02 10:02:37 +000011499#if ENABLE_SH_MATH_SUPPORT
Eric Andersencb57d552001-06-28 07:25:16 +000011500/*
11501 * Parse an arithmetic expansion (indicate start of one and set state)
11502 */
Eric Andersenc470f442003-07-28 09:56:35 +000011503parsearith: {
Eric Andersenc470f442003-07-28 09:56:35 +000011504 if (++arinest == 1) {
11505 prevsyntax = syntax;
11506 syntax = ARISYNTAX;
11507 USTPUTC(CTLARI, out);
11508 if (dblquote)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000011509 USTPUTC('"', out);
Eric Andersenc470f442003-07-28 09:56:35 +000011510 else
Denis Vlasenkoa624c112007-02-19 22:45:43 +000011511 USTPUTC(' ', out);
Eric Andersenc470f442003-07-28 09:56:35 +000011512 } else {
11513 /*
11514 * we collapse embedded arithmetic expansion to
11515 * parenthesis, which should be equivalent
11516 */
11517 USTPUTC('(', out);
Eric Andersencb57d552001-06-28 07:25:16 +000011518 }
Eric Andersenc470f442003-07-28 09:56:35 +000011519 goto parsearith_return;
11520}
11521#endif
Eric Andersencb57d552001-06-28 07:25:16 +000011522
Eric Andersenc470f442003-07-28 09:56:35 +000011523} /* end of readtoken */
11524
Eric Andersencb57d552001-06-28 07:25:16 +000011525/*
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011526 * Read the next input token.
11527 * If the token is a word, we set backquotelist to the list of cmds in
11528 * backquotes. We set quoteflag to true if any part of the word was
11529 * quoted.
11530 * If the token is TREDIR, then we set redirnode to a structure containing
11531 * the redirection.
11532 * In all cases, the variable startlinno is set to the number of the line
11533 * on which the token starts.
11534 *
11535 * [Change comment: here documents and internal procedures]
11536 * [Readtoken shouldn't have any arguments. Perhaps we should make the
11537 * word parsing code into a separate routine. In this case, readtoken
11538 * doesn't need to have any internal procedures, but parseword does.
11539 * We could also make parseoperator in essence the main routine, and
11540 * have parseword (readtoken1?) handle both words and redirection.]
Eric Andersencb57d552001-06-28 07:25:16 +000011541 */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011542#define NEW_xxreadtoken
11543#ifdef NEW_xxreadtoken
11544/* singles must be first! */
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011545static const char xxreadtoken_chars[7] ALIGN1 = {
Denis Vlasenko834dee72008-10-07 09:18:30 +000011546 '\n', '(', ')', /* singles */
11547 '&', '|', ';', /* doubles */
11548 0
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011549};
Eric Andersencb57d552001-06-28 07:25:16 +000011550
Denis Vlasenko834dee72008-10-07 09:18:30 +000011551#define xxreadtoken_singles 3
11552#define xxreadtoken_doubles 3
11553
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011554static const char xxreadtoken_tokens[] ALIGN1 = {
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011555 TNL, TLP, TRP, /* only single occurrence allowed */
11556 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
11557 TEOF, /* corresponds to trailing nul */
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011558 TAND, TOR, TENDCASE /* if double occurrence */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011559};
11560
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011561static int
11562xxreadtoken(void)
11563{
11564 int c;
11565
11566 if (tokpushback) {
11567 tokpushback = 0;
11568 return lasttoken;
Eric Andersencb57d552001-06-28 07:25:16 +000011569 }
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011570 if (needprompt) {
11571 setprompt(2);
11572 }
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011573 startlinno = g_parsefile->linno;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011574 for (;;) { /* until token or start of word found */
Denis Vlasenko834dee72008-10-07 09:18:30 +000011575 c = pgetc_fast();
Denis Vlasenko5e34ff22009-04-21 11:09:40 +000011576 if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011577 continue;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011578
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011579 if (c == '#') {
11580 while ((c = pgetc()) != '\n' && c != PEOF)
11581 continue;
11582 pungetc();
11583 } else if (c == '\\') {
11584 if (pgetc() != '\n') {
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011585 pungetc();
Denis Vlasenko834dee72008-10-07 09:18:30 +000011586 break; /* return readtoken1(...) */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011587 }
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011588 startlinno = ++g_parsefile->linno;
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011589 if (doprompt)
11590 setprompt(2);
11591 } else {
11592 const char *p;
11593
11594 p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
11595 if (c != PEOF) {
11596 if (c == '\n') {
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011597 g_parsefile->linno++;
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011598 needprompt = doprompt;
11599 }
11600
11601 p = strchr(xxreadtoken_chars, c);
Denis Vlasenko834dee72008-10-07 09:18:30 +000011602 if (p == NULL)
11603 break; /* return readtoken1(...) */
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011604
Denis Vlasenko834dee72008-10-07 09:18:30 +000011605 if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
11606 int cc = pgetc();
11607 if (cc == c) { /* double occurrence? */
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011608 p += xxreadtoken_doubles + 1;
11609 } else {
11610 pungetc();
Denis Vlasenko834dee72008-10-07 09:18:30 +000011611#if ENABLE_ASH_BASH_COMPAT
11612 if (c == '&' && cc == '>') /* &> */
11613 break; /* return readtoken1(...) */
11614#endif
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011615 }
11616 }
11617 }
11618 lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
11619 return lasttoken;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011620 }
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011621 } /* for (;;) */
Denis Vlasenko834dee72008-10-07 09:18:30 +000011622
11623 return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011624}
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011625#else /* old xxreadtoken */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011626#define RETURN(token) return lasttoken = token
11627static int
11628xxreadtoken(void)
11629{
11630 int c;
11631
11632 if (tokpushback) {
11633 tokpushback = 0;
11634 return lasttoken;
11635 }
11636 if (needprompt) {
11637 setprompt(2);
11638 }
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011639 startlinno = g_parsefile->linno;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011640 for (;;) { /* until token or start of word found */
Denis Vlasenko834dee72008-10-07 09:18:30 +000011641 c = pgetc_fast();
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011642 switch (c) {
11643 case ' ': case '\t':
11644#if ENABLE_ASH_ALIAS
11645 case PEOA:
11646#endif
11647 continue;
11648 case '#':
Denis Vlasenkof7d56652008-03-25 05:51:41 +000011649 while ((c = pgetc()) != '\n' && c != PEOF)
11650 continue;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011651 pungetc();
11652 continue;
11653 case '\\':
11654 if (pgetc() == '\n') {
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011655 startlinno = ++g_parsefile->linno;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011656 if (doprompt)
11657 setprompt(2);
11658 continue;
11659 }
11660 pungetc();
11661 goto breakloop;
11662 case '\n':
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011663 g_parsefile->linno++;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011664 needprompt = doprompt;
11665 RETURN(TNL);
11666 case PEOF:
11667 RETURN(TEOF);
11668 case '&':
11669 if (pgetc() == '&')
11670 RETURN(TAND);
11671 pungetc();
11672 RETURN(TBACKGND);
11673 case '|':
11674 if (pgetc() == '|')
11675 RETURN(TOR);
11676 pungetc();
11677 RETURN(TPIPE);
11678 case ';':
11679 if (pgetc() == ';')
11680 RETURN(TENDCASE);
11681 pungetc();
11682 RETURN(TSEMI);
11683 case '(':
11684 RETURN(TLP);
11685 case ')':
11686 RETURN(TRP);
11687 default:
11688 goto breakloop;
11689 }
11690 }
11691 breakloop:
11692 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
11693#undef RETURN
11694}
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011695#endif /* old xxreadtoken */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011696
11697static int
11698readtoken(void)
11699{
11700 int t;
11701#if DEBUG
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011702 smallint alreadyseen = tokpushback;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011703#endif
11704
11705#if ENABLE_ASH_ALIAS
11706 top:
11707#endif
11708
11709 t = xxreadtoken();
11710
11711 /*
11712 * eat newlines
11713 */
11714 if (checkkwd & CHKNL) {
11715 while (t == TNL) {
11716 parseheredoc();
11717 t = xxreadtoken();
11718 }
11719 }
11720
11721 if (t != TWORD || quoteflag) {
11722 goto out;
11723 }
11724
11725 /*
11726 * check for keywords
11727 */
11728 if (checkkwd & CHKKWD) {
11729 const char *const *pp;
11730
11731 pp = findkwd(wordtext);
11732 if (pp) {
11733 lasttoken = t = pp - tokname_array;
11734 TRACE(("keyword %s recognized\n", tokname(t)));
11735 goto out;
11736 }
11737 }
11738
11739 if (checkkwd & CHKALIAS) {
11740#if ENABLE_ASH_ALIAS
11741 struct alias *ap;
11742 ap = lookupalias(wordtext, 1);
11743 if (ap != NULL) {
11744 if (*ap->val) {
11745 pushstring(ap->val, ap);
11746 }
11747 goto top;
11748 }
11749#endif
11750 }
11751 out:
11752 checkkwd = 0;
11753#if DEBUG
11754 if (!alreadyseen)
11755 TRACE(("token %s %s\n", tokname(t), t == TWORD ? wordtext : ""));
11756 else
11757 TRACE(("reread token %s %s\n", tokname(t), t == TWORD ? wordtext : ""));
11758#endif
11759 return t;
Eric Andersencb57d552001-06-28 07:25:16 +000011760}
11761
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011762static char
11763peektoken(void)
11764{
11765 int t;
11766
11767 t = readtoken();
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011768 tokpushback = 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011769 return tokname_array[t][0];
11770}
Eric Andersencb57d552001-06-28 07:25:16 +000011771
11772/*
Denys Vlasenko86e83ec2009-07-23 22:07:07 +020011773 * Read and parse a command. Returns NODE_EOF on end of file.
11774 * (NULL is a valid parse tree indicating a blank line.)
Eric Andersencb57d552001-06-28 07:25:16 +000011775 */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011776static union node *
11777parsecmd(int interact)
Eric Andersen90898442003-08-06 11:20:52 +000011778{
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011779 int t;
Eric Andersencb57d552001-06-28 07:25:16 +000011780
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011781 tokpushback = 0;
11782 doprompt = interact;
11783 if (doprompt)
11784 setprompt(doprompt);
11785 needprompt = 0;
11786 t = readtoken();
11787 if (t == TEOF)
Denys Vlasenko86e83ec2009-07-23 22:07:07 +020011788 return NODE_EOF;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011789 if (t == TNL)
11790 return NULL;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011791 tokpushback = 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011792 return list(1);
11793}
11794
11795/*
11796 * Input any here documents.
11797 */
11798static void
11799parseheredoc(void)
11800{
11801 struct heredoc *here;
11802 union node *n;
11803
11804 here = heredoclist;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000011805 heredoclist = NULL;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011806
11807 while (here) {
11808 if (needprompt) {
11809 setprompt(2);
11810 }
11811 readtoken1(pgetc(), here->here->type == NHERE? SQSYNTAX : DQSYNTAX,
11812 here->eofmark, here->striptabs);
Denis Vlasenko597906c2008-02-20 16:38:54 +000011813 n = stzalloc(sizeof(struct narg));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011814 n->narg.type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000011815 /*n->narg.next = NULL; - stzalloc did it */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011816 n->narg.text = wordtext;
11817 n->narg.backquote = backquotelist;
11818 here->here->nhere.doc = n;
11819 here = here->next;
Eric Andersencb57d552001-06-28 07:25:16 +000011820 }
Eric Andersencb57d552001-06-28 07:25:16 +000011821}
11822
11823
11824/*
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +000011825 * called by editline -- any expansions to the prompt should be added here.
Eric Andersencb57d552001-06-28 07:25:16 +000011826 */
Denis Vlasenko131ae172007-02-18 13:00:19 +000011827#if ENABLE_ASH_EXPAND_PRMT
"Vladimir N. Oleynik"bef14d72005-09-05 13:25:11 +000011828static const char *
11829expandstr(const char *ps)
11830{
11831 union node n;
11832
Denis Vlasenko5c2b8142009-03-19 01:59:59 +000011833 /* XXX Fix (char *) cast. It _is_ a bug. ps is variable's value,
11834 * and token processing _can_ alter it (delete NULs etc). */
"Vladimir N. Oleynik"bef14d72005-09-05 13:25:11 +000011835 setinputstring((char *)ps);
Denis Vlasenko46a53062007-09-24 18:30:02 +000011836 readtoken1(pgetc(), PSSYNTAX, nullstr, 0);
"Vladimir N. Oleynik"bef14d72005-09-05 13:25:11 +000011837 popfile();
11838
11839 n.narg.type = NARG;
11840 n.narg.next = NULL;
11841 n.narg.text = wordtext;
11842 n.narg.backquote = backquotelist;
11843
11844 expandarg(&n, NULL, 0);
11845 return stackblock();
11846}
11847#endif
11848
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011849/*
11850 * Execute a command or commands contained in a string.
11851 */
11852static int
11853evalstring(char *s, int mask)
Eric Andersenc470f442003-07-28 09:56:35 +000011854{
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011855 union node *n;
11856 struct stackmark smark;
11857 int skip;
11858
11859 setinputstring(s);
11860 setstackmark(&smark);
11861
11862 skip = 0;
Denys Vlasenko86e83ec2009-07-23 22:07:07 +020011863 while ((n = parsecmd(0)) != NODE_EOF) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011864 evaltree(n, 0);
11865 popstackmark(&smark);
11866 skip = evalskip;
11867 if (skip)
11868 break;
11869 }
11870 popfile();
11871
11872 skip &= mask;
11873 evalskip = skip;
11874 return skip;
Eric Andersenc470f442003-07-28 09:56:35 +000011875}
11876
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011877/*
11878 * The eval command.
11879 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011880static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000011881evalcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011882{
11883 char *p;
11884 char *concat;
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011885
Denis Vlasenko68404f12008-03-17 09:00:54 +000011886 if (argv[1]) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011887 p = argv[1];
Denis Vlasenko68404f12008-03-17 09:00:54 +000011888 argv += 2;
11889 if (argv[0]) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011890 STARTSTACKSTR(concat);
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011891 for (;;) {
11892 concat = stack_putstr(p, concat);
Denis Vlasenko68404f12008-03-17 09:00:54 +000011893 p = *argv++;
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011894 if (p == NULL)
11895 break;
11896 STPUTC(' ', concat);
11897 }
11898 STPUTC('\0', concat);
11899 p = grabstackstr(concat);
11900 }
11901 evalstring(p, ~SKIPEVAL);
11902
11903 }
11904 return exitstatus;
11905}
11906
11907/*
11908 * Read and execute commands. "Top" is nonzero for the top level command
11909 * loop; it turns on prompting if the shell is interactive.
11910 */
11911static int
11912cmdloop(int top)
11913{
11914 union node *n;
11915 struct stackmark smark;
11916 int inter;
11917 int numeof = 0;
11918
11919 TRACE(("cmdloop(%d) called\n", top));
11920 for (;;) {
11921 int skip;
11922
11923 setstackmark(&smark);
11924#if JOBS
Denis Vlasenkob07a4962008-06-22 13:16:23 +000011925 if (doing_jobctl)
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011926 showjobs(stderr, SHOW_CHANGED);
11927#endif
11928 inter = 0;
11929 if (iflag && top) {
11930 inter++;
11931#if ENABLE_ASH_MAIL
11932 chkmail();
11933#endif
11934 }
11935 n = parsecmd(inter);
Denys Vlasenko7cee00e2009-07-24 01:08:03 +020011936#if DEBUG
11937 if (DEBUG > 2 && debug && (n != NODE_EOF))
Denys Vlasenko883cea42009-07-11 15:31:59 +020011938 showtree(n);
Denis Vlasenko135cecb2009-04-12 00:00:57 +000011939#endif
Denys Vlasenko86e83ec2009-07-23 22:07:07 +020011940 if (n == NODE_EOF) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011941 if (!top || numeof >= 50)
11942 break;
11943 if (!stoppedjobs()) {
11944 if (!Iflag)
11945 break;
11946 out2str("\nUse \"exit\" to leave shell.\n");
11947 }
11948 numeof++;
11949 } else if (nflag == 0) {
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +000011950 /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
11951 job_warning >>= 1;
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011952 numeof = 0;
11953 evaltree(n, 0);
11954 }
11955 popstackmark(&smark);
11956 skip = evalskip;
11957
11958 if (skip) {
11959 evalskip = 0;
11960 return skip & SKIPEVAL;
11961 }
11962 }
11963 return 0;
11964}
11965
Denis Vlasenko0dec6de2007-02-23 21:10:47 +000011966/*
11967 * Take commands from a file. To be compatible we should do a path
11968 * search for the file, which is necessary to find sub-commands.
11969 */
11970static char *
11971find_dot_file(char *name)
11972{
11973 char *fullname;
11974 const char *path = pathval();
11975 struct stat statb;
11976
11977 /* don't try this for absolute or relative paths */
11978 if (strchr(name, '/'))
11979 return name;
11980
Denis Vlasenko8ad78e12009-02-15 12:40:30 +000011981 /* IIRC standards do not say whether . is to be searched.
11982 * And it is even smaller this way, making it unconditional for now:
11983 */
11984 if (1) { /* ENABLE_ASH_BASH_COMPAT */
11985 fullname = name;
11986 goto try_cur_dir;
11987 }
11988
Denys Vlasenko82a6fb32009-06-14 19:42:12 +020011989 while ((fullname = path_advance(&path, name)) != NULL) {
Denis Vlasenko8ad78e12009-02-15 12:40:30 +000011990 try_cur_dir:
Denis Vlasenko0dec6de2007-02-23 21:10:47 +000011991 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
11992 /*
11993 * Don't bother freeing here, since it will
11994 * be freed by the caller.
11995 */
11996 return fullname;
11997 }
Denys Vlasenko82a6fb32009-06-14 19:42:12 +020011998 if (fullname != name)
11999 stunalloc(fullname);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +000012000 }
12001
12002 /* not found in the PATH */
12003 ash_msg_and_raise_error("%s: not found", name);
12004 /* NOTREACHED */
12005}
12006
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012007static int FAST_FUNC
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012008dotcmd(int argc, char **argv)
12009{
12010 struct strlist *sp;
12011 volatile struct shparam saveparam;
12012 int status = 0;
12013
12014 for (sp = cmdenviron; sp; sp = sp->next)
Denis Vlasenko4222ae42007-02-25 02:37:49 +000012015 setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012016
Denis Vlasenko68404f12008-03-17 09:00:54 +000012017 if (argv[1]) { /* That's what SVR2 does */
12018 char *fullname = find_dot_file(argv[1]);
12019 argv += 2;
12020 argc -= 2;
12021 if (argc) { /* argc > 0, argv[0] != NULL */
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012022 saveparam = shellparam;
Denis Vlasenko01631112007-12-16 17:20:38 +000012023 shellparam.malloced = 0;
Denis Vlasenko68404f12008-03-17 09:00:54 +000012024 shellparam.nparam = argc;
12025 shellparam.p = argv;
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012026 };
12027
12028 setinputfile(fullname, INPUT_PUSH_FILE);
12029 commandname = fullname;
12030 cmdloop(0);
12031 popfile();
12032
Denis Vlasenko68404f12008-03-17 09:00:54 +000012033 if (argc) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012034 freeparam(&shellparam);
12035 shellparam = saveparam;
12036 };
12037 status = exitstatus;
12038 }
12039 return status;
12040}
12041
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012042static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012043exitcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012044{
12045 if (stoppedjobs())
12046 return 0;
Denis Vlasenko68404f12008-03-17 09:00:54 +000012047 if (argv[1])
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012048 exitstatus = number(argv[1]);
12049 raise_exception(EXEXIT);
12050 /* NOTREACHED */
12051}
12052
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012053/*
12054 * Read a file containing shell functions.
12055 */
12056static void
12057readcmdfile(char *name)
12058{
12059 setinputfile(name, INPUT_PUSH_FILE);
12060 cmdloop(0);
12061 popfile();
12062}
12063
12064
Denis Vlasenkocc571512007-02-23 21:10:35 +000012065/* ============ find_command inplementation */
12066
12067/*
12068 * Resolve a command name. If you change this routine, you may have to
12069 * change the shellexec routine as well.
12070 */
12071static void
12072find_command(char *name, struct cmdentry *entry, int act, const char *path)
12073{
12074 struct tblentry *cmdp;
12075 int idx;
12076 int prev;
12077 char *fullname;
12078 struct stat statb;
12079 int e;
12080 int updatetbl;
12081 struct builtincmd *bcmd;
12082
12083 /* If name contains a slash, don't use PATH or hash table */
12084 if (strchr(name, '/') != NULL) {
12085 entry->u.index = -1;
12086 if (act & DO_ABS) {
12087 while (stat(name, &statb) < 0) {
12088#ifdef SYSV
12089 if (errno == EINTR)
12090 continue;
12091#endif
12092 entry->cmdtype = CMDUNKNOWN;
12093 return;
12094 }
12095 }
12096 entry->cmdtype = CMDNORMAL;
12097 return;
12098 }
12099
Denis Vlasenkof20de5b2007-04-29 23:42:54 +000012100/* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
Denis Vlasenkocc571512007-02-23 21:10:35 +000012101
12102 updatetbl = (path == pathval());
12103 if (!updatetbl) {
12104 act |= DO_ALTPATH;
12105 if (strstr(path, "%builtin") != NULL)
12106 act |= DO_ALTBLTIN;
12107 }
12108
12109 /* If name is in the table, check answer will be ok */
12110 cmdp = cmdlookup(name, 0);
12111 if (cmdp != NULL) {
12112 int bit;
12113
12114 switch (cmdp->cmdtype) {
12115 default:
12116#if DEBUG
12117 abort();
12118#endif
12119 case CMDNORMAL:
12120 bit = DO_ALTPATH;
12121 break;
12122 case CMDFUNCTION:
12123 bit = DO_NOFUNC;
12124 break;
12125 case CMDBUILTIN:
12126 bit = DO_ALTBLTIN;
12127 break;
12128 }
12129 if (act & bit) {
12130 updatetbl = 0;
12131 cmdp = NULL;
12132 } else if (cmdp->rehash == 0)
12133 /* if not invalidated by cd, we're done */
12134 goto success;
12135 }
12136
12137 /* If %builtin not in path, check for builtin next */
12138 bcmd = find_builtin(name);
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +000012139 if (bcmd) {
12140 if (IS_BUILTIN_REGULAR(bcmd))
12141 goto builtin_success;
12142 if (act & DO_ALTPATH) {
12143 if (!(act & DO_ALTBLTIN))
12144 goto builtin_success;
12145 } else if (builtinloc <= 0) {
12146 goto builtin_success;
Denis Vlasenko8e858e22007-03-07 09:35:43 +000012147 }
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +000012148 }
Denis Vlasenkocc571512007-02-23 21:10:35 +000012149
Denis Vlasenkof20de5b2007-04-29 23:42:54 +000012150#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko7465dbc2008-04-13 02:25:53 +000012151 {
12152 int applet_no = find_applet_by_name(name);
12153 if (applet_no >= 0) {
12154 entry->cmdtype = CMDNORMAL;
12155 entry->u.index = -2 - applet_no;
12156 return;
12157 }
Denis Vlasenkof20de5b2007-04-29 23:42:54 +000012158 }
12159#endif
12160
Denis Vlasenkocc571512007-02-23 21:10:35 +000012161 /* We have to search path. */
12162 prev = -1; /* where to start */
12163 if (cmdp && cmdp->rehash) { /* doing a rehash */
12164 if (cmdp->cmdtype == CMDBUILTIN)
12165 prev = builtinloc;
12166 else
12167 prev = cmdp->param.index;
12168 }
12169
12170 e = ENOENT;
12171 idx = -1;
12172 loop:
Denys Vlasenko82a6fb32009-06-14 19:42:12 +020012173 while ((fullname = path_advance(&path, name)) != NULL) {
Denis Vlasenkocc571512007-02-23 21:10:35 +000012174 stunalloc(fullname);
Denis Vlasenkodee82b62007-07-29 14:05:27 +000012175 /* NB: code below will still use fullname
12176 * despite it being "unallocated" */
Denis Vlasenkocc571512007-02-23 21:10:35 +000012177 idx++;
12178 if (pathopt) {
12179 if (prefix(pathopt, "builtin")) {
12180 if (bcmd)
12181 goto builtin_success;
12182 continue;
Denis Vlasenko4a9ca132008-04-12 20:07:08 +000012183 }
12184 if ((act & DO_NOFUNC)
12185 || !prefix(pathopt, "func")
12186 ) { /* ignore unimplemented options */
Denis Vlasenkocc571512007-02-23 21:10:35 +000012187 continue;
12188 }
12189 }
12190 /* if rehash, don't redo absolute path names */
12191 if (fullname[0] == '/' && idx <= prev) {
12192 if (idx < prev)
12193 continue;
12194 TRACE(("searchexec \"%s\": no change\n", name));
12195 goto success;
12196 }
12197 while (stat(fullname, &statb) < 0) {
12198#ifdef SYSV
12199 if (errno == EINTR)
12200 continue;
12201#endif
12202 if (errno != ENOENT && errno != ENOTDIR)
12203 e = errno;
12204 goto loop;
12205 }
12206 e = EACCES; /* if we fail, this will be the error */
12207 if (!S_ISREG(statb.st_mode))
12208 continue;
12209 if (pathopt) { /* this is a %func directory */
12210 stalloc(strlen(fullname) + 1);
Denis Vlasenkodee82b62007-07-29 14:05:27 +000012211 /* NB: stalloc will return space pointed by fullname
12212 * (because we don't have any intervening allocations
12213 * between stunalloc above and this stalloc) */
Denis Vlasenkocc571512007-02-23 21:10:35 +000012214 readcmdfile(fullname);
12215 cmdp = cmdlookup(name, 0);
12216 if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
12217 ash_msg_and_raise_error("%s not defined in %s", name, fullname);
12218 stunalloc(fullname);
12219 goto success;
12220 }
12221 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
12222 if (!updatetbl) {
12223 entry->cmdtype = CMDNORMAL;
12224 entry->u.index = idx;
12225 return;
12226 }
12227 INT_OFF;
12228 cmdp = cmdlookup(name, 1);
12229 cmdp->cmdtype = CMDNORMAL;
12230 cmdp->param.index = idx;
12231 INT_ON;
12232 goto success;
12233 }
12234
12235 /* We failed. If there was an entry for this command, delete it */
12236 if (cmdp && updatetbl)
12237 delete_cmd_entry();
12238 if (act & DO_ERR)
12239 ash_msg("%s: %s", name, errmsg(e, "not found"));
12240 entry->cmdtype = CMDUNKNOWN;
12241 return;
12242
12243 builtin_success:
12244 if (!updatetbl) {
12245 entry->cmdtype = CMDBUILTIN;
12246 entry->u.cmd = bcmd;
12247 return;
12248 }
12249 INT_OFF;
12250 cmdp = cmdlookup(name, 1);
12251 cmdp->cmdtype = CMDBUILTIN;
12252 cmdp->param.cmd = bcmd;
12253 INT_ON;
12254 success:
12255 cmdp->rehash = 0;
12256 entry->cmdtype = cmdp->cmdtype;
12257 entry->u = cmdp->param;
12258}
12259
12260
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012261/* ============ trap.c */
Eric Andersenc470f442003-07-28 09:56:35 +000012262
Eric Andersencb57d552001-06-28 07:25:16 +000012263/*
Eric Andersencb57d552001-06-28 07:25:16 +000012264 * The trap builtin.
12265 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012266static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012267trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersencb57d552001-06-28 07:25:16 +000012268{
12269 char *action;
12270 char **ap;
12271 int signo;
12272
Eric Andersenc470f442003-07-28 09:56:35 +000012273 nextopt(nullstr);
12274 ap = argptr;
12275 if (!*ap) {
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012276 for (signo = 0; signo < NSIG; signo++) {
Denys Vlasenko21d87d42009-09-25 00:06:51 +020012277 char *tr = trap_ptr[signo];
12278 if (tr) {
Denys Vlasenkoe74aaf92009-09-27 02:05:45 +020012279 /* note: bash adds "SIG", but only if invoked
12280 * as "bash". If called as "sh", or if set -o posix,
12281 * then it prints short signal names.
12282 * We are printing short names: */
12283 out1fmt("trap -- %s %s\n",
Denys Vlasenko21d87d42009-09-25 00:06:51 +020012284 single_quote(tr),
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +000012285 get_signame(signo));
Denys Vlasenko726e1a02009-09-25 02:58:20 +020012286 /* trap_ptr != trap only if we are in special-cased `trap` code.
12287 * In this case, we will exit very soon, no need to free(). */
Denys Vlasenkoe74aaf92009-09-27 02:05:45 +020012288 /* if (trap_ptr != trap && tp[0]) */
Denys Vlasenko726e1a02009-09-25 02:58:20 +020012289 /* free(tr); */
Eric Andersencb57d552001-06-28 07:25:16 +000012290 }
12291 }
Denys Vlasenko726e1a02009-09-25 02:58:20 +020012292 /*
Denys Vlasenko21d87d42009-09-25 00:06:51 +020012293 if (trap_ptr != trap) {
12294 free(trap_ptr);
12295 trap_ptr = trap;
12296 }
Denys Vlasenko726e1a02009-09-25 02:58:20 +020012297 */
Eric Andersencb57d552001-06-28 07:25:16 +000012298 return 0;
12299 }
Denys Vlasenko21d87d42009-09-25 00:06:51 +020012300
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +000012301 action = NULL;
12302 if (ap[1])
Eric Andersencb57d552001-06-28 07:25:16 +000012303 action = *ap++;
12304 while (*ap) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +000012305 signo = get_signum(*ap);
12306 if (signo < 0)
Denis Vlasenkob012b102007-02-19 22:43:01 +000012307 ash_msg_and_raise_error("%s: bad trap", *ap);
12308 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +000012309 if (action) {
Denis Vlasenko9f739442006-12-16 23:49:13 +000012310 if (LONE_DASH(action))
Eric Andersencb57d552001-06-28 07:25:16 +000012311 action = NULL;
12312 else
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012313 action = ckstrdup(action);
Eric Andersencb57d552001-06-28 07:25:16 +000012314 }
Denis Vlasenko60818682007-09-28 22:07:23 +000012315 free(trap[signo]);
Eric Andersencb57d552001-06-28 07:25:16 +000012316 trap[signo] = action;
12317 if (signo != 0)
12318 setsignal(signo);
Denis Vlasenkob012b102007-02-19 22:43:01 +000012319 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +000012320 ap++;
12321 }
12322 return 0;
12323}
12324
Eric Andersenc470f442003-07-28 09:56:35 +000012325
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012326/* ============ Builtins */
Eric Andersenc470f442003-07-28 09:56:35 +000012327
Denis Vlasenko8e1c7152007-01-22 07:21:38 +000012328#if !ENABLE_FEATURE_SH_EXTRA_QUIET
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012329/*
12330 * Lists available builtins
12331 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012332static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012333helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersenc470f442003-07-28 09:56:35 +000012334{
Denis Vlasenko6b06cb82008-05-15 21:30:45 +000012335 unsigned col;
12336 unsigned i;
Eric Andersenc470f442003-07-28 09:56:35 +000012337
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +020012338 out1fmt(
Denis Vlasenko34d4d892009-04-04 20:24:37 +000012339 "Built-in commands:\n"
12340 "------------------\n");
Denis Vlasenkob71c6682007-07-21 15:08:09 +000012341 for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
Eric Andersenc470f442003-07-28 09:56:35 +000012342 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
Denis Vlasenko52764022007-02-24 13:42:56 +000012343 builtintab[i].name + 1);
Eric Andersenc470f442003-07-28 09:56:35 +000012344 if (col > 60) {
12345 out1fmt("\n");
12346 col = 0;
12347 }
12348 }
Denis Vlasenko80d14be2007-04-10 23:03:30 +000012349#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko1aa7e472007-11-28 06:49:03 +000012350 {
12351 const char *a = applet_names;
12352 while (*a) {
12353 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
12354 if (col > 60) {
12355 out1fmt("\n");
12356 col = 0;
12357 }
12358 a += strlen(a) + 1;
Eric Andersenc470f442003-07-28 09:56:35 +000012359 }
12360 }
12361#endif
12362 out1fmt("\n\n");
12363 return EXIT_SUCCESS;
12364}
Denis Vlasenko131ae172007-02-18 13:00:19 +000012365#endif /* FEATURE_SH_EXTRA_QUIET */
Eric Andersenc470f442003-07-28 09:56:35 +000012366
Eric Andersencb57d552001-06-28 07:25:16 +000012367/*
Eric Andersencb57d552001-06-28 07:25:16 +000012368 * The export and readonly commands.
12369 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012370static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012371exportcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +000012372{
12373 struct var *vp;
12374 char *name;
12375 const char *p;
Eric Andersenc470f442003-07-28 09:56:35 +000012376 char **aptr;
Denis Vlasenkob7304742008-10-20 08:15:51 +000012377 int flag = argv[0][0] == 'r' ? VREADONLY : VEXPORT;
Eric Andersencb57d552001-06-28 07:25:16 +000012378
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012379 if (nextopt("p") != 'p') {
12380 aptr = argptr;
12381 name = *aptr;
12382 if (name) {
12383 do {
12384 p = strchr(name, '=');
12385 if (p != NULL) {
12386 p++;
12387 } else {
12388 vp = *findvar(hashvar(name), name);
12389 if (vp) {
12390 vp->flags |= flag;
12391 continue;
12392 }
Eric Andersencb57d552001-06-28 07:25:16 +000012393 }
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012394 setvar(name, p, flag);
12395 } while ((name = *++aptr) != NULL);
12396 return 0;
12397 }
Eric Andersencb57d552001-06-28 07:25:16 +000012398 }
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012399 showvars(argv[0], flag, 0);
Eric Andersencb57d552001-06-28 07:25:16 +000012400 return 0;
12401}
12402
Eric Andersencb57d552001-06-28 07:25:16 +000012403/*
Denis Vlasenko5651bfc2007-02-23 21:08:58 +000012404 * Delete a function if it exists.
Eric Andersencb57d552001-06-28 07:25:16 +000012405 */
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012406static void
Denis Vlasenko5651bfc2007-02-23 21:08:58 +000012407unsetfunc(const char *name)
Aaron Lehmannb6ecbdc2001-12-06 03:37:38 +000012408{
Denis Vlasenko5651bfc2007-02-23 21:08:58 +000012409 struct tblentry *cmdp;
Eric Andersencb57d552001-06-28 07:25:16 +000012410
Denis Vlasenko5651bfc2007-02-23 21:08:58 +000012411 cmdp = cmdlookup(name, 0);
12412 if (cmdp!= NULL && cmdp->cmdtype == CMDFUNCTION)
12413 delete_cmd_entry();
Eric Andersenc470f442003-07-28 09:56:35 +000012414}
12415
Eric Andersencb57d552001-06-28 07:25:16 +000012416/*
Eric Andersencb57d552001-06-28 07:25:16 +000012417 * The unset builtin command. We unset the function before we unset the
12418 * variable to allow a function to be unset when there is a readonly variable
12419 * with the same name.
12420 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012421static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012422unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersencb57d552001-06-28 07:25:16 +000012423{
12424 char **ap;
12425 int i;
Eric Andersenc470f442003-07-28 09:56:35 +000012426 int flag = 0;
Eric Andersencb57d552001-06-28 07:25:16 +000012427 int ret = 0;
12428
12429 while ((i = nextopt("vf")) != '\0') {
Eric Andersenc470f442003-07-28 09:56:35 +000012430 flag = i;
Eric Andersencb57d552001-06-28 07:25:16 +000012431 }
Eric Andersencb57d552001-06-28 07:25:16 +000012432
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012433 for (ap = argptr; *ap; ap++) {
Eric Andersenc470f442003-07-28 09:56:35 +000012434 if (flag != 'f') {
12435 i = unsetvar(*ap);
12436 ret |= i;
12437 if (!(i & 2))
12438 continue;
12439 }
12440 if (flag != 'v')
Eric Andersencb57d552001-06-28 07:25:16 +000012441 unsetfunc(*ap);
Eric Andersencb57d552001-06-28 07:25:16 +000012442 }
Eric Andersenc470f442003-07-28 09:56:35 +000012443 return ret & 1;
Eric Andersencb57d552001-06-28 07:25:16 +000012444}
12445
12446
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +000012447/* setmode.c */
Eric Andersencb57d552001-06-28 07:25:16 +000012448
Eric Andersenc470f442003-07-28 09:56:35 +000012449#include <sys/times.h>
12450
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000012451static const unsigned char timescmd_str[] ALIGN1 = {
Manuel Novoa III 4456f252003-08-13 17:48:47 +000012452 ' ', offsetof(struct tms, tms_utime),
12453 '\n', offsetof(struct tms, tms_stime),
12454 ' ', offsetof(struct tms, tms_cutime),
12455 '\n', offsetof(struct tms, tms_cstime),
12456 0
12457};
Eric Andersencb57d552001-06-28 07:25:16 +000012458
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012459static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012460timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Manuel Novoa III 4456f252003-08-13 17:48:47 +000012461{
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012462 long clk_tck, s, t;
Manuel Novoa III 4456f252003-08-13 17:48:47 +000012463 const unsigned char *p;
12464 struct tms buf;
12465
12466 clk_tck = sysconf(_SC_CLK_TCK);
Eric Andersencb57d552001-06-28 07:25:16 +000012467 times(&buf);
Manuel Novoa III 4456f252003-08-13 17:48:47 +000012468
12469 p = timescmd_str;
12470 do {
12471 t = *(clock_t *)(((char *) &buf) + p[1]);
12472 s = t / clk_tck;
12473 out1fmt("%ldm%ld.%.3lds%c",
12474 s/60, s%60,
12475 ((t - s * clk_tck) * 1000) / clk_tck,
12476 p[0]);
12477 } while (*(p += 2));
12478
Eric Andersencb57d552001-06-28 07:25:16 +000012479 return 0;
12480}
12481
Mike Frysinger98c52642009-04-02 10:02:37 +000012482#if ENABLE_SH_MATH_SUPPORT
Eric Andersenc470f442003-07-28 09:56:35 +000012483/*
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +000012484 * The let builtin. partial stolen from GNU Bash, the Bourne Again SHell.
12485 * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
Eric Andersen90898442003-08-06 11:20:52 +000012486 *
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +000012487 * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
Eric Andersenc470f442003-07-28 09:56:35 +000012488 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012489static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012490letcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersenc470f442003-07-28 09:56:35 +000012491{
Denis Vlasenko68404f12008-03-17 09:00:54 +000012492 arith_t i;
Eric Andersenc470f442003-07-28 09:56:35 +000012493
Denis Vlasenko68404f12008-03-17 09:00:54 +000012494 argv++;
12495 if (!*argv)
Denis Vlasenkob012b102007-02-19 22:43:01 +000012496 ash_msg_and_raise_error("expression expected");
Denis Vlasenko68404f12008-03-17 09:00:54 +000012497 do {
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +000012498 i = ash_arith(*argv);
Denis Vlasenko68404f12008-03-17 09:00:54 +000012499 } while (*++argv);
Eric Andersenc470f442003-07-28 09:56:35 +000012500
Denis Vlasenkod9e15f22006-11-27 16:49:55 +000012501 return !i;
Eric Andersenc470f442003-07-28 09:56:35 +000012502}
Mike Frysinger98c52642009-04-02 10:02:37 +000012503#endif /* SH_MATH_SUPPORT */
Eric Andersenc470f442003-07-28 09:56:35 +000012504
Eric Andersenc470f442003-07-28 09:56:35 +000012505
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012506/* ============ miscbltin.c
12507 *
Eric Andersenaff114c2004-04-14 17:51:38 +000012508 * Miscellaneous builtins.
Eric Andersenc470f442003-07-28 09:56:35 +000012509 */
12510
12511#undef rflag
12512
Denis Vlasenko83e5d6f2006-12-18 21:49:06 +000012513#if defined(__GLIBC__) && __GLIBC__ == 2 && __GLIBC_MINOR__ < 1
Eric Andersenc470f442003-07-28 09:56:35 +000012514typedef enum __rlimit_resource rlim_t;
12515#endif
Eric Andersen74bcd162001-07-30 21:41:37 +000012516
Eric Andersenc470f442003-07-28 09:56:35 +000012517/*
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012518 * The read builtin. Options:
12519 * -r Do not interpret '\' specially
12520 * -s Turn off echo (tty only)
12521 * -n NCHARS Read NCHARS max
12522 * -p PROMPT Display PROMPT on stderr (if input is from tty)
12523 * -t SECONDS Timeout after SECONDS (tty or pipe only)
12524 * -u FD Read from given FD instead of fd 0
Eric Andersenc470f442003-07-28 09:56:35 +000012525 * This uses unbuffered input, which may be avoidable in some cases.
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012526 * TODO: bash also has:
12527 * -a ARRAY Read into array[0],[1],etc
12528 * -d DELIM End on DELIM char, not newline
12529 * -e Use line editing (tty only)
Eric Andersenc470f442003-07-28 09:56:35 +000012530 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012531static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012532readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersenc470f442003-07-28 09:56:35 +000012533{
Denis Vlasenko9cd4c762008-06-18 19:22:19 +000012534 static const char *const arg_REPLY[] = { "REPLY", NULL };
12535
Eric Andersenc470f442003-07-28 09:56:35 +000012536 char **ap;
12537 int backslash;
12538 char c;
12539 int rflag;
12540 char *prompt;
12541 const char *ifs;
12542 char *p;
12543 int startword;
12544 int status;
12545 int i;
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012546 int fd = 0;
Denis Vlasenko131ae172007-02-18 13:00:19 +000012547#if ENABLE_ASH_READ_NCHARS
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012548 int nchars = 0; /* if != 0, -n is in effect */
Paul Fox02eb9342005-09-07 16:56:02 +000012549 int silent = 0;
12550 struct termios tty, old_tty;
12551#endif
Denis Vlasenko131ae172007-02-18 13:00:19 +000012552#if ENABLE_ASH_READ_TIMEOUT
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012553 unsigned end_ms = 0;
12554 unsigned timeout = 0;
Paul Fox02eb9342005-09-07 16:56:02 +000012555#endif
Eric Andersenc470f442003-07-28 09:56:35 +000012556
12557 rflag = 0;
12558 prompt = NULL;
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012559 while ((i = nextopt("p:u:r"
Denis Vlasenko5e34ff22009-04-21 11:09:40 +000012560 IF_ASH_READ_TIMEOUT("t:")
12561 IF_ASH_READ_NCHARS("n:s")
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012562 )) != '\0') {
Denis Vlasenkobf0a2012006-12-26 10:42:51 +000012563 switch (i) {
Paul Fox02eb9342005-09-07 16:56:02 +000012564 case 'p':
Eric Andersenc470f442003-07-28 09:56:35 +000012565 prompt = optionarg;
Paul Fox02eb9342005-09-07 16:56:02 +000012566 break;
Denis Vlasenko131ae172007-02-18 13:00:19 +000012567#if ENABLE_ASH_READ_NCHARS
Paul Fox02eb9342005-09-07 16:56:02 +000012568 case 'n':
Denis Vlasenko037576d2007-10-20 18:30:38 +000012569 nchars = bb_strtou(optionarg, NULL, 10);
12570 if (nchars < 0 || errno)
Denis Vlasenkob012b102007-02-19 22:43:01 +000012571 ash_msg_and_raise_error("invalid count");
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012572 /* nchars == 0: off (bash 3.2 does this too) */
Paul Fox02eb9342005-09-07 16:56:02 +000012573 break;
12574 case 's':
12575 silent = 1;
12576 break;
Ned Ludd2123b7c2005-02-09 21:07:23 +000012577#endif
Denis Vlasenko131ae172007-02-18 13:00:19 +000012578#if ENABLE_ASH_READ_TIMEOUT
Paul Fox02eb9342005-09-07 16:56:02 +000012579 case 't':
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012580 timeout = bb_strtou(optionarg, NULL, 10);
12581 if (errno || timeout > UINT_MAX / 2048)
12582 ash_msg_and_raise_error("invalid timeout");
12583 timeout *= 1000;
12584#if 0 /* even bash have no -t N.NNN support */
Denis Vlasenko037576d2007-10-20 18:30:38 +000012585 ts.tv_sec = bb_strtou(optionarg, &p, 10);
Paul Fox02eb9342005-09-07 16:56:02 +000012586 ts.tv_usec = 0;
Denis Vlasenko037576d2007-10-20 18:30:38 +000012587 /* EINVAL means number is ok, but not terminated by NUL */
12588 if (*p == '.' && errno == EINVAL) {
Paul Fox02eb9342005-09-07 16:56:02 +000012589 char *p2;
12590 if (*++p) {
12591 int scale;
Denis Vlasenko037576d2007-10-20 18:30:38 +000012592 ts.tv_usec = bb_strtou(p, &p2, 10);
12593 if (errno)
Denis Vlasenkob012b102007-02-19 22:43:01 +000012594 ash_msg_and_raise_error("invalid timeout");
Paul Fox02eb9342005-09-07 16:56:02 +000012595 scale = p2 - p;
12596 /* normalize to usec */
12597 if (scale > 6)
Denis Vlasenkob012b102007-02-19 22:43:01 +000012598 ash_msg_and_raise_error("invalid timeout");
Paul Fox02eb9342005-09-07 16:56:02 +000012599 while (scale++ < 6)
12600 ts.tv_usec *= 10;
12601 }
Denis Vlasenko037576d2007-10-20 18:30:38 +000012602 } else if (ts.tv_sec < 0 || errno) {
Denis Vlasenkob012b102007-02-19 22:43:01 +000012603 ash_msg_and_raise_error("invalid timeout");
Paul Fox02eb9342005-09-07 16:56:02 +000012604 }
Denis Vlasenko037576d2007-10-20 18:30:38 +000012605 if (!(ts.tv_sec | ts.tv_usec)) { /* both are 0? */
Denis Vlasenkob012b102007-02-19 22:43:01 +000012606 ash_msg_and_raise_error("invalid timeout");
Denis Vlasenko037576d2007-10-20 18:30:38 +000012607 }
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012608#endif /* if 0 */
Paul Fox02eb9342005-09-07 16:56:02 +000012609 break;
12610#endif
12611 case 'r':
12612 rflag = 1;
12613 break;
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012614 case 'u':
12615 fd = bb_strtou(optionarg, NULL, 10);
12616 if (fd < 0 || errno)
12617 ash_msg_and_raise_error("invalid file descriptor");
12618 break;
Paul Fox02eb9342005-09-07 16:56:02 +000012619 default:
12620 break;
12621 }
Eric Andersenc470f442003-07-28 09:56:35 +000012622 }
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012623 if (prompt && isatty(fd)) {
Eric Andersenc470f442003-07-28 09:56:35 +000012624 out2str(prompt);
Eric Andersenc470f442003-07-28 09:56:35 +000012625 }
Denis Vlasenko5cedb752007-02-18 19:56:41 +000012626 ap = argptr;
12627 if (*ap == NULL)
Denis Vlasenko9cd4c762008-06-18 19:22:19 +000012628 ap = (char**)arg_REPLY;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000012629 ifs = bltinlookup("IFS");
12630 if (ifs == NULL)
Eric Andersenc470f442003-07-28 09:56:35 +000012631 ifs = defifs;
Denis Vlasenko131ae172007-02-18 13:00:19 +000012632#if ENABLE_ASH_READ_NCHARS
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012633 tcgetattr(fd, &tty);
12634 old_tty = tty;
12635 if (nchars || silent) {
12636 if (nchars) {
12637 tty.c_lflag &= ~ICANON;
12638 tty.c_cc[VMIN] = nchars < 256 ? nchars : 255;
Paul Fox02eb9342005-09-07 16:56:02 +000012639 }
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012640 if (silent) {
12641 tty.c_lflag &= ~(ECHO | ECHOK | ECHONL);
12642 }
12643 /* if tcgetattr failed, tcsetattr will fail too.
12644 * Ignoring, it's harmless. */
12645 tcsetattr(fd, TCSANOW, &tty);
Paul Fox02eb9342005-09-07 16:56:02 +000012646 }
12647#endif
Paul Fox02eb9342005-09-07 16:56:02 +000012648
Eric Andersenc470f442003-07-28 09:56:35 +000012649 status = 0;
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012650 startword = 2;
Eric Andersenc470f442003-07-28 09:56:35 +000012651 backslash = 0;
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012652#if ENABLE_ASH_READ_TIMEOUT
12653 if (timeout) /* NB: ensuring end_ms is nonzero */
12654 end_ms = ((unsigned)(monotonic_us() / 1000) + timeout) | 1;
12655#endif
Eric Andersenc470f442003-07-28 09:56:35 +000012656 STARTSTACKSTR(p);
Denis Vlasenko037576d2007-10-20 18:30:38 +000012657 do {
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012658 const char *is_ifs;
12659
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012660#if ENABLE_ASH_READ_TIMEOUT
12661 if (end_ms) {
12662 struct pollfd pfd[1];
12663 pfd[0].fd = fd;
12664 pfd[0].events = POLLIN;
12665 timeout = end_ms - (unsigned)(monotonic_us() / 1000);
12666 if ((int)timeout <= 0 /* already late? */
12667 || safe_poll(pfd, 1, timeout) != 1 /* no? wait... */
12668 ) { /* timed out! */
12669#if ENABLE_ASH_READ_NCHARS
12670 tcsetattr(fd, TCSANOW, &old_tty);
12671#endif
12672 return 1;
12673 }
12674 }
12675#endif
12676 if (nonblock_safe_read(fd, &c, 1) != 1) {
Eric Andersenc470f442003-07-28 09:56:35 +000012677 status = 1;
12678 break;
12679 }
12680 if (c == '\0')
12681 continue;
12682 if (backslash) {
12683 backslash = 0;
12684 if (c != '\n')
12685 goto put;
12686 continue;
12687 }
12688 if (!rflag && c == '\\') {
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012689 backslash = 1;
Eric Andersenc470f442003-07-28 09:56:35 +000012690 continue;
12691 }
12692 if (c == '\n')
12693 break;
Denis Vlasenkof6fbd622009-03-31 19:36:58 +000012694 /* $IFS splitting */
Denis Vlasenko551ffdc2009-04-01 19:48:05 +000012695/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_05 */
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012696 is_ifs = strchr(ifs, c);
12697 if (startword && is_ifs) {
12698 if (isspace(c))
12699 continue;
Denis Vlasenkof6fbd622009-03-31 19:36:58 +000012700 /* it is a non-space ifs char */
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012701 startword--;
12702 if (startword == 1) /* first one? */
Denis Vlasenkof6fbd622009-03-31 19:36:58 +000012703 continue; /* yes, it is not next word yet */
Eric Andersenc470f442003-07-28 09:56:35 +000012704 }
12705 startword = 0;
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012706 if (ap[1] != NULL && is_ifs) {
12707 const char *beg;
Eric Andersenc470f442003-07-28 09:56:35 +000012708 STACKSTRNUL(p);
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012709 beg = stackblock();
12710 setvar(*ap, beg, 0);
Eric Andersenc470f442003-07-28 09:56:35 +000012711 ap++;
Denis Vlasenkof6fbd622009-03-31 19:36:58 +000012712 /* can we skip one non-space ifs char? (2: yes) */
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012713 startword = isspace(c) ? 2 : 1;
Eric Andersenc470f442003-07-28 09:56:35 +000012714 STARTSTACKSTR(p);
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012715 continue;
Eric Andersenc470f442003-07-28 09:56:35 +000012716 }
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012717 put:
12718 STPUTC(c, p);
Eric Andersenc470f442003-07-28 09:56:35 +000012719 }
Denis Vlasenko037576d2007-10-20 18:30:38 +000012720/* end of do {} while: */
Denis Vlasenko131ae172007-02-18 13:00:19 +000012721#if ENABLE_ASH_READ_NCHARS
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012722 while (--nchars);
Denis Vlasenko037576d2007-10-20 18:30:38 +000012723#else
12724 while (1);
12725#endif
12726
12727#if ENABLE_ASH_READ_NCHARS
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012728 tcsetattr(fd, TCSANOW, &old_tty);
Paul Fox02eb9342005-09-07 16:56:02 +000012729#endif
12730
Eric Andersenc470f442003-07-28 09:56:35 +000012731 STACKSTRNUL(p);
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012732 /* Remove trailing space ifs chars */
12733 while ((char *)stackblock() <= --p && isspace(*p) && strchr(ifs, *p) != NULL)
Eric Andersenc470f442003-07-28 09:56:35 +000012734 *p = '\0';
12735 setvar(*ap, stackblock(), 0);
12736 while (*++ap != NULL)
12737 setvar(*ap, nullstr, 0);
12738 return status;
12739}
12740
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012741static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012742umaskcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersenc470f442003-07-28 09:56:35 +000012743{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000012744 static const char permuser[3] ALIGN1 = "ugo";
12745 static const char permmode[3] ALIGN1 = "rwx";
12746 static const short permmask[] ALIGN2 = {
Eric Andersenc470f442003-07-28 09:56:35 +000012747 S_IRUSR, S_IWUSR, S_IXUSR,
12748 S_IRGRP, S_IWGRP, S_IXGRP,
12749 S_IROTH, S_IWOTH, S_IXOTH
12750 };
12751
Denis Vlasenkoeb858492009-04-18 02:06:54 +000012752 /* TODO: use bb_parse_mode() instead */
12753
Eric Andersenc470f442003-07-28 09:56:35 +000012754 char *ap;
12755 mode_t mask;
12756 int i;
12757 int symbolic_mode = 0;
12758
12759 while (nextopt("S") != '\0') {
12760 symbolic_mode = 1;
12761 }
12762
Denis Vlasenkob012b102007-02-19 22:43:01 +000012763 INT_OFF;
Eric Andersenc470f442003-07-28 09:56:35 +000012764 mask = umask(0);
12765 umask(mask);
Denis Vlasenkob012b102007-02-19 22:43:01 +000012766 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +000012767
Denis Vlasenko5cedb752007-02-18 19:56:41 +000012768 ap = *argptr;
12769 if (ap == NULL) {
Eric Andersenc470f442003-07-28 09:56:35 +000012770 if (symbolic_mode) {
12771 char buf[18];
12772 char *p = buf;
12773
12774 for (i = 0; i < 3; i++) {
12775 int j;
12776
12777 *p++ = permuser[i];
12778 *p++ = '=';
12779 for (j = 0; j < 3; j++) {
12780 if ((mask & permmask[3 * i + j]) == 0) {
12781 *p++ = permmode[j];
12782 }
12783 }
12784 *p++ = ',';
12785 }
12786 *--p = 0;
12787 puts(buf);
12788 } else {
12789 out1fmt("%.4o\n", mask);
12790 }
12791 } else {
Denis Vlasenkoaa744452007-02-23 01:04:22 +000012792 if (isdigit((unsigned char) *ap)) {
Eric Andersenc470f442003-07-28 09:56:35 +000012793 mask = 0;
12794 do {
12795 if (*ap >= '8' || *ap < '0')
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +020012796 ash_msg_and_raise_error(msg_illnum, argv[1]);
Eric Andersenc470f442003-07-28 09:56:35 +000012797 mask = (mask << 3) + (*ap - '0');
12798 } while (*++ap != '\0');
12799 umask(mask);
12800 } else {
12801 mask = ~mask & 0777;
12802 if (!bb_parse_mode(ap, &mask)) {
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +000012803 ash_msg_and_raise_error("illegal mode: %s", ap);
Eric Andersenc470f442003-07-28 09:56:35 +000012804 }
12805 umask(~mask & 0777);
12806 }
12807 }
12808 return 0;
12809}
12810
12811/*
12812 * ulimit builtin
12813 *
12814 * This code, originally by Doug Gwyn, Doug Kingston, Eric Gisin, and
12815 * Michael Rendell was ripped from pdksh 5.0.8 and hacked for use with
12816 * ash by J.T. Conklin.
12817 *
12818 * Public domain.
12819 */
Eric Andersenc470f442003-07-28 09:56:35 +000012820struct limits {
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012821 uint8_t cmd; /* RLIMIT_xxx fit into it */
12822 uint8_t factor_shift; /* shift by to get rlim_{cur,max} values */
Eric Andersenc470f442003-07-28 09:56:35 +000012823 char option;
12824};
12825
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012826static const struct limits limits_tbl[] = {
Eric Andersenc470f442003-07-28 09:56:35 +000012827#ifdef RLIMIT_CPU
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012828 { RLIMIT_CPU, 0, 't' },
Eric Andersenc470f442003-07-28 09:56:35 +000012829#endif
12830#ifdef RLIMIT_FSIZE
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012831 { RLIMIT_FSIZE, 9, 'f' },
Eric Andersenc470f442003-07-28 09:56:35 +000012832#endif
12833#ifdef RLIMIT_DATA
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012834 { RLIMIT_DATA, 10, 'd' },
Eric Andersenc470f442003-07-28 09:56:35 +000012835#endif
12836#ifdef RLIMIT_STACK
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012837 { RLIMIT_STACK, 10, 's' },
Eric Andersenc470f442003-07-28 09:56:35 +000012838#endif
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012839#ifdef RLIMIT_CORE
12840 { RLIMIT_CORE, 9, 'c' },
Eric Andersenc470f442003-07-28 09:56:35 +000012841#endif
12842#ifdef RLIMIT_RSS
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012843 { RLIMIT_RSS, 10, 'm' },
Eric Andersenc470f442003-07-28 09:56:35 +000012844#endif
12845#ifdef RLIMIT_MEMLOCK
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012846 { RLIMIT_MEMLOCK, 10, 'l' },
Eric Andersenc470f442003-07-28 09:56:35 +000012847#endif
12848#ifdef RLIMIT_NPROC
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012849 { RLIMIT_NPROC, 0, 'p' },
Eric Andersenc470f442003-07-28 09:56:35 +000012850#endif
12851#ifdef RLIMIT_NOFILE
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012852 { RLIMIT_NOFILE, 0, 'n' },
Eric Andersenc470f442003-07-28 09:56:35 +000012853#endif
Glenn L McGrath76620622004-01-13 10:19:37 +000012854#ifdef RLIMIT_AS
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012855 { RLIMIT_AS, 10, 'v' },
Eric Andersenc470f442003-07-28 09:56:35 +000012856#endif
Glenn L McGrath76620622004-01-13 10:19:37 +000012857#ifdef RLIMIT_LOCKS
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012858 { RLIMIT_LOCKS, 0, 'w' },
Eric Andersenc470f442003-07-28 09:56:35 +000012859#endif
Eric Andersenc470f442003-07-28 09:56:35 +000012860};
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012861static const char limits_name[] =
12862#ifdef RLIMIT_CPU
12863 "time(seconds)" "\0"
12864#endif
12865#ifdef RLIMIT_FSIZE
12866 "file(blocks)" "\0"
12867#endif
12868#ifdef RLIMIT_DATA
12869 "data(kb)" "\0"
12870#endif
12871#ifdef RLIMIT_STACK
12872 "stack(kb)" "\0"
12873#endif
12874#ifdef RLIMIT_CORE
12875 "coredump(blocks)" "\0"
12876#endif
12877#ifdef RLIMIT_RSS
12878 "memory(kb)" "\0"
12879#endif
12880#ifdef RLIMIT_MEMLOCK
12881 "locked memory(kb)" "\0"
12882#endif
12883#ifdef RLIMIT_NPROC
12884 "process" "\0"
12885#endif
12886#ifdef RLIMIT_NOFILE
12887 "nofiles" "\0"
12888#endif
12889#ifdef RLIMIT_AS
12890 "vmemory(kb)" "\0"
12891#endif
12892#ifdef RLIMIT_LOCKS
12893 "locks" "\0"
12894#endif
12895;
Eric Andersenc470f442003-07-28 09:56:35 +000012896
Glenn L McGrath76620622004-01-13 10:19:37 +000012897enum limtype { SOFT = 0x1, HARD = 0x2 };
12898
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012899static void
12900printlim(enum limtype how, const struct rlimit *limit,
Glenn L McGrath76620622004-01-13 10:19:37 +000012901 const struct limits *l)
12902{
12903 rlim_t val;
12904
12905 val = limit->rlim_max;
12906 if (how & SOFT)
12907 val = limit->rlim_cur;
12908
12909 if (val == RLIM_INFINITY)
12910 out1fmt("unlimited\n");
12911 else {
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012912 val >>= l->factor_shift;
Glenn L McGrath76620622004-01-13 10:19:37 +000012913 out1fmt("%lld\n", (long long) val);
12914 }
12915}
12916
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012917static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012918ulimitcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersenc470f442003-07-28 09:56:35 +000012919{
Denys Vlasenko76622db2009-10-04 01:14:19 +020012920 rlim_t val;
Glenn L McGrath76620622004-01-13 10:19:37 +000012921 enum limtype how = SOFT | HARD;
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012922 const struct limits *l;
12923 int set, all = 0;
12924 int optc, what;
12925 struct rlimit limit;
Eric Andersenc470f442003-07-28 09:56:35 +000012926
12927 what = 'f';
Glenn L McGrath16e45d72004-02-04 08:24:39 +000012928 while ((optc = nextopt("HSa"
12929#ifdef RLIMIT_CPU
12930 "t"
12931#endif
12932#ifdef RLIMIT_FSIZE
12933 "f"
12934#endif
12935#ifdef RLIMIT_DATA
12936 "d"
12937#endif
12938#ifdef RLIMIT_STACK
12939 "s"
12940#endif
12941#ifdef RLIMIT_CORE
12942 "c"
12943#endif
12944#ifdef RLIMIT_RSS
12945 "m"
12946#endif
12947#ifdef RLIMIT_MEMLOCK
12948 "l"
12949#endif
12950#ifdef RLIMIT_NPROC
12951 "p"
12952#endif
12953#ifdef RLIMIT_NOFILE
12954 "n"
12955#endif
12956#ifdef RLIMIT_AS
12957 "v"
12958#endif
12959#ifdef RLIMIT_LOCKS
12960 "w"
12961#endif
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000012962 )) != '\0')
Eric Andersenc470f442003-07-28 09:56:35 +000012963 switch (optc) {
12964 case 'H':
12965 how = HARD;
12966 break;
12967 case 'S':
12968 how = SOFT;
12969 break;
12970 case 'a':
12971 all = 1;
12972 break;
12973 default:
12974 what = optc;
12975 }
12976
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012977 for (l = limits_tbl; l->option != what; l++)
12978 continue;
Eric Andersenc470f442003-07-28 09:56:35 +000012979
12980 set = *argptr ? 1 : 0;
Denys Vlasenko76622db2009-10-04 01:14:19 +020012981 val = 0;
Eric Andersenc470f442003-07-28 09:56:35 +000012982 if (set) {
12983 char *p = *argptr;
12984
12985 if (all || argptr[1])
Denis Vlasenkob012b102007-02-19 22:43:01 +000012986 ash_msg_and_raise_error("too many arguments");
Eric Andersen81fe1232003-07-29 06:38:40 +000012987 if (strncmp(p, "unlimited\n", 9) == 0)
Eric Andersenc470f442003-07-28 09:56:35 +000012988 val = RLIM_INFINITY;
12989 else {
Denys Vlasenko76622db2009-10-04 01:14:19 +020012990 if (sizeof(val) == sizeof(int))
12991 val = bb_strtou(p, NULL, 10);
12992 else if (sizeof(val) == sizeof(long))
12993 val = bb_strtoul(p, NULL, 10);
12994 else
12995 val = bb_strtoull(p, NULL, 10);
12996 if (errno)
Denis Vlasenkob012b102007-02-19 22:43:01 +000012997 ash_msg_and_raise_error("bad number");
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012998 val <<= l->factor_shift;
Eric Andersenc470f442003-07-28 09:56:35 +000012999 }
13000 }
13001 if (all) {
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000013002 const char *lname = limits_name;
13003 for (l = limits_tbl; l != &limits_tbl[ARRAY_SIZE(limits_tbl)]; l++) {
Eric Andersenc470f442003-07-28 09:56:35 +000013004 getrlimit(l->cmd, &limit);
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000013005 out1fmt("%-20s ", lname);
13006 lname += strlen(lname) + 1;
Glenn L McGrath76620622004-01-13 10:19:37 +000013007 printlim(how, &limit, l);
Eric Andersenc470f442003-07-28 09:56:35 +000013008 }
13009 return 0;
13010 }
13011
13012 getrlimit(l->cmd, &limit);
13013 if (set) {
13014 if (how & HARD)
13015 limit.rlim_max = val;
13016 if (how & SOFT)
13017 limit.rlim_cur = val;
13018 if (setrlimit(l->cmd, &limit) < 0)
Denis Vlasenkob012b102007-02-19 22:43:01 +000013019 ash_msg_and_raise_error("error setting limit (%m)");
Eric Andersenc470f442003-07-28 09:56:35 +000013020 } else {
Glenn L McGrath76620622004-01-13 10:19:37 +000013021 printlim(how, &limit, l);
Eric Andersenc470f442003-07-28 09:56:35 +000013022 }
13023 return 0;
13024}
13025
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000013026/* ============ main() and helpers */
13027
13028/*
13029 * Called to exit the shell.
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013030 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000013031static void exitshell(void) NORETURN;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000013032static void
13033exitshell(void)
13034{
13035 struct jmploc loc;
13036 char *p;
13037 int status;
13038
13039 status = exitstatus;
13040 TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
13041 if (setjmp(loc.loc)) {
Denis Vlasenko7f88e342009-03-19 03:36:18 +000013042 if (exception_type == EXEXIT)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000013043/* dash bug: it just does _exit(exitstatus) here
13044 * but we have to do setjobctl(0) first!
13045 * (bug is still not fixed in dash-0.5.3 - if you run dash
13046 * under Midnight Commander, on exit from dash MC is backgrounded) */
13047 status = exitstatus;
13048 goto out;
13049 }
13050 exception_handler = &loc;
13051 p = trap[0];
13052 if (p) {
13053 trap[0] = NULL;
13054 evalstring(p, 0);
Denys Vlasenko0800e3a2009-09-24 03:09:26 +020013055 free(p);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000013056 }
13057 flush_stdout_stderr();
13058 out:
13059 setjobctl(0);
13060 _exit(status);
13061 /* NOTREACHED */
13062}
13063
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000013064static void
13065init(void)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013066{
13067 /* from input.c: */
Denis Vlasenko41eb3002008-11-28 03:42:31 +000013068 basepf.next_to_pgetc = basepf.buf = basebuf;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013069
13070 /* from trap.c: */
13071 signal(SIGCHLD, SIG_DFL);
13072
13073 /* from var.c: */
13074 {
13075 char **envp;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013076 const char *p;
13077 struct stat st1, st2;
13078
13079 initvar();
13080 for (envp = environ; envp && *envp; envp++) {
13081 if (strchr(*envp, '=')) {
13082 setvareq(*envp, VEXPORT|VTEXTFIXED);
13083 }
13084 }
13085
Denys Vlasenko7bb346f2009-10-06 22:09:50 +020013086 setvar("PPID", utoa(getppid()), 0);
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013087
13088 p = lookupvar("PWD");
13089 if (p)
13090 if (*p != '/' || stat(p, &st1) || stat(".", &st2)
13091 || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino)
13092 p = '\0';
13093 setpwd(p, 0);
13094 }
13095}
13096
13097/*
13098 * Process the shell command line arguments.
13099 */
13100static void
Denis Vlasenko68404f12008-03-17 09:00:54 +000013101procargs(char **argv)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013102{
13103 int i;
13104 const char *xminusc;
13105 char **xargv;
13106
13107 xargv = argv;
13108 arg0 = xargv[0];
Denis Vlasenko68404f12008-03-17 09:00:54 +000013109 /* if (xargv[0]) - mmm, this is always true! */
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013110 xargv++;
13111 for (i = 0; i < NOPTS; i++)
13112 optlist[i] = 2;
13113 argptr = xargv;
Denis Vlasenko28bf6712008-02-14 15:01:47 +000013114 if (options(1)) {
13115 /* it already printed err message */
13116 raise_exception(EXERROR);
13117 }
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013118 xargv = argptr;
13119 xminusc = minusc;
13120 if (*xargv == NULL) {
13121 if (xminusc)
13122 ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
13123 sflag = 1;
13124 }
13125 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
13126 iflag = 1;
13127 if (mflag == 2)
13128 mflag = iflag;
13129 for (i = 0; i < NOPTS; i++)
13130 if (optlist[i] == 2)
13131 optlist[i] = 0;
13132#if DEBUG == 2
13133 debug = 1;
13134#endif
13135 /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
13136 if (xminusc) {
13137 minusc = *xargv++;
13138 if (*xargv)
13139 goto setarg0;
13140 } else if (!sflag) {
13141 setinputfile(*xargv, 0);
13142 setarg0:
13143 arg0 = *xargv++;
13144 commandname = arg0;
13145 }
13146
13147 shellparam.p = xargv;
13148#if ENABLE_ASH_GETOPTS
13149 shellparam.optind = 1;
13150 shellparam.optoff = -1;
13151#endif
Denis Vlasenko01631112007-12-16 17:20:38 +000013152 /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013153 while (*xargv) {
13154 shellparam.nparam++;
13155 xargv++;
13156 }
13157 optschanged();
13158}
13159
13160/*
13161 * Read /etc/profile or .profile.
13162 */
13163static void
13164read_profile(const char *name)
13165{
13166 int skip;
13167
13168 if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
13169 return;
13170 skip = cmdloop(0);
13171 popfile();
13172 if (skip)
13173 exitshell();
13174}
13175
Denis Vlasenko0c032a42007-02-23 01:03:40 +000013176/*
13177 * This routine is called when an error or an interrupt occurs in an
13178 * interactive shell and control is returned to the main command loop.
13179 */
13180static void
13181reset(void)
13182{
13183 /* from eval.c: */
13184 evalskip = 0;
13185 loopnest = 0;
13186 /* from input.c: */
Denis Vlasenko41eb3002008-11-28 03:42:31 +000013187 g_parsefile->left_in_buffer = 0;
13188 g_parsefile->left_in_line = 0; /* clear input buffer */
Denis Vlasenko0c032a42007-02-23 01:03:40 +000013189 popallfiles();
13190 /* from parser.c: */
13191 tokpushback = 0;
13192 checkkwd = 0;
13193 /* from redir.c: */
Denis Vlasenko34c73c42008-08-16 11:48:02 +000013194 clearredir(/*drop:*/ 0);
Denis Vlasenko0c032a42007-02-23 01:03:40 +000013195}
13196
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013197#if PROFILE
13198static short profile_buf[16384];
13199extern int etext();
13200#endif
13201
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000013202/*
13203 * Main routine. We initialize things, parse the arguments, execute
13204 * profiles if we're a login shell, and then call cmdloop to execute
13205 * commands. The setjmp call sets up the location to jump to when an
13206 * exception occurs. When an exception occurs the variable "state"
13207 * is used to figure out how far we had gotten.
13208 */
Denis Vlasenko9b49a5e2007-10-11 10:05:36 +000013209int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000013210int ash_main(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013211{
Mike Frysinger98c52642009-04-02 10:02:37 +000013212 const char *shinit;
Denis Vlasenko4e12b1a2008-12-23 23:36:47 +000013213 volatile smallint state;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013214 struct jmploc jmploc;
13215 struct stackmark smark;
13216
Denis Vlasenko01631112007-12-16 17:20:38 +000013217 /* Initialize global data */
13218 INIT_G_misc();
13219 INIT_G_memstack();
13220 INIT_G_var();
Denis Vlasenkoee87ebf2007-12-21 22:18:16 +000013221#if ENABLE_ASH_ALIAS
Denis Vlasenko01631112007-12-16 17:20:38 +000013222 INIT_G_alias();
Denis Vlasenkoee87ebf2007-12-21 22:18:16 +000013223#endif
Denis Vlasenko01631112007-12-16 17:20:38 +000013224 INIT_G_cmdtable();
13225
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013226#if PROFILE
13227 monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
13228#endif
13229
13230#if ENABLE_FEATURE_EDITING
13231 line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
13232#endif
13233 state = 0;
13234 if (setjmp(jmploc.loc)) {
Denis Vlasenko7f88e342009-03-19 03:36:18 +000013235 smallint e;
Denis Vlasenko4e12b1a2008-12-23 23:36:47 +000013236 smallint s;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013237
13238 reset();
13239
Denis Vlasenko7f88e342009-03-19 03:36:18 +000013240 e = exception_type;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013241 if (e == EXERROR)
13242 exitstatus = 2;
13243 s = state;
13244 if (e == EXEXIT || s == 0 || iflag == 0 || shlvl)
13245 exitshell();
Denis Vlasenko7f88e342009-03-19 03:36:18 +000013246 if (e == EXINT)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013247 outcslow('\n', stderr);
Denis Vlasenko7f88e342009-03-19 03:36:18 +000013248
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013249 popstackmark(&smark);
13250 FORCE_INT_ON; /* enable interrupts */
13251 if (s == 1)
13252 goto state1;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000013253 if (s == 2)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013254 goto state2;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000013255 if (s == 3)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013256 goto state3;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000013257 goto state4;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013258 }
13259 exception_handler = &jmploc;
13260#if DEBUG
13261 opentrace();
Denis Vlasenko653d8e72009-03-19 21:59:35 +000013262 TRACE(("Shell args: "));
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000013263 trace_puts_args(argv);
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013264#endif
13265 rootpid = getpid();
13266
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013267 init();
13268 setstackmark(&smark);
Denis Vlasenko68404f12008-03-17 09:00:54 +000013269 procargs(argv);
13270
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013271#if ENABLE_FEATURE_EDITING_SAVEHISTORY
13272 if (iflag) {
13273 const char *hp = lookupvar("HISTFILE");
13274
13275 if (hp == NULL) {
13276 hp = lookupvar("HOME");
13277 if (hp != NULL) {
13278 char *defhp = concat_path_file(hp, ".ash_history");
13279 setvar("HISTFILE", defhp, 0);
13280 free(defhp);
13281 }
13282 }
13283 }
13284#endif
Denis Vlasenko4e12b1a2008-12-23 23:36:47 +000013285 if (/* argv[0] && */ argv[0][0] == '-')
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013286 isloginsh = 1;
13287 if (isloginsh) {
13288 state = 1;
13289 read_profile("/etc/profile");
13290 state1:
13291 state = 2;
13292 read_profile(".profile");
13293 }
13294 state2:
13295 state = 3;
13296 if (
13297#ifndef linux
Denis Vlasenko0c032a42007-02-23 01:03:40 +000013298 getuid() == geteuid() && getgid() == getegid() &&
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013299#endif
Denis Vlasenko0c032a42007-02-23 01:03:40 +000013300 iflag
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013301 ) {
13302 shinit = lookupvar("ENV");
13303 if (shinit != NULL && *shinit != '\0') {
13304 read_profile(shinit);
13305 }
13306 }
13307 state3:
13308 state = 4;
Denis Vlasenko5c2b8142009-03-19 01:59:59 +000013309 if (minusc) {
13310 /* evalstring pushes parsefile stack.
13311 * Ensure we don't falsely claim that 0 (stdin)
Denis Vlasenko5368ad52009-03-20 10:20:08 +000013312 * is one of stacked source fds.
13313 * Testcase: ash -c 'exec 1>&0' must not complain. */
Denis Vlasenko5c2b8142009-03-19 01:59:59 +000013314 if (!sflag)
13315 g_parsefile->fd = -1;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013316 evalstring(minusc, 0);
Denis Vlasenko5c2b8142009-03-19 01:59:59 +000013317 }
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013318
13319 if (sflag || minusc == NULL) {
Denys Vlasenkodb9c57e2009-09-27 02:48:53 +020013320#if MAX_HISTORY > 0 && ENABLE_FEATURE_EDITING_SAVEHISTORY
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +000013321 if (iflag) {
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013322 const char *hp = lookupvar("HISTFILE");
Denis Vlasenko5c2b8142009-03-19 01:59:59 +000013323 if (hp)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013324 line_input_state->hist_file = hp;
13325 }
13326#endif
13327 state4: /* XXX ??? - why isn't this before the "if" statement */
13328 cmdloop(1);
13329 }
13330#if PROFILE
13331 monitor(0);
13332#endif
13333#ifdef GPROF
13334 {
13335 extern void _mcleanup(void);
13336 _mcleanup();
13337 }
13338#endif
13339 exitshell();
13340 /* NOTREACHED */
13341}
13342
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013343
Eric Andersendf82f612001-06-28 07:46:40 +000013344/*-
13345 * Copyright (c) 1989, 1991, 1993, 1994
Eric Andersen2870d962001-07-02 17:27:21 +000013346 * The Regents of the University of California. All rights reserved.
Eric Andersendf82f612001-06-28 07:46:40 +000013347 *
13348 * This code is derived from software contributed to Berkeley by
13349 * Kenneth Almquist.
13350 *
13351 * Redistribution and use in source and binary forms, with or without
13352 * modification, are permitted provided that the following conditions
13353 * are met:
13354 * 1. Redistributions of source code must retain the above copyright
13355 * notice, this list of conditions and the following disclaimer.
13356 * 2. Redistributions in binary form must reproduce the above copyright
13357 * notice, this list of conditions and the following disclaimer in the
13358 * documentation and/or other materials provided with the distribution.
"Vladimir N. Oleynik"ddc280e2005-12-15 12:01:49 +000013359 * 3. Neither the name of the University nor the names of its contributors
Eric Andersendf82f612001-06-28 07:46:40 +000013360 * may be used to endorse or promote products derived from this software
13361 * without specific prior written permission.
13362 *
13363 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
13364 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
13365 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
13366 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
13367 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
13368 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
13369 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
13370 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
13371 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
13372 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
13373 * SUCH DAMAGE.
13374 */