blob: 65d41cc5b3423fdab98c937d1b7c1a38f47392fc [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"
Denys Vlasenko36df0482009-10-19 16:07:28 +020056#else
57# define CLEAR_RANDOM_T(rnd) ((void)0)
Denys Vlasenko3ea2e822009-10-09 20:59:04 +020058#endif
Denis Vlasenko61befda2008-11-25 01:36:03 +000059
60#if defined SINGLE_APPLET_MAIN
61/* STANDALONE does not make sense, and won't compile */
Denys Vlasenko3ea2e822009-10-09 20:59:04 +020062# undef CONFIG_FEATURE_SH_STANDALONE
63# undef ENABLE_FEATURE_SH_STANDALONE
64# undef IF_FEATURE_SH_STANDALONE
65# undef IF_NOT_FEATURE_SH_STANDALONE(...)
66# define ENABLE_FEATURE_SH_STANDALONE 0
67# define IF_FEATURE_SH_STANDALONE(...)
68# define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
Eric Andersencb57d552001-06-28 07:25:16 +000069#endif
70
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000071#ifndef PIPE_BUF
Denis Vlasenko653d8e72009-03-19 21:59:35 +000072# define PIPE_BUF 4096 /* amount of buffering in a pipe */
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000073#endif
74
Denis Vlasenkob012b102007-02-19 22:43:01 +000075#if defined(__uClinux__)
Denis Vlasenko653d8e72009-03-19 21:59:35 +000076# error "Do not even bother, ash will not run on NOMMU machine"
Denis Vlasenkob012b102007-02-19 22:43:01 +000077#endif
78
Denis Vlasenkob012b102007-02-19 22:43:01 +000079
Denis Vlasenko01631112007-12-16 17:20:38 +000080/* ============ Hash table sizes. Configurable. */
81
82#define VTABSIZE 39
83#define ATABSIZE 39
84#define CMDTABLESIZE 31 /* should be prime */
85
86
Denis Vlasenkob012b102007-02-19 22:43:01 +000087/* ============ Shell options */
88
89static const char *const optletters_optnames[] = {
90 "e" "errexit",
91 "f" "noglob",
92 "I" "ignoreeof",
93 "i" "interactive",
94 "m" "monitor",
95 "n" "noexec",
96 "s" "stdin",
97 "x" "xtrace",
98 "v" "verbose",
99 "C" "noclobber",
100 "a" "allexport",
101 "b" "notify",
102 "u" "nounset",
Denys Vlasenko285ad152009-12-04 23:02:27 +0100103 "\0" "vi",
Denis Vlasenkob012b102007-02-19 22:43:01 +0000104#if DEBUG
Denis Vlasenko6ca409e2007-08-12 20:58:27 +0000105 ,"\0" "nolog"
106 ,"\0" "debug"
Denis Vlasenkob012b102007-02-19 22:43:01 +0000107#endif
108};
109
Denys Vlasenko285ad152009-12-04 23:02:27 +0100110#define optletters(n) optletters_optnames[n][0]
111#define optnames(n) (optletters_optnames[n] + 1)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000112
Denis Vlasenko80b8b392007-06-25 10:55:35 +0000113enum { NOPTS = ARRAY_SIZE(optletters_optnames) };
Denis Vlasenkob012b102007-02-19 22:43:01 +0000114
Eric Andersenc470f442003-07-28 09:56:35 +0000115
Denis Vlasenkob012b102007-02-19 22:43:01 +0000116/* ============ Misc data */
Eric Andersenc470f442003-07-28 09:56:35 +0000117
Denis Vlasenko6ca409e2007-08-12 20:58:27 +0000118static const char homestr[] ALIGN1 = "HOME";
119static const char snlfmt[] ALIGN1 = "%s\n";
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200120static const char msg_illnum[] ALIGN1 = "Illegal number: %s";
Denis Vlasenkoaa744452007-02-23 01:04:22 +0000121
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +0000122/*
Eric Andersenc470f442003-07-28 09:56:35 +0000123 * We enclose jmp_buf in a structure so that we can declare pointers to
124 * jump locations. The global variable handler contains the location to
Denis Vlasenkof1733952009-03-19 23:21:55 +0000125 * jump to when an exception occurs, and the global variable exception_type
Eric Andersenaff114c2004-04-14 17:51:38 +0000126 * contains a code identifying the exception. To implement nested
Eric Andersenc470f442003-07-28 09:56:35 +0000127 * exception handlers, the user should save the value of handler on entry
128 * to an inner scope, set handler to point to a jmploc structure for the
129 * inner scope, and restore handler on exit from the scope.
130 */
Eric Andersenc470f442003-07-28 09:56:35 +0000131struct jmploc {
132 jmp_buf loc;
133};
Denis Vlasenko01631112007-12-16 17:20:38 +0000134
135struct globals_misc {
136 /* pid of main shell */
137 int rootpid;
138 /* shell level: 0 for the main shell, 1 for its children, and so on */
139 int shlvl;
140#define rootshell (!shlvl)
141 char *minusc; /* argument to -c option */
142
143 char *curdir; // = nullstr; /* current working directory */
144 char *physdir; // = nullstr; /* physical working directory */
145
146 char *arg0; /* value of $0 */
147
148 struct jmploc *exception_handler;
Denis Vlasenko991a1da2008-02-10 19:02:53 +0000149
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200150 volatile int suppress_int; /* counter */
151 volatile /*sig_atomic_t*/ smallint pending_int; /* 1 = got SIGINT */
Denis Vlasenko991a1da2008-02-10 19:02:53 +0000152 /* last pending signal */
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200153 volatile /*sig_atomic_t*/ smallint pending_sig;
Denis Vlasenko7f88e342009-03-19 03:36:18 +0000154 smallint exception_type; /* kind of exception (0..5) */
Denis Vlasenko01631112007-12-16 17:20:38 +0000155 /* exceptions */
Eric Andersenc470f442003-07-28 09:56:35 +0000156#define EXINT 0 /* SIGINT received */
157#define EXERROR 1 /* a generic error */
158#define EXSHELLPROC 2 /* execute a shell procedure */
159#define EXEXEC 3 /* command execution failed */
160#define EXEXIT 4 /* exit the shell */
161#define EXSIG 5 /* trapped signal in wait(1) */
Eric Andersen2870d962001-07-02 17:27:21 +0000162
Denis Vlasenko01631112007-12-16 17:20:38 +0000163 smallint isloginsh;
Denis Vlasenkob07a4962008-06-22 13:16:23 +0000164 char nullstr[1]; /* zero length string */
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000165
166 char optlist[NOPTS];
167#define eflag optlist[0]
168#define fflag optlist[1]
169#define Iflag optlist[2]
170#define iflag optlist[3]
171#define mflag optlist[4]
172#define nflag optlist[5]
173#define sflag optlist[6]
174#define xflag optlist[7]
175#define vflag optlist[8]
176#define Cflag optlist[9]
177#define aflag optlist[10]
178#define bflag optlist[11]
179#define uflag optlist[12]
180#define viflag optlist[13]
181#if DEBUG
182#define nolog optlist[14]
183#define debug optlist[15]
184#endif
185
186 /* trap handler commands */
Denis Vlasenko01631112007-12-16 17:20:38 +0000187 /*
188 * Sigmode records the current value of the signal handlers for the various
189 * modes. A value of zero means that the current handler is not known.
Denis Vlasenkof8535cc2008-12-03 10:36:26 +0000190 * S_HARD_IGN indicates that the signal was ignored on entry to the shell.
Denis Vlasenko01631112007-12-16 17:20:38 +0000191 */
192 char sigmode[NSIG - 1];
Denis Vlasenkof8535cc2008-12-03 10:36:26 +0000193#define S_DFL 1 /* default signal handling (SIG_DFL) */
194#define S_CATCH 2 /* signal is caught */
195#define S_IGN 3 /* signal is ignored (SIG_IGN) */
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +0000196#define S_HARD_IGN 4 /* signal is ignored permenantly */
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +0000197
Denis Vlasenko01631112007-12-16 17:20:38 +0000198 /* indicates specified signal received */
Denis Vlasenko4b875702009-03-19 13:30:04 +0000199 uint8_t gotsig[NSIG - 1]; /* offset by 1: "signal" 0 is meaningless */
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000200 char *trap[NSIG];
Denys Vlasenko21d87d42009-09-25 00:06:51 +0200201 char **trap_ptr; /* used only by "trap hack" */
Denis Vlasenko448d30e2008-06-27 00:24:11 +0000202
203 /* Rarely referenced stuff */
204#if ENABLE_ASH_RANDOM_SUPPORT
Denys Vlasenko3ea2e822009-10-09 20:59:04 +0200205 random_t random_gen;
Denis Vlasenko448d30e2008-06-27 00:24:11 +0000206#endif
207 pid_t backgndpid; /* pid of last background process */
208 smallint job_warning; /* user was warned about stopped jobs (can be 2, 1 or 0). */
Denis Vlasenko01631112007-12-16 17:20:38 +0000209};
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000210extern struct globals_misc *const ash_ptr_to_globals_misc;
211#define G_misc (*ash_ptr_to_globals_misc)
Denis Vlasenko26bc57d2008-06-27 00:29:34 +0000212#define rootpid (G_misc.rootpid )
213#define shlvl (G_misc.shlvl )
214#define minusc (G_misc.minusc )
215#define curdir (G_misc.curdir )
216#define physdir (G_misc.physdir )
217#define arg0 (G_misc.arg0 )
Denis Vlasenko01631112007-12-16 17:20:38 +0000218#define exception_handler (G_misc.exception_handler)
Denis Vlasenko7f88e342009-03-19 03:36:18 +0000219#define exception_type (G_misc.exception_type )
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200220#define suppress_int (G_misc.suppress_int )
221#define pending_int (G_misc.pending_int )
222#define pending_sig (G_misc.pending_sig )
Denis Vlasenko26bc57d2008-06-27 00:29:34 +0000223#define isloginsh (G_misc.isloginsh )
224#define nullstr (G_misc.nullstr )
225#define optlist (G_misc.optlist )
226#define sigmode (G_misc.sigmode )
227#define gotsig (G_misc.gotsig )
228#define trap (G_misc.trap )
Denys Vlasenko21d87d42009-09-25 00:06:51 +0200229#define trap_ptr (G_misc.trap_ptr )
Denys Vlasenko3ea2e822009-10-09 20:59:04 +0200230#define random_gen (G_misc.random_gen )
Denis Vlasenko448d30e2008-06-27 00:24:11 +0000231#define backgndpid (G_misc.backgndpid )
232#define job_warning (G_misc.job_warning)
Denis Vlasenko01631112007-12-16 17:20:38 +0000233#define INIT_G_misc() do { \
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000234 (*(struct globals_misc**)&ash_ptr_to_globals_misc) = xzalloc(sizeof(G_misc)); \
235 barrier(); \
Denis Vlasenko01631112007-12-16 17:20:38 +0000236 curdir = nullstr; \
237 physdir = nullstr; \
Denys Vlasenko21d87d42009-09-25 00:06:51 +0200238 trap_ptr = trap; \
Denis Vlasenko01631112007-12-16 17:20:38 +0000239} while (0)
240
241
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000242/* ============ DEBUG */
243#if DEBUG
244static void trace_printf(const char *fmt, ...);
245static void trace_vprintf(const char *fmt, va_list va);
246# define TRACE(param) trace_printf param
247# define TRACEV(param) trace_vprintf param
Denis Vlasenko1bb3d7e2009-03-20 07:45:36 +0000248# define close(fd) do { \
249 int dfd = (fd); \
Denis Vlasenkob9e70dd2009-03-20 01:24:08 +0000250 if (close(dfd) < 0) \
Denys Vlasenko883cea42009-07-11 15:31:59 +0200251 bb_error_msg("bug on %d: closing %d(0x%x)", \
Denis Vlasenko1bb3d7e2009-03-20 07:45:36 +0000252 __LINE__, dfd, dfd); \
Denis Vlasenkob9e70dd2009-03-20 01:24:08 +0000253} while (0)
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000254#else
255# define TRACE(param)
256# define TRACEV(param)
257#endif
258
259
Denis Vlasenko559691a2008-10-05 18:39:31 +0000260/* ============ Utility functions */
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000261#define xbarrier() do { __asm__ __volatile__ ("": : :"memory"); } while (0)
262
Denis Vlasenko559691a2008-10-05 18:39:31 +0000263static int isdigit_str9(const char *str)
264{
265 int maxlen = 9 + 1; /* max 9 digits: 999999999 */
266 while (--maxlen && isdigit(*str))
267 str++;
268 return (*str == '\0');
269}
Denis Vlasenko01631112007-12-16 17:20:38 +0000270
Denis Vlasenko559691a2008-10-05 18:39:31 +0000271
272/* ============ Interrupts / exceptions */
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +0000273/*
Eric Andersen2870d962001-07-02 17:27:21 +0000274 * These macros allow the user to suspend the handling of interrupt signals
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +0000275 * over a period of time. This is similar to SIGHOLD or to sigblock, but
Eric Andersen2870d962001-07-02 17:27:21 +0000276 * much more efficient and portable. (But hacking the kernel is so much
277 * more fun than worrying about efficiency and portability. :-))
278 */
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000279#define INT_OFF do { \
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200280 suppress_int++; \
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000281 xbarrier(); \
282} while (0)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000283
284/*
285 * Called to raise an exception. Since C doesn't include exceptions, we
286 * just do a longjmp to the exception handler. The type of exception is
Denis Vlasenko4b875702009-03-19 13:30:04 +0000287 * stored in the global variable "exception_type".
Denis Vlasenkob012b102007-02-19 22:43:01 +0000288 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +0000289static void raise_exception(int) NORETURN;
Denis Vlasenkob012b102007-02-19 22:43:01 +0000290static void
291raise_exception(int e)
292{
293#if DEBUG
Denis Vlasenko2da584f2007-02-19 22:44:05 +0000294 if (exception_handler == NULL)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000295 abort();
296#endif
297 INT_OFF;
Denis Vlasenko7f88e342009-03-19 03:36:18 +0000298 exception_type = e;
Denis Vlasenko2da584f2007-02-19 22:44:05 +0000299 longjmp(exception_handler->loc, 1);
Denis Vlasenkob012b102007-02-19 22:43:01 +0000300}
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000301#if DEBUG
302#define raise_exception(e) do { \
303 TRACE(("raising exception %d on line %d\n", (e), __LINE__)); \
304 raise_exception(e); \
305} while (0)
306#endif
Denis Vlasenkob012b102007-02-19 22:43:01 +0000307
308/*
309 * Called from trap.c when a SIGINT is received. (If the user specifies
310 * that SIGINT is to be trapped or ignored using the trap builtin, then
311 * this routine is not called.) Suppressint is nonzero when interrupts
312 * are held using the INT_OFF macro. (The test for iflag is just
313 * defensive programming.)
314 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +0000315static void raise_interrupt(void) NORETURN;
Denis Vlasenkob012b102007-02-19 22:43:01 +0000316static void
317raise_interrupt(void)
318{
Denis Vlasenko4b875702009-03-19 13:30:04 +0000319 int ex_type;
Denis Vlasenkob012b102007-02-19 22:43:01 +0000320
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200321 pending_int = 0;
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +0000322 /* Signal is not automatically unmasked after it is raised,
323 * do it ourself - unmask all signals */
Denis Vlasenko3f165fa2008-03-17 08:29:08 +0000324 sigprocmask_allsigs(SIG_UNBLOCK);
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200325 /* pending_sig = 0; - now done in onsig() */
Denis Vlasenko7c139b42007-03-21 20:17:27 +0000326
Denis Vlasenko4b875702009-03-19 13:30:04 +0000327 ex_type = EXSIG;
Denis Vlasenkob012b102007-02-19 22:43:01 +0000328 if (gotsig[SIGINT - 1] && !trap[SIGINT]) {
329 if (!(rootshell && iflag)) {
Denis Vlasenko991a1da2008-02-10 19:02:53 +0000330 /* Kill ourself with SIGINT */
Denis Vlasenkob012b102007-02-19 22:43:01 +0000331 signal(SIGINT, SIG_DFL);
332 raise(SIGINT);
333 }
Denis Vlasenko4b875702009-03-19 13:30:04 +0000334 ex_type = EXINT;
Denis Vlasenkob012b102007-02-19 22:43:01 +0000335 }
Denis Vlasenko4b875702009-03-19 13:30:04 +0000336 raise_exception(ex_type);
Denis Vlasenkob012b102007-02-19 22:43:01 +0000337 /* NOTREACHED */
338}
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000339#if DEBUG
340#define raise_interrupt() do { \
341 TRACE(("raising interrupt on line %d\n", __LINE__)); \
342 raise_interrupt(); \
343} while (0)
344#endif
Denis Vlasenkob012b102007-02-19 22:43:01 +0000345
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000346static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000347int_on(void)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000348{
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +0000349 xbarrier();
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200350 if (--suppress_int == 0 && pending_int) {
Denis Vlasenkob012b102007-02-19 22:43:01 +0000351 raise_interrupt();
352 }
353}
354#define INT_ON int_on()
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000355static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000356force_int_on(void)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000357{
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +0000358 xbarrier();
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200359 suppress_int = 0;
360 if (pending_int)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000361 raise_interrupt();
362}
363#define FORCE_INT_ON force_int_on()
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000364
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200365#define SAVE_INT(v) ((v) = suppress_int)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000366
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000367#define RESTORE_INT(v) do { \
368 xbarrier(); \
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200369 suppress_int = (v); \
370 if (suppress_int == 0 && pending_int) \
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000371 raise_interrupt(); \
372} while (0)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000373
Glenn L McGrath9fef17d2002-08-22 18:41:20 +0000374
Denis Vlasenkobc54cff2007-02-23 01:05:52 +0000375/* ============ Stdout/stderr output */
Eric Andersenc470f442003-07-28 09:56:35 +0000376
Eric Andersenc470f442003-07-28 09:56:35 +0000377static void
Denis Vlasenkob012b102007-02-19 22:43:01 +0000378outstr(const char *p, FILE *file)
Denis Vlasenkoe5570da2007-02-19 22:41:55 +0000379{
Denis Vlasenkob012b102007-02-19 22:43:01 +0000380 INT_OFF;
381 fputs(p, file);
382 INT_ON;
383}
384
385static void
386flush_stdout_stderr(void)
387{
388 INT_OFF;
Denys Vlasenko8131eea2009-11-02 14:19:51 +0100389 fflush_all();
Denis Vlasenkob012b102007-02-19 22:43:01 +0000390 INT_ON;
391}
392
393static void
394outcslow(int c, FILE *dest)
395{
396 INT_OFF;
397 putc(c, dest);
398 fflush(dest);
399 INT_ON;
400}
401
402static int out1fmt(const char *, ...) __attribute__((__format__(__printf__,1,2)));
403static int
404out1fmt(const char *fmt, ...)
405{
406 va_list ap;
407 int r;
408
409 INT_OFF;
410 va_start(ap, fmt);
411 r = vprintf(fmt, ap);
412 va_end(ap);
413 INT_ON;
414 return r;
415}
416
417static int fmtstr(char *, size_t, const char *, ...) __attribute__((__format__(__printf__,3,4)));
418static int
419fmtstr(char *outbuf, size_t length, const char *fmt, ...)
420{
421 va_list ap;
422 int ret;
423
424 va_start(ap, fmt);
425 INT_OFF;
426 ret = vsnprintf(outbuf, length, fmt, ap);
427 va_end(ap);
428 INT_ON;
429 return ret;
430}
431
432static void
433out1str(const char *p)
434{
435 outstr(p, stdout);
436}
437
438static void
439out2str(const char *p)
440{
441 outstr(p, stderr);
Denys Vlasenko8131eea2009-11-02 14:19:51 +0100442 flush_stdout_stderr();
Denis Vlasenkob012b102007-02-19 22:43:01 +0000443}
444
445
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +0000446/* ============ Parser structures */
Denis Vlasenko4d2183b2007-02-23 01:05:38 +0000447
Denis Vlasenko5651bfc2007-02-23 21:08:58 +0000448/* control characters in argument strings */
Denys Vlasenko2ce42e92009-11-29 02:18:13 +0100449#define CTL_FIRST CTLESC
Denys Vlasenkob6c84342009-08-29 20:23:20 +0200450#define CTLESC ((unsigned char)'\201') /* escape next character */
451#define CTLVAR ((unsigned char)'\202') /* variable defn */
452#define CTLENDVAR ((unsigned char)'\203')
453#define CTLBACKQ ((unsigned char)'\204')
Denis Vlasenko5651bfc2007-02-23 21:08:58 +0000454#define CTLQUOTE 01 /* ored with CTLBACKQ code if in quotes */
455/* CTLBACKQ | CTLQUOTE == '\205' */
Denys Vlasenkob6c84342009-08-29 20:23:20 +0200456#define CTLARI ((unsigned char)'\206') /* arithmetic expression */
457#define CTLENDARI ((unsigned char)'\207')
458#define CTLQUOTEMARK ((unsigned char)'\210')
Denys Vlasenko2ce42e92009-11-29 02:18:13 +0100459#define CTL_LAST CTLQUOTEMARK
Denis Vlasenko5651bfc2007-02-23 21:08:58 +0000460
461/* variable substitution byte (follows CTLVAR) */
462#define VSTYPE 0x0f /* type of variable substitution */
463#define VSNUL 0x10 /* colon--treat the empty string as unset */
464#define VSQUOTE 0x80 /* inside double quotes--suppress splitting */
465
466/* values of VSTYPE field */
Denis Vlasenko92e13c22008-03-25 01:17:40 +0000467#define VSNORMAL 0x1 /* normal variable: $var or ${var} */
468#define VSMINUS 0x2 /* ${var-text} */
469#define VSPLUS 0x3 /* ${var+text} */
470#define VSQUESTION 0x4 /* ${var?message} */
471#define VSASSIGN 0x5 /* ${var=text} */
472#define VSTRIMRIGHT 0x6 /* ${var%pattern} */
473#define VSTRIMRIGHTMAX 0x7 /* ${var%%pattern} */
474#define VSTRIMLEFT 0x8 /* ${var#pattern} */
475#define VSTRIMLEFTMAX 0x9 /* ${var##pattern} */
476#define VSLENGTH 0xa /* ${#var} */
477#if ENABLE_ASH_BASH_COMPAT
478#define VSSUBSTR 0xc /* ${var:position:length} */
479#define VSREPLACE 0xd /* ${var/pattern/replacement} */
480#define VSREPLACEALL 0xe /* ${var//pattern/replacement} */
481#endif
Denis Vlasenko5651bfc2007-02-23 21:08:58 +0000482
Denis Vlasenko6ca409e2007-08-12 20:58:27 +0000483static const char dolatstr[] ALIGN1 = {
484 CTLVAR, VSNORMAL|VSQUOTE, '@', '=', '\0'
485};
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +0000486
Denis Vlasenko559691a2008-10-05 18:39:31 +0000487#define NCMD 0
488#define NPIPE 1
489#define NREDIR 2
490#define NBACKGND 3
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000491#define NSUBSHELL 4
Denis Vlasenko559691a2008-10-05 18:39:31 +0000492#define NAND 5
493#define NOR 6
494#define NSEMI 7
495#define NIF 8
496#define NWHILE 9
497#define NUNTIL 10
498#define NFOR 11
499#define NCASE 12
500#define NCLIST 13
501#define NDEFUN 14
502#define NARG 15
503#define NTO 16
504#if ENABLE_ASH_BASH_COMPAT
505#define NTO2 17
506#endif
507#define NCLOBBER 18
508#define NFROM 19
509#define NFROMTO 20
510#define NAPPEND 21
511#define NTOFD 22
512#define NFROMFD 23
513#define NHERE 24
514#define NXHERE 25
515#define NNOT 26
Denis Vlasenko340299a2008-11-21 10:36:36 +0000516#define N_NUMBER 27
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000517
518union node;
519
520struct ncmd {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000521 smallint type; /* Nxxxx */
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000522 union node *assign;
523 union node *args;
524 union node *redirect;
525};
526
527struct npipe {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000528 smallint type;
529 smallint pipe_backgnd;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000530 struct nodelist *cmdlist;
531};
532
533struct nredir {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000534 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000535 union node *n;
536 union node *redirect;
537};
538
539struct nbinary {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000540 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000541 union node *ch1;
542 union node *ch2;
543};
544
545struct nif {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000546 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000547 union node *test;
548 union node *ifpart;
549 union node *elsepart;
550};
551
552struct nfor {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000553 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000554 union node *args;
555 union node *body;
556 char *var;
557};
558
559struct ncase {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000560 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000561 union node *expr;
562 union node *cases;
563};
564
565struct nclist {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000566 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000567 union node *next;
568 union node *pattern;
569 union node *body;
570};
571
572struct narg {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000573 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000574 union node *next;
575 char *text;
576 struct nodelist *backquote;
577};
578
Denis Vlasenko559691a2008-10-05 18:39:31 +0000579/* nfile and ndup layout must match!
580 * NTOFD (>&fdnum) uses ndup structure, but we may discover mid-flight
581 * that it is actually NTO2 (>&file), and change its type.
582 */
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000583struct nfile {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000584 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000585 union node *next;
586 int fd;
Denis Vlasenko559691a2008-10-05 18:39:31 +0000587 int _unused_dupfd;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000588 union node *fname;
589 char *expfname;
590};
591
592struct ndup {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000593 smallint type;
Denis Vlasenko559691a2008-10-05 18:39:31 +0000594 union node *next;
595 int fd;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000596 int dupfd;
597 union node *vname;
Denis Vlasenko559691a2008-10-05 18:39:31 +0000598 char *_unused_expfname;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000599};
600
601struct nhere {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000602 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000603 union node *next;
604 int fd;
605 union node *doc;
606};
607
608struct nnot {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000609 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000610 union node *com;
611};
612
613union node {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000614 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000615 struct ncmd ncmd;
616 struct npipe npipe;
617 struct nredir nredir;
618 struct nbinary nbinary;
619 struct nif nif;
620 struct nfor nfor;
621 struct ncase ncase;
622 struct nclist nclist;
623 struct narg narg;
624 struct nfile nfile;
625 struct ndup ndup;
626 struct nhere nhere;
627 struct nnot nnot;
628};
629
Denys Vlasenko86e83ec2009-07-23 22:07:07 +0200630/*
631 * NODE_EOF is returned by parsecmd when it encounters an end of file.
632 * It must be distinct from NULL.
633 */
634#define NODE_EOF ((union node *) -1L)
635
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000636struct nodelist {
637 struct nodelist *next;
638 union node *n;
639};
640
641struct funcnode {
642 int count;
643 union node n;
644};
645
Denis Vlasenko5651bfc2007-02-23 21:08:58 +0000646/*
647 * Free a parse tree.
648 */
649static void
650freefunc(struct funcnode *f)
651{
652 if (f && --f->count < 0)
653 free(f);
654}
655
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000656
657/* ============ Debugging output */
658
659#if DEBUG
660
661static FILE *tracefile;
662
663static void
664trace_printf(const char *fmt, ...)
665{
666 va_list va;
667
668 if (debug != 1)
669 return;
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000670 if (DEBUG_TIME)
671 fprintf(tracefile, "%u ", (int) time(NULL));
672 if (DEBUG_PID)
673 fprintf(tracefile, "[%u] ", (int) getpid());
674 if (DEBUG_SIG)
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200675 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000676 va_start(va, fmt);
677 vfprintf(tracefile, fmt, va);
678 va_end(va);
679}
680
681static void
682trace_vprintf(const char *fmt, va_list va)
683{
684 if (debug != 1)
685 return;
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000686 if (DEBUG_TIME)
687 fprintf(tracefile, "%u ", (int) time(NULL));
688 if (DEBUG_PID)
689 fprintf(tracefile, "[%u] ", (int) getpid());
690 if (DEBUG_SIG)
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200691 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000692 vfprintf(tracefile, fmt, va);
693}
694
695static void
696trace_puts(const char *s)
697{
698 if (debug != 1)
699 return;
700 fputs(s, tracefile);
701}
702
703static void
704trace_puts_quoted(char *s)
705{
706 char *p;
707 char c;
708
709 if (debug != 1)
710 return;
711 putc('"', tracefile);
712 for (p = s; *p; p++) {
Denys Vlasenkocd716832009-11-28 22:14:02 +0100713 switch ((unsigned char)*p) {
714 case '\n': c = 'n'; goto backslash;
715 case '\t': c = 't'; goto backslash;
716 case '\r': c = 'r'; goto backslash;
717 case '\"': c = '\"'; goto backslash;
718 case '\\': c = '\\'; goto backslash;
719 case CTLESC: c = 'e'; goto backslash;
720 case CTLVAR: c = 'v'; goto backslash;
721 case CTLVAR+CTLQUOTE: c = 'V'; goto backslash;
722 case CTLBACKQ: c = 'q'; goto backslash;
723 case CTLBACKQ+CTLQUOTE: c = 'Q'; goto backslash;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000724 backslash:
725 putc('\\', tracefile);
726 putc(c, tracefile);
727 break;
728 default:
729 if (*p >= ' ' && *p <= '~')
730 putc(*p, tracefile);
731 else {
732 putc('\\', tracefile);
Denys Vlasenkocd716832009-11-28 22:14:02 +0100733 putc((*p >> 6) & 03, tracefile);
734 putc((*p >> 3) & 07, tracefile);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000735 putc(*p & 07, tracefile);
736 }
737 break;
738 }
739 }
740 putc('"', tracefile);
741}
742
743static void
744trace_puts_args(char **ap)
745{
746 if (debug != 1)
747 return;
748 if (!*ap)
749 return;
750 while (1) {
751 trace_puts_quoted(*ap);
752 if (!*++ap) {
753 putc('\n', tracefile);
754 break;
755 }
756 putc(' ', tracefile);
757 }
758}
759
760static void
761opentrace(void)
762{
763 char s[100];
764#ifdef O_APPEND
765 int flags;
766#endif
767
768 if (debug != 1) {
769 if (tracefile)
770 fflush(tracefile);
771 /* leave open because libedit might be using it */
772 return;
773 }
774 strcpy(s, "./trace");
775 if (tracefile) {
776 if (!freopen(s, "a", tracefile)) {
777 fprintf(stderr, "Can't re-open %s\n", s);
778 debug = 0;
779 return;
780 }
781 } else {
782 tracefile = fopen(s, "a");
783 if (tracefile == NULL) {
784 fprintf(stderr, "Can't open %s\n", s);
785 debug = 0;
786 return;
787 }
788 }
789#ifdef O_APPEND
Denis Vlasenkod37f2222007-08-19 13:42:08 +0000790 flags = fcntl(fileno(tracefile), F_GETFL);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000791 if (flags >= 0)
792 fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
793#endif
794 setlinebuf(tracefile);
795 fputs("\nTracing started.\n", tracefile);
796}
797
798static void
799indent(int amount, char *pfx, FILE *fp)
800{
801 int i;
802
803 for (i = 0; i < amount; i++) {
804 if (pfx && i == amount - 1)
805 fputs(pfx, fp);
806 putc('\t', fp);
807 }
808}
809
810/* little circular references here... */
811static void shtree(union node *n, int ind, char *pfx, FILE *fp);
812
813static void
814sharg(union node *arg, FILE *fp)
815{
816 char *p;
817 struct nodelist *bqlist;
Denys Vlasenkocd716832009-11-28 22:14:02 +0100818 unsigned char subtype;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000819
820 if (arg->type != NARG) {
821 out1fmt("<node type %d>\n", arg->type);
822 abort();
823 }
824 bqlist = arg->narg.backquote;
825 for (p = arg->narg.text; *p; p++) {
Denys Vlasenkocd716832009-11-28 22:14:02 +0100826 switch ((unsigned char)*p) {
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000827 case CTLESC:
828 putc(*++p, fp);
829 break;
830 case CTLVAR:
831 putc('$', fp);
832 putc('{', fp);
833 subtype = *++p;
834 if (subtype == VSLENGTH)
835 putc('#', fp);
836
837 while (*p != '=')
838 putc(*p++, fp);
839
840 if (subtype & VSNUL)
841 putc(':', fp);
842
843 switch (subtype & VSTYPE) {
844 case VSNORMAL:
845 putc('}', fp);
846 break;
847 case VSMINUS:
848 putc('-', fp);
849 break;
850 case VSPLUS:
851 putc('+', fp);
852 break;
853 case VSQUESTION:
854 putc('?', fp);
855 break;
856 case VSASSIGN:
857 putc('=', fp);
858 break;
859 case VSTRIMLEFT:
860 putc('#', fp);
861 break;
862 case VSTRIMLEFTMAX:
863 putc('#', fp);
864 putc('#', fp);
865 break;
866 case VSTRIMRIGHT:
867 putc('%', fp);
868 break;
869 case VSTRIMRIGHTMAX:
870 putc('%', fp);
871 putc('%', fp);
872 break;
873 case VSLENGTH:
874 break;
875 default:
876 out1fmt("<subtype %d>", subtype);
877 }
878 break;
879 case CTLENDVAR:
880 putc('}', fp);
881 break;
882 case CTLBACKQ:
883 case CTLBACKQ|CTLQUOTE:
884 putc('$', fp);
885 putc('(', fp);
886 shtree(bqlist->n, -1, NULL, fp);
887 putc(')', fp);
888 break;
889 default:
890 putc(*p, fp);
891 break;
892 }
893 }
894}
895
Denys Vlasenko641dd7b2009-06-11 19:30:19 +0200896static void
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000897shcmd(union node *cmd, FILE *fp)
898{
899 union node *np;
900 int first;
901 const char *s;
902 int dftfd;
903
904 first = 1;
905 for (np = cmd->ncmd.args; np; np = np->narg.next) {
Denis Vlasenko40ba9982007-07-14 00:48:29 +0000906 if (!first)
907 putc(' ', fp);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000908 sharg(np, fp);
909 first = 0;
910 }
911 for (np = cmd->ncmd.redirect; np; np = np->nfile.next) {
Denis Vlasenko40ba9982007-07-14 00:48:29 +0000912 if (!first)
913 putc(' ', fp);
914 dftfd = 0;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000915 switch (np->nfile.type) {
Denis Vlasenko40ba9982007-07-14 00:48:29 +0000916 case NTO: s = ">>"+1; dftfd = 1; break;
917 case NCLOBBER: s = ">|"; dftfd = 1; break;
918 case NAPPEND: s = ">>"; dftfd = 1; break;
Denis Vlasenko559691a2008-10-05 18:39:31 +0000919#if ENABLE_ASH_BASH_COMPAT
920 case NTO2:
921#endif
Denis Vlasenko40ba9982007-07-14 00:48:29 +0000922 case NTOFD: s = ">&"; dftfd = 1; break;
Denis Vlasenko559691a2008-10-05 18:39:31 +0000923 case NFROM: s = "<"; break;
Denis Vlasenko40ba9982007-07-14 00:48:29 +0000924 case NFROMFD: s = "<&"; break;
925 case NFROMTO: s = "<>"; break;
926 default: s = "*error*"; break;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000927 }
928 if (np->nfile.fd != dftfd)
929 fprintf(fp, "%d", np->nfile.fd);
930 fputs(s, fp);
931 if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
932 fprintf(fp, "%d", np->ndup.dupfd);
933 } else {
934 sharg(np->nfile.fname, fp);
935 }
936 first = 0;
937 }
938}
939
940static void
941shtree(union node *n, int ind, char *pfx, FILE *fp)
942{
943 struct nodelist *lp;
944 const char *s;
945
946 if (n == NULL)
947 return;
948
949 indent(ind, pfx, fp);
Denys Vlasenko86e83ec2009-07-23 22:07:07 +0200950
951 if (n == NODE_EOF) {
952 fputs("<EOF>", fp);
953 return;
954 }
955
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000956 switch (n->type) {
957 case NSEMI:
958 s = "; ";
959 goto binop;
960 case NAND:
961 s = " && ";
962 goto binop;
963 case NOR:
964 s = " || ";
965 binop:
966 shtree(n->nbinary.ch1, ind, NULL, fp);
967 /* if (ind < 0) */
968 fputs(s, fp);
969 shtree(n->nbinary.ch2, ind, NULL, fp);
970 break;
971 case NCMD:
972 shcmd(n, fp);
973 if (ind >= 0)
974 putc('\n', fp);
975 break;
976 case NPIPE:
977 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
Denys Vlasenko7cee00e2009-07-24 01:08:03 +0200978 shtree(lp->n, 0, NULL, fp);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000979 if (lp->next)
980 fputs(" | ", fp);
981 }
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000982 if (n->npipe.pipe_backgnd)
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000983 fputs(" &", fp);
984 if (ind >= 0)
985 putc('\n', fp);
986 break;
987 default:
988 fprintf(fp, "<node type %d>", n->type);
989 if (ind >= 0)
990 putc('\n', fp);
991 break;
992 }
993}
994
995static void
996showtree(union node *n)
997{
998 trace_puts("showtree called\n");
Denys Vlasenko883cea42009-07-11 15:31:59 +0200999 shtree(n, 1, NULL, stderr);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00001000}
1001
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00001002#endif /* DEBUG */
1003
1004
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00001005/* ============ Parser data */
1006
1007/*
Denis Vlasenkob012b102007-02-19 22:43:01 +00001008 * ash_vmsg() needs parsefile->fd, hence parsefile definition is moved up.
1009 */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001010struct strlist {
1011 struct strlist *next;
1012 char *text;
1013};
1014
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00001015struct alias;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00001016
Denis Vlasenkob012b102007-02-19 22:43:01 +00001017struct strpush {
1018 struct strpush *prev; /* preceding string on stack */
Denis Vlasenko41eb3002008-11-28 03:42:31 +00001019 char *prev_string;
1020 int prev_left_in_line;
Denis Vlasenkob012b102007-02-19 22:43:01 +00001021#if ENABLE_ASH_ALIAS
1022 struct alias *ap; /* if push was associated with an alias */
1023#endif
1024 char *string; /* remember the string since it may change */
1025};
1026
1027struct parsefile {
1028 struct parsefile *prev; /* preceding file on stack */
1029 int linno; /* current line */
1030 int fd; /* file descriptor (or -1 if string) */
Denis Vlasenko41eb3002008-11-28 03:42:31 +00001031 int left_in_line; /* number of chars left in this line */
1032 int left_in_buffer; /* number of chars left in this buffer past the line */
1033 char *next_to_pgetc; /* next char in buffer */
Denis Vlasenkob012b102007-02-19 22:43:01 +00001034 char *buf; /* input buffer */
1035 struct strpush *strpush; /* for pushing strings at this level */
1036 struct strpush basestrpush; /* so pushing one is fast */
1037};
1038
Denis Vlasenko448d30e2008-06-27 00:24:11 +00001039static struct parsefile basepf; /* top level input file */
Denis Vlasenkob07a4962008-06-22 13:16:23 +00001040static struct parsefile *g_parsefile = &basepf; /* current input file */
Denis Vlasenkob012b102007-02-19 22:43:01 +00001041static int startlinno; /* line # where last token started */
1042static char *commandname; /* currently executing command */
1043static struct strlist *cmdenviron; /* environment for builtin command */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00001044static uint8_t exitstatus; /* exit status of last command */
Denis Vlasenkob012b102007-02-19 22:43:01 +00001045
1046
1047/* ============ Message printing */
1048
1049static void
1050ash_vmsg(const char *msg, va_list ap)
1051{
1052 fprintf(stderr, "%s: ", arg0);
1053 if (commandname) {
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00001054 if (strcmp(arg0, commandname))
1055 fprintf(stderr, "%s: ", commandname);
Denis Vlasenkob07a4962008-06-22 13:16:23 +00001056 if (!iflag || g_parsefile->fd)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00001057 fprintf(stderr, "line %d: ", startlinno);
Eric Andersenc470f442003-07-28 09:56:35 +00001058 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00001059 vfprintf(stderr, msg, ap);
1060 outcslow('\n', stderr);
Eric Andersenc470f442003-07-28 09:56:35 +00001061}
Denis Vlasenkob012b102007-02-19 22:43:01 +00001062
1063/*
1064 * Exverror is called to raise the error exception. If the second argument
1065 * is not NULL then error prints an error message using printf style
1066 * formatting. It then raises the error exception.
1067 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001068static void ash_vmsg_and_raise(int, const char *, va_list) NORETURN;
Denis Vlasenkob012b102007-02-19 22:43:01 +00001069static void
1070ash_vmsg_and_raise(int cond, const char *msg, va_list ap)
Eric Andersenc470f442003-07-28 09:56:35 +00001071{
Denis Vlasenkob012b102007-02-19 22:43:01 +00001072#if DEBUG
1073 if (msg) {
1074 TRACE(("ash_vmsg_and_raise(%d, \"", cond));
1075 TRACEV((msg, ap));
1076 TRACE(("\") pid=%d\n", getpid()));
1077 } else
1078 TRACE(("ash_vmsg_and_raise(%d, NULL) pid=%d\n", cond, getpid()));
1079 if (msg)
1080#endif
1081 ash_vmsg(msg, ap);
1082
1083 flush_stdout_stderr();
1084 raise_exception(cond);
1085 /* NOTREACHED */
Eric Andersenc470f442003-07-28 09:56:35 +00001086}
Denis Vlasenkob012b102007-02-19 22:43:01 +00001087
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001088static void ash_msg_and_raise_error(const char *, ...) NORETURN;
Denis Vlasenkob012b102007-02-19 22:43:01 +00001089static void
1090ash_msg_and_raise_error(const char *msg, ...)
1091{
1092 va_list ap;
1093
1094 va_start(ap, msg);
1095 ash_vmsg_and_raise(EXERROR, msg, ap);
1096 /* NOTREACHED */
1097 va_end(ap);
1098}
1099
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00001100static void raise_error_syntax(const char *) NORETURN;
1101static void
1102raise_error_syntax(const char *msg)
1103{
1104 ash_msg_and_raise_error("syntax error: %s", msg);
1105 /* NOTREACHED */
1106}
1107
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001108static void ash_msg_and_raise(int, const char *, ...) NORETURN;
Denis Vlasenkob012b102007-02-19 22:43:01 +00001109static void
1110ash_msg_and_raise(int cond, const char *msg, ...)
1111{
1112 va_list ap;
1113
1114 va_start(ap, msg);
1115 ash_vmsg_and_raise(cond, msg, ap);
1116 /* NOTREACHED */
1117 va_end(ap);
1118}
1119
1120/*
1121 * error/warning routines for external builtins
1122 */
1123static void
1124ash_msg(const char *fmt, ...)
1125{
1126 va_list ap;
1127
1128 va_start(ap, fmt);
1129 ash_vmsg(fmt, ap);
1130 va_end(ap);
1131}
1132
1133/*
1134 * Return a string describing an error. The returned string may be a
1135 * pointer to a static buffer that will be overwritten on the next call.
1136 * Action describes the operation that got the error.
1137 */
1138static const char *
1139errmsg(int e, const char *em)
1140{
1141 if (e == ENOENT || e == ENOTDIR) {
1142 return em;
1143 }
1144 return strerror(e);
1145}
1146
1147
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001148/* ============ Memory allocation */
1149
Denys Vlasenkoe7670ff2009-10-11 00:45:25 +02001150#if 0
1151/* I consider these wrappers nearly useless:
1152 * ok, they return you to nearest exception handler, but
1153 * how much memory do you leak in the process, making
1154 * memory starvation worse?
1155 */
1156static void *
1157ckrealloc(void * p, size_t nbytes)
1158{
1159 p = realloc(p, nbytes);
1160 if (!p)
1161 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1162 return p;
1163}
1164
1165static void *
1166ckmalloc(size_t nbytes)
1167{
1168 return ckrealloc(NULL, nbytes);
1169}
1170
1171static void *
1172ckzalloc(size_t nbytes)
1173{
1174 return memset(ckmalloc(nbytes), 0, nbytes);
1175}
1176
1177static char *
1178ckstrdup(const char *s)
1179{
1180 char *p = strdup(s);
1181 if (!p)
1182 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1183 return p;
1184}
1185#else
1186/* Using bbox equivalents. They exit if out of memory */
1187# define ckrealloc xrealloc
1188# define ckmalloc xmalloc
1189# define ckzalloc xzalloc
1190# define ckstrdup xstrdup
1191#endif
1192
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001193/*
1194 * It appears that grabstackstr() will barf with such alignments
1195 * because stalloc() will return a string allocated in a new stackblock.
1196 */
1197#define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
1198enum {
1199 /* Most machines require the value returned from malloc to be aligned
1200 * in some way. The following macro will get this right
1201 * on many machines. */
Denys Vlasenko0e5e4ea2009-10-11 00:36:20 +02001202 SHELL_SIZE = sizeof(union { int i; char *cp; double d; }) - 1,
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001203 /* Minimum size of a block */
Denis Vlasenko01631112007-12-16 17:20:38 +00001204 MINSIZE = SHELL_ALIGN(504),
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001205};
1206
1207struct stack_block {
1208 struct stack_block *prev;
1209 char space[MINSIZE];
1210};
1211
1212struct stackmark {
1213 struct stack_block *stackp;
1214 char *stacknxt;
1215 size_t stacknleft;
1216 struct stackmark *marknext;
1217};
1218
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001219
Denis Vlasenko01631112007-12-16 17:20:38 +00001220struct globals_memstack {
1221 struct stack_block *g_stackp; // = &stackbase;
1222 struct stackmark *markp;
1223 char *g_stacknxt; // = stackbase.space;
1224 char *sstrend; // = stackbase.space + MINSIZE;
1225 size_t g_stacknleft; // = MINSIZE;
1226 int herefd; // = -1;
1227 struct stack_block stackbase;
1228};
Denis Vlasenko574f2f42008-02-27 18:41:59 +00001229extern struct globals_memstack *const ash_ptr_to_globals_memstack;
1230#define G_memstack (*ash_ptr_to_globals_memstack)
Denis Vlasenko01631112007-12-16 17:20:38 +00001231#define g_stackp (G_memstack.g_stackp )
1232#define markp (G_memstack.markp )
1233#define g_stacknxt (G_memstack.g_stacknxt )
1234#define sstrend (G_memstack.sstrend )
1235#define g_stacknleft (G_memstack.g_stacknleft)
1236#define herefd (G_memstack.herefd )
1237#define stackbase (G_memstack.stackbase )
1238#define INIT_G_memstack() do { \
Denis Vlasenko574f2f42008-02-27 18:41:59 +00001239 (*(struct globals_memstack**)&ash_ptr_to_globals_memstack) = xzalloc(sizeof(G_memstack)); \
1240 barrier(); \
Denis Vlasenko01631112007-12-16 17:20:38 +00001241 g_stackp = &stackbase; \
1242 g_stacknxt = stackbase.space; \
1243 g_stacknleft = MINSIZE; \
1244 sstrend = stackbase.space + MINSIZE; \
1245 herefd = -1; \
1246} while (0)
1247
Denys Vlasenkoe7670ff2009-10-11 00:45:25 +02001248
Denis Vlasenko01631112007-12-16 17:20:38 +00001249#define stackblock() ((void *)g_stacknxt)
1250#define stackblocksize() g_stacknleft
1251
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001252/*
1253 * Parse trees for commands are allocated in lifo order, so we use a stack
1254 * to make this more efficient, and also to avoid all sorts of exception
1255 * handling code to handle interrupts in the middle of a parse.
1256 *
1257 * The size 504 was chosen because the Ultrix malloc handles that size
1258 * well.
1259 */
1260static void *
1261stalloc(size_t nbytes)
1262{
1263 char *p;
1264 size_t aligned;
1265
1266 aligned = SHELL_ALIGN(nbytes);
Denis Vlasenko01631112007-12-16 17:20:38 +00001267 if (aligned > g_stacknleft) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001268 size_t len;
1269 size_t blocksize;
1270 struct stack_block *sp;
1271
1272 blocksize = aligned;
1273 if (blocksize < MINSIZE)
1274 blocksize = MINSIZE;
1275 len = sizeof(struct stack_block) - MINSIZE + blocksize;
1276 if (len < blocksize)
1277 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1278 INT_OFF;
1279 sp = ckmalloc(len);
Denis Vlasenko01631112007-12-16 17:20:38 +00001280 sp->prev = g_stackp;
1281 g_stacknxt = sp->space;
1282 g_stacknleft = blocksize;
1283 sstrend = g_stacknxt + blocksize;
1284 g_stackp = sp;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001285 INT_ON;
1286 }
Denis Vlasenko01631112007-12-16 17:20:38 +00001287 p = g_stacknxt;
1288 g_stacknxt += aligned;
1289 g_stacknleft -= aligned;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001290 return p;
1291}
1292
Denis Vlasenko597906c2008-02-20 16:38:54 +00001293static void *
1294stzalloc(size_t nbytes)
1295{
1296 return memset(stalloc(nbytes), 0, nbytes);
1297}
1298
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001299static void
1300stunalloc(void *p)
1301{
1302#if DEBUG
Denis Vlasenko01631112007-12-16 17:20:38 +00001303 if (!p || (g_stacknxt < (char *)p) || ((char *)p < g_stackp->space)) {
Bernhard Reutner-Fischer5e25ddb2008-05-19 09:48:17 +00001304 write(STDERR_FILENO, "stunalloc\n", 10);
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001305 abort();
1306 }
1307#endif
Denis Vlasenko01631112007-12-16 17:20:38 +00001308 g_stacknleft += g_stacknxt - (char *)p;
1309 g_stacknxt = p;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001310}
1311
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001312/*
1313 * Like strdup but works with the ash stack.
1314 */
1315static char *
1316ststrdup(const char *p)
1317{
1318 size_t len = strlen(p) + 1;
1319 return memcpy(stalloc(len), p, len);
1320}
1321
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001322static void
1323setstackmark(struct stackmark *mark)
1324{
Denis Vlasenko01631112007-12-16 17:20:38 +00001325 mark->stackp = g_stackp;
1326 mark->stacknxt = g_stacknxt;
1327 mark->stacknleft = g_stacknleft;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001328 mark->marknext = markp;
1329 markp = mark;
1330}
1331
1332static void
1333popstackmark(struct stackmark *mark)
1334{
1335 struct stack_block *sp;
1336
Denis Vlasenko93ebd4f2007-03-13 20:55:36 +00001337 if (!mark->stackp)
1338 return;
1339
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001340 INT_OFF;
1341 markp = mark->marknext;
Denis Vlasenko01631112007-12-16 17:20:38 +00001342 while (g_stackp != mark->stackp) {
1343 sp = g_stackp;
1344 g_stackp = sp->prev;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001345 free(sp);
1346 }
Denis Vlasenko01631112007-12-16 17:20:38 +00001347 g_stacknxt = mark->stacknxt;
1348 g_stacknleft = mark->stacknleft;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001349 sstrend = mark->stacknxt + mark->stacknleft;
1350 INT_ON;
1351}
1352
1353/*
1354 * When the parser reads in a string, it wants to stick the string on the
1355 * stack and only adjust the stack pointer when it knows how big the
1356 * string is. Stackblock (defined in stack.h) returns a pointer to a block
1357 * of space on top of the stack and stackblocklen returns the length of
1358 * this block. Growstackblock will grow this space by at least one byte,
1359 * possibly moving it (like realloc). Grabstackblock actually allocates the
1360 * part of the block that has been used.
1361 */
1362static void
1363growstackblock(void)
1364{
1365 size_t newlen;
1366
Denis Vlasenko01631112007-12-16 17:20:38 +00001367 newlen = g_stacknleft * 2;
1368 if (newlen < g_stacknleft)
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001369 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1370 if (newlen < 128)
1371 newlen += 128;
1372
Denis Vlasenko01631112007-12-16 17:20:38 +00001373 if (g_stacknxt == g_stackp->space && g_stackp != &stackbase) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001374 struct stack_block *oldstackp;
1375 struct stackmark *xmark;
1376 struct stack_block *sp;
1377 struct stack_block *prevstackp;
1378 size_t grosslen;
1379
1380 INT_OFF;
Denis Vlasenko01631112007-12-16 17:20:38 +00001381 oldstackp = g_stackp;
1382 sp = g_stackp;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001383 prevstackp = sp->prev;
1384 grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
1385 sp = ckrealloc(sp, grosslen);
1386 sp->prev = prevstackp;
Denis Vlasenko01631112007-12-16 17:20:38 +00001387 g_stackp = sp;
1388 g_stacknxt = sp->space;
1389 g_stacknleft = newlen;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001390 sstrend = sp->space + newlen;
1391
1392 /*
1393 * Stack marks pointing to the start of the old block
1394 * must be relocated to point to the new block
1395 */
1396 xmark = markp;
1397 while (xmark != NULL && xmark->stackp == oldstackp) {
Denis Vlasenko01631112007-12-16 17:20:38 +00001398 xmark->stackp = g_stackp;
1399 xmark->stacknxt = g_stacknxt;
1400 xmark->stacknleft = g_stacknleft;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001401 xmark = xmark->marknext;
1402 }
1403 INT_ON;
1404 } else {
Denis Vlasenko01631112007-12-16 17:20:38 +00001405 char *oldspace = g_stacknxt;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00001406 size_t oldlen = g_stacknleft;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001407 char *p = stalloc(newlen);
1408
1409 /* free the space we just allocated */
Denis Vlasenko01631112007-12-16 17:20:38 +00001410 g_stacknxt = memcpy(p, oldspace, oldlen);
1411 g_stacknleft += newlen;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001412 }
1413}
1414
1415static void
1416grabstackblock(size_t len)
1417{
1418 len = SHELL_ALIGN(len);
Denis Vlasenko01631112007-12-16 17:20:38 +00001419 g_stacknxt += len;
1420 g_stacknleft -= len;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001421}
1422
1423/*
1424 * The following routines are somewhat easier to use than the above.
1425 * The user declares a variable of type STACKSTR, which may be declared
1426 * to be a register. The macro STARTSTACKSTR initializes things. Then
1427 * the user uses the macro STPUTC to add characters to the string. In
1428 * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
1429 * grown as necessary. When the user is done, she can just leave the
1430 * string there and refer to it using stackblock(). Or she can allocate
1431 * the space for it using grabstackstr(). If it is necessary to allow
1432 * someone else to use the stack temporarily and then continue to grow
1433 * the string, the user should use grabstack to allocate the space, and
1434 * then call ungrabstr(p) to return to the previous mode of operation.
1435 *
1436 * USTPUTC is like STPUTC except that it doesn't check for overflow.
1437 * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
1438 * is space for at least one character.
1439 */
1440static void *
1441growstackstr(void)
1442{
1443 size_t len = stackblocksize();
1444 if (herefd >= 0 && len >= 1024) {
1445 full_write(herefd, stackblock(), len);
1446 return stackblock();
1447 }
1448 growstackblock();
Denis Vlasenko29eb3592008-05-18 14:06:08 +00001449 return (char *)stackblock() + len;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001450}
1451
1452/*
1453 * Called from CHECKSTRSPACE.
1454 */
1455static char *
1456makestrspace(size_t newlen, char *p)
1457{
Denis Vlasenko01631112007-12-16 17:20:38 +00001458 size_t len = p - g_stacknxt;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001459 size_t size = stackblocksize();
1460
1461 for (;;) {
1462 size_t nleft;
1463
1464 size = stackblocksize();
1465 nleft = size - len;
1466 if (nleft >= newlen)
1467 break;
1468 growstackblock();
1469 }
Denis Vlasenko29eb3592008-05-18 14:06:08 +00001470 return (char *)stackblock() + len;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001471}
1472
1473static char *
1474stack_nputstr(const char *s, size_t n, char *p)
1475{
1476 p = makestrspace(n, p);
Denis Vlasenko29eb3592008-05-18 14:06:08 +00001477 p = (char *)memcpy(p, s, n) + n;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001478 return p;
1479}
1480
1481static char *
1482stack_putstr(const char *s, char *p)
1483{
1484 return stack_nputstr(s, strlen(s), p);
1485}
1486
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001487static char *
1488_STPUTC(int c, char *p)
1489{
1490 if (p == sstrend)
1491 p = growstackstr();
1492 *p++ = c;
1493 return p;
1494}
1495
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00001496#define STARTSTACKSTR(p) ((p) = stackblock())
1497#define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
Denis Vlasenko843cbd52008-06-27 00:23:18 +00001498#define CHECKSTRSPACE(n, p) do { \
1499 char *q = (p); \
1500 size_t l = (n); \
1501 size_t m = sstrend - q; \
1502 if (l > m) \
1503 (p) = makestrspace(l, q); \
1504} while (0)
Denis Vlasenkoef527f52008-06-23 01:52:30 +00001505#define USTPUTC(c, p) (*(p)++ = (c))
Denis Vlasenko843cbd52008-06-27 00:23:18 +00001506#define STACKSTRNUL(p) do { \
1507 if ((p) == sstrend) \
1508 (p) = growstackstr(); \
1509 *(p) = '\0'; \
1510} while (0)
Denis Vlasenkoef527f52008-06-23 01:52:30 +00001511#define STUNPUTC(p) (--(p))
1512#define STTOPC(p) ((p)[-1])
1513#define STADJUST(amount, p) ((p) += (amount))
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001514
1515#define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
Denis Vlasenkoef527f52008-06-23 01:52:30 +00001516#define ungrabstackstr(s, p) stunalloc(s)
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001517#define stackstrend() ((void *)sstrend)
1518
1519
1520/* ============ String helpers */
1521
1522/*
1523 * prefix -- see if pfx is a prefix of string.
1524 */
1525static char *
1526prefix(const char *string, const char *pfx)
1527{
1528 while (*pfx) {
1529 if (*pfx++ != *string++)
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00001530 return NULL;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001531 }
1532 return (char *) string;
1533}
1534
1535/*
1536 * Check for a valid number. This should be elsewhere.
1537 */
1538static int
1539is_number(const char *p)
1540{
1541 do {
1542 if (!isdigit(*p))
1543 return 0;
1544 } while (*++p != '\0');
1545 return 1;
1546}
1547
1548/*
1549 * Convert a string of digits to an integer, printing an error message on
1550 * failure.
1551 */
1552static int
1553number(const char *s)
1554{
1555 if (!is_number(s))
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02001556 ash_msg_and_raise_error(msg_illnum, s);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001557 return atoi(s);
1558}
1559
1560/*
1561 * Produce a possibly single quoted string suitable as input to the shell.
1562 * The return string is allocated on the stack.
1563 */
1564static char *
1565single_quote(const char *s)
1566{
1567 char *p;
1568
1569 STARTSTACKSTR(p);
1570
1571 do {
1572 char *q;
1573 size_t len;
1574
1575 len = strchrnul(s, '\'') - s;
1576
1577 q = p = makestrspace(len + 3, p);
1578
1579 *q++ = '\'';
Denis Vlasenko29eb3592008-05-18 14:06:08 +00001580 q = (char *)memcpy(q, s, len) + len;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001581 *q++ = '\'';
1582 s += len;
1583
1584 STADJUST(q - p, p);
1585
Denys Vlasenkocd716832009-11-28 22:14:02 +01001586 if (*s != '\'')
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001587 break;
Denys Vlasenkocd716832009-11-28 22:14:02 +01001588 len = 0;
1589 do len++; while (*++s == '\'');
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001590
1591 q = p = makestrspace(len + 3, p);
1592
1593 *q++ = '"';
Denys Vlasenkocd716832009-11-28 22:14:02 +01001594 q = (char *)memcpy(q, s - len, len) + len;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001595 *q++ = '"';
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001596
1597 STADJUST(q - p, p);
1598 } while (*s);
1599
Denys Vlasenkocd716832009-11-28 22:14:02 +01001600 USTPUTC('\0', p);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001601
1602 return stackblock();
1603}
1604
1605
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00001606/* ============ nextopt */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001607
1608static char **argptr; /* argument list for builtin commands */
1609static char *optionarg; /* set by nextopt (like getopt) */
1610static char *optptr; /* used by nextopt */
1611
1612/*
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001613 * XXX - should get rid of. Have all builtins use getopt(3).
1614 * The library getopt must have the BSD extension static variable
1615 * "optreset", otherwise it can't be used within the shell safely.
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001616 *
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001617 * Standard option processing (a la getopt) for builtin routines.
1618 * The only argument that is passed to nextopt is the option string;
1619 * the other arguments are unnecessary. It returns the character,
1620 * or '\0' on end of input.
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001621 */
1622static int
1623nextopt(const char *optstring)
1624{
1625 char *p;
1626 const char *q;
1627 char c;
1628
1629 p = optptr;
1630 if (p == NULL || *p == '\0') {
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001631 /* We ate entire "-param", take next one */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001632 p = *argptr;
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001633 if (p == NULL)
1634 return '\0';
1635 if (*p != '-')
1636 return '\0';
1637 if (*++p == '\0') /* just "-" ? */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001638 return '\0';
1639 argptr++;
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001640 if (LONE_DASH(p)) /* "--" ? */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001641 return '\0';
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001642 /* p => next "-param" */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001643 }
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001644 /* p => some option char in the middle of a "-param" */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001645 c = *p++;
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +00001646 for (q = optstring; *q != c;) {
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001647 if (*q == '\0')
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00001648 ash_msg_and_raise_error("illegal option -%c", c);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001649 if (*++q == ':')
1650 q++;
1651 }
1652 if (*++q == ':') {
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001653 if (*p == '\0') {
1654 p = *argptr++;
1655 if (p == NULL)
1656 ash_msg_and_raise_error("no arg for -%c option", c);
1657 }
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001658 optionarg = p;
1659 p = NULL;
1660 }
1661 optptr = p;
1662 return c;
1663}
1664
1665
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00001666/* ============ Shell variables */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001667
Denis Vlasenko01631112007-12-16 17:20:38 +00001668/*
1669 * The parsefile structure pointed to by the global variable parsefile
1670 * contains information about the current file being read.
1671 */
Denis Vlasenko01631112007-12-16 17:20:38 +00001672struct shparam {
1673 int nparam; /* # of positional parameters (without $0) */
1674#if ENABLE_ASH_GETOPTS
1675 int optind; /* next parameter to be processed by getopts */
1676 int optoff; /* used by getopts */
1677#endif
1678 unsigned char malloced; /* if parameter list dynamically allocated */
1679 char **p; /* parameter list */
1680};
1681
1682/*
1683 * Free the list of positional parameters.
1684 */
1685static void
1686freeparam(volatile struct shparam *param)
1687{
Denis Vlasenko01631112007-12-16 17:20:38 +00001688 if (param->malloced) {
Denis Vlasenko3177ba02008-07-13 20:39:23 +00001689 char **ap, **ap1;
1690 ap = ap1 = param->p;
1691 while (*ap)
1692 free(*ap++);
1693 free(ap1);
Denis Vlasenko01631112007-12-16 17:20:38 +00001694 }
1695}
1696
1697#if ENABLE_ASH_GETOPTS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001698static void FAST_FUNC getoptsreset(const char *value);
Denis Vlasenko01631112007-12-16 17:20:38 +00001699#endif
1700
1701struct var {
1702 struct var *next; /* next entry in hash list */
1703 int flags; /* flags are defined above */
1704 const char *text; /* name=value */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001705 void (*func)(const char *) FAST_FUNC; /* function to be called when */
Denis Vlasenko01631112007-12-16 17:20:38 +00001706 /* the variable gets set/unset */
1707};
1708
1709struct localvar {
1710 struct localvar *next; /* next local variable in list */
1711 struct var *vp; /* the variable that was made local */
1712 int flags; /* saved flags */
1713 const char *text; /* saved text */
1714};
1715
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001716/* flags */
1717#define VEXPORT 0x01 /* variable is exported */
1718#define VREADONLY 0x02 /* variable cannot be modified */
1719#define VSTRFIXED 0x04 /* variable struct is statically allocated */
1720#define VTEXTFIXED 0x08 /* text is statically allocated */
1721#define VSTACK 0x10 /* text is allocated on the stack */
1722#define VUNSET 0x20 /* the variable is not set */
1723#define VNOFUNC 0x40 /* don't call the callback function */
1724#define VNOSET 0x80 /* do not set variable - just readonly test */
1725#define VNOSAVE 0x100 /* when text is on the heap before setvareq */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00001726#if ENABLE_ASH_RANDOM_SUPPORT
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00001727# define VDYNAMIC 0x200 /* dynamic variable */
1728#else
1729# define VDYNAMIC 0
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001730#endif
1731
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001732#ifdef IFS_BROKEN
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00001733static const char defifsvar[] ALIGN1 = "IFS= \t\n";
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001734#define defifs (defifsvar + 4)
1735#else
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00001736static const char defifs[] ALIGN1 = " \t\n";
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001737#endif
1738
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00001739
Denis Vlasenko01631112007-12-16 17:20:38 +00001740/* Need to be before varinit_data[] */
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00001741#if ENABLE_LOCALE_SUPPORT
Denys Vlasenko2634bf32009-06-09 18:40:07 +02001742static void FAST_FUNC
Denis Vlasenkoa8915072007-02-23 21:10:06 +00001743change_lc_all(const char *value)
1744{
1745 if (value && *value != '\0')
1746 setlocale(LC_ALL, value);
1747}
Denys Vlasenko2634bf32009-06-09 18:40:07 +02001748static void FAST_FUNC
Denis Vlasenkoa8915072007-02-23 21:10:06 +00001749change_lc_ctype(const char *value)
1750{
1751 if (value && *value != '\0')
1752 setlocale(LC_CTYPE, value);
1753}
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00001754#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001755#if ENABLE_ASH_MAIL
1756static void chkmail(void);
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001757static void changemail(const char *) FAST_FUNC;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001758#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001759static void changepath(const char *) FAST_FUNC;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001760#if ENABLE_ASH_RANDOM_SUPPORT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001761static void change_random(const char *) FAST_FUNC;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001762#endif
1763
Denis Vlasenko01631112007-12-16 17:20:38 +00001764static const struct {
1765 int flags;
1766 const char *text;
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001767 void (*func)(const char *) FAST_FUNC;
Denis Vlasenko01631112007-12-16 17:20:38 +00001768} varinit_data[] = {
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001769#ifdef IFS_BROKEN
Denis Vlasenko01631112007-12-16 17:20:38 +00001770 { VSTRFIXED|VTEXTFIXED , defifsvar , NULL },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001771#else
Denis Vlasenko01631112007-12-16 17:20:38 +00001772 { VSTRFIXED|VTEXTFIXED|VUNSET, "IFS\0" , NULL },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001773#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001774#if ENABLE_ASH_MAIL
Denis Vlasenko01631112007-12-16 17:20:38 +00001775 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL\0" , changemail },
1776 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH\0", changemail },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001777#endif
Denis Vlasenko01631112007-12-16 17:20:38 +00001778 { VSTRFIXED|VTEXTFIXED , bb_PATH_root_path, changepath },
1779 { VSTRFIXED|VTEXTFIXED , "PS1=$ " , NULL },
1780 { VSTRFIXED|VTEXTFIXED , "PS2=> " , NULL },
1781 { VSTRFIXED|VTEXTFIXED , "PS4=+ " , NULL },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001782#if ENABLE_ASH_GETOPTS
Denis Vlasenko01631112007-12-16 17:20:38 +00001783 { VSTRFIXED|VTEXTFIXED , "OPTIND=1" , getoptsreset },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001784#endif
1785#if ENABLE_ASH_RANDOM_SUPPORT
Denis Vlasenko01631112007-12-16 17:20:38 +00001786 { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM\0", change_random },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001787#endif
1788#if ENABLE_LOCALE_SUPPORT
Denis Vlasenko01631112007-12-16 17:20:38 +00001789 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL\0" , change_lc_all },
1790 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE\0", change_lc_ctype },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001791#endif
1792#if ENABLE_FEATURE_EDITING_SAVEHISTORY
Denis Vlasenko01631112007-12-16 17:20:38 +00001793 { VSTRFIXED|VTEXTFIXED|VUNSET, "HISTFILE\0", NULL },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001794#endif
1795};
1796
Denis Vlasenko0b769642008-07-24 07:54:57 +00001797struct redirtab;
Denis Vlasenko01631112007-12-16 17:20:38 +00001798
1799struct globals_var {
1800 struct shparam shellparam; /* $@ current positional parameters */
1801 struct redirtab *redirlist;
1802 int g_nullredirs;
1803 int preverrout_fd; /* save fd2 before print debug if xflag is set. */
1804 struct var *vartab[VTABSIZE];
1805 struct var varinit[ARRAY_SIZE(varinit_data)];
1806};
Denis Vlasenko574f2f42008-02-27 18:41:59 +00001807extern struct globals_var *const ash_ptr_to_globals_var;
1808#define G_var (*ash_ptr_to_globals_var)
Denis Vlasenko01631112007-12-16 17:20:38 +00001809#define shellparam (G_var.shellparam )
Denis Vlasenko0b769642008-07-24 07:54:57 +00001810//#define redirlist (G_var.redirlist )
Denis Vlasenko01631112007-12-16 17:20:38 +00001811#define g_nullredirs (G_var.g_nullredirs )
1812#define preverrout_fd (G_var.preverrout_fd)
1813#define vartab (G_var.vartab )
1814#define varinit (G_var.varinit )
1815#define INIT_G_var() do { \
Denis Vlasenko6b06cb82008-05-15 21:30:45 +00001816 unsigned i; \
Denis Vlasenko574f2f42008-02-27 18:41:59 +00001817 (*(struct globals_var**)&ash_ptr_to_globals_var) = xzalloc(sizeof(G_var)); \
1818 barrier(); \
Denis Vlasenko01631112007-12-16 17:20:38 +00001819 for (i = 0; i < ARRAY_SIZE(varinit_data); i++) { \
1820 varinit[i].flags = varinit_data[i].flags; \
1821 varinit[i].text = varinit_data[i].text; \
1822 varinit[i].func = varinit_data[i].func; \
1823 } \
1824} while (0)
1825
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001826#define vifs varinit[0]
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001827#if ENABLE_ASH_MAIL
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001828# define vmail (&vifs)[1]
1829# define vmpath (&vmail)[1]
1830# define vpath (&vmpath)[1]
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001831#else
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001832# define vpath (&vifs)[1]
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001833#endif
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001834#define vps1 (&vpath)[1]
1835#define vps2 (&vps1)[1]
1836#define vps4 (&vps2)[1]
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001837#if ENABLE_ASH_GETOPTS
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001838# define voptind (&vps4)[1]
1839# if ENABLE_ASH_RANDOM_SUPPORT
1840# define vrandom (&voptind)[1]
1841# endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001842#else
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001843# if ENABLE_ASH_RANDOM_SUPPORT
1844# define vrandom (&vps4)[1]
1845# endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001846#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001847
1848/*
1849 * The following macros access the values of the above variables.
1850 * They have to skip over the name. They return the null string
1851 * for unset variables.
1852 */
1853#define ifsval() (vifs.text + 4)
1854#define ifsset() ((vifs.flags & VUNSET) == 0)
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001855#if ENABLE_ASH_MAIL
1856# define mailval() (vmail.text + 5)
1857# define mpathval() (vmpath.text + 9)
1858# define mpathset() ((vmpath.flags & VUNSET) == 0)
1859#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001860#define pathval() (vpath.text + 5)
1861#define ps1val() (vps1.text + 4)
1862#define ps2val() (vps2.text + 4)
1863#define ps4val() (vps4.text + 4)
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001864#if ENABLE_ASH_GETOPTS
1865# define optindval() (voptind.text + 7)
1866#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001867
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001868
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001869#define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
1870#define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
1871
Denis Vlasenko01631112007-12-16 17:20:38 +00001872#if ENABLE_ASH_GETOPTS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001873static void FAST_FUNC
Denis Vlasenko01631112007-12-16 17:20:38 +00001874getoptsreset(const char *value)
1875{
1876 shellparam.optind = number(value);
1877 shellparam.optoff = -1;
1878}
1879#endif
1880
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001881/*
1882 * Return of a legal variable name (a letter or underscore followed by zero or
1883 * more letters, underscores, and digits).
1884 */
1885static char *
1886endofname(const char *name)
1887{
1888 char *p;
1889
1890 p = (char *) name;
1891 if (!is_name(*p))
1892 return p;
1893 while (*++p) {
1894 if (!is_in_name(*p))
1895 break;
1896 }
1897 return p;
1898}
1899
1900/*
1901 * Compares two strings up to the first = or '\0'. The first
1902 * string must be terminated by '='; the second may be terminated by
1903 * either '=' or '\0'.
1904 */
1905static int
1906varcmp(const char *p, const char *q)
1907{
1908 int c, d;
1909
1910 while ((c = *p) == (d = *q)) {
1911 if (!c || c == '=')
1912 goto out;
1913 p++;
1914 q++;
1915 }
1916 if (c == '=')
Denis Vlasenko9650f362007-02-23 01:04:37 +00001917 c = '\0';
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001918 if (d == '=')
Denis Vlasenko9650f362007-02-23 01:04:37 +00001919 d = '\0';
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001920 out:
1921 return c - d;
1922}
1923
1924static int
1925varequal(const char *a, const char *b)
1926{
1927 return !varcmp(a, b);
1928}
1929
1930/*
1931 * Find the appropriate entry in the hash table from the name.
1932 */
1933static struct var **
1934hashvar(const char *p)
1935{
1936 unsigned hashval;
1937
1938 hashval = ((unsigned char) *p) << 4;
1939 while (*p && *p != '=')
1940 hashval += (unsigned char) *p++;
1941 return &vartab[hashval % VTABSIZE];
1942}
1943
1944static int
1945vpcmp(const void *a, const void *b)
1946{
1947 return varcmp(*(const char **)a, *(const char **)b);
1948}
1949
1950/*
1951 * This routine initializes the builtin variables.
1952 */
1953static void
1954initvar(void)
1955{
1956 struct var *vp;
1957 struct var *end;
1958 struct var **vpp;
1959
1960 /*
1961 * PS1 depends on uid
1962 */
1963#if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
1964 vps1.text = "PS1=\\w \\$ ";
1965#else
1966 if (!geteuid())
1967 vps1.text = "PS1=# ";
1968#endif
1969 vp = varinit;
Denis Vlasenko80b8b392007-06-25 10:55:35 +00001970 end = vp + ARRAY_SIZE(varinit);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001971 do {
1972 vpp = hashvar(vp->text);
1973 vp->next = *vpp;
1974 *vpp = vp;
1975 } while (++vp < end);
1976}
1977
1978static struct var **
1979findvar(struct var **vpp, const char *name)
1980{
1981 for (; *vpp; vpp = &(*vpp)->next) {
1982 if (varequal((*vpp)->text, name)) {
1983 break;
1984 }
1985 }
1986 return vpp;
1987}
1988
1989/*
1990 * Find the value of a variable. Returns NULL if not set.
1991 */
Mike Frysinger98c52642009-04-02 10:02:37 +00001992static const char *
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001993lookupvar(const char *name)
1994{
1995 struct var *v;
1996
1997 v = *findvar(hashvar(name), name);
1998 if (v) {
Denis Vlasenko448d30e2008-06-27 00:24:11 +00001999#if ENABLE_ASH_RANDOM_SUPPORT
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002000 /*
2001 * Dynamic variables are implemented roughly the same way they are
2002 * in bash. Namely, they're "special" so long as they aren't unset.
2003 * As soon as they're unset, they're no longer dynamic, and dynamic
2004 * lookup will no longer happen at that point. -- PFM.
2005 */
2006 if ((v->flags & VDYNAMIC))
2007 (*v->func)(NULL);
2008#endif
2009 if (!(v->flags & VUNSET))
2010 return strchrnul(v->text, '=') + 1;
2011 }
2012 return NULL;
2013}
2014
2015/*
2016 * Search the environment of a builtin command.
2017 */
Mike Frysinger98c52642009-04-02 10:02:37 +00002018static const char *
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002019bltinlookup(const char *name)
2020{
2021 struct strlist *sp;
2022
2023 for (sp = cmdenviron; sp; sp = sp->next) {
2024 if (varequal(sp->text, name))
2025 return strchrnul(sp->text, '=') + 1;
2026 }
2027 return lookupvar(name);
2028}
2029
2030/*
2031 * Same as setvar except that the variable and value are passed in
2032 * the first argument as name=value. Since the first argument will
2033 * be actually stored in the table, it should not be a string that
2034 * will go away.
2035 * Called with interrupts off.
2036 */
2037static void
2038setvareq(char *s, int flags)
2039{
2040 struct var *vp, **vpp;
2041
2042 vpp = hashvar(s);
2043 flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
2044 vp = *findvar(vpp, s);
2045 if (vp) {
2046 if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
2047 const char *n;
2048
2049 if (flags & VNOSAVE)
2050 free(s);
2051 n = vp->text;
2052 ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
2053 }
2054
2055 if (flags & VNOSET)
2056 return;
2057
2058 if (vp->func && (flags & VNOFUNC) == 0)
2059 (*vp->func)(strchrnul(s, '=') + 1);
2060
2061 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
2062 free((char*)vp->text);
2063
2064 flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
2065 } else {
2066 if (flags & VNOSET)
2067 return;
2068 /* not found */
Denis Vlasenko597906c2008-02-20 16:38:54 +00002069 vp = ckzalloc(sizeof(*vp));
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002070 vp->next = *vpp;
Denis Vlasenko597906c2008-02-20 16:38:54 +00002071 /*vp->func = NULL; - ckzalloc did it */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002072 *vpp = vp;
2073 }
2074 if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
2075 s = ckstrdup(s);
2076 vp->text = s;
2077 vp->flags = flags;
2078}
2079
2080/*
2081 * Set the value of a variable. The flags argument is ored with the
2082 * flags of the variable. If val is NULL, the variable is unset.
2083 */
2084static void
2085setvar(const char *name, const char *val, int flags)
2086{
2087 char *p, *q;
2088 size_t namelen;
2089 char *nameeq;
2090 size_t vallen;
2091
2092 q = endofname(name);
2093 p = strchrnul(q, '=');
2094 namelen = p - name;
2095 if (!namelen || p != q)
2096 ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
2097 vallen = 0;
2098 if (val == NULL) {
2099 flags |= VUNSET;
2100 } else {
2101 vallen = strlen(val);
2102 }
2103 INT_OFF;
2104 nameeq = ckmalloc(namelen + vallen + 2);
Denis Vlasenko29eb3592008-05-18 14:06:08 +00002105 p = (char *)memcpy(nameeq, name, namelen) + namelen;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002106 if (val) {
2107 *p++ = '=';
Denis Vlasenko29eb3592008-05-18 14:06:08 +00002108 p = (char *)memcpy(p, val, vallen) + vallen;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002109 }
2110 *p = '\0';
2111 setvareq(nameeq, flags | VNOSAVE);
2112 INT_ON;
2113}
2114
2115#if ENABLE_ASH_GETOPTS
2116/*
2117 * Safe version of setvar, returns 1 on success 0 on failure.
2118 */
2119static int
2120setvarsafe(const char *name, const char *val, int flags)
2121{
2122 int err;
2123 volatile int saveint;
2124 struct jmploc *volatile savehandler = exception_handler;
2125 struct jmploc jmploc;
2126
2127 SAVE_INT(saveint);
2128 if (setjmp(jmploc.loc))
2129 err = 1;
2130 else {
2131 exception_handler = &jmploc;
2132 setvar(name, val, flags);
2133 err = 0;
2134 }
2135 exception_handler = savehandler;
2136 RESTORE_INT(saveint);
2137 return err;
2138}
2139#endif
2140
2141/*
2142 * Unset the specified variable.
2143 */
2144static int
2145unsetvar(const char *s)
2146{
2147 struct var **vpp;
2148 struct var *vp;
2149 int retval;
2150
2151 vpp = findvar(hashvar(s), s);
2152 vp = *vpp;
2153 retval = 2;
2154 if (vp) {
2155 int flags = vp->flags;
2156
2157 retval = 1;
2158 if (flags & VREADONLY)
2159 goto out;
Denis Vlasenko448d30e2008-06-27 00:24:11 +00002160#if ENABLE_ASH_RANDOM_SUPPORT
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002161 vp->flags &= ~VDYNAMIC;
2162#endif
2163 if (flags & VUNSET)
2164 goto ok;
2165 if ((flags & VSTRFIXED) == 0) {
2166 INT_OFF;
2167 if ((flags & (VTEXTFIXED|VSTACK)) == 0)
2168 free((char*)vp->text);
2169 *vpp = vp->next;
2170 free(vp);
2171 INT_ON;
2172 } else {
2173 setvar(s, 0, 0);
2174 vp->flags &= ~VEXPORT;
2175 }
2176 ok:
2177 retval = 0;
2178 }
2179 out:
2180 return retval;
2181}
2182
2183/*
2184 * Process a linked list of variable assignments.
2185 */
2186static void
2187listsetvar(struct strlist *list_set_var, int flags)
2188{
2189 struct strlist *lp = list_set_var;
2190
2191 if (!lp)
2192 return;
2193 INT_OFF;
2194 do {
2195 setvareq(lp->text, flags);
Denis Vlasenko9650f362007-02-23 01:04:37 +00002196 lp = lp->next;
2197 } while (lp);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002198 INT_ON;
2199}
2200
2201/*
2202 * Generate a list of variables satisfying the given conditions.
2203 */
2204static char **
2205listvars(int on, int off, char ***end)
2206{
2207 struct var **vpp;
2208 struct var *vp;
2209 char **ep;
2210 int mask;
2211
2212 STARTSTACKSTR(ep);
2213 vpp = vartab;
2214 mask = on | off;
2215 do {
2216 for (vp = *vpp; vp; vp = vp->next) {
2217 if ((vp->flags & mask) == on) {
2218 if (ep == stackstrend())
2219 ep = growstackstr();
2220 *ep++ = (char *) vp->text;
2221 }
2222 }
2223 } while (++vpp < vartab + VTABSIZE);
2224 if (ep == stackstrend())
2225 ep = growstackstr();
2226 if (end)
2227 *end = ep;
2228 *ep++ = NULL;
2229 return grabstackstr(ep);
2230}
2231
2232
2233/* ============ Path search helper
2234 *
2235 * The variable path (passed by reference) should be set to the start
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02002236 * of the path before the first call; path_advance will update
2237 * this value as it proceeds. Successive calls to path_advance will return
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002238 * the possible path expansions in sequence. If an option (indicated by
2239 * a percent sign) appears in the path entry then the global variable
2240 * pathopt will be set to point to it; otherwise pathopt will be set to
2241 * NULL.
2242 */
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02002243static const char *pathopt; /* set by path_advance */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002244
2245static char *
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02002246path_advance(const char **path, const char *name)
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002247{
2248 const char *p;
2249 char *q;
2250 const char *start;
2251 size_t len;
2252
2253 if (*path == NULL)
2254 return NULL;
2255 start = *path;
Denis Vlasenkof7d56652008-03-25 05:51:41 +00002256 for (p = start; *p && *p != ':' && *p != '%'; p++)
2257 continue;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002258 len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
2259 while (stackblocksize() < len)
2260 growstackblock();
2261 q = stackblock();
2262 if (p != start) {
2263 memcpy(q, start, p - start);
2264 q += p - start;
2265 *q++ = '/';
2266 }
2267 strcpy(q, name);
2268 pathopt = NULL;
2269 if (*p == '%') {
2270 pathopt = ++p;
Denis Vlasenkof7d56652008-03-25 05:51:41 +00002271 while (*p && *p != ':')
2272 p++;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002273 }
2274 if (*p == ':')
2275 *path = p + 1;
2276 else
2277 *path = NULL;
2278 return stalloc(len);
2279}
2280
2281
2282/* ============ Prompt */
2283
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +00002284static smallint doprompt; /* if set, prompt the user */
2285static smallint needprompt; /* true if interactive and at start of line */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002286
2287#if ENABLE_FEATURE_EDITING
2288static line_input_t *line_input_state;
2289static const char *cmdedit_prompt;
2290static void
2291putprompt(const char *s)
2292{
2293 if (ENABLE_ASH_EXPAND_PRMT) {
2294 free((char*)cmdedit_prompt);
Denis Vlasenko4222ae42007-02-25 02:37:49 +00002295 cmdedit_prompt = ckstrdup(s);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002296 return;
2297 }
2298 cmdedit_prompt = s;
2299}
2300#else
2301static void
2302putprompt(const char *s)
2303{
2304 out2str(s);
2305}
2306#endif
2307
2308#if ENABLE_ASH_EXPAND_PRMT
2309/* expandstr() needs parsing machinery, so it is far away ahead... */
2310static const char *expandstr(const char *ps);
2311#else
2312#define expandstr(s) s
2313#endif
2314
2315static void
2316setprompt(int whichprompt)
2317{
2318 const char *prompt;
2319#if ENABLE_ASH_EXPAND_PRMT
2320 struct stackmark smark;
2321#endif
2322
2323 needprompt = 0;
2324
2325 switch (whichprompt) {
2326 case 1:
2327 prompt = ps1val();
2328 break;
2329 case 2:
2330 prompt = ps2val();
2331 break;
2332 default: /* 0 */
2333 prompt = nullstr;
2334 }
2335#if ENABLE_ASH_EXPAND_PRMT
2336 setstackmark(&smark);
2337 stalloc(stackblocksize());
2338#endif
2339 putprompt(expandstr(prompt));
2340#if ENABLE_ASH_EXPAND_PRMT
2341 popstackmark(&smark);
2342#endif
2343}
2344
2345
2346/* ============ The cd and pwd commands */
2347
2348#define CD_PHYSICAL 1
2349#define CD_PRINT 2
2350
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002351static int
2352cdopt(void)
2353{
2354 int flags = 0;
2355 int i, j;
2356
2357 j = 'L';
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02002358 while ((i = nextopt("LP")) != '\0') {
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002359 if (i != j) {
2360 flags ^= CD_PHYSICAL;
2361 j = i;
2362 }
2363 }
2364
2365 return flags;
2366}
2367
2368/*
2369 * Update curdir (the name of the current directory) in response to a
2370 * cd command.
2371 */
2372static const char *
2373updatepwd(const char *dir)
2374{
2375 char *new;
2376 char *p;
2377 char *cdcomppath;
2378 const char *lim;
2379
2380 cdcomppath = ststrdup(dir);
2381 STARTSTACKSTR(new);
2382 if (*dir != '/') {
2383 if (curdir == nullstr)
2384 return 0;
2385 new = stack_putstr(curdir, new);
2386 }
2387 new = makestrspace(strlen(dir) + 2, new);
Denis Vlasenko29eb3592008-05-18 14:06:08 +00002388 lim = (char *)stackblock() + 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002389 if (*dir != '/') {
2390 if (new[-1] != '/')
2391 USTPUTC('/', new);
2392 if (new > lim && *lim == '/')
2393 lim++;
2394 } else {
2395 USTPUTC('/', new);
2396 cdcomppath++;
2397 if (dir[1] == '/' && dir[2] != '/') {
2398 USTPUTC('/', new);
2399 cdcomppath++;
2400 lim++;
2401 }
2402 }
2403 p = strtok(cdcomppath, "/");
2404 while (p) {
2405 switch (*p) {
2406 case '.':
2407 if (p[1] == '.' && p[2] == '\0') {
2408 while (new > lim) {
2409 STUNPUTC(new);
2410 if (new[-1] == '/')
2411 break;
2412 }
2413 break;
Denis Vlasenko16abcd92007-04-13 23:59:52 +00002414 }
2415 if (p[1] == '\0')
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002416 break;
2417 /* fall through */
2418 default:
2419 new = stack_putstr(p, new);
2420 USTPUTC('/', new);
2421 }
2422 p = strtok(0, "/");
2423 }
2424 if (new > lim)
2425 STUNPUTC(new);
2426 *new = 0;
2427 return stackblock();
2428}
2429
2430/*
2431 * Find out what the current directory is. If we already know the current
2432 * directory, this routine returns immediately.
2433 */
2434static char *
2435getpwd(void)
2436{
Denis Vlasenko01631112007-12-16 17:20:38 +00002437 char *dir = getcwd(NULL, 0); /* huh, using glibc extension? */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002438 return dir ? dir : nullstr;
2439}
2440
2441static void
2442setpwd(const char *val, int setold)
2443{
2444 char *oldcur, *dir;
2445
2446 oldcur = dir = curdir;
2447
2448 if (setold) {
2449 setvar("OLDPWD", oldcur, VEXPORT);
2450 }
2451 INT_OFF;
2452 if (physdir != nullstr) {
2453 if (physdir != oldcur)
2454 free(physdir);
2455 physdir = nullstr;
2456 }
2457 if (oldcur == val || !val) {
2458 char *s = getpwd();
2459 physdir = s;
2460 if (!val)
2461 dir = s;
2462 } else
2463 dir = ckstrdup(val);
2464 if (oldcur != dir && oldcur != nullstr) {
2465 free(oldcur);
2466 }
2467 curdir = dir;
2468 INT_ON;
2469 setvar("PWD", dir, VEXPORT);
2470}
2471
2472static void hashcd(void);
2473
2474/*
2475 * Actually do the chdir. We also call hashcd to let the routines in exec.c
2476 * know that the current directory has changed.
2477 */
2478static int
2479docd(const char *dest, int flags)
2480{
2481 const char *dir = 0;
2482 int err;
2483
2484 TRACE(("docd(\"%s\", %d) called\n", dest, flags));
2485
2486 INT_OFF;
2487 if (!(flags & CD_PHYSICAL)) {
2488 dir = updatepwd(dest);
2489 if (dir)
2490 dest = dir;
2491 }
2492 err = chdir(dest);
2493 if (err)
2494 goto out;
2495 setpwd(dir, 1);
2496 hashcd();
2497 out:
2498 INT_ON;
2499 return err;
2500}
2501
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02002502static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00002503cdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002504{
2505 const char *dest;
2506 const char *path;
2507 const char *p;
2508 char c;
2509 struct stat statb;
2510 int flags;
2511
2512 flags = cdopt();
2513 dest = *argptr;
2514 if (!dest)
2515 dest = bltinlookup(homestr);
2516 else if (LONE_DASH(dest)) {
2517 dest = bltinlookup("OLDPWD");
2518 flags |= CD_PRINT;
2519 }
2520 if (!dest)
2521 dest = nullstr;
2522 if (*dest == '/')
2523 goto step7;
2524 if (*dest == '.') {
2525 c = dest[1];
2526 dotdot:
2527 switch (c) {
2528 case '\0':
2529 case '/':
2530 goto step6;
2531 case '.':
2532 c = dest[2];
2533 if (c != '.')
2534 goto dotdot;
2535 }
2536 }
2537 if (!*dest)
2538 dest = ".";
2539 path = bltinlookup("CDPATH");
2540 if (!path) {
2541 step6:
2542 step7:
2543 p = dest;
2544 goto docd;
2545 }
2546 do {
2547 c = *path;
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02002548 p = path_advance(&path, dest);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002549 if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
2550 if (c && c != ':')
2551 flags |= CD_PRINT;
2552 docd:
2553 if (!docd(p, flags))
2554 goto out;
2555 break;
2556 }
2557 } while (path);
2558 ash_msg_and_raise_error("can't cd to %s", dest);
2559 /* NOTREACHED */
2560 out:
2561 if (flags & CD_PRINT)
2562 out1fmt(snlfmt, curdir);
2563 return 0;
2564}
2565
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02002566static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00002567pwdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002568{
2569 int flags;
2570 const char *dir = curdir;
2571
2572 flags = cdopt();
2573 if (flags) {
2574 if (physdir == nullstr)
2575 setpwd(dir, 0);
2576 dir = physdir;
2577 }
2578 out1fmt(snlfmt, dir);
2579 return 0;
2580}
2581
Denis Vlasenko0c032a42007-02-23 01:03:40 +00002582
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00002583/* ============ ... */
Eric Andersenc470f442003-07-28 09:56:35 +00002584
Denis Vlasenko834dee72008-10-07 09:18:30 +00002585
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +00002586#define IBUFSIZ COMMON_BUFSIZE
Denis Vlasenko834dee72008-10-07 09:18:30 +00002587/* buffer for top level input file */
2588#define basebuf bb_common_bufsiz1
Eric Andersenc470f442003-07-28 09:56:35 +00002589
Eric Andersenc470f442003-07-28 09:56:35 +00002590/* Syntax classes */
Denis Vlasenko834dee72008-10-07 09:18:30 +00002591#define CWORD 0 /* character is nothing special */
2592#define CNL 1 /* newline character */
2593#define CBACK 2 /* a backslash character */
2594#define CSQUOTE 3 /* single quote */
2595#define CDQUOTE 4 /* double quote */
Eric Andersenc470f442003-07-28 09:56:35 +00002596#define CENDQUOTE 5 /* a terminating quote */
Denis Vlasenko834dee72008-10-07 09:18:30 +00002597#define CBQUOTE 6 /* backwards single quote */
2598#define CVAR 7 /* a dollar sign */
2599#define CENDVAR 8 /* a '}' character */
2600#define CLP 9 /* a left paren in arithmetic */
2601#define CRP 10 /* a right paren in arithmetic */
Eric Andersenc470f442003-07-28 09:56:35 +00002602#define CENDFILE 11 /* end of file */
Denis Vlasenko834dee72008-10-07 09:18:30 +00002603#define CCTL 12 /* like CWORD, except it must be escaped */
2604#define CSPCL 13 /* these terminate a word */
2605#define CIGN 14 /* character should be ignored */
Eric Andersenc470f442003-07-28 09:56:35 +00002606
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002607#define PEOF 256
Denis Vlasenko131ae172007-02-18 13:00:19 +00002608#if ENABLE_ASH_ALIAS
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002609# define PEOA 257
Eric Andersenc470f442003-07-28 09:56:35 +00002610#endif
2611
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002612#define USE_SIT_FUNCTION ENABLE_ASH_OPTIMIZE_FOR_SIZE
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002613
Mike Frysinger98c52642009-04-02 10:02:37 +00002614#if ENABLE_SH_MATH_SUPPORT
Denys Vlasenko76bc2d62009-11-29 01:37:46 +01002615# define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8) | (d << 12))
Eric Andersenc470f442003-07-28 09:56:35 +00002616#else
Denys Vlasenko76bc2d62009-11-29 01:37:46 +01002617# define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8))
Denys Vlasenko76bc2d62009-11-29 01:37:46 +01002618#endif
Denys Vlasenko068d3862009-11-29 01:41:11 +01002619static const uint16_t S_I_T[] = {
Denys Vlasenko76bc2d62009-11-29 01:37:46 +01002620#if ENABLE_ASH_ALIAS
2621 SIT_ITEM(CSPCL , CIGN , CIGN , CIGN ), /* 0, PEOA */
2622#endif
2623 SIT_ITEM(CSPCL , CWORD , CWORD, CWORD ), /* 1, ' ' */
2624 SIT_ITEM(CNL , CNL , CNL , CNL ), /* 2, \n */
2625 SIT_ITEM(CWORD , CCTL , CCTL , CWORD ), /* 3, !*-/:=?[]~ */
2626 SIT_ITEM(CDQUOTE , CENDQUOTE, CWORD, CWORD ), /* 4, '"' */
2627 SIT_ITEM(CVAR , CVAR , CWORD, CVAR ), /* 5, $ */
2628 SIT_ITEM(CSQUOTE , CWORD , CENDQUOTE, CWORD), /* 6, "'" */
2629 SIT_ITEM(CSPCL , CWORD , CWORD, CLP ), /* 7, ( */
2630 SIT_ITEM(CSPCL , CWORD , CWORD, CRP ), /* 8, ) */
2631 SIT_ITEM(CBACK , CBACK , CCTL , CBACK ), /* 9, \ */
2632 SIT_ITEM(CBQUOTE , CBQUOTE , CWORD, CBQUOTE), /* 10, ` */
2633 SIT_ITEM(CENDVAR , CENDVAR , CWORD, CENDVAR), /* 11, } */
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002634#if !USE_SIT_FUNCTION
Denys Vlasenko76bc2d62009-11-29 01:37:46 +01002635 SIT_ITEM(CENDFILE, CENDFILE , CENDFILE, CENDFILE),/* 12, PEOF */
2636 SIT_ITEM(CWORD , CWORD , CWORD, CWORD ), /* 13, 0-9A-Za-z */
2637 SIT_ITEM(CCTL , CCTL , CCTL , CCTL ) /* 14, CTLESC ... */
2638#endif
2639#undef SIT_ITEM
Eric Andersenc470f442003-07-28 09:56:35 +00002640};
Denys Vlasenko76bc2d62009-11-29 01:37:46 +01002641/* Constants below must match table above */
2642enum {
2643#if ENABLE_ASH_ALIAS
2644 CSPCL_CIGN_CIGN_CIGN , /* 0 */
2645#endif
2646 CSPCL_CWORD_CWORD_CWORD , /* 1 */
2647 CNL_CNL_CNL_CNL , /* 2 */
2648 CWORD_CCTL_CCTL_CWORD , /* 3 */
2649 CDQUOTE_CENDQUOTE_CWORD_CWORD , /* 4 */
2650 CVAR_CVAR_CWORD_CVAR , /* 5 */
2651 CSQUOTE_CWORD_CENDQUOTE_CWORD , /* 6 */
2652 CSPCL_CWORD_CWORD_CLP , /* 7 */
2653 CSPCL_CWORD_CWORD_CRP , /* 8 */
2654 CBACK_CBACK_CCTL_CBACK , /* 9 */
2655 CBQUOTE_CBQUOTE_CWORD_CBQUOTE , /* 10 */
2656 CENDVAR_CENDVAR_CWORD_CENDVAR , /* 11 */
2657 CENDFILE_CENDFILE_CENDFILE_CENDFILE, /* 12 */
2658 CWORD_CWORD_CWORD_CWORD , /* 13 */
2659 CCTL_CCTL_CCTL_CCTL , /* 14 */
2660};
Eric Andersen2870d962001-07-02 17:27:21 +00002661
Denys Vlasenkocd716832009-11-28 22:14:02 +01002662/* c in SIT(c, syntax) must be an *unsigned char* or PEOA or PEOF,
2663 * caller must ensure proper cast on it if c is *char_ptr!
2664 */
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002665/* Values for syntax param */
2666#define BASESYNTAX 0 /* not in quotes */
2667#define DQSYNTAX 1 /* in double quotes */
2668#define SQSYNTAX 2 /* in single quotes */
2669#define ARISYNTAX 3 /* in arithmetic */
2670#define PSSYNTAX 4 /* prompt. never passed to SIT() */
Denys Vlasenkocd716832009-11-28 22:14:02 +01002671
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002672#if USE_SIT_FUNCTION
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002673
Denis Vlasenko0c032a42007-02-23 01:03:40 +00002674static int
2675SIT(int c, int syntax)
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002676{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00002677 static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-/:;<=>?[\\]`|}~";
Denys Vlasenkocd716832009-11-28 22:14:02 +01002678# if ENABLE_ASH_ALIAS
2679 static const uint8_t syntax_index_table[] ALIGN1 = {
Eric Andersenc470f442003-07-28 09:56:35 +00002680 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
2681 7, 8, 3, 3, 3, 3, 1, 1, /* "()*-/:;<" */
2682 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
2683 11, 3 /* "}~" */
2684 };
Denys Vlasenkocd716832009-11-28 22:14:02 +01002685# else
2686 static const uint8_t syntax_index_table[] ALIGN1 = {
Eric Andersenc470f442003-07-28 09:56:35 +00002687 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
2688 6, 7, 2, 2, 2, 2, 0, 0, /* "()*-/:;<" */
2689 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
2690 10, 2 /* "}~" */
2691 };
Denys Vlasenkocd716832009-11-28 22:14:02 +01002692# endif
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002693 const char *s;
2694 int indx;
2695
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002696 if (c == PEOF)
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002697 return CENDFILE;
Denys Vlasenkocd716832009-11-28 22:14:02 +01002698# if ENABLE_ASH_ALIAS
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002699 if (c == PEOA)
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +00002700 indx = 0;
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002701 else
Denys Vlasenkocd716832009-11-28 22:14:02 +01002702# endif
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +00002703 {
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002704 /* Cast is purely for paranoia here,
2705 * just in case someone passed signed char to us */
2706 if ((unsigned char)c >= CTL_FIRST
2707 && (unsigned char)c <= CTL_LAST
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +00002708 ) {
2709 return CCTL;
2710 }
2711 s = strchrnul(spec_symbls, c);
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002712 if (*s == '\0')
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +00002713 return CWORD;
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +00002714 indx = syntax_index_table[s - spec_symbls];
2715 }
Denys Vlasenko76bc2d62009-11-29 01:37:46 +01002716 return (S_I_T[indx] >> (syntax*4)) & 0xf;
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002717}
2718
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00002719#else /* !USE_SIT_FUNCTION */
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002720
Denys Vlasenko76bc2d62009-11-29 01:37:46 +01002721static const uint8_t syntax_index_table[] = {
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00002722 /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
Denys Vlasenkocd716832009-11-28 22:14:02 +01002723 /* 0 */ CWORD_CWORD_CWORD_CWORD,
2724 /* 1 */ CWORD_CWORD_CWORD_CWORD,
2725 /* 2 */ CWORD_CWORD_CWORD_CWORD,
2726 /* 3 */ CWORD_CWORD_CWORD_CWORD,
2727 /* 4 */ CWORD_CWORD_CWORD_CWORD,
2728 /* 5 */ CWORD_CWORD_CWORD_CWORD,
2729 /* 6 */ CWORD_CWORD_CWORD_CWORD,
2730 /* 7 */ CWORD_CWORD_CWORD_CWORD,
2731 /* 8 */ CWORD_CWORD_CWORD_CWORD,
2732 /* 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
2733 /* 10 "\n" */ CNL_CNL_CNL_CNL,
2734 /* 11 */ CWORD_CWORD_CWORD_CWORD,
2735 /* 12 */ CWORD_CWORD_CWORD_CWORD,
2736 /* 13 */ CWORD_CWORD_CWORD_CWORD,
2737 /* 14 */ CWORD_CWORD_CWORD_CWORD,
2738 /* 15 */ CWORD_CWORD_CWORD_CWORD,
2739 /* 16 */ CWORD_CWORD_CWORD_CWORD,
2740 /* 17 */ CWORD_CWORD_CWORD_CWORD,
2741 /* 18 */ CWORD_CWORD_CWORD_CWORD,
2742 /* 19 */ CWORD_CWORD_CWORD_CWORD,
2743 /* 20 */ CWORD_CWORD_CWORD_CWORD,
2744 /* 21 */ CWORD_CWORD_CWORD_CWORD,
2745 /* 22 */ CWORD_CWORD_CWORD_CWORD,
2746 /* 23 */ CWORD_CWORD_CWORD_CWORD,
2747 /* 24 */ CWORD_CWORD_CWORD_CWORD,
2748 /* 25 */ CWORD_CWORD_CWORD_CWORD,
2749 /* 26 */ CWORD_CWORD_CWORD_CWORD,
2750 /* 27 */ CWORD_CWORD_CWORD_CWORD,
2751 /* 28 */ CWORD_CWORD_CWORD_CWORD,
2752 /* 29 */ CWORD_CWORD_CWORD_CWORD,
2753 /* 30 */ CWORD_CWORD_CWORD_CWORD,
2754 /* 31 */ CWORD_CWORD_CWORD_CWORD,
2755 /* 32 " " */ CSPCL_CWORD_CWORD_CWORD,
2756 /* 33 "!" */ CWORD_CCTL_CCTL_CWORD,
2757 /* 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
2758 /* 35 "#" */ CWORD_CWORD_CWORD_CWORD,
2759 /* 36 "$" */ CVAR_CVAR_CWORD_CVAR,
2760 /* 37 "%" */ CWORD_CWORD_CWORD_CWORD,
2761 /* 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
2762 /* 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
2763 /* 40 "(" */ CSPCL_CWORD_CWORD_CLP,
2764 /* 41 ")" */ CSPCL_CWORD_CWORD_CRP,
2765 /* 42 "*" */ CWORD_CCTL_CCTL_CWORD,
2766 /* 43 "+" */ CWORD_CWORD_CWORD_CWORD,
2767 /* 44 "," */ CWORD_CWORD_CWORD_CWORD,
2768 /* 45 "-" */ CWORD_CCTL_CCTL_CWORD,
2769 /* 46 "." */ CWORD_CWORD_CWORD_CWORD,
2770 /* 47 "/" */ CWORD_CCTL_CCTL_CWORD,
2771 /* 48 "0" */ CWORD_CWORD_CWORD_CWORD,
2772 /* 49 "1" */ CWORD_CWORD_CWORD_CWORD,
2773 /* 50 "2" */ CWORD_CWORD_CWORD_CWORD,
2774 /* 51 "3" */ CWORD_CWORD_CWORD_CWORD,
2775 /* 52 "4" */ CWORD_CWORD_CWORD_CWORD,
2776 /* 53 "5" */ CWORD_CWORD_CWORD_CWORD,
2777 /* 54 "6" */ CWORD_CWORD_CWORD_CWORD,
2778 /* 55 "7" */ CWORD_CWORD_CWORD_CWORD,
2779 /* 56 "8" */ CWORD_CWORD_CWORD_CWORD,
2780 /* 57 "9" */ CWORD_CWORD_CWORD_CWORD,
2781 /* 58 ":" */ CWORD_CCTL_CCTL_CWORD,
2782 /* 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
2783 /* 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
2784 /* 61 "=" */ CWORD_CCTL_CCTL_CWORD,
2785 /* 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
2786 /* 63 "?" */ CWORD_CCTL_CCTL_CWORD,
2787 /* 64 "@" */ CWORD_CWORD_CWORD_CWORD,
2788 /* 65 "A" */ CWORD_CWORD_CWORD_CWORD,
2789 /* 66 "B" */ CWORD_CWORD_CWORD_CWORD,
2790 /* 67 "C" */ CWORD_CWORD_CWORD_CWORD,
2791 /* 68 "D" */ CWORD_CWORD_CWORD_CWORD,
2792 /* 69 "E" */ CWORD_CWORD_CWORD_CWORD,
2793 /* 70 "F" */ CWORD_CWORD_CWORD_CWORD,
2794 /* 71 "G" */ CWORD_CWORD_CWORD_CWORD,
2795 /* 72 "H" */ CWORD_CWORD_CWORD_CWORD,
2796 /* 73 "I" */ CWORD_CWORD_CWORD_CWORD,
2797 /* 74 "J" */ CWORD_CWORD_CWORD_CWORD,
2798 /* 75 "K" */ CWORD_CWORD_CWORD_CWORD,
2799 /* 76 "L" */ CWORD_CWORD_CWORD_CWORD,
2800 /* 77 "M" */ CWORD_CWORD_CWORD_CWORD,
2801 /* 78 "N" */ CWORD_CWORD_CWORD_CWORD,
2802 /* 79 "O" */ CWORD_CWORD_CWORD_CWORD,
2803 /* 80 "P" */ CWORD_CWORD_CWORD_CWORD,
2804 /* 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
2805 /* 82 "R" */ CWORD_CWORD_CWORD_CWORD,
2806 /* 83 "S" */ CWORD_CWORD_CWORD_CWORD,
2807 /* 84 "T" */ CWORD_CWORD_CWORD_CWORD,
2808 /* 85 "U" */ CWORD_CWORD_CWORD_CWORD,
2809 /* 86 "V" */ CWORD_CWORD_CWORD_CWORD,
2810 /* 87 "W" */ CWORD_CWORD_CWORD_CWORD,
2811 /* 88 "X" */ CWORD_CWORD_CWORD_CWORD,
2812 /* 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
2813 /* 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
2814 /* 91 "[" */ CWORD_CCTL_CCTL_CWORD,
2815 /* 92 "\" */ CBACK_CBACK_CCTL_CBACK,
2816 /* 93 "]" */ CWORD_CCTL_CCTL_CWORD,
2817 /* 94 "^" */ CWORD_CWORD_CWORD_CWORD,
2818 /* 95 "_" */ CWORD_CWORD_CWORD_CWORD,
2819 /* 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
2820 /* 97 "a" */ CWORD_CWORD_CWORD_CWORD,
2821 /* 98 "b" */ CWORD_CWORD_CWORD_CWORD,
2822 /* 99 "c" */ CWORD_CWORD_CWORD_CWORD,
2823 /* 100 "d" */ CWORD_CWORD_CWORD_CWORD,
2824 /* 101 "e" */ CWORD_CWORD_CWORD_CWORD,
2825 /* 102 "f" */ CWORD_CWORD_CWORD_CWORD,
2826 /* 103 "g" */ CWORD_CWORD_CWORD_CWORD,
2827 /* 104 "h" */ CWORD_CWORD_CWORD_CWORD,
2828 /* 105 "i" */ CWORD_CWORD_CWORD_CWORD,
2829 /* 106 "j" */ CWORD_CWORD_CWORD_CWORD,
2830 /* 107 "k" */ CWORD_CWORD_CWORD_CWORD,
2831 /* 108 "l" */ CWORD_CWORD_CWORD_CWORD,
2832 /* 109 "m" */ CWORD_CWORD_CWORD_CWORD,
2833 /* 110 "n" */ CWORD_CWORD_CWORD_CWORD,
2834 /* 111 "o" */ CWORD_CWORD_CWORD_CWORD,
2835 /* 112 "p" */ CWORD_CWORD_CWORD_CWORD,
2836 /* 113 "q" */ CWORD_CWORD_CWORD_CWORD,
2837 /* 114 "r" */ CWORD_CWORD_CWORD_CWORD,
2838 /* 115 "s" */ CWORD_CWORD_CWORD_CWORD,
2839 /* 116 "t" */ CWORD_CWORD_CWORD_CWORD,
2840 /* 117 "u" */ CWORD_CWORD_CWORD_CWORD,
2841 /* 118 "v" */ CWORD_CWORD_CWORD_CWORD,
2842 /* 119 "w" */ CWORD_CWORD_CWORD_CWORD,
2843 /* 120 "x" */ CWORD_CWORD_CWORD_CWORD,
2844 /* 121 "y" */ CWORD_CWORD_CWORD_CWORD,
2845 /* 122 "z" */ CWORD_CWORD_CWORD_CWORD,
2846 /* 123 "{" */ CWORD_CWORD_CWORD_CWORD,
2847 /* 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
2848 /* 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
2849 /* 126 "~" */ CWORD_CCTL_CCTL_CWORD,
2850 /* 127 del */ CWORD_CWORD_CWORD_CWORD,
2851 /* 128 0x80 */ CWORD_CWORD_CWORD_CWORD,
2852 /* 129 CTLESC */ CCTL_CCTL_CCTL_CCTL,
2853 /* 130 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
2854 /* 131 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
2855 /* 132 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
2856 /* 133 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
2857 /* 134 CTLARI */ CCTL_CCTL_CCTL_CCTL,
2858 /* 135 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
2859 /* 136 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
2860 /* 137 */ CWORD_CWORD_CWORD_CWORD,
2861 /* 138 */ CWORD_CWORD_CWORD_CWORD,
2862 /* 139 */ CWORD_CWORD_CWORD_CWORD,
2863 /* 140 */ CWORD_CWORD_CWORD_CWORD,
2864 /* 141 */ CWORD_CWORD_CWORD_CWORD,
2865 /* 142 */ CWORD_CWORD_CWORD_CWORD,
2866 /* 143 */ CWORD_CWORD_CWORD_CWORD,
2867 /* 144 */ CWORD_CWORD_CWORD_CWORD,
2868 /* 145 */ CWORD_CWORD_CWORD_CWORD,
2869 /* 146 */ CWORD_CWORD_CWORD_CWORD,
2870 /* 147 */ CWORD_CWORD_CWORD_CWORD,
2871 /* 148 */ CWORD_CWORD_CWORD_CWORD,
2872 /* 149 */ CWORD_CWORD_CWORD_CWORD,
2873 /* 150 */ CWORD_CWORD_CWORD_CWORD,
2874 /* 151 */ CWORD_CWORD_CWORD_CWORD,
2875 /* 152 */ CWORD_CWORD_CWORD_CWORD,
2876 /* 153 */ CWORD_CWORD_CWORD_CWORD,
2877 /* 154 */ CWORD_CWORD_CWORD_CWORD,
2878 /* 155 */ CWORD_CWORD_CWORD_CWORD,
2879 /* 156 */ CWORD_CWORD_CWORD_CWORD,
2880 /* 157 */ CWORD_CWORD_CWORD_CWORD,
2881 /* 158 */ CWORD_CWORD_CWORD_CWORD,
2882 /* 159 */ CWORD_CWORD_CWORD_CWORD,
2883 /* 160 */ CWORD_CWORD_CWORD_CWORD,
2884 /* 161 */ CWORD_CWORD_CWORD_CWORD,
2885 /* 162 */ CWORD_CWORD_CWORD_CWORD,
2886 /* 163 */ CWORD_CWORD_CWORD_CWORD,
2887 /* 164 */ CWORD_CWORD_CWORD_CWORD,
2888 /* 165 */ CWORD_CWORD_CWORD_CWORD,
2889 /* 166 */ CWORD_CWORD_CWORD_CWORD,
2890 /* 167 */ CWORD_CWORD_CWORD_CWORD,
2891 /* 168 */ CWORD_CWORD_CWORD_CWORD,
2892 /* 169 */ CWORD_CWORD_CWORD_CWORD,
2893 /* 170 */ CWORD_CWORD_CWORD_CWORD,
2894 /* 171 */ CWORD_CWORD_CWORD_CWORD,
2895 /* 172 */ CWORD_CWORD_CWORD_CWORD,
2896 /* 173 */ CWORD_CWORD_CWORD_CWORD,
2897 /* 174 */ CWORD_CWORD_CWORD_CWORD,
2898 /* 175 */ CWORD_CWORD_CWORD_CWORD,
2899 /* 176 */ CWORD_CWORD_CWORD_CWORD,
2900 /* 177 */ CWORD_CWORD_CWORD_CWORD,
2901 /* 178 */ CWORD_CWORD_CWORD_CWORD,
2902 /* 179 */ CWORD_CWORD_CWORD_CWORD,
2903 /* 180 */ CWORD_CWORD_CWORD_CWORD,
2904 /* 181 */ CWORD_CWORD_CWORD_CWORD,
2905 /* 182 */ CWORD_CWORD_CWORD_CWORD,
2906 /* 183 */ CWORD_CWORD_CWORD_CWORD,
2907 /* 184 */ CWORD_CWORD_CWORD_CWORD,
2908 /* 185 */ CWORD_CWORD_CWORD_CWORD,
2909 /* 186 */ CWORD_CWORD_CWORD_CWORD,
2910 /* 187 */ CWORD_CWORD_CWORD_CWORD,
2911 /* 188 */ CWORD_CWORD_CWORD_CWORD,
2912 /* 189 */ CWORD_CWORD_CWORD_CWORD,
2913 /* 190 */ CWORD_CWORD_CWORD_CWORD,
2914 /* 191 */ CWORD_CWORD_CWORD_CWORD,
2915 /* 192 */ CWORD_CWORD_CWORD_CWORD,
2916 /* 193 */ CWORD_CWORD_CWORD_CWORD,
2917 /* 194 */ CWORD_CWORD_CWORD_CWORD,
2918 /* 195 */ CWORD_CWORD_CWORD_CWORD,
2919 /* 196 */ CWORD_CWORD_CWORD_CWORD,
2920 /* 197 */ CWORD_CWORD_CWORD_CWORD,
2921 /* 198 */ CWORD_CWORD_CWORD_CWORD,
2922 /* 199 */ CWORD_CWORD_CWORD_CWORD,
2923 /* 200 */ CWORD_CWORD_CWORD_CWORD,
2924 /* 201 */ CWORD_CWORD_CWORD_CWORD,
2925 /* 202 */ CWORD_CWORD_CWORD_CWORD,
2926 /* 203 */ CWORD_CWORD_CWORD_CWORD,
2927 /* 204 */ CWORD_CWORD_CWORD_CWORD,
2928 /* 205 */ CWORD_CWORD_CWORD_CWORD,
2929 /* 206 */ CWORD_CWORD_CWORD_CWORD,
2930 /* 207 */ CWORD_CWORD_CWORD_CWORD,
2931 /* 208 */ CWORD_CWORD_CWORD_CWORD,
2932 /* 209 */ CWORD_CWORD_CWORD_CWORD,
2933 /* 210 */ CWORD_CWORD_CWORD_CWORD,
2934 /* 211 */ CWORD_CWORD_CWORD_CWORD,
2935 /* 212 */ CWORD_CWORD_CWORD_CWORD,
2936 /* 213 */ CWORD_CWORD_CWORD_CWORD,
2937 /* 214 */ CWORD_CWORD_CWORD_CWORD,
2938 /* 215 */ CWORD_CWORD_CWORD_CWORD,
2939 /* 216 */ CWORD_CWORD_CWORD_CWORD,
2940 /* 217 */ CWORD_CWORD_CWORD_CWORD,
2941 /* 218 */ CWORD_CWORD_CWORD_CWORD,
2942 /* 219 */ CWORD_CWORD_CWORD_CWORD,
2943 /* 220 */ CWORD_CWORD_CWORD_CWORD,
2944 /* 221 */ CWORD_CWORD_CWORD_CWORD,
2945 /* 222 */ CWORD_CWORD_CWORD_CWORD,
2946 /* 223 */ CWORD_CWORD_CWORD_CWORD,
2947 /* 224 */ CWORD_CWORD_CWORD_CWORD,
2948 /* 225 */ CWORD_CWORD_CWORD_CWORD,
2949 /* 226 */ CWORD_CWORD_CWORD_CWORD,
2950 /* 227 */ CWORD_CWORD_CWORD_CWORD,
2951 /* 228 */ CWORD_CWORD_CWORD_CWORD,
2952 /* 229 */ CWORD_CWORD_CWORD_CWORD,
2953 /* 230 */ CWORD_CWORD_CWORD_CWORD,
2954 /* 231 */ CWORD_CWORD_CWORD_CWORD,
2955 /* 232 */ CWORD_CWORD_CWORD_CWORD,
2956 /* 233 */ CWORD_CWORD_CWORD_CWORD,
2957 /* 234 */ CWORD_CWORD_CWORD_CWORD,
2958 /* 235 */ CWORD_CWORD_CWORD_CWORD,
2959 /* 236 */ CWORD_CWORD_CWORD_CWORD,
2960 /* 237 */ CWORD_CWORD_CWORD_CWORD,
2961 /* 238 */ CWORD_CWORD_CWORD_CWORD,
2962 /* 239 */ CWORD_CWORD_CWORD_CWORD,
2963 /* 230 */ CWORD_CWORD_CWORD_CWORD,
2964 /* 241 */ CWORD_CWORD_CWORD_CWORD,
2965 /* 242 */ CWORD_CWORD_CWORD_CWORD,
2966 /* 243 */ CWORD_CWORD_CWORD_CWORD,
2967 /* 244 */ CWORD_CWORD_CWORD_CWORD,
2968 /* 245 */ CWORD_CWORD_CWORD_CWORD,
2969 /* 246 */ CWORD_CWORD_CWORD_CWORD,
2970 /* 247 */ CWORD_CWORD_CWORD_CWORD,
2971 /* 248 */ CWORD_CWORD_CWORD_CWORD,
2972 /* 249 */ CWORD_CWORD_CWORD_CWORD,
2973 /* 250 */ CWORD_CWORD_CWORD_CWORD,
2974 /* 251 */ CWORD_CWORD_CWORD_CWORD,
2975 /* 252 */ CWORD_CWORD_CWORD_CWORD,
2976 /* 253 */ CWORD_CWORD_CWORD_CWORD,
2977 /* 254 */ CWORD_CWORD_CWORD_CWORD,
2978 /* 255 */ CWORD_CWORD_CWORD_CWORD,
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002979 /* PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
Denys Vlasenkocd716832009-11-28 22:14:02 +01002980# if ENABLE_ASH_ALIAS
2981 /* PEOA */ CSPCL_CIGN_CIGN_CIGN,
2982# endif
Eric Andersen2870d962001-07-02 17:27:21 +00002983};
2984
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002985# define SIT(c, syntax) ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf)
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00002986
Denys Vlasenko76bc2d62009-11-29 01:37:46 +01002987#endif /* !USE_SIT_FUNCTION */
Eric Andersenc470f442003-07-28 09:56:35 +00002988
Eric Andersen2870d962001-07-02 17:27:21 +00002989
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00002990/* ============ Alias handling */
Denis Vlasenkofc06f292007-02-23 21:09:35 +00002991
Denis Vlasenko131ae172007-02-18 13:00:19 +00002992#if ENABLE_ASH_ALIAS
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00002993
2994#define ALIASINUSE 1
2995#define ALIASDEAD 2
2996
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00002997struct alias {
2998 struct alias *next;
2999 char *name;
3000 char *val;
3001 int flag;
3002};
3003
Denis Vlasenko01631112007-12-16 17:20:38 +00003004
3005static struct alias **atab; // [ATABSIZE];
3006#define INIT_G_alias() do { \
3007 atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
3008} while (0)
3009
Eric Andersen2870d962001-07-02 17:27:21 +00003010
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00003011static struct alias **
3012__lookupalias(const char *name) {
3013 unsigned int hashval;
3014 struct alias **app;
3015 const char *p;
3016 unsigned int ch;
3017
3018 p = name;
3019
3020 ch = (unsigned char)*p;
3021 hashval = ch << 4;
3022 while (ch) {
3023 hashval += ch;
3024 ch = (unsigned char)*++p;
3025 }
3026 app = &atab[hashval % ATABSIZE];
3027
3028 for (; *app; app = &(*app)->next) {
3029 if (strcmp(name, (*app)->name) == 0) {
3030 break;
3031 }
3032 }
3033
3034 return app;
3035}
3036
3037static struct alias *
3038lookupalias(const char *name, int check)
3039{
3040 struct alias *ap = *__lookupalias(name);
3041
3042 if (check && ap && (ap->flag & ALIASINUSE))
3043 return NULL;
3044 return ap;
3045}
3046
3047static struct alias *
3048freealias(struct alias *ap)
3049{
3050 struct alias *next;
3051
3052 if (ap->flag & ALIASINUSE) {
3053 ap->flag |= ALIASDEAD;
3054 return ap;
3055 }
3056
3057 next = ap->next;
3058 free(ap->name);
3059 free(ap->val);
3060 free(ap);
3061 return next;
3062}
Eric Andersencb57d552001-06-28 07:25:16 +00003063
Eric Andersenc470f442003-07-28 09:56:35 +00003064static void
3065setalias(const char *name, const char *val)
Eric Andersencb57d552001-06-28 07:25:16 +00003066{
3067 struct alias *ap, **app;
3068
3069 app = __lookupalias(name);
3070 ap = *app;
Denis Vlasenkob012b102007-02-19 22:43:01 +00003071 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +00003072 if (ap) {
3073 if (!(ap->flag & ALIASINUSE)) {
Denis Vlasenkob012b102007-02-19 22:43:01 +00003074 free(ap->val);
Eric Andersencb57d552001-06-28 07:25:16 +00003075 }
Denis Vlasenko0c032a42007-02-23 01:03:40 +00003076 ap->val = ckstrdup(val);
Eric Andersencb57d552001-06-28 07:25:16 +00003077 ap->flag &= ~ALIASDEAD;
3078 } else {
3079 /* not found */
Denis Vlasenko597906c2008-02-20 16:38:54 +00003080 ap = ckzalloc(sizeof(struct alias));
Denis Vlasenko0c032a42007-02-23 01:03:40 +00003081 ap->name = ckstrdup(name);
3082 ap->val = ckstrdup(val);
Denis Vlasenko597906c2008-02-20 16:38:54 +00003083 /*ap->flag = 0; - ckzalloc did it */
3084 /*ap->next = NULL;*/
Eric Andersencb57d552001-06-28 07:25:16 +00003085 *app = ap;
3086 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00003087 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00003088}
3089
Eric Andersenc470f442003-07-28 09:56:35 +00003090static int
3091unalias(const char *name)
Eric Andersen2870d962001-07-02 17:27:21 +00003092{
Eric Andersencb57d552001-06-28 07:25:16 +00003093 struct alias **app;
3094
3095 app = __lookupalias(name);
3096
3097 if (*app) {
Denis Vlasenkob012b102007-02-19 22:43:01 +00003098 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +00003099 *app = freealias(*app);
Denis Vlasenkob012b102007-02-19 22:43:01 +00003100 INT_ON;
Denis Vlasenko079f8af2006-11-27 16:49:31 +00003101 return 0;
Eric Andersencb57d552001-06-28 07:25:16 +00003102 }
3103
Denis Vlasenko079f8af2006-11-27 16:49:31 +00003104 return 1;
Eric Andersencb57d552001-06-28 07:25:16 +00003105}
3106
Eric Andersenc470f442003-07-28 09:56:35 +00003107static void
3108rmaliases(void)
Eric Andersen2870d962001-07-02 17:27:21 +00003109{
Eric Andersencb57d552001-06-28 07:25:16 +00003110 struct alias *ap, **app;
3111 int i;
3112
Denis Vlasenkob012b102007-02-19 22:43:01 +00003113 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +00003114 for (i = 0; i < ATABSIZE; i++) {
3115 app = &atab[i];
3116 for (ap = *app; ap; ap = *app) {
3117 *app = freealias(*app);
3118 if (ap == *app) {
3119 app = &ap->next;
3120 }
3121 }
3122 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00003123 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00003124}
3125
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00003126static void
3127printalias(const struct alias *ap)
3128{
3129 out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
3130}
3131
Eric Andersencb57d552001-06-28 07:25:16 +00003132/*
3133 * TODO - sort output
3134 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02003135static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00003136aliascmd(int argc UNUSED_PARAM, char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +00003137{
3138 char *n, *v;
3139 int ret = 0;
3140 struct alias *ap;
3141
Denis Vlasenko68404f12008-03-17 09:00:54 +00003142 if (!argv[1]) {
Eric Andersencb57d552001-06-28 07:25:16 +00003143 int i;
3144
Denis Vlasenko68404f12008-03-17 09:00:54 +00003145 for (i = 0; i < ATABSIZE; i++) {
Eric Andersencb57d552001-06-28 07:25:16 +00003146 for (ap = atab[i]; ap; ap = ap->next) {
3147 printalias(ap);
3148 }
Denis Vlasenko68404f12008-03-17 09:00:54 +00003149 }
Denis Vlasenko079f8af2006-11-27 16:49:31 +00003150 return 0;
Eric Andersencb57d552001-06-28 07:25:16 +00003151 }
3152 while ((n = *++argv) != NULL) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00003153 v = strchr(n+1, '=');
3154 if (v == NULL) { /* n+1: funny ksh stuff */
3155 ap = *__lookupalias(n);
3156 if (ap == NULL) {
Eric Andersenc470f442003-07-28 09:56:35 +00003157 fprintf(stderr, "%s: %s not found\n", "alias", n);
Eric Andersencb57d552001-06-28 07:25:16 +00003158 ret = 1;
3159 } else
3160 printalias(ap);
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00003161 } else {
Eric Andersencb57d552001-06-28 07:25:16 +00003162 *v++ = '\0';
3163 setalias(n, v);
3164 }
3165 }
3166
Denis Vlasenkod9e15f22006-11-27 16:49:55 +00003167 return ret;
Eric Andersencb57d552001-06-28 07:25:16 +00003168}
3169
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02003170static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00003171unaliascmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersencb57d552001-06-28 07:25:16 +00003172{
3173 int i;
3174
3175 while ((i = nextopt("a")) != '\0') {
3176 if (i == 'a') {
3177 rmaliases();
Denis Vlasenko079f8af2006-11-27 16:49:31 +00003178 return 0;
Eric Andersencb57d552001-06-28 07:25:16 +00003179 }
3180 }
3181 for (i = 0; *argptr; argptr++) {
3182 if (unalias(*argptr)) {
Eric Andersenc470f442003-07-28 09:56:35 +00003183 fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
Eric Andersencb57d552001-06-28 07:25:16 +00003184 i = 1;
3185 }
3186 }
3187
Denis Vlasenkod9e15f22006-11-27 16:49:55 +00003188 return i;
Eric Andersencb57d552001-06-28 07:25:16 +00003189}
Denis Vlasenkofc06f292007-02-23 21:09:35 +00003190
Denis Vlasenko131ae172007-02-18 13:00:19 +00003191#endif /* ASH_ALIAS */
Eric Andersencb57d552001-06-28 07:25:16 +00003192
Eric Andersenc470f442003-07-28 09:56:35 +00003193
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003194/* ============ jobs.c */
3195
3196/* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
Denys Vlasenko285ad152009-12-04 23:02:27 +01003197#define FORK_FG 0
3198#define FORK_BG 1
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003199#define FORK_NOJOB 2
3200
3201/* mode flags for showjob(s) */
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003202#define SHOW_ONLY_PGID 0x01 /* show only pgid (jobs -p) */
3203#define SHOW_PIDS 0x02 /* show individual pids, not just one line per job */
3204#define SHOW_CHANGED 0x04 /* only jobs whose state has changed */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003205
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003206/*
3207 * A job structure contains information about a job. A job is either a
3208 * single process or a set of processes contained in a pipeline. In the
3209 * latter case, pidlist will be non-NULL, and will point to a -1 terminated
3210 * array of pids.
3211 */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003212struct procstat {
Denys Vlasenko285ad152009-12-04 23:02:27 +01003213 pid_t ps_pid; /* process id */
3214 int ps_status; /* last process status from wait() */
3215 char *ps_cmd; /* text of command being run */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003216};
3217
3218struct job {
3219 struct procstat ps0; /* status of process */
3220 struct procstat *ps; /* status or processes when more than one */
3221#if JOBS
3222 int stopstatus; /* status of a stopped job */
3223#endif
3224 uint32_t
3225 nprocs: 16, /* number of processes */
3226 state: 8,
3227#define JOBRUNNING 0 /* at least one proc running */
3228#define JOBSTOPPED 1 /* all procs are stopped */
3229#define JOBDONE 2 /* all procs are completed */
3230#if JOBS
3231 sigint: 1, /* job was killed by SIGINT */
3232 jobctl: 1, /* job running under job control */
3233#endif
3234 waited: 1, /* true if this entry has been waited for */
3235 used: 1, /* true if this entry is in used */
3236 changed: 1; /* true if status has changed */
3237 struct job *prev_job; /* previous job */
3238};
3239
Denis Vlasenko68404f12008-03-17 09:00:54 +00003240static struct job *makejob(/*union node *,*/ int);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003241static int forkshell(struct job *, union node *, int);
3242static int waitforjob(struct job *);
3243
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003244#if !JOBS
Denis Vlasenkob07a4962008-06-22 13:16:23 +00003245enum { doing_jobctl = 0 };
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003246#define setjobctl(on) do {} while (0)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003247#else
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003248static smallint doing_jobctl; //references:8
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003249static void setjobctl(int);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003250#endif
3251
3252/*
Denis Vlasenko4b875702009-03-19 13:30:04 +00003253 * Ignore a signal.
3254 */
3255static void
3256ignoresig(int signo)
3257{
3258 /* Avoid unnecessary system calls. Is it already SIG_IGNed? */
3259 if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
3260 /* No, need to do it */
3261 signal(signo, SIG_IGN);
3262 }
3263 sigmode[signo - 1] = S_HARD_IGN;
3264}
3265
3266/*
3267 * Signal handler. Only one usage site - in setsignal()
3268 */
3269static void
3270onsig(int signo)
3271{
3272 gotsig[signo - 1] = 1;
3273
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02003274 if (signo == SIGINT && !trap[SIGINT]) {
3275 if (!suppress_int) {
3276 pending_sig = 0;
Denis Vlasenko4b875702009-03-19 13:30:04 +00003277 raise_interrupt(); /* does not return */
3278 }
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02003279 pending_int = 1;
Denis Vlasenko4b875702009-03-19 13:30:04 +00003280 } else {
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02003281 pending_sig = signo;
Denis Vlasenko4b875702009-03-19 13:30:04 +00003282 }
3283}
3284
3285/*
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003286 * Set the signal handler for the specified signal. The routine figures
3287 * out what it should be set to.
3288 */
3289static void
3290setsignal(int signo)
3291{
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003292 char *t;
3293 char cur_act, new_act;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003294 struct sigaction act;
3295
3296 t = trap[signo];
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003297 new_act = S_DFL;
3298 if (t != NULL) { /* trap for this sig is set */
3299 new_act = S_CATCH;
3300 if (t[0] == '\0') /* trap is "": ignore this sig */
3301 new_act = S_IGN;
3302 }
3303
3304 if (rootshell && new_act == S_DFL) {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003305 switch (signo) {
3306 case SIGINT:
3307 if (iflag || minusc || sflag == 0)
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003308 new_act = S_CATCH;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003309 break;
3310 case SIGQUIT:
3311#if DEBUG
3312 if (debug)
3313 break;
3314#endif
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003315 /* man bash:
3316 * "In all cases, bash ignores SIGQUIT. Non-builtin
3317 * commands run by bash have signal handlers
3318 * set to the values inherited by the shell
3319 * from its parent". */
3320 new_act = S_IGN;
3321 break;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003322 case SIGTERM:
3323 if (iflag)
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003324 new_act = S_IGN;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003325 break;
3326#if JOBS
3327 case SIGTSTP:
3328 case SIGTTOU:
3329 if (mflag)
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003330 new_act = S_IGN;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003331 break;
3332#endif
3333 }
3334 }
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003335//TODO: if !rootshell, we reset SIGQUIT to DFL,
3336//whereas we have to restore it to what shell got on entry
3337//from the parent. See comment above
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003338
3339 t = &sigmode[signo - 1];
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003340 cur_act = *t;
3341 if (cur_act == 0) {
3342 /* current setting is not yet known */
3343 if (sigaction(signo, NULL, &act)) {
3344 /* pretend it worked; maybe we should give a warning,
3345 * but other shells don't. We don't alter sigmode,
3346 * so we retry every time.
3347 * btw, in Linux it never fails. --vda */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003348 return;
3349 }
3350 if (act.sa_handler == SIG_IGN) {
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003351 cur_act = S_HARD_IGN;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003352 if (mflag
3353 && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
3354 ) {
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003355 cur_act = S_IGN; /* don't hard ignore these */
Denis Vlasenko991a1da2008-02-10 19:02:53 +00003356 }
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003357 }
3358 }
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003359 if (cur_act == S_HARD_IGN || cur_act == new_act)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003360 return;
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003361
Denis Vlasenko991a1da2008-02-10 19:02:53 +00003362 act.sa_handler = SIG_DFL;
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003363 switch (new_act) {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003364 case S_CATCH:
3365 act.sa_handler = onsig;
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003366 act.sa_flags = 0; /* matters only if !DFL and !IGN */
3367 sigfillset(&act.sa_mask); /* ditto */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003368 break;
3369 case S_IGN:
3370 act.sa_handler = SIG_IGN;
3371 break;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003372 }
Denis Vlasenko8e2cfec2008-03-12 23:19:35 +00003373 sigaction_set(signo, &act);
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003374
3375 *t = new_act;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003376}
3377
3378/* mode flags for set_curjob */
3379#define CUR_DELETE 2
3380#define CUR_RUNNING 1
3381#define CUR_STOPPED 0
3382
3383/* mode flags for dowait */
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00003384#define DOWAIT_NONBLOCK WNOHANG
3385#define DOWAIT_BLOCK 0
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003386
3387#if JOBS
3388/* pgrp of shell on invocation */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003389static int initialpgrp; //references:2
3390static int ttyfd = -1; //5
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003391#endif
3392/* array of jobs */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003393static struct job *jobtab; //5
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003394/* size of array */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003395static unsigned njobs; //4
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003396/* current job */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003397static struct job *curjob; //lots
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003398/* number of presumed living untracked jobs */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003399static int jobless; //4
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003400
3401static void
3402set_curjob(struct job *jp, unsigned mode)
3403{
3404 struct job *jp1;
3405 struct job **jpp, **curp;
3406
3407 /* first remove from list */
3408 jpp = curp = &curjob;
3409 do {
3410 jp1 = *jpp;
3411 if (jp1 == jp)
3412 break;
3413 jpp = &jp1->prev_job;
3414 } while (1);
3415 *jpp = jp1->prev_job;
3416
3417 /* Then re-insert in correct position */
3418 jpp = curp;
3419 switch (mode) {
3420 default:
3421#if DEBUG
3422 abort();
3423#endif
3424 case CUR_DELETE:
3425 /* job being deleted */
3426 break;
3427 case CUR_RUNNING:
3428 /* newly created job or backgrounded job,
3429 put after all stopped jobs. */
3430 do {
3431 jp1 = *jpp;
3432#if JOBS
3433 if (!jp1 || jp1->state != JOBSTOPPED)
3434#endif
3435 break;
3436 jpp = &jp1->prev_job;
3437 } while (1);
3438 /* FALLTHROUGH */
3439#if JOBS
3440 case CUR_STOPPED:
3441#endif
3442 /* newly stopped job - becomes curjob */
3443 jp->prev_job = *jpp;
3444 *jpp = jp;
3445 break;
3446 }
3447}
3448
3449#if JOBS || DEBUG
3450static int
3451jobno(const struct job *jp)
3452{
3453 return jp - jobtab + 1;
3454}
3455#endif
3456
3457/*
3458 * Convert a job name to a job structure.
3459 */
Denis Vlasenko85c24712008-03-17 09:04:04 +00003460#if !JOBS
3461#define getjob(name, getctl) getjob(name)
3462#endif
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003463static struct job *
3464getjob(const char *name, int getctl)
3465{
3466 struct job *jp;
3467 struct job *found;
Denys Vlasenkoffc39202009-08-17 02:12:20 +02003468 const char *err_msg = "%s: no such job";
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003469 unsigned num;
3470 int c;
3471 const char *p;
3472 char *(*match)(const char *, const char *);
3473
3474 jp = curjob;
3475 p = name;
3476 if (!p)
3477 goto currentjob;
3478
3479 if (*p != '%')
3480 goto err;
3481
3482 c = *++p;
3483 if (!c)
3484 goto currentjob;
3485
3486 if (!p[1]) {
3487 if (c == '+' || c == '%') {
3488 currentjob:
3489 err_msg = "No current job";
3490 goto check;
3491 }
3492 if (c == '-') {
3493 if (jp)
3494 jp = jp->prev_job;
3495 err_msg = "No previous job";
3496 check:
3497 if (!jp)
3498 goto err;
3499 goto gotit;
3500 }
3501 }
3502
3503 if (is_number(p)) {
3504 num = atoi(p);
3505 if (num < njobs) {
3506 jp = jobtab + num - 1;
3507 if (jp->used)
3508 goto gotit;
3509 goto err;
3510 }
3511 }
3512
3513 match = prefix;
3514 if (*p == '?') {
3515 match = strstr;
3516 p++;
3517 }
3518
Denys Vlasenkoffc39202009-08-17 02:12:20 +02003519 found = NULL;
3520 while (jp) {
Denys Vlasenko285ad152009-12-04 23:02:27 +01003521 if (match(jp->ps[0].ps_cmd, p)) {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003522 if (found)
3523 goto err;
3524 found = jp;
3525 err_msg = "%s: ambiguous";
3526 }
3527 jp = jp->prev_job;
3528 }
Denys Vlasenkoffc39202009-08-17 02:12:20 +02003529 if (!found)
3530 goto err;
3531 jp = found;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003532
3533 gotit:
3534#if JOBS
3535 err_msg = "job %s not created under job control";
3536 if (getctl && jp->jobctl == 0)
3537 goto err;
3538#endif
3539 return jp;
3540 err:
3541 ash_msg_and_raise_error(err_msg, name);
3542}
3543
3544/*
3545 * Mark a job structure as unused.
3546 */
3547static void
3548freejob(struct job *jp)
3549{
3550 struct procstat *ps;
3551 int i;
3552
3553 INT_OFF;
3554 for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
Denys Vlasenko285ad152009-12-04 23:02:27 +01003555 if (ps->ps_cmd != nullstr)
3556 free(ps->ps_cmd);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003557 }
3558 if (jp->ps != &jp->ps0)
3559 free(jp->ps);
3560 jp->used = 0;
3561 set_curjob(jp, CUR_DELETE);
3562 INT_ON;
3563}
3564
3565#if JOBS
3566static void
3567xtcsetpgrp(int fd, pid_t pgrp)
3568{
3569 if (tcsetpgrp(fd, pgrp))
Bernhard Reutner-Fischera53de7f2008-07-21 13:46:54 +00003570 ash_msg_and_raise_error("can't set tty process group (%m)");
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003571}
3572
3573/*
3574 * Turn job control on and off.
3575 *
3576 * Note: This code assumes that the third arg to ioctl is a character
3577 * pointer, which is true on Berkeley systems but not System V. Since
3578 * System V doesn't have job control yet, this isn't a problem now.
3579 *
3580 * Called with interrupts off.
3581 */
3582static void
3583setjobctl(int on)
3584{
3585 int fd;
3586 int pgrp;
3587
Denis Vlasenkob07a4962008-06-22 13:16:23 +00003588 if (on == doing_jobctl || rootshell == 0)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003589 return;
3590 if (on) {
3591 int ofd;
3592 ofd = fd = open(_PATH_TTY, O_RDWR);
3593 if (fd < 0) {
3594 /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
3595 * That sometimes helps to acquire controlling tty.
3596 * Obviously, a workaround for bugs when someone
3597 * failed to provide a controlling tty to bash! :) */
Denis Vlasenkoed270a52007-11-26 05:37:07 +00003598 fd = 2;
3599 while (!isatty(fd))
3600 if (--fd < 0)
3601 goto out;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003602 }
3603 fd = fcntl(fd, F_DUPFD, 10);
Denis Vlasenkoed270a52007-11-26 05:37:07 +00003604 if (ofd >= 0)
3605 close(ofd);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003606 if (fd < 0)
3607 goto out;
Denis Vlasenkoed270a52007-11-26 05:37:07 +00003608 /* fd is a tty at this point */
Denis Vlasenko96e1b382007-09-30 23:50:48 +00003609 close_on_exec_on(fd);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003610 do { /* while we are in the background */
3611 pgrp = tcgetpgrp(fd);
3612 if (pgrp < 0) {
3613 out:
3614 ash_msg("can't access tty; job control turned off");
3615 mflag = on = 0;
3616 goto close;
3617 }
3618 if (pgrp == getpgrp())
3619 break;
3620 killpg(0, SIGTTIN);
3621 } while (1);
3622 initialpgrp = pgrp;
3623
3624 setsignal(SIGTSTP);
3625 setsignal(SIGTTOU);
3626 setsignal(SIGTTIN);
3627 pgrp = rootpid;
3628 setpgid(0, pgrp);
3629 xtcsetpgrp(fd, pgrp);
3630 } else {
3631 /* turning job control off */
3632 fd = ttyfd;
3633 pgrp = initialpgrp;
Denis Vlasenko08c8c1d2007-04-28 22:39:02 +00003634 /* was xtcsetpgrp, but this can make exiting ash
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00003635 * loop forever if pty is already deleted */
Denis Vlasenko08c8c1d2007-04-28 22:39:02 +00003636 tcsetpgrp(fd, pgrp);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003637 setpgid(0, pgrp);
3638 setsignal(SIGTSTP);
3639 setsignal(SIGTTOU);
3640 setsignal(SIGTTIN);
3641 close:
Denis Vlasenkoed270a52007-11-26 05:37:07 +00003642 if (fd >= 0)
3643 close(fd);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003644 fd = -1;
3645 }
3646 ttyfd = fd;
Denis Vlasenkob07a4962008-06-22 13:16:23 +00003647 doing_jobctl = on;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003648}
3649
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02003650static int FAST_FUNC
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003651killcmd(int argc, char **argv)
3652{
Denis Vlasenko68404f12008-03-17 09:00:54 +00003653 int i = 1;
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003654 if (argv[1] && strcmp(argv[1], "-l") != 0) {
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003655 do {
3656 if (argv[i][0] == '%') {
3657 struct job *jp = getjob(argv[i], 0);
Denys Vlasenko285ad152009-12-04 23:02:27 +01003658 unsigned pid = jp->ps[0].ps_pid;
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003659 /* Enough space for ' -NNN<nul>' */
3660 argv[i] = alloca(sizeof(int)*3 + 3);
3661 /* kill_main has matching code to expect
3662 * leading space. Needed to not confuse
3663 * negative pids with "kill -SIGNAL_NO" syntax */
3664 sprintf(argv[i], " -%u", pid);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003665 }
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003666 } while (argv[++i]);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003667 }
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003668 return kill_main(argc, argv);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003669}
3670
3671static void
Denys Vlasenko285ad152009-12-04 23:02:27 +01003672showpipe(struct job *jp /*, FILE *out*/)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003673{
Denys Vlasenko285ad152009-12-04 23:02:27 +01003674 struct procstat *ps;
3675 struct procstat *psend;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003676
Denys Vlasenko285ad152009-12-04 23:02:27 +01003677 psend = jp->ps + jp->nprocs;
3678 for (ps = jp->ps + 1; ps < psend; ps++)
3679 printf(" | %s", ps->ps_cmd);
3680 outcslow('\n', stdout);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003681 flush_stdout_stderr();
3682}
3683
3684
3685static int
3686restartjob(struct job *jp, int mode)
3687{
3688 struct procstat *ps;
3689 int i;
3690 int status;
3691 pid_t pgid;
3692
3693 INT_OFF;
3694 if (jp->state == JOBDONE)
3695 goto out;
3696 jp->state = JOBRUNNING;
Denys Vlasenko285ad152009-12-04 23:02:27 +01003697 pgid = jp->ps[0].ps_pid;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003698 if (mode == FORK_FG)
3699 xtcsetpgrp(ttyfd, pgid);
3700 killpg(pgid, SIGCONT);
3701 ps = jp->ps;
3702 i = jp->nprocs;
3703 do {
Denys Vlasenko285ad152009-12-04 23:02:27 +01003704 if (WIFSTOPPED(ps->ps_status)) {
3705 ps->ps_status = -1;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003706 }
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003707 ps++;
3708 } while (--i);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003709 out:
3710 status = (mode == FORK_FG) ? waitforjob(jp) : 0;
3711 INT_ON;
3712 return status;
3713}
3714
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02003715static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00003716fg_bgcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003717{
3718 struct job *jp;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003719 int mode;
3720 int retval;
3721
3722 mode = (**argv == 'f') ? FORK_FG : FORK_BG;
3723 nextopt(nullstr);
3724 argv = argptr;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003725 do {
3726 jp = getjob(*argv, 1);
3727 if (mode == FORK_BG) {
3728 set_curjob(jp, CUR_RUNNING);
Denys Vlasenko285ad152009-12-04 23:02:27 +01003729 printf("[%d] ", jobno(jp));
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003730 }
Denys Vlasenko285ad152009-12-04 23:02:27 +01003731 out1str(jp->ps[0].ps_cmd);
3732 showpipe(jp /*, stdout*/);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003733 retval = restartjob(jp, mode);
3734 } while (*argv && *++argv);
3735 return retval;
3736}
3737#endif
3738
3739static int
3740sprint_status(char *s, int status, int sigonly)
3741{
3742 int col;
3743 int st;
3744
3745 col = 0;
3746 if (!WIFEXITED(status)) {
3747#if JOBS
3748 if (WIFSTOPPED(status))
3749 st = WSTOPSIG(status);
3750 else
3751#endif
3752 st = WTERMSIG(status);
3753 if (sigonly) {
3754 if (st == SIGINT || st == SIGPIPE)
3755 goto out;
3756#if JOBS
3757 if (WIFSTOPPED(status))
3758 goto out;
3759#endif
3760 }
3761 st &= 0x7f;
3762 col = fmtstr(s, 32, strsignal(st));
3763 if (WCOREDUMP(status)) {
3764 col += fmtstr(s + col, 16, " (core dumped)");
3765 }
3766 } else if (!sigonly) {
3767 st = WEXITSTATUS(status);
3768 if (st)
3769 col = fmtstr(s, 16, "Done(%d)", st);
3770 else
3771 col = fmtstr(s, 16, "Done");
3772 }
3773 out:
3774 return col;
3775}
3776
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003777static int
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00003778dowait(int wait_flags, struct job *job)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003779{
3780 int pid;
3781 int status;
3782 struct job *jp;
3783 struct job *thisjob;
3784 int state;
3785
Denis Vlasenkobe54d6b2008-10-27 14:25:52 +00003786 TRACE(("dowait(0x%x) called\n", wait_flags));
3787
3788 /* Do a wait system call. If job control is compiled in, we accept
3789 * stopped processes. wait_flags may have WNOHANG, preventing blocking.
3790 * NB: _not_ safe_waitpid, we need to detect EINTR */
Denys Vlasenko285ad152009-12-04 23:02:27 +01003791 if (doing_jobctl)
3792 wait_flags |= WUNTRACED;
3793 pid = waitpid(-1, &status, wait_flags);
Denis Vlasenkob21f3792009-03-19 23:09:58 +00003794 TRACE(("wait returns pid=%d, status=0x%x, errno=%d(%s)\n",
3795 pid, status, errno, strerror(errno)));
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003796 if (pid <= 0)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003797 return pid;
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003798
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003799 INT_OFF;
3800 thisjob = NULL;
3801 for (jp = curjob; jp; jp = jp->prev_job) {
Denys Vlasenko285ad152009-12-04 23:02:27 +01003802 struct procstat *ps;
3803 struct procstat *psend;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003804 if (jp->state == JOBDONE)
3805 continue;
3806 state = JOBDONE;
Denys Vlasenko285ad152009-12-04 23:02:27 +01003807 ps = jp->ps;
3808 psend = ps + jp->nprocs;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003809 do {
Denys Vlasenko285ad152009-12-04 23:02:27 +01003810 if (ps->ps_pid == pid) {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003811 TRACE(("Job %d: changing status of proc %d "
3812 "from 0x%x to 0x%x\n",
Denys Vlasenko285ad152009-12-04 23:02:27 +01003813 jobno(jp), pid, ps->ps_status, status));
3814 ps->ps_status = status;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003815 thisjob = jp;
3816 }
Denys Vlasenko285ad152009-12-04 23:02:27 +01003817 if (ps->ps_status == -1)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003818 state = JOBRUNNING;
3819#if JOBS
3820 if (state == JOBRUNNING)
3821 continue;
Denys Vlasenko285ad152009-12-04 23:02:27 +01003822 if (WIFSTOPPED(ps->ps_status)) {
3823 jp->stopstatus = ps->ps_status;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003824 state = JOBSTOPPED;
3825 }
3826#endif
Denys Vlasenko285ad152009-12-04 23:02:27 +01003827 } while (++ps < psend);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003828 if (thisjob)
3829 goto gotjob;
3830 }
3831#if JOBS
3832 if (!WIFSTOPPED(status))
3833#endif
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003834 jobless--;
3835 goto out;
3836
3837 gotjob:
3838 if (state != JOBRUNNING) {
3839 thisjob->changed = 1;
3840
3841 if (thisjob->state != state) {
3842 TRACE(("Job %d: changing state from %d to %d\n",
3843 jobno(thisjob), thisjob->state, state));
3844 thisjob->state = state;
3845#if JOBS
3846 if (state == JOBSTOPPED) {
3847 set_curjob(thisjob, CUR_STOPPED);
3848 }
3849#endif
3850 }
3851 }
3852
3853 out:
3854 INT_ON;
3855
3856 if (thisjob && thisjob == job) {
3857 char s[48 + 1];
3858 int len;
3859
3860 len = sprint_status(s, status, 1);
3861 if (len) {
3862 s[len] = '\n';
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00003863 s[len + 1] = '\0';
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003864 out2str(s);
3865 }
3866 }
3867 return pid;
3868}
3869
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003870static int
3871blocking_wait_with_raise_on_sig(struct job *job)
3872{
3873 pid_t pid = dowait(DOWAIT_BLOCK, job);
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02003874 if (pid <= 0 && pending_sig)
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003875 raise_exception(EXSIG);
3876 return pid;
3877}
3878
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003879#if JOBS
3880static void
3881showjob(FILE *out, struct job *jp, int mode)
3882{
3883 struct procstat *ps;
3884 struct procstat *psend;
3885 int col;
Denis Vlasenko40ba9982007-07-14 00:48:29 +00003886 int indent_col;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003887 char s[80];
3888
3889 ps = jp->ps;
3890
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003891 if (mode & SHOW_ONLY_PGID) { /* jobs -p */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003892 /* just output process (group) id of pipeline */
Denys Vlasenko285ad152009-12-04 23:02:27 +01003893 fprintf(out, "%d\n", ps->ps_pid);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003894 return;
3895 }
3896
3897 col = fmtstr(s, 16, "[%d] ", jobno(jp));
Denis Vlasenko40ba9982007-07-14 00:48:29 +00003898 indent_col = col;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003899
3900 if (jp == curjob)
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003901 s[col - 3] = '+';
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003902 else if (curjob && jp == curjob->prev_job)
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003903 s[col - 3] = '-';
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003904
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003905 if (mode & SHOW_PIDS)
Denys Vlasenko285ad152009-12-04 23:02:27 +01003906 col += fmtstr(s + col, 16, "%d ", ps->ps_pid);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003907
3908 psend = ps + jp->nprocs;
3909
3910 if (jp->state == JOBRUNNING) {
3911 strcpy(s + col, "Running");
3912 col += sizeof("Running") - 1;
3913 } else {
Denys Vlasenko285ad152009-12-04 23:02:27 +01003914 int status = psend[-1].ps_status;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003915 if (jp->state == JOBSTOPPED)
3916 status = jp->stopstatus;
3917 col += sprint_status(s + col, status, 0);
3918 }
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003919 /* By now, "[JOBID]* [maybe PID] STATUS" is printed */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003920
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003921 /* This loop either prints "<cmd1> | <cmd2> | <cmd3>" line
3922 * or prints several "PID | <cmdN>" lines,
3923 * depending on SHOW_PIDS bit.
3924 * We do not print status of individual processes
3925 * between PID and <cmdN>. bash does it, but not very well:
3926 * first line shows overall job status, not process status,
3927 * making it impossible to know 1st process status.
3928 */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003929 goto start;
Denys Vlasenko285ad152009-12-04 23:02:27 +01003930 do {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003931 /* for each process */
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003932 s[0] = '\0';
3933 col = 33;
3934 if (mode & SHOW_PIDS)
Denys Vlasenko285ad152009-12-04 23:02:27 +01003935 col = fmtstr(s, 48, "\n%*c%d ", indent_col, ' ', ps->ps_pid) - 1;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003936 start:
Denys Vlasenko285ad152009-12-04 23:02:27 +01003937 fprintf(out, "%s%*c%s%s",
3938 s,
3939 33 - col >= 0 ? 33 - col : 0, ' ',
3940 ps == jp->ps ? "" : "| ",
3941 ps->ps_cmd
3942 );
3943 } while (++ps != psend);
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003944 outcslow('\n', out);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003945
3946 jp->changed = 0;
3947
3948 if (jp->state == JOBDONE) {
3949 TRACE(("showjob: freeing job %d\n", jobno(jp)));
3950 freejob(jp);
3951 }
3952}
3953
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003954/*
3955 * Print a list of jobs. If "change" is nonzero, only print jobs whose
3956 * statuses have changed since the last call to showjobs.
3957 */
3958static void
3959showjobs(FILE *out, int mode)
3960{
3961 struct job *jp;
3962
Denys Vlasenko883cea42009-07-11 15:31:59 +02003963 TRACE(("showjobs(0x%x) called\n", mode));
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003964
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003965 /* Handle all finished jobs */
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00003966 while (dowait(DOWAIT_NONBLOCK, NULL) > 0)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003967 continue;
3968
3969 for (jp = curjob; jp; jp = jp->prev_job) {
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003970 if (!(mode & SHOW_CHANGED) || jp->changed) {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003971 showjob(out, jp, mode);
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003972 }
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003973 }
3974}
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003975
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02003976static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00003977jobscmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003978{
3979 int mode, m;
3980
3981 mode = 0;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02003982 while ((m = nextopt("lp")) != '\0') {
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003983 if (m == 'l')
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003984 mode |= SHOW_PIDS;
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003985 else
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003986 mode |= SHOW_ONLY_PGID;
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003987 }
3988
3989 argv = argptr;
3990 if (*argv) {
3991 do
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003992 showjob(stdout, getjob(*argv, 0), mode);
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003993 while (*++argv);
Denys Vlasenko285ad152009-12-04 23:02:27 +01003994 } else {
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003995 showjobs(stdout, mode);
Denys Vlasenko285ad152009-12-04 23:02:27 +01003996 }
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003997
3998 return 0;
3999}
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004000#endif /* JOBS */
4001
4002static int
4003getstatus(struct job *job)
4004{
4005 int status;
4006 int retval;
4007
Denys Vlasenko285ad152009-12-04 23:02:27 +01004008 status = job->ps[job->nprocs - 1].ps_status;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004009 retval = WEXITSTATUS(status);
4010 if (!WIFEXITED(status)) {
4011#if JOBS
4012 retval = WSTOPSIG(status);
4013 if (!WIFSTOPPED(status))
4014#endif
4015 {
4016 /* XXX: limits number of signals */
4017 retval = WTERMSIG(status);
4018#if JOBS
4019 if (retval == SIGINT)
4020 job->sigint = 1;
4021#endif
4022 }
4023 retval += 128;
4024 }
Denys Vlasenko883cea42009-07-11 15:31:59 +02004025 TRACE(("getstatus: job %d, nproc %d, status 0x%x, retval 0x%x\n",
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004026 jobno(job), job->nprocs, status, retval));
4027 return retval;
4028}
4029
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02004030static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00004031waitcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004032{
4033 struct job *job;
4034 int retval;
4035 struct job *jp;
4036
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02004037 if (pending_sig)
Denis Vlasenko991a1da2008-02-10 19:02:53 +00004038 raise_exception(EXSIG);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004039
4040 nextopt(nullstr);
4041 retval = 0;
4042
4043 argv = argptr;
4044 if (!*argv) {
4045 /* wait for all jobs */
4046 for (;;) {
4047 jp = curjob;
4048 while (1) {
Denis Vlasenko991a1da2008-02-10 19:02:53 +00004049 if (!jp) /* no running procs */
4050 goto ret;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004051 if (jp->state == JOBRUNNING)
4052 break;
4053 jp->waited = 1;
4054 jp = jp->prev_job;
4055 }
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004056 /* man bash:
4057 * "When bash is waiting for an asynchronous command via
4058 * the wait builtin, the reception of a signal for which a trap
4059 * has been set will cause the wait builtin to return immediately
4060 * with an exit status greater than 128, immediately after which
4061 * the trap is executed."
4062 * Do we do it that way? */
4063 blocking_wait_with_raise_on_sig(NULL);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004064 }
4065 }
4066
4067 retval = 127;
4068 do {
4069 if (**argv != '%') {
4070 pid_t pid = number(*argv);
4071 job = curjob;
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00004072 while (1) {
4073 if (!job)
4074 goto repeat;
Denys Vlasenko285ad152009-12-04 23:02:27 +01004075 if (job->ps[job->nprocs - 1].ps_pid == pid)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004076 break;
4077 job = job->prev_job;
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00004078 }
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004079 } else
4080 job = getjob(*argv, 0);
4081 /* loop until process terminated or stopped */
4082 while (job->state == JOBRUNNING)
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004083 blocking_wait_with_raise_on_sig(NULL);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004084 job->waited = 1;
4085 retval = getstatus(job);
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004086 repeat: ;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004087 } while (*++argv);
4088
Denis Vlasenko991a1da2008-02-10 19:02:53 +00004089 ret:
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004090 return retval;
4091}
4092
4093static struct job *
4094growjobtab(void)
4095{
4096 size_t len;
4097 ptrdiff_t offset;
4098 struct job *jp, *jq;
4099
4100 len = njobs * sizeof(*jp);
4101 jq = jobtab;
4102 jp = ckrealloc(jq, len + 4 * sizeof(*jp));
4103
4104 offset = (char *)jp - (char *)jq;
4105 if (offset) {
4106 /* Relocate pointers */
4107 size_t l = len;
4108
4109 jq = (struct job *)((char *)jq + l);
4110 while (l) {
4111 l -= sizeof(*jp);
4112 jq--;
4113#define joff(p) ((struct job *)((char *)(p) + l))
4114#define jmove(p) (p) = (void *)((char *)(p) + offset)
4115 if (joff(jp)->ps == &jq->ps0)
4116 jmove(joff(jp)->ps);
4117 if (joff(jp)->prev_job)
4118 jmove(joff(jp)->prev_job);
4119 }
4120 if (curjob)
4121 jmove(curjob);
4122#undef joff
4123#undef jmove
4124 }
4125
4126 njobs += 4;
4127 jobtab = jp;
4128 jp = (struct job *)((char *)jp + len);
4129 jq = jp + 3;
4130 do {
4131 jq->used = 0;
4132 } while (--jq >= jp);
4133 return jp;
4134}
4135
4136/*
4137 * Return a new job structure.
4138 * Called with interrupts off.
4139 */
4140static struct job *
Denis Vlasenko68404f12008-03-17 09:00:54 +00004141makejob(/*union node *node,*/ int nprocs)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004142{
4143 int i;
4144 struct job *jp;
4145
4146 for (i = njobs, jp = jobtab; ; jp++) {
4147 if (--i < 0) {
4148 jp = growjobtab();
4149 break;
4150 }
4151 if (jp->used == 0)
4152 break;
4153 if (jp->state != JOBDONE || !jp->waited)
4154 continue;
4155#if JOBS
Denis Vlasenkob07a4962008-06-22 13:16:23 +00004156 if (doing_jobctl)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004157 continue;
4158#endif
4159 freejob(jp);
4160 break;
4161 }
4162 memset(jp, 0, sizeof(*jp));
4163#if JOBS
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00004164 /* jp->jobctl is a bitfield.
4165 * "jp->jobctl |= jobctl" likely to give awful code */
Denis Vlasenkob07a4962008-06-22 13:16:23 +00004166 if (doing_jobctl)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004167 jp->jobctl = 1;
4168#endif
4169 jp->prev_job = curjob;
4170 curjob = jp;
4171 jp->used = 1;
4172 jp->ps = &jp->ps0;
4173 if (nprocs > 1) {
4174 jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
4175 }
Denis Vlasenko68404f12008-03-17 09:00:54 +00004176 TRACE(("makejob(%d) returns %%%d\n", nprocs,
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004177 jobno(jp)));
4178 return jp;
4179}
4180
4181#if JOBS
4182/*
4183 * Return a string identifying a command (to be printed by the
4184 * jobs command).
4185 */
4186static char *cmdnextc;
4187
4188static void
4189cmdputs(const char *s)
4190{
Denis Vlasenko92e13c22008-03-25 01:17:40 +00004191 static const char vstype[VSTYPE + 1][3] = {
4192 "", "}", "-", "+", "?", "=",
4193 "%", "%%", "#", "##"
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00004194 IF_ASH_BASH_COMPAT(, ":", "/", "//")
Denis Vlasenko92e13c22008-03-25 01:17:40 +00004195 };
4196
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004197 const char *p, *str;
Denys Vlasenkocd716832009-11-28 22:14:02 +01004198 char cc[2] = " ";
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004199 char *nextc;
Denys Vlasenkocd716832009-11-28 22:14:02 +01004200 unsigned char c;
4201 unsigned char subtype = 0;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004202 int quoted = 0;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004203
4204 nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
4205 p = s;
4206 while ((c = *p++) != 0) {
Denis Vlasenkoef527f52008-06-23 01:52:30 +00004207 str = NULL;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004208 switch (c) {
4209 case CTLESC:
4210 c = *p++;
4211 break;
4212 case CTLVAR:
4213 subtype = *p++;
4214 if ((subtype & VSTYPE) == VSLENGTH)
4215 str = "${#";
4216 else
4217 str = "${";
4218 if (!(subtype & VSQUOTE) == !(quoted & 1))
4219 goto dostr;
4220 quoted ^= 1;
4221 c = '"';
4222 break;
4223 case CTLENDVAR:
4224 str = "\"}" + !(quoted & 1);
4225 quoted >>= 1;
4226 subtype = 0;
4227 goto dostr;
4228 case CTLBACKQ:
4229 str = "$(...)";
4230 goto dostr;
4231 case CTLBACKQ+CTLQUOTE:
4232 str = "\"$(...)\"";
4233 goto dostr;
Mike Frysinger98c52642009-04-02 10:02:37 +00004234#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004235 case CTLARI:
4236 str = "$((";
4237 goto dostr;
4238 case CTLENDARI:
4239 str = "))";
4240 goto dostr;
4241#endif
4242 case CTLQUOTEMARK:
4243 quoted ^= 1;
4244 c = '"';
4245 break;
4246 case '=':
4247 if (subtype == 0)
4248 break;
4249 if ((subtype & VSTYPE) != VSNORMAL)
4250 quoted <<= 1;
4251 str = vstype[subtype & VSTYPE];
4252 if (subtype & VSNUL)
4253 c = ':';
4254 else
4255 goto checkstr;
4256 break;
4257 case '\'':
4258 case '\\':
4259 case '"':
4260 case '$':
4261 /* These can only happen inside quotes */
4262 cc[0] = c;
4263 str = cc;
4264 c = '\\';
4265 break;
4266 default:
4267 break;
4268 }
4269 USTPUTC(c, nextc);
4270 checkstr:
4271 if (!str)
4272 continue;
4273 dostr:
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02004274 while ((c = *str++) != '\0') {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004275 USTPUTC(c, nextc);
4276 }
4277 }
4278 if (quoted & 1) {
4279 USTPUTC('"', nextc);
4280 }
4281 *nextc = 0;
4282 cmdnextc = nextc;
4283}
4284
4285/* cmdtxt() and cmdlist() call each other */
4286static void cmdtxt(union node *n);
4287
4288static void
4289cmdlist(union node *np, int sep)
4290{
4291 for (; np; np = np->narg.next) {
4292 if (!sep)
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00004293 cmdputs(" ");
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004294 cmdtxt(np);
4295 if (sep && np->narg.next)
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00004296 cmdputs(" ");
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004297 }
4298}
4299
4300static void
4301cmdtxt(union node *n)
4302{
4303 union node *np;
4304 struct nodelist *lp;
4305 const char *p;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004306
4307 if (!n)
4308 return;
4309 switch (n->type) {
4310 default:
4311#if DEBUG
4312 abort();
4313#endif
4314 case NPIPE:
4315 lp = n->npipe.cmdlist;
4316 for (;;) {
4317 cmdtxt(lp->n);
4318 lp = lp->next;
4319 if (!lp)
4320 break;
4321 cmdputs(" | ");
4322 }
4323 break;
4324 case NSEMI:
4325 p = "; ";
4326 goto binop;
4327 case NAND:
4328 p = " && ";
4329 goto binop;
4330 case NOR:
4331 p = " || ";
4332 binop:
4333 cmdtxt(n->nbinary.ch1);
4334 cmdputs(p);
4335 n = n->nbinary.ch2;
4336 goto donode;
4337 case NREDIR:
4338 case NBACKGND:
4339 n = n->nredir.n;
4340 goto donode;
4341 case NNOT:
4342 cmdputs("!");
4343 n = n->nnot.com;
4344 donode:
4345 cmdtxt(n);
4346 break;
4347 case NIF:
4348 cmdputs("if ");
4349 cmdtxt(n->nif.test);
4350 cmdputs("; then ");
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004351 if (n->nif.elsepart) {
Denys Vlasenko7cee00e2009-07-24 01:08:03 +02004352 cmdtxt(n->nif.ifpart);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004353 cmdputs("; else ");
4354 n = n->nif.elsepart;
Denys Vlasenko7cee00e2009-07-24 01:08:03 +02004355 } else {
4356 n = n->nif.ifpart;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004357 }
4358 p = "; fi";
4359 goto dotail;
4360 case NSUBSHELL:
4361 cmdputs("(");
4362 n = n->nredir.n;
4363 p = ")";
4364 goto dotail;
4365 case NWHILE:
4366 p = "while ";
4367 goto until;
4368 case NUNTIL:
4369 p = "until ";
4370 until:
4371 cmdputs(p);
4372 cmdtxt(n->nbinary.ch1);
4373 n = n->nbinary.ch2;
4374 p = "; done";
4375 dodo:
4376 cmdputs("; do ");
4377 dotail:
4378 cmdtxt(n);
4379 goto dotail2;
4380 case NFOR:
4381 cmdputs("for ");
4382 cmdputs(n->nfor.var);
4383 cmdputs(" in ");
4384 cmdlist(n->nfor.args, 1);
4385 n = n->nfor.body;
4386 p = "; done";
4387 goto dodo;
4388 case NDEFUN:
4389 cmdputs(n->narg.text);
4390 p = "() { ... }";
4391 goto dotail2;
4392 case NCMD:
4393 cmdlist(n->ncmd.args, 1);
4394 cmdlist(n->ncmd.redirect, 0);
4395 break;
4396 case NARG:
4397 p = n->narg.text;
4398 dotail2:
4399 cmdputs(p);
4400 break;
4401 case NHERE:
4402 case NXHERE:
4403 p = "<<...";
4404 goto dotail2;
4405 case NCASE:
4406 cmdputs("case ");
4407 cmdputs(n->ncase.expr->narg.text);
4408 cmdputs(" in ");
4409 for (np = n->ncase.cases; np; np = np->nclist.next) {
4410 cmdtxt(np->nclist.pattern);
4411 cmdputs(") ");
4412 cmdtxt(np->nclist.body);
4413 cmdputs(";; ");
4414 }
4415 p = "esac";
4416 goto dotail2;
4417 case NTO:
4418 p = ">";
4419 goto redir;
4420 case NCLOBBER:
4421 p = ">|";
4422 goto redir;
4423 case NAPPEND:
4424 p = ">>";
4425 goto redir;
Denis Vlasenko559691a2008-10-05 18:39:31 +00004426#if ENABLE_ASH_BASH_COMPAT
4427 case NTO2:
4428#endif
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004429 case NTOFD:
4430 p = ">&";
4431 goto redir;
4432 case NFROM:
4433 p = "<";
4434 goto redir;
4435 case NFROMFD:
4436 p = "<&";
4437 goto redir;
4438 case NFROMTO:
4439 p = "<>";
4440 redir:
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00004441 cmdputs(utoa(n->nfile.fd));
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004442 cmdputs(p);
4443 if (n->type == NTOFD || n->type == NFROMFD) {
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00004444 cmdputs(utoa(n->ndup.dupfd));
4445 break;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004446 }
4447 n = n->nfile.fname;
4448 goto donode;
4449 }
4450}
4451
4452static char *
4453commandtext(union node *n)
4454{
4455 char *name;
4456
4457 STARTSTACKSTR(cmdnextc);
4458 cmdtxt(n);
4459 name = stackblock();
4460 TRACE(("commandtext: name %p, end %p\n\t\"%s\"\n",
4461 name, cmdnextc, cmdnextc));
4462 return ckstrdup(name);
4463}
4464#endif /* JOBS */
4465
4466/*
4467 * Fork off a subshell. If we are doing job control, give the subshell its
4468 * own process group. Jp is a job structure that the job is to be added to.
4469 * N is the command that will be evaluated by the child. Both jp and n may
4470 * be NULL. The mode parameter can be one of the following:
4471 * FORK_FG - Fork off a foreground process.
4472 * FORK_BG - Fork off a background process.
4473 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
4474 * process group even if job control is on.
4475 *
4476 * When job control is turned off, background processes have their standard
4477 * input redirected to /dev/null (except for the second and later processes
4478 * in a pipeline).
4479 *
4480 * Called with interrupts off.
4481 */
4482/*
4483 * Clear traps on a fork.
4484 */
4485static void
4486clear_traps(void)
4487{
4488 char **tp;
4489
4490 for (tp = trap; tp < &trap[NSIG]; tp++) {
Denis Vlasenko991a1da2008-02-10 19:02:53 +00004491 if (*tp && **tp) { /* trap not NULL or "" (SIG_IGN) */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004492 INT_OFF;
Denys Vlasenkoe305c282009-09-25 02:12:27 +02004493 if (trap_ptr == trap)
4494 free(*tp);
4495 /* else: it "belongs" to trap_ptr vector, don't free */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004496 *tp = NULL;
Denys Vlasenko0800e3a2009-09-24 03:09:26 +02004497 if ((tp - trap) != 0)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004498 setsignal(tp - trap);
4499 INT_ON;
4500 }
4501 }
4502}
Denis Vlasenkobdc406d2007-07-15 01:13:25 +00004503
4504/* Lives far away from here, needed for forkchild */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004505static void closescript(void);
Denis Vlasenko41770222007-10-07 18:02:52 +00004506
Denis Vlasenkobdc406d2007-07-15 01:13:25 +00004507/* Called after fork(), in child */
Denys Vlasenko21d87d42009-09-25 00:06:51 +02004508static NOINLINE void
Denys Vlasenkoe56f22a2009-07-24 00:16:59 +02004509forkchild(struct job *jp, union node *n, int mode)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004510{
4511 int oldlvl;
4512
4513 TRACE(("Child shell %d\n", getpid()));
4514 oldlvl = shlvl;
4515 shlvl++;
4516
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004517 /* man bash: "Non-builtin commands run by bash have signal handlers
4518 * set to the values inherited by the shell from its parent".
4519 * Do we do it correctly? */
4520
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004521 closescript();
Denys Vlasenko844f9902009-09-23 03:25:52 +02004522
4523 if (mode == FORK_NOJOB /* is it `xxx` ? */
4524 && n && n->type == NCMD /* is it single cmd? */
4525 /* && n->ncmd.args->type == NARG - always true? */
4526 && strcmp(n->ncmd.args->narg.text, "trap") == 0
4527 && n->ncmd.args->narg.next == NULL /* "trap" with no arguments */
4528 /* && n->ncmd.args->narg.backquote == NULL - do we need to check this? */
4529 ) {
4530 TRACE(("Trap hack\n"));
4531 /* Awful hack for `trap` or $(trap).
4532 *
4533 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
4534 * contains an example where "trap" is executed in a subshell:
4535 *
4536 * save_traps=$(trap)
4537 * ...
4538 * eval "$save_traps"
4539 *
4540 * Standard does not say that "trap" in subshell shall print
4541 * parent shell's traps. It only says that its output
4542 * must have suitable form, but then, in the above example
4543 * (which is not supposed to be normative), it implies that.
4544 *
4545 * bash (and probably other shell) does implement it
4546 * (traps are reset to defaults, but "trap" still shows them),
4547 * but as a result, "trap" logic is hopelessly messed up:
4548 *
4549 * # trap
4550 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
4551 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
4552 * # true | trap <--- trap is in subshell - no output (ditto)
4553 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
4554 * trap -- 'echo Ho' SIGWINCH
4555 * # echo `(trap)` <--- in subshell in subshell - output
4556 * trap -- 'echo Ho' SIGWINCH
4557 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
4558 * trap -- 'echo Ho' SIGWINCH
4559 *
4560 * The rules when to forget and when to not forget traps
4561 * get really complex and nonsensical.
4562 *
4563 * Our solution: ONLY bare $(trap) or `trap` is special.
4564 */
Denys Vlasenko8f88d852009-09-25 12:12:53 +02004565 /* Save trap handler strings for trap builtin to print */
Denys Vlasenko21d87d42009-09-25 00:06:51 +02004566 trap_ptr = memcpy(xmalloc(sizeof(trap)), trap, sizeof(trap));
Denys Vlasenko8f88d852009-09-25 12:12:53 +02004567 /* Fall through into clearing traps */
Denys Vlasenko844f9902009-09-23 03:25:52 +02004568 }
Denys Vlasenkoe305c282009-09-25 02:12:27 +02004569 clear_traps();
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004570#if JOBS
4571 /* do job control only in root shell */
Denis Vlasenkob07a4962008-06-22 13:16:23 +00004572 doing_jobctl = 0;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004573 if (mode != FORK_NOJOB && jp->jobctl && !oldlvl) {
4574 pid_t pgrp;
4575
4576 if (jp->nprocs == 0)
4577 pgrp = getpid();
4578 else
Denys Vlasenko285ad152009-12-04 23:02:27 +01004579 pgrp = jp->ps[0].ps_pid;
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004580 /* this can fail because we are doing it in the parent also */
4581 setpgid(0, pgrp);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004582 if (mode == FORK_FG)
4583 xtcsetpgrp(ttyfd, pgrp);
4584 setsignal(SIGTSTP);
4585 setsignal(SIGTTOU);
4586 } else
4587#endif
4588 if (mode == FORK_BG) {
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004589 /* man bash: "When job control is not in effect,
4590 * asynchronous commands ignore SIGINT and SIGQUIT" */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004591 ignoresig(SIGINT);
4592 ignoresig(SIGQUIT);
4593 if (jp->nprocs == 0) {
4594 close(0);
4595 if (open(bb_dev_null, O_RDONLY) != 0)
Denis Vlasenko9604e1b2009-03-03 18:47:56 +00004596 ash_msg_and_raise_error("can't open '%s'", bb_dev_null);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004597 }
4598 }
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004599 if (!oldlvl) {
4600 if (iflag) { /* why if iflag only? */
4601 setsignal(SIGINT);
4602 setsignal(SIGTERM);
4603 }
4604 /* man bash:
4605 * "In all cases, bash ignores SIGQUIT. Non-builtin
4606 * commands run by bash have signal handlers
4607 * set to the values inherited by the shell
4608 * from its parent".
4609 * Take care of the second rule: */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004610 setsignal(SIGQUIT);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004611 }
Denys Vlasenkoe56f22a2009-07-24 00:16:59 +02004612#if JOBS
Denys Vlasenko844f9902009-09-23 03:25:52 +02004613 if (n && n->type == NCMD
4614 && strcmp(n->ncmd.args->narg.text, "jobs") == 0
4615 ) {
Denys Vlasenkoe56f22a2009-07-24 00:16:59 +02004616 TRACE(("Job hack\n"));
Denys Vlasenko844f9902009-09-23 03:25:52 +02004617 /* "jobs": we do not want to clear job list for it,
4618 * instead we remove only _its_ own_ job from job list.
4619 * This makes "jobs .... | cat" more useful.
4620 */
Denys Vlasenkoe56f22a2009-07-24 00:16:59 +02004621 freejob(curjob);
4622 return;
4623 }
4624#endif
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004625 for (jp = curjob; jp; jp = jp->prev_job)
4626 freejob(jp);
4627 jobless = 0;
4628}
4629
Denis Vlasenkobdc406d2007-07-15 01:13:25 +00004630/* Called after fork(), in parent */
Denis Vlasenko85c24712008-03-17 09:04:04 +00004631#if !JOBS
4632#define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
4633#endif
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004634static void
4635forkparent(struct job *jp, union node *n, int mode, pid_t pid)
4636{
4637 TRACE(("In parent shell: child = %d\n", pid));
4638 if (!jp) {
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00004639 while (jobless && dowait(DOWAIT_NONBLOCK, NULL) > 0)
4640 continue;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004641 jobless++;
4642 return;
4643 }
4644#if JOBS
4645 if (mode != FORK_NOJOB && jp->jobctl) {
4646 int pgrp;
4647
4648 if (jp->nprocs == 0)
4649 pgrp = pid;
4650 else
Denys Vlasenko285ad152009-12-04 23:02:27 +01004651 pgrp = jp->ps[0].ps_pid;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004652 /* This can fail because we are doing it in the child also */
4653 setpgid(pid, pgrp);
4654 }
4655#endif
4656 if (mode == FORK_BG) {
4657 backgndpid = pid; /* set $! */
4658 set_curjob(jp, CUR_RUNNING);
4659 }
4660 if (jp) {
4661 struct procstat *ps = &jp->ps[jp->nprocs++];
Denys Vlasenko285ad152009-12-04 23:02:27 +01004662 ps->ps_pid = pid;
4663 ps->ps_status = -1;
4664 ps->ps_cmd = nullstr;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004665#if JOBS
Denis Vlasenkob07a4962008-06-22 13:16:23 +00004666 if (doing_jobctl && n)
Denys Vlasenko285ad152009-12-04 23:02:27 +01004667 ps->ps_cmd = commandtext(n);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004668#endif
4669 }
4670}
4671
4672static int
4673forkshell(struct job *jp, union node *n, int mode)
4674{
4675 int pid;
4676
4677 TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
4678 pid = fork();
4679 if (pid < 0) {
4680 TRACE(("Fork failed, errno=%d", errno));
4681 if (jp)
4682 freejob(jp);
Denis Vlasenkofa0b56d2008-07-01 16:09:07 +00004683 ash_msg_and_raise_error("can't fork");
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004684 }
Denys Vlasenko76ace252009-10-12 15:25:01 +02004685 if (pid == 0) {
4686 CLEAR_RANDOM_T(&random_gen); /* or else $RANDOM repeats in child */
Denys Vlasenkoe56f22a2009-07-24 00:16:59 +02004687 forkchild(jp, n, mode);
Denys Vlasenko76ace252009-10-12 15:25:01 +02004688 } else {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004689 forkparent(jp, n, mode, pid);
Denys Vlasenko76ace252009-10-12 15:25:01 +02004690 }
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004691 return pid;
4692}
4693
4694/*
4695 * Wait for job to finish.
4696 *
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004697 * Under job control we have the problem that while a child process
4698 * is running interrupts generated by the user are sent to the child
4699 * but not to the shell. This means that an infinite loop started by
4700 * an interactive user may be hard to kill. With job control turned off,
4701 * an interactive user may place an interactive program inside a loop.
4702 * If the interactive program catches interrupts, the user doesn't want
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004703 * these interrupts to also abort the loop. The approach we take here
4704 * is to have the shell ignore interrupt signals while waiting for a
4705 * foreground process to terminate, and then send itself an interrupt
4706 * signal if the child process was terminated by an interrupt signal.
4707 * Unfortunately, some programs want to do a bit of cleanup and then
4708 * exit on interrupt; unless these processes terminate themselves by
4709 * sending a signal to themselves (instead of calling exit) they will
4710 * confuse this approach.
4711 *
4712 * Called with interrupts off.
4713 */
4714static int
4715waitforjob(struct job *jp)
4716{
4717 int st;
4718
4719 TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004720
4721 INT_OFF;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004722 while (jp->state == JOBRUNNING) {
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004723 /* In non-interactive shells, we _can_ get
4724 * a keyboard signal here and be EINTRed,
4725 * but we just loop back, waiting for command to complete.
4726 *
4727 * man bash:
4728 * "If bash is waiting for a command to complete and receives
4729 * a signal for which a trap has been set, the trap
4730 * will not be executed until the command completes."
4731 *
4732 * Reality is that even if trap is not set, bash
4733 * will not act on the signal until command completes.
4734 * Try this. sleep5intoff.c:
4735 * #include <signal.h>
4736 * #include <unistd.h>
4737 * int main() {
4738 * sigset_t set;
4739 * sigemptyset(&set);
4740 * sigaddset(&set, SIGINT);
4741 * sigaddset(&set, SIGQUIT);
4742 * sigprocmask(SIG_BLOCK, &set, NULL);
4743 * sleep(5);
4744 * return 0;
4745 * }
4746 * $ bash -c './sleep5intoff; echo hi'
4747 * ^C^C^C^C <--- pressing ^C once a second
4748 * $ _
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004749 * $ bash -c './sleep5intoff; echo hi'
4750 * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
4751 * $ _
4752 */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004753 dowait(DOWAIT_BLOCK, jp);
4754 }
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004755 INT_ON;
4756
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004757 st = getstatus(jp);
4758#if JOBS
4759 if (jp->jobctl) {
4760 xtcsetpgrp(ttyfd, rootpid);
4761 /*
4762 * This is truly gross.
4763 * If we're doing job control, then we did a TIOCSPGRP which
4764 * caused us (the shell) to no longer be in the controlling
4765 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
4766 * intuit from the subprocess exit status whether a SIGINT
4767 * occurred, and if so interrupt ourselves. Yuck. - mycroft
4768 */
Denis Vlasenko991a1da2008-02-10 19:02:53 +00004769 if (jp->sigint) /* TODO: do the same with all signals */
4770 raise(SIGINT); /* ... by raise(jp->sig) instead? */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004771 }
4772 if (jp->state == JOBDONE)
4773#endif
4774 freejob(jp);
4775 return st;
4776}
4777
4778/*
4779 * return 1 if there are stopped jobs, otherwise 0
4780 */
4781static int
4782stoppedjobs(void)
4783{
4784 struct job *jp;
4785 int retval;
4786
4787 retval = 0;
4788 if (job_warning)
4789 goto out;
4790 jp = curjob;
4791 if (jp && jp->state == JOBSTOPPED) {
4792 out2str("You have stopped jobs.\n");
4793 job_warning = 2;
4794 retval++;
4795 }
4796 out:
4797 return retval;
4798}
4799
4800
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004801/* ============ redir.c
4802 *
4803 * Code for dealing with input/output redirection.
4804 */
4805
4806#define EMPTY -2 /* marks an unused slot in redirtab */
Denis Vlasenko7d75a962007-11-22 08:16:57 +00004807#define CLOSED -3 /* marks a slot of previously-closed fd */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004808
4809/*
4810 * Open a file in noclobber mode.
4811 * The code was copied from bash.
4812 */
4813static int
4814noclobberopen(const char *fname)
4815{
4816 int r, fd;
4817 struct stat finfo, finfo2;
4818
4819 /*
4820 * If the file exists and is a regular file, return an error
4821 * immediately.
4822 */
4823 r = stat(fname, &finfo);
4824 if (r == 0 && S_ISREG(finfo.st_mode)) {
4825 errno = EEXIST;
4826 return -1;
4827 }
4828
4829 /*
4830 * If the file was not present (r != 0), make sure we open it
4831 * exclusively so that if it is created before we open it, our open
4832 * will fail. Make sure that we do not truncate an existing file.
4833 * Note that we don't turn on O_EXCL unless the stat failed -- if the
4834 * file was not a regular file, we leave O_EXCL off.
4835 */
4836 if (r != 0)
4837 return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
4838 fd = open(fname, O_WRONLY|O_CREAT, 0666);
4839
4840 /* If the open failed, return the file descriptor right away. */
4841 if (fd < 0)
4842 return fd;
4843
4844 /*
4845 * OK, the open succeeded, but the file may have been changed from a
4846 * non-regular file to a regular file between the stat and the open.
4847 * We are assuming that the O_EXCL open handles the case where FILENAME
4848 * did not exist and is symlinked to an existing file between the stat
4849 * and open.
4850 */
4851
4852 /*
4853 * If we can open it and fstat the file descriptor, and neither check
4854 * revealed that it was a regular file, and the file has not been
4855 * replaced, return the file descriptor.
4856 */
4857 if (fstat(fd, &finfo2) == 0 && !S_ISREG(finfo2.st_mode)
4858 && finfo.st_dev == finfo2.st_dev && finfo.st_ino == finfo2.st_ino)
4859 return fd;
4860
4861 /* The file has been replaced. badness. */
4862 close(fd);
4863 errno = EEXIST;
4864 return -1;
4865}
4866
4867/*
4868 * Handle here documents. Normally we fork off a process to write the
4869 * data to a pipe. If the document is short, we can stuff the data in
4870 * the pipe without forking.
4871 */
4872/* openhere needs this forward reference */
4873static void expandhere(union node *arg, int fd);
4874static int
4875openhere(union node *redir)
4876{
4877 int pip[2];
4878 size_t len = 0;
4879
4880 if (pipe(pip) < 0)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00004881 ash_msg_and_raise_error("pipe call failed");
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004882 if (redir->type == NHERE) {
4883 len = strlen(redir->nhere.doc->narg.text);
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00004884 if (len <= PIPE_BUF) {
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004885 full_write(pip[1], redir->nhere.doc->narg.text, len);
4886 goto out;
4887 }
4888 }
4889 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
Denis Vlasenko0b769642008-07-24 07:54:57 +00004890 /* child */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004891 close(pip[0]);
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004892 ignoresig(SIGINT); //signal(SIGINT, SIG_IGN);
4893 ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
4894 ignoresig(SIGHUP); //signal(SIGHUP, SIG_IGN);
4895 ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004896 signal(SIGPIPE, SIG_DFL);
4897 if (redir->type == NHERE)
4898 full_write(pip[1], redir->nhere.doc->narg.text, len);
Denis Vlasenko0b769642008-07-24 07:54:57 +00004899 else /* NXHERE */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004900 expandhere(redir->nhere.doc, pip[1]);
Bernhard Reutner-Fischer636a1f82008-05-19 09:29:47 +00004901 _exit(EXIT_SUCCESS);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004902 }
4903 out:
4904 close(pip[1]);
4905 return pip[0];
4906}
4907
4908static int
4909openredirect(union node *redir)
4910{
4911 char *fname;
4912 int f;
4913
4914 switch (redir->nfile.type) {
4915 case NFROM:
4916 fname = redir->nfile.expfname;
4917 f = open(fname, O_RDONLY);
4918 if (f < 0)
4919 goto eopen;
4920 break;
4921 case NFROMTO:
4922 fname = redir->nfile.expfname;
4923 f = open(fname, O_RDWR|O_CREAT|O_TRUNC, 0666);
4924 if (f < 0)
4925 goto ecreate;
4926 break;
4927 case NTO:
Denis Vlasenko559691a2008-10-05 18:39:31 +00004928#if ENABLE_ASH_BASH_COMPAT
4929 case NTO2:
4930#endif
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004931 /* Take care of noclobber mode. */
4932 if (Cflag) {
4933 fname = redir->nfile.expfname;
4934 f = noclobberopen(fname);
4935 if (f < 0)
4936 goto ecreate;
4937 break;
4938 }
4939 /* FALLTHROUGH */
4940 case NCLOBBER:
4941 fname = redir->nfile.expfname;
4942 f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
4943 if (f < 0)
4944 goto ecreate;
4945 break;
4946 case NAPPEND:
4947 fname = redir->nfile.expfname;
4948 f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
4949 if (f < 0)
4950 goto ecreate;
4951 break;
4952 default:
4953#if DEBUG
4954 abort();
4955#endif
4956 /* Fall through to eliminate warning. */
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00004957/* Our single caller does this itself */
Denis Vlasenko0b769642008-07-24 07:54:57 +00004958// case NTOFD:
4959// case NFROMFD:
4960// f = -1;
4961// break;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004962 case NHERE:
4963 case NXHERE:
4964 f = openhere(redir);
4965 break;
4966 }
4967
4968 return f;
4969 ecreate:
Bernhard Reutner-Fischera53de7f2008-07-21 13:46:54 +00004970 ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004971 eopen:
Bernhard Reutner-Fischera53de7f2008-07-21 13:46:54 +00004972 ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004973}
4974
4975/*
4976 * Copy a file descriptor to be >= to. Returns -1
4977 * if the source file descriptor is closed, EMPTY if there are no unused
4978 * file descriptors left.
4979 */
Denis Vlasenko5a867312008-07-24 19:46:38 +00004980/* 0x800..00: bit to set in "to" to request dup2 instead of fcntl(F_DUPFD).
4981 * old code was doing close(to) prior to copyfd() to achieve the same */
Denis Vlasenko22f74142008-07-24 22:34:43 +00004982enum {
4983 COPYFD_EXACT = (int)~(INT_MAX),
4984 COPYFD_RESTORE = (int)((unsigned)COPYFD_EXACT >> 1),
4985};
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004986static int
4987copyfd(int from, int to)
4988{
4989 int newfd;
4990
Denis Vlasenko5a867312008-07-24 19:46:38 +00004991 if (to & COPYFD_EXACT) {
4992 to &= ~COPYFD_EXACT;
4993 /*if (from != to)*/
4994 newfd = dup2(from, to);
4995 } else {
4996 newfd = fcntl(from, F_DUPFD, to);
4997 }
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004998 if (newfd < 0) {
4999 if (errno == EMFILE)
5000 return EMPTY;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005001 /* Happens when source fd is not open: try "echo >&99" */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005002 ash_msg_and_raise_error("%d: %m", from);
5003 }
5004 return newfd;
5005}
5006
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005007/* Struct def and variable are moved down to the first usage site */
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005008struct two_fd_t {
5009 int orig, copy;
5010};
Denis Vlasenko0b769642008-07-24 07:54:57 +00005011struct redirtab {
5012 struct redirtab *next;
Denis Vlasenko0b769642008-07-24 07:54:57 +00005013 int nullredirs;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005014 int pair_count;
Denys Vlasenko606291b2009-09-23 23:15:43 +02005015 struct two_fd_t two_fd[];
Denis Vlasenko0b769642008-07-24 07:54:57 +00005016};
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005017#define redirlist (G_var.redirlist)
Denis Vlasenko0b769642008-07-24 07:54:57 +00005018
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005019static int need_to_remember(struct redirtab *rp, int fd)
5020{
5021 int i;
5022
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005023 if (!rp) /* remembering was not requested */
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005024 return 0;
5025
5026 for (i = 0; i < rp->pair_count; i++) {
5027 if (rp->two_fd[i].orig == fd) {
5028 /* already remembered */
5029 return 0;
5030 }
5031 }
5032 return 1;
5033}
5034
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005035/* "hidden" fd is a fd used to read scripts, or a copy of such */
5036static int is_hidden_fd(struct redirtab *rp, int fd)
5037{
5038 int i;
Denis Vlasenko34c73c42008-08-16 11:48:02 +00005039 struct parsefile *pf;
5040
5041 if (fd == -1)
5042 return 0;
5043 pf = g_parsefile;
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005044 while (pf) {
5045 if (fd == pf->fd) {
5046 return 1;
5047 }
5048 pf = pf->prev;
5049 }
5050 if (!rp)
5051 return 0;
5052 fd |= COPYFD_RESTORE;
5053 for (i = 0; i < rp->pair_count; i++) {
5054 if (rp->two_fd[i].copy == fd) {
5055 return 1;
5056 }
5057 }
5058 return 0;
5059}
5060
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005061/*
5062 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
5063 * old file descriptors are stashed away so that the redirection can be
5064 * undone by calling popredir. If the REDIR_BACKQ flag is set, then the
5065 * standard output, and the standard error if it becomes a duplicate of
5066 * stdout, is saved in memory.
5067 */
5068/* flags passed to redirect */
5069#define REDIR_PUSH 01 /* save previous values of file descriptors */
5070#define REDIR_SAVEFD2 03 /* set preverrout */
5071static void
5072redirect(union node *redir, int flags)
5073{
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005074 struct redirtab *sv;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005075 int sv_pos;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005076 int i;
5077 int fd;
5078 int newfd;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005079 int copied_fd2 = -1;
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005080
Denis Vlasenko01631112007-12-16 17:20:38 +00005081 g_nullredirs++;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005082 if (!redir) {
5083 return;
5084 }
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005085
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005086 sv = NULL;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005087 sv_pos = 0;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005088 INT_OFF;
5089 if (flags & REDIR_PUSH) {
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005090 union node *tmp = redir;
5091 do {
5092 sv_pos++;
Denis Vlasenko559691a2008-10-05 18:39:31 +00005093#if ENABLE_ASH_BASH_COMPAT
5094 if (redir->nfile.type == NTO2)
5095 sv_pos++;
5096#endif
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005097 tmp = tmp->nfile.next;
5098 } while (tmp);
5099 sv = ckmalloc(sizeof(*sv) + sv_pos * sizeof(sv->two_fd[0]));
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005100 sv->next = redirlist;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005101 sv->pair_count = sv_pos;
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005102 redirlist = sv;
Denis Vlasenko01631112007-12-16 17:20:38 +00005103 sv->nullredirs = g_nullredirs - 1;
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005104 g_nullredirs = 0;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005105 while (sv_pos > 0) {
5106 sv_pos--;
5107 sv->two_fd[sv_pos].orig = sv->two_fd[sv_pos].copy = EMPTY;
5108 }
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005109 }
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005110
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005111 do {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00005112 fd = redir->nfile.fd;
Denis Vlasenko0b769642008-07-24 07:54:57 +00005113 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005114 int right_fd = redir->ndup.dupfd;
5115 /* redirect from/to same file descriptor? */
5116 if (right_fd == fd)
5117 continue;
5118 /* echo >&10 and 10 is a fd opened to the sh script? */
5119 if (is_hidden_fd(sv, right_fd)) {
5120 errno = EBADF; /* as if it is closed */
5121 ash_msg_and_raise_error("%d: %m", right_fd);
5122 }
Denis Vlasenko0b769642008-07-24 07:54:57 +00005123 newfd = -1;
5124 } else {
5125 newfd = openredirect(redir); /* always >= 0 */
5126 if (fd == newfd) {
5127 /* Descriptor wasn't open before redirect.
5128 * Mark it for close in the future */
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005129 if (need_to_remember(sv, fd)) {
Denis Vlasenko5a867312008-07-24 19:46:38 +00005130 goto remember_to_close;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005131 }
Denis Vlasenko0b769642008-07-24 07:54:57 +00005132 continue;
5133 }
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005134 }
Denis Vlasenko559691a2008-10-05 18:39:31 +00005135#if ENABLE_ASH_BASH_COMPAT
5136 redirect_more:
5137#endif
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005138 if (need_to_remember(sv, fd)) {
Denis Vlasenko0b769642008-07-24 07:54:57 +00005139 /* Copy old descriptor */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005140 i = fcntl(fd, F_DUPFD, 10);
Denis Vlasenko5a867312008-07-24 19:46:38 +00005141/* You'd expect copy to be CLOEXECed. Currently these extra "saved" fds
5142 * are closed in popredir() in the child, preventing them from leaking
5143 * into child. (popredir() also cleans up the mess in case of failures)
5144 */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005145 if (i == -1) {
5146 i = errno;
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005147 if (i != EBADF) {
5148 /* Strange error (e.g. "too many files" EMFILE?) */
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005149 if (newfd >= 0)
5150 close(newfd);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005151 errno = i;
5152 ash_msg_and_raise_error("%d: %m", fd);
5153 /* NOTREACHED */
5154 }
Denis Vlasenko5a867312008-07-24 19:46:38 +00005155 /* EBADF: it is not open - good, remember to close it */
5156 remember_to_close:
5157 i = CLOSED;
Denis Vlasenko22f74142008-07-24 22:34:43 +00005158 } else { /* fd is open, save its copy */
5159 /* "exec fd>&-" should not close fds
5160 * which point to script file(s).
5161 * Force them to be restored afterwards */
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005162 if (is_hidden_fd(sv, fd))
5163 i |= COPYFD_RESTORE;
Denis Vlasenko22f74142008-07-24 22:34:43 +00005164 }
Denis Vlasenko5a867312008-07-24 19:46:38 +00005165 if (fd == 2)
5166 copied_fd2 = i;
5167 sv->two_fd[sv_pos].orig = fd;
5168 sv->two_fd[sv_pos].copy = i;
5169 sv_pos++;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005170 }
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005171 if (newfd < 0) {
5172 /* NTOFD/NFROMFD: copy redir->ndup.dupfd to fd */
Denis Vlasenko22f74142008-07-24 22:34:43 +00005173 if (redir->ndup.dupfd < 0) { /* "fd>&-" */
Denis Vlasenkob9e70dd2009-03-20 01:24:08 +00005174 /* Don't want to trigger debugging */
5175 if (fd != -1)
5176 close(fd);
Denis Vlasenko5a867312008-07-24 19:46:38 +00005177 } else {
5178 copyfd(redir->ndup.dupfd, fd | COPYFD_EXACT);
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005179 }
Denis Vlasenko5a867312008-07-24 19:46:38 +00005180 } else if (fd != newfd) { /* move newfd to fd */
5181 copyfd(newfd, fd | COPYFD_EXACT);
Denis Vlasenko559691a2008-10-05 18:39:31 +00005182#if ENABLE_ASH_BASH_COMPAT
5183 if (!(redir->nfile.type == NTO2 && fd == 2))
5184#endif
5185 close(newfd);
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005186 }
Denis Vlasenko559691a2008-10-05 18:39:31 +00005187#if ENABLE_ASH_BASH_COMPAT
5188 if (redir->nfile.type == NTO2 && fd == 1) {
5189 /* We already redirected it to fd 1, now copy it to 2 */
5190 newfd = 1;
5191 fd = 2;
5192 goto redirect_more;
5193 }
5194#endif
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00005195 } while ((redir = redir->nfile.next) != NULL);
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005196
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005197 INT_ON;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005198 if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
5199 preverrout_fd = copied_fd2;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005200}
5201
5202/*
5203 * Undo the effects of the last redirection.
5204 */
5205static void
Denis Vlasenko34c73c42008-08-16 11:48:02 +00005206popredir(int drop, int restore)
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005207{
5208 struct redirtab *rp;
5209 int i;
5210
Denis Vlasenko01631112007-12-16 17:20:38 +00005211 if (--g_nullredirs >= 0)
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005212 return;
5213 INT_OFF;
5214 rp = redirlist;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005215 for (i = 0; i < rp->pair_count; i++) {
5216 int fd = rp->two_fd[i].orig;
Denis Vlasenko22f74142008-07-24 22:34:43 +00005217 int copy = rp->two_fd[i].copy;
5218 if (copy == CLOSED) {
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005219 if (!drop)
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005220 close(fd);
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005221 continue;
5222 }
Denis Vlasenko22f74142008-07-24 22:34:43 +00005223 if (copy != EMPTY) {
Denis Vlasenko34c73c42008-08-16 11:48:02 +00005224 if (!drop || (restore && (copy & COPYFD_RESTORE))) {
Denis Vlasenko22f74142008-07-24 22:34:43 +00005225 copy &= ~COPYFD_RESTORE;
Denis Vlasenko5a867312008-07-24 19:46:38 +00005226 /*close(fd);*/
Denis Vlasenko22f74142008-07-24 22:34:43 +00005227 copyfd(copy, fd | COPYFD_EXACT);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005228 }
Denis Vlasenkob9e70dd2009-03-20 01:24:08 +00005229 close(copy & ~COPYFD_RESTORE);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005230 }
5231 }
5232 redirlist = rp->next;
Denis Vlasenko01631112007-12-16 17:20:38 +00005233 g_nullredirs = rp->nullredirs;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005234 free(rp);
5235 INT_ON;
5236}
5237
5238/*
5239 * Undo all redirections. Called on error or interrupt.
5240 */
5241
5242/*
5243 * Discard all saved file descriptors.
5244 */
5245static void
5246clearredir(int drop)
5247{
5248 for (;;) {
Denis Vlasenko01631112007-12-16 17:20:38 +00005249 g_nullredirs = 0;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005250 if (!redirlist)
5251 break;
Denis Vlasenko34c73c42008-08-16 11:48:02 +00005252 popredir(drop, /*restore:*/ 0);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005253 }
5254}
5255
5256static int
5257redirectsafe(union node *redir, int flags)
5258{
5259 int err;
5260 volatile int saveint;
5261 struct jmploc *volatile savehandler = exception_handler;
5262 struct jmploc jmploc;
5263
5264 SAVE_INT(saveint);
Denis Vlasenko5a867312008-07-24 19:46:38 +00005265 /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
5266 err = setjmp(jmploc.loc); // huh?? was = setjmp(jmploc.loc) * 2;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005267 if (!err) {
5268 exception_handler = &jmploc;
5269 redirect(redir, flags);
5270 }
5271 exception_handler = savehandler;
Denis Vlasenko7f88e342009-03-19 03:36:18 +00005272 if (err && exception_type != EXERROR)
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005273 longjmp(exception_handler->loc, 1);
5274 RESTORE_INT(saveint);
5275 return err;
5276}
5277
5278
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005279/* ============ Routines to expand arguments to commands
5280 *
5281 * We have to deal with backquotes, shell variables, and file metacharacters.
5282 */
5283
Mike Frysinger98c52642009-04-02 10:02:37 +00005284#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00005285static arith_t
5286ash_arith(const char *s)
5287{
5288 arith_eval_hooks_t math_hooks;
5289 arith_t result;
5290 int errcode = 0;
5291
5292 math_hooks.lookupvar = lookupvar;
5293 math_hooks.setvar = setvar;
5294 math_hooks.endofname = endofname;
5295
5296 INT_OFF;
5297 result = arith(s, &errcode, &math_hooks);
5298 if (errcode < 0) {
5299 if (errcode == -3)
5300 ash_msg_and_raise_error("exponent less than 0");
5301 if (errcode == -2)
5302 ash_msg_and_raise_error("divide by zero");
5303 if (errcode == -5)
5304 ash_msg_and_raise_error("expression recursion loop detected");
5305 raise_error_syntax(s);
5306 }
5307 INT_ON;
5308
5309 return result;
5310}
Denis Vlasenko448d30e2008-06-27 00:24:11 +00005311#endif
5312
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005313/*
5314 * expandarg flags
5315 */
5316#define EXP_FULL 0x1 /* perform word splitting & file globbing */
5317#define EXP_TILDE 0x2 /* do normal tilde expansion */
5318#define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
5319#define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
5320#define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
5321#define EXP_RECORD 0x20 /* need to record arguments for ifs breakup */
5322#define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
5323#define EXP_WORD 0x80 /* expand word in parameter expansion */
5324#define EXP_QWORD 0x100 /* expand word in quoted parameter expansion */
5325/*
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005326 * rmescape() flags
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005327 */
5328#define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
5329#define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
5330#define RMESCAPE_QUOTED 0x4 /* Remove CTLESC unless in quotes */
5331#define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
5332#define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
5333
5334/*
5335 * Structure specifying which parts of the string should be searched
5336 * for IFS characters.
5337 */
5338struct ifsregion {
5339 struct ifsregion *next; /* next region in list */
5340 int begoff; /* offset of start of region */
5341 int endoff; /* offset of end of region */
5342 int nulonly; /* search for nul bytes only */
5343};
5344
5345struct arglist {
5346 struct strlist *list;
5347 struct strlist **lastp;
5348};
5349
5350/* output of current string */
5351static char *expdest;
5352/* list of back quote expressions */
5353static struct nodelist *argbackq;
5354/* first struct in list of ifs regions */
5355static struct ifsregion ifsfirst;
5356/* last struct in list */
5357static struct ifsregion *ifslastp;
5358/* holds expanded arg list */
5359static struct arglist exparg;
5360
5361/*
5362 * Our own itoa().
5363 */
5364static int
5365cvtnum(arith_t num)
5366{
5367 int len;
5368
5369 expdest = makestrspace(32, expdest);
Mike Frysinger98c52642009-04-02 10:02:37 +00005370 len = fmtstr(expdest, 32, arith_t_fmt, num);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005371 STADJUST(len, expdest);
5372 return len;
5373}
5374
5375static size_t
5376esclen(const char *start, const char *p)
5377{
5378 size_t esc = 0;
5379
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005380 while (p > start && (unsigned char)*--p == CTLESC) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005381 esc++;
5382 }
5383 return esc;
5384}
5385
5386/*
5387 * Remove any CTLESC characters from a string.
5388 */
5389static char *
Denys Vlasenkob6c84342009-08-29 20:23:20 +02005390rmescapes(char *str, int flag)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005391{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00005392 static const char qchars[] ALIGN1 = { CTLESC, CTLQUOTEMARK, '\0' };
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00005393
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005394 char *p, *q, *r;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005395 unsigned inquotes;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005396 unsigned protect_against_glob;
5397 unsigned globbing;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005398
5399 p = strpbrk(str, qchars);
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005400 if (!p)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005401 return str;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005402
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005403 q = p;
5404 r = str;
5405 if (flag & RMESCAPE_ALLOC) {
5406 size_t len = p - str;
5407 size_t fulllen = len + strlen(p) + 1;
5408
5409 if (flag & RMESCAPE_GROW) {
5410 r = makestrspace(fulllen, expdest);
5411 } else if (flag & RMESCAPE_HEAP) {
5412 r = ckmalloc(fulllen);
5413 } else {
5414 r = stalloc(fulllen);
5415 }
5416 q = r;
5417 if (len > 0) {
Denis Vlasenko29eb3592008-05-18 14:06:08 +00005418 q = (char *)memcpy(q, str, len) + len;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005419 }
5420 }
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005421
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005422 inquotes = (flag & RMESCAPE_QUOTED) ^ RMESCAPE_QUOTED;
5423 globbing = flag & RMESCAPE_GLOB;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005424 protect_against_glob = globbing;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005425 while (*p) {
Denys Vlasenkocd716832009-11-28 22:14:02 +01005426 if ((unsigned char)*p == CTLQUOTEMARK) {
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005427// TODO: if no RMESCAPE_QUOTED in flags, inquotes never becomes 0
5428// (alternates between RMESCAPE_QUOTED and ~RMESCAPE_QUOTED). Is it ok?
5429// Note: both inquotes and protect_against_glob only affect whether
5430// CTLESC,<ch> gets converted to <ch> or to \<ch>
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005431 inquotes = ~inquotes;
5432 p++;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005433 protect_against_glob = globbing;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005434 continue;
5435 }
5436 if (*p == '\\') {
5437 /* naked back slash */
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005438 protect_against_glob = 0;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005439 goto copy;
5440 }
Denys Vlasenkocd716832009-11-28 22:14:02 +01005441 if ((unsigned char)*p == CTLESC) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005442 p++;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005443 if (protect_against_glob && inquotes && *p != '/') {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005444 *q++ = '\\';
5445 }
5446 }
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005447 protect_against_glob = globbing;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005448 copy:
5449 *q++ = *p++;
5450 }
5451 *q = '\0';
5452 if (flag & RMESCAPE_GROW) {
5453 expdest = r;
5454 STADJUST(q - r + 1, expdest);
5455 }
5456 return r;
5457}
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005458#define pmatch(a, b) !fnmatch((a), (b), 0)
5459
5460/*
5461 * Prepare a pattern for a expmeta (internal glob(3)) call.
5462 *
5463 * Returns an stalloced string.
5464 */
5465static char *
5466preglob(const char *pattern, int quoted, int flag)
5467{
5468 flag |= RMESCAPE_GLOB;
5469 if (quoted) {
5470 flag |= RMESCAPE_QUOTED;
5471 }
Denys Vlasenkob6c84342009-08-29 20:23:20 +02005472 return rmescapes((char *)pattern, flag);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005473}
5474
5475/*
5476 * Put a string on the stack.
5477 */
5478static void
5479memtodest(const char *p, size_t len, int syntax, int quotes)
5480{
5481 char *q = expdest;
5482
Denys Vlasenkob6c84342009-08-29 20:23:20 +02005483 q = makestrspace(quotes ? len * 2 : len, q);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005484
5485 while (len--) {
Denys Vlasenkocd716832009-11-28 22:14:02 +01005486 unsigned char c = *p++;
5487 if (c == '\0')
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005488 continue;
Denys Vlasenkob6c84342009-08-29 20:23:20 +02005489 if (quotes) {
5490 int n = SIT(c, syntax);
5491 if (n == CCTL || n == CBACK)
5492 USTPUTC(CTLESC, q);
5493 }
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005494 USTPUTC(c, q);
5495 }
5496
5497 expdest = q;
5498}
5499
5500static void
5501strtodest(const char *p, int syntax, int quotes)
5502{
5503 memtodest(p, strlen(p), syntax, quotes);
5504}
5505
5506/*
5507 * Record the fact that we have to scan this region of the
5508 * string for IFS characters.
5509 */
5510static void
5511recordregion(int start, int end, int nulonly)
5512{
5513 struct ifsregion *ifsp;
5514
5515 if (ifslastp == NULL) {
5516 ifsp = &ifsfirst;
5517 } else {
5518 INT_OFF;
Denis Vlasenko597906c2008-02-20 16:38:54 +00005519 ifsp = ckzalloc(sizeof(*ifsp));
5520 /*ifsp->next = NULL; - ckzalloc did it */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005521 ifslastp->next = ifsp;
5522 INT_ON;
5523 }
5524 ifslastp = ifsp;
5525 ifslastp->begoff = start;
5526 ifslastp->endoff = end;
5527 ifslastp->nulonly = nulonly;
5528}
5529
5530static void
5531removerecordregions(int endoff)
5532{
5533 if (ifslastp == NULL)
5534 return;
5535
5536 if (ifsfirst.endoff > endoff) {
5537 while (ifsfirst.next != NULL) {
5538 struct ifsregion *ifsp;
5539 INT_OFF;
5540 ifsp = ifsfirst.next->next;
5541 free(ifsfirst.next);
5542 ifsfirst.next = ifsp;
5543 INT_ON;
5544 }
5545 if (ifsfirst.begoff > endoff)
5546 ifslastp = NULL;
5547 else {
5548 ifslastp = &ifsfirst;
5549 ifsfirst.endoff = endoff;
5550 }
5551 return;
5552 }
5553
5554 ifslastp = &ifsfirst;
5555 while (ifslastp->next && ifslastp->next->begoff < endoff)
5556 ifslastp=ifslastp->next;
5557 while (ifslastp->next != NULL) {
5558 struct ifsregion *ifsp;
5559 INT_OFF;
5560 ifsp = ifslastp->next->next;
5561 free(ifslastp->next);
5562 ifslastp->next = ifsp;
5563 INT_ON;
5564 }
5565 if (ifslastp->endoff > endoff)
5566 ifslastp->endoff = endoff;
5567}
5568
5569static char *
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005570exptilde(char *startp, char *p, int flags)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005571{
Denys Vlasenkocd716832009-11-28 22:14:02 +01005572 unsigned char c;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005573 char *name;
5574 struct passwd *pw;
5575 const char *home;
Denys Vlasenko1166d7b2009-09-16 16:20:31 +02005576 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005577 int startloc;
5578
5579 name = p + 1;
5580
5581 while ((c = *++p) != '\0') {
5582 switch (c) {
5583 case CTLESC:
5584 return startp;
5585 case CTLQUOTEMARK:
5586 return startp;
5587 case ':':
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005588 if (flags & EXP_VARTILDE)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005589 goto done;
5590 break;
5591 case '/':
5592 case CTLENDVAR:
5593 goto done;
5594 }
5595 }
5596 done:
5597 *p = '\0';
5598 if (*name == '\0') {
5599 home = lookupvar(homestr);
5600 } else {
5601 pw = getpwnam(name);
5602 if (pw == NULL)
5603 goto lose;
5604 home = pw->pw_dir;
5605 }
5606 if (!home || !*home)
5607 goto lose;
5608 *p = c;
5609 startloc = expdest - (char *)stackblock();
5610 strtodest(home, SQSYNTAX, quotes);
5611 recordregion(startloc, expdest - (char *)stackblock(), 0);
5612 return p;
5613 lose:
5614 *p = c;
5615 return startp;
5616}
5617
5618/*
5619 * Execute a command inside back quotes. If it's a builtin command, we
5620 * want to save its output in a block obtained from malloc. Otherwise
5621 * we fork off a subprocess and get the output of the command via a pipe.
5622 * Should be called with interrupts off.
5623 */
5624struct backcmd { /* result of evalbackcmd */
5625 int fd; /* file descriptor to read from */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005626 int nleft; /* number of chars in buffer */
Denis Vlasenkob07a4962008-06-22 13:16:23 +00005627 char *buf; /* buffer */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005628 struct job *jp; /* job structure for command */
5629};
5630
5631/* These forward decls are needed to use "eval" code for backticks handling: */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00005632static uint8_t back_exitstatus; /* exit status of backquoted command */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005633#define EV_EXIT 01 /* exit after evaluating tree */
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02005634static void evaltree(union node *, int);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005635
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02005636static void FAST_FUNC
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005637evalbackcmd(union node *n, struct backcmd *result)
5638{
5639 int saveherefd;
5640
5641 result->fd = -1;
5642 result->buf = NULL;
5643 result->nleft = 0;
5644 result->jp = NULL;
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00005645 if (n == NULL)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005646 goto out;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005647
5648 saveherefd = herefd;
5649 herefd = -1;
5650
5651 {
5652 int pip[2];
5653 struct job *jp;
5654
5655 if (pipe(pip) < 0)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00005656 ash_msg_and_raise_error("pipe call failed");
Denis Vlasenko68404f12008-03-17 09:00:54 +00005657 jp = makejob(/*n,*/ 1);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005658 if (forkshell(jp, n, FORK_NOJOB) == 0) {
5659 FORCE_INT_ON;
5660 close(pip[0]);
5661 if (pip[1] != 1) {
Denis Vlasenko5a867312008-07-24 19:46:38 +00005662 /*close(1);*/
5663 copyfd(pip[1], 1 | COPYFD_EXACT);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005664 close(pip[1]);
5665 }
5666 eflag = 0;
5667 evaltree(n, EV_EXIT); /* actually evaltreenr... */
5668 /* NOTREACHED */
5669 }
5670 close(pip[1]);
5671 result->fd = pip[0];
5672 result->jp = jp;
5673 }
5674 herefd = saveherefd;
5675 out:
5676 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
5677 result->fd, result->buf, result->nleft, result->jp));
5678}
5679
5680/*
5681 * Expand stuff in backwards quotes.
5682 */
5683static void
5684expbackq(union node *cmd, int quoted, int quotes)
5685{
5686 struct backcmd in;
5687 int i;
5688 char buf[128];
5689 char *p;
5690 char *dest;
5691 int startloc;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00005692 int syntax = quoted ? DQSYNTAX : BASESYNTAX;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005693 struct stackmark smark;
5694
5695 INT_OFF;
5696 setstackmark(&smark);
5697 dest = expdest;
5698 startloc = dest - (char *)stackblock();
5699 grabstackstr(dest);
5700 evalbackcmd(cmd, &in);
5701 popstackmark(&smark);
5702
5703 p = in.buf;
5704 i = in.nleft;
5705 if (i == 0)
5706 goto read;
5707 for (;;) {
5708 memtodest(p, i, syntax, quotes);
5709 read:
5710 if (in.fd < 0)
5711 break;
Denis Vlasenkoe376d452008-02-20 22:23:24 +00005712 i = nonblock_safe_read(in.fd, buf, sizeof(buf));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005713 TRACE(("expbackq: read returns %d\n", i));
5714 if (i <= 0)
5715 break;
5716 p = buf;
5717 }
5718
Denis Vlasenko60818682007-09-28 22:07:23 +00005719 free(in.buf);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005720 if (in.fd >= 0) {
5721 close(in.fd);
5722 back_exitstatus = waitforjob(in.jp);
5723 }
5724 INT_ON;
5725
5726 /* Eat all trailing newlines */
5727 dest = expdest;
5728 for (; dest > (char *)stackblock() && dest[-1] == '\n';)
5729 STUNPUTC(dest);
5730 expdest = dest;
5731
5732 if (quoted == 0)
5733 recordregion(startloc, dest - (char *)stackblock(), 0);
5734 TRACE(("evalbackq: size=%d: \"%.*s\"\n",
5735 (dest - (char *)stackblock()) - startloc,
5736 (dest - (char *)stackblock()) - startloc,
5737 stackblock() + startloc));
5738}
5739
Mike Frysinger98c52642009-04-02 10:02:37 +00005740#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005741/*
5742 * Expand arithmetic expression. Backup to start of expression,
5743 * evaluate, place result in (backed up) result, adjust string position.
5744 */
5745static void
5746expari(int quotes)
5747{
5748 char *p, *start;
5749 int begoff;
5750 int flag;
5751 int len;
5752
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00005753 /* ifsfree(); */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005754
5755 /*
5756 * This routine is slightly over-complicated for
5757 * efficiency. Next we scan backwards looking for the
5758 * start of arithmetic.
5759 */
5760 start = stackblock();
5761 p = expdest - 1;
5762 *p = '\0';
5763 p--;
5764 do {
5765 int esc;
5766
Denys Vlasenkocd716832009-11-28 22:14:02 +01005767 while ((unsigned char)*p != CTLARI) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005768 p--;
5769#if DEBUG
5770 if (p < start) {
5771 ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
5772 }
5773#endif
5774 }
5775
5776 esc = esclen(start, p);
5777 if (!(esc % 2)) {
5778 break;
5779 }
5780
5781 p -= esc + 1;
5782 } while (1);
5783
5784 begoff = p - start;
5785
5786 removerecordregions(begoff);
5787
5788 flag = p[1];
5789
5790 expdest = p;
5791
5792 if (quotes)
Denys Vlasenkob6c84342009-08-29 20:23:20 +02005793 rmescapes(p + 2, 0);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005794
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00005795 len = cvtnum(ash_arith(p + 2));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005796
5797 if (flag != '"')
5798 recordregion(begoff, begoff + len, 0);
5799}
5800#endif
5801
5802/* argstr needs it */
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005803static char *evalvar(char *p, int flags, struct strlist *var_str_list);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005804
5805/*
5806 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
5807 * characters to allow for further processing. Otherwise treat
5808 * $@ like $* since no splitting will be performed.
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00005809 *
5810 * var_str_list (can be NULL) is a list of "VAR=val" strings which take precedence
5811 * over shell varables. Needed for "A=a B=$A; echo $B" case - we use it
5812 * for correct expansion of "B=$A" word.
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005813 */
5814static void
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005815argstr(char *p, int flags, struct strlist *var_str_list)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005816{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00005817 static const char spclchars[] ALIGN1 = {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005818 '=',
5819 ':',
5820 CTLQUOTEMARK,
5821 CTLENDVAR,
5822 CTLESC,
5823 CTLVAR,
5824 CTLBACKQ,
5825 CTLBACKQ | CTLQUOTE,
Mike Frysinger98c52642009-04-02 10:02:37 +00005826#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005827 CTLENDARI,
5828#endif
Denys Vlasenkocd716832009-11-28 22:14:02 +01005829 '\0'
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005830 };
5831 const char *reject = spclchars;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005832 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR); /* do CTLESC */
5833 int breakall = flags & EXP_WORD;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005834 int inquotes;
5835 size_t length;
5836 int startloc;
5837
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005838 if (!(flags & EXP_VARTILDE)) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005839 reject += 2;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005840 } else if (flags & EXP_VARTILDE2) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005841 reject++;
5842 }
5843 inquotes = 0;
5844 length = 0;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005845 if (flags & EXP_TILDE) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005846 char *q;
5847
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005848 flags &= ~EXP_TILDE;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005849 tilde:
5850 q = p;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005851 if (*q == CTLESC && (flags & EXP_QWORD))
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005852 q++;
5853 if (*q == '~')
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005854 p = exptilde(p, q, flags);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005855 }
5856 start:
5857 startloc = expdest - (char *)stackblock();
5858 for (;;) {
Denys Vlasenkocd716832009-11-28 22:14:02 +01005859 unsigned char c;
5860
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005861 length += strcspn(p + length, reject);
Denys Vlasenkocd716832009-11-28 22:14:02 +01005862 c = p[length];
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005863 if (c) {
5864 if (!(c & 0x80)
Mike Frysinger98c52642009-04-02 10:02:37 +00005865#if ENABLE_SH_MATH_SUPPORT
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005866 || c == CTLENDARI
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005867#endif
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005868 ) {
5869 /* c == '=' || c == ':' || c == CTLENDARI */
5870 length++;
5871 }
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005872 }
5873 if (length > 0) {
5874 int newloc;
5875 expdest = stack_nputstr(p, length, expdest);
5876 newloc = expdest - (char *)stackblock();
5877 if (breakall && !inquotes && newloc > startloc) {
5878 recordregion(startloc, newloc, 0);
5879 }
5880 startloc = newloc;
5881 }
5882 p += length + 1;
5883 length = 0;
5884
5885 switch (c) {
5886 case '\0':
5887 goto breakloop;
5888 case '=':
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005889 if (flags & EXP_VARTILDE2) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005890 p--;
5891 continue;
5892 }
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005893 flags |= EXP_VARTILDE2;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005894 reject++;
5895 /* fall through */
5896 case ':':
5897 /*
5898 * sort of a hack - expand tildes in variable
5899 * assignments (after the first '=' and after ':'s).
5900 */
5901 if (*--p == '~') {
5902 goto tilde;
5903 }
5904 continue;
5905 }
5906
5907 switch (c) {
5908 case CTLENDVAR: /* ??? */
5909 goto breakloop;
5910 case CTLQUOTEMARK:
5911 /* "$@" syntax adherence hack */
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005912 if (!inquotes
5913 && memcmp(p, dolatstr, 4) == 0
5914 && ( p[4] == CTLQUOTEMARK
5915 || (p[4] == CTLENDVAR && p[5] == CTLQUOTEMARK)
5916 )
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005917 ) {
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005918 p = evalvar(p + 1, flags, /* var_str_list: */ NULL) + 1;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005919 goto start;
5920 }
5921 inquotes = !inquotes;
5922 addquote:
5923 if (quotes) {
5924 p--;
5925 length++;
5926 startloc++;
5927 }
5928 break;
5929 case CTLESC:
5930 startloc++;
5931 length++;
5932 goto addquote;
5933 case CTLVAR:
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005934 p = evalvar(p, flags, var_str_list);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005935 goto start;
5936 case CTLBACKQ:
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005937 c = '\0';
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005938 case CTLBACKQ|CTLQUOTE:
5939 expbackq(argbackq->n, c, quotes);
5940 argbackq = argbackq->next;
5941 goto start;
Mike Frysinger98c52642009-04-02 10:02:37 +00005942#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005943 case CTLENDARI:
5944 p--;
5945 expari(quotes);
5946 goto start;
5947#endif
5948 }
5949 }
5950 breakloop:
5951 ;
5952}
5953
5954static char *
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00005955scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM, char *str, int quotes,
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005956 int zero)
5957{
Denis Vlasenkoc7131c32008-04-14 01:59:53 +00005958// This commented out code was added by James Simmons <jsimmons@infradead.org>
5959// as part of a larger change when he added support for ${var/a/b}.
5960// However, it broke # and % operators:
5961//
5962//var=ababcdcd
5963// ok bad
5964//echo ${var#ab} abcdcd abcdcd
5965//echo ${var##ab} abcdcd abcdcd
5966//echo ${var#a*b} abcdcd ababcdcd (!)
5967//echo ${var##a*b} cdcd cdcd
5968//echo ${var#?} babcdcd ababcdcd (!)
5969//echo ${var##?} babcdcd babcdcd
5970//echo ${var#*} ababcdcd babcdcd (!)
5971//echo ${var##*}
5972//echo ${var%cd} ababcd ababcd
5973//echo ${var%%cd} ababcd abab (!)
5974//echo ${var%c*d} ababcd ababcd
5975//echo ${var%%c*d} abab ababcdcd (!)
5976//echo ${var%?} ababcdc ababcdc
5977//echo ${var%%?} ababcdc ababcdcd (!)
5978//echo ${var%*} ababcdcd ababcdcd
5979//echo ${var%%*}
5980//
5981// Commenting it back out helped. Remove it completely if it really
5982// is not needed.
5983
5984 char *loc, *loc2; //, *full;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005985 char c;
5986
5987 loc = startp;
5988 loc2 = rmesc;
5989 do {
Denis Vlasenkoc7131c32008-04-14 01:59:53 +00005990 int match; // = strlen(str);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005991 const char *s = loc2;
Denis Vlasenko92e13c22008-03-25 01:17:40 +00005992
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005993 c = *loc2;
5994 if (zero) {
5995 *loc2 = '\0';
5996 s = rmesc;
5997 }
Denis Vlasenkoc7131c32008-04-14 01:59:53 +00005998 match = pmatch(str, s); // this line was deleted
Denis Vlasenko92e13c22008-03-25 01:17:40 +00005999
Denis Vlasenkoc7131c32008-04-14 01:59:53 +00006000// // chop off end if its '*'
6001// full = strrchr(str, '*');
6002// if (full && full != str)
6003// match--;
6004//
6005// // If str starts with '*' replace with s.
6006// if ((*str == '*') && strlen(s) >= match) {
6007// full = xstrdup(s);
6008// strncpy(full+strlen(s)-match+1, str+1, match-1);
6009// } else
6010// full = xstrndup(str, match);
6011// match = strncmp(s, full, strlen(full));
6012// free(full);
6013//
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006014 *loc2 = c;
Denis Vlasenkoc7131c32008-04-14 01:59:53 +00006015 if (match) // if (!match)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006016 return loc;
Denys Vlasenkocd716832009-11-28 22:14:02 +01006017 if (quotes && (unsigned char)*loc == CTLESC)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006018 loc++;
6019 loc++;
6020 loc2++;
6021 } while (c);
6022 return 0;
6023}
6024
6025static char *
6026scanright(char *startp, char *rmesc, char *rmescend, char *str, int quotes,
6027 int zero)
6028{
6029 int esc = 0;
6030 char *loc;
6031 char *loc2;
6032
6033 for (loc = str - 1, loc2 = rmescend; loc >= startp; loc2--) {
6034 int match;
6035 char c = *loc2;
6036 const char *s = loc2;
6037 if (zero) {
6038 *loc2 = '\0';
6039 s = rmesc;
6040 }
6041 match = pmatch(str, s);
6042 *loc2 = c;
6043 if (match)
6044 return loc;
6045 loc--;
6046 if (quotes) {
6047 if (--esc < 0) {
6048 esc = esclen(startp, loc);
6049 }
6050 if (esc % 2) {
6051 esc--;
6052 loc--;
6053 }
6054 }
6055 }
6056 return 0;
6057}
6058
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00006059static void varunset(const char *, const char *, const char *, int) NORETURN;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006060static void
6061varunset(const char *end, const char *var, const char *umsg, int varflags)
6062{
6063 const char *msg;
6064 const char *tail;
6065
6066 tail = nullstr;
6067 msg = "parameter not set";
6068 if (umsg) {
Denys Vlasenkocd716832009-11-28 22:14:02 +01006069 if ((unsigned char)*end == CTLENDVAR) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006070 if (varflags & VSNUL)
6071 tail = " or null";
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00006072 } else {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006073 msg = umsg;
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00006074 }
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006075 }
6076 ash_msg_and_raise_error("%.*s: %s%s", end - var - 1, var, msg, tail);
6077}
6078
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006079#if ENABLE_ASH_BASH_COMPAT
6080static char *
6081parse_sub_pattern(char *arg, int inquotes)
6082{
6083 char *idx, *repl = NULL;
6084 unsigned char c;
6085
Denis Vlasenko2659c632008-06-14 06:04:59 +00006086 idx = arg;
6087 while (1) {
6088 c = *arg;
6089 if (!c)
6090 break;
6091 if (c == '/') {
6092 /* Only the first '/' seen is our separator */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006093 if (!repl) {
Denis Vlasenko2659c632008-06-14 06:04:59 +00006094 repl = idx + 1;
6095 c = '\0';
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006096 }
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006097 }
Denis Vlasenko2659c632008-06-14 06:04:59 +00006098 *idx++ = c;
6099 if (!inquotes && c == '\\' && arg[1] == '\\')
6100 arg++; /* skip both \\, not just first one */
6101 arg++;
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006102 }
Denis Vlasenko29038c02008-06-14 06:14:02 +00006103 *idx = c; /* NUL */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006104
6105 return repl;
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006106}
6107#endif /* ENABLE_ASH_BASH_COMPAT */
6108
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006109static const char *
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006110subevalvar(char *p, char *str, int strloc, int subtype,
6111 int startloc, int varflags, int quotes, struct strlist *var_str_list)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006112{
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006113 struct nodelist *saveargbackq = argbackq;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006114 char *startp;
6115 char *loc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006116 char *rmesc, *rmescend;
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00006117 IF_ASH_BASH_COMPAT(char *repl = NULL;)
6118 IF_ASH_BASH_COMPAT(char null = '\0';)
6119 IF_ASH_BASH_COMPAT(int pos, len, orig_len;)
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006120 int saveherefd = herefd;
6121 int amount, workloc, resetloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006122 int zero;
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006123 char *(*scan)(char*, char*, char*, char*, int, int);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006124
6125 herefd = -1;
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006126 argstr(p, (subtype != VSASSIGN && subtype != VSQUESTION) ? EXP_CASE : 0,
6127 var_str_list);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006128 STPUTC('\0', expdest);
6129 herefd = saveherefd;
6130 argbackq = saveargbackq;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00006131 startp = (char *)stackblock() + startloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006132
6133 switch (subtype) {
6134 case VSASSIGN:
6135 setvar(str, startp, 0);
6136 amount = startp - expdest;
6137 STADJUST(amount, expdest);
6138 return startp;
6139
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006140#if ENABLE_ASH_BASH_COMPAT
6141 case VSSUBSTR:
6142 loc = str = stackblock() + strloc;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006143 /* Read POS in ${var:POS:LEN} */
6144 pos = atoi(loc); /* number(loc) errors out on "1:4" */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006145 len = str - startp - 1;
6146
6147 /* *loc != '\0', guaranteed by parser */
6148 if (quotes) {
6149 char *ptr;
6150
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006151 /* Adjust the length by the number of escapes */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006152 for (ptr = startp; ptr < (str - 1); ptr++) {
Denys Vlasenkocd716832009-11-28 22:14:02 +01006153 if ((unsigned char)*ptr == CTLESC) {
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006154 len--;
6155 ptr++;
6156 }
6157 }
6158 }
6159 orig_len = len;
6160
6161 if (*loc++ == ':') {
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006162 /* ${var::LEN} */
6163 len = number(loc);
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006164 } else {
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006165 /* Skip POS in ${var:POS:LEN} */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006166 len = orig_len;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006167 while (*loc && *loc != ':') {
6168 /* TODO?
6169 * bash complains on: var=qwe; echo ${var:1a:123}
6170 if (!isdigit(*loc))
6171 ash_msg_and_raise_error(msg_illnum, str);
6172 */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006173 loc++;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006174 }
6175 if (*loc++ == ':') {
6176 len = number(loc);
6177 }
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006178 }
6179 if (pos >= orig_len) {
6180 pos = 0;
6181 len = 0;
6182 }
6183 if (len > (orig_len - pos))
6184 len = orig_len - pos;
6185
6186 for (str = startp; pos; str++, pos--) {
Denys Vlasenkocd716832009-11-28 22:14:02 +01006187 if (quotes && (unsigned char)*str == CTLESC)
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006188 str++;
6189 }
6190 for (loc = startp; len; len--) {
Denys Vlasenkocd716832009-11-28 22:14:02 +01006191 if (quotes && (unsigned char)*str == CTLESC)
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006192 *loc++ = *str++;
6193 *loc++ = *str++;
6194 }
6195 *loc = '\0';
6196 amount = loc - expdest;
6197 STADJUST(amount, expdest);
6198 return loc;
6199#endif
6200
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006201 case VSQUESTION:
6202 varunset(p, str, startp, varflags);
6203 /* NOTREACHED */
6204 }
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006205 resetloc = expdest - (char *)stackblock();
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006206
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006207 /* We'll comeback here if we grow the stack while handling
6208 * a VSREPLACE or VSREPLACEALL, since our pointers into the
6209 * stack will need rebasing, and we'll need to remove our work
6210 * areas each time
6211 */
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00006212 IF_ASH_BASH_COMPAT(restart:)
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006213
6214 amount = expdest - ((char *)stackblock() + resetloc);
6215 STADJUST(-amount, expdest);
Denis Vlasenko29eb3592008-05-18 14:06:08 +00006216 startp = (char *)stackblock() + startloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006217
6218 rmesc = startp;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00006219 rmescend = (char *)stackblock() + strloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006220 if (quotes) {
Denys Vlasenkob6c84342009-08-29 20:23:20 +02006221 rmesc = rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006222 if (rmesc != startp) {
6223 rmescend = expdest;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00006224 startp = (char *)stackblock() + startloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006225 }
6226 }
6227 rmescend--;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00006228 str = (char *)stackblock() + strloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006229 preglob(str, varflags & VSQUOTE, 0);
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006230 workloc = expdest - (char *)stackblock();
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006231
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006232#if ENABLE_ASH_BASH_COMPAT
6233 if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
6234 char *idx, *end, *restart_detect;
6235
Denis Vlasenkod6855d12008-09-27 14:03:25 +00006236 if (!repl) {
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006237 repl = parse_sub_pattern(str, varflags & VSQUOTE);
6238 if (!repl)
6239 repl = &null;
6240 }
6241
6242 /* If there's no pattern to match, return the expansion unmolested */
6243 if (*str == '\0')
6244 return 0;
6245
6246 len = 0;
6247 idx = startp;
6248 end = str - 1;
6249 while (idx < end) {
6250 loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
6251 if (!loc) {
6252 /* No match, advance */
6253 restart_detect = stackblock();
6254 STPUTC(*idx, expdest);
Denys Vlasenkocd716832009-11-28 22:14:02 +01006255 if (quotes && (unsigned char)*idx == CTLESC) {
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006256 idx++;
6257 len++;
6258 STPUTC(*idx, expdest);
6259 }
6260 if (stackblock() != restart_detect)
6261 goto restart;
6262 idx++;
6263 len++;
6264 rmesc++;
6265 continue;
6266 }
6267
6268 if (subtype == VSREPLACEALL) {
6269 while (idx < loc) {
Denys Vlasenkocd716832009-11-28 22:14:02 +01006270 if (quotes && (unsigned char)*idx == CTLESC)
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006271 idx++;
6272 idx++;
6273 rmesc++;
6274 }
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00006275 } else {
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006276 idx = loc;
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00006277 }
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006278
6279 for (loc = repl; *loc; loc++) {
6280 restart_detect = stackblock();
6281 STPUTC(*loc, expdest);
6282 if (stackblock() != restart_detect)
6283 goto restart;
6284 len++;
6285 }
6286
6287 if (subtype == VSREPLACE) {
6288 while (*idx) {
6289 restart_detect = stackblock();
6290 STPUTC(*idx, expdest);
6291 if (stackblock() != restart_detect)
6292 goto restart;
6293 len++;
6294 idx++;
6295 }
6296 break;
6297 }
6298 }
6299
6300 /* We've put the replaced text into a buffer at workloc, now
6301 * move it to the right place and adjust the stack.
6302 */
6303 startp = stackblock() + startloc;
6304 STPUTC('\0', expdest);
6305 memmove(startp, stackblock() + workloc, len);
6306 startp[len++] = '\0';
6307 amount = expdest - ((char *)stackblock() + startloc + len - 1);
6308 STADJUST(-amount, expdest);
6309 return startp;
6310 }
6311#endif /* ENABLE_ASH_BASH_COMPAT */
6312
6313 subtype -= VSTRIMRIGHT;
6314#if DEBUG
6315 if (subtype < 0 || subtype > 7)
6316 abort();
6317#endif
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006318 /* zero = subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX */
6319 zero = subtype >> 1;
6320 /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
6321 scan = (subtype & 1) ^ zero ? scanleft : scanright;
6322
6323 loc = scan(startp, rmesc, rmescend, str, quotes, zero);
6324 if (loc) {
6325 if (zero) {
6326 memmove(startp, loc, str - loc);
6327 loc = startp + (str - loc) - 1;
6328 }
6329 *loc = '\0';
6330 amount = loc - expdest;
6331 STADJUST(amount, expdest);
6332 }
6333 return loc;
6334}
6335
6336/*
6337 * Add the value of a specialized variable to the stack string.
Denys Vlasenko4d8873f2009-10-04 03:14:41 +02006338 * name parameter (examples):
6339 * ash -c 'echo $1' name:'1='
6340 * ash -c 'echo $qwe' name:'qwe='
6341 * ash -c 'echo $$' name:'$='
6342 * ash -c 'echo ${$}' name:'$='
6343 * ash -c 'echo ${$##q}' name:'$=q'
6344 * ash -c 'echo ${#$}' name:'$='
6345 * note: examples with bad shell syntax:
6346 * ash -c 'echo ${#$1}' name:'$=1'
6347 * ash -c 'echo ${#1#}' name:'1=#'
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006348 */
Denys Vlasenkoadf922e2009-10-08 14:35:37 +02006349static NOINLINE ssize_t
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006350varvalue(char *name, int varflags, int flags, struct strlist *var_str_list)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006351{
Mike Frysinger98c52642009-04-02 10:02:37 +00006352 const char *p;
Denys Vlasenko8eda4a92009-11-30 12:16:17 +01006353 int num;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006354 int i;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006355 int sepq = 0;
6356 ssize_t len = 0;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006357 int subtype = varflags & VSTYPE;
Denys Vlasenko1166d7b2009-09-16 16:20:31 +02006358 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR);
Denys Vlasenko8eda4a92009-11-30 12:16:17 +01006359 int quoted = varflags & VSQUOTE;
6360 int syntax = quoted ? DQSYNTAX : BASESYNTAX;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006361
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006362 switch (*name) {
6363 case '$':
6364 num = rootpid;
6365 goto numvar;
6366 case '?':
6367 num = exitstatus;
6368 goto numvar;
6369 case '#':
6370 num = shellparam.nparam;
6371 goto numvar;
6372 case '!':
6373 num = backgndpid;
6374 if (num == 0)
6375 return -1;
6376 numvar:
6377 len = cvtnum(num);
Denys Vlasenko4d8873f2009-10-04 03:14:41 +02006378 goto check_1char_name;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006379 case '-':
Mike Frysinger98c52642009-04-02 10:02:37 +00006380 expdest = makestrspace(NOPTS, expdest);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006381 for (i = NOPTS - 1; i >= 0; i--) {
6382 if (optlist[i]) {
Mike Frysinger98c52642009-04-02 10:02:37 +00006383 USTPUTC(optletters(i), expdest);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006384 len++;
6385 }
6386 }
Denys Vlasenko4d8873f2009-10-04 03:14:41 +02006387 check_1char_name:
6388#if 0
6389 /* handles cases similar to ${#$1} */
6390 if (name[2] != '\0')
6391 raise_error_syntax("bad substitution");
6392#endif
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006393 break;
Denys Vlasenko8eda4a92009-11-30 12:16:17 +01006394 case '@': {
6395 char **ap;
6396 int sep;
6397
6398 if (quoted && (flags & EXP_FULL)) {
6399 /* note: this is not meant as PEOF value */
6400 sep = 1 << CHAR_BIT;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006401 goto param;
Denys Vlasenko8eda4a92009-11-30 12:16:17 +01006402 }
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006403 /* fall through */
6404 case '*':
Denys Vlasenkocd716832009-11-28 22:14:02 +01006405 sep = ifsset() ? (unsigned char)(ifsval()[0]) : ' ';
Denys Vlasenko8eda4a92009-11-30 12:16:17 +01006406 i = SIT(sep, syntax);
6407 if (quotes && (i == CCTL || i == CBACK))
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006408 sepq = 1;
6409 param:
6410 ap = shellparam.p;
6411 if (!ap)
6412 return -1;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006413 while ((p = *ap++) != NULL) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006414 size_t partlen;
6415
6416 partlen = strlen(p);
6417 len += partlen;
6418
6419 if (!(subtype == VSPLUS || subtype == VSLENGTH))
6420 memtodest(p, partlen, syntax, quotes);
6421
6422 if (*ap && sep) {
6423 char *q;
6424
6425 len++;
6426 if (subtype == VSPLUS || subtype == VSLENGTH) {
6427 continue;
6428 }
6429 q = expdest;
6430 if (sepq)
6431 STPUTC(CTLESC, q);
Denys Vlasenko8eda4a92009-11-30 12:16:17 +01006432 /* note: may put NUL despite sep != 0
6433 * (see sep = 1 << CHAR_BIT above) */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006434 STPUTC(sep, q);
6435 expdest = q;
6436 }
6437 }
6438 return len;
Denys Vlasenko8eda4a92009-11-30 12:16:17 +01006439 } /* case '@' and '*' */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006440 case '0':
6441 case '1':
6442 case '2':
6443 case '3':
6444 case '4':
6445 case '5':
6446 case '6':
6447 case '7':
6448 case '8':
6449 case '9':
Denys Vlasenkoa00329c2009-08-30 20:05:10 +02006450 num = atoi(name); /* number(name) fails on ${N#str} etc */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006451 if (num < 0 || num > shellparam.nparam)
6452 return -1;
6453 p = num ? shellparam.p[num - 1] : arg0;
6454 goto value;
6455 default:
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006456 /* NB: name has form "VAR=..." */
6457
6458 /* "A=a B=$A" case: var_str_list is a list of "A=a" strings
6459 * which should be considered before we check variables. */
6460 if (var_str_list) {
6461 unsigned name_len = (strchrnul(name, '=') - name) + 1;
6462 p = NULL;
6463 do {
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00006464 char *str, *eq;
6465 str = var_str_list->text;
6466 eq = strchr(str, '=');
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006467 if (!eq) /* stop at first non-assignment */
6468 break;
6469 eq++;
Denis Vlasenko6b06cb82008-05-15 21:30:45 +00006470 if (name_len == (unsigned)(eq - str)
Denys Vlasenko8eda4a92009-11-30 12:16:17 +01006471 && strncmp(str, name, name_len) == 0
6472 ) {
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006473 p = eq;
6474 /* goto value; - WRONG! */
6475 /* think "A=1 A=2 B=$A" */
6476 }
6477 var_str_list = var_str_list->next;
6478 } while (var_str_list);
6479 if (p)
6480 goto value;
6481 }
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006482 p = lookupvar(name);
6483 value:
6484 if (!p)
6485 return -1;
6486
6487 len = strlen(p);
6488 if (!(subtype == VSPLUS || subtype == VSLENGTH))
6489 memtodest(p, len, syntax, quotes);
6490 return len;
6491 }
6492
6493 if (subtype == VSPLUS || subtype == VSLENGTH)
6494 STADJUST(-len, expdest);
6495 return len;
6496}
6497
6498/*
6499 * Expand a variable, and return a pointer to the next character in the
6500 * input string.
6501 */
6502static char *
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006503evalvar(char *p, int flags, struct strlist *var_str_list)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006504{
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006505 char varflags;
6506 char subtype;
6507 char quoted;
6508 char easy;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006509 char *var;
6510 int patloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006511 int startloc;
6512 ssize_t varlen;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006513
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006514 varflags = (unsigned char) *p++;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006515 subtype = varflags & VSTYPE;
6516 quoted = varflags & VSQUOTE;
6517 var = p;
6518 easy = (!quoted || (*var == '@' && shellparam.nparam));
6519 startloc = expdest - (char *)stackblock();
6520 p = strchr(p, '=') + 1;
6521
6522 again:
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006523 varlen = varvalue(var, varflags, flags, var_str_list);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006524 if (varflags & VSNUL)
6525 varlen--;
6526
6527 if (subtype == VSPLUS) {
6528 varlen = -1 - varlen;
6529 goto vsplus;
6530 }
6531
6532 if (subtype == VSMINUS) {
6533 vsplus:
6534 if (varlen < 0) {
6535 argstr(
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006536 p, flags | EXP_TILDE |
6537 (quoted ? EXP_QWORD : EXP_WORD),
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006538 var_str_list
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006539 );
6540 goto end;
6541 }
6542 if (easy)
6543 goto record;
6544 goto end;
6545 }
6546
6547 if (subtype == VSASSIGN || subtype == VSQUESTION) {
6548 if (varlen < 0) {
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006549 if (subevalvar(p, var, /* strloc: */ 0,
6550 subtype, startloc, varflags,
6551 /* quotes: */ 0,
6552 var_str_list)
6553 ) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006554 varflags &= ~VSNUL;
6555 /*
6556 * Remove any recorded regions beyond
6557 * start of variable
6558 */
6559 removerecordregions(startloc);
6560 goto again;
6561 }
6562 goto end;
6563 }
6564 if (easy)
6565 goto record;
6566 goto end;
6567 }
6568
6569 if (varlen < 0 && uflag)
6570 varunset(p, var, 0, 0);
6571
6572 if (subtype == VSLENGTH) {
6573 cvtnum(varlen > 0 ? varlen : 0);
6574 goto record;
6575 }
6576
6577 if (subtype == VSNORMAL) {
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006578 if (easy)
6579 goto record;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006580 goto end;
6581 }
6582
6583#if DEBUG
6584 switch (subtype) {
6585 case VSTRIMLEFT:
6586 case VSTRIMLEFTMAX:
6587 case VSTRIMRIGHT:
6588 case VSTRIMRIGHTMAX:
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006589#if ENABLE_ASH_BASH_COMPAT
6590 case VSSUBSTR:
6591 case VSREPLACE:
6592 case VSREPLACEALL:
6593#endif
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006594 break;
6595 default:
6596 abort();
6597 }
6598#endif
6599
6600 if (varlen >= 0) {
6601 /*
6602 * Terminate the string and start recording the pattern
6603 * right after it
6604 */
6605 STPUTC('\0', expdest);
6606 patloc = expdest - (char *)stackblock();
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006607 if (0 == subevalvar(p, /* str: */ NULL, patloc, subtype,
6608 startloc, varflags,
Denys Vlasenko1166d7b2009-09-16 16:20:31 +02006609//TODO: | EXP_REDIR too? All other such places do it too
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006610 /* quotes: */ flags & (EXP_FULL | EXP_CASE),
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006611 var_str_list)
6612 ) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006613 int amount = expdest - (
6614 (char *)stackblock() + patloc - 1
6615 );
6616 STADJUST(-amount, expdest);
6617 }
6618 /* Remove any recorded regions beyond start of variable */
6619 removerecordregions(startloc);
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006620 record:
6621 recordregion(startloc, expdest - (char *)stackblock(), quoted);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006622 }
6623
6624 end:
6625 if (subtype != VSNORMAL) { /* skip to end of alternative */
6626 int nesting = 1;
6627 for (;;) {
Denys Vlasenkocd716832009-11-28 22:14:02 +01006628 unsigned char c = *p++;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006629 if (c == CTLESC)
6630 p++;
6631 else if (c == CTLBACKQ || c == (CTLBACKQ|CTLQUOTE)) {
6632 if (varlen >= 0)
6633 argbackq = argbackq->next;
6634 } else if (c == CTLVAR) {
6635 if ((*p++ & VSTYPE) != VSNORMAL)
6636 nesting++;
6637 } else if (c == CTLENDVAR) {
6638 if (--nesting == 0)
6639 break;
6640 }
6641 }
6642 }
6643 return p;
6644}
6645
6646/*
6647 * Break the argument string into pieces based upon IFS and add the
6648 * strings to the argument list. The regions of the string to be
6649 * searched for IFS characters have been stored by recordregion.
6650 */
6651static void
6652ifsbreakup(char *string, struct arglist *arglist)
6653{
6654 struct ifsregion *ifsp;
6655 struct strlist *sp;
6656 char *start;
6657 char *p;
6658 char *q;
6659 const char *ifs, *realifs;
6660 int ifsspc;
6661 int nulonly;
6662
6663 start = string;
6664 if (ifslastp != NULL) {
6665 ifsspc = 0;
6666 nulonly = 0;
6667 realifs = ifsset() ? ifsval() : defifs;
6668 ifsp = &ifsfirst;
6669 do {
6670 p = string + ifsp->begoff;
6671 nulonly = ifsp->nulonly;
6672 ifs = nulonly ? nullstr : realifs;
6673 ifsspc = 0;
6674 while (p < string + ifsp->endoff) {
6675 q = p;
Denys Vlasenkocd716832009-11-28 22:14:02 +01006676 if ((unsigned char)*p == CTLESC)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006677 p++;
6678 if (!strchr(ifs, *p)) {
6679 p++;
6680 continue;
6681 }
6682 if (!nulonly)
6683 ifsspc = (strchr(defifs, *p) != NULL);
6684 /* Ignore IFS whitespace at start */
6685 if (q == start && ifsspc) {
6686 p++;
6687 start = p;
6688 continue;
6689 }
6690 *q = '\0';
Denis Vlasenko597906c2008-02-20 16:38:54 +00006691 sp = stzalloc(sizeof(*sp));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006692 sp->text = start;
6693 *arglist->lastp = sp;
6694 arglist->lastp = &sp->next;
6695 p++;
6696 if (!nulonly) {
6697 for (;;) {
6698 if (p >= string + ifsp->endoff) {
6699 break;
6700 }
6701 q = p;
Denys Vlasenkocd716832009-11-28 22:14:02 +01006702 if ((unsigned char)*p == CTLESC)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006703 p++;
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +00006704 if (strchr(ifs, *p) == NULL) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006705 p = q;
6706 break;
Denis Vlasenko597906c2008-02-20 16:38:54 +00006707 }
6708 if (strchr(defifs, *p) == NULL) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006709 if (ifsspc) {
6710 p++;
6711 ifsspc = 0;
6712 } else {
6713 p = q;
6714 break;
6715 }
6716 } else
6717 p++;
6718 }
6719 }
6720 start = p;
6721 } /* while */
6722 ifsp = ifsp->next;
6723 } while (ifsp != NULL);
6724 if (nulonly)
6725 goto add;
6726 }
6727
6728 if (!*start)
6729 return;
6730
6731 add:
Denis Vlasenko597906c2008-02-20 16:38:54 +00006732 sp = stzalloc(sizeof(*sp));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006733 sp->text = start;
6734 *arglist->lastp = sp;
6735 arglist->lastp = &sp->next;
6736}
6737
6738static void
6739ifsfree(void)
6740{
6741 struct ifsregion *p;
6742
6743 INT_OFF;
6744 p = ifsfirst.next;
6745 do {
6746 struct ifsregion *ifsp;
6747 ifsp = p->next;
6748 free(p);
6749 p = ifsp;
6750 } while (p);
6751 ifslastp = NULL;
6752 ifsfirst.next = NULL;
6753 INT_ON;
6754}
6755
6756/*
6757 * Add a file name to the list.
6758 */
6759static void
6760addfname(const char *name)
6761{
6762 struct strlist *sp;
6763
Denis Vlasenko597906c2008-02-20 16:38:54 +00006764 sp = stzalloc(sizeof(*sp));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006765 sp->text = ststrdup(name);
6766 *exparg.lastp = sp;
6767 exparg.lastp = &sp->next;
6768}
6769
6770static char *expdir;
6771
6772/*
6773 * Do metacharacter (i.e. *, ?, [...]) expansion.
6774 */
6775static void
6776expmeta(char *enddir, char *name)
6777{
6778 char *p;
6779 const char *cp;
6780 char *start;
6781 char *endname;
6782 int metaflag;
6783 struct stat statb;
6784 DIR *dirp;
6785 struct dirent *dp;
6786 int atend;
6787 int matchdot;
6788
6789 metaflag = 0;
6790 start = name;
6791 for (p = name; *p; p++) {
6792 if (*p == '*' || *p == '?')
6793 metaflag = 1;
6794 else if (*p == '[') {
6795 char *q = p + 1;
6796 if (*q == '!')
6797 q++;
6798 for (;;) {
6799 if (*q == '\\')
6800 q++;
6801 if (*q == '/' || *q == '\0')
6802 break;
6803 if (*++q == ']') {
6804 metaflag = 1;
6805 break;
6806 }
6807 }
6808 } else if (*p == '\\')
6809 p++;
6810 else if (*p == '/') {
6811 if (metaflag)
6812 goto out;
6813 start = p + 1;
6814 }
6815 }
6816 out:
6817 if (metaflag == 0) { /* we've reached the end of the file name */
6818 if (enddir != expdir)
6819 metaflag++;
6820 p = name;
6821 do {
6822 if (*p == '\\')
6823 p++;
6824 *enddir++ = *p;
6825 } while (*p++);
6826 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
6827 addfname(expdir);
6828 return;
6829 }
6830 endname = p;
6831 if (name < start) {
6832 p = name;
6833 do {
6834 if (*p == '\\')
6835 p++;
6836 *enddir++ = *p++;
6837 } while (p < start);
6838 }
6839 if (enddir == expdir) {
6840 cp = ".";
6841 } else if (enddir == expdir + 1 && *expdir == '/') {
6842 cp = "/";
6843 } else {
6844 cp = expdir;
6845 enddir[-1] = '\0';
6846 }
6847 dirp = opendir(cp);
6848 if (dirp == NULL)
6849 return;
6850 if (enddir != expdir)
6851 enddir[-1] = '/';
6852 if (*endname == 0) {
6853 atend = 1;
6854 } else {
6855 atend = 0;
6856 *endname++ = '\0';
6857 }
6858 matchdot = 0;
6859 p = start;
6860 if (*p == '\\')
6861 p++;
6862 if (*p == '.')
6863 matchdot++;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006864 while (!pending_int && (dp = readdir(dirp)) != NULL) {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00006865 if (dp->d_name[0] == '.' && !matchdot)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006866 continue;
6867 if (pmatch(start, dp->d_name)) {
6868 if (atend) {
6869 strcpy(enddir, dp->d_name);
6870 addfname(expdir);
6871 } else {
6872 for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
6873 continue;
6874 p[-1] = '/';
6875 expmeta(p, endname);
6876 }
6877 }
6878 }
6879 closedir(dirp);
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00006880 if (!atend)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006881 endname[-1] = '/';
6882}
6883
6884static struct strlist *
6885msort(struct strlist *list, int len)
6886{
6887 struct strlist *p, *q = NULL;
6888 struct strlist **lpp;
6889 int half;
6890 int n;
6891
6892 if (len <= 1)
6893 return list;
6894 half = len >> 1;
6895 p = list;
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +00006896 for (n = half; --n >= 0;) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006897 q = p;
6898 p = p->next;
6899 }
6900 q->next = NULL; /* terminate first half of list */
6901 q = msort(list, half); /* sort first half of list */
6902 p = msort(p, len - half); /* sort second half */
6903 lpp = &list;
6904 for (;;) {
6905#if ENABLE_LOCALE_SUPPORT
6906 if (strcoll(p->text, q->text) < 0)
6907#else
6908 if (strcmp(p->text, q->text) < 0)
6909#endif
6910 {
6911 *lpp = p;
6912 lpp = &p->next;
6913 p = *lpp;
6914 if (p == NULL) {
6915 *lpp = q;
6916 break;
6917 }
6918 } else {
6919 *lpp = q;
6920 lpp = &q->next;
6921 q = *lpp;
6922 if (q == NULL) {
6923 *lpp = p;
6924 break;
6925 }
6926 }
6927 }
6928 return list;
6929}
6930
6931/*
6932 * Sort the results of file name expansion. It calculates the number of
6933 * strings to sort and then calls msort (short for merge sort) to do the
6934 * work.
6935 */
6936static struct strlist *
6937expsort(struct strlist *str)
6938{
6939 int len;
6940 struct strlist *sp;
6941
6942 len = 0;
6943 for (sp = str; sp; sp = sp->next)
6944 len++;
6945 return msort(str, len);
6946}
6947
6948static void
Denis Vlasenko68404f12008-03-17 09:00:54 +00006949expandmeta(struct strlist *str /*, int flag*/)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006950{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00006951 static const char metachars[] ALIGN1 = {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006952 '*', '?', '[', 0
6953 };
6954 /* TODO - EXP_REDIR */
6955
6956 while (str) {
6957 struct strlist **savelastp;
6958 struct strlist *sp;
6959 char *p;
6960
6961 if (fflag)
6962 goto nometa;
6963 if (!strpbrk(str->text, metachars))
6964 goto nometa;
6965 savelastp = exparg.lastp;
6966
6967 INT_OFF;
6968 p = preglob(str->text, 0, RMESCAPE_ALLOC | RMESCAPE_HEAP);
6969 {
6970 int i = strlen(str->text);
6971 expdir = ckmalloc(i < 2048 ? 2048 : i); /* XXX */
6972 }
6973
6974 expmeta(expdir, p);
6975 free(expdir);
6976 if (p != str->text)
6977 free(p);
6978 INT_ON;
6979 if (exparg.lastp == savelastp) {
6980 /*
6981 * no matches
6982 */
6983 nometa:
6984 *exparg.lastp = str;
Denys Vlasenkob6c84342009-08-29 20:23:20 +02006985 rmescapes(str->text, 0);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006986 exparg.lastp = &str->next;
6987 } else {
6988 *exparg.lastp = NULL;
6989 *savelastp = sp = expsort(*savelastp);
6990 while (sp->next != NULL)
6991 sp = sp->next;
6992 exparg.lastp = &sp->next;
6993 }
6994 str = str->next;
6995 }
6996}
6997
6998/*
6999 * Perform variable substitution and command substitution on an argument,
7000 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
7001 * perform splitting and file name expansion. When arglist is NULL, perform
7002 * here document expansion.
7003 */
7004static void
7005expandarg(union node *arg, struct arglist *arglist, int flag)
7006{
7007 struct strlist *sp;
7008 char *p;
7009
7010 argbackq = arg->narg.backquote;
7011 STARTSTACKSTR(expdest);
7012 ifsfirst.next = NULL;
7013 ifslastp = NULL;
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00007014 argstr(arg->narg.text, flag,
7015 /* var_str_list: */ arglist ? arglist->list : NULL);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007016 p = _STPUTC('\0', expdest);
7017 expdest = p - 1;
7018 if (arglist == NULL) {
7019 return; /* here document expanded */
7020 }
7021 p = grabstackstr(p);
7022 exparg.lastp = &exparg.list;
7023 /*
7024 * TODO - EXP_REDIR
7025 */
7026 if (flag & EXP_FULL) {
7027 ifsbreakup(p, &exparg);
7028 *exparg.lastp = NULL;
7029 exparg.lastp = &exparg.list;
Denis Vlasenko68404f12008-03-17 09:00:54 +00007030 expandmeta(exparg.list /*, flag*/);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007031 } else {
7032 if (flag & EXP_REDIR) /*XXX - for now, just remove escapes */
Denys Vlasenkob6c84342009-08-29 20:23:20 +02007033 rmescapes(p, 0);
Denis Vlasenko597906c2008-02-20 16:38:54 +00007034 sp = stzalloc(sizeof(*sp));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007035 sp->text = p;
7036 *exparg.lastp = sp;
7037 exparg.lastp = &sp->next;
7038 }
7039 if (ifsfirst.next)
7040 ifsfree();
7041 *exparg.lastp = NULL;
7042 if (exparg.list) {
7043 *arglist->lastp = exparg.list;
7044 arglist->lastp = exparg.lastp;
7045 }
7046}
7047
7048/*
7049 * Expand shell variables and backquotes inside a here document.
7050 */
7051static void
7052expandhere(union node *arg, int fd)
7053{
7054 herefd = fd;
7055 expandarg(arg, (struct arglist *)NULL, 0);
7056 full_write(fd, stackblock(), expdest - (char *)stackblock());
7057}
7058
7059/*
7060 * Returns true if the pattern matches the string.
7061 */
7062static int
7063patmatch(char *pattern, const char *string)
7064{
7065 return pmatch(preglob(pattern, 0, 0), string);
7066}
7067
7068/*
7069 * See if a pattern matches in a case statement.
7070 */
7071static int
7072casematch(union node *pattern, char *val)
7073{
7074 struct stackmark smark;
7075 int result;
7076
7077 setstackmark(&smark);
7078 argbackq = pattern->narg.backquote;
7079 STARTSTACKSTR(expdest);
7080 ifslastp = NULL;
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00007081 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE,
7082 /* var_str_list: */ NULL);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007083 STACKSTRNUL(expdest);
7084 result = patmatch(stackblock(), val);
7085 popstackmark(&smark);
7086 return result;
7087}
7088
7089
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007090/* ============ find_command */
7091
7092struct builtincmd {
7093 const char *name;
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007094 int (*builtin)(int, char **) FAST_FUNC;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007095 /* unsigned flags; */
7096};
7097#define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
Denis Vlasenkoe26b2782008-02-12 07:40:29 +00007098/* "regular" builtins always take precedence over commands,
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007099 * regardless of PATH=....%builtin... position */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007100#define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007101#define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007102
7103struct cmdentry {
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00007104 smallint cmdtype; /* CMDxxx */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007105 union param {
7106 int index;
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00007107 /* index >= 0 for commands without path (slashes) */
7108 /* (TODO: what exactly does the value mean? PATH position?) */
7109 /* index == -1 for commands with slashes */
7110 /* index == (-2 - applet_no) for NOFORK applets */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007111 const struct builtincmd *cmd;
7112 struct funcnode *func;
7113 } u;
7114};
7115/* values of cmdtype */
7116#define CMDUNKNOWN -1 /* no entry in table for command */
7117#define CMDNORMAL 0 /* command is an executable program */
7118#define CMDFUNCTION 1 /* command is a shell function */
7119#define CMDBUILTIN 2 /* command is a shell builtin */
7120
7121/* action to find_command() */
7122#define DO_ERR 0x01 /* prints errors */
7123#define DO_ABS 0x02 /* checks absolute paths */
7124#define DO_NOFUNC 0x04 /* don't return shell functions, for command */
7125#define DO_ALTPATH 0x08 /* using alternate path */
7126#define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
7127
7128static void find_command(char *, struct cmdentry *, int, const char *);
7129
7130
7131/* ============ Hashing commands */
7132
7133/*
7134 * When commands are first encountered, they are entered in a hash table.
7135 * This ensures that a full path search will not have to be done for them
7136 * on each invocation.
7137 *
7138 * We should investigate converting to a linear search, even though that
7139 * would make the command name "hash" a misnomer.
7140 */
7141
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007142struct tblentry {
7143 struct tblentry *next; /* next entry in hash chain */
7144 union param param; /* definition of builtin function */
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00007145 smallint cmdtype; /* CMDxxx */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007146 char rehash; /* if set, cd done since entry created */
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007147 char cmdname[1]; /* name of command */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007148};
7149
Denis Vlasenko01631112007-12-16 17:20:38 +00007150static struct tblentry **cmdtable;
7151#define INIT_G_cmdtable() do { \
7152 cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
7153} while (0)
7154
7155static int builtinloc = -1; /* index in path of %builtin, or -1 */
7156
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007157
7158static void
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00007159tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) char *cmd, char **argv, char **envp)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007160{
7161 int repeated = 0;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007162
Denis Vlasenko80d14be2007-04-10 23:03:30 +00007163#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007164 if (applet_no >= 0) {
Denis Vlasenkob7304742008-10-20 08:15:51 +00007165 if (APPLET_IS_NOEXEC(applet_no)) {
7166 while (*envp)
7167 putenv(*envp++);
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007168 run_applet_no_and_exit(applet_no, argv);
Denis Vlasenkob7304742008-10-20 08:15:51 +00007169 }
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007170 /* re-exec ourselves with the new arguments */
7171 execve(bb_busybox_exec_path, argv, envp);
7172 /* If they called chroot or otherwise made the binary no longer
7173 * executable, fall through */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007174 }
7175#endif
7176
7177 repeat:
7178#ifdef SYSV
7179 do {
7180 execve(cmd, argv, envp);
7181 } while (errno == EINTR);
7182#else
7183 execve(cmd, argv, envp);
7184#endif
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007185 if (repeated) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007186 free(argv);
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007187 return;
7188 }
7189 if (errno == ENOEXEC) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007190 char **ap;
7191 char **new;
7192
7193 for (ap = argv; *ap; ap++)
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007194 continue;
7195 ap = new = ckmalloc((ap - argv + 2) * sizeof(ap[0]));
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007196 ap[1] = cmd;
Denis Vlasenkoc44ab012007-04-09 03:11:58 +00007197 ap[0] = cmd = (char *)DEFAULT_SHELL;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007198 ap += 2;
7199 argv++;
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007200 while ((*ap++ = *argv++) != NULL)
Denis Vlasenko597906c2008-02-20 16:38:54 +00007201 continue;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007202 argv = new;
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007203 repeated++;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007204 goto repeat;
7205 }
7206}
7207
7208/*
7209 * Exec a program. Never returns. If you change this routine, you may
7210 * have to change the find_command routine as well.
7211 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00007212static void shellexec(char **, const char *, int) NORETURN;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007213static void
7214shellexec(char **argv, const char *path, int idx)
7215{
7216 char *cmdname;
7217 int e;
7218 char **envp;
7219 int exerrno;
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007220#if ENABLE_FEATURE_SH_STANDALONE
7221 int applet_no = -1;
7222#endif
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007223
Denis Vlasenko34c73c42008-08-16 11:48:02 +00007224 clearredir(/*drop:*/ 1);
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007225 envp = listvars(VEXPORT, VUNSET, 0);
7226 if (strchr(argv[0], '/') != NULL
Denis Vlasenko80d14be2007-04-10 23:03:30 +00007227#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007228 || (applet_no = find_applet_by_name(argv[0])) >= 0
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007229#endif
7230 ) {
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00007231 tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) argv[0], argv, envp);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007232 e = errno;
7233 } else {
7234 e = ENOENT;
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02007235 while ((cmdname = path_advance(&path, argv[0])) != NULL) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007236 if (--idx < 0 && pathopt == NULL) {
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00007237 tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007238 if (errno != ENOENT && errno != ENOTDIR)
7239 e = errno;
7240 }
7241 stunalloc(cmdname);
7242 }
7243 }
7244
7245 /* Map to POSIX errors */
7246 switch (e) {
7247 case EACCES:
7248 exerrno = 126;
7249 break;
7250 case ENOENT:
7251 exerrno = 127;
7252 break;
7253 default:
7254 exerrno = 2;
7255 break;
7256 }
7257 exitstatus = exerrno;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02007258 TRACE(("shellexec failed for %s, errno %d, suppress_int %d\n",
7259 argv[0], e, suppress_int));
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007260 ash_msg_and_raise(EXEXEC, "%s: %s", argv[0], errmsg(e, "not found"));
7261 /* NOTREACHED */
7262}
7263
7264static void
7265printentry(struct tblentry *cmdp)
7266{
7267 int idx;
7268 const char *path;
7269 char *name;
7270
7271 idx = cmdp->param.index;
7272 path = pathval();
7273 do {
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02007274 name = path_advance(&path, cmdp->cmdname);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007275 stunalloc(name);
7276 } while (--idx >= 0);
7277 out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
7278}
7279
7280/*
7281 * Clear out command entries. The argument specifies the first entry in
7282 * PATH which has changed.
7283 */
7284static void
7285clearcmdentry(int firstchange)
7286{
7287 struct tblentry **tblp;
7288 struct tblentry **pp;
7289 struct tblentry *cmdp;
7290
7291 INT_OFF;
7292 for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
7293 pp = tblp;
7294 while ((cmdp = *pp) != NULL) {
7295 if ((cmdp->cmdtype == CMDNORMAL &&
7296 cmdp->param.index >= firstchange)
7297 || (cmdp->cmdtype == CMDBUILTIN &&
7298 builtinloc >= firstchange)
7299 ) {
7300 *pp = cmdp->next;
7301 free(cmdp);
7302 } else {
7303 pp = &cmdp->next;
7304 }
7305 }
7306 }
7307 INT_ON;
7308}
7309
7310/*
7311 * Locate a command in the command hash table. If "add" is nonzero,
7312 * add the command to the table if it is not already present. The
7313 * variable "lastcmdentry" is set to point to the address of the link
7314 * pointing to the entry, so that delete_cmd_entry can delete the
7315 * entry.
7316 *
7317 * Interrupts must be off if called with add != 0.
7318 */
7319static struct tblentry **lastcmdentry;
7320
7321static struct tblentry *
7322cmdlookup(const char *name, int add)
7323{
7324 unsigned int hashval;
7325 const char *p;
7326 struct tblentry *cmdp;
7327 struct tblentry **pp;
7328
7329 p = name;
7330 hashval = (unsigned char)*p << 4;
7331 while (*p)
7332 hashval += (unsigned char)*p++;
7333 hashval &= 0x7FFF;
7334 pp = &cmdtable[hashval % CMDTABLESIZE];
7335 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7336 if (strcmp(cmdp->cmdname, name) == 0)
7337 break;
7338 pp = &cmdp->next;
7339 }
7340 if (add && cmdp == NULL) {
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007341 cmdp = *pp = ckzalloc(sizeof(struct tblentry)
7342 + strlen(name)
7343 /* + 1 - already done because
7344 * tblentry::cmdname is char[1] */);
Denis Vlasenko597906c2008-02-20 16:38:54 +00007345 /*cmdp->next = NULL; - ckzalloc did it */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007346 cmdp->cmdtype = CMDUNKNOWN;
7347 strcpy(cmdp->cmdname, name);
7348 }
7349 lastcmdentry = pp;
7350 return cmdp;
7351}
7352
7353/*
7354 * Delete the command entry returned on the last lookup.
7355 */
7356static void
7357delete_cmd_entry(void)
7358{
7359 struct tblentry *cmdp;
7360
7361 INT_OFF;
7362 cmdp = *lastcmdentry;
7363 *lastcmdentry = cmdp->next;
7364 if (cmdp->cmdtype == CMDFUNCTION)
7365 freefunc(cmdp->param.func);
7366 free(cmdp);
7367 INT_ON;
7368}
7369
7370/*
7371 * Add a new command entry, replacing any existing command entry for
7372 * the same name - except special builtins.
7373 */
7374static void
7375addcmdentry(char *name, struct cmdentry *entry)
7376{
7377 struct tblentry *cmdp;
7378
7379 cmdp = cmdlookup(name, 1);
7380 if (cmdp->cmdtype == CMDFUNCTION) {
7381 freefunc(cmdp->param.func);
7382 }
7383 cmdp->cmdtype = entry->cmdtype;
7384 cmdp->param = entry->u;
7385 cmdp->rehash = 0;
7386}
7387
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007388static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00007389hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007390{
7391 struct tblentry **pp;
7392 struct tblentry *cmdp;
7393 int c;
7394 struct cmdentry entry;
7395 char *name;
7396
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007397 if (nextopt("r") != '\0') {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007398 clearcmdentry(0);
7399 return 0;
7400 }
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007401
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007402 if (*argptr == NULL) {
7403 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7404 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7405 if (cmdp->cmdtype == CMDNORMAL)
7406 printentry(cmdp);
7407 }
7408 }
7409 return 0;
7410 }
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007411
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007412 c = 0;
7413 while ((name = *argptr) != NULL) {
7414 cmdp = cmdlookup(name, 0);
7415 if (cmdp != NULL
7416 && (cmdp->cmdtype == CMDNORMAL
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007417 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
7418 ) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007419 delete_cmd_entry();
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007420 }
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007421 find_command(name, &entry, DO_ERR, pathval());
7422 if (entry.cmdtype == CMDUNKNOWN)
7423 c = 1;
7424 argptr++;
7425 }
7426 return c;
7427}
7428
7429/*
7430 * Called when a cd is done. Marks all commands so the next time they
7431 * are executed they will be rehashed.
7432 */
7433static void
7434hashcd(void)
7435{
7436 struct tblentry **pp;
7437 struct tblentry *cmdp;
7438
7439 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7440 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007441 if (cmdp->cmdtype == CMDNORMAL
7442 || (cmdp->cmdtype == CMDBUILTIN
7443 && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
7444 && builtinloc > 0)
7445 ) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007446 cmdp->rehash = 1;
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007447 }
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007448 }
7449 }
7450}
7451
7452/*
7453 * Fix command hash table when PATH changed.
7454 * Called before PATH is changed. The argument is the new value of PATH;
7455 * pathval() still returns the old value at this point.
7456 * Called with interrupts off.
7457 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007458static void FAST_FUNC
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007459changepath(const char *new)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007460{
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007461 const char *old;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007462 int firstchange;
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007463 int idx;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007464 int idx_bltin;
7465
7466 old = pathval();
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007467 firstchange = 9999; /* assume no change */
7468 idx = 0;
7469 idx_bltin = -1;
7470 for (;;) {
7471 if (*old != *new) {
7472 firstchange = idx;
7473 if ((*old == '\0' && *new == ':')
7474 || (*old == ':' && *new == '\0'))
7475 firstchange++;
7476 old = new; /* ignore subsequent differences */
7477 }
7478 if (*new == '\0')
7479 break;
7480 if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
7481 idx_bltin = idx;
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007482 if (*new == ':')
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007483 idx++;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007484 new++, old++;
7485 }
7486 if (builtinloc < 0 && idx_bltin >= 0)
7487 builtinloc = idx_bltin; /* zap builtins */
7488 if (builtinloc >= 0 && idx_bltin < 0)
7489 firstchange = 0;
7490 clearcmdentry(firstchange);
7491 builtinloc = idx_bltin;
7492}
7493
7494#define TEOF 0
7495#define TNL 1
7496#define TREDIR 2
7497#define TWORD 3
7498#define TSEMI 4
7499#define TBACKGND 5
7500#define TAND 6
7501#define TOR 7
7502#define TPIPE 8
7503#define TLP 9
7504#define TRP 10
7505#define TENDCASE 11
7506#define TENDBQUOTE 12
7507#define TNOT 13
7508#define TCASE 14
7509#define TDO 15
7510#define TDONE 16
7511#define TELIF 17
7512#define TELSE 18
7513#define TESAC 19
7514#define TFI 20
7515#define TFOR 21
7516#define TIF 22
7517#define TIN 23
7518#define TTHEN 24
7519#define TUNTIL 25
7520#define TWHILE 26
7521#define TBEGIN 27
7522#define TEND 28
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007523typedef smallint token_id_t;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007524
7525/* first char is indicating which tokens mark the end of a list */
7526static const char *const tokname_array[] = {
7527 "\1end of file",
7528 "\0newline",
7529 "\0redirection",
7530 "\0word",
7531 "\0;",
7532 "\0&",
7533 "\0&&",
7534 "\0||",
7535 "\0|",
7536 "\0(",
7537 "\1)",
7538 "\1;;",
7539 "\1`",
7540#define KWDOFFSET 13
7541 /* the following are keywords */
7542 "\0!",
7543 "\0case",
7544 "\1do",
7545 "\1done",
7546 "\1elif",
7547 "\1else",
7548 "\1esac",
7549 "\1fi",
7550 "\0for",
7551 "\0if",
7552 "\0in",
7553 "\1then",
7554 "\0until",
7555 "\0while",
7556 "\0{",
7557 "\1}",
7558};
7559
7560static const char *
7561tokname(int tok)
7562{
7563 static char buf[16];
7564
Denis Vlasenko240a1cf2007-04-08 16:07:02 +00007565//try this:
7566//if (tok < TSEMI) return tokname_array[tok] + 1;
7567//sprintf(buf, "\"%s\"", tokname_array[tok] + 1);
7568//return buf;
7569
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007570 if (tok >= TSEMI)
7571 buf[0] = '"';
7572 sprintf(buf + (tok >= TSEMI), "%s%c",
7573 tokname_array[tok] + 1, (tok >= TSEMI ? '"' : 0));
7574 return buf;
7575}
7576
7577/* Wrapper around strcmp for qsort/bsearch/... */
7578static int
7579pstrcmp(const void *a, const void *b)
7580{
Denis Vlasenko240a1cf2007-04-08 16:07:02 +00007581 return strcmp((char*) a, (*(char**) b) + 1);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007582}
7583
7584static const char *const *
7585findkwd(const char *s)
7586{
7587 return bsearch(s, tokname_array + KWDOFFSET,
Denis Vlasenko80b8b392007-06-25 10:55:35 +00007588 ARRAY_SIZE(tokname_array) - KWDOFFSET,
7589 sizeof(tokname_array[0]), pstrcmp);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007590}
7591
7592/*
7593 * Locate and print what a word is...
7594 */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007595static int
7596describe_command(char *command, int describe_command_verbose)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007597{
7598 struct cmdentry entry;
7599 struct tblentry *cmdp;
7600#if ENABLE_ASH_ALIAS
7601 const struct alias *ap;
7602#endif
7603 const char *path = pathval();
7604
7605 if (describe_command_verbose) {
7606 out1str(command);
7607 }
7608
7609 /* First look at the keywords */
7610 if (findkwd(command)) {
7611 out1str(describe_command_verbose ? " is a shell keyword" : command);
7612 goto out;
7613 }
7614
7615#if ENABLE_ASH_ALIAS
7616 /* Then look at the aliases */
7617 ap = lookupalias(command, 0);
7618 if (ap != NULL) {
Denis Vlasenko46846e22007-05-20 13:08:31 +00007619 if (!describe_command_verbose) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007620 out1str("alias ");
7621 printalias(ap);
7622 return 0;
7623 }
Denis Vlasenko46846e22007-05-20 13:08:31 +00007624 out1fmt(" is an alias for %s", ap->val);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007625 goto out;
7626 }
7627#endif
7628 /* Then check if it is a tracked alias */
7629 cmdp = cmdlookup(command, 0);
7630 if (cmdp != NULL) {
7631 entry.cmdtype = cmdp->cmdtype;
7632 entry.u = cmdp->param;
7633 } else {
7634 /* Finally use brute force */
7635 find_command(command, &entry, DO_ABS, path);
7636 }
7637
7638 switch (entry.cmdtype) {
7639 case CMDNORMAL: {
7640 int j = entry.u.index;
7641 char *p;
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00007642 if (j < 0) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007643 p = command;
7644 } else {
7645 do {
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02007646 p = path_advance(&path, command);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007647 stunalloc(p);
7648 } while (--j >= 0);
7649 }
7650 if (describe_command_verbose) {
7651 out1fmt(" is%s %s",
7652 (cmdp ? " a tracked alias for" : nullstr), p
7653 );
7654 } else {
7655 out1str(p);
7656 }
7657 break;
7658 }
7659
7660 case CMDFUNCTION:
7661 if (describe_command_verbose) {
7662 out1str(" is a shell function");
7663 } else {
7664 out1str(command);
7665 }
7666 break;
7667
7668 case CMDBUILTIN:
7669 if (describe_command_verbose) {
7670 out1fmt(" is a %sshell builtin",
7671 IS_BUILTIN_SPECIAL(entry.u.cmd) ?
7672 "special " : nullstr
7673 );
7674 } else {
7675 out1str(command);
7676 }
7677 break;
7678
7679 default:
7680 if (describe_command_verbose) {
7681 out1str(": not found\n");
7682 }
7683 return 127;
7684 }
7685 out:
Denys Vlasenko285ad152009-12-04 23:02:27 +01007686 out1str("\n");
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007687 return 0;
7688}
7689
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007690static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00007691typecmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007692{
Denis Vlasenko46846e22007-05-20 13:08:31 +00007693 int i = 1;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007694 int err = 0;
Denis Vlasenko46846e22007-05-20 13:08:31 +00007695 int verbose = 1;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007696
Denis Vlasenko46846e22007-05-20 13:08:31 +00007697 /* type -p ... ? (we don't bother checking for 'p') */
Denis Vlasenko1fc62382007-06-25 22:55:34 +00007698 if (argv[1] && argv[1][0] == '-') {
Denis Vlasenko46846e22007-05-20 13:08:31 +00007699 i++;
7700 verbose = 0;
7701 }
Denis Vlasenko68404f12008-03-17 09:00:54 +00007702 while (argv[i]) {
Denis Vlasenko46846e22007-05-20 13:08:31 +00007703 err |= describe_command(argv[i++], verbose);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007704 }
7705 return err;
7706}
7707
7708#if ENABLE_ASH_CMDCMD
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007709static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00007710commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007711{
7712 int c;
7713 enum {
7714 VERIFY_BRIEF = 1,
7715 VERIFY_VERBOSE = 2,
7716 } verify = 0;
7717
7718 while ((c = nextopt("pvV")) != '\0')
7719 if (c == 'V')
7720 verify |= VERIFY_VERBOSE;
7721 else if (c == 'v')
7722 verify |= VERIFY_BRIEF;
7723#if DEBUG
7724 else if (c != 'p')
7725 abort();
7726#endif
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00007727 /* Mimic bash: just "command -v" doesn't complain, it's a nop */
7728 if (verify && (*argptr != NULL)) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007729 return describe_command(*argptr, verify - VERIFY_BRIEF);
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00007730 }
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007731
7732 return 0;
7733}
7734#endif
7735
7736
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007737/* ============ eval.c */
Eric Andersencb57d552001-06-28 07:25:16 +00007738
Denis Vlasenko340299a2008-11-21 10:36:36 +00007739static int funcblocksize; /* size of structures in function */
7740static int funcstringsize; /* size of strings in node */
7741static void *funcblock; /* block to allocate function from */
7742static char *funcstring; /* block to allocate strings from */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007743
Eric Andersencb57d552001-06-28 07:25:16 +00007744/* flags in argument to evaltree */
Denis Vlasenko340299a2008-11-21 10:36:36 +00007745#define EV_EXIT 01 /* exit after evaluating tree */
7746#define EV_TESTED 02 /* exit status is checked; ignore -e flag */
Eric Andersenc470f442003-07-28 09:56:35 +00007747#define EV_BACKCMD 04 /* command executing within back quotes */
Eric Andersencb57d552001-06-28 07:25:16 +00007748
Denys Vlasenko0e5e4ea2009-10-11 00:36:20 +02007749static const uint8_t nodesize[N_NUMBER] = {
Denis Vlasenko340299a2008-11-21 10:36:36 +00007750 [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
7751 [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
7752 [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
7753 [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
7754 [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
7755 [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
7756 [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
7757 [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
7758 [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
7759 [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
7760 [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
7761 [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
7762 [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
7763 [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
7764 [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
7765 [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
7766 [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
Denis Vlasenkocc5feab2008-11-22 01:32:40 +00007767#if ENABLE_ASH_BASH_COMPAT
Denis Vlasenko340299a2008-11-21 10:36:36 +00007768 [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
Denis Vlasenkocc5feab2008-11-22 01:32:40 +00007769#endif
Denis Vlasenko340299a2008-11-21 10:36:36 +00007770 [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
7771 [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
7772 [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
7773 [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
7774 [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
7775 [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
7776 [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
7777 [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
7778 [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007779};
7780
7781static void calcsize(union node *n);
7782
7783static void
7784sizenodelist(struct nodelist *lp)
7785{
7786 while (lp) {
7787 funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
7788 calcsize(lp->n);
7789 lp = lp->next;
7790 }
7791}
7792
7793static void
7794calcsize(union node *n)
7795{
7796 if (n == NULL)
7797 return;
7798 funcblocksize += nodesize[n->type];
7799 switch (n->type) {
7800 case NCMD:
7801 calcsize(n->ncmd.redirect);
7802 calcsize(n->ncmd.args);
7803 calcsize(n->ncmd.assign);
7804 break;
7805 case NPIPE:
7806 sizenodelist(n->npipe.cmdlist);
7807 break;
7808 case NREDIR:
7809 case NBACKGND:
7810 case NSUBSHELL:
7811 calcsize(n->nredir.redirect);
7812 calcsize(n->nredir.n);
7813 break;
7814 case NAND:
7815 case NOR:
7816 case NSEMI:
7817 case NWHILE:
7818 case NUNTIL:
7819 calcsize(n->nbinary.ch2);
7820 calcsize(n->nbinary.ch1);
7821 break;
7822 case NIF:
7823 calcsize(n->nif.elsepart);
7824 calcsize(n->nif.ifpart);
7825 calcsize(n->nif.test);
7826 break;
7827 case NFOR:
7828 funcstringsize += strlen(n->nfor.var) + 1;
7829 calcsize(n->nfor.body);
7830 calcsize(n->nfor.args);
7831 break;
7832 case NCASE:
7833 calcsize(n->ncase.cases);
7834 calcsize(n->ncase.expr);
7835 break;
7836 case NCLIST:
7837 calcsize(n->nclist.body);
7838 calcsize(n->nclist.pattern);
7839 calcsize(n->nclist.next);
7840 break;
7841 case NDEFUN:
7842 case NARG:
7843 sizenodelist(n->narg.backquote);
7844 funcstringsize += strlen(n->narg.text) + 1;
7845 calcsize(n->narg.next);
7846 break;
7847 case NTO:
Denis Vlasenko559691a2008-10-05 18:39:31 +00007848#if ENABLE_ASH_BASH_COMPAT
7849 case NTO2:
7850#endif
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007851 case NCLOBBER:
7852 case NFROM:
7853 case NFROMTO:
7854 case NAPPEND:
7855 calcsize(n->nfile.fname);
7856 calcsize(n->nfile.next);
7857 break;
7858 case NTOFD:
7859 case NFROMFD:
7860 calcsize(n->ndup.vname);
7861 calcsize(n->ndup.next);
7862 break;
7863 case NHERE:
7864 case NXHERE:
7865 calcsize(n->nhere.doc);
7866 calcsize(n->nhere.next);
7867 break;
7868 case NNOT:
7869 calcsize(n->nnot.com);
7870 break;
7871 };
7872}
7873
7874static char *
7875nodeckstrdup(char *s)
7876{
7877 char *rtn = funcstring;
7878
7879 strcpy(funcstring, s);
7880 funcstring += strlen(s) + 1;
7881 return rtn;
7882}
7883
7884static union node *copynode(union node *);
7885
7886static struct nodelist *
7887copynodelist(struct nodelist *lp)
7888{
7889 struct nodelist *start;
7890 struct nodelist **lpp;
7891
7892 lpp = &start;
7893 while (lp) {
7894 *lpp = funcblock;
7895 funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
7896 (*lpp)->n = copynode(lp->n);
7897 lp = lp->next;
7898 lpp = &(*lpp)->next;
7899 }
7900 *lpp = NULL;
7901 return start;
7902}
7903
7904static union node *
7905copynode(union node *n)
7906{
7907 union node *new;
7908
7909 if (n == NULL)
7910 return NULL;
7911 new = funcblock;
7912 funcblock = (char *) funcblock + nodesize[n->type];
7913
7914 switch (n->type) {
7915 case NCMD:
7916 new->ncmd.redirect = copynode(n->ncmd.redirect);
7917 new->ncmd.args = copynode(n->ncmd.args);
7918 new->ncmd.assign = copynode(n->ncmd.assign);
7919 break;
7920 case NPIPE:
7921 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00007922 new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007923 break;
7924 case NREDIR:
7925 case NBACKGND:
7926 case NSUBSHELL:
7927 new->nredir.redirect = copynode(n->nredir.redirect);
7928 new->nredir.n = copynode(n->nredir.n);
7929 break;
7930 case NAND:
7931 case NOR:
7932 case NSEMI:
7933 case NWHILE:
7934 case NUNTIL:
7935 new->nbinary.ch2 = copynode(n->nbinary.ch2);
7936 new->nbinary.ch1 = copynode(n->nbinary.ch1);
7937 break;
7938 case NIF:
7939 new->nif.elsepart = copynode(n->nif.elsepart);
7940 new->nif.ifpart = copynode(n->nif.ifpart);
7941 new->nif.test = copynode(n->nif.test);
7942 break;
7943 case NFOR:
7944 new->nfor.var = nodeckstrdup(n->nfor.var);
7945 new->nfor.body = copynode(n->nfor.body);
7946 new->nfor.args = copynode(n->nfor.args);
7947 break;
7948 case NCASE:
7949 new->ncase.cases = copynode(n->ncase.cases);
7950 new->ncase.expr = copynode(n->ncase.expr);
7951 break;
7952 case NCLIST:
7953 new->nclist.body = copynode(n->nclist.body);
7954 new->nclist.pattern = copynode(n->nclist.pattern);
7955 new->nclist.next = copynode(n->nclist.next);
7956 break;
7957 case NDEFUN:
7958 case NARG:
7959 new->narg.backquote = copynodelist(n->narg.backquote);
7960 new->narg.text = nodeckstrdup(n->narg.text);
7961 new->narg.next = copynode(n->narg.next);
7962 break;
7963 case NTO:
Denis Vlasenko559691a2008-10-05 18:39:31 +00007964#if ENABLE_ASH_BASH_COMPAT
7965 case NTO2:
7966#endif
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007967 case NCLOBBER:
7968 case NFROM:
7969 case NFROMTO:
7970 case NAPPEND:
7971 new->nfile.fname = copynode(n->nfile.fname);
7972 new->nfile.fd = n->nfile.fd;
7973 new->nfile.next = copynode(n->nfile.next);
7974 break;
7975 case NTOFD:
7976 case NFROMFD:
7977 new->ndup.vname = copynode(n->ndup.vname);
7978 new->ndup.dupfd = n->ndup.dupfd;
7979 new->ndup.fd = n->ndup.fd;
7980 new->ndup.next = copynode(n->ndup.next);
7981 break;
7982 case NHERE:
7983 case NXHERE:
7984 new->nhere.doc = copynode(n->nhere.doc);
7985 new->nhere.fd = n->nhere.fd;
7986 new->nhere.next = copynode(n->nhere.next);
7987 break;
7988 case NNOT:
7989 new->nnot.com = copynode(n->nnot.com);
7990 break;
7991 };
7992 new->type = n->type;
7993 return new;
7994}
7995
7996/*
7997 * Make a copy of a parse tree.
7998 */
7999static struct funcnode *
8000copyfunc(union node *n)
8001{
8002 struct funcnode *f;
8003 size_t blocksize;
8004
8005 funcblocksize = offsetof(struct funcnode, n);
8006 funcstringsize = 0;
8007 calcsize(n);
8008 blocksize = funcblocksize;
8009 f = ckmalloc(blocksize + funcstringsize);
8010 funcblock = (char *) f + offsetof(struct funcnode, n);
8011 funcstring = (char *) f + blocksize;
8012 copynode(n);
8013 f->count = 0;
8014 return f;
8015}
8016
8017/*
8018 * Define a shell function.
8019 */
8020static void
8021defun(char *name, union node *func)
8022{
8023 struct cmdentry entry;
8024
8025 INT_OFF;
8026 entry.cmdtype = CMDFUNCTION;
8027 entry.u.func = copyfunc(func);
8028 addcmdentry(name, &entry);
8029 INT_ON;
8030}
8031
Denis Vlasenko4b875702009-03-19 13:30:04 +00008032/* Reasons for skipping commands (see comment on breakcmd routine) */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008033#define SKIPBREAK (1 << 0)
8034#define SKIPCONT (1 << 1)
8035#define SKIPFUNC (1 << 2)
8036#define SKIPFILE (1 << 3)
8037#define SKIPEVAL (1 << 4)
Denis Vlasenko4b875702009-03-19 13:30:04 +00008038static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008039static int skipcount; /* number of levels to skip */
8040static int funcnest; /* depth of function calls */
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +00008041static int loopnest; /* current loop nesting level */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008042
Denis Vlasenko4b875702009-03-19 13:30:04 +00008043/* Forward decl way out to parsing code - dotrap needs it */
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008044static int evalstring(char *s, int mask);
8045
Denis Vlasenko4b875702009-03-19 13:30:04 +00008046/* Called to execute a trap.
8047 * Single callsite - at the end of evaltree().
8048 * If we return non-zero, exaltree raises EXEXIT exception.
8049 *
8050 * Perhaps we should avoid entering new trap handlers
8051 * while we are executing a trap handler. [is it a TODO?]
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008052 */
8053static int
8054dotrap(void)
8055{
Denis Vlasenko4b875702009-03-19 13:30:04 +00008056 uint8_t *g;
8057 int sig;
8058 uint8_t savestatus;
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008059
8060 savestatus = exitstatus;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02008061 pending_sig = 0;
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008062 xbarrier();
8063
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008064 TRACE(("dotrap entered\n"));
Denis Vlasenko4b875702009-03-19 13:30:04 +00008065 for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
8066 int want_exexit;
8067 char *t;
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008068
Denis Vlasenko4b875702009-03-19 13:30:04 +00008069 if (*g == 0)
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008070 continue;
Denis Vlasenko4b875702009-03-19 13:30:04 +00008071 t = trap[sig];
8072 /* non-trapped SIGINT is handled separately by raise_interrupt,
8073 * don't upset it by resetting gotsig[SIGINT-1] */
8074 if (sig == SIGINT && !t)
8075 continue;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008076
8077 TRACE(("sig %d is active, will run handler '%s'\n", sig, t));
Denis Vlasenko4b875702009-03-19 13:30:04 +00008078 *g = 0;
8079 if (!t)
8080 continue;
8081 want_exexit = evalstring(t, SKIPEVAL);
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008082 exitstatus = savestatus;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008083 if (want_exexit) {
Denis Vlasenkob21f3792009-03-19 23:09:58 +00008084 TRACE(("dotrap returns %d\n", want_exexit));
Denis Vlasenko4b875702009-03-19 13:30:04 +00008085 return want_exexit;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008086 }
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008087 }
8088
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008089 TRACE(("dotrap returns 0\n"));
Denis Vlasenko991a1da2008-02-10 19:02:53 +00008090 return 0;
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008091}
8092
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00008093/* forward declarations - evaluation is fairly recursive business... */
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008094static void evalloop(union node *, int);
8095static void evalfor(union node *, int);
8096static void evalcase(union node *, int);
8097static void evalsubshell(union node *, int);
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00008098static void expredir(union node *);
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008099static void evalpipe(union node *, int);
8100static void evalcommand(union node *, int);
Eric Andersenc470f442003-07-28 09:56:35 +00008101static int evalbltin(const struct builtincmd *, int, char **);
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008102static void prehash(union node *);
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00008103
Eric Andersen62483552001-07-10 06:09:16 +00008104/*
Eric Andersenc470f442003-07-28 09:56:35 +00008105 * Evaluate a parse tree. The value is left in the global variable
8106 * exitstatus.
Eric Andersen62483552001-07-10 06:09:16 +00008107 */
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008108static void
Eric Andersenc470f442003-07-28 09:56:35 +00008109evaltree(union node *n, int flags)
Eric Andersen62483552001-07-10 06:09:16 +00008110{
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008111 struct jmploc *volatile savehandler = exception_handler;
8112 struct jmploc jmploc;
Eric Andersenc470f442003-07-28 09:56:35 +00008113 int checkexit = 0;
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008114 void (*evalfn)(union node *, int);
Eric Andersenc470f442003-07-28 09:56:35 +00008115 int status;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008116 int int_level;
8117
8118 SAVE_INT(int_level);
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008119
Eric Andersenc470f442003-07-28 09:56:35 +00008120 if (n == NULL) {
8121 TRACE(("evaltree(NULL) called\n"));
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008122 goto out1;
Eric Andersen62483552001-07-10 06:09:16 +00008123 }
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008124 TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008125
8126 exception_handler = &jmploc;
8127 {
8128 int err = setjmp(jmploc.loc);
8129 if (err) {
8130 /* if it was a signal, check for trap handlers */
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008131 if (exception_type == EXSIG) {
Denis Vlasenkob21f3792009-03-19 23:09:58 +00008132 TRACE(("exception %d (EXSIG) in evaltree, err=%d\n",
8133 exception_type, err));
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008134 goto out;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008135 }
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008136 /* continue on the way out */
Denis Vlasenkob21f3792009-03-19 23:09:58 +00008137 TRACE(("exception %d in evaltree, propagating err=%d\n",
8138 exception_type, err));
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008139 exception_handler = savehandler;
8140 longjmp(exception_handler->loc, err);
8141 }
8142 }
8143
Eric Andersenc470f442003-07-28 09:56:35 +00008144 switch (n->type) {
8145 default:
Denis Vlasenkoa7189f02006-11-17 20:29:00 +00008146#if DEBUG
Eric Andersenc470f442003-07-28 09:56:35 +00008147 out1fmt("Node type = %d\n", n->type);
Denys Vlasenko8131eea2009-11-02 14:19:51 +01008148 fflush_all();
Eric Andersenc470f442003-07-28 09:56:35 +00008149 break;
8150#endif
8151 case NNOT:
8152 evaltree(n->nnot.com, EV_TESTED);
8153 status = !exitstatus;
8154 goto setstatus;
8155 case NREDIR:
8156 expredir(n->nredir.redirect);
8157 status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
8158 if (!status) {
8159 evaltree(n->nredir.n, flags & EV_TESTED);
8160 status = exitstatus;
8161 }
Denis Vlasenko34c73c42008-08-16 11:48:02 +00008162 popredir(/*drop:*/ 0, /*restore:*/ 0 /* not sure */);
Eric Andersenc470f442003-07-28 09:56:35 +00008163 goto setstatus;
8164 case NCMD:
8165 evalfn = evalcommand;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008166 checkexit:
Eric Andersenc470f442003-07-28 09:56:35 +00008167 if (eflag && !(flags & EV_TESTED))
8168 checkexit = ~0;
8169 goto calleval;
8170 case NFOR:
8171 evalfn = evalfor;
8172 goto calleval;
8173 case NWHILE:
8174 case NUNTIL:
8175 evalfn = evalloop;
8176 goto calleval;
8177 case NSUBSHELL:
8178 case NBACKGND:
8179 evalfn = evalsubshell;
8180 goto calleval;
8181 case NPIPE:
8182 evalfn = evalpipe;
8183 goto checkexit;
8184 case NCASE:
8185 evalfn = evalcase;
8186 goto calleval;
8187 case NAND:
8188 case NOR:
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008189 case NSEMI: {
8190
Eric Andersenc470f442003-07-28 09:56:35 +00008191#if NAND + 1 != NOR
8192#error NAND + 1 != NOR
8193#endif
8194#if NOR + 1 != NSEMI
8195#error NOR + 1 != NSEMI
8196#endif
Denis Vlasenko87d5fd92008-07-26 13:48:35 +00008197 unsigned is_or = n->type - NAND;
Eric Andersenc470f442003-07-28 09:56:35 +00008198 evaltree(
8199 n->nbinary.ch1,
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008200 (flags | ((is_or >> 1) - 1)) & EV_TESTED
Eric Andersenc470f442003-07-28 09:56:35 +00008201 );
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008202 if (!exitstatus == is_or)
Eric Andersenc470f442003-07-28 09:56:35 +00008203 break;
8204 if (!evalskip) {
8205 n = n->nbinary.ch2;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008206 evaln:
Eric Andersenc470f442003-07-28 09:56:35 +00008207 evalfn = evaltree;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008208 calleval:
Eric Andersenc470f442003-07-28 09:56:35 +00008209 evalfn(n, flags);
8210 break;
8211 }
8212 break;
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008213 }
Eric Andersenc470f442003-07-28 09:56:35 +00008214 case NIF:
8215 evaltree(n->nif.test, EV_TESTED);
8216 if (evalskip)
8217 break;
8218 if (exitstatus == 0) {
8219 n = n->nif.ifpart;
8220 goto evaln;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008221 }
8222 if (n->nif.elsepart) {
Eric Andersenc470f442003-07-28 09:56:35 +00008223 n = n->nif.elsepart;
8224 goto evaln;
8225 }
8226 goto success;
8227 case NDEFUN:
8228 defun(n->narg.text, n->narg.next);
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008229 success:
Eric Andersenc470f442003-07-28 09:56:35 +00008230 status = 0;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008231 setstatus:
Eric Andersenc470f442003-07-28 09:56:35 +00008232 exitstatus = status;
8233 break;
8234 }
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008235
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008236 out:
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008237 exception_handler = savehandler;
8238 out1:
8239 if (checkexit & exitstatus)
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00008240 evalskip |= SKIPEVAL;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02008241 else if (pending_sig && dotrap())
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00008242 goto exexit;
8243
8244 if (flags & EV_EXIT) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008245 exexit:
Denis Vlasenkob012b102007-02-19 22:43:01 +00008246 raise_exception(EXEXIT);
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00008247 }
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008248
8249 RESTORE_INT(int_level);
8250 TRACE(("leaving evaltree (no interrupts)\n"));
Eric Andersen62483552001-07-10 06:09:16 +00008251}
8252
Eric Andersenc470f442003-07-28 09:56:35 +00008253#if !defined(__alpha__) || (defined(__GNUC__) && __GNUC__ >= 3)
8254static
8255#endif
8256void evaltreenr(union node *, int) __attribute__ ((alias("evaltree"),__noreturn__));
8257
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008258static void
Eric Andersenc470f442003-07-28 09:56:35 +00008259evalloop(union node *n, int flags)
Eric Andersencb57d552001-06-28 07:25:16 +00008260{
8261 int status;
8262
8263 loopnest++;
8264 status = 0;
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008265 flags &= EV_TESTED;
Eric Andersencb57d552001-06-28 07:25:16 +00008266 for (;;) {
Eric Andersenc470f442003-07-28 09:56:35 +00008267 int i;
8268
Eric Andersencb57d552001-06-28 07:25:16 +00008269 evaltree(n->nbinary.ch1, EV_TESTED);
8270 if (evalskip) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008271 skipping:
8272 if (evalskip == SKIPCONT && --skipcount <= 0) {
Eric Andersencb57d552001-06-28 07:25:16 +00008273 evalskip = 0;
8274 continue;
8275 }
8276 if (evalskip == SKIPBREAK && --skipcount <= 0)
8277 evalskip = 0;
8278 break;
8279 }
Eric Andersenc470f442003-07-28 09:56:35 +00008280 i = exitstatus;
8281 if (n->type != NWHILE)
8282 i = !i;
8283 if (i != 0)
8284 break;
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008285 evaltree(n->nbinary.ch2, flags);
Eric Andersencb57d552001-06-28 07:25:16 +00008286 status = exitstatus;
8287 if (evalskip)
8288 goto skipping;
8289 }
8290 loopnest--;
8291 exitstatus = status;
8292}
8293
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008294static void
Eric Andersenc470f442003-07-28 09:56:35 +00008295evalfor(union node *n, int flags)
Eric Andersencb57d552001-06-28 07:25:16 +00008296{
8297 struct arglist arglist;
8298 union node *argp;
8299 struct strlist *sp;
8300 struct stackmark smark;
8301
8302 setstackmark(&smark);
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00008303 arglist.list = NULL;
Eric Andersencb57d552001-06-28 07:25:16 +00008304 arglist.lastp = &arglist.list;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008305 for (argp = n->nfor.args; argp; argp = argp->narg.next) {
Eric Andersencb57d552001-06-28 07:25:16 +00008306 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE | EXP_RECORD);
Eric Andersenc470f442003-07-28 09:56:35 +00008307 /* XXX */
Eric Andersencb57d552001-06-28 07:25:16 +00008308 if (evalskip)
8309 goto out;
8310 }
8311 *arglist.lastp = NULL;
8312
8313 exitstatus = 0;
8314 loopnest++;
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008315 flags &= EV_TESTED;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008316 for (sp = arglist.list; sp; sp = sp->next) {
Eric Andersencb57d552001-06-28 07:25:16 +00008317 setvar(n->nfor.var, sp->text, 0);
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008318 evaltree(n->nfor.body, flags);
Eric Andersencb57d552001-06-28 07:25:16 +00008319 if (evalskip) {
8320 if (evalskip == SKIPCONT && --skipcount <= 0) {
8321 evalskip = 0;
8322 continue;
8323 }
8324 if (evalskip == SKIPBREAK && --skipcount <= 0)
8325 evalskip = 0;
8326 break;
8327 }
8328 }
8329 loopnest--;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008330 out:
Eric Andersencb57d552001-06-28 07:25:16 +00008331 popstackmark(&smark);
8332}
8333
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008334static void
Eric Andersenc470f442003-07-28 09:56:35 +00008335evalcase(union node *n, int flags)
Eric Andersencb57d552001-06-28 07:25:16 +00008336{
8337 union node *cp;
8338 union node *patp;
8339 struct arglist arglist;
8340 struct stackmark smark;
8341
8342 setstackmark(&smark);
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00008343 arglist.list = NULL;
Eric Andersencb57d552001-06-28 07:25:16 +00008344 arglist.lastp = &arglist.list;
Eric Andersencb57d552001-06-28 07:25:16 +00008345 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
Eric Andersenc470f442003-07-28 09:56:35 +00008346 exitstatus = 0;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008347 for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
8348 for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
Eric Andersencb57d552001-06-28 07:25:16 +00008349 if (casematch(patp, arglist.list->text)) {
8350 if (evalskip == 0) {
8351 evaltree(cp->nclist.body, flags);
8352 }
8353 goto out;
8354 }
8355 }
8356 }
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008357 out:
Eric Andersencb57d552001-06-28 07:25:16 +00008358 popstackmark(&smark);
8359}
8360
Eric Andersenc470f442003-07-28 09:56:35 +00008361/*
8362 * Kick off a subshell to evaluate a tree.
8363 */
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008364static void
Eric Andersenc470f442003-07-28 09:56:35 +00008365evalsubshell(union node *n, int flags)
8366{
8367 struct job *jp;
8368 int backgnd = (n->type == NBACKGND);
8369 int status;
8370
8371 expredir(n->nredir.redirect);
8372 if (!backgnd && flags & EV_EXIT && !trap[0])
8373 goto nofork;
Denis Vlasenkob012b102007-02-19 22:43:01 +00008374 INT_OFF;
Denis Vlasenko68404f12008-03-17 09:00:54 +00008375 jp = makejob(/*n,*/ 1);
Eric Andersenc470f442003-07-28 09:56:35 +00008376 if (forkshell(jp, n, backgnd) == 0) {
Denis Vlasenkob012b102007-02-19 22:43:01 +00008377 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00008378 flags |= EV_EXIT;
8379 if (backgnd)
8380 flags &=~ EV_TESTED;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00008381 nofork:
Eric Andersenc470f442003-07-28 09:56:35 +00008382 redirect(n->nredir.redirect, 0);
8383 evaltreenr(n->nredir.n, flags);
8384 /* never returns */
8385 }
8386 status = 0;
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00008387 if (!backgnd)
Eric Andersenc470f442003-07-28 09:56:35 +00008388 status = waitforjob(jp);
8389 exitstatus = status;
Denis Vlasenkob012b102007-02-19 22:43:01 +00008390 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00008391}
8392
Eric Andersenc470f442003-07-28 09:56:35 +00008393/*
8394 * Compute the names of the files in a redirection list.
8395 */
Denis Vlasenko99eb8502007-02-23 21:09:49 +00008396static void fixredir(union node *, const char *, int);
Eric Andersenc470f442003-07-28 09:56:35 +00008397static void
8398expredir(union node *n)
8399{
8400 union node *redir;
8401
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008402 for (redir = n; redir; redir = redir->nfile.next) {
Eric Andersenc470f442003-07-28 09:56:35 +00008403 struct arglist fn;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008404
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00008405 fn.list = NULL;
Eric Andersenc470f442003-07-28 09:56:35 +00008406 fn.lastp = &fn.list;
8407 switch (redir->type) {
8408 case NFROMTO:
8409 case NFROM:
8410 case NTO:
Denis Vlasenko559691a2008-10-05 18:39:31 +00008411#if ENABLE_ASH_BASH_COMPAT
8412 case NTO2:
8413#endif
Eric Andersenc470f442003-07-28 09:56:35 +00008414 case NCLOBBER:
8415 case NAPPEND:
8416 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
Denis Vlasenko559691a2008-10-05 18:39:31 +00008417#if ENABLE_ASH_BASH_COMPAT
8418 store_expfname:
8419#endif
Eric Andersenc470f442003-07-28 09:56:35 +00008420 redir->nfile.expfname = fn.list->text;
8421 break;
8422 case NFROMFD:
Denis Vlasenko559691a2008-10-05 18:39:31 +00008423 case NTOFD: /* >& */
Eric Andersenc470f442003-07-28 09:56:35 +00008424 if (redir->ndup.vname) {
8425 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008426 if (fn.list == NULL)
Denis Vlasenkob012b102007-02-19 22:43:01 +00008427 ash_msg_and_raise_error("redir error");
Denis Vlasenko559691a2008-10-05 18:39:31 +00008428#if ENABLE_ASH_BASH_COMPAT
8429//FIXME: we used expandarg with different args!
8430 if (!isdigit_str9(fn.list->text)) {
8431 /* >&file, not >&fd */
8432 if (redir->nfile.fd != 1) /* 123>&file - BAD */
8433 ash_msg_and_raise_error("redir error");
8434 redir->type = NTO2;
8435 goto store_expfname;
8436 }
8437#endif
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008438 fixredir(redir, fn.list->text, 1);
Eric Andersenc470f442003-07-28 09:56:35 +00008439 }
8440 break;
8441 }
8442 }
8443}
8444
Eric Andersencb57d552001-06-28 07:25:16 +00008445/*
Eric Andersencb57d552001-06-28 07:25:16 +00008446 * Evaluate a pipeline. All the processes in the pipeline are children
8447 * of the process creating the pipeline. (This differs from some versions
8448 * of the shell, which make the last process in a pipeline the parent
8449 * of all the rest.)
8450 */
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008451static void
Eric Andersenc470f442003-07-28 09:56:35 +00008452evalpipe(union node *n, int flags)
Eric Andersencb57d552001-06-28 07:25:16 +00008453{
8454 struct job *jp;
8455 struct nodelist *lp;
8456 int pipelen;
8457 int prevfd;
8458 int pip[2];
8459
Eric Andersenc470f442003-07-28 09:56:35 +00008460 TRACE(("evalpipe(0x%lx) called\n", (long)n));
Eric Andersencb57d552001-06-28 07:25:16 +00008461 pipelen = 0;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008462 for (lp = n->npipe.cmdlist; lp; lp = lp->next)
Eric Andersencb57d552001-06-28 07:25:16 +00008463 pipelen++;
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008464 flags |= EV_EXIT;
Denis Vlasenkob012b102007-02-19 22:43:01 +00008465 INT_OFF;
Denis Vlasenko68404f12008-03-17 09:00:54 +00008466 jp = makejob(/*n,*/ pipelen);
Eric Andersencb57d552001-06-28 07:25:16 +00008467 prevfd = -1;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008468 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008469 prehash(lp->n);
Eric Andersencb57d552001-06-28 07:25:16 +00008470 pip[1] = -1;
8471 if (lp->next) {
8472 if (pipe(pip) < 0) {
8473 close(prevfd);
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00008474 ash_msg_and_raise_error("pipe call failed");
Eric Andersencb57d552001-06-28 07:25:16 +00008475 }
8476 }
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00008477 if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
Denis Vlasenkob012b102007-02-19 22:43:01 +00008478 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00008479 if (pip[1] >= 0) {
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008480 close(pip[0]);
Eric Andersencb57d552001-06-28 07:25:16 +00008481 }
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008482 if (prevfd > 0) {
8483 dup2(prevfd, 0);
8484 close(prevfd);
8485 }
8486 if (pip[1] > 1) {
8487 dup2(pip[1], 1);
8488 close(pip[1]);
8489 }
Eric Andersenc470f442003-07-28 09:56:35 +00008490 evaltreenr(lp->n, flags);
8491 /* never returns */
Eric Andersencb57d552001-06-28 07:25:16 +00008492 }
8493 if (prevfd >= 0)
8494 close(prevfd);
8495 prevfd = pip[0];
Denis Vlasenkob9e70dd2009-03-20 01:24:08 +00008496 /* Don't want to trigger debugging */
8497 if (pip[1] != -1)
8498 close(pip[1]);
Eric Andersencb57d552001-06-28 07:25:16 +00008499 }
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00008500 if (n->npipe.pipe_backgnd == 0) {
Eric Andersencb57d552001-06-28 07:25:16 +00008501 exitstatus = waitforjob(jp);
8502 TRACE(("evalpipe: job done exit status %d\n", exitstatus));
Eric Andersencb57d552001-06-28 07:25:16 +00008503 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00008504 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00008505}
8506
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008507/*
8508 * Controls whether the shell is interactive or not.
8509 */
8510static void
8511setinteractive(int on)
8512{
Denis Vlasenkob07a4962008-06-22 13:16:23 +00008513 static smallint is_interactive;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008514
8515 if (++on == is_interactive)
8516 return;
8517 is_interactive = on;
8518 setsignal(SIGINT);
8519 setsignal(SIGQUIT);
8520 setsignal(SIGTERM);
8521#if !ENABLE_FEATURE_SH_EXTRA_QUIET
8522 if (is_interactive > 1) {
8523 /* Looks like they want an interactive shell */
Denis Vlasenkoca525b42007-06-13 12:27:17 +00008524 static smallint did_banner;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008525
Denis Vlasenkoca525b42007-06-13 12:27:17 +00008526 if (!did_banner) {
Denys Vlasenkoc34c0332009-09-29 12:25:30 +02008527 /* note: ash and hush share this string */
8528 out1fmt("\n\n%s %s\n"
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008529 "Enter 'help' for a list of built-in commands."
8530 "\n\n",
Denys Vlasenkoc34c0332009-09-29 12:25:30 +02008531 bb_banner,
8532 "built-in shell (ash)"
8533 );
Denis Vlasenkoca525b42007-06-13 12:27:17 +00008534 did_banner = 1;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008535 }
8536 }
8537#endif
8538}
8539
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008540static void
8541optschanged(void)
8542{
8543#if DEBUG
8544 opentrace();
8545#endif
8546 setinteractive(iflag);
8547 setjobctl(mflag);
Denis Vlasenkob07a4962008-06-22 13:16:23 +00008548#if ENABLE_FEATURE_EDITING_VI
8549 if (viflag)
8550 line_input_state->flags |= VI_MODE;
8551 else
8552 line_input_state->flags &= ~VI_MODE;
8553#else
8554 viflag = 0; /* forcibly keep the option off */
8555#endif
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008556}
8557
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008558static struct localvar *localvars;
8559
8560/*
8561 * Called after a function returns.
8562 * Interrupts must be off.
8563 */
8564static void
8565poplocalvars(void)
8566{
8567 struct localvar *lvp;
8568 struct var *vp;
8569
8570 while ((lvp = localvars) != NULL) {
8571 localvars = lvp->next;
8572 vp = lvp->vp;
Denys Vlasenko883cea42009-07-11 15:31:59 +02008573 TRACE(("poplocalvar %s\n", vp ? vp->text : "-"));
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008574 if (vp == NULL) { /* $- saved */
8575 memcpy(optlist, lvp->text, sizeof(optlist));
8576 free((char*)lvp->text);
8577 optschanged();
8578 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
8579 unsetvar(vp->text);
8580 } else {
8581 if (vp->func)
8582 (*vp->func)(strchrnul(lvp->text, '=') + 1);
8583 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
8584 free((char*)vp->text);
8585 vp->flags = lvp->flags;
8586 vp->text = lvp->text;
8587 }
8588 free(lvp);
8589 }
8590}
8591
8592static int
8593evalfun(struct funcnode *func, int argc, char **argv, int flags)
8594{
8595 volatile struct shparam saveparam;
8596 struct localvar *volatile savelocalvars;
8597 struct jmploc *volatile savehandler;
8598 struct jmploc jmploc;
8599 int e;
8600
8601 saveparam = shellparam;
8602 savelocalvars = localvars;
8603 e = setjmp(jmploc.loc);
8604 if (e) {
8605 goto funcdone;
8606 }
8607 INT_OFF;
8608 savehandler = exception_handler;
8609 exception_handler = &jmploc;
8610 localvars = NULL;
Denis Vlasenko01631112007-12-16 17:20:38 +00008611 shellparam.malloced = 0;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008612 func->count++;
8613 funcnest++;
8614 INT_ON;
8615 shellparam.nparam = argc - 1;
8616 shellparam.p = argv + 1;
8617#if ENABLE_ASH_GETOPTS
8618 shellparam.optind = 1;
8619 shellparam.optoff = -1;
8620#endif
8621 evaltree(&func->n, flags & EV_TESTED);
Denis Vlasenko01631112007-12-16 17:20:38 +00008622 funcdone:
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008623 INT_OFF;
8624 funcnest--;
8625 freefunc(func);
8626 poplocalvars();
8627 localvars = savelocalvars;
8628 freeparam(&shellparam);
8629 shellparam = saveparam;
8630 exception_handler = savehandler;
8631 INT_ON;
8632 evalskip &= ~SKIPFUNC;
8633 return e;
8634}
8635
Denis Vlasenko131ae172007-02-18 13:00:19 +00008636#if ENABLE_ASH_CMDCMD
Denis Vlasenkoaa744452007-02-23 01:04:22 +00008637static char **
8638parse_command_args(char **argv, const char **path)
Eric Andersenc470f442003-07-28 09:56:35 +00008639{
8640 char *cp, c;
8641
8642 for (;;) {
8643 cp = *++argv;
8644 if (!cp)
8645 return 0;
8646 if (*cp++ != '-')
8647 break;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008648 c = *cp++;
8649 if (!c)
Eric Andersenc470f442003-07-28 09:56:35 +00008650 break;
8651 if (c == '-' && !*cp) {
8652 argv++;
8653 break;
8654 }
8655 do {
8656 switch (c) {
8657 case 'p':
Denis Vlasenkof5f75c52007-06-12 22:35:19 +00008658 *path = bb_default_path;
Eric Andersenc470f442003-07-28 09:56:35 +00008659 break;
8660 default:
8661 /* run 'typecmd' for other options */
8662 return 0;
8663 }
Denis Vlasenko9650f362007-02-23 01:04:37 +00008664 c = *cp++;
8665 } while (c);
Eric Andersenc470f442003-07-28 09:56:35 +00008666 }
8667 return argv;
8668}
8669#endif
8670
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008671/*
8672 * Make a variable a local variable. When a variable is made local, it's
8673 * value and flags are saved in a localvar structure. The saved values
8674 * will be restored when the shell function returns. We handle the name
8675 * "-" as a special case.
8676 */
8677static void
8678mklocal(char *name)
8679{
8680 struct localvar *lvp;
8681 struct var **vpp;
8682 struct var *vp;
8683
8684 INT_OFF;
Denis Vlasenko838ffd52008-02-21 04:32:08 +00008685 lvp = ckzalloc(sizeof(struct localvar));
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008686 if (LONE_DASH(name)) {
8687 char *p;
8688 p = ckmalloc(sizeof(optlist));
8689 lvp->text = memcpy(p, optlist, sizeof(optlist));
8690 vp = NULL;
8691 } else {
8692 char *eq;
8693
8694 vpp = hashvar(name);
8695 vp = *findvar(vpp, name);
8696 eq = strchr(name, '=');
8697 if (vp == NULL) {
8698 if (eq)
8699 setvareq(name, VSTRFIXED);
8700 else
8701 setvar(name, NULL, VSTRFIXED);
8702 vp = *vpp; /* the new variable */
8703 lvp->flags = VUNSET;
8704 } else {
8705 lvp->text = vp->text;
8706 lvp->flags = vp->flags;
8707 vp->flags |= VSTRFIXED|VTEXTFIXED;
8708 if (eq)
8709 setvareq(name, 0);
8710 }
8711 }
8712 lvp->vp = vp;
8713 lvp->next = localvars;
8714 localvars = lvp;
8715 INT_ON;
8716}
8717
8718/*
8719 * The "local" command.
8720 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008721static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008722localcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008723{
8724 char *name;
8725
8726 argv = argptr;
8727 while ((name = *argv++) != NULL) {
8728 mklocal(name);
8729 }
8730 return 0;
8731}
8732
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008733static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008734falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008735{
8736 return 1;
8737}
8738
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008739static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008740truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008741{
8742 return 0;
8743}
8744
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008745static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008746execcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008747{
Denis Vlasenko68404f12008-03-17 09:00:54 +00008748 if (argv[1]) {
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008749 iflag = 0; /* exit on error */
8750 mflag = 0;
8751 optschanged();
8752 shellexec(argv + 1, pathval(), 0);
8753 }
8754 return 0;
8755}
8756
8757/*
8758 * The return command.
8759 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008760static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008761returncmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008762{
8763 /*
8764 * If called outside a function, do what ksh does;
8765 * skip the rest of the file.
8766 */
8767 evalskip = funcnest ? SKIPFUNC : SKIPFILE;
8768 return argv[1] ? number(argv[1]) : exitstatus;
8769}
8770
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008771/* Forward declarations for builtintab[] */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008772static int breakcmd(int, char **) FAST_FUNC;
8773static int dotcmd(int, char **) FAST_FUNC;
8774static int evalcmd(int, char **) FAST_FUNC;
8775static int exitcmd(int, char **) FAST_FUNC;
8776static int exportcmd(int, char **) FAST_FUNC;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008777#if ENABLE_ASH_GETOPTS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008778static int getoptscmd(int, char **) FAST_FUNC;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008779#endif
Denis Vlasenko52764022007-02-24 13:42:56 +00008780#if !ENABLE_FEATURE_SH_EXTRA_QUIET
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008781static int helpcmd(int, char **) FAST_FUNC;
Denis Vlasenko52764022007-02-24 13:42:56 +00008782#endif
Mike Frysinger98c52642009-04-02 10:02:37 +00008783#if ENABLE_SH_MATH_SUPPORT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008784static int letcmd(int, char **) FAST_FUNC;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008785#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008786static int readcmd(int, char **) FAST_FUNC;
8787static int setcmd(int, char **) FAST_FUNC;
8788static int shiftcmd(int, char **) FAST_FUNC;
8789static int timescmd(int, char **) FAST_FUNC;
8790static int trapcmd(int, char **) FAST_FUNC;
8791static int umaskcmd(int, char **) FAST_FUNC;
8792static int unsetcmd(int, char **) FAST_FUNC;
8793static int ulimitcmd(int, char **) FAST_FUNC;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008794
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008795#define BUILTIN_NOSPEC "0"
8796#define BUILTIN_SPECIAL "1"
8797#define BUILTIN_REGULAR "2"
8798#define BUILTIN_SPEC_REG "3"
8799#define BUILTIN_ASSIGN "4"
8800#define BUILTIN_SPEC_ASSG "5"
8801#define BUILTIN_REG_ASSG "6"
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008802#define BUILTIN_SPEC_REG_ASSG "7"
8803
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008804/* Stubs for calling non-FAST_FUNC's */
Denys Vlasenko2634bf32009-06-09 18:40:07 +02008805#if ENABLE_ASH_BUILTIN_ECHO
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008806static int FAST_FUNC echocmd(int argc, char **argv) { return echo_main(argc, argv); }
Denys Vlasenko2634bf32009-06-09 18:40:07 +02008807#endif
8808#if ENABLE_ASH_BUILTIN_PRINTF
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008809static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
Denys Vlasenko2634bf32009-06-09 18:40:07 +02008810#endif
8811#if ENABLE_ASH_BUILTIN_TEST
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008812static int FAST_FUNC testcmd(int argc, char **argv) { return test_main(argc, argv); }
Denys Vlasenko2634bf32009-06-09 18:40:07 +02008813#endif
Denis Vlasenko468aea22008-04-01 14:47:57 +00008814
Denis Vlasenkof7d56652008-03-25 05:51:41 +00008815/* Keep these in proper order since it is searched via bsearch() */
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008816static const struct builtincmd builtintab[] = {
8817 { BUILTIN_SPEC_REG ".", dotcmd },
8818 { BUILTIN_SPEC_REG ":", truecmd },
8819#if ENABLE_ASH_BUILTIN_TEST
Denis Vlasenkocd2663f2008-06-01 22:36:39 +00008820 { BUILTIN_REGULAR "[", testcmd },
Denis Vlasenko80591b02008-03-25 07:49:43 +00008821#if ENABLE_ASH_BASH_COMPAT
Denis Vlasenkocd2663f2008-06-01 22:36:39 +00008822 { BUILTIN_REGULAR "[[", testcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008823#endif
Denis Vlasenko80591b02008-03-25 07:49:43 +00008824#endif
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008825#if ENABLE_ASH_ALIAS
8826 { BUILTIN_REG_ASSG "alias", aliascmd },
8827#endif
8828#if JOBS
8829 { BUILTIN_REGULAR "bg", fg_bgcmd },
8830#endif
8831 { BUILTIN_SPEC_REG "break", breakcmd },
8832 { BUILTIN_REGULAR "cd", cdcmd },
8833 { BUILTIN_NOSPEC "chdir", cdcmd },
8834#if ENABLE_ASH_CMDCMD
8835 { BUILTIN_REGULAR "command", commandcmd },
8836#endif
8837 { BUILTIN_SPEC_REG "continue", breakcmd },
8838#if ENABLE_ASH_BUILTIN_ECHO
8839 { BUILTIN_REGULAR "echo", echocmd },
8840#endif
8841 { BUILTIN_SPEC_REG "eval", evalcmd },
8842 { BUILTIN_SPEC_REG "exec", execcmd },
8843 { BUILTIN_SPEC_REG "exit", exitcmd },
8844 { BUILTIN_SPEC_REG_ASSG "export", exportcmd },
8845 { BUILTIN_REGULAR "false", falsecmd },
8846#if JOBS
8847 { BUILTIN_REGULAR "fg", fg_bgcmd },
8848#endif
8849#if ENABLE_ASH_GETOPTS
8850 { BUILTIN_REGULAR "getopts", getoptscmd },
8851#endif
8852 { BUILTIN_NOSPEC "hash", hashcmd },
8853#if !ENABLE_FEATURE_SH_EXTRA_QUIET
8854 { BUILTIN_NOSPEC "help", helpcmd },
8855#endif
8856#if JOBS
8857 { BUILTIN_REGULAR "jobs", jobscmd },
8858 { BUILTIN_REGULAR "kill", killcmd },
8859#endif
Mike Frysinger98c52642009-04-02 10:02:37 +00008860#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008861 { BUILTIN_NOSPEC "let", letcmd },
8862#endif
8863 { BUILTIN_ASSIGN "local", localcmd },
Denis Vlasenkocd2663f2008-06-01 22:36:39 +00008864#if ENABLE_ASH_BUILTIN_PRINTF
8865 { BUILTIN_REGULAR "printf", printfcmd },
8866#endif
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008867 { BUILTIN_NOSPEC "pwd", pwdcmd },
8868 { BUILTIN_REGULAR "read", readcmd },
8869 { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
8870 { BUILTIN_SPEC_REG "return", returncmd },
8871 { BUILTIN_SPEC_REG "set", setcmd },
8872 { BUILTIN_SPEC_REG "shift", shiftcmd },
8873 { BUILTIN_SPEC_REG "source", dotcmd },
8874#if ENABLE_ASH_BUILTIN_TEST
Denis Vlasenkocd2663f2008-06-01 22:36:39 +00008875 { BUILTIN_REGULAR "test", testcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008876#endif
8877 { BUILTIN_SPEC_REG "times", timescmd },
8878 { BUILTIN_SPEC_REG "trap", trapcmd },
8879 { BUILTIN_REGULAR "true", truecmd },
8880 { BUILTIN_NOSPEC "type", typecmd },
8881 { BUILTIN_NOSPEC "ulimit", ulimitcmd },
8882 { BUILTIN_REGULAR "umask", umaskcmd },
8883#if ENABLE_ASH_ALIAS
8884 { BUILTIN_REGULAR "unalias", unaliascmd },
8885#endif
8886 { BUILTIN_SPEC_REG "unset", unsetcmd },
8887 { BUILTIN_REGULAR "wait", waitcmd },
8888};
8889
Denis Vlasenko80591b02008-03-25 07:49:43 +00008890/* Should match the above table! */
8891#define COMMANDCMD (builtintab + \
8892 2 + \
8893 1 * ENABLE_ASH_BUILTIN_TEST + \
8894 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
8895 1 * ENABLE_ASH_ALIAS + \
8896 1 * ENABLE_ASH_JOB_CONTROL + \
8897 3)
8898#define EXECCMD (builtintab + \
8899 2 + \
8900 1 * ENABLE_ASH_BUILTIN_TEST + \
8901 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
8902 1 * ENABLE_ASH_ALIAS + \
8903 1 * ENABLE_ASH_JOB_CONTROL + \
8904 3 + \
8905 1 * ENABLE_ASH_CMDCMD + \
8906 1 + \
8907 ENABLE_ASH_BUILTIN_ECHO + \
8908 1)
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008909
8910/*
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008911 * Search the table of builtin commands.
8912 */
8913static struct builtincmd *
8914find_builtin(const char *name)
8915{
8916 struct builtincmd *bp;
8917
8918 bp = bsearch(
Denis Vlasenko80b8b392007-06-25 10:55:35 +00008919 name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008920 pstrcmp
8921 );
8922 return bp;
8923}
8924
8925/*
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008926 * Execute a simple command.
8927 */
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008928static int
8929isassignment(const char *p)
Paul Foxc3850c82005-07-20 18:23:39 +00008930{
8931 const char *q = endofname(p);
8932 if (p == q)
8933 return 0;
8934 return *q == '=';
8935}
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008936static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008937bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008938{
8939 /* Preserve exitstatus of a previous possible redirection
8940 * as POSIX mandates */
8941 return back_exitstatus;
8942}
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008943static void
Eric Andersenc470f442003-07-28 09:56:35 +00008944evalcommand(union node *cmd, int flags)
8945{
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00008946 static const struct builtincmd null_bltin = {
8947 "\0\0", bltincmd /* why three NULs? */
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008948 };
Eric Andersenc470f442003-07-28 09:56:35 +00008949 struct stackmark smark;
8950 union node *argp;
8951 struct arglist arglist;
8952 struct arglist varlist;
8953 char **argv;
8954 int argc;
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00008955 const struct strlist *sp;
Eric Andersenc470f442003-07-28 09:56:35 +00008956 struct cmdentry cmdentry;
8957 struct job *jp;
8958 char *lastarg;
8959 const char *path;
8960 int spclbltin;
Eric Andersenc470f442003-07-28 09:56:35 +00008961 int status;
8962 char **nargv;
Paul Foxc3850c82005-07-20 18:23:39 +00008963 struct builtincmd *bcmd;
Denis Vlasenko34c73c42008-08-16 11:48:02 +00008964 smallint cmd_is_exec;
8965 smallint pseudovarflag = 0;
Eric Andersenc470f442003-07-28 09:56:35 +00008966
8967 /* First expand the arguments. */
8968 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
8969 setstackmark(&smark);
8970 back_exitstatus = 0;
8971
8972 cmdentry.cmdtype = CMDBUILTIN;
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00008973 cmdentry.u.cmd = &null_bltin;
Eric Andersenc470f442003-07-28 09:56:35 +00008974 varlist.lastp = &varlist.list;
8975 *varlist.lastp = NULL;
8976 arglist.lastp = &arglist.list;
8977 *arglist.lastp = NULL;
8978
8979 argc = 0;
Denis Vlasenkob012b102007-02-19 22:43:01 +00008980 if (cmd->ncmd.args) {
Paul Foxc3850c82005-07-20 18:23:39 +00008981 bcmd = find_builtin(cmd->ncmd.args->narg.text);
8982 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
8983 }
8984
Eric Andersenc470f442003-07-28 09:56:35 +00008985 for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
8986 struct strlist **spp;
8987
8988 spp = arglist.lastp;
"Vladimir N. Oleynik"bef14d72005-09-05 13:25:11 +00008989 if (pseudovarflag && isassignment(argp->narg.text))
Paul Foxc3850c82005-07-20 18:23:39 +00008990 expandarg(argp, &arglist, EXP_VARTILDE);
8991 else
8992 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
8993
Eric Andersenc470f442003-07-28 09:56:35 +00008994 for (sp = *spp; sp; sp = sp->next)
8995 argc++;
8996 }
8997
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +00008998 argv = nargv = stalloc(sizeof(char *) * (argc + 1));
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008999 for (sp = arglist.list; sp; sp = sp->next) {
Eric Andersenc470f442003-07-28 09:56:35 +00009000 TRACE(("evalcommand arg: %s\n", sp->text));
9001 *nargv++ = sp->text;
9002 }
9003 *nargv = NULL;
9004
9005 lastarg = NULL;
9006 if (iflag && funcnest == 0 && argc > 0)
9007 lastarg = nargv[-1];
9008
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009009 preverrout_fd = 2;
Eric Andersenc470f442003-07-28 09:56:35 +00009010 expredir(cmd->ncmd.redirect);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009011 status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
Eric Andersenc470f442003-07-28 09:56:35 +00009012
9013 path = vpath.text;
9014 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
9015 struct strlist **spp;
9016 char *p;
9017
9018 spp = varlist.lastp;
9019 expandarg(argp, &varlist, EXP_VARTILDE);
9020
9021 /*
9022 * Modify the command lookup path, if a PATH= assignment
9023 * is present
9024 */
9025 p = (*spp)->text;
9026 if (varequal(p, path))
9027 path = p;
9028 }
9029
9030 /* Print the command if xflag is set. */
9031 if (xflag) {
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009032 int n;
9033 const char *p = " %s";
Eric Andersenc470f442003-07-28 09:56:35 +00009034
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009035 p++;
Denis Vlasenko0de37e12007-10-17 11:08:53 +00009036 fdprintf(preverrout_fd, p, expandstr(ps4val()));
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009037
9038 sp = varlist.list;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +00009039 for (n = 0; n < 2; n++) {
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009040 while (sp) {
Denis Vlasenko0de37e12007-10-17 11:08:53 +00009041 fdprintf(preverrout_fd, p, sp->text);
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009042 sp = sp->next;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +00009043 if (*p == '%') {
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009044 p--;
9045 }
9046 }
9047 sp = arglist.list;
9048 }
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00009049 safe_write(preverrout_fd, "\n", 1);
Eric Andersenc470f442003-07-28 09:56:35 +00009050 }
9051
9052 cmd_is_exec = 0;
9053 spclbltin = -1;
9054
9055 /* Now locate the command. */
9056 if (argc) {
9057 const char *oldpath;
9058 int cmd_flag = DO_ERR;
9059
9060 path += 5;
9061 oldpath = path;
9062 for (;;) {
9063 find_command(argv[0], &cmdentry, cmd_flag, path);
9064 if (cmdentry.cmdtype == CMDUNKNOWN) {
Denys Vlasenko8131eea2009-11-02 14:19:51 +01009065 flush_stdout_stderr();
Denis Vlasenko6514c5e2008-07-24 13:41:37 +00009066 status = 127;
Eric Andersenc470f442003-07-28 09:56:35 +00009067 goto bail;
9068 }
9069
9070 /* implement bltin and command here */
9071 if (cmdentry.cmdtype != CMDBUILTIN)
9072 break;
9073 if (spclbltin < 0)
9074 spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
9075 if (cmdentry.u.cmd == EXECCMD)
Denis Vlasenko34c73c42008-08-16 11:48:02 +00009076 cmd_is_exec = 1;
Denis Vlasenko131ae172007-02-18 13:00:19 +00009077#if ENABLE_ASH_CMDCMD
Eric Andersenc470f442003-07-28 09:56:35 +00009078 if (cmdentry.u.cmd == COMMANDCMD) {
Eric Andersenc470f442003-07-28 09:56:35 +00009079 path = oldpath;
9080 nargv = parse_command_args(argv, &path);
9081 if (!nargv)
9082 break;
9083 argc -= nargv - argv;
9084 argv = nargv;
9085 cmd_flag |= DO_NOFUNC;
9086 } else
9087#endif
9088 break;
9089 }
9090 }
9091
9092 if (status) {
9093 /* We have a redirection error. */
9094 if (spclbltin > 0)
Denis Vlasenkob012b102007-02-19 22:43:01 +00009095 raise_exception(EXERROR);
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009096 bail:
Eric Andersenc470f442003-07-28 09:56:35 +00009097 exitstatus = status;
9098 goto out;
9099 }
9100
9101 /* Execute the command. */
9102 switch (cmdentry.cmdtype) {
9103 default:
Denis Vlasenkobe54d6b2008-10-27 14:25:52 +00009104
Denis Vlasenko9bc80d72008-04-12 20:07:53 +00009105#if ENABLE_FEATURE_SH_NOFORK
Denis Vlasenkobe54d6b2008-10-27 14:25:52 +00009106/* Hmmm... shouldn't it happen somewhere in forkshell() instead?
9107 * Why "fork off a child process if necessary" doesn't apply to NOFORK? */
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00009108 {
9109 /* find_command() encodes applet_no as (-2 - applet_no) */
9110 int applet_no = (- cmdentry.u.index - 2);
Denis Vlasenko9bc80d72008-04-12 20:07:53 +00009111 if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
Denis Vlasenko9bc80d72008-04-12 20:07:53 +00009112 listsetvar(varlist.list, VEXPORT|VSTACK);
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00009113 /* run <applet>_main() */
9114 exitstatus = run_nofork_applet(applet_no, argv);
Denis Vlasenko9bc80d72008-04-12 20:07:53 +00009115 break;
9116 }
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00009117 }
Denis Vlasenko9bc80d72008-04-12 20:07:53 +00009118#endif
Eric Andersenc470f442003-07-28 09:56:35 +00009119 /* Fork off a child process if necessary. */
9120 if (!(flags & EV_EXIT) || trap[0]) {
Denis Vlasenkob012b102007-02-19 22:43:01 +00009121 INT_OFF;
Denis Vlasenko68404f12008-03-17 09:00:54 +00009122 jp = makejob(/*cmd,*/ 1);
Eric Andersenc470f442003-07-28 09:56:35 +00009123 if (forkshell(jp, cmd, FORK_FG) != 0) {
9124 exitstatus = waitforjob(jp);
Denis Vlasenkob012b102007-02-19 22:43:01 +00009125 INT_ON;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00009126 TRACE(("forked child exited with %d\n", exitstatus));
Eric Andersenc470f442003-07-28 09:56:35 +00009127 break;
9128 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00009129 FORCE_INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00009130 }
9131 listsetvar(varlist.list, VEXPORT|VSTACK);
9132 shellexec(argv, path, cmdentry.u.index);
9133 /* NOTREACHED */
9134
9135 case CMDBUILTIN:
9136 cmdenviron = varlist.list;
9137 if (cmdenviron) {
9138 struct strlist *list = cmdenviron;
9139 int i = VNOSET;
9140 if (spclbltin > 0 || argc == 0) {
9141 i = 0;
9142 if (cmd_is_exec && argc > 1)
9143 i = VEXPORT;
9144 }
9145 listsetvar(list, i);
9146 }
Denis Vlasenkobe54d6b2008-10-27 14:25:52 +00009147 /* Tight loop with builtins only:
9148 * "while kill -0 $child; do true; done"
9149 * will never exit even if $child died, unless we do this
9150 * to reap the zombie and make kill detect that it's gone: */
9151 dowait(DOWAIT_NONBLOCK, NULL);
9152
Eric Andersenc470f442003-07-28 09:56:35 +00009153 if (evalbltin(cmdentry.u.cmd, argc, argv)) {
9154 int exit_status;
Denis Vlasenko7f88e342009-03-19 03:36:18 +00009155 int i = exception_type;
Eric Andersenc470f442003-07-28 09:56:35 +00009156 if (i == EXEXIT)
9157 goto raise;
Eric Andersenc470f442003-07-28 09:56:35 +00009158 exit_status = 2;
Eric Andersenc470f442003-07-28 09:56:35 +00009159 if (i == EXINT)
Denis Vlasenko991a1da2008-02-10 19:02:53 +00009160 exit_status = 128 + SIGINT;
Eric Andersenc470f442003-07-28 09:56:35 +00009161 if (i == EXSIG)
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02009162 exit_status = 128 + pending_sig;
Eric Andersenc470f442003-07-28 09:56:35 +00009163 exitstatus = exit_status;
Eric Andersenc470f442003-07-28 09:56:35 +00009164 if (i == EXINT || spclbltin > 0) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009165 raise:
Denis Vlasenko2da584f2007-02-19 22:44:05 +00009166 longjmp(exception_handler->loc, 1);
Eric Andersenc470f442003-07-28 09:56:35 +00009167 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00009168 FORCE_INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00009169 }
9170 break;
9171
9172 case CMDFUNCTION:
9173 listsetvar(varlist.list, 0);
Denis Vlasenkobe54d6b2008-10-27 14:25:52 +00009174 /* See above for the rationale */
9175 dowait(DOWAIT_NONBLOCK, NULL);
Eric Andersenc470f442003-07-28 09:56:35 +00009176 if (evalfun(cmdentry.u.func, argc, argv, flags))
9177 goto raise;
9178 break;
9179 }
9180
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009181 out:
Denis Vlasenko34c73c42008-08-16 11:48:02 +00009182 popredir(/*drop:*/ cmd_is_exec, /*restore:*/ cmd_is_exec);
Denis Vlasenko6514c5e2008-07-24 13:41:37 +00009183 if (lastarg) {
Eric Andersenc470f442003-07-28 09:56:35 +00009184 /* dsl: I think this is intended to be used to support
9185 * '_' in 'vi' command mode during line editing...
9186 * However I implemented that within libedit itself.
9187 */
9188 setvar("_", lastarg, 0);
Denis Vlasenko6514c5e2008-07-24 13:41:37 +00009189 }
Eric Andersenc470f442003-07-28 09:56:35 +00009190 popstackmark(&smark);
9191}
9192
9193static int
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009194evalbltin(const struct builtincmd *cmd, int argc, char **argv)
9195{
Eric Andersenc470f442003-07-28 09:56:35 +00009196 char *volatile savecmdname;
9197 struct jmploc *volatile savehandler;
9198 struct jmploc jmploc;
9199 int i;
9200
9201 savecmdname = commandname;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009202 i = setjmp(jmploc.loc);
9203 if (i)
Eric Andersenc470f442003-07-28 09:56:35 +00009204 goto cmddone;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00009205 savehandler = exception_handler;
9206 exception_handler = &jmploc;
Eric Andersenc470f442003-07-28 09:56:35 +00009207 commandname = argv[0];
9208 argptr = argv + 1;
9209 optptr = NULL; /* initialize nextopt */
9210 exitstatus = (*cmd->builtin)(argc, argv);
Denis Vlasenkob012b102007-02-19 22:43:01 +00009211 flush_stdout_stderr();
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009212 cmddone:
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009213 exitstatus |= ferror(stdout);
Rob Landleyf296f0b2006-07-06 01:09:21 +00009214 clearerr(stdout);
Eric Andersenc470f442003-07-28 09:56:35 +00009215 commandname = savecmdname;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00009216 exception_handler = savehandler;
Eric Andersenc470f442003-07-28 09:56:35 +00009217
9218 return i;
9219}
9220
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009221static int
9222goodname(const char *p)
Glenn L McGrath16e45d72004-02-04 08:24:39 +00009223{
9224 return !*endofname(p);
9225}
9226
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009227
Glenn L McGrath50812ff2002-08-23 13:14:48 +00009228/*
9229 * Search for a command. This is called before we fork so that the
9230 * location of the command will be available in the parent as well as
Glenn L McGrath16e45d72004-02-04 08:24:39 +00009231 * the child. The check for "goodname" is an overly conservative
9232 * check that the name will not be subject to expansion.
Glenn L McGrath50812ff2002-08-23 13:14:48 +00009233 */
Eric Andersenc470f442003-07-28 09:56:35 +00009234static void
9235prehash(union node *n)
Glenn L McGrath50812ff2002-08-23 13:14:48 +00009236{
9237 struct cmdentry entry;
9238
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +00009239 if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
9240 find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
Glenn L McGrath50812ff2002-08-23 13:14:48 +00009241}
9242
Eric Andersencb57d552001-06-28 07:25:16 +00009243
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00009244/* ============ Builtin commands
9245 *
9246 * Builtin commands whose functions are closely tied to evaluation
9247 * are implemented here.
Eric Andersencb57d552001-06-28 07:25:16 +00009248 */
9249
9250/*
Eric Andersencb57d552001-06-28 07:25:16 +00009251 * Handle break and continue commands. Break, continue, and return are
9252 * all handled by setting the evalskip flag. The evaluation routines
9253 * above all check this flag, and if it is set they start skipping
9254 * commands rather than executing them. The variable skipcount is
9255 * the number of loops to break/continue, or the number of function
9256 * levels to return. (The latter is always 1.) It should probably
9257 * be an error to break out of more loops than exist, but it isn't
9258 * in the standard shell so we don't make it one here.
9259 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009260static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00009261breakcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +00009262{
Denis Vlasenko68404f12008-03-17 09:00:54 +00009263 int n = argv[1] ? number(argv[1]) : 1;
Eric Andersencb57d552001-06-28 07:25:16 +00009264
Aaron Lehmann2aef3a62001-12-31 06:03:12 +00009265 if (n <= 0)
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02009266 ash_msg_and_raise_error(msg_illnum, argv[1]);
Eric Andersencb57d552001-06-28 07:25:16 +00009267 if (n > loopnest)
9268 n = loopnest;
9269 if (n > 0) {
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00009270 evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
Eric Andersencb57d552001-06-28 07:25:16 +00009271 skipcount = n;
9272 }
9273 return 0;
9274}
9275
Eric Andersenc470f442003-07-28 09:56:35 +00009276
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009277/* ============ input.c
9278 *
Eric Andersen90898442003-08-06 11:20:52 +00009279 * This implements the input routines used by the parser.
Eric Andersencb57d552001-06-28 07:25:16 +00009280 */
Denis Vlasenko99eb8502007-02-23 21:09:49 +00009281
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009282enum {
9283 INPUT_PUSH_FILE = 1,
9284 INPUT_NOFILE_OK = 2,
9285};
Eric Andersencb57d552001-06-28 07:25:16 +00009286
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009287static smallint checkkwd;
Denis Vlasenko99eb8502007-02-23 21:09:49 +00009288/* values of checkkwd variable */
9289#define CHKALIAS 0x1
9290#define CHKKWD 0x2
9291#define CHKNL 0x4
9292
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009293/*
9294 * Push a string back onto the input at this current parsefile level.
9295 * We handle aliases this way.
9296 */
9297#if !ENABLE_ASH_ALIAS
9298#define pushstring(s, ap) pushstring(s)
9299#endif
9300static void
9301pushstring(char *s, struct alias *ap)
9302{
9303 struct strpush *sp;
9304 int len;
9305
9306 len = strlen(s);
9307 INT_OFF;
9308 if (g_parsefile->strpush) {
9309 sp = ckzalloc(sizeof(*sp));
9310 sp->prev = g_parsefile->strpush;
9311 } else {
9312 sp = &(g_parsefile->basestrpush);
9313 }
9314 g_parsefile->strpush = sp;
9315 sp->prev_string = g_parsefile->next_to_pgetc;
9316 sp->prev_left_in_line = g_parsefile->left_in_line;
9317#if ENABLE_ASH_ALIAS
9318 sp->ap = ap;
9319 if (ap) {
9320 ap->flag |= ALIASINUSE;
9321 sp->string = s;
9322 }
9323#endif
9324 g_parsefile->next_to_pgetc = s;
9325 g_parsefile->left_in_line = len;
9326 INT_ON;
9327}
9328
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009329static void
9330popstring(void)
Eric Andersenc470f442003-07-28 09:56:35 +00009331{
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009332 struct strpush *sp = g_parsefile->strpush;
Eric Andersenc470f442003-07-28 09:56:35 +00009333
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009334 INT_OFF;
Denis Vlasenko131ae172007-02-18 13:00:19 +00009335#if ENABLE_ASH_ALIAS
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009336 if (sp->ap) {
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009337 if (g_parsefile->next_to_pgetc[-1] == ' '
9338 || g_parsefile->next_to_pgetc[-1] == '\t'
9339 ) {
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009340 checkkwd |= CHKALIAS;
Glenn L McGrath28939ad2004-07-21 10:20:19 +00009341 }
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009342 if (sp->string != sp->ap->val) {
9343 free(sp->string);
9344 }
9345 sp->ap->flag &= ~ALIASINUSE;
9346 if (sp->ap->flag & ALIASDEAD) {
9347 unalias(sp->ap->name);
9348 }
Glenn L McGrath28939ad2004-07-21 10:20:19 +00009349 }
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009350#endif
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009351 g_parsefile->next_to_pgetc = sp->prev_string;
9352 g_parsefile->left_in_line = sp->prev_left_in_line;
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009353 g_parsefile->strpush = sp->prev;
9354 if (sp != &(g_parsefile->basestrpush))
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009355 free(sp);
9356 INT_ON;
9357}
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009358
Denis Vlasenkoe27dafd2008-11-28 04:01:03 +00009359//FIXME: BASH_COMPAT with "...&" does TWO pungetc():
9360//it peeks whether it is &>, and then pushes back both chars.
9361//This function needs to save last *next_to_pgetc to buf[0]
9362//to make two pungetc() reliable. Currently,
9363// pgetc (out of buf: does preadfd), pgetc, pungetc, pungetc won't work...
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009364static int
9365preadfd(void)
Eric Andersencb57d552001-06-28 07:25:16 +00009366{
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00009367 int nr;
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00009368 char *buf = g_parsefile->buf;
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00009369
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009370 g_parsefile->next_to_pgetc = buf;
Denis Vlasenko38f63192007-01-22 09:03:07 +00009371#if ENABLE_FEATURE_EDITING
Denis Vlasenko85c24712008-03-17 09:04:04 +00009372 retry:
Denis Vlasenko727752d2008-11-28 03:41:47 +00009373 if (!iflag || g_parsefile->fd != STDIN_FILENO)
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009374 nr = nonblock_safe_read(g_parsefile->fd, buf, BUFSIZ - 1);
Eric Andersenc470f442003-07-28 09:56:35 +00009375 else {
Denis Vlasenko38f63192007-01-22 09:03:07 +00009376#if ENABLE_FEATURE_TAB_COMPLETION
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009377 line_input_state->path_lookup = pathval();
Eric Andersen4a79c0e2004-09-08 10:01:07 +00009378#endif
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009379 nr = read_line_input(cmdedit_prompt, buf, BUFSIZ, line_input_state);
9380 if (nr == 0) {
9381 /* Ctrl+C pressed */
9382 if (trap[SIGINT]) {
Glenn L McGrath16e45d72004-02-04 08:24:39 +00009383 buf[0] = '\n';
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009384 buf[1] = '\0';
Glenn L McGrath16e45d72004-02-04 08:24:39 +00009385 raise(SIGINT);
9386 return 1;
9387 }
Eric Andersenc470f442003-07-28 09:56:35 +00009388 goto retry;
9389 }
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009390 if (nr < 0 && errno == 0) {
Denis Vlasenko9cb220b2007-12-09 10:03:28 +00009391 /* Ctrl+D pressed */
Eric Andersenc470f442003-07-28 09:56:35 +00009392 nr = 0;
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00009393 }
Eric Andersencb57d552001-06-28 07:25:16 +00009394 }
9395#else
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +00009396 nr = nonblock_safe_read(g_parsefile->fd, buf, BUFSIZ - 1);
Eric Andersencb57d552001-06-28 07:25:16 +00009397#endif
9398
Denis Vlasenkoe376d452008-02-20 22:23:24 +00009399#if 0
9400/* nonblock_safe_read() handles this problem */
Eric Andersencb57d552001-06-28 07:25:16 +00009401 if (nr < 0) {
Eric Andersencb57d552001-06-28 07:25:16 +00009402 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
Denis Vlasenkod37f2222007-08-19 13:42:08 +00009403 int flags = fcntl(0, F_GETFL);
Denis Vlasenko9cb220b2007-12-09 10:03:28 +00009404 if (flags >= 0 && (flags & O_NONBLOCK)) {
9405 flags &= ~O_NONBLOCK;
Eric Andersencb57d552001-06-28 07:25:16 +00009406 if (fcntl(0, F_SETFL, flags) >= 0) {
9407 out2str("sh: turning off NDELAY mode\n");
9408 goto retry;
9409 }
9410 }
9411 }
9412 }
Denis Vlasenkoe376d452008-02-20 22:23:24 +00009413#endif
Eric Andersencb57d552001-06-28 07:25:16 +00009414 return nr;
9415}
9416
9417/*
9418 * Refill the input buffer and return the next input character:
9419 *
9420 * 1) If a string was pushed back on the input, pop it;
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009421 * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
9422 * or we are reading from a string so we can't refill the buffer,
9423 * return EOF.
Denys Vlasenko883cea42009-07-11 15:31:59 +02009424 * 3) If there is more stuff in this buffer, use it else call read to fill it.
Eric Andersencb57d552001-06-28 07:25:16 +00009425 * 4) Process input up to the next newline, deleting nul characters.
9426 */
Denis Vlasenko727752d2008-11-28 03:41:47 +00009427//#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
9428#define pgetc_debug(...) ((void)0)
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009429static int
Eric Andersenc470f442003-07-28 09:56:35 +00009430preadbuffer(void)
Eric Andersencb57d552001-06-28 07:25:16 +00009431{
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009432 char *q;
Eric Andersencb57d552001-06-28 07:25:16 +00009433 int more;
Eric Andersencb57d552001-06-28 07:25:16 +00009434
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009435 while (g_parsefile->strpush) {
Denis Vlasenko131ae172007-02-18 13:00:19 +00009436#if ENABLE_ASH_ALIAS
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009437 if (g_parsefile->left_in_line == -1
9438 && g_parsefile->strpush->ap
9439 && g_parsefile->next_to_pgetc[-1] != ' '
9440 && g_parsefile->next_to_pgetc[-1] != '\t'
Denis Vlasenko16898402008-11-25 01:34:52 +00009441 ) {
Denis Vlasenko727752d2008-11-28 03:41:47 +00009442 pgetc_debug("preadbuffer PEOA");
Eric Andersencb57d552001-06-28 07:25:16 +00009443 return PEOA;
9444 }
Eric Andersen2870d962001-07-02 17:27:21 +00009445#endif
Eric Andersencb57d552001-06-28 07:25:16 +00009446 popstring();
Denis Vlasenko727752d2008-11-28 03:41:47 +00009447 /* try "pgetc" now: */
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009448 pgetc_debug("preadbuffer internal pgetc at %d:%p'%s'",
9449 g_parsefile->left_in_line,
9450 g_parsefile->next_to_pgetc,
9451 g_parsefile->next_to_pgetc);
9452 if (--g_parsefile->left_in_line >= 0)
9453 return (unsigned char)(*g_parsefile->next_to_pgetc++);
Eric Andersencb57d552001-06-28 07:25:16 +00009454 }
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009455 /* on both branches above g_parsefile->left_in_line < 0.
Denis Vlasenko727752d2008-11-28 03:41:47 +00009456 * "pgetc" needs refilling.
9457 */
9458
Denis Vlasenkoe27dafd2008-11-28 04:01:03 +00009459 /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009460 * pungetc() may increment it a few times.
Denis Vlasenkoe27dafd2008-11-28 04:01:03 +00009461 * Assuming it won't increment it to less than -90.
Denis Vlasenko727752d2008-11-28 03:41:47 +00009462 */
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009463 if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
Denis Vlasenko727752d2008-11-28 03:41:47 +00009464 pgetc_debug("preadbuffer PEOF1");
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009465 /* even in failure keep left_in_line and next_to_pgetc
9466 * in lock step, for correct multi-layer pungetc.
9467 * left_in_line was decremented before preadbuffer(),
9468 * must inc next_to_pgetc: */
9469 g_parsefile->next_to_pgetc++;
Eric Andersencb57d552001-06-28 07:25:16 +00009470 return PEOF;
Denis Vlasenko727752d2008-11-28 03:41:47 +00009471 }
Eric Andersencb57d552001-06-28 07:25:16 +00009472
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009473 more = g_parsefile->left_in_buffer;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009474 if (more <= 0) {
Denis Vlasenko727752d2008-11-28 03:41:47 +00009475 flush_stdout_stderr();
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009476 again:
9477 more = preadfd();
9478 if (more <= 0) {
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009479 /* don't try reading again */
9480 g_parsefile->left_in_line = -99;
Denis Vlasenko727752d2008-11-28 03:41:47 +00009481 pgetc_debug("preadbuffer PEOF2");
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009482 g_parsefile->next_to_pgetc++;
Eric Andersencb57d552001-06-28 07:25:16 +00009483 return PEOF;
9484 }
9485 }
9486
Denis Vlasenko727752d2008-11-28 03:41:47 +00009487 /* Find out where's the end of line.
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009488 * Set g_parsefile->left_in_line
9489 * and g_parsefile->left_in_buffer acordingly.
Denis Vlasenko727752d2008-11-28 03:41:47 +00009490 * NUL chars are deleted.
9491 */
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009492 q = g_parsefile->next_to_pgetc;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009493 for (;;) {
Denis Vlasenko727752d2008-11-28 03:41:47 +00009494 char c;
Eric Andersencb57d552001-06-28 07:25:16 +00009495
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009496 more--;
Eric Andersenc470f442003-07-28 09:56:35 +00009497
Denis Vlasenko727752d2008-11-28 03:41:47 +00009498 c = *q;
9499 if (c == '\0') {
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009500 memmove(q, q + 1, more);
Denis Vlasenko727752d2008-11-28 03:41:47 +00009501 } else {
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009502 q++;
9503 if (c == '\n') {
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009504 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009505 break;
9506 }
Eric Andersencb57d552001-06-28 07:25:16 +00009507 }
9508
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009509 if (more <= 0) {
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009510 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9511 if (g_parsefile->left_in_line < 0)
Eric Andersencb57d552001-06-28 07:25:16 +00009512 goto again;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009513 break;
Eric Andersencb57d552001-06-28 07:25:16 +00009514 }
9515 }
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009516 g_parsefile->left_in_buffer = more;
Eric Andersencb57d552001-06-28 07:25:16 +00009517
Eric Andersencb57d552001-06-28 07:25:16 +00009518 if (vflag) {
Denis Vlasenko727752d2008-11-28 03:41:47 +00009519 char save = *q;
9520 *q = '\0';
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009521 out2str(g_parsefile->next_to_pgetc);
Denis Vlasenko727752d2008-11-28 03:41:47 +00009522 *q = save;
Eric Andersencb57d552001-06-28 07:25:16 +00009523 }
9524
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009525 pgetc_debug("preadbuffer at %d:%p'%s'",
9526 g_parsefile->left_in_line,
9527 g_parsefile->next_to_pgetc,
9528 g_parsefile->next_to_pgetc);
Denys Vlasenkocd716832009-11-28 22:14:02 +01009529 return (unsigned char)*g_parsefile->next_to_pgetc++;
Eric Andersencb57d552001-06-28 07:25:16 +00009530}
9531
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009532#define pgetc_as_macro() \
9533 (--g_parsefile->left_in_line >= 0 \
Denys Vlasenkocd716832009-11-28 22:14:02 +01009534 ? (unsigned char)*g_parsefile->next_to_pgetc++ \
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009535 : preadbuffer() \
9536 )
Denis Vlasenko727752d2008-11-28 03:41:47 +00009537
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009538static int
9539pgetc(void)
9540{
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009541 pgetc_debug("pgetc_fast at %d:%p'%s'",
9542 g_parsefile->left_in_line,
9543 g_parsefile->next_to_pgetc,
9544 g_parsefile->next_to_pgetc);
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009545 return pgetc_as_macro();
9546}
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00009547
9548#if ENABLE_ASH_OPTIMIZE_FOR_SIZE
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01009549# define pgetc_fast() pgetc()
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009550#else
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01009551# define pgetc_fast() pgetc_as_macro()
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009552#endif
9553
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009554#if ENABLE_ASH_ALIAS
9555static int
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01009556pgetc_without_PEOA(void)
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009557{
9558 int c;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009559 do {
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009560 pgetc_debug("pgetc_fast at %d:%p'%s'",
9561 g_parsefile->left_in_line,
9562 g_parsefile->next_to_pgetc,
9563 g_parsefile->next_to_pgetc);
Denis Vlasenko834dee72008-10-07 09:18:30 +00009564 c = pgetc_fast();
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009565 } while (c == PEOA);
9566 return c;
9567}
9568#else
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01009569# define pgetc_without_PEOA() pgetc()
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009570#endif
9571
9572/*
9573 * Read a line from the script.
9574 */
9575static char *
9576pfgets(char *line, int len)
9577{
9578 char *p = line;
9579 int nleft = len;
9580 int c;
9581
9582 while (--nleft > 0) {
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01009583 c = pgetc_without_PEOA();
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009584 if (c == PEOF) {
9585 if (p == line)
9586 return NULL;
9587 break;
9588 }
9589 *p++ = c;
9590 if (c == '\n')
9591 break;
9592 }
9593 *p = '\0';
9594 return line;
9595}
9596
Eric Andersenc470f442003-07-28 09:56:35 +00009597/*
9598 * Undo the last call to pgetc. Only one character may be pushed back.
9599 * PEOF may be pushed back.
9600 */
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009601static void
Eric Andersenc470f442003-07-28 09:56:35 +00009602pungetc(void)
9603{
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009604 g_parsefile->left_in_line++;
9605 g_parsefile->next_to_pgetc--;
9606 pgetc_debug("pushed back to %d:%p'%s'",
9607 g_parsefile->left_in_line,
9608 g_parsefile->next_to_pgetc,
9609 g_parsefile->next_to_pgetc);
Eric Andersencb57d552001-06-28 07:25:16 +00009610}
9611
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009612/*
9613 * To handle the "." command, a stack of input files is used. Pushfile
9614 * adds a new entry to the stack and popfile restores the previous level.
9615 */
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009616static void
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009617pushfile(void)
Eric Andersenc470f442003-07-28 09:56:35 +00009618{
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009619 struct parsefile *pf;
9620
Denis Vlasenko597906c2008-02-20 16:38:54 +00009621 pf = ckzalloc(sizeof(*pf));
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009622 pf->prev = g_parsefile;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009623 pf->fd = -1;
Denis Vlasenko597906c2008-02-20 16:38:54 +00009624 /*pf->strpush = NULL; - ckzalloc did it */
9625 /*pf->basestrpush.prev = NULL;*/
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009626 g_parsefile = pf;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009627}
9628
9629static void
9630popfile(void)
9631{
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009632 struct parsefile *pf = g_parsefile;
Eric Andersenc470f442003-07-28 09:56:35 +00009633
Denis Vlasenkob012b102007-02-19 22:43:01 +00009634 INT_OFF;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009635 if (pf->fd >= 0)
9636 close(pf->fd);
Denis Vlasenko60818682007-09-28 22:07:23 +00009637 free(pf->buf);
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009638 while (pf->strpush)
9639 popstring();
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009640 g_parsefile = pf->prev;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009641 free(pf);
Denis Vlasenkob012b102007-02-19 22:43:01 +00009642 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00009643}
9644
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009645/*
9646 * Return to top level.
9647 */
9648static void
9649popallfiles(void)
9650{
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009651 while (g_parsefile != &basepf)
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009652 popfile();
9653}
9654
9655/*
9656 * Close the file(s) that the shell is reading commands from. Called
9657 * after a fork is done.
9658 */
9659static void
9660closescript(void)
9661{
9662 popallfiles();
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009663 if (g_parsefile->fd > 0) {
9664 close(g_parsefile->fd);
9665 g_parsefile->fd = 0;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009666 }
9667}
9668
9669/*
9670 * Like setinputfile, but takes an open file descriptor. Call this with
9671 * interrupts off.
9672 */
9673static void
9674setinputfd(int fd, int push)
9675{
Denis Vlasenko96e1b382007-09-30 23:50:48 +00009676 close_on_exec_on(fd);
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009677 if (push) {
9678 pushfile();
Denis Vlasenko727752d2008-11-28 03:41:47 +00009679 g_parsefile->buf = NULL;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009680 }
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009681 g_parsefile->fd = fd;
9682 if (g_parsefile->buf == NULL)
9683 g_parsefile->buf = ckmalloc(IBUFSIZ);
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009684 g_parsefile->left_in_buffer = 0;
9685 g_parsefile->left_in_line = 0;
9686 g_parsefile->linno = 1;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009687}
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009688
Eric Andersenc470f442003-07-28 09:56:35 +00009689/*
9690 * Set the input to take input from a file. If push is set, push the
9691 * old input onto the stack first.
9692 */
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009693static int
9694setinputfile(const char *fname, int flags)
Eric Andersenc470f442003-07-28 09:56:35 +00009695{
9696 int fd;
9697 int fd2;
9698
Denis Vlasenkob012b102007-02-19 22:43:01 +00009699 INT_OFF;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009700 fd = open(fname, O_RDONLY);
9701 if (fd < 0) {
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009702 if (flags & INPUT_NOFILE_OK)
9703 goto out;
Denis Vlasenko9604e1b2009-03-03 18:47:56 +00009704 ash_msg_and_raise_error("can't open '%s'", fname);
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009705 }
Eric Andersenc470f442003-07-28 09:56:35 +00009706 if (fd < 10) {
9707 fd2 = copyfd(fd, 10);
9708 close(fd);
9709 if (fd2 < 0)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00009710 ash_msg_and_raise_error("out of file descriptors");
Eric Andersenc470f442003-07-28 09:56:35 +00009711 fd = fd2;
9712 }
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009713 setinputfd(fd, flags & INPUT_PUSH_FILE);
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009714 out:
Denis Vlasenkob012b102007-02-19 22:43:01 +00009715 INT_ON;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009716 return fd;
Eric Andersenc470f442003-07-28 09:56:35 +00009717}
9718
Eric Andersencb57d552001-06-28 07:25:16 +00009719/*
9720 * Like setinputfile, but takes input from a string.
9721 */
Eric Andersenc470f442003-07-28 09:56:35 +00009722static void
9723setinputstring(char *string)
Eric Andersen62483552001-07-10 06:09:16 +00009724{
Denis Vlasenkob012b102007-02-19 22:43:01 +00009725 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +00009726 pushfile();
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009727 g_parsefile->next_to_pgetc = string;
9728 g_parsefile->left_in_line = strlen(string);
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009729 g_parsefile->buf = NULL;
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009730 g_parsefile->linno = 1;
Denis Vlasenkob012b102007-02-19 22:43:01 +00009731 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00009732}
9733
9734
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00009735/* ============ mail.c
9736 *
9737 * Routines to check for mail.
Eric Andersencb57d552001-06-28 07:25:16 +00009738 */
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00009739
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00009740#if ENABLE_ASH_MAIL
Eric Andersencb57d552001-06-28 07:25:16 +00009741
Eric Andersencb57d552001-06-28 07:25:16 +00009742#define MAXMBOXES 10
9743
Eric Andersenc470f442003-07-28 09:56:35 +00009744/* times of mailboxes */
9745static time_t mailtime[MAXMBOXES];
9746/* Set if MAIL or MAILPATH is changed. */
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +00009747static smallint mail_var_path_changed;
Eric Andersencb57d552001-06-28 07:25:16 +00009748
Eric Andersencb57d552001-06-28 07:25:16 +00009749/*
Eric Andersenc470f442003-07-28 09:56:35 +00009750 * Print appropriate message(s) if mail has arrived.
9751 * If mail_var_path_changed is set,
9752 * then the value of MAIL has mail_var_path_changed,
9753 * so we just update the values.
Eric Andersencb57d552001-06-28 07:25:16 +00009754 */
Eric Andersenc470f442003-07-28 09:56:35 +00009755static void
9756chkmail(void)
Eric Andersencb57d552001-06-28 07:25:16 +00009757{
Eric Andersencb57d552001-06-28 07:25:16 +00009758 const char *mpath;
9759 char *p;
9760 char *q;
Eric Andersenc470f442003-07-28 09:56:35 +00009761 time_t *mtp;
Eric Andersencb57d552001-06-28 07:25:16 +00009762 struct stackmark smark;
9763 struct stat statb;
9764
Eric Andersencb57d552001-06-28 07:25:16 +00009765 setstackmark(&smark);
Eric Andersenc470f442003-07-28 09:56:35 +00009766 mpath = mpathset() ? mpathval() : mailval();
9767 for (mtp = mailtime; mtp < mailtime + MAXMBOXES; mtp++) {
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02009768 p = path_advance(&mpath, nullstr);
Eric Andersencb57d552001-06-28 07:25:16 +00009769 if (p == NULL)
9770 break;
9771 if (*p == '\0')
9772 continue;
Denis Vlasenkof7d56652008-03-25 05:51:41 +00009773 for (q = p; *q; q++)
9774 continue;
Denis Vlasenkoa7189f02006-11-17 20:29:00 +00009775#if DEBUG
Eric Andersencb57d552001-06-28 07:25:16 +00009776 if (q[-1] != '/')
9777 abort();
9778#endif
Eric Andersenc470f442003-07-28 09:56:35 +00009779 q[-1] = '\0'; /* delete trailing '/' */
9780 if (stat(p, &statb) < 0) {
9781 *mtp = 0;
9782 continue;
Eric Andersencb57d552001-06-28 07:25:16 +00009783 }
Eric Andersenc470f442003-07-28 09:56:35 +00009784 if (!mail_var_path_changed && statb.st_mtime != *mtp) {
9785 fprintf(
9786 stderr, snlfmt,
9787 pathopt ? pathopt : "you have mail"
9788 );
9789 }
9790 *mtp = statb.st_mtime;
Eric Andersencb57d552001-06-28 07:25:16 +00009791 }
Eric Andersenc470f442003-07-28 09:56:35 +00009792 mail_var_path_changed = 0;
Eric Andersencb57d552001-06-28 07:25:16 +00009793 popstackmark(&smark);
9794}
Eric Andersencb57d552001-06-28 07:25:16 +00009795
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009796static void FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00009797changemail(const char *val UNUSED_PARAM)
Eric Andersenc470f442003-07-28 09:56:35 +00009798{
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +00009799 mail_var_path_changed = 1;
Eric Andersenc470f442003-07-28 09:56:35 +00009800}
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00009801
Denis Vlasenko131ae172007-02-18 13:00:19 +00009802#endif /* ASH_MAIL */
Eric Andersenc470f442003-07-28 09:56:35 +00009803
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00009804
9805/* ============ ??? */
9806
Eric Andersencb57d552001-06-28 07:25:16 +00009807/*
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009808 * Set the shell parameters.
Eric Andersencb57d552001-06-28 07:25:16 +00009809 */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009810static void
9811setparam(char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +00009812{
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009813 char **newparam;
9814 char **ap;
9815 int nparam;
Eric Andersencb57d552001-06-28 07:25:16 +00009816
Denis Vlasenkof7d56652008-03-25 05:51:41 +00009817 for (nparam = 0; argv[nparam]; nparam++)
9818 continue;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009819 ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
9820 while (*argv) {
9821 *ap++ = ckstrdup(*argv++);
Eric Andersencb57d552001-06-28 07:25:16 +00009822 }
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009823 *ap = NULL;
9824 freeparam(&shellparam);
Denis Vlasenko01631112007-12-16 17:20:38 +00009825 shellparam.malloced = 1;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009826 shellparam.nparam = nparam;
9827 shellparam.p = newparam;
9828#if ENABLE_ASH_GETOPTS
9829 shellparam.optind = 1;
9830 shellparam.optoff = -1;
9831#endif
Eric Andersencb57d552001-06-28 07:25:16 +00009832}
9833
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00009834/*
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009835 * Process shell options. The global variable argptr contains a pointer
9836 * to the argument list; we advance it past the options.
Denis Vlasenko94e87bc2008-02-14 16:51:58 +00009837 *
9838 * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
9839 * For a non-interactive shell, an error condition encountered
9840 * by a special built-in ... shall cause the shell to write a diagnostic message
9841 * to standard error and exit as shown in the following table:
Denis Vlasenko56244732008-02-17 15:14:04 +00009842 * Error Special Built-In
Denis Vlasenko94e87bc2008-02-14 16:51:58 +00009843 * ...
9844 * Utility syntax error (option or operand error) Shall exit
9845 * ...
9846 * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
9847 * we see that bash does not do that (set "finishes" with error code 1 instead,
9848 * and shell continues), and people rely on this behavior!
9849 * Testcase:
9850 * set -o barfoo 2>/dev/null
9851 * echo $?
9852 *
9853 * Oh well. Let's mimic that.
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00009854 */
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009855static int
Denis Vlasenkodddfaff2008-05-06 15:30:27 +00009856plus_minus_o(char *name, int val)
Eric Andersen62483552001-07-10 06:09:16 +00009857{
9858 int i;
9859
Denis Vlasenkoa624c112007-02-19 22:45:43 +00009860 if (name) {
9861 for (i = 0; i < NOPTS; i++) {
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00009862 if (strcmp(name, optnames(i)) == 0) {
Eric Andersenc470f442003-07-28 09:56:35 +00009863 optlist[i] = val;
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009864 return 0;
Eric Andersen62483552001-07-10 06:09:16 +00009865 }
Denis Vlasenkoa624c112007-02-19 22:45:43 +00009866 }
Denis Vlasenkodddfaff2008-05-06 15:30:27 +00009867 ash_msg("illegal option %co %s", val ? '-' : '+', name);
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009868 return 1;
Eric Andersen62483552001-07-10 06:09:16 +00009869 }
Denis Vlasenko6b06cb82008-05-15 21:30:45 +00009870 for (i = 0; i < NOPTS; i++) {
Denis Vlasenkodddfaff2008-05-06 15:30:27 +00009871 if (val) {
9872 out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
9873 } else {
9874 out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
9875 }
Denis Vlasenko6b06cb82008-05-15 21:30:45 +00009876 }
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009877 return 0;
Eric Andersen62483552001-07-10 06:09:16 +00009878}
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009879static void
9880setoption(int flag, int val)
9881{
9882 int i;
9883
9884 for (i = 0; i < NOPTS; i++) {
9885 if (optletters(i) == flag) {
9886 optlist[i] = val;
9887 return;
9888 }
9889 }
Denis Vlasenkodddfaff2008-05-06 15:30:27 +00009890 ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009891 /* NOTREACHED */
9892}
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009893static int
Eric Andersenc470f442003-07-28 09:56:35 +00009894options(int cmdline)
Eric Andersencb57d552001-06-28 07:25:16 +00009895{
9896 char *p;
9897 int val;
9898 int c;
9899
9900 if (cmdline)
9901 minusc = NULL;
9902 while ((p = *argptr) != NULL) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009903 c = *p++;
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +00009904 if (c != '-' && c != '+')
9905 break;
9906 argptr++;
9907 val = 0; /* val = 0 if c == '+' */
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009908 if (c == '-') {
Eric Andersencb57d552001-06-28 07:25:16 +00009909 val = 1;
Denis Vlasenko9f739442006-12-16 23:49:13 +00009910 if (p[0] == '\0' || LONE_DASH(p)) {
Eric Andersen2870d962001-07-02 17:27:21 +00009911 if (!cmdline) {
9912 /* "-" means turn off -x and -v */
9913 if (p[0] == '\0')
9914 xflag = vflag = 0;
9915 /* "--" means reset params */
9916 else if (*argptr == NULL)
Eric Andersencb57d552001-06-28 07:25:16 +00009917 setparam(argptr);
Eric Andersen2870d962001-07-02 17:27:21 +00009918 }
Eric Andersenc470f442003-07-28 09:56:35 +00009919 break; /* "-" or "--" terminates options */
Eric Andersencb57d552001-06-28 07:25:16 +00009920 }
Eric Andersencb57d552001-06-28 07:25:16 +00009921 }
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +00009922 /* first char was + or - */
Eric Andersencb57d552001-06-28 07:25:16 +00009923 while ((c = *p++) != '\0') {
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +00009924 /* bash 3.2 indeed handles -c CMD and +c CMD the same */
Eric Andersencb57d552001-06-28 07:25:16 +00009925 if (c == 'c' && cmdline) {
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +00009926 minusc = p; /* command is after shell args */
Eric Andersencb57d552001-06-28 07:25:16 +00009927 } else if (c == 'o') {
Denis Vlasenkodddfaff2008-05-06 15:30:27 +00009928 if (plus_minus_o(*argptr, val)) {
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009929 /* it already printed err message */
9930 return 1; /* error */
9931 }
Eric Andersencb57d552001-06-28 07:25:16 +00009932 if (*argptr)
9933 argptr++;
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +00009934 } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
9935 isloginsh = 1;
9936 /* bash does not accept +-login, we also won't */
9937 } else if (cmdline && val && (c == '-')) { /* long options */
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00009938 if (strcmp(p, "login") == 0)
Robert Griebl64f70cc2002-05-14 23:22:06 +00009939 isloginsh = 1;
9940 break;
Eric Andersencb57d552001-06-28 07:25:16 +00009941 } else {
9942 setoption(c, val);
9943 }
9944 }
9945 }
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009946 return 0;
Eric Andersencb57d552001-06-28 07:25:16 +00009947}
9948
Eric Andersencb57d552001-06-28 07:25:16 +00009949/*
Eric Andersencb57d552001-06-28 07:25:16 +00009950 * The shift builtin command.
9951 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009952static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00009953shiftcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +00009954{
9955 int n;
9956 char **ap1, **ap2;
9957
9958 n = 1;
Denis Vlasenko68404f12008-03-17 09:00:54 +00009959 if (argv[1])
Eric Andersencb57d552001-06-28 07:25:16 +00009960 n = number(argv[1]);
9961 if (n > shellparam.nparam)
Denis Vlasenkoc90e1be2008-07-30 15:35:05 +00009962 n = 0; /* bash compat, was = shellparam.nparam; */
Denis Vlasenkob012b102007-02-19 22:43:01 +00009963 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +00009964 shellparam.nparam -= n;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00009965 for (ap1 = shellparam.p; --n >= 0; ap1++) {
Denis Vlasenko01631112007-12-16 17:20:38 +00009966 if (shellparam.malloced)
Denis Vlasenkob012b102007-02-19 22:43:01 +00009967 free(*ap1);
Eric Andersencb57d552001-06-28 07:25:16 +00009968 }
9969 ap2 = shellparam.p;
Denis Vlasenkof7d56652008-03-25 05:51:41 +00009970 while ((*ap2++ = *ap1++) != NULL)
9971 continue;
Denis Vlasenko131ae172007-02-18 13:00:19 +00009972#if ENABLE_ASH_GETOPTS
Eric Andersencb57d552001-06-28 07:25:16 +00009973 shellparam.optind = 1;
9974 shellparam.optoff = -1;
Eric Andersenc470f442003-07-28 09:56:35 +00009975#endif
Denis Vlasenkob012b102007-02-19 22:43:01 +00009976 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00009977 return 0;
9978}
9979
Eric Andersencb57d552001-06-28 07:25:16 +00009980/*
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009981 * POSIX requires that 'set' (but not export or readonly) output the
9982 * variables in lexicographic order - by the locale's collating order (sigh).
9983 * Maybe we could keep them in an ordered balanced binary tree
9984 * instead of hashed lists.
9985 * For now just roll 'em through qsort for printing...
9986 */
9987static int
9988showvars(const char *sep_prefix, int on, int off)
9989{
9990 const char *sep;
9991 char **ep, **epend;
9992
9993 ep = listvars(on, off, &epend);
9994 qsort(ep, epend - ep, sizeof(char *), vpcmp);
9995
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00009996 sep = *sep_prefix ? " " : sep_prefix;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009997
9998 for (; ep < epend; ep++) {
9999 const char *p;
10000 const char *q;
10001
10002 p = strchrnul(*ep, '=');
10003 q = nullstr;
10004 if (*p)
10005 q = single_quote(++p);
10006 out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
10007 }
10008 return 0;
10009}
10010
10011/*
Eric Andersencb57d552001-06-28 07:25:16 +000010012 * The set command builtin.
10013 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010014static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000010015setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersencb57d552001-06-28 07:25:16 +000010016{
Denis Vlasenko28bf6712008-02-14 15:01:47 +000010017 int retval;
10018
Denis Vlasenko68404f12008-03-17 09:00:54 +000010019 if (!argv[1])
Eric Andersenc470f442003-07-28 09:56:35 +000010020 return showvars(nullstr, 0, VUNSET);
Denis Vlasenkob012b102007-02-19 22:43:01 +000010021 INT_OFF;
Denis Vlasenko28bf6712008-02-14 15:01:47 +000010022 retval = 1;
10023 if (!options(0)) { /* if no parse error... */
10024 retval = 0;
10025 optschanged();
10026 if (*argptr != NULL) {
10027 setparam(argptr);
10028 }
Eric Andersencb57d552001-06-28 07:25:16 +000010029 }
Denis Vlasenkob012b102007-02-19 22:43:01 +000010030 INT_ON;
Denis Vlasenko28bf6712008-02-14 15:01:47 +000010031 return retval;
Eric Andersencb57d552001-06-28 07:25:16 +000010032}
10033
Denis Vlasenko131ae172007-02-18 13:00:19 +000010034#if ENABLE_ASH_RANDOM_SUPPORT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010035static void FAST_FUNC
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000010036change_random(const char *value)
Eric Andersenef02f822004-03-11 13:34:24 +000010037{
Denys Vlasenko3ea2e822009-10-09 20:59:04 +020010038 uint32_t t;
10039
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010040 if (value == NULL) {
Eric Andersen16767e22004-03-16 05:14:10 +000010041 /* "get", generate */
Denys Vlasenko3ea2e822009-10-09 20:59:04 +020010042 t = next_random(&random_gen);
Eric Andersen16767e22004-03-16 05:14:10 +000010043 /* set without recursion */
Denis Vlasenko448d30e2008-06-27 00:24:11 +000010044 setvar(vrandom.text, utoa(t), VNOFUNC);
Eric Andersen16767e22004-03-16 05:14:10 +000010045 vrandom.flags &= ~VNOFUNC;
10046 } else {
10047 /* set/reset */
Denys Vlasenko3ea2e822009-10-09 20:59:04 +020010048 t = strtoul(value, NULL, 10);
10049 INIT_RANDOM_T(&random_gen, (t ? t : 1), t);
Eric Andersen16767e22004-03-16 05:14:10 +000010050 }
Eric Andersenef02f822004-03-11 13:34:24 +000010051}
Eric Andersen16767e22004-03-16 05:14:10 +000010052#endif
10053
Denis Vlasenko131ae172007-02-18 13:00:19 +000010054#if ENABLE_ASH_GETOPTS
Eric Andersencb57d552001-06-28 07:25:16 +000010055static int
Eric Andersenc470f442003-07-28 09:56:35 +000010056getopts(char *optstr, char *optvar, char **optfirst, int *param_optind, int *optoff)
Eric Andersencb57d552001-06-28 07:25:16 +000010057{
10058 char *p, *q;
10059 char c = '?';
10060 int done = 0;
10061 int err = 0;
Eric Andersena48b0a32003-10-22 10:56:47 +000010062 char s[12];
10063 char **optnext;
Eric Andersencb57d552001-06-28 07:25:16 +000010064
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010065 if (*param_optind < 1)
Eric Andersena48b0a32003-10-22 10:56:47 +000010066 return 1;
10067 optnext = optfirst + *param_optind - 1;
10068
Denis Vlasenko6b06cb82008-05-15 21:30:45 +000010069 if (*param_optind <= 1 || *optoff < 0 || (int)strlen(optnext[-1]) < *optoff)
Eric Andersencb57d552001-06-28 07:25:16 +000010070 p = NULL;
10071 else
Eric Andersena48b0a32003-10-22 10:56:47 +000010072 p = optnext[-1] + *optoff;
Eric Andersencb57d552001-06-28 07:25:16 +000010073 if (p == NULL || *p == '\0') {
10074 /* Current word is done, advance */
Eric Andersencb57d552001-06-28 07:25:16 +000010075 p = *optnext;
10076 if (p == NULL || *p != '-' || *++p == '\0') {
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010077 atend:
Eric Andersencb57d552001-06-28 07:25:16 +000010078 p = NULL;
10079 done = 1;
10080 goto out;
10081 }
10082 optnext++;
Denis Vlasenko9f739442006-12-16 23:49:13 +000010083 if (LONE_DASH(p)) /* check for "--" */
Eric Andersencb57d552001-06-28 07:25:16 +000010084 goto atend;
10085 }
10086
10087 c = *p++;
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +000010088 for (q = optstr; *q != c;) {
Eric Andersencb57d552001-06-28 07:25:16 +000010089 if (*q == '\0') {
10090 if (optstr[0] == ':') {
10091 s[0] = c;
10092 s[1] = '\0';
10093 err |= setvarsafe("OPTARG", s, 0);
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010094 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000010095 fprintf(stderr, "Illegal option -%c\n", c);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010096 unsetvar("OPTARG");
Eric Andersencb57d552001-06-28 07:25:16 +000010097 }
10098 c = '?';
Eric Andersenc470f442003-07-28 09:56:35 +000010099 goto out;
Eric Andersencb57d552001-06-28 07:25:16 +000010100 }
10101 if (*++q == ':')
10102 q++;
10103 }
10104
10105 if (*++q == ':') {
10106 if (*p == '\0' && (p = *optnext) == NULL) {
10107 if (optstr[0] == ':') {
10108 s[0] = c;
10109 s[1] = '\0';
10110 err |= setvarsafe("OPTARG", s, 0);
10111 c = ':';
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010112 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000010113 fprintf(stderr, "No arg for -%c option\n", c);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010114 unsetvar("OPTARG");
Eric Andersencb57d552001-06-28 07:25:16 +000010115 c = '?';
10116 }
Eric Andersenc470f442003-07-28 09:56:35 +000010117 goto out;
Eric Andersencb57d552001-06-28 07:25:16 +000010118 }
10119
10120 if (p == *optnext)
10121 optnext++;
Eric Andersenc470f442003-07-28 09:56:35 +000010122 err |= setvarsafe("OPTARG", p, 0);
Eric Andersencb57d552001-06-28 07:25:16 +000010123 p = NULL;
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010124 } else
Eric Andersenc470f442003-07-28 09:56:35 +000010125 err |= setvarsafe("OPTARG", nullstr, 0);
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010126 out:
Eric Andersencb57d552001-06-28 07:25:16 +000010127 *optoff = p ? p - *(optnext - 1) : -1;
Eric Andersenc470f442003-07-28 09:56:35 +000010128 *param_optind = optnext - optfirst + 1;
10129 fmtstr(s, sizeof(s), "%d", *param_optind);
Eric Andersencb57d552001-06-28 07:25:16 +000010130 err |= setvarsafe("OPTIND", s, VNOFUNC);
10131 s[0] = c;
10132 s[1] = '\0';
10133 err |= setvarsafe(optvar, s, 0);
10134 if (err) {
Eric Andersenc470f442003-07-28 09:56:35 +000010135 *param_optind = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010136 *optoff = -1;
Denis Vlasenkob012b102007-02-19 22:43:01 +000010137 flush_stdout_stderr();
10138 raise_exception(EXERROR);
Eric Andersencb57d552001-06-28 07:25:16 +000010139 }
10140 return done;
10141}
Eric Andersenc470f442003-07-28 09:56:35 +000010142
10143/*
10144 * The getopts builtin. Shellparam.optnext points to the next argument
10145 * to be processed. Shellparam.optptr points to the next character to
10146 * be processed in the current argument. If shellparam.optnext is NULL,
10147 * then it's the first time getopts has been called.
10148 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010149static int FAST_FUNC
Eric Andersenc470f442003-07-28 09:56:35 +000010150getoptscmd(int argc, char **argv)
10151{
10152 char **optbase;
10153
10154 if (argc < 3)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +000010155 ash_msg_and_raise_error("usage: getopts optstring var [arg]");
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010156 if (argc == 3) {
Eric Andersenc470f442003-07-28 09:56:35 +000010157 optbase = shellparam.p;
10158 if (shellparam.optind > shellparam.nparam + 1) {
10159 shellparam.optind = 1;
10160 shellparam.optoff = -1;
10161 }
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010162 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000010163 optbase = &argv[3];
10164 if (shellparam.optind > argc - 2) {
10165 shellparam.optind = 1;
10166 shellparam.optoff = -1;
10167 }
10168 }
10169
10170 return getopts(argv[1], argv[2], optbase, &shellparam.optind,
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010171 &shellparam.optoff);
Eric Andersenc470f442003-07-28 09:56:35 +000010172}
Denis Vlasenko131ae172007-02-18 13:00:19 +000010173#endif /* ASH_GETOPTS */
Eric Andersencb57d552001-06-28 07:25:16 +000010174
Eric Andersencb57d552001-06-28 07:25:16 +000010175
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010176/* ============ Shell parser */
Eric Andersencb57d552001-06-28 07:25:16 +000010177
Denis Vlasenkob07a4962008-06-22 13:16:23 +000010178struct heredoc {
10179 struct heredoc *next; /* next here document in list */
10180 union node *here; /* redirection node */
10181 char *eofmark; /* string indicating end of input */
10182 smallint striptabs; /* if set, strip leading tabs */
10183};
10184
10185static smallint tokpushback; /* last token pushed back */
10186static smallint parsebackquote; /* nonzero if we are inside backquotes */
10187static smallint quoteflag; /* set if (part of) last token was quoted */
10188static token_id_t lasttoken; /* last token read (integer id Txxx) */
10189static struct heredoc *heredoclist; /* list of here documents to read */
10190static char *wordtext; /* text of last word returned by readtoken */
10191static struct nodelist *backquotelist;
10192static union node *redirnode;
10193static struct heredoc *heredoc;
Denis Vlasenko99eb8502007-02-23 21:09:49 +000010194
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010195/*
10196 * Called when an unexpected token is read during the parse. The argument
10197 * is the token that is expected, or -1 if more than one type of token can
10198 * occur at this point.
10199 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000010200static void raise_error_unexpected_syntax(int) NORETURN;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010201static void
10202raise_error_unexpected_syntax(int token)
10203{
10204 char msg[64];
10205 int l;
10206
Denis Vlasenko7b2294e2008-11-28 03:50:46 +000010207 l = sprintf(msg, "unexpected %s", tokname(lasttoken));
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010208 if (token >= 0)
10209 sprintf(msg + l, " (expecting %s)", tokname(token));
10210 raise_error_syntax(msg);
10211 /* NOTREACHED */
10212}
Eric Andersencb57d552001-06-28 07:25:16 +000010213
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010214#define EOFMARKLEN 79
Eric Andersencb57d552001-06-28 07:25:16 +000010215
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010216/* parsing is heavily cross-recursive, need these forward decls */
10217static union node *andor(void);
10218static union node *pipeline(void);
10219static union node *parse_command(void);
10220static void parseheredoc(void);
10221static char peektoken(void);
10222static int readtoken(void);
Eric Andersencb57d552001-06-28 07:25:16 +000010223
Eric Andersenc470f442003-07-28 09:56:35 +000010224static union node *
10225list(int nlflag)
Eric Andersencb57d552001-06-28 07:25:16 +000010226{
10227 union node *n1, *n2, *n3;
10228 int tok;
10229
Eric Andersenc470f442003-07-28 09:56:35 +000010230 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10231 if (nlflag == 2 && peektoken())
Eric Andersencb57d552001-06-28 07:25:16 +000010232 return NULL;
10233 n1 = NULL;
10234 for (;;) {
10235 n2 = andor();
10236 tok = readtoken();
10237 if (tok == TBACKGND) {
Eric Andersenc470f442003-07-28 09:56:35 +000010238 if (n2->type == NPIPE) {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +000010239 n2->npipe.pipe_backgnd = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010240 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000010241 if (n2->type != NREDIR) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010242 n3 = stzalloc(sizeof(struct nredir));
Eric Andersenc470f442003-07-28 09:56:35 +000010243 n3->nredir.n = n2;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010244 /*n3->nredir.redirect = NULL; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000010245 n2 = n3;
10246 }
10247 n2->type = NBACKGND;
Eric Andersencb57d552001-06-28 07:25:16 +000010248 }
10249 }
10250 if (n1 == NULL) {
10251 n1 = n2;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010252 } else {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010253 n3 = stzalloc(sizeof(struct nbinary));
Eric Andersencb57d552001-06-28 07:25:16 +000010254 n3->type = NSEMI;
10255 n3->nbinary.ch1 = n1;
10256 n3->nbinary.ch2 = n2;
10257 n1 = n3;
10258 }
10259 switch (tok) {
10260 case TBACKGND:
10261 case TSEMI:
10262 tok = readtoken();
10263 /* fall through */
10264 case TNL:
10265 if (tok == TNL) {
10266 parseheredoc();
Eric Andersenc470f442003-07-28 09:56:35 +000010267 if (nlflag == 1)
Eric Andersencb57d552001-06-28 07:25:16 +000010268 return n1;
10269 } else {
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010270 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010271 }
Eric Andersenc470f442003-07-28 09:56:35 +000010272 checkkwd = CHKNL | CHKKWD | CHKALIAS;
Manuel Novoa III 16815d42001-08-10 19:36:07 +000010273 if (peektoken())
Eric Andersencb57d552001-06-28 07:25:16 +000010274 return n1;
10275 break;
10276 case TEOF:
10277 if (heredoclist)
10278 parseheredoc();
10279 else
Eric Andersenc470f442003-07-28 09:56:35 +000010280 pungetc(); /* push back EOF on input */
Eric Andersencb57d552001-06-28 07:25:16 +000010281 return n1;
10282 default:
Eric Andersenc470f442003-07-28 09:56:35 +000010283 if (nlflag == 1)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010284 raise_error_unexpected_syntax(-1);
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010285 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010286 return n1;
10287 }
10288 }
10289}
10290
Eric Andersenc470f442003-07-28 09:56:35 +000010291static union node *
10292andor(void)
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010293{
Eric Andersencb57d552001-06-28 07:25:16 +000010294 union node *n1, *n2, *n3;
10295 int t;
10296
Eric Andersencb57d552001-06-28 07:25:16 +000010297 n1 = pipeline();
10298 for (;;) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010299 t = readtoken();
10300 if (t == TAND) {
Eric Andersencb57d552001-06-28 07:25:16 +000010301 t = NAND;
10302 } else if (t == TOR) {
10303 t = NOR;
10304 } else {
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010305 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010306 return n1;
10307 }
Eric Andersenc470f442003-07-28 09:56:35 +000010308 checkkwd = CHKNL | CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010309 n2 = pipeline();
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010310 n3 = stzalloc(sizeof(struct nbinary));
Eric Andersencb57d552001-06-28 07:25:16 +000010311 n3->type = t;
10312 n3->nbinary.ch1 = n1;
10313 n3->nbinary.ch2 = n2;
10314 n1 = n3;
10315 }
10316}
10317
Eric Andersenc470f442003-07-28 09:56:35 +000010318static union node *
10319pipeline(void)
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010320{
Eric Andersencb57d552001-06-28 07:25:16 +000010321 union node *n1, *n2, *pipenode;
10322 struct nodelist *lp, *prev;
10323 int negate;
10324
10325 negate = 0;
10326 TRACE(("pipeline: entered\n"));
10327 if (readtoken() == TNOT) {
10328 negate = !negate;
Eric Andersenc470f442003-07-28 09:56:35 +000010329 checkkwd = CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010330 } else
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010331 tokpushback = 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010332 n1 = parse_command();
Eric Andersencb57d552001-06-28 07:25:16 +000010333 if (readtoken() == TPIPE) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010334 pipenode = stzalloc(sizeof(struct npipe));
Eric Andersencb57d552001-06-28 07:25:16 +000010335 pipenode->type = NPIPE;
Denis Vlasenko2dc240c2008-07-24 06:07:50 +000010336 /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010337 lp = stzalloc(sizeof(struct nodelist));
Eric Andersencb57d552001-06-28 07:25:16 +000010338 pipenode->npipe.cmdlist = lp;
10339 lp->n = n1;
10340 do {
10341 prev = lp;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010342 lp = stzalloc(sizeof(struct nodelist));
Eric Andersenc470f442003-07-28 09:56:35 +000010343 checkkwd = CHKNL | CHKKWD | CHKALIAS;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010344 lp->n = parse_command();
Eric Andersencb57d552001-06-28 07:25:16 +000010345 prev->next = lp;
10346 } while (readtoken() == TPIPE);
10347 lp->next = NULL;
10348 n1 = pipenode;
10349 }
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010350 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010351 if (negate) {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010352 n2 = stzalloc(sizeof(struct nnot));
Eric Andersencb57d552001-06-28 07:25:16 +000010353 n2->type = NNOT;
10354 n2->nnot.com = n1;
10355 return n2;
Denis Vlasenko2da584f2007-02-19 22:44:05 +000010356 }
10357 return n1;
Eric Andersencb57d552001-06-28 07:25:16 +000010358}
10359
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010360static union node *
10361makename(void)
10362{
10363 union node *n;
10364
Denis Vlasenko597906c2008-02-20 16:38:54 +000010365 n = stzalloc(sizeof(struct narg));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010366 n->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010367 /*n->narg.next = NULL; - stzalloc did it */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010368 n->narg.text = wordtext;
10369 n->narg.backquote = backquotelist;
10370 return n;
10371}
10372
10373static void
10374fixredir(union node *n, const char *text, int err)
10375{
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000010376 int fd;
10377
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010378 TRACE(("Fix redir %s %d\n", text, err));
10379 if (!err)
10380 n->ndup.vname = NULL;
10381
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000010382 fd = bb_strtou(text, NULL, 10);
10383 if (!errno && fd >= 0)
10384 n->ndup.dupfd = fd;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010385 else if (LONE_DASH(text))
10386 n->ndup.dupfd = -1;
10387 else {
10388 if (err)
Denis Vlasenko559691a2008-10-05 18:39:31 +000010389 raise_error_syntax("bad fd number");
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010390 n->ndup.vname = makename();
10391 }
10392}
10393
10394/*
10395 * Returns true if the text contains nothing to expand (no dollar signs
10396 * or backquotes).
10397 */
10398static int
Denis Vlasenko68819d12008-12-15 11:26:36 +000010399noexpand(const char *text)
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010400{
Denys Vlasenkocd716832009-11-28 22:14:02 +010010401 unsigned char c;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010402
Denys Vlasenkocd716832009-11-28 22:14:02 +010010403 while ((c = *text++) != '\0') {
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010404 if (c == CTLQUOTEMARK)
10405 continue;
10406 if (c == CTLESC)
Denys Vlasenkocd716832009-11-28 22:14:02 +010010407 text++;
Denys Vlasenko76bc2d62009-11-29 01:37:46 +010010408 else if (SIT(c, BASESYNTAX) == CCTL)
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010409 return 0;
10410 }
10411 return 1;
10412}
10413
10414static void
10415parsefname(void)
10416{
10417 union node *n = redirnode;
10418
10419 if (readtoken() != TWORD)
10420 raise_error_unexpected_syntax(-1);
10421 if (n->type == NHERE) {
10422 struct heredoc *here = heredoc;
10423 struct heredoc *p;
10424 int i;
10425
10426 if (quoteflag == 0)
10427 n->type = NXHERE;
10428 TRACE(("Here document %d\n", n->type));
10429 if (!noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
Denis Vlasenko559691a2008-10-05 18:39:31 +000010430 raise_error_syntax("illegal eof marker for << redirection");
Denys Vlasenkob6c84342009-08-29 20:23:20 +020010431 rmescapes(wordtext, 0);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010432 here->eofmark = wordtext;
10433 here->next = NULL;
10434 if (heredoclist == NULL)
10435 heredoclist = here;
10436 else {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010437 for (p = heredoclist; p->next; p = p->next)
10438 continue;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010439 p->next = here;
10440 }
10441 } else if (n->type == NTOFD || n->type == NFROMFD) {
10442 fixredir(n, wordtext, 0);
10443 } else {
10444 n->nfile.fname = makename();
10445 }
10446}
Eric Andersencb57d552001-06-28 07:25:16 +000010447
Eric Andersenc470f442003-07-28 09:56:35 +000010448static union node *
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010449simplecmd(void)
10450{
10451 union node *args, **app;
10452 union node *n = NULL;
10453 union node *vars, **vpp;
10454 union node **rpp, *redir;
10455 int savecheckkwd;
Denis Vlasenko80591b02008-03-25 07:49:43 +000010456#if ENABLE_ASH_BASH_COMPAT
10457 smallint double_brackets_flag = 0;
10458#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010459
10460 args = NULL;
10461 app = &args;
10462 vars = NULL;
10463 vpp = &vars;
10464 redir = NULL;
10465 rpp = &redir;
10466
10467 savecheckkwd = CHKALIAS;
10468 for (;;) {
Denis Vlasenko80591b02008-03-25 07:49:43 +000010469 int t;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010470 checkkwd = savecheckkwd;
Denis Vlasenko80591b02008-03-25 07:49:43 +000010471 t = readtoken();
10472 switch (t) {
10473#if ENABLE_ASH_BASH_COMPAT
10474 case TAND: /* "&&" */
10475 case TOR: /* "||" */
10476 if (!double_brackets_flag) {
10477 tokpushback = 1;
10478 goto out;
10479 }
10480 wordtext = (char *) (t == TAND ? "-a" : "-o");
10481#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010482 case TWORD:
Denis Vlasenko597906c2008-02-20 16:38:54 +000010483 n = stzalloc(sizeof(struct narg));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010484 n->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010485 /*n->narg.next = NULL; - stzalloc did it */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010486 n->narg.text = wordtext;
Denis Vlasenko80591b02008-03-25 07:49:43 +000010487#if ENABLE_ASH_BASH_COMPAT
10488 if (strcmp("[[", wordtext) == 0)
10489 double_brackets_flag = 1;
10490 else if (strcmp("]]", wordtext) == 0)
10491 double_brackets_flag = 0;
10492#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010493 n->narg.backquote = backquotelist;
10494 if (savecheckkwd && isassignment(wordtext)) {
10495 *vpp = n;
10496 vpp = &n->narg.next;
10497 } else {
10498 *app = n;
10499 app = &n->narg.next;
10500 savecheckkwd = 0;
10501 }
10502 break;
10503 case TREDIR:
10504 *rpp = n = redirnode;
10505 rpp = &n->nfile.next;
10506 parsefname(); /* read name of redirection file */
10507 break;
10508 case TLP:
10509 if (args && app == &args->narg.next
10510 && !vars && !redir
10511 ) {
10512 struct builtincmd *bcmd;
10513 const char *name;
10514
10515 /* We have a function */
10516 if (readtoken() != TRP)
10517 raise_error_unexpected_syntax(TRP);
10518 name = n->narg.text;
10519 if (!goodname(name)
10520 || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
10521 ) {
Denis Vlasenko559691a2008-10-05 18:39:31 +000010522 raise_error_syntax("bad function name");
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010523 }
10524 n->type = NDEFUN;
10525 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10526 n->narg.next = parse_command();
10527 return n;
10528 }
10529 /* fall through */
10530 default:
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010531 tokpushback = 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010532 goto out;
10533 }
10534 }
10535 out:
10536 *app = NULL;
10537 *vpp = NULL;
10538 *rpp = NULL;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010539 n = stzalloc(sizeof(struct ncmd));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010540 n->type = NCMD;
10541 n->ncmd.args = args;
10542 n->ncmd.assign = vars;
10543 n->ncmd.redirect = redir;
10544 return n;
10545}
10546
10547static union node *
10548parse_command(void)
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010549{
Eric Andersencb57d552001-06-28 07:25:16 +000010550 union node *n1, *n2;
10551 union node *ap, **app;
10552 union node *cp, **cpp;
10553 union node *redir, **rpp;
Eric Andersenc470f442003-07-28 09:56:35 +000010554 union node **rpp2;
Eric Andersencb57d552001-06-28 07:25:16 +000010555 int t;
10556
10557 redir = NULL;
Eric Andersenc470f442003-07-28 09:56:35 +000010558 rpp2 = &redir;
Eric Andersen88cec252001-09-06 17:35:20 +000010559
Eric Andersencb57d552001-06-28 07:25:16 +000010560 switch (readtoken()) {
Eric Andersenc470f442003-07-28 09:56:35 +000010561 default:
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010562 raise_error_unexpected_syntax(-1);
Eric Andersenc470f442003-07-28 09:56:35 +000010563 /* NOTREACHED */
Eric Andersencb57d552001-06-28 07:25:16 +000010564 case TIF:
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010565 n1 = stzalloc(sizeof(struct nif));
Eric Andersencb57d552001-06-28 07:25:16 +000010566 n1->type = NIF;
10567 n1->nif.test = list(0);
10568 if (readtoken() != TTHEN)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010569 raise_error_unexpected_syntax(TTHEN);
Eric Andersencb57d552001-06-28 07:25:16 +000010570 n1->nif.ifpart = list(0);
10571 n2 = n1;
10572 while (readtoken() == TELIF) {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010573 n2->nif.elsepart = stzalloc(sizeof(struct nif));
Eric Andersencb57d552001-06-28 07:25:16 +000010574 n2 = n2->nif.elsepart;
10575 n2->type = NIF;
10576 n2->nif.test = list(0);
10577 if (readtoken() != TTHEN)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010578 raise_error_unexpected_syntax(TTHEN);
Eric Andersencb57d552001-06-28 07:25:16 +000010579 n2->nif.ifpart = list(0);
10580 }
10581 if (lasttoken == TELSE)
10582 n2->nif.elsepart = list(0);
10583 else {
10584 n2->nif.elsepart = NULL;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010585 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010586 }
Eric Andersenc470f442003-07-28 09:56:35 +000010587 t = TFI;
Eric Andersencb57d552001-06-28 07:25:16 +000010588 break;
10589 case TWHILE:
Eric Andersenc470f442003-07-28 09:56:35 +000010590 case TUNTIL: {
Eric Andersencb57d552001-06-28 07:25:16 +000010591 int got;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010592 n1 = stzalloc(sizeof(struct nbinary));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010593 n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
Eric Andersencb57d552001-06-28 07:25:16 +000010594 n1->nbinary.ch1 = list(0);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010595 got = readtoken();
10596 if (got != TDO) {
Denis Vlasenko131ae172007-02-18 13:00:19 +000010597 TRACE(("expecting DO got %s %s\n", tokname(got),
10598 got == TWORD ? wordtext : ""));
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010599 raise_error_unexpected_syntax(TDO);
Eric Andersencb57d552001-06-28 07:25:16 +000010600 }
10601 n1->nbinary.ch2 = list(0);
Eric Andersenc470f442003-07-28 09:56:35 +000010602 t = TDONE;
Eric Andersencb57d552001-06-28 07:25:16 +000010603 break;
10604 }
10605 case TFOR:
Denis Vlasenko2dc240c2008-07-24 06:07:50 +000010606 if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
Denis Vlasenko559691a2008-10-05 18:39:31 +000010607 raise_error_syntax("bad for loop variable");
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010608 n1 = stzalloc(sizeof(struct nfor));
Eric Andersencb57d552001-06-28 07:25:16 +000010609 n1->type = NFOR;
10610 n1->nfor.var = wordtext;
Eric Andersenc470f442003-07-28 09:56:35 +000010611 checkkwd = CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010612 if (readtoken() == TIN) {
10613 app = &ap;
10614 while (readtoken() == TWORD) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010615 n2 = stzalloc(sizeof(struct narg));
Eric Andersencb57d552001-06-28 07:25:16 +000010616 n2->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010617 /*n2->narg.next = NULL; - stzalloc did it */
Eric Andersencb57d552001-06-28 07:25:16 +000010618 n2->narg.text = wordtext;
10619 n2->narg.backquote = backquotelist;
10620 *app = n2;
10621 app = &n2->narg.next;
10622 }
10623 *app = NULL;
10624 n1->nfor.args = ap;
10625 if (lasttoken != TNL && lasttoken != TSEMI)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010626 raise_error_unexpected_syntax(-1);
Eric Andersencb57d552001-06-28 07:25:16 +000010627 } else {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010628 n2 = stzalloc(sizeof(struct narg));
Eric Andersencb57d552001-06-28 07:25:16 +000010629 n2->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010630 /*n2->narg.next = NULL; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000010631 n2->narg.text = (char *)dolatstr;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010632 /*n2->narg.backquote = NULL;*/
Eric Andersencb57d552001-06-28 07:25:16 +000010633 n1->nfor.args = n2;
10634 /*
10635 * Newline or semicolon here is optional (but note
10636 * that the original Bourne shell only allowed NL).
10637 */
10638 if (lasttoken != TNL && lasttoken != TSEMI)
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010639 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010640 }
Eric Andersenc470f442003-07-28 09:56:35 +000010641 checkkwd = CHKNL | CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010642 if (readtoken() != TDO)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010643 raise_error_unexpected_syntax(TDO);
Eric Andersencb57d552001-06-28 07:25:16 +000010644 n1->nfor.body = list(0);
Eric Andersenc470f442003-07-28 09:56:35 +000010645 t = TDONE;
Eric Andersencb57d552001-06-28 07:25:16 +000010646 break;
10647 case TCASE:
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010648 n1 = stzalloc(sizeof(struct ncase));
Eric Andersencb57d552001-06-28 07:25:16 +000010649 n1->type = NCASE;
10650 if (readtoken() != TWORD)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010651 raise_error_unexpected_syntax(TWORD);
Denis Vlasenko597906c2008-02-20 16:38:54 +000010652 n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
Eric Andersencb57d552001-06-28 07:25:16 +000010653 n2->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010654 /*n2->narg.next = NULL; - stzalloc did it */
Eric Andersencb57d552001-06-28 07:25:16 +000010655 n2->narg.text = wordtext;
10656 n2->narg.backquote = backquotelist;
Eric Andersencb57d552001-06-28 07:25:16 +000010657 do {
Eric Andersenc470f442003-07-28 09:56:35 +000010658 checkkwd = CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010659 } while (readtoken() == TNL);
10660 if (lasttoken != TIN)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010661 raise_error_unexpected_syntax(TIN);
Eric Andersencb57d552001-06-28 07:25:16 +000010662 cpp = &n1->ncase.cases;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010663 next_case:
Eric Andersenc470f442003-07-28 09:56:35 +000010664 checkkwd = CHKNL | CHKKWD;
10665 t = readtoken();
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010666 while (t != TESAC) {
Eric Andersencb57d552001-06-28 07:25:16 +000010667 if (lasttoken == TLP)
10668 readtoken();
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010669 *cpp = cp = stzalloc(sizeof(struct nclist));
Eric Andersencb57d552001-06-28 07:25:16 +000010670 cp->type = NCLIST;
10671 app = &cp->nclist.pattern;
10672 for (;;) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010673 *app = ap = stzalloc(sizeof(struct narg));
Eric Andersencb57d552001-06-28 07:25:16 +000010674 ap->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010675 /*ap->narg.next = NULL; - stzalloc did it */
Eric Andersencb57d552001-06-28 07:25:16 +000010676 ap->narg.text = wordtext;
10677 ap->narg.backquote = backquotelist;
Eric Andersenc470f442003-07-28 09:56:35 +000010678 if (readtoken() != TPIPE)
Eric Andersencb57d552001-06-28 07:25:16 +000010679 break;
10680 app = &ap->narg.next;
10681 readtoken();
10682 }
Denis Vlasenko597906c2008-02-20 16:38:54 +000010683 //ap->narg.next = NULL;
Eric Andersencb57d552001-06-28 07:25:16 +000010684 if (lasttoken != TRP)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010685 raise_error_unexpected_syntax(TRP);
Eric Andersenc470f442003-07-28 09:56:35 +000010686 cp->nclist.body = list(2);
Eric Andersencb57d552001-06-28 07:25:16 +000010687
Eric Andersenc470f442003-07-28 09:56:35 +000010688 cpp = &cp->nclist.next;
10689
10690 checkkwd = CHKNL | CHKKWD;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010691 t = readtoken();
10692 if (t != TESAC) {
Eric Andersencb57d552001-06-28 07:25:16 +000010693 if (t != TENDCASE)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010694 raise_error_unexpected_syntax(TENDCASE);
10695 goto next_case;
Eric Andersencb57d552001-06-28 07:25:16 +000010696 }
Eric Andersenc470f442003-07-28 09:56:35 +000010697 }
Eric Andersencb57d552001-06-28 07:25:16 +000010698 *cpp = NULL;
Eric Andersenc470f442003-07-28 09:56:35 +000010699 goto redir;
Eric Andersencb57d552001-06-28 07:25:16 +000010700 case TLP:
Denis Vlasenko597906c2008-02-20 16:38:54 +000010701 n1 = stzalloc(sizeof(struct nredir));
Eric Andersencb57d552001-06-28 07:25:16 +000010702 n1->type = NSUBSHELL;
10703 n1->nredir.n = list(0);
Denis Vlasenko597906c2008-02-20 16:38:54 +000010704 /*n1->nredir.redirect = NULL; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000010705 t = TRP;
Eric Andersencb57d552001-06-28 07:25:16 +000010706 break;
10707 case TBEGIN:
10708 n1 = list(0);
Eric Andersenc470f442003-07-28 09:56:35 +000010709 t = TEND;
Eric Andersencb57d552001-06-28 07:25:16 +000010710 break;
Eric Andersencb57d552001-06-28 07:25:16 +000010711 case TWORD:
Eric Andersenc470f442003-07-28 09:56:35 +000010712 case TREDIR:
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010713 tokpushback = 1;
Eric Andersenc470f442003-07-28 09:56:35 +000010714 return simplecmd();
Eric Andersencb57d552001-06-28 07:25:16 +000010715 }
10716
Eric Andersenc470f442003-07-28 09:56:35 +000010717 if (readtoken() != t)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010718 raise_error_unexpected_syntax(t);
Eric Andersenc470f442003-07-28 09:56:35 +000010719
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010720 redir:
Eric Andersencb57d552001-06-28 07:25:16 +000010721 /* Now check for redirection which may follow command */
Eric Andersenc470f442003-07-28 09:56:35 +000010722 checkkwd = CHKKWD | CHKALIAS;
10723 rpp = rpp2;
Eric Andersencb57d552001-06-28 07:25:16 +000010724 while (readtoken() == TREDIR) {
10725 *rpp = n2 = redirnode;
10726 rpp = &n2->nfile.next;
10727 parsefname();
10728 }
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010729 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010730 *rpp = NULL;
10731 if (redir) {
10732 if (n1->type != NSUBSHELL) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010733 n2 = stzalloc(sizeof(struct nredir));
Eric Andersencb57d552001-06-28 07:25:16 +000010734 n2->type = NREDIR;
10735 n2->nredir.n = n1;
10736 n1 = n2;
10737 }
10738 n1->nredir.redirect = redir;
10739 }
Eric Andersencb57d552001-06-28 07:25:16 +000010740 return n1;
10741}
10742
Denis Vlasenkoef527f52008-06-23 01:52:30 +000010743#if ENABLE_ASH_BASH_COMPAT
10744static int decode_dollar_squote(void)
10745{
10746 static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
10747 int c, cnt;
10748 char *p;
10749 char buf[4];
10750
10751 c = pgetc();
10752 p = strchr(C_escapes, c);
10753 if (p) {
10754 buf[0] = c;
10755 p = buf;
10756 cnt = 3;
10757 if ((unsigned char)(c - '0') <= 7) { /* \ooo */
10758 do {
10759 c = pgetc();
10760 *++p = c;
10761 } while ((unsigned char)(c - '0') <= 7 && --cnt);
10762 pungetc();
10763 } else if (c == 'x') { /* \xHH */
10764 do {
10765 c = pgetc();
10766 *++p = c;
10767 } while (isxdigit(c) && --cnt);
10768 pungetc();
10769 if (cnt == 3) { /* \x but next char is "bad" */
10770 c = 'x';
10771 goto unrecognized;
10772 }
10773 } else { /* simple seq like \\ or \t */
10774 p++;
10775 }
10776 *p = '\0';
10777 p = buf;
10778 c = bb_process_escape_sequence((void*)&p);
10779 } else { /* unrecognized "\z": print both chars unless ' or " */
10780 if (c != '\'' && c != '"') {
10781 unrecognized:
10782 c |= 0x100; /* "please encode \, then me" */
10783 }
10784 }
10785 return c;
10786}
10787#endif
10788
Eric Andersencb57d552001-06-28 07:25:16 +000010789/*
10790 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
10791 * is not NULL, read a here document. In the latter case, eofmark is the
10792 * word which marks the end of the document and striptabs is true if
Denys Vlasenkocd716832009-11-28 22:14:02 +010010793 * leading tabs should be stripped from the document. The argument c
Eric Andersencb57d552001-06-28 07:25:16 +000010794 * is the first character of the input token or document.
10795 *
10796 * Because C does not have internal subroutines, I have simulated them
10797 * using goto's to implement the subroutine linkage. The following macros
10798 * will run code that appears at the end of readtoken1.
10799 */
Eric Andersen2870d962001-07-02 17:27:21 +000010800#define CHECKEND() {goto checkend; checkend_return:;}
10801#define PARSEREDIR() {goto parseredir; parseredir_return:;}
10802#define PARSESUB() {goto parsesub; parsesub_return:;}
10803#define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
10804#define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
10805#define PARSEARITH() {goto parsearith; parsearith_return:;}
Eric Andersencb57d552001-06-28 07:25:16 +000010806static int
Denys Vlasenkocd716832009-11-28 22:14:02 +010010807readtoken1(int c, int syntax, char *eofmark, int striptabs)
Manuel Novoa III 16815d42001-08-10 19:36:07 +000010808{
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010809 /* NB: syntax parameter fits into smallint */
Denys Vlasenkocd716832009-11-28 22:14:02 +010010810 /* c parameter is an unsigned char or PEOF or PEOA */
Eric Andersencb57d552001-06-28 07:25:16 +000010811 char *out;
10812 int len;
10813 char line[EOFMARKLEN + 1];
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010814 struct nodelist *bqlist;
10815 smallint quotef;
10816 smallint dblquote;
10817 smallint oldstyle;
10818 smallint prevsyntax; /* syntax before arithmetic */
Denis Vlasenko46a53062007-09-24 18:30:02 +000010819#if ENABLE_ASH_EXPAND_PRMT
10820 smallint pssyntax; /* we are expanding a prompt string */
10821#endif
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010822 int varnest; /* levels of variables expansion */
10823 int arinest; /* levels of arithmetic expansion */
10824 int parenlevel; /* levels of parens in arithmetic */
10825 int dqvarnest; /* levels of variables expansion within double quotes */
10826
Denis Vlasenko5e34ff22009-04-21 11:09:40 +000010827 IF_ASH_BASH_COMPAT(smallint bash_dollar_squote = 0;)
Denis Vlasenkoef527f52008-06-23 01:52:30 +000010828
Eric Andersencb57d552001-06-28 07:25:16 +000010829#if __GNUC__
10830 /* Avoid longjmp clobbering */
10831 (void) &out;
10832 (void) &quotef;
10833 (void) &dblquote;
10834 (void) &varnest;
10835 (void) &arinest;
10836 (void) &parenlevel;
10837 (void) &dqvarnest;
10838 (void) &oldstyle;
10839 (void) &prevsyntax;
10840 (void) &syntax;
10841#endif
Denis Vlasenko41eb3002008-11-28 03:42:31 +000010842 startlinno = g_parsefile->linno;
Eric Andersencb57d552001-06-28 07:25:16 +000010843 bqlist = NULL;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010844 quotef = 0;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010845 oldstyle = 0;
10846 prevsyntax = 0;
Denis Vlasenko46a53062007-09-24 18:30:02 +000010847#if ENABLE_ASH_EXPAND_PRMT
10848 pssyntax = (syntax == PSSYNTAX);
10849 if (pssyntax)
10850 syntax = DQSYNTAX;
10851#endif
10852 dblquote = (syntax == DQSYNTAX);
Eric Andersencb57d552001-06-28 07:25:16 +000010853 varnest = 0;
10854 arinest = 0;
10855 parenlevel = 0;
10856 dqvarnest = 0;
10857
10858 STARTSTACKSTR(out);
Denis Vlasenko176d49d2008-10-06 09:51:47 +000010859 loop:
10860 /* For each line, until end of word */
10861 {
Eric Andersenc470f442003-07-28 09:56:35 +000010862 CHECKEND(); /* set c to PEOF if at end of here document */
10863 for (;;) { /* until end of line or end of word */
10864 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
Denis Vlasenkobf0a2012006-12-26 10:42:51 +000010865 switch (SIT(c, syntax)) {
Eric Andersenc470f442003-07-28 09:56:35 +000010866 case CNL: /* '\n' */
Eric Andersencb57d552001-06-28 07:25:16 +000010867 if (syntax == BASESYNTAX)
Eric Andersenc470f442003-07-28 09:56:35 +000010868 goto endword; /* exit outer loop */
Eric Andersencb57d552001-06-28 07:25:16 +000010869 USTPUTC(c, out);
Denis Vlasenko41eb3002008-11-28 03:42:31 +000010870 g_parsefile->linno++;
Eric Andersencb57d552001-06-28 07:25:16 +000010871 if (doprompt)
10872 setprompt(2);
Eric Andersencb57d552001-06-28 07:25:16 +000010873 c = pgetc();
Eric Andersenc470f442003-07-28 09:56:35 +000010874 goto loop; /* continue outer loop */
Eric Andersencb57d552001-06-28 07:25:16 +000010875 case CWORD:
10876 USTPUTC(c, out);
10877 break;
10878 case CCTL:
Eric Andersenc470f442003-07-28 09:56:35 +000010879 if (eofmark == NULL || dblquote)
Eric Andersencb57d552001-06-28 07:25:16 +000010880 USTPUTC(CTLESC, out);
Denis Vlasenkoef527f52008-06-23 01:52:30 +000010881#if ENABLE_ASH_BASH_COMPAT
10882 if (c == '\\' && bash_dollar_squote) {
10883 c = decode_dollar_squote();
10884 if (c & 0x100) {
10885 USTPUTC('\\', out);
10886 c = (unsigned char)c;
10887 }
10888 }
10889#endif
Eric Andersencb57d552001-06-28 07:25:16 +000010890 USTPUTC(c, out);
10891 break;
Eric Andersenc470f442003-07-28 09:56:35 +000010892 case CBACK: /* backslash */
Denys Vlasenko2ce42e92009-11-29 02:18:13 +010010893 c = pgetc_without_PEOA();
Eric Andersencb57d552001-06-28 07:25:16 +000010894 if (c == PEOF) {
Eric Andersenc470f442003-07-28 09:56:35 +000010895 USTPUTC(CTLESC, out);
Eric Andersencb57d552001-06-28 07:25:16 +000010896 USTPUTC('\\', out);
10897 pungetc();
10898 } else if (c == '\n') {
10899 if (doprompt)
10900 setprompt(2);
Eric Andersencb57d552001-06-28 07:25:16 +000010901 } else {
Denis Vlasenko46a53062007-09-24 18:30:02 +000010902#if ENABLE_ASH_EXPAND_PRMT
10903 if (c == '$' && pssyntax) {
10904 USTPUTC(CTLESC, out);
10905 USTPUTC('\\', out);
10906 }
10907#endif
Denis Vlasenkoef527f52008-06-23 01:52:30 +000010908 if (dblquote && c != '\\'
10909 && c != '`' && c != '$'
10910 && (c != '"' || eofmark != NULL)
Eric Andersenc470f442003-07-28 09:56:35 +000010911 ) {
10912 USTPUTC(CTLESC, out);
Eric Andersencb57d552001-06-28 07:25:16 +000010913 USTPUTC('\\', out);
Eric Andersenc470f442003-07-28 09:56:35 +000010914 }
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010915 if (SIT(c, SQSYNTAX) == CCTL)
Eric Andersencb57d552001-06-28 07:25:16 +000010916 USTPUTC(CTLESC, out);
Eric Andersencb57d552001-06-28 07:25:16 +000010917 USTPUTC(c, out);
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010918 quotef = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010919 }
10920 break;
10921 case CSQUOTE:
Eric Andersencb57d552001-06-28 07:25:16 +000010922 syntax = SQSYNTAX;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010923 quotemark:
Eric Andersenc470f442003-07-28 09:56:35 +000010924 if (eofmark == NULL) {
10925 USTPUTC(CTLQUOTEMARK, out);
10926 }
Eric Andersencb57d552001-06-28 07:25:16 +000010927 break;
10928 case CDQUOTE:
Eric Andersencb57d552001-06-28 07:25:16 +000010929 syntax = DQSYNTAX;
10930 dblquote = 1;
Eric Andersenc470f442003-07-28 09:56:35 +000010931 goto quotemark;
Eric Andersencb57d552001-06-28 07:25:16 +000010932 case CENDQUOTE:
Denis Vlasenko5e34ff22009-04-21 11:09:40 +000010933 IF_ASH_BASH_COMPAT(bash_dollar_squote = 0;)
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010934 if (eofmark != NULL && arinest == 0
10935 && varnest == 0
10936 ) {
Eric Andersencb57d552001-06-28 07:25:16 +000010937 USTPUTC(c, out);
10938 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000010939 if (dqvarnest == 0) {
Eric Andersencb57d552001-06-28 07:25:16 +000010940 syntax = BASESYNTAX;
10941 dblquote = 0;
10942 }
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010943 quotef = 1;
Eric Andersenc470f442003-07-28 09:56:35 +000010944 goto quotemark;
Eric Andersencb57d552001-06-28 07:25:16 +000010945 }
10946 break;
Eric Andersenc470f442003-07-28 09:56:35 +000010947 case CVAR: /* '$' */
10948 PARSESUB(); /* parse substitution */
Eric Andersencb57d552001-06-28 07:25:16 +000010949 break;
Eric Andersenc470f442003-07-28 09:56:35 +000010950 case CENDVAR: /* '}' */
Eric Andersencb57d552001-06-28 07:25:16 +000010951 if (varnest > 0) {
10952 varnest--;
10953 if (dqvarnest > 0) {
10954 dqvarnest--;
10955 }
10956 USTPUTC(CTLENDVAR, out);
10957 } else {
10958 USTPUTC(c, out);
10959 }
10960 break;
Mike Frysinger98c52642009-04-02 10:02:37 +000010961#if ENABLE_SH_MATH_SUPPORT
Eric Andersenc470f442003-07-28 09:56:35 +000010962 case CLP: /* '(' in arithmetic */
Eric Andersencb57d552001-06-28 07:25:16 +000010963 parenlevel++;
10964 USTPUTC(c, out);
10965 break;
Eric Andersenc470f442003-07-28 09:56:35 +000010966 case CRP: /* ')' in arithmetic */
Eric Andersencb57d552001-06-28 07:25:16 +000010967 if (parenlevel > 0) {
10968 USTPUTC(c, out);
10969 --parenlevel;
10970 } else {
10971 if (pgetc() == ')') {
10972 if (--arinest == 0) {
10973 USTPUTC(CTLENDARI, out);
10974 syntax = prevsyntax;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010975 dblquote = (syntax == DQSYNTAX);
Eric Andersencb57d552001-06-28 07:25:16 +000010976 } else
10977 USTPUTC(')', out);
10978 } else {
10979 /*
10980 * unbalanced parens
10981 * (don't 2nd guess - no error)
10982 */
10983 pungetc();
10984 USTPUTC(')', out);
10985 }
10986 }
10987 break;
10988#endif
Eric Andersenc470f442003-07-28 09:56:35 +000010989 case CBQUOTE: /* '`' */
Eric Andersencb57d552001-06-28 07:25:16 +000010990 PARSEBACKQOLD();
10991 break;
Eric Andersen2870d962001-07-02 17:27:21 +000010992 case CENDFILE:
Eric Andersenc470f442003-07-28 09:56:35 +000010993 goto endword; /* exit outer loop */
Eric Andersencb57d552001-06-28 07:25:16 +000010994 case CIGN:
10995 break;
10996 default:
Denis Vlasenko834dee72008-10-07 09:18:30 +000010997 if (varnest == 0) {
10998#if ENABLE_ASH_BASH_COMPAT
10999 if (c == '&') {
11000 if (pgetc() == '>')
11001 c = 0x100 + '>'; /* flag &> */
11002 pungetc();
11003 }
11004#endif
Eric Andersenc470f442003-07-28 09:56:35 +000011005 goto endword; /* exit outer loop */
Denis Vlasenko834dee72008-10-07 09:18:30 +000011006 }
Denys Vlasenko2ce42e92009-11-29 02:18:13 +010011007 IF_ASH_ALIAS(if (c != PEOA))
Eric Andersencb57d552001-06-28 07:25:16 +000011008 USTPUTC(c, out);
Eric Andersen3102ac42001-07-06 04:26:23 +000011009
Eric Andersencb57d552001-06-28 07:25:16 +000011010 }
Denis Vlasenko834dee72008-10-07 09:18:30 +000011011 c = pgetc_fast();
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000011012 } /* for (;;) */
Eric Andersencb57d552001-06-28 07:25:16 +000011013 }
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011014 endword:
Mike Frysinger98c52642009-04-02 10:02:37 +000011015#if ENABLE_SH_MATH_SUPPORT
Eric Andersencb57d552001-06-28 07:25:16 +000011016 if (syntax == ARISYNTAX)
Denis Vlasenko559691a2008-10-05 18:39:31 +000011017 raise_error_syntax("missing '))'");
Eric Andersenc470f442003-07-28 09:56:35 +000011018#endif
Denis Vlasenko99eb8502007-02-23 21:09:49 +000011019 if (syntax != BASESYNTAX && !parsebackquote && eofmark == NULL)
Denis Vlasenko559691a2008-10-05 18:39:31 +000011020 raise_error_syntax("unterminated quoted string");
Eric Andersencb57d552001-06-28 07:25:16 +000011021 if (varnest != 0) {
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011022 startlinno = g_parsefile->linno;
Eric Andersenc470f442003-07-28 09:56:35 +000011023 /* { */
Denis Vlasenko559691a2008-10-05 18:39:31 +000011024 raise_error_syntax("missing '}'");
Eric Andersencb57d552001-06-28 07:25:16 +000011025 }
11026 USTPUTC('\0', out);
Eric Andersenc470f442003-07-28 09:56:35 +000011027 len = out - (char *)stackblock();
Eric Andersencb57d552001-06-28 07:25:16 +000011028 out = stackblock();
11029 if (eofmark == NULL) {
Denis Vlasenko5e34ff22009-04-21 11:09:40 +000011030 if ((c == '>' || c == '<' IF_ASH_BASH_COMPAT( || c == 0x100 + '>'))
Denis Vlasenko834dee72008-10-07 09:18:30 +000011031 && quotef == 0
11032 ) {
Denis Vlasenko559691a2008-10-05 18:39:31 +000011033 if (isdigit_str9(out)) {
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000011034 PARSEREDIR(); /* passed as params: out, c */
11035 lasttoken = TREDIR;
11036 return lasttoken;
11037 }
11038 /* else: non-number X seen, interpret it
11039 * as "NNNX>file" = "NNNX >file" */
Eric Andersencb57d552001-06-28 07:25:16 +000011040 }
Denis Vlasenkoef527f52008-06-23 01:52:30 +000011041 pungetc();
Eric Andersencb57d552001-06-28 07:25:16 +000011042 }
11043 quoteflag = quotef;
11044 backquotelist = bqlist;
11045 grabstackblock(len);
11046 wordtext = out;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011047 lasttoken = TWORD;
11048 return lasttoken;
Eric Andersencb57d552001-06-28 07:25:16 +000011049/* end of readtoken routine */
11050
Eric Andersencb57d552001-06-28 07:25:16 +000011051/*
11052 * Check to see whether we are at the end of the here document. When this
11053 * is called, c is set to the first character of the next input line. If
11054 * we are at the end of the here document, this routine sets the c to PEOF.
11055 */
Eric Andersenc470f442003-07-28 09:56:35 +000011056checkend: {
11057 if (eofmark) {
Denis Vlasenko131ae172007-02-18 13:00:19 +000011058#if ENABLE_ASH_ALIAS
Denys Vlasenko2ce42e92009-11-29 02:18:13 +010011059 if (c == PEOA)
11060 c = pgetc_without_PEOA();
Eric Andersenc470f442003-07-28 09:56:35 +000011061#endif
11062 if (striptabs) {
11063 while (c == '\t') {
Denys Vlasenko2ce42e92009-11-29 02:18:13 +010011064 c = pgetc_without_PEOA();
Eric Andersencb57d552001-06-28 07:25:16 +000011065 }
Eric Andersenc470f442003-07-28 09:56:35 +000011066 }
11067 if (c == *eofmark) {
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011068 if (pfgets(line, sizeof(line)) != NULL) {
Eric Andersenc470f442003-07-28 09:56:35 +000011069 char *p, *q;
Eric Andersencb57d552001-06-28 07:25:16 +000011070
Eric Andersenc470f442003-07-28 09:56:35 +000011071 p = line;
Denis Vlasenkof7d56652008-03-25 05:51:41 +000011072 for (q = eofmark + 1; *q && *p == *q; p++, q++)
11073 continue;
Eric Andersenc470f442003-07-28 09:56:35 +000011074 if (*p == '\n' && *q == '\0') {
11075 c = PEOF;
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011076 g_parsefile->linno++;
Eric Andersenc470f442003-07-28 09:56:35 +000011077 needprompt = doprompt;
11078 } else {
11079 pushstring(line, NULL);
Eric Andersencb57d552001-06-28 07:25:16 +000011080 }
11081 }
11082 }
11083 }
Eric Andersenc470f442003-07-28 09:56:35 +000011084 goto checkend_return;
11085}
Eric Andersencb57d552001-06-28 07:25:16 +000011086
Eric Andersencb57d552001-06-28 07:25:16 +000011087/*
11088 * Parse a redirection operator. The variable "out" points to a string
11089 * specifying the fd to be redirected. The variable "c" contains the
11090 * first character of the redirection operator.
11091 */
Eric Andersenc470f442003-07-28 09:56:35 +000011092parseredir: {
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000011093 /* out is already checked to be a valid number or "" */
11094 int fd = (*out == '\0' ? -1 : atoi(out));
Eric Andersenc470f442003-07-28 09:56:35 +000011095 union node *np;
Eric Andersencb57d552001-06-28 07:25:16 +000011096
Denis Vlasenko597906c2008-02-20 16:38:54 +000011097 np = stzalloc(sizeof(struct nfile));
Eric Andersenc470f442003-07-28 09:56:35 +000011098 if (c == '>') {
11099 np->nfile.fd = 1;
11100 c = pgetc();
11101 if (c == '>')
11102 np->type = NAPPEND;
11103 else if (c == '|')
11104 np->type = NCLOBBER;
11105 else if (c == '&')
11106 np->type = NTOFD;
Denis Vlasenko559691a2008-10-05 18:39:31 +000011107 /* it also can be NTO2 (>&file), but we can't figure it out yet */
Eric Andersenc470f442003-07-28 09:56:35 +000011108 else {
11109 np->type = NTO;
11110 pungetc();
Eric Andersencb57d552001-06-28 07:25:16 +000011111 }
Denis Vlasenko834dee72008-10-07 09:18:30 +000011112 }
11113#if ENABLE_ASH_BASH_COMPAT
11114 else if (c == 0x100 + '>') { /* this flags &> redirection */
11115 np->nfile.fd = 1;
11116 pgetc(); /* this is '>', no need to check */
11117 np->type = NTO2;
11118 }
11119#endif
11120 else { /* c == '<' */
Denis Vlasenko597906c2008-02-20 16:38:54 +000011121 /*np->nfile.fd = 0; - stzalloc did it */
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011122 c = pgetc();
11123 switch (c) {
Eric Andersenc470f442003-07-28 09:56:35 +000011124 case '<':
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011125 if (sizeof(struct nfile) != sizeof(struct nhere)) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000011126 np = stzalloc(sizeof(struct nhere));
11127 /*np->nfile.fd = 0; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000011128 }
11129 np->type = NHERE;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000011130 heredoc = stzalloc(sizeof(struct heredoc));
Eric Andersenc470f442003-07-28 09:56:35 +000011131 heredoc->here = np;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011132 c = pgetc();
11133 if (c == '-') {
Eric Andersenc470f442003-07-28 09:56:35 +000011134 heredoc->striptabs = 1;
11135 } else {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000011136 /*heredoc->striptabs = 0; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000011137 pungetc();
11138 }
11139 break;
11140
11141 case '&':
11142 np->type = NFROMFD;
11143 break;
11144
11145 case '>':
11146 np->type = NFROMTO;
11147 break;
11148
11149 default:
11150 np->type = NFROM;
11151 pungetc();
11152 break;
11153 }
Eric Andersencb57d552001-06-28 07:25:16 +000011154 }
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000011155 if (fd >= 0)
11156 np->nfile.fd = fd;
Eric Andersenc470f442003-07-28 09:56:35 +000011157 redirnode = np;
11158 goto parseredir_return;
11159}
Eric Andersencb57d552001-06-28 07:25:16 +000011160
Eric Andersencb57d552001-06-28 07:25:16 +000011161/*
11162 * Parse a substitution. At this point, we have read the dollar sign
11163 * and nothing else.
11164 */
Denis Vlasenkocc571512007-02-23 21:10:35 +000011165
11166/* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
11167 * (assuming ascii char codes, as the original implementation did) */
11168#define is_special(c) \
Denis Vlasenkoef527f52008-06-23 01:52:30 +000011169 (((unsigned)(c) - 33 < 32) \
11170 && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
Eric Andersenc470f442003-07-28 09:56:35 +000011171parsesub: {
Denys Vlasenkocd716832009-11-28 22:14:02 +010011172 unsigned char subtype;
Eric Andersenc470f442003-07-28 09:56:35 +000011173 int typeloc;
11174 int flags;
11175 char *p;
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011176 static const char types[] ALIGN1 = "}-+?=";
Eric Andersencb57d552001-06-28 07:25:16 +000011177
Eric Andersenc470f442003-07-28 09:56:35 +000011178 c = pgetc();
Denys Vlasenkocd716832009-11-28 22:14:02 +010011179 if (c > 255 /* PEOA or PEOF */
Denis Vlasenkoef527f52008-06-23 01:52:30 +000011180 || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
Eric Andersenc470f442003-07-28 09:56:35 +000011181 ) {
Denis Vlasenkoef527f52008-06-23 01:52:30 +000011182#if ENABLE_ASH_BASH_COMPAT
11183 if (c == '\'')
11184 bash_dollar_squote = 1;
11185 else
11186#endif
11187 USTPUTC('$', out);
Eric Andersenc470f442003-07-28 09:56:35 +000011188 pungetc();
11189 } else if (c == '(') { /* $(command) or $((arith)) */
11190 if (pgetc() == '(') {
Mike Frysinger98c52642009-04-02 10:02:37 +000011191#if ENABLE_SH_MATH_SUPPORT
Eric Andersenc470f442003-07-28 09:56:35 +000011192 PARSEARITH();
11193#else
Mike Frysinger98a6f562008-06-09 09:38:45 +000011194 raise_error_syntax("you disabled math support for $((arith)) syntax");
Eric Andersenc470f442003-07-28 09:56:35 +000011195#endif
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000011196 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000011197 pungetc();
11198 PARSEBACKQNEW();
11199 }
11200 } else {
11201 USTPUTC(CTLVAR, out);
11202 typeloc = out - (char *)stackblock();
11203 USTPUTC(VSNORMAL, out);
11204 subtype = VSNORMAL;
11205 if (c == '{') {
11206 c = pgetc();
11207 if (c == '#') {
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011208 c = pgetc();
11209 if (c == '}')
Eric Andersenc470f442003-07-28 09:56:35 +000011210 c = '#';
11211 else
11212 subtype = VSLENGTH;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011213 } else
Eric Andersenc470f442003-07-28 09:56:35 +000011214 subtype = 0;
11215 }
Denys Vlasenkocd716832009-11-28 22:14:02 +010011216 if (c <= 255 /* not PEOA or PEOF */ && is_name(c)) {
Eric Andersenc470f442003-07-28 09:56:35 +000011217 do {
11218 STPUTC(c, out);
Eric Andersencb57d552001-06-28 07:25:16 +000011219 c = pgetc();
Denys Vlasenkocd716832009-11-28 22:14:02 +010011220 } while (c <= 255 /* not PEOA or PEOF */ && is_in_name(c));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011221 } else if (isdigit(c)) {
Eric Andersenc470f442003-07-28 09:56:35 +000011222 do {
11223 STPUTC(c, out);
11224 c = pgetc();
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011225 } while (isdigit(c));
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011226 } else if (is_special(c)) {
Eric Andersenc470f442003-07-28 09:56:35 +000011227 USTPUTC(c, out);
11228 c = pgetc();
Denis Vlasenko559691a2008-10-05 18:39:31 +000011229 } else {
11230 badsub:
11231 raise_error_syntax("bad substitution");
11232 }
Cristian Ionescu-Idbohrn301f5ec2009-10-05 02:07:23 +020011233 if (c != '}' && subtype == VSLENGTH)
11234 goto badsub;
Eric Andersencb57d552001-06-28 07:25:16 +000011235
Eric Andersenc470f442003-07-28 09:56:35 +000011236 STPUTC('=', out);
11237 flags = 0;
11238 if (subtype == 0) {
11239 switch (c) {
11240 case ':':
Eric Andersenc470f442003-07-28 09:56:35 +000011241 c = pgetc();
Denis Vlasenko92e13c22008-03-25 01:17:40 +000011242#if ENABLE_ASH_BASH_COMPAT
11243 if (c == ':' || c == '$' || isdigit(c)) {
11244 pungetc();
11245 subtype = VSSUBSTR;
11246 break;
11247 }
11248#endif
11249 flags = VSNUL;
Eric Andersenc470f442003-07-28 09:56:35 +000011250 /*FALLTHROUGH*/
11251 default:
11252 p = strchr(types, c);
11253 if (p == NULL)
11254 goto badsub;
11255 subtype = p - types + VSNORMAL;
11256 break;
11257 case '%':
Denis Vlasenko92e13c22008-03-25 01:17:40 +000011258 case '#': {
11259 int cc = c;
11260 subtype = c == '#' ? VSTRIMLEFT : VSTRIMRIGHT;
11261 c = pgetc();
11262 if (c == cc)
11263 subtype++;
11264 else
11265 pungetc();
11266 break;
11267 }
11268#if ENABLE_ASH_BASH_COMPAT
11269 case '/':
11270 subtype = VSREPLACE;
11271 c = pgetc();
11272 if (c == '/')
11273 subtype++; /* VSREPLACEALL */
11274 else
11275 pungetc();
11276 break;
11277#endif
Eric Andersencb57d552001-06-28 07:25:16 +000011278 }
Eric Andersenc470f442003-07-28 09:56:35 +000011279 } else {
11280 pungetc();
11281 }
11282 if (dblquote || arinest)
11283 flags |= VSQUOTE;
Denys Vlasenkocd716832009-11-28 22:14:02 +010011284 ((unsigned char *)stackblock())[typeloc] = subtype | flags;
Eric Andersenc470f442003-07-28 09:56:35 +000011285 if (subtype != VSNORMAL) {
11286 varnest++;
11287 if (dblquote || arinest) {
11288 dqvarnest++;
Eric Andersencb57d552001-06-28 07:25:16 +000011289 }
11290 }
11291 }
Eric Andersenc470f442003-07-28 09:56:35 +000011292 goto parsesub_return;
11293}
Eric Andersencb57d552001-06-28 07:25:16 +000011294
Eric Andersencb57d552001-06-28 07:25:16 +000011295/*
11296 * Called to parse command substitutions. Newstyle is set if the command
11297 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
11298 * list of commands (passed by reference), and savelen is the number of
11299 * characters on the top of the stack which must be preserved.
11300 */
Eric Andersenc470f442003-07-28 09:56:35 +000011301parsebackq: {
11302 struct nodelist **nlpp;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011303 smallint savepbq;
Eric Andersenc470f442003-07-28 09:56:35 +000011304 union node *n;
11305 char *volatile str;
11306 struct jmploc jmploc;
11307 struct jmploc *volatile savehandler;
11308 size_t savelen;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011309 smallint saveprompt = 0;
11310
Eric Andersencb57d552001-06-28 07:25:16 +000011311#ifdef __GNUC__
Eric Andersenc470f442003-07-28 09:56:35 +000011312 (void) &saveprompt;
Eric Andersencb57d552001-06-28 07:25:16 +000011313#endif
Eric Andersenc470f442003-07-28 09:56:35 +000011314 savepbq = parsebackquote;
11315 if (setjmp(jmploc.loc)) {
Denis Vlasenko60818682007-09-28 22:07:23 +000011316 free(str);
Eric Andersenc470f442003-07-28 09:56:35 +000011317 parsebackquote = 0;
Denis Vlasenko2da584f2007-02-19 22:44:05 +000011318 exception_handler = savehandler;
11319 longjmp(exception_handler->loc, 1);
Eric Andersenc470f442003-07-28 09:56:35 +000011320 }
Denis Vlasenkob012b102007-02-19 22:43:01 +000011321 INT_OFF;
Eric Andersenc470f442003-07-28 09:56:35 +000011322 str = NULL;
11323 savelen = out - (char *)stackblock();
11324 if (savelen > 0) {
11325 str = ckmalloc(savelen);
11326 memcpy(str, stackblock(), savelen);
11327 }
Denis Vlasenko2da584f2007-02-19 22:44:05 +000011328 savehandler = exception_handler;
11329 exception_handler = &jmploc;
Denis Vlasenkob012b102007-02-19 22:43:01 +000011330 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +000011331 if (oldstyle) {
11332 /* We must read until the closing backquote, giving special
11333 treatment to some slashes, and then push the string and
11334 reread it as input, interpreting it normally. */
11335 char *pout;
11336 int pc;
11337 size_t psavelen;
11338 char *pstr;
11339
11340
11341 STARTSTACKSTR(pout);
11342 for (;;) {
11343 if (needprompt) {
11344 setprompt(2);
Eric Andersenc470f442003-07-28 09:56:35 +000011345 }
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011346 pc = pgetc();
11347 switch (pc) {
Eric Andersenc470f442003-07-28 09:56:35 +000011348 case '`':
11349 goto done;
11350
11351 case '\\':
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011352 pc = pgetc();
11353 if (pc == '\n') {
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011354 g_parsefile->linno++;
Eric Andersenc470f442003-07-28 09:56:35 +000011355 if (doprompt)
11356 setprompt(2);
11357 /*
11358 * If eating a newline, avoid putting
11359 * the newline into the new character
11360 * stream (via the STPUTC after the
11361 * switch).
11362 */
11363 continue;
11364 }
11365 if (pc != '\\' && pc != '`' && pc != '$'
Denys Vlasenko76bc2d62009-11-29 01:37:46 +010011366 && (!dblquote || pc != '"')
11367 ) {
Eric Andersenc470f442003-07-28 09:56:35 +000011368 STPUTC('\\', pout);
Denys Vlasenko76bc2d62009-11-29 01:37:46 +010011369 }
Denys Vlasenkocd716832009-11-28 22:14:02 +010011370 if (pc <= 255 /* not PEOA or PEOF */) {
Eric Andersenc470f442003-07-28 09:56:35 +000011371 break;
11372 }
11373 /* fall through */
11374
11375 case PEOF:
Denys Vlasenko2ce42e92009-11-29 02:18:13 +010011376 IF_ASH_ALIAS(case PEOA:)
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011377 startlinno = g_parsefile->linno;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000011378 raise_error_syntax("EOF in backquote substitution");
Eric Andersenc470f442003-07-28 09:56:35 +000011379
11380 case '\n':
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011381 g_parsefile->linno++;
Eric Andersenc470f442003-07-28 09:56:35 +000011382 needprompt = doprompt;
11383 break;
11384
11385 default:
11386 break;
11387 }
11388 STPUTC(pc, pout);
11389 }
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011390 done:
Eric Andersenc470f442003-07-28 09:56:35 +000011391 STPUTC('\0', pout);
11392 psavelen = pout - (char *)stackblock();
11393 if (psavelen > 0) {
11394 pstr = grabstackstr(pout);
11395 setinputstring(pstr);
11396 }
11397 }
11398 nlpp = &bqlist;
11399 while (*nlpp)
11400 nlpp = &(*nlpp)->next;
Denis Vlasenko597906c2008-02-20 16:38:54 +000011401 *nlpp = stzalloc(sizeof(**nlpp));
11402 /* (*nlpp)->next = NULL; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000011403 parsebackquote = oldstyle;
11404
11405 if (oldstyle) {
11406 saveprompt = doprompt;
11407 doprompt = 0;
Eric Andersencb57d552001-06-28 07:25:16 +000011408 }
11409
Eric Andersenc470f442003-07-28 09:56:35 +000011410 n = list(2);
11411
11412 if (oldstyle)
11413 doprompt = saveprompt;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011414 else if (readtoken() != TRP)
11415 raise_error_unexpected_syntax(TRP);
Eric Andersenc470f442003-07-28 09:56:35 +000011416
11417 (*nlpp)->n = n;
11418 if (oldstyle) {
11419 /*
11420 * Start reading from old file again, ignoring any pushed back
11421 * tokens left from the backquote parsing
11422 */
11423 popfile();
11424 tokpushback = 0;
11425 }
11426 while (stackblocksize() <= savelen)
11427 growstackblock();
11428 STARTSTACKSTR(out);
11429 if (str) {
11430 memcpy(out, str, savelen);
11431 STADJUST(savelen, out);
Denis Vlasenkob012b102007-02-19 22:43:01 +000011432 INT_OFF;
11433 free(str);
Eric Andersenc470f442003-07-28 09:56:35 +000011434 str = NULL;
Denis Vlasenkob012b102007-02-19 22:43:01 +000011435 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +000011436 }
11437 parsebackquote = savepbq;
Denis Vlasenko2da584f2007-02-19 22:44:05 +000011438 exception_handler = savehandler;
Eric Andersenc470f442003-07-28 09:56:35 +000011439 if (arinest || dblquote)
11440 USTPUTC(CTLBACKQ | CTLQUOTE, out);
11441 else
11442 USTPUTC(CTLBACKQ, out);
11443 if (oldstyle)
11444 goto parsebackq_oldreturn;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000011445 goto parsebackq_newreturn;
Eric Andersenc470f442003-07-28 09:56:35 +000011446}
11447
Mike Frysinger98c52642009-04-02 10:02:37 +000011448#if ENABLE_SH_MATH_SUPPORT
Eric Andersencb57d552001-06-28 07:25:16 +000011449/*
11450 * Parse an arithmetic expansion (indicate start of one and set state)
11451 */
Eric Andersenc470f442003-07-28 09:56:35 +000011452parsearith: {
Eric Andersenc470f442003-07-28 09:56:35 +000011453 if (++arinest == 1) {
11454 prevsyntax = syntax;
11455 syntax = ARISYNTAX;
11456 USTPUTC(CTLARI, out);
11457 if (dblquote)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000011458 USTPUTC('"', out);
Eric Andersenc470f442003-07-28 09:56:35 +000011459 else
Denis Vlasenkoa624c112007-02-19 22:45:43 +000011460 USTPUTC(' ', out);
Eric Andersenc470f442003-07-28 09:56:35 +000011461 } else {
11462 /*
11463 * we collapse embedded arithmetic expansion to
11464 * parenthesis, which should be equivalent
11465 */
11466 USTPUTC('(', out);
Eric Andersencb57d552001-06-28 07:25:16 +000011467 }
Eric Andersenc470f442003-07-28 09:56:35 +000011468 goto parsearith_return;
11469}
11470#endif
Eric Andersencb57d552001-06-28 07:25:16 +000011471
Eric Andersenc470f442003-07-28 09:56:35 +000011472} /* end of readtoken */
11473
Eric Andersencb57d552001-06-28 07:25:16 +000011474/*
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011475 * Read the next input token.
11476 * If the token is a word, we set backquotelist to the list of cmds in
11477 * backquotes. We set quoteflag to true if any part of the word was
11478 * quoted.
11479 * If the token is TREDIR, then we set redirnode to a structure containing
11480 * the redirection.
11481 * In all cases, the variable startlinno is set to the number of the line
11482 * on which the token starts.
11483 *
11484 * [Change comment: here documents and internal procedures]
11485 * [Readtoken shouldn't have any arguments. Perhaps we should make the
11486 * word parsing code into a separate routine. In this case, readtoken
11487 * doesn't need to have any internal procedures, but parseword does.
11488 * We could also make parseoperator in essence the main routine, and
11489 * have parseword (readtoken1?) handle both words and redirection.]
Eric Andersencb57d552001-06-28 07:25:16 +000011490 */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011491#define NEW_xxreadtoken
11492#ifdef NEW_xxreadtoken
11493/* singles must be first! */
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011494static const char xxreadtoken_chars[7] ALIGN1 = {
Denis Vlasenko834dee72008-10-07 09:18:30 +000011495 '\n', '(', ')', /* singles */
11496 '&', '|', ';', /* doubles */
11497 0
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011498};
Eric Andersencb57d552001-06-28 07:25:16 +000011499
Denis Vlasenko834dee72008-10-07 09:18:30 +000011500#define xxreadtoken_singles 3
11501#define xxreadtoken_doubles 3
11502
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011503static const char xxreadtoken_tokens[] ALIGN1 = {
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011504 TNL, TLP, TRP, /* only single occurrence allowed */
11505 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
11506 TEOF, /* corresponds to trailing nul */
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011507 TAND, TOR, TENDCASE /* if double occurrence */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011508};
11509
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011510static int
11511xxreadtoken(void)
11512{
11513 int c;
11514
11515 if (tokpushback) {
11516 tokpushback = 0;
11517 return lasttoken;
Eric Andersencb57d552001-06-28 07:25:16 +000011518 }
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011519 if (needprompt) {
11520 setprompt(2);
11521 }
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011522 startlinno = g_parsefile->linno;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011523 for (;;) { /* until token or start of word found */
Denis Vlasenko834dee72008-10-07 09:18:30 +000011524 c = pgetc_fast();
Denis Vlasenko5e34ff22009-04-21 11:09:40 +000011525 if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011526 continue;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011527
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011528 if (c == '#') {
11529 while ((c = pgetc()) != '\n' && c != PEOF)
11530 continue;
11531 pungetc();
11532 } else if (c == '\\') {
11533 if (pgetc() != '\n') {
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011534 pungetc();
Denis Vlasenko834dee72008-10-07 09:18:30 +000011535 break; /* return readtoken1(...) */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011536 }
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011537 startlinno = ++g_parsefile->linno;
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011538 if (doprompt)
11539 setprompt(2);
11540 } else {
11541 const char *p;
11542
11543 p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
11544 if (c != PEOF) {
11545 if (c == '\n') {
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011546 g_parsefile->linno++;
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011547 needprompt = doprompt;
11548 }
11549
11550 p = strchr(xxreadtoken_chars, c);
Denis Vlasenko834dee72008-10-07 09:18:30 +000011551 if (p == NULL)
11552 break; /* return readtoken1(...) */
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011553
Denis Vlasenko834dee72008-10-07 09:18:30 +000011554 if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
11555 int cc = pgetc();
11556 if (cc == c) { /* double occurrence? */
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011557 p += xxreadtoken_doubles + 1;
11558 } else {
11559 pungetc();
Denis Vlasenko834dee72008-10-07 09:18:30 +000011560#if ENABLE_ASH_BASH_COMPAT
11561 if (c == '&' && cc == '>') /* &> */
11562 break; /* return readtoken1(...) */
11563#endif
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011564 }
11565 }
11566 }
11567 lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
11568 return lasttoken;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011569 }
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011570 } /* for (;;) */
Denis Vlasenko834dee72008-10-07 09:18:30 +000011571
11572 return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011573}
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011574#else /* old xxreadtoken */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011575#define RETURN(token) return lasttoken = token
11576static int
11577xxreadtoken(void)
11578{
11579 int c;
11580
11581 if (tokpushback) {
11582 tokpushback = 0;
11583 return lasttoken;
11584 }
11585 if (needprompt) {
11586 setprompt(2);
11587 }
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011588 startlinno = g_parsefile->linno;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011589 for (;;) { /* until token or start of word found */
Denis Vlasenko834dee72008-10-07 09:18:30 +000011590 c = pgetc_fast();
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011591 switch (c) {
11592 case ' ': case '\t':
Denys Vlasenko2ce42e92009-11-29 02:18:13 +010011593 IF_ASH_ALIAS(case PEOA:)
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011594 continue;
11595 case '#':
Denis Vlasenkof7d56652008-03-25 05:51:41 +000011596 while ((c = pgetc()) != '\n' && c != PEOF)
11597 continue;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011598 pungetc();
11599 continue;
11600 case '\\':
11601 if (pgetc() == '\n') {
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011602 startlinno = ++g_parsefile->linno;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011603 if (doprompt)
11604 setprompt(2);
11605 continue;
11606 }
11607 pungetc();
11608 goto breakloop;
11609 case '\n':
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011610 g_parsefile->linno++;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011611 needprompt = doprompt;
11612 RETURN(TNL);
11613 case PEOF:
11614 RETURN(TEOF);
11615 case '&':
11616 if (pgetc() == '&')
11617 RETURN(TAND);
11618 pungetc();
11619 RETURN(TBACKGND);
11620 case '|':
11621 if (pgetc() == '|')
11622 RETURN(TOR);
11623 pungetc();
11624 RETURN(TPIPE);
11625 case ';':
11626 if (pgetc() == ';')
11627 RETURN(TENDCASE);
11628 pungetc();
11629 RETURN(TSEMI);
11630 case '(':
11631 RETURN(TLP);
11632 case ')':
11633 RETURN(TRP);
11634 default:
11635 goto breakloop;
11636 }
11637 }
11638 breakloop:
11639 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
11640#undef RETURN
11641}
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011642#endif /* old xxreadtoken */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011643
11644static int
11645readtoken(void)
11646{
11647 int t;
11648#if DEBUG
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011649 smallint alreadyseen = tokpushback;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011650#endif
11651
11652#if ENABLE_ASH_ALIAS
11653 top:
11654#endif
11655
11656 t = xxreadtoken();
11657
11658 /*
11659 * eat newlines
11660 */
11661 if (checkkwd & CHKNL) {
11662 while (t == TNL) {
11663 parseheredoc();
11664 t = xxreadtoken();
11665 }
11666 }
11667
11668 if (t != TWORD || quoteflag) {
11669 goto out;
11670 }
11671
11672 /*
11673 * check for keywords
11674 */
11675 if (checkkwd & CHKKWD) {
11676 const char *const *pp;
11677
11678 pp = findkwd(wordtext);
11679 if (pp) {
11680 lasttoken = t = pp - tokname_array;
11681 TRACE(("keyword %s recognized\n", tokname(t)));
11682 goto out;
11683 }
11684 }
11685
11686 if (checkkwd & CHKALIAS) {
11687#if ENABLE_ASH_ALIAS
11688 struct alias *ap;
11689 ap = lookupalias(wordtext, 1);
11690 if (ap != NULL) {
11691 if (*ap->val) {
11692 pushstring(ap->val, ap);
11693 }
11694 goto top;
11695 }
11696#endif
11697 }
11698 out:
11699 checkkwd = 0;
11700#if DEBUG
11701 if (!alreadyseen)
11702 TRACE(("token %s %s\n", tokname(t), t == TWORD ? wordtext : ""));
11703 else
11704 TRACE(("reread token %s %s\n", tokname(t), t == TWORD ? wordtext : ""));
11705#endif
11706 return t;
Eric Andersencb57d552001-06-28 07:25:16 +000011707}
11708
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011709static char
11710peektoken(void)
11711{
11712 int t;
11713
11714 t = readtoken();
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011715 tokpushback = 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011716 return tokname_array[t][0];
11717}
Eric Andersencb57d552001-06-28 07:25:16 +000011718
11719/*
Denys Vlasenko86e83ec2009-07-23 22:07:07 +020011720 * Read and parse a command. Returns NODE_EOF on end of file.
11721 * (NULL is a valid parse tree indicating a blank line.)
Eric Andersencb57d552001-06-28 07:25:16 +000011722 */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011723static union node *
11724parsecmd(int interact)
Eric Andersen90898442003-08-06 11:20:52 +000011725{
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011726 int t;
Eric Andersencb57d552001-06-28 07:25:16 +000011727
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011728 tokpushback = 0;
11729 doprompt = interact;
11730 if (doprompt)
11731 setprompt(doprompt);
11732 needprompt = 0;
11733 t = readtoken();
11734 if (t == TEOF)
Denys Vlasenko86e83ec2009-07-23 22:07:07 +020011735 return NODE_EOF;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011736 if (t == TNL)
11737 return NULL;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011738 tokpushback = 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011739 return list(1);
11740}
11741
11742/*
11743 * Input any here documents.
11744 */
11745static void
11746parseheredoc(void)
11747{
11748 struct heredoc *here;
11749 union node *n;
11750
11751 here = heredoclist;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000011752 heredoclist = NULL;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011753
11754 while (here) {
11755 if (needprompt) {
11756 setprompt(2);
11757 }
11758 readtoken1(pgetc(), here->here->type == NHERE? SQSYNTAX : DQSYNTAX,
11759 here->eofmark, here->striptabs);
Denis Vlasenko597906c2008-02-20 16:38:54 +000011760 n = stzalloc(sizeof(struct narg));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011761 n->narg.type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000011762 /*n->narg.next = NULL; - stzalloc did it */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011763 n->narg.text = wordtext;
11764 n->narg.backquote = backquotelist;
11765 here->here->nhere.doc = n;
11766 here = here->next;
Eric Andersencb57d552001-06-28 07:25:16 +000011767 }
Eric Andersencb57d552001-06-28 07:25:16 +000011768}
11769
11770
11771/*
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +000011772 * called by editline -- any expansions to the prompt should be added here.
Eric Andersencb57d552001-06-28 07:25:16 +000011773 */
Denis Vlasenko131ae172007-02-18 13:00:19 +000011774#if ENABLE_ASH_EXPAND_PRMT
"Vladimir N. Oleynik"bef14d72005-09-05 13:25:11 +000011775static const char *
11776expandstr(const char *ps)
11777{
11778 union node n;
11779
Denis Vlasenko5c2b8142009-03-19 01:59:59 +000011780 /* XXX Fix (char *) cast. It _is_ a bug. ps is variable's value,
11781 * and token processing _can_ alter it (delete NULs etc). */
"Vladimir N. Oleynik"bef14d72005-09-05 13:25:11 +000011782 setinputstring((char *)ps);
Denis Vlasenko46a53062007-09-24 18:30:02 +000011783 readtoken1(pgetc(), PSSYNTAX, nullstr, 0);
"Vladimir N. Oleynik"bef14d72005-09-05 13:25:11 +000011784 popfile();
11785
11786 n.narg.type = NARG;
11787 n.narg.next = NULL;
11788 n.narg.text = wordtext;
11789 n.narg.backquote = backquotelist;
11790
11791 expandarg(&n, NULL, 0);
11792 return stackblock();
11793}
11794#endif
11795
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011796/*
11797 * Execute a command or commands contained in a string.
11798 */
11799static int
11800evalstring(char *s, int mask)
Eric Andersenc470f442003-07-28 09:56:35 +000011801{
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011802 union node *n;
11803 struct stackmark smark;
11804 int skip;
11805
11806 setinputstring(s);
11807 setstackmark(&smark);
11808
11809 skip = 0;
Denys Vlasenko86e83ec2009-07-23 22:07:07 +020011810 while ((n = parsecmd(0)) != NODE_EOF) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011811 evaltree(n, 0);
11812 popstackmark(&smark);
11813 skip = evalskip;
11814 if (skip)
11815 break;
11816 }
11817 popfile();
11818
11819 skip &= mask;
11820 evalskip = skip;
11821 return skip;
Eric Andersenc470f442003-07-28 09:56:35 +000011822}
11823
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011824/*
11825 * The eval command.
11826 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011827static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000011828evalcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011829{
11830 char *p;
11831 char *concat;
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011832
Denis Vlasenko68404f12008-03-17 09:00:54 +000011833 if (argv[1]) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011834 p = argv[1];
Denis Vlasenko68404f12008-03-17 09:00:54 +000011835 argv += 2;
11836 if (argv[0]) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011837 STARTSTACKSTR(concat);
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011838 for (;;) {
11839 concat = stack_putstr(p, concat);
Denis Vlasenko68404f12008-03-17 09:00:54 +000011840 p = *argv++;
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011841 if (p == NULL)
11842 break;
11843 STPUTC(' ', concat);
11844 }
11845 STPUTC('\0', concat);
11846 p = grabstackstr(concat);
11847 }
11848 evalstring(p, ~SKIPEVAL);
11849
11850 }
11851 return exitstatus;
11852}
11853
11854/*
Denys Vlasenko285ad152009-12-04 23:02:27 +010011855 * Read and execute commands.
11856 * "Top" is nonzero for the top level command loop;
11857 * it turns on prompting if the shell is interactive.
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011858 */
11859static int
11860cmdloop(int top)
11861{
11862 union node *n;
11863 struct stackmark smark;
11864 int inter;
11865 int numeof = 0;
11866
11867 TRACE(("cmdloop(%d) called\n", top));
11868 for (;;) {
11869 int skip;
11870
11871 setstackmark(&smark);
11872#if JOBS
Denis Vlasenkob07a4962008-06-22 13:16:23 +000011873 if (doing_jobctl)
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011874 showjobs(stderr, SHOW_CHANGED);
11875#endif
11876 inter = 0;
11877 if (iflag && top) {
11878 inter++;
11879#if ENABLE_ASH_MAIL
11880 chkmail();
11881#endif
11882 }
11883 n = parsecmd(inter);
Denys Vlasenko7cee00e2009-07-24 01:08:03 +020011884#if DEBUG
11885 if (DEBUG > 2 && debug && (n != NODE_EOF))
Denys Vlasenko883cea42009-07-11 15:31:59 +020011886 showtree(n);
Denis Vlasenko135cecb2009-04-12 00:00:57 +000011887#endif
Denys Vlasenko86e83ec2009-07-23 22:07:07 +020011888 if (n == NODE_EOF) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011889 if (!top || numeof >= 50)
11890 break;
11891 if (!stoppedjobs()) {
11892 if (!Iflag)
11893 break;
11894 out2str("\nUse \"exit\" to leave shell.\n");
11895 }
11896 numeof++;
11897 } else if (nflag == 0) {
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +000011898 /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
11899 job_warning >>= 1;
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011900 numeof = 0;
11901 evaltree(n, 0);
11902 }
11903 popstackmark(&smark);
11904 skip = evalskip;
11905
11906 if (skip) {
11907 evalskip = 0;
11908 return skip & SKIPEVAL;
11909 }
11910 }
11911 return 0;
11912}
11913
Denis Vlasenko0dec6de2007-02-23 21:10:47 +000011914/*
11915 * Take commands from a file. To be compatible we should do a path
11916 * search for the file, which is necessary to find sub-commands.
11917 */
11918static char *
11919find_dot_file(char *name)
11920{
11921 char *fullname;
11922 const char *path = pathval();
11923 struct stat statb;
11924
11925 /* don't try this for absolute or relative paths */
11926 if (strchr(name, '/'))
11927 return name;
11928
Denis Vlasenko8ad78e12009-02-15 12:40:30 +000011929 /* IIRC standards do not say whether . is to be searched.
11930 * And it is even smaller this way, making it unconditional for now:
11931 */
11932 if (1) { /* ENABLE_ASH_BASH_COMPAT */
11933 fullname = name;
11934 goto try_cur_dir;
11935 }
11936
Denys Vlasenko82a6fb32009-06-14 19:42:12 +020011937 while ((fullname = path_advance(&path, name)) != NULL) {
Denis Vlasenko8ad78e12009-02-15 12:40:30 +000011938 try_cur_dir:
Denis Vlasenko0dec6de2007-02-23 21:10:47 +000011939 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
11940 /*
11941 * Don't bother freeing here, since it will
11942 * be freed by the caller.
11943 */
11944 return fullname;
11945 }
Denys Vlasenko82a6fb32009-06-14 19:42:12 +020011946 if (fullname != name)
11947 stunalloc(fullname);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +000011948 }
11949
11950 /* not found in the PATH */
11951 ash_msg_and_raise_error("%s: not found", name);
11952 /* NOTREACHED */
11953}
11954
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011955static int FAST_FUNC
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011956dotcmd(int argc, char **argv)
11957{
11958 struct strlist *sp;
11959 volatile struct shparam saveparam;
11960 int status = 0;
11961
11962 for (sp = cmdenviron; sp; sp = sp->next)
Denis Vlasenko4222ae42007-02-25 02:37:49 +000011963 setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011964
Denis Vlasenko68404f12008-03-17 09:00:54 +000011965 if (argv[1]) { /* That's what SVR2 does */
11966 char *fullname = find_dot_file(argv[1]);
11967 argv += 2;
11968 argc -= 2;
11969 if (argc) { /* argc > 0, argv[0] != NULL */
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011970 saveparam = shellparam;
Denis Vlasenko01631112007-12-16 17:20:38 +000011971 shellparam.malloced = 0;
Denis Vlasenko68404f12008-03-17 09:00:54 +000011972 shellparam.nparam = argc;
11973 shellparam.p = argv;
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011974 };
11975
11976 setinputfile(fullname, INPUT_PUSH_FILE);
11977 commandname = fullname;
11978 cmdloop(0);
11979 popfile();
11980
Denis Vlasenko68404f12008-03-17 09:00:54 +000011981 if (argc) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011982 freeparam(&shellparam);
11983 shellparam = saveparam;
11984 };
11985 status = exitstatus;
11986 }
11987 return status;
11988}
11989
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011990static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000011991exitcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011992{
11993 if (stoppedjobs())
11994 return 0;
Denis Vlasenko68404f12008-03-17 09:00:54 +000011995 if (argv[1])
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011996 exitstatus = number(argv[1]);
11997 raise_exception(EXEXIT);
11998 /* NOTREACHED */
11999}
12000
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012001/*
12002 * Read a file containing shell functions.
12003 */
12004static void
12005readcmdfile(char *name)
12006{
12007 setinputfile(name, INPUT_PUSH_FILE);
12008 cmdloop(0);
12009 popfile();
12010}
12011
12012
Denis Vlasenkocc571512007-02-23 21:10:35 +000012013/* ============ find_command inplementation */
12014
12015/*
12016 * Resolve a command name. If you change this routine, you may have to
12017 * change the shellexec routine as well.
12018 */
12019static void
12020find_command(char *name, struct cmdentry *entry, int act, const char *path)
12021{
12022 struct tblentry *cmdp;
12023 int idx;
12024 int prev;
12025 char *fullname;
12026 struct stat statb;
12027 int e;
12028 int updatetbl;
12029 struct builtincmd *bcmd;
12030
12031 /* If name contains a slash, don't use PATH or hash table */
12032 if (strchr(name, '/') != NULL) {
12033 entry->u.index = -1;
12034 if (act & DO_ABS) {
12035 while (stat(name, &statb) < 0) {
12036#ifdef SYSV
12037 if (errno == EINTR)
12038 continue;
12039#endif
12040 entry->cmdtype = CMDUNKNOWN;
12041 return;
12042 }
12043 }
12044 entry->cmdtype = CMDNORMAL;
12045 return;
12046 }
12047
Denis Vlasenkof20de5b2007-04-29 23:42:54 +000012048/* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
Denis Vlasenkocc571512007-02-23 21:10:35 +000012049
12050 updatetbl = (path == pathval());
12051 if (!updatetbl) {
12052 act |= DO_ALTPATH;
12053 if (strstr(path, "%builtin") != NULL)
12054 act |= DO_ALTBLTIN;
12055 }
12056
12057 /* If name is in the table, check answer will be ok */
12058 cmdp = cmdlookup(name, 0);
12059 if (cmdp != NULL) {
12060 int bit;
12061
12062 switch (cmdp->cmdtype) {
12063 default:
12064#if DEBUG
12065 abort();
12066#endif
12067 case CMDNORMAL:
12068 bit = DO_ALTPATH;
12069 break;
12070 case CMDFUNCTION:
12071 bit = DO_NOFUNC;
12072 break;
12073 case CMDBUILTIN:
12074 bit = DO_ALTBLTIN;
12075 break;
12076 }
12077 if (act & bit) {
12078 updatetbl = 0;
12079 cmdp = NULL;
12080 } else if (cmdp->rehash == 0)
12081 /* if not invalidated by cd, we're done */
12082 goto success;
12083 }
12084
12085 /* If %builtin not in path, check for builtin next */
12086 bcmd = find_builtin(name);
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +000012087 if (bcmd) {
12088 if (IS_BUILTIN_REGULAR(bcmd))
12089 goto builtin_success;
12090 if (act & DO_ALTPATH) {
12091 if (!(act & DO_ALTBLTIN))
12092 goto builtin_success;
12093 } else if (builtinloc <= 0) {
12094 goto builtin_success;
Denis Vlasenko8e858e22007-03-07 09:35:43 +000012095 }
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +000012096 }
Denis Vlasenkocc571512007-02-23 21:10:35 +000012097
Denis Vlasenkof20de5b2007-04-29 23:42:54 +000012098#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko7465dbc2008-04-13 02:25:53 +000012099 {
12100 int applet_no = find_applet_by_name(name);
12101 if (applet_no >= 0) {
12102 entry->cmdtype = CMDNORMAL;
12103 entry->u.index = -2 - applet_no;
12104 return;
12105 }
Denis Vlasenkof20de5b2007-04-29 23:42:54 +000012106 }
12107#endif
12108
Denis Vlasenkocc571512007-02-23 21:10:35 +000012109 /* We have to search path. */
12110 prev = -1; /* where to start */
12111 if (cmdp && cmdp->rehash) { /* doing a rehash */
12112 if (cmdp->cmdtype == CMDBUILTIN)
12113 prev = builtinloc;
12114 else
12115 prev = cmdp->param.index;
12116 }
12117
12118 e = ENOENT;
12119 idx = -1;
12120 loop:
Denys Vlasenko82a6fb32009-06-14 19:42:12 +020012121 while ((fullname = path_advance(&path, name)) != NULL) {
Denis Vlasenkocc571512007-02-23 21:10:35 +000012122 stunalloc(fullname);
Denis Vlasenkodee82b62007-07-29 14:05:27 +000012123 /* NB: code below will still use fullname
12124 * despite it being "unallocated" */
Denis Vlasenkocc571512007-02-23 21:10:35 +000012125 idx++;
12126 if (pathopt) {
12127 if (prefix(pathopt, "builtin")) {
12128 if (bcmd)
12129 goto builtin_success;
12130 continue;
Denis Vlasenko4a9ca132008-04-12 20:07:08 +000012131 }
12132 if ((act & DO_NOFUNC)
12133 || !prefix(pathopt, "func")
12134 ) { /* ignore unimplemented options */
Denis Vlasenkocc571512007-02-23 21:10:35 +000012135 continue;
12136 }
12137 }
12138 /* if rehash, don't redo absolute path names */
12139 if (fullname[0] == '/' && idx <= prev) {
12140 if (idx < prev)
12141 continue;
12142 TRACE(("searchexec \"%s\": no change\n", name));
12143 goto success;
12144 }
12145 while (stat(fullname, &statb) < 0) {
12146#ifdef SYSV
12147 if (errno == EINTR)
12148 continue;
12149#endif
12150 if (errno != ENOENT && errno != ENOTDIR)
12151 e = errno;
12152 goto loop;
12153 }
12154 e = EACCES; /* if we fail, this will be the error */
12155 if (!S_ISREG(statb.st_mode))
12156 continue;
12157 if (pathopt) { /* this is a %func directory */
12158 stalloc(strlen(fullname) + 1);
Denis Vlasenkodee82b62007-07-29 14:05:27 +000012159 /* NB: stalloc will return space pointed by fullname
12160 * (because we don't have any intervening allocations
12161 * between stunalloc above and this stalloc) */
Denis Vlasenkocc571512007-02-23 21:10:35 +000012162 readcmdfile(fullname);
12163 cmdp = cmdlookup(name, 0);
12164 if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
12165 ash_msg_and_raise_error("%s not defined in %s", name, fullname);
12166 stunalloc(fullname);
12167 goto success;
12168 }
12169 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
12170 if (!updatetbl) {
12171 entry->cmdtype = CMDNORMAL;
12172 entry->u.index = idx;
12173 return;
12174 }
12175 INT_OFF;
12176 cmdp = cmdlookup(name, 1);
12177 cmdp->cmdtype = CMDNORMAL;
12178 cmdp->param.index = idx;
12179 INT_ON;
12180 goto success;
12181 }
12182
12183 /* We failed. If there was an entry for this command, delete it */
12184 if (cmdp && updatetbl)
12185 delete_cmd_entry();
12186 if (act & DO_ERR)
12187 ash_msg("%s: %s", name, errmsg(e, "not found"));
12188 entry->cmdtype = CMDUNKNOWN;
12189 return;
12190
12191 builtin_success:
12192 if (!updatetbl) {
12193 entry->cmdtype = CMDBUILTIN;
12194 entry->u.cmd = bcmd;
12195 return;
12196 }
12197 INT_OFF;
12198 cmdp = cmdlookup(name, 1);
12199 cmdp->cmdtype = CMDBUILTIN;
12200 cmdp->param.cmd = bcmd;
12201 INT_ON;
12202 success:
12203 cmdp->rehash = 0;
12204 entry->cmdtype = cmdp->cmdtype;
12205 entry->u = cmdp->param;
12206}
12207
12208
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012209/* ============ trap.c */
Eric Andersenc470f442003-07-28 09:56:35 +000012210
Eric Andersencb57d552001-06-28 07:25:16 +000012211/*
Eric Andersencb57d552001-06-28 07:25:16 +000012212 * The trap builtin.
12213 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012214static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012215trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersencb57d552001-06-28 07:25:16 +000012216{
12217 char *action;
12218 char **ap;
12219 int signo;
12220
Eric Andersenc470f442003-07-28 09:56:35 +000012221 nextopt(nullstr);
12222 ap = argptr;
12223 if (!*ap) {
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012224 for (signo = 0; signo < NSIG; signo++) {
Denys Vlasenko21d87d42009-09-25 00:06:51 +020012225 char *tr = trap_ptr[signo];
12226 if (tr) {
Denys Vlasenkoe74aaf92009-09-27 02:05:45 +020012227 /* note: bash adds "SIG", but only if invoked
12228 * as "bash". If called as "sh", or if set -o posix,
12229 * then it prints short signal names.
12230 * We are printing short names: */
12231 out1fmt("trap -- %s %s\n",
Denys Vlasenko21d87d42009-09-25 00:06:51 +020012232 single_quote(tr),
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +000012233 get_signame(signo));
Denys Vlasenko726e1a02009-09-25 02:58:20 +020012234 /* trap_ptr != trap only if we are in special-cased `trap` code.
12235 * In this case, we will exit very soon, no need to free(). */
Denys Vlasenkoe74aaf92009-09-27 02:05:45 +020012236 /* if (trap_ptr != trap && tp[0]) */
Denys Vlasenko726e1a02009-09-25 02:58:20 +020012237 /* free(tr); */
Eric Andersencb57d552001-06-28 07:25:16 +000012238 }
12239 }
Denys Vlasenko726e1a02009-09-25 02:58:20 +020012240 /*
Denys Vlasenko21d87d42009-09-25 00:06:51 +020012241 if (trap_ptr != trap) {
12242 free(trap_ptr);
12243 trap_ptr = trap;
12244 }
Denys Vlasenko726e1a02009-09-25 02:58:20 +020012245 */
Eric Andersencb57d552001-06-28 07:25:16 +000012246 return 0;
12247 }
Denys Vlasenko21d87d42009-09-25 00:06:51 +020012248
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +000012249 action = NULL;
12250 if (ap[1])
Eric Andersencb57d552001-06-28 07:25:16 +000012251 action = *ap++;
12252 while (*ap) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +000012253 signo = get_signum(*ap);
12254 if (signo < 0)
Denis Vlasenkob012b102007-02-19 22:43:01 +000012255 ash_msg_and_raise_error("%s: bad trap", *ap);
12256 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +000012257 if (action) {
Denis Vlasenko9f739442006-12-16 23:49:13 +000012258 if (LONE_DASH(action))
Eric Andersencb57d552001-06-28 07:25:16 +000012259 action = NULL;
12260 else
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012261 action = ckstrdup(action);
Eric Andersencb57d552001-06-28 07:25:16 +000012262 }
Denis Vlasenko60818682007-09-28 22:07:23 +000012263 free(trap[signo]);
Eric Andersencb57d552001-06-28 07:25:16 +000012264 trap[signo] = action;
12265 if (signo != 0)
12266 setsignal(signo);
Denis Vlasenkob012b102007-02-19 22:43:01 +000012267 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +000012268 ap++;
12269 }
12270 return 0;
12271}
12272
Eric Andersenc470f442003-07-28 09:56:35 +000012273
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012274/* ============ Builtins */
Eric Andersenc470f442003-07-28 09:56:35 +000012275
Denis Vlasenko8e1c7152007-01-22 07:21:38 +000012276#if !ENABLE_FEATURE_SH_EXTRA_QUIET
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012277/*
12278 * Lists available builtins
12279 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012280static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012281helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersenc470f442003-07-28 09:56:35 +000012282{
Denis Vlasenko6b06cb82008-05-15 21:30:45 +000012283 unsigned col;
12284 unsigned i;
Eric Andersenc470f442003-07-28 09:56:35 +000012285
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +020012286 out1fmt(
Denis Vlasenko34d4d892009-04-04 20:24:37 +000012287 "Built-in commands:\n"
12288 "------------------\n");
Denis Vlasenkob71c6682007-07-21 15:08:09 +000012289 for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
Eric Andersenc470f442003-07-28 09:56:35 +000012290 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
Denis Vlasenko52764022007-02-24 13:42:56 +000012291 builtintab[i].name + 1);
Eric Andersenc470f442003-07-28 09:56:35 +000012292 if (col > 60) {
12293 out1fmt("\n");
12294 col = 0;
12295 }
12296 }
Denis Vlasenko80d14be2007-04-10 23:03:30 +000012297#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko1aa7e472007-11-28 06:49:03 +000012298 {
12299 const char *a = applet_names;
12300 while (*a) {
12301 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
12302 if (col > 60) {
12303 out1fmt("\n");
12304 col = 0;
12305 }
12306 a += strlen(a) + 1;
Eric Andersenc470f442003-07-28 09:56:35 +000012307 }
12308 }
12309#endif
12310 out1fmt("\n\n");
12311 return EXIT_SUCCESS;
12312}
Denis Vlasenko131ae172007-02-18 13:00:19 +000012313#endif /* FEATURE_SH_EXTRA_QUIET */
Eric Andersenc470f442003-07-28 09:56:35 +000012314
Eric Andersencb57d552001-06-28 07:25:16 +000012315/*
Eric Andersencb57d552001-06-28 07:25:16 +000012316 * The export and readonly commands.
12317 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012318static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012319exportcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +000012320{
12321 struct var *vp;
12322 char *name;
12323 const char *p;
Eric Andersenc470f442003-07-28 09:56:35 +000012324 char **aptr;
Denis Vlasenkob7304742008-10-20 08:15:51 +000012325 int flag = argv[0][0] == 'r' ? VREADONLY : VEXPORT;
Eric Andersencb57d552001-06-28 07:25:16 +000012326
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012327 if (nextopt("p") != 'p') {
12328 aptr = argptr;
12329 name = *aptr;
12330 if (name) {
12331 do {
12332 p = strchr(name, '=');
12333 if (p != NULL) {
12334 p++;
12335 } else {
12336 vp = *findvar(hashvar(name), name);
12337 if (vp) {
12338 vp->flags |= flag;
12339 continue;
12340 }
Eric Andersencb57d552001-06-28 07:25:16 +000012341 }
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012342 setvar(name, p, flag);
12343 } while ((name = *++aptr) != NULL);
12344 return 0;
12345 }
Eric Andersencb57d552001-06-28 07:25:16 +000012346 }
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012347 showvars(argv[0], flag, 0);
Eric Andersencb57d552001-06-28 07:25:16 +000012348 return 0;
12349}
12350
Eric Andersencb57d552001-06-28 07:25:16 +000012351/*
Denis Vlasenko5651bfc2007-02-23 21:08:58 +000012352 * Delete a function if it exists.
Eric Andersencb57d552001-06-28 07:25:16 +000012353 */
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012354static void
Denis Vlasenko5651bfc2007-02-23 21:08:58 +000012355unsetfunc(const char *name)
Aaron Lehmannb6ecbdc2001-12-06 03:37:38 +000012356{
Denis Vlasenko5651bfc2007-02-23 21:08:58 +000012357 struct tblentry *cmdp;
Eric Andersencb57d552001-06-28 07:25:16 +000012358
Denis Vlasenko5651bfc2007-02-23 21:08:58 +000012359 cmdp = cmdlookup(name, 0);
12360 if (cmdp!= NULL && cmdp->cmdtype == CMDFUNCTION)
12361 delete_cmd_entry();
Eric Andersenc470f442003-07-28 09:56:35 +000012362}
12363
Eric Andersencb57d552001-06-28 07:25:16 +000012364/*
Eric Andersencb57d552001-06-28 07:25:16 +000012365 * The unset builtin command. We unset the function before we unset the
12366 * variable to allow a function to be unset when there is a readonly variable
12367 * with the same name.
12368 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012369static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012370unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersencb57d552001-06-28 07:25:16 +000012371{
12372 char **ap;
12373 int i;
Eric Andersenc470f442003-07-28 09:56:35 +000012374 int flag = 0;
Eric Andersencb57d552001-06-28 07:25:16 +000012375 int ret = 0;
12376
12377 while ((i = nextopt("vf")) != '\0') {
Eric Andersenc470f442003-07-28 09:56:35 +000012378 flag = i;
Eric Andersencb57d552001-06-28 07:25:16 +000012379 }
Eric Andersencb57d552001-06-28 07:25:16 +000012380
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012381 for (ap = argptr; *ap; ap++) {
Eric Andersenc470f442003-07-28 09:56:35 +000012382 if (flag != 'f') {
12383 i = unsetvar(*ap);
12384 ret |= i;
12385 if (!(i & 2))
12386 continue;
12387 }
12388 if (flag != 'v')
Eric Andersencb57d552001-06-28 07:25:16 +000012389 unsetfunc(*ap);
Eric Andersencb57d552001-06-28 07:25:16 +000012390 }
Eric Andersenc470f442003-07-28 09:56:35 +000012391 return ret & 1;
Eric Andersencb57d552001-06-28 07:25:16 +000012392}
12393
12394
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +000012395/* setmode.c */
Eric Andersencb57d552001-06-28 07:25:16 +000012396
Eric Andersenc470f442003-07-28 09:56:35 +000012397#include <sys/times.h>
12398
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000012399static const unsigned char timescmd_str[] ALIGN1 = {
Manuel Novoa III 4456f252003-08-13 17:48:47 +000012400 ' ', offsetof(struct tms, tms_utime),
12401 '\n', offsetof(struct tms, tms_stime),
12402 ' ', offsetof(struct tms, tms_cutime),
12403 '\n', offsetof(struct tms, tms_cstime),
12404 0
12405};
Eric Andersencb57d552001-06-28 07:25:16 +000012406
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012407static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012408timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Manuel Novoa III 4456f252003-08-13 17:48:47 +000012409{
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012410 long clk_tck, s, t;
Manuel Novoa III 4456f252003-08-13 17:48:47 +000012411 const unsigned char *p;
12412 struct tms buf;
12413
12414 clk_tck = sysconf(_SC_CLK_TCK);
Eric Andersencb57d552001-06-28 07:25:16 +000012415 times(&buf);
Manuel Novoa III 4456f252003-08-13 17:48:47 +000012416
12417 p = timescmd_str;
12418 do {
12419 t = *(clock_t *)(((char *) &buf) + p[1]);
12420 s = t / clk_tck;
12421 out1fmt("%ldm%ld.%.3lds%c",
12422 s/60, s%60,
12423 ((t - s * clk_tck) * 1000) / clk_tck,
12424 p[0]);
12425 } while (*(p += 2));
12426
Eric Andersencb57d552001-06-28 07:25:16 +000012427 return 0;
12428}
12429
Mike Frysinger98c52642009-04-02 10:02:37 +000012430#if ENABLE_SH_MATH_SUPPORT
Eric Andersenc470f442003-07-28 09:56:35 +000012431/*
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +000012432 * The let builtin. partial stolen from GNU Bash, the Bourne Again SHell.
12433 * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
Eric Andersen90898442003-08-06 11:20:52 +000012434 *
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +000012435 * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
Eric Andersenc470f442003-07-28 09:56:35 +000012436 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012437static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012438letcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersenc470f442003-07-28 09:56:35 +000012439{
Denis Vlasenko68404f12008-03-17 09:00:54 +000012440 arith_t i;
Eric Andersenc470f442003-07-28 09:56:35 +000012441
Denis Vlasenko68404f12008-03-17 09:00:54 +000012442 argv++;
12443 if (!*argv)
Denis Vlasenkob012b102007-02-19 22:43:01 +000012444 ash_msg_and_raise_error("expression expected");
Denis Vlasenko68404f12008-03-17 09:00:54 +000012445 do {
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +000012446 i = ash_arith(*argv);
Denis Vlasenko68404f12008-03-17 09:00:54 +000012447 } while (*++argv);
Eric Andersenc470f442003-07-28 09:56:35 +000012448
Denis Vlasenkod9e15f22006-11-27 16:49:55 +000012449 return !i;
Eric Andersenc470f442003-07-28 09:56:35 +000012450}
Mike Frysinger98c52642009-04-02 10:02:37 +000012451#endif /* SH_MATH_SUPPORT */
Eric Andersenc470f442003-07-28 09:56:35 +000012452
Eric Andersenc470f442003-07-28 09:56:35 +000012453
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012454/* ============ miscbltin.c
12455 *
Eric Andersenaff114c2004-04-14 17:51:38 +000012456 * Miscellaneous builtins.
Eric Andersenc470f442003-07-28 09:56:35 +000012457 */
12458
12459#undef rflag
12460
Denis Vlasenko83e5d6f2006-12-18 21:49:06 +000012461#if defined(__GLIBC__) && __GLIBC__ == 2 && __GLIBC_MINOR__ < 1
Eric Andersenc470f442003-07-28 09:56:35 +000012462typedef enum __rlimit_resource rlim_t;
12463#endif
Eric Andersen74bcd162001-07-30 21:41:37 +000012464
Eric Andersenc470f442003-07-28 09:56:35 +000012465/*
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012466 * The read builtin. Options:
12467 * -r Do not interpret '\' specially
12468 * -s Turn off echo (tty only)
12469 * -n NCHARS Read NCHARS max
12470 * -p PROMPT Display PROMPT on stderr (if input is from tty)
12471 * -t SECONDS Timeout after SECONDS (tty or pipe only)
12472 * -u FD Read from given FD instead of fd 0
Eric Andersenc470f442003-07-28 09:56:35 +000012473 * This uses unbuffered input, which may be avoidable in some cases.
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012474 * TODO: bash also has:
12475 * -a ARRAY Read into array[0],[1],etc
12476 * -d DELIM End on DELIM char, not newline
12477 * -e Use line editing (tty only)
Eric Andersenc470f442003-07-28 09:56:35 +000012478 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012479static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012480readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersenc470f442003-07-28 09:56:35 +000012481{
Denis Vlasenko9cd4c762008-06-18 19:22:19 +000012482 static const char *const arg_REPLY[] = { "REPLY", NULL };
12483
Eric Andersenc470f442003-07-28 09:56:35 +000012484 char **ap;
12485 int backslash;
12486 char c;
12487 int rflag;
12488 char *prompt;
12489 const char *ifs;
12490 char *p;
12491 int startword;
12492 int status;
12493 int i;
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012494 int fd = 0;
Denis Vlasenko131ae172007-02-18 13:00:19 +000012495#if ENABLE_ASH_READ_NCHARS
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012496 int nchars = 0; /* if != 0, -n is in effect */
Paul Fox02eb9342005-09-07 16:56:02 +000012497 int silent = 0;
12498 struct termios tty, old_tty;
12499#endif
Denis Vlasenko131ae172007-02-18 13:00:19 +000012500#if ENABLE_ASH_READ_TIMEOUT
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012501 unsigned end_ms = 0;
12502 unsigned timeout = 0;
Paul Fox02eb9342005-09-07 16:56:02 +000012503#endif
Eric Andersenc470f442003-07-28 09:56:35 +000012504
12505 rflag = 0;
12506 prompt = NULL;
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012507 while ((i = nextopt("p:u:r"
Denis Vlasenko5e34ff22009-04-21 11:09:40 +000012508 IF_ASH_READ_TIMEOUT("t:")
12509 IF_ASH_READ_NCHARS("n:s")
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012510 )) != '\0') {
Denis Vlasenkobf0a2012006-12-26 10:42:51 +000012511 switch (i) {
Paul Fox02eb9342005-09-07 16:56:02 +000012512 case 'p':
Eric Andersenc470f442003-07-28 09:56:35 +000012513 prompt = optionarg;
Paul Fox02eb9342005-09-07 16:56:02 +000012514 break;
Denis Vlasenko131ae172007-02-18 13:00:19 +000012515#if ENABLE_ASH_READ_NCHARS
Paul Fox02eb9342005-09-07 16:56:02 +000012516 case 'n':
Denis Vlasenko037576d2007-10-20 18:30:38 +000012517 nchars = bb_strtou(optionarg, NULL, 10);
12518 if (nchars < 0 || errno)
Denis Vlasenkob012b102007-02-19 22:43:01 +000012519 ash_msg_and_raise_error("invalid count");
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012520 /* nchars == 0: off (bash 3.2 does this too) */
Paul Fox02eb9342005-09-07 16:56:02 +000012521 break;
12522 case 's':
12523 silent = 1;
12524 break;
Ned Ludd2123b7c2005-02-09 21:07:23 +000012525#endif
Denis Vlasenko131ae172007-02-18 13:00:19 +000012526#if ENABLE_ASH_READ_TIMEOUT
Paul Fox02eb9342005-09-07 16:56:02 +000012527 case 't':
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012528 timeout = bb_strtou(optionarg, NULL, 10);
12529 if (errno || timeout > UINT_MAX / 2048)
12530 ash_msg_and_raise_error("invalid timeout");
12531 timeout *= 1000;
12532#if 0 /* even bash have no -t N.NNN support */
Denis Vlasenko037576d2007-10-20 18:30:38 +000012533 ts.tv_sec = bb_strtou(optionarg, &p, 10);
Paul Fox02eb9342005-09-07 16:56:02 +000012534 ts.tv_usec = 0;
Denis Vlasenko037576d2007-10-20 18:30:38 +000012535 /* EINVAL means number is ok, but not terminated by NUL */
12536 if (*p == '.' && errno == EINVAL) {
Paul Fox02eb9342005-09-07 16:56:02 +000012537 char *p2;
12538 if (*++p) {
12539 int scale;
Denis Vlasenko037576d2007-10-20 18:30:38 +000012540 ts.tv_usec = bb_strtou(p, &p2, 10);
12541 if (errno)
Denis Vlasenkob012b102007-02-19 22:43:01 +000012542 ash_msg_and_raise_error("invalid timeout");
Paul Fox02eb9342005-09-07 16:56:02 +000012543 scale = p2 - p;
12544 /* normalize to usec */
12545 if (scale > 6)
Denis Vlasenkob012b102007-02-19 22:43:01 +000012546 ash_msg_and_raise_error("invalid timeout");
Paul Fox02eb9342005-09-07 16:56:02 +000012547 while (scale++ < 6)
12548 ts.tv_usec *= 10;
12549 }
Denis Vlasenko037576d2007-10-20 18:30:38 +000012550 } else if (ts.tv_sec < 0 || errno) {
Denis Vlasenkob012b102007-02-19 22:43:01 +000012551 ash_msg_and_raise_error("invalid timeout");
Paul Fox02eb9342005-09-07 16:56:02 +000012552 }
Denis Vlasenko037576d2007-10-20 18:30:38 +000012553 if (!(ts.tv_sec | ts.tv_usec)) { /* both are 0? */
Denis Vlasenkob012b102007-02-19 22:43:01 +000012554 ash_msg_and_raise_error("invalid timeout");
Denis Vlasenko037576d2007-10-20 18:30:38 +000012555 }
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012556#endif /* if 0 */
Paul Fox02eb9342005-09-07 16:56:02 +000012557 break;
12558#endif
12559 case 'r':
12560 rflag = 1;
12561 break;
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012562 case 'u':
12563 fd = bb_strtou(optionarg, NULL, 10);
12564 if (fd < 0 || errno)
12565 ash_msg_and_raise_error("invalid file descriptor");
12566 break;
Paul Fox02eb9342005-09-07 16:56:02 +000012567 default:
12568 break;
12569 }
Eric Andersenc470f442003-07-28 09:56:35 +000012570 }
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012571 if (prompt && isatty(fd)) {
Eric Andersenc470f442003-07-28 09:56:35 +000012572 out2str(prompt);
Eric Andersenc470f442003-07-28 09:56:35 +000012573 }
Denis Vlasenko5cedb752007-02-18 19:56:41 +000012574 ap = argptr;
12575 if (*ap == NULL)
Denis Vlasenko9cd4c762008-06-18 19:22:19 +000012576 ap = (char**)arg_REPLY;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000012577 ifs = bltinlookup("IFS");
12578 if (ifs == NULL)
Eric Andersenc470f442003-07-28 09:56:35 +000012579 ifs = defifs;
Denis Vlasenko131ae172007-02-18 13:00:19 +000012580#if ENABLE_ASH_READ_NCHARS
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012581 tcgetattr(fd, &tty);
12582 old_tty = tty;
12583 if (nchars || silent) {
12584 if (nchars) {
12585 tty.c_lflag &= ~ICANON;
12586 tty.c_cc[VMIN] = nchars < 256 ? nchars : 255;
Paul Fox02eb9342005-09-07 16:56:02 +000012587 }
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012588 if (silent) {
12589 tty.c_lflag &= ~(ECHO | ECHOK | ECHONL);
12590 }
12591 /* if tcgetattr failed, tcsetattr will fail too.
12592 * Ignoring, it's harmless. */
12593 tcsetattr(fd, TCSANOW, &tty);
Paul Fox02eb9342005-09-07 16:56:02 +000012594 }
12595#endif
Paul Fox02eb9342005-09-07 16:56:02 +000012596
Eric Andersenc470f442003-07-28 09:56:35 +000012597 status = 0;
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012598 startword = 2;
Eric Andersenc470f442003-07-28 09:56:35 +000012599 backslash = 0;
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012600#if ENABLE_ASH_READ_TIMEOUT
12601 if (timeout) /* NB: ensuring end_ms is nonzero */
12602 end_ms = ((unsigned)(monotonic_us() / 1000) + timeout) | 1;
12603#endif
Eric Andersenc470f442003-07-28 09:56:35 +000012604 STARTSTACKSTR(p);
Denis Vlasenko037576d2007-10-20 18:30:38 +000012605 do {
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012606 const char *is_ifs;
12607
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012608#if ENABLE_ASH_READ_TIMEOUT
12609 if (end_ms) {
12610 struct pollfd pfd[1];
12611 pfd[0].fd = fd;
12612 pfd[0].events = POLLIN;
12613 timeout = end_ms - (unsigned)(monotonic_us() / 1000);
12614 if ((int)timeout <= 0 /* already late? */
12615 || safe_poll(pfd, 1, timeout) != 1 /* no? wait... */
12616 ) { /* timed out! */
12617#if ENABLE_ASH_READ_NCHARS
12618 tcsetattr(fd, TCSANOW, &old_tty);
12619#endif
12620 return 1;
12621 }
12622 }
12623#endif
12624 if (nonblock_safe_read(fd, &c, 1) != 1) {
Eric Andersenc470f442003-07-28 09:56:35 +000012625 status = 1;
12626 break;
12627 }
12628 if (c == '\0')
12629 continue;
12630 if (backslash) {
12631 backslash = 0;
12632 if (c != '\n')
12633 goto put;
12634 continue;
12635 }
12636 if (!rflag && c == '\\') {
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012637 backslash = 1;
Eric Andersenc470f442003-07-28 09:56:35 +000012638 continue;
12639 }
12640 if (c == '\n')
12641 break;
Denis Vlasenkof6fbd622009-03-31 19:36:58 +000012642 /* $IFS splitting */
Denis Vlasenko551ffdc2009-04-01 19:48:05 +000012643/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_05 */
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012644 is_ifs = strchr(ifs, c);
12645 if (startword && is_ifs) {
12646 if (isspace(c))
12647 continue;
Denis Vlasenkof6fbd622009-03-31 19:36:58 +000012648 /* it is a non-space ifs char */
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012649 startword--;
12650 if (startword == 1) /* first one? */
Denis Vlasenkof6fbd622009-03-31 19:36:58 +000012651 continue; /* yes, it is not next word yet */
Eric Andersenc470f442003-07-28 09:56:35 +000012652 }
12653 startword = 0;
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012654 if (ap[1] != NULL && is_ifs) {
12655 const char *beg;
Eric Andersenc470f442003-07-28 09:56:35 +000012656 STACKSTRNUL(p);
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012657 beg = stackblock();
12658 setvar(*ap, beg, 0);
Eric Andersenc470f442003-07-28 09:56:35 +000012659 ap++;
Denis Vlasenkof6fbd622009-03-31 19:36:58 +000012660 /* can we skip one non-space ifs char? (2: yes) */
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012661 startword = isspace(c) ? 2 : 1;
Eric Andersenc470f442003-07-28 09:56:35 +000012662 STARTSTACKSTR(p);
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012663 continue;
Eric Andersenc470f442003-07-28 09:56:35 +000012664 }
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012665 put:
12666 STPUTC(c, p);
Eric Andersenc470f442003-07-28 09:56:35 +000012667 }
Denis Vlasenko037576d2007-10-20 18:30:38 +000012668/* end of do {} while: */
Denis Vlasenko131ae172007-02-18 13:00:19 +000012669#if ENABLE_ASH_READ_NCHARS
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012670 while (--nchars);
Denis Vlasenko037576d2007-10-20 18:30:38 +000012671#else
12672 while (1);
12673#endif
12674
12675#if ENABLE_ASH_READ_NCHARS
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012676 tcsetattr(fd, TCSANOW, &old_tty);
Paul Fox02eb9342005-09-07 16:56:02 +000012677#endif
12678
Eric Andersenc470f442003-07-28 09:56:35 +000012679 STACKSTRNUL(p);
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012680 /* Remove trailing space ifs chars */
12681 while ((char *)stackblock() <= --p && isspace(*p) && strchr(ifs, *p) != NULL)
Eric Andersenc470f442003-07-28 09:56:35 +000012682 *p = '\0';
12683 setvar(*ap, stackblock(), 0);
12684 while (*++ap != NULL)
12685 setvar(*ap, nullstr, 0);
12686 return status;
12687}
12688
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012689static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012690umaskcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersenc470f442003-07-28 09:56:35 +000012691{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000012692 static const char permuser[3] ALIGN1 = "ugo";
12693 static const char permmode[3] ALIGN1 = "rwx";
12694 static const short permmask[] ALIGN2 = {
Eric Andersenc470f442003-07-28 09:56:35 +000012695 S_IRUSR, S_IWUSR, S_IXUSR,
12696 S_IRGRP, S_IWGRP, S_IXGRP,
12697 S_IROTH, S_IWOTH, S_IXOTH
12698 };
12699
Denis Vlasenkoeb858492009-04-18 02:06:54 +000012700 /* TODO: use bb_parse_mode() instead */
12701
Eric Andersenc470f442003-07-28 09:56:35 +000012702 char *ap;
12703 mode_t mask;
12704 int i;
12705 int symbolic_mode = 0;
12706
12707 while (nextopt("S") != '\0') {
12708 symbolic_mode = 1;
12709 }
12710
Denis Vlasenkob012b102007-02-19 22:43:01 +000012711 INT_OFF;
Eric Andersenc470f442003-07-28 09:56:35 +000012712 mask = umask(0);
12713 umask(mask);
Denis Vlasenkob012b102007-02-19 22:43:01 +000012714 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +000012715
Denis Vlasenko5cedb752007-02-18 19:56:41 +000012716 ap = *argptr;
12717 if (ap == NULL) {
Eric Andersenc470f442003-07-28 09:56:35 +000012718 if (symbolic_mode) {
12719 char buf[18];
12720 char *p = buf;
12721
12722 for (i = 0; i < 3; i++) {
12723 int j;
12724
12725 *p++ = permuser[i];
12726 *p++ = '=';
12727 for (j = 0; j < 3; j++) {
12728 if ((mask & permmask[3 * i + j]) == 0) {
12729 *p++ = permmode[j];
12730 }
12731 }
12732 *p++ = ',';
12733 }
12734 *--p = 0;
12735 puts(buf);
12736 } else {
12737 out1fmt("%.4o\n", mask);
12738 }
12739 } else {
Denis Vlasenkoaa744452007-02-23 01:04:22 +000012740 if (isdigit((unsigned char) *ap)) {
Eric Andersenc470f442003-07-28 09:56:35 +000012741 mask = 0;
12742 do {
12743 if (*ap >= '8' || *ap < '0')
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +020012744 ash_msg_and_raise_error(msg_illnum, argv[1]);
Eric Andersenc470f442003-07-28 09:56:35 +000012745 mask = (mask << 3) + (*ap - '0');
12746 } while (*++ap != '\0');
12747 umask(mask);
12748 } else {
12749 mask = ~mask & 0777;
12750 if (!bb_parse_mode(ap, &mask)) {
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +000012751 ash_msg_and_raise_error("illegal mode: %s", ap);
Eric Andersenc470f442003-07-28 09:56:35 +000012752 }
12753 umask(~mask & 0777);
12754 }
12755 }
12756 return 0;
12757}
12758
12759/*
12760 * ulimit builtin
12761 *
12762 * This code, originally by Doug Gwyn, Doug Kingston, Eric Gisin, and
12763 * Michael Rendell was ripped from pdksh 5.0.8 and hacked for use with
12764 * ash by J.T. Conklin.
12765 *
12766 * Public domain.
12767 */
Eric Andersenc470f442003-07-28 09:56:35 +000012768struct limits {
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012769 uint8_t cmd; /* RLIMIT_xxx fit into it */
12770 uint8_t factor_shift; /* shift by to get rlim_{cur,max} values */
Eric Andersenc470f442003-07-28 09:56:35 +000012771 char option;
12772};
12773
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012774static const struct limits limits_tbl[] = {
Eric Andersenc470f442003-07-28 09:56:35 +000012775#ifdef RLIMIT_CPU
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012776 { RLIMIT_CPU, 0, 't' },
Eric Andersenc470f442003-07-28 09:56:35 +000012777#endif
12778#ifdef RLIMIT_FSIZE
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012779 { RLIMIT_FSIZE, 9, 'f' },
Eric Andersenc470f442003-07-28 09:56:35 +000012780#endif
12781#ifdef RLIMIT_DATA
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012782 { RLIMIT_DATA, 10, 'd' },
Eric Andersenc470f442003-07-28 09:56:35 +000012783#endif
12784#ifdef RLIMIT_STACK
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012785 { RLIMIT_STACK, 10, 's' },
Eric Andersenc470f442003-07-28 09:56:35 +000012786#endif
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012787#ifdef RLIMIT_CORE
12788 { RLIMIT_CORE, 9, 'c' },
Eric Andersenc470f442003-07-28 09:56:35 +000012789#endif
12790#ifdef RLIMIT_RSS
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012791 { RLIMIT_RSS, 10, 'm' },
Eric Andersenc470f442003-07-28 09:56:35 +000012792#endif
12793#ifdef RLIMIT_MEMLOCK
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012794 { RLIMIT_MEMLOCK, 10, 'l' },
Eric Andersenc470f442003-07-28 09:56:35 +000012795#endif
12796#ifdef RLIMIT_NPROC
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012797 { RLIMIT_NPROC, 0, 'p' },
Eric Andersenc470f442003-07-28 09:56:35 +000012798#endif
12799#ifdef RLIMIT_NOFILE
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012800 { RLIMIT_NOFILE, 0, 'n' },
Eric Andersenc470f442003-07-28 09:56:35 +000012801#endif
Glenn L McGrath76620622004-01-13 10:19:37 +000012802#ifdef RLIMIT_AS
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012803 { RLIMIT_AS, 10, 'v' },
Eric Andersenc470f442003-07-28 09:56:35 +000012804#endif
Glenn L McGrath76620622004-01-13 10:19:37 +000012805#ifdef RLIMIT_LOCKS
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012806 { RLIMIT_LOCKS, 0, 'w' },
Eric Andersenc470f442003-07-28 09:56:35 +000012807#endif
Eric Andersenc470f442003-07-28 09:56:35 +000012808};
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012809static const char limits_name[] =
12810#ifdef RLIMIT_CPU
12811 "time(seconds)" "\0"
12812#endif
12813#ifdef RLIMIT_FSIZE
12814 "file(blocks)" "\0"
12815#endif
12816#ifdef RLIMIT_DATA
12817 "data(kb)" "\0"
12818#endif
12819#ifdef RLIMIT_STACK
12820 "stack(kb)" "\0"
12821#endif
12822#ifdef RLIMIT_CORE
12823 "coredump(blocks)" "\0"
12824#endif
12825#ifdef RLIMIT_RSS
12826 "memory(kb)" "\0"
12827#endif
12828#ifdef RLIMIT_MEMLOCK
12829 "locked memory(kb)" "\0"
12830#endif
12831#ifdef RLIMIT_NPROC
12832 "process" "\0"
12833#endif
12834#ifdef RLIMIT_NOFILE
12835 "nofiles" "\0"
12836#endif
12837#ifdef RLIMIT_AS
12838 "vmemory(kb)" "\0"
12839#endif
12840#ifdef RLIMIT_LOCKS
12841 "locks" "\0"
12842#endif
12843;
Eric Andersenc470f442003-07-28 09:56:35 +000012844
Glenn L McGrath76620622004-01-13 10:19:37 +000012845enum limtype { SOFT = 0x1, HARD = 0x2 };
12846
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012847static void
12848printlim(enum limtype how, const struct rlimit *limit,
Glenn L McGrath76620622004-01-13 10:19:37 +000012849 const struct limits *l)
12850{
12851 rlim_t val;
12852
12853 val = limit->rlim_max;
12854 if (how & SOFT)
12855 val = limit->rlim_cur;
12856
12857 if (val == RLIM_INFINITY)
12858 out1fmt("unlimited\n");
12859 else {
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012860 val >>= l->factor_shift;
Glenn L McGrath76620622004-01-13 10:19:37 +000012861 out1fmt("%lld\n", (long long) val);
12862 }
12863}
12864
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012865static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012866ulimitcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersenc470f442003-07-28 09:56:35 +000012867{
Denys Vlasenko76622db2009-10-04 01:14:19 +020012868 rlim_t val;
Glenn L McGrath76620622004-01-13 10:19:37 +000012869 enum limtype how = SOFT | HARD;
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012870 const struct limits *l;
12871 int set, all = 0;
12872 int optc, what;
12873 struct rlimit limit;
Eric Andersenc470f442003-07-28 09:56:35 +000012874
12875 what = 'f';
Glenn L McGrath16e45d72004-02-04 08:24:39 +000012876 while ((optc = nextopt("HSa"
12877#ifdef RLIMIT_CPU
12878 "t"
12879#endif
12880#ifdef RLIMIT_FSIZE
12881 "f"
12882#endif
12883#ifdef RLIMIT_DATA
12884 "d"
12885#endif
12886#ifdef RLIMIT_STACK
12887 "s"
12888#endif
12889#ifdef RLIMIT_CORE
12890 "c"
12891#endif
12892#ifdef RLIMIT_RSS
12893 "m"
12894#endif
12895#ifdef RLIMIT_MEMLOCK
12896 "l"
12897#endif
12898#ifdef RLIMIT_NPROC
12899 "p"
12900#endif
12901#ifdef RLIMIT_NOFILE
12902 "n"
12903#endif
12904#ifdef RLIMIT_AS
12905 "v"
12906#endif
12907#ifdef RLIMIT_LOCKS
12908 "w"
12909#endif
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000012910 )) != '\0')
Eric Andersenc470f442003-07-28 09:56:35 +000012911 switch (optc) {
12912 case 'H':
12913 how = HARD;
12914 break;
12915 case 'S':
12916 how = SOFT;
12917 break;
12918 case 'a':
12919 all = 1;
12920 break;
12921 default:
12922 what = optc;
12923 }
12924
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012925 for (l = limits_tbl; l->option != what; l++)
12926 continue;
Eric Andersenc470f442003-07-28 09:56:35 +000012927
12928 set = *argptr ? 1 : 0;
Denys Vlasenko76622db2009-10-04 01:14:19 +020012929 val = 0;
Eric Andersenc470f442003-07-28 09:56:35 +000012930 if (set) {
12931 char *p = *argptr;
12932
12933 if (all || argptr[1])
Denis Vlasenkob012b102007-02-19 22:43:01 +000012934 ash_msg_and_raise_error("too many arguments");
Eric Andersen81fe1232003-07-29 06:38:40 +000012935 if (strncmp(p, "unlimited\n", 9) == 0)
Eric Andersenc470f442003-07-28 09:56:35 +000012936 val = RLIM_INFINITY;
12937 else {
Denys Vlasenko76622db2009-10-04 01:14:19 +020012938 if (sizeof(val) == sizeof(int))
12939 val = bb_strtou(p, NULL, 10);
12940 else if (sizeof(val) == sizeof(long))
12941 val = bb_strtoul(p, NULL, 10);
12942 else
12943 val = bb_strtoull(p, NULL, 10);
12944 if (errno)
Denis Vlasenkob012b102007-02-19 22:43:01 +000012945 ash_msg_and_raise_error("bad number");
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012946 val <<= l->factor_shift;
Eric Andersenc470f442003-07-28 09:56:35 +000012947 }
12948 }
12949 if (all) {
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012950 const char *lname = limits_name;
12951 for (l = limits_tbl; l != &limits_tbl[ARRAY_SIZE(limits_tbl)]; l++) {
Eric Andersenc470f442003-07-28 09:56:35 +000012952 getrlimit(l->cmd, &limit);
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012953 out1fmt("%-20s ", lname);
12954 lname += strlen(lname) + 1;
Glenn L McGrath76620622004-01-13 10:19:37 +000012955 printlim(how, &limit, l);
Eric Andersenc470f442003-07-28 09:56:35 +000012956 }
12957 return 0;
12958 }
12959
12960 getrlimit(l->cmd, &limit);
12961 if (set) {
12962 if (how & HARD)
12963 limit.rlim_max = val;
12964 if (how & SOFT)
12965 limit.rlim_cur = val;
12966 if (setrlimit(l->cmd, &limit) < 0)
Denis Vlasenkob012b102007-02-19 22:43:01 +000012967 ash_msg_and_raise_error("error setting limit (%m)");
Eric Andersenc470f442003-07-28 09:56:35 +000012968 } else {
Glenn L McGrath76620622004-01-13 10:19:37 +000012969 printlim(how, &limit, l);
Eric Andersenc470f442003-07-28 09:56:35 +000012970 }
12971 return 0;
12972}
12973
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012974/* ============ main() and helpers */
12975
12976/*
12977 * Called to exit the shell.
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012978 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012979static void exitshell(void) NORETURN;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012980static void
12981exitshell(void)
12982{
12983 struct jmploc loc;
12984 char *p;
12985 int status;
12986
12987 status = exitstatus;
12988 TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
12989 if (setjmp(loc.loc)) {
Denis Vlasenko7f88e342009-03-19 03:36:18 +000012990 if (exception_type == EXEXIT)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012991/* dash bug: it just does _exit(exitstatus) here
12992 * but we have to do setjobctl(0) first!
12993 * (bug is still not fixed in dash-0.5.3 - if you run dash
12994 * under Midnight Commander, on exit from dash MC is backgrounded) */
12995 status = exitstatus;
12996 goto out;
12997 }
12998 exception_handler = &loc;
12999 p = trap[0];
13000 if (p) {
13001 trap[0] = NULL;
13002 evalstring(p, 0);
Denys Vlasenko0800e3a2009-09-24 03:09:26 +020013003 free(p);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000013004 }
13005 flush_stdout_stderr();
13006 out:
13007 setjobctl(0);
13008 _exit(status);
13009 /* NOTREACHED */
13010}
13011
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000013012static void
13013init(void)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013014{
13015 /* from input.c: */
Denis Vlasenko41eb3002008-11-28 03:42:31 +000013016 basepf.next_to_pgetc = basepf.buf = basebuf;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013017
13018 /* from trap.c: */
13019 signal(SIGCHLD, SIG_DFL);
Denys Vlasenko7a7b0342009-12-04 04:18:31 +010013020 /* bash re-enables SIGHUP which is SIG_IGNed on entry.
13021 * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
13022 */
13023 signal(SIGHUP, SIG_DFL);
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013024
13025 /* from var.c: */
13026 {
13027 char **envp;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013028 const char *p;
13029 struct stat st1, st2;
13030
13031 initvar();
13032 for (envp = environ; envp && *envp; envp++) {
13033 if (strchr(*envp, '=')) {
13034 setvareq(*envp, VEXPORT|VTEXTFIXED);
13035 }
13036 }
13037
Denys Vlasenko7bb346f2009-10-06 22:09:50 +020013038 setvar("PPID", utoa(getppid()), 0);
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013039
13040 p = lookupvar("PWD");
13041 if (p)
13042 if (*p != '/' || stat(p, &st1) || stat(".", &st2)
13043 || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino)
13044 p = '\0';
13045 setpwd(p, 0);
13046 }
13047}
13048
13049/*
13050 * Process the shell command line arguments.
13051 */
13052static void
Denis Vlasenko68404f12008-03-17 09:00:54 +000013053procargs(char **argv)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013054{
13055 int i;
13056 const char *xminusc;
13057 char **xargv;
13058
13059 xargv = argv;
13060 arg0 = xargv[0];
Denis Vlasenko68404f12008-03-17 09:00:54 +000013061 /* if (xargv[0]) - mmm, this is always true! */
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013062 xargv++;
13063 for (i = 0; i < NOPTS; i++)
13064 optlist[i] = 2;
13065 argptr = xargv;
Denis Vlasenko28bf6712008-02-14 15:01:47 +000013066 if (options(1)) {
13067 /* it already printed err message */
13068 raise_exception(EXERROR);
13069 }
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013070 xargv = argptr;
13071 xminusc = minusc;
13072 if (*xargv == NULL) {
13073 if (xminusc)
13074 ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
13075 sflag = 1;
13076 }
13077 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
13078 iflag = 1;
13079 if (mflag == 2)
13080 mflag = iflag;
13081 for (i = 0; i < NOPTS; i++)
13082 if (optlist[i] == 2)
13083 optlist[i] = 0;
13084#if DEBUG == 2
13085 debug = 1;
13086#endif
13087 /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
13088 if (xminusc) {
13089 minusc = *xargv++;
13090 if (*xargv)
13091 goto setarg0;
13092 } else if (!sflag) {
13093 setinputfile(*xargv, 0);
13094 setarg0:
13095 arg0 = *xargv++;
13096 commandname = arg0;
13097 }
13098
13099 shellparam.p = xargv;
13100#if ENABLE_ASH_GETOPTS
13101 shellparam.optind = 1;
13102 shellparam.optoff = -1;
13103#endif
Denis Vlasenko01631112007-12-16 17:20:38 +000013104 /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013105 while (*xargv) {
13106 shellparam.nparam++;
13107 xargv++;
13108 }
13109 optschanged();
13110}
13111
13112/*
13113 * Read /etc/profile or .profile.
13114 */
13115static void
13116read_profile(const char *name)
13117{
13118 int skip;
13119
13120 if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
13121 return;
13122 skip = cmdloop(0);
13123 popfile();
13124 if (skip)
13125 exitshell();
13126}
13127
Denis Vlasenko0c032a42007-02-23 01:03:40 +000013128/*
13129 * This routine is called when an error or an interrupt occurs in an
13130 * interactive shell and control is returned to the main command loop.
13131 */
13132static void
13133reset(void)
13134{
13135 /* from eval.c: */
13136 evalskip = 0;
13137 loopnest = 0;
13138 /* from input.c: */
Denis Vlasenko41eb3002008-11-28 03:42:31 +000013139 g_parsefile->left_in_buffer = 0;
13140 g_parsefile->left_in_line = 0; /* clear input buffer */
Denis Vlasenko0c032a42007-02-23 01:03:40 +000013141 popallfiles();
13142 /* from parser.c: */
13143 tokpushback = 0;
13144 checkkwd = 0;
13145 /* from redir.c: */
Denis Vlasenko34c73c42008-08-16 11:48:02 +000013146 clearredir(/*drop:*/ 0);
Denis Vlasenko0c032a42007-02-23 01:03:40 +000013147}
13148
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013149#if PROFILE
13150static short profile_buf[16384];
13151extern int etext();
13152#endif
13153
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000013154/*
13155 * Main routine. We initialize things, parse the arguments, execute
13156 * profiles if we're a login shell, and then call cmdloop to execute
13157 * commands. The setjmp call sets up the location to jump to when an
13158 * exception occurs. When an exception occurs the variable "state"
13159 * is used to figure out how far we had gotten.
13160 */
Denis Vlasenko9b49a5e2007-10-11 10:05:36 +000013161int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000013162int ash_main(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013163{
Mike Frysinger98c52642009-04-02 10:02:37 +000013164 const char *shinit;
Denis Vlasenko4e12b1a2008-12-23 23:36:47 +000013165 volatile smallint state;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013166 struct jmploc jmploc;
13167 struct stackmark smark;
13168
Denis Vlasenko01631112007-12-16 17:20:38 +000013169 /* Initialize global data */
13170 INIT_G_misc();
13171 INIT_G_memstack();
13172 INIT_G_var();
Denis Vlasenkoee87ebf2007-12-21 22:18:16 +000013173#if ENABLE_ASH_ALIAS
Denis Vlasenko01631112007-12-16 17:20:38 +000013174 INIT_G_alias();
Denis Vlasenkoee87ebf2007-12-21 22:18:16 +000013175#endif
Denis Vlasenko01631112007-12-16 17:20:38 +000013176 INIT_G_cmdtable();
13177
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013178#if PROFILE
13179 monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
13180#endif
13181
13182#if ENABLE_FEATURE_EDITING
13183 line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
13184#endif
13185 state = 0;
13186 if (setjmp(jmploc.loc)) {
Denis Vlasenko7f88e342009-03-19 03:36:18 +000013187 smallint e;
Denis Vlasenko4e12b1a2008-12-23 23:36:47 +000013188 smallint s;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013189
13190 reset();
13191
Denis Vlasenko7f88e342009-03-19 03:36:18 +000013192 e = exception_type;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013193 if (e == EXERROR)
13194 exitstatus = 2;
13195 s = state;
13196 if (e == EXEXIT || s == 0 || iflag == 0 || shlvl)
13197 exitshell();
Denis Vlasenko7f88e342009-03-19 03:36:18 +000013198 if (e == EXINT)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013199 outcslow('\n', stderr);
Denis Vlasenko7f88e342009-03-19 03:36:18 +000013200
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013201 popstackmark(&smark);
13202 FORCE_INT_ON; /* enable interrupts */
13203 if (s == 1)
13204 goto state1;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000013205 if (s == 2)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013206 goto state2;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000013207 if (s == 3)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013208 goto state3;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000013209 goto state4;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013210 }
13211 exception_handler = &jmploc;
13212#if DEBUG
13213 opentrace();
Denis Vlasenko653d8e72009-03-19 21:59:35 +000013214 TRACE(("Shell args: "));
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000013215 trace_puts_args(argv);
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013216#endif
13217 rootpid = getpid();
13218
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013219 init();
13220 setstackmark(&smark);
Denis Vlasenko68404f12008-03-17 09:00:54 +000013221 procargs(argv);
13222
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013223#if ENABLE_FEATURE_EDITING_SAVEHISTORY
13224 if (iflag) {
13225 const char *hp = lookupvar("HISTFILE");
13226
13227 if (hp == NULL) {
13228 hp = lookupvar("HOME");
13229 if (hp != NULL) {
13230 char *defhp = concat_path_file(hp, ".ash_history");
13231 setvar("HISTFILE", defhp, 0);
13232 free(defhp);
13233 }
13234 }
13235 }
13236#endif
Denis Vlasenko4e12b1a2008-12-23 23:36:47 +000013237 if (/* argv[0] && */ argv[0][0] == '-')
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013238 isloginsh = 1;
13239 if (isloginsh) {
13240 state = 1;
13241 read_profile("/etc/profile");
13242 state1:
13243 state = 2;
13244 read_profile(".profile");
13245 }
13246 state2:
13247 state = 3;
13248 if (
13249#ifndef linux
Denis Vlasenko0c032a42007-02-23 01:03:40 +000013250 getuid() == geteuid() && getgid() == getegid() &&
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013251#endif
Denis Vlasenko0c032a42007-02-23 01:03:40 +000013252 iflag
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013253 ) {
13254 shinit = lookupvar("ENV");
13255 if (shinit != NULL && *shinit != '\0') {
13256 read_profile(shinit);
13257 }
13258 }
13259 state3:
13260 state = 4;
Denis Vlasenko5c2b8142009-03-19 01:59:59 +000013261 if (minusc) {
13262 /* evalstring pushes parsefile stack.
13263 * Ensure we don't falsely claim that 0 (stdin)
Denis Vlasenko5368ad52009-03-20 10:20:08 +000013264 * is one of stacked source fds.
13265 * Testcase: ash -c 'exec 1>&0' must not complain. */
Denis Vlasenko5c2b8142009-03-19 01:59:59 +000013266 if (!sflag)
13267 g_parsefile->fd = -1;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013268 evalstring(minusc, 0);
Denis Vlasenko5c2b8142009-03-19 01:59:59 +000013269 }
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013270
13271 if (sflag || minusc == NULL) {
Denys Vlasenko0337e032009-11-29 00:12:30 +010013272#if defined MAX_HISTORY && MAX_HISTORY > 0 && ENABLE_FEATURE_EDITING_SAVEHISTORY
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +000013273 if (iflag) {
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013274 const char *hp = lookupvar("HISTFILE");
Denis Vlasenko5c2b8142009-03-19 01:59:59 +000013275 if (hp)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013276 line_input_state->hist_file = hp;
13277 }
13278#endif
13279 state4: /* XXX ??? - why isn't this before the "if" statement */
13280 cmdloop(1);
13281 }
13282#if PROFILE
13283 monitor(0);
13284#endif
13285#ifdef GPROF
13286 {
13287 extern void _mcleanup(void);
13288 _mcleanup();
13289 }
13290#endif
13291 exitshell();
13292 /* NOTREACHED */
13293}
13294
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013295
Eric Andersendf82f612001-06-28 07:46:40 +000013296/*-
13297 * Copyright (c) 1989, 1991, 1993, 1994
Eric Andersen2870d962001-07-02 17:27:21 +000013298 * The Regents of the University of California. All rights reserved.
Eric Andersendf82f612001-06-28 07:46:40 +000013299 *
13300 * This code is derived from software contributed to Berkeley by
13301 * Kenneth Almquist.
13302 *
13303 * Redistribution and use in source and binary forms, with or without
13304 * modification, are permitted provided that the following conditions
13305 * are met:
13306 * 1. Redistributions of source code must retain the above copyright
13307 * notice, this list of conditions and the following disclaimer.
13308 * 2. Redistributions in binary form must reproduce the above copyright
13309 * notice, this list of conditions and the following disclaimer in the
13310 * documentation and/or other materials provided with the distribution.
"Vladimir N. Oleynik"ddc280e2005-12-15 12:01:49 +000013311 * 3. Neither the name of the University nor the names of its contributors
Eric Andersendf82f612001-06-28 07:46:40 +000013312 * may be used to endorse or promote products derived from this software
13313 * without specific prior written permission.
13314 *
13315 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
13316 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
13317 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
13318 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
13319 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
13320 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
13321 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
13322 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
13323 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
13324 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
13325 * SUCH DAMAGE.
13326 */