blob: cc2677126ece2d9fe5748810a5439f9b9dfae961 [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 }
4728 if (pid == 0)
Denys Vlasenkoe56f22a2009-07-24 00:16:59 +02004729 forkchild(jp, n, mode);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004730 else
4731 forkparent(jp, n, mode, pid);
4732 return pid;
4733}
4734
4735/*
4736 * Wait for job to finish.
4737 *
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004738 * Under job control we have the problem that while a child process
4739 * is running interrupts generated by the user are sent to the child
4740 * but not to the shell. This means that an infinite loop started by
4741 * an interactive user may be hard to kill. With job control turned off,
4742 * an interactive user may place an interactive program inside a loop.
4743 * If the interactive program catches interrupts, the user doesn't want
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004744 * these interrupts to also abort the loop. The approach we take here
4745 * is to have the shell ignore interrupt signals while waiting for a
4746 * foreground process to terminate, and then send itself an interrupt
4747 * signal if the child process was terminated by an interrupt signal.
4748 * Unfortunately, some programs want to do a bit of cleanup and then
4749 * exit on interrupt; unless these processes terminate themselves by
4750 * sending a signal to themselves (instead of calling exit) they will
4751 * confuse this approach.
4752 *
4753 * Called with interrupts off.
4754 */
4755static int
4756waitforjob(struct job *jp)
4757{
4758 int st;
4759
4760 TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004761
4762 INT_OFF;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004763 while (jp->state == JOBRUNNING) {
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004764 /* In non-interactive shells, we _can_ get
4765 * a keyboard signal here and be EINTRed,
4766 * but we just loop back, waiting for command to complete.
4767 *
4768 * man bash:
4769 * "If bash is waiting for a command to complete and receives
4770 * a signal for which a trap has been set, the trap
4771 * will not be executed until the command completes."
4772 *
4773 * Reality is that even if trap is not set, bash
4774 * will not act on the signal until command completes.
4775 * Try this. sleep5intoff.c:
4776 * #include <signal.h>
4777 * #include <unistd.h>
4778 * int main() {
4779 * sigset_t set;
4780 * sigemptyset(&set);
4781 * sigaddset(&set, SIGINT);
4782 * sigaddset(&set, SIGQUIT);
4783 * sigprocmask(SIG_BLOCK, &set, NULL);
4784 * sleep(5);
4785 * return 0;
4786 * }
4787 * $ bash -c './sleep5intoff; echo hi'
4788 * ^C^C^C^C <--- pressing ^C once a second
4789 * $ _
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004790 * $ bash -c './sleep5intoff; echo hi'
4791 * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
4792 * $ _
4793 */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004794 dowait(DOWAIT_BLOCK, jp);
4795 }
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004796 INT_ON;
4797
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004798 st = getstatus(jp);
4799#if JOBS
4800 if (jp->jobctl) {
4801 xtcsetpgrp(ttyfd, rootpid);
4802 /*
4803 * This is truly gross.
4804 * If we're doing job control, then we did a TIOCSPGRP which
4805 * caused us (the shell) to no longer be in the controlling
4806 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
4807 * intuit from the subprocess exit status whether a SIGINT
4808 * occurred, and if so interrupt ourselves. Yuck. - mycroft
4809 */
Denis Vlasenko991a1da2008-02-10 19:02:53 +00004810 if (jp->sigint) /* TODO: do the same with all signals */
4811 raise(SIGINT); /* ... by raise(jp->sig) instead? */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004812 }
4813 if (jp->state == JOBDONE)
4814#endif
4815 freejob(jp);
4816 return st;
4817}
4818
4819/*
4820 * return 1 if there are stopped jobs, otherwise 0
4821 */
4822static int
4823stoppedjobs(void)
4824{
4825 struct job *jp;
4826 int retval;
4827
4828 retval = 0;
4829 if (job_warning)
4830 goto out;
4831 jp = curjob;
4832 if (jp && jp->state == JOBSTOPPED) {
4833 out2str("You have stopped jobs.\n");
4834 job_warning = 2;
4835 retval++;
4836 }
4837 out:
4838 return retval;
4839}
4840
4841
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004842/* ============ redir.c
4843 *
4844 * Code for dealing with input/output redirection.
4845 */
4846
4847#define EMPTY -2 /* marks an unused slot in redirtab */
Denis Vlasenko7d75a962007-11-22 08:16:57 +00004848#define CLOSED -3 /* marks a slot of previously-closed fd */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004849
4850/*
4851 * Open a file in noclobber mode.
4852 * The code was copied from bash.
4853 */
4854static int
4855noclobberopen(const char *fname)
4856{
4857 int r, fd;
4858 struct stat finfo, finfo2;
4859
4860 /*
4861 * If the file exists and is a regular file, return an error
4862 * immediately.
4863 */
4864 r = stat(fname, &finfo);
4865 if (r == 0 && S_ISREG(finfo.st_mode)) {
4866 errno = EEXIST;
4867 return -1;
4868 }
4869
4870 /*
4871 * If the file was not present (r != 0), make sure we open it
4872 * exclusively so that if it is created before we open it, our open
4873 * will fail. Make sure that we do not truncate an existing file.
4874 * Note that we don't turn on O_EXCL unless the stat failed -- if the
4875 * file was not a regular file, we leave O_EXCL off.
4876 */
4877 if (r != 0)
4878 return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
4879 fd = open(fname, O_WRONLY|O_CREAT, 0666);
4880
4881 /* If the open failed, return the file descriptor right away. */
4882 if (fd < 0)
4883 return fd;
4884
4885 /*
4886 * OK, the open succeeded, but the file may have been changed from a
4887 * non-regular file to a regular file between the stat and the open.
4888 * We are assuming that the O_EXCL open handles the case where FILENAME
4889 * did not exist and is symlinked to an existing file between the stat
4890 * and open.
4891 */
4892
4893 /*
4894 * If we can open it and fstat the file descriptor, and neither check
4895 * revealed that it was a regular file, and the file has not been
4896 * replaced, return the file descriptor.
4897 */
4898 if (fstat(fd, &finfo2) == 0 && !S_ISREG(finfo2.st_mode)
4899 && finfo.st_dev == finfo2.st_dev && finfo.st_ino == finfo2.st_ino)
4900 return fd;
4901
4902 /* The file has been replaced. badness. */
4903 close(fd);
4904 errno = EEXIST;
4905 return -1;
4906}
4907
4908/*
4909 * Handle here documents. Normally we fork off a process to write the
4910 * data to a pipe. If the document is short, we can stuff the data in
4911 * the pipe without forking.
4912 */
4913/* openhere needs this forward reference */
4914static void expandhere(union node *arg, int fd);
4915static int
4916openhere(union node *redir)
4917{
4918 int pip[2];
4919 size_t len = 0;
4920
4921 if (pipe(pip) < 0)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00004922 ash_msg_and_raise_error("pipe call failed");
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004923 if (redir->type == NHERE) {
4924 len = strlen(redir->nhere.doc->narg.text);
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00004925 if (len <= PIPE_BUF) {
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004926 full_write(pip[1], redir->nhere.doc->narg.text, len);
4927 goto out;
4928 }
4929 }
4930 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
Denis Vlasenko0b769642008-07-24 07:54:57 +00004931 /* child */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004932 close(pip[0]);
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004933 ignoresig(SIGINT); //signal(SIGINT, SIG_IGN);
4934 ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
4935 ignoresig(SIGHUP); //signal(SIGHUP, SIG_IGN);
4936 ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004937 signal(SIGPIPE, SIG_DFL);
4938 if (redir->type == NHERE)
4939 full_write(pip[1], redir->nhere.doc->narg.text, len);
Denis Vlasenko0b769642008-07-24 07:54:57 +00004940 else /* NXHERE */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004941 expandhere(redir->nhere.doc, pip[1]);
Bernhard Reutner-Fischer636a1f82008-05-19 09:29:47 +00004942 _exit(EXIT_SUCCESS);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004943 }
4944 out:
4945 close(pip[1]);
4946 return pip[0];
4947}
4948
4949static int
4950openredirect(union node *redir)
4951{
4952 char *fname;
4953 int f;
4954
4955 switch (redir->nfile.type) {
4956 case NFROM:
4957 fname = redir->nfile.expfname;
4958 f = open(fname, O_RDONLY);
4959 if (f < 0)
4960 goto eopen;
4961 break;
4962 case NFROMTO:
4963 fname = redir->nfile.expfname;
4964 f = open(fname, O_RDWR|O_CREAT|O_TRUNC, 0666);
4965 if (f < 0)
4966 goto ecreate;
4967 break;
4968 case NTO:
Denis Vlasenko559691a2008-10-05 18:39:31 +00004969#if ENABLE_ASH_BASH_COMPAT
4970 case NTO2:
4971#endif
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004972 /* Take care of noclobber mode. */
4973 if (Cflag) {
4974 fname = redir->nfile.expfname;
4975 f = noclobberopen(fname);
4976 if (f < 0)
4977 goto ecreate;
4978 break;
4979 }
4980 /* FALLTHROUGH */
4981 case NCLOBBER:
4982 fname = redir->nfile.expfname;
4983 f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
4984 if (f < 0)
4985 goto ecreate;
4986 break;
4987 case NAPPEND:
4988 fname = redir->nfile.expfname;
4989 f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
4990 if (f < 0)
4991 goto ecreate;
4992 break;
4993 default:
4994#if DEBUG
4995 abort();
4996#endif
4997 /* Fall through to eliminate warning. */
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00004998/* Our single caller does this itself */
Denis Vlasenko0b769642008-07-24 07:54:57 +00004999// case NTOFD:
5000// case NFROMFD:
5001// f = -1;
5002// break;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005003 case NHERE:
5004 case NXHERE:
5005 f = openhere(redir);
5006 break;
5007 }
5008
5009 return f;
5010 ecreate:
Bernhard Reutner-Fischera53de7f2008-07-21 13:46:54 +00005011 ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005012 eopen:
Bernhard Reutner-Fischera53de7f2008-07-21 13:46:54 +00005013 ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005014}
5015
5016/*
5017 * Copy a file descriptor to be >= to. Returns -1
5018 * if the source file descriptor is closed, EMPTY if there are no unused
5019 * file descriptors left.
5020 */
Denis Vlasenko5a867312008-07-24 19:46:38 +00005021/* 0x800..00: bit to set in "to" to request dup2 instead of fcntl(F_DUPFD).
5022 * old code was doing close(to) prior to copyfd() to achieve the same */
Denis Vlasenko22f74142008-07-24 22:34:43 +00005023enum {
5024 COPYFD_EXACT = (int)~(INT_MAX),
5025 COPYFD_RESTORE = (int)((unsigned)COPYFD_EXACT >> 1),
5026};
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005027static int
5028copyfd(int from, int to)
5029{
5030 int newfd;
5031
Denis Vlasenko5a867312008-07-24 19:46:38 +00005032 if (to & COPYFD_EXACT) {
5033 to &= ~COPYFD_EXACT;
5034 /*if (from != to)*/
5035 newfd = dup2(from, to);
5036 } else {
5037 newfd = fcntl(from, F_DUPFD, to);
5038 }
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005039 if (newfd < 0) {
5040 if (errno == EMFILE)
5041 return EMPTY;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005042 /* Happens when source fd is not open: try "echo >&99" */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005043 ash_msg_and_raise_error("%d: %m", from);
5044 }
5045 return newfd;
5046}
5047
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005048/* Struct def and variable are moved down to the first usage site */
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005049struct two_fd_t {
5050 int orig, copy;
5051};
Denis Vlasenko0b769642008-07-24 07:54:57 +00005052struct redirtab {
5053 struct redirtab *next;
Denis Vlasenko0b769642008-07-24 07:54:57 +00005054 int nullredirs;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005055 int pair_count;
Denys Vlasenko606291b2009-09-23 23:15:43 +02005056 struct two_fd_t two_fd[];
Denis Vlasenko0b769642008-07-24 07:54:57 +00005057};
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005058#define redirlist (G_var.redirlist)
Denis Vlasenko0b769642008-07-24 07:54:57 +00005059
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005060static int need_to_remember(struct redirtab *rp, int fd)
5061{
5062 int i;
5063
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005064 if (!rp) /* remembering was not requested */
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005065 return 0;
5066
5067 for (i = 0; i < rp->pair_count; i++) {
5068 if (rp->two_fd[i].orig == fd) {
5069 /* already remembered */
5070 return 0;
5071 }
5072 }
5073 return 1;
5074}
5075
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005076/* "hidden" fd is a fd used to read scripts, or a copy of such */
5077static int is_hidden_fd(struct redirtab *rp, int fd)
5078{
5079 int i;
Denis Vlasenko34c73c42008-08-16 11:48:02 +00005080 struct parsefile *pf;
5081
5082 if (fd == -1)
5083 return 0;
5084 pf = g_parsefile;
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005085 while (pf) {
5086 if (fd == pf->fd) {
5087 return 1;
5088 }
5089 pf = pf->prev;
5090 }
5091 if (!rp)
5092 return 0;
5093 fd |= COPYFD_RESTORE;
5094 for (i = 0; i < rp->pair_count; i++) {
5095 if (rp->two_fd[i].copy == fd) {
5096 return 1;
5097 }
5098 }
5099 return 0;
5100}
5101
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005102/*
5103 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
5104 * old file descriptors are stashed away so that the redirection can be
5105 * undone by calling popredir. If the REDIR_BACKQ flag is set, then the
5106 * standard output, and the standard error if it becomes a duplicate of
5107 * stdout, is saved in memory.
5108 */
5109/* flags passed to redirect */
5110#define REDIR_PUSH 01 /* save previous values of file descriptors */
5111#define REDIR_SAVEFD2 03 /* set preverrout */
5112static void
5113redirect(union node *redir, int flags)
5114{
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005115 struct redirtab *sv;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005116 int sv_pos;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005117 int i;
5118 int fd;
5119 int newfd;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005120 int copied_fd2 = -1;
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005121
Denis Vlasenko01631112007-12-16 17:20:38 +00005122 g_nullredirs++;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005123 if (!redir) {
5124 return;
5125 }
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005126
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005127 sv = NULL;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005128 sv_pos = 0;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005129 INT_OFF;
5130 if (flags & REDIR_PUSH) {
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005131 union node *tmp = redir;
5132 do {
5133 sv_pos++;
Denis Vlasenko559691a2008-10-05 18:39:31 +00005134#if ENABLE_ASH_BASH_COMPAT
5135 if (redir->nfile.type == NTO2)
5136 sv_pos++;
5137#endif
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005138 tmp = tmp->nfile.next;
5139 } while (tmp);
5140 sv = ckmalloc(sizeof(*sv) + sv_pos * sizeof(sv->two_fd[0]));
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005141 sv->next = redirlist;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005142 sv->pair_count = sv_pos;
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005143 redirlist = sv;
Denis Vlasenko01631112007-12-16 17:20:38 +00005144 sv->nullredirs = g_nullredirs - 1;
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005145 g_nullredirs = 0;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005146 while (sv_pos > 0) {
5147 sv_pos--;
5148 sv->two_fd[sv_pos].orig = sv->two_fd[sv_pos].copy = EMPTY;
5149 }
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005150 }
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005151
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005152 do {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00005153 fd = redir->nfile.fd;
Denis Vlasenko0b769642008-07-24 07:54:57 +00005154 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005155 int right_fd = redir->ndup.dupfd;
5156 /* redirect from/to same file descriptor? */
5157 if (right_fd == fd)
5158 continue;
5159 /* echo >&10 and 10 is a fd opened to the sh script? */
5160 if (is_hidden_fd(sv, right_fd)) {
5161 errno = EBADF; /* as if it is closed */
5162 ash_msg_and_raise_error("%d: %m", right_fd);
5163 }
Denis Vlasenko0b769642008-07-24 07:54:57 +00005164 newfd = -1;
5165 } else {
5166 newfd = openredirect(redir); /* always >= 0 */
5167 if (fd == newfd) {
5168 /* Descriptor wasn't open before redirect.
5169 * Mark it for close in the future */
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005170 if (need_to_remember(sv, fd)) {
Denis Vlasenko5a867312008-07-24 19:46:38 +00005171 goto remember_to_close;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005172 }
Denis Vlasenko0b769642008-07-24 07:54:57 +00005173 continue;
5174 }
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005175 }
Denis Vlasenko559691a2008-10-05 18:39:31 +00005176#if ENABLE_ASH_BASH_COMPAT
5177 redirect_more:
5178#endif
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005179 if (need_to_remember(sv, fd)) {
Denis Vlasenko0b769642008-07-24 07:54:57 +00005180 /* Copy old descriptor */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005181 i = fcntl(fd, F_DUPFD, 10);
Denis Vlasenko5a867312008-07-24 19:46:38 +00005182/* You'd expect copy to be CLOEXECed. Currently these extra "saved" fds
5183 * are closed in popredir() in the child, preventing them from leaking
5184 * into child. (popredir() also cleans up the mess in case of failures)
5185 */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005186 if (i == -1) {
5187 i = errno;
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005188 if (i != EBADF) {
5189 /* Strange error (e.g. "too many files" EMFILE?) */
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005190 if (newfd >= 0)
5191 close(newfd);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005192 errno = i;
5193 ash_msg_and_raise_error("%d: %m", fd);
5194 /* NOTREACHED */
5195 }
Denis Vlasenko5a867312008-07-24 19:46:38 +00005196 /* EBADF: it is not open - good, remember to close it */
5197 remember_to_close:
5198 i = CLOSED;
Denis Vlasenko22f74142008-07-24 22:34:43 +00005199 } else { /* fd is open, save its copy */
5200 /* "exec fd>&-" should not close fds
5201 * which point to script file(s).
5202 * Force them to be restored afterwards */
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005203 if (is_hidden_fd(sv, fd))
5204 i |= COPYFD_RESTORE;
Denis Vlasenko22f74142008-07-24 22:34:43 +00005205 }
Denis Vlasenko5a867312008-07-24 19:46:38 +00005206 if (fd == 2)
5207 copied_fd2 = i;
5208 sv->two_fd[sv_pos].orig = fd;
5209 sv->two_fd[sv_pos].copy = i;
5210 sv_pos++;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005211 }
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005212 if (newfd < 0) {
5213 /* NTOFD/NFROMFD: copy redir->ndup.dupfd to fd */
Denis Vlasenko22f74142008-07-24 22:34:43 +00005214 if (redir->ndup.dupfd < 0) { /* "fd>&-" */
Denis Vlasenkob9e70dd2009-03-20 01:24:08 +00005215 /* Don't want to trigger debugging */
5216 if (fd != -1)
5217 close(fd);
Denis Vlasenko5a867312008-07-24 19:46:38 +00005218 } else {
5219 copyfd(redir->ndup.dupfd, fd | COPYFD_EXACT);
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005220 }
Denis Vlasenko5a867312008-07-24 19:46:38 +00005221 } else if (fd != newfd) { /* move newfd to fd */
5222 copyfd(newfd, fd | COPYFD_EXACT);
Denis Vlasenko559691a2008-10-05 18:39:31 +00005223#if ENABLE_ASH_BASH_COMPAT
5224 if (!(redir->nfile.type == NTO2 && fd == 2))
5225#endif
5226 close(newfd);
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005227 }
Denis Vlasenko559691a2008-10-05 18:39:31 +00005228#if ENABLE_ASH_BASH_COMPAT
5229 if (redir->nfile.type == NTO2 && fd == 1) {
5230 /* We already redirected it to fd 1, now copy it to 2 */
5231 newfd = 1;
5232 fd = 2;
5233 goto redirect_more;
5234 }
5235#endif
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00005236 } while ((redir = redir->nfile.next) != NULL);
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005237
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005238 INT_ON;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005239 if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
5240 preverrout_fd = copied_fd2;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005241}
5242
5243/*
5244 * Undo the effects of the last redirection.
5245 */
5246static void
Denis Vlasenko34c73c42008-08-16 11:48:02 +00005247popredir(int drop, int restore)
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005248{
5249 struct redirtab *rp;
5250 int i;
5251
Denis Vlasenko01631112007-12-16 17:20:38 +00005252 if (--g_nullredirs >= 0)
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005253 return;
5254 INT_OFF;
5255 rp = redirlist;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005256 for (i = 0; i < rp->pair_count; i++) {
5257 int fd = rp->two_fd[i].orig;
Denis Vlasenko22f74142008-07-24 22:34:43 +00005258 int copy = rp->two_fd[i].copy;
5259 if (copy == CLOSED) {
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005260 if (!drop)
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005261 close(fd);
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005262 continue;
5263 }
Denis Vlasenko22f74142008-07-24 22:34:43 +00005264 if (copy != EMPTY) {
Denis Vlasenko34c73c42008-08-16 11:48:02 +00005265 if (!drop || (restore && (copy & COPYFD_RESTORE))) {
Denis Vlasenko22f74142008-07-24 22:34:43 +00005266 copy &= ~COPYFD_RESTORE;
Denis Vlasenko5a867312008-07-24 19:46:38 +00005267 /*close(fd);*/
Denis Vlasenko22f74142008-07-24 22:34:43 +00005268 copyfd(copy, fd | COPYFD_EXACT);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005269 }
Denis Vlasenkob9e70dd2009-03-20 01:24:08 +00005270 close(copy & ~COPYFD_RESTORE);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005271 }
5272 }
5273 redirlist = rp->next;
Denis Vlasenko01631112007-12-16 17:20:38 +00005274 g_nullredirs = rp->nullredirs;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005275 free(rp);
5276 INT_ON;
5277}
5278
5279/*
5280 * Undo all redirections. Called on error or interrupt.
5281 */
5282
5283/*
5284 * Discard all saved file descriptors.
5285 */
5286static void
5287clearredir(int drop)
5288{
5289 for (;;) {
Denis Vlasenko01631112007-12-16 17:20:38 +00005290 g_nullredirs = 0;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005291 if (!redirlist)
5292 break;
Denis Vlasenko34c73c42008-08-16 11:48:02 +00005293 popredir(drop, /*restore:*/ 0);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005294 }
5295}
5296
5297static int
5298redirectsafe(union node *redir, int flags)
5299{
5300 int err;
5301 volatile int saveint;
5302 struct jmploc *volatile savehandler = exception_handler;
5303 struct jmploc jmploc;
5304
5305 SAVE_INT(saveint);
Denis Vlasenko5a867312008-07-24 19:46:38 +00005306 /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
5307 err = setjmp(jmploc.loc); // huh?? was = setjmp(jmploc.loc) * 2;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005308 if (!err) {
5309 exception_handler = &jmploc;
5310 redirect(redir, flags);
5311 }
5312 exception_handler = savehandler;
Denis Vlasenko7f88e342009-03-19 03:36:18 +00005313 if (err && exception_type != EXERROR)
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005314 longjmp(exception_handler->loc, 1);
5315 RESTORE_INT(saveint);
5316 return err;
5317}
5318
5319
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005320/* ============ Routines to expand arguments to commands
5321 *
5322 * We have to deal with backquotes, shell variables, and file metacharacters.
5323 */
5324
Mike Frysinger98c52642009-04-02 10:02:37 +00005325#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00005326static arith_t
5327ash_arith(const char *s)
5328{
5329 arith_eval_hooks_t math_hooks;
5330 arith_t result;
5331 int errcode = 0;
5332
5333 math_hooks.lookupvar = lookupvar;
5334 math_hooks.setvar = setvar;
5335 math_hooks.endofname = endofname;
5336
5337 INT_OFF;
5338 result = arith(s, &errcode, &math_hooks);
5339 if (errcode < 0) {
5340 if (errcode == -3)
5341 ash_msg_and_raise_error("exponent less than 0");
5342 if (errcode == -2)
5343 ash_msg_and_raise_error("divide by zero");
5344 if (errcode == -5)
5345 ash_msg_and_raise_error("expression recursion loop detected");
5346 raise_error_syntax(s);
5347 }
5348 INT_ON;
5349
5350 return result;
5351}
Denis Vlasenko448d30e2008-06-27 00:24:11 +00005352#endif
5353
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005354/*
5355 * expandarg flags
5356 */
5357#define EXP_FULL 0x1 /* perform word splitting & file globbing */
5358#define EXP_TILDE 0x2 /* do normal tilde expansion */
5359#define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
5360#define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
5361#define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
5362#define EXP_RECORD 0x20 /* need to record arguments for ifs breakup */
5363#define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
5364#define EXP_WORD 0x80 /* expand word in parameter expansion */
5365#define EXP_QWORD 0x100 /* expand word in quoted parameter expansion */
5366/*
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005367 * rmescape() flags
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005368 */
5369#define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
5370#define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
5371#define RMESCAPE_QUOTED 0x4 /* Remove CTLESC unless in quotes */
5372#define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
5373#define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
5374
5375/*
5376 * Structure specifying which parts of the string should be searched
5377 * for IFS characters.
5378 */
5379struct ifsregion {
5380 struct ifsregion *next; /* next region in list */
5381 int begoff; /* offset of start of region */
5382 int endoff; /* offset of end of region */
5383 int nulonly; /* search for nul bytes only */
5384};
5385
5386struct arglist {
5387 struct strlist *list;
5388 struct strlist **lastp;
5389};
5390
5391/* output of current string */
5392static char *expdest;
5393/* list of back quote expressions */
5394static struct nodelist *argbackq;
5395/* first struct in list of ifs regions */
5396static struct ifsregion ifsfirst;
5397/* last struct in list */
5398static struct ifsregion *ifslastp;
5399/* holds expanded arg list */
5400static struct arglist exparg;
5401
5402/*
5403 * Our own itoa().
5404 */
5405static int
5406cvtnum(arith_t num)
5407{
5408 int len;
5409
5410 expdest = makestrspace(32, expdest);
Mike Frysinger98c52642009-04-02 10:02:37 +00005411 len = fmtstr(expdest, 32, arith_t_fmt, num);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005412 STADJUST(len, expdest);
5413 return len;
5414}
5415
5416static size_t
5417esclen(const char *start, const char *p)
5418{
5419 size_t esc = 0;
5420
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005421 while (p > start && (unsigned char)*--p == CTLESC) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005422 esc++;
5423 }
5424 return esc;
5425}
5426
5427/*
5428 * Remove any CTLESC characters from a string.
5429 */
5430static char *
Denys Vlasenkob6c84342009-08-29 20:23:20 +02005431rmescapes(char *str, int flag)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005432{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00005433 static const char qchars[] ALIGN1 = { CTLESC, CTLQUOTEMARK, '\0' };
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00005434
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005435 char *p, *q, *r;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005436 unsigned inquotes;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005437 unsigned protect_against_glob;
5438 unsigned globbing;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005439
5440 p = strpbrk(str, qchars);
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005441 if (!p)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005442 return str;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005443
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005444 q = p;
5445 r = str;
5446 if (flag & RMESCAPE_ALLOC) {
5447 size_t len = p - str;
5448 size_t fulllen = len + strlen(p) + 1;
5449
5450 if (flag & RMESCAPE_GROW) {
5451 r = makestrspace(fulllen, expdest);
5452 } else if (flag & RMESCAPE_HEAP) {
5453 r = ckmalloc(fulllen);
5454 } else {
5455 r = stalloc(fulllen);
5456 }
5457 q = r;
5458 if (len > 0) {
Denis Vlasenko29eb3592008-05-18 14:06:08 +00005459 q = (char *)memcpy(q, str, len) + len;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005460 }
5461 }
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005462
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005463 inquotes = (flag & RMESCAPE_QUOTED) ^ RMESCAPE_QUOTED;
5464 globbing = flag & RMESCAPE_GLOB;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005465 protect_against_glob = globbing;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005466 while (*p) {
5467 if (*p == CTLQUOTEMARK) {
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005468// TODO: if no RMESCAPE_QUOTED in flags, inquotes never becomes 0
5469// (alternates between RMESCAPE_QUOTED and ~RMESCAPE_QUOTED). Is it ok?
5470// Note: both inquotes and protect_against_glob only affect whether
5471// CTLESC,<ch> gets converted to <ch> or to \<ch>
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005472 inquotes = ~inquotes;
5473 p++;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005474 protect_against_glob = globbing;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005475 continue;
5476 }
5477 if (*p == '\\') {
5478 /* naked back slash */
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005479 protect_against_glob = 0;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005480 goto copy;
5481 }
5482 if (*p == CTLESC) {
5483 p++;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005484 if (protect_against_glob && inquotes && *p != '/') {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005485 *q++ = '\\';
5486 }
5487 }
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005488 protect_against_glob = globbing;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005489 copy:
5490 *q++ = *p++;
5491 }
5492 *q = '\0';
5493 if (flag & RMESCAPE_GROW) {
5494 expdest = r;
5495 STADJUST(q - r + 1, expdest);
5496 }
5497 return r;
5498}
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005499#define pmatch(a, b) !fnmatch((a), (b), 0)
5500
5501/*
5502 * Prepare a pattern for a expmeta (internal glob(3)) call.
5503 *
5504 * Returns an stalloced string.
5505 */
5506static char *
5507preglob(const char *pattern, int quoted, int flag)
5508{
5509 flag |= RMESCAPE_GLOB;
5510 if (quoted) {
5511 flag |= RMESCAPE_QUOTED;
5512 }
Denys Vlasenkob6c84342009-08-29 20:23:20 +02005513 return rmescapes((char *)pattern, flag);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005514}
5515
5516/*
5517 * Put a string on the stack.
5518 */
5519static void
5520memtodest(const char *p, size_t len, int syntax, int quotes)
5521{
5522 char *q = expdest;
5523
Denys Vlasenkob6c84342009-08-29 20:23:20 +02005524 q = makestrspace(quotes ? len * 2 : len, q);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005525
5526 while (len--) {
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00005527 int c = signed_char2int(*p++);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005528 if (!c)
5529 continue;
Denys Vlasenkob6c84342009-08-29 20:23:20 +02005530 if (quotes) {
5531 int n = SIT(c, syntax);
5532 if (n == CCTL || n == CBACK)
5533 USTPUTC(CTLESC, q);
5534 }
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005535 USTPUTC(c, q);
5536 }
5537
5538 expdest = q;
5539}
5540
5541static void
5542strtodest(const char *p, int syntax, int quotes)
5543{
5544 memtodest(p, strlen(p), syntax, quotes);
5545}
5546
5547/*
5548 * Record the fact that we have to scan this region of the
5549 * string for IFS characters.
5550 */
5551static void
5552recordregion(int start, int end, int nulonly)
5553{
5554 struct ifsregion *ifsp;
5555
5556 if (ifslastp == NULL) {
5557 ifsp = &ifsfirst;
5558 } else {
5559 INT_OFF;
Denis Vlasenko597906c2008-02-20 16:38:54 +00005560 ifsp = ckzalloc(sizeof(*ifsp));
5561 /*ifsp->next = NULL; - ckzalloc did it */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005562 ifslastp->next = ifsp;
5563 INT_ON;
5564 }
5565 ifslastp = ifsp;
5566 ifslastp->begoff = start;
5567 ifslastp->endoff = end;
5568 ifslastp->nulonly = nulonly;
5569}
5570
5571static void
5572removerecordregions(int endoff)
5573{
5574 if (ifslastp == NULL)
5575 return;
5576
5577 if (ifsfirst.endoff > endoff) {
5578 while (ifsfirst.next != NULL) {
5579 struct ifsregion *ifsp;
5580 INT_OFF;
5581 ifsp = ifsfirst.next->next;
5582 free(ifsfirst.next);
5583 ifsfirst.next = ifsp;
5584 INT_ON;
5585 }
5586 if (ifsfirst.begoff > endoff)
5587 ifslastp = NULL;
5588 else {
5589 ifslastp = &ifsfirst;
5590 ifsfirst.endoff = endoff;
5591 }
5592 return;
5593 }
5594
5595 ifslastp = &ifsfirst;
5596 while (ifslastp->next && ifslastp->next->begoff < endoff)
5597 ifslastp=ifslastp->next;
5598 while (ifslastp->next != NULL) {
5599 struct ifsregion *ifsp;
5600 INT_OFF;
5601 ifsp = ifslastp->next->next;
5602 free(ifslastp->next);
5603 ifslastp->next = ifsp;
5604 INT_ON;
5605 }
5606 if (ifslastp->endoff > endoff)
5607 ifslastp->endoff = endoff;
5608}
5609
5610static char *
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005611exptilde(char *startp, char *p, int flags)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005612{
5613 char c;
5614 char *name;
5615 struct passwd *pw;
5616 const char *home;
Denys Vlasenko1166d7b2009-09-16 16:20:31 +02005617 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005618 int startloc;
5619
5620 name = p + 1;
5621
5622 while ((c = *++p) != '\0') {
5623 switch (c) {
5624 case CTLESC:
5625 return startp;
5626 case CTLQUOTEMARK:
5627 return startp;
5628 case ':':
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005629 if (flags & EXP_VARTILDE)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005630 goto done;
5631 break;
5632 case '/':
5633 case CTLENDVAR:
5634 goto done;
5635 }
5636 }
5637 done:
5638 *p = '\0';
5639 if (*name == '\0') {
5640 home = lookupvar(homestr);
5641 } else {
5642 pw = getpwnam(name);
5643 if (pw == NULL)
5644 goto lose;
5645 home = pw->pw_dir;
5646 }
5647 if (!home || !*home)
5648 goto lose;
5649 *p = c;
5650 startloc = expdest - (char *)stackblock();
5651 strtodest(home, SQSYNTAX, quotes);
5652 recordregion(startloc, expdest - (char *)stackblock(), 0);
5653 return p;
5654 lose:
5655 *p = c;
5656 return startp;
5657}
5658
5659/*
5660 * Execute a command inside back quotes. If it's a builtin command, we
5661 * want to save its output in a block obtained from malloc. Otherwise
5662 * we fork off a subprocess and get the output of the command via a pipe.
5663 * Should be called with interrupts off.
5664 */
5665struct backcmd { /* result of evalbackcmd */
5666 int fd; /* file descriptor to read from */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005667 int nleft; /* number of chars in buffer */
Denis Vlasenkob07a4962008-06-22 13:16:23 +00005668 char *buf; /* buffer */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005669 struct job *jp; /* job structure for command */
5670};
5671
5672/* These forward decls are needed to use "eval" code for backticks handling: */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00005673static uint8_t back_exitstatus; /* exit status of backquoted command */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005674#define EV_EXIT 01 /* exit after evaluating tree */
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02005675static void evaltree(union node *, int);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005676
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02005677static void FAST_FUNC
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005678evalbackcmd(union node *n, struct backcmd *result)
5679{
5680 int saveherefd;
5681
5682 result->fd = -1;
5683 result->buf = NULL;
5684 result->nleft = 0;
5685 result->jp = NULL;
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00005686 if (n == NULL)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005687 goto out;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005688
5689 saveherefd = herefd;
5690 herefd = -1;
5691
5692 {
5693 int pip[2];
5694 struct job *jp;
5695
5696 if (pipe(pip) < 0)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00005697 ash_msg_and_raise_error("pipe call failed");
Denis Vlasenko68404f12008-03-17 09:00:54 +00005698 jp = makejob(/*n,*/ 1);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005699 if (forkshell(jp, n, FORK_NOJOB) == 0) {
5700 FORCE_INT_ON;
5701 close(pip[0]);
5702 if (pip[1] != 1) {
Denis Vlasenko5a867312008-07-24 19:46:38 +00005703 /*close(1);*/
5704 copyfd(pip[1], 1 | COPYFD_EXACT);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005705 close(pip[1]);
5706 }
5707 eflag = 0;
5708 evaltree(n, EV_EXIT); /* actually evaltreenr... */
5709 /* NOTREACHED */
5710 }
5711 close(pip[1]);
5712 result->fd = pip[0];
5713 result->jp = jp;
5714 }
5715 herefd = saveherefd;
5716 out:
5717 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
5718 result->fd, result->buf, result->nleft, result->jp));
5719}
5720
5721/*
5722 * Expand stuff in backwards quotes.
5723 */
5724static void
5725expbackq(union node *cmd, int quoted, int quotes)
5726{
5727 struct backcmd in;
5728 int i;
5729 char buf[128];
5730 char *p;
5731 char *dest;
5732 int startloc;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00005733 int syntax = quoted ? DQSYNTAX : BASESYNTAX;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005734 struct stackmark smark;
5735
5736 INT_OFF;
5737 setstackmark(&smark);
5738 dest = expdest;
5739 startloc = dest - (char *)stackblock();
5740 grabstackstr(dest);
5741 evalbackcmd(cmd, &in);
5742 popstackmark(&smark);
5743
5744 p = in.buf;
5745 i = in.nleft;
5746 if (i == 0)
5747 goto read;
5748 for (;;) {
5749 memtodest(p, i, syntax, quotes);
5750 read:
5751 if (in.fd < 0)
5752 break;
Denis Vlasenkoe376d452008-02-20 22:23:24 +00005753 i = nonblock_safe_read(in.fd, buf, sizeof(buf));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005754 TRACE(("expbackq: read returns %d\n", i));
5755 if (i <= 0)
5756 break;
5757 p = buf;
5758 }
5759
Denis Vlasenko60818682007-09-28 22:07:23 +00005760 free(in.buf);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005761 if (in.fd >= 0) {
5762 close(in.fd);
5763 back_exitstatus = waitforjob(in.jp);
5764 }
5765 INT_ON;
5766
5767 /* Eat all trailing newlines */
5768 dest = expdest;
5769 for (; dest > (char *)stackblock() && dest[-1] == '\n';)
5770 STUNPUTC(dest);
5771 expdest = dest;
5772
5773 if (quoted == 0)
5774 recordregion(startloc, dest - (char *)stackblock(), 0);
5775 TRACE(("evalbackq: size=%d: \"%.*s\"\n",
5776 (dest - (char *)stackblock()) - startloc,
5777 (dest - (char *)stackblock()) - startloc,
5778 stackblock() + startloc));
5779}
5780
Mike Frysinger98c52642009-04-02 10:02:37 +00005781#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005782/*
5783 * Expand arithmetic expression. Backup to start of expression,
5784 * evaluate, place result in (backed up) result, adjust string position.
5785 */
5786static void
5787expari(int quotes)
5788{
5789 char *p, *start;
5790 int begoff;
5791 int flag;
5792 int len;
5793
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00005794 /* ifsfree(); */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005795
5796 /*
5797 * This routine is slightly over-complicated for
5798 * efficiency. Next we scan backwards looking for the
5799 * start of arithmetic.
5800 */
5801 start = stackblock();
5802 p = expdest - 1;
5803 *p = '\0';
5804 p--;
5805 do {
5806 int esc;
5807
5808 while (*p != CTLARI) {
5809 p--;
5810#if DEBUG
5811 if (p < start) {
5812 ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
5813 }
5814#endif
5815 }
5816
5817 esc = esclen(start, p);
5818 if (!(esc % 2)) {
5819 break;
5820 }
5821
5822 p -= esc + 1;
5823 } while (1);
5824
5825 begoff = p - start;
5826
5827 removerecordregions(begoff);
5828
5829 flag = p[1];
5830
5831 expdest = p;
5832
5833 if (quotes)
Denys Vlasenkob6c84342009-08-29 20:23:20 +02005834 rmescapes(p + 2, 0);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005835
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00005836 len = cvtnum(ash_arith(p + 2));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005837
5838 if (flag != '"')
5839 recordregion(begoff, begoff + len, 0);
5840}
5841#endif
5842
5843/* argstr needs it */
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005844static char *evalvar(char *p, int flags, struct strlist *var_str_list);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005845
5846/*
5847 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
5848 * characters to allow for further processing. Otherwise treat
5849 * $@ like $* since no splitting will be performed.
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00005850 *
5851 * var_str_list (can be NULL) is a list of "VAR=val" strings which take precedence
5852 * over shell varables. Needed for "A=a B=$A; echo $B" case - we use it
5853 * for correct expansion of "B=$A" word.
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005854 */
5855static void
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005856argstr(char *p, int flags, struct strlist *var_str_list)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005857{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00005858 static const char spclchars[] ALIGN1 = {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005859 '=',
5860 ':',
5861 CTLQUOTEMARK,
5862 CTLENDVAR,
5863 CTLESC,
5864 CTLVAR,
5865 CTLBACKQ,
5866 CTLBACKQ | CTLQUOTE,
Mike Frysinger98c52642009-04-02 10:02:37 +00005867#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005868 CTLENDARI,
5869#endif
5870 0
5871 };
5872 const char *reject = spclchars;
5873 int c;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005874 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR); /* do CTLESC */
5875 int breakall = flags & EXP_WORD;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005876 int inquotes;
5877 size_t length;
5878 int startloc;
5879
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005880 if (!(flags & EXP_VARTILDE)) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005881 reject += 2;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005882 } else if (flags & EXP_VARTILDE2) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005883 reject++;
5884 }
5885 inquotes = 0;
5886 length = 0;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005887 if (flags & EXP_TILDE) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005888 char *q;
5889
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005890 flags &= ~EXP_TILDE;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005891 tilde:
5892 q = p;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005893 if (*q == CTLESC && (flags & EXP_QWORD))
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005894 q++;
5895 if (*q == '~')
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005896 p = exptilde(p, q, flags);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005897 }
5898 start:
5899 startloc = expdest - (char *)stackblock();
5900 for (;;) {
5901 length += strcspn(p + length, reject);
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005902 c = (unsigned char) p[length];
5903 if (c) {
5904 if (!(c & 0x80)
Mike Frysinger98c52642009-04-02 10:02:37 +00005905#if ENABLE_SH_MATH_SUPPORT
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005906 || c == CTLENDARI
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005907#endif
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005908 ) {
5909 /* c == '=' || c == ':' || c == CTLENDARI */
5910 length++;
5911 }
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005912 }
5913 if (length > 0) {
5914 int newloc;
5915 expdest = stack_nputstr(p, length, expdest);
5916 newloc = expdest - (char *)stackblock();
5917 if (breakall && !inquotes && newloc > startloc) {
5918 recordregion(startloc, newloc, 0);
5919 }
5920 startloc = newloc;
5921 }
5922 p += length + 1;
5923 length = 0;
5924
5925 switch (c) {
5926 case '\0':
5927 goto breakloop;
5928 case '=':
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005929 if (flags & EXP_VARTILDE2) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005930 p--;
5931 continue;
5932 }
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005933 flags |= EXP_VARTILDE2;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005934 reject++;
5935 /* fall through */
5936 case ':':
5937 /*
5938 * sort of a hack - expand tildes in variable
5939 * assignments (after the first '=' and after ':'s).
5940 */
5941 if (*--p == '~') {
5942 goto tilde;
5943 }
5944 continue;
5945 }
5946
5947 switch (c) {
5948 case CTLENDVAR: /* ??? */
5949 goto breakloop;
5950 case CTLQUOTEMARK:
5951 /* "$@" syntax adherence hack */
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005952 if (!inquotes
5953 && memcmp(p, dolatstr, 4) == 0
5954 && ( p[4] == CTLQUOTEMARK
5955 || (p[4] == CTLENDVAR && p[5] == CTLQUOTEMARK)
5956 )
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005957 ) {
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005958 p = evalvar(p + 1, flags, /* var_str_list: */ NULL) + 1;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005959 goto start;
5960 }
5961 inquotes = !inquotes;
5962 addquote:
5963 if (quotes) {
5964 p--;
5965 length++;
5966 startloc++;
5967 }
5968 break;
5969 case CTLESC:
5970 startloc++;
5971 length++;
5972 goto addquote;
5973 case CTLVAR:
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005974 p = evalvar(p, flags, var_str_list);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005975 goto start;
5976 case CTLBACKQ:
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005977 c = '\0';
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005978 case CTLBACKQ|CTLQUOTE:
5979 expbackq(argbackq->n, c, quotes);
5980 argbackq = argbackq->next;
5981 goto start;
Mike Frysinger98c52642009-04-02 10:02:37 +00005982#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005983 case CTLENDARI:
5984 p--;
5985 expari(quotes);
5986 goto start;
5987#endif
5988 }
5989 }
5990 breakloop:
5991 ;
5992}
5993
5994static char *
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00005995scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM, char *str, int quotes,
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005996 int zero)
5997{
Denis Vlasenkoc7131c32008-04-14 01:59:53 +00005998// This commented out code was added by James Simmons <jsimmons@infradead.org>
5999// as part of a larger change when he added support for ${var/a/b}.
6000// However, it broke # and % operators:
6001//
6002//var=ababcdcd
6003// ok bad
6004//echo ${var#ab} abcdcd abcdcd
6005//echo ${var##ab} abcdcd abcdcd
6006//echo ${var#a*b} abcdcd ababcdcd (!)
6007//echo ${var##a*b} cdcd cdcd
6008//echo ${var#?} babcdcd ababcdcd (!)
6009//echo ${var##?} babcdcd babcdcd
6010//echo ${var#*} ababcdcd babcdcd (!)
6011//echo ${var##*}
6012//echo ${var%cd} ababcd ababcd
6013//echo ${var%%cd} ababcd abab (!)
6014//echo ${var%c*d} ababcd ababcd
6015//echo ${var%%c*d} abab ababcdcd (!)
6016//echo ${var%?} ababcdc ababcdc
6017//echo ${var%%?} ababcdc ababcdcd (!)
6018//echo ${var%*} ababcdcd ababcdcd
6019//echo ${var%%*}
6020//
6021// Commenting it back out helped. Remove it completely if it really
6022// is not needed.
6023
6024 char *loc, *loc2; //, *full;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006025 char c;
6026
6027 loc = startp;
6028 loc2 = rmesc;
6029 do {
Denis Vlasenkoc7131c32008-04-14 01:59:53 +00006030 int match; // = strlen(str);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006031 const char *s = loc2;
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006032
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006033 c = *loc2;
6034 if (zero) {
6035 *loc2 = '\0';
6036 s = rmesc;
6037 }
Denis Vlasenkoc7131c32008-04-14 01:59:53 +00006038 match = pmatch(str, s); // this line was deleted
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006039
Denis Vlasenkoc7131c32008-04-14 01:59:53 +00006040// // chop off end if its '*'
6041// full = strrchr(str, '*');
6042// if (full && full != str)
6043// match--;
6044//
6045// // If str starts with '*' replace with s.
6046// if ((*str == '*') && strlen(s) >= match) {
6047// full = xstrdup(s);
6048// strncpy(full+strlen(s)-match+1, str+1, match-1);
6049// } else
6050// full = xstrndup(str, match);
6051// match = strncmp(s, full, strlen(full));
6052// free(full);
6053//
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006054 *loc2 = c;
Denis Vlasenkoc7131c32008-04-14 01:59:53 +00006055 if (match) // if (!match)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006056 return loc;
6057 if (quotes && *loc == CTLESC)
6058 loc++;
6059 loc++;
6060 loc2++;
6061 } while (c);
6062 return 0;
6063}
6064
6065static char *
6066scanright(char *startp, char *rmesc, char *rmescend, char *str, int quotes,
6067 int zero)
6068{
6069 int esc = 0;
6070 char *loc;
6071 char *loc2;
6072
6073 for (loc = str - 1, loc2 = rmescend; loc >= startp; loc2--) {
6074 int match;
6075 char c = *loc2;
6076 const char *s = loc2;
6077 if (zero) {
6078 *loc2 = '\0';
6079 s = rmesc;
6080 }
6081 match = pmatch(str, s);
6082 *loc2 = c;
6083 if (match)
6084 return loc;
6085 loc--;
6086 if (quotes) {
6087 if (--esc < 0) {
6088 esc = esclen(startp, loc);
6089 }
6090 if (esc % 2) {
6091 esc--;
6092 loc--;
6093 }
6094 }
6095 }
6096 return 0;
6097}
6098
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00006099static void varunset(const char *, const char *, const char *, int) NORETURN;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006100static void
6101varunset(const char *end, const char *var, const char *umsg, int varflags)
6102{
6103 const char *msg;
6104 const char *tail;
6105
6106 tail = nullstr;
6107 msg = "parameter not set";
6108 if (umsg) {
6109 if (*end == CTLENDVAR) {
6110 if (varflags & VSNUL)
6111 tail = " or null";
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00006112 } else {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006113 msg = umsg;
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00006114 }
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006115 }
6116 ash_msg_and_raise_error("%.*s: %s%s", end - var - 1, var, msg, tail);
6117}
6118
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006119#if ENABLE_ASH_BASH_COMPAT
6120static char *
6121parse_sub_pattern(char *arg, int inquotes)
6122{
6123 char *idx, *repl = NULL;
6124 unsigned char c;
6125
Denis Vlasenko2659c632008-06-14 06:04:59 +00006126 idx = arg;
6127 while (1) {
6128 c = *arg;
6129 if (!c)
6130 break;
6131 if (c == '/') {
6132 /* Only the first '/' seen is our separator */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006133 if (!repl) {
Denis Vlasenko2659c632008-06-14 06:04:59 +00006134 repl = idx + 1;
6135 c = '\0';
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006136 }
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006137 }
Denis Vlasenko2659c632008-06-14 06:04:59 +00006138 *idx++ = c;
6139 if (!inquotes && c == '\\' && arg[1] == '\\')
6140 arg++; /* skip both \\, not just first one */
6141 arg++;
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006142 }
Denis Vlasenko29038c02008-06-14 06:14:02 +00006143 *idx = c; /* NUL */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006144
6145 return repl;
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006146}
6147#endif /* ENABLE_ASH_BASH_COMPAT */
6148
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006149static const char *
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006150subevalvar(char *p, char *str, int strloc, int subtype,
6151 int startloc, int varflags, int quotes, struct strlist *var_str_list)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006152{
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006153 struct nodelist *saveargbackq = argbackq;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006154 char *startp;
6155 char *loc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006156 char *rmesc, *rmescend;
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00006157 IF_ASH_BASH_COMPAT(char *repl = NULL;)
6158 IF_ASH_BASH_COMPAT(char null = '\0';)
6159 IF_ASH_BASH_COMPAT(int pos, len, orig_len;)
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006160 int saveherefd = herefd;
6161 int amount, workloc, resetloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006162 int zero;
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006163 char *(*scan)(char*, char*, char*, char*, int, int);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006164
6165 herefd = -1;
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006166 argstr(p, (subtype != VSASSIGN && subtype != VSQUESTION) ? EXP_CASE : 0,
6167 var_str_list);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006168 STPUTC('\0', expdest);
6169 herefd = saveherefd;
6170 argbackq = saveargbackq;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00006171 startp = (char *)stackblock() + startloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006172
6173 switch (subtype) {
6174 case VSASSIGN:
6175 setvar(str, startp, 0);
6176 amount = startp - expdest;
6177 STADJUST(amount, expdest);
6178 return startp;
6179
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006180#if ENABLE_ASH_BASH_COMPAT
6181 case VSSUBSTR:
6182 loc = str = stackblock() + strloc;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006183 /* Read POS in ${var:POS:LEN} */
6184 pos = atoi(loc); /* number(loc) errors out on "1:4" */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006185 len = str - startp - 1;
6186
6187 /* *loc != '\0', guaranteed by parser */
6188 if (quotes) {
6189 char *ptr;
6190
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006191 /* Adjust the length by the number of escapes */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006192 for (ptr = startp; ptr < (str - 1); ptr++) {
Denis Vlasenkod6855d12008-09-27 14:03:25 +00006193 if (*ptr == CTLESC) {
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006194 len--;
6195 ptr++;
6196 }
6197 }
6198 }
6199 orig_len = len;
6200
6201 if (*loc++ == ':') {
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006202 /* ${var::LEN} */
6203 len = number(loc);
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006204 } else {
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006205 /* Skip POS in ${var:POS:LEN} */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006206 len = orig_len;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006207 while (*loc && *loc != ':') {
6208 /* TODO?
6209 * bash complains on: var=qwe; echo ${var:1a:123}
6210 if (!isdigit(*loc))
6211 ash_msg_and_raise_error(msg_illnum, str);
6212 */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006213 loc++;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006214 }
6215 if (*loc++ == ':') {
6216 len = number(loc);
6217 }
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006218 }
6219 if (pos >= orig_len) {
6220 pos = 0;
6221 len = 0;
6222 }
6223 if (len > (orig_len - pos))
6224 len = orig_len - pos;
6225
6226 for (str = startp; pos; str++, pos--) {
6227 if (quotes && *str == CTLESC)
6228 str++;
6229 }
6230 for (loc = startp; len; len--) {
6231 if (quotes && *str == CTLESC)
6232 *loc++ = *str++;
6233 *loc++ = *str++;
6234 }
6235 *loc = '\0';
6236 amount = loc - expdest;
6237 STADJUST(amount, expdest);
6238 return loc;
6239#endif
6240
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006241 case VSQUESTION:
6242 varunset(p, str, startp, varflags);
6243 /* NOTREACHED */
6244 }
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006245 resetloc = expdest - (char *)stackblock();
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006246
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006247 /* We'll comeback here if we grow the stack while handling
6248 * a VSREPLACE or VSREPLACEALL, since our pointers into the
6249 * stack will need rebasing, and we'll need to remove our work
6250 * areas each time
6251 */
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00006252 IF_ASH_BASH_COMPAT(restart:)
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006253
6254 amount = expdest - ((char *)stackblock() + resetloc);
6255 STADJUST(-amount, expdest);
Denis Vlasenko29eb3592008-05-18 14:06:08 +00006256 startp = (char *)stackblock() + startloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006257
6258 rmesc = startp;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00006259 rmescend = (char *)stackblock() + strloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006260 if (quotes) {
Denys Vlasenkob6c84342009-08-29 20:23:20 +02006261 rmesc = rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006262 if (rmesc != startp) {
6263 rmescend = expdest;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00006264 startp = (char *)stackblock() + startloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006265 }
6266 }
6267 rmescend--;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00006268 str = (char *)stackblock() + strloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006269 preglob(str, varflags & VSQUOTE, 0);
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006270 workloc = expdest - (char *)stackblock();
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006271
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006272#if ENABLE_ASH_BASH_COMPAT
6273 if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
6274 char *idx, *end, *restart_detect;
6275
Denis Vlasenkod6855d12008-09-27 14:03:25 +00006276 if (!repl) {
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006277 repl = parse_sub_pattern(str, varflags & VSQUOTE);
6278 if (!repl)
6279 repl = &null;
6280 }
6281
6282 /* If there's no pattern to match, return the expansion unmolested */
6283 if (*str == '\0')
6284 return 0;
6285
6286 len = 0;
6287 idx = startp;
6288 end = str - 1;
6289 while (idx < end) {
6290 loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
6291 if (!loc) {
6292 /* No match, advance */
6293 restart_detect = stackblock();
6294 STPUTC(*idx, expdest);
6295 if (quotes && *idx == CTLESC) {
6296 idx++;
6297 len++;
6298 STPUTC(*idx, expdest);
6299 }
6300 if (stackblock() != restart_detect)
6301 goto restart;
6302 idx++;
6303 len++;
6304 rmesc++;
6305 continue;
6306 }
6307
6308 if (subtype == VSREPLACEALL) {
6309 while (idx < loc) {
6310 if (quotes && *idx == CTLESC)
6311 idx++;
6312 idx++;
6313 rmesc++;
6314 }
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00006315 } else {
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006316 idx = loc;
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00006317 }
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006318
6319 for (loc = repl; *loc; loc++) {
6320 restart_detect = stackblock();
6321 STPUTC(*loc, expdest);
6322 if (stackblock() != restart_detect)
6323 goto restart;
6324 len++;
6325 }
6326
6327 if (subtype == VSREPLACE) {
6328 while (*idx) {
6329 restart_detect = stackblock();
6330 STPUTC(*idx, expdest);
6331 if (stackblock() != restart_detect)
6332 goto restart;
6333 len++;
6334 idx++;
6335 }
6336 break;
6337 }
6338 }
6339
6340 /* We've put the replaced text into a buffer at workloc, now
6341 * move it to the right place and adjust the stack.
6342 */
6343 startp = stackblock() + startloc;
6344 STPUTC('\0', expdest);
6345 memmove(startp, stackblock() + workloc, len);
6346 startp[len++] = '\0';
6347 amount = expdest - ((char *)stackblock() + startloc + len - 1);
6348 STADJUST(-amount, expdest);
6349 return startp;
6350 }
6351#endif /* ENABLE_ASH_BASH_COMPAT */
6352
6353 subtype -= VSTRIMRIGHT;
6354#if DEBUG
6355 if (subtype < 0 || subtype > 7)
6356 abort();
6357#endif
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006358 /* zero = subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX */
6359 zero = subtype >> 1;
6360 /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
6361 scan = (subtype & 1) ^ zero ? scanleft : scanright;
6362
6363 loc = scan(startp, rmesc, rmescend, str, quotes, zero);
6364 if (loc) {
6365 if (zero) {
6366 memmove(startp, loc, str - loc);
6367 loc = startp + (str - loc) - 1;
6368 }
6369 *loc = '\0';
6370 amount = loc - expdest;
6371 STADJUST(amount, expdest);
6372 }
6373 return loc;
6374}
6375
6376/*
6377 * Add the value of a specialized variable to the stack string.
Denys Vlasenko4d8873f2009-10-04 03:14:41 +02006378 * name parameter (examples):
6379 * ash -c 'echo $1' name:'1='
6380 * ash -c 'echo $qwe' name:'qwe='
6381 * ash -c 'echo $$' name:'$='
6382 * ash -c 'echo ${$}' name:'$='
6383 * ash -c 'echo ${$##q}' name:'$=q'
6384 * ash -c 'echo ${#$}' name:'$='
6385 * note: examples with bad shell syntax:
6386 * ash -c 'echo ${#$1}' name:'$=1'
6387 * ash -c 'echo ${#1#}' name:'1=#'
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006388 */
Denys Vlasenkoadf922e2009-10-08 14:35:37 +02006389static NOINLINE ssize_t
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006390varvalue(char *name, int varflags, int flags, struct strlist *var_str_list)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006391{
6392 int num;
Mike Frysinger98c52642009-04-02 10:02:37 +00006393 const char *p;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006394 int i;
6395 int sep = 0;
6396 int sepq = 0;
6397 ssize_t len = 0;
6398 char **ap;
6399 int syntax;
6400 int quoted = varflags & VSQUOTE;
6401 int subtype = varflags & VSTYPE;
Denys Vlasenko1166d7b2009-09-16 16:20:31 +02006402 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006403
6404 if (quoted && (flags & EXP_FULL))
6405 sep = 1 << CHAR_BIT;
6406
6407 syntax = quoted ? DQSYNTAX : BASESYNTAX;
6408 switch (*name) {
6409 case '$':
6410 num = rootpid;
6411 goto numvar;
6412 case '?':
6413 num = exitstatus;
6414 goto numvar;
6415 case '#':
6416 num = shellparam.nparam;
6417 goto numvar;
6418 case '!':
6419 num = backgndpid;
6420 if (num == 0)
6421 return -1;
6422 numvar:
6423 len = cvtnum(num);
Denys Vlasenko4d8873f2009-10-04 03:14:41 +02006424 goto check_1char_name;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006425 case '-':
Mike Frysinger98c52642009-04-02 10:02:37 +00006426 expdest = makestrspace(NOPTS, expdest);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006427 for (i = NOPTS - 1; i >= 0; i--) {
6428 if (optlist[i]) {
Mike Frysinger98c52642009-04-02 10:02:37 +00006429 USTPUTC(optletters(i), expdest);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006430 len++;
6431 }
6432 }
Denys Vlasenko4d8873f2009-10-04 03:14:41 +02006433 check_1char_name:
6434#if 0
6435 /* handles cases similar to ${#$1} */
6436 if (name[2] != '\0')
6437 raise_error_syntax("bad substitution");
6438#endif
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006439 break;
6440 case '@':
6441 if (sep)
6442 goto param;
6443 /* fall through */
6444 case '*':
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00006445 sep = ifsset() ? signed_char2int(ifsval()[0]) : ' ';
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006446 if (quotes && (SIT(sep, syntax) == CCTL || SIT(sep, syntax) == CBACK))
6447 sepq = 1;
6448 param:
6449 ap = shellparam.p;
6450 if (!ap)
6451 return -1;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006452 while ((p = *ap++) != NULL) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006453 size_t partlen;
6454
6455 partlen = strlen(p);
6456 len += partlen;
6457
6458 if (!(subtype == VSPLUS || subtype == VSLENGTH))
6459 memtodest(p, partlen, syntax, quotes);
6460
6461 if (*ap && sep) {
6462 char *q;
6463
6464 len++;
6465 if (subtype == VSPLUS || subtype == VSLENGTH) {
6466 continue;
6467 }
6468 q = expdest;
6469 if (sepq)
6470 STPUTC(CTLESC, q);
6471 STPUTC(sep, q);
6472 expdest = q;
6473 }
6474 }
6475 return len;
6476 case '0':
6477 case '1':
6478 case '2':
6479 case '3':
6480 case '4':
6481 case '5':
6482 case '6':
6483 case '7':
6484 case '8':
6485 case '9':
Denys Vlasenkoa00329c2009-08-30 20:05:10 +02006486 num = atoi(name); /* number(name) fails on ${N#str} etc */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006487 if (num < 0 || num > shellparam.nparam)
6488 return -1;
6489 p = num ? shellparam.p[num - 1] : arg0;
6490 goto value;
6491 default:
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006492 /* NB: name has form "VAR=..." */
6493
6494 /* "A=a B=$A" case: var_str_list is a list of "A=a" strings
6495 * which should be considered before we check variables. */
6496 if (var_str_list) {
6497 unsigned name_len = (strchrnul(name, '=') - name) + 1;
6498 p = NULL;
6499 do {
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00006500 char *str, *eq;
6501 str = var_str_list->text;
6502 eq = strchr(str, '=');
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006503 if (!eq) /* stop at first non-assignment */
6504 break;
6505 eq++;
Denis Vlasenko6b06cb82008-05-15 21:30:45 +00006506 if (name_len == (unsigned)(eq - str)
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006507 && strncmp(str, name, name_len) == 0) {
6508 p = eq;
6509 /* goto value; - WRONG! */
6510 /* think "A=1 A=2 B=$A" */
6511 }
6512 var_str_list = var_str_list->next;
6513 } while (var_str_list);
6514 if (p)
6515 goto value;
6516 }
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006517 p = lookupvar(name);
6518 value:
6519 if (!p)
6520 return -1;
6521
6522 len = strlen(p);
6523 if (!(subtype == VSPLUS || subtype == VSLENGTH))
6524 memtodest(p, len, syntax, quotes);
6525 return len;
6526 }
6527
6528 if (subtype == VSPLUS || subtype == VSLENGTH)
6529 STADJUST(-len, expdest);
6530 return len;
6531}
6532
6533/*
6534 * Expand a variable, and return a pointer to the next character in the
6535 * input string.
6536 */
6537static char *
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006538evalvar(char *p, int flags, struct strlist *var_str_list)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006539{
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006540 char varflags;
6541 char subtype;
6542 char quoted;
6543 char easy;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006544 char *var;
6545 int patloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006546 int startloc;
6547 ssize_t varlen;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006548
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006549 varflags = (unsigned char) *p++;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006550 subtype = varflags & VSTYPE;
6551 quoted = varflags & VSQUOTE;
6552 var = p;
6553 easy = (!quoted || (*var == '@' && shellparam.nparam));
6554 startloc = expdest - (char *)stackblock();
6555 p = strchr(p, '=') + 1;
6556
6557 again:
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006558 varlen = varvalue(var, varflags, flags, var_str_list);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006559 if (varflags & VSNUL)
6560 varlen--;
6561
6562 if (subtype == VSPLUS) {
6563 varlen = -1 - varlen;
6564 goto vsplus;
6565 }
6566
6567 if (subtype == VSMINUS) {
6568 vsplus:
6569 if (varlen < 0) {
6570 argstr(
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006571 p, flags | EXP_TILDE |
6572 (quoted ? EXP_QWORD : EXP_WORD),
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006573 var_str_list
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006574 );
6575 goto end;
6576 }
6577 if (easy)
6578 goto record;
6579 goto end;
6580 }
6581
6582 if (subtype == VSASSIGN || subtype == VSQUESTION) {
6583 if (varlen < 0) {
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006584 if (subevalvar(p, var, /* strloc: */ 0,
6585 subtype, startloc, varflags,
6586 /* quotes: */ 0,
6587 var_str_list)
6588 ) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006589 varflags &= ~VSNUL;
6590 /*
6591 * Remove any recorded regions beyond
6592 * start of variable
6593 */
6594 removerecordregions(startloc);
6595 goto again;
6596 }
6597 goto end;
6598 }
6599 if (easy)
6600 goto record;
6601 goto end;
6602 }
6603
6604 if (varlen < 0 && uflag)
6605 varunset(p, var, 0, 0);
6606
6607 if (subtype == VSLENGTH) {
6608 cvtnum(varlen > 0 ? varlen : 0);
6609 goto record;
6610 }
6611
6612 if (subtype == VSNORMAL) {
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006613 if (easy)
6614 goto record;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006615 goto end;
6616 }
6617
6618#if DEBUG
6619 switch (subtype) {
6620 case VSTRIMLEFT:
6621 case VSTRIMLEFTMAX:
6622 case VSTRIMRIGHT:
6623 case VSTRIMRIGHTMAX:
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006624#if ENABLE_ASH_BASH_COMPAT
6625 case VSSUBSTR:
6626 case VSREPLACE:
6627 case VSREPLACEALL:
6628#endif
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006629 break;
6630 default:
6631 abort();
6632 }
6633#endif
6634
6635 if (varlen >= 0) {
6636 /*
6637 * Terminate the string and start recording the pattern
6638 * right after it
6639 */
6640 STPUTC('\0', expdest);
6641 patloc = expdest - (char *)stackblock();
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006642 if (0 == subevalvar(p, /* str: */ NULL, patloc, subtype,
6643 startloc, varflags,
Denys Vlasenko1166d7b2009-09-16 16:20:31 +02006644//TODO: | EXP_REDIR too? All other such places do it too
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006645 /* quotes: */ flags & (EXP_FULL | EXP_CASE),
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006646 var_str_list)
6647 ) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006648 int amount = expdest - (
6649 (char *)stackblock() + patloc - 1
6650 );
6651 STADJUST(-amount, expdest);
6652 }
6653 /* Remove any recorded regions beyond start of variable */
6654 removerecordregions(startloc);
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006655 record:
6656 recordregion(startloc, expdest - (char *)stackblock(), quoted);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006657 }
6658
6659 end:
6660 if (subtype != VSNORMAL) { /* skip to end of alternative */
6661 int nesting = 1;
6662 for (;;) {
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006663 char c = *p++;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006664 if (c == CTLESC)
6665 p++;
6666 else if (c == CTLBACKQ || c == (CTLBACKQ|CTLQUOTE)) {
6667 if (varlen >= 0)
6668 argbackq = argbackq->next;
6669 } else if (c == CTLVAR) {
6670 if ((*p++ & VSTYPE) != VSNORMAL)
6671 nesting++;
6672 } else if (c == CTLENDVAR) {
6673 if (--nesting == 0)
6674 break;
6675 }
6676 }
6677 }
6678 return p;
6679}
6680
6681/*
6682 * Break the argument string into pieces based upon IFS and add the
6683 * strings to the argument list. The regions of the string to be
6684 * searched for IFS characters have been stored by recordregion.
6685 */
6686static void
6687ifsbreakup(char *string, struct arglist *arglist)
6688{
6689 struct ifsregion *ifsp;
6690 struct strlist *sp;
6691 char *start;
6692 char *p;
6693 char *q;
6694 const char *ifs, *realifs;
6695 int ifsspc;
6696 int nulonly;
6697
6698 start = string;
6699 if (ifslastp != NULL) {
6700 ifsspc = 0;
6701 nulonly = 0;
6702 realifs = ifsset() ? ifsval() : defifs;
6703 ifsp = &ifsfirst;
6704 do {
6705 p = string + ifsp->begoff;
6706 nulonly = ifsp->nulonly;
6707 ifs = nulonly ? nullstr : realifs;
6708 ifsspc = 0;
6709 while (p < string + ifsp->endoff) {
6710 q = p;
6711 if (*p == CTLESC)
6712 p++;
6713 if (!strchr(ifs, *p)) {
6714 p++;
6715 continue;
6716 }
6717 if (!nulonly)
6718 ifsspc = (strchr(defifs, *p) != NULL);
6719 /* Ignore IFS whitespace at start */
6720 if (q == start && ifsspc) {
6721 p++;
6722 start = p;
6723 continue;
6724 }
6725 *q = '\0';
Denis Vlasenko597906c2008-02-20 16:38:54 +00006726 sp = stzalloc(sizeof(*sp));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006727 sp->text = start;
6728 *arglist->lastp = sp;
6729 arglist->lastp = &sp->next;
6730 p++;
6731 if (!nulonly) {
6732 for (;;) {
6733 if (p >= string + ifsp->endoff) {
6734 break;
6735 }
6736 q = p;
6737 if (*p == CTLESC)
6738 p++;
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +00006739 if (strchr(ifs, *p) == NULL) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006740 p = q;
6741 break;
Denis Vlasenko597906c2008-02-20 16:38:54 +00006742 }
6743 if (strchr(defifs, *p) == NULL) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006744 if (ifsspc) {
6745 p++;
6746 ifsspc = 0;
6747 } else {
6748 p = q;
6749 break;
6750 }
6751 } else
6752 p++;
6753 }
6754 }
6755 start = p;
6756 } /* while */
6757 ifsp = ifsp->next;
6758 } while (ifsp != NULL);
6759 if (nulonly)
6760 goto add;
6761 }
6762
6763 if (!*start)
6764 return;
6765
6766 add:
Denis Vlasenko597906c2008-02-20 16:38:54 +00006767 sp = stzalloc(sizeof(*sp));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006768 sp->text = start;
6769 *arglist->lastp = sp;
6770 arglist->lastp = &sp->next;
6771}
6772
6773static void
6774ifsfree(void)
6775{
6776 struct ifsregion *p;
6777
6778 INT_OFF;
6779 p = ifsfirst.next;
6780 do {
6781 struct ifsregion *ifsp;
6782 ifsp = p->next;
6783 free(p);
6784 p = ifsp;
6785 } while (p);
6786 ifslastp = NULL;
6787 ifsfirst.next = NULL;
6788 INT_ON;
6789}
6790
6791/*
6792 * Add a file name to the list.
6793 */
6794static void
6795addfname(const char *name)
6796{
6797 struct strlist *sp;
6798
Denis Vlasenko597906c2008-02-20 16:38:54 +00006799 sp = stzalloc(sizeof(*sp));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006800 sp->text = ststrdup(name);
6801 *exparg.lastp = sp;
6802 exparg.lastp = &sp->next;
6803}
6804
6805static char *expdir;
6806
6807/*
6808 * Do metacharacter (i.e. *, ?, [...]) expansion.
6809 */
6810static void
6811expmeta(char *enddir, char *name)
6812{
6813 char *p;
6814 const char *cp;
6815 char *start;
6816 char *endname;
6817 int metaflag;
6818 struct stat statb;
6819 DIR *dirp;
6820 struct dirent *dp;
6821 int atend;
6822 int matchdot;
6823
6824 metaflag = 0;
6825 start = name;
6826 for (p = name; *p; p++) {
6827 if (*p == '*' || *p == '?')
6828 metaflag = 1;
6829 else if (*p == '[') {
6830 char *q = p + 1;
6831 if (*q == '!')
6832 q++;
6833 for (;;) {
6834 if (*q == '\\')
6835 q++;
6836 if (*q == '/' || *q == '\0')
6837 break;
6838 if (*++q == ']') {
6839 metaflag = 1;
6840 break;
6841 }
6842 }
6843 } else if (*p == '\\')
6844 p++;
6845 else if (*p == '/') {
6846 if (metaflag)
6847 goto out;
6848 start = p + 1;
6849 }
6850 }
6851 out:
6852 if (metaflag == 0) { /* we've reached the end of the file name */
6853 if (enddir != expdir)
6854 metaflag++;
6855 p = name;
6856 do {
6857 if (*p == '\\')
6858 p++;
6859 *enddir++ = *p;
6860 } while (*p++);
6861 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
6862 addfname(expdir);
6863 return;
6864 }
6865 endname = p;
6866 if (name < start) {
6867 p = name;
6868 do {
6869 if (*p == '\\')
6870 p++;
6871 *enddir++ = *p++;
6872 } while (p < start);
6873 }
6874 if (enddir == expdir) {
6875 cp = ".";
6876 } else if (enddir == expdir + 1 && *expdir == '/') {
6877 cp = "/";
6878 } else {
6879 cp = expdir;
6880 enddir[-1] = '\0';
6881 }
6882 dirp = opendir(cp);
6883 if (dirp == NULL)
6884 return;
6885 if (enddir != expdir)
6886 enddir[-1] = '/';
6887 if (*endname == 0) {
6888 atend = 1;
6889 } else {
6890 atend = 0;
6891 *endname++ = '\0';
6892 }
6893 matchdot = 0;
6894 p = start;
6895 if (*p == '\\')
6896 p++;
6897 if (*p == '.')
6898 matchdot++;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006899 while (!pending_int && (dp = readdir(dirp)) != NULL) {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00006900 if (dp->d_name[0] == '.' && !matchdot)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006901 continue;
6902 if (pmatch(start, dp->d_name)) {
6903 if (atend) {
6904 strcpy(enddir, dp->d_name);
6905 addfname(expdir);
6906 } else {
6907 for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
6908 continue;
6909 p[-1] = '/';
6910 expmeta(p, endname);
6911 }
6912 }
6913 }
6914 closedir(dirp);
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00006915 if (!atend)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006916 endname[-1] = '/';
6917}
6918
6919static struct strlist *
6920msort(struct strlist *list, int len)
6921{
6922 struct strlist *p, *q = NULL;
6923 struct strlist **lpp;
6924 int half;
6925 int n;
6926
6927 if (len <= 1)
6928 return list;
6929 half = len >> 1;
6930 p = list;
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +00006931 for (n = half; --n >= 0;) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006932 q = p;
6933 p = p->next;
6934 }
6935 q->next = NULL; /* terminate first half of list */
6936 q = msort(list, half); /* sort first half of list */
6937 p = msort(p, len - half); /* sort second half */
6938 lpp = &list;
6939 for (;;) {
6940#if ENABLE_LOCALE_SUPPORT
6941 if (strcoll(p->text, q->text) < 0)
6942#else
6943 if (strcmp(p->text, q->text) < 0)
6944#endif
6945 {
6946 *lpp = p;
6947 lpp = &p->next;
6948 p = *lpp;
6949 if (p == NULL) {
6950 *lpp = q;
6951 break;
6952 }
6953 } else {
6954 *lpp = q;
6955 lpp = &q->next;
6956 q = *lpp;
6957 if (q == NULL) {
6958 *lpp = p;
6959 break;
6960 }
6961 }
6962 }
6963 return list;
6964}
6965
6966/*
6967 * Sort the results of file name expansion. It calculates the number of
6968 * strings to sort and then calls msort (short for merge sort) to do the
6969 * work.
6970 */
6971static struct strlist *
6972expsort(struct strlist *str)
6973{
6974 int len;
6975 struct strlist *sp;
6976
6977 len = 0;
6978 for (sp = str; sp; sp = sp->next)
6979 len++;
6980 return msort(str, len);
6981}
6982
6983static void
Denis Vlasenko68404f12008-03-17 09:00:54 +00006984expandmeta(struct strlist *str /*, int flag*/)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006985{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00006986 static const char metachars[] ALIGN1 = {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006987 '*', '?', '[', 0
6988 };
6989 /* TODO - EXP_REDIR */
6990
6991 while (str) {
6992 struct strlist **savelastp;
6993 struct strlist *sp;
6994 char *p;
6995
6996 if (fflag)
6997 goto nometa;
6998 if (!strpbrk(str->text, metachars))
6999 goto nometa;
7000 savelastp = exparg.lastp;
7001
7002 INT_OFF;
7003 p = preglob(str->text, 0, RMESCAPE_ALLOC | RMESCAPE_HEAP);
7004 {
7005 int i = strlen(str->text);
7006 expdir = ckmalloc(i < 2048 ? 2048 : i); /* XXX */
7007 }
7008
7009 expmeta(expdir, p);
7010 free(expdir);
7011 if (p != str->text)
7012 free(p);
7013 INT_ON;
7014 if (exparg.lastp == savelastp) {
7015 /*
7016 * no matches
7017 */
7018 nometa:
7019 *exparg.lastp = str;
Denys Vlasenkob6c84342009-08-29 20:23:20 +02007020 rmescapes(str->text, 0);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007021 exparg.lastp = &str->next;
7022 } else {
7023 *exparg.lastp = NULL;
7024 *savelastp = sp = expsort(*savelastp);
7025 while (sp->next != NULL)
7026 sp = sp->next;
7027 exparg.lastp = &sp->next;
7028 }
7029 str = str->next;
7030 }
7031}
7032
7033/*
7034 * Perform variable substitution and command substitution on an argument,
7035 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
7036 * perform splitting and file name expansion. When arglist is NULL, perform
7037 * here document expansion.
7038 */
7039static void
7040expandarg(union node *arg, struct arglist *arglist, int flag)
7041{
7042 struct strlist *sp;
7043 char *p;
7044
7045 argbackq = arg->narg.backquote;
7046 STARTSTACKSTR(expdest);
7047 ifsfirst.next = NULL;
7048 ifslastp = NULL;
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00007049 argstr(arg->narg.text, flag,
7050 /* var_str_list: */ arglist ? arglist->list : NULL);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007051 p = _STPUTC('\0', expdest);
7052 expdest = p - 1;
7053 if (arglist == NULL) {
7054 return; /* here document expanded */
7055 }
7056 p = grabstackstr(p);
7057 exparg.lastp = &exparg.list;
7058 /*
7059 * TODO - EXP_REDIR
7060 */
7061 if (flag & EXP_FULL) {
7062 ifsbreakup(p, &exparg);
7063 *exparg.lastp = NULL;
7064 exparg.lastp = &exparg.list;
Denis Vlasenko68404f12008-03-17 09:00:54 +00007065 expandmeta(exparg.list /*, flag*/);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007066 } else {
7067 if (flag & EXP_REDIR) /*XXX - for now, just remove escapes */
Denys Vlasenkob6c84342009-08-29 20:23:20 +02007068 rmescapes(p, 0);
Denis Vlasenko597906c2008-02-20 16:38:54 +00007069 sp = stzalloc(sizeof(*sp));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007070 sp->text = p;
7071 *exparg.lastp = sp;
7072 exparg.lastp = &sp->next;
7073 }
7074 if (ifsfirst.next)
7075 ifsfree();
7076 *exparg.lastp = NULL;
7077 if (exparg.list) {
7078 *arglist->lastp = exparg.list;
7079 arglist->lastp = exparg.lastp;
7080 }
7081}
7082
7083/*
7084 * Expand shell variables and backquotes inside a here document.
7085 */
7086static void
7087expandhere(union node *arg, int fd)
7088{
7089 herefd = fd;
7090 expandarg(arg, (struct arglist *)NULL, 0);
7091 full_write(fd, stackblock(), expdest - (char *)stackblock());
7092}
7093
7094/*
7095 * Returns true if the pattern matches the string.
7096 */
7097static int
7098patmatch(char *pattern, const char *string)
7099{
7100 return pmatch(preglob(pattern, 0, 0), string);
7101}
7102
7103/*
7104 * See if a pattern matches in a case statement.
7105 */
7106static int
7107casematch(union node *pattern, char *val)
7108{
7109 struct stackmark smark;
7110 int result;
7111
7112 setstackmark(&smark);
7113 argbackq = pattern->narg.backquote;
7114 STARTSTACKSTR(expdest);
7115 ifslastp = NULL;
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00007116 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE,
7117 /* var_str_list: */ NULL);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007118 STACKSTRNUL(expdest);
7119 result = patmatch(stackblock(), val);
7120 popstackmark(&smark);
7121 return result;
7122}
7123
7124
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007125/* ============ find_command */
7126
7127struct builtincmd {
7128 const char *name;
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007129 int (*builtin)(int, char **) FAST_FUNC;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007130 /* unsigned flags; */
7131};
7132#define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
Denis Vlasenkoe26b2782008-02-12 07:40:29 +00007133/* "regular" builtins always take precedence over commands,
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007134 * regardless of PATH=....%builtin... position */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007135#define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007136#define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007137
7138struct cmdentry {
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00007139 smallint cmdtype; /* CMDxxx */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007140 union param {
7141 int index;
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00007142 /* index >= 0 for commands without path (slashes) */
7143 /* (TODO: what exactly does the value mean? PATH position?) */
7144 /* index == -1 for commands with slashes */
7145 /* index == (-2 - applet_no) for NOFORK applets */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007146 const struct builtincmd *cmd;
7147 struct funcnode *func;
7148 } u;
7149};
7150/* values of cmdtype */
7151#define CMDUNKNOWN -1 /* no entry in table for command */
7152#define CMDNORMAL 0 /* command is an executable program */
7153#define CMDFUNCTION 1 /* command is a shell function */
7154#define CMDBUILTIN 2 /* command is a shell builtin */
7155
7156/* action to find_command() */
7157#define DO_ERR 0x01 /* prints errors */
7158#define DO_ABS 0x02 /* checks absolute paths */
7159#define DO_NOFUNC 0x04 /* don't return shell functions, for command */
7160#define DO_ALTPATH 0x08 /* using alternate path */
7161#define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
7162
7163static void find_command(char *, struct cmdentry *, int, const char *);
7164
7165
7166/* ============ Hashing commands */
7167
7168/*
7169 * When commands are first encountered, they are entered in a hash table.
7170 * This ensures that a full path search will not have to be done for them
7171 * on each invocation.
7172 *
7173 * We should investigate converting to a linear search, even though that
7174 * would make the command name "hash" a misnomer.
7175 */
7176
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007177struct tblentry {
7178 struct tblentry *next; /* next entry in hash chain */
7179 union param param; /* definition of builtin function */
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00007180 smallint cmdtype; /* CMDxxx */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007181 char rehash; /* if set, cd done since entry created */
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007182 char cmdname[1]; /* name of command */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007183};
7184
Denis Vlasenko01631112007-12-16 17:20:38 +00007185static struct tblentry **cmdtable;
7186#define INIT_G_cmdtable() do { \
7187 cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
7188} while (0)
7189
7190static int builtinloc = -1; /* index in path of %builtin, or -1 */
7191
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007192
7193static void
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00007194tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) char *cmd, char **argv, char **envp)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007195{
7196 int repeated = 0;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007197
Denis Vlasenko80d14be2007-04-10 23:03:30 +00007198#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007199 if (applet_no >= 0) {
Denis Vlasenkob7304742008-10-20 08:15:51 +00007200 if (APPLET_IS_NOEXEC(applet_no)) {
7201 while (*envp)
7202 putenv(*envp++);
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007203 run_applet_no_and_exit(applet_no, argv);
Denis Vlasenkob7304742008-10-20 08:15:51 +00007204 }
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007205 /* re-exec ourselves with the new arguments */
7206 execve(bb_busybox_exec_path, argv, envp);
7207 /* If they called chroot or otherwise made the binary no longer
7208 * executable, fall through */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007209 }
7210#endif
7211
7212 repeat:
7213#ifdef SYSV
7214 do {
7215 execve(cmd, argv, envp);
7216 } while (errno == EINTR);
7217#else
7218 execve(cmd, argv, envp);
7219#endif
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007220 if (repeated) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007221 free(argv);
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007222 return;
7223 }
7224 if (errno == ENOEXEC) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007225 char **ap;
7226 char **new;
7227
7228 for (ap = argv; *ap; ap++)
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007229 continue;
7230 ap = new = ckmalloc((ap - argv + 2) * sizeof(ap[0]));
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007231 ap[1] = cmd;
Denis Vlasenkoc44ab012007-04-09 03:11:58 +00007232 ap[0] = cmd = (char *)DEFAULT_SHELL;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007233 ap += 2;
7234 argv++;
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007235 while ((*ap++ = *argv++) != NULL)
Denis Vlasenko597906c2008-02-20 16:38:54 +00007236 continue;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007237 argv = new;
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007238 repeated++;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007239 goto repeat;
7240 }
7241}
7242
7243/*
7244 * Exec a program. Never returns. If you change this routine, you may
7245 * have to change the find_command routine as well.
7246 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00007247static void shellexec(char **, const char *, int) NORETURN;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007248static void
7249shellexec(char **argv, const char *path, int idx)
7250{
7251 char *cmdname;
7252 int e;
7253 char **envp;
7254 int exerrno;
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007255#if ENABLE_FEATURE_SH_STANDALONE
7256 int applet_no = -1;
7257#endif
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007258
Denis Vlasenko34c73c42008-08-16 11:48:02 +00007259 clearredir(/*drop:*/ 1);
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007260 envp = listvars(VEXPORT, VUNSET, 0);
7261 if (strchr(argv[0], '/') != NULL
Denis Vlasenko80d14be2007-04-10 23:03:30 +00007262#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007263 || (applet_no = find_applet_by_name(argv[0])) >= 0
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007264#endif
7265 ) {
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00007266 tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) argv[0], argv, envp);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007267 e = errno;
7268 } else {
7269 e = ENOENT;
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02007270 while ((cmdname = path_advance(&path, argv[0])) != NULL) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007271 if (--idx < 0 && pathopt == NULL) {
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00007272 tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007273 if (errno != ENOENT && errno != ENOTDIR)
7274 e = errno;
7275 }
7276 stunalloc(cmdname);
7277 }
7278 }
7279
7280 /* Map to POSIX errors */
7281 switch (e) {
7282 case EACCES:
7283 exerrno = 126;
7284 break;
7285 case ENOENT:
7286 exerrno = 127;
7287 break;
7288 default:
7289 exerrno = 2;
7290 break;
7291 }
7292 exitstatus = exerrno;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02007293 TRACE(("shellexec failed for %s, errno %d, suppress_int %d\n",
7294 argv[0], e, suppress_int));
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007295 ash_msg_and_raise(EXEXEC, "%s: %s", argv[0], errmsg(e, "not found"));
7296 /* NOTREACHED */
7297}
7298
7299static void
7300printentry(struct tblentry *cmdp)
7301{
7302 int idx;
7303 const char *path;
7304 char *name;
7305
7306 idx = cmdp->param.index;
7307 path = pathval();
7308 do {
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02007309 name = path_advance(&path, cmdp->cmdname);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007310 stunalloc(name);
7311 } while (--idx >= 0);
7312 out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
7313}
7314
7315/*
7316 * Clear out command entries. The argument specifies the first entry in
7317 * PATH which has changed.
7318 */
7319static void
7320clearcmdentry(int firstchange)
7321{
7322 struct tblentry **tblp;
7323 struct tblentry **pp;
7324 struct tblentry *cmdp;
7325
7326 INT_OFF;
7327 for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
7328 pp = tblp;
7329 while ((cmdp = *pp) != NULL) {
7330 if ((cmdp->cmdtype == CMDNORMAL &&
7331 cmdp->param.index >= firstchange)
7332 || (cmdp->cmdtype == CMDBUILTIN &&
7333 builtinloc >= firstchange)
7334 ) {
7335 *pp = cmdp->next;
7336 free(cmdp);
7337 } else {
7338 pp = &cmdp->next;
7339 }
7340 }
7341 }
7342 INT_ON;
7343}
7344
7345/*
7346 * Locate a command in the command hash table. If "add" is nonzero,
7347 * add the command to the table if it is not already present. The
7348 * variable "lastcmdentry" is set to point to the address of the link
7349 * pointing to the entry, so that delete_cmd_entry can delete the
7350 * entry.
7351 *
7352 * Interrupts must be off if called with add != 0.
7353 */
7354static struct tblentry **lastcmdentry;
7355
7356static struct tblentry *
7357cmdlookup(const char *name, int add)
7358{
7359 unsigned int hashval;
7360 const char *p;
7361 struct tblentry *cmdp;
7362 struct tblentry **pp;
7363
7364 p = name;
7365 hashval = (unsigned char)*p << 4;
7366 while (*p)
7367 hashval += (unsigned char)*p++;
7368 hashval &= 0x7FFF;
7369 pp = &cmdtable[hashval % CMDTABLESIZE];
7370 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7371 if (strcmp(cmdp->cmdname, name) == 0)
7372 break;
7373 pp = &cmdp->next;
7374 }
7375 if (add && cmdp == NULL) {
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007376 cmdp = *pp = ckzalloc(sizeof(struct tblentry)
7377 + strlen(name)
7378 /* + 1 - already done because
7379 * tblentry::cmdname is char[1] */);
Denis Vlasenko597906c2008-02-20 16:38:54 +00007380 /*cmdp->next = NULL; - ckzalloc did it */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007381 cmdp->cmdtype = CMDUNKNOWN;
7382 strcpy(cmdp->cmdname, name);
7383 }
7384 lastcmdentry = pp;
7385 return cmdp;
7386}
7387
7388/*
7389 * Delete the command entry returned on the last lookup.
7390 */
7391static void
7392delete_cmd_entry(void)
7393{
7394 struct tblentry *cmdp;
7395
7396 INT_OFF;
7397 cmdp = *lastcmdentry;
7398 *lastcmdentry = cmdp->next;
7399 if (cmdp->cmdtype == CMDFUNCTION)
7400 freefunc(cmdp->param.func);
7401 free(cmdp);
7402 INT_ON;
7403}
7404
7405/*
7406 * Add a new command entry, replacing any existing command entry for
7407 * the same name - except special builtins.
7408 */
7409static void
7410addcmdentry(char *name, struct cmdentry *entry)
7411{
7412 struct tblentry *cmdp;
7413
7414 cmdp = cmdlookup(name, 1);
7415 if (cmdp->cmdtype == CMDFUNCTION) {
7416 freefunc(cmdp->param.func);
7417 }
7418 cmdp->cmdtype = entry->cmdtype;
7419 cmdp->param = entry->u;
7420 cmdp->rehash = 0;
7421}
7422
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007423static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00007424hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007425{
7426 struct tblentry **pp;
7427 struct tblentry *cmdp;
7428 int c;
7429 struct cmdentry entry;
7430 char *name;
7431
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007432 if (nextopt("r") != '\0') {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007433 clearcmdentry(0);
7434 return 0;
7435 }
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007436
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007437 if (*argptr == NULL) {
7438 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7439 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7440 if (cmdp->cmdtype == CMDNORMAL)
7441 printentry(cmdp);
7442 }
7443 }
7444 return 0;
7445 }
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007446
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007447 c = 0;
7448 while ((name = *argptr) != NULL) {
7449 cmdp = cmdlookup(name, 0);
7450 if (cmdp != NULL
7451 && (cmdp->cmdtype == CMDNORMAL
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007452 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
7453 ) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007454 delete_cmd_entry();
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007455 }
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007456 find_command(name, &entry, DO_ERR, pathval());
7457 if (entry.cmdtype == CMDUNKNOWN)
7458 c = 1;
7459 argptr++;
7460 }
7461 return c;
7462}
7463
7464/*
7465 * Called when a cd is done. Marks all commands so the next time they
7466 * are executed they will be rehashed.
7467 */
7468static void
7469hashcd(void)
7470{
7471 struct tblentry **pp;
7472 struct tblentry *cmdp;
7473
7474 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7475 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007476 if (cmdp->cmdtype == CMDNORMAL
7477 || (cmdp->cmdtype == CMDBUILTIN
7478 && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
7479 && builtinloc > 0)
7480 ) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007481 cmdp->rehash = 1;
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007482 }
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007483 }
7484 }
7485}
7486
7487/*
7488 * Fix command hash table when PATH changed.
7489 * Called before PATH is changed. The argument is the new value of PATH;
7490 * pathval() still returns the old value at this point.
7491 * Called with interrupts off.
7492 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007493static void FAST_FUNC
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007494changepath(const char *new)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007495{
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007496 const char *old;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007497 int firstchange;
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007498 int idx;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007499 int idx_bltin;
7500
7501 old = pathval();
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007502 firstchange = 9999; /* assume no change */
7503 idx = 0;
7504 idx_bltin = -1;
7505 for (;;) {
7506 if (*old != *new) {
7507 firstchange = idx;
7508 if ((*old == '\0' && *new == ':')
7509 || (*old == ':' && *new == '\0'))
7510 firstchange++;
7511 old = new; /* ignore subsequent differences */
7512 }
7513 if (*new == '\0')
7514 break;
7515 if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
7516 idx_bltin = idx;
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007517 if (*new == ':')
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007518 idx++;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007519 new++, old++;
7520 }
7521 if (builtinloc < 0 && idx_bltin >= 0)
7522 builtinloc = idx_bltin; /* zap builtins */
7523 if (builtinloc >= 0 && idx_bltin < 0)
7524 firstchange = 0;
7525 clearcmdentry(firstchange);
7526 builtinloc = idx_bltin;
7527}
7528
7529#define TEOF 0
7530#define TNL 1
7531#define TREDIR 2
7532#define TWORD 3
7533#define TSEMI 4
7534#define TBACKGND 5
7535#define TAND 6
7536#define TOR 7
7537#define TPIPE 8
7538#define TLP 9
7539#define TRP 10
7540#define TENDCASE 11
7541#define TENDBQUOTE 12
7542#define TNOT 13
7543#define TCASE 14
7544#define TDO 15
7545#define TDONE 16
7546#define TELIF 17
7547#define TELSE 18
7548#define TESAC 19
7549#define TFI 20
7550#define TFOR 21
7551#define TIF 22
7552#define TIN 23
7553#define TTHEN 24
7554#define TUNTIL 25
7555#define TWHILE 26
7556#define TBEGIN 27
7557#define TEND 28
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007558typedef smallint token_id_t;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007559
7560/* first char is indicating which tokens mark the end of a list */
7561static const char *const tokname_array[] = {
7562 "\1end of file",
7563 "\0newline",
7564 "\0redirection",
7565 "\0word",
7566 "\0;",
7567 "\0&",
7568 "\0&&",
7569 "\0||",
7570 "\0|",
7571 "\0(",
7572 "\1)",
7573 "\1;;",
7574 "\1`",
7575#define KWDOFFSET 13
7576 /* the following are keywords */
7577 "\0!",
7578 "\0case",
7579 "\1do",
7580 "\1done",
7581 "\1elif",
7582 "\1else",
7583 "\1esac",
7584 "\1fi",
7585 "\0for",
7586 "\0if",
7587 "\0in",
7588 "\1then",
7589 "\0until",
7590 "\0while",
7591 "\0{",
7592 "\1}",
7593};
7594
7595static const char *
7596tokname(int tok)
7597{
7598 static char buf[16];
7599
Denis Vlasenko240a1cf2007-04-08 16:07:02 +00007600//try this:
7601//if (tok < TSEMI) return tokname_array[tok] + 1;
7602//sprintf(buf, "\"%s\"", tokname_array[tok] + 1);
7603//return buf;
7604
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007605 if (tok >= TSEMI)
7606 buf[0] = '"';
7607 sprintf(buf + (tok >= TSEMI), "%s%c",
7608 tokname_array[tok] + 1, (tok >= TSEMI ? '"' : 0));
7609 return buf;
7610}
7611
7612/* Wrapper around strcmp for qsort/bsearch/... */
7613static int
7614pstrcmp(const void *a, const void *b)
7615{
Denis Vlasenko240a1cf2007-04-08 16:07:02 +00007616 return strcmp((char*) a, (*(char**) b) + 1);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007617}
7618
7619static const char *const *
7620findkwd(const char *s)
7621{
7622 return bsearch(s, tokname_array + KWDOFFSET,
Denis Vlasenko80b8b392007-06-25 10:55:35 +00007623 ARRAY_SIZE(tokname_array) - KWDOFFSET,
7624 sizeof(tokname_array[0]), pstrcmp);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007625}
7626
7627/*
7628 * Locate and print what a word is...
7629 */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007630static int
7631describe_command(char *command, int describe_command_verbose)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007632{
7633 struct cmdentry entry;
7634 struct tblentry *cmdp;
7635#if ENABLE_ASH_ALIAS
7636 const struct alias *ap;
7637#endif
7638 const char *path = pathval();
7639
7640 if (describe_command_verbose) {
7641 out1str(command);
7642 }
7643
7644 /* First look at the keywords */
7645 if (findkwd(command)) {
7646 out1str(describe_command_verbose ? " is a shell keyword" : command);
7647 goto out;
7648 }
7649
7650#if ENABLE_ASH_ALIAS
7651 /* Then look at the aliases */
7652 ap = lookupalias(command, 0);
7653 if (ap != NULL) {
Denis Vlasenko46846e22007-05-20 13:08:31 +00007654 if (!describe_command_verbose) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007655 out1str("alias ");
7656 printalias(ap);
7657 return 0;
7658 }
Denis Vlasenko46846e22007-05-20 13:08:31 +00007659 out1fmt(" is an alias for %s", ap->val);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007660 goto out;
7661 }
7662#endif
7663 /* Then check if it is a tracked alias */
7664 cmdp = cmdlookup(command, 0);
7665 if (cmdp != NULL) {
7666 entry.cmdtype = cmdp->cmdtype;
7667 entry.u = cmdp->param;
7668 } else {
7669 /* Finally use brute force */
7670 find_command(command, &entry, DO_ABS, path);
7671 }
7672
7673 switch (entry.cmdtype) {
7674 case CMDNORMAL: {
7675 int j = entry.u.index;
7676 char *p;
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00007677 if (j < 0) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007678 p = command;
7679 } else {
7680 do {
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02007681 p = path_advance(&path, command);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007682 stunalloc(p);
7683 } while (--j >= 0);
7684 }
7685 if (describe_command_verbose) {
7686 out1fmt(" is%s %s",
7687 (cmdp ? " a tracked alias for" : nullstr), p
7688 );
7689 } else {
7690 out1str(p);
7691 }
7692 break;
7693 }
7694
7695 case CMDFUNCTION:
7696 if (describe_command_verbose) {
7697 out1str(" is a shell function");
7698 } else {
7699 out1str(command);
7700 }
7701 break;
7702
7703 case CMDBUILTIN:
7704 if (describe_command_verbose) {
7705 out1fmt(" is a %sshell builtin",
7706 IS_BUILTIN_SPECIAL(entry.u.cmd) ?
7707 "special " : nullstr
7708 );
7709 } else {
7710 out1str(command);
7711 }
7712 break;
7713
7714 default:
7715 if (describe_command_verbose) {
7716 out1str(": not found\n");
7717 }
7718 return 127;
7719 }
7720 out:
7721 outstr("\n", stdout);
7722 return 0;
7723}
7724
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007725static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00007726typecmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007727{
Denis Vlasenko46846e22007-05-20 13:08:31 +00007728 int i = 1;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007729 int err = 0;
Denis Vlasenko46846e22007-05-20 13:08:31 +00007730 int verbose = 1;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007731
Denis Vlasenko46846e22007-05-20 13:08:31 +00007732 /* type -p ... ? (we don't bother checking for 'p') */
Denis Vlasenko1fc62382007-06-25 22:55:34 +00007733 if (argv[1] && argv[1][0] == '-') {
Denis Vlasenko46846e22007-05-20 13:08:31 +00007734 i++;
7735 verbose = 0;
7736 }
Denis Vlasenko68404f12008-03-17 09:00:54 +00007737 while (argv[i]) {
Denis Vlasenko46846e22007-05-20 13:08:31 +00007738 err |= describe_command(argv[i++], verbose);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007739 }
7740 return err;
7741}
7742
7743#if ENABLE_ASH_CMDCMD
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007744static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00007745commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007746{
7747 int c;
7748 enum {
7749 VERIFY_BRIEF = 1,
7750 VERIFY_VERBOSE = 2,
7751 } verify = 0;
7752
7753 while ((c = nextopt("pvV")) != '\0')
7754 if (c == 'V')
7755 verify |= VERIFY_VERBOSE;
7756 else if (c == 'v')
7757 verify |= VERIFY_BRIEF;
7758#if DEBUG
7759 else if (c != 'p')
7760 abort();
7761#endif
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00007762 /* Mimic bash: just "command -v" doesn't complain, it's a nop */
7763 if (verify && (*argptr != NULL)) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007764 return describe_command(*argptr, verify - VERIFY_BRIEF);
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00007765 }
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007766
7767 return 0;
7768}
7769#endif
7770
7771
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007772/* ============ eval.c */
Eric Andersencb57d552001-06-28 07:25:16 +00007773
Denis Vlasenko340299a2008-11-21 10:36:36 +00007774static int funcblocksize; /* size of structures in function */
7775static int funcstringsize; /* size of strings in node */
7776static void *funcblock; /* block to allocate function from */
7777static char *funcstring; /* block to allocate strings from */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007778
Eric Andersencb57d552001-06-28 07:25:16 +00007779/* flags in argument to evaltree */
Denis Vlasenko340299a2008-11-21 10:36:36 +00007780#define EV_EXIT 01 /* exit after evaluating tree */
7781#define EV_TESTED 02 /* exit status is checked; ignore -e flag */
Eric Andersenc470f442003-07-28 09:56:35 +00007782#define EV_BACKCMD 04 /* command executing within back quotes */
Eric Andersencb57d552001-06-28 07:25:16 +00007783
Denys Vlasenko0e5e4ea2009-10-11 00:36:20 +02007784static const uint8_t nodesize[N_NUMBER] = {
Denis Vlasenko340299a2008-11-21 10:36:36 +00007785 [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
7786 [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
7787 [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
7788 [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
7789 [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
7790 [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
7791 [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
7792 [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
7793 [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
7794 [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
7795 [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
7796 [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
7797 [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
7798 [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
7799 [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
7800 [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
7801 [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
Denis Vlasenkocc5feab2008-11-22 01:32:40 +00007802#if ENABLE_ASH_BASH_COMPAT
Denis Vlasenko340299a2008-11-21 10:36:36 +00007803 [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
Denis Vlasenkocc5feab2008-11-22 01:32:40 +00007804#endif
Denis Vlasenko340299a2008-11-21 10:36:36 +00007805 [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
7806 [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
7807 [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
7808 [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
7809 [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
7810 [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
7811 [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
7812 [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
7813 [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007814};
7815
7816static void calcsize(union node *n);
7817
7818static void
7819sizenodelist(struct nodelist *lp)
7820{
7821 while (lp) {
7822 funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
7823 calcsize(lp->n);
7824 lp = lp->next;
7825 }
7826}
7827
7828static void
7829calcsize(union node *n)
7830{
7831 if (n == NULL)
7832 return;
7833 funcblocksize += nodesize[n->type];
7834 switch (n->type) {
7835 case NCMD:
7836 calcsize(n->ncmd.redirect);
7837 calcsize(n->ncmd.args);
7838 calcsize(n->ncmd.assign);
7839 break;
7840 case NPIPE:
7841 sizenodelist(n->npipe.cmdlist);
7842 break;
7843 case NREDIR:
7844 case NBACKGND:
7845 case NSUBSHELL:
7846 calcsize(n->nredir.redirect);
7847 calcsize(n->nredir.n);
7848 break;
7849 case NAND:
7850 case NOR:
7851 case NSEMI:
7852 case NWHILE:
7853 case NUNTIL:
7854 calcsize(n->nbinary.ch2);
7855 calcsize(n->nbinary.ch1);
7856 break;
7857 case NIF:
7858 calcsize(n->nif.elsepart);
7859 calcsize(n->nif.ifpart);
7860 calcsize(n->nif.test);
7861 break;
7862 case NFOR:
7863 funcstringsize += strlen(n->nfor.var) + 1;
7864 calcsize(n->nfor.body);
7865 calcsize(n->nfor.args);
7866 break;
7867 case NCASE:
7868 calcsize(n->ncase.cases);
7869 calcsize(n->ncase.expr);
7870 break;
7871 case NCLIST:
7872 calcsize(n->nclist.body);
7873 calcsize(n->nclist.pattern);
7874 calcsize(n->nclist.next);
7875 break;
7876 case NDEFUN:
7877 case NARG:
7878 sizenodelist(n->narg.backquote);
7879 funcstringsize += strlen(n->narg.text) + 1;
7880 calcsize(n->narg.next);
7881 break;
7882 case NTO:
Denis Vlasenko559691a2008-10-05 18:39:31 +00007883#if ENABLE_ASH_BASH_COMPAT
7884 case NTO2:
7885#endif
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007886 case NCLOBBER:
7887 case NFROM:
7888 case NFROMTO:
7889 case NAPPEND:
7890 calcsize(n->nfile.fname);
7891 calcsize(n->nfile.next);
7892 break;
7893 case NTOFD:
7894 case NFROMFD:
7895 calcsize(n->ndup.vname);
7896 calcsize(n->ndup.next);
7897 break;
7898 case NHERE:
7899 case NXHERE:
7900 calcsize(n->nhere.doc);
7901 calcsize(n->nhere.next);
7902 break;
7903 case NNOT:
7904 calcsize(n->nnot.com);
7905 break;
7906 };
7907}
7908
7909static char *
7910nodeckstrdup(char *s)
7911{
7912 char *rtn = funcstring;
7913
7914 strcpy(funcstring, s);
7915 funcstring += strlen(s) + 1;
7916 return rtn;
7917}
7918
7919static union node *copynode(union node *);
7920
7921static struct nodelist *
7922copynodelist(struct nodelist *lp)
7923{
7924 struct nodelist *start;
7925 struct nodelist **lpp;
7926
7927 lpp = &start;
7928 while (lp) {
7929 *lpp = funcblock;
7930 funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
7931 (*lpp)->n = copynode(lp->n);
7932 lp = lp->next;
7933 lpp = &(*lpp)->next;
7934 }
7935 *lpp = NULL;
7936 return start;
7937}
7938
7939static union node *
7940copynode(union node *n)
7941{
7942 union node *new;
7943
7944 if (n == NULL)
7945 return NULL;
7946 new = funcblock;
7947 funcblock = (char *) funcblock + nodesize[n->type];
7948
7949 switch (n->type) {
7950 case NCMD:
7951 new->ncmd.redirect = copynode(n->ncmd.redirect);
7952 new->ncmd.args = copynode(n->ncmd.args);
7953 new->ncmd.assign = copynode(n->ncmd.assign);
7954 break;
7955 case NPIPE:
7956 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00007957 new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007958 break;
7959 case NREDIR:
7960 case NBACKGND:
7961 case NSUBSHELL:
7962 new->nredir.redirect = copynode(n->nredir.redirect);
7963 new->nredir.n = copynode(n->nredir.n);
7964 break;
7965 case NAND:
7966 case NOR:
7967 case NSEMI:
7968 case NWHILE:
7969 case NUNTIL:
7970 new->nbinary.ch2 = copynode(n->nbinary.ch2);
7971 new->nbinary.ch1 = copynode(n->nbinary.ch1);
7972 break;
7973 case NIF:
7974 new->nif.elsepart = copynode(n->nif.elsepart);
7975 new->nif.ifpart = copynode(n->nif.ifpart);
7976 new->nif.test = copynode(n->nif.test);
7977 break;
7978 case NFOR:
7979 new->nfor.var = nodeckstrdup(n->nfor.var);
7980 new->nfor.body = copynode(n->nfor.body);
7981 new->nfor.args = copynode(n->nfor.args);
7982 break;
7983 case NCASE:
7984 new->ncase.cases = copynode(n->ncase.cases);
7985 new->ncase.expr = copynode(n->ncase.expr);
7986 break;
7987 case NCLIST:
7988 new->nclist.body = copynode(n->nclist.body);
7989 new->nclist.pattern = copynode(n->nclist.pattern);
7990 new->nclist.next = copynode(n->nclist.next);
7991 break;
7992 case NDEFUN:
7993 case NARG:
7994 new->narg.backquote = copynodelist(n->narg.backquote);
7995 new->narg.text = nodeckstrdup(n->narg.text);
7996 new->narg.next = copynode(n->narg.next);
7997 break;
7998 case NTO:
Denis Vlasenko559691a2008-10-05 18:39:31 +00007999#if ENABLE_ASH_BASH_COMPAT
8000 case NTO2:
8001#endif
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008002 case NCLOBBER:
8003 case NFROM:
8004 case NFROMTO:
8005 case NAPPEND:
8006 new->nfile.fname = copynode(n->nfile.fname);
8007 new->nfile.fd = n->nfile.fd;
8008 new->nfile.next = copynode(n->nfile.next);
8009 break;
8010 case NTOFD:
8011 case NFROMFD:
8012 new->ndup.vname = copynode(n->ndup.vname);
8013 new->ndup.dupfd = n->ndup.dupfd;
8014 new->ndup.fd = n->ndup.fd;
8015 new->ndup.next = copynode(n->ndup.next);
8016 break;
8017 case NHERE:
8018 case NXHERE:
8019 new->nhere.doc = copynode(n->nhere.doc);
8020 new->nhere.fd = n->nhere.fd;
8021 new->nhere.next = copynode(n->nhere.next);
8022 break;
8023 case NNOT:
8024 new->nnot.com = copynode(n->nnot.com);
8025 break;
8026 };
8027 new->type = n->type;
8028 return new;
8029}
8030
8031/*
8032 * Make a copy of a parse tree.
8033 */
8034static struct funcnode *
8035copyfunc(union node *n)
8036{
8037 struct funcnode *f;
8038 size_t blocksize;
8039
8040 funcblocksize = offsetof(struct funcnode, n);
8041 funcstringsize = 0;
8042 calcsize(n);
8043 blocksize = funcblocksize;
8044 f = ckmalloc(blocksize + funcstringsize);
8045 funcblock = (char *) f + offsetof(struct funcnode, n);
8046 funcstring = (char *) f + blocksize;
8047 copynode(n);
8048 f->count = 0;
8049 return f;
8050}
8051
8052/*
8053 * Define a shell function.
8054 */
8055static void
8056defun(char *name, union node *func)
8057{
8058 struct cmdentry entry;
8059
8060 INT_OFF;
8061 entry.cmdtype = CMDFUNCTION;
8062 entry.u.func = copyfunc(func);
8063 addcmdentry(name, &entry);
8064 INT_ON;
8065}
8066
Denis Vlasenko4b875702009-03-19 13:30:04 +00008067/* Reasons for skipping commands (see comment on breakcmd routine) */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008068#define SKIPBREAK (1 << 0)
8069#define SKIPCONT (1 << 1)
8070#define SKIPFUNC (1 << 2)
8071#define SKIPFILE (1 << 3)
8072#define SKIPEVAL (1 << 4)
Denis Vlasenko4b875702009-03-19 13:30:04 +00008073static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008074static int skipcount; /* number of levels to skip */
8075static int funcnest; /* depth of function calls */
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +00008076static int loopnest; /* current loop nesting level */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008077
Denis Vlasenko4b875702009-03-19 13:30:04 +00008078/* Forward decl way out to parsing code - dotrap needs it */
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008079static int evalstring(char *s, int mask);
8080
Denis Vlasenko4b875702009-03-19 13:30:04 +00008081/* Called to execute a trap.
8082 * Single callsite - at the end of evaltree().
8083 * If we return non-zero, exaltree raises EXEXIT exception.
8084 *
8085 * Perhaps we should avoid entering new trap handlers
8086 * while we are executing a trap handler. [is it a TODO?]
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008087 */
8088static int
8089dotrap(void)
8090{
Denis Vlasenko4b875702009-03-19 13:30:04 +00008091 uint8_t *g;
8092 int sig;
8093 uint8_t savestatus;
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008094
8095 savestatus = exitstatus;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02008096 pending_sig = 0;
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008097 xbarrier();
8098
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008099 TRACE(("dotrap entered\n"));
Denis Vlasenko4b875702009-03-19 13:30:04 +00008100 for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
8101 int want_exexit;
8102 char *t;
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008103
Denis Vlasenko4b875702009-03-19 13:30:04 +00008104 if (*g == 0)
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008105 continue;
Denis Vlasenko4b875702009-03-19 13:30:04 +00008106 t = trap[sig];
8107 /* non-trapped SIGINT is handled separately by raise_interrupt,
8108 * don't upset it by resetting gotsig[SIGINT-1] */
8109 if (sig == SIGINT && !t)
8110 continue;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008111
8112 TRACE(("sig %d is active, will run handler '%s'\n", sig, t));
Denis Vlasenko4b875702009-03-19 13:30:04 +00008113 *g = 0;
8114 if (!t)
8115 continue;
8116 want_exexit = evalstring(t, SKIPEVAL);
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008117 exitstatus = savestatus;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008118 if (want_exexit) {
Denis Vlasenkob21f3792009-03-19 23:09:58 +00008119 TRACE(("dotrap returns %d\n", want_exexit));
Denis Vlasenko4b875702009-03-19 13:30:04 +00008120 return want_exexit;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008121 }
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008122 }
8123
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008124 TRACE(("dotrap returns 0\n"));
Denis Vlasenko991a1da2008-02-10 19:02:53 +00008125 return 0;
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008126}
8127
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00008128/* forward declarations - evaluation is fairly recursive business... */
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008129static void evalloop(union node *, int);
8130static void evalfor(union node *, int);
8131static void evalcase(union node *, int);
8132static void evalsubshell(union node *, int);
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00008133static void expredir(union node *);
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008134static void evalpipe(union node *, int);
8135static void evalcommand(union node *, int);
Eric Andersenc470f442003-07-28 09:56:35 +00008136static int evalbltin(const struct builtincmd *, int, char **);
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008137static void prehash(union node *);
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00008138
Eric Andersen62483552001-07-10 06:09:16 +00008139/*
Eric Andersenc470f442003-07-28 09:56:35 +00008140 * Evaluate a parse tree. The value is left in the global variable
8141 * exitstatus.
Eric Andersen62483552001-07-10 06:09:16 +00008142 */
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008143static void
Eric Andersenc470f442003-07-28 09:56:35 +00008144evaltree(union node *n, int flags)
Eric Andersen62483552001-07-10 06:09:16 +00008145{
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008146 struct jmploc *volatile savehandler = exception_handler;
8147 struct jmploc jmploc;
Eric Andersenc470f442003-07-28 09:56:35 +00008148 int checkexit = 0;
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008149 void (*evalfn)(union node *, int);
Eric Andersenc470f442003-07-28 09:56:35 +00008150 int status;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008151 int int_level;
8152
8153 SAVE_INT(int_level);
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008154
Eric Andersenc470f442003-07-28 09:56:35 +00008155 if (n == NULL) {
8156 TRACE(("evaltree(NULL) called\n"));
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008157 goto out1;
Eric Andersen62483552001-07-10 06:09:16 +00008158 }
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008159 TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008160
8161 exception_handler = &jmploc;
8162 {
8163 int err = setjmp(jmploc.loc);
8164 if (err) {
8165 /* if it was a signal, check for trap handlers */
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008166 if (exception_type == EXSIG) {
Denis Vlasenkob21f3792009-03-19 23:09:58 +00008167 TRACE(("exception %d (EXSIG) in evaltree, err=%d\n",
8168 exception_type, err));
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008169 goto out;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008170 }
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008171 /* continue on the way out */
Denis Vlasenkob21f3792009-03-19 23:09:58 +00008172 TRACE(("exception %d in evaltree, propagating err=%d\n",
8173 exception_type, err));
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008174 exception_handler = savehandler;
8175 longjmp(exception_handler->loc, err);
8176 }
8177 }
8178
Eric Andersenc470f442003-07-28 09:56:35 +00008179 switch (n->type) {
8180 default:
Denis Vlasenkoa7189f02006-11-17 20:29:00 +00008181#if DEBUG
Eric Andersenc470f442003-07-28 09:56:35 +00008182 out1fmt("Node type = %d\n", n->type);
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00008183 fflush(stdout);
Eric Andersenc470f442003-07-28 09:56:35 +00008184 break;
8185#endif
8186 case NNOT:
8187 evaltree(n->nnot.com, EV_TESTED);
8188 status = !exitstatus;
8189 goto setstatus;
8190 case NREDIR:
8191 expredir(n->nredir.redirect);
8192 status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
8193 if (!status) {
8194 evaltree(n->nredir.n, flags & EV_TESTED);
8195 status = exitstatus;
8196 }
Denis Vlasenko34c73c42008-08-16 11:48:02 +00008197 popredir(/*drop:*/ 0, /*restore:*/ 0 /* not sure */);
Eric Andersenc470f442003-07-28 09:56:35 +00008198 goto setstatus;
8199 case NCMD:
8200 evalfn = evalcommand;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008201 checkexit:
Eric Andersenc470f442003-07-28 09:56:35 +00008202 if (eflag && !(flags & EV_TESTED))
8203 checkexit = ~0;
8204 goto calleval;
8205 case NFOR:
8206 evalfn = evalfor;
8207 goto calleval;
8208 case NWHILE:
8209 case NUNTIL:
8210 evalfn = evalloop;
8211 goto calleval;
8212 case NSUBSHELL:
8213 case NBACKGND:
8214 evalfn = evalsubshell;
8215 goto calleval;
8216 case NPIPE:
8217 evalfn = evalpipe;
8218 goto checkexit;
8219 case NCASE:
8220 evalfn = evalcase;
8221 goto calleval;
8222 case NAND:
8223 case NOR:
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008224 case NSEMI: {
8225
Eric Andersenc470f442003-07-28 09:56:35 +00008226#if NAND + 1 != NOR
8227#error NAND + 1 != NOR
8228#endif
8229#if NOR + 1 != NSEMI
8230#error NOR + 1 != NSEMI
8231#endif
Denis Vlasenko87d5fd92008-07-26 13:48:35 +00008232 unsigned is_or = n->type - NAND;
Eric Andersenc470f442003-07-28 09:56:35 +00008233 evaltree(
8234 n->nbinary.ch1,
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008235 (flags | ((is_or >> 1) - 1)) & EV_TESTED
Eric Andersenc470f442003-07-28 09:56:35 +00008236 );
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008237 if (!exitstatus == is_or)
Eric Andersenc470f442003-07-28 09:56:35 +00008238 break;
8239 if (!evalskip) {
8240 n = n->nbinary.ch2;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008241 evaln:
Eric Andersenc470f442003-07-28 09:56:35 +00008242 evalfn = evaltree;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008243 calleval:
Eric Andersenc470f442003-07-28 09:56:35 +00008244 evalfn(n, flags);
8245 break;
8246 }
8247 break;
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008248 }
Eric Andersenc470f442003-07-28 09:56:35 +00008249 case NIF:
8250 evaltree(n->nif.test, EV_TESTED);
8251 if (evalskip)
8252 break;
8253 if (exitstatus == 0) {
8254 n = n->nif.ifpart;
8255 goto evaln;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008256 }
8257 if (n->nif.elsepart) {
Eric Andersenc470f442003-07-28 09:56:35 +00008258 n = n->nif.elsepart;
8259 goto evaln;
8260 }
8261 goto success;
8262 case NDEFUN:
8263 defun(n->narg.text, n->narg.next);
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008264 success:
Eric Andersenc470f442003-07-28 09:56:35 +00008265 status = 0;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008266 setstatus:
Eric Andersenc470f442003-07-28 09:56:35 +00008267 exitstatus = status;
8268 break;
8269 }
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008270
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008271 out:
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008272 exception_handler = savehandler;
8273 out1:
8274 if (checkexit & exitstatus)
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00008275 evalskip |= SKIPEVAL;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02008276 else if (pending_sig && dotrap())
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00008277 goto exexit;
8278
8279 if (flags & EV_EXIT) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008280 exexit:
Denis Vlasenkob012b102007-02-19 22:43:01 +00008281 raise_exception(EXEXIT);
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00008282 }
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008283
8284 RESTORE_INT(int_level);
8285 TRACE(("leaving evaltree (no interrupts)\n"));
Eric Andersen62483552001-07-10 06:09:16 +00008286}
8287
Eric Andersenc470f442003-07-28 09:56:35 +00008288#if !defined(__alpha__) || (defined(__GNUC__) && __GNUC__ >= 3)
8289static
8290#endif
8291void evaltreenr(union node *, int) __attribute__ ((alias("evaltree"),__noreturn__));
8292
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008293static void
Eric Andersenc470f442003-07-28 09:56:35 +00008294evalloop(union node *n, int flags)
Eric Andersencb57d552001-06-28 07:25:16 +00008295{
8296 int status;
8297
8298 loopnest++;
8299 status = 0;
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008300 flags &= EV_TESTED;
Eric Andersencb57d552001-06-28 07:25:16 +00008301 for (;;) {
Eric Andersenc470f442003-07-28 09:56:35 +00008302 int i;
8303
Eric Andersencb57d552001-06-28 07:25:16 +00008304 evaltree(n->nbinary.ch1, EV_TESTED);
8305 if (evalskip) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008306 skipping:
8307 if (evalskip == SKIPCONT && --skipcount <= 0) {
Eric Andersencb57d552001-06-28 07:25:16 +00008308 evalskip = 0;
8309 continue;
8310 }
8311 if (evalskip == SKIPBREAK && --skipcount <= 0)
8312 evalskip = 0;
8313 break;
8314 }
Eric Andersenc470f442003-07-28 09:56:35 +00008315 i = exitstatus;
8316 if (n->type != NWHILE)
8317 i = !i;
8318 if (i != 0)
8319 break;
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008320 evaltree(n->nbinary.ch2, flags);
Eric Andersencb57d552001-06-28 07:25:16 +00008321 status = exitstatus;
8322 if (evalskip)
8323 goto skipping;
8324 }
8325 loopnest--;
8326 exitstatus = status;
8327}
8328
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008329static void
Eric Andersenc470f442003-07-28 09:56:35 +00008330evalfor(union node *n, int flags)
Eric Andersencb57d552001-06-28 07:25:16 +00008331{
8332 struct arglist arglist;
8333 union node *argp;
8334 struct strlist *sp;
8335 struct stackmark smark;
8336
8337 setstackmark(&smark);
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00008338 arglist.list = NULL;
Eric Andersencb57d552001-06-28 07:25:16 +00008339 arglist.lastp = &arglist.list;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008340 for (argp = n->nfor.args; argp; argp = argp->narg.next) {
Eric Andersencb57d552001-06-28 07:25:16 +00008341 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE | EXP_RECORD);
Eric Andersenc470f442003-07-28 09:56:35 +00008342 /* XXX */
Eric Andersencb57d552001-06-28 07:25:16 +00008343 if (evalskip)
8344 goto out;
8345 }
8346 *arglist.lastp = NULL;
8347
8348 exitstatus = 0;
8349 loopnest++;
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008350 flags &= EV_TESTED;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008351 for (sp = arglist.list; sp; sp = sp->next) {
Eric Andersencb57d552001-06-28 07:25:16 +00008352 setvar(n->nfor.var, sp->text, 0);
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008353 evaltree(n->nfor.body, flags);
Eric Andersencb57d552001-06-28 07:25:16 +00008354 if (evalskip) {
8355 if (evalskip == SKIPCONT && --skipcount <= 0) {
8356 evalskip = 0;
8357 continue;
8358 }
8359 if (evalskip == SKIPBREAK && --skipcount <= 0)
8360 evalskip = 0;
8361 break;
8362 }
8363 }
8364 loopnest--;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008365 out:
Eric Andersencb57d552001-06-28 07:25:16 +00008366 popstackmark(&smark);
8367}
8368
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008369static void
Eric Andersenc470f442003-07-28 09:56:35 +00008370evalcase(union node *n, int flags)
Eric Andersencb57d552001-06-28 07:25:16 +00008371{
8372 union node *cp;
8373 union node *patp;
8374 struct arglist arglist;
8375 struct stackmark smark;
8376
8377 setstackmark(&smark);
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00008378 arglist.list = NULL;
Eric Andersencb57d552001-06-28 07:25:16 +00008379 arglist.lastp = &arglist.list;
Eric Andersencb57d552001-06-28 07:25:16 +00008380 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
Eric Andersenc470f442003-07-28 09:56:35 +00008381 exitstatus = 0;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008382 for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
8383 for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
Eric Andersencb57d552001-06-28 07:25:16 +00008384 if (casematch(patp, arglist.list->text)) {
8385 if (evalskip == 0) {
8386 evaltree(cp->nclist.body, flags);
8387 }
8388 goto out;
8389 }
8390 }
8391 }
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008392 out:
Eric Andersencb57d552001-06-28 07:25:16 +00008393 popstackmark(&smark);
8394}
8395
Eric Andersenc470f442003-07-28 09:56:35 +00008396/*
8397 * Kick off a subshell to evaluate a tree.
8398 */
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008399static void
Eric Andersenc470f442003-07-28 09:56:35 +00008400evalsubshell(union node *n, int flags)
8401{
8402 struct job *jp;
8403 int backgnd = (n->type == NBACKGND);
8404 int status;
8405
8406 expredir(n->nredir.redirect);
8407 if (!backgnd && flags & EV_EXIT && !trap[0])
8408 goto nofork;
Denis Vlasenkob012b102007-02-19 22:43:01 +00008409 INT_OFF;
Denis Vlasenko68404f12008-03-17 09:00:54 +00008410 jp = makejob(/*n,*/ 1);
Eric Andersenc470f442003-07-28 09:56:35 +00008411 if (forkshell(jp, n, backgnd) == 0) {
Denis Vlasenkob012b102007-02-19 22:43:01 +00008412 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00008413 flags |= EV_EXIT;
8414 if (backgnd)
8415 flags &=~ EV_TESTED;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00008416 nofork:
Eric Andersenc470f442003-07-28 09:56:35 +00008417 redirect(n->nredir.redirect, 0);
8418 evaltreenr(n->nredir.n, flags);
8419 /* never returns */
8420 }
8421 status = 0;
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00008422 if (!backgnd)
Eric Andersenc470f442003-07-28 09:56:35 +00008423 status = waitforjob(jp);
8424 exitstatus = status;
Denis Vlasenkob012b102007-02-19 22:43:01 +00008425 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00008426}
8427
Eric Andersenc470f442003-07-28 09:56:35 +00008428/*
8429 * Compute the names of the files in a redirection list.
8430 */
Denis Vlasenko99eb8502007-02-23 21:09:49 +00008431static void fixredir(union node *, const char *, int);
Eric Andersenc470f442003-07-28 09:56:35 +00008432static void
8433expredir(union node *n)
8434{
8435 union node *redir;
8436
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008437 for (redir = n; redir; redir = redir->nfile.next) {
Eric Andersenc470f442003-07-28 09:56:35 +00008438 struct arglist fn;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008439
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00008440 fn.list = NULL;
Eric Andersenc470f442003-07-28 09:56:35 +00008441 fn.lastp = &fn.list;
8442 switch (redir->type) {
8443 case NFROMTO:
8444 case NFROM:
8445 case NTO:
Denis Vlasenko559691a2008-10-05 18:39:31 +00008446#if ENABLE_ASH_BASH_COMPAT
8447 case NTO2:
8448#endif
Eric Andersenc470f442003-07-28 09:56:35 +00008449 case NCLOBBER:
8450 case NAPPEND:
8451 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
Denis Vlasenko559691a2008-10-05 18:39:31 +00008452#if ENABLE_ASH_BASH_COMPAT
8453 store_expfname:
8454#endif
Eric Andersenc470f442003-07-28 09:56:35 +00008455 redir->nfile.expfname = fn.list->text;
8456 break;
8457 case NFROMFD:
Denis Vlasenko559691a2008-10-05 18:39:31 +00008458 case NTOFD: /* >& */
Eric Andersenc470f442003-07-28 09:56:35 +00008459 if (redir->ndup.vname) {
8460 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008461 if (fn.list == NULL)
Denis Vlasenkob012b102007-02-19 22:43:01 +00008462 ash_msg_and_raise_error("redir error");
Denis Vlasenko559691a2008-10-05 18:39:31 +00008463#if ENABLE_ASH_BASH_COMPAT
8464//FIXME: we used expandarg with different args!
8465 if (!isdigit_str9(fn.list->text)) {
8466 /* >&file, not >&fd */
8467 if (redir->nfile.fd != 1) /* 123>&file - BAD */
8468 ash_msg_and_raise_error("redir error");
8469 redir->type = NTO2;
8470 goto store_expfname;
8471 }
8472#endif
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008473 fixredir(redir, fn.list->text, 1);
Eric Andersenc470f442003-07-28 09:56:35 +00008474 }
8475 break;
8476 }
8477 }
8478}
8479
Eric Andersencb57d552001-06-28 07:25:16 +00008480/*
Eric Andersencb57d552001-06-28 07:25:16 +00008481 * Evaluate a pipeline. All the processes in the pipeline are children
8482 * of the process creating the pipeline. (This differs from some versions
8483 * of the shell, which make the last process in a pipeline the parent
8484 * of all the rest.)
8485 */
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008486static void
Eric Andersenc470f442003-07-28 09:56:35 +00008487evalpipe(union node *n, int flags)
Eric Andersencb57d552001-06-28 07:25:16 +00008488{
8489 struct job *jp;
8490 struct nodelist *lp;
8491 int pipelen;
8492 int prevfd;
8493 int pip[2];
8494
Eric Andersenc470f442003-07-28 09:56:35 +00008495 TRACE(("evalpipe(0x%lx) called\n", (long)n));
Eric Andersencb57d552001-06-28 07:25:16 +00008496 pipelen = 0;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008497 for (lp = n->npipe.cmdlist; lp; lp = lp->next)
Eric Andersencb57d552001-06-28 07:25:16 +00008498 pipelen++;
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008499 flags |= EV_EXIT;
Denis Vlasenkob012b102007-02-19 22:43:01 +00008500 INT_OFF;
Denis Vlasenko68404f12008-03-17 09:00:54 +00008501 jp = makejob(/*n,*/ pipelen);
Eric Andersencb57d552001-06-28 07:25:16 +00008502 prevfd = -1;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008503 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008504 prehash(lp->n);
Eric Andersencb57d552001-06-28 07:25:16 +00008505 pip[1] = -1;
8506 if (lp->next) {
8507 if (pipe(pip) < 0) {
8508 close(prevfd);
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00008509 ash_msg_and_raise_error("pipe call failed");
Eric Andersencb57d552001-06-28 07:25:16 +00008510 }
8511 }
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00008512 if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
Denis Vlasenkob012b102007-02-19 22:43:01 +00008513 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00008514 if (pip[1] >= 0) {
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008515 close(pip[0]);
Eric Andersencb57d552001-06-28 07:25:16 +00008516 }
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008517 if (prevfd > 0) {
8518 dup2(prevfd, 0);
8519 close(prevfd);
8520 }
8521 if (pip[1] > 1) {
8522 dup2(pip[1], 1);
8523 close(pip[1]);
8524 }
Eric Andersenc470f442003-07-28 09:56:35 +00008525 evaltreenr(lp->n, flags);
8526 /* never returns */
Eric Andersencb57d552001-06-28 07:25:16 +00008527 }
8528 if (prevfd >= 0)
8529 close(prevfd);
8530 prevfd = pip[0];
Denis Vlasenkob9e70dd2009-03-20 01:24:08 +00008531 /* Don't want to trigger debugging */
8532 if (pip[1] != -1)
8533 close(pip[1]);
Eric Andersencb57d552001-06-28 07:25:16 +00008534 }
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00008535 if (n->npipe.pipe_backgnd == 0) {
Eric Andersencb57d552001-06-28 07:25:16 +00008536 exitstatus = waitforjob(jp);
8537 TRACE(("evalpipe: job done exit status %d\n", exitstatus));
Eric Andersencb57d552001-06-28 07:25:16 +00008538 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00008539 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00008540}
8541
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008542/*
8543 * Controls whether the shell is interactive or not.
8544 */
8545static void
8546setinteractive(int on)
8547{
Denis Vlasenkob07a4962008-06-22 13:16:23 +00008548 static smallint is_interactive;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008549
8550 if (++on == is_interactive)
8551 return;
8552 is_interactive = on;
8553 setsignal(SIGINT);
8554 setsignal(SIGQUIT);
8555 setsignal(SIGTERM);
8556#if !ENABLE_FEATURE_SH_EXTRA_QUIET
8557 if (is_interactive > 1) {
8558 /* Looks like they want an interactive shell */
Denis Vlasenkoca525b42007-06-13 12:27:17 +00008559 static smallint did_banner;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008560
Denis Vlasenkoca525b42007-06-13 12:27:17 +00008561 if (!did_banner) {
Denys Vlasenkoc34c0332009-09-29 12:25:30 +02008562 /* note: ash and hush share this string */
8563 out1fmt("\n\n%s %s\n"
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008564 "Enter 'help' for a list of built-in commands."
8565 "\n\n",
Denys Vlasenkoc34c0332009-09-29 12:25:30 +02008566 bb_banner,
8567 "built-in shell (ash)"
8568 );
Denis Vlasenkoca525b42007-06-13 12:27:17 +00008569 did_banner = 1;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008570 }
8571 }
8572#endif
8573}
8574
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008575static void
8576optschanged(void)
8577{
8578#if DEBUG
8579 opentrace();
8580#endif
8581 setinteractive(iflag);
8582 setjobctl(mflag);
Denis Vlasenkob07a4962008-06-22 13:16:23 +00008583#if ENABLE_FEATURE_EDITING_VI
8584 if (viflag)
8585 line_input_state->flags |= VI_MODE;
8586 else
8587 line_input_state->flags &= ~VI_MODE;
8588#else
8589 viflag = 0; /* forcibly keep the option off */
8590#endif
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008591}
8592
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008593static struct localvar *localvars;
8594
8595/*
8596 * Called after a function returns.
8597 * Interrupts must be off.
8598 */
8599static void
8600poplocalvars(void)
8601{
8602 struct localvar *lvp;
8603 struct var *vp;
8604
8605 while ((lvp = localvars) != NULL) {
8606 localvars = lvp->next;
8607 vp = lvp->vp;
Denys Vlasenko883cea42009-07-11 15:31:59 +02008608 TRACE(("poplocalvar %s\n", vp ? vp->text : "-"));
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008609 if (vp == NULL) { /* $- saved */
8610 memcpy(optlist, lvp->text, sizeof(optlist));
8611 free((char*)lvp->text);
8612 optschanged();
8613 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
8614 unsetvar(vp->text);
8615 } else {
8616 if (vp->func)
8617 (*vp->func)(strchrnul(lvp->text, '=') + 1);
8618 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
8619 free((char*)vp->text);
8620 vp->flags = lvp->flags;
8621 vp->text = lvp->text;
8622 }
8623 free(lvp);
8624 }
8625}
8626
8627static int
8628evalfun(struct funcnode *func, int argc, char **argv, int flags)
8629{
8630 volatile struct shparam saveparam;
8631 struct localvar *volatile savelocalvars;
8632 struct jmploc *volatile savehandler;
8633 struct jmploc jmploc;
8634 int e;
8635
8636 saveparam = shellparam;
8637 savelocalvars = localvars;
8638 e = setjmp(jmploc.loc);
8639 if (e) {
8640 goto funcdone;
8641 }
8642 INT_OFF;
8643 savehandler = exception_handler;
8644 exception_handler = &jmploc;
8645 localvars = NULL;
Denis Vlasenko01631112007-12-16 17:20:38 +00008646 shellparam.malloced = 0;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008647 func->count++;
8648 funcnest++;
8649 INT_ON;
8650 shellparam.nparam = argc - 1;
8651 shellparam.p = argv + 1;
8652#if ENABLE_ASH_GETOPTS
8653 shellparam.optind = 1;
8654 shellparam.optoff = -1;
8655#endif
8656 evaltree(&func->n, flags & EV_TESTED);
Denis Vlasenko01631112007-12-16 17:20:38 +00008657 funcdone:
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008658 INT_OFF;
8659 funcnest--;
8660 freefunc(func);
8661 poplocalvars();
8662 localvars = savelocalvars;
8663 freeparam(&shellparam);
8664 shellparam = saveparam;
8665 exception_handler = savehandler;
8666 INT_ON;
8667 evalskip &= ~SKIPFUNC;
8668 return e;
8669}
8670
Denis Vlasenko131ae172007-02-18 13:00:19 +00008671#if ENABLE_ASH_CMDCMD
Denis Vlasenkoaa744452007-02-23 01:04:22 +00008672static char **
8673parse_command_args(char **argv, const char **path)
Eric Andersenc470f442003-07-28 09:56:35 +00008674{
8675 char *cp, c;
8676
8677 for (;;) {
8678 cp = *++argv;
8679 if (!cp)
8680 return 0;
8681 if (*cp++ != '-')
8682 break;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008683 c = *cp++;
8684 if (!c)
Eric Andersenc470f442003-07-28 09:56:35 +00008685 break;
8686 if (c == '-' && !*cp) {
8687 argv++;
8688 break;
8689 }
8690 do {
8691 switch (c) {
8692 case 'p':
Denis Vlasenkof5f75c52007-06-12 22:35:19 +00008693 *path = bb_default_path;
Eric Andersenc470f442003-07-28 09:56:35 +00008694 break;
8695 default:
8696 /* run 'typecmd' for other options */
8697 return 0;
8698 }
Denis Vlasenko9650f362007-02-23 01:04:37 +00008699 c = *cp++;
8700 } while (c);
Eric Andersenc470f442003-07-28 09:56:35 +00008701 }
8702 return argv;
8703}
8704#endif
8705
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008706/*
8707 * Make a variable a local variable. When a variable is made local, it's
8708 * value and flags are saved in a localvar structure. The saved values
8709 * will be restored when the shell function returns. We handle the name
8710 * "-" as a special case.
8711 */
8712static void
8713mklocal(char *name)
8714{
8715 struct localvar *lvp;
8716 struct var **vpp;
8717 struct var *vp;
8718
8719 INT_OFF;
Denis Vlasenko838ffd52008-02-21 04:32:08 +00008720 lvp = ckzalloc(sizeof(struct localvar));
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008721 if (LONE_DASH(name)) {
8722 char *p;
8723 p = ckmalloc(sizeof(optlist));
8724 lvp->text = memcpy(p, optlist, sizeof(optlist));
8725 vp = NULL;
8726 } else {
8727 char *eq;
8728
8729 vpp = hashvar(name);
8730 vp = *findvar(vpp, name);
8731 eq = strchr(name, '=');
8732 if (vp == NULL) {
8733 if (eq)
8734 setvareq(name, VSTRFIXED);
8735 else
8736 setvar(name, NULL, VSTRFIXED);
8737 vp = *vpp; /* the new variable */
8738 lvp->flags = VUNSET;
8739 } else {
8740 lvp->text = vp->text;
8741 lvp->flags = vp->flags;
8742 vp->flags |= VSTRFIXED|VTEXTFIXED;
8743 if (eq)
8744 setvareq(name, 0);
8745 }
8746 }
8747 lvp->vp = vp;
8748 lvp->next = localvars;
8749 localvars = lvp;
8750 INT_ON;
8751}
8752
8753/*
8754 * The "local" command.
8755 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008756static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008757localcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008758{
8759 char *name;
8760
8761 argv = argptr;
8762 while ((name = *argv++) != NULL) {
8763 mklocal(name);
8764 }
8765 return 0;
8766}
8767
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008768static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008769falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008770{
8771 return 1;
8772}
8773
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008774static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008775truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008776{
8777 return 0;
8778}
8779
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008780static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008781execcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008782{
Denis Vlasenko68404f12008-03-17 09:00:54 +00008783 if (argv[1]) {
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008784 iflag = 0; /* exit on error */
8785 mflag = 0;
8786 optschanged();
8787 shellexec(argv + 1, pathval(), 0);
8788 }
8789 return 0;
8790}
8791
8792/*
8793 * The return command.
8794 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008795static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008796returncmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008797{
8798 /*
8799 * If called outside a function, do what ksh does;
8800 * skip the rest of the file.
8801 */
8802 evalskip = funcnest ? SKIPFUNC : SKIPFILE;
8803 return argv[1] ? number(argv[1]) : exitstatus;
8804}
8805
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008806/* Forward declarations for builtintab[] */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008807static int breakcmd(int, char **) FAST_FUNC;
8808static int dotcmd(int, char **) FAST_FUNC;
8809static int evalcmd(int, char **) FAST_FUNC;
8810static int exitcmd(int, char **) FAST_FUNC;
8811static int exportcmd(int, char **) FAST_FUNC;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008812#if ENABLE_ASH_GETOPTS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008813static int getoptscmd(int, char **) FAST_FUNC;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008814#endif
Denis Vlasenko52764022007-02-24 13:42:56 +00008815#if !ENABLE_FEATURE_SH_EXTRA_QUIET
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008816static int helpcmd(int, char **) FAST_FUNC;
Denis Vlasenko52764022007-02-24 13:42:56 +00008817#endif
Mike Frysinger98c52642009-04-02 10:02:37 +00008818#if ENABLE_SH_MATH_SUPPORT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008819static int letcmd(int, char **) FAST_FUNC;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008820#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008821static int readcmd(int, char **) FAST_FUNC;
8822static int setcmd(int, char **) FAST_FUNC;
8823static int shiftcmd(int, char **) FAST_FUNC;
8824static int timescmd(int, char **) FAST_FUNC;
8825static int trapcmd(int, char **) FAST_FUNC;
8826static int umaskcmd(int, char **) FAST_FUNC;
8827static int unsetcmd(int, char **) FAST_FUNC;
8828static int ulimitcmd(int, char **) FAST_FUNC;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008829
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008830#define BUILTIN_NOSPEC "0"
8831#define BUILTIN_SPECIAL "1"
8832#define BUILTIN_REGULAR "2"
8833#define BUILTIN_SPEC_REG "3"
8834#define BUILTIN_ASSIGN "4"
8835#define BUILTIN_SPEC_ASSG "5"
8836#define BUILTIN_REG_ASSG "6"
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008837#define BUILTIN_SPEC_REG_ASSG "7"
8838
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008839/* Stubs for calling non-FAST_FUNC's */
Denys Vlasenko2634bf32009-06-09 18:40:07 +02008840#if ENABLE_ASH_BUILTIN_ECHO
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008841static int FAST_FUNC echocmd(int argc, char **argv) { return echo_main(argc, argv); }
Denys Vlasenko2634bf32009-06-09 18:40:07 +02008842#endif
8843#if ENABLE_ASH_BUILTIN_PRINTF
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008844static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
Denys Vlasenko2634bf32009-06-09 18:40:07 +02008845#endif
8846#if ENABLE_ASH_BUILTIN_TEST
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008847static int FAST_FUNC testcmd(int argc, char **argv) { return test_main(argc, argv); }
Denys Vlasenko2634bf32009-06-09 18:40:07 +02008848#endif
Denis Vlasenko468aea22008-04-01 14:47:57 +00008849
Denis Vlasenkof7d56652008-03-25 05:51:41 +00008850/* Keep these in proper order since it is searched via bsearch() */
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008851static const struct builtincmd builtintab[] = {
8852 { BUILTIN_SPEC_REG ".", dotcmd },
8853 { BUILTIN_SPEC_REG ":", truecmd },
8854#if ENABLE_ASH_BUILTIN_TEST
Denis Vlasenkocd2663f2008-06-01 22:36:39 +00008855 { BUILTIN_REGULAR "[", testcmd },
Denis Vlasenko80591b02008-03-25 07:49:43 +00008856#if ENABLE_ASH_BASH_COMPAT
Denis Vlasenkocd2663f2008-06-01 22:36:39 +00008857 { BUILTIN_REGULAR "[[", testcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008858#endif
Denis Vlasenko80591b02008-03-25 07:49:43 +00008859#endif
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008860#if ENABLE_ASH_ALIAS
8861 { BUILTIN_REG_ASSG "alias", aliascmd },
8862#endif
8863#if JOBS
8864 { BUILTIN_REGULAR "bg", fg_bgcmd },
8865#endif
8866 { BUILTIN_SPEC_REG "break", breakcmd },
8867 { BUILTIN_REGULAR "cd", cdcmd },
8868 { BUILTIN_NOSPEC "chdir", cdcmd },
8869#if ENABLE_ASH_CMDCMD
8870 { BUILTIN_REGULAR "command", commandcmd },
8871#endif
8872 { BUILTIN_SPEC_REG "continue", breakcmd },
8873#if ENABLE_ASH_BUILTIN_ECHO
8874 { BUILTIN_REGULAR "echo", echocmd },
8875#endif
8876 { BUILTIN_SPEC_REG "eval", evalcmd },
8877 { BUILTIN_SPEC_REG "exec", execcmd },
8878 { BUILTIN_SPEC_REG "exit", exitcmd },
8879 { BUILTIN_SPEC_REG_ASSG "export", exportcmd },
8880 { BUILTIN_REGULAR "false", falsecmd },
8881#if JOBS
8882 { BUILTIN_REGULAR "fg", fg_bgcmd },
8883#endif
8884#if ENABLE_ASH_GETOPTS
8885 { BUILTIN_REGULAR "getopts", getoptscmd },
8886#endif
8887 { BUILTIN_NOSPEC "hash", hashcmd },
8888#if !ENABLE_FEATURE_SH_EXTRA_QUIET
8889 { BUILTIN_NOSPEC "help", helpcmd },
8890#endif
8891#if JOBS
8892 { BUILTIN_REGULAR "jobs", jobscmd },
8893 { BUILTIN_REGULAR "kill", killcmd },
8894#endif
Mike Frysinger98c52642009-04-02 10:02:37 +00008895#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008896 { BUILTIN_NOSPEC "let", letcmd },
8897#endif
8898 { BUILTIN_ASSIGN "local", localcmd },
Denis Vlasenkocd2663f2008-06-01 22:36:39 +00008899#if ENABLE_ASH_BUILTIN_PRINTF
8900 { BUILTIN_REGULAR "printf", printfcmd },
8901#endif
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008902 { BUILTIN_NOSPEC "pwd", pwdcmd },
8903 { BUILTIN_REGULAR "read", readcmd },
8904 { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
8905 { BUILTIN_SPEC_REG "return", returncmd },
8906 { BUILTIN_SPEC_REG "set", setcmd },
8907 { BUILTIN_SPEC_REG "shift", shiftcmd },
8908 { BUILTIN_SPEC_REG "source", dotcmd },
8909#if ENABLE_ASH_BUILTIN_TEST
Denis Vlasenkocd2663f2008-06-01 22:36:39 +00008910 { BUILTIN_REGULAR "test", testcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008911#endif
8912 { BUILTIN_SPEC_REG "times", timescmd },
8913 { BUILTIN_SPEC_REG "trap", trapcmd },
8914 { BUILTIN_REGULAR "true", truecmd },
8915 { BUILTIN_NOSPEC "type", typecmd },
8916 { BUILTIN_NOSPEC "ulimit", ulimitcmd },
8917 { BUILTIN_REGULAR "umask", umaskcmd },
8918#if ENABLE_ASH_ALIAS
8919 { BUILTIN_REGULAR "unalias", unaliascmd },
8920#endif
8921 { BUILTIN_SPEC_REG "unset", unsetcmd },
8922 { BUILTIN_REGULAR "wait", waitcmd },
8923};
8924
Denis Vlasenko80591b02008-03-25 07:49:43 +00008925/* Should match the above table! */
8926#define COMMANDCMD (builtintab + \
8927 2 + \
8928 1 * ENABLE_ASH_BUILTIN_TEST + \
8929 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
8930 1 * ENABLE_ASH_ALIAS + \
8931 1 * ENABLE_ASH_JOB_CONTROL + \
8932 3)
8933#define EXECCMD (builtintab + \
8934 2 + \
8935 1 * ENABLE_ASH_BUILTIN_TEST + \
8936 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
8937 1 * ENABLE_ASH_ALIAS + \
8938 1 * ENABLE_ASH_JOB_CONTROL + \
8939 3 + \
8940 1 * ENABLE_ASH_CMDCMD + \
8941 1 + \
8942 ENABLE_ASH_BUILTIN_ECHO + \
8943 1)
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008944
8945/*
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008946 * Search the table of builtin commands.
8947 */
8948static struct builtincmd *
8949find_builtin(const char *name)
8950{
8951 struct builtincmd *bp;
8952
8953 bp = bsearch(
Denis Vlasenko80b8b392007-06-25 10:55:35 +00008954 name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008955 pstrcmp
8956 );
8957 return bp;
8958}
8959
8960/*
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008961 * Execute a simple command.
8962 */
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008963static int
8964isassignment(const char *p)
Paul Foxc3850c82005-07-20 18:23:39 +00008965{
8966 const char *q = endofname(p);
8967 if (p == q)
8968 return 0;
8969 return *q == '=';
8970}
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008971static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008972bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008973{
8974 /* Preserve exitstatus of a previous possible redirection
8975 * as POSIX mandates */
8976 return back_exitstatus;
8977}
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008978static void
Eric Andersenc470f442003-07-28 09:56:35 +00008979evalcommand(union node *cmd, int flags)
8980{
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00008981 static const struct builtincmd null_bltin = {
8982 "\0\0", bltincmd /* why three NULs? */
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008983 };
Eric Andersenc470f442003-07-28 09:56:35 +00008984 struct stackmark smark;
8985 union node *argp;
8986 struct arglist arglist;
8987 struct arglist varlist;
8988 char **argv;
8989 int argc;
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00008990 const struct strlist *sp;
Eric Andersenc470f442003-07-28 09:56:35 +00008991 struct cmdentry cmdentry;
8992 struct job *jp;
8993 char *lastarg;
8994 const char *path;
8995 int spclbltin;
Eric Andersenc470f442003-07-28 09:56:35 +00008996 int status;
8997 char **nargv;
Paul Foxc3850c82005-07-20 18:23:39 +00008998 struct builtincmd *bcmd;
Denis Vlasenko34c73c42008-08-16 11:48:02 +00008999 smallint cmd_is_exec;
9000 smallint pseudovarflag = 0;
Eric Andersenc470f442003-07-28 09:56:35 +00009001
9002 /* First expand the arguments. */
9003 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
9004 setstackmark(&smark);
9005 back_exitstatus = 0;
9006
9007 cmdentry.cmdtype = CMDBUILTIN;
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00009008 cmdentry.u.cmd = &null_bltin;
Eric Andersenc470f442003-07-28 09:56:35 +00009009 varlist.lastp = &varlist.list;
9010 *varlist.lastp = NULL;
9011 arglist.lastp = &arglist.list;
9012 *arglist.lastp = NULL;
9013
9014 argc = 0;
Denis Vlasenkob012b102007-02-19 22:43:01 +00009015 if (cmd->ncmd.args) {
Paul Foxc3850c82005-07-20 18:23:39 +00009016 bcmd = find_builtin(cmd->ncmd.args->narg.text);
9017 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
9018 }
9019
Eric Andersenc470f442003-07-28 09:56:35 +00009020 for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
9021 struct strlist **spp;
9022
9023 spp = arglist.lastp;
"Vladimir N. Oleynik"bef14d72005-09-05 13:25:11 +00009024 if (pseudovarflag && isassignment(argp->narg.text))
Paul Foxc3850c82005-07-20 18:23:39 +00009025 expandarg(argp, &arglist, EXP_VARTILDE);
9026 else
9027 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
9028
Eric Andersenc470f442003-07-28 09:56:35 +00009029 for (sp = *spp; sp; sp = sp->next)
9030 argc++;
9031 }
9032
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +00009033 argv = nargv = stalloc(sizeof(char *) * (argc + 1));
Denis Vlasenko2da584f2007-02-19 22:44:05 +00009034 for (sp = arglist.list; sp; sp = sp->next) {
Eric Andersenc470f442003-07-28 09:56:35 +00009035 TRACE(("evalcommand arg: %s\n", sp->text));
9036 *nargv++ = sp->text;
9037 }
9038 *nargv = NULL;
9039
9040 lastarg = NULL;
9041 if (iflag && funcnest == 0 && argc > 0)
9042 lastarg = nargv[-1];
9043
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009044 preverrout_fd = 2;
Eric Andersenc470f442003-07-28 09:56:35 +00009045 expredir(cmd->ncmd.redirect);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009046 status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
Eric Andersenc470f442003-07-28 09:56:35 +00009047
9048 path = vpath.text;
9049 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
9050 struct strlist **spp;
9051 char *p;
9052
9053 spp = varlist.lastp;
9054 expandarg(argp, &varlist, EXP_VARTILDE);
9055
9056 /*
9057 * Modify the command lookup path, if a PATH= assignment
9058 * is present
9059 */
9060 p = (*spp)->text;
9061 if (varequal(p, path))
9062 path = p;
9063 }
9064
9065 /* Print the command if xflag is set. */
9066 if (xflag) {
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009067 int n;
9068 const char *p = " %s";
Eric Andersenc470f442003-07-28 09:56:35 +00009069
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009070 p++;
Denis Vlasenko0de37e12007-10-17 11:08:53 +00009071 fdprintf(preverrout_fd, p, expandstr(ps4val()));
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009072
9073 sp = varlist.list;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +00009074 for (n = 0; n < 2; n++) {
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009075 while (sp) {
Denis Vlasenko0de37e12007-10-17 11:08:53 +00009076 fdprintf(preverrout_fd, p, sp->text);
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009077 sp = sp->next;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +00009078 if (*p == '%') {
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009079 p--;
9080 }
9081 }
9082 sp = arglist.list;
9083 }
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00009084 safe_write(preverrout_fd, "\n", 1);
Eric Andersenc470f442003-07-28 09:56:35 +00009085 }
9086
9087 cmd_is_exec = 0;
9088 spclbltin = -1;
9089
9090 /* Now locate the command. */
9091 if (argc) {
9092 const char *oldpath;
9093 int cmd_flag = DO_ERR;
9094
9095 path += 5;
9096 oldpath = path;
9097 for (;;) {
9098 find_command(argv[0], &cmdentry, cmd_flag, path);
9099 if (cmdentry.cmdtype == CMDUNKNOWN) {
Denis Vlasenkob012b102007-02-19 22:43:01 +00009100 flush_stderr();
Denis Vlasenko6514c5e2008-07-24 13:41:37 +00009101 status = 127;
Eric Andersenc470f442003-07-28 09:56:35 +00009102 goto bail;
9103 }
9104
9105 /* implement bltin and command here */
9106 if (cmdentry.cmdtype != CMDBUILTIN)
9107 break;
9108 if (spclbltin < 0)
9109 spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
9110 if (cmdentry.u.cmd == EXECCMD)
Denis Vlasenko34c73c42008-08-16 11:48:02 +00009111 cmd_is_exec = 1;
Denis Vlasenko131ae172007-02-18 13:00:19 +00009112#if ENABLE_ASH_CMDCMD
Eric Andersenc470f442003-07-28 09:56:35 +00009113 if (cmdentry.u.cmd == COMMANDCMD) {
Eric Andersenc470f442003-07-28 09:56:35 +00009114 path = oldpath;
9115 nargv = parse_command_args(argv, &path);
9116 if (!nargv)
9117 break;
9118 argc -= nargv - argv;
9119 argv = nargv;
9120 cmd_flag |= DO_NOFUNC;
9121 } else
9122#endif
9123 break;
9124 }
9125 }
9126
9127 if (status) {
9128 /* We have a redirection error. */
9129 if (spclbltin > 0)
Denis Vlasenkob012b102007-02-19 22:43:01 +00009130 raise_exception(EXERROR);
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009131 bail:
Eric Andersenc470f442003-07-28 09:56:35 +00009132 exitstatus = status;
9133 goto out;
9134 }
9135
9136 /* Execute the command. */
9137 switch (cmdentry.cmdtype) {
9138 default:
Denis Vlasenkobe54d6b2008-10-27 14:25:52 +00009139
Denis Vlasenko9bc80d72008-04-12 20:07:53 +00009140#if ENABLE_FEATURE_SH_NOFORK
Denis Vlasenkobe54d6b2008-10-27 14:25:52 +00009141/* Hmmm... shouldn't it happen somewhere in forkshell() instead?
9142 * Why "fork off a child process if necessary" doesn't apply to NOFORK? */
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00009143 {
9144 /* find_command() encodes applet_no as (-2 - applet_no) */
9145 int applet_no = (- cmdentry.u.index - 2);
Denis Vlasenko9bc80d72008-04-12 20:07:53 +00009146 if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
Denis Vlasenko9bc80d72008-04-12 20:07:53 +00009147 listsetvar(varlist.list, VEXPORT|VSTACK);
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00009148 /* run <applet>_main() */
9149 exitstatus = run_nofork_applet(applet_no, argv);
Denis Vlasenko9bc80d72008-04-12 20:07:53 +00009150 break;
9151 }
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00009152 }
Denis Vlasenko9bc80d72008-04-12 20:07:53 +00009153#endif
Eric Andersenc470f442003-07-28 09:56:35 +00009154 /* Fork off a child process if necessary. */
9155 if (!(flags & EV_EXIT) || trap[0]) {
Denis Vlasenkob012b102007-02-19 22:43:01 +00009156 INT_OFF;
Denis Vlasenko68404f12008-03-17 09:00:54 +00009157 jp = makejob(/*cmd,*/ 1);
Eric Andersenc470f442003-07-28 09:56:35 +00009158 if (forkshell(jp, cmd, FORK_FG) != 0) {
9159 exitstatus = waitforjob(jp);
Denis Vlasenkob012b102007-02-19 22:43:01 +00009160 INT_ON;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00009161 TRACE(("forked child exited with %d\n", exitstatus));
Eric Andersenc470f442003-07-28 09:56:35 +00009162 break;
9163 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00009164 FORCE_INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00009165 }
9166 listsetvar(varlist.list, VEXPORT|VSTACK);
9167 shellexec(argv, path, cmdentry.u.index);
9168 /* NOTREACHED */
9169
9170 case CMDBUILTIN:
9171 cmdenviron = varlist.list;
9172 if (cmdenviron) {
9173 struct strlist *list = cmdenviron;
9174 int i = VNOSET;
9175 if (spclbltin > 0 || argc == 0) {
9176 i = 0;
9177 if (cmd_is_exec && argc > 1)
9178 i = VEXPORT;
9179 }
9180 listsetvar(list, i);
9181 }
Denis Vlasenkobe54d6b2008-10-27 14:25:52 +00009182 /* Tight loop with builtins only:
9183 * "while kill -0 $child; do true; done"
9184 * will never exit even if $child died, unless we do this
9185 * to reap the zombie and make kill detect that it's gone: */
9186 dowait(DOWAIT_NONBLOCK, NULL);
9187
Eric Andersenc470f442003-07-28 09:56:35 +00009188 if (evalbltin(cmdentry.u.cmd, argc, argv)) {
9189 int exit_status;
Denis Vlasenko7f88e342009-03-19 03:36:18 +00009190 int i = exception_type;
Eric Andersenc470f442003-07-28 09:56:35 +00009191 if (i == EXEXIT)
9192 goto raise;
Eric Andersenc470f442003-07-28 09:56:35 +00009193 exit_status = 2;
Eric Andersenc470f442003-07-28 09:56:35 +00009194 if (i == EXINT)
Denis Vlasenko991a1da2008-02-10 19:02:53 +00009195 exit_status = 128 + SIGINT;
Eric Andersenc470f442003-07-28 09:56:35 +00009196 if (i == EXSIG)
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02009197 exit_status = 128 + pending_sig;
Eric Andersenc470f442003-07-28 09:56:35 +00009198 exitstatus = exit_status;
Eric Andersenc470f442003-07-28 09:56:35 +00009199 if (i == EXINT || spclbltin > 0) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009200 raise:
Denis Vlasenko2da584f2007-02-19 22:44:05 +00009201 longjmp(exception_handler->loc, 1);
Eric Andersenc470f442003-07-28 09:56:35 +00009202 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00009203 FORCE_INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00009204 }
9205 break;
9206
9207 case CMDFUNCTION:
9208 listsetvar(varlist.list, 0);
Denis Vlasenkobe54d6b2008-10-27 14:25:52 +00009209 /* See above for the rationale */
9210 dowait(DOWAIT_NONBLOCK, NULL);
Eric Andersenc470f442003-07-28 09:56:35 +00009211 if (evalfun(cmdentry.u.func, argc, argv, flags))
9212 goto raise;
9213 break;
9214 }
9215
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009216 out:
Denis Vlasenko34c73c42008-08-16 11:48:02 +00009217 popredir(/*drop:*/ cmd_is_exec, /*restore:*/ cmd_is_exec);
Denis Vlasenko6514c5e2008-07-24 13:41:37 +00009218 if (lastarg) {
Eric Andersenc470f442003-07-28 09:56:35 +00009219 /* dsl: I think this is intended to be used to support
9220 * '_' in 'vi' command mode during line editing...
9221 * However I implemented that within libedit itself.
9222 */
9223 setvar("_", lastarg, 0);
Denis Vlasenko6514c5e2008-07-24 13:41:37 +00009224 }
Eric Andersenc470f442003-07-28 09:56:35 +00009225 popstackmark(&smark);
9226}
9227
9228static int
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009229evalbltin(const struct builtincmd *cmd, int argc, char **argv)
9230{
Eric Andersenc470f442003-07-28 09:56:35 +00009231 char *volatile savecmdname;
9232 struct jmploc *volatile savehandler;
9233 struct jmploc jmploc;
9234 int i;
9235
9236 savecmdname = commandname;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009237 i = setjmp(jmploc.loc);
9238 if (i)
Eric Andersenc470f442003-07-28 09:56:35 +00009239 goto cmddone;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00009240 savehandler = exception_handler;
9241 exception_handler = &jmploc;
Eric Andersenc470f442003-07-28 09:56:35 +00009242 commandname = argv[0];
9243 argptr = argv + 1;
9244 optptr = NULL; /* initialize nextopt */
9245 exitstatus = (*cmd->builtin)(argc, argv);
Denis Vlasenkob012b102007-02-19 22:43:01 +00009246 flush_stdout_stderr();
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009247 cmddone:
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009248 exitstatus |= ferror(stdout);
Rob Landleyf296f0b2006-07-06 01:09:21 +00009249 clearerr(stdout);
Eric Andersenc470f442003-07-28 09:56:35 +00009250 commandname = savecmdname;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00009251 exception_handler = savehandler;
Eric Andersenc470f442003-07-28 09:56:35 +00009252
9253 return i;
9254}
9255
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009256static int
9257goodname(const char *p)
Glenn L McGrath16e45d72004-02-04 08:24:39 +00009258{
9259 return !*endofname(p);
9260}
9261
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009262
Glenn L McGrath50812ff2002-08-23 13:14:48 +00009263/*
9264 * Search for a command. This is called before we fork so that the
9265 * location of the command will be available in the parent as well as
Glenn L McGrath16e45d72004-02-04 08:24:39 +00009266 * the child. The check for "goodname" is an overly conservative
9267 * check that the name will not be subject to expansion.
Glenn L McGrath50812ff2002-08-23 13:14:48 +00009268 */
Eric Andersenc470f442003-07-28 09:56:35 +00009269static void
9270prehash(union node *n)
Glenn L McGrath50812ff2002-08-23 13:14:48 +00009271{
9272 struct cmdentry entry;
9273
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +00009274 if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
9275 find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
Glenn L McGrath50812ff2002-08-23 13:14:48 +00009276}
9277
Eric Andersencb57d552001-06-28 07:25:16 +00009278
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00009279/* ============ Builtin commands
9280 *
9281 * Builtin commands whose functions are closely tied to evaluation
9282 * are implemented here.
Eric Andersencb57d552001-06-28 07:25:16 +00009283 */
9284
9285/*
Eric Andersencb57d552001-06-28 07:25:16 +00009286 * Handle break and continue commands. Break, continue, and return are
9287 * all handled by setting the evalskip flag. The evaluation routines
9288 * above all check this flag, and if it is set they start skipping
9289 * commands rather than executing them. The variable skipcount is
9290 * the number of loops to break/continue, or the number of function
9291 * levels to return. (The latter is always 1.) It should probably
9292 * be an error to break out of more loops than exist, but it isn't
9293 * in the standard shell so we don't make it one here.
9294 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009295static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00009296breakcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +00009297{
Denis Vlasenko68404f12008-03-17 09:00:54 +00009298 int n = argv[1] ? number(argv[1]) : 1;
Eric Andersencb57d552001-06-28 07:25:16 +00009299
Aaron Lehmann2aef3a62001-12-31 06:03:12 +00009300 if (n <= 0)
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02009301 ash_msg_and_raise_error(msg_illnum, argv[1]);
Eric Andersencb57d552001-06-28 07:25:16 +00009302 if (n > loopnest)
9303 n = loopnest;
9304 if (n > 0) {
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00009305 evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
Eric Andersencb57d552001-06-28 07:25:16 +00009306 skipcount = n;
9307 }
9308 return 0;
9309}
9310
Eric Andersenc470f442003-07-28 09:56:35 +00009311
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009312/* ============ input.c
9313 *
Eric Andersen90898442003-08-06 11:20:52 +00009314 * This implements the input routines used by the parser.
Eric Andersencb57d552001-06-28 07:25:16 +00009315 */
Denis Vlasenko99eb8502007-02-23 21:09:49 +00009316
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009317enum {
9318 INPUT_PUSH_FILE = 1,
9319 INPUT_NOFILE_OK = 2,
9320};
Eric Andersencb57d552001-06-28 07:25:16 +00009321
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009322static smallint checkkwd;
Denis Vlasenko99eb8502007-02-23 21:09:49 +00009323/* values of checkkwd variable */
9324#define CHKALIAS 0x1
9325#define CHKKWD 0x2
9326#define CHKNL 0x4
9327
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009328/*
9329 * Push a string back onto the input at this current parsefile level.
9330 * We handle aliases this way.
9331 */
9332#if !ENABLE_ASH_ALIAS
9333#define pushstring(s, ap) pushstring(s)
9334#endif
9335static void
9336pushstring(char *s, struct alias *ap)
9337{
9338 struct strpush *sp;
9339 int len;
9340
9341 len = strlen(s);
9342 INT_OFF;
9343 if (g_parsefile->strpush) {
9344 sp = ckzalloc(sizeof(*sp));
9345 sp->prev = g_parsefile->strpush;
9346 } else {
9347 sp = &(g_parsefile->basestrpush);
9348 }
9349 g_parsefile->strpush = sp;
9350 sp->prev_string = g_parsefile->next_to_pgetc;
9351 sp->prev_left_in_line = g_parsefile->left_in_line;
9352#if ENABLE_ASH_ALIAS
9353 sp->ap = ap;
9354 if (ap) {
9355 ap->flag |= ALIASINUSE;
9356 sp->string = s;
9357 }
9358#endif
9359 g_parsefile->next_to_pgetc = s;
9360 g_parsefile->left_in_line = len;
9361 INT_ON;
9362}
9363
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009364static void
9365popstring(void)
Eric Andersenc470f442003-07-28 09:56:35 +00009366{
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009367 struct strpush *sp = g_parsefile->strpush;
Eric Andersenc470f442003-07-28 09:56:35 +00009368
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009369 INT_OFF;
Denis Vlasenko131ae172007-02-18 13:00:19 +00009370#if ENABLE_ASH_ALIAS
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009371 if (sp->ap) {
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009372 if (g_parsefile->next_to_pgetc[-1] == ' '
9373 || g_parsefile->next_to_pgetc[-1] == '\t'
9374 ) {
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009375 checkkwd |= CHKALIAS;
Glenn L McGrath28939ad2004-07-21 10:20:19 +00009376 }
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009377 if (sp->string != sp->ap->val) {
9378 free(sp->string);
9379 }
9380 sp->ap->flag &= ~ALIASINUSE;
9381 if (sp->ap->flag & ALIASDEAD) {
9382 unalias(sp->ap->name);
9383 }
Glenn L McGrath28939ad2004-07-21 10:20:19 +00009384 }
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009385#endif
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009386 g_parsefile->next_to_pgetc = sp->prev_string;
9387 g_parsefile->left_in_line = sp->prev_left_in_line;
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009388 g_parsefile->strpush = sp->prev;
9389 if (sp != &(g_parsefile->basestrpush))
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009390 free(sp);
9391 INT_ON;
9392}
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009393
Denis Vlasenkoe27dafd2008-11-28 04:01:03 +00009394//FIXME: BASH_COMPAT with "...&" does TWO pungetc():
9395//it peeks whether it is &>, and then pushes back both chars.
9396//This function needs to save last *next_to_pgetc to buf[0]
9397//to make two pungetc() reliable. Currently,
9398// pgetc (out of buf: does preadfd), pgetc, pungetc, pungetc won't work...
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009399static int
9400preadfd(void)
Eric Andersencb57d552001-06-28 07:25:16 +00009401{
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00009402 int nr;
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00009403 char *buf = g_parsefile->buf;
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00009404
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009405 g_parsefile->next_to_pgetc = buf;
Denis Vlasenko38f63192007-01-22 09:03:07 +00009406#if ENABLE_FEATURE_EDITING
Denis Vlasenko85c24712008-03-17 09:04:04 +00009407 retry:
Denis Vlasenko727752d2008-11-28 03:41:47 +00009408 if (!iflag || g_parsefile->fd != STDIN_FILENO)
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009409 nr = nonblock_safe_read(g_parsefile->fd, buf, BUFSIZ - 1);
Eric Andersenc470f442003-07-28 09:56:35 +00009410 else {
Denis Vlasenko38f63192007-01-22 09:03:07 +00009411#if ENABLE_FEATURE_TAB_COMPLETION
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009412 line_input_state->path_lookup = pathval();
Eric Andersen4a79c0e2004-09-08 10:01:07 +00009413#endif
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009414 nr = read_line_input(cmdedit_prompt, buf, BUFSIZ, line_input_state);
9415 if (nr == 0) {
9416 /* Ctrl+C pressed */
9417 if (trap[SIGINT]) {
Glenn L McGrath16e45d72004-02-04 08:24:39 +00009418 buf[0] = '\n';
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009419 buf[1] = '\0';
Glenn L McGrath16e45d72004-02-04 08:24:39 +00009420 raise(SIGINT);
9421 return 1;
9422 }
Eric Andersenc470f442003-07-28 09:56:35 +00009423 goto retry;
9424 }
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009425 if (nr < 0 && errno == 0) {
Denis Vlasenko9cb220b2007-12-09 10:03:28 +00009426 /* Ctrl+D pressed */
Eric Andersenc470f442003-07-28 09:56:35 +00009427 nr = 0;
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00009428 }
Eric Andersencb57d552001-06-28 07:25:16 +00009429 }
9430#else
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +00009431 nr = nonblock_safe_read(g_parsefile->fd, buf, BUFSIZ - 1);
Eric Andersencb57d552001-06-28 07:25:16 +00009432#endif
9433
Denis Vlasenkoe376d452008-02-20 22:23:24 +00009434#if 0
9435/* nonblock_safe_read() handles this problem */
Eric Andersencb57d552001-06-28 07:25:16 +00009436 if (nr < 0) {
Eric Andersencb57d552001-06-28 07:25:16 +00009437 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
Denis Vlasenkod37f2222007-08-19 13:42:08 +00009438 int flags = fcntl(0, F_GETFL);
Denis Vlasenko9cb220b2007-12-09 10:03:28 +00009439 if (flags >= 0 && (flags & O_NONBLOCK)) {
9440 flags &= ~O_NONBLOCK;
Eric Andersencb57d552001-06-28 07:25:16 +00009441 if (fcntl(0, F_SETFL, flags) >= 0) {
9442 out2str("sh: turning off NDELAY mode\n");
9443 goto retry;
9444 }
9445 }
9446 }
9447 }
Denis Vlasenkoe376d452008-02-20 22:23:24 +00009448#endif
Eric Andersencb57d552001-06-28 07:25:16 +00009449 return nr;
9450}
9451
9452/*
9453 * Refill the input buffer and return the next input character:
9454 *
9455 * 1) If a string was pushed back on the input, pop it;
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009456 * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
9457 * or we are reading from a string so we can't refill the buffer,
9458 * return EOF.
Denys Vlasenko883cea42009-07-11 15:31:59 +02009459 * 3) If there is more stuff in this buffer, use it else call read to fill it.
Eric Andersencb57d552001-06-28 07:25:16 +00009460 * 4) Process input up to the next newline, deleting nul characters.
9461 */
Denis Vlasenko727752d2008-11-28 03:41:47 +00009462//#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
9463#define pgetc_debug(...) ((void)0)
Denis Vlasenko68819d12008-12-15 11:26:36 +00009464/*
9465 * NB: due to SIT(c) internals (syntax_index_table[] vector),
9466 * pgetc() and related functions must return chars SIGN-EXTENDED into ints,
9467 * not zero-extended. Seems fragile to me. Affects only !USE_SIT_FUNCTION case,
9468 * so we can fix it by ditching !USE_SIT_FUNCTION if Unicode requires that.
9469 */
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009470static int
Eric Andersenc470f442003-07-28 09:56:35 +00009471preadbuffer(void)
Eric Andersencb57d552001-06-28 07:25:16 +00009472{
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009473 char *q;
Eric Andersencb57d552001-06-28 07:25:16 +00009474 int more;
Eric Andersencb57d552001-06-28 07:25:16 +00009475
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009476 while (g_parsefile->strpush) {
Denis Vlasenko131ae172007-02-18 13:00:19 +00009477#if ENABLE_ASH_ALIAS
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009478 if (g_parsefile->left_in_line == -1
9479 && g_parsefile->strpush->ap
9480 && g_parsefile->next_to_pgetc[-1] != ' '
9481 && g_parsefile->next_to_pgetc[-1] != '\t'
Denis Vlasenko16898402008-11-25 01:34:52 +00009482 ) {
Denis Vlasenko727752d2008-11-28 03:41:47 +00009483 pgetc_debug("preadbuffer PEOA");
Eric Andersencb57d552001-06-28 07:25:16 +00009484 return PEOA;
9485 }
Eric Andersen2870d962001-07-02 17:27:21 +00009486#endif
Eric Andersencb57d552001-06-28 07:25:16 +00009487 popstring();
Denis Vlasenko727752d2008-11-28 03:41:47 +00009488 /* try "pgetc" now: */
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009489 pgetc_debug("preadbuffer internal pgetc at %d:%p'%s'",
9490 g_parsefile->left_in_line,
9491 g_parsefile->next_to_pgetc,
9492 g_parsefile->next_to_pgetc);
9493 if (--g_parsefile->left_in_line >= 0)
9494 return (unsigned char)(*g_parsefile->next_to_pgetc++);
Eric Andersencb57d552001-06-28 07:25:16 +00009495 }
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009496 /* on both branches above g_parsefile->left_in_line < 0.
Denis Vlasenko727752d2008-11-28 03:41:47 +00009497 * "pgetc" needs refilling.
9498 */
9499
Denis Vlasenkoe27dafd2008-11-28 04:01:03 +00009500 /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009501 * pungetc() may increment it a few times.
Denis Vlasenkoe27dafd2008-11-28 04:01:03 +00009502 * Assuming it won't increment it to less than -90.
Denis Vlasenko727752d2008-11-28 03:41:47 +00009503 */
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009504 if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
Denis Vlasenko727752d2008-11-28 03:41:47 +00009505 pgetc_debug("preadbuffer PEOF1");
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009506 /* even in failure keep left_in_line and next_to_pgetc
9507 * in lock step, for correct multi-layer pungetc.
9508 * left_in_line was decremented before preadbuffer(),
9509 * must inc next_to_pgetc: */
9510 g_parsefile->next_to_pgetc++;
Eric Andersencb57d552001-06-28 07:25:16 +00009511 return PEOF;
Denis Vlasenko727752d2008-11-28 03:41:47 +00009512 }
Eric Andersencb57d552001-06-28 07:25:16 +00009513
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009514 more = g_parsefile->left_in_buffer;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009515 if (more <= 0) {
Denis Vlasenko727752d2008-11-28 03:41:47 +00009516 flush_stdout_stderr();
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009517 again:
9518 more = preadfd();
9519 if (more <= 0) {
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009520 /* don't try reading again */
9521 g_parsefile->left_in_line = -99;
Denis Vlasenko727752d2008-11-28 03:41:47 +00009522 pgetc_debug("preadbuffer PEOF2");
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009523 g_parsefile->next_to_pgetc++;
Eric Andersencb57d552001-06-28 07:25:16 +00009524 return PEOF;
9525 }
9526 }
9527
Denis Vlasenko727752d2008-11-28 03:41:47 +00009528 /* Find out where's the end of line.
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009529 * Set g_parsefile->left_in_line
9530 * and g_parsefile->left_in_buffer acordingly.
Denis Vlasenko727752d2008-11-28 03:41:47 +00009531 * NUL chars are deleted.
9532 */
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009533 q = g_parsefile->next_to_pgetc;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009534 for (;;) {
Denis Vlasenko727752d2008-11-28 03:41:47 +00009535 char c;
Eric Andersencb57d552001-06-28 07:25:16 +00009536
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009537 more--;
Eric Andersenc470f442003-07-28 09:56:35 +00009538
Denis Vlasenko727752d2008-11-28 03:41:47 +00009539 c = *q;
9540 if (c == '\0') {
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009541 memmove(q, q + 1, more);
Denis Vlasenko727752d2008-11-28 03:41:47 +00009542 } else {
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009543 q++;
9544 if (c == '\n') {
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009545 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009546 break;
9547 }
Eric Andersencb57d552001-06-28 07:25:16 +00009548 }
9549
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009550 if (more <= 0) {
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009551 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9552 if (g_parsefile->left_in_line < 0)
Eric Andersencb57d552001-06-28 07:25:16 +00009553 goto again;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009554 break;
Eric Andersencb57d552001-06-28 07:25:16 +00009555 }
9556 }
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009557 g_parsefile->left_in_buffer = more;
Eric Andersencb57d552001-06-28 07:25:16 +00009558
Eric Andersencb57d552001-06-28 07:25:16 +00009559 if (vflag) {
Denis Vlasenko727752d2008-11-28 03:41:47 +00009560 char save = *q;
9561 *q = '\0';
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009562 out2str(g_parsefile->next_to_pgetc);
Denis Vlasenko727752d2008-11-28 03:41:47 +00009563 *q = save;
Eric Andersencb57d552001-06-28 07:25:16 +00009564 }
9565
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009566 pgetc_debug("preadbuffer at %d:%p'%s'",
9567 g_parsefile->left_in_line,
9568 g_parsefile->next_to_pgetc,
9569 g_parsefile->next_to_pgetc);
Denis Vlasenko68819d12008-12-15 11:26:36 +00009570 return signed_char2int(*g_parsefile->next_to_pgetc++);
Eric Andersencb57d552001-06-28 07:25:16 +00009571}
9572
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009573#define pgetc_as_macro() \
9574 (--g_parsefile->left_in_line >= 0 \
Denis Vlasenko68819d12008-12-15 11:26:36 +00009575 ? signed_char2int(*g_parsefile->next_to_pgetc++) \
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009576 : preadbuffer() \
9577 )
Denis Vlasenko727752d2008-11-28 03:41:47 +00009578
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009579static int
9580pgetc(void)
9581{
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009582 pgetc_debug("pgetc_fast at %d:%p'%s'",
9583 g_parsefile->left_in_line,
9584 g_parsefile->next_to_pgetc,
9585 g_parsefile->next_to_pgetc);
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009586 return pgetc_as_macro();
9587}
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00009588
9589#if ENABLE_ASH_OPTIMIZE_FOR_SIZE
Denis Vlasenko834dee72008-10-07 09:18:30 +00009590#define pgetc_fast() pgetc()
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009591#else
Denis Vlasenko834dee72008-10-07 09:18:30 +00009592#define pgetc_fast() pgetc_as_macro()
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009593#endif
9594
9595/*
9596 * Same as pgetc(), but ignores PEOA.
9597 */
9598#if ENABLE_ASH_ALIAS
9599static int
9600pgetc2(void)
9601{
9602 int c;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009603 do {
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009604 pgetc_debug("pgetc_fast at %d:%p'%s'",
9605 g_parsefile->left_in_line,
9606 g_parsefile->next_to_pgetc,
9607 g_parsefile->next_to_pgetc);
Denis Vlasenko834dee72008-10-07 09:18:30 +00009608 c = pgetc_fast();
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009609 } while (c == PEOA);
9610 return c;
9611}
9612#else
Denis Vlasenko834dee72008-10-07 09:18:30 +00009613#define pgetc2() pgetc()
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009614#endif
9615
9616/*
9617 * Read a line from the script.
9618 */
9619static char *
9620pfgets(char *line, int len)
9621{
9622 char *p = line;
9623 int nleft = len;
9624 int c;
9625
9626 while (--nleft > 0) {
9627 c = pgetc2();
9628 if (c == PEOF) {
9629 if (p == line)
9630 return NULL;
9631 break;
9632 }
9633 *p++ = c;
9634 if (c == '\n')
9635 break;
9636 }
9637 *p = '\0';
9638 return line;
9639}
9640
Eric Andersenc470f442003-07-28 09:56:35 +00009641/*
9642 * Undo the last call to pgetc. Only one character may be pushed back.
9643 * PEOF may be pushed back.
9644 */
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009645static void
Eric Andersenc470f442003-07-28 09:56:35 +00009646pungetc(void)
9647{
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009648 g_parsefile->left_in_line++;
9649 g_parsefile->next_to_pgetc--;
9650 pgetc_debug("pushed back to %d:%p'%s'",
9651 g_parsefile->left_in_line,
9652 g_parsefile->next_to_pgetc,
9653 g_parsefile->next_to_pgetc);
Eric Andersencb57d552001-06-28 07:25:16 +00009654}
9655
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009656/*
9657 * To handle the "." command, a stack of input files is used. Pushfile
9658 * adds a new entry to the stack and popfile restores the previous level.
9659 */
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009660static void
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009661pushfile(void)
Eric Andersenc470f442003-07-28 09:56:35 +00009662{
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009663 struct parsefile *pf;
9664
Denis Vlasenko597906c2008-02-20 16:38:54 +00009665 pf = ckzalloc(sizeof(*pf));
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009666 pf->prev = g_parsefile;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009667 pf->fd = -1;
Denis Vlasenko597906c2008-02-20 16:38:54 +00009668 /*pf->strpush = NULL; - ckzalloc did it */
9669 /*pf->basestrpush.prev = NULL;*/
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009670 g_parsefile = pf;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009671}
9672
9673static void
9674popfile(void)
9675{
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009676 struct parsefile *pf = g_parsefile;
Eric Andersenc470f442003-07-28 09:56:35 +00009677
Denis Vlasenkob012b102007-02-19 22:43:01 +00009678 INT_OFF;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009679 if (pf->fd >= 0)
9680 close(pf->fd);
Denis Vlasenko60818682007-09-28 22:07:23 +00009681 free(pf->buf);
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009682 while (pf->strpush)
9683 popstring();
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009684 g_parsefile = pf->prev;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009685 free(pf);
Denis Vlasenkob012b102007-02-19 22:43:01 +00009686 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00009687}
9688
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009689/*
9690 * Return to top level.
9691 */
9692static void
9693popallfiles(void)
9694{
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009695 while (g_parsefile != &basepf)
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009696 popfile();
9697}
9698
9699/*
9700 * Close the file(s) that the shell is reading commands from. Called
9701 * after a fork is done.
9702 */
9703static void
9704closescript(void)
9705{
9706 popallfiles();
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009707 if (g_parsefile->fd > 0) {
9708 close(g_parsefile->fd);
9709 g_parsefile->fd = 0;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009710 }
9711}
9712
9713/*
9714 * Like setinputfile, but takes an open file descriptor. Call this with
9715 * interrupts off.
9716 */
9717static void
9718setinputfd(int fd, int push)
9719{
Denis Vlasenko96e1b382007-09-30 23:50:48 +00009720 close_on_exec_on(fd);
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009721 if (push) {
9722 pushfile();
Denis Vlasenko727752d2008-11-28 03:41:47 +00009723 g_parsefile->buf = NULL;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009724 }
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009725 g_parsefile->fd = fd;
9726 if (g_parsefile->buf == NULL)
9727 g_parsefile->buf = ckmalloc(IBUFSIZ);
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009728 g_parsefile->left_in_buffer = 0;
9729 g_parsefile->left_in_line = 0;
9730 g_parsefile->linno = 1;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009731}
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009732
Eric Andersenc470f442003-07-28 09:56:35 +00009733/*
9734 * Set the input to take input from a file. If push is set, push the
9735 * old input onto the stack first.
9736 */
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009737static int
9738setinputfile(const char *fname, int flags)
Eric Andersenc470f442003-07-28 09:56:35 +00009739{
9740 int fd;
9741 int fd2;
9742
Denis Vlasenkob012b102007-02-19 22:43:01 +00009743 INT_OFF;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009744 fd = open(fname, O_RDONLY);
9745 if (fd < 0) {
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009746 if (flags & INPUT_NOFILE_OK)
9747 goto out;
Denis Vlasenko9604e1b2009-03-03 18:47:56 +00009748 ash_msg_and_raise_error("can't open '%s'", fname);
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009749 }
Eric Andersenc470f442003-07-28 09:56:35 +00009750 if (fd < 10) {
9751 fd2 = copyfd(fd, 10);
9752 close(fd);
9753 if (fd2 < 0)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00009754 ash_msg_and_raise_error("out of file descriptors");
Eric Andersenc470f442003-07-28 09:56:35 +00009755 fd = fd2;
9756 }
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009757 setinputfd(fd, flags & INPUT_PUSH_FILE);
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009758 out:
Denis Vlasenkob012b102007-02-19 22:43:01 +00009759 INT_ON;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009760 return fd;
Eric Andersenc470f442003-07-28 09:56:35 +00009761}
9762
Eric Andersencb57d552001-06-28 07:25:16 +00009763/*
9764 * Like setinputfile, but takes input from a string.
9765 */
Eric Andersenc470f442003-07-28 09:56:35 +00009766static void
9767setinputstring(char *string)
Eric Andersen62483552001-07-10 06:09:16 +00009768{
Denis Vlasenkob012b102007-02-19 22:43:01 +00009769 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +00009770 pushfile();
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009771 g_parsefile->next_to_pgetc = string;
9772 g_parsefile->left_in_line = strlen(string);
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009773 g_parsefile->buf = NULL;
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009774 g_parsefile->linno = 1;
Denis Vlasenkob012b102007-02-19 22:43:01 +00009775 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00009776}
9777
9778
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00009779/* ============ mail.c
9780 *
9781 * Routines to check for mail.
Eric Andersencb57d552001-06-28 07:25:16 +00009782 */
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00009783
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00009784#if ENABLE_ASH_MAIL
Eric Andersencb57d552001-06-28 07:25:16 +00009785
Eric Andersencb57d552001-06-28 07:25:16 +00009786#define MAXMBOXES 10
9787
Eric Andersenc470f442003-07-28 09:56:35 +00009788/* times of mailboxes */
9789static time_t mailtime[MAXMBOXES];
9790/* Set if MAIL or MAILPATH is changed. */
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +00009791static smallint mail_var_path_changed;
Eric Andersencb57d552001-06-28 07:25:16 +00009792
Eric Andersencb57d552001-06-28 07:25:16 +00009793/*
Eric Andersenc470f442003-07-28 09:56:35 +00009794 * Print appropriate message(s) if mail has arrived.
9795 * If mail_var_path_changed is set,
9796 * then the value of MAIL has mail_var_path_changed,
9797 * so we just update the values.
Eric Andersencb57d552001-06-28 07:25:16 +00009798 */
Eric Andersenc470f442003-07-28 09:56:35 +00009799static void
9800chkmail(void)
Eric Andersencb57d552001-06-28 07:25:16 +00009801{
Eric Andersencb57d552001-06-28 07:25:16 +00009802 const char *mpath;
9803 char *p;
9804 char *q;
Eric Andersenc470f442003-07-28 09:56:35 +00009805 time_t *mtp;
Eric Andersencb57d552001-06-28 07:25:16 +00009806 struct stackmark smark;
9807 struct stat statb;
9808
Eric Andersencb57d552001-06-28 07:25:16 +00009809 setstackmark(&smark);
Eric Andersenc470f442003-07-28 09:56:35 +00009810 mpath = mpathset() ? mpathval() : mailval();
9811 for (mtp = mailtime; mtp < mailtime + MAXMBOXES; mtp++) {
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02009812 p = path_advance(&mpath, nullstr);
Eric Andersencb57d552001-06-28 07:25:16 +00009813 if (p == NULL)
9814 break;
9815 if (*p == '\0')
9816 continue;
Denis Vlasenkof7d56652008-03-25 05:51:41 +00009817 for (q = p; *q; q++)
9818 continue;
Denis Vlasenkoa7189f02006-11-17 20:29:00 +00009819#if DEBUG
Eric Andersencb57d552001-06-28 07:25:16 +00009820 if (q[-1] != '/')
9821 abort();
9822#endif
Eric Andersenc470f442003-07-28 09:56:35 +00009823 q[-1] = '\0'; /* delete trailing '/' */
9824 if (stat(p, &statb) < 0) {
9825 *mtp = 0;
9826 continue;
Eric Andersencb57d552001-06-28 07:25:16 +00009827 }
Eric Andersenc470f442003-07-28 09:56:35 +00009828 if (!mail_var_path_changed && statb.st_mtime != *mtp) {
9829 fprintf(
9830 stderr, snlfmt,
9831 pathopt ? pathopt : "you have mail"
9832 );
9833 }
9834 *mtp = statb.st_mtime;
Eric Andersencb57d552001-06-28 07:25:16 +00009835 }
Eric Andersenc470f442003-07-28 09:56:35 +00009836 mail_var_path_changed = 0;
Eric Andersencb57d552001-06-28 07:25:16 +00009837 popstackmark(&smark);
9838}
Eric Andersencb57d552001-06-28 07:25:16 +00009839
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009840static void FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00009841changemail(const char *val UNUSED_PARAM)
Eric Andersenc470f442003-07-28 09:56:35 +00009842{
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +00009843 mail_var_path_changed = 1;
Eric Andersenc470f442003-07-28 09:56:35 +00009844}
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00009845
Denis Vlasenko131ae172007-02-18 13:00:19 +00009846#endif /* ASH_MAIL */
Eric Andersenc470f442003-07-28 09:56:35 +00009847
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00009848
9849/* ============ ??? */
9850
Eric Andersencb57d552001-06-28 07:25:16 +00009851/*
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009852 * Set the shell parameters.
Eric Andersencb57d552001-06-28 07:25:16 +00009853 */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009854static void
9855setparam(char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +00009856{
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009857 char **newparam;
9858 char **ap;
9859 int nparam;
Eric Andersencb57d552001-06-28 07:25:16 +00009860
Denis Vlasenkof7d56652008-03-25 05:51:41 +00009861 for (nparam = 0; argv[nparam]; nparam++)
9862 continue;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009863 ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
9864 while (*argv) {
9865 *ap++ = ckstrdup(*argv++);
Eric Andersencb57d552001-06-28 07:25:16 +00009866 }
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009867 *ap = NULL;
9868 freeparam(&shellparam);
Denis Vlasenko01631112007-12-16 17:20:38 +00009869 shellparam.malloced = 1;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009870 shellparam.nparam = nparam;
9871 shellparam.p = newparam;
9872#if ENABLE_ASH_GETOPTS
9873 shellparam.optind = 1;
9874 shellparam.optoff = -1;
9875#endif
Eric Andersencb57d552001-06-28 07:25:16 +00009876}
9877
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00009878/*
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009879 * Process shell options. The global variable argptr contains a pointer
9880 * to the argument list; we advance it past the options.
Denis Vlasenko94e87bc2008-02-14 16:51:58 +00009881 *
9882 * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
9883 * For a non-interactive shell, an error condition encountered
9884 * by a special built-in ... shall cause the shell to write a diagnostic message
9885 * to standard error and exit as shown in the following table:
Denis Vlasenko56244732008-02-17 15:14:04 +00009886 * Error Special Built-In
Denis Vlasenko94e87bc2008-02-14 16:51:58 +00009887 * ...
9888 * Utility syntax error (option or operand error) Shall exit
9889 * ...
9890 * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
9891 * we see that bash does not do that (set "finishes" with error code 1 instead,
9892 * and shell continues), and people rely on this behavior!
9893 * Testcase:
9894 * set -o barfoo 2>/dev/null
9895 * echo $?
9896 *
9897 * Oh well. Let's mimic that.
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00009898 */
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009899static int
Denis Vlasenkodddfaff2008-05-06 15:30:27 +00009900plus_minus_o(char *name, int val)
Eric Andersen62483552001-07-10 06:09:16 +00009901{
9902 int i;
9903
Denis Vlasenkoa624c112007-02-19 22:45:43 +00009904 if (name) {
9905 for (i = 0; i < NOPTS; i++) {
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00009906 if (strcmp(name, optnames(i)) == 0) {
Eric Andersenc470f442003-07-28 09:56:35 +00009907 optlist[i] = val;
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009908 return 0;
Eric Andersen62483552001-07-10 06:09:16 +00009909 }
Denis Vlasenkoa624c112007-02-19 22:45:43 +00009910 }
Denis Vlasenkodddfaff2008-05-06 15:30:27 +00009911 ash_msg("illegal option %co %s", val ? '-' : '+', name);
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009912 return 1;
Eric Andersen62483552001-07-10 06:09:16 +00009913 }
Denis Vlasenko6b06cb82008-05-15 21:30:45 +00009914 for (i = 0; i < NOPTS; i++) {
Denis Vlasenkodddfaff2008-05-06 15:30:27 +00009915 if (val) {
9916 out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
9917 } else {
9918 out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
9919 }
Denis Vlasenko6b06cb82008-05-15 21:30:45 +00009920 }
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009921 return 0;
Eric Andersen62483552001-07-10 06:09:16 +00009922}
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009923static void
9924setoption(int flag, int val)
9925{
9926 int i;
9927
9928 for (i = 0; i < NOPTS; i++) {
9929 if (optletters(i) == flag) {
9930 optlist[i] = val;
9931 return;
9932 }
9933 }
Denis Vlasenkodddfaff2008-05-06 15:30:27 +00009934 ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009935 /* NOTREACHED */
9936}
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009937static int
Eric Andersenc470f442003-07-28 09:56:35 +00009938options(int cmdline)
Eric Andersencb57d552001-06-28 07:25:16 +00009939{
9940 char *p;
9941 int val;
9942 int c;
9943
9944 if (cmdline)
9945 minusc = NULL;
9946 while ((p = *argptr) != NULL) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009947 c = *p++;
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +00009948 if (c != '-' && c != '+')
9949 break;
9950 argptr++;
9951 val = 0; /* val = 0 if c == '+' */
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009952 if (c == '-') {
Eric Andersencb57d552001-06-28 07:25:16 +00009953 val = 1;
Denis Vlasenko9f739442006-12-16 23:49:13 +00009954 if (p[0] == '\0' || LONE_DASH(p)) {
Eric Andersen2870d962001-07-02 17:27:21 +00009955 if (!cmdline) {
9956 /* "-" means turn off -x and -v */
9957 if (p[0] == '\0')
9958 xflag = vflag = 0;
9959 /* "--" means reset params */
9960 else if (*argptr == NULL)
Eric Andersencb57d552001-06-28 07:25:16 +00009961 setparam(argptr);
Eric Andersen2870d962001-07-02 17:27:21 +00009962 }
Eric Andersenc470f442003-07-28 09:56:35 +00009963 break; /* "-" or "--" terminates options */
Eric Andersencb57d552001-06-28 07:25:16 +00009964 }
Eric Andersencb57d552001-06-28 07:25:16 +00009965 }
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +00009966 /* first char was + or - */
Eric Andersencb57d552001-06-28 07:25:16 +00009967 while ((c = *p++) != '\0') {
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +00009968 /* bash 3.2 indeed handles -c CMD and +c CMD the same */
Eric Andersencb57d552001-06-28 07:25:16 +00009969 if (c == 'c' && cmdline) {
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +00009970 minusc = p; /* command is after shell args */
Eric Andersencb57d552001-06-28 07:25:16 +00009971 } else if (c == 'o') {
Denis Vlasenkodddfaff2008-05-06 15:30:27 +00009972 if (plus_minus_o(*argptr, val)) {
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009973 /* it already printed err message */
9974 return 1; /* error */
9975 }
Eric Andersencb57d552001-06-28 07:25:16 +00009976 if (*argptr)
9977 argptr++;
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +00009978 } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
9979 isloginsh = 1;
9980 /* bash does not accept +-login, we also won't */
9981 } else if (cmdline && val && (c == '-')) { /* long options */
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00009982 if (strcmp(p, "login") == 0)
Robert Griebl64f70cc2002-05-14 23:22:06 +00009983 isloginsh = 1;
9984 break;
Eric Andersencb57d552001-06-28 07:25:16 +00009985 } else {
9986 setoption(c, val);
9987 }
9988 }
9989 }
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009990 return 0;
Eric Andersencb57d552001-06-28 07:25:16 +00009991}
9992
Eric Andersencb57d552001-06-28 07:25:16 +00009993/*
Eric Andersencb57d552001-06-28 07:25:16 +00009994 * The shift builtin command.
9995 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009996static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00009997shiftcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +00009998{
9999 int n;
10000 char **ap1, **ap2;
10001
10002 n = 1;
Denis Vlasenko68404f12008-03-17 09:00:54 +000010003 if (argv[1])
Eric Andersencb57d552001-06-28 07:25:16 +000010004 n = number(argv[1]);
10005 if (n > shellparam.nparam)
Denis Vlasenkoc90e1be2008-07-30 15:35:05 +000010006 n = 0; /* bash compat, was = shellparam.nparam; */
Denis Vlasenkob012b102007-02-19 22:43:01 +000010007 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +000010008 shellparam.nparam -= n;
Denis Vlasenko2da584f2007-02-19 22:44:05 +000010009 for (ap1 = shellparam.p; --n >= 0; ap1++) {
Denis Vlasenko01631112007-12-16 17:20:38 +000010010 if (shellparam.malloced)
Denis Vlasenkob012b102007-02-19 22:43:01 +000010011 free(*ap1);
Eric Andersencb57d552001-06-28 07:25:16 +000010012 }
10013 ap2 = shellparam.p;
Denis Vlasenkof7d56652008-03-25 05:51:41 +000010014 while ((*ap2++ = *ap1++) != NULL)
10015 continue;
Denis Vlasenko131ae172007-02-18 13:00:19 +000010016#if ENABLE_ASH_GETOPTS
Eric Andersencb57d552001-06-28 07:25:16 +000010017 shellparam.optind = 1;
10018 shellparam.optoff = -1;
Eric Andersenc470f442003-07-28 09:56:35 +000010019#endif
Denis Vlasenkob012b102007-02-19 22:43:01 +000010020 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +000010021 return 0;
10022}
10023
Eric Andersencb57d552001-06-28 07:25:16 +000010024/*
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010025 * POSIX requires that 'set' (but not export or readonly) output the
10026 * variables in lexicographic order - by the locale's collating order (sigh).
10027 * Maybe we could keep them in an ordered balanced binary tree
10028 * instead of hashed lists.
10029 * For now just roll 'em through qsort for printing...
10030 */
10031static int
10032showvars(const char *sep_prefix, int on, int off)
10033{
10034 const char *sep;
10035 char **ep, **epend;
10036
10037 ep = listvars(on, off, &epend);
10038 qsort(ep, epend - ep, sizeof(char *), vpcmp);
10039
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +000010040 sep = *sep_prefix ? " " : sep_prefix;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010041
10042 for (; ep < epend; ep++) {
10043 const char *p;
10044 const char *q;
10045
10046 p = strchrnul(*ep, '=');
10047 q = nullstr;
10048 if (*p)
10049 q = single_quote(++p);
10050 out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
10051 }
10052 return 0;
10053}
10054
10055/*
Eric Andersencb57d552001-06-28 07:25:16 +000010056 * The set command builtin.
10057 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010058static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000010059setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersencb57d552001-06-28 07:25:16 +000010060{
Denis Vlasenko28bf6712008-02-14 15:01:47 +000010061 int retval;
10062
Denis Vlasenko68404f12008-03-17 09:00:54 +000010063 if (!argv[1])
Eric Andersenc470f442003-07-28 09:56:35 +000010064 return showvars(nullstr, 0, VUNSET);
Denis Vlasenkob012b102007-02-19 22:43:01 +000010065 INT_OFF;
Denis Vlasenko28bf6712008-02-14 15:01:47 +000010066 retval = 1;
10067 if (!options(0)) { /* if no parse error... */
10068 retval = 0;
10069 optschanged();
10070 if (*argptr != NULL) {
10071 setparam(argptr);
10072 }
Eric Andersencb57d552001-06-28 07:25:16 +000010073 }
Denis Vlasenkob012b102007-02-19 22:43:01 +000010074 INT_ON;
Denis Vlasenko28bf6712008-02-14 15:01:47 +000010075 return retval;
Eric Andersencb57d552001-06-28 07:25:16 +000010076}
10077
Denis Vlasenko131ae172007-02-18 13:00:19 +000010078#if ENABLE_ASH_RANDOM_SUPPORT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010079static void FAST_FUNC
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000010080change_random(const char *value)
Eric Andersenef02f822004-03-11 13:34:24 +000010081{
Denis Vlasenko448d30e2008-06-27 00:24:11 +000010082 /* Galois LFSR parameter */
10083 /* Taps at 32 31 29 1: */
10084 enum { MASK = 0x8000000b };
10085 /* Another example - taps at 32 31 30 10: */
10086 /* MASK = 0x00400007 */
10087
Denys Vlasenko3ea2e822009-10-09 20:59:04 +020010088 uint32_t t;
10089
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010090 if (value == NULL) {
Eric Andersen16767e22004-03-16 05:14:10 +000010091 /* "get", generate */
Denys Vlasenko3ea2e822009-10-09 20:59:04 +020010092 t = next_random(&random_gen);
Eric Andersen16767e22004-03-16 05:14:10 +000010093 /* set without recursion */
Denis Vlasenko448d30e2008-06-27 00:24:11 +000010094 setvar(vrandom.text, utoa(t), VNOFUNC);
Eric Andersen16767e22004-03-16 05:14:10 +000010095 vrandom.flags &= ~VNOFUNC;
10096 } else {
10097 /* set/reset */
Denys Vlasenko3ea2e822009-10-09 20:59:04 +020010098 t = strtoul(value, NULL, 10);
10099 INIT_RANDOM_T(&random_gen, (t ? t : 1), t);
Eric Andersen16767e22004-03-16 05:14:10 +000010100 }
Eric Andersenef02f822004-03-11 13:34:24 +000010101}
Eric Andersen16767e22004-03-16 05:14:10 +000010102#endif
10103
Denis Vlasenko131ae172007-02-18 13:00:19 +000010104#if ENABLE_ASH_GETOPTS
Eric Andersencb57d552001-06-28 07:25:16 +000010105static int
Eric Andersenc470f442003-07-28 09:56:35 +000010106getopts(char *optstr, char *optvar, char **optfirst, int *param_optind, int *optoff)
Eric Andersencb57d552001-06-28 07:25:16 +000010107{
10108 char *p, *q;
10109 char c = '?';
10110 int done = 0;
10111 int err = 0;
Eric Andersena48b0a32003-10-22 10:56:47 +000010112 char s[12];
10113 char **optnext;
Eric Andersencb57d552001-06-28 07:25:16 +000010114
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010115 if (*param_optind < 1)
Eric Andersena48b0a32003-10-22 10:56:47 +000010116 return 1;
10117 optnext = optfirst + *param_optind - 1;
10118
Denis Vlasenko6b06cb82008-05-15 21:30:45 +000010119 if (*param_optind <= 1 || *optoff < 0 || (int)strlen(optnext[-1]) < *optoff)
Eric Andersencb57d552001-06-28 07:25:16 +000010120 p = NULL;
10121 else
Eric Andersena48b0a32003-10-22 10:56:47 +000010122 p = optnext[-1] + *optoff;
Eric Andersencb57d552001-06-28 07:25:16 +000010123 if (p == NULL || *p == '\0') {
10124 /* Current word is done, advance */
Eric Andersencb57d552001-06-28 07:25:16 +000010125 p = *optnext;
10126 if (p == NULL || *p != '-' || *++p == '\0') {
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010127 atend:
Eric Andersencb57d552001-06-28 07:25:16 +000010128 p = NULL;
10129 done = 1;
10130 goto out;
10131 }
10132 optnext++;
Denis Vlasenko9f739442006-12-16 23:49:13 +000010133 if (LONE_DASH(p)) /* check for "--" */
Eric Andersencb57d552001-06-28 07:25:16 +000010134 goto atend;
10135 }
10136
10137 c = *p++;
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +000010138 for (q = optstr; *q != c;) {
Eric Andersencb57d552001-06-28 07:25:16 +000010139 if (*q == '\0') {
10140 if (optstr[0] == ':') {
10141 s[0] = c;
10142 s[1] = '\0';
10143 err |= setvarsafe("OPTARG", s, 0);
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010144 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000010145 fprintf(stderr, "Illegal option -%c\n", c);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010146 unsetvar("OPTARG");
Eric Andersencb57d552001-06-28 07:25:16 +000010147 }
10148 c = '?';
Eric Andersenc470f442003-07-28 09:56:35 +000010149 goto out;
Eric Andersencb57d552001-06-28 07:25:16 +000010150 }
10151 if (*++q == ':')
10152 q++;
10153 }
10154
10155 if (*++q == ':') {
10156 if (*p == '\0' && (p = *optnext) == NULL) {
10157 if (optstr[0] == ':') {
10158 s[0] = c;
10159 s[1] = '\0';
10160 err |= setvarsafe("OPTARG", s, 0);
10161 c = ':';
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010162 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000010163 fprintf(stderr, "No arg for -%c option\n", c);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010164 unsetvar("OPTARG");
Eric Andersencb57d552001-06-28 07:25:16 +000010165 c = '?';
10166 }
Eric Andersenc470f442003-07-28 09:56:35 +000010167 goto out;
Eric Andersencb57d552001-06-28 07:25:16 +000010168 }
10169
10170 if (p == *optnext)
10171 optnext++;
Eric Andersenc470f442003-07-28 09:56:35 +000010172 err |= setvarsafe("OPTARG", p, 0);
Eric Andersencb57d552001-06-28 07:25:16 +000010173 p = NULL;
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010174 } else
Eric Andersenc470f442003-07-28 09:56:35 +000010175 err |= setvarsafe("OPTARG", nullstr, 0);
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010176 out:
Eric Andersencb57d552001-06-28 07:25:16 +000010177 *optoff = p ? p - *(optnext - 1) : -1;
Eric Andersenc470f442003-07-28 09:56:35 +000010178 *param_optind = optnext - optfirst + 1;
10179 fmtstr(s, sizeof(s), "%d", *param_optind);
Eric Andersencb57d552001-06-28 07:25:16 +000010180 err |= setvarsafe("OPTIND", s, VNOFUNC);
10181 s[0] = c;
10182 s[1] = '\0';
10183 err |= setvarsafe(optvar, s, 0);
10184 if (err) {
Eric Andersenc470f442003-07-28 09:56:35 +000010185 *param_optind = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010186 *optoff = -1;
Denis Vlasenkob012b102007-02-19 22:43:01 +000010187 flush_stdout_stderr();
10188 raise_exception(EXERROR);
Eric Andersencb57d552001-06-28 07:25:16 +000010189 }
10190 return done;
10191}
Eric Andersenc470f442003-07-28 09:56:35 +000010192
10193/*
10194 * The getopts builtin. Shellparam.optnext points to the next argument
10195 * to be processed. Shellparam.optptr points to the next character to
10196 * be processed in the current argument. If shellparam.optnext is NULL,
10197 * then it's the first time getopts has been called.
10198 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010199static int FAST_FUNC
Eric Andersenc470f442003-07-28 09:56:35 +000010200getoptscmd(int argc, char **argv)
10201{
10202 char **optbase;
10203
10204 if (argc < 3)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +000010205 ash_msg_and_raise_error("usage: getopts optstring var [arg]");
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010206 if (argc == 3) {
Eric Andersenc470f442003-07-28 09:56:35 +000010207 optbase = shellparam.p;
10208 if (shellparam.optind > shellparam.nparam + 1) {
10209 shellparam.optind = 1;
10210 shellparam.optoff = -1;
10211 }
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010212 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000010213 optbase = &argv[3];
10214 if (shellparam.optind > argc - 2) {
10215 shellparam.optind = 1;
10216 shellparam.optoff = -1;
10217 }
10218 }
10219
10220 return getopts(argv[1], argv[2], optbase, &shellparam.optind,
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010221 &shellparam.optoff);
Eric Andersenc470f442003-07-28 09:56:35 +000010222}
Denis Vlasenko131ae172007-02-18 13:00:19 +000010223#endif /* ASH_GETOPTS */
Eric Andersencb57d552001-06-28 07:25:16 +000010224
Eric Andersencb57d552001-06-28 07:25:16 +000010225
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010226/* ============ Shell parser */
Eric Andersencb57d552001-06-28 07:25:16 +000010227
Denis Vlasenkob07a4962008-06-22 13:16:23 +000010228struct heredoc {
10229 struct heredoc *next; /* next here document in list */
10230 union node *here; /* redirection node */
10231 char *eofmark; /* string indicating end of input */
10232 smallint striptabs; /* if set, strip leading tabs */
10233};
10234
10235static smallint tokpushback; /* last token pushed back */
10236static smallint parsebackquote; /* nonzero if we are inside backquotes */
10237static smallint quoteflag; /* set if (part of) last token was quoted */
10238static token_id_t lasttoken; /* last token read (integer id Txxx) */
10239static struct heredoc *heredoclist; /* list of here documents to read */
10240static char *wordtext; /* text of last word returned by readtoken */
10241static struct nodelist *backquotelist;
10242static union node *redirnode;
10243static struct heredoc *heredoc;
Denis Vlasenko99eb8502007-02-23 21:09:49 +000010244
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010245/*
10246 * Called when an unexpected token is read during the parse. The argument
10247 * is the token that is expected, or -1 if more than one type of token can
10248 * occur at this point.
10249 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000010250static void raise_error_unexpected_syntax(int) NORETURN;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010251static void
10252raise_error_unexpected_syntax(int token)
10253{
10254 char msg[64];
10255 int l;
10256
Denis Vlasenko7b2294e2008-11-28 03:50:46 +000010257 l = sprintf(msg, "unexpected %s", tokname(lasttoken));
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010258 if (token >= 0)
10259 sprintf(msg + l, " (expecting %s)", tokname(token));
10260 raise_error_syntax(msg);
10261 /* NOTREACHED */
10262}
Eric Andersencb57d552001-06-28 07:25:16 +000010263
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010264#define EOFMARKLEN 79
Eric Andersencb57d552001-06-28 07:25:16 +000010265
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010266/* parsing is heavily cross-recursive, need these forward decls */
10267static union node *andor(void);
10268static union node *pipeline(void);
10269static union node *parse_command(void);
10270static void parseheredoc(void);
10271static char peektoken(void);
10272static int readtoken(void);
Eric Andersencb57d552001-06-28 07:25:16 +000010273
Eric Andersenc470f442003-07-28 09:56:35 +000010274static union node *
10275list(int nlflag)
Eric Andersencb57d552001-06-28 07:25:16 +000010276{
10277 union node *n1, *n2, *n3;
10278 int tok;
10279
Eric Andersenc470f442003-07-28 09:56:35 +000010280 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10281 if (nlflag == 2 && peektoken())
Eric Andersencb57d552001-06-28 07:25:16 +000010282 return NULL;
10283 n1 = NULL;
10284 for (;;) {
10285 n2 = andor();
10286 tok = readtoken();
10287 if (tok == TBACKGND) {
Eric Andersenc470f442003-07-28 09:56:35 +000010288 if (n2->type == NPIPE) {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +000010289 n2->npipe.pipe_backgnd = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010290 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000010291 if (n2->type != NREDIR) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010292 n3 = stzalloc(sizeof(struct nredir));
Eric Andersenc470f442003-07-28 09:56:35 +000010293 n3->nredir.n = n2;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010294 /*n3->nredir.redirect = NULL; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000010295 n2 = n3;
10296 }
10297 n2->type = NBACKGND;
Eric Andersencb57d552001-06-28 07:25:16 +000010298 }
10299 }
10300 if (n1 == NULL) {
10301 n1 = n2;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010302 } else {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010303 n3 = stzalloc(sizeof(struct nbinary));
Eric Andersencb57d552001-06-28 07:25:16 +000010304 n3->type = NSEMI;
10305 n3->nbinary.ch1 = n1;
10306 n3->nbinary.ch2 = n2;
10307 n1 = n3;
10308 }
10309 switch (tok) {
10310 case TBACKGND:
10311 case TSEMI:
10312 tok = readtoken();
10313 /* fall through */
10314 case TNL:
10315 if (tok == TNL) {
10316 parseheredoc();
Eric Andersenc470f442003-07-28 09:56:35 +000010317 if (nlflag == 1)
Eric Andersencb57d552001-06-28 07:25:16 +000010318 return n1;
10319 } else {
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010320 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010321 }
Eric Andersenc470f442003-07-28 09:56:35 +000010322 checkkwd = CHKNL | CHKKWD | CHKALIAS;
Manuel Novoa III 16815d42001-08-10 19:36:07 +000010323 if (peektoken())
Eric Andersencb57d552001-06-28 07:25:16 +000010324 return n1;
10325 break;
10326 case TEOF:
10327 if (heredoclist)
10328 parseheredoc();
10329 else
Eric Andersenc470f442003-07-28 09:56:35 +000010330 pungetc(); /* push back EOF on input */
Eric Andersencb57d552001-06-28 07:25:16 +000010331 return n1;
10332 default:
Eric Andersenc470f442003-07-28 09:56:35 +000010333 if (nlflag == 1)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010334 raise_error_unexpected_syntax(-1);
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010335 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010336 return n1;
10337 }
10338 }
10339}
10340
Eric Andersenc470f442003-07-28 09:56:35 +000010341static union node *
10342andor(void)
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010343{
Eric Andersencb57d552001-06-28 07:25:16 +000010344 union node *n1, *n2, *n3;
10345 int t;
10346
Eric Andersencb57d552001-06-28 07:25:16 +000010347 n1 = pipeline();
10348 for (;;) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010349 t = readtoken();
10350 if (t == TAND) {
Eric Andersencb57d552001-06-28 07:25:16 +000010351 t = NAND;
10352 } else if (t == TOR) {
10353 t = NOR;
10354 } else {
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010355 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010356 return n1;
10357 }
Eric Andersenc470f442003-07-28 09:56:35 +000010358 checkkwd = CHKNL | CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010359 n2 = pipeline();
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010360 n3 = stzalloc(sizeof(struct nbinary));
Eric Andersencb57d552001-06-28 07:25:16 +000010361 n3->type = t;
10362 n3->nbinary.ch1 = n1;
10363 n3->nbinary.ch2 = n2;
10364 n1 = n3;
10365 }
10366}
10367
Eric Andersenc470f442003-07-28 09:56:35 +000010368static union node *
10369pipeline(void)
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010370{
Eric Andersencb57d552001-06-28 07:25:16 +000010371 union node *n1, *n2, *pipenode;
10372 struct nodelist *lp, *prev;
10373 int negate;
10374
10375 negate = 0;
10376 TRACE(("pipeline: entered\n"));
10377 if (readtoken() == TNOT) {
10378 negate = !negate;
Eric Andersenc470f442003-07-28 09:56:35 +000010379 checkkwd = CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010380 } else
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010381 tokpushback = 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010382 n1 = parse_command();
Eric Andersencb57d552001-06-28 07:25:16 +000010383 if (readtoken() == TPIPE) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010384 pipenode = stzalloc(sizeof(struct npipe));
Eric Andersencb57d552001-06-28 07:25:16 +000010385 pipenode->type = NPIPE;
Denis Vlasenko2dc240c2008-07-24 06:07:50 +000010386 /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010387 lp = stzalloc(sizeof(struct nodelist));
Eric Andersencb57d552001-06-28 07:25:16 +000010388 pipenode->npipe.cmdlist = lp;
10389 lp->n = n1;
10390 do {
10391 prev = lp;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010392 lp = stzalloc(sizeof(struct nodelist));
Eric Andersenc470f442003-07-28 09:56:35 +000010393 checkkwd = CHKNL | CHKKWD | CHKALIAS;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010394 lp->n = parse_command();
Eric Andersencb57d552001-06-28 07:25:16 +000010395 prev->next = lp;
10396 } while (readtoken() == TPIPE);
10397 lp->next = NULL;
10398 n1 = pipenode;
10399 }
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010400 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010401 if (negate) {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010402 n2 = stzalloc(sizeof(struct nnot));
Eric Andersencb57d552001-06-28 07:25:16 +000010403 n2->type = NNOT;
10404 n2->nnot.com = n1;
10405 return n2;
Denis Vlasenko2da584f2007-02-19 22:44:05 +000010406 }
10407 return n1;
Eric Andersencb57d552001-06-28 07:25:16 +000010408}
10409
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010410static union node *
10411makename(void)
10412{
10413 union node *n;
10414
Denis Vlasenko597906c2008-02-20 16:38:54 +000010415 n = stzalloc(sizeof(struct narg));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010416 n->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010417 /*n->narg.next = NULL; - stzalloc did it */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010418 n->narg.text = wordtext;
10419 n->narg.backquote = backquotelist;
10420 return n;
10421}
10422
10423static void
10424fixredir(union node *n, const char *text, int err)
10425{
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000010426 int fd;
10427
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010428 TRACE(("Fix redir %s %d\n", text, err));
10429 if (!err)
10430 n->ndup.vname = NULL;
10431
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000010432 fd = bb_strtou(text, NULL, 10);
10433 if (!errno && fd >= 0)
10434 n->ndup.dupfd = fd;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010435 else if (LONE_DASH(text))
10436 n->ndup.dupfd = -1;
10437 else {
10438 if (err)
Denis Vlasenko559691a2008-10-05 18:39:31 +000010439 raise_error_syntax("bad fd number");
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010440 n->ndup.vname = makename();
10441 }
10442}
10443
10444/*
10445 * Returns true if the text contains nothing to expand (no dollar signs
10446 * or backquotes).
10447 */
10448static int
Denis Vlasenko68819d12008-12-15 11:26:36 +000010449noexpand(const char *text)
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010450{
Denis Vlasenko68819d12008-12-15 11:26:36 +000010451 const char *p;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010452 char c;
10453
10454 p = text;
10455 while ((c = *p++) != '\0') {
10456 if (c == CTLQUOTEMARK)
10457 continue;
10458 if (c == CTLESC)
10459 p++;
Denis Vlasenko68819d12008-12-15 11:26:36 +000010460 else if (SIT((signed char)c, BASESYNTAX) == CCTL)
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010461 return 0;
10462 }
10463 return 1;
10464}
10465
10466static void
10467parsefname(void)
10468{
10469 union node *n = redirnode;
10470
10471 if (readtoken() != TWORD)
10472 raise_error_unexpected_syntax(-1);
10473 if (n->type == NHERE) {
10474 struct heredoc *here = heredoc;
10475 struct heredoc *p;
10476 int i;
10477
10478 if (quoteflag == 0)
10479 n->type = NXHERE;
10480 TRACE(("Here document %d\n", n->type));
10481 if (!noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
Denis Vlasenko559691a2008-10-05 18:39:31 +000010482 raise_error_syntax("illegal eof marker for << redirection");
Denys Vlasenkob6c84342009-08-29 20:23:20 +020010483 rmescapes(wordtext, 0);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010484 here->eofmark = wordtext;
10485 here->next = NULL;
10486 if (heredoclist == NULL)
10487 heredoclist = here;
10488 else {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010489 for (p = heredoclist; p->next; p = p->next)
10490 continue;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010491 p->next = here;
10492 }
10493 } else if (n->type == NTOFD || n->type == NFROMFD) {
10494 fixredir(n, wordtext, 0);
10495 } else {
10496 n->nfile.fname = makename();
10497 }
10498}
Eric Andersencb57d552001-06-28 07:25:16 +000010499
Eric Andersenc470f442003-07-28 09:56:35 +000010500static union node *
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010501simplecmd(void)
10502{
10503 union node *args, **app;
10504 union node *n = NULL;
10505 union node *vars, **vpp;
10506 union node **rpp, *redir;
10507 int savecheckkwd;
Denis Vlasenko80591b02008-03-25 07:49:43 +000010508#if ENABLE_ASH_BASH_COMPAT
10509 smallint double_brackets_flag = 0;
10510#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010511
10512 args = NULL;
10513 app = &args;
10514 vars = NULL;
10515 vpp = &vars;
10516 redir = NULL;
10517 rpp = &redir;
10518
10519 savecheckkwd = CHKALIAS;
10520 for (;;) {
Denis Vlasenko80591b02008-03-25 07:49:43 +000010521 int t;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010522 checkkwd = savecheckkwd;
Denis Vlasenko80591b02008-03-25 07:49:43 +000010523 t = readtoken();
10524 switch (t) {
10525#if ENABLE_ASH_BASH_COMPAT
10526 case TAND: /* "&&" */
10527 case TOR: /* "||" */
10528 if (!double_brackets_flag) {
10529 tokpushback = 1;
10530 goto out;
10531 }
10532 wordtext = (char *) (t == TAND ? "-a" : "-o");
10533#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010534 case TWORD:
Denis Vlasenko597906c2008-02-20 16:38:54 +000010535 n = stzalloc(sizeof(struct narg));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010536 n->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010537 /*n->narg.next = NULL; - stzalloc did it */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010538 n->narg.text = wordtext;
Denis Vlasenko80591b02008-03-25 07:49:43 +000010539#if ENABLE_ASH_BASH_COMPAT
10540 if (strcmp("[[", wordtext) == 0)
10541 double_brackets_flag = 1;
10542 else if (strcmp("]]", wordtext) == 0)
10543 double_brackets_flag = 0;
10544#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010545 n->narg.backquote = backquotelist;
10546 if (savecheckkwd && isassignment(wordtext)) {
10547 *vpp = n;
10548 vpp = &n->narg.next;
10549 } else {
10550 *app = n;
10551 app = &n->narg.next;
10552 savecheckkwd = 0;
10553 }
10554 break;
10555 case TREDIR:
10556 *rpp = n = redirnode;
10557 rpp = &n->nfile.next;
10558 parsefname(); /* read name of redirection file */
10559 break;
10560 case TLP:
10561 if (args && app == &args->narg.next
10562 && !vars && !redir
10563 ) {
10564 struct builtincmd *bcmd;
10565 const char *name;
10566
10567 /* We have a function */
10568 if (readtoken() != TRP)
10569 raise_error_unexpected_syntax(TRP);
10570 name = n->narg.text;
10571 if (!goodname(name)
10572 || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
10573 ) {
Denis Vlasenko559691a2008-10-05 18:39:31 +000010574 raise_error_syntax("bad function name");
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010575 }
10576 n->type = NDEFUN;
10577 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10578 n->narg.next = parse_command();
10579 return n;
10580 }
10581 /* fall through */
10582 default:
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010583 tokpushback = 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010584 goto out;
10585 }
10586 }
10587 out:
10588 *app = NULL;
10589 *vpp = NULL;
10590 *rpp = NULL;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010591 n = stzalloc(sizeof(struct ncmd));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010592 n->type = NCMD;
10593 n->ncmd.args = args;
10594 n->ncmd.assign = vars;
10595 n->ncmd.redirect = redir;
10596 return n;
10597}
10598
10599static union node *
10600parse_command(void)
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010601{
Eric Andersencb57d552001-06-28 07:25:16 +000010602 union node *n1, *n2;
10603 union node *ap, **app;
10604 union node *cp, **cpp;
10605 union node *redir, **rpp;
Eric Andersenc470f442003-07-28 09:56:35 +000010606 union node **rpp2;
Eric Andersencb57d552001-06-28 07:25:16 +000010607 int t;
10608
10609 redir = NULL;
Eric Andersenc470f442003-07-28 09:56:35 +000010610 rpp2 = &redir;
Eric Andersen88cec252001-09-06 17:35:20 +000010611
Eric Andersencb57d552001-06-28 07:25:16 +000010612 switch (readtoken()) {
Eric Andersenc470f442003-07-28 09:56:35 +000010613 default:
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010614 raise_error_unexpected_syntax(-1);
Eric Andersenc470f442003-07-28 09:56:35 +000010615 /* NOTREACHED */
Eric Andersencb57d552001-06-28 07:25:16 +000010616 case TIF:
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010617 n1 = stzalloc(sizeof(struct nif));
Eric Andersencb57d552001-06-28 07:25:16 +000010618 n1->type = NIF;
10619 n1->nif.test = list(0);
10620 if (readtoken() != TTHEN)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010621 raise_error_unexpected_syntax(TTHEN);
Eric Andersencb57d552001-06-28 07:25:16 +000010622 n1->nif.ifpart = list(0);
10623 n2 = n1;
10624 while (readtoken() == TELIF) {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010625 n2->nif.elsepart = stzalloc(sizeof(struct nif));
Eric Andersencb57d552001-06-28 07:25:16 +000010626 n2 = n2->nif.elsepart;
10627 n2->type = NIF;
10628 n2->nif.test = list(0);
10629 if (readtoken() != TTHEN)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010630 raise_error_unexpected_syntax(TTHEN);
Eric Andersencb57d552001-06-28 07:25:16 +000010631 n2->nif.ifpart = list(0);
10632 }
10633 if (lasttoken == TELSE)
10634 n2->nif.elsepart = list(0);
10635 else {
10636 n2->nif.elsepart = NULL;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010637 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010638 }
Eric Andersenc470f442003-07-28 09:56:35 +000010639 t = TFI;
Eric Andersencb57d552001-06-28 07:25:16 +000010640 break;
10641 case TWHILE:
Eric Andersenc470f442003-07-28 09:56:35 +000010642 case TUNTIL: {
Eric Andersencb57d552001-06-28 07:25:16 +000010643 int got;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010644 n1 = stzalloc(sizeof(struct nbinary));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010645 n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
Eric Andersencb57d552001-06-28 07:25:16 +000010646 n1->nbinary.ch1 = list(0);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010647 got = readtoken();
10648 if (got != TDO) {
Denis Vlasenko131ae172007-02-18 13:00:19 +000010649 TRACE(("expecting DO got %s %s\n", tokname(got),
10650 got == TWORD ? wordtext : ""));
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010651 raise_error_unexpected_syntax(TDO);
Eric Andersencb57d552001-06-28 07:25:16 +000010652 }
10653 n1->nbinary.ch2 = list(0);
Eric Andersenc470f442003-07-28 09:56:35 +000010654 t = TDONE;
Eric Andersencb57d552001-06-28 07:25:16 +000010655 break;
10656 }
10657 case TFOR:
Denis Vlasenko2dc240c2008-07-24 06:07:50 +000010658 if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
Denis Vlasenko559691a2008-10-05 18:39:31 +000010659 raise_error_syntax("bad for loop variable");
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010660 n1 = stzalloc(sizeof(struct nfor));
Eric Andersencb57d552001-06-28 07:25:16 +000010661 n1->type = NFOR;
10662 n1->nfor.var = wordtext;
Eric Andersenc470f442003-07-28 09:56:35 +000010663 checkkwd = CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010664 if (readtoken() == TIN) {
10665 app = &ap;
10666 while (readtoken() == TWORD) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010667 n2 = stzalloc(sizeof(struct narg));
Eric Andersencb57d552001-06-28 07:25:16 +000010668 n2->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010669 /*n2->narg.next = NULL; - stzalloc did it */
Eric Andersencb57d552001-06-28 07:25:16 +000010670 n2->narg.text = wordtext;
10671 n2->narg.backquote = backquotelist;
10672 *app = n2;
10673 app = &n2->narg.next;
10674 }
10675 *app = NULL;
10676 n1->nfor.args = ap;
10677 if (lasttoken != TNL && lasttoken != TSEMI)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010678 raise_error_unexpected_syntax(-1);
Eric Andersencb57d552001-06-28 07:25:16 +000010679 } else {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010680 n2 = stzalloc(sizeof(struct narg));
Eric Andersencb57d552001-06-28 07:25:16 +000010681 n2->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010682 /*n2->narg.next = NULL; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000010683 n2->narg.text = (char *)dolatstr;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010684 /*n2->narg.backquote = NULL;*/
Eric Andersencb57d552001-06-28 07:25:16 +000010685 n1->nfor.args = n2;
10686 /*
10687 * Newline or semicolon here is optional (but note
10688 * that the original Bourne shell only allowed NL).
10689 */
10690 if (lasttoken != TNL && lasttoken != TSEMI)
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010691 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010692 }
Eric Andersenc470f442003-07-28 09:56:35 +000010693 checkkwd = CHKNL | CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010694 if (readtoken() != TDO)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010695 raise_error_unexpected_syntax(TDO);
Eric Andersencb57d552001-06-28 07:25:16 +000010696 n1->nfor.body = list(0);
Eric Andersenc470f442003-07-28 09:56:35 +000010697 t = TDONE;
Eric Andersencb57d552001-06-28 07:25:16 +000010698 break;
10699 case TCASE:
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010700 n1 = stzalloc(sizeof(struct ncase));
Eric Andersencb57d552001-06-28 07:25:16 +000010701 n1->type = NCASE;
10702 if (readtoken() != TWORD)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010703 raise_error_unexpected_syntax(TWORD);
Denis Vlasenko597906c2008-02-20 16:38:54 +000010704 n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
Eric Andersencb57d552001-06-28 07:25:16 +000010705 n2->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010706 /*n2->narg.next = NULL; - stzalloc did it */
Eric Andersencb57d552001-06-28 07:25:16 +000010707 n2->narg.text = wordtext;
10708 n2->narg.backquote = backquotelist;
Eric Andersencb57d552001-06-28 07:25:16 +000010709 do {
Eric Andersenc470f442003-07-28 09:56:35 +000010710 checkkwd = CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010711 } while (readtoken() == TNL);
10712 if (lasttoken != TIN)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010713 raise_error_unexpected_syntax(TIN);
Eric Andersencb57d552001-06-28 07:25:16 +000010714 cpp = &n1->ncase.cases;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010715 next_case:
Eric Andersenc470f442003-07-28 09:56:35 +000010716 checkkwd = CHKNL | CHKKWD;
10717 t = readtoken();
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010718 while (t != TESAC) {
Eric Andersencb57d552001-06-28 07:25:16 +000010719 if (lasttoken == TLP)
10720 readtoken();
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010721 *cpp = cp = stzalloc(sizeof(struct nclist));
Eric Andersencb57d552001-06-28 07:25:16 +000010722 cp->type = NCLIST;
10723 app = &cp->nclist.pattern;
10724 for (;;) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010725 *app = ap = stzalloc(sizeof(struct narg));
Eric Andersencb57d552001-06-28 07:25:16 +000010726 ap->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010727 /*ap->narg.next = NULL; - stzalloc did it */
Eric Andersencb57d552001-06-28 07:25:16 +000010728 ap->narg.text = wordtext;
10729 ap->narg.backquote = backquotelist;
Eric Andersenc470f442003-07-28 09:56:35 +000010730 if (readtoken() != TPIPE)
Eric Andersencb57d552001-06-28 07:25:16 +000010731 break;
10732 app = &ap->narg.next;
10733 readtoken();
10734 }
Denis Vlasenko597906c2008-02-20 16:38:54 +000010735 //ap->narg.next = NULL;
Eric Andersencb57d552001-06-28 07:25:16 +000010736 if (lasttoken != TRP)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010737 raise_error_unexpected_syntax(TRP);
Eric Andersenc470f442003-07-28 09:56:35 +000010738 cp->nclist.body = list(2);
Eric Andersencb57d552001-06-28 07:25:16 +000010739
Eric Andersenc470f442003-07-28 09:56:35 +000010740 cpp = &cp->nclist.next;
10741
10742 checkkwd = CHKNL | CHKKWD;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010743 t = readtoken();
10744 if (t != TESAC) {
Eric Andersencb57d552001-06-28 07:25:16 +000010745 if (t != TENDCASE)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010746 raise_error_unexpected_syntax(TENDCASE);
10747 goto next_case;
Eric Andersencb57d552001-06-28 07:25:16 +000010748 }
Eric Andersenc470f442003-07-28 09:56:35 +000010749 }
Eric Andersencb57d552001-06-28 07:25:16 +000010750 *cpp = NULL;
Eric Andersenc470f442003-07-28 09:56:35 +000010751 goto redir;
Eric Andersencb57d552001-06-28 07:25:16 +000010752 case TLP:
Denis Vlasenko597906c2008-02-20 16:38:54 +000010753 n1 = stzalloc(sizeof(struct nredir));
Eric Andersencb57d552001-06-28 07:25:16 +000010754 n1->type = NSUBSHELL;
10755 n1->nredir.n = list(0);
Denis Vlasenko597906c2008-02-20 16:38:54 +000010756 /*n1->nredir.redirect = NULL; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000010757 t = TRP;
Eric Andersencb57d552001-06-28 07:25:16 +000010758 break;
10759 case TBEGIN:
10760 n1 = list(0);
Eric Andersenc470f442003-07-28 09:56:35 +000010761 t = TEND;
Eric Andersencb57d552001-06-28 07:25:16 +000010762 break;
Eric Andersencb57d552001-06-28 07:25:16 +000010763 case TWORD:
Eric Andersenc470f442003-07-28 09:56:35 +000010764 case TREDIR:
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010765 tokpushback = 1;
Eric Andersenc470f442003-07-28 09:56:35 +000010766 return simplecmd();
Eric Andersencb57d552001-06-28 07:25:16 +000010767 }
10768
Eric Andersenc470f442003-07-28 09:56:35 +000010769 if (readtoken() != t)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010770 raise_error_unexpected_syntax(t);
Eric Andersenc470f442003-07-28 09:56:35 +000010771
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010772 redir:
Eric Andersencb57d552001-06-28 07:25:16 +000010773 /* Now check for redirection which may follow command */
Eric Andersenc470f442003-07-28 09:56:35 +000010774 checkkwd = CHKKWD | CHKALIAS;
10775 rpp = rpp2;
Eric Andersencb57d552001-06-28 07:25:16 +000010776 while (readtoken() == TREDIR) {
10777 *rpp = n2 = redirnode;
10778 rpp = &n2->nfile.next;
10779 parsefname();
10780 }
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010781 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010782 *rpp = NULL;
10783 if (redir) {
10784 if (n1->type != NSUBSHELL) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010785 n2 = stzalloc(sizeof(struct nredir));
Eric Andersencb57d552001-06-28 07:25:16 +000010786 n2->type = NREDIR;
10787 n2->nredir.n = n1;
10788 n1 = n2;
10789 }
10790 n1->nredir.redirect = redir;
10791 }
Eric Andersencb57d552001-06-28 07:25:16 +000010792 return n1;
10793}
10794
Denis Vlasenkoef527f52008-06-23 01:52:30 +000010795#if ENABLE_ASH_BASH_COMPAT
10796static int decode_dollar_squote(void)
10797{
10798 static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
10799 int c, cnt;
10800 char *p;
10801 char buf[4];
10802
10803 c = pgetc();
10804 p = strchr(C_escapes, c);
10805 if (p) {
10806 buf[0] = c;
10807 p = buf;
10808 cnt = 3;
10809 if ((unsigned char)(c - '0') <= 7) { /* \ooo */
10810 do {
10811 c = pgetc();
10812 *++p = c;
10813 } while ((unsigned char)(c - '0') <= 7 && --cnt);
10814 pungetc();
10815 } else if (c == 'x') { /* \xHH */
10816 do {
10817 c = pgetc();
10818 *++p = c;
10819 } while (isxdigit(c) && --cnt);
10820 pungetc();
10821 if (cnt == 3) { /* \x but next char is "bad" */
10822 c = 'x';
10823 goto unrecognized;
10824 }
10825 } else { /* simple seq like \\ or \t */
10826 p++;
10827 }
10828 *p = '\0';
10829 p = buf;
10830 c = bb_process_escape_sequence((void*)&p);
10831 } else { /* unrecognized "\z": print both chars unless ' or " */
10832 if (c != '\'' && c != '"') {
10833 unrecognized:
10834 c |= 0x100; /* "please encode \, then me" */
10835 }
10836 }
10837 return c;
10838}
10839#endif
10840
Eric Andersencb57d552001-06-28 07:25:16 +000010841/*
10842 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
10843 * is not NULL, read a here document. In the latter case, eofmark is the
10844 * word which marks the end of the document and striptabs is true if
10845 * leading tabs should be stripped from the document. The argument firstc
10846 * is the first character of the input token or document.
10847 *
10848 * Because C does not have internal subroutines, I have simulated them
10849 * using goto's to implement the subroutine linkage. The following macros
10850 * will run code that appears at the end of readtoken1.
10851 */
Eric Andersen2870d962001-07-02 17:27:21 +000010852#define CHECKEND() {goto checkend; checkend_return:;}
10853#define PARSEREDIR() {goto parseredir; parseredir_return:;}
10854#define PARSESUB() {goto parsesub; parsesub_return:;}
10855#define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
10856#define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
10857#define PARSEARITH() {goto parsearith; parsearith_return:;}
Eric Andersencb57d552001-06-28 07:25:16 +000010858static int
Eric Andersenc470f442003-07-28 09:56:35 +000010859readtoken1(int firstc, int syntax, char *eofmark, int striptabs)
Manuel Novoa III 16815d42001-08-10 19:36:07 +000010860{
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010861 /* NB: syntax parameter fits into smallint */
Eric Andersencb57d552001-06-28 07:25:16 +000010862 int c = firstc;
10863 char *out;
10864 int len;
10865 char line[EOFMARKLEN + 1];
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010866 struct nodelist *bqlist;
10867 smallint quotef;
10868 smallint dblquote;
10869 smallint oldstyle;
10870 smallint prevsyntax; /* syntax before arithmetic */
Denis Vlasenko46a53062007-09-24 18:30:02 +000010871#if ENABLE_ASH_EXPAND_PRMT
10872 smallint pssyntax; /* we are expanding a prompt string */
10873#endif
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010874 int varnest; /* levels of variables expansion */
10875 int arinest; /* levels of arithmetic expansion */
10876 int parenlevel; /* levels of parens in arithmetic */
10877 int dqvarnest; /* levels of variables expansion within double quotes */
10878
Denis Vlasenko5e34ff22009-04-21 11:09:40 +000010879 IF_ASH_BASH_COMPAT(smallint bash_dollar_squote = 0;)
Denis Vlasenkoef527f52008-06-23 01:52:30 +000010880
Eric Andersencb57d552001-06-28 07:25:16 +000010881#if __GNUC__
10882 /* Avoid longjmp clobbering */
10883 (void) &out;
10884 (void) &quotef;
10885 (void) &dblquote;
10886 (void) &varnest;
10887 (void) &arinest;
10888 (void) &parenlevel;
10889 (void) &dqvarnest;
10890 (void) &oldstyle;
10891 (void) &prevsyntax;
10892 (void) &syntax;
10893#endif
Denis Vlasenko41eb3002008-11-28 03:42:31 +000010894 startlinno = g_parsefile->linno;
Eric Andersencb57d552001-06-28 07:25:16 +000010895 bqlist = NULL;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010896 quotef = 0;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010897 oldstyle = 0;
10898 prevsyntax = 0;
Denis Vlasenko46a53062007-09-24 18:30:02 +000010899#if ENABLE_ASH_EXPAND_PRMT
10900 pssyntax = (syntax == PSSYNTAX);
10901 if (pssyntax)
10902 syntax = DQSYNTAX;
10903#endif
10904 dblquote = (syntax == DQSYNTAX);
Eric Andersencb57d552001-06-28 07:25:16 +000010905 varnest = 0;
10906 arinest = 0;
10907 parenlevel = 0;
10908 dqvarnest = 0;
10909
10910 STARTSTACKSTR(out);
Denis Vlasenko176d49d2008-10-06 09:51:47 +000010911 loop:
10912 /* For each line, until end of word */
10913 {
Eric Andersenc470f442003-07-28 09:56:35 +000010914 CHECKEND(); /* set c to PEOF if at end of here document */
10915 for (;;) { /* until end of line or end of word */
10916 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
Denis Vlasenkobf0a2012006-12-26 10:42:51 +000010917 switch (SIT(c, syntax)) {
Eric Andersenc470f442003-07-28 09:56:35 +000010918 case CNL: /* '\n' */
Eric Andersencb57d552001-06-28 07:25:16 +000010919 if (syntax == BASESYNTAX)
Eric Andersenc470f442003-07-28 09:56:35 +000010920 goto endword; /* exit outer loop */
Eric Andersencb57d552001-06-28 07:25:16 +000010921 USTPUTC(c, out);
Denis Vlasenko41eb3002008-11-28 03:42:31 +000010922 g_parsefile->linno++;
Eric Andersencb57d552001-06-28 07:25:16 +000010923 if (doprompt)
10924 setprompt(2);
Eric Andersencb57d552001-06-28 07:25:16 +000010925 c = pgetc();
Eric Andersenc470f442003-07-28 09:56:35 +000010926 goto loop; /* continue outer loop */
Eric Andersencb57d552001-06-28 07:25:16 +000010927 case CWORD:
10928 USTPUTC(c, out);
10929 break;
10930 case CCTL:
Eric Andersenc470f442003-07-28 09:56:35 +000010931 if (eofmark == NULL || dblquote)
Eric Andersencb57d552001-06-28 07:25:16 +000010932 USTPUTC(CTLESC, out);
Denis Vlasenkoef527f52008-06-23 01:52:30 +000010933#if ENABLE_ASH_BASH_COMPAT
10934 if (c == '\\' && bash_dollar_squote) {
10935 c = decode_dollar_squote();
10936 if (c & 0x100) {
10937 USTPUTC('\\', out);
10938 c = (unsigned char)c;
10939 }
10940 }
10941#endif
Eric Andersencb57d552001-06-28 07:25:16 +000010942 USTPUTC(c, out);
10943 break;
Eric Andersenc470f442003-07-28 09:56:35 +000010944 case CBACK: /* backslash */
Eric Andersencb57d552001-06-28 07:25:16 +000010945 c = pgetc2();
10946 if (c == PEOF) {
Eric Andersenc470f442003-07-28 09:56:35 +000010947 USTPUTC(CTLESC, out);
Eric Andersencb57d552001-06-28 07:25:16 +000010948 USTPUTC('\\', out);
10949 pungetc();
10950 } else if (c == '\n') {
10951 if (doprompt)
10952 setprompt(2);
Eric Andersencb57d552001-06-28 07:25:16 +000010953 } else {
Denis Vlasenko46a53062007-09-24 18:30:02 +000010954#if ENABLE_ASH_EXPAND_PRMT
10955 if (c == '$' && pssyntax) {
10956 USTPUTC(CTLESC, out);
10957 USTPUTC('\\', out);
10958 }
10959#endif
Denis Vlasenkoef527f52008-06-23 01:52:30 +000010960 if (dblquote && c != '\\'
10961 && c != '`' && c != '$'
10962 && (c != '"' || eofmark != NULL)
Eric Andersenc470f442003-07-28 09:56:35 +000010963 ) {
10964 USTPUTC(CTLESC, out);
Eric Andersencb57d552001-06-28 07:25:16 +000010965 USTPUTC('\\', out);
Eric Andersenc470f442003-07-28 09:56:35 +000010966 }
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010967 if (SIT(c, SQSYNTAX) == CCTL)
Eric Andersencb57d552001-06-28 07:25:16 +000010968 USTPUTC(CTLESC, out);
Eric Andersencb57d552001-06-28 07:25:16 +000010969 USTPUTC(c, out);
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010970 quotef = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010971 }
10972 break;
10973 case CSQUOTE:
Eric Andersencb57d552001-06-28 07:25:16 +000010974 syntax = SQSYNTAX;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010975 quotemark:
Eric Andersenc470f442003-07-28 09:56:35 +000010976 if (eofmark == NULL) {
10977 USTPUTC(CTLQUOTEMARK, out);
10978 }
Eric Andersencb57d552001-06-28 07:25:16 +000010979 break;
10980 case CDQUOTE:
Eric Andersencb57d552001-06-28 07:25:16 +000010981 syntax = DQSYNTAX;
10982 dblquote = 1;
Eric Andersenc470f442003-07-28 09:56:35 +000010983 goto quotemark;
Eric Andersencb57d552001-06-28 07:25:16 +000010984 case CENDQUOTE:
Denis Vlasenko5e34ff22009-04-21 11:09:40 +000010985 IF_ASH_BASH_COMPAT(bash_dollar_squote = 0;)
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010986 if (eofmark != NULL && arinest == 0
10987 && varnest == 0
10988 ) {
Eric Andersencb57d552001-06-28 07:25:16 +000010989 USTPUTC(c, out);
10990 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000010991 if (dqvarnest == 0) {
Eric Andersencb57d552001-06-28 07:25:16 +000010992 syntax = BASESYNTAX;
10993 dblquote = 0;
10994 }
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010995 quotef = 1;
Eric Andersenc470f442003-07-28 09:56:35 +000010996 goto quotemark;
Eric Andersencb57d552001-06-28 07:25:16 +000010997 }
10998 break;
Eric Andersenc470f442003-07-28 09:56:35 +000010999 case CVAR: /* '$' */
11000 PARSESUB(); /* parse substitution */
Eric Andersencb57d552001-06-28 07:25:16 +000011001 break;
Eric Andersenc470f442003-07-28 09:56:35 +000011002 case CENDVAR: /* '}' */
Eric Andersencb57d552001-06-28 07:25:16 +000011003 if (varnest > 0) {
11004 varnest--;
11005 if (dqvarnest > 0) {
11006 dqvarnest--;
11007 }
11008 USTPUTC(CTLENDVAR, out);
11009 } else {
11010 USTPUTC(c, out);
11011 }
11012 break;
Mike Frysinger98c52642009-04-02 10:02:37 +000011013#if ENABLE_SH_MATH_SUPPORT
Eric Andersenc470f442003-07-28 09:56:35 +000011014 case CLP: /* '(' in arithmetic */
Eric Andersencb57d552001-06-28 07:25:16 +000011015 parenlevel++;
11016 USTPUTC(c, out);
11017 break;
Eric Andersenc470f442003-07-28 09:56:35 +000011018 case CRP: /* ')' in arithmetic */
Eric Andersencb57d552001-06-28 07:25:16 +000011019 if (parenlevel > 0) {
11020 USTPUTC(c, out);
11021 --parenlevel;
11022 } else {
11023 if (pgetc() == ')') {
11024 if (--arinest == 0) {
11025 USTPUTC(CTLENDARI, out);
11026 syntax = prevsyntax;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011027 dblquote = (syntax == DQSYNTAX);
Eric Andersencb57d552001-06-28 07:25:16 +000011028 } else
11029 USTPUTC(')', out);
11030 } else {
11031 /*
11032 * unbalanced parens
11033 * (don't 2nd guess - no error)
11034 */
11035 pungetc();
11036 USTPUTC(')', out);
11037 }
11038 }
11039 break;
11040#endif
Eric Andersenc470f442003-07-28 09:56:35 +000011041 case CBQUOTE: /* '`' */
Eric Andersencb57d552001-06-28 07:25:16 +000011042 PARSEBACKQOLD();
11043 break;
Eric Andersen2870d962001-07-02 17:27:21 +000011044 case CENDFILE:
Eric Andersenc470f442003-07-28 09:56:35 +000011045 goto endword; /* exit outer loop */
Eric Andersencb57d552001-06-28 07:25:16 +000011046 case CIGN:
11047 break;
11048 default:
Denis Vlasenko834dee72008-10-07 09:18:30 +000011049 if (varnest == 0) {
11050#if ENABLE_ASH_BASH_COMPAT
11051 if (c == '&') {
11052 if (pgetc() == '>')
11053 c = 0x100 + '>'; /* flag &> */
11054 pungetc();
11055 }
11056#endif
Eric Andersenc470f442003-07-28 09:56:35 +000011057 goto endword; /* exit outer loop */
Denis Vlasenko834dee72008-10-07 09:18:30 +000011058 }
Denis Vlasenko131ae172007-02-18 13:00:19 +000011059#if ENABLE_ASH_ALIAS
Eric Andersen3102ac42001-07-06 04:26:23 +000011060 if (c != PEOA)
11061#endif
Eric Andersencb57d552001-06-28 07:25:16 +000011062 USTPUTC(c, out);
Eric Andersen3102ac42001-07-06 04:26:23 +000011063
Eric Andersencb57d552001-06-28 07:25:16 +000011064 }
Denis Vlasenko834dee72008-10-07 09:18:30 +000011065 c = pgetc_fast();
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000011066 } /* for (;;) */
Eric Andersencb57d552001-06-28 07:25:16 +000011067 }
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011068 endword:
Mike Frysinger98c52642009-04-02 10:02:37 +000011069#if ENABLE_SH_MATH_SUPPORT
Eric Andersencb57d552001-06-28 07:25:16 +000011070 if (syntax == ARISYNTAX)
Denis Vlasenko559691a2008-10-05 18:39:31 +000011071 raise_error_syntax("missing '))'");
Eric Andersenc470f442003-07-28 09:56:35 +000011072#endif
Denis Vlasenko99eb8502007-02-23 21:09:49 +000011073 if (syntax != BASESYNTAX && !parsebackquote && eofmark == NULL)
Denis Vlasenko559691a2008-10-05 18:39:31 +000011074 raise_error_syntax("unterminated quoted string");
Eric Andersencb57d552001-06-28 07:25:16 +000011075 if (varnest != 0) {
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011076 startlinno = g_parsefile->linno;
Eric Andersenc470f442003-07-28 09:56:35 +000011077 /* { */
Denis Vlasenko559691a2008-10-05 18:39:31 +000011078 raise_error_syntax("missing '}'");
Eric Andersencb57d552001-06-28 07:25:16 +000011079 }
11080 USTPUTC('\0', out);
Eric Andersenc470f442003-07-28 09:56:35 +000011081 len = out - (char *)stackblock();
Eric Andersencb57d552001-06-28 07:25:16 +000011082 out = stackblock();
11083 if (eofmark == NULL) {
Denis Vlasenko5e34ff22009-04-21 11:09:40 +000011084 if ((c == '>' || c == '<' IF_ASH_BASH_COMPAT( || c == 0x100 + '>'))
Denis Vlasenko834dee72008-10-07 09:18:30 +000011085 && quotef == 0
11086 ) {
Denis Vlasenko559691a2008-10-05 18:39:31 +000011087 if (isdigit_str9(out)) {
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000011088 PARSEREDIR(); /* passed as params: out, c */
11089 lasttoken = TREDIR;
11090 return lasttoken;
11091 }
11092 /* else: non-number X seen, interpret it
11093 * as "NNNX>file" = "NNNX >file" */
Eric Andersencb57d552001-06-28 07:25:16 +000011094 }
Denis Vlasenkoef527f52008-06-23 01:52:30 +000011095 pungetc();
Eric Andersencb57d552001-06-28 07:25:16 +000011096 }
11097 quoteflag = quotef;
11098 backquotelist = bqlist;
11099 grabstackblock(len);
11100 wordtext = out;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011101 lasttoken = TWORD;
11102 return lasttoken;
Eric Andersencb57d552001-06-28 07:25:16 +000011103/* end of readtoken routine */
11104
Eric Andersencb57d552001-06-28 07:25:16 +000011105/*
11106 * Check to see whether we are at the end of the here document. When this
11107 * is called, c is set to the first character of the next input line. If
11108 * we are at the end of the here document, this routine sets the c to PEOF.
11109 */
Eric Andersenc470f442003-07-28 09:56:35 +000011110checkend: {
11111 if (eofmark) {
Denis Vlasenko131ae172007-02-18 13:00:19 +000011112#if ENABLE_ASH_ALIAS
Eric Andersenc470f442003-07-28 09:56:35 +000011113 if (c == PEOA) {
11114 c = pgetc2();
11115 }
11116#endif
11117 if (striptabs) {
11118 while (c == '\t') {
Eric Andersencb57d552001-06-28 07:25:16 +000011119 c = pgetc2();
11120 }
Eric Andersenc470f442003-07-28 09:56:35 +000011121 }
11122 if (c == *eofmark) {
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011123 if (pfgets(line, sizeof(line)) != NULL) {
Eric Andersenc470f442003-07-28 09:56:35 +000011124 char *p, *q;
Eric Andersencb57d552001-06-28 07:25:16 +000011125
Eric Andersenc470f442003-07-28 09:56:35 +000011126 p = line;
Denis Vlasenkof7d56652008-03-25 05:51:41 +000011127 for (q = eofmark + 1; *q && *p == *q; p++, q++)
11128 continue;
Eric Andersenc470f442003-07-28 09:56:35 +000011129 if (*p == '\n' && *q == '\0') {
11130 c = PEOF;
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011131 g_parsefile->linno++;
Eric Andersenc470f442003-07-28 09:56:35 +000011132 needprompt = doprompt;
11133 } else {
11134 pushstring(line, NULL);
Eric Andersencb57d552001-06-28 07:25:16 +000011135 }
11136 }
11137 }
11138 }
Eric Andersenc470f442003-07-28 09:56:35 +000011139 goto checkend_return;
11140}
Eric Andersencb57d552001-06-28 07:25:16 +000011141
Eric Andersencb57d552001-06-28 07:25:16 +000011142/*
11143 * Parse a redirection operator. The variable "out" points to a string
11144 * specifying the fd to be redirected. The variable "c" contains the
11145 * first character of the redirection operator.
11146 */
Eric Andersenc470f442003-07-28 09:56:35 +000011147parseredir: {
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000011148 /* out is already checked to be a valid number or "" */
11149 int fd = (*out == '\0' ? -1 : atoi(out));
Eric Andersenc470f442003-07-28 09:56:35 +000011150 union node *np;
Eric Andersencb57d552001-06-28 07:25:16 +000011151
Denis Vlasenko597906c2008-02-20 16:38:54 +000011152 np = stzalloc(sizeof(struct nfile));
Eric Andersenc470f442003-07-28 09:56:35 +000011153 if (c == '>') {
11154 np->nfile.fd = 1;
11155 c = pgetc();
11156 if (c == '>')
11157 np->type = NAPPEND;
11158 else if (c == '|')
11159 np->type = NCLOBBER;
11160 else if (c == '&')
11161 np->type = NTOFD;
Denis Vlasenko559691a2008-10-05 18:39:31 +000011162 /* it also can be NTO2 (>&file), but we can't figure it out yet */
Eric Andersenc470f442003-07-28 09:56:35 +000011163 else {
11164 np->type = NTO;
11165 pungetc();
Eric Andersencb57d552001-06-28 07:25:16 +000011166 }
Denis Vlasenko834dee72008-10-07 09:18:30 +000011167 }
11168#if ENABLE_ASH_BASH_COMPAT
11169 else if (c == 0x100 + '>') { /* this flags &> redirection */
11170 np->nfile.fd = 1;
11171 pgetc(); /* this is '>', no need to check */
11172 np->type = NTO2;
11173 }
11174#endif
11175 else { /* c == '<' */
Denis Vlasenko597906c2008-02-20 16:38:54 +000011176 /*np->nfile.fd = 0; - stzalloc did it */
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011177 c = pgetc();
11178 switch (c) {
Eric Andersenc470f442003-07-28 09:56:35 +000011179 case '<':
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011180 if (sizeof(struct nfile) != sizeof(struct nhere)) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000011181 np = stzalloc(sizeof(struct nhere));
11182 /*np->nfile.fd = 0; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000011183 }
11184 np->type = NHERE;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000011185 heredoc = stzalloc(sizeof(struct heredoc));
Eric Andersenc470f442003-07-28 09:56:35 +000011186 heredoc->here = np;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011187 c = pgetc();
11188 if (c == '-') {
Eric Andersenc470f442003-07-28 09:56:35 +000011189 heredoc->striptabs = 1;
11190 } else {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000011191 /*heredoc->striptabs = 0; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000011192 pungetc();
11193 }
11194 break;
11195
11196 case '&':
11197 np->type = NFROMFD;
11198 break;
11199
11200 case '>':
11201 np->type = NFROMTO;
11202 break;
11203
11204 default:
11205 np->type = NFROM;
11206 pungetc();
11207 break;
11208 }
Eric Andersencb57d552001-06-28 07:25:16 +000011209 }
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000011210 if (fd >= 0)
11211 np->nfile.fd = fd;
Eric Andersenc470f442003-07-28 09:56:35 +000011212 redirnode = np;
11213 goto parseredir_return;
11214}
Eric Andersencb57d552001-06-28 07:25:16 +000011215
Eric Andersencb57d552001-06-28 07:25:16 +000011216/*
11217 * Parse a substitution. At this point, we have read the dollar sign
11218 * and nothing else.
11219 */
Denis Vlasenkocc571512007-02-23 21:10:35 +000011220
11221/* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
11222 * (assuming ascii char codes, as the original implementation did) */
11223#define is_special(c) \
Denis Vlasenkoef527f52008-06-23 01:52:30 +000011224 (((unsigned)(c) - 33 < 32) \
11225 && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
Eric Andersenc470f442003-07-28 09:56:35 +000011226parsesub: {
11227 int subtype;
11228 int typeloc;
11229 int flags;
11230 char *p;
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011231 static const char types[] ALIGN1 = "}-+?=";
Eric Andersencb57d552001-06-28 07:25:16 +000011232
Eric Andersenc470f442003-07-28 09:56:35 +000011233 c = pgetc();
Denis Vlasenkoef527f52008-06-23 01:52:30 +000011234 if (c <= PEOA_OR_PEOF
11235 || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
Eric Andersenc470f442003-07-28 09:56:35 +000011236 ) {
Denis Vlasenkoef527f52008-06-23 01:52:30 +000011237#if ENABLE_ASH_BASH_COMPAT
11238 if (c == '\'')
11239 bash_dollar_squote = 1;
11240 else
11241#endif
11242 USTPUTC('$', out);
Eric Andersenc470f442003-07-28 09:56:35 +000011243 pungetc();
11244 } else if (c == '(') { /* $(command) or $((arith)) */
11245 if (pgetc() == '(') {
Mike Frysinger98c52642009-04-02 10:02:37 +000011246#if ENABLE_SH_MATH_SUPPORT
Eric Andersenc470f442003-07-28 09:56:35 +000011247 PARSEARITH();
11248#else
Mike Frysinger98a6f562008-06-09 09:38:45 +000011249 raise_error_syntax("you disabled math support for $((arith)) syntax");
Eric Andersenc470f442003-07-28 09:56:35 +000011250#endif
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000011251 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000011252 pungetc();
11253 PARSEBACKQNEW();
11254 }
11255 } else {
11256 USTPUTC(CTLVAR, out);
11257 typeloc = out - (char *)stackblock();
11258 USTPUTC(VSNORMAL, out);
11259 subtype = VSNORMAL;
11260 if (c == '{') {
11261 c = pgetc();
11262 if (c == '#') {
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011263 c = pgetc();
11264 if (c == '}')
Eric Andersenc470f442003-07-28 09:56:35 +000011265 c = '#';
11266 else
11267 subtype = VSLENGTH;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011268 } else
Eric Andersenc470f442003-07-28 09:56:35 +000011269 subtype = 0;
11270 }
11271 if (c > PEOA_OR_PEOF && is_name(c)) {
11272 do {
11273 STPUTC(c, out);
Eric Andersencb57d552001-06-28 07:25:16 +000011274 c = pgetc();
Eric Andersenc470f442003-07-28 09:56:35 +000011275 } while (c > PEOA_OR_PEOF && is_in_name(c));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011276 } else if (isdigit(c)) {
Eric Andersenc470f442003-07-28 09:56:35 +000011277 do {
11278 STPUTC(c, out);
11279 c = pgetc();
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011280 } while (isdigit(c));
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011281 } else if (is_special(c)) {
Eric Andersenc470f442003-07-28 09:56:35 +000011282 USTPUTC(c, out);
11283 c = pgetc();
Denis Vlasenko559691a2008-10-05 18:39:31 +000011284 } else {
11285 badsub:
11286 raise_error_syntax("bad substitution");
11287 }
Cristian Ionescu-Idbohrn301f5ec2009-10-05 02:07:23 +020011288 if (c != '}' && subtype == VSLENGTH)
11289 goto badsub;
Eric Andersencb57d552001-06-28 07:25:16 +000011290
Eric Andersenc470f442003-07-28 09:56:35 +000011291 STPUTC('=', out);
11292 flags = 0;
11293 if (subtype == 0) {
11294 switch (c) {
11295 case ':':
Eric Andersenc470f442003-07-28 09:56:35 +000011296 c = pgetc();
Denis Vlasenko92e13c22008-03-25 01:17:40 +000011297#if ENABLE_ASH_BASH_COMPAT
11298 if (c == ':' || c == '$' || isdigit(c)) {
11299 pungetc();
11300 subtype = VSSUBSTR;
11301 break;
11302 }
11303#endif
11304 flags = VSNUL;
Eric Andersenc470f442003-07-28 09:56:35 +000011305 /*FALLTHROUGH*/
11306 default:
11307 p = strchr(types, c);
11308 if (p == NULL)
11309 goto badsub;
11310 subtype = p - types + VSNORMAL;
11311 break;
11312 case '%':
Denis Vlasenko92e13c22008-03-25 01:17:40 +000011313 case '#': {
11314 int cc = c;
11315 subtype = c == '#' ? VSTRIMLEFT : VSTRIMRIGHT;
11316 c = pgetc();
11317 if (c == cc)
11318 subtype++;
11319 else
11320 pungetc();
11321 break;
11322 }
11323#if ENABLE_ASH_BASH_COMPAT
11324 case '/':
11325 subtype = VSREPLACE;
11326 c = pgetc();
11327 if (c == '/')
11328 subtype++; /* VSREPLACEALL */
11329 else
11330 pungetc();
11331 break;
11332#endif
Eric Andersencb57d552001-06-28 07:25:16 +000011333 }
Eric Andersenc470f442003-07-28 09:56:35 +000011334 } else {
11335 pungetc();
11336 }
11337 if (dblquote || arinest)
11338 flags |= VSQUOTE;
11339 *((char *)stackblock() + typeloc) = subtype | flags;
11340 if (subtype != VSNORMAL) {
11341 varnest++;
11342 if (dblquote || arinest) {
11343 dqvarnest++;
Eric Andersencb57d552001-06-28 07:25:16 +000011344 }
11345 }
11346 }
Eric Andersenc470f442003-07-28 09:56:35 +000011347 goto parsesub_return;
11348}
Eric Andersencb57d552001-06-28 07:25:16 +000011349
Eric Andersencb57d552001-06-28 07:25:16 +000011350/*
11351 * Called to parse command substitutions. Newstyle is set if the command
11352 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
11353 * list of commands (passed by reference), and savelen is the number of
11354 * characters on the top of the stack which must be preserved.
11355 */
Eric Andersenc470f442003-07-28 09:56:35 +000011356parsebackq: {
11357 struct nodelist **nlpp;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011358 smallint savepbq;
Eric Andersenc470f442003-07-28 09:56:35 +000011359 union node *n;
11360 char *volatile str;
11361 struct jmploc jmploc;
11362 struct jmploc *volatile savehandler;
11363 size_t savelen;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011364 smallint saveprompt = 0;
11365
Eric Andersencb57d552001-06-28 07:25:16 +000011366#ifdef __GNUC__
Eric Andersenc470f442003-07-28 09:56:35 +000011367 (void) &saveprompt;
Eric Andersencb57d552001-06-28 07:25:16 +000011368#endif
Eric Andersenc470f442003-07-28 09:56:35 +000011369 savepbq = parsebackquote;
11370 if (setjmp(jmploc.loc)) {
Denis Vlasenko60818682007-09-28 22:07:23 +000011371 free(str);
Eric Andersenc470f442003-07-28 09:56:35 +000011372 parsebackquote = 0;
Denis Vlasenko2da584f2007-02-19 22:44:05 +000011373 exception_handler = savehandler;
11374 longjmp(exception_handler->loc, 1);
Eric Andersenc470f442003-07-28 09:56:35 +000011375 }
Denis Vlasenkob012b102007-02-19 22:43:01 +000011376 INT_OFF;
Eric Andersenc470f442003-07-28 09:56:35 +000011377 str = NULL;
11378 savelen = out - (char *)stackblock();
11379 if (savelen > 0) {
11380 str = ckmalloc(savelen);
11381 memcpy(str, stackblock(), savelen);
11382 }
Denis Vlasenko2da584f2007-02-19 22:44:05 +000011383 savehandler = exception_handler;
11384 exception_handler = &jmploc;
Denis Vlasenkob012b102007-02-19 22:43:01 +000011385 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +000011386 if (oldstyle) {
11387 /* We must read until the closing backquote, giving special
11388 treatment to some slashes, and then push the string and
11389 reread it as input, interpreting it normally. */
11390 char *pout;
11391 int pc;
11392 size_t psavelen;
11393 char *pstr;
11394
11395
11396 STARTSTACKSTR(pout);
11397 for (;;) {
11398 if (needprompt) {
11399 setprompt(2);
Eric Andersenc470f442003-07-28 09:56:35 +000011400 }
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011401 pc = pgetc();
11402 switch (pc) {
Eric Andersenc470f442003-07-28 09:56:35 +000011403 case '`':
11404 goto done;
11405
11406 case '\\':
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011407 pc = pgetc();
11408 if (pc == '\n') {
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011409 g_parsefile->linno++;
Eric Andersenc470f442003-07-28 09:56:35 +000011410 if (doprompt)
11411 setprompt(2);
11412 /*
11413 * If eating a newline, avoid putting
11414 * the newline into the new character
11415 * stream (via the STPUTC after the
11416 * switch).
11417 */
11418 continue;
11419 }
11420 if (pc != '\\' && pc != '`' && pc != '$'
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011421 && (!dblquote || pc != '"'))
Eric Andersenc470f442003-07-28 09:56:35 +000011422 STPUTC('\\', pout);
11423 if (pc > PEOA_OR_PEOF) {
11424 break;
11425 }
11426 /* fall through */
11427
11428 case PEOF:
Denis Vlasenko131ae172007-02-18 13:00:19 +000011429#if ENABLE_ASH_ALIAS
Eric Andersenc470f442003-07-28 09:56:35 +000011430 case PEOA:
11431#endif
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011432 startlinno = g_parsefile->linno;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000011433 raise_error_syntax("EOF in backquote substitution");
Eric Andersenc470f442003-07-28 09:56:35 +000011434
11435 case '\n':
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011436 g_parsefile->linno++;
Eric Andersenc470f442003-07-28 09:56:35 +000011437 needprompt = doprompt;
11438 break;
11439
11440 default:
11441 break;
11442 }
11443 STPUTC(pc, pout);
11444 }
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011445 done:
Eric Andersenc470f442003-07-28 09:56:35 +000011446 STPUTC('\0', pout);
11447 psavelen = pout - (char *)stackblock();
11448 if (psavelen > 0) {
11449 pstr = grabstackstr(pout);
11450 setinputstring(pstr);
11451 }
11452 }
11453 nlpp = &bqlist;
11454 while (*nlpp)
11455 nlpp = &(*nlpp)->next;
Denis Vlasenko597906c2008-02-20 16:38:54 +000011456 *nlpp = stzalloc(sizeof(**nlpp));
11457 /* (*nlpp)->next = NULL; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000011458 parsebackquote = oldstyle;
11459
11460 if (oldstyle) {
11461 saveprompt = doprompt;
11462 doprompt = 0;
Eric Andersencb57d552001-06-28 07:25:16 +000011463 }
11464
Eric Andersenc470f442003-07-28 09:56:35 +000011465 n = list(2);
11466
11467 if (oldstyle)
11468 doprompt = saveprompt;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011469 else if (readtoken() != TRP)
11470 raise_error_unexpected_syntax(TRP);
Eric Andersenc470f442003-07-28 09:56:35 +000011471
11472 (*nlpp)->n = n;
11473 if (oldstyle) {
11474 /*
11475 * Start reading from old file again, ignoring any pushed back
11476 * tokens left from the backquote parsing
11477 */
11478 popfile();
11479 tokpushback = 0;
11480 }
11481 while (stackblocksize() <= savelen)
11482 growstackblock();
11483 STARTSTACKSTR(out);
11484 if (str) {
11485 memcpy(out, str, savelen);
11486 STADJUST(savelen, out);
Denis Vlasenkob012b102007-02-19 22:43:01 +000011487 INT_OFF;
11488 free(str);
Eric Andersenc470f442003-07-28 09:56:35 +000011489 str = NULL;
Denis Vlasenkob012b102007-02-19 22:43:01 +000011490 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +000011491 }
11492 parsebackquote = savepbq;
Denis Vlasenko2da584f2007-02-19 22:44:05 +000011493 exception_handler = savehandler;
Eric Andersenc470f442003-07-28 09:56:35 +000011494 if (arinest || dblquote)
11495 USTPUTC(CTLBACKQ | CTLQUOTE, out);
11496 else
11497 USTPUTC(CTLBACKQ, out);
11498 if (oldstyle)
11499 goto parsebackq_oldreturn;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000011500 goto parsebackq_newreturn;
Eric Andersenc470f442003-07-28 09:56:35 +000011501}
11502
Mike Frysinger98c52642009-04-02 10:02:37 +000011503#if ENABLE_SH_MATH_SUPPORT
Eric Andersencb57d552001-06-28 07:25:16 +000011504/*
11505 * Parse an arithmetic expansion (indicate start of one and set state)
11506 */
Eric Andersenc470f442003-07-28 09:56:35 +000011507parsearith: {
Eric Andersenc470f442003-07-28 09:56:35 +000011508 if (++arinest == 1) {
11509 prevsyntax = syntax;
11510 syntax = ARISYNTAX;
11511 USTPUTC(CTLARI, out);
11512 if (dblquote)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000011513 USTPUTC('"', out);
Eric Andersenc470f442003-07-28 09:56:35 +000011514 else
Denis Vlasenkoa624c112007-02-19 22:45:43 +000011515 USTPUTC(' ', out);
Eric Andersenc470f442003-07-28 09:56:35 +000011516 } else {
11517 /*
11518 * we collapse embedded arithmetic expansion to
11519 * parenthesis, which should be equivalent
11520 */
11521 USTPUTC('(', out);
Eric Andersencb57d552001-06-28 07:25:16 +000011522 }
Eric Andersenc470f442003-07-28 09:56:35 +000011523 goto parsearith_return;
11524}
11525#endif
Eric Andersencb57d552001-06-28 07:25:16 +000011526
Eric Andersenc470f442003-07-28 09:56:35 +000011527} /* end of readtoken */
11528
Eric Andersencb57d552001-06-28 07:25:16 +000011529/*
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011530 * Read the next input token.
11531 * If the token is a word, we set backquotelist to the list of cmds in
11532 * backquotes. We set quoteflag to true if any part of the word was
11533 * quoted.
11534 * If the token is TREDIR, then we set redirnode to a structure containing
11535 * the redirection.
11536 * In all cases, the variable startlinno is set to the number of the line
11537 * on which the token starts.
11538 *
11539 * [Change comment: here documents and internal procedures]
11540 * [Readtoken shouldn't have any arguments. Perhaps we should make the
11541 * word parsing code into a separate routine. In this case, readtoken
11542 * doesn't need to have any internal procedures, but parseword does.
11543 * We could also make parseoperator in essence the main routine, and
11544 * have parseword (readtoken1?) handle both words and redirection.]
Eric Andersencb57d552001-06-28 07:25:16 +000011545 */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011546#define NEW_xxreadtoken
11547#ifdef NEW_xxreadtoken
11548/* singles must be first! */
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011549static const char xxreadtoken_chars[7] ALIGN1 = {
Denis Vlasenko834dee72008-10-07 09:18:30 +000011550 '\n', '(', ')', /* singles */
11551 '&', '|', ';', /* doubles */
11552 0
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011553};
Eric Andersencb57d552001-06-28 07:25:16 +000011554
Denis Vlasenko834dee72008-10-07 09:18:30 +000011555#define xxreadtoken_singles 3
11556#define xxreadtoken_doubles 3
11557
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011558static const char xxreadtoken_tokens[] ALIGN1 = {
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011559 TNL, TLP, TRP, /* only single occurrence allowed */
11560 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
11561 TEOF, /* corresponds to trailing nul */
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011562 TAND, TOR, TENDCASE /* if double occurrence */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011563};
11564
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011565static int
11566xxreadtoken(void)
11567{
11568 int c;
11569
11570 if (tokpushback) {
11571 tokpushback = 0;
11572 return lasttoken;
Eric Andersencb57d552001-06-28 07:25:16 +000011573 }
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011574 if (needprompt) {
11575 setprompt(2);
11576 }
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011577 startlinno = g_parsefile->linno;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011578 for (;;) { /* until token or start of word found */
Denis Vlasenko834dee72008-10-07 09:18:30 +000011579 c = pgetc_fast();
Denis Vlasenko5e34ff22009-04-21 11:09:40 +000011580 if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011581 continue;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011582
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011583 if (c == '#') {
11584 while ((c = pgetc()) != '\n' && c != PEOF)
11585 continue;
11586 pungetc();
11587 } else if (c == '\\') {
11588 if (pgetc() != '\n') {
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011589 pungetc();
Denis Vlasenko834dee72008-10-07 09:18:30 +000011590 break; /* return readtoken1(...) */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011591 }
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011592 startlinno = ++g_parsefile->linno;
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011593 if (doprompt)
11594 setprompt(2);
11595 } else {
11596 const char *p;
11597
11598 p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
11599 if (c != PEOF) {
11600 if (c == '\n') {
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011601 g_parsefile->linno++;
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011602 needprompt = doprompt;
11603 }
11604
11605 p = strchr(xxreadtoken_chars, c);
Denis Vlasenko834dee72008-10-07 09:18:30 +000011606 if (p == NULL)
11607 break; /* return readtoken1(...) */
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011608
Denis Vlasenko834dee72008-10-07 09:18:30 +000011609 if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
11610 int cc = pgetc();
11611 if (cc == c) { /* double occurrence? */
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011612 p += xxreadtoken_doubles + 1;
11613 } else {
11614 pungetc();
Denis Vlasenko834dee72008-10-07 09:18:30 +000011615#if ENABLE_ASH_BASH_COMPAT
11616 if (c == '&' && cc == '>') /* &> */
11617 break; /* return readtoken1(...) */
11618#endif
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011619 }
11620 }
11621 }
11622 lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
11623 return lasttoken;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011624 }
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011625 } /* for (;;) */
Denis Vlasenko834dee72008-10-07 09:18:30 +000011626
11627 return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011628}
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011629#else /* old xxreadtoken */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011630#define RETURN(token) return lasttoken = token
11631static int
11632xxreadtoken(void)
11633{
11634 int c;
11635
11636 if (tokpushback) {
11637 tokpushback = 0;
11638 return lasttoken;
11639 }
11640 if (needprompt) {
11641 setprompt(2);
11642 }
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011643 startlinno = g_parsefile->linno;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011644 for (;;) { /* until token or start of word found */
Denis Vlasenko834dee72008-10-07 09:18:30 +000011645 c = pgetc_fast();
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011646 switch (c) {
11647 case ' ': case '\t':
11648#if ENABLE_ASH_ALIAS
11649 case PEOA:
11650#endif
11651 continue;
11652 case '#':
Denis Vlasenkof7d56652008-03-25 05:51:41 +000011653 while ((c = pgetc()) != '\n' && c != PEOF)
11654 continue;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011655 pungetc();
11656 continue;
11657 case '\\':
11658 if (pgetc() == '\n') {
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011659 startlinno = ++g_parsefile->linno;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011660 if (doprompt)
11661 setprompt(2);
11662 continue;
11663 }
11664 pungetc();
11665 goto breakloop;
11666 case '\n':
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011667 g_parsefile->linno++;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011668 needprompt = doprompt;
11669 RETURN(TNL);
11670 case PEOF:
11671 RETURN(TEOF);
11672 case '&':
11673 if (pgetc() == '&')
11674 RETURN(TAND);
11675 pungetc();
11676 RETURN(TBACKGND);
11677 case '|':
11678 if (pgetc() == '|')
11679 RETURN(TOR);
11680 pungetc();
11681 RETURN(TPIPE);
11682 case ';':
11683 if (pgetc() == ';')
11684 RETURN(TENDCASE);
11685 pungetc();
11686 RETURN(TSEMI);
11687 case '(':
11688 RETURN(TLP);
11689 case ')':
11690 RETURN(TRP);
11691 default:
11692 goto breakloop;
11693 }
11694 }
11695 breakloop:
11696 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
11697#undef RETURN
11698}
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011699#endif /* old xxreadtoken */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011700
11701static int
11702readtoken(void)
11703{
11704 int t;
11705#if DEBUG
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011706 smallint alreadyseen = tokpushback;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011707#endif
11708
11709#if ENABLE_ASH_ALIAS
11710 top:
11711#endif
11712
11713 t = xxreadtoken();
11714
11715 /*
11716 * eat newlines
11717 */
11718 if (checkkwd & CHKNL) {
11719 while (t == TNL) {
11720 parseheredoc();
11721 t = xxreadtoken();
11722 }
11723 }
11724
11725 if (t != TWORD || quoteflag) {
11726 goto out;
11727 }
11728
11729 /*
11730 * check for keywords
11731 */
11732 if (checkkwd & CHKKWD) {
11733 const char *const *pp;
11734
11735 pp = findkwd(wordtext);
11736 if (pp) {
11737 lasttoken = t = pp - tokname_array;
11738 TRACE(("keyword %s recognized\n", tokname(t)));
11739 goto out;
11740 }
11741 }
11742
11743 if (checkkwd & CHKALIAS) {
11744#if ENABLE_ASH_ALIAS
11745 struct alias *ap;
11746 ap = lookupalias(wordtext, 1);
11747 if (ap != NULL) {
11748 if (*ap->val) {
11749 pushstring(ap->val, ap);
11750 }
11751 goto top;
11752 }
11753#endif
11754 }
11755 out:
11756 checkkwd = 0;
11757#if DEBUG
11758 if (!alreadyseen)
11759 TRACE(("token %s %s\n", tokname(t), t == TWORD ? wordtext : ""));
11760 else
11761 TRACE(("reread token %s %s\n", tokname(t), t == TWORD ? wordtext : ""));
11762#endif
11763 return t;
Eric Andersencb57d552001-06-28 07:25:16 +000011764}
11765
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011766static char
11767peektoken(void)
11768{
11769 int t;
11770
11771 t = readtoken();
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011772 tokpushback = 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011773 return tokname_array[t][0];
11774}
Eric Andersencb57d552001-06-28 07:25:16 +000011775
11776/*
Denys Vlasenko86e83ec2009-07-23 22:07:07 +020011777 * Read and parse a command. Returns NODE_EOF on end of file.
11778 * (NULL is a valid parse tree indicating a blank line.)
Eric Andersencb57d552001-06-28 07:25:16 +000011779 */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011780static union node *
11781parsecmd(int interact)
Eric Andersen90898442003-08-06 11:20:52 +000011782{
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011783 int t;
Eric Andersencb57d552001-06-28 07:25:16 +000011784
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011785 tokpushback = 0;
11786 doprompt = interact;
11787 if (doprompt)
11788 setprompt(doprompt);
11789 needprompt = 0;
11790 t = readtoken();
11791 if (t == TEOF)
Denys Vlasenko86e83ec2009-07-23 22:07:07 +020011792 return NODE_EOF;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011793 if (t == TNL)
11794 return NULL;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011795 tokpushback = 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011796 return list(1);
11797}
11798
11799/*
11800 * Input any here documents.
11801 */
11802static void
11803parseheredoc(void)
11804{
11805 struct heredoc *here;
11806 union node *n;
11807
11808 here = heredoclist;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000011809 heredoclist = NULL;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011810
11811 while (here) {
11812 if (needprompt) {
11813 setprompt(2);
11814 }
11815 readtoken1(pgetc(), here->here->type == NHERE? SQSYNTAX : DQSYNTAX,
11816 here->eofmark, here->striptabs);
Denis Vlasenko597906c2008-02-20 16:38:54 +000011817 n = stzalloc(sizeof(struct narg));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011818 n->narg.type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000011819 /*n->narg.next = NULL; - stzalloc did it */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011820 n->narg.text = wordtext;
11821 n->narg.backquote = backquotelist;
11822 here->here->nhere.doc = n;
11823 here = here->next;
Eric Andersencb57d552001-06-28 07:25:16 +000011824 }
Eric Andersencb57d552001-06-28 07:25:16 +000011825}
11826
11827
11828/*
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +000011829 * called by editline -- any expansions to the prompt should be added here.
Eric Andersencb57d552001-06-28 07:25:16 +000011830 */
Denis Vlasenko131ae172007-02-18 13:00:19 +000011831#if ENABLE_ASH_EXPAND_PRMT
"Vladimir N. Oleynik"bef14d72005-09-05 13:25:11 +000011832static const char *
11833expandstr(const char *ps)
11834{
11835 union node n;
11836
Denis Vlasenko5c2b8142009-03-19 01:59:59 +000011837 /* XXX Fix (char *) cast. It _is_ a bug. ps is variable's value,
11838 * and token processing _can_ alter it (delete NULs etc). */
"Vladimir N. Oleynik"bef14d72005-09-05 13:25:11 +000011839 setinputstring((char *)ps);
Denis Vlasenko46a53062007-09-24 18:30:02 +000011840 readtoken1(pgetc(), PSSYNTAX, nullstr, 0);
"Vladimir N. Oleynik"bef14d72005-09-05 13:25:11 +000011841 popfile();
11842
11843 n.narg.type = NARG;
11844 n.narg.next = NULL;
11845 n.narg.text = wordtext;
11846 n.narg.backquote = backquotelist;
11847
11848 expandarg(&n, NULL, 0);
11849 return stackblock();
11850}
11851#endif
11852
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011853/*
11854 * Execute a command or commands contained in a string.
11855 */
11856static int
11857evalstring(char *s, int mask)
Eric Andersenc470f442003-07-28 09:56:35 +000011858{
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011859 union node *n;
11860 struct stackmark smark;
11861 int skip;
11862
11863 setinputstring(s);
11864 setstackmark(&smark);
11865
11866 skip = 0;
Denys Vlasenko86e83ec2009-07-23 22:07:07 +020011867 while ((n = parsecmd(0)) != NODE_EOF) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011868 evaltree(n, 0);
11869 popstackmark(&smark);
11870 skip = evalskip;
11871 if (skip)
11872 break;
11873 }
11874 popfile();
11875
11876 skip &= mask;
11877 evalskip = skip;
11878 return skip;
Eric Andersenc470f442003-07-28 09:56:35 +000011879}
11880
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011881/*
11882 * The eval command.
11883 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011884static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000011885evalcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011886{
11887 char *p;
11888 char *concat;
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011889
Denis Vlasenko68404f12008-03-17 09:00:54 +000011890 if (argv[1]) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011891 p = argv[1];
Denis Vlasenko68404f12008-03-17 09:00:54 +000011892 argv += 2;
11893 if (argv[0]) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011894 STARTSTACKSTR(concat);
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011895 for (;;) {
11896 concat = stack_putstr(p, concat);
Denis Vlasenko68404f12008-03-17 09:00:54 +000011897 p = *argv++;
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011898 if (p == NULL)
11899 break;
11900 STPUTC(' ', concat);
11901 }
11902 STPUTC('\0', concat);
11903 p = grabstackstr(concat);
11904 }
11905 evalstring(p, ~SKIPEVAL);
11906
11907 }
11908 return exitstatus;
11909}
11910
11911/*
11912 * Read and execute commands. "Top" is nonzero for the top level command
11913 * loop; it turns on prompting if the shell is interactive.
11914 */
11915static int
11916cmdloop(int top)
11917{
11918 union node *n;
11919 struct stackmark smark;
11920 int inter;
11921 int numeof = 0;
11922
11923 TRACE(("cmdloop(%d) called\n", top));
11924 for (;;) {
11925 int skip;
11926
11927 setstackmark(&smark);
11928#if JOBS
Denis Vlasenkob07a4962008-06-22 13:16:23 +000011929 if (doing_jobctl)
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011930 showjobs(stderr, SHOW_CHANGED);
11931#endif
11932 inter = 0;
11933 if (iflag && top) {
11934 inter++;
11935#if ENABLE_ASH_MAIL
11936 chkmail();
11937#endif
11938 }
11939 n = parsecmd(inter);
Denys Vlasenko7cee00e2009-07-24 01:08:03 +020011940#if DEBUG
11941 if (DEBUG > 2 && debug && (n != NODE_EOF))
Denys Vlasenko883cea42009-07-11 15:31:59 +020011942 showtree(n);
Denis Vlasenko135cecb2009-04-12 00:00:57 +000011943#endif
Denys Vlasenko86e83ec2009-07-23 22:07:07 +020011944 if (n == NODE_EOF) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011945 if (!top || numeof >= 50)
11946 break;
11947 if (!stoppedjobs()) {
11948 if (!Iflag)
11949 break;
11950 out2str("\nUse \"exit\" to leave shell.\n");
11951 }
11952 numeof++;
11953 } else if (nflag == 0) {
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +000011954 /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
11955 job_warning >>= 1;
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011956 numeof = 0;
11957 evaltree(n, 0);
11958 }
11959 popstackmark(&smark);
11960 skip = evalskip;
11961
11962 if (skip) {
11963 evalskip = 0;
11964 return skip & SKIPEVAL;
11965 }
11966 }
11967 return 0;
11968}
11969
Denis Vlasenko0dec6de2007-02-23 21:10:47 +000011970/*
11971 * Take commands from a file. To be compatible we should do a path
11972 * search for the file, which is necessary to find sub-commands.
11973 */
11974static char *
11975find_dot_file(char *name)
11976{
11977 char *fullname;
11978 const char *path = pathval();
11979 struct stat statb;
11980
11981 /* don't try this for absolute or relative paths */
11982 if (strchr(name, '/'))
11983 return name;
11984
Denis Vlasenko8ad78e12009-02-15 12:40:30 +000011985 /* IIRC standards do not say whether . is to be searched.
11986 * And it is even smaller this way, making it unconditional for now:
11987 */
11988 if (1) { /* ENABLE_ASH_BASH_COMPAT */
11989 fullname = name;
11990 goto try_cur_dir;
11991 }
11992
Denys Vlasenko82a6fb32009-06-14 19:42:12 +020011993 while ((fullname = path_advance(&path, name)) != NULL) {
Denis Vlasenko8ad78e12009-02-15 12:40:30 +000011994 try_cur_dir:
Denis Vlasenko0dec6de2007-02-23 21:10:47 +000011995 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
11996 /*
11997 * Don't bother freeing here, since it will
11998 * be freed by the caller.
11999 */
12000 return fullname;
12001 }
Denys Vlasenko82a6fb32009-06-14 19:42:12 +020012002 if (fullname != name)
12003 stunalloc(fullname);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +000012004 }
12005
12006 /* not found in the PATH */
12007 ash_msg_and_raise_error("%s: not found", name);
12008 /* NOTREACHED */
12009}
12010
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012011static int FAST_FUNC
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012012dotcmd(int argc, char **argv)
12013{
12014 struct strlist *sp;
12015 volatile struct shparam saveparam;
12016 int status = 0;
12017
12018 for (sp = cmdenviron; sp; sp = sp->next)
Denis Vlasenko4222ae42007-02-25 02:37:49 +000012019 setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012020
Denis Vlasenko68404f12008-03-17 09:00:54 +000012021 if (argv[1]) { /* That's what SVR2 does */
12022 char *fullname = find_dot_file(argv[1]);
12023 argv += 2;
12024 argc -= 2;
12025 if (argc) { /* argc > 0, argv[0] != NULL */
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012026 saveparam = shellparam;
Denis Vlasenko01631112007-12-16 17:20:38 +000012027 shellparam.malloced = 0;
Denis Vlasenko68404f12008-03-17 09:00:54 +000012028 shellparam.nparam = argc;
12029 shellparam.p = argv;
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012030 };
12031
12032 setinputfile(fullname, INPUT_PUSH_FILE);
12033 commandname = fullname;
12034 cmdloop(0);
12035 popfile();
12036
Denis Vlasenko68404f12008-03-17 09:00:54 +000012037 if (argc) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012038 freeparam(&shellparam);
12039 shellparam = saveparam;
12040 };
12041 status = exitstatus;
12042 }
12043 return status;
12044}
12045
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012046static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012047exitcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012048{
12049 if (stoppedjobs())
12050 return 0;
Denis Vlasenko68404f12008-03-17 09:00:54 +000012051 if (argv[1])
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012052 exitstatus = number(argv[1]);
12053 raise_exception(EXEXIT);
12054 /* NOTREACHED */
12055}
12056
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012057/*
12058 * Read a file containing shell functions.
12059 */
12060static void
12061readcmdfile(char *name)
12062{
12063 setinputfile(name, INPUT_PUSH_FILE);
12064 cmdloop(0);
12065 popfile();
12066}
12067
12068
Denis Vlasenkocc571512007-02-23 21:10:35 +000012069/* ============ find_command inplementation */
12070
12071/*
12072 * Resolve a command name. If you change this routine, you may have to
12073 * change the shellexec routine as well.
12074 */
12075static void
12076find_command(char *name, struct cmdentry *entry, int act, const char *path)
12077{
12078 struct tblentry *cmdp;
12079 int idx;
12080 int prev;
12081 char *fullname;
12082 struct stat statb;
12083 int e;
12084 int updatetbl;
12085 struct builtincmd *bcmd;
12086
12087 /* If name contains a slash, don't use PATH or hash table */
12088 if (strchr(name, '/') != NULL) {
12089 entry->u.index = -1;
12090 if (act & DO_ABS) {
12091 while (stat(name, &statb) < 0) {
12092#ifdef SYSV
12093 if (errno == EINTR)
12094 continue;
12095#endif
12096 entry->cmdtype = CMDUNKNOWN;
12097 return;
12098 }
12099 }
12100 entry->cmdtype = CMDNORMAL;
12101 return;
12102 }
12103
Denis Vlasenkof20de5b2007-04-29 23:42:54 +000012104/* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
Denis Vlasenkocc571512007-02-23 21:10:35 +000012105
12106 updatetbl = (path == pathval());
12107 if (!updatetbl) {
12108 act |= DO_ALTPATH;
12109 if (strstr(path, "%builtin") != NULL)
12110 act |= DO_ALTBLTIN;
12111 }
12112
12113 /* If name is in the table, check answer will be ok */
12114 cmdp = cmdlookup(name, 0);
12115 if (cmdp != NULL) {
12116 int bit;
12117
12118 switch (cmdp->cmdtype) {
12119 default:
12120#if DEBUG
12121 abort();
12122#endif
12123 case CMDNORMAL:
12124 bit = DO_ALTPATH;
12125 break;
12126 case CMDFUNCTION:
12127 bit = DO_NOFUNC;
12128 break;
12129 case CMDBUILTIN:
12130 bit = DO_ALTBLTIN;
12131 break;
12132 }
12133 if (act & bit) {
12134 updatetbl = 0;
12135 cmdp = NULL;
12136 } else if (cmdp->rehash == 0)
12137 /* if not invalidated by cd, we're done */
12138 goto success;
12139 }
12140
12141 /* If %builtin not in path, check for builtin next */
12142 bcmd = find_builtin(name);
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +000012143 if (bcmd) {
12144 if (IS_BUILTIN_REGULAR(bcmd))
12145 goto builtin_success;
12146 if (act & DO_ALTPATH) {
12147 if (!(act & DO_ALTBLTIN))
12148 goto builtin_success;
12149 } else if (builtinloc <= 0) {
12150 goto builtin_success;
Denis Vlasenko8e858e22007-03-07 09:35:43 +000012151 }
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +000012152 }
Denis Vlasenkocc571512007-02-23 21:10:35 +000012153
Denis Vlasenkof20de5b2007-04-29 23:42:54 +000012154#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko7465dbc2008-04-13 02:25:53 +000012155 {
12156 int applet_no = find_applet_by_name(name);
12157 if (applet_no >= 0) {
12158 entry->cmdtype = CMDNORMAL;
12159 entry->u.index = -2 - applet_no;
12160 return;
12161 }
Denis Vlasenkof20de5b2007-04-29 23:42:54 +000012162 }
12163#endif
12164
Denis Vlasenkocc571512007-02-23 21:10:35 +000012165 /* We have to search path. */
12166 prev = -1; /* where to start */
12167 if (cmdp && cmdp->rehash) { /* doing a rehash */
12168 if (cmdp->cmdtype == CMDBUILTIN)
12169 prev = builtinloc;
12170 else
12171 prev = cmdp->param.index;
12172 }
12173
12174 e = ENOENT;
12175 idx = -1;
12176 loop:
Denys Vlasenko82a6fb32009-06-14 19:42:12 +020012177 while ((fullname = path_advance(&path, name)) != NULL) {
Denis Vlasenkocc571512007-02-23 21:10:35 +000012178 stunalloc(fullname);
Denis Vlasenkodee82b62007-07-29 14:05:27 +000012179 /* NB: code below will still use fullname
12180 * despite it being "unallocated" */
Denis Vlasenkocc571512007-02-23 21:10:35 +000012181 idx++;
12182 if (pathopt) {
12183 if (prefix(pathopt, "builtin")) {
12184 if (bcmd)
12185 goto builtin_success;
12186 continue;
Denis Vlasenko4a9ca132008-04-12 20:07:08 +000012187 }
12188 if ((act & DO_NOFUNC)
12189 || !prefix(pathopt, "func")
12190 ) { /* ignore unimplemented options */
Denis Vlasenkocc571512007-02-23 21:10:35 +000012191 continue;
12192 }
12193 }
12194 /* if rehash, don't redo absolute path names */
12195 if (fullname[0] == '/' && idx <= prev) {
12196 if (idx < prev)
12197 continue;
12198 TRACE(("searchexec \"%s\": no change\n", name));
12199 goto success;
12200 }
12201 while (stat(fullname, &statb) < 0) {
12202#ifdef SYSV
12203 if (errno == EINTR)
12204 continue;
12205#endif
12206 if (errno != ENOENT && errno != ENOTDIR)
12207 e = errno;
12208 goto loop;
12209 }
12210 e = EACCES; /* if we fail, this will be the error */
12211 if (!S_ISREG(statb.st_mode))
12212 continue;
12213 if (pathopt) { /* this is a %func directory */
12214 stalloc(strlen(fullname) + 1);
Denis Vlasenkodee82b62007-07-29 14:05:27 +000012215 /* NB: stalloc will return space pointed by fullname
12216 * (because we don't have any intervening allocations
12217 * between stunalloc above and this stalloc) */
Denis Vlasenkocc571512007-02-23 21:10:35 +000012218 readcmdfile(fullname);
12219 cmdp = cmdlookup(name, 0);
12220 if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
12221 ash_msg_and_raise_error("%s not defined in %s", name, fullname);
12222 stunalloc(fullname);
12223 goto success;
12224 }
12225 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
12226 if (!updatetbl) {
12227 entry->cmdtype = CMDNORMAL;
12228 entry->u.index = idx;
12229 return;
12230 }
12231 INT_OFF;
12232 cmdp = cmdlookup(name, 1);
12233 cmdp->cmdtype = CMDNORMAL;
12234 cmdp->param.index = idx;
12235 INT_ON;
12236 goto success;
12237 }
12238
12239 /* We failed. If there was an entry for this command, delete it */
12240 if (cmdp && updatetbl)
12241 delete_cmd_entry();
12242 if (act & DO_ERR)
12243 ash_msg("%s: %s", name, errmsg(e, "not found"));
12244 entry->cmdtype = CMDUNKNOWN;
12245 return;
12246
12247 builtin_success:
12248 if (!updatetbl) {
12249 entry->cmdtype = CMDBUILTIN;
12250 entry->u.cmd = bcmd;
12251 return;
12252 }
12253 INT_OFF;
12254 cmdp = cmdlookup(name, 1);
12255 cmdp->cmdtype = CMDBUILTIN;
12256 cmdp->param.cmd = bcmd;
12257 INT_ON;
12258 success:
12259 cmdp->rehash = 0;
12260 entry->cmdtype = cmdp->cmdtype;
12261 entry->u = cmdp->param;
12262}
12263
12264
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012265/* ============ trap.c */
Eric Andersenc470f442003-07-28 09:56:35 +000012266
Eric Andersencb57d552001-06-28 07:25:16 +000012267/*
Eric Andersencb57d552001-06-28 07:25:16 +000012268 * The trap builtin.
12269 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012270static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012271trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersencb57d552001-06-28 07:25:16 +000012272{
12273 char *action;
12274 char **ap;
12275 int signo;
12276
Eric Andersenc470f442003-07-28 09:56:35 +000012277 nextopt(nullstr);
12278 ap = argptr;
12279 if (!*ap) {
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012280 for (signo = 0; signo < NSIG; signo++) {
Denys Vlasenko21d87d42009-09-25 00:06:51 +020012281 char *tr = trap_ptr[signo];
12282 if (tr) {
Denys Vlasenkoe74aaf92009-09-27 02:05:45 +020012283 /* note: bash adds "SIG", but only if invoked
12284 * as "bash". If called as "sh", or if set -o posix,
12285 * then it prints short signal names.
12286 * We are printing short names: */
12287 out1fmt("trap -- %s %s\n",
Denys Vlasenko21d87d42009-09-25 00:06:51 +020012288 single_quote(tr),
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +000012289 get_signame(signo));
Denys Vlasenko726e1a02009-09-25 02:58:20 +020012290 /* trap_ptr != trap only if we are in special-cased `trap` code.
12291 * In this case, we will exit very soon, no need to free(). */
Denys Vlasenkoe74aaf92009-09-27 02:05:45 +020012292 /* if (trap_ptr != trap && tp[0]) */
Denys Vlasenko726e1a02009-09-25 02:58:20 +020012293 /* free(tr); */
Eric Andersencb57d552001-06-28 07:25:16 +000012294 }
12295 }
Denys Vlasenko726e1a02009-09-25 02:58:20 +020012296 /*
Denys Vlasenko21d87d42009-09-25 00:06:51 +020012297 if (trap_ptr != trap) {
12298 free(trap_ptr);
12299 trap_ptr = trap;
12300 }
Denys Vlasenko726e1a02009-09-25 02:58:20 +020012301 */
Eric Andersencb57d552001-06-28 07:25:16 +000012302 return 0;
12303 }
Denys Vlasenko21d87d42009-09-25 00:06:51 +020012304
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +000012305 action = NULL;
12306 if (ap[1])
Eric Andersencb57d552001-06-28 07:25:16 +000012307 action = *ap++;
12308 while (*ap) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +000012309 signo = get_signum(*ap);
12310 if (signo < 0)
Denis Vlasenkob012b102007-02-19 22:43:01 +000012311 ash_msg_and_raise_error("%s: bad trap", *ap);
12312 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +000012313 if (action) {
Denis Vlasenko9f739442006-12-16 23:49:13 +000012314 if (LONE_DASH(action))
Eric Andersencb57d552001-06-28 07:25:16 +000012315 action = NULL;
12316 else
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012317 action = ckstrdup(action);
Eric Andersencb57d552001-06-28 07:25:16 +000012318 }
Denis Vlasenko60818682007-09-28 22:07:23 +000012319 free(trap[signo]);
Eric Andersencb57d552001-06-28 07:25:16 +000012320 trap[signo] = action;
12321 if (signo != 0)
12322 setsignal(signo);
Denis Vlasenkob012b102007-02-19 22:43:01 +000012323 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +000012324 ap++;
12325 }
12326 return 0;
12327}
12328
Eric Andersenc470f442003-07-28 09:56:35 +000012329
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012330/* ============ Builtins */
Eric Andersenc470f442003-07-28 09:56:35 +000012331
Denis Vlasenko8e1c7152007-01-22 07:21:38 +000012332#if !ENABLE_FEATURE_SH_EXTRA_QUIET
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012333/*
12334 * Lists available builtins
12335 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012336static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012337helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersenc470f442003-07-28 09:56:35 +000012338{
Denis Vlasenko6b06cb82008-05-15 21:30:45 +000012339 unsigned col;
12340 unsigned i;
Eric Andersenc470f442003-07-28 09:56:35 +000012341
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +020012342 out1fmt(
Denis Vlasenko34d4d892009-04-04 20:24:37 +000012343 "Built-in commands:\n"
12344 "------------------\n");
Denis Vlasenkob71c6682007-07-21 15:08:09 +000012345 for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
Eric Andersenc470f442003-07-28 09:56:35 +000012346 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
Denis Vlasenko52764022007-02-24 13:42:56 +000012347 builtintab[i].name + 1);
Eric Andersenc470f442003-07-28 09:56:35 +000012348 if (col > 60) {
12349 out1fmt("\n");
12350 col = 0;
12351 }
12352 }
Denis Vlasenko80d14be2007-04-10 23:03:30 +000012353#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko1aa7e472007-11-28 06:49:03 +000012354 {
12355 const char *a = applet_names;
12356 while (*a) {
12357 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
12358 if (col > 60) {
12359 out1fmt("\n");
12360 col = 0;
12361 }
12362 a += strlen(a) + 1;
Eric Andersenc470f442003-07-28 09:56:35 +000012363 }
12364 }
12365#endif
12366 out1fmt("\n\n");
12367 return EXIT_SUCCESS;
12368}
Denis Vlasenko131ae172007-02-18 13:00:19 +000012369#endif /* FEATURE_SH_EXTRA_QUIET */
Eric Andersenc470f442003-07-28 09:56:35 +000012370
Eric Andersencb57d552001-06-28 07:25:16 +000012371/*
Eric Andersencb57d552001-06-28 07:25:16 +000012372 * The export and readonly commands.
12373 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012374static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012375exportcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +000012376{
12377 struct var *vp;
12378 char *name;
12379 const char *p;
Eric Andersenc470f442003-07-28 09:56:35 +000012380 char **aptr;
Denis Vlasenkob7304742008-10-20 08:15:51 +000012381 int flag = argv[0][0] == 'r' ? VREADONLY : VEXPORT;
Eric Andersencb57d552001-06-28 07:25:16 +000012382
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012383 if (nextopt("p") != 'p') {
12384 aptr = argptr;
12385 name = *aptr;
12386 if (name) {
12387 do {
12388 p = strchr(name, '=');
12389 if (p != NULL) {
12390 p++;
12391 } else {
12392 vp = *findvar(hashvar(name), name);
12393 if (vp) {
12394 vp->flags |= flag;
12395 continue;
12396 }
Eric Andersencb57d552001-06-28 07:25:16 +000012397 }
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012398 setvar(name, p, flag);
12399 } while ((name = *++aptr) != NULL);
12400 return 0;
12401 }
Eric Andersencb57d552001-06-28 07:25:16 +000012402 }
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012403 showvars(argv[0], flag, 0);
Eric Andersencb57d552001-06-28 07:25:16 +000012404 return 0;
12405}
12406
Eric Andersencb57d552001-06-28 07:25:16 +000012407/*
Denis Vlasenko5651bfc2007-02-23 21:08:58 +000012408 * Delete a function if it exists.
Eric Andersencb57d552001-06-28 07:25:16 +000012409 */
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012410static void
Denis Vlasenko5651bfc2007-02-23 21:08:58 +000012411unsetfunc(const char *name)
Aaron Lehmannb6ecbdc2001-12-06 03:37:38 +000012412{
Denis Vlasenko5651bfc2007-02-23 21:08:58 +000012413 struct tblentry *cmdp;
Eric Andersencb57d552001-06-28 07:25:16 +000012414
Denis Vlasenko5651bfc2007-02-23 21:08:58 +000012415 cmdp = cmdlookup(name, 0);
12416 if (cmdp!= NULL && cmdp->cmdtype == CMDFUNCTION)
12417 delete_cmd_entry();
Eric Andersenc470f442003-07-28 09:56:35 +000012418}
12419
Eric Andersencb57d552001-06-28 07:25:16 +000012420/*
Eric Andersencb57d552001-06-28 07:25:16 +000012421 * The unset builtin command. We unset the function before we unset the
12422 * variable to allow a function to be unset when there is a readonly variable
12423 * with the same name.
12424 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012425static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012426unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersencb57d552001-06-28 07:25:16 +000012427{
12428 char **ap;
12429 int i;
Eric Andersenc470f442003-07-28 09:56:35 +000012430 int flag = 0;
Eric Andersencb57d552001-06-28 07:25:16 +000012431 int ret = 0;
12432
12433 while ((i = nextopt("vf")) != '\0') {
Eric Andersenc470f442003-07-28 09:56:35 +000012434 flag = i;
Eric Andersencb57d552001-06-28 07:25:16 +000012435 }
Eric Andersencb57d552001-06-28 07:25:16 +000012436
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012437 for (ap = argptr; *ap; ap++) {
Eric Andersenc470f442003-07-28 09:56:35 +000012438 if (flag != 'f') {
12439 i = unsetvar(*ap);
12440 ret |= i;
12441 if (!(i & 2))
12442 continue;
12443 }
12444 if (flag != 'v')
Eric Andersencb57d552001-06-28 07:25:16 +000012445 unsetfunc(*ap);
Eric Andersencb57d552001-06-28 07:25:16 +000012446 }
Eric Andersenc470f442003-07-28 09:56:35 +000012447 return ret & 1;
Eric Andersencb57d552001-06-28 07:25:16 +000012448}
12449
12450
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +000012451/* setmode.c */
Eric Andersencb57d552001-06-28 07:25:16 +000012452
Eric Andersenc470f442003-07-28 09:56:35 +000012453#include <sys/times.h>
12454
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000012455static const unsigned char timescmd_str[] ALIGN1 = {
Manuel Novoa III 4456f252003-08-13 17:48:47 +000012456 ' ', offsetof(struct tms, tms_utime),
12457 '\n', offsetof(struct tms, tms_stime),
12458 ' ', offsetof(struct tms, tms_cutime),
12459 '\n', offsetof(struct tms, tms_cstime),
12460 0
12461};
Eric Andersencb57d552001-06-28 07:25:16 +000012462
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012463static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012464timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Manuel Novoa III 4456f252003-08-13 17:48:47 +000012465{
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012466 long clk_tck, s, t;
Manuel Novoa III 4456f252003-08-13 17:48:47 +000012467 const unsigned char *p;
12468 struct tms buf;
12469
12470 clk_tck = sysconf(_SC_CLK_TCK);
Eric Andersencb57d552001-06-28 07:25:16 +000012471 times(&buf);
Manuel Novoa III 4456f252003-08-13 17:48:47 +000012472
12473 p = timescmd_str;
12474 do {
12475 t = *(clock_t *)(((char *) &buf) + p[1]);
12476 s = t / clk_tck;
12477 out1fmt("%ldm%ld.%.3lds%c",
12478 s/60, s%60,
12479 ((t - s * clk_tck) * 1000) / clk_tck,
12480 p[0]);
12481 } while (*(p += 2));
12482
Eric Andersencb57d552001-06-28 07:25:16 +000012483 return 0;
12484}
12485
Mike Frysinger98c52642009-04-02 10:02:37 +000012486#if ENABLE_SH_MATH_SUPPORT
Eric Andersenc470f442003-07-28 09:56:35 +000012487/*
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +000012488 * The let builtin. partial stolen from GNU Bash, the Bourne Again SHell.
12489 * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
Eric Andersen90898442003-08-06 11:20:52 +000012490 *
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +000012491 * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
Eric Andersenc470f442003-07-28 09:56:35 +000012492 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012493static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012494letcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersenc470f442003-07-28 09:56:35 +000012495{
Denis Vlasenko68404f12008-03-17 09:00:54 +000012496 arith_t i;
Eric Andersenc470f442003-07-28 09:56:35 +000012497
Denis Vlasenko68404f12008-03-17 09:00:54 +000012498 argv++;
12499 if (!*argv)
Denis Vlasenkob012b102007-02-19 22:43:01 +000012500 ash_msg_and_raise_error("expression expected");
Denis Vlasenko68404f12008-03-17 09:00:54 +000012501 do {
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +000012502 i = ash_arith(*argv);
Denis Vlasenko68404f12008-03-17 09:00:54 +000012503 } while (*++argv);
Eric Andersenc470f442003-07-28 09:56:35 +000012504
Denis Vlasenkod9e15f22006-11-27 16:49:55 +000012505 return !i;
Eric Andersenc470f442003-07-28 09:56:35 +000012506}
Mike Frysinger98c52642009-04-02 10:02:37 +000012507#endif /* SH_MATH_SUPPORT */
Eric Andersenc470f442003-07-28 09:56:35 +000012508
Eric Andersenc470f442003-07-28 09:56:35 +000012509
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012510/* ============ miscbltin.c
12511 *
Eric Andersenaff114c2004-04-14 17:51:38 +000012512 * Miscellaneous builtins.
Eric Andersenc470f442003-07-28 09:56:35 +000012513 */
12514
12515#undef rflag
12516
Denis Vlasenko83e5d6f2006-12-18 21:49:06 +000012517#if defined(__GLIBC__) && __GLIBC__ == 2 && __GLIBC_MINOR__ < 1
Eric Andersenc470f442003-07-28 09:56:35 +000012518typedef enum __rlimit_resource rlim_t;
12519#endif
Eric Andersen74bcd162001-07-30 21:41:37 +000012520
Eric Andersenc470f442003-07-28 09:56:35 +000012521/*
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012522 * The read builtin. Options:
12523 * -r Do not interpret '\' specially
12524 * -s Turn off echo (tty only)
12525 * -n NCHARS Read NCHARS max
12526 * -p PROMPT Display PROMPT on stderr (if input is from tty)
12527 * -t SECONDS Timeout after SECONDS (tty or pipe only)
12528 * -u FD Read from given FD instead of fd 0
Eric Andersenc470f442003-07-28 09:56:35 +000012529 * This uses unbuffered input, which may be avoidable in some cases.
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012530 * TODO: bash also has:
12531 * -a ARRAY Read into array[0],[1],etc
12532 * -d DELIM End on DELIM char, not newline
12533 * -e Use line editing (tty only)
Eric Andersenc470f442003-07-28 09:56:35 +000012534 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012535static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012536readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersenc470f442003-07-28 09:56:35 +000012537{
Denis Vlasenko9cd4c762008-06-18 19:22:19 +000012538 static const char *const arg_REPLY[] = { "REPLY", NULL };
12539
Eric Andersenc470f442003-07-28 09:56:35 +000012540 char **ap;
12541 int backslash;
12542 char c;
12543 int rflag;
12544 char *prompt;
12545 const char *ifs;
12546 char *p;
12547 int startword;
12548 int status;
12549 int i;
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012550 int fd = 0;
Denis Vlasenko131ae172007-02-18 13:00:19 +000012551#if ENABLE_ASH_READ_NCHARS
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012552 int nchars = 0; /* if != 0, -n is in effect */
Paul Fox02eb9342005-09-07 16:56:02 +000012553 int silent = 0;
12554 struct termios tty, old_tty;
12555#endif
Denis Vlasenko131ae172007-02-18 13:00:19 +000012556#if ENABLE_ASH_READ_TIMEOUT
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012557 unsigned end_ms = 0;
12558 unsigned timeout = 0;
Paul Fox02eb9342005-09-07 16:56:02 +000012559#endif
Eric Andersenc470f442003-07-28 09:56:35 +000012560
12561 rflag = 0;
12562 prompt = NULL;
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012563 while ((i = nextopt("p:u:r"
Denis Vlasenko5e34ff22009-04-21 11:09:40 +000012564 IF_ASH_READ_TIMEOUT("t:")
12565 IF_ASH_READ_NCHARS("n:s")
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012566 )) != '\0') {
Denis Vlasenkobf0a2012006-12-26 10:42:51 +000012567 switch (i) {
Paul Fox02eb9342005-09-07 16:56:02 +000012568 case 'p':
Eric Andersenc470f442003-07-28 09:56:35 +000012569 prompt = optionarg;
Paul Fox02eb9342005-09-07 16:56:02 +000012570 break;
Denis Vlasenko131ae172007-02-18 13:00:19 +000012571#if ENABLE_ASH_READ_NCHARS
Paul Fox02eb9342005-09-07 16:56:02 +000012572 case 'n':
Denis Vlasenko037576d2007-10-20 18:30:38 +000012573 nchars = bb_strtou(optionarg, NULL, 10);
12574 if (nchars < 0 || errno)
Denis Vlasenkob012b102007-02-19 22:43:01 +000012575 ash_msg_and_raise_error("invalid count");
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012576 /* nchars == 0: off (bash 3.2 does this too) */
Paul Fox02eb9342005-09-07 16:56:02 +000012577 break;
12578 case 's':
12579 silent = 1;
12580 break;
Ned Ludd2123b7c2005-02-09 21:07:23 +000012581#endif
Denis Vlasenko131ae172007-02-18 13:00:19 +000012582#if ENABLE_ASH_READ_TIMEOUT
Paul Fox02eb9342005-09-07 16:56:02 +000012583 case 't':
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012584 timeout = bb_strtou(optionarg, NULL, 10);
12585 if (errno || timeout > UINT_MAX / 2048)
12586 ash_msg_and_raise_error("invalid timeout");
12587 timeout *= 1000;
12588#if 0 /* even bash have no -t N.NNN support */
Denis Vlasenko037576d2007-10-20 18:30:38 +000012589 ts.tv_sec = bb_strtou(optionarg, &p, 10);
Paul Fox02eb9342005-09-07 16:56:02 +000012590 ts.tv_usec = 0;
Denis Vlasenko037576d2007-10-20 18:30:38 +000012591 /* EINVAL means number is ok, but not terminated by NUL */
12592 if (*p == '.' && errno == EINVAL) {
Paul Fox02eb9342005-09-07 16:56:02 +000012593 char *p2;
12594 if (*++p) {
12595 int scale;
Denis Vlasenko037576d2007-10-20 18:30:38 +000012596 ts.tv_usec = bb_strtou(p, &p2, 10);
12597 if (errno)
Denis Vlasenkob012b102007-02-19 22:43:01 +000012598 ash_msg_and_raise_error("invalid timeout");
Paul Fox02eb9342005-09-07 16:56:02 +000012599 scale = p2 - p;
12600 /* normalize to usec */
12601 if (scale > 6)
Denis Vlasenkob012b102007-02-19 22:43:01 +000012602 ash_msg_and_raise_error("invalid timeout");
Paul Fox02eb9342005-09-07 16:56:02 +000012603 while (scale++ < 6)
12604 ts.tv_usec *= 10;
12605 }
Denis Vlasenko037576d2007-10-20 18:30:38 +000012606 } else if (ts.tv_sec < 0 || errno) {
Denis Vlasenkob012b102007-02-19 22:43:01 +000012607 ash_msg_and_raise_error("invalid timeout");
Paul Fox02eb9342005-09-07 16:56:02 +000012608 }
Denis Vlasenko037576d2007-10-20 18:30:38 +000012609 if (!(ts.tv_sec | ts.tv_usec)) { /* both are 0? */
Denis Vlasenkob012b102007-02-19 22:43:01 +000012610 ash_msg_and_raise_error("invalid timeout");
Denis Vlasenko037576d2007-10-20 18:30:38 +000012611 }
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012612#endif /* if 0 */
Paul Fox02eb9342005-09-07 16:56:02 +000012613 break;
12614#endif
12615 case 'r':
12616 rflag = 1;
12617 break;
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012618 case 'u':
12619 fd = bb_strtou(optionarg, NULL, 10);
12620 if (fd < 0 || errno)
12621 ash_msg_and_raise_error("invalid file descriptor");
12622 break;
Paul Fox02eb9342005-09-07 16:56:02 +000012623 default:
12624 break;
12625 }
Eric Andersenc470f442003-07-28 09:56:35 +000012626 }
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012627 if (prompt && isatty(fd)) {
Eric Andersenc470f442003-07-28 09:56:35 +000012628 out2str(prompt);
Eric Andersenc470f442003-07-28 09:56:35 +000012629 }
Denis Vlasenko5cedb752007-02-18 19:56:41 +000012630 ap = argptr;
12631 if (*ap == NULL)
Denis Vlasenko9cd4c762008-06-18 19:22:19 +000012632 ap = (char**)arg_REPLY;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000012633 ifs = bltinlookup("IFS");
12634 if (ifs == NULL)
Eric Andersenc470f442003-07-28 09:56:35 +000012635 ifs = defifs;
Denis Vlasenko131ae172007-02-18 13:00:19 +000012636#if ENABLE_ASH_READ_NCHARS
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012637 tcgetattr(fd, &tty);
12638 old_tty = tty;
12639 if (nchars || silent) {
12640 if (nchars) {
12641 tty.c_lflag &= ~ICANON;
12642 tty.c_cc[VMIN] = nchars < 256 ? nchars : 255;
Paul Fox02eb9342005-09-07 16:56:02 +000012643 }
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012644 if (silent) {
12645 tty.c_lflag &= ~(ECHO | ECHOK | ECHONL);
12646 }
12647 /* if tcgetattr failed, tcsetattr will fail too.
12648 * Ignoring, it's harmless. */
12649 tcsetattr(fd, TCSANOW, &tty);
Paul Fox02eb9342005-09-07 16:56:02 +000012650 }
12651#endif
Paul Fox02eb9342005-09-07 16:56:02 +000012652
Eric Andersenc470f442003-07-28 09:56:35 +000012653 status = 0;
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012654 startword = 2;
Eric Andersenc470f442003-07-28 09:56:35 +000012655 backslash = 0;
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012656#if ENABLE_ASH_READ_TIMEOUT
12657 if (timeout) /* NB: ensuring end_ms is nonzero */
12658 end_ms = ((unsigned)(monotonic_us() / 1000) + timeout) | 1;
12659#endif
Eric Andersenc470f442003-07-28 09:56:35 +000012660 STARTSTACKSTR(p);
Denis Vlasenko037576d2007-10-20 18:30:38 +000012661 do {
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012662 const char *is_ifs;
12663
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012664#if ENABLE_ASH_READ_TIMEOUT
12665 if (end_ms) {
12666 struct pollfd pfd[1];
12667 pfd[0].fd = fd;
12668 pfd[0].events = POLLIN;
12669 timeout = end_ms - (unsigned)(monotonic_us() / 1000);
12670 if ((int)timeout <= 0 /* already late? */
12671 || safe_poll(pfd, 1, timeout) != 1 /* no? wait... */
12672 ) { /* timed out! */
12673#if ENABLE_ASH_READ_NCHARS
12674 tcsetattr(fd, TCSANOW, &old_tty);
12675#endif
12676 return 1;
12677 }
12678 }
12679#endif
12680 if (nonblock_safe_read(fd, &c, 1) != 1) {
Eric Andersenc470f442003-07-28 09:56:35 +000012681 status = 1;
12682 break;
12683 }
12684 if (c == '\0')
12685 continue;
12686 if (backslash) {
12687 backslash = 0;
12688 if (c != '\n')
12689 goto put;
12690 continue;
12691 }
12692 if (!rflag && c == '\\') {
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012693 backslash = 1;
Eric Andersenc470f442003-07-28 09:56:35 +000012694 continue;
12695 }
12696 if (c == '\n')
12697 break;
Denis Vlasenkof6fbd622009-03-31 19:36:58 +000012698 /* $IFS splitting */
Denis Vlasenko551ffdc2009-04-01 19:48:05 +000012699/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_05 */
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012700 is_ifs = strchr(ifs, c);
12701 if (startword && is_ifs) {
12702 if (isspace(c))
12703 continue;
Denis Vlasenkof6fbd622009-03-31 19:36:58 +000012704 /* it is a non-space ifs char */
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012705 startword--;
12706 if (startword == 1) /* first one? */
Denis Vlasenkof6fbd622009-03-31 19:36:58 +000012707 continue; /* yes, it is not next word yet */
Eric Andersenc470f442003-07-28 09:56:35 +000012708 }
12709 startword = 0;
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012710 if (ap[1] != NULL && is_ifs) {
12711 const char *beg;
Eric Andersenc470f442003-07-28 09:56:35 +000012712 STACKSTRNUL(p);
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012713 beg = stackblock();
12714 setvar(*ap, beg, 0);
Eric Andersenc470f442003-07-28 09:56:35 +000012715 ap++;
Denis Vlasenkof6fbd622009-03-31 19:36:58 +000012716 /* can we skip one non-space ifs char? (2: yes) */
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012717 startword = isspace(c) ? 2 : 1;
Eric Andersenc470f442003-07-28 09:56:35 +000012718 STARTSTACKSTR(p);
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012719 continue;
Eric Andersenc470f442003-07-28 09:56:35 +000012720 }
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012721 put:
12722 STPUTC(c, p);
Eric Andersenc470f442003-07-28 09:56:35 +000012723 }
Denis Vlasenko037576d2007-10-20 18:30:38 +000012724/* end of do {} while: */
Denis Vlasenko131ae172007-02-18 13:00:19 +000012725#if ENABLE_ASH_READ_NCHARS
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012726 while (--nchars);
Denis Vlasenko037576d2007-10-20 18:30:38 +000012727#else
12728 while (1);
12729#endif
12730
12731#if ENABLE_ASH_READ_NCHARS
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012732 tcsetattr(fd, TCSANOW, &old_tty);
Paul Fox02eb9342005-09-07 16:56:02 +000012733#endif
12734
Eric Andersenc470f442003-07-28 09:56:35 +000012735 STACKSTRNUL(p);
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012736 /* Remove trailing space ifs chars */
12737 while ((char *)stackblock() <= --p && isspace(*p) && strchr(ifs, *p) != NULL)
Eric Andersenc470f442003-07-28 09:56:35 +000012738 *p = '\0';
12739 setvar(*ap, stackblock(), 0);
12740 while (*++ap != NULL)
12741 setvar(*ap, nullstr, 0);
12742 return status;
12743}
12744
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012745static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012746umaskcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersenc470f442003-07-28 09:56:35 +000012747{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000012748 static const char permuser[3] ALIGN1 = "ugo";
12749 static const char permmode[3] ALIGN1 = "rwx";
12750 static const short permmask[] ALIGN2 = {
Eric Andersenc470f442003-07-28 09:56:35 +000012751 S_IRUSR, S_IWUSR, S_IXUSR,
12752 S_IRGRP, S_IWGRP, S_IXGRP,
12753 S_IROTH, S_IWOTH, S_IXOTH
12754 };
12755
Denis Vlasenkoeb858492009-04-18 02:06:54 +000012756 /* TODO: use bb_parse_mode() instead */
12757
Eric Andersenc470f442003-07-28 09:56:35 +000012758 char *ap;
12759 mode_t mask;
12760 int i;
12761 int symbolic_mode = 0;
12762
12763 while (nextopt("S") != '\0') {
12764 symbolic_mode = 1;
12765 }
12766
Denis Vlasenkob012b102007-02-19 22:43:01 +000012767 INT_OFF;
Eric Andersenc470f442003-07-28 09:56:35 +000012768 mask = umask(0);
12769 umask(mask);
Denis Vlasenkob012b102007-02-19 22:43:01 +000012770 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +000012771
Denis Vlasenko5cedb752007-02-18 19:56:41 +000012772 ap = *argptr;
12773 if (ap == NULL) {
Eric Andersenc470f442003-07-28 09:56:35 +000012774 if (symbolic_mode) {
12775 char buf[18];
12776 char *p = buf;
12777
12778 for (i = 0; i < 3; i++) {
12779 int j;
12780
12781 *p++ = permuser[i];
12782 *p++ = '=';
12783 for (j = 0; j < 3; j++) {
12784 if ((mask & permmask[3 * i + j]) == 0) {
12785 *p++ = permmode[j];
12786 }
12787 }
12788 *p++ = ',';
12789 }
12790 *--p = 0;
12791 puts(buf);
12792 } else {
12793 out1fmt("%.4o\n", mask);
12794 }
12795 } else {
Denis Vlasenkoaa744452007-02-23 01:04:22 +000012796 if (isdigit((unsigned char) *ap)) {
Eric Andersenc470f442003-07-28 09:56:35 +000012797 mask = 0;
12798 do {
12799 if (*ap >= '8' || *ap < '0')
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +020012800 ash_msg_and_raise_error(msg_illnum, argv[1]);
Eric Andersenc470f442003-07-28 09:56:35 +000012801 mask = (mask << 3) + (*ap - '0');
12802 } while (*++ap != '\0');
12803 umask(mask);
12804 } else {
12805 mask = ~mask & 0777;
12806 if (!bb_parse_mode(ap, &mask)) {
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +000012807 ash_msg_and_raise_error("illegal mode: %s", ap);
Eric Andersenc470f442003-07-28 09:56:35 +000012808 }
12809 umask(~mask & 0777);
12810 }
12811 }
12812 return 0;
12813}
12814
12815/*
12816 * ulimit builtin
12817 *
12818 * This code, originally by Doug Gwyn, Doug Kingston, Eric Gisin, and
12819 * Michael Rendell was ripped from pdksh 5.0.8 and hacked for use with
12820 * ash by J.T. Conklin.
12821 *
12822 * Public domain.
12823 */
Eric Andersenc470f442003-07-28 09:56:35 +000012824struct limits {
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012825 uint8_t cmd; /* RLIMIT_xxx fit into it */
12826 uint8_t factor_shift; /* shift by to get rlim_{cur,max} values */
Eric Andersenc470f442003-07-28 09:56:35 +000012827 char option;
12828};
12829
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012830static const struct limits limits_tbl[] = {
Eric Andersenc470f442003-07-28 09:56:35 +000012831#ifdef RLIMIT_CPU
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012832 { RLIMIT_CPU, 0, 't' },
Eric Andersenc470f442003-07-28 09:56:35 +000012833#endif
12834#ifdef RLIMIT_FSIZE
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012835 { RLIMIT_FSIZE, 9, 'f' },
Eric Andersenc470f442003-07-28 09:56:35 +000012836#endif
12837#ifdef RLIMIT_DATA
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012838 { RLIMIT_DATA, 10, 'd' },
Eric Andersenc470f442003-07-28 09:56:35 +000012839#endif
12840#ifdef RLIMIT_STACK
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012841 { RLIMIT_STACK, 10, 's' },
Eric Andersenc470f442003-07-28 09:56:35 +000012842#endif
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012843#ifdef RLIMIT_CORE
12844 { RLIMIT_CORE, 9, 'c' },
Eric Andersenc470f442003-07-28 09:56:35 +000012845#endif
12846#ifdef RLIMIT_RSS
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012847 { RLIMIT_RSS, 10, 'm' },
Eric Andersenc470f442003-07-28 09:56:35 +000012848#endif
12849#ifdef RLIMIT_MEMLOCK
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012850 { RLIMIT_MEMLOCK, 10, 'l' },
Eric Andersenc470f442003-07-28 09:56:35 +000012851#endif
12852#ifdef RLIMIT_NPROC
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012853 { RLIMIT_NPROC, 0, 'p' },
Eric Andersenc470f442003-07-28 09:56:35 +000012854#endif
12855#ifdef RLIMIT_NOFILE
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012856 { RLIMIT_NOFILE, 0, 'n' },
Eric Andersenc470f442003-07-28 09:56:35 +000012857#endif
Glenn L McGrath76620622004-01-13 10:19:37 +000012858#ifdef RLIMIT_AS
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012859 { RLIMIT_AS, 10, 'v' },
Eric Andersenc470f442003-07-28 09:56:35 +000012860#endif
Glenn L McGrath76620622004-01-13 10:19:37 +000012861#ifdef RLIMIT_LOCKS
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012862 { RLIMIT_LOCKS, 0, 'w' },
Eric Andersenc470f442003-07-28 09:56:35 +000012863#endif
Eric Andersenc470f442003-07-28 09:56:35 +000012864};
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012865static const char limits_name[] =
12866#ifdef RLIMIT_CPU
12867 "time(seconds)" "\0"
12868#endif
12869#ifdef RLIMIT_FSIZE
12870 "file(blocks)" "\0"
12871#endif
12872#ifdef RLIMIT_DATA
12873 "data(kb)" "\0"
12874#endif
12875#ifdef RLIMIT_STACK
12876 "stack(kb)" "\0"
12877#endif
12878#ifdef RLIMIT_CORE
12879 "coredump(blocks)" "\0"
12880#endif
12881#ifdef RLIMIT_RSS
12882 "memory(kb)" "\0"
12883#endif
12884#ifdef RLIMIT_MEMLOCK
12885 "locked memory(kb)" "\0"
12886#endif
12887#ifdef RLIMIT_NPROC
12888 "process" "\0"
12889#endif
12890#ifdef RLIMIT_NOFILE
12891 "nofiles" "\0"
12892#endif
12893#ifdef RLIMIT_AS
12894 "vmemory(kb)" "\0"
12895#endif
12896#ifdef RLIMIT_LOCKS
12897 "locks" "\0"
12898#endif
12899;
Eric Andersenc470f442003-07-28 09:56:35 +000012900
Glenn L McGrath76620622004-01-13 10:19:37 +000012901enum limtype { SOFT = 0x1, HARD = 0x2 };
12902
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012903static void
12904printlim(enum limtype how, const struct rlimit *limit,
Glenn L McGrath76620622004-01-13 10:19:37 +000012905 const struct limits *l)
12906{
12907 rlim_t val;
12908
12909 val = limit->rlim_max;
12910 if (how & SOFT)
12911 val = limit->rlim_cur;
12912
12913 if (val == RLIM_INFINITY)
12914 out1fmt("unlimited\n");
12915 else {
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012916 val >>= l->factor_shift;
Glenn L McGrath76620622004-01-13 10:19:37 +000012917 out1fmt("%lld\n", (long long) val);
12918 }
12919}
12920
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012921static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012922ulimitcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersenc470f442003-07-28 09:56:35 +000012923{
Denys Vlasenko76622db2009-10-04 01:14:19 +020012924 rlim_t val;
Glenn L McGrath76620622004-01-13 10:19:37 +000012925 enum limtype how = SOFT | HARD;
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012926 const struct limits *l;
12927 int set, all = 0;
12928 int optc, what;
12929 struct rlimit limit;
Eric Andersenc470f442003-07-28 09:56:35 +000012930
12931 what = 'f';
Glenn L McGrath16e45d72004-02-04 08:24:39 +000012932 while ((optc = nextopt("HSa"
12933#ifdef RLIMIT_CPU
12934 "t"
12935#endif
12936#ifdef RLIMIT_FSIZE
12937 "f"
12938#endif
12939#ifdef RLIMIT_DATA
12940 "d"
12941#endif
12942#ifdef RLIMIT_STACK
12943 "s"
12944#endif
12945#ifdef RLIMIT_CORE
12946 "c"
12947#endif
12948#ifdef RLIMIT_RSS
12949 "m"
12950#endif
12951#ifdef RLIMIT_MEMLOCK
12952 "l"
12953#endif
12954#ifdef RLIMIT_NPROC
12955 "p"
12956#endif
12957#ifdef RLIMIT_NOFILE
12958 "n"
12959#endif
12960#ifdef RLIMIT_AS
12961 "v"
12962#endif
12963#ifdef RLIMIT_LOCKS
12964 "w"
12965#endif
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000012966 )) != '\0')
Eric Andersenc470f442003-07-28 09:56:35 +000012967 switch (optc) {
12968 case 'H':
12969 how = HARD;
12970 break;
12971 case 'S':
12972 how = SOFT;
12973 break;
12974 case 'a':
12975 all = 1;
12976 break;
12977 default:
12978 what = optc;
12979 }
12980
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012981 for (l = limits_tbl; l->option != what; l++)
12982 continue;
Eric Andersenc470f442003-07-28 09:56:35 +000012983
12984 set = *argptr ? 1 : 0;
Denys Vlasenko76622db2009-10-04 01:14:19 +020012985 val = 0;
Eric Andersenc470f442003-07-28 09:56:35 +000012986 if (set) {
12987 char *p = *argptr;
12988
12989 if (all || argptr[1])
Denis Vlasenkob012b102007-02-19 22:43:01 +000012990 ash_msg_and_raise_error("too many arguments");
Eric Andersen81fe1232003-07-29 06:38:40 +000012991 if (strncmp(p, "unlimited\n", 9) == 0)
Eric Andersenc470f442003-07-28 09:56:35 +000012992 val = RLIM_INFINITY;
12993 else {
Denys Vlasenko76622db2009-10-04 01:14:19 +020012994 if (sizeof(val) == sizeof(int))
12995 val = bb_strtou(p, NULL, 10);
12996 else if (sizeof(val) == sizeof(long))
12997 val = bb_strtoul(p, NULL, 10);
12998 else
12999 val = bb_strtoull(p, NULL, 10);
13000 if (errno)
Denis Vlasenkob012b102007-02-19 22:43:01 +000013001 ash_msg_and_raise_error("bad number");
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000013002 val <<= l->factor_shift;
Eric Andersenc470f442003-07-28 09:56:35 +000013003 }
13004 }
13005 if (all) {
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000013006 const char *lname = limits_name;
13007 for (l = limits_tbl; l != &limits_tbl[ARRAY_SIZE(limits_tbl)]; l++) {
Eric Andersenc470f442003-07-28 09:56:35 +000013008 getrlimit(l->cmd, &limit);
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000013009 out1fmt("%-20s ", lname);
13010 lname += strlen(lname) + 1;
Glenn L McGrath76620622004-01-13 10:19:37 +000013011 printlim(how, &limit, l);
Eric Andersenc470f442003-07-28 09:56:35 +000013012 }
13013 return 0;
13014 }
13015
13016 getrlimit(l->cmd, &limit);
13017 if (set) {
13018 if (how & HARD)
13019 limit.rlim_max = val;
13020 if (how & SOFT)
13021 limit.rlim_cur = val;
13022 if (setrlimit(l->cmd, &limit) < 0)
Denis Vlasenkob012b102007-02-19 22:43:01 +000013023 ash_msg_and_raise_error("error setting limit (%m)");
Eric Andersenc470f442003-07-28 09:56:35 +000013024 } else {
Glenn L McGrath76620622004-01-13 10:19:37 +000013025 printlim(how, &limit, l);
Eric Andersenc470f442003-07-28 09:56:35 +000013026 }
13027 return 0;
13028}
13029
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000013030/* ============ main() and helpers */
13031
13032/*
13033 * Called to exit the shell.
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013034 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000013035static void exitshell(void) NORETURN;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000013036static void
13037exitshell(void)
13038{
13039 struct jmploc loc;
13040 char *p;
13041 int status;
13042
13043 status = exitstatus;
13044 TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
13045 if (setjmp(loc.loc)) {
Denis Vlasenko7f88e342009-03-19 03:36:18 +000013046 if (exception_type == EXEXIT)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000013047/* dash bug: it just does _exit(exitstatus) here
13048 * but we have to do setjobctl(0) first!
13049 * (bug is still not fixed in dash-0.5.3 - if you run dash
13050 * under Midnight Commander, on exit from dash MC is backgrounded) */
13051 status = exitstatus;
13052 goto out;
13053 }
13054 exception_handler = &loc;
13055 p = trap[0];
13056 if (p) {
13057 trap[0] = NULL;
13058 evalstring(p, 0);
Denys Vlasenko0800e3a2009-09-24 03:09:26 +020013059 free(p);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000013060 }
13061 flush_stdout_stderr();
13062 out:
13063 setjobctl(0);
13064 _exit(status);
13065 /* NOTREACHED */
13066}
13067
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000013068static void
13069init(void)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013070{
13071 /* from input.c: */
Denis Vlasenko41eb3002008-11-28 03:42:31 +000013072 basepf.next_to_pgetc = basepf.buf = basebuf;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013073
13074 /* from trap.c: */
13075 signal(SIGCHLD, SIG_DFL);
13076
13077 /* from var.c: */
13078 {
13079 char **envp;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013080 const char *p;
13081 struct stat st1, st2;
13082
13083 initvar();
13084 for (envp = environ; envp && *envp; envp++) {
13085 if (strchr(*envp, '=')) {
13086 setvareq(*envp, VEXPORT|VTEXTFIXED);
13087 }
13088 }
13089
Denys Vlasenko7bb346f2009-10-06 22:09:50 +020013090 setvar("PPID", utoa(getppid()), 0);
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013091
13092 p = lookupvar("PWD");
13093 if (p)
13094 if (*p != '/' || stat(p, &st1) || stat(".", &st2)
13095 || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino)
13096 p = '\0';
13097 setpwd(p, 0);
13098 }
13099}
13100
13101/*
13102 * Process the shell command line arguments.
13103 */
13104static void
Denis Vlasenko68404f12008-03-17 09:00:54 +000013105procargs(char **argv)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013106{
13107 int i;
13108 const char *xminusc;
13109 char **xargv;
13110
13111 xargv = argv;
13112 arg0 = xargv[0];
Denis Vlasenko68404f12008-03-17 09:00:54 +000013113 /* if (xargv[0]) - mmm, this is always true! */
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013114 xargv++;
13115 for (i = 0; i < NOPTS; i++)
13116 optlist[i] = 2;
13117 argptr = xargv;
Denis Vlasenko28bf6712008-02-14 15:01:47 +000013118 if (options(1)) {
13119 /* it already printed err message */
13120 raise_exception(EXERROR);
13121 }
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013122 xargv = argptr;
13123 xminusc = minusc;
13124 if (*xargv == NULL) {
13125 if (xminusc)
13126 ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
13127 sflag = 1;
13128 }
13129 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
13130 iflag = 1;
13131 if (mflag == 2)
13132 mflag = iflag;
13133 for (i = 0; i < NOPTS; i++)
13134 if (optlist[i] == 2)
13135 optlist[i] = 0;
13136#if DEBUG == 2
13137 debug = 1;
13138#endif
13139 /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
13140 if (xminusc) {
13141 minusc = *xargv++;
13142 if (*xargv)
13143 goto setarg0;
13144 } else if (!sflag) {
13145 setinputfile(*xargv, 0);
13146 setarg0:
13147 arg0 = *xargv++;
13148 commandname = arg0;
13149 }
13150
13151 shellparam.p = xargv;
13152#if ENABLE_ASH_GETOPTS
13153 shellparam.optind = 1;
13154 shellparam.optoff = -1;
13155#endif
Denis Vlasenko01631112007-12-16 17:20:38 +000013156 /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013157 while (*xargv) {
13158 shellparam.nparam++;
13159 xargv++;
13160 }
13161 optschanged();
13162}
13163
13164/*
13165 * Read /etc/profile or .profile.
13166 */
13167static void
13168read_profile(const char *name)
13169{
13170 int skip;
13171
13172 if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
13173 return;
13174 skip = cmdloop(0);
13175 popfile();
13176 if (skip)
13177 exitshell();
13178}
13179
Denis Vlasenko0c032a42007-02-23 01:03:40 +000013180/*
13181 * This routine is called when an error or an interrupt occurs in an
13182 * interactive shell and control is returned to the main command loop.
13183 */
13184static void
13185reset(void)
13186{
13187 /* from eval.c: */
13188 evalskip = 0;
13189 loopnest = 0;
13190 /* from input.c: */
Denis Vlasenko41eb3002008-11-28 03:42:31 +000013191 g_parsefile->left_in_buffer = 0;
13192 g_parsefile->left_in_line = 0; /* clear input buffer */
Denis Vlasenko0c032a42007-02-23 01:03:40 +000013193 popallfiles();
13194 /* from parser.c: */
13195 tokpushback = 0;
13196 checkkwd = 0;
13197 /* from redir.c: */
Denis Vlasenko34c73c42008-08-16 11:48:02 +000013198 clearredir(/*drop:*/ 0);
Denis Vlasenko0c032a42007-02-23 01:03:40 +000013199}
13200
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013201#if PROFILE
13202static short profile_buf[16384];
13203extern int etext();
13204#endif
13205
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000013206/*
13207 * Main routine. We initialize things, parse the arguments, execute
13208 * profiles if we're a login shell, and then call cmdloop to execute
13209 * commands. The setjmp call sets up the location to jump to when an
13210 * exception occurs. When an exception occurs the variable "state"
13211 * is used to figure out how far we had gotten.
13212 */
Denis Vlasenko9b49a5e2007-10-11 10:05:36 +000013213int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000013214int ash_main(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013215{
Mike Frysinger98c52642009-04-02 10:02:37 +000013216 const char *shinit;
Denis Vlasenko4e12b1a2008-12-23 23:36:47 +000013217 volatile smallint state;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013218 struct jmploc jmploc;
13219 struct stackmark smark;
13220
Denis Vlasenko01631112007-12-16 17:20:38 +000013221 /* Initialize global data */
13222 INIT_G_misc();
13223 INIT_G_memstack();
13224 INIT_G_var();
Denis Vlasenkoee87ebf2007-12-21 22:18:16 +000013225#if ENABLE_ASH_ALIAS
Denis Vlasenko01631112007-12-16 17:20:38 +000013226 INIT_G_alias();
Denis Vlasenkoee87ebf2007-12-21 22:18:16 +000013227#endif
Denis Vlasenko01631112007-12-16 17:20:38 +000013228 INIT_G_cmdtable();
13229
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013230#if PROFILE
13231 monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
13232#endif
13233
13234#if ENABLE_FEATURE_EDITING
13235 line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
13236#endif
13237 state = 0;
13238 if (setjmp(jmploc.loc)) {
Denis Vlasenko7f88e342009-03-19 03:36:18 +000013239 smallint e;
Denis Vlasenko4e12b1a2008-12-23 23:36:47 +000013240 smallint s;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013241
13242 reset();
13243
Denis Vlasenko7f88e342009-03-19 03:36:18 +000013244 e = exception_type;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013245 if (e == EXERROR)
13246 exitstatus = 2;
13247 s = state;
13248 if (e == EXEXIT || s == 0 || iflag == 0 || shlvl)
13249 exitshell();
Denis Vlasenko7f88e342009-03-19 03:36:18 +000013250 if (e == EXINT)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013251 outcslow('\n', stderr);
Denis Vlasenko7f88e342009-03-19 03:36:18 +000013252
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013253 popstackmark(&smark);
13254 FORCE_INT_ON; /* enable interrupts */
13255 if (s == 1)
13256 goto state1;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000013257 if (s == 2)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013258 goto state2;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000013259 if (s == 3)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013260 goto state3;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000013261 goto state4;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013262 }
13263 exception_handler = &jmploc;
13264#if DEBUG
13265 opentrace();
Denis Vlasenko653d8e72009-03-19 21:59:35 +000013266 TRACE(("Shell args: "));
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000013267 trace_puts_args(argv);
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013268#endif
13269 rootpid = getpid();
13270
13271#if ENABLE_ASH_RANDOM_SUPPORT
Denis Vlasenkoce13b762008-06-29 02:25:53 +000013272 /* Can use monotonic_ns() for better randomness but for now it is
13273 * not used anywhere else in busybox... so avoid bloat */
Denys Vlasenko3ea2e822009-10-09 20:59:04 +020013274 INIT_RANDOM_T(&random_gen, rootpid, monotonic_us());
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013275#endif
13276 init();
13277 setstackmark(&smark);
Denis Vlasenko68404f12008-03-17 09:00:54 +000013278 procargs(argv);
13279
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013280#if ENABLE_FEATURE_EDITING_SAVEHISTORY
13281 if (iflag) {
13282 const char *hp = lookupvar("HISTFILE");
13283
13284 if (hp == NULL) {
13285 hp = lookupvar("HOME");
13286 if (hp != NULL) {
13287 char *defhp = concat_path_file(hp, ".ash_history");
13288 setvar("HISTFILE", defhp, 0);
13289 free(defhp);
13290 }
13291 }
13292 }
13293#endif
Denis Vlasenko4e12b1a2008-12-23 23:36:47 +000013294 if (/* argv[0] && */ argv[0][0] == '-')
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013295 isloginsh = 1;
13296 if (isloginsh) {
13297 state = 1;
13298 read_profile("/etc/profile");
13299 state1:
13300 state = 2;
13301 read_profile(".profile");
13302 }
13303 state2:
13304 state = 3;
13305 if (
13306#ifndef linux
Denis Vlasenko0c032a42007-02-23 01:03:40 +000013307 getuid() == geteuid() && getgid() == getegid() &&
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013308#endif
Denis Vlasenko0c032a42007-02-23 01:03:40 +000013309 iflag
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013310 ) {
13311 shinit = lookupvar("ENV");
13312 if (shinit != NULL && *shinit != '\0') {
13313 read_profile(shinit);
13314 }
13315 }
13316 state3:
13317 state = 4;
Denis Vlasenko5c2b8142009-03-19 01:59:59 +000013318 if (minusc) {
13319 /* evalstring pushes parsefile stack.
13320 * Ensure we don't falsely claim that 0 (stdin)
Denis Vlasenko5368ad52009-03-20 10:20:08 +000013321 * is one of stacked source fds.
13322 * Testcase: ash -c 'exec 1>&0' must not complain. */
Denis Vlasenko5c2b8142009-03-19 01:59:59 +000013323 if (!sflag)
13324 g_parsefile->fd = -1;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013325 evalstring(minusc, 0);
Denis Vlasenko5c2b8142009-03-19 01:59:59 +000013326 }
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013327
13328 if (sflag || minusc == NULL) {
Denys Vlasenkodb9c57e2009-09-27 02:48:53 +020013329#if MAX_HISTORY > 0 && ENABLE_FEATURE_EDITING_SAVEHISTORY
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +000013330 if (iflag) {
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013331 const char *hp = lookupvar("HISTFILE");
Denis Vlasenko5c2b8142009-03-19 01:59:59 +000013332 if (hp)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013333 line_input_state->hist_file = hp;
13334 }
13335#endif
13336 state4: /* XXX ??? - why isn't this before the "if" statement */
13337 cmdloop(1);
13338 }
13339#if PROFILE
13340 monitor(0);
13341#endif
13342#ifdef GPROF
13343 {
13344 extern void _mcleanup(void);
13345 _mcleanup();
13346 }
13347#endif
13348 exitshell();
13349 /* NOTREACHED */
13350}
13351
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013352
Eric Andersendf82f612001-06-28 07:46:40 +000013353/*-
13354 * Copyright (c) 1989, 1991, 1993, 1994
Eric Andersen2870d962001-07-02 17:27:21 +000013355 * The Regents of the University of California. All rights reserved.
Eric Andersendf82f612001-06-28 07:46:40 +000013356 *
13357 * This code is derived from software contributed to Berkeley by
13358 * Kenneth Almquist.
13359 *
13360 * Redistribution and use in source and binary forms, with or without
13361 * modification, are permitted provided that the following conditions
13362 * are met:
13363 * 1. Redistributions of source code must retain the above copyright
13364 * notice, this list of conditions and the following disclaimer.
13365 * 2. Redistributions in binary form must reproduce the above copyright
13366 * notice, this list of conditions and the following disclaimer in the
13367 * documentation and/or other materials provided with the distribution.
"Vladimir N. Oleynik"ddc280e2005-12-15 12:01:49 +000013368 * 3. Neither the name of the University nor the names of its contributors
Eric Andersendf82f612001-06-28 07:46:40 +000013369 * may be used to endorse or promote products derived from this software
13370 * without specific prior written permission.
13371 *
13372 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
13373 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
13374 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
13375 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
13376 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
13377 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
13378 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
13379 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
13380 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
13381 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
13382 * SUCH DAMAGE.
13383 */