blob: b47f0e881f3d7058bab84e05ec6cd010f3efcecb [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 Vlasenkoe9ac32a2009-12-05 02:01:25 +0100103 "\0" "vi"
Michael Abbott359da5e2009-12-04 23:03:29 +0100104#if ENABLE_ASH_BASH_COMPAT
Denys Vlasenkoe9ac32a2009-12-05 02:01:25 +0100105 ,"\0" "pipefail"
Michael Abbott359da5e2009-12-04 23:03:29 +0100106#endif
Denis Vlasenkob012b102007-02-19 22:43:01 +0000107#if DEBUG
Denis Vlasenko6ca409e2007-08-12 20:58:27 +0000108 ,"\0" "nolog"
109 ,"\0" "debug"
Denis Vlasenkob012b102007-02-19 22:43:01 +0000110#endif
111};
112
Denys Vlasenko285ad152009-12-04 23:02:27 +0100113#define optletters(n) optletters_optnames[n][0]
114#define optnames(n) (optletters_optnames[n] + 1)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000115
Denis Vlasenko80b8b392007-06-25 10:55:35 +0000116enum { NOPTS = ARRAY_SIZE(optletters_optnames) };
Denis Vlasenkob012b102007-02-19 22:43:01 +0000117
Eric Andersenc470f442003-07-28 09:56:35 +0000118
Denis Vlasenkob012b102007-02-19 22:43:01 +0000119/* ============ Misc data */
Eric Andersenc470f442003-07-28 09:56:35 +0000120
Denis Vlasenko6ca409e2007-08-12 20:58:27 +0000121static const char homestr[] ALIGN1 = "HOME";
122static const char snlfmt[] ALIGN1 = "%s\n";
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200123static const char msg_illnum[] ALIGN1 = "Illegal number: %s";
Denis Vlasenkoaa744452007-02-23 01:04:22 +0000124
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +0000125/*
Eric Andersenc470f442003-07-28 09:56:35 +0000126 * We enclose jmp_buf in a structure so that we can declare pointers to
127 * jump locations. The global variable handler contains the location to
Denis Vlasenkof1733952009-03-19 23:21:55 +0000128 * jump to when an exception occurs, and the global variable exception_type
Eric Andersenaff114c2004-04-14 17:51:38 +0000129 * contains a code identifying the exception. To implement nested
Eric Andersenc470f442003-07-28 09:56:35 +0000130 * exception handlers, the user should save the value of handler on entry
131 * to an inner scope, set handler to point to a jmploc structure for the
132 * inner scope, and restore handler on exit from the scope.
133 */
Eric Andersenc470f442003-07-28 09:56:35 +0000134struct jmploc {
135 jmp_buf loc;
136};
Denis Vlasenko01631112007-12-16 17:20:38 +0000137
138struct globals_misc {
139 /* pid of main shell */
140 int rootpid;
141 /* shell level: 0 for the main shell, 1 for its children, and so on */
142 int shlvl;
143#define rootshell (!shlvl)
144 char *minusc; /* argument to -c option */
145
146 char *curdir; // = nullstr; /* current working directory */
147 char *physdir; // = nullstr; /* physical working directory */
148
149 char *arg0; /* value of $0 */
150
151 struct jmploc *exception_handler;
Denis Vlasenko991a1da2008-02-10 19:02:53 +0000152
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200153 volatile int suppress_int; /* counter */
154 volatile /*sig_atomic_t*/ smallint pending_int; /* 1 = got SIGINT */
Denis Vlasenko991a1da2008-02-10 19:02:53 +0000155 /* last pending signal */
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200156 volatile /*sig_atomic_t*/ smallint pending_sig;
Denis Vlasenko7f88e342009-03-19 03:36:18 +0000157 smallint exception_type; /* kind of exception (0..5) */
Denis Vlasenko01631112007-12-16 17:20:38 +0000158 /* exceptions */
Eric Andersenc470f442003-07-28 09:56:35 +0000159#define EXINT 0 /* SIGINT received */
160#define EXERROR 1 /* a generic error */
161#define EXSHELLPROC 2 /* execute a shell procedure */
162#define EXEXEC 3 /* command execution failed */
163#define EXEXIT 4 /* exit the shell */
164#define EXSIG 5 /* trapped signal in wait(1) */
Eric Andersen2870d962001-07-02 17:27:21 +0000165
Denis Vlasenko01631112007-12-16 17:20:38 +0000166 smallint isloginsh;
Denis Vlasenkob07a4962008-06-22 13:16:23 +0000167 char nullstr[1]; /* zero length string */
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000168
169 char optlist[NOPTS];
170#define eflag optlist[0]
171#define fflag optlist[1]
172#define Iflag optlist[2]
173#define iflag optlist[3]
174#define mflag optlist[4]
175#define nflag optlist[5]
176#define sflag optlist[6]
177#define xflag optlist[7]
178#define vflag optlist[8]
179#define Cflag optlist[9]
180#define aflag optlist[10]
181#define bflag optlist[11]
182#define uflag optlist[12]
183#define viflag optlist[13]
Michael Abbott359da5e2009-12-04 23:03:29 +0100184#if ENABLE_ASH_BASH_COMPAT
185# define pipefail optlist[14]
186#else
187# define pipefail 0
188#endif
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000189#if DEBUG
Michael Abbott359da5e2009-12-04 23:03:29 +0100190# define nolog optlist[14 + ENABLE_ASH_BASH_COMPAT]
191# define debug optlist[15 + ENABLE_ASH_BASH_COMPAT]
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000192#endif
193
194 /* trap handler commands */
Denis Vlasenko01631112007-12-16 17:20:38 +0000195 /*
196 * Sigmode records the current value of the signal handlers for the various
197 * modes. A value of zero means that the current handler is not known.
Denis Vlasenkof8535cc2008-12-03 10:36:26 +0000198 * S_HARD_IGN indicates that the signal was ignored on entry to the shell.
Denis Vlasenko01631112007-12-16 17:20:38 +0000199 */
200 char sigmode[NSIG - 1];
Denis Vlasenkof8535cc2008-12-03 10:36:26 +0000201#define S_DFL 1 /* default signal handling (SIG_DFL) */
202#define S_CATCH 2 /* signal is caught */
203#define S_IGN 3 /* signal is ignored (SIG_IGN) */
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +0000204#define S_HARD_IGN 4 /* signal is ignored permenantly */
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +0000205
Denis Vlasenko01631112007-12-16 17:20:38 +0000206 /* indicates specified signal received */
Denis Vlasenko4b875702009-03-19 13:30:04 +0000207 uint8_t gotsig[NSIG - 1]; /* offset by 1: "signal" 0 is meaningless */
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000208 char *trap[NSIG];
Denys Vlasenko21d87d42009-09-25 00:06:51 +0200209 char **trap_ptr; /* used only by "trap hack" */
Denis Vlasenko448d30e2008-06-27 00:24:11 +0000210
211 /* Rarely referenced stuff */
212#if ENABLE_ASH_RANDOM_SUPPORT
Denys Vlasenko3ea2e822009-10-09 20:59:04 +0200213 random_t random_gen;
Denis Vlasenko448d30e2008-06-27 00:24:11 +0000214#endif
215 pid_t backgndpid; /* pid of last background process */
216 smallint job_warning; /* user was warned about stopped jobs (can be 2, 1 or 0). */
Denis Vlasenko01631112007-12-16 17:20:38 +0000217};
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000218extern struct globals_misc *const ash_ptr_to_globals_misc;
219#define G_misc (*ash_ptr_to_globals_misc)
Denis Vlasenko26bc57d2008-06-27 00:29:34 +0000220#define rootpid (G_misc.rootpid )
221#define shlvl (G_misc.shlvl )
222#define minusc (G_misc.minusc )
223#define curdir (G_misc.curdir )
224#define physdir (G_misc.physdir )
225#define arg0 (G_misc.arg0 )
Denis Vlasenko01631112007-12-16 17:20:38 +0000226#define exception_handler (G_misc.exception_handler)
Denis Vlasenko7f88e342009-03-19 03:36:18 +0000227#define exception_type (G_misc.exception_type )
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200228#define suppress_int (G_misc.suppress_int )
229#define pending_int (G_misc.pending_int )
230#define pending_sig (G_misc.pending_sig )
Denis Vlasenko26bc57d2008-06-27 00:29:34 +0000231#define isloginsh (G_misc.isloginsh )
232#define nullstr (G_misc.nullstr )
233#define optlist (G_misc.optlist )
234#define sigmode (G_misc.sigmode )
235#define gotsig (G_misc.gotsig )
236#define trap (G_misc.trap )
Denys Vlasenko21d87d42009-09-25 00:06:51 +0200237#define trap_ptr (G_misc.trap_ptr )
Denys Vlasenko3ea2e822009-10-09 20:59:04 +0200238#define random_gen (G_misc.random_gen )
Denis Vlasenko448d30e2008-06-27 00:24:11 +0000239#define backgndpid (G_misc.backgndpid )
240#define job_warning (G_misc.job_warning)
Denis Vlasenko01631112007-12-16 17:20:38 +0000241#define INIT_G_misc() do { \
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000242 (*(struct globals_misc**)&ash_ptr_to_globals_misc) = xzalloc(sizeof(G_misc)); \
243 barrier(); \
Denis Vlasenko01631112007-12-16 17:20:38 +0000244 curdir = nullstr; \
245 physdir = nullstr; \
Denys Vlasenko21d87d42009-09-25 00:06:51 +0200246 trap_ptr = trap; \
Denis Vlasenko01631112007-12-16 17:20:38 +0000247} while (0)
248
249
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000250/* ============ DEBUG */
251#if DEBUG
252static void trace_printf(const char *fmt, ...);
253static void trace_vprintf(const char *fmt, va_list va);
254# define TRACE(param) trace_printf param
255# define TRACEV(param) trace_vprintf param
Denis Vlasenko1bb3d7e2009-03-20 07:45:36 +0000256# define close(fd) do { \
257 int dfd = (fd); \
Denis Vlasenkob9e70dd2009-03-20 01:24:08 +0000258 if (close(dfd) < 0) \
Denys Vlasenko883cea42009-07-11 15:31:59 +0200259 bb_error_msg("bug on %d: closing %d(0x%x)", \
Denis Vlasenko1bb3d7e2009-03-20 07:45:36 +0000260 __LINE__, dfd, dfd); \
Denis Vlasenkob9e70dd2009-03-20 01:24:08 +0000261} while (0)
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000262#else
263# define TRACE(param)
264# define TRACEV(param)
265#endif
266
267
Denis Vlasenko559691a2008-10-05 18:39:31 +0000268/* ============ Utility functions */
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000269#define xbarrier() do { __asm__ __volatile__ ("": : :"memory"); } while (0)
270
Denis Vlasenko559691a2008-10-05 18:39:31 +0000271static int isdigit_str9(const char *str)
272{
273 int maxlen = 9 + 1; /* max 9 digits: 999999999 */
274 while (--maxlen && isdigit(*str))
275 str++;
276 return (*str == '\0');
277}
Denis Vlasenko01631112007-12-16 17:20:38 +0000278
Denis Vlasenko559691a2008-10-05 18:39:31 +0000279
280/* ============ Interrupts / exceptions */
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +0000281/*
Eric Andersen2870d962001-07-02 17:27:21 +0000282 * These macros allow the user to suspend the handling of interrupt signals
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +0000283 * over a period of time. This is similar to SIGHOLD or to sigblock, but
Eric Andersen2870d962001-07-02 17:27:21 +0000284 * much more efficient and portable. (But hacking the kernel is so much
285 * more fun than worrying about efficiency and portability. :-))
286 */
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000287#define INT_OFF do { \
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200288 suppress_int++; \
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000289 xbarrier(); \
290} while (0)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000291
292/*
293 * Called to raise an exception. Since C doesn't include exceptions, we
294 * just do a longjmp to the exception handler. The type of exception is
Denis Vlasenko4b875702009-03-19 13:30:04 +0000295 * stored in the global variable "exception_type".
Denis Vlasenkob012b102007-02-19 22:43:01 +0000296 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +0000297static void raise_exception(int) NORETURN;
Denis Vlasenkob012b102007-02-19 22:43:01 +0000298static void
299raise_exception(int e)
300{
301#if DEBUG
Denis Vlasenko2da584f2007-02-19 22:44:05 +0000302 if (exception_handler == NULL)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000303 abort();
304#endif
305 INT_OFF;
Denis Vlasenko7f88e342009-03-19 03:36:18 +0000306 exception_type = e;
Denis Vlasenko2da584f2007-02-19 22:44:05 +0000307 longjmp(exception_handler->loc, 1);
Denis Vlasenkob012b102007-02-19 22:43:01 +0000308}
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000309#if DEBUG
310#define raise_exception(e) do { \
311 TRACE(("raising exception %d on line %d\n", (e), __LINE__)); \
312 raise_exception(e); \
313} while (0)
314#endif
Denis Vlasenkob012b102007-02-19 22:43:01 +0000315
316/*
317 * Called from trap.c when a SIGINT is received. (If the user specifies
318 * that SIGINT is to be trapped or ignored using the trap builtin, then
319 * this routine is not called.) Suppressint is nonzero when interrupts
320 * are held using the INT_OFF macro. (The test for iflag is just
321 * defensive programming.)
322 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +0000323static void raise_interrupt(void) NORETURN;
Denis Vlasenkob012b102007-02-19 22:43:01 +0000324static void
325raise_interrupt(void)
326{
Denis Vlasenko4b875702009-03-19 13:30:04 +0000327 int ex_type;
Denis Vlasenkob012b102007-02-19 22:43:01 +0000328
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200329 pending_int = 0;
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +0000330 /* Signal is not automatically unmasked after it is raised,
331 * do it ourself - unmask all signals */
Denis Vlasenko3f165fa2008-03-17 08:29:08 +0000332 sigprocmask_allsigs(SIG_UNBLOCK);
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200333 /* pending_sig = 0; - now done in onsig() */
Denis Vlasenko7c139b42007-03-21 20:17:27 +0000334
Denis Vlasenko4b875702009-03-19 13:30:04 +0000335 ex_type = EXSIG;
Denis Vlasenkob012b102007-02-19 22:43:01 +0000336 if (gotsig[SIGINT - 1] && !trap[SIGINT]) {
337 if (!(rootshell && iflag)) {
Denis Vlasenko991a1da2008-02-10 19:02:53 +0000338 /* Kill ourself with SIGINT */
Denis Vlasenkob012b102007-02-19 22:43:01 +0000339 signal(SIGINT, SIG_DFL);
340 raise(SIGINT);
341 }
Denis Vlasenko4b875702009-03-19 13:30:04 +0000342 ex_type = EXINT;
Denis Vlasenkob012b102007-02-19 22:43:01 +0000343 }
Denis Vlasenko4b875702009-03-19 13:30:04 +0000344 raise_exception(ex_type);
Denis Vlasenkob012b102007-02-19 22:43:01 +0000345 /* NOTREACHED */
346}
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000347#if DEBUG
348#define raise_interrupt() do { \
349 TRACE(("raising interrupt on line %d\n", __LINE__)); \
350 raise_interrupt(); \
351} while (0)
352#endif
Denis Vlasenkob012b102007-02-19 22:43:01 +0000353
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000354static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000355int_on(void)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000356{
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +0000357 xbarrier();
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200358 if (--suppress_int == 0 && pending_int) {
Denis Vlasenkob012b102007-02-19 22:43:01 +0000359 raise_interrupt();
360 }
361}
362#define INT_ON int_on()
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000363static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000364force_int_on(void)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000365{
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +0000366 xbarrier();
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200367 suppress_int = 0;
368 if (pending_int)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000369 raise_interrupt();
370}
371#define FORCE_INT_ON force_int_on()
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000372
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200373#define SAVE_INT(v) ((v) = suppress_int)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000374
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000375#define RESTORE_INT(v) do { \
376 xbarrier(); \
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200377 suppress_int = (v); \
378 if (suppress_int == 0 && pending_int) \
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000379 raise_interrupt(); \
380} while (0)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000381
Glenn L McGrath9fef17d2002-08-22 18:41:20 +0000382
Denis Vlasenkobc54cff2007-02-23 01:05:52 +0000383/* ============ Stdout/stderr output */
Eric Andersenc470f442003-07-28 09:56:35 +0000384
Eric Andersenc470f442003-07-28 09:56:35 +0000385static void
Denis Vlasenkob012b102007-02-19 22:43:01 +0000386outstr(const char *p, FILE *file)
Denis Vlasenkoe5570da2007-02-19 22:41:55 +0000387{
Denis Vlasenkob012b102007-02-19 22:43:01 +0000388 INT_OFF;
389 fputs(p, file);
390 INT_ON;
391}
392
393static void
394flush_stdout_stderr(void)
395{
396 INT_OFF;
Denys Vlasenko8131eea2009-11-02 14:19:51 +0100397 fflush_all();
Denis Vlasenkob012b102007-02-19 22:43:01 +0000398 INT_ON;
399}
400
401static void
402outcslow(int c, FILE *dest)
403{
404 INT_OFF;
405 putc(c, dest);
406 fflush(dest);
407 INT_ON;
408}
409
410static int out1fmt(const char *, ...) __attribute__((__format__(__printf__,1,2)));
411static int
412out1fmt(const char *fmt, ...)
413{
414 va_list ap;
415 int r;
416
417 INT_OFF;
418 va_start(ap, fmt);
419 r = vprintf(fmt, ap);
420 va_end(ap);
421 INT_ON;
422 return r;
423}
424
425static int fmtstr(char *, size_t, const char *, ...) __attribute__((__format__(__printf__,3,4)));
426static int
427fmtstr(char *outbuf, size_t length, const char *fmt, ...)
428{
429 va_list ap;
430 int ret;
431
432 va_start(ap, fmt);
433 INT_OFF;
434 ret = vsnprintf(outbuf, length, fmt, ap);
435 va_end(ap);
436 INT_ON;
437 return ret;
438}
439
440static void
441out1str(const char *p)
442{
443 outstr(p, stdout);
444}
445
446static void
447out2str(const char *p)
448{
449 outstr(p, stderr);
Denys Vlasenko8131eea2009-11-02 14:19:51 +0100450 flush_stdout_stderr();
Denis Vlasenkob012b102007-02-19 22:43:01 +0000451}
452
453
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +0000454/* ============ Parser structures */
Denis Vlasenko4d2183b2007-02-23 01:05:38 +0000455
Denis Vlasenko5651bfc2007-02-23 21:08:58 +0000456/* control characters in argument strings */
Denys Vlasenko2ce42e92009-11-29 02:18:13 +0100457#define CTL_FIRST CTLESC
Denys Vlasenkob6c84342009-08-29 20:23:20 +0200458#define CTLESC ((unsigned char)'\201') /* escape next character */
459#define CTLVAR ((unsigned char)'\202') /* variable defn */
460#define CTLENDVAR ((unsigned char)'\203')
461#define CTLBACKQ ((unsigned char)'\204')
Denis Vlasenko5651bfc2007-02-23 21:08:58 +0000462#define CTLQUOTE 01 /* ored with CTLBACKQ code if in quotes */
463/* CTLBACKQ | CTLQUOTE == '\205' */
Denys Vlasenkob6c84342009-08-29 20:23:20 +0200464#define CTLARI ((unsigned char)'\206') /* arithmetic expression */
465#define CTLENDARI ((unsigned char)'\207')
466#define CTLQUOTEMARK ((unsigned char)'\210')
Denys Vlasenko2ce42e92009-11-29 02:18:13 +0100467#define CTL_LAST CTLQUOTEMARK
Denis Vlasenko5651bfc2007-02-23 21:08:58 +0000468
469/* variable substitution byte (follows CTLVAR) */
470#define VSTYPE 0x0f /* type of variable substitution */
471#define VSNUL 0x10 /* colon--treat the empty string as unset */
472#define VSQUOTE 0x80 /* inside double quotes--suppress splitting */
473
474/* values of VSTYPE field */
Denis Vlasenko92e13c22008-03-25 01:17:40 +0000475#define VSNORMAL 0x1 /* normal variable: $var or ${var} */
476#define VSMINUS 0x2 /* ${var-text} */
477#define VSPLUS 0x3 /* ${var+text} */
478#define VSQUESTION 0x4 /* ${var?message} */
479#define VSASSIGN 0x5 /* ${var=text} */
480#define VSTRIMRIGHT 0x6 /* ${var%pattern} */
481#define VSTRIMRIGHTMAX 0x7 /* ${var%%pattern} */
482#define VSTRIMLEFT 0x8 /* ${var#pattern} */
483#define VSTRIMLEFTMAX 0x9 /* ${var##pattern} */
484#define VSLENGTH 0xa /* ${#var} */
485#if ENABLE_ASH_BASH_COMPAT
486#define VSSUBSTR 0xc /* ${var:position:length} */
487#define VSREPLACE 0xd /* ${var/pattern/replacement} */
488#define VSREPLACEALL 0xe /* ${var//pattern/replacement} */
489#endif
Denis Vlasenko5651bfc2007-02-23 21:08:58 +0000490
Denis Vlasenko6ca409e2007-08-12 20:58:27 +0000491static const char dolatstr[] ALIGN1 = {
492 CTLVAR, VSNORMAL|VSQUOTE, '@', '=', '\0'
493};
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +0000494
Denis Vlasenko559691a2008-10-05 18:39:31 +0000495#define NCMD 0
496#define NPIPE 1
497#define NREDIR 2
498#define NBACKGND 3
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000499#define NSUBSHELL 4
Denis Vlasenko559691a2008-10-05 18:39:31 +0000500#define NAND 5
501#define NOR 6
502#define NSEMI 7
503#define NIF 8
504#define NWHILE 9
505#define NUNTIL 10
506#define NFOR 11
507#define NCASE 12
508#define NCLIST 13
509#define NDEFUN 14
510#define NARG 15
511#define NTO 16
512#if ENABLE_ASH_BASH_COMPAT
513#define NTO2 17
514#endif
515#define NCLOBBER 18
516#define NFROM 19
517#define NFROMTO 20
518#define NAPPEND 21
519#define NTOFD 22
520#define NFROMFD 23
521#define NHERE 24
522#define NXHERE 25
523#define NNOT 26
Denis Vlasenko340299a2008-11-21 10:36:36 +0000524#define N_NUMBER 27
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000525
526union node;
527
528struct ncmd {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000529 smallint type; /* Nxxxx */
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000530 union node *assign;
531 union node *args;
532 union node *redirect;
533};
534
535struct npipe {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000536 smallint type;
537 smallint pipe_backgnd;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000538 struct nodelist *cmdlist;
539};
540
541struct nredir {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000542 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000543 union node *n;
544 union node *redirect;
545};
546
547struct nbinary {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000548 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000549 union node *ch1;
550 union node *ch2;
551};
552
553struct nif {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000554 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000555 union node *test;
556 union node *ifpart;
557 union node *elsepart;
558};
559
560struct nfor {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000561 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000562 union node *args;
563 union node *body;
564 char *var;
565};
566
567struct ncase {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000568 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000569 union node *expr;
570 union node *cases;
571};
572
573struct nclist {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000574 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000575 union node *next;
576 union node *pattern;
577 union node *body;
578};
579
580struct narg {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000581 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000582 union node *next;
583 char *text;
584 struct nodelist *backquote;
585};
586
Denis Vlasenko559691a2008-10-05 18:39:31 +0000587/* nfile and ndup layout must match!
588 * NTOFD (>&fdnum) uses ndup structure, but we may discover mid-flight
589 * that it is actually NTO2 (>&file), and change its type.
590 */
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000591struct nfile {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000592 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000593 union node *next;
594 int fd;
Denis Vlasenko559691a2008-10-05 18:39:31 +0000595 int _unused_dupfd;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000596 union node *fname;
597 char *expfname;
598};
599
600struct ndup {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000601 smallint type;
Denis Vlasenko559691a2008-10-05 18:39:31 +0000602 union node *next;
603 int fd;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000604 int dupfd;
605 union node *vname;
Denis Vlasenko559691a2008-10-05 18:39:31 +0000606 char *_unused_expfname;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000607};
608
609struct nhere {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000610 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000611 union node *next;
612 int fd;
613 union node *doc;
614};
615
616struct nnot {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000617 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000618 union node *com;
619};
620
621union node {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000622 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000623 struct ncmd ncmd;
624 struct npipe npipe;
625 struct nredir nredir;
626 struct nbinary nbinary;
627 struct nif nif;
628 struct nfor nfor;
629 struct ncase ncase;
630 struct nclist nclist;
631 struct narg narg;
632 struct nfile nfile;
633 struct ndup ndup;
634 struct nhere nhere;
635 struct nnot nnot;
636};
637
Denys Vlasenko86e83ec2009-07-23 22:07:07 +0200638/*
639 * NODE_EOF is returned by parsecmd when it encounters an end of file.
640 * It must be distinct from NULL.
641 */
642#define NODE_EOF ((union node *) -1L)
643
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000644struct nodelist {
645 struct nodelist *next;
646 union node *n;
647};
648
649struct funcnode {
650 int count;
651 union node n;
652};
653
Denis Vlasenko5651bfc2007-02-23 21:08:58 +0000654/*
655 * Free a parse tree.
656 */
657static void
658freefunc(struct funcnode *f)
659{
660 if (f && --f->count < 0)
661 free(f);
662}
663
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000664
665/* ============ Debugging output */
666
667#if DEBUG
668
669static FILE *tracefile;
670
671static void
672trace_printf(const char *fmt, ...)
673{
674 va_list va;
675
676 if (debug != 1)
677 return;
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000678 if (DEBUG_TIME)
679 fprintf(tracefile, "%u ", (int) time(NULL));
680 if (DEBUG_PID)
681 fprintf(tracefile, "[%u] ", (int) getpid());
682 if (DEBUG_SIG)
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200683 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000684 va_start(va, fmt);
685 vfprintf(tracefile, fmt, va);
686 va_end(va);
687}
688
689static void
690trace_vprintf(const char *fmt, va_list va)
691{
692 if (debug != 1)
693 return;
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000694 if (DEBUG_TIME)
695 fprintf(tracefile, "%u ", (int) time(NULL));
696 if (DEBUG_PID)
697 fprintf(tracefile, "[%u] ", (int) getpid());
698 if (DEBUG_SIG)
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200699 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000700 vfprintf(tracefile, fmt, va);
701}
702
703static void
704trace_puts(const char *s)
705{
706 if (debug != 1)
707 return;
708 fputs(s, tracefile);
709}
710
711static void
712trace_puts_quoted(char *s)
713{
714 char *p;
715 char c;
716
717 if (debug != 1)
718 return;
719 putc('"', tracefile);
720 for (p = s; *p; p++) {
Denys Vlasenkocd716832009-11-28 22:14:02 +0100721 switch ((unsigned char)*p) {
722 case '\n': c = 'n'; goto backslash;
723 case '\t': c = 't'; goto backslash;
724 case '\r': c = 'r'; goto backslash;
725 case '\"': c = '\"'; goto backslash;
726 case '\\': c = '\\'; goto backslash;
727 case CTLESC: c = 'e'; goto backslash;
728 case CTLVAR: c = 'v'; goto backslash;
729 case CTLVAR+CTLQUOTE: c = 'V'; goto backslash;
730 case CTLBACKQ: c = 'q'; goto backslash;
731 case CTLBACKQ+CTLQUOTE: c = 'Q'; goto backslash;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000732 backslash:
733 putc('\\', tracefile);
734 putc(c, tracefile);
735 break;
736 default:
737 if (*p >= ' ' && *p <= '~')
738 putc(*p, tracefile);
739 else {
740 putc('\\', tracefile);
Denys Vlasenkocd716832009-11-28 22:14:02 +0100741 putc((*p >> 6) & 03, tracefile);
742 putc((*p >> 3) & 07, tracefile);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000743 putc(*p & 07, tracefile);
744 }
745 break;
746 }
747 }
748 putc('"', tracefile);
749}
750
751static void
752trace_puts_args(char **ap)
753{
754 if (debug != 1)
755 return;
756 if (!*ap)
757 return;
758 while (1) {
759 trace_puts_quoted(*ap);
760 if (!*++ap) {
761 putc('\n', tracefile);
762 break;
763 }
764 putc(' ', tracefile);
765 }
766}
767
768static void
769opentrace(void)
770{
771 char s[100];
772#ifdef O_APPEND
773 int flags;
774#endif
775
776 if (debug != 1) {
777 if (tracefile)
778 fflush(tracefile);
779 /* leave open because libedit might be using it */
780 return;
781 }
782 strcpy(s, "./trace");
783 if (tracefile) {
784 if (!freopen(s, "a", tracefile)) {
785 fprintf(stderr, "Can't re-open %s\n", s);
786 debug = 0;
787 return;
788 }
789 } else {
790 tracefile = fopen(s, "a");
791 if (tracefile == NULL) {
792 fprintf(stderr, "Can't open %s\n", s);
793 debug = 0;
794 return;
795 }
796 }
797#ifdef O_APPEND
Denis Vlasenkod37f2222007-08-19 13:42:08 +0000798 flags = fcntl(fileno(tracefile), F_GETFL);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000799 if (flags >= 0)
800 fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
801#endif
802 setlinebuf(tracefile);
803 fputs("\nTracing started.\n", tracefile);
804}
805
806static void
807indent(int amount, char *pfx, FILE *fp)
808{
809 int i;
810
811 for (i = 0; i < amount; i++) {
812 if (pfx && i == amount - 1)
813 fputs(pfx, fp);
814 putc('\t', fp);
815 }
816}
817
818/* little circular references here... */
819static void shtree(union node *n, int ind, char *pfx, FILE *fp);
820
821static void
822sharg(union node *arg, FILE *fp)
823{
824 char *p;
825 struct nodelist *bqlist;
Denys Vlasenkocd716832009-11-28 22:14:02 +0100826 unsigned char subtype;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000827
828 if (arg->type != NARG) {
829 out1fmt("<node type %d>\n", arg->type);
830 abort();
831 }
832 bqlist = arg->narg.backquote;
833 for (p = arg->narg.text; *p; p++) {
Denys Vlasenkocd716832009-11-28 22:14:02 +0100834 switch ((unsigned char)*p) {
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000835 case CTLESC:
836 putc(*++p, fp);
837 break;
838 case CTLVAR:
839 putc('$', fp);
840 putc('{', fp);
841 subtype = *++p;
842 if (subtype == VSLENGTH)
843 putc('#', fp);
844
845 while (*p != '=')
846 putc(*p++, fp);
847
848 if (subtype & VSNUL)
849 putc(':', fp);
850
851 switch (subtype & VSTYPE) {
852 case VSNORMAL:
853 putc('}', fp);
854 break;
855 case VSMINUS:
856 putc('-', fp);
857 break;
858 case VSPLUS:
859 putc('+', fp);
860 break;
861 case VSQUESTION:
862 putc('?', fp);
863 break;
864 case VSASSIGN:
865 putc('=', fp);
866 break;
867 case VSTRIMLEFT:
868 putc('#', fp);
869 break;
870 case VSTRIMLEFTMAX:
871 putc('#', fp);
872 putc('#', fp);
873 break;
874 case VSTRIMRIGHT:
875 putc('%', fp);
876 break;
877 case VSTRIMRIGHTMAX:
878 putc('%', fp);
879 putc('%', fp);
880 break;
881 case VSLENGTH:
882 break;
883 default:
884 out1fmt("<subtype %d>", subtype);
885 }
886 break;
887 case CTLENDVAR:
888 putc('}', fp);
889 break;
890 case CTLBACKQ:
891 case CTLBACKQ|CTLQUOTE:
892 putc('$', fp);
893 putc('(', fp);
894 shtree(bqlist->n, -1, NULL, fp);
895 putc(')', fp);
896 break;
897 default:
898 putc(*p, fp);
899 break;
900 }
901 }
902}
903
Denys Vlasenko641dd7b2009-06-11 19:30:19 +0200904static void
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000905shcmd(union node *cmd, FILE *fp)
906{
907 union node *np;
908 int first;
909 const char *s;
910 int dftfd;
911
912 first = 1;
913 for (np = cmd->ncmd.args; np; np = np->narg.next) {
Denis Vlasenko40ba9982007-07-14 00:48:29 +0000914 if (!first)
915 putc(' ', fp);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000916 sharg(np, fp);
917 first = 0;
918 }
919 for (np = cmd->ncmd.redirect; np; np = np->nfile.next) {
Denis Vlasenko40ba9982007-07-14 00:48:29 +0000920 if (!first)
921 putc(' ', fp);
922 dftfd = 0;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000923 switch (np->nfile.type) {
Denis Vlasenko40ba9982007-07-14 00:48:29 +0000924 case NTO: s = ">>"+1; dftfd = 1; break;
925 case NCLOBBER: s = ">|"; dftfd = 1; break;
926 case NAPPEND: s = ">>"; dftfd = 1; break;
Denis Vlasenko559691a2008-10-05 18:39:31 +0000927#if ENABLE_ASH_BASH_COMPAT
928 case NTO2:
929#endif
Denis Vlasenko40ba9982007-07-14 00:48:29 +0000930 case NTOFD: s = ">&"; dftfd = 1; break;
Denis Vlasenko559691a2008-10-05 18:39:31 +0000931 case NFROM: s = "<"; break;
Denis Vlasenko40ba9982007-07-14 00:48:29 +0000932 case NFROMFD: s = "<&"; break;
933 case NFROMTO: s = "<>"; break;
934 default: s = "*error*"; break;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000935 }
936 if (np->nfile.fd != dftfd)
937 fprintf(fp, "%d", np->nfile.fd);
938 fputs(s, fp);
939 if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
940 fprintf(fp, "%d", np->ndup.dupfd);
941 } else {
942 sharg(np->nfile.fname, fp);
943 }
944 first = 0;
945 }
946}
947
948static void
949shtree(union node *n, int ind, char *pfx, FILE *fp)
950{
951 struct nodelist *lp;
952 const char *s;
953
954 if (n == NULL)
955 return;
956
957 indent(ind, pfx, fp);
Denys Vlasenko86e83ec2009-07-23 22:07:07 +0200958
959 if (n == NODE_EOF) {
960 fputs("<EOF>", fp);
961 return;
962 }
963
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000964 switch (n->type) {
965 case NSEMI:
966 s = "; ";
967 goto binop;
968 case NAND:
969 s = " && ";
970 goto binop;
971 case NOR:
972 s = " || ";
973 binop:
974 shtree(n->nbinary.ch1, ind, NULL, fp);
975 /* if (ind < 0) */
976 fputs(s, fp);
977 shtree(n->nbinary.ch2, ind, NULL, fp);
978 break;
979 case NCMD:
980 shcmd(n, fp);
981 if (ind >= 0)
982 putc('\n', fp);
983 break;
984 case NPIPE:
985 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
Denys Vlasenko7cee00e2009-07-24 01:08:03 +0200986 shtree(lp->n, 0, NULL, fp);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000987 if (lp->next)
988 fputs(" | ", fp);
989 }
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000990 if (n->npipe.pipe_backgnd)
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000991 fputs(" &", fp);
992 if (ind >= 0)
993 putc('\n', fp);
994 break;
995 default:
996 fprintf(fp, "<node type %d>", n->type);
997 if (ind >= 0)
998 putc('\n', fp);
999 break;
1000 }
1001}
1002
1003static void
1004showtree(union node *n)
1005{
1006 trace_puts("showtree called\n");
Denys Vlasenko883cea42009-07-11 15:31:59 +02001007 shtree(n, 1, NULL, stderr);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00001008}
1009
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00001010#endif /* DEBUG */
1011
1012
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00001013/* ============ Parser data */
1014
1015/*
Denis Vlasenkob012b102007-02-19 22:43:01 +00001016 * ash_vmsg() needs parsefile->fd, hence parsefile definition is moved up.
1017 */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001018struct strlist {
1019 struct strlist *next;
1020 char *text;
1021};
1022
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00001023struct alias;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00001024
Denis Vlasenkob012b102007-02-19 22:43:01 +00001025struct strpush {
1026 struct strpush *prev; /* preceding string on stack */
Denis Vlasenko41eb3002008-11-28 03:42:31 +00001027 char *prev_string;
1028 int prev_left_in_line;
Denis Vlasenkob012b102007-02-19 22:43:01 +00001029#if ENABLE_ASH_ALIAS
1030 struct alias *ap; /* if push was associated with an alias */
1031#endif
1032 char *string; /* remember the string since it may change */
1033};
1034
1035struct parsefile {
1036 struct parsefile *prev; /* preceding file on stack */
1037 int linno; /* current line */
1038 int fd; /* file descriptor (or -1 if string) */
Denis Vlasenko41eb3002008-11-28 03:42:31 +00001039 int left_in_line; /* number of chars left in this line */
1040 int left_in_buffer; /* number of chars left in this buffer past the line */
1041 char *next_to_pgetc; /* next char in buffer */
Denis Vlasenkob012b102007-02-19 22:43:01 +00001042 char *buf; /* input buffer */
1043 struct strpush *strpush; /* for pushing strings at this level */
1044 struct strpush basestrpush; /* so pushing one is fast */
1045};
1046
Denis Vlasenko448d30e2008-06-27 00:24:11 +00001047static struct parsefile basepf; /* top level input file */
Denis Vlasenkob07a4962008-06-22 13:16:23 +00001048static struct parsefile *g_parsefile = &basepf; /* current input file */
Denis Vlasenkob012b102007-02-19 22:43:01 +00001049static int startlinno; /* line # where last token started */
1050static char *commandname; /* currently executing command */
1051static struct strlist *cmdenviron; /* environment for builtin command */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00001052static uint8_t exitstatus; /* exit status of last command */
Denis Vlasenkob012b102007-02-19 22:43:01 +00001053
1054
1055/* ============ Message printing */
1056
1057static void
1058ash_vmsg(const char *msg, va_list ap)
1059{
1060 fprintf(stderr, "%s: ", arg0);
1061 if (commandname) {
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00001062 if (strcmp(arg0, commandname))
1063 fprintf(stderr, "%s: ", commandname);
Denis Vlasenkob07a4962008-06-22 13:16:23 +00001064 if (!iflag || g_parsefile->fd)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00001065 fprintf(stderr, "line %d: ", startlinno);
Eric Andersenc470f442003-07-28 09:56:35 +00001066 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00001067 vfprintf(stderr, msg, ap);
1068 outcslow('\n', stderr);
Eric Andersenc470f442003-07-28 09:56:35 +00001069}
Denis Vlasenkob012b102007-02-19 22:43:01 +00001070
1071/*
1072 * Exverror is called to raise the error exception. If the second argument
1073 * is not NULL then error prints an error message using printf style
1074 * formatting. It then raises the error exception.
1075 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001076static void ash_vmsg_and_raise(int, const char *, va_list) NORETURN;
Denis Vlasenkob012b102007-02-19 22:43:01 +00001077static void
1078ash_vmsg_and_raise(int cond, const char *msg, va_list ap)
Eric Andersenc470f442003-07-28 09:56:35 +00001079{
Denis Vlasenkob012b102007-02-19 22:43:01 +00001080#if DEBUG
1081 if (msg) {
1082 TRACE(("ash_vmsg_and_raise(%d, \"", cond));
1083 TRACEV((msg, ap));
1084 TRACE(("\") pid=%d\n", getpid()));
1085 } else
1086 TRACE(("ash_vmsg_and_raise(%d, NULL) pid=%d\n", cond, getpid()));
1087 if (msg)
1088#endif
1089 ash_vmsg(msg, ap);
1090
1091 flush_stdout_stderr();
1092 raise_exception(cond);
1093 /* NOTREACHED */
Eric Andersenc470f442003-07-28 09:56:35 +00001094}
Denis Vlasenkob012b102007-02-19 22:43:01 +00001095
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001096static void ash_msg_and_raise_error(const char *, ...) NORETURN;
Denis Vlasenkob012b102007-02-19 22:43:01 +00001097static void
1098ash_msg_and_raise_error(const char *msg, ...)
1099{
1100 va_list ap;
1101
1102 va_start(ap, msg);
1103 ash_vmsg_and_raise(EXERROR, msg, ap);
1104 /* NOTREACHED */
1105 va_end(ap);
1106}
1107
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00001108static void raise_error_syntax(const char *) NORETURN;
1109static void
1110raise_error_syntax(const char *msg)
1111{
1112 ash_msg_and_raise_error("syntax error: %s", msg);
1113 /* NOTREACHED */
1114}
1115
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001116static void ash_msg_and_raise(int, const char *, ...) NORETURN;
Denis Vlasenkob012b102007-02-19 22:43:01 +00001117static void
1118ash_msg_and_raise(int cond, const char *msg, ...)
1119{
1120 va_list ap;
1121
1122 va_start(ap, msg);
1123 ash_vmsg_and_raise(cond, msg, ap);
1124 /* NOTREACHED */
1125 va_end(ap);
1126}
1127
1128/*
1129 * error/warning routines for external builtins
1130 */
1131static void
1132ash_msg(const char *fmt, ...)
1133{
1134 va_list ap;
1135
1136 va_start(ap, fmt);
1137 ash_vmsg(fmt, ap);
1138 va_end(ap);
1139}
1140
1141/*
1142 * Return a string describing an error. The returned string may be a
1143 * pointer to a static buffer that will be overwritten on the next call.
1144 * Action describes the operation that got the error.
1145 */
1146static const char *
1147errmsg(int e, const char *em)
1148{
1149 if (e == ENOENT || e == ENOTDIR) {
1150 return em;
1151 }
1152 return strerror(e);
1153}
1154
1155
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001156/* ============ Memory allocation */
1157
Denys Vlasenkoe7670ff2009-10-11 00:45:25 +02001158#if 0
1159/* I consider these wrappers nearly useless:
1160 * ok, they return you to nearest exception handler, but
1161 * how much memory do you leak in the process, making
1162 * memory starvation worse?
1163 */
1164static void *
1165ckrealloc(void * p, size_t nbytes)
1166{
1167 p = realloc(p, nbytes);
1168 if (!p)
1169 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1170 return p;
1171}
1172
1173static void *
1174ckmalloc(size_t nbytes)
1175{
1176 return ckrealloc(NULL, nbytes);
1177}
1178
1179static void *
1180ckzalloc(size_t nbytes)
1181{
1182 return memset(ckmalloc(nbytes), 0, nbytes);
1183}
1184
1185static char *
1186ckstrdup(const char *s)
1187{
1188 char *p = strdup(s);
1189 if (!p)
1190 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1191 return p;
1192}
1193#else
1194/* Using bbox equivalents. They exit if out of memory */
1195# define ckrealloc xrealloc
1196# define ckmalloc xmalloc
1197# define ckzalloc xzalloc
1198# define ckstrdup xstrdup
1199#endif
1200
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001201/*
1202 * It appears that grabstackstr() will barf with such alignments
1203 * because stalloc() will return a string allocated in a new stackblock.
1204 */
1205#define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
1206enum {
1207 /* Most machines require the value returned from malloc to be aligned
1208 * in some way. The following macro will get this right
1209 * on many machines. */
Denys Vlasenko0e5e4ea2009-10-11 00:36:20 +02001210 SHELL_SIZE = sizeof(union { int i; char *cp; double d; }) - 1,
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001211 /* Minimum size of a block */
Denis Vlasenko01631112007-12-16 17:20:38 +00001212 MINSIZE = SHELL_ALIGN(504),
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001213};
1214
1215struct stack_block {
1216 struct stack_block *prev;
1217 char space[MINSIZE];
1218};
1219
1220struct stackmark {
1221 struct stack_block *stackp;
1222 char *stacknxt;
1223 size_t stacknleft;
1224 struct stackmark *marknext;
1225};
1226
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001227
Denis Vlasenko01631112007-12-16 17:20:38 +00001228struct globals_memstack {
1229 struct stack_block *g_stackp; // = &stackbase;
1230 struct stackmark *markp;
1231 char *g_stacknxt; // = stackbase.space;
1232 char *sstrend; // = stackbase.space + MINSIZE;
1233 size_t g_stacknleft; // = MINSIZE;
1234 int herefd; // = -1;
1235 struct stack_block stackbase;
1236};
Denis Vlasenko574f2f42008-02-27 18:41:59 +00001237extern struct globals_memstack *const ash_ptr_to_globals_memstack;
1238#define G_memstack (*ash_ptr_to_globals_memstack)
Denis Vlasenko01631112007-12-16 17:20:38 +00001239#define g_stackp (G_memstack.g_stackp )
1240#define markp (G_memstack.markp )
1241#define g_stacknxt (G_memstack.g_stacknxt )
1242#define sstrend (G_memstack.sstrend )
1243#define g_stacknleft (G_memstack.g_stacknleft)
1244#define herefd (G_memstack.herefd )
1245#define stackbase (G_memstack.stackbase )
1246#define INIT_G_memstack() do { \
Denis Vlasenko574f2f42008-02-27 18:41:59 +00001247 (*(struct globals_memstack**)&ash_ptr_to_globals_memstack) = xzalloc(sizeof(G_memstack)); \
1248 barrier(); \
Denis Vlasenko01631112007-12-16 17:20:38 +00001249 g_stackp = &stackbase; \
1250 g_stacknxt = stackbase.space; \
1251 g_stacknleft = MINSIZE; \
1252 sstrend = stackbase.space + MINSIZE; \
1253 herefd = -1; \
1254} while (0)
1255
Denys Vlasenkoe7670ff2009-10-11 00:45:25 +02001256
Denis Vlasenko01631112007-12-16 17:20:38 +00001257#define stackblock() ((void *)g_stacknxt)
1258#define stackblocksize() g_stacknleft
1259
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001260/*
1261 * Parse trees for commands are allocated in lifo order, so we use a stack
1262 * to make this more efficient, and also to avoid all sorts of exception
1263 * handling code to handle interrupts in the middle of a parse.
1264 *
1265 * The size 504 was chosen because the Ultrix malloc handles that size
1266 * well.
1267 */
1268static void *
1269stalloc(size_t nbytes)
1270{
1271 char *p;
1272 size_t aligned;
1273
1274 aligned = SHELL_ALIGN(nbytes);
Denis Vlasenko01631112007-12-16 17:20:38 +00001275 if (aligned > g_stacknleft) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001276 size_t len;
1277 size_t blocksize;
1278 struct stack_block *sp;
1279
1280 blocksize = aligned;
1281 if (blocksize < MINSIZE)
1282 blocksize = MINSIZE;
1283 len = sizeof(struct stack_block) - MINSIZE + blocksize;
1284 if (len < blocksize)
1285 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1286 INT_OFF;
1287 sp = ckmalloc(len);
Denis Vlasenko01631112007-12-16 17:20:38 +00001288 sp->prev = g_stackp;
1289 g_stacknxt = sp->space;
1290 g_stacknleft = blocksize;
1291 sstrend = g_stacknxt + blocksize;
1292 g_stackp = sp;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001293 INT_ON;
1294 }
Denis Vlasenko01631112007-12-16 17:20:38 +00001295 p = g_stacknxt;
1296 g_stacknxt += aligned;
1297 g_stacknleft -= aligned;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001298 return p;
1299}
1300
Denis Vlasenko597906c2008-02-20 16:38:54 +00001301static void *
1302stzalloc(size_t nbytes)
1303{
1304 return memset(stalloc(nbytes), 0, nbytes);
1305}
1306
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001307static void
1308stunalloc(void *p)
1309{
1310#if DEBUG
Denis Vlasenko01631112007-12-16 17:20:38 +00001311 if (!p || (g_stacknxt < (char *)p) || ((char *)p < g_stackp->space)) {
Bernhard Reutner-Fischer5e25ddb2008-05-19 09:48:17 +00001312 write(STDERR_FILENO, "stunalloc\n", 10);
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001313 abort();
1314 }
1315#endif
Denis Vlasenko01631112007-12-16 17:20:38 +00001316 g_stacknleft += g_stacknxt - (char *)p;
1317 g_stacknxt = p;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001318}
1319
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001320/*
1321 * Like strdup but works with the ash stack.
1322 */
1323static char *
1324ststrdup(const char *p)
1325{
1326 size_t len = strlen(p) + 1;
1327 return memcpy(stalloc(len), p, len);
1328}
1329
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001330static void
1331setstackmark(struct stackmark *mark)
1332{
Denis Vlasenko01631112007-12-16 17:20:38 +00001333 mark->stackp = g_stackp;
1334 mark->stacknxt = g_stacknxt;
1335 mark->stacknleft = g_stacknleft;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001336 mark->marknext = markp;
1337 markp = mark;
1338}
1339
1340static void
1341popstackmark(struct stackmark *mark)
1342{
1343 struct stack_block *sp;
1344
Denis Vlasenko93ebd4f2007-03-13 20:55:36 +00001345 if (!mark->stackp)
1346 return;
1347
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001348 INT_OFF;
1349 markp = mark->marknext;
Denis Vlasenko01631112007-12-16 17:20:38 +00001350 while (g_stackp != mark->stackp) {
1351 sp = g_stackp;
1352 g_stackp = sp->prev;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001353 free(sp);
1354 }
Denis Vlasenko01631112007-12-16 17:20:38 +00001355 g_stacknxt = mark->stacknxt;
1356 g_stacknleft = mark->stacknleft;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001357 sstrend = mark->stacknxt + mark->stacknleft;
1358 INT_ON;
1359}
1360
1361/*
1362 * When the parser reads in a string, it wants to stick the string on the
1363 * stack and only adjust the stack pointer when it knows how big the
1364 * string is. Stackblock (defined in stack.h) returns a pointer to a block
1365 * of space on top of the stack and stackblocklen returns the length of
1366 * this block. Growstackblock will grow this space by at least one byte,
1367 * possibly moving it (like realloc). Grabstackblock actually allocates the
1368 * part of the block that has been used.
1369 */
1370static void
1371growstackblock(void)
1372{
1373 size_t newlen;
1374
Denis Vlasenko01631112007-12-16 17:20:38 +00001375 newlen = g_stacknleft * 2;
1376 if (newlen < g_stacknleft)
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001377 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1378 if (newlen < 128)
1379 newlen += 128;
1380
Denis Vlasenko01631112007-12-16 17:20:38 +00001381 if (g_stacknxt == g_stackp->space && g_stackp != &stackbase) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001382 struct stack_block *oldstackp;
1383 struct stackmark *xmark;
1384 struct stack_block *sp;
1385 struct stack_block *prevstackp;
1386 size_t grosslen;
1387
1388 INT_OFF;
Denis Vlasenko01631112007-12-16 17:20:38 +00001389 oldstackp = g_stackp;
1390 sp = g_stackp;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001391 prevstackp = sp->prev;
1392 grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
1393 sp = ckrealloc(sp, grosslen);
1394 sp->prev = prevstackp;
Denis Vlasenko01631112007-12-16 17:20:38 +00001395 g_stackp = sp;
1396 g_stacknxt = sp->space;
1397 g_stacknleft = newlen;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001398 sstrend = sp->space + newlen;
1399
1400 /*
1401 * Stack marks pointing to the start of the old block
1402 * must be relocated to point to the new block
1403 */
1404 xmark = markp;
1405 while (xmark != NULL && xmark->stackp == oldstackp) {
Denis Vlasenko01631112007-12-16 17:20:38 +00001406 xmark->stackp = g_stackp;
1407 xmark->stacknxt = g_stacknxt;
1408 xmark->stacknleft = g_stacknleft;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001409 xmark = xmark->marknext;
1410 }
1411 INT_ON;
1412 } else {
Denis Vlasenko01631112007-12-16 17:20:38 +00001413 char *oldspace = g_stacknxt;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00001414 size_t oldlen = g_stacknleft;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001415 char *p = stalloc(newlen);
1416
1417 /* free the space we just allocated */
Denis Vlasenko01631112007-12-16 17:20:38 +00001418 g_stacknxt = memcpy(p, oldspace, oldlen);
1419 g_stacknleft += newlen;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001420 }
1421}
1422
1423static void
1424grabstackblock(size_t len)
1425{
1426 len = SHELL_ALIGN(len);
Denis Vlasenko01631112007-12-16 17:20:38 +00001427 g_stacknxt += len;
1428 g_stacknleft -= len;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001429}
1430
1431/*
1432 * The following routines are somewhat easier to use than the above.
1433 * The user declares a variable of type STACKSTR, which may be declared
1434 * to be a register. The macro STARTSTACKSTR initializes things. Then
1435 * the user uses the macro STPUTC to add characters to the string. In
1436 * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
1437 * grown as necessary. When the user is done, she can just leave the
1438 * string there and refer to it using stackblock(). Or she can allocate
1439 * the space for it using grabstackstr(). If it is necessary to allow
1440 * someone else to use the stack temporarily and then continue to grow
1441 * the string, the user should use grabstack to allocate the space, and
1442 * then call ungrabstr(p) to return to the previous mode of operation.
1443 *
1444 * USTPUTC is like STPUTC except that it doesn't check for overflow.
1445 * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
1446 * is space for at least one character.
1447 */
1448static void *
1449growstackstr(void)
1450{
1451 size_t len = stackblocksize();
1452 if (herefd >= 0 && len >= 1024) {
1453 full_write(herefd, stackblock(), len);
1454 return stackblock();
1455 }
1456 growstackblock();
Denis Vlasenko29eb3592008-05-18 14:06:08 +00001457 return (char *)stackblock() + len;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001458}
1459
1460/*
1461 * Called from CHECKSTRSPACE.
1462 */
1463static char *
1464makestrspace(size_t newlen, char *p)
1465{
Denis Vlasenko01631112007-12-16 17:20:38 +00001466 size_t len = p - g_stacknxt;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001467 size_t size = stackblocksize();
1468
1469 for (;;) {
1470 size_t nleft;
1471
1472 size = stackblocksize();
1473 nleft = size - len;
1474 if (nleft >= newlen)
1475 break;
1476 growstackblock();
1477 }
Denis Vlasenko29eb3592008-05-18 14:06:08 +00001478 return (char *)stackblock() + len;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001479}
1480
1481static char *
1482stack_nputstr(const char *s, size_t n, char *p)
1483{
1484 p = makestrspace(n, p);
Denis Vlasenko29eb3592008-05-18 14:06:08 +00001485 p = (char *)memcpy(p, s, n) + n;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001486 return p;
1487}
1488
1489static char *
1490stack_putstr(const char *s, char *p)
1491{
1492 return stack_nputstr(s, strlen(s), p);
1493}
1494
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001495static char *
1496_STPUTC(int c, char *p)
1497{
1498 if (p == sstrend)
1499 p = growstackstr();
1500 *p++ = c;
1501 return p;
1502}
1503
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00001504#define STARTSTACKSTR(p) ((p) = stackblock())
1505#define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
Denis Vlasenko843cbd52008-06-27 00:23:18 +00001506#define CHECKSTRSPACE(n, p) do { \
1507 char *q = (p); \
1508 size_t l = (n); \
1509 size_t m = sstrend - q; \
1510 if (l > m) \
1511 (p) = makestrspace(l, q); \
1512} while (0)
Denis Vlasenkoef527f52008-06-23 01:52:30 +00001513#define USTPUTC(c, p) (*(p)++ = (c))
Denis Vlasenko843cbd52008-06-27 00:23:18 +00001514#define STACKSTRNUL(p) do { \
1515 if ((p) == sstrend) \
1516 (p) = growstackstr(); \
1517 *(p) = '\0'; \
1518} while (0)
Denis Vlasenkoef527f52008-06-23 01:52:30 +00001519#define STUNPUTC(p) (--(p))
1520#define STTOPC(p) ((p)[-1])
1521#define STADJUST(amount, p) ((p) += (amount))
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001522
1523#define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
Denis Vlasenkoef527f52008-06-23 01:52:30 +00001524#define ungrabstackstr(s, p) stunalloc(s)
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001525#define stackstrend() ((void *)sstrend)
1526
1527
1528/* ============ String helpers */
1529
1530/*
1531 * prefix -- see if pfx is a prefix of string.
1532 */
1533static char *
1534prefix(const char *string, const char *pfx)
1535{
1536 while (*pfx) {
1537 if (*pfx++ != *string++)
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00001538 return NULL;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001539 }
1540 return (char *) string;
1541}
1542
1543/*
1544 * Check for a valid number. This should be elsewhere.
1545 */
1546static int
1547is_number(const char *p)
1548{
1549 do {
1550 if (!isdigit(*p))
1551 return 0;
1552 } while (*++p != '\0');
1553 return 1;
1554}
1555
1556/*
1557 * Convert a string of digits to an integer, printing an error message on
1558 * failure.
1559 */
1560static int
1561number(const char *s)
1562{
1563 if (!is_number(s))
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02001564 ash_msg_and_raise_error(msg_illnum, s);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001565 return atoi(s);
1566}
1567
1568/*
1569 * Produce a possibly single quoted string suitable as input to the shell.
1570 * The return string is allocated on the stack.
1571 */
1572static char *
1573single_quote(const char *s)
1574{
1575 char *p;
1576
1577 STARTSTACKSTR(p);
1578
1579 do {
1580 char *q;
1581 size_t len;
1582
1583 len = strchrnul(s, '\'') - s;
1584
1585 q = p = makestrspace(len + 3, p);
1586
1587 *q++ = '\'';
Denis Vlasenko29eb3592008-05-18 14:06:08 +00001588 q = (char *)memcpy(q, s, len) + len;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001589 *q++ = '\'';
1590 s += len;
1591
1592 STADJUST(q - p, p);
1593
Denys Vlasenkocd716832009-11-28 22:14:02 +01001594 if (*s != '\'')
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001595 break;
Denys Vlasenkocd716832009-11-28 22:14:02 +01001596 len = 0;
1597 do len++; while (*++s == '\'');
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001598
1599 q = p = makestrspace(len + 3, p);
1600
1601 *q++ = '"';
Denys Vlasenkocd716832009-11-28 22:14:02 +01001602 q = (char *)memcpy(q, s - len, len) + len;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001603 *q++ = '"';
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001604
1605 STADJUST(q - p, p);
1606 } while (*s);
1607
Denys Vlasenkocd716832009-11-28 22:14:02 +01001608 USTPUTC('\0', p);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001609
1610 return stackblock();
1611}
1612
1613
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00001614/* ============ nextopt */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001615
1616static char **argptr; /* argument list for builtin commands */
1617static char *optionarg; /* set by nextopt (like getopt) */
1618static char *optptr; /* used by nextopt */
1619
1620/*
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001621 * XXX - should get rid of. Have all builtins use getopt(3).
1622 * The library getopt must have the BSD extension static variable
1623 * "optreset", otherwise it can't be used within the shell safely.
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001624 *
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001625 * Standard option processing (a la getopt) for builtin routines.
1626 * The only argument that is passed to nextopt is the option string;
1627 * the other arguments are unnecessary. It returns the character,
1628 * or '\0' on end of input.
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001629 */
1630static int
1631nextopt(const char *optstring)
1632{
1633 char *p;
1634 const char *q;
1635 char c;
1636
1637 p = optptr;
1638 if (p == NULL || *p == '\0') {
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001639 /* We ate entire "-param", take next one */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001640 p = *argptr;
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001641 if (p == NULL)
1642 return '\0';
1643 if (*p != '-')
1644 return '\0';
1645 if (*++p == '\0') /* just "-" ? */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001646 return '\0';
1647 argptr++;
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001648 if (LONE_DASH(p)) /* "--" ? */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001649 return '\0';
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001650 /* p => next "-param" */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001651 }
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001652 /* p => some option char in the middle of a "-param" */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001653 c = *p++;
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +00001654 for (q = optstring; *q != c;) {
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001655 if (*q == '\0')
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00001656 ash_msg_and_raise_error("illegal option -%c", c);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001657 if (*++q == ':')
1658 q++;
1659 }
1660 if (*++q == ':') {
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001661 if (*p == '\0') {
1662 p = *argptr++;
1663 if (p == NULL)
1664 ash_msg_and_raise_error("no arg for -%c option", c);
1665 }
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001666 optionarg = p;
1667 p = NULL;
1668 }
1669 optptr = p;
1670 return c;
1671}
1672
1673
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00001674/* ============ Shell variables */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001675
Denis Vlasenko01631112007-12-16 17:20:38 +00001676/*
1677 * The parsefile structure pointed to by the global variable parsefile
1678 * contains information about the current file being read.
1679 */
Denis Vlasenko01631112007-12-16 17:20:38 +00001680struct shparam {
1681 int nparam; /* # of positional parameters (without $0) */
1682#if ENABLE_ASH_GETOPTS
1683 int optind; /* next parameter to be processed by getopts */
1684 int optoff; /* used by getopts */
1685#endif
1686 unsigned char malloced; /* if parameter list dynamically allocated */
1687 char **p; /* parameter list */
1688};
1689
1690/*
1691 * Free the list of positional parameters.
1692 */
1693static void
1694freeparam(volatile struct shparam *param)
1695{
Denis Vlasenko01631112007-12-16 17:20:38 +00001696 if (param->malloced) {
Denis Vlasenko3177ba02008-07-13 20:39:23 +00001697 char **ap, **ap1;
1698 ap = ap1 = param->p;
1699 while (*ap)
1700 free(*ap++);
1701 free(ap1);
Denis Vlasenko01631112007-12-16 17:20:38 +00001702 }
1703}
1704
1705#if ENABLE_ASH_GETOPTS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001706static void FAST_FUNC getoptsreset(const char *value);
Denis Vlasenko01631112007-12-16 17:20:38 +00001707#endif
1708
1709struct var {
1710 struct var *next; /* next entry in hash list */
1711 int flags; /* flags are defined above */
1712 const char *text; /* name=value */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001713 void (*func)(const char *) FAST_FUNC; /* function to be called when */
Denis Vlasenko01631112007-12-16 17:20:38 +00001714 /* the variable gets set/unset */
1715};
1716
1717struct localvar {
1718 struct localvar *next; /* next local variable in list */
1719 struct var *vp; /* the variable that was made local */
1720 int flags; /* saved flags */
1721 const char *text; /* saved text */
1722};
1723
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001724/* flags */
1725#define VEXPORT 0x01 /* variable is exported */
1726#define VREADONLY 0x02 /* variable cannot be modified */
1727#define VSTRFIXED 0x04 /* variable struct is statically allocated */
1728#define VTEXTFIXED 0x08 /* text is statically allocated */
1729#define VSTACK 0x10 /* text is allocated on the stack */
1730#define VUNSET 0x20 /* the variable is not set */
1731#define VNOFUNC 0x40 /* don't call the callback function */
1732#define VNOSET 0x80 /* do not set variable - just readonly test */
1733#define VNOSAVE 0x100 /* when text is on the heap before setvareq */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00001734#if ENABLE_ASH_RANDOM_SUPPORT
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00001735# define VDYNAMIC 0x200 /* dynamic variable */
1736#else
1737# define VDYNAMIC 0
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001738#endif
1739
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001740#ifdef IFS_BROKEN
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00001741static const char defifsvar[] ALIGN1 = "IFS= \t\n";
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001742#define defifs (defifsvar + 4)
1743#else
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00001744static const char defifs[] ALIGN1 = " \t\n";
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001745#endif
1746
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00001747
Denis Vlasenko01631112007-12-16 17:20:38 +00001748/* Need to be before varinit_data[] */
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00001749#if ENABLE_LOCALE_SUPPORT
Denys Vlasenko2634bf32009-06-09 18:40:07 +02001750static void FAST_FUNC
Denis Vlasenkoa8915072007-02-23 21:10:06 +00001751change_lc_all(const char *value)
1752{
1753 if (value && *value != '\0')
1754 setlocale(LC_ALL, value);
1755}
Denys Vlasenko2634bf32009-06-09 18:40:07 +02001756static void FAST_FUNC
Denis Vlasenkoa8915072007-02-23 21:10:06 +00001757change_lc_ctype(const char *value)
1758{
1759 if (value && *value != '\0')
1760 setlocale(LC_CTYPE, value);
1761}
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00001762#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001763#if ENABLE_ASH_MAIL
1764static void chkmail(void);
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001765static void changemail(const char *) FAST_FUNC;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001766#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001767static void changepath(const char *) FAST_FUNC;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001768#if ENABLE_ASH_RANDOM_SUPPORT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001769static void change_random(const char *) FAST_FUNC;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001770#endif
1771
Denis Vlasenko01631112007-12-16 17:20:38 +00001772static const struct {
1773 int flags;
1774 const char *text;
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001775 void (*func)(const char *) FAST_FUNC;
Denis Vlasenko01631112007-12-16 17:20:38 +00001776} varinit_data[] = {
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001777#ifdef IFS_BROKEN
Denis Vlasenko01631112007-12-16 17:20:38 +00001778 { VSTRFIXED|VTEXTFIXED , defifsvar , NULL },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001779#else
Denis Vlasenko01631112007-12-16 17:20:38 +00001780 { VSTRFIXED|VTEXTFIXED|VUNSET, "IFS\0" , NULL },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001781#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001782#if ENABLE_ASH_MAIL
Denis Vlasenko01631112007-12-16 17:20:38 +00001783 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL\0" , changemail },
1784 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH\0", changemail },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001785#endif
Denis Vlasenko01631112007-12-16 17:20:38 +00001786 { VSTRFIXED|VTEXTFIXED , bb_PATH_root_path, changepath },
1787 { VSTRFIXED|VTEXTFIXED , "PS1=$ " , NULL },
1788 { VSTRFIXED|VTEXTFIXED , "PS2=> " , NULL },
1789 { VSTRFIXED|VTEXTFIXED , "PS4=+ " , NULL },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001790#if ENABLE_ASH_GETOPTS
Denis Vlasenko01631112007-12-16 17:20:38 +00001791 { VSTRFIXED|VTEXTFIXED , "OPTIND=1" , getoptsreset },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001792#endif
1793#if ENABLE_ASH_RANDOM_SUPPORT
Denis Vlasenko01631112007-12-16 17:20:38 +00001794 { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM\0", change_random },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001795#endif
1796#if ENABLE_LOCALE_SUPPORT
Denis Vlasenko01631112007-12-16 17:20:38 +00001797 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL\0" , change_lc_all },
1798 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE\0", change_lc_ctype },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001799#endif
1800#if ENABLE_FEATURE_EDITING_SAVEHISTORY
Denis Vlasenko01631112007-12-16 17:20:38 +00001801 { VSTRFIXED|VTEXTFIXED|VUNSET, "HISTFILE\0", NULL },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001802#endif
1803};
1804
Denis Vlasenko0b769642008-07-24 07:54:57 +00001805struct redirtab;
Denis Vlasenko01631112007-12-16 17:20:38 +00001806
1807struct globals_var {
1808 struct shparam shellparam; /* $@ current positional parameters */
1809 struct redirtab *redirlist;
1810 int g_nullredirs;
1811 int preverrout_fd; /* save fd2 before print debug if xflag is set. */
1812 struct var *vartab[VTABSIZE];
1813 struct var varinit[ARRAY_SIZE(varinit_data)];
1814};
Denis Vlasenko574f2f42008-02-27 18:41:59 +00001815extern struct globals_var *const ash_ptr_to_globals_var;
1816#define G_var (*ash_ptr_to_globals_var)
Denis Vlasenko01631112007-12-16 17:20:38 +00001817#define shellparam (G_var.shellparam )
Denis Vlasenko0b769642008-07-24 07:54:57 +00001818//#define redirlist (G_var.redirlist )
Denis Vlasenko01631112007-12-16 17:20:38 +00001819#define g_nullredirs (G_var.g_nullredirs )
1820#define preverrout_fd (G_var.preverrout_fd)
1821#define vartab (G_var.vartab )
1822#define varinit (G_var.varinit )
1823#define INIT_G_var() do { \
Denis Vlasenko6b06cb82008-05-15 21:30:45 +00001824 unsigned i; \
Denis Vlasenko574f2f42008-02-27 18:41:59 +00001825 (*(struct globals_var**)&ash_ptr_to_globals_var) = xzalloc(sizeof(G_var)); \
1826 barrier(); \
Denis Vlasenko01631112007-12-16 17:20:38 +00001827 for (i = 0; i < ARRAY_SIZE(varinit_data); i++) { \
1828 varinit[i].flags = varinit_data[i].flags; \
1829 varinit[i].text = varinit_data[i].text; \
1830 varinit[i].func = varinit_data[i].func; \
1831 } \
1832} while (0)
1833
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001834#define vifs varinit[0]
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001835#if ENABLE_ASH_MAIL
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001836# define vmail (&vifs)[1]
1837# define vmpath (&vmail)[1]
1838# define vpath (&vmpath)[1]
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001839#else
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001840# define vpath (&vifs)[1]
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001841#endif
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001842#define vps1 (&vpath)[1]
1843#define vps2 (&vps1)[1]
1844#define vps4 (&vps2)[1]
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001845#if ENABLE_ASH_GETOPTS
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001846# define voptind (&vps4)[1]
1847# if ENABLE_ASH_RANDOM_SUPPORT
1848# define vrandom (&voptind)[1]
1849# endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001850#else
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001851# if ENABLE_ASH_RANDOM_SUPPORT
1852# define vrandom (&vps4)[1]
1853# endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001854#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001855
1856/*
1857 * The following macros access the values of the above variables.
1858 * They have to skip over the name. They return the null string
1859 * for unset variables.
1860 */
1861#define ifsval() (vifs.text + 4)
1862#define ifsset() ((vifs.flags & VUNSET) == 0)
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001863#if ENABLE_ASH_MAIL
1864# define mailval() (vmail.text + 5)
1865# define mpathval() (vmpath.text + 9)
1866# define mpathset() ((vmpath.flags & VUNSET) == 0)
1867#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001868#define pathval() (vpath.text + 5)
1869#define ps1val() (vps1.text + 4)
1870#define ps2val() (vps2.text + 4)
1871#define ps4val() (vps4.text + 4)
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001872#if ENABLE_ASH_GETOPTS
1873# define optindval() (voptind.text + 7)
1874#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001875
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001876
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001877#define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
1878#define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
1879
Denis Vlasenko01631112007-12-16 17:20:38 +00001880#if ENABLE_ASH_GETOPTS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001881static void FAST_FUNC
Denis Vlasenko01631112007-12-16 17:20:38 +00001882getoptsreset(const char *value)
1883{
1884 shellparam.optind = number(value);
1885 shellparam.optoff = -1;
1886}
1887#endif
1888
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001889/*
1890 * Return of a legal variable name (a letter or underscore followed by zero or
1891 * more letters, underscores, and digits).
1892 */
1893static char *
1894endofname(const char *name)
1895{
1896 char *p;
1897
1898 p = (char *) name;
1899 if (!is_name(*p))
1900 return p;
1901 while (*++p) {
1902 if (!is_in_name(*p))
1903 break;
1904 }
1905 return p;
1906}
1907
1908/*
1909 * Compares two strings up to the first = or '\0'. The first
1910 * string must be terminated by '='; the second may be terminated by
1911 * either '=' or '\0'.
1912 */
1913static int
1914varcmp(const char *p, const char *q)
1915{
1916 int c, d;
1917
1918 while ((c = *p) == (d = *q)) {
1919 if (!c || c == '=')
1920 goto out;
1921 p++;
1922 q++;
1923 }
1924 if (c == '=')
Denis Vlasenko9650f362007-02-23 01:04:37 +00001925 c = '\0';
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001926 if (d == '=')
Denis Vlasenko9650f362007-02-23 01:04:37 +00001927 d = '\0';
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001928 out:
1929 return c - d;
1930}
1931
1932static int
1933varequal(const char *a, const char *b)
1934{
1935 return !varcmp(a, b);
1936}
1937
1938/*
1939 * Find the appropriate entry in the hash table from the name.
1940 */
1941static struct var **
1942hashvar(const char *p)
1943{
1944 unsigned hashval;
1945
1946 hashval = ((unsigned char) *p) << 4;
1947 while (*p && *p != '=')
1948 hashval += (unsigned char) *p++;
1949 return &vartab[hashval % VTABSIZE];
1950}
1951
1952static int
1953vpcmp(const void *a, const void *b)
1954{
1955 return varcmp(*(const char **)a, *(const char **)b);
1956}
1957
1958/*
1959 * This routine initializes the builtin variables.
1960 */
1961static void
1962initvar(void)
1963{
1964 struct var *vp;
1965 struct var *end;
1966 struct var **vpp;
1967
1968 /*
1969 * PS1 depends on uid
1970 */
1971#if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
1972 vps1.text = "PS1=\\w \\$ ";
1973#else
1974 if (!geteuid())
1975 vps1.text = "PS1=# ";
1976#endif
1977 vp = varinit;
Denis Vlasenko80b8b392007-06-25 10:55:35 +00001978 end = vp + ARRAY_SIZE(varinit);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001979 do {
1980 vpp = hashvar(vp->text);
1981 vp->next = *vpp;
1982 *vpp = vp;
1983 } while (++vp < end);
1984}
1985
1986static struct var **
1987findvar(struct var **vpp, const char *name)
1988{
1989 for (; *vpp; vpp = &(*vpp)->next) {
1990 if (varequal((*vpp)->text, name)) {
1991 break;
1992 }
1993 }
1994 return vpp;
1995}
1996
1997/*
1998 * Find the value of a variable. Returns NULL if not set.
1999 */
Mike Frysinger98c52642009-04-02 10:02:37 +00002000static const char *
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002001lookupvar(const char *name)
2002{
2003 struct var *v;
2004
2005 v = *findvar(hashvar(name), name);
2006 if (v) {
Denis Vlasenko448d30e2008-06-27 00:24:11 +00002007#if ENABLE_ASH_RANDOM_SUPPORT
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002008 /*
2009 * Dynamic variables are implemented roughly the same way they are
2010 * in bash. Namely, they're "special" so long as they aren't unset.
2011 * As soon as they're unset, they're no longer dynamic, and dynamic
2012 * lookup will no longer happen at that point. -- PFM.
2013 */
2014 if ((v->flags & VDYNAMIC))
2015 (*v->func)(NULL);
2016#endif
2017 if (!(v->flags & VUNSET))
2018 return strchrnul(v->text, '=') + 1;
2019 }
2020 return NULL;
2021}
2022
2023/*
2024 * Search the environment of a builtin command.
2025 */
Mike Frysinger98c52642009-04-02 10:02:37 +00002026static const char *
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002027bltinlookup(const char *name)
2028{
2029 struct strlist *sp;
2030
2031 for (sp = cmdenviron; sp; sp = sp->next) {
2032 if (varequal(sp->text, name))
2033 return strchrnul(sp->text, '=') + 1;
2034 }
2035 return lookupvar(name);
2036}
2037
2038/*
2039 * Same as setvar except that the variable and value are passed in
2040 * the first argument as name=value. Since the first argument will
2041 * be actually stored in the table, it should not be a string that
2042 * will go away.
2043 * Called with interrupts off.
2044 */
2045static void
2046setvareq(char *s, int flags)
2047{
2048 struct var *vp, **vpp;
2049
2050 vpp = hashvar(s);
2051 flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
2052 vp = *findvar(vpp, s);
2053 if (vp) {
2054 if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
2055 const char *n;
2056
2057 if (flags & VNOSAVE)
2058 free(s);
2059 n = vp->text;
2060 ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
2061 }
2062
2063 if (flags & VNOSET)
2064 return;
2065
2066 if (vp->func && (flags & VNOFUNC) == 0)
2067 (*vp->func)(strchrnul(s, '=') + 1);
2068
2069 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
2070 free((char*)vp->text);
2071
2072 flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
2073 } else {
2074 if (flags & VNOSET)
2075 return;
2076 /* not found */
Denis Vlasenko597906c2008-02-20 16:38:54 +00002077 vp = ckzalloc(sizeof(*vp));
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002078 vp->next = *vpp;
Denis Vlasenko597906c2008-02-20 16:38:54 +00002079 /*vp->func = NULL; - ckzalloc did it */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002080 *vpp = vp;
2081 }
2082 if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
2083 s = ckstrdup(s);
2084 vp->text = s;
2085 vp->flags = flags;
2086}
2087
2088/*
2089 * Set the value of a variable. The flags argument is ored with the
2090 * flags of the variable. If val is NULL, the variable is unset.
2091 */
2092static void
2093setvar(const char *name, const char *val, int flags)
2094{
2095 char *p, *q;
2096 size_t namelen;
2097 char *nameeq;
2098 size_t vallen;
2099
2100 q = endofname(name);
2101 p = strchrnul(q, '=');
2102 namelen = p - name;
2103 if (!namelen || p != q)
2104 ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
2105 vallen = 0;
2106 if (val == NULL) {
2107 flags |= VUNSET;
2108 } else {
2109 vallen = strlen(val);
2110 }
2111 INT_OFF;
2112 nameeq = ckmalloc(namelen + vallen + 2);
Denis Vlasenko29eb3592008-05-18 14:06:08 +00002113 p = (char *)memcpy(nameeq, name, namelen) + namelen;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002114 if (val) {
2115 *p++ = '=';
Denis Vlasenko29eb3592008-05-18 14:06:08 +00002116 p = (char *)memcpy(p, val, vallen) + vallen;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002117 }
2118 *p = '\0';
2119 setvareq(nameeq, flags | VNOSAVE);
2120 INT_ON;
2121}
2122
2123#if ENABLE_ASH_GETOPTS
2124/*
2125 * Safe version of setvar, returns 1 on success 0 on failure.
2126 */
2127static int
2128setvarsafe(const char *name, const char *val, int flags)
2129{
2130 int err;
2131 volatile int saveint;
2132 struct jmploc *volatile savehandler = exception_handler;
2133 struct jmploc jmploc;
2134
2135 SAVE_INT(saveint);
2136 if (setjmp(jmploc.loc))
2137 err = 1;
2138 else {
2139 exception_handler = &jmploc;
2140 setvar(name, val, flags);
2141 err = 0;
2142 }
2143 exception_handler = savehandler;
2144 RESTORE_INT(saveint);
2145 return err;
2146}
2147#endif
2148
2149/*
2150 * Unset the specified variable.
2151 */
2152static int
2153unsetvar(const char *s)
2154{
2155 struct var **vpp;
2156 struct var *vp;
2157 int retval;
2158
2159 vpp = findvar(hashvar(s), s);
2160 vp = *vpp;
2161 retval = 2;
2162 if (vp) {
2163 int flags = vp->flags;
2164
2165 retval = 1;
2166 if (flags & VREADONLY)
2167 goto out;
Denis Vlasenko448d30e2008-06-27 00:24:11 +00002168#if ENABLE_ASH_RANDOM_SUPPORT
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002169 vp->flags &= ~VDYNAMIC;
2170#endif
2171 if (flags & VUNSET)
2172 goto ok;
2173 if ((flags & VSTRFIXED) == 0) {
2174 INT_OFF;
2175 if ((flags & (VTEXTFIXED|VSTACK)) == 0)
2176 free((char*)vp->text);
2177 *vpp = vp->next;
2178 free(vp);
2179 INT_ON;
2180 } else {
2181 setvar(s, 0, 0);
2182 vp->flags &= ~VEXPORT;
2183 }
2184 ok:
2185 retval = 0;
2186 }
2187 out:
2188 return retval;
2189}
2190
2191/*
2192 * Process a linked list of variable assignments.
2193 */
2194static void
2195listsetvar(struct strlist *list_set_var, int flags)
2196{
2197 struct strlist *lp = list_set_var;
2198
2199 if (!lp)
2200 return;
2201 INT_OFF;
2202 do {
2203 setvareq(lp->text, flags);
Denis Vlasenko9650f362007-02-23 01:04:37 +00002204 lp = lp->next;
2205 } while (lp);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002206 INT_ON;
2207}
2208
2209/*
2210 * Generate a list of variables satisfying the given conditions.
2211 */
2212static char **
2213listvars(int on, int off, char ***end)
2214{
2215 struct var **vpp;
2216 struct var *vp;
2217 char **ep;
2218 int mask;
2219
2220 STARTSTACKSTR(ep);
2221 vpp = vartab;
2222 mask = on | off;
2223 do {
2224 for (vp = *vpp; vp; vp = vp->next) {
2225 if ((vp->flags & mask) == on) {
2226 if (ep == stackstrend())
2227 ep = growstackstr();
2228 *ep++ = (char *) vp->text;
2229 }
2230 }
2231 } while (++vpp < vartab + VTABSIZE);
2232 if (ep == stackstrend())
2233 ep = growstackstr();
2234 if (end)
2235 *end = ep;
2236 *ep++ = NULL;
2237 return grabstackstr(ep);
2238}
2239
2240
2241/* ============ Path search helper
2242 *
2243 * The variable path (passed by reference) should be set to the start
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02002244 * of the path before the first call; path_advance will update
2245 * this value as it proceeds. Successive calls to path_advance will return
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002246 * the possible path expansions in sequence. If an option (indicated by
2247 * a percent sign) appears in the path entry then the global variable
2248 * pathopt will be set to point to it; otherwise pathopt will be set to
2249 * NULL.
2250 */
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02002251static const char *pathopt; /* set by path_advance */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002252
2253static char *
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02002254path_advance(const char **path, const char *name)
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002255{
2256 const char *p;
2257 char *q;
2258 const char *start;
2259 size_t len;
2260
2261 if (*path == NULL)
2262 return NULL;
2263 start = *path;
Denis Vlasenkof7d56652008-03-25 05:51:41 +00002264 for (p = start; *p && *p != ':' && *p != '%'; p++)
2265 continue;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002266 len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
2267 while (stackblocksize() < len)
2268 growstackblock();
2269 q = stackblock();
2270 if (p != start) {
2271 memcpy(q, start, p - start);
2272 q += p - start;
2273 *q++ = '/';
2274 }
2275 strcpy(q, name);
2276 pathopt = NULL;
2277 if (*p == '%') {
2278 pathopt = ++p;
Denis Vlasenkof7d56652008-03-25 05:51:41 +00002279 while (*p && *p != ':')
2280 p++;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002281 }
2282 if (*p == ':')
2283 *path = p + 1;
2284 else
2285 *path = NULL;
2286 return stalloc(len);
2287}
2288
2289
2290/* ============ Prompt */
2291
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +00002292static smallint doprompt; /* if set, prompt the user */
2293static smallint needprompt; /* true if interactive and at start of line */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002294
2295#if ENABLE_FEATURE_EDITING
2296static line_input_t *line_input_state;
2297static const char *cmdedit_prompt;
2298static void
2299putprompt(const char *s)
2300{
2301 if (ENABLE_ASH_EXPAND_PRMT) {
2302 free((char*)cmdedit_prompt);
Denis Vlasenko4222ae42007-02-25 02:37:49 +00002303 cmdedit_prompt = ckstrdup(s);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002304 return;
2305 }
2306 cmdedit_prompt = s;
2307}
2308#else
2309static void
2310putprompt(const char *s)
2311{
2312 out2str(s);
2313}
2314#endif
2315
2316#if ENABLE_ASH_EXPAND_PRMT
2317/* expandstr() needs parsing machinery, so it is far away ahead... */
2318static const char *expandstr(const char *ps);
2319#else
2320#define expandstr(s) s
2321#endif
2322
2323static void
2324setprompt(int whichprompt)
2325{
2326 const char *prompt;
2327#if ENABLE_ASH_EXPAND_PRMT
2328 struct stackmark smark;
2329#endif
2330
2331 needprompt = 0;
2332
2333 switch (whichprompt) {
2334 case 1:
2335 prompt = ps1val();
2336 break;
2337 case 2:
2338 prompt = ps2val();
2339 break;
2340 default: /* 0 */
2341 prompt = nullstr;
2342 }
2343#if ENABLE_ASH_EXPAND_PRMT
2344 setstackmark(&smark);
2345 stalloc(stackblocksize());
2346#endif
2347 putprompt(expandstr(prompt));
2348#if ENABLE_ASH_EXPAND_PRMT
2349 popstackmark(&smark);
2350#endif
2351}
2352
2353
2354/* ============ The cd and pwd commands */
2355
2356#define CD_PHYSICAL 1
2357#define CD_PRINT 2
2358
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002359static int
2360cdopt(void)
2361{
2362 int flags = 0;
2363 int i, j;
2364
2365 j = 'L';
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02002366 while ((i = nextopt("LP")) != '\0') {
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002367 if (i != j) {
2368 flags ^= CD_PHYSICAL;
2369 j = i;
2370 }
2371 }
2372
2373 return flags;
2374}
2375
2376/*
2377 * Update curdir (the name of the current directory) in response to a
2378 * cd command.
2379 */
2380static const char *
2381updatepwd(const char *dir)
2382{
2383 char *new;
2384 char *p;
2385 char *cdcomppath;
2386 const char *lim;
2387
2388 cdcomppath = ststrdup(dir);
2389 STARTSTACKSTR(new);
2390 if (*dir != '/') {
2391 if (curdir == nullstr)
2392 return 0;
2393 new = stack_putstr(curdir, new);
2394 }
2395 new = makestrspace(strlen(dir) + 2, new);
Denis Vlasenko29eb3592008-05-18 14:06:08 +00002396 lim = (char *)stackblock() + 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002397 if (*dir != '/') {
2398 if (new[-1] != '/')
2399 USTPUTC('/', new);
2400 if (new > lim && *lim == '/')
2401 lim++;
2402 } else {
2403 USTPUTC('/', new);
2404 cdcomppath++;
2405 if (dir[1] == '/' && dir[2] != '/') {
2406 USTPUTC('/', new);
2407 cdcomppath++;
2408 lim++;
2409 }
2410 }
2411 p = strtok(cdcomppath, "/");
2412 while (p) {
2413 switch (*p) {
2414 case '.':
2415 if (p[1] == '.' && p[2] == '\0') {
2416 while (new > lim) {
2417 STUNPUTC(new);
2418 if (new[-1] == '/')
2419 break;
2420 }
2421 break;
Denis Vlasenko16abcd92007-04-13 23:59:52 +00002422 }
2423 if (p[1] == '\0')
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002424 break;
2425 /* fall through */
2426 default:
2427 new = stack_putstr(p, new);
2428 USTPUTC('/', new);
2429 }
2430 p = strtok(0, "/");
2431 }
2432 if (new > lim)
2433 STUNPUTC(new);
2434 *new = 0;
2435 return stackblock();
2436}
2437
2438/*
2439 * Find out what the current directory is. If we already know the current
2440 * directory, this routine returns immediately.
2441 */
2442static char *
2443getpwd(void)
2444{
Denis Vlasenko01631112007-12-16 17:20:38 +00002445 char *dir = getcwd(NULL, 0); /* huh, using glibc extension? */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002446 return dir ? dir : nullstr;
2447}
2448
2449static void
2450setpwd(const char *val, int setold)
2451{
2452 char *oldcur, *dir;
2453
2454 oldcur = dir = curdir;
2455
2456 if (setold) {
2457 setvar("OLDPWD", oldcur, VEXPORT);
2458 }
2459 INT_OFF;
2460 if (physdir != nullstr) {
2461 if (physdir != oldcur)
2462 free(physdir);
2463 physdir = nullstr;
2464 }
2465 if (oldcur == val || !val) {
2466 char *s = getpwd();
2467 physdir = s;
2468 if (!val)
2469 dir = s;
2470 } else
2471 dir = ckstrdup(val);
2472 if (oldcur != dir && oldcur != nullstr) {
2473 free(oldcur);
2474 }
2475 curdir = dir;
2476 INT_ON;
2477 setvar("PWD", dir, VEXPORT);
2478}
2479
2480static void hashcd(void);
2481
2482/*
2483 * Actually do the chdir. We also call hashcd to let the routines in exec.c
2484 * know that the current directory has changed.
2485 */
2486static int
2487docd(const char *dest, int flags)
2488{
2489 const char *dir = 0;
2490 int err;
2491
2492 TRACE(("docd(\"%s\", %d) called\n", dest, flags));
2493
2494 INT_OFF;
2495 if (!(flags & CD_PHYSICAL)) {
2496 dir = updatepwd(dest);
2497 if (dir)
2498 dest = dir;
2499 }
2500 err = chdir(dest);
2501 if (err)
2502 goto out;
2503 setpwd(dir, 1);
2504 hashcd();
2505 out:
2506 INT_ON;
2507 return err;
2508}
2509
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02002510static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00002511cdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002512{
2513 const char *dest;
2514 const char *path;
2515 const char *p;
2516 char c;
2517 struct stat statb;
2518 int flags;
2519
2520 flags = cdopt();
2521 dest = *argptr;
2522 if (!dest)
2523 dest = bltinlookup(homestr);
2524 else if (LONE_DASH(dest)) {
2525 dest = bltinlookup("OLDPWD");
2526 flags |= CD_PRINT;
2527 }
2528 if (!dest)
2529 dest = nullstr;
2530 if (*dest == '/')
2531 goto step7;
2532 if (*dest == '.') {
2533 c = dest[1];
2534 dotdot:
2535 switch (c) {
2536 case '\0':
2537 case '/':
2538 goto step6;
2539 case '.':
2540 c = dest[2];
2541 if (c != '.')
2542 goto dotdot;
2543 }
2544 }
2545 if (!*dest)
2546 dest = ".";
2547 path = bltinlookup("CDPATH");
2548 if (!path) {
2549 step6:
2550 step7:
2551 p = dest;
2552 goto docd;
2553 }
2554 do {
2555 c = *path;
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02002556 p = path_advance(&path, dest);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002557 if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
2558 if (c && c != ':')
2559 flags |= CD_PRINT;
2560 docd:
2561 if (!docd(p, flags))
2562 goto out;
2563 break;
2564 }
2565 } while (path);
2566 ash_msg_and_raise_error("can't cd to %s", dest);
2567 /* NOTREACHED */
2568 out:
2569 if (flags & CD_PRINT)
2570 out1fmt(snlfmt, curdir);
2571 return 0;
2572}
2573
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02002574static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00002575pwdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002576{
2577 int flags;
2578 const char *dir = curdir;
2579
2580 flags = cdopt();
2581 if (flags) {
2582 if (physdir == nullstr)
2583 setpwd(dir, 0);
2584 dir = physdir;
2585 }
2586 out1fmt(snlfmt, dir);
2587 return 0;
2588}
2589
Denis Vlasenko0c032a42007-02-23 01:03:40 +00002590
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00002591/* ============ ... */
Eric Andersenc470f442003-07-28 09:56:35 +00002592
Denis Vlasenko834dee72008-10-07 09:18:30 +00002593
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +00002594#define IBUFSIZ COMMON_BUFSIZE
Denis Vlasenko834dee72008-10-07 09:18:30 +00002595/* buffer for top level input file */
2596#define basebuf bb_common_bufsiz1
Eric Andersenc470f442003-07-28 09:56:35 +00002597
Eric Andersenc470f442003-07-28 09:56:35 +00002598/* Syntax classes */
Denis Vlasenko834dee72008-10-07 09:18:30 +00002599#define CWORD 0 /* character is nothing special */
2600#define CNL 1 /* newline character */
2601#define CBACK 2 /* a backslash character */
2602#define CSQUOTE 3 /* single quote */
2603#define CDQUOTE 4 /* double quote */
Eric Andersenc470f442003-07-28 09:56:35 +00002604#define CENDQUOTE 5 /* a terminating quote */
Denis Vlasenko834dee72008-10-07 09:18:30 +00002605#define CBQUOTE 6 /* backwards single quote */
2606#define CVAR 7 /* a dollar sign */
2607#define CENDVAR 8 /* a '}' character */
2608#define CLP 9 /* a left paren in arithmetic */
2609#define CRP 10 /* a right paren in arithmetic */
Eric Andersenc470f442003-07-28 09:56:35 +00002610#define CENDFILE 11 /* end of file */
Denis Vlasenko834dee72008-10-07 09:18:30 +00002611#define CCTL 12 /* like CWORD, except it must be escaped */
2612#define CSPCL 13 /* these terminate a word */
2613#define CIGN 14 /* character should be ignored */
Eric Andersenc470f442003-07-28 09:56:35 +00002614
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002615#define PEOF 256
Denis Vlasenko131ae172007-02-18 13:00:19 +00002616#if ENABLE_ASH_ALIAS
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002617# define PEOA 257
Eric Andersenc470f442003-07-28 09:56:35 +00002618#endif
2619
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002620#define USE_SIT_FUNCTION ENABLE_ASH_OPTIMIZE_FOR_SIZE
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002621
Mike Frysinger98c52642009-04-02 10:02:37 +00002622#if ENABLE_SH_MATH_SUPPORT
Denys Vlasenko76bc2d62009-11-29 01:37:46 +01002623# define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8) | (d << 12))
Eric Andersenc470f442003-07-28 09:56:35 +00002624#else
Denys Vlasenko76bc2d62009-11-29 01:37:46 +01002625# define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8))
Denys Vlasenko76bc2d62009-11-29 01:37:46 +01002626#endif
Denys Vlasenko068d3862009-11-29 01:41:11 +01002627static const uint16_t S_I_T[] = {
Denys Vlasenko76bc2d62009-11-29 01:37:46 +01002628#if ENABLE_ASH_ALIAS
2629 SIT_ITEM(CSPCL , CIGN , CIGN , CIGN ), /* 0, PEOA */
2630#endif
2631 SIT_ITEM(CSPCL , CWORD , CWORD, CWORD ), /* 1, ' ' */
2632 SIT_ITEM(CNL , CNL , CNL , CNL ), /* 2, \n */
2633 SIT_ITEM(CWORD , CCTL , CCTL , CWORD ), /* 3, !*-/:=?[]~ */
2634 SIT_ITEM(CDQUOTE , CENDQUOTE, CWORD, CWORD ), /* 4, '"' */
2635 SIT_ITEM(CVAR , CVAR , CWORD, CVAR ), /* 5, $ */
2636 SIT_ITEM(CSQUOTE , CWORD , CENDQUOTE, CWORD), /* 6, "'" */
2637 SIT_ITEM(CSPCL , CWORD , CWORD, CLP ), /* 7, ( */
2638 SIT_ITEM(CSPCL , CWORD , CWORD, CRP ), /* 8, ) */
2639 SIT_ITEM(CBACK , CBACK , CCTL , CBACK ), /* 9, \ */
2640 SIT_ITEM(CBQUOTE , CBQUOTE , CWORD, CBQUOTE), /* 10, ` */
2641 SIT_ITEM(CENDVAR , CENDVAR , CWORD, CENDVAR), /* 11, } */
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002642#if !USE_SIT_FUNCTION
Denys Vlasenko76bc2d62009-11-29 01:37:46 +01002643 SIT_ITEM(CENDFILE, CENDFILE , CENDFILE, CENDFILE),/* 12, PEOF */
2644 SIT_ITEM(CWORD , CWORD , CWORD, CWORD ), /* 13, 0-9A-Za-z */
2645 SIT_ITEM(CCTL , CCTL , CCTL , CCTL ) /* 14, CTLESC ... */
2646#endif
2647#undef SIT_ITEM
Eric Andersenc470f442003-07-28 09:56:35 +00002648};
Denys Vlasenko76bc2d62009-11-29 01:37:46 +01002649/* Constants below must match table above */
2650enum {
2651#if ENABLE_ASH_ALIAS
2652 CSPCL_CIGN_CIGN_CIGN , /* 0 */
2653#endif
2654 CSPCL_CWORD_CWORD_CWORD , /* 1 */
2655 CNL_CNL_CNL_CNL , /* 2 */
2656 CWORD_CCTL_CCTL_CWORD , /* 3 */
2657 CDQUOTE_CENDQUOTE_CWORD_CWORD , /* 4 */
2658 CVAR_CVAR_CWORD_CVAR , /* 5 */
2659 CSQUOTE_CWORD_CENDQUOTE_CWORD , /* 6 */
2660 CSPCL_CWORD_CWORD_CLP , /* 7 */
2661 CSPCL_CWORD_CWORD_CRP , /* 8 */
2662 CBACK_CBACK_CCTL_CBACK , /* 9 */
2663 CBQUOTE_CBQUOTE_CWORD_CBQUOTE , /* 10 */
2664 CENDVAR_CENDVAR_CWORD_CENDVAR , /* 11 */
2665 CENDFILE_CENDFILE_CENDFILE_CENDFILE, /* 12 */
2666 CWORD_CWORD_CWORD_CWORD , /* 13 */
2667 CCTL_CCTL_CCTL_CCTL , /* 14 */
2668};
Eric Andersen2870d962001-07-02 17:27:21 +00002669
Denys Vlasenkocd716832009-11-28 22:14:02 +01002670/* c in SIT(c, syntax) must be an *unsigned char* or PEOA or PEOF,
2671 * caller must ensure proper cast on it if c is *char_ptr!
2672 */
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002673/* Values for syntax param */
2674#define BASESYNTAX 0 /* not in quotes */
2675#define DQSYNTAX 1 /* in double quotes */
2676#define SQSYNTAX 2 /* in single quotes */
2677#define ARISYNTAX 3 /* in arithmetic */
2678#define PSSYNTAX 4 /* prompt. never passed to SIT() */
Denys Vlasenkocd716832009-11-28 22:14:02 +01002679
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002680#if USE_SIT_FUNCTION
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002681
Denis Vlasenko0c032a42007-02-23 01:03:40 +00002682static int
2683SIT(int c, int syntax)
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002684{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00002685 static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-/:;<=>?[\\]`|}~";
Denys Vlasenkocd716832009-11-28 22:14:02 +01002686# if ENABLE_ASH_ALIAS
2687 static const uint8_t syntax_index_table[] ALIGN1 = {
Eric Andersenc470f442003-07-28 09:56:35 +00002688 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
2689 7, 8, 3, 3, 3, 3, 1, 1, /* "()*-/:;<" */
2690 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
2691 11, 3 /* "}~" */
2692 };
Denys Vlasenkocd716832009-11-28 22:14:02 +01002693# else
2694 static const uint8_t syntax_index_table[] ALIGN1 = {
Eric Andersenc470f442003-07-28 09:56:35 +00002695 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
2696 6, 7, 2, 2, 2, 2, 0, 0, /* "()*-/:;<" */
2697 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
2698 10, 2 /* "}~" */
2699 };
Denys Vlasenkocd716832009-11-28 22:14:02 +01002700# endif
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002701 const char *s;
2702 int indx;
2703
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002704 if (c == PEOF)
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002705 return CENDFILE;
Denys Vlasenkocd716832009-11-28 22:14:02 +01002706# if ENABLE_ASH_ALIAS
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002707 if (c == PEOA)
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +00002708 indx = 0;
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002709 else
Denys Vlasenkocd716832009-11-28 22:14:02 +01002710# endif
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +00002711 {
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002712 /* Cast is purely for paranoia here,
2713 * just in case someone passed signed char to us */
2714 if ((unsigned char)c >= CTL_FIRST
2715 && (unsigned char)c <= CTL_LAST
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +00002716 ) {
2717 return CCTL;
2718 }
2719 s = strchrnul(spec_symbls, c);
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002720 if (*s == '\0')
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +00002721 return CWORD;
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +00002722 indx = syntax_index_table[s - spec_symbls];
2723 }
Denys Vlasenko76bc2d62009-11-29 01:37:46 +01002724 return (S_I_T[indx] >> (syntax*4)) & 0xf;
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002725}
2726
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00002727#else /* !USE_SIT_FUNCTION */
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002728
Denys Vlasenko76bc2d62009-11-29 01:37:46 +01002729static const uint8_t syntax_index_table[] = {
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00002730 /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
Denys Vlasenkocd716832009-11-28 22:14:02 +01002731 /* 0 */ CWORD_CWORD_CWORD_CWORD,
2732 /* 1 */ CWORD_CWORD_CWORD_CWORD,
2733 /* 2 */ CWORD_CWORD_CWORD_CWORD,
2734 /* 3 */ CWORD_CWORD_CWORD_CWORD,
2735 /* 4 */ CWORD_CWORD_CWORD_CWORD,
2736 /* 5 */ CWORD_CWORD_CWORD_CWORD,
2737 /* 6 */ CWORD_CWORD_CWORD_CWORD,
2738 /* 7 */ CWORD_CWORD_CWORD_CWORD,
2739 /* 8 */ CWORD_CWORD_CWORD_CWORD,
2740 /* 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
2741 /* 10 "\n" */ CNL_CNL_CNL_CNL,
2742 /* 11 */ CWORD_CWORD_CWORD_CWORD,
2743 /* 12 */ CWORD_CWORD_CWORD_CWORD,
2744 /* 13 */ CWORD_CWORD_CWORD_CWORD,
2745 /* 14 */ CWORD_CWORD_CWORD_CWORD,
2746 /* 15 */ CWORD_CWORD_CWORD_CWORD,
2747 /* 16 */ CWORD_CWORD_CWORD_CWORD,
2748 /* 17 */ CWORD_CWORD_CWORD_CWORD,
2749 /* 18 */ CWORD_CWORD_CWORD_CWORD,
2750 /* 19 */ CWORD_CWORD_CWORD_CWORD,
2751 /* 20 */ CWORD_CWORD_CWORD_CWORD,
2752 /* 21 */ CWORD_CWORD_CWORD_CWORD,
2753 /* 22 */ CWORD_CWORD_CWORD_CWORD,
2754 /* 23 */ CWORD_CWORD_CWORD_CWORD,
2755 /* 24 */ CWORD_CWORD_CWORD_CWORD,
2756 /* 25 */ CWORD_CWORD_CWORD_CWORD,
2757 /* 26 */ CWORD_CWORD_CWORD_CWORD,
2758 /* 27 */ CWORD_CWORD_CWORD_CWORD,
2759 /* 28 */ CWORD_CWORD_CWORD_CWORD,
2760 /* 29 */ CWORD_CWORD_CWORD_CWORD,
2761 /* 30 */ CWORD_CWORD_CWORD_CWORD,
2762 /* 31 */ CWORD_CWORD_CWORD_CWORD,
2763 /* 32 " " */ CSPCL_CWORD_CWORD_CWORD,
2764 /* 33 "!" */ CWORD_CCTL_CCTL_CWORD,
2765 /* 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
2766 /* 35 "#" */ CWORD_CWORD_CWORD_CWORD,
2767 /* 36 "$" */ CVAR_CVAR_CWORD_CVAR,
2768 /* 37 "%" */ CWORD_CWORD_CWORD_CWORD,
2769 /* 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
2770 /* 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
2771 /* 40 "(" */ CSPCL_CWORD_CWORD_CLP,
2772 /* 41 ")" */ CSPCL_CWORD_CWORD_CRP,
2773 /* 42 "*" */ CWORD_CCTL_CCTL_CWORD,
2774 /* 43 "+" */ CWORD_CWORD_CWORD_CWORD,
2775 /* 44 "," */ CWORD_CWORD_CWORD_CWORD,
2776 /* 45 "-" */ CWORD_CCTL_CCTL_CWORD,
2777 /* 46 "." */ CWORD_CWORD_CWORD_CWORD,
2778 /* 47 "/" */ CWORD_CCTL_CCTL_CWORD,
2779 /* 48 "0" */ CWORD_CWORD_CWORD_CWORD,
2780 /* 49 "1" */ CWORD_CWORD_CWORD_CWORD,
2781 /* 50 "2" */ CWORD_CWORD_CWORD_CWORD,
2782 /* 51 "3" */ CWORD_CWORD_CWORD_CWORD,
2783 /* 52 "4" */ CWORD_CWORD_CWORD_CWORD,
2784 /* 53 "5" */ CWORD_CWORD_CWORD_CWORD,
2785 /* 54 "6" */ CWORD_CWORD_CWORD_CWORD,
2786 /* 55 "7" */ CWORD_CWORD_CWORD_CWORD,
2787 /* 56 "8" */ CWORD_CWORD_CWORD_CWORD,
2788 /* 57 "9" */ CWORD_CWORD_CWORD_CWORD,
2789 /* 58 ":" */ CWORD_CCTL_CCTL_CWORD,
2790 /* 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
2791 /* 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
2792 /* 61 "=" */ CWORD_CCTL_CCTL_CWORD,
2793 /* 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
2794 /* 63 "?" */ CWORD_CCTL_CCTL_CWORD,
2795 /* 64 "@" */ CWORD_CWORD_CWORD_CWORD,
2796 /* 65 "A" */ CWORD_CWORD_CWORD_CWORD,
2797 /* 66 "B" */ CWORD_CWORD_CWORD_CWORD,
2798 /* 67 "C" */ CWORD_CWORD_CWORD_CWORD,
2799 /* 68 "D" */ CWORD_CWORD_CWORD_CWORD,
2800 /* 69 "E" */ CWORD_CWORD_CWORD_CWORD,
2801 /* 70 "F" */ CWORD_CWORD_CWORD_CWORD,
2802 /* 71 "G" */ CWORD_CWORD_CWORD_CWORD,
2803 /* 72 "H" */ CWORD_CWORD_CWORD_CWORD,
2804 /* 73 "I" */ CWORD_CWORD_CWORD_CWORD,
2805 /* 74 "J" */ CWORD_CWORD_CWORD_CWORD,
2806 /* 75 "K" */ CWORD_CWORD_CWORD_CWORD,
2807 /* 76 "L" */ CWORD_CWORD_CWORD_CWORD,
2808 /* 77 "M" */ CWORD_CWORD_CWORD_CWORD,
2809 /* 78 "N" */ CWORD_CWORD_CWORD_CWORD,
2810 /* 79 "O" */ CWORD_CWORD_CWORD_CWORD,
2811 /* 80 "P" */ CWORD_CWORD_CWORD_CWORD,
2812 /* 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
2813 /* 82 "R" */ CWORD_CWORD_CWORD_CWORD,
2814 /* 83 "S" */ CWORD_CWORD_CWORD_CWORD,
2815 /* 84 "T" */ CWORD_CWORD_CWORD_CWORD,
2816 /* 85 "U" */ CWORD_CWORD_CWORD_CWORD,
2817 /* 86 "V" */ CWORD_CWORD_CWORD_CWORD,
2818 /* 87 "W" */ CWORD_CWORD_CWORD_CWORD,
2819 /* 88 "X" */ CWORD_CWORD_CWORD_CWORD,
2820 /* 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
2821 /* 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
2822 /* 91 "[" */ CWORD_CCTL_CCTL_CWORD,
2823 /* 92 "\" */ CBACK_CBACK_CCTL_CBACK,
2824 /* 93 "]" */ CWORD_CCTL_CCTL_CWORD,
2825 /* 94 "^" */ CWORD_CWORD_CWORD_CWORD,
2826 /* 95 "_" */ CWORD_CWORD_CWORD_CWORD,
2827 /* 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
2828 /* 97 "a" */ CWORD_CWORD_CWORD_CWORD,
2829 /* 98 "b" */ CWORD_CWORD_CWORD_CWORD,
2830 /* 99 "c" */ CWORD_CWORD_CWORD_CWORD,
2831 /* 100 "d" */ CWORD_CWORD_CWORD_CWORD,
2832 /* 101 "e" */ CWORD_CWORD_CWORD_CWORD,
2833 /* 102 "f" */ CWORD_CWORD_CWORD_CWORD,
2834 /* 103 "g" */ CWORD_CWORD_CWORD_CWORD,
2835 /* 104 "h" */ CWORD_CWORD_CWORD_CWORD,
2836 /* 105 "i" */ CWORD_CWORD_CWORD_CWORD,
2837 /* 106 "j" */ CWORD_CWORD_CWORD_CWORD,
2838 /* 107 "k" */ CWORD_CWORD_CWORD_CWORD,
2839 /* 108 "l" */ CWORD_CWORD_CWORD_CWORD,
2840 /* 109 "m" */ CWORD_CWORD_CWORD_CWORD,
2841 /* 110 "n" */ CWORD_CWORD_CWORD_CWORD,
2842 /* 111 "o" */ CWORD_CWORD_CWORD_CWORD,
2843 /* 112 "p" */ CWORD_CWORD_CWORD_CWORD,
2844 /* 113 "q" */ CWORD_CWORD_CWORD_CWORD,
2845 /* 114 "r" */ CWORD_CWORD_CWORD_CWORD,
2846 /* 115 "s" */ CWORD_CWORD_CWORD_CWORD,
2847 /* 116 "t" */ CWORD_CWORD_CWORD_CWORD,
2848 /* 117 "u" */ CWORD_CWORD_CWORD_CWORD,
2849 /* 118 "v" */ CWORD_CWORD_CWORD_CWORD,
2850 /* 119 "w" */ CWORD_CWORD_CWORD_CWORD,
2851 /* 120 "x" */ CWORD_CWORD_CWORD_CWORD,
2852 /* 121 "y" */ CWORD_CWORD_CWORD_CWORD,
2853 /* 122 "z" */ CWORD_CWORD_CWORD_CWORD,
2854 /* 123 "{" */ CWORD_CWORD_CWORD_CWORD,
2855 /* 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
2856 /* 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
2857 /* 126 "~" */ CWORD_CCTL_CCTL_CWORD,
2858 /* 127 del */ CWORD_CWORD_CWORD_CWORD,
2859 /* 128 0x80 */ CWORD_CWORD_CWORD_CWORD,
2860 /* 129 CTLESC */ CCTL_CCTL_CCTL_CCTL,
2861 /* 130 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
2862 /* 131 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
2863 /* 132 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
2864 /* 133 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
2865 /* 134 CTLARI */ CCTL_CCTL_CCTL_CCTL,
2866 /* 135 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
2867 /* 136 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
2868 /* 137 */ CWORD_CWORD_CWORD_CWORD,
2869 /* 138 */ CWORD_CWORD_CWORD_CWORD,
2870 /* 139 */ CWORD_CWORD_CWORD_CWORD,
2871 /* 140 */ CWORD_CWORD_CWORD_CWORD,
2872 /* 141 */ CWORD_CWORD_CWORD_CWORD,
2873 /* 142 */ CWORD_CWORD_CWORD_CWORD,
2874 /* 143 */ CWORD_CWORD_CWORD_CWORD,
2875 /* 144 */ CWORD_CWORD_CWORD_CWORD,
2876 /* 145 */ CWORD_CWORD_CWORD_CWORD,
2877 /* 146 */ CWORD_CWORD_CWORD_CWORD,
2878 /* 147 */ CWORD_CWORD_CWORD_CWORD,
2879 /* 148 */ CWORD_CWORD_CWORD_CWORD,
2880 /* 149 */ CWORD_CWORD_CWORD_CWORD,
2881 /* 150 */ CWORD_CWORD_CWORD_CWORD,
2882 /* 151 */ CWORD_CWORD_CWORD_CWORD,
2883 /* 152 */ CWORD_CWORD_CWORD_CWORD,
2884 /* 153 */ CWORD_CWORD_CWORD_CWORD,
2885 /* 154 */ CWORD_CWORD_CWORD_CWORD,
2886 /* 155 */ CWORD_CWORD_CWORD_CWORD,
2887 /* 156 */ CWORD_CWORD_CWORD_CWORD,
2888 /* 157 */ CWORD_CWORD_CWORD_CWORD,
2889 /* 158 */ CWORD_CWORD_CWORD_CWORD,
2890 /* 159 */ CWORD_CWORD_CWORD_CWORD,
2891 /* 160 */ CWORD_CWORD_CWORD_CWORD,
2892 /* 161 */ CWORD_CWORD_CWORD_CWORD,
2893 /* 162 */ CWORD_CWORD_CWORD_CWORD,
2894 /* 163 */ CWORD_CWORD_CWORD_CWORD,
2895 /* 164 */ CWORD_CWORD_CWORD_CWORD,
2896 /* 165 */ CWORD_CWORD_CWORD_CWORD,
2897 /* 166 */ CWORD_CWORD_CWORD_CWORD,
2898 /* 167 */ CWORD_CWORD_CWORD_CWORD,
2899 /* 168 */ CWORD_CWORD_CWORD_CWORD,
2900 /* 169 */ CWORD_CWORD_CWORD_CWORD,
2901 /* 170 */ CWORD_CWORD_CWORD_CWORD,
2902 /* 171 */ CWORD_CWORD_CWORD_CWORD,
2903 /* 172 */ CWORD_CWORD_CWORD_CWORD,
2904 /* 173 */ CWORD_CWORD_CWORD_CWORD,
2905 /* 174 */ CWORD_CWORD_CWORD_CWORD,
2906 /* 175 */ CWORD_CWORD_CWORD_CWORD,
2907 /* 176 */ CWORD_CWORD_CWORD_CWORD,
2908 /* 177 */ CWORD_CWORD_CWORD_CWORD,
2909 /* 178 */ CWORD_CWORD_CWORD_CWORD,
2910 /* 179 */ CWORD_CWORD_CWORD_CWORD,
2911 /* 180 */ CWORD_CWORD_CWORD_CWORD,
2912 /* 181 */ CWORD_CWORD_CWORD_CWORD,
2913 /* 182 */ CWORD_CWORD_CWORD_CWORD,
2914 /* 183 */ CWORD_CWORD_CWORD_CWORD,
2915 /* 184 */ CWORD_CWORD_CWORD_CWORD,
2916 /* 185 */ CWORD_CWORD_CWORD_CWORD,
2917 /* 186 */ CWORD_CWORD_CWORD_CWORD,
2918 /* 187 */ CWORD_CWORD_CWORD_CWORD,
2919 /* 188 */ CWORD_CWORD_CWORD_CWORD,
2920 /* 189 */ CWORD_CWORD_CWORD_CWORD,
2921 /* 190 */ CWORD_CWORD_CWORD_CWORD,
2922 /* 191 */ CWORD_CWORD_CWORD_CWORD,
2923 /* 192 */ CWORD_CWORD_CWORD_CWORD,
2924 /* 193 */ CWORD_CWORD_CWORD_CWORD,
2925 /* 194 */ CWORD_CWORD_CWORD_CWORD,
2926 /* 195 */ CWORD_CWORD_CWORD_CWORD,
2927 /* 196 */ CWORD_CWORD_CWORD_CWORD,
2928 /* 197 */ CWORD_CWORD_CWORD_CWORD,
2929 /* 198 */ CWORD_CWORD_CWORD_CWORD,
2930 /* 199 */ CWORD_CWORD_CWORD_CWORD,
2931 /* 200 */ CWORD_CWORD_CWORD_CWORD,
2932 /* 201 */ CWORD_CWORD_CWORD_CWORD,
2933 /* 202 */ CWORD_CWORD_CWORD_CWORD,
2934 /* 203 */ CWORD_CWORD_CWORD_CWORD,
2935 /* 204 */ CWORD_CWORD_CWORD_CWORD,
2936 /* 205 */ CWORD_CWORD_CWORD_CWORD,
2937 /* 206 */ CWORD_CWORD_CWORD_CWORD,
2938 /* 207 */ CWORD_CWORD_CWORD_CWORD,
2939 /* 208 */ CWORD_CWORD_CWORD_CWORD,
2940 /* 209 */ CWORD_CWORD_CWORD_CWORD,
2941 /* 210 */ CWORD_CWORD_CWORD_CWORD,
2942 /* 211 */ CWORD_CWORD_CWORD_CWORD,
2943 /* 212 */ CWORD_CWORD_CWORD_CWORD,
2944 /* 213 */ CWORD_CWORD_CWORD_CWORD,
2945 /* 214 */ CWORD_CWORD_CWORD_CWORD,
2946 /* 215 */ CWORD_CWORD_CWORD_CWORD,
2947 /* 216 */ CWORD_CWORD_CWORD_CWORD,
2948 /* 217 */ CWORD_CWORD_CWORD_CWORD,
2949 /* 218 */ CWORD_CWORD_CWORD_CWORD,
2950 /* 219 */ CWORD_CWORD_CWORD_CWORD,
2951 /* 220 */ CWORD_CWORD_CWORD_CWORD,
2952 /* 221 */ CWORD_CWORD_CWORD_CWORD,
2953 /* 222 */ CWORD_CWORD_CWORD_CWORD,
2954 /* 223 */ CWORD_CWORD_CWORD_CWORD,
2955 /* 224 */ CWORD_CWORD_CWORD_CWORD,
2956 /* 225 */ CWORD_CWORD_CWORD_CWORD,
2957 /* 226 */ CWORD_CWORD_CWORD_CWORD,
2958 /* 227 */ CWORD_CWORD_CWORD_CWORD,
2959 /* 228 */ CWORD_CWORD_CWORD_CWORD,
2960 /* 229 */ CWORD_CWORD_CWORD_CWORD,
2961 /* 230 */ CWORD_CWORD_CWORD_CWORD,
2962 /* 231 */ CWORD_CWORD_CWORD_CWORD,
2963 /* 232 */ CWORD_CWORD_CWORD_CWORD,
2964 /* 233 */ CWORD_CWORD_CWORD_CWORD,
2965 /* 234 */ CWORD_CWORD_CWORD_CWORD,
2966 /* 235 */ CWORD_CWORD_CWORD_CWORD,
2967 /* 236 */ CWORD_CWORD_CWORD_CWORD,
2968 /* 237 */ CWORD_CWORD_CWORD_CWORD,
2969 /* 238 */ CWORD_CWORD_CWORD_CWORD,
2970 /* 239 */ CWORD_CWORD_CWORD_CWORD,
2971 /* 230 */ CWORD_CWORD_CWORD_CWORD,
2972 /* 241 */ CWORD_CWORD_CWORD_CWORD,
2973 /* 242 */ CWORD_CWORD_CWORD_CWORD,
2974 /* 243 */ CWORD_CWORD_CWORD_CWORD,
2975 /* 244 */ CWORD_CWORD_CWORD_CWORD,
2976 /* 245 */ CWORD_CWORD_CWORD_CWORD,
2977 /* 246 */ CWORD_CWORD_CWORD_CWORD,
2978 /* 247 */ CWORD_CWORD_CWORD_CWORD,
2979 /* 248 */ CWORD_CWORD_CWORD_CWORD,
2980 /* 249 */ CWORD_CWORD_CWORD_CWORD,
2981 /* 250 */ CWORD_CWORD_CWORD_CWORD,
2982 /* 251 */ CWORD_CWORD_CWORD_CWORD,
2983 /* 252 */ CWORD_CWORD_CWORD_CWORD,
2984 /* 253 */ CWORD_CWORD_CWORD_CWORD,
2985 /* 254 */ CWORD_CWORD_CWORD_CWORD,
2986 /* 255 */ CWORD_CWORD_CWORD_CWORD,
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002987 /* PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
Denys Vlasenkocd716832009-11-28 22:14:02 +01002988# if ENABLE_ASH_ALIAS
2989 /* PEOA */ CSPCL_CIGN_CIGN_CIGN,
2990# endif
Eric Andersen2870d962001-07-02 17:27:21 +00002991};
2992
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01002993# define SIT(c, syntax) ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf)
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00002994
Denys Vlasenko76bc2d62009-11-29 01:37:46 +01002995#endif /* !USE_SIT_FUNCTION */
Eric Andersenc470f442003-07-28 09:56:35 +00002996
Eric Andersen2870d962001-07-02 17:27:21 +00002997
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00002998/* ============ Alias handling */
Denis Vlasenkofc06f292007-02-23 21:09:35 +00002999
Denis Vlasenko131ae172007-02-18 13:00:19 +00003000#if ENABLE_ASH_ALIAS
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00003001
3002#define ALIASINUSE 1
3003#define ALIASDEAD 2
3004
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00003005struct alias {
3006 struct alias *next;
3007 char *name;
3008 char *val;
3009 int flag;
3010};
3011
Denis Vlasenko01631112007-12-16 17:20:38 +00003012
3013static struct alias **atab; // [ATABSIZE];
3014#define INIT_G_alias() do { \
3015 atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
3016} while (0)
3017
Eric Andersen2870d962001-07-02 17:27:21 +00003018
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00003019static struct alias **
3020__lookupalias(const char *name) {
3021 unsigned int hashval;
3022 struct alias **app;
3023 const char *p;
3024 unsigned int ch;
3025
3026 p = name;
3027
3028 ch = (unsigned char)*p;
3029 hashval = ch << 4;
3030 while (ch) {
3031 hashval += ch;
3032 ch = (unsigned char)*++p;
3033 }
3034 app = &atab[hashval % ATABSIZE];
3035
3036 for (; *app; app = &(*app)->next) {
3037 if (strcmp(name, (*app)->name) == 0) {
3038 break;
3039 }
3040 }
3041
3042 return app;
3043}
3044
3045static struct alias *
3046lookupalias(const char *name, int check)
3047{
3048 struct alias *ap = *__lookupalias(name);
3049
3050 if (check && ap && (ap->flag & ALIASINUSE))
3051 return NULL;
3052 return ap;
3053}
3054
3055static struct alias *
3056freealias(struct alias *ap)
3057{
3058 struct alias *next;
3059
3060 if (ap->flag & ALIASINUSE) {
3061 ap->flag |= ALIASDEAD;
3062 return ap;
3063 }
3064
3065 next = ap->next;
3066 free(ap->name);
3067 free(ap->val);
3068 free(ap);
3069 return next;
3070}
Eric Andersencb57d552001-06-28 07:25:16 +00003071
Eric Andersenc470f442003-07-28 09:56:35 +00003072static void
3073setalias(const char *name, const char *val)
Eric Andersencb57d552001-06-28 07:25:16 +00003074{
3075 struct alias *ap, **app;
3076
3077 app = __lookupalias(name);
3078 ap = *app;
Denis Vlasenkob012b102007-02-19 22:43:01 +00003079 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +00003080 if (ap) {
3081 if (!(ap->flag & ALIASINUSE)) {
Denis Vlasenkob012b102007-02-19 22:43:01 +00003082 free(ap->val);
Eric Andersencb57d552001-06-28 07:25:16 +00003083 }
Denis Vlasenko0c032a42007-02-23 01:03:40 +00003084 ap->val = ckstrdup(val);
Eric Andersencb57d552001-06-28 07:25:16 +00003085 ap->flag &= ~ALIASDEAD;
3086 } else {
3087 /* not found */
Denis Vlasenko597906c2008-02-20 16:38:54 +00003088 ap = ckzalloc(sizeof(struct alias));
Denis Vlasenko0c032a42007-02-23 01:03:40 +00003089 ap->name = ckstrdup(name);
3090 ap->val = ckstrdup(val);
Denis Vlasenko597906c2008-02-20 16:38:54 +00003091 /*ap->flag = 0; - ckzalloc did it */
3092 /*ap->next = NULL;*/
Eric Andersencb57d552001-06-28 07:25:16 +00003093 *app = ap;
3094 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00003095 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00003096}
3097
Eric Andersenc470f442003-07-28 09:56:35 +00003098static int
3099unalias(const char *name)
Eric Andersen2870d962001-07-02 17:27:21 +00003100{
Eric Andersencb57d552001-06-28 07:25:16 +00003101 struct alias **app;
3102
3103 app = __lookupalias(name);
3104
3105 if (*app) {
Denis Vlasenkob012b102007-02-19 22:43:01 +00003106 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +00003107 *app = freealias(*app);
Denis Vlasenkob012b102007-02-19 22:43:01 +00003108 INT_ON;
Denis Vlasenko079f8af2006-11-27 16:49:31 +00003109 return 0;
Eric Andersencb57d552001-06-28 07:25:16 +00003110 }
3111
Denis Vlasenko079f8af2006-11-27 16:49:31 +00003112 return 1;
Eric Andersencb57d552001-06-28 07:25:16 +00003113}
3114
Eric Andersenc470f442003-07-28 09:56:35 +00003115static void
3116rmaliases(void)
Eric Andersen2870d962001-07-02 17:27:21 +00003117{
Eric Andersencb57d552001-06-28 07:25:16 +00003118 struct alias *ap, **app;
3119 int i;
3120
Denis Vlasenkob012b102007-02-19 22:43:01 +00003121 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +00003122 for (i = 0; i < ATABSIZE; i++) {
3123 app = &atab[i];
3124 for (ap = *app; ap; ap = *app) {
3125 *app = freealias(*app);
3126 if (ap == *app) {
3127 app = &ap->next;
3128 }
3129 }
3130 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00003131 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00003132}
3133
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00003134static void
3135printalias(const struct alias *ap)
3136{
3137 out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
3138}
3139
Eric Andersencb57d552001-06-28 07:25:16 +00003140/*
3141 * TODO - sort output
3142 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02003143static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00003144aliascmd(int argc UNUSED_PARAM, char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +00003145{
3146 char *n, *v;
3147 int ret = 0;
3148 struct alias *ap;
3149
Denis Vlasenko68404f12008-03-17 09:00:54 +00003150 if (!argv[1]) {
Eric Andersencb57d552001-06-28 07:25:16 +00003151 int i;
3152
Denis Vlasenko68404f12008-03-17 09:00:54 +00003153 for (i = 0; i < ATABSIZE; i++) {
Eric Andersencb57d552001-06-28 07:25:16 +00003154 for (ap = atab[i]; ap; ap = ap->next) {
3155 printalias(ap);
3156 }
Denis Vlasenko68404f12008-03-17 09:00:54 +00003157 }
Denis Vlasenko079f8af2006-11-27 16:49:31 +00003158 return 0;
Eric Andersencb57d552001-06-28 07:25:16 +00003159 }
3160 while ((n = *++argv) != NULL) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00003161 v = strchr(n+1, '=');
3162 if (v == NULL) { /* n+1: funny ksh stuff */
3163 ap = *__lookupalias(n);
3164 if (ap == NULL) {
Eric Andersenc470f442003-07-28 09:56:35 +00003165 fprintf(stderr, "%s: %s not found\n", "alias", n);
Eric Andersencb57d552001-06-28 07:25:16 +00003166 ret = 1;
3167 } else
3168 printalias(ap);
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00003169 } else {
Eric Andersencb57d552001-06-28 07:25:16 +00003170 *v++ = '\0';
3171 setalias(n, v);
3172 }
3173 }
3174
Denis Vlasenkod9e15f22006-11-27 16:49:55 +00003175 return ret;
Eric Andersencb57d552001-06-28 07:25:16 +00003176}
3177
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02003178static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00003179unaliascmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersencb57d552001-06-28 07:25:16 +00003180{
3181 int i;
3182
3183 while ((i = nextopt("a")) != '\0') {
3184 if (i == 'a') {
3185 rmaliases();
Denis Vlasenko079f8af2006-11-27 16:49:31 +00003186 return 0;
Eric Andersencb57d552001-06-28 07:25:16 +00003187 }
3188 }
3189 for (i = 0; *argptr; argptr++) {
3190 if (unalias(*argptr)) {
Eric Andersenc470f442003-07-28 09:56:35 +00003191 fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
Eric Andersencb57d552001-06-28 07:25:16 +00003192 i = 1;
3193 }
3194 }
3195
Denis Vlasenkod9e15f22006-11-27 16:49:55 +00003196 return i;
Eric Andersencb57d552001-06-28 07:25:16 +00003197}
Denis Vlasenkofc06f292007-02-23 21:09:35 +00003198
Denis Vlasenko131ae172007-02-18 13:00:19 +00003199#endif /* ASH_ALIAS */
Eric Andersencb57d552001-06-28 07:25:16 +00003200
Eric Andersenc470f442003-07-28 09:56:35 +00003201
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003202/* ============ jobs.c */
3203
3204/* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
Denys Vlasenko285ad152009-12-04 23:02:27 +01003205#define FORK_FG 0
3206#define FORK_BG 1
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003207#define FORK_NOJOB 2
3208
3209/* mode flags for showjob(s) */
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003210#define SHOW_ONLY_PGID 0x01 /* show only pgid (jobs -p) */
3211#define SHOW_PIDS 0x02 /* show individual pids, not just one line per job */
3212#define SHOW_CHANGED 0x04 /* only jobs whose state has changed */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003213
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003214/*
3215 * A job structure contains information about a job. A job is either a
3216 * single process or a set of processes contained in a pipeline. In the
3217 * latter case, pidlist will be non-NULL, and will point to a -1 terminated
3218 * array of pids.
3219 */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003220struct procstat {
Denys Vlasenko285ad152009-12-04 23:02:27 +01003221 pid_t ps_pid; /* process id */
3222 int ps_status; /* last process status from wait() */
3223 char *ps_cmd; /* text of command being run */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003224};
3225
3226struct job {
3227 struct procstat ps0; /* status of process */
3228 struct procstat *ps; /* status or processes when more than one */
3229#if JOBS
3230 int stopstatus; /* status of a stopped job */
3231#endif
3232 uint32_t
3233 nprocs: 16, /* number of processes */
3234 state: 8,
3235#define JOBRUNNING 0 /* at least one proc running */
3236#define JOBSTOPPED 1 /* all procs are stopped */
3237#define JOBDONE 2 /* all procs are completed */
3238#if JOBS
3239 sigint: 1, /* job was killed by SIGINT */
3240 jobctl: 1, /* job running under job control */
3241#endif
3242 waited: 1, /* true if this entry has been waited for */
3243 used: 1, /* true if this entry is in used */
3244 changed: 1; /* true if status has changed */
3245 struct job *prev_job; /* previous job */
3246};
3247
Denis Vlasenko68404f12008-03-17 09:00:54 +00003248static struct job *makejob(/*union node *,*/ int);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003249static int forkshell(struct job *, union node *, int);
3250static int waitforjob(struct job *);
3251
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003252#if !JOBS
Denis Vlasenkob07a4962008-06-22 13:16:23 +00003253enum { doing_jobctl = 0 };
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003254#define setjobctl(on) do {} while (0)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003255#else
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003256static smallint doing_jobctl; //references:8
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003257static void setjobctl(int);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003258#endif
3259
3260/*
Denis Vlasenko4b875702009-03-19 13:30:04 +00003261 * Ignore a signal.
3262 */
3263static void
3264ignoresig(int signo)
3265{
3266 /* Avoid unnecessary system calls. Is it already SIG_IGNed? */
3267 if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
3268 /* No, need to do it */
3269 signal(signo, SIG_IGN);
3270 }
3271 sigmode[signo - 1] = S_HARD_IGN;
3272}
3273
3274/*
3275 * Signal handler. Only one usage site - in setsignal()
3276 */
3277static void
3278onsig(int signo)
3279{
3280 gotsig[signo - 1] = 1;
3281
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02003282 if (signo == SIGINT && !trap[SIGINT]) {
3283 if (!suppress_int) {
3284 pending_sig = 0;
Denis Vlasenko4b875702009-03-19 13:30:04 +00003285 raise_interrupt(); /* does not return */
3286 }
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02003287 pending_int = 1;
Denis Vlasenko4b875702009-03-19 13:30:04 +00003288 } else {
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02003289 pending_sig = signo;
Denis Vlasenko4b875702009-03-19 13:30:04 +00003290 }
3291}
3292
3293/*
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003294 * Set the signal handler for the specified signal. The routine figures
3295 * out what it should be set to.
3296 */
3297static void
3298setsignal(int signo)
3299{
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003300 char *t;
3301 char cur_act, new_act;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003302 struct sigaction act;
3303
3304 t = trap[signo];
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003305 new_act = S_DFL;
3306 if (t != NULL) { /* trap for this sig is set */
3307 new_act = S_CATCH;
3308 if (t[0] == '\0') /* trap is "": ignore this sig */
3309 new_act = S_IGN;
3310 }
3311
3312 if (rootshell && new_act == S_DFL) {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003313 switch (signo) {
3314 case SIGINT:
3315 if (iflag || minusc || sflag == 0)
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003316 new_act = S_CATCH;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003317 break;
3318 case SIGQUIT:
3319#if DEBUG
3320 if (debug)
3321 break;
3322#endif
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003323 /* man bash:
3324 * "In all cases, bash ignores SIGQUIT. Non-builtin
3325 * commands run by bash have signal handlers
3326 * set to the values inherited by the shell
3327 * from its parent". */
3328 new_act = S_IGN;
3329 break;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003330 case SIGTERM:
3331 if (iflag)
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003332 new_act = S_IGN;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003333 break;
3334#if JOBS
3335 case SIGTSTP:
3336 case SIGTTOU:
3337 if (mflag)
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003338 new_act = S_IGN;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003339 break;
3340#endif
3341 }
3342 }
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003343//TODO: if !rootshell, we reset SIGQUIT to DFL,
3344//whereas we have to restore it to what shell got on entry
3345//from the parent. See comment above
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003346
3347 t = &sigmode[signo - 1];
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003348 cur_act = *t;
3349 if (cur_act == 0) {
3350 /* current setting is not yet known */
3351 if (sigaction(signo, NULL, &act)) {
3352 /* pretend it worked; maybe we should give a warning,
3353 * but other shells don't. We don't alter sigmode,
3354 * so we retry every time.
3355 * btw, in Linux it never fails. --vda */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003356 return;
3357 }
3358 if (act.sa_handler == SIG_IGN) {
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003359 cur_act = S_HARD_IGN;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003360 if (mflag
3361 && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
3362 ) {
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003363 cur_act = S_IGN; /* don't hard ignore these */
Denis Vlasenko991a1da2008-02-10 19:02:53 +00003364 }
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003365 }
3366 }
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003367 if (cur_act == S_HARD_IGN || cur_act == new_act)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003368 return;
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003369
Denis Vlasenko991a1da2008-02-10 19:02:53 +00003370 act.sa_handler = SIG_DFL;
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003371 switch (new_act) {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003372 case S_CATCH:
3373 act.sa_handler = onsig;
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003374 act.sa_flags = 0; /* matters only if !DFL and !IGN */
3375 sigfillset(&act.sa_mask); /* ditto */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003376 break;
3377 case S_IGN:
3378 act.sa_handler = SIG_IGN;
3379 break;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003380 }
Denis Vlasenko8e2cfec2008-03-12 23:19:35 +00003381 sigaction_set(signo, &act);
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003382
3383 *t = new_act;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003384}
3385
3386/* mode flags for set_curjob */
3387#define CUR_DELETE 2
3388#define CUR_RUNNING 1
3389#define CUR_STOPPED 0
3390
3391/* mode flags for dowait */
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00003392#define DOWAIT_NONBLOCK WNOHANG
3393#define DOWAIT_BLOCK 0
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003394
3395#if JOBS
3396/* pgrp of shell on invocation */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003397static int initialpgrp; //references:2
3398static int ttyfd = -1; //5
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003399#endif
3400/* array of jobs */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003401static struct job *jobtab; //5
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003402/* size of array */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003403static unsigned njobs; //4
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003404/* current job */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003405static struct job *curjob; //lots
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003406/* number of presumed living untracked jobs */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003407static int jobless; //4
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003408
3409static void
3410set_curjob(struct job *jp, unsigned mode)
3411{
3412 struct job *jp1;
3413 struct job **jpp, **curp;
3414
3415 /* first remove from list */
3416 jpp = curp = &curjob;
3417 do {
3418 jp1 = *jpp;
3419 if (jp1 == jp)
3420 break;
3421 jpp = &jp1->prev_job;
3422 } while (1);
3423 *jpp = jp1->prev_job;
3424
3425 /* Then re-insert in correct position */
3426 jpp = curp;
3427 switch (mode) {
3428 default:
3429#if DEBUG
3430 abort();
3431#endif
3432 case CUR_DELETE:
3433 /* job being deleted */
3434 break;
3435 case CUR_RUNNING:
3436 /* newly created job or backgrounded job,
3437 put after all stopped jobs. */
3438 do {
3439 jp1 = *jpp;
3440#if JOBS
3441 if (!jp1 || jp1->state != JOBSTOPPED)
3442#endif
3443 break;
3444 jpp = &jp1->prev_job;
3445 } while (1);
3446 /* FALLTHROUGH */
3447#if JOBS
3448 case CUR_STOPPED:
3449#endif
3450 /* newly stopped job - becomes curjob */
3451 jp->prev_job = *jpp;
3452 *jpp = jp;
3453 break;
3454 }
3455}
3456
3457#if JOBS || DEBUG
3458static int
3459jobno(const struct job *jp)
3460{
3461 return jp - jobtab + 1;
3462}
3463#endif
3464
3465/*
3466 * Convert a job name to a job structure.
3467 */
Denis Vlasenko85c24712008-03-17 09:04:04 +00003468#if !JOBS
3469#define getjob(name, getctl) getjob(name)
3470#endif
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003471static struct job *
3472getjob(const char *name, int getctl)
3473{
3474 struct job *jp;
3475 struct job *found;
Denys Vlasenkoffc39202009-08-17 02:12:20 +02003476 const char *err_msg = "%s: no such job";
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003477 unsigned num;
3478 int c;
3479 const char *p;
3480 char *(*match)(const char *, const char *);
3481
3482 jp = curjob;
3483 p = name;
3484 if (!p)
3485 goto currentjob;
3486
3487 if (*p != '%')
3488 goto err;
3489
3490 c = *++p;
3491 if (!c)
3492 goto currentjob;
3493
3494 if (!p[1]) {
3495 if (c == '+' || c == '%') {
3496 currentjob:
3497 err_msg = "No current job";
3498 goto check;
3499 }
3500 if (c == '-') {
3501 if (jp)
3502 jp = jp->prev_job;
3503 err_msg = "No previous job";
3504 check:
3505 if (!jp)
3506 goto err;
3507 goto gotit;
3508 }
3509 }
3510
3511 if (is_number(p)) {
3512 num = atoi(p);
3513 if (num < njobs) {
3514 jp = jobtab + num - 1;
3515 if (jp->used)
3516 goto gotit;
3517 goto err;
3518 }
3519 }
3520
3521 match = prefix;
3522 if (*p == '?') {
3523 match = strstr;
3524 p++;
3525 }
3526
Denys Vlasenkoffc39202009-08-17 02:12:20 +02003527 found = NULL;
3528 while (jp) {
Denys Vlasenko285ad152009-12-04 23:02:27 +01003529 if (match(jp->ps[0].ps_cmd, p)) {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003530 if (found)
3531 goto err;
3532 found = jp;
3533 err_msg = "%s: ambiguous";
3534 }
3535 jp = jp->prev_job;
3536 }
Denys Vlasenkoffc39202009-08-17 02:12:20 +02003537 if (!found)
3538 goto err;
3539 jp = found;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003540
3541 gotit:
3542#if JOBS
3543 err_msg = "job %s not created under job control";
3544 if (getctl && jp->jobctl == 0)
3545 goto err;
3546#endif
3547 return jp;
3548 err:
3549 ash_msg_and_raise_error(err_msg, name);
3550}
3551
3552/*
3553 * Mark a job structure as unused.
3554 */
3555static void
3556freejob(struct job *jp)
3557{
3558 struct procstat *ps;
3559 int i;
3560
3561 INT_OFF;
3562 for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
Denys Vlasenko285ad152009-12-04 23:02:27 +01003563 if (ps->ps_cmd != nullstr)
3564 free(ps->ps_cmd);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003565 }
3566 if (jp->ps != &jp->ps0)
3567 free(jp->ps);
3568 jp->used = 0;
3569 set_curjob(jp, CUR_DELETE);
3570 INT_ON;
3571}
3572
3573#if JOBS
3574static void
3575xtcsetpgrp(int fd, pid_t pgrp)
3576{
3577 if (tcsetpgrp(fd, pgrp))
Bernhard Reutner-Fischera53de7f2008-07-21 13:46:54 +00003578 ash_msg_and_raise_error("can't set tty process group (%m)");
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003579}
3580
3581/*
3582 * Turn job control on and off.
3583 *
3584 * Note: This code assumes that the third arg to ioctl is a character
3585 * pointer, which is true on Berkeley systems but not System V. Since
3586 * System V doesn't have job control yet, this isn't a problem now.
3587 *
3588 * Called with interrupts off.
3589 */
3590static void
3591setjobctl(int on)
3592{
3593 int fd;
3594 int pgrp;
3595
Denis Vlasenkob07a4962008-06-22 13:16:23 +00003596 if (on == doing_jobctl || rootshell == 0)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003597 return;
3598 if (on) {
3599 int ofd;
3600 ofd = fd = open(_PATH_TTY, O_RDWR);
3601 if (fd < 0) {
3602 /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
3603 * That sometimes helps to acquire controlling tty.
3604 * Obviously, a workaround for bugs when someone
3605 * failed to provide a controlling tty to bash! :) */
Denis Vlasenkoed270a52007-11-26 05:37:07 +00003606 fd = 2;
3607 while (!isatty(fd))
3608 if (--fd < 0)
3609 goto out;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003610 }
3611 fd = fcntl(fd, F_DUPFD, 10);
Denis Vlasenkoed270a52007-11-26 05:37:07 +00003612 if (ofd >= 0)
3613 close(ofd);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003614 if (fd < 0)
3615 goto out;
Denis Vlasenkoed270a52007-11-26 05:37:07 +00003616 /* fd is a tty at this point */
Denis Vlasenko96e1b382007-09-30 23:50:48 +00003617 close_on_exec_on(fd);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003618 do { /* while we are in the background */
3619 pgrp = tcgetpgrp(fd);
3620 if (pgrp < 0) {
3621 out:
3622 ash_msg("can't access tty; job control turned off");
3623 mflag = on = 0;
3624 goto close;
3625 }
3626 if (pgrp == getpgrp())
3627 break;
3628 killpg(0, SIGTTIN);
3629 } while (1);
3630 initialpgrp = pgrp;
3631
3632 setsignal(SIGTSTP);
3633 setsignal(SIGTTOU);
3634 setsignal(SIGTTIN);
3635 pgrp = rootpid;
3636 setpgid(0, pgrp);
3637 xtcsetpgrp(fd, pgrp);
3638 } else {
3639 /* turning job control off */
3640 fd = ttyfd;
3641 pgrp = initialpgrp;
Denis Vlasenko08c8c1d2007-04-28 22:39:02 +00003642 /* was xtcsetpgrp, but this can make exiting ash
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00003643 * loop forever if pty is already deleted */
Denis Vlasenko08c8c1d2007-04-28 22:39:02 +00003644 tcsetpgrp(fd, pgrp);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003645 setpgid(0, pgrp);
3646 setsignal(SIGTSTP);
3647 setsignal(SIGTTOU);
3648 setsignal(SIGTTIN);
3649 close:
Denis Vlasenkoed270a52007-11-26 05:37:07 +00003650 if (fd >= 0)
3651 close(fd);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003652 fd = -1;
3653 }
3654 ttyfd = fd;
Denis Vlasenkob07a4962008-06-22 13:16:23 +00003655 doing_jobctl = on;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003656}
3657
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02003658static int FAST_FUNC
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003659killcmd(int argc, char **argv)
3660{
Denis Vlasenko68404f12008-03-17 09:00:54 +00003661 int i = 1;
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003662 if (argv[1] && strcmp(argv[1], "-l") != 0) {
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003663 do {
3664 if (argv[i][0] == '%') {
3665 struct job *jp = getjob(argv[i], 0);
Denys Vlasenko285ad152009-12-04 23:02:27 +01003666 unsigned pid = jp->ps[0].ps_pid;
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003667 /* Enough space for ' -NNN<nul>' */
3668 argv[i] = alloca(sizeof(int)*3 + 3);
3669 /* kill_main has matching code to expect
3670 * leading space. Needed to not confuse
3671 * negative pids with "kill -SIGNAL_NO" syntax */
3672 sprintf(argv[i], " -%u", pid);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003673 }
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003674 } while (argv[++i]);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003675 }
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003676 return kill_main(argc, argv);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003677}
3678
3679static void
Denys Vlasenko285ad152009-12-04 23:02:27 +01003680showpipe(struct job *jp /*, FILE *out*/)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003681{
Denys Vlasenko285ad152009-12-04 23:02:27 +01003682 struct procstat *ps;
3683 struct procstat *psend;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003684
Denys Vlasenko285ad152009-12-04 23:02:27 +01003685 psend = jp->ps + jp->nprocs;
3686 for (ps = jp->ps + 1; ps < psend; ps++)
3687 printf(" | %s", ps->ps_cmd);
3688 outcslow('\n', stdout);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003689 flush_stdout_stderr();
3690}
3691
3692
3693static int
3694restartjob(struct job *jp, int mode)
3695{
3696 struct procstat *ps;
3697 int i;
3698 int status;
3699 pid_t pgid;
3700
3701 INT_OFF;
3702 if (jp->state == JOBDONE)
3703 goto out;
3704 jp->state = JOBRUNNING;
Denys Vlasenko285ad152009-12-04 23:02:27 +01003705 pgid = jp->ps[0].ps_pid;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003706 if (mode == FORK_FG)
3707 xtcsetpgrp(ttyfd, pgid);
3708 killpg(pgid, SIGCONT);
3709 ps = jp->ps;
3710 i = jp->nprocs;
3711 do {
Denys Vlasenko285ad152009-12-04 23:02:27 +01003712 if (WIFSTOPPED(ps->ps_status)) {
3713 ps->ps_status = -1;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003714 }
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003715 ps++;
3716 } while (--i);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003717 out:
3718 status = (mode == FORK_FG) ? waitforjob(jp) : 0;
3719 INT_ON;
3720 return status;
3721}
3722
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02003723static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00003724fg_bgcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003725{
3726 struct job *jp;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003727 int mode;
3728 int retval;
3729
3730 mode = (**argv == 'f') ? FORK_FG : FORK_BG;
3731 nextopt(nullstr);
3732 argv = argptr;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003733 do {
3734 jp = getjob(*argv, 1);
3735 if (mode == FORK_BG) {
3736 set_curjob(jp, CUR_RUNNING);
Denys Vlasenko285ad152009-12-04 23:02:27 +01003737 printf("[%d] ", jobno(jp));
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003738 }
Denys Vlasenko285ad152009-12-04 23:02:27 +01003739 out1str(jp->ps[0].ps_cmd);
3740 showpipe(jp /*, stdout*/);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003741 retval = restartjob(jp, mode);
3742 } while (*argv && *++argv);
3743 return retval;
3744}
3745#endif
3746
3747static int
3748sprint_status(char *s, int status, int sigonly)
3749{
3750 int col;
3751 int st;
3752
3753 col = 0;
3754 if (!WIFEXITED(status)) {
3755#if JOBS
3756 if (WIFSTOPPED(status))
3757 st = WSTOPSIG(status);
3758 else
3759#endif
3760 st = WTERMSIG(status);
3761 if (sigonly) {
3762 if (st == SIGINT || st == SIGPIPE)
3763 goto out;
3764#if JOBS
3765 if (WIFSTOPPED(status))
3766 goto out;
3767#endif
3768 }
3769 st &= 0x7f;
3770 col = fmtstr(s, 32, strsignal(st));
3771 if (WCOREDUMP(status)) {
3772 col += fmtstr(s + col, 16, " (core dumped)");
3773 }
3774 } else if (!sigonly) {
3775 st = WEXITSTATUS(status);
3776 if (st)
3777 col = fmtstr(s, 16, "Done(%d)", st);
3778 else
3779 col = fmtstr(s, 16, "Done");
3780 }
3781 out:
3782 return col;
3783}
3784
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003785static int
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00003786dowait(int wait_flags, struct job *job)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003787{
3788 int pid;
3789 int status;
3790 struct job *jp;
3791 struct job *thisjob;
3792 int state;
3793
Denis Vlasenkobe54d6b2008-10-27 14:25:52 +00003794 TRACE(("dowait(0x%x) called\n", wait_flags));
3795
3796 /* Do a wait system call. If job control is compiled in, we accept
3797 * stopped processes. wait_flags may have WNOHANG, preventing blocking.
3798 * NB: _not_ safe_waitpid, we need to detect EINTR */
Denys Vlasenko285ad152009-12-04 23:02:27 +01003799 if (doing_jobctl)
3800 wait_flags |= WUNTRACED;
3801 pid = waitpid(-1, &status, wait_flags);
Denis Vlasenkob21f3792009-03-19 23:09:58 +00003802 TRACE(("wait returns pid=%d, status=0x%x, errno=%d(%s)\n",
3803 pid, status, errno, strerror(errno)));
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003804 if (pid <= 0)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003805 return pid;
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003806
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003807 INT_OFF;
3808 thisjob = NULL;
3809 for (jp = curjob; jp; jp = jp->prev_job) {
Denys Vlasenko285ad152009-12-04 23:02:27 +01003810 struct procstat *ps;
3811 struct procstat *psend;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003812 if (jp->state == JOBDONE)
3813 continue;
3814 state = JOBDONE;
Denys Vlasenko285ad152009-12-04 23:02:27 +01003815 ps = jp->ps;
3816 psend = ps + jp->nprocs;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003817 do {
Denys Vlasenko285ad152009-12-04 23:02:27 +01003818 if (ps->ps_pid == pid) {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003819 TRACE(("Job %d: changing status of proc %d "
3820 "from 0x%x to 0x%x\n",
Denys Vlasenko285ad152009-12-04 23:02:27 +01003821 jobno(jp), pid, ps->ps_status, status));
3822 ps->ps_status = status;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003823 thisjob = jp;
3824 }
Denys Vlasenko285ad152009-12-04 23:02:27 +01003825 if (ps->ps_status == -1)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003826 state = JOBRUNNING;
3827#if JOBS
3828 if (state == JOBRUNNING)
3829 continue;
Denys Vlasenko285ad152009-12-04 23:02:27 +01003830 if (WIFSTOPPED(ps->ps_status)) {
3831 jp->stopstatus = ps->ps_status;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003832 state = JOBSTOPPED;
3833 }
3834#endif
Denys Vlasenko285ad152009-12-04 23:02:27 +01003835 } while (++ps < psend);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003836 if (thisjob)
3837 goto gotjob;
3838 }
3839#if JOBS
3840 if (!WIFSTOPPED(status))
3841#endif
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003842 jobless--;
3843 goto out;
3844
3845 gotjob:
3846 if (state != JOBRUNNING) {
3847 thisjob->changed = 1;
3848
3849 if (thisjob->state != state) {
3850 TRACE(("Job %d: changing state from %d to %d\n",
3851 jobno(thisjob), thisjob->state, state));
3852 thisjob->state = state;
3853#if JOBS
3854 if (state == JOBSTOPPED) {
3855 set_curjob(thisjob, CUR_STOPPED);
3856 }
3857#endif
3858 }
3859 }
3860
3861 out:
3862 INT_ON;
3863
3864 if (thisjob && thisjob == job) {
3865 char s[48 + 1];
3866 int len;
3867
3868 len = sprint_status(s, status, 1);
3869 if (len) {
3870 s[len] = '\n';
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00003871 s[len + 1] = '\0';
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003872 out2str(s);
3873 }
3874 }
3875 return pid;
3876}
3877
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003878static int
3879blocking_wait_with_raise_on_sig(struct job *job)
3880{
3881 pid_t pid = dowait(DOWAIT_BLOCK, job);
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02003882 if (pid <= 0 && pending_sig)
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003883 raise_exception(EXSIG);
3884 return pid;
3885}
3886
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003887#if JOBS
3888static void
3889showjob(FILE *out, struct job *jp, int mode)
3890{
3891 struct procstat *ps;
3892 struct procstat *psend;
3893 int col;
Denis Vlasenko40ba9982007-07-14 00:48:29 +00003894 int indent_col;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003895 char s[80];
3896
3897 ps = jp->ps;
3898
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003899 if (mode & SHOW_ONLY_PGID) { /* jobs -p */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003900 /* just output process (group) id of pipeline */
Denys Vlasenko285ad152009-12-04 23:02:27 +01003901 fprintf(out, "%d\n", ps->ps_pid);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003902 return;
3903 }
3904
3905 col = fmtstr(s, 16, "[%d] ", jobno(jp));
Denis Vlasenko40ba9982007-07-14 00:48:29 +00003906 indent_col = col;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003907
3908 if (jp == curjob)
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003909 s[col - 3] = '+';
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003910 else if (curjob && jp == curjob->prev_job)
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003911 s[col - 3] = '-';
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003912
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003913 if (mode & SHOW_PIDS)
Denys Vlasenko285ad152009-12-04 23:02:27 +01003914 col += fmtstr(s + col, 16, "%d ", ps->ps_pid);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003915
3916 psend = ps + jp->nprocs;
3917
3918 if (jp->state == JOBRUNNING) {
3919 strcpy(s + col, "Running");
3920 col += sizeof("Running") - 1;
3921 } else {
Denys Vlasenko285ad152009-12-04 23:02:27 +01003922 int status = psend[-1].ps_status;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003923 if (jp->state == JOBSTOPPED)
3924 status = jp->stopstatus;
3925 col += sprint_status(s + col, status, 0);
3926 }
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003927 /* By now, "[JOBID]* [maybe PID] STATUS" is printed */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003928
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003929 /* This loop either prints "<cmd1> | <cmd2> | <cmd3>" line
3930 * or prints several "PID | <cmdN>" lines,
3931 * depending on SHOW_PIDS bit.
3932 * We do not print status of individual processes
3933 * between PID and <cmdN>. bash does it, but not very well:
3934 * first line shows overall job status, not process status,
3935 * making it impossible to know 1st process status.
3936 */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003937 goto start;
Denys Vlasenko285ad152009-12-04 23:02:27 +01003938 do {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003939 /* for each process */
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003940 s[0] = '\0';
3941 col = 33;
3942 if (mode & SHOW_PIDS)
Denys Vlasenko285ad152009-12-04 23:02:27 +01003943 col = fmtstr(s, 48, "\n%*c%d ", indent_col, ' ', ps->ps_pid) - 1;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003944 start:
Denys Vlasenko285ad152009-12-04 23:02:27 +01003945 fprintf(out, "%s%*c%s%s",
3946 s,
3947 33 - col >= 0 ? 33 - col : 0, ' ',
3948 ps == jp->ps ? "" : "| ",
3949 ps->ps_cmd
3950 );
3951 } while (++ps != psend);
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003952 outcslow('\n', out);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003953
3954 jp->changed = 0;
3955
3956 if (jp->state == JOBDONE) {
3957 TRACE(("showjob: freeing job %d\n", jobno(jp)));
3958 freejob(jp);
3959 }
3960}
3961
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003962/*
3963 * Print a list of jobs. If "change" is nonzero, only print jobs whose
3964 * statuses have changed since the last call to showjobs.
3965 */
3966static void
3967showjobs(FILE *out, int mode)
3968{
3969 struct job *jp;
3970
Denys Vlasenko883cea42009-07-11 15:31:59 +02003971 TRACE(("showjobs(0x%x) called\n", mode));
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003972
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003973 /* Handle all finished jobs */
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00003974 while (dowait(DOWAIT_NONBLOCK, NULL) > 0)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003975 continue;
3976
3977 for (jp = curjob; jp; jp = jp->prev_job) {
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003978 if (!(mode & SHOW_CHANGED) || jp->changed) {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003979 showjob(out, jp, mode);
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003980 }
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003981 }
3982}
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003983
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02003984static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00003985jobscmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003986{
3987 int mode, m;
3988
3989 mode = 0;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02003990 while ((m = nextopt("lp")) != '\0') {
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003991 if (m == 'l')
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003992 mode |= SHOW_PIDS;
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003993 else
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003994 mode |= SHOW_ONLY_PGID;
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003995 }
3996
3997 argv = argptr;
3998 if (*argv) {
3999 do
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02004000 showjob(stdout, getjob(*argv, 0), mode);
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00004001 while (*++argv);
Denys Vlasenko285ad152009-12-04 23:02:27 +01004002 } else {
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00004003 showjobs(stdout, mode);
Denys Vlasenko285ad152009-12-04 23:02:27 +01004004 }
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00004005
4006 return 0;
4007}
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004008#endif /* JOBS */
4009
Michael Abbott359da5e2009-12-04 23:03:29 +01004010/* Called only on finished or stopped jobs (no members are running) */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004011static int
4012getstatus(struct job *job)
4013{
4014 int status;
4015 int retval;
Michael Abbott359da5e2009-12-04 23:03:29 +01004016 struct procstat *ps;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004017
Michael Abbott359da5e2009-12-04 23:03:29 +01004018 /* Fetch last member's status */
4019 ps = job->ps + job->nprocs - 1;
4020 status = ps->ps_status;
4021 if (pipefail) {
4022 /* "set -o pipefail" mode: use last _nonzero_ status */
4023 while (status == 0 && --ps >= job->ps)
4024 status = ps->ps_status;
4025 }
4026
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004027 retval = WEXITSTATUS(status);
4028 if (!WIFEXITED(status)) {
4029#if JOBS
4030 retval = WSTOPSIG(status);
4031 if (!WIFSTOPPED(status))
4032#endif
4033 {
4034 /* XXX: limits number of signals */
4035 retval = WTERMSIG(status);
4036#if JOBS
4037 if (retval == SIGINT)
4038 job->sigint = 1;
4039#endif
4040 }
4041 retval += 128;
4042 }
Denys Vlasenko883cea42009-07-11 15:31:59 +02004043 TRACE(("getstatus: job %d, nproc %d, status 0x%x, retval 0x%x\n",
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004044 jobno(job), job->nprocs, status, retval));
4045 return retval;
4046}
4047
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02004048static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00004049waitcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004050{
4051 struct job *job;
4052 int retval;
4053 struct job *jp;
4054
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02004055 if (pending_sig)
Denis Vlasenko991a1da2008-02-10 19:02:53 +00004056 raise_exception(EXSIG);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004057
4058 nextopt(nullstr);
4059 retval = 0;
4060
4061 argv = argptr;
4062 if (!*argv) {
4063 /* wait for all jobs */
4064 for (;;) {
4065 jp = curjob;
4066 while (1) {
Denis Vlasenko991a1da2008-02-10 19:02:53 +00004067 if (!jp) /* no running procs */
4068 goto ret;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004069 if (jp->state == JOBRUNNING)
4070 break;
4071 jp->waited = 1;
4072 jp = jp->prev_job;
4073 }
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004074 /* man bash:
4075 * "When bash is waiting for an asynchronous command via
4076 * the wait builtin, the reception of a signal for which a trap
4077 * has been set will cause the wait builtin to return immediately
4078 * with an exit status greater than 128, immediately after which
4079 * the trap is executed."
4080 * Do we do it that way? */
4081 blocking_wait_with_raise_on_sig(NULL);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004082 }
4083 }
4084
4085 retval = 127;
4086 do {
4087 if (**argv != '%') {
4088 pid_t pid = number(*argv);
4089 job = curjob;
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00004090 while (1) {
4091 if (!job)
4092 goto repeat;
Denys Vlasenko285ad152009-12-04 23:02:27 +01004093 if (job->ps[job->nprocs - 1].ps_pid == pid)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004094 break;
4095 job = job->prev_job;
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00004096 }
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004097 } else
4098 job = getjob(*argv, 0);
4099 /* loop until process terminated or stopped */
4100 while (job->state == JOBRUNNING)
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004101 blocking_wait_with_raise_on_sig(NULL);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004102 job->waited = 1;
4103 retval = getstatus(job);
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004104 repeat: ;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004105 } while (*++argv);
4106
Denis Vlasenko991a1da2008-02-10 19:02:53 +00004107 ret:
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004108 return retval;
4109}
4110
4111static struct job *
4112growjobtab(void)
4113{
4114 size_t len;
4115 ptrdiff_t offset;
4116 struct job *jp, *jq;
4117
4118 len = njobs * sizeof(*jp);
4119 jq = jobtab;
4120 jp = ckrealloc(jq, len + 4 * sizeof(*jp));
4121
4122 offset = (char *)jp - (char *)jq;
4123 if (offset) {
4124 /* Relocate pointers */
4125 size_t l = len;
4126
4127 jq = (struct job *)((char *)jq + l);
4128 while (l) {
4129 l -= sizeof(*jp);
4130 jq--;
4131#define joff(p) ((struct job *)((char *)(p) + l))
4132#define jmove(p) (p) = (void *)((char *)(p) + offset)
4133 if (joff(jp)->ps == &jq->ps0)
4134 jmove(joff(jp)->ps);
4135 if (joff(jp)->prev_job)
4136 jmove(joff(jp)->prev_job);
4137 }
4138 if (curjob)
4139 jmove(curjob);
4140#undef joff
4141#undef jmove
4142 }
4143
4144 njobs += 4;
4145 jobtab = jp;
4146 jp = (struct job *)((char *)jp + len);
4147 jq = jp + 3;
4148 do {
4149 jq->used = 0;
4150 } while (--jq >= jp);
4151 return jp;
4152}
4153
4154/*
4155 * Return a new job structure.
4156 * Called with interrupts off.
4157 */
4158static struct job *
Denis Vlasenko68404f12008-03-17 09:00:54 +00004159makejob(/*union node *node,*/ int nprocs)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004160{
4161 int i;
4162 struct job *jp;
4163
4164 for (i = njobs, jp = jobtab; ; jp++) {
4165 if (--i < 0) {
4166 jp = growjobtab();
4167 break;
4168 }
4169 if (jp->used == 0)
4170 break;
4171 if (jp->state != JOBDONE || !jp->waited)
4172 continue;
4173#if JOBS
Denis Vlasenkob07a4962008-06-22 13:16:23 +00004174 if (doing_jobctl)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004175 continue;
4176#endif
4177 freejob(jp);
4178 break;
4179 }
4180 memset(jp, 0, sizeof(*jp));
4181#if JOBS
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00004182 /* jp->jobctl is a bitfield.
4183 * "jp->jobctl |= jobctl" likely to give awful code */
Denis Vlasenkob07a4962008-06-22 13:16:23 +00004184 if (doing_jobctl)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004185 jp->jobctl = 1;
4186#endif
4187 jp->prev_job = curjob;
4188 curjob = jp;
4189 jp->used = 1;
4190 jp->ps = &jp->ps0;
4191 if (nprocs > 1) {
4192 jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
4193 }
Denis Vlasenko68404f12008-03-17 09:00:54 +00004194 TRACE(("makejob(%d) returns %%%d\n", nprocs,
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004195 jobno(jp)));
4196 return jp;
4197}
4198
4199#if JOBS
4200/*
4201 * Return a string identifying a command (to be printed by the
4202 * jobs command).
4203 */
4204static char *cmdnextc;
4205
4206static void
4207cmdputs(const char *s)
4208{
Denis Vlasenko92e13c22008-03-25 01:17:40 +00004209 static const char vstype[VSTYPE + 1][3] = {
4210 "", "}", "-", "+", "?", "=",
4211 "%", "%%", "#", "##"
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00004212 IF_ASH_BASH_COMPAT(, ":", "/", "//")
Denis Vlasenko92e13c22008-03-25 01:17:40 +00004213 };
4214
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004215 const char *p, *str;
Denys Vlasenko46a14772009-12-10 21:27:13 +01004216 char cc[2];
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004217 char *nextc;
Denys Vlasenkocd716832009-11-28 22:14:02 +01004218 unsigned char c;
4219 unsigned char subtype = 0;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004220 int quoted = 0;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004221
Denys Vlasenko46a14772009-12-10 21:27:13 +01004222 cc[1] = '\0';
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004223 nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
4224 p = s;
Denys Vlasenko46a14772009-12-10 21:27:13 +01004225 while ((c = *p++) != '\0') {
Denis Vlasenkoef527f52008-06-23 01:52:30 +00004226 str = NULL;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004227 switch (c) {
4228 case CTLESC:
4229 c = *p++;
4230 break;
4231 case CTLVAR:
4232 subtype = *p++;
4233 if ((subtype & VSTYPE) == VSLENGTH)
4234 str = "${#";
4235 else
4236 str = "${";
4237 if (!(subtype & VSQUOTE) == !(quoted & 1))
4238 goto dostr;
4239 quoted ^= 1;
4240 c = '"';
4241 break;
4242 case CTLENDVAR:
4243 str = "\"}" + !(quoted & 1);
4244 quoted >>= 1;
4245 subtype = 0;
4246 goto dostr;
4247 case CTLBACKQ:
4248 str = "$(...)";
4249 goto dostr;
4250 case CTLBACKQ+CTLQUOTE:
4251 str = "\"$(...)\"";
4252 goto dostr;
Mike Frysinger98c52642009-04-02 10:02:37 +00004253#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004254 case CTLARI:
4255 str = "$((";
4256 goto dostr;
4257 case CTLENDARI:
4258 str = "))";
4259 goto dostr;
4260#endif
4261 case CTLQUOTEMARK:
4262 quoted ^= 1;
4263 c = '"';
4264 break;
4265 case '=':
4266 if (subtype == 0)
4267 break;
4268 if ((subtype & VSTYPE) != VSNORMAL)
4269 quoted <<= 1;
4270 str = vstype[subtype & VSTYPE];
4271 if (subtype & VSNUL)
4272 c = ':';
4273 else
4274 goto checkstr;
4275 break;
4276 case '\'':
4277 case '\\':
4278 case '"':
4279 case '$':
4280 /* These can only happen inside quotes */
4281 cc[0] = c;
4282 str = cc;
4283 c = '\\';
4284 break;
4285 default:
4286 break;
4287 }
4288 USTPUTC(c, nextc);
4289 checkstr:
4290 if (!str)
4291 continue;
4292 dostr:
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02004293 while ((c = *str++) != '\0') {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004294 USTPUTC(c, nextc);
4295 }
Denys Vlasenko46a14772009-12-10 21:27:13 +01004296 } /* while *p++ not NUL */
4297
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004298 if (quoted & 1) {
4299 USTPUTC('"', nextc);
4300 }
4301 *nextc = 0;
4302 cmdnextc = nextc;
4303}
4304
4305/* cmdtxt() and cmdlist() call each other */
4306static void cmdtxt(union node *n);
4307
4308static void
4309cmdlist(union node *np, int sep)
4310{
4311 for (; np; np = np->narg.next) {
4312 if (!sep)
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00004313 cmdputs(" ");
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004314 cmdtxt(np);
4315 if (sep && np->narg.next)
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00004316 cmdputs(" ");
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004317 }
4318}
4319
4320static void
4321cmdtxt(union node *n)
4322{
4323 union node *np;
4324 struct nodelist *lp;
4325 const char *p;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004326
4327 if (!n)
4328 return;
4329 switch (n->type) {
4330 default:
4331#if DEBUG
4332 abort();
4333#endif
4334 case NPIPE:
4335 lp = n->npipe.cmdlist;
4336 for (;;) {
4337 cmdtxt(lp->n);
4338 lp = lp->next;
4339 if (!lp)
4340 break;
4341 cmdputs(" | ");
4342 }
4343 break;
4344 case NSEMI:
4345 p = "; ";
4346 goto binop;
4347 case NAND:
4348 p = " && ";
4349 goto binop;
4350 case NOR:
4351 p = " || ";
4352 binop:
4353 cmdtxt(n->nbinary.ch1);
4354 cmdputs(p);
4355 n = n->nbinary.ch2;
4356 goto donode;
4357 case NREDIR:
4358 case NBACKGND:
4359 n = n->nredir.n;
4360 goto donode;
4361 case NNOT:
4362 cmdputs("!");
4363 n = n->nnot.com;
4364 donode:
4365 cmdtxt(n);
4366 break;
4367 case NIF:
4368 cmdputs("if ");
4369 cmdtxt(n->nif.test);
4370 cmdputs("; then ");
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004371 if (n->nif.elsepart) {
Denys Vlasenko7cee00e2009-07-24 01:08:03 +02004372 cmdtxt(n->nif.ifpart);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004373 cmdputs("; else ");
4374 n = n->nif.elsepart;
Denys Vlasenko7cee00e2009-07-24 01:08:03 +02004375 } else {
4376 n = n->nif.ifpart;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004377 }
4378 p = "; fi";
4379 goto dotail;
4380 case NSUBSHELL:
4381 cmdputs("(");
4382 n = n->nredir.n;
4383 p = ")";
4384 goto dotail;
4385 case NWHILE:
4386 p = "while ";
4387 goto until;
4388 case NUNTIL:
4389 p = "until ";
4390 until:
4391 cmdputs(p);
4392 cmdtxt(n->nbinary.ch1);
4393 n = n->nbinary.ch2;
4394 p = "; done";
4395 dodo:
4396 cmdputs("; do ");
4397 dotail:
4398 cmdtxt(n);
4399 goto dotail2;
4400 case NFOR:
4401 cmdputs("for ");
4402 cmdputs(n->nfor.var);
4403 cmdputs(" in ");
4404 cmdlist(n->nfor.args, 1);
4405 n = n->nfor.body;
4406 p = "; done";
4407 goto dodo;
4408 case NDEFUN:
4409 cmdputs(n->narg.text);
4410 p = "() { ... }";
4411 goto dotail2;
4412 case NCMD:
4413 cmdlist(n->ncmd.args, 1);
4414 cmdlist(n->ncmd.redirect, 0);
4415 break;
4416 case NARG:
4417 p = n->narg.text;
4418 dotail2:
4419 cmdputs(p);
4420 break;
4421 case NHERE:
4422 case NXHERE:
4423 p = "<<...";
4424 goto dotail2;
4425 case NCASE:
4426 cmdputs("case ");
4427 cmdputs(n->ncase.expr->narg.text);
4428 cmdputs(" in ");
4429 for (np = n->ncase.cases; np; np = np->nclist.next) {
4430 cmdtxt(np->nclist.pattern);
4431 cmdputs(") ");
4432 cmdtxt(np->nclist.body);
4433 cmdputs(";; ");
4434 }
4435 p = "esac";
4436 goto dotail2;
4437 case NTO:
4438 p = ">";
4439 goto redir;
4440 case NCLOBBER:
4441 p = ">|";
4442 goto redir;
4443 case NAPPEND:
4444 p = ">>";
4445 goto redir;
Denis Vlasenko559691a2008-10-05 18:39:31 +00004446#if ENABLE_ASH_BASH_COMPAT
4447 case NTO2:
4448#endif
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004449 case NTOFD:
4450 p = ">&";
4451 goto redir;
4452 case NFROM:
4453 p = "<";
4454 goto redir;
4455 case NFROMFD:
4456 p = "<&";
4457 goto redir;
4458 case NFROMTO:
4459 p = "<>";
4460 redir:
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00004461 cmdputs(utoa(n->nfile.fd));
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004462 cmdputs(p);
4463 if (n->type == NTOFD || n->type == NFROMFD) {
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00004464 cmdputs(utoa(n->ndup.dupfd));
4465 break;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004466 }
4467 n = n->nfile.fname;
4468 goto donode;
4469 }
4470}
4471
4472static char *
4473commandtext(union node *n)
4474{
4475 char *name;
4476
4477 STARTSTACKSTR(cmdnextc);
4478 cmdtxt(n);
4479 name = stackblock();
4480 TRACE(("commandtext: name %p, end %p\n\t\"%s\"\n",
4481 name, cmdnextc, cmdnextc));
4482 return ckstrdup(name);
4483}
4484#endif /* JOBS */
4485
4486/*
4487 * Fork off a subshell. If we are doing job control, give the subshell its
4488 * own process group. Jp is a job structure that the job is to be added to.
4489 * N is the command that will be evaluated by the child. Both jp and n may
4490 * be NULL. The mode parameter can be one of the following:
4491 * FORK_FG - Fork off a foreground process.
4492 * FORK_BG - Fork off a background process.
4493 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
4494 * process group even if job control is on.
4495 *
4496 * When job control is turned off, background processes have their standard
4497 * input redirected to /dev/null (except for the second and later processes
4498 * in a pipeline).
4499 *
4500 * Called with interrupts off.
4501 */
4502/*
4503 * Clear traps on a fork.
4504 */
4505static void
4506clear_traps(void)
4507{
4508 char **tp;
4509
4510 for (tp = trap; tp < &trap[NSIG]; tp++) {
Denis Vlasenko991a1da2008-02-10 19:02:53 +00004511 if (*tp && **tp) { /* trap not NULL or "" (SIG_IGN) */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004512 INT_OFF;
Denys Vlasenkoe305c282009-09-25 02:12:27 +02004513 if (trap_ptr == trap)
4514 free(*tp);
4515 /* else: it "belongs" to trap_ptr vector, don't free */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004516 *tp = NULL;
Denys Vlasenko0800e3a2009-09-24 03:09:26 +02004517 if ((tp - trap) != 0)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004518 setsignal(tp - trap);
4519 INT_ON;
4520 }
4521 }
4522}
Denis Vlasenkobdc406d2007-07-15 01:13:25 +00004523
4524/* Lives far away from here, needed for forkchild */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004525static void closescript(void);
Denis Vlasenko41770222007-10-07 18:02:52 +00004526
Denis Vlasenkobdc406d2007-07-15 01:13:25 +00004527/* Called after fork(), in child */
Denys Vlasenko21d87d42009-09-25 00:06:51 +02004528static NOINLINE void
Denys Vlasenkoe56f22a2009-07-24 00:16:59 +02004529forkchild(struct job *jp, union node *n, int mode)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004530{
4531 int oldlvl;
4532
4533 TRACE(("Child shell %d\n", getpid()));
4534 oldlvl = shlvl;
4535 shlvl++;
4536
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004537 /* man bash: "Non-builtin commands run by bash have signal handlers
4538 * set to the values inherited by the shell from its parent".
4539 * Do we do it correctly? */
4540
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004541 closescript();
Denys Vlasenko844f9902009-09-23 03:25:52 +02004542
4543 if (mode == FORK_NOJOB /* is it `xxx` ? */
4544 && n && n->type == NCMD /* is it single cmd? */
4545 /* && n->ncmd.args->type == NARG - always true? */
4546 && strcmp(n->ncmd.args->narg.text, "trap") == 0
4547 && n->ncmd.args->narg.next == NULL /* "trap" with no arguments */
4548 /* && n->ncmd.args->narg.backquote == NULL - do we need to check this? */
4549 ) {
4550 TRACE(("Trap hack\n"));
4551 /* Awful hack for `trap` or $(trap).
4552 *
4553 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
4554 * contains an example where "trap" is executed in a subshell:
4555 *
4556 * save_traps=$(trap)
4557 * ...
4558 * eval "$save_traps"
4559 *
4560 * Standard does not say that "trap" in subshell shall print
4561 * parent shell's traps. It only says that its output
4562 * must have suitable form, but then, in the above example
4563 * (which is not supposed to be normative), it implies that.
4564 *
4565 * bash (and probably other shell) does implement it
4566 * (traps are reset to defaults, but "trap" still shows them),
4567 * but as a result, "trap" logic is hopelessly messed up:
4568 *
4569 * # trap
4570 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
4571 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
4572 * # true | trap <--- trap is in subshell - no output (ditto)
4573 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
4574 * trap -- 'echo Ho' SIGWINCH
4575 * # echo `(trap)` <--- in subshell in subshell - output
4576 * trap -- 'echo Ho' SIGWINCH
4577 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
4578 * trap -- 'echo Ho' SIGWINCH
4579 *
4580 * The rules when to forget and when to not forget traps
4581 * get really complex and nonsensical.
4582 *
4583 * Our solution: ONLY bare $(trap) or `trap` is special.
4584 */
Denys Vlasenko8f88d852009-09-25 12:12:53 +02004585 /* Save trap handler strings for trap builtin to print */
Denys Vlasenko21d87d42009-09-25 00:06:51 +02004586 trap_ptr = memcpy(xmalloc(sizeof(trap)), trap, sizeof(trap));
Denys Vlasenko8f88d852009-09-25 12:12:53 +02004587 /* Fall through into clearing traps */
Denys Vlasenko844f9902009-09-23 03:25:52 +02004588 }
Denys Vlasenkoe305c282009-09-25 02:12:27 +02004589 clear_traps();
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004590#if JOBS
4591 /* do job control only in root shell */
Denis Vlasenkob07a4962008-06-22 13:16:23 +00004592 doing_jobctl = 0;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004593 if (mode != FORK_NOJOB && jp->jobctl && !oldlvl) {
4594 pid_t pgrp;
4595
4596 if (jp->nprocs == 0)
4597 pgrp = getpid();
4598 else
Denys Vlasenko285ad152009-12-04 23:02:27 +01004599 pgrp = jp->ps[0].ps_pid;
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004600 /* this can fail because we are doing it in the parent also */
4601 setpgid(0, pgrp);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004602 if (mode == FORK_FG)
4603 xtcsetpgrp(ttyfd, pgrp);
4604 setsignal(SIGTSTP);
4605 setsignal(SIGTTOU);
4606 } else
4607#endif
4608 if (mode == FORK_BG) {
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004609 /* man bash: "When job control is not in effect,
4610 * asynchronous commands ignore SIGINT and SIGQUIT" */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004611 ignoresig(SIGINT);
4612 ignoresig(SIGQUIT);
4613 if (jp->nprocs == 0) {
4614 close(0);
4615 if (open(bb_dev_null, O_RDONLY) != 0)
Denis Vlasenko9604e1b2009-03-03 18:47:56 +00004616 ash_msg_and_raise_error("can't open '%s'", bb_dev_null);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004617 }
4618 }
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004619 if (!oldlvl) {
4620 if (iflag) { /* why if iflag only? */
4621 setsignal(SIGINT);
4622 setsignal(SIGTERM);
4623 }
4624 /* man bash:
4625 * "In all cases, bash ignores SIGQUIT. Non-builtin
4626 * commands run by bash have signal handlers
4627 * set to the values inherited by the shell
4628 * from its parent".
4629 * Take care of the second rule: */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004630 setsignal(SIGQUIT);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004631 }
Denys Vlasenkoe56f22a2009-07-24 00:16:59 +02004632#if JOBS
Denys Vlasenko844f9902009-09-23 03:25:52 +02004633 if (n && n->type == NCMD
4634 && strcmp(n->ncmd.args->narg.text, "jobs") == 0
4635 ) {
Denys Vlasenkoe56f22a2009-07-24 00:16:59 +02004636 TRACE(("Job hack\n"));
Denys Vlasenko844f9902009-09-23 03:25:52 +02004637 /* "jobs": we do not want to clear job list for it,
4638 * instead we remove only _its_ own_ job from job list.
4639 * This makes "jobs .... | cat" more useful.
4640 */
Denys Vlasenkoe56f22a2009-07-24 00:16:59 +02004641 freejob(curjob);
4642 return;
4643 }
4644#endif
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004645 for (jp = curjob; jp; jp = jp->prev_job)
4646 freejob(jp);
4647 jobless = 0;
4648}
4649
Denis Vlasenkobdc406d2007-07-15 01:13:25 +00004650/* Called after fork(), in parent */
Denis Vlasenko85c24712008-03-17 09:04:04 +00004651#if !JOBS
4652#define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
4653#endif
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004654static void
4655forkparent(struct job *jp, union node *n, int mode, pid_t pid)
4656{
4657 TRACE(("In parent shell: child = %d\n", pid));
4658 if (!jp) {
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00004659 while (jobless && dowait(DOWAIT_NONBLOCK, NULL) > 0)
4660 continue;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004661 jobless++;
4662 return;
4663 }
4664#if JOBS
4665 if (mode != FORK_NOJOB && jp->jobctl) {
4666 int pgrp;
4667
4668 if (jp->nprocs == 0)
4669 pgrp = pid;
4670 else
Denys Vlasenko285ad152009-12-04 23:02:27 +01004671 pgrp = jp->ps[0].ps_pid;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004672 /* This can fail because we are doing it in the child also */
4673 setpgid(pid, pgrp);
4674 }
4675#endif
4676 if (mode == FORK_BG) {
4677 backgndpid = pid; /* set $! */
4678 set_curjob(jp, CUR_RUNNING);
4679 }
4680 if (jp) {
4681 struct procstat *ps = &jp->ps[jp->nprocs++];
Denys Vlasenko285ad152009-12-04 23:02:27 +01004682 ps->ps_pid = pid;
4683 ps->ps_status = -1;
4684 ps->ps_cmd = nullstr;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004685#if JOBS
Denis Vlasenkob07a4962008-06-22 13:16:23 +00004686 if (doing_jobctl && n)
Denys Vlasenko285ad152009-12-04 23:02:27 +01004687 ps->ps_cmd = commandtext(n);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004688#endif
4689 }
4690}
4691
4692static int
4693forkshell(struct job *jp, union node *n, int mode)
4694{
4695 int pid;
4696
4697 TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
4698 pid = fork();
4699 if (pid < 0) {
4700 TRACE(("Fork failed, errno=%d", errno));
4701 if (jp)
4702 freejob(jp);
Denis Vlasenkofa0b56d2008-07-01 16:09:07 +00004703 ash_msg_and_raise_error("can't fork");
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004704 }
Denys Vlasenko76ace252009-10-12 15:25:01 +02004705 if (pid == 0) {
4706 CLEAR_RANDOM_T(&random_gen); /* or else $RANDOM repeats in child */
Denys Vlasenkoe56f22a2009-07-24 00:16:59 +02004707 forkchild(jp, n, mode);
Denys Vlasenko76ace252009-10-12 15:25:01 +02004708 } else {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004709 forkparent(jp, n, mode, pid);
Denys Vlasenko76ace252009-10-12 15:25:01 +02004710 }
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004711 return pid;
4712}
4713
4714/*
4715 * Wait for job to finish.
4716 *
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004717 * Under job control we have the problem that while a child process
4718 * is running interrupts generated by the user are sent to the child
4719 * but not to the shell. This means that an infinite loop started by
4720 * an interactive user may be hard to kill. With job control turned off,
4721 * an interactive user may place an interactive program inside a loop.
4722 * If the interactive program catches interrupts, the user doesn't want
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004723 * these interrupts to also abort the loop. The approach we take here
4724 * is to have the shell ignore interrupt signals while waiting for a
4725 * foreground process to terminate, and then send itself an interrupt
4726 * signal if the child process was terminated by an interrupt signal.
4727 * Unfortunately, some programs want to do a bit of cleanup and then
4728 * exit on interrupt; unless these processes terminate themselves by
4729 * sending a signal to themselves (instead of calling exit) they will
4730 * confuse this approach.
4731 *
4732 * Called with interrupts off.
4733 */
4734static int
4735waitforjob(struct job *jp)
4736{
4737 int st;
4738
4739 TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004740
4741 INT_OFF;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004742 while (jp->state == JOBRUNNING) {
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004743 /* In non-interactive shells, we _can_ get
4744 * a keyboard signal here and be EINTRed,
4745 * but we just loop back, waiting for command to complete.
4746 *
4747 * man bash:
4748 * "If bash is waiting for a command to complete and receives
4749 * a signal for which a trap has been set, the trap
4750 * will not be executed until the command completes."
4751 *
4752 * Reality is that even if trap is not set, bash
4753 * will not act on the signal until command completes.
4754 * Try this. sleep5intoff.c:
4755 * #include <signal.h>
4756 * #include <unistd.h>
4757 * int main() {
4758 * sigset_t set;
4759 * sigemptyset(&set);
4760 * sigaddset(&set, SIGINT);
4761 * sigaddset(&set, SIGQUIT);
4762 * sigprocmask(SIG_BLOCK, &set, NULL);
4763 * sleep(5);
4764 * return 0;
4765 * }
4766 * $ bash -c './sleep5intoff; echo hi'
4767 * ^C^C^C^C <--- pressing ^C once a second
4768 * $ _
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004769 * $ bash -c './sleep5intoff; echo hi'
4770 * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
4771 * $ _
4772 */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004773 dowait(DOWAIT_BLOCK, jp);
4774 }
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004775 INT_ON;
4776
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004777 st = getstatus(jp);
4778#if JOBS
4779 if (jp->jobctl) {
4780 xtcsetpgrp(ttyfd, rootpid);
4781 /*
4782 * This is truly gross.
4783 * If we're doing job control, then we did a TIOCSPGRP which
4784 * caused us (the shell) to no longer be in the controlling
4785 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
4786 * intuit from the subprocess exit status whether a SIGINT
4787 * occurred, and if so interrupt ourselves. Yuck. - mycroft
4788 */
Denis Vlasenko991a1da2008-02-10 19:02:53 +00004789 if (jp->sigint) /* TODO: do the same with all signals */
4790 raise(SIGINT); /* ... by raise(jp->sig) instead? */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004791 }
4792 if (jp->state == JOBDONE)
4793#endif
4794 freejob(jp);
4795 return st;
4796}
4797
4798/*
4799 * return 1 if there are stopped jobs, otherwise 0
4800 */
4801static int
4802stoppedjobs(void)
4803{
4804 struct job *jp;
4805 int retval;
4806
4807 retval = 0;
4808 if (job_warning)
4809 goto out;
4810 jp = curjob;
4811 if (jp && jp->state == JOBSTOPPED) {
4812 out2str("You have stopped jobs.\n");
4813 job_warning = 2;
4814 retval++;
4815 }
4816 out:
4817 return retval;
4818}
4819
4820
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004821/* ============ redir.c
4822 *
4823 * Code for dealing with input/output redirection.
4824 */
4825
4826#define EMPTY -2 /* marks an unused slot in redirtab */
Denis Vlasenko7d75a962007-11-22 08:16:57 +00004827#define CLOSED -3 /* marks a slot of previously-closed fd */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004828
4829/*
4830 * Open a file in noclobber mode.
4831 * The code was copied from bash.
4832 */
4833static int
4834noclobberopen(const char *fname)
4835{
4836 int r, fd;
4837 struct stat finfo, finfo2;
4838
4839 /*
4840 * If the file exists and is a regular file, return an error
4841 * immediately.
4842 */
4843 r = stat(fname, &finfo);
4844 if (r == 0 && S_ISREG(finfo.st_mode)) {
4845 errno = EEXIST;
4846 return -1;
4847 }
4848
4849 /*
4850 * If the file was not present (r != 0), make sure we open it
4851 * exclusively so that if it is created before we open it, our open
4852 * will fail. Make sure that we do not truncate an existing file.
4853 * Note that we don't turn on O_EXCL unless the stat failed -- if the
4854 * file was not a regular file, we leave O_EXCL off.
4855 */
4856 if (r != 0)
4857 return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
4858 fd = open(fname, O_WRONLY|O_CREAT, 0666);
4859
4860 /* If the open failed, return the file descriptor right away. */
4861 if (fd < 0)
4862 return fd;
4863
4864 /*
4865 * OK, the open succeeded, but the file may have been changed from a
4866 * non-regular file to a regular file between the stat and the open.
4867 * We are assuming that the O_EXCL open handles the case where FILENAME
4868 * did not exist and is symlinked to an existing file between the stat
4869 * and open.
4870 */
4871
4872 /*
4873 * If we can open it and fstat the file descriptor, and neither check
4874 * revealed that it was a regular file, and the file has not been
4875 * replaced, return the file descriptor.
4876 */
4877 if (fstat(fd, &finfo2) == 0 && !S_ISREG(finfo2.st_mode)
4878 && finfo.st_dev == finfo2.st_dev && finfo.st_ino == finfo2.st_ino)
4879 return fd;
4880
4881 /* The file has been replaced. badness. */
4882 close(fd);
4883 errno = EEXIST;
4884 return -1;
4885}
4886
4887/*
4888 * Handle here documents. Normally we fork off a process to write the
4889 * data to a pipe. If the document is short, we can stuff the data in
4890 * the pipe without forking.
4891 */
4892/* openhere needs this forward reference */
4893static void expandhere(union node *arg, int fd);
4894static int
4895openhere(union node *redir)
4896{
4897 int pip[2];
4898 size_t len = 0;
4899
4900 if (pipe(pip) < 0)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00004901 ash_msg_and_raise_error("pipe call failed");
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004902 if (redir->type == NHERE) {
4903 len = strlen(redir->nhere.doc->narg.text);
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00004904 if (len <= PIPE_BUF) {
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004905 full_write(pip[1], redir->nhere.doc->narg.text, len);
4906 goto out;
4907 }
4908 }
4909 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
Denis Vlasenko0b769642008-07-24 07:54:57 +00004910 /* child */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004911 close(pip[0]);
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004912 ignoresig(SIGINT); //signal(SIGINT, SIG_IGN);
4913 ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
4914 ignoresig(SIGHUP); //signal(SIGHUP, SIG_IGN);
4915 ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004916 signal(SIGPIPE, SIG_DFL);
4917 if (redir->type == NHERE)
4918 full_write(pip[1], redir->nhere.doc->narg.text, len);
Denis Vlasenko0b769642008-07-24 07:54:57 +00004919 else /* NXHERE */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004920 expandhere(redir->nhere.doc, pip[1]);
Bernhard Reutner-Fischer636a1f82008-05-19 09:29:47 +00004921 _exit(EXIT_SUCCESS);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004922 }
4923 out:
4924 close(pip[1]);
4925 return pip[0];
4926}
4927
4928static int
4929openredirect(union node *redir)
4930{
4931 char *fname;
4932 int f;
4933
4934 switch (redir->nfile.type) {
4935 case NFROM:
4936 fname = redir->nfile.expfname;
4937 f = open(fname, O_RDONLY);
4938 if (f < 0)
4939 goto eopen;
4940 break;
4941 case NFROMTO:
4942 fname = redir->nfile.expfname;
4943 f = open(fname, O_RDWR|O_CREAT|O_TRUNC, 0666);
4944 if (f < 0)
4945 goto ecreate;
4946 break;
4947 case NTO:
Denis Vlasenko559691a2008-10-05 18:39:31 +00004948#if ENABLE_ASH_BASH_COMPAT
4949 case NTO2:
4950#endif
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004951 /* Take care of noclobber mode. */
4952 if (Cflag) {
4953 fname = redir->nfile.expfname;
4954 f = noclobberopen(fname);
4955 if (f < 0)
4956 goto ecreate;
4957 break;
4958 }
4959 /* FALLTHROUGH */
4960 case NCLOBBER:
4961 fname = redir->nfile.expfname;
4962 f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
4963 if (f < 0)
4964 goto ecreate;
4965 break;
4966 case NAPPEND:
4967 fname = redir->nfile.expfname;
4968 f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
4969 if (f < 0)
4970 goto ecreate;
4971 break;
4972 default:
4973#if DEBUG
4974 abort();
4975#endif
4976 /* Fall through to eliminate warning. */
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00004977/* Our single caller does this itself */
Denis Vlasenko0b769642008-07-24 07:54:57 +00004978// case NTOFD:
4979// case NFROMFD:
4980// f = -1;
4981// break;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004982 case NHERE:
4983 case NXHERE:
4984 f = openhere(redir);
4985 break;
4986 }
4987
4988 return f;
4989 ecreate:
Bernhard Reutner-Fischera53de7f2008-07-21 13:46:54 +00004990 ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004991 eopen:
Bernhard Reutner-Fischera53de7f2008-07-21 13:46:54 +00004992 ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004993}
4994
4995/*
4996 * Copy a file descriptor to be >= to. Returns -1
4997 * if the source file descriptor is closed, EMPTY if there are no unused
4998 * file descriptors left.
4999 */
Denis Vlasenko5a867312008-07-24 19:46:38 +00005000/* 0x800..00: bit to set in "to" to request dup2 instead of fcntl(F_DUPFD).
5001 * old code was doing close(to) prior to copyfd() to achieve the same */
Denis Vlasenko22f74142008-07-24 22:34:43 +00005002enum {
5003 COPYFD_EXACT = (int)~(INT_MAX),
5004 COPYFD_RESTORE = (int)((unsigned)COPYFD_EXACT >> 1),
5005};
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005006static int
5007copyfd(int from, int to)
5008{
5009 int newfd;
5010
Denis Vlasenko5a867312008-07-24 19:46:38 +00005011 if (to & COPYFD_EXACT) {
5012 to &= ~COPYFD_EXACT;
5013 /*if (from != to)*/
5014 newfd = dup2(from, to);
5015 } else {
5016 newfd = fcntl(from, F_DUPFD, to);
5017 }
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005018 if (newfd < 0) {
5019 if (errno == EMFILE)
5020 return EMPTY;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005021 /* Happens when source fd is not open: try "echo >&99" */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005022 ash_msg_and_raise_error("%d: %m", from);
5023 }
5024 return newfd;
5025}
5026
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005027/* Struct def and variable are moved down to the first usage site */
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005028struct two_fd_t {
5029 int orig, copy;
5030};
Denis Vlasenko0b769642008-07-24 07:54:57 +00005031struct redirtab {
5032 struct redirtab *next;
Denis Vlasenko0b769642008-07-24 07:54:57 +00005033 int nullredirs;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005034 int pair_count;
Denys Vlasenko606291b2009-09-23 23:15:43 +02005035 struct two_fd_t two_fd[];
Denis Vlasenko0b769642008-07-24 07:54:57 +00005036};
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005037#define redirlist (G_var.redirlist)
Denis Vlasenko0b769642008-07-24 07:54:57 +00005038
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005039static int need_to_remember(struct redirtab *rp, int fd)
5040{
5041 int i;
5042
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005043 if (!rp) /* remembering was not requested */
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005044 return 0;
5045
5046 for (i = 0; i < rp->pair_count; i++) {
5047 if (rp->two_fd[i].orig == fd) {
5048 /* already remembered */
5049 return 0;
5050 }
5051 }
5052 return 1;
5053}
5054
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005055/* "hidden" fd is a fd used to read scripts, or a copy of such */
5056static int is_hidden_fd(struct redirtab *rp, int fd)
5057{
5058 int i;
Denis Vlasenko34c73c42008-08-16 11:48:02 +00005059 struct parsefile *pf;
5060
5061 if (fd == -1)
5062 return 0;
5063 pf = g_parsefile;
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005064 while (pf) {
5065 if (fd == pf->fd) {
5066 return 1;
5067 }
5068 pf = pf->prev;
5069 }
5070 if (!rp)
5071 return 0;
5072 fd |= COPYFD_RESTORE;
5073 for (i = 0; i < rp->pair_count; i++) {
5074 if (rp->two_fd[i].copy == fd) {
5075 return 1;
5076 }
5077 }
5078 return 0;
5079}
5080
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005081/*
5082 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
5083 * old file descriptors are stashed away so that the redirection can be
5084 * undone by calling popredir. If the REDIR_BACKQ flag is set, then the
5085 * standard output, and the standard error if it becomes a duplicate of
5086 * stdout, is saved in memory.
5087 */
5088/* flags passed to redirect */
5089#define REDIR_PUSH 01 /* save previous values of file descriptors */
5090#define REDIR_SAVEFD2 03 /* set preverrout */
5091static void
5092redirect(union node *redir, int flags)
5093{
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005094 struct redirtab *sv;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005095 int sv_pos;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005096 int i;
5097 int fd;
5098 int newfd;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005099 int copied_fd2 = -1;
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005100
Denis Vlasenko01631112007-12-16 17:20:38 +00005101 g_nullredirs++;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005102 if (!redir) {
5103 return;
5104 }
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005105
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005106 sv = NULL;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005107 sv_pos = 0;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005108 INT_OFF;
5109 if (flags & REDIR_PUSH) {
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005110 union node *tmp = redir;
5111 do {
5112 sv_pos++;
Denis Vlasenko559691a2008-10-05 18:39:31 +00005113#if ENABLE_ASH_BASH_COMPAT
Chris Metcalfc3c1fb62010-01-08 13:18:06 +01005114 if (tmp->nfile.type == NTO2)
Denis Vlasenko559691a2008-10-05 18:39:31 +00005115 sv_pos++;
5116#endif
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005117 tmp = tmp->nfile.next;
5118 } while (tmp);
5119 sv = ckmalloc(sizeof(*sv) + sv_pos * sizeof(sv->two_fd[0]));
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005120 sv->next = redirlist;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005121 sv->pair_count = sv_pos;
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005122 redirlist = sv;
Denis Vlasenko01631112007-12-16 17:20:38 +00005123 sv->nullredirs = g_nullredirs - 1;
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005124 g_nullredirs = 0;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005125 while (sv_pos > 0) {
5126 sv_pos--;
5127 sv->two_fd[sv_pos].orig = sv->two_fd[sv_pos].copy = EMPTY;
5128 }
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005129 }
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005130
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005131 do {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00005132 fd = redir->nfile.fd;
Denis Vlasenko0b769642008-07-24 07:54:57 +00005133 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005134 int right_fd = redir->ndup.dupfd;
5135 /* redirect from/to same file descriptor? */
5136 if (right_fd == fd)
5137 continue;
5138 /* echo >&10 and 10 is a fd opened to the sh script? */
5139 if (is_hidden_fd(sv, right_fd)) {
5140 errno = EBADF; /* as if it is closed */
5141 ash_msg_and_raise_error("%d: %m", right_fd);
5142 }
Denis Vlasenko0b769642008-07-24 07:54:57 +00005143 newfd = -1;
5144 } else {
5145 newfd = openredirect(redir); /* always >= 0 */
5146 if (fd == newfd) {
5147 /* Descriptor wasn't open before redirect.
5148 * Mark it for close in the future */
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005149 if (need_to_remember(sv, fd)) {
Denis Vlasenko5a867312008-07-24 19:46:38 +00005150 goto remember_to_close;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005151 }
Denis Vlasenko0b769642008-07-24 07:54:57 +00005152 continue;
5153 }
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005154 }
Denis Vlasenko559691a2008-10-05 18:39:31 +00005155#if ENABLE_ASH_BASH_COMPAT
5156 redirect_more:
5157#endif
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005158 if (need_to_remember(sv, fd)) {
Denis Vlasenko0b769642008-07-24 07:54:57 +00005159 /* Copy old descriptor */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005160 i = fcntl(fd, F_DUPFD, 10);
Denis Vlasenko5a867312008-07-24 19:46:38 +00005161/* You'd expect copy to be CLOEXECed. Currently these extra "saved" fds
5162 * are closed in popredir() in the child, preventing them from leaking
5163 * into child. (popredir() also cleans up the mess in case of failures)
5164 */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005165 if (i == -1) {
5166 i = errno;
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005167 if (i != EBADF) {
5168 /* Strange error (e.g. "too many files" EMFILE?) */
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005169 if (newfd >= 0)
5170 close(newfd);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005171 errno = i;
5172 ash_msg_and_raise_error("%d: %m", fd);
5173 /* NOTREACHED */
5174 }
Denis Vlasenko5a867312008-07-24 19:46:38 +00005175 /* EBADF: it is not open - good, remember to close it */
5176 remember_to_close:
5177 i = CLOSED;
Denis Vlasenko22f74142008-07-24 22:34:43 +00005178 } else { /* fd is open, save its copy */
5179 /* "exec fd>&-" should not close fds
5180 * which point to script file(s).
5181 * Force them to be restored afterwards */
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005182 if (is_hidden_fd(sv, fd))
5183 i |= COPYFD_RESTORE;
Denis Vlasenko22f74142008-07-24 22:34:43 +00005184 }
Denis Vlasenko5a867312008-07-24 19:46:38 +00005185 if (fd == 2)
5186 copied_fd2 = i;
5187 sv->two_fd[sv_pos].orig = fd;
5188 sv->two_fd[sv_pos].copy = i;
5189 sv_pos++;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005190 }
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005191 if (newfd < 0) {
5192 /* NTOFD/NFROMFD: copy redir->ndup.dupfd to fd */
Denis Vlasenko22f74142008-07-24 22:34:43 +00005193 if (redir->ndup.dupfd < 0) { /* "fd>&-" */
Denis Vlasenkob9e70dd2009-03-20 01:24:08 +00005194 /* Don't want to trigger debugging */
5195 if (fd != -1)
5196 close(fd);
Denis Vlasenko5a867312008-07-24 19:46:38 +00005197 } else {
5198 copyfd(redir->ndup.dupfd, fd | COPYFD_EXACT);
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005199 }
Denis Vlasenko5a867312008-07-24 19:46:38 +00005200 } else if (fd != newfd) { /* move newfd to fd */
5201 copyfd(newfd, fd | COPYFD_EXACT);
Denis Vlasenko559691a2008-10-05 18:39:31 +00005202#if ENABLE_ASH_BASH_COMPAT
5203 if (!(redir->nfile.type == NTO2 && fd == 2))
5204#endif
5205 close(newfd);
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005206 }
Denis Vlasenko559691a2008-10-05 18:39:31 +00005207#if ENABLE_ASH_BASH_COMPAT
5208 if (redir->nfile.type == NTO2 && fd == 1) {
5209 /* We already redirected it to fd 1, now copy it to 2 */
5210 newfd = 1;
5211 fd = 2;
5212 goto redirect_more;
5213 }
5214#endif
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00005215 } while ((redir = redir->nfile.next) != NULL);
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005216
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005217 INT_ON;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005218 if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
5219 preverrout_fd = copied_fd2;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005220}
5221
5222/*
5223 * Undo the effects of the last redirection.
5224 */
5225static void
Denis Vlasenko34c73c42008-08-16 11:48:02 +00005226popredir(int drop, int restore)
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005227{
5228 struct redirtab *rp;
5229 int i;
5230
Denis Vlasenko01631112007-12-16 17:20:38 +00005231 if (--g_nullredirs >= 0)
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005232 return;
5233 INT_OFF;
5234 rp = redirlist;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005235 for (i = 0; i < rp->pair_count; i++) {
5236 int fd = rp->two_fd[i].orig;
Denis Vlasenko22f74142008-07-24 22:34:43 +00005237 int copy = rp->two_fd[i].copy;
5238 if (copy == CLOSED) {
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005239 if (!drop)
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005240 close(fd);
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005241 continue;
5242 }
Denis Vlasenko22f74142008-07-24 22:34:43 +00005243 if (copy != EMPTY) {
Denis Vlasenko34c73c42008-08-16 11:48:02 +00005244 if (!drop || (restore && (copy & COPYFD_RESTORE))) {
Denis Vlasenko22f74142008-07-24 22:34:43 +00005245 copy &= ~COPYFD_RESTORE;
Denis Vlasenko5a867312008-07-24 19:46:38 +00005246 /*close(fd);*/
Denis Vlasenko22f74142008-07-24 22:34:43 +00005247 copyfd(copy, fd | COPYFD_EXACT);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005248 }
Denis Vlasenkob9e70dd2009-03-20 01:24:08 +00005249 close(copy & ~COPYFD_RESTORE);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005250 }
5251 }
5252 redirlist = rp->next;
Denis Vlasenko01631112007-12-16 17:20:38 +00005253 g_nullredirs = rp->nullredirs;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005254 free(rp);
5255 INT_ON;
5256}
5257
5258/*
5259 * Undo all redirections. Called on error or interrupt.
5260 */
5261
5262/*
5263 * Discard all saved file descriptors.
5264 */
5265static void
5266clearredir(int drop)
5267{
5268 for (;;) {
Denis Vlasenko01631112007-12-16 17:20:38 +00005269 g_nullredirs = 0;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005270 if (!redirlist)
5271 break;
Denis Vlasenko34c73c42008-08-16 11:48:02 +00005272 popredir(drop, /*restore:*/ 0);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005273 }
5274}
5275
5276static int
5277redirectsafe(union node *redir, int flags)
5278{
5279 int err;
5280 volatile int saveint;
5281 struct jmploc *volatile savehandler = exception_handler;
5282 struct jmploc jmploc;
5283
5284 SAVE_INT(saveint);
Denis Vlasenko5a867312008-07-24 19:46:38 +00005285 /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
5286 err = setjmp(jmploc.loc); // huh?? was = setjmp(jmploc.loc) * 2;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005287 if (!err) {
5288 exception_handler = &jmploc;
5289 redirect(redir, flags);
5290 }
5291 exception_handler = savehandler;
Denis Vlasenko7f88e342009-03-19 03:36:18 +00005292 if (err && exception_type != EXERROR)
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005293 longjmp(exception_handler->loc, 1);
5294 RESTORE_INT(saveint);
5295 return err;
5296}
5297
5298
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005299/* ============ Routines to expand arguments to commands
5300 *
5301 * We have to deal with backquotes, shell variables, and file metacharacters.
5302 */
5303
Mike Frysinger98c52642009-04-02 10:02:37 +00005304#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00005305static arith_t
5306ash_arith(const char *s)
5307{
5308 arith_eval_hooks_t math_hooks;
5309 arith_t result;
5310 int errcode = 0;
5311
5312 math_hooks.lookupvar = lookupvar;
5313 math_hooks.setvar = setvar;
5314 math_hooks.endofname = endofname;
5315
5316 INT_OFF;
5317 result = arith(s, &errcode, &math_hooks);
5318 if (errcode < 0) {
5319 if (errcode == -3)
5320 ash_msg_and_raise_error("exponent less than 0");
5321 if (errcode == -2)
5322 ash_msg_and_raise_error("divide by zero");
5323 if (errcode == -5)
5324 ash_msg_and_raise_error("expression recursion loop detected");
5325 raise_error_syntax(s);
5326 }
5327 INT_ON;
5328
5329 return result;
5330}
Denis Vlasenko448d30e2008-06-27 00:24:11 +00005331#endif
5332
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005333/*
5334 * expandarg flags
5335 */
5336#define EXP_FULL 0x1 /* perform word splitting & file globbing */
5337#define EXP_TILDE 0x2 /* do normal tilde expansion */
5338#define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
5339#define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
5340#define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
5341#define EXP_RECORD 0x20 /* need to record arguments for ifs breakup */
5342#define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
5343#define EXP_WORD 0x80 /* expand word in parameter expansion */
5344#define EXP_QWORD 0x100 /* expand word in quoted parameter expansion */
5345/*
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005346 * rmescape() flags
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005347 */
5348#define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
5349#define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
5350#define RMESCAPE_QUOTED 0x4 /* Remove CTLESC unless in quotes */
5351#define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
5352#define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
5353
5354/*
5355 * Structure specifying which parts of the string should be searched
5356 * for IFS characters.
5357 */
5358struct ifsregion {
5359 struct ifsregion *next; /* next region in list */
5360 int begoff; /* offset of start of region */
5361 int endoff; /* offset of end of region */
5362 int nulonly; /* search for nul bytes only */
5363};
5364
5365struct arglist {
5366 struct strlist *list;
5367 struct strlist **lastp;
5368};
5369
5370/* output of current string */
5371static char *expdest;
5372/* list of back quote expressions */
5373static struct nodelist *argbackq;
5374/* first struct in list of ifs regions */
5375static struct ifsregion ifsfirst;
5376/* last struct in list */
5377static struct ifsregion *ifslastp;
5378/* holds expanded arg list */
5379static struct arglist exparg;
5380
5381/*
5382 * Our own itoa().
5383 */
5384static int
5385cvtnum(arith_t num)
5386{
5387 int len;
5388
5389 expdest = makestrspace(32, expdest);
Mike Frysinger98c52642009-04-02 10:02:37 +00005390 len = fmtstr(expdest, 32, arith_t_fmt, num);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005391 STADJUST(len, expdest);
5392 return len;
5393}
5394
5395static size_t
5396esclen(const char *start, const char *p)
5397{
5398 size_t esc = 0;
5399
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005400 while (p > start && (unsigned char)*--p == CTLESC) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005401 esc++;
5402 }
5403 return esc;
5404}
5405
5406/*
5407 * Remove any CTLESC characters from a string.
5408 */
5409static char *
Denys Vlasenkob6c84342009-08-29 20:23:20 +02005410rmescapes(char *str, int flag)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005411{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00005412 static const char qchars[] ALIGN1 = { CTLESC, CTLQUOTEMARK, '\0' };
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00005413
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005414 char *p, *q, *r;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005415 unsigned inquotes;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005416 unsigned protect_against_glob;
5417 unsigned globbing;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005418
5419 p = strpbrk(str, qchars);
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005420 if (!p)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005421 return str;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005422
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005423 q = p;
5424 r = str;
5425 if (flag & RMESCAPE_ALLOC) {
5426 size_t len = p - str;
5427 size_t fulllen = len + strlen(p) + 1;
5428
5429 if (flag & RMESCAPE_GROW) {
5430 r = makestrspace(fulllen, expdest);
5431 } else if (flag & RMESCAPE_HEAP) {
5432 r = ckmalloc(fulllen);
5433 } else {
5434 r = stalloc(fulllen);
5435 }
5436 q = r;
5437 if (len > 0) {
Denis Vlasenko29eb3592008-05-18 14:06:08 +00005438 q = (char *)memcpy(q, str, len) + len;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005439 }
5440 }
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005441
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005442 inquotes = (flag & RMESCAPE_QUOTED) ^ RMESCAPE_QUOTED;
5443 globbing = flag & RMESCAPE_GLOB;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005444 protect_against_glob = globbing;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005445 while (*p) {
Denys Vlasenkocd716832009-11-28 22:14:02 +01005446 if ((unsigned char)*p == CTLQUOTEMARK) {
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005447// TODO: if no RMESCAPE_QUOTED in flags, inquotes never becomes 0
5448// (alternates between RMESCAPE_QUOTED and ~RMESCAPE_QUOTED). Is it ok?
5449// Note: both inquotes and protect_against_glob only affect whether
5450// CTLESC,<ch> gets converted to <ch> or to \<ch>
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005451 inquotes = ~inquotes;
5452 p++;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005453 protect_against_glob = globbing;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005454 continue;
5455 }
5456 if (*p == '\\') {
5457 /* naked back slash */
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005458 protect_against_glob = 0;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005459 goto copy;
5460 }
Denys Vlasenkocd716832009-11-28 22:14:02 +01005461 if ((unsigned char)*p == CTLESC) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005462 p++;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005463 if (protect_against_glob && inquotes && *p != '/') {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005464 *q++ = '\\';
5465 }
5466 }
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005467 protect_against_glob = globbing;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005468 copy:
5469 *q++ = *p++;
5470 }
5471 *q = '\0';
5472 if (flag & RMESCAPE_GROW) {
5473 expdest = r;
5474 STADJUST(q - r + 1, expdest);
5475 }
5476 return r;
5477}
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005478#define pmatch(a, b) !fnmatch((a), (b), 0)
5479
5480/*
5481 * Prepare a pattern for a expmeta (internal glob(3)) call.
5482 *
5483 * Returns an stalloced string.
5484 */
5485static char *
5486preglob(const char *pattern, int quoted, int flag)
5487{
5488 flag |= RMESCAPE_GLOB;
5489 if (quoted) {
5490 flag |= RMESCAPE_QUOTED;
5491 }
Denys Vlasenkob6c84342009-08-29 20:23:20 +02005492 return rmescapes((char *)pattern, flag);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005493}
5494
5495/*
5496 * Put a string on the stack.
5497 */
5498static void
5499memtodest(const char *p, size_t len, int syntax, int quotes)
5500{
5501 char *q = expdest;
5502
Denys Vlasenkob6c84342009-08-29 20:23:20 +02005503 q = makestrspace(quotes ? len * 2 : len, q);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005504
5505 while (len--) {
Denys Vlasenkocd716832009-11-28 22:14:02 +01005506 unsigned char c = *p++;
5507 if (c == '\0')
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005508 continue;
Denys Vlasenkob6c84342009-08-29 20:23:20 +02005509 if (quotes) {
5510 int n = SIT(c, syntax);
5511 if (n == CCTL || n == CBACK)
5512 USTPUTC(CTLESC, q);
5513 }
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005514 USTPUTC(c, q);
5515 }
5516
5517 expdest = q;
5518}
5519
5520static void
5521strtodest(const char *p, int syntax, int quotes)
5522{
5523 memtodest(p, strlen(p), syntax, quotes);
5524}
5525
5526/*
5527 * Record the fact that we have to scan this region of the
5528 * string for IFS characters.
5529 */
5530static void
5531recordregion(int start, int end, int nulonly)
5532{
5533 struct ifsregion *ifsp;
5534
5535 if (ifslastp == NULL) {
5536 ifsp = &ifsfirst;
5537 } else {
5538 INT_OFF;
Denis Vlasenko597906c2008-02-20 16:38:54 +00005539 ifsp = ckzalloc(sizeof(*ifsp));
5540 /*ifsp->next = NULL; - ckzalloc did it */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005541 ifslastp->next = ifsp;
5542 INT_ON;
5543 }
5544 ifslastp = ifsp;
5545 ifslastp->begoff = start;
5546 ifslastp->endoff = end;
5547 ifslastp->nulonly = nulonly;
5548}
5549
5550static void
5551removerecordregions(int endoff)
5552{
5553 if (ifslastp == NULL)
5554 return;
5555
5556 if (ifsfirst.endoff > endoff) {
5557 while (ifsfirst.next != NULL) {
5558 struct ifsregion *ifsp;
5559 INT_OFF;
5560 ifsp = ifsfirst.next->next;
5561 free(ifsfirst.next);
5562 ifsfirst.next = ifsp;
5563 INT_ON;
5564 }
5565 if (ifsfirst.begoff > endoff)
5566 ifslastp = NULL;
5567 else {
5568 ifslastp = &ifsfirst;
5569 ifsfirst.endoff = endoff;
5570 }
5571 return;
5572 }
5573
5574 ifslastp = &ifsfirst;
5575 while (ifslastp->next && ifslastp->next->begoff < endoff)
5576 ifslastp=ifslastp->next;
5577 while (ifslastp->next != NULL) {
5578 struct ifsregion *ifsp;
5579 INT_OFF;
5580 ifsp = ifslastp->next->next;
5581 free(ifslastp->next);
5582 ifslastp->next = ifsp;
5583 INT_ON;
5584 }
5585 if (ifslastp->endoff > endoff)
5586 ifslastp->endoff = endoff;
5587}
5588
5589static char *
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005590exptilde(char *startp, char *p, int flags)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005591{
Denys Vlasenkocd716832009-11-28 22:14:02 +01005592 unsigned char c;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005593 char *name;
5594 struct passwd *pw;
5595 const char *home;
Denys Vlasenko1166d7b2009-09-16 16:20:31 +02005596 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005597 int startloc;
5598
5599 name = p + 1;
5600
5601 while ((c = *++p) != '\0') {
5602 switch (c) {
5603 case CTLESC:
5604 return startp;
5605 case CTLQUOTEMARK:
5606 return startp;
5607 case ':':
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005608 if (flags & EXP_VARTILDE)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005609 goto done;
5610 break;
5611 case '/':
5612 case CTLENDVAR:
5613 goto done;
5614 }
5615 }
5616 done:
5617 *p = '\0';
5618 if (*name == '\0') {
5619 home = lookupvar(homestr);
5620 } else {
5621 pw = getpwnam(name);
5622 if (pw == NULL)
5623 goto lose;
5624 home = pw->pw_dir;
5625 }
5626 if (!home || !*home)
5627 goto lose;
5628 *p = c;
5629 startloc = expdest - (char *)stackblock();
5630 strtodest(home, SQSYNTAX, quotes);
5631 recordregion(startloc, expdest - (char *)stackblock(), 0);
5632 return p;
5633 lose:
5634 *p = c;
5635 return startp;
5636}
5637
5638/*
5639 * Execute a command inside back quotes. If it's a builtin command, we
5640 * want to save its output in a block obtained from malloc. Otherwise
5641 * we fork off a subprocess and get the output of the command via a pipe.
5642 * Should be called with interrupts off.
5643 */
5644struct backcmd { /* result of evalbackcmd */
5645 int fd; /* file descriptor to read from */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005646 int nleft; /* number of chars in buffer */
Denis Vlasenkob07a4962008-06-22 13:16:23 +00005647 char *buf; /* buffer */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005648 struct job *jp; /* job structure for command */
5649};
5650
5651/* These forward decls are needed to use "eval" code for backticks handling: */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00005652static uint8_t back_exitstatus; /* exit status of backquoted command */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005653#define EV_EXIT 01 /* exit after evaluating tree */
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02005654static void evaltree(union node *, int);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005655
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02005656static void FAST_FUNC
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005657evalbackcmd(union node *n, struct backcmd *result)
5658{
5659 int saveherefd;
5660
5661 result->fd = -1;
5662 result->buf = NULL;
5663 result->nleft = 0;
5664 result->jp = NULL;
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00005665 if (n == NULL)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005666 goto out;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005667
5668 saveherefd = herefd;
5669 herefd = -1;
5670
5671 {
5672 int pip[2];
5673 struct job *jp;
5674
5675 if (pipe(pip) < 0)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00005676 ash_msg_and_raise_error("pipe call failed");
Denis Vlasenko68404f12008-03-17 09:00:54 +00005677 jp = makejob(/*n,*/ 1);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005678 if (forkshell(jp, n, FORK_NOJOB) == 0) {
5679 FORCE_INT_ON;
5680 close(pip[0]);
5681 if (pip[1] != 1) {
Denis Vlasenko5a867312008-07-24 19:46:38 +00005682 /*close(1);*/
5683 copyfd(pip[1], 1 | COPYFD_EXACT);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005684 close(pip[1]);
5685 }
5686 eflag = 0;
5687 evaltree(n, EV_EXIT); /* actually evaltreenr... */
5688 /* NOTREACHED */
5689 }
5690 close(pip[1]);
5691 result->fd = pip[0];
5692 result->jp = jp;
5693 }
5694 herefd = saveherefd;
5695 out:
5696 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
5697 result->fd, result->buf, result->nleft, result->jp));
5698}
5699
5700/*
5701 * Expand stuff in backwards quotes.
5702 */
5703static void
5704expbackq(union node *cmd, int quoted, int quotes)
5705{
5706 struct backcmd in;
5707 int i;
5708 char buf[128];
5709 char *p;
5710 char *dest;
5711 int startloc;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00005712 int syntax = quoted ? DQSYNTAX : BASESYNTAX;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005713 struct stackmark smark;
5714
5715 INT_OFF;
5716 setstackmark(&smark);
5717 dest = expdest;
5718 startloc = dest - (char *)stackblock();
5719 grabstackstr(dest);
5720 evalbackcmd(cmd, &in);
5721 popstackmark(&smark);
5722
5723 p = in.buf;
5724 i = in.nleft;
5725 if (i == 0)
5726 goto read;
5727 for (;;) {
5728 memtodest(p, i, syntax, quotes);
5729 read:
5730 if (in.fd < 0)
5731 break;
Denis Vlasenkoe376d452008-02-20 22:23:24 +00005732 i = nonblock_safe_read(in.fd, buf, sizeof(buf));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005733 TRACE(("expbackq: read returns %d\n", i));
5734 if (i <= 0)
5735 break;
5736 p = buf;
5737 }
5738
Denis Vlasenko60818682007-09-28 22:07:23 +00005739 free(in.buf);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005740 if (in.fd >= 0) {
5741 close(in.fd);
5742 back_exitstatus = waitforjob(in.jp);
5743 }
5744 INT_ON;
5745
5746 /* Eat all trailing newlines */
5747 dest = expdest;
5748 for (; dest > (char *)stackblock() && dest[-1] == '\n';)
5749 STUNPUTC(dest);
5750 expdest = dest;
5751
5752 if (quoted == 0)
5753 recordregion(startloc, dest - (char *)stackblock(), 0);
5754 TRACE(("evalbackq: size=%d: \"%.*s\"\n",
5755 (dest - (char *)stackblock()) - startloc,
5756 (dest - (char *)stackblock()) - startloc,
5757 stackblock() + startloc));
5758}
5759
Mike Frysinger98c52642009-04-02 10:02:37 +00005760#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005761/*
5762 * Expand arithmetic expression. Backup to start of expression,
5763 * evaluate, place result in (backed up) result, adjust string position.
5764 */
5765static void
5766expari(int quotes)
5767{
5768 char *p, *start;
5769 int begoff;
5770 int flag;
5771 int len;
5772
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00005773 /* ifsfree(); */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005774
5775 /*
5776 * This routine is slightly over-complicated for
5777 * efficiency. Next we scan backwards looking for the
5778 * start of arithmetic.
5779 */
5780 start = stackblock();
5781 p = expdest - 1;
5782 *p = '\0';
5783 p--;
5784 do {
5785 int esc;
5786
Denys Vlasenkocd716832009-11-28 22:14:02 +01005787 while ((unsigned char)*p != CTLARI) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005788 p--;
5789#if DEBUG
5790 if (p < start) {
5791 ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
5792 }
5793#endif
5794 }
5795
5796 esc = esclen(start, p);
5797 if (!(esc % 2)) {
5798 break;
5799 }
5800
5801 p -= esc + 1;
5802 } while (1);
5803
5804 begoff = p - start;
5805
5806 removerecordregions(begoff);
5807
5808 flag = p[1];
5809
5810 expdest = p;
5811
5812 if (quotes)
Denys Vlasenkob6c84342009-08-29 20:23:20 +02005813 rmescapes(p + 2, 0);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005814
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00005815 len = cvtnum(ash_arith(p + 2));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005816
5817 if (flag != '"')
5818 recordregion(begoff, begoff + len, 0);
5819}
5820#endif
5821
5822/* argstr needs it */
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005823static char *evalvar(char *p, int flags, struct strlist *var_str_list);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005824
5825/*
5826 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
5827 * characters to allow for further processing. Otherwise treat
5828 * $@ like $* since no splitting will be performed.
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00005829 *
5830 * var_str_list (can be NULL) is a list of "VAR=val" strings which take precedence
5831 * over shell varables. Needed for "A=a B=$A; echo $B" case - we use it
5832 * for correct expansion of "B=$A" word.
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005833 */
5834static void
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005835argstr(char *p, int flags, struct strlist *var_str_list)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005836{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00005837 static const char spclchars[] ALIGN1 = {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005838 '=',
5839 ':',
5840 CTLQUOTEMARK,
5841 CTLENDVAR,
5842 CTLESC,
5843 CTLVAR,
5844 CTLBACKQ,
5845 CTLBACKQ | CTLQUOTE,
Mike Frysinger98c52642009-04-02 10:02:37 +00005846#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005847 CTLENDARI,
5848#endif
Denys Vlasenkocd716832009-11-28 22:14:02 +01005849 '\0'
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005850 };
5851 const char *reject = spclchars;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005852 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR); /* do CTLESC */
5853 int breakall = flags & EXP_WORD;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005854 int inquotes;
5855 size_t length;
5856 int startloc;
5857
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005858 if (!(flags & EXP_VARTILDE)) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005859 reject += 2;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005860 } else if (flags & EXP_VARTILDE2) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005861 reject++;
5862 }
5863 inquotes = 0;
5864 length = 0;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005865 if (flags & EXP_TILDE) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005866 char *q;
5867
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005868 flags &= ~EXP_TILDE;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005869 tilde:
5870 q = p;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005871 if (*q == CTLESC && (flags & EXP_QWORD))
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005872 q++;
5873 if (*q == '~')
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005874 p = exptilde(p, q, flags);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005875 }
5876 start:
5877 startloc = expdest - (char *)stackblock();
5878 for (;;) {
Denys Vlasenkocd716832009-11-28 22:14:02 +01005879 unsigned char c;
5880
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005881 length += strcspn(p + length, reject);
Denys Vlasenkocd716832009-11-28 22:14:02 +01005882 c = p[length];
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005883 if (c) {
5884 if (!(c & 0x80)
Mike Frysinger98c52642009-04-02 10:02:37 +00005885#if ENABLE_SH_MATH_SUPPORT
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005886 || c == CTLENDARI
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005887#endif
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005888 ) {
5889 /* c == '=' || c == ':' || c == CTLENDARI */
5890 length++;
5891 }
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005892 }
5893 if (length > 0) {
5894 int newloc;
5895 expdest = stack_nputstr(p, length, expdest);
5896 newloc = expdest - (char *)stackblock();
5897 if (breakall && !inquotes && newloc > startloc) {
5898 recordregion(startloc, newloc, 0);
5899 }
5900 startloc = newloc;
5901 }
5902 p += length + 1;
5903 length = 0;
5904
5905 switch (c) {
5906 case '\0':
5907 goto breakloop;
5908 case '=':
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005909 if (flags & EXP_VARTILDE2) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005910 p--;
5911 continue;
5912 }
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005913 flags |= EXP_VARTILDE2;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005914 reject++;
5915 /* fall through */
5916 case ':':
5917 /*
5918 * sort of a hack - expand tildes in variable
5919 * assignments (after the first '=' and after ':'s).
5920 */
5921 if (*--p == '~') {
5922 goto tilde;
5923 }
5924 continue;
5925 }
5926
5927 switch (c) {
5928 case CTLENDVAR: /* ??? */
5929 goto breakloop;
5930 case CTLQUOTEMARK:
5931 /* "$@" syntax adherence hack */
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005932 if (!inquotes
5933 && memcmp(p, dolatstr, 4) == 0
5934 && ( p[4] == CTLQUOTEMARK
5935 || (p[4] == CTLENDVAR && p[5] == CTLQUOTEMARK)
5936 )
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005937 ) {
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005938 p = evalvar(p + 1, flags, /* var_str_list: */ NULL) + 1;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005939 goto start;
5940 }
5941 inquotes = !inquotes;
5942 addquote:
5943 if (quotes) {
5944 p--;
5945 length++;
5946 startloc++;
5947 }
5948 break;
5949 case CTLESC:
5950 startloc++;
5951 length++;
5952 goto addquote;
5953 case CTLVAR:
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005954 p = evalvar(p, flags, var_str_list);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005955 goto start;
5956 case CTLBACKQ:
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005957 c = '\0';
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005958 case CTLBACKQ|CTLQUOTE:
5959 expbackq(argbackq->n, c, quotes);
5960 argbackq = argbackq->next;
5961 goto start;
Mike Frysinger98c52642009-04-02 10:02:37 +00005962#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005963 case CTLENDARI:
5964 p--;
5965 expari(quotes);
5966 goto start;
5967#endif
5968 }
5969 }
5970 breakloop:
5971 ;
5972}
5973
5974static char *
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00005975scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM, char *str, int quotes,
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005976 int zero)
5977{
Denis Vlasenkoc7131c32008-04-14 01:59:53 +00005978// This commented out code was added by James Simmons <jsimmons@infradead.org>
5979// as part of a larger change when he added support for ${var/a/b}.
5980// However, it broke # and % operators:
5981//
5982//var=ababcdcd
5983// ok bad
5984//echo ${var#ab} abcdcd abcdcd
5985//echo ${var##ab} abcdcd abcdcd
5986//echo ${var#a*b} abcdcd ababcdcd (!)
5987//echo ${var##a*b} cdcd cdcd
5988//echo ${var#?} babcdcd ababcdcd (!)
5989//echo ${var##?} babcdcd babcdcd
5990//echo ${var#*} ababcdcd babcdcd (!)
5991//echo ${var##*}
5992//echo ${var%cd} ababcd ababcd
5993//echo ${var%%cd} ababcd abab (!)
5994//echo ${var%c*d} ababcd ababcd
5995//echo ${var%%c*d} abab ababcdcd (!)
5996//echo ${var%?} ababcdc ababcdc
5997//echo ${var%%?} ababcdc ababcdcd (!)
5998//echo ${var%*} ababcdcd ababcdcd
5999//echo ${var%%*}
6000//
6001// Commenting it back out helped. Remove it completely if it really
6002// is not needed.
6003
6004 char *loc, *loc2; //, *full;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006005 char c;
6006
6007 loc = startp;
6008 loc2 = rmesc;
6009 do {
Denis Vlasenkoc7131c32008-04-14 01:59:53 +00006010 int match; // = strlen(str);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006011 const char *s = loc2;
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006012
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006013 c = *loc2;
6014 if (zero) {
6015 *loc2 = '\0';
6016 s = rmesc;
6017 }
Denis Vlasenkoc7131c32008-04-14 01:59:53 +00006018 match = pmatch(str, s); // this line was deleted
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006019
Denis Vlasenkoc7131c32008-04-14 01:59:53 +00006020// // chop off end if its '*'
6021// full = strrchr(str, '*');
6022// if (full && full != str)
6023// match--;
6024//
6025// // If str starts with '*' replace with s.
6026// if ((*str == '*') && strlen(s) >= match) {
6027// full = xstrdup(s);
6028// strncpy(full+strlen(s)-match+1, str+1, match-1);
6029// } else
6030// full = xstrndup(str, match);
6031// match = strncmp(s, full, strlen(full));
6032// free(full);
6033//
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006034 *loc2 = c;
Denis Vlasenkoc7131c32008-04-14 01:59:53 +00006035 if (match) // if (!match)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006036 return loc;
Denys Vlasenkocd716832009-11-28 22:14:02 +01006037 if (quotes && (unsigned char)*loc == CTLESC)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006038 loc++;
6039 loc++;
6040 loc2++;
6041 } while (c);
6042 return 0;
6043}
6044
6045static char *
6046scanright(char *startp, char *rmesc, char *rmescend, char *str, int quotes,
6047 int zero)
6048{
6049 int esc = 0;
6050 char *loc;
6051 char *loc2;
6052
6053 for (loc = str - 1, loc2 = rmescend; loc >= startp; loc2--) {
6054 int match;
6055 char c = *loc2;
6056 const char *s = loc2;
6057 if (zero) {
6058 *loc2 = '\0';
6059 s = rmesc;
6060 }
6061 match = pmatch(str, s);
6062 *loc2 = c;
6063 if (match)
6064 return loc;
6065 loc--;
6066 if (quotes) {
6067 if (--esc < 0) {
6068 esc = esclen(startp, loc);
6069 }
6070 if (esc % 2) {
6071 esc--;
6072 loc--;
6073 }
6074 }
6075 }
6076 return 0;
6077}
6078
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00006079static void varunset(const char *, const char *, const char *, int) NORETURN;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006080static void
6081varunset(const char *end, const char *var, const char *umsg, int varflags)
6082{
6083 const char *msg;
6084 const char *tail;
6085
6086 tail = nullstr;
6087 msg = "parameter not set";
6088 if (umsg) {
Denys Vlasenkocd716832009-11-28 22:14:02 +01006089 if ((unsigned char)*end == CTLENDVAR) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006090 if (varflags & VSNUL)
6091 tail = " or null";
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00006092 } else {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006093 msg = umsg;
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00006094 }
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006095 }
6096 ash_msg_and_raise_error("%.*s: %s%s", end - var - 1, var, msg, tail);
6097}
6098
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006099#if ENABLE_ASH_BASH_COMPAT
6100static char *
6101parse_sub_pattern(char *arg, int inquotes)
6102{
6103 char *idx, *repl = NULL;
6104 unsigned char c;
6105
Denis Vlasenko2659c632008-06-14 06:04:59 +00006106 idx = arg;
6107 while (1) {
6108 c = *arg;
6109 if (!c)
6110 break;
6111 if (c == '/') {
6112 /* Only the first '/' seen is our separator */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006113 if (!repl) {
Denis Vlasenko2659c632008-06-14 06:04:59 +00006114 repl = idx + 1;
6115 c = '\0';
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006116 }
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006117 }
Denis Vlasenko2659c632008-06-14 06:04:59 +00006118 *idx++ = c;
6119 if (!inquotes && c == '\\' && arg[1] == '\\')
6120 arg++; /* skip both \\, not just first one */
6121 arg++;
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006122 }
Denis Vlasenko29038c02008-06-14 06:14:02 +00006123 *idx = c; /* NUL */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006124
6125 return repl;
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006126}
6127#endif /* ENABLE_ASH_BASH_COMPAT */
6128
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006129static const char *
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006130subevalvar(char *p, char *str, int strloc, int subtype,
6131 int startloc, int varflags, int quotes, struct strlist *var_str_list)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006132{
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006133 struct nodelist *saveargbackq = argbackq;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006134 char *startp;
6135 char *loc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006136 char *rmesc, *rmescend;
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00006137 IF_ASH_BASH_COMPAT(char *repl = NULL;)
6138 IF_ASH_BASH_COMPAT(char null = '\0';)
6139 IF_ASH_BASH_COMPAT(int pos, len, orig_len;)
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006140 int saveherefd = herefd;
6141 int amount, workloc, resetloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006142 int zero;
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006143 char *(*scan)(char*, char*, char*, char*, int, int);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006144
6145 herefd = -1;
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006146 argstr(p, (subtype != VSASSIGN && subtype != VSQUESTION) ? EXP_CASE : 0,
6147 var_str_list);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006148 STPUTC('\0', expdest);
6149 herefd = saveherefd;
6150 argbackq = saveargbackq;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00006151 startp = (char *)stackblock() + startloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006152
6153 switch (subtype) {
6154 case VSASSIGN:
6155 setvar(str, startp, 0);
6156 amount = startp - expdest;
6157 STADJUST(amount, expdest);
6158 return startp;
6159
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006160#if ENABLE_ASH_BASH_COMPAT
6161 case VSSUBSTR:
6162 loc = str = stackblock() + strloc;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006163 /* Read POS in ${var:POS:LEN} */
6164 pos = atoi(loc); /* number(loc) errors out on "1:4" */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006165 len = str - startp - 1;
6166
6167 /* *loc != '\0', guaranteed by parser */
6168 if (quotes) {
6169 char *ptr;
6170
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006171 /* Adjust the length by the number of escapes */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006172 for (ptr = startp; ptr < (str - 1); ptr++) {
Denys Vlasenkocd716832009-11-28 22:14:02 +01006173 if ((unsigned char)*ptr == CTLESC) {
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006174 len--;
6175 ptr++;
6176 }
6177 }
6178 }
6179 orig_len = len;
6180
6181 if (*loc++ == ':') {
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006182 /* ${var::LEN} */
6183 len = number(loc);
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006184 } else {
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006185 /* Skip POS in ${var:POS:LEN} */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006186 len = orig_len;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006187 while (*loc && *loc != ':') {
6188 /* TODO?
6189 * bash complains on: var=qwe; echo ${var:1a:123}
6190 if (!isdigit(*loc))
6191 ash_msg_and_raise_error(msg_illnum, str);
6192 */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006193 loc++;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006194 }
6195 if (*loc++ == ':') {
6196 len = number(loc);
6197 }
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006198 }
6199 if (pos >= orig_len) {
6200 pos = 0;
6201 len = 0;
6202 }
6203 if (len > (orig_len - pos))
6204 len = orig_len - pos;
6205
6206 for (str = startp; pos; str++, pos--) {
Denys Vlasenkocd716832009-11-28 22:14:02 +01006207 if (quotes && (unsigned char)*str == CTLESC)
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006208 str++;
6209 }
6210 for (loc = startp; len; len--) {
Denys Vlasenkocd716832009-11-28 22:14:02 +01006211 if (quotes && (unsigned char)*str == CTLESC)
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006212 *loc++ = *str++;
6213 *loc++ = *str++;
6214 }
6215 *loc = '\0';
6216 amount = loc - expdest;
6217 STADJUST(amount, expdest);
6218 return loc;
6219#endif
6220
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006221 case VSQUESTION:
6222 varunset(p, str, startp, varflags);
6223 /* NOTREACHED */
6224 }
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006225 resetloc = expdest - (char *)stackblock();
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006226
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006227 /* We'll comeback here if we grow the stack while handling
6228 * a VSREPLACE or VSREPLACEALL, since our pointers into the
6229 * stack will need rebasing, and we'll need to remove our work
6230 * areas each time
6231 */
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00006232 IF_ASH_BASH_COMPAT(restart:)
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006233
6234 amount = expdest - ((char *)stackblock() + resetloc);
6235 STADJUST(-amount, expdest);
Denis Vlasenko29eb3592008-05-18 14:06:08 +00006236 startp = (char *)stackblock() + startloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006237
6238 rmesc = startp;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00006239 rmescend = (char *)stackblock() + strloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006240 if (quotes) {
Denys Vlasenkob6c84342009-08-29 20:23:20 +02006241 rmesc = rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006242 if (rmesc != startp) {
6243 rmescend = expdest;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00006244 startp = (char *)stackblock() + startloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006245 }
6246 }
6247 rmescend--;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00006248 str = (char *)stackblock() + strloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006249 preglob(str, varflags & VSQUOTE, 0);
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006250 workloc = expdest - (char *)stackblock();
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006251
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006252#if ENABLE_ASH_BASH_COMPAT
6253 if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
6254 char *idx, *end, *restart_detect;
6255
Denis Vlasenkod6855d12008-09-27 14:03:25 +00006256 if (!repl) {
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006257 repl = parse_sub_pattern(str, varflags & VSQUOTE);
6258 if (!repl)
6259 repl = &null;
6260 }
6261
6262 /* If there's no pattern to match, return the expansion unmolested */
6263 if (*str == '\0')
6264 return 0;
6265
6266 len = 0;
6267 idx = startp;
6268 end = str - 1;
6269 while (idx < end) {
6270 loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
6271 if (!loc) {
6272 /* No match, advance */
6273 restart_detect = stackblock();
6274 STPUTC(*idx, expdest);
Denys Vlasenkocd716832009-11-28 22:14:02 +01006275 if (quotes && (unsigned char)*idx == CTLESC) {
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006276 idx++;
6277 len++;
6278 STPUTC(*idx, expdest);
6279 }
6280 if (stackblock() != restart_detect)
6281 goto restart;
6282 idx++;
6283 len++;
6284 rmesc++;
6285 continue;
6286 }
6287
6288 if (subtype == VSREPLACEALL) {
6289 while (idx < loc) {
Denys Vlasenkocd716832009-11-28 22:14:02 +01006290 if (quotes && (unsigned char)*idx == CTLESC)
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006291 idx++;
6292 idx++;
6293 rmesc++;
6294 }
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00006295 } else {
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006296 idx = loc;
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00006297 }
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006298
6299 for (loc = repl; *loc; loc++) {
6300 restart_detect = stackblock();
6301 STPUTC(*loc, expdest);
6302 if (stackblock() != restart_detect)
6303 goto restart;
6304 len++;
6305 }
6306
6307 if (subtype == VSREPLACE) {
6308 while (*idx) {
6309 restart_detect = stackblock();
6310 STPUTC(*idx, expdest);
6311 if (stackblock() != restart_detect)
6312 goto restart;
6313 len++;
6314 idx++;
6315 }
6316 break;
6317 }
6318 }
6319
6320 /* We've put the replaced text into a buffer at workloc, now
6321 * move it to the right place and adjust the stack.
6322 */
6323 startp = stackblock() + startloc;
6324 STPUTC('\0', expdest);
6325 memmove(startp, stackblock() + workloc, len);
6326 startp[len++] = '\0';
6327 amount = expdest - ((char *)stackblock() + startloc + len - 1);
6328 STADJUST(-amount, expdest);
6329 return startp;
6330 }
6331#endif /* ENABLE_ASH_BASH_COMPAT */
6332
6333 subtype -= VSTRIMRIGHT;
6334#if DEBUG
6335 if (subtype < 0 || subtype > 7)
6336 abort();
6337#endif
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006338 /* zero = subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX */
6339 zero = subtype >> 1;
6340 /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
6341 scan = (subtype & 1) ^ zero ? scanleft : scanright;
6342
6343 loc = scan(startp, rmesc, rmescend, str, quotes, zero);
6344 if (loc) {
6345 if (zero) {
6346 memmove(startp, loc, str - loc);
6347 loc = startp + (str - loc) - 1;
6348 }
6349 *loc = '\0';
6350 amount = loc - expdest;
6351 STADJUST(amount, expdest);
6352 }
6353 return loc;
6354}
6355
6356/*
6357 * Add the value of a specialized variable to the stack string.
Denys Vlasenko4d8873f2009-10-04 03:14:41 +02006358 * name parameter (examples):
6359 * ash -c 'echo $1' name:'1='
6360 * ash -c 'echo $qwe' name:'qwe='
6361 * ash -c 'echo $$' name:'$='
6362 * ash -c 'echo ${$}' name:'$='
6363 * ash -c 'echo ${$##q}' name:'$=q'
6364 * ash -c 'echo ${#$}' name:'$='
6365 * note: examples with bad shell syntax:
6366 * ash -c 'echo ${#$1}' name:'$=1'
6367 * ash -c 'echo ${#1#}' name:'1=#'
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006368 */
Denys Vlasenkoadf922e2009-10-08 14:35:37 +02006369static NOINLINE ssize_t
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006370varvalue(char *name, int varflags, int flags, struct strlist *var_str_list)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006371{
Mike Frysinger98c52642009-04-02 10:02:37 +00006372 const char *p;
Denys Vlasenko8eda4a92009-11-30 12:16:17 +01006373 int num;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006374 int i;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006375 int sepq = 0;
6376 ssize_t len = 0;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006377 int subtype = varflags & VSTYPE;
Denys Vlasenko1166d7b2009-09-16 16:20:31 +02006378 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR);
Denys Vlasenko8eda4a92009-11-30 12:16:17 +01006379 int quoted = varflags & VSQUOTE;
6380 int syntax = quoted ? DQSYNTAX : BASESYNTAX;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006381
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006382 switch (*name) {
6383 case '$':
6384 num = rootpid;
6385 goto numvar;
6386 case '?':
6387 num = exitstatus;
6388 goto numvar;
6389 case '#':
6390 num = shellparam.nparam;
6391 goto numvar;
6392 case '!':
6393 num = backgndpid;
6394 if (num == 0)
6395 return -1;
6396 numvar:
6397 len = cvtnum(num);
Denys Vlasenko4d8873f2009-10-04 03:14:41 +02006398 goto check_1char_name;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006399 case '-':
Mike Frysinger98c52642009-04-02 10:02:37 +00006400 expdest = makestrspace(NOPTS, expdest);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006401 for (i = NOPTS - 1; i >= 0; i--) {
6402 if (optlist[i]) {
Mike Frysinger98c52642009-04-02 10:02:37 +00006403 USTPUTC(optletters(i), expdest);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006404 len++;
6405 }
6406 }
Denys Vlasenko4d8873f2009-10-04 03:14:41 +02006407 check_1char_name:
6408#if 0
6409 /* handles cases similar to ${#$1} */
6410 if (name[2] != '\0')
6411 raise_error_syntax("bad substitution");
6412#endif
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006413 break;
Denys Vlasenko8eda4a92009-11-30 12:16:17 +01006414 case '@': {
6415 char **ap;
6416 int sep;
6417
6418 if (quoted && (flags & EXP_FULL)) {
6419 /* note: this is not meant as PEOF value */
6420 sep = 1 << CHAR_BIT;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006421 goto param;
Denys Vlasenko8eda4a92009-11-30 12:16:17 +01006422 }
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006423 /* fall through */
6424 case '*':
Denys Vlasenkocd716832009-11-28 22:14:02 +01006425 sep = ifsset() ? (unsigned char)(ifsval()[0]) : ' ';
Denys Vlasenko8eda4a92009-11-30 12:16:17 +01006426 i = SIT(sep, syntax);
6427 if (quotes && (i == CCTL || i == CBACK))
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006428 sepq = 1;
6429 param:
6430 ap = shellparam.p;
6431 if (!ap)
6432 return -1;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006433 while ((p = *ap++) != NULL) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006434 size_t partlen;
6435
6436 partlen = strlen(p);
6437 len += partlen;
6438
6439 if (!(subtype == VSPLUS || subtype == VSLENGTH))
6440 memtodest(p, partlen, syntax, quotes);
6441
6442 if (*ap && sep) {
6443 char *q;
6444
6445 len++;
6446 if (subtype == VSPLUS || subtype == VSLENGTH) {
6447 continue;
6448 }
6449 q = expdest;
6450 if (sepq)
6451 STPUTC(CTLESC, q);
Denys Vlasenko8eda4a92009-11-30 12:16:17 +01006452 /* note: may put NUL despite sep != 0
6453 * (see sep = 1 << CHAR_BIT above) */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006454 STPUTC(sep, q);
6455 expdest = q;
6456 }
6457 }
6458 return len;
Denys Vlasenko8eda4a92009-11-30 12:16:17 +01006459 } /* case '@' and '*' */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006460 case '0':
6461 case '1':
6462 case '2':
6463 case '3':
6464 case '4':
6465 case '5':
6466 case '6':
6467 case '7':
6468 case '8':
6469 case '9':
Denys Vlasenkoa00329c2009-08-30 20:05:10 +02006470 num = atoi(name); /* number(name) fails on ${N#str} etc */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006471 if (num < 0 || num > shellparam.nparam)
6472 return -1;
6473 p = num ? shellparam.p[num - 1] : arg0;
6474 goto value;
6475 default:
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006476 /* NB: name has form "VAR=..." */
6477
6478 /* "A=a B=$A" case: var_str_list is a list of "A=a" strings
6479 * which should be considered before we check variables. */
6480 if (var_str_list) {
6481 unsigned name_len = (strchrnul(name, '=') - name) + 1;
6482 p = NULL;
6483 do {
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00006484 char *str, *eq;
6485 str = var_str_list->text;
6486 eq = strchr(str, '=');
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006487 if (!eq) /* stop at first non-assignment */
6488 break;
6489 eq++;
Denis Vlasenko6b06cb82008-05-15 21:30:45 +00006490 if (name_len == (unsigned)(eq - str)
Denys Vlasenko8eda4a92009-11-30 12:16:17 +01006491 && strncmp(str, name, name_len) == 0
6492 ) {
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006493 p = eq;
6494 /* goto value; - WRONG! */
6495 /* think "A=1 A=2 B=$A" */
6496 }
6497 var_str_list = var_str_list->next;
6498 } while (var_str_list);
6499 if (p)
6500 goto value;
6501 }
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006502 p = lookupvar(name);
6503 value:
6504 if (!p)
6505 return -1;
6506
6507 len = strlen(p);
6508 if (!(subtype == VSPLUS || subtype == VSLENGTH))
6509 memtodest(p, len, syntax, quotes);
6510 return len;
6511 }
6512
6513 if (subtype == VSPLUS || subtype == VSLENGTH)
6514 STADJUST(-len, expdest);
6515 return len;
6516}
6517
6518/*
6519 * Expand a variable, and return a pointer to the next character in the
6520 * input string.
6521 */
6522static char *
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006523evalvar(char *p, int flags, struct strlist *var_str_list)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006524{
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006525 char varflags;
6526 char subtype;
6527 char quoted;
6528 char easy;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006529 char *var;
6530 int patloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006531 int startloc;
6532 ssize_t varlen;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006533
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006534 varflags = (unsigned char) *p++;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006535 subtype = varflags & VSTYPE;
6536 quoted = varflags & VSQUOTE;
6537 var = p;
6538 easy = (!quoted || (*var == '@' && shellparam.nparam));
6539 startloc = expdest - (char *)stackblock();
6540 p = strchr(p, '=') + 1;
6541
6542 again:
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006543 varlen = varvalue(var, varflags, flags, var_str_list);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006544 if (varflags & VSNUL)
6545 varlen--;
6546
6547 if (subtype == VSPLUS) {
6548 varlen = -1 - varlen;
6549 goto vsplus;
6550 }
6551
6552 if (subtype == VSMINUS) {
6553 vsplus:
6554 if (varlen < 0) {
6555 argstr(
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006556 p, flags | EXP_TILDE |
6557 (quoted ? EXP_QWORD : EXP_WORD),
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006558 var_str_list
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006559 );
6560 goto end;
6561 }
6562 if (easy)
6563 goto record;
6564 goto end;
6565 }
6566
6567 if (subtype == VSASSIGN || subtype == VSQUESTION) {
6568 if (varlen < 0) {
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006569 if (subevalvar(p, var, /* strloc: */ 0,
6570 subtype, startloc, varflags,
6571 /* quotes: */ 0,
6572 var_str_list)
6573 ) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006574 varflags &= ~VSNUL;
6575 /*
6576 * Remove any recorded regions beyond
6577 * start of variable
6578 */
6579 removerecordregions(startloc);
6580 goto again;
6581 }
6582 goto end;
6583 }
6584 if (easy)
6585 goto record;
6586 goto end;
6587 }
6588
6589 if (varlen < 0 && uflag)
6590 varunset(p, var, 0, 0);
6591
6592 if (subtype == VSLENGTH) {
6593 cvtnum(varlen > 0 ? varlen : 0);
6594 goto record;
6595 }
6596
6597 if (subtype == VSNORMAL) {
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006598 if (easy)
6599 goto record;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006600 goto end;
6601 }
6602
6603#if DEBUG
6604 switch (subtype) {
6605 case VSTRIMLEFT:
6606 case VSTRIMLEFTMAX:
6607 case VSTRIMRIGHT:
6608 case VSTRIMRIGHTMAX:
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006609#if ENABLE_ASH_BASH_COMPAT
6610 case VSSUBSTR:
6611 case VSREPLACE:
6612 case VSREPLACEALL:
6613#endif
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006614 break;
6615 default:
6616 abort();
6617 }
6618#endif
6619
6620 if (varlen >= 0) {
6621 /*
6622 * Terminate the string and start recording the pattern
6623 * right after it
6624 */
6625 STPUTC('\0', expdest);
6626 patloc = expdest - (char *)stackblock();
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006627 if (0 == subevalvar(p, /* str: */ NULL, patloc, subtype,
6628 startloc, varflags,
Denys Vlasenko1166d7b2009-09-16 16:20:31 +02006629//TODO: | EXP_REDIR too? All other such places do it too
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006630 /* quotes: */ flags & (EXP_FULL | EXP_CASE),
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006631 var_str_list)
6632 ) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006633 int amount = expdest - (
6634 (char *)stackblock() + patloc - 1
6635 );
6636 STADJUST(-amount, expdest);
6637 }
6638 /* Remove any recorded regions beyond start of variable */
6639 removerecordregions(startloc);
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006640 record:
6641 recordregion(startloc, expdest - (char *)stackblock(), quoted);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006642 }
6643
6644 end:
6645 if (subtype != VSNORMAL) { /* skip to end of alternative */
6646 int nesting = 1;
6647 for (;;) {
Denys Vlasenkocd716832009-11-28 22:14:02 +01006648 unsigned char c = *p++;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006649 if (c == CTLESC)
6650 p++;
6651 else if (c == CTLBACKQ || c == (CTLBACKQ|CTLQUOTE)) {
6652 if (varlen >= 0)
6653 argbackq = argbackq->next;
6654 } else if (c == CTLVAR) {
6655 if ((*p++ & VSTYPE) != VSNORMAL)
6656 nesting++;
6657 } else if (c == CTLENDVAR) {
6658 if (--nesting == 0)
6659 break;
6660 }
6661 }
6662 }
6663 return p;
6664}
6665
6666/*
6667 * Break the argument string into pieces based upon IFS and add the
6668 * strings to the argument list. The regions of the string to be
6669 * searched for IFS characters have been stored by recordregion.
6670 */
6671static void
6672ifsbreakup(char *string, struct arglist *arglist)
6673{
6674 struct ifsregion *ifsp;
6675 struct strlist *sp;
6676 char *start;
6677 char *p;
6678 char *q;
6679 const char *ifs, *realifs;
6680 int ifsspc;
6681 int nulonly;
6682
6683 start = string;
6684 if (ifslastp != NULL) {
6685 ifsspc = 0;
6686 nulonly = 0;
6687 realifs = ifsset() ? ifsval() : defifs;
6688 ifsp = &ifsfirst;
6689 do {
6690 p = string + ifsp->begoff;
6691 nulonly = ifsp->nulonly;
6692 ifs = nulonly ? nullstr : realifs;
6693 ifsspc = 0;
6694 while (p < string + ifsp->endoff) {
6695 q = p;
Denys Vlasenkocd716832009-11-28 22:14:02 +01006696 if ((unsigned char)*p == CTLESC)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006697 p++;
6698 if (!strchr(ifs, *p)) {
6699 p++;
6700 continue;
6701 }
6702 if (!nulonly)
6703 ifsspc = (strchr(defifs, *p) != NULL);
6704 /* Ignore IFS whitespace at start */
6705 if (q == start && ifsspc) {
6706 p++;
6707 start = p;
6708 continue;
6709 }
6710 *q = '\0';
Denis Vlasenko597906c2008-02-20 16:38:54 +00006711 sp = stzalloc(sizeof(*sp));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006712 sp->text = start;
6713 *arglist->lastp = sp;
6714 arglist->lastp = &sp->next;
6715 p++;
6716 if (!nulonly) {
6717 for (;;) {
6718 if (p >= string + ifsp->endoff) {
6719 break;
6720 }
6721 q = p;
Denys Vlasenkocd716832009-11-28 22:14:02 +01006722 if ((unsigned char)*p == CTLESC)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006723 p++;
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +00006724 if (strchr(ifs, *p) == NULL) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006725 p = q;
6726 break;
Denis Vlasenko597906c2008-02-20 16:38:54 +00006727 }
6728 if (strchr(defifs, *p) == NULL) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006729 if (ifsspc) {
6730 p++;
6731 ifsspc = 0;
6732 } else {
6733 p = q;
6734 break;
6735 }
6736 } else
6737 p++;
6738 }
6739 }
6740 start = p;
6741 } /* while */
6742 ifsp = ifsp->next;
6743 } while (ifsp != NULL);
6744 if (nulonly)
6745 goto add;
6746 }
6747
6748 if (!*start)
6749 return;
6750
6751 add:
Denis Vlasenko597906c2008-02-20 16:38:54 +00006752 sp = stzalloc(sizeof(*sp));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006753 sp->text = start;
6754 *arglist->lastp = sp;
6755 arglist->lastp = &sp->next;
6756}
6757
6758static void
6759ifsfree(void)
6760{
6761 struct ifsregion *p;
6762
6763 INT_OFF;
6764 p = ifsfirst.next;
6765 do {
6766 struct ifsregion *ifsp;
6767 ifsp = p->next;
6768 free(p);
6769 p = ifsp;
6770 } while (p);
6771 ifslastp = NULL;
6772 ifsfirst.next = NULL;
6773 INT_ON;
6774}
6775
6776/*
6777 * Add a file name to the list.
6778 */
6779static void
6780addfname(const char *name)
6781{
6782 struct strlist *sp;
6783
Denis Vlasenko597906c2008-02-20 16:38:54 +00006784 sp = stzalloc(sizeof(*sp));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006785 sp->text = ststrdup(name);
6786 *exparg.lastp = sp;
6787 exparg.lastp = &sp->next;
6788}
6789
6790static char *expdir;
6791
6792/*
6793 * Do metacharacter (i.e. *, ?, [...]) expansion.
6794 */
6795static void
6796expmeta(char *enddir, char *name)
6797{
6798 char *p;
6799 const char *cp;
6800 char *start;
6801 char *endname;
6802 int metaflag;
6803 struct stat statb;
6804 DIR *dirp;
6805 struct dirent *dp;
6806 int atend;
6807 int matchdot;
6808
6809 metaflag = 0;
6810 start = name;
6811 for (p = name; *p; p++) {
6812 if (*p == '*' || *p == '?')
6813 metaflag = 1;
6814 else if (*p == '[') {
6815 char *q = p + 1;
6816 if (*q == '!')
6817 q++;
6818 for (;;) {
6819 if (*q == '\\')
6820 q++;
6821 if (*q == '/' || *q == '\0')
6822 break;
6823 if (*++q == ']') {
6824 metaflag = 1;
6825 break;
6826 }
6827 }
6828 } else if (*p == '\\')
6829 p++;
6830 else if (*p == '/') {
6831 if (metaflag)
6832 goto out;
6833 start = p + 1;
6834 }
6835 }
6836 out:
6837 if (metaflag == 0) { /* we've reached the end of the file name */
6838 if (enddir != expdir)
6839 metaflag++;
6840 p = name;
6841 do {
6842 if (*p == '\\')
6843 p++;
6844 *enddir++ = *p;
6845 } while (*p++);
6846 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
6847 addfname(expdir);
6848 return;
6849 }
6850 endname = p;
6851 if (name < start) {
6852 p = name;
6853 do {
6854 if (*p == '\\')
6855 p++;
6856 *enddir++ = *p++;
6857 } while (p < start);
6858 }
6859 if (enddir == expdir) {
6860 cp = ".";
6861 } else if (enddir == expdir + 1 && *expdir == '/') {
6862 cp = "/";
6863 } else {
6864 cp = expdir;
6865 enddir[-1] = '\0';
6866 }
6867 dirp = opendir(cp);
6868 if (dirp == NULL)
6869 return;
6870 if (enddir != expdir)
6871 enddir[-1] = '/';
6872 if (*endname == 0) {
6873 atend = 1;
6874 } else {
6875 atend = 0;
6876 *endname++ = '\0';
6877 }
6878 matchdot = 0;
6879 p = start;
6880 if (*p == '\\')
6881 p++;
6882 if (*p == '.')
6883 matchdot++;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006884 while (!pending_int && (dp = readdir(dirp)) != NULL) {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00006885 if (dp->d_name[0] == '.' && !matchdot)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006886 continue;
6887 if (pmatch(start, dp->d_name)) {
6888 if (atend) {
6889 strcpy(enddir, dp->d_name);
6890 addfname(expdir);
6891 } else {
6892 for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
6893 continue;
6894 p[-1] = '/';
6895 expmeta(p, endname);
6896 }
6897 }
6898 }
6899 closedir(dirp);
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00006900 if (!atend)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006901 endname[-1] = '/';
6902}
6903
6904static struct strlist *
6905msort(struct strlist *list, int len)
6906{
6907 struct strlist *p, *q = NULL;
6908 struct strlist **lpp;
6909 int half;
6910 int n;
6911
6912 if (len <= 1)
6913 return list;
6914 half = len >> 1;
6915 p = list;
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +00006916 for (n = half; --n >= 0;) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006917 q = p;
6918 p = p->next;
6919 }
6920 q->next = NULL; /* terminate first half of list */
6921 q = msort(list, half); /* sort first half of list */
6922 p = msort(p, len - half); /* sort second half */
6923 lpp = &list;
6924 for (;;) {
6925#if ENABLE_LOCALE_SUPPORT
6926 if (strcoll(p->text, q->text) < 0)
6927#else
6928 if (strcmp(p->text, q->text) < 0)
6929#endif
6930 {
6931 *lpp = p;
6932 lpp = &p->next;
6933 p = *lpp;
6934 if (p == NULL) {
6935 *lpp = q;
6936 break;
6937 }
6938 } else {
6939 *lpp = q;
6940 lpp = &q->next;
6941 q = *lpp;
6942 if (q == NULL) {
6943 *lpp = p;
6944 break;
6945 }
6946 }
6947 }
6948 return list;
6949}
6950
6951/*
6952 * Sort the results of file name expansion. It calculates the number of
6953 * strings to sort and then calls msort (short for merge sort) to do the
6954 * work.
6955 */
6956static struct strlist *
6957expsort(struct strlist *str)
6958{
6959 int len;
6960 struct strlist *sp;
6961
6962 len = 0;
6963 for (sp = str; sp; sp = sp->next)
6964 len++;
6965 return msort(str, len);
6966}
6967
6968static void
Denis Vlasenko68404f12008-03-17 09:00:54 +00006969expandmeta(struct strlist *str /*, int flag*/)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006970{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00006971 static const char metachars[] ALIGN1 = {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006972 '*', '?', '[', 0
6973 };
6974 /* TODO - EXP_REDIR */
6975
6976 while (str) {
6977 struct strlist **savelastp;
6978 struct strlist *sp;
6979 char *p;
6980
6981 if (fflag)
6982 goto nometa;
6983 if (!strpbrk(str->text, metachars))
6984 goto nometa;
6985 savelastp = exparg.lastp;
6986
6987 INT_OFF;
6988 p = preglob(str->text, 0, RMESCAPE_ALLOC | RMESCAPE_HEAP);
6989 {
6990 int i = strlen(str->text);
6991 expdir = ckmalloc(i < 2048 ? 2048 : i); /* XXX */
6992 }
6993
6994 expmeta(expdir, p);
6995 free(expdir);
6996 if (p != str->text)
6997 free(p);
6998 INT_ON;
6999 if (exparg.lastp == savelastp) {
7000 /*
7001 * no matches
7002 */
7003 nometa:
7004 *exparg.lastp = str;
Denys Vlasenkob6c84342009-08-29 20:23:20 +02007005 rmescapes(str->text, 0);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007006 exparg.lastp = &str->next;
7007 } else {
7008 *exparg.lastp = NULL;
7009 *savelastp = sp = expsort(*savelastp);
7010 while (sp->next != NULL)
7011 sp = sp->next;
7012 exparg.lastp = &sp->next;
7013 }
7014 str = str->next;
7015 }
7016}
7017
7018/*
7019 * Perform variable substitution and command substitution on an argument,
7020 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
7021 * perform splitting and file name expansion. When arglist is NULL, perform
7022 * here document expansion.
7023 */
7024static void
7025expandarg(union node *arg, struct arglist *arglist, int flag)
7026{
7027 struct strlist *sp;
7028 char *p;
7029
7030 argbackq = arg->narg.backquote;
7031 STARTSTACKSTR(expdest);
7032 ifsfirst.next = NULL;
7033 ifslastp = NULL;
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00007034 argstr(arg->narg.text, flag,
7035 /* var_str_list: */ arglist ? arglist->list : NULL);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007036 p = _STPUTC('\0', expdest);
7037 expdest = p - 1;
7038 if (arglist == NULL) {
7039 return; /* here document expanded */
7040 }
7041 p = grabstackstr(p);
7042 exparg.lastp = &exparg.list;
7043 /*
7044 * TODO - EXP_REDIR
7045 */
7046 if (flag & EXP_FULL) {
7047 ifsbreakup(p, &exparg);
7048 *exparg.lastp = NULL;
7049 exparg.lastp = &exparg.list;
Denis Vlasenko68404f12008-03-17 09:00:54 +00007050 expandmeta(exparg.list /*, flag*/);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007051 } else {
7052 if (flag & EXP_REDIR) /*XXX - for now, just remove escapes */
Denys Vlasenkob6c84342009-08-29 20:23:20 +02007053 rmescapes(p, 0);
Denis Vlasenko597906c2008-02-20 16:38:54 +00007054 sp = stzalloc(sizeof(*sp));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007055 sp->text = p;
7056 *exparg.lastp = sp;
7057 exparg.lastp = &sp->next;
7058 }
7059 if (ifsfirst.next)
7060 ifsfree();
7061 *exparg.lastp = NULL;
7062 if (exparg.list) {
7063 *arglist->lastp = exparg.list;
7064 arglist->lastp = exparg.lastp;
7065 }
7066}
7067
7068/*
7069 * Expand shell variables and backquotes inside a here document.
7070 */
7071static void
7072expandhere(union node *arg, int fd)
7073{
7074 herefd = fd;
7075 expandarg(arg, (struct arglist *)NULL, 0);
7076 full_write(fd, stackblock(), expdest - (char *)stackblock());
7077}
7078
7079/*
7080 * Returns true if the pattern matches the string.
7081 */
7082static int
7083patmatch(char *pattern, const char *string)
7084{
7085 return pmatch(preglob(pattern, 0, 0), string);
7086}
7087
7088/*
7089 * See if a pattern matches in a case statement.
7090 */
7091static int
7092casematch(union node *pattern, char *val)
7093{
7094 struct stackmark smark;
7095 int result;
7096
7097 setstackmark(&smark);
7098 argbackq = pattern->narg.backquote;
7099 STARTSTACKSTR(expdest);
7100 ifslastp = NULL;
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00007101 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE,
7102 /* var_str_list: */ NULL);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007103 STACKSTRNUL(expdest);
7104 result = patmatch(stackblock(), val);
7105 popstackmark(&smark);
7106 return result;
7107}
7108
7109
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007110/* ============ find_command */
7111
7112struct builtincmd {
7113 const char *name;
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007114 int (*builtin)(int, char **) FAST_FUNC;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007115 /* unsigned flags; */
7116};
7117#define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
Denis Vlasenkoe26b2782008-02-12 07:40:29 +00007118/* "regular" builtins always take precedence over commands,
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007119 * regardless of PATH=....%builtin... position */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007120#define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007121#define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007122
7123struct cmdentry {
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00007124 smallint cmdtype; /* CMDxxx */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007125 union param {
7126 int index;
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00007127 /* index >= 0 for commands without path (slashes) */
7128 /* (TODO: what exactly does the value mean? PATH position?) */
7129 /* index == -1 for commands with slashes */
7130 /* index == (-2 - applet_no) for NOFORK applets */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007131 const struct builtincmd *cmd;
7132 struct funcnode *func;
7133 } u;
7134};
7135/* values of cmdtype */
7136#define CMDUNKNOWN -1 /* no entry in table for command */
7137#define CMDNORMAL 0 /* command is an executable program */
7138#define CMDFUNCTION 1 /* command is a shell function */
7139#define CMDBUILTIN 2 /* command is a shell builtin */
7140
7141/* action to find_command() */
7142#define DO_ERR 0x01 /* prints errors */
7143#define DO_ABS 0x02 /* checks absolute paths */
7144#define DO_NOFUNC 0x04 /* don't return shell functions, for command */
7145#define DO_ALTPATH 0x08 /* using alternate path */
7146#define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
7147
7148static void find_command(char *, struct cmdentry *, int, const char *);
7149
7150
7151/* ============ Hashing commands */
7152
7153/*
7154 * When commands are first encountered, they are entered in a hash table.
7155 * This ensures that a full path search will not have to be done for them
7156 * on each invocation.
7157 *
7158 * We should investigate converting to a linear search, even though that
7159 * would make the command name "hash" a misnomer.
7160 */
7161
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007162struct tblentry {
7163 struct tblentry *next; /* next entry in hash chain */
7164 union param param; /* definition of builtin function */
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00007165 smallint cmdtype; /* CMDxxx */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007166 char rehash; /* if set, cd done since entry created */
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007167 char cmdname[1]; /* name of command */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007168};
7169
Denis Vlasenko01631112007-12-16 17:20:38 +00007170static struct tblentry **cmdtable;
7171#define INIT_G_cmdtable() do { \
7172 cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
7173} while (0)
7174
7175static int builtinloc = -1; /* index in path of %builtin, or -1 */
7176
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007177
7178static void
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00007179tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) char *cmd, char **argv, char **envp)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007180{
7181 int repeated = 0;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007182
Denis Vlasenko80d14be2007-04-10 23:03:30 +00007183#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007184 if (applet_no >= 0) {
Denis Vlasenkob7304742008-10-20 08:15:51 +00007185 if (APPLET_IS_NOEXEC(applet_no)) {
7186 while (*envp)
7187 putenv(*envp++);
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007188 run_applet_no_and_exit(applet_no, argv);
Denis Vlasenkob7304742008-10-20 08:15:51 +00007189 }
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007190 /* re-exec ourselves with the new arguments */
7191 execve(bb_busybox_exec_path, argv, envp);
7192 /* If they called chroot or otherwise made the binary no longer
7193 * executable, fall through */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007194 }
7195#endif
7196
7197 repeat:
7198#ifdef SYSV
7199 do {
7200 execve(cmd, argv, envp);
7201 } while (errno == EINTR);
7202#else
7203 execve(cmd, argv, envp);
7204#endif
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007205 if (repeated) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007206 free(argv);
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007207 return;
7208 }
7209 if (errno == ENOEXEC) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007210 char **ap;
7211 char **new;
7212
7213 for (ap = argv; *ap; ap++)
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007214 continue;
7215 ap = new = ckmalloc((ap - argv + 2) * sizeof(ap[0]));
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007216 ap[1] = cmd;
Denis Vlasenkoc44ab012007-04-09 03:11:58 +00007217 ap[0] = cmd = (char *)DEFAULT_SHELL;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007218 ap += 2;
7219 argv++;
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007220 while ((*ap++ = *argv++) != NULL)
Denis Vlasenko597906c2008-02-20 16:38:54 +00007221 continue;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007222 argv = new;
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007223 repeated++;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007224 goto repeat;
7225 }
7226}
7227
7228/*
7229 * Exec a program. Never returns. If you change this routine, you may
7230 * have to change the find_command routine as well.
7231 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00007232static void shellexec(char **, const char *, int) NORETURN;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007233static void
7234shellexec(char **argv, const char *path, int idx)
7235{
7236 char *cmdname;
7237 int e;
7238 char **envp;
7239 int exerrno;
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007240#if ENABLE_FEATURE_SH_STANDALONE
7241 int applet_no = -1;
7242#endif
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007243
Denis Vlasenko34c73c42008-08-16 11:48:02 +00007244 clearredir(/*drop:*/ 1);
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007245 envp = listvars(VEXPORT, VUNSET, 0);
7246 if (strchr(argv[0], '/') != NULL
Denis Vlasenko80d14be2007-04-10 23:03:30 +00007247#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007248 || (applet_no = find_applet_by_name(argv[0])) >= 0
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007249#endif
7250 ) {
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00007251 tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) argv[0], argv, envp);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007252 e = errno;
7253 } else {
7254 e = ENOENT;
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02007255 while ((cmdname = path_advance(&path, argv[0])) != NULL) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007256 if (--idx < 0 && pathopt == NULL) {
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00007257 tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007258 if (errno != ENOENT && errno != ENOTDIR)
7259 e = errno;
7260 }
7261 stunalloc(cmdname);
7262 }
7263 }
7264
7265 /* Map to POSIX errors */
7266 switch (e) {
7267 case EACCES:
7268 exerrno = 126;
7269 break;
7270 case ENOENT:
7271 exerrno = 127;
7272 break;
7273 default:
7274 exerrno = 2;
7275 break;
7276 }
7277 exitstatus = exerrno;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02007278 TRACE(("shellexec failed for %s, errno %d, suppress_int %d\n",
7279 argv[0], e, suppress_int));
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007280 ash_msg_and_raise(EXEXEC, "%s: %s", argv[0], errmsg(e, "not found"));
7281 /* NOTREACHED */
7282}
7283
7284static void
7285printentry(struct tblentry *cmdp)
7286{
7287 int idx;
7288 const char *path;
7289 char *name;
7290
7291 idx = cmdp->param.index;
7292 path = pathval();
7293 do {
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02007294 name = path_advance(&path, cmdp->cmdname);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007295 stunalloc(name);
7296 } while (--idx >= 0);
7297 out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
7298}
7299
7300/*
7301 * Clear out command entries. The argument specifies the first entry in
7302 * PATH which has changed.
7303 */
7304static void
7305clearcmdentry(int firstchange)
7306{
7307 struct tblentry **tblp;
7308 struct tblentry **pp;
7309 struct tblentry *cmdp;
7310
7311 INT_OFF;
7312 for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
7313 pp = tblp;
7314 while ((cmdp = *pp) != NULL) {
7315 if ((cmdp->cmdtype == CMDNORMAL &&
7316 cmdp->param.index >= firstchange)
7317 || (cmdp->cmdtype == CMDBUILTIN &&
7318 builtinloc >= firstchange)
7319 ) {
7320 *pp = cmdp->next;
7321 free(cmdp);
7322 } else {
7323 pp = &cmdp->next;
7324 }
7325 }
7326 }
7327 INT_ON;
7328}
7329
7330/*
7331 * Locate a command in the command hash table. If "add" is nonzero,
7332 * add the command to the table if it is not already present. The
7333 * variable "lastcmdentry" is set to point to the address of the link
7334 * pointing to the entry, so that delete_cmd_entry can delete the
7335 * entry.
7336 *
7337 * Interrupts must be off if called with add != 0.
7338 */
7339static struct tblentry **lastcmdentry;
7340
7341static struct tblentry *
7342cmdlookup(const char *name, int add)
7343{
7344 unsigned int hashval;
7345 const char *p;
7346 struct tblentry *cmdp;
7347 struct tblentry **pp;
7348
7349 p = name;
7350 hashval = (unsigned char)*p << 4;
7351 while (*p)
7352 hashval += (unsigned char)*p++;
7353 hashval &= 0x7FFF;
7354 pp = &cmdtable[hashval % CMDTABLESIZE];
7355 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7356 if (strcmp(cmdp->cmdname, name) == 0)
7357 break;
7358 pp = &cmdp->next;
7359 }
7360 if (add && cmdp == NULL) {
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007361 cmdp = *pp = ckzalloc(sizeof(struct tblentry)
7362 + strlen(name)
7363 /* + 1 - already done because
7364 * tblentry::cmdname is char[1] */);
Denis Vlasenko597906c2008-02-20 16:38:54 +00007365 /*cmdp->next = NULL; - ckzalloc did it */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007366 cmdp->cmdtype = CMDUNKNOWN;
7367 strcpy(cmdp->cmdname, name);
7368 }
7369 lastcmdentry = pp;
7370 return cmdp;
7371}
7372
7373/*
7374 * Delete the command entry returned on the last lookup.
7375 */
7376static void
7377delete_cmd_entry(void)
7378{
7379 struct tblentry *cmdp;
7380
7381 INT_OFF;
7382 cmdp = *lastcmdentry;
7383 *lastcmdentry = cmdp->next;
7384 if (cmdp->cmdtype == CMDFUNCTION)
7385 freefunc(cmdp->param.func);
7386 free(cmdp);
7387 INT_ON;
7388}
7389
7390/*
7391 * Add a new command entry, replacing any existing command entry for
7392 * the same name - except special builtins.
7393 */
7394static void
7395addcmdentry(char *name, struct cmdentry *entry)
7396{
7397 struct tblentry *cmdp;
7398
7399 cmdp = cmdlookup(name, 1);
7400 if (cmdp->cmdtype == CMDFUNCTION) {
7401 freefunc(cmdp->param.func);
7402 }
7403 cmdp->cmdtype = entry->cmdtype;
7404 cmdp->param = entry->u;
7405 cmdp->rehash = 0;
7406}
7407
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007408static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00007409hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007410{
7411 struct tblentry **pp;
7412 struct tblentry *cmdp;
7413 int c;
7414 struct cmdentry entry;
7415 char *name;
7416
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007417 if (nextopt("r") != '\0') {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007418 clearcmdentry(0);
7419 return 0;
7420 }
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007421
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007422 if (*argptr == NULL) {
7423 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7424 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7425 if (cmdp->cmdtype == CMDNORMAL)
7426 printentry(cmdp);
7427 }
7428 }
7429 return 0;
7430 }
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007431
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007432 c = 0;
7433 while ((name = *argptr) != NULL) {
7434 cmdp = cmdlookup(name, 0);
7435 if (cmdp != NULL
7436 && (cmdp->cmdtype == CMDNORMAL
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007437 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
7438 ) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007439 delete_cmd_entry();
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007440 }
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007441 find_command(name, &entry, DO_ERR, pathval());
7442 if (entry.cmdtype == CMDUNKNOWN)
7443 c = 1;
7444 argptr++;
7445 }
7446 return c;
7447}
7448
7449/*
7450 * Called when a cd is done. Marks all commands so the next time they
7451 * are executed they will be rehashed.
7452 */
7453static void
7454hashcd(void)
7455{
7456 struct tblentry **pp;
7457 struct tblentry *cmdp;
7458
7459 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7460 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007461 if (cmdp->cmdtype == CMDNORMAL
7462 || (cmdp->cmdtype == CMDBUILTIN
7463 && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
7464 && builtinloc > 0)
7465 ) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007466 cmdp->rehash = 1;
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007467 }
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007468 }
7469 }
7470}
7471
7472/*
7473 * Fix command hash table when PATH changed.
7474 * Called before PATH is changed. The argument is the new value of PATH;
7475 * pathval() still returns the old value at this point.
7476 * Called with interrupts off.
7477 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007478static void FAST_FUNC
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007479changepath(const char *new)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007480{
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007481 const char *old;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007482 int firstchange;
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007483 int idx;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007484 int idx_bltin;
7485
7486 old = pathval();
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007487 firstchange = 9999; /* assume no change */
7488 idx = 0;
7489 idx_bltin = -1;
7490 for (;;) {
7491 if (*old != *new) {
7492 firstchange = idx;
7493 if ((*old == '\0' && *new == ':')
7494 || (*old == ':' && *new == '\0'))
7495 firstchange++;
7496 old = new; /* ignore subsequent differences */
7497 }
7498 if (*new == '\0')
7499 break;
7500 if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
7501 idx_bltin = idx;
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007502 if (*new == ':')
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007503 idx++;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007504 new++, old++;
7505 }
7506 if (builtinloc < 0 && idx_bltin >= 0)
7507 builtinloc = idx_bltin; /* zap builtins */
7508 if (builtinloc >= 0 && idx_bltin < 0)
7509 firstchange = 0;
7510 clearcmdentry(firstchange);
7511 builtinloc = idx_bltin;
7512}
7513
7514#define TEOF 0
7515#define TNL 1
7516#define TREDIR 2
7517#define TWORD 3
7518#define TSEMI 4
7519#define TBACKGND 5
7520#define TAND 6
7521#define TOR 7
7522#define TPIPE 8
7523#define TLP 9
7524#define TRP 10
7525#define TENDCASE 11
7526#define TENDBQUOTE 12
7527#define TNOT 13
7528#define TCASE 14
7529#define TDO 15
7530#define TDONE 16
7531#define TELIF 17
7532#define TELSE 18
7533#define TESAC 19
7534#define TFI 20
7535#define TFOR 21
7536#define TIF 22
7537#define TIN 23
7538#define TTHEN 24
7539#define TUNTIL 25
7540#define TWHILE 26
7541#define TBEGIN 27
7542#define TEND 28
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007543typedef smallint token_id_t;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007544
7545/* first char is indicating which tokens mark the end of a list */
7546static const char *const tokname_array[] = {
7547 "\1end of file",
7548 "\0newline",
7549 "\0redirection",
7550 "\0word",
7551 "\0;",
7552 "\0&",
7553 "\0&&",
7554 "\0||",
7555 "\0|",
7556 "\0(",
7557 "\1)",
7558 "\1;;",
7559 "\1`",
7560#define KWDOFFSET 13
7561 /* the following are keywords */
7562 "\0!",
7563 "\0case",
7564 "\1do",
7565 "\1done",
7566 "\1elif",
7567 "\1else",
7568 "\1esac",
7569 "\1fi",
7570 "\0for",
7571 "\0if",
7572 "\0in",
7573 "\1then",
7574 "\0until",
7575 "\0while",
7576 "\0{",
7577 "\1}",
7578};
7579
7580static const char *
7581tokname(int tok)
7582{
7583 static char buf[16];
7584
Denis Vlasenko240a1cf2007-04-08 16:07:02 +00007585//try this:
7586//if (tok < TSEMI) return tokname_array[tok] + 1;
7587//sprintf(buf, "\"%s\"", tokname_array[tok] + 1);
7588//return buf;
7589
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007590 if (tok >= TSEMI)
7591 buf[0] = '"';
7592 sprintf(buf + (tok >= TSEMI), "%s%c",
7593 tokname_array[tok] + 1, (tok >= TSEMI ? '"' : 0));
7594 return buf;
7595}
7596
7597/* Wrapper around strcmp for qsort/bsearch/... */
7598static int
7599pstrcmp(const void *a, const void *b)
7600{
Denis Vlasenko240a1cf2007-04-08 16:07:02 +00007601 return strcmp((char*) a, (*(char**) b) + 1);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007602}
7603
7604static const char *const *
7605findkwd(const char *s)
7606{
7607 return bsearch(s, tokname_array + KWDOFFSET,
Denis Vlasenko80b8b392007-06-25 10:55:35 +00007608 ARRAY_SIZE(tokname_array) - KWDOFFSET,
7609 sizeof(tokname_array[0]), pstrcmp);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007610}
7611
7612/*
7613 * Locate and print what a word is...
7614 */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007615static int
7616describe_command(char *command, int describe_command_verbose)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007617{
7618 struct cmdentry entry;
7619 struct tblentry *cmdp;
7620#if ENABLE_ASH_ALIAS
7621 const struct alias *ap;
7622#endif
7623 const char *path = pathval();
7624
7625 if (describe_command_verbose) {
7626 out1str(command);
7627 }
7628
7629 /* First look at the keywords */
7630 if (findkwd(command)) {
7631 out1str(describe_command_verbose ? " is a shell keyword" : command);
7632 goto out;
7633 }
7634
7635#if ENABLE_ASH_ALIAS
7636 /* Then look at the aliases */
7637 ap = lookupalias(command, 0);
7638 if (ap != NULL) {
Denis Vlasenko46846e22007-05-20 13:08:31 +00007639 if (!describe_command_verbose) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007640 out1str("alias ");
7641 printalias(ap);
7642 return 0;
7643 }
Denis Vlasenko46846e22007-05-20 13:08:31 +00007644 out1fmt(" is an alias for %s", ap->val);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007645 goto out;
7646 }
7647#endif
7648 /* Then check if it is a tracked alias */
7649 cmdp = cmdlookup(command, 0);
7650 if (cmdp != NULL) {
7651 entry.cmdtype = cmdp->cmdtype;
7652 entry.u = cmdp->param;
7653 } else {
7654 /* Finally use brute force */
7655 find_command(command, &entry, DO_ABS, path);
7656 }
7657
7658 switch (entry.cmdtype) {
7659 case CMDNORMAL: {
7660 int j = entry.u.index;
7661 char *p;
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00007662 if (j < 0) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007663 p = command;
7664 } else {
7665 do {
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02007666 p = path_advance(&path, command);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007667 stunalloc(p);
7668 } while (--j >= 0);
7669 }
7670 if (describe_command_verbose) {
7671 out1fmt(" is%s %s",
7672 (cmdp ? " a tracked alias for" : nullstr), p
7673 );
7674 } else {
7675 out1str(p);
7676 }
7677 break;
7678 }
7679
7680 case CMDFUNCTION:
7681 if (describe_command_verbose) {
7682 out1str(" is a shell function");
7683 } else {
7684 out1str(command);
7685 }
7686 break;
7687
7688 case CMDBUILTIN:
7689 if (describe_command_verbose) {
7690 out1fmt(" is a %sshell builtin",
7691 IS_BUILTIN_SPECIAL(entry.u.cmd) ?
7692 "special " : nullstr
7693 );
7694 } else {
7695 out1str(command);
7696 }
7697 break;
7698
7699 default:
7700 if (describe_command_verbose) {
7701 out1str(": not found\n");
7702 }
7703 return 127;
7704 }
7705 out:
Denys Vlasenko285ad152009-12-04 23:02:27 +01007706 out1str("\n");
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007707 return 0;
7708}
7709
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007710static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00007711typecmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007712{
Denis Vlasenko46846e22007-05-20 13:08:31 +00007713 int i = 1;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007714 int err = 0;
Denis Vlasenko46846e22007-05-20 13:08:31 +00007715 int verbose = 1;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007716
Denis Vlasenko46846e22007-05-20 13:08:31 +00007717 /* type -p ... ? (we don't bother checking for 'p') */
Denis Vlasenko1fc62382007-06-25 22:55:34 +00007718 if (argv[1] && argv[1][0] == '-') {
Denis Vlasenko46846e22007-05-20 13:08:31 +00007719 i++;
7720 verbose = 0;
7721 }
Denis Vlasenko68404f12008-03-17 09:00:54 +00007722 while (argv[i]) {
Denis Vlasenko46846e22007-05-20 13:08:31 +00007723 err |= describe_command(argv[i++], verbose);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007724 }
7725 return err;
7726}
7727
7728#if ENABLE_ASH_CMDCMD
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007729static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00007730commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007731{
7732 int c;
7733 enum {
7734 VERIFY_BRIEF = 1,
7735 VERIFY_VERBOSE = 2,
7736 } verify = 0;
7737
7738 while ((c = nextopt("pvV")) != '\0')
7739 if (c == 'V')
7740 verify |= VERIFY_VERBOSE;
7741 else if (c == 'v')
7742 verify |= VERIFY_BRIEF;
7743#if DEBUG
7744 else if (c != 'p')
7745 abort();
7746#endif
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00007747 /* Mimic bash: just "command -v" doesn't complain, it's a nop */
7748 if (verify && (*argptr != NULL)) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007749 return describe_command(*argptr, verify - VERIFY_BRIEF);
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00007750 }
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007751
7752 return 0;
7753}
7754#endif
7755
7756
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007757/* ============ eval.c */
Eric Andersencb57d552001-06-28 07:25:16 +00007758
Denis Vlasenko340299a2008-11-21 10:36:36 +00007759static int funcblocksize; /* size of structures in function */
7760static int funcstringsize; /* size of strings in node */
7761static void *funcblock; /* block to allocate function from */
7762static char *funcstring; /* block to allocate strings from */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007763
Eric Andersencb57d552001-06-28 07:25:16 +00007764/* flags in argument to evaltree */
Denis Vlasenko340299a2008-11-21 10:36:36 +00007765#define EV_EXIT 01 /* exit after evaluating tree */
7766#define EV_TESTED 02 /* exit status is checked; ignore -e flag */
Eric Andersenc470f442003-07-28 09:56:35 +00007767#define EV_BACKCMD 04 /* command executing within back quotes */
Eric Andersencb57d552001-06-28 07:25:16 +00007768
Denys Vlasenko0e5e4ea2009-10-11 00:36:20 +02007769static const uint8_t nodesize[N_NUMBER] = {
Denis Vlasenko340299a2008-11-21 10:36:36 +00007770 [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
7771 [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
7772 [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
7773 [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
7774 [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
7775 [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
7776 [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
7777 [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
7778 [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
7779 [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
7780 [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
7781 [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
7782 [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
7783 [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
7784 [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
7785 [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
7786 [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
Denis Vlasenkocc5feab2008-11-22 01:32:40 +00007787#if ENABLE_ASH_BASH_COMPAT
Denis Vlasenko340299a2008-11-21 10:36:36 +00007788 [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
Denis Vlasenkocc5feab2008-11-22 01:32:40 +00007789#endif
Denis Vlasenko340299a2008-11-21 10:36:36 +00007790 [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
7791 [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
7792 [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
7793 [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
7794 [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
7795 [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
7796 [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
7797 [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
7798 [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007799};
7800
7801static void calcsize(union node *n);
7802
7803static void
7804sizenodelist(struct nodelist *lp)
7805{
7806 while (lp) {
7807 funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
7808 calcsize(lp->n);
7809 lp = lp->next;
7810 }
7811}
7812
7813static void
7814calcsize(union node *n)
7815{
7816 if (n == NULL)
7817 return;
7818 funcblocksize += nodesize[n->type];
7819 switch (n->type) {
7820 case NCMD:
7821 calcsize(n->ncmd.redirect);
7822 calcsize(n->ncmd.args);
7823 calcsize(n->ncmd.assign);
7824 break;
7825 case NPIPE:
7826 sizenodelist(n->npipe.cmdlist);
7827 break;
7828 case NREDIR:
7829 case NBACKGND:
7830 case NSUBSHELL:
7831 calcsize(n->nredir.redirect);
7832 calcsize(n->nredir.n);
7833 break;
7834 case NAND:
7835 case NOR:
7836 case NSEMI:
7837 case NWHILE:
7838 case NUNTIL:
7839 calcsize(n->nbinary.ch2);
7840 calcsize(n->nbinary.ch1);
7841 break;
7842 case NIF:
7843 calcsize(n->nif.elsepart);
7844 calcsize(n->nif.ifpart);
7845 calcsize(n->nif.test);
7846 break;
7847 case NFOR:
7848 funcstringsize += strlen(n->nfor.var) + 1;
7849 calcsize(n->nfor.body);
7850 calcsize(n->nfor.args);
7851 break;
7852 case NCASE:
7853 calcsize(n->ncase.cases);
7854 calcsize(n->ncase.expr);
7855 break;
7856 case NCLIST:
7857 calcsize(n->nclist.body);
7858 calcsize(n->nclist.pattern);
7859 calcsize(n->nclist.next);
7860 break;
7861 case NDEFUN:
7862 case NARG:
7863 sizenodelist(n->narg.backquote);
7864 funcstringsize += strlen(n->narg.text) + 1;
7865 calcsize(n->narg.next);
7866 break;
7867 case NTO:
Denis Vlasenko559691a2008-10-05 18:39:31 +00007868#if ENABLE_ASH_BASH_COMPAT
7869 case NTO2:
7870#endif
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007871 case NCLOBBER:
7872 case NFROM:
7873 case NFROMTO:
7874 case NAPPEND:
7875 calcsize(n->nfile.fname);
7876 calcsize(n->nfile.next);
7877 break;
7878 case NTOFD:
7879 case NFROMFD:
7880 calcsize(n->ndup.vname);
7881 calcsize(n->ndup.next);
7882 break;
7883 case NHERE:
7884 case NXHERE:
7885 calcsize(n->nhere.doc);
7886 calcsize(n->nhere.next);
7887 break;
7888 case NNOT:
7889 calcsize(n->nnot.com);
7890 break;
7891 };
7892}
7893
7894static char *
7895nodeckstrdup(char *s)
7896{
7897 char *rtn = funcstring;
7898
7899 strcpy(funcstring, s);
7900 funcstring += strlen(s) + 1;
7901 return rtn;
7902}
7903
7904static union node *copynode(union node *);
7905
7906static struct nodelist *
7907copynodelist(struct nodelist *lp)
7908{
7909 struct nodelist *start;
7910 struct nodelist **lpp;
7911
7912 lpp = &start;
7913 while (lp) {
7914 *lpp = funcblock;
7915 funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
7916 (*lpp)->n = copynode(lp->n);
7917 lp = lp->next;
7918 lpp = &(*lpp)->next;
7919 }
7920 *lpp = NULL;
7921 return start;
7922}
7923
7924static union node *
7925copynode(union node *n)
7926{
7927 union node *new;
7928
7929 if (n == NULL)
7930 return NULL;
7931 new = funcblock;
7932 funcblock = (char *) funcblock + nodesize[n->type];
7933
7934 switch (n->type) {
7935 case NCMD:
7936 new->ncmd.redirect = copynode(n->ncmd.redirect);
7937 new->ncmd.args = copynode(n->ncmd.args);
7938 new->ncmd.assign = copynode(n->ncmd.assign);
7939 break;
7940 case NPIPE:
7941 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00007942 new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007943 break;
7944 case NREDIR:
7945 case NBACKGND:
7946 case NSUBSHELL:
7947 new->nredir.redirect = copynode(n->nredir.redirect);
7948 new->nredir.n = copynode(n->nredir.n);
7949 break;
7950 case NAND:
7951 case NOR:
7952 case NSEMI:
7953 case NWHILE:
7954 case NUNTIL:
7955 new->nbinary.ch2 = copynode(n->nbinary.ch2);
7956 new->nbinary.ch1 = copynode(n->nbinary.ch1);
7957 break;
7958 case NIF:
7959 new->nif.elsepart = copynode(n->nif.elsepart);
7960 new->nif.ifpart = copynode(n->nif.ifpart);
7961 new->nif.test = copynode(n->nif.test);
7962 break;
7963 case NFOR:
7964 new->nfor.var = nodeckstrdup(n->nfor.var);
7965 new->nfor.body = copynode(n->nfor.body);
7966 new->nfor.args = copynode(n->nfor.args);
7967 break;
7968 case NCASE:
7969 new->ncase.cases = copynode(n->ncase.cases);
7970 new->ncase.expr = copynode(n->ncase.expr);
7971 break;
7972 case NCLIST:
7973 new->nclist.body = copynode(n->nclist.body);
7974 new->nclist.pattern = copynode(n->nclist.pattern);
7975 new->nclist.next = copynode(n->nclist.next);
7976 break;
7977 case NDEFUN:
7978 case NARG:
7979 new->narg.backquote = copynodelist(n->narg.backquote);
7980 new->narg.text = nodeckstrdup(n->narg.text);
7981 new->narg.next = copynode(n->narg.next);
7982 break;
7983 case NTO:
Denis Vlasenko559691a2008-10-05 18:39:31 +00007984#if ENABLE_ASH_BASH_COMPAT
7985 case NTO2:
7986#endif
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007987 case NCLOBBER:
7988 case NFROM:
7989 case NFROMTO:
7990 case NAPPEND:
7991 new->nfile.fname = copynode(n->nfile.fname);
7992 new->nfile.fd = n->nfile.fd;
7993 new->nfile.next = copynode(n->nfile.next);
7994 break;
7995 case NTOFD:
7996 case NFROMFD:
7997 new->ndup.vname = copynode(n->ndup.vname);
7998 new->ndup.dupfd = n->ndup.dupfd;
7999 new->ndup.fd = n->ndup.fd;
8000 new->ndup.next = copynode(n->ndup.next);
8001 break;
8002 case NHERE:
8003 case NXHERE:
8004 new->nhere.doc = copynode(n->nhere.doc);
8005 new->nhere.fd = n->nhere.fd;
8006 new->nhere.next = copynode(n->nhere.next);
8007 break;
8008 case NNOT:
8009 new->nnot.com = copynode(n->nnot.com);
8010 break;
8011 };
8012 new->type = n->type;
8013 return new;
8014}
8015
8016/*
8017 * Make a copy of a parse tree.
8018 */
8019static struct funcnode *
8020copyfunc(union node *n)
8021{
8022 struct funcnode *f;
8023 size_t blocksize;
8024
8025 funcblocksize = offsetof(struct funcnode, n);
8026 funcstringsize = 0;
8027 calcsize(n);
8028 blocksize = funcblocksize;
8029 f = ckmalloc(blocksize + funcstringsize);
8030 funcblock = (char *) f + offsetof(struct funcnode, n);
8031 funcstring = (char *) f + blocksize;
8032 copynode(n);
8033 f->count = 0;
8034 return f;
8035}
8036
8037/*
8038 * Define a shell function.
8039 */
8040static void
8041defun(char *name, union node *func)
8042{
8043 struct cmdentry entry;
8044
8045 INT_OFF;
8046 entry.cmdtype = CMDFUNCTION;
8047 entry.u.func = copyfunc(func);
8048 addcmdentry(name, &entry);
8049 INT_ON;
8050}
8051
Denis Vlasenko4b875702009-03-19 13:30:04 +00008052/* Reasons for skipping commands (see comment on breakcmd routine) */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008053#define SKIPBREAK (1 << 0)
8054#define SKIPCONT (1 << 1)
8055#define SKIPFUNC (1 << 2)
8056#define SKIPFILE (1 << 3)
8057#define SKIPEVAL (1 << 4)
Denis Vlasenko4b875702009-03-19 13:30:04 +00008058static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008059static int skipcount; /* number of levels to skip */
8060static int funcnest; /* depth of function calls */
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +00008061static int loopnest; /* current loop nesting level */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008062
Denis Vlasenko4b875702009-03-19 13:30:04 +00008063/* Forward decl way out to parsing code - dotrap needs it */
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008064static int evalstring(char *s, int mask);
8065
Denis Vlasenko4b875702009-03-19 13:30:04 +00008066/* Called to execute a trap.
8067 * Single callsite - at the end of evaltree().
8068 * If we return non-zero, exaltree raises EXEXIT exception.
8069 *
8070 * Perhaps we should avoid entering new trap handlers
8071 * while we are executing a trap handler. [is it a TODO?]
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008072 */
8073static int
8074dotrap(void)
8075{
Denis Vlasenko4b875702009-03-19 13:30:04 +00008076 uint8_t *g;
8077 int sig;
8078 uint8_t savestatus;
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008079
8080 savestatus = exitstatus;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02008081 pending_sig = 0;
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008082 xbarrier();
8083
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008084 TRACE(("dotrap entered\n"));
Denis Vlasenko4b875702009-03-19 13:30:04 +00008085 for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
8086 int want_exexit;
8087 char *t;
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008088
Denis Vlasenko4b875702009-03-19 13:30:04 +00008089 if (*g == 0)
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008090 continue;
Denis Vlasenko4b875702009-03-19 13:30:04 +00008091 t = trap[sig];
8092 /* non-trapped SIGINT is handled separately by raise_interrupt,
8093 * don't upset it by resetting gotsig[SIGINT-1] */
8094 if (sig == SIGINT && !t)
8095 continue;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008096
8097 TRACE(("sig %d is active, will run handler '%s'\n", sig, t));
Denis Vlasenko4b875702009-03-19 13:30:04 +00008098 *g = 0;
8099 if (!t)
8100 continue;
8101 want_exexit = evalstring(t, SKIPEVAL);
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008102 exitstatus = savestatus;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008103 if (want_exexit) {
Denis Vlasenkob21f3792009-03-19 23:09:58 +00008104 TRACE(("dotrap returns %d\n", want_exexit));
Denis Vlasenko4b875702009-03-19 13:30:04 +00008105 return want_exexit;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008106 }
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008107 }
8108
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008109 TRACE(("dotrap returns 0\n"));
Denis Vlasenko991a1da2008-02-10 19:02:53 +00008110 return 0;
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008111}
8112
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00008113/* forward declarations - evaluation is fairly recursive business... */
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008114static void evalloop(union node *, int);
8115static void evalfor(union node *, int);
8116static void evalcase(union node *, int);
8117static void evalsubshell(union node *, int);
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00008118static void expredir(union node *);
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008119static void evalpipe(union node *, int);
8120static void evalcommand(union node *, int);
Eric Andersenc470f442003-07-28 09:56:35 +00008121static int evalbltin(const struct builtincmd *, int, char **);
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008122static void prehash(union node *);
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00008123
Eric Andersen62483552001-07-10 06:09:16 +00008124/*
Eric Andersenc470f442003-07-28 09:56:35 +00008125 * Evaluate a parse tree. The value is left in the global variable
8126 * exitstatus.
Eric Andersen62483552001-07-10 06:09:16 +00008127 */
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008128static void
Eric Andersenc470f442003-07-28 09:56:35 +00008129evaltree(union node *n, int flags)
Eric Andersen62483552001-07-10 06:09:16 +00008130{
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008131 struct jmploc *volatile savehandler = exception_handler;
8132 struct jmploc jmploc;
Eric Andersenc470f442003-07-28 09:56:35 +00008133 int checkexit = 0;
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008134 void (*evalfn)(union node *, int);
Eric Andersenc470f442003-07-28 09:56:35 +00008135 int status;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008136 int int_level;
8137
8138 SAVE_INT(int_level);
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008139
Eric Andersenc470f442003-07-28 09:56:35 +00008140 if (n == NULL) {
8141 TRACE(("evaltree(NULL) called\n"));
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008142 goto out1;
Eric Andersen62483552001-07-10 06:09:16 +00008143 }
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008144 TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008145
8146 exception_handler = &jmploc;
8147 {
8148 int err = setjmp(jmploc.loc);
8149 if (err) {
8150 /* if it was a signal, check for trap handlers */
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008151 if (exception_type == EXSIG) {
Denis Vlasenkob21f3792009-03-19 23:09:58 +00008152 TRACE(("exception %d (EXSIG) in evaltree, err=%d\n",
8153 exception_type, err));
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008154 goto out;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008155 }
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008156 /* continue on the way out */
Denis Vlasenkob21f3792009-03-19 23:09:58 +00008157 TRACE(("exception %d in evaltree, propagating err=%d\n",
8158 exception_type, err));
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008159 exception_handler = savehandler;
8160 longjmp(exception_handler->loc, err);
8161 }
8162 }
8163
Eric Andersenc470f442003-07-28 09:56:35 +00008164 switch (n->type) {
8165 default:
Denis Vlasenkoa7189f02006-11-17 20:29:00 +00008166#if DEBUG
Eric Andersenc470f442003-07-28 09:56:35 +00008167 out1fmt("Node type = %d\n", n->type);
Denys Vlasenko8131eea2009-11-02 14:19:51 +01008168 fflush_all();
Eric Andersenc470f442003-07-28 09:56:35 +00008169 break;
8170#endif
8171 case NNOT:
8172 evaltree(n->nnot.com, EV_TESTED);
8173 status = !exitstatus;
8174 goto setstatus;
8175 case NREDIR:
8176 expredir(n->nredir.redirect);
8177 status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
8178 if (!status) {
8179 evaltree(n->nredir.n, flags & EV_TESTED);
8180 status = exitstatus;
8181 }
Denis Vlasenko34c73c42008-08-16 11:48:02 +00008182 popredir(/*drop:*/ 0, /*restore:*/ 0 /* not sure */);
Eric Andersenc470f442003-07-28 09:56:35 +00008183 goto setstatus;
8184 case NCMD:
8185 evalfn = evalcommand;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008186 checkexit:
Eric Andersenc470f442003-07-28 09:56:35 +00008187 if (eflag && !(flags & EV_TESTED))
8188 checkexit = ~0;
8189 goto calleval;
8190 case NFOR:
8191 evalfn = evalfor;
8192 goto calleval;
8193 case NWHILE:
8194 case NUNTIL:
8195 evalfn = evalloop;
8196 goto calleval;
8197 case NSUBSHELL:
8198 case NBACKGND:
8199 evalfn = evalsubshell;
8200 goto calleval;
8201 case NPIPE:
8202 evalfn = evalpipe;
8203 goto checkexit;
8204 case NCASE:
8205 evalfn = evalcase;
8206 goto calleval;
8207 case NAND:
8208 case NOR:
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008209 case NSEMI: {
8210
Eric Andersenc470f442003-07-28 09:56:35 +00008211#if NAND + 1 != NOR
8212#error NAND + 1 != NOR
8213#endif
8214#if NOR + 1 != NSEMI
8215#error NOR + 1 != NSEMI
8216#endif
Denis Vlasenko87d5fd92008-07-26 13:48:35 +00008217 unsigned is_or = n->type - NAND;
Eric Andersenc470f442003-07-28 09:56:35 +00008218 evaltree(
8219 n->nbinary.ch1,
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008220 (flags | ((is_or >> 1) - 1)) & EV_TESTED
Eric Andersenc470f442003-07-28 09:56:35 +00008221 );
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008222 if (!exitstatus == is_or)
Eric Andersenc470f442003-07-28 09:56:35 +00008223 break;
8224 if (!evalskip) {
8225 n = n->nbinary.ch2;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008226 evaln:
Eric Andersenc470f442003-07-28 09:56:35 +00008227 evalfn = evaltree;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008228 calleval:
Eric Andersenc470f442003-07-28 09:56:35 +00008229 evalfn(n, flags);
8230 break;
8231 }
8232 break;
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008233 }
Eric Andersenc470f442003-07-28 09:56:35 +00008234 case NIF:
8235 evaltree(n->nif.test, EV_TESTED);
8236 if (evalskip)
8237 break;
8238 if (exitstatus == 0) {
8239 n = n->nif.ifpart;
8240 goto evaln;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008241 }
8242 if (n->nif.elsepart) {
Eric Andersenc470f442003-07-28 09:56:35 +00008243 n = n->nif.elsepart;
8244 goto evaln;
8245 }
8246 goto success;
8247 case NDEFUN:
8248 defun(n->narg.text, n->narg.next);
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008249 success:
Eric Andersenc470f442003-07-28 09:56:35 +00008250 status = 0;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008251 setstatus:
Eric Andersenc470f442003-07-28 09:56:35 +00008252 exitstatus = status;
8253 break;
8254 }
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008255
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008256 out:
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008257 exception_handler = savehandler;
8258 out1:
8259 if (checkexit & exitstatus)
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00008260 evalskip |= SKIPEVAL;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02008261 else if (pending_sig && dotrap())
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00008262 goto exexit;
8263
8264 if (flags & EV_EXIT) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008265 exexit:
Denis Vlasenkob012b102007-02-19 22:43:01 +00008266 raise_exception(EXEXIT);
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00008267 }
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008268
8269 RESTORE_INT(int_level);
8270 TRACE(("leaving evaltree (no interrupts)\n"));
Eric Andersen62483552001-07-10 06:09:16 +00008271}
8272
Eric Andersenc470f442003-07-28 09:56:35 +00008273#if !defined(__alpha__) || (defined(__GNUC__) && __GNUC__ >= 3)
8274static
8275#endif
8276void evaltreenr(union node *, int) __attribute__ ((alias("evaltree"),__noreturn__));
8277
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008278static void
Eric Andersenc470f442003-07-28 09:56:35 +00008279evalloop(union node *n, int flags)
Eric Andersencb57d552001-06-28 07:25:16 +00008280{
8281 int status;
8282
8283 loopnest++;
8284 status = 0;
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008285 flags &= EV_TESTED;
Eric Andersencb57d552001-06-28 07:25:16 +00008286 for (;;) {
Eric Andersenc470f442003-07-28 09:56:35 +00008287 int i;
8288
Eric Andersencb57d552001-06-28 07:25:16 +00008289 evaltree(n->nbinary.ch1, EV_TESTED);
8290 if (evalskip) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008291 skipping:
8292 if (evalskip == SKIPCONT && --skipcount <= 0) {
Eric Andersencb57d552001-06-28 07:25:16 +00008293 evalskip = 0;
8294 continue;
8295 }
8296 if (evalskip == SKIPBREAK && --skipcount <= 0)
8297 evalskip = 0;
8298 break;
8299 }
Eric Andersenc470f442003-07-28 09:56:35 +00008300 i = exitstatus;
8301 if (n->type != NWHILE)
8302 i = !i;
8303 if (i != 0)
8304 break;
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008305 evaltree(n->nbinary.ch2, flags);
Eric Andersencb57d552001-06-28 07:25:16 +00008306 status = exitstatus;
8307 if (evalskip)
8308 goto skipping;
8309 }
8310 loopnest--;
8311 exitstatus = status;
8312}
8313
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008314static void
Eric Andersenc470f442003-07-28 09:56:35 +00008315evalfor(union node *n, int flags)
Eric Andersencb57d552001-06-28 07:25:16 +00008316{
8317 struct arglist arglist;
8318 union node *argp;
8319 struct strlist *sp;
8320 struct stackmark smark;
8321
8322 setstackmark(&smark);
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00008323 arglist.list = NULL;
Eric Andersencb57d552001-06-28 07:25:16 +00008324 arglist.lastp = &arglist.list;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008325 for (argp = n->nfor.args; argp; argp = argp->narg.next) {
Eric Andersencb57d552001-06-28 07:25:16 +00008326 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE | EXP_RECORD);
Eric Andersenc470f442003-07-28 09:56:35 +00008327 /* XXX */
Eric Andersencb57d552001-06-28 07:25:16 +00008328 if (evalskip)
8329 goto out;
8330 }
8331 *arglist.lastp = NULL;
8332
8333 exitstatus = 0;
8334 loopnest++;
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008335 flags &= EV_TESTED;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008336 for (sp = arglist.list; sp; sp = sp->next) {
Eric Andersencb57d552001-06-28 07:25:16 +00008337 setvar(n->nfor.var, sp->text, 0);
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008338 evaltree(n->nfor.body, flags);
Eric Andersencb57d552001-06-28 07:25:16 +00008339 if (evalskip) {
8340 if (evalskip == SKIPCONT && --skipcount <= 0) {
8341 evalskip = 0;
8342 continue;
8343 }
8344 if (evalskip == SKIPBREAK && --skipcount <= 0)
8345 evalskip = 0;
8346 break;
8347 }
8348 }
8349 loopnest--;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008350 out:
Eric Andersencb57d552001-06-28 07:25:16 +00008351 popstackmark(&smark);
8352}
8353
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008354static void
Eric Andersenc470f442003-07-28 09:56:35 +00008355evalcase(union node *n, int flags)
Eric Andersencb57d552001-06-28 07:25:16 +00008356{
8357 union node *cp;
8358 union node *patp;
8359 struct arglist arglist;
8360 struct stackmark smark;
8361
8362 setstackmark(&smark);
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00008363 arglist.list = NULL;
Eric Andersencb57d552001-06-28 07:25:16 +00008364 arglist.lastp = &arglist.list;
Eric Andersencb57d552001-06-28 07:25:16 +00008365 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
Eric Andersenc470f442003-07-28 09:56:35 +00008366 exitstatus = 0;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008367 for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
8368 for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
Eric Andersencb57d552001-06-28 07:25:16 +00008369 if (casematch(patp, arglist.list->text)) {
8370 if (evalskip == 0) {
8371 evaltree(cp->nclist.body, flags);
8372 }
8373 goto out;
8374 }
8375 }
8376 }
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008377 out:
Eric Andersencb57d552001-06-28 07:25:16 +00008378 popstackmark(&smark);
8379}
8380
Eric Andersenc470f442003-07-28 09:56:35 +00008381/*
8382 * Kick off a subshell to evaluate a tree.
8383 */
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008384static void
Eric Andersenc470f442003-07-28 09:56:35 +00008385evalsubshell(union node *n, int flags)
8386{
8387 struct job *jp;
8388 int backgnd = (n->type == NBACKGND);
8389 int status;
8390
8391 expredir(n->nredir.redirect);
8392 if (!backgnd && flags & EV_EXIT && !trap[0])
8393 goto nofork;
Denis Vlasenkob012b102007-02-19 22:43:01 +00008394 INT_OFF;
Denis Vlasenko68404f12008-03-17 09:00:54 +00008395 jp = makejob(/*n,*/ 1);
Eric Andersenc470f442003-07-28 09:56:35 +00008396 if (forkshell(jp, n, backgnd) == 0) {
Denis Vlasenkob012b102007-02-19 22:43:01 +00008397 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00008398 flags |= EV_EXIT;
8399 if (backgnd)
8400 flags &=~ EV_TESTED;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00008401 nofork:
Eric Andersenc470f442003-07-28 09:56:35 +00008402 redirect(n->nredir.redirect, 0);
8403 evaltreenr(n->nredir.n, flags);
8404 /* never returns */
8405 }
8406 status = 0;
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00008407 if (!backgnd)
Eric Andersenc470f442003-07-28 09:56:35 +00008408 status = waitforjob(jp);
8409 exitstatus = status;
Denis Vlasenkob012b102007-02-19 22:43:01 +00008410 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00008411}
8412
Eric Andersenc470f442003-07-28 09:56:35 +00008413/*
8414 * Compute the names of the files in a redirection list.
8415 */
Denis Vlasenko99eb8502007-02-23 21:09:49 +00008416static void fixredir(union node *, const char *, int);
Eric Andersenc470f442003-07-28 09:56:35 +00008417static void
8418expredir(union node *n)
8419{
8420 union node *redir;
8421
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008422 for (redir = n; redir; redir = redir->nfile.next) {
Eric Andersenc470f442003-07-28 09:56:35 +00008423 struct arglist fn;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008424
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00008425 fn.list = NULL;
Eric Andersenc470f442003-07-28 09:56:35 +00008426 fn.lastp = &fn.list;
8427 switch (redir->type) {
8428 case NFROMTO:
8429 case NFROM:
8430 case NTO:
Denis Vlasenko559691a2008-10-05 18:39:31 +00008431#if ENABLE_ASH_BASH_COMPAT
8432 case NTO2:
8433#endif
Eric Andersenc470f442003-07-28 09:56:35 +00008434 case NCLOBBER:
8435 case NAPPEND:
8436 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
Denis Vlasenko559691a2008-10-05 18:39:31 +00008437#if ENABLE_ASH_BASH_COMPAT
8438 store_expfname:
8439#endif
Eric Andersenc470f442003-07-28 09:56:35 +00008440 redir->nfile.expfname = fn.list->text;
8441 break;
8442 case NFROMFD:
Denis Vlasenko559691a2008-10-05 18:39:31 +00008443 case NTOFD: /* >& */
Eric Andersenc470f442003-07-28 09:56:35 +00008444 if (redir->ndup.vname) {
8445 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008446 if (fn.list == NULL)
Denis Vlasenkob012b102007-02-19 22:43:01 +00008447 ash_msg_and_raise_error("redir error");
Denis Vlasenko559691a2008-10-05 18:39:31 +00008448#if ENABLE_ASH_BASH_COMPAT
8449//FIXME: we used expandarg with different args!
8450 if (!isdigit_str9(fn.list->text)) {
8451 /* >&file, not >&fd */
8452 if (redir->nfile.fd != 1) /* 123>&file - BAD */
8453 ash_msg_and_raise_error("redir error");
8454 redir->type = NTO2;
8455 goto store_expfname;
8456 }
8457#endif
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008458 fixredir(redir, fn.list->text, 1);
Eric Andersenc470f442003-07-28 09:56:35 +00008459 }
8460 break;
8461 }
8462 }
8463}
8464
Eric Andersencb57d552001-06-28 07:25:16 +00008465/*
Eric Andersencb57d552001-06-28 07:25:16 +00008466 * Evaluate a pipeline. All the processes in the pipeline are children
8467 * of the process creating the pipeline. (This differs from some versions
8468 * of the shell, which make the last process in a pipeline the parent
8469 * of all the rest.)
8470 */
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008471static void
Eric Andersenc470f442003-07-28 09:56:35 +00008472evalpipe(union node *n, int flags)
Eric Andersencb57d552001-06-28 07:25:16 +00008473{
8474 struct job *jp;
8475 struct nodelist *lp;
8476 int pipelen;
8477 int prevfd;
8478 int pip[2];
8479
Eric Andersenc470f442003-07-28 09:56:35 +00008480 TRACE(("evalpipe(0x%lx) called\n", (long)n));
Eric Andersencb57d552001-06-28 07:25:16 +00008481 pipelen = 0;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008482 for (lp = n->npipe.cmdlist; lp; lp = lp->next)
Eric Andersencb57d552001-06-28 07:25:16 +00008483 pipelen++;
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008484 flags |= EV_EXIT;
Denis Vlasenkob012b102007-02-19 22:43:01 +00008485 INT_OFF;
Denis Vlasenko68404f12008-03-17 09:00:54 +00008486 jp = makejob(/*n,*/ pipelen);
Eric Andersencb57d552001-06-28 07:25:16 +00008487 prevfd = -1;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008488 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008489 prehash(lp->n);
Eric Andersencb57d552001-06-28 07:25:16 +00008490 pip[1] = -1;
8491 if (lp->next) {
8492 if (pipe(pip) < 0) {
8493 close(prevfd);
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00008494 ash_msg_and_raise_error("pipe call failed");
Eric Andersencb57d552001-06-28 07:25:16 +00008495 }
8496 }
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00008497 if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
Denis Vlasenkob012b102007-02-19 22:43:01 +00008498 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00008499 if (pip[1] >= 0) {
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008500 close(pip[0]);
Eric Andersencb57d552001-06-28 07:25:16 +00008501 }
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008502 if (prevfd > 0) {
8503 dup2(prevfd, 0);
8504 close(prevfd);
8505 }
8506 if (pip[1] > 1) {
8507 dup2(pip[1], 1);
8508 close(pip[1]);
8509 }
Eric Andersenc470f442003-07-28 09:56:35 +00008510 evaltreenr(lp->n, flags);
8511 /* never returns */
Eric Andersencb57d552001-06-28 07:25:16 +00008512 }
8513 if (prevfd >= 0)
8514 close(prevfd);
8515 prevfd = pip[0];
Denis Vlasenkob9e70dd2009-03-20 01:24:08 +00008516 /* Don't want to trigger debugging */
8517 if (pip[1] != -1)
8518 close(pip[1]);
Eric Andersencb57d552001-06-28 07:25:16 +00008519 }
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00008520 if (n->npipe.pipe_backgnd == 0) {
Eric Andersencb57d552001-06-28 07:25:16 +00008521 exitstatus = waitforjob(jp);
8522 TRACE(("evalpipe: job done exit status %d\n", exitstatus));
Eric Andersencb57d552001-06-28 07:25:16 +00008523 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00008524 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00008525}
8526
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008527/*
8528 * Controls whether the shell is interactive or not.
8529 */
8530static void
8531setinteractive(int on)
8532{
Denis Vlasenkob07a4962008-06-22 13:16:23 +00008533 static smallint is_interactive;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008534
8535 if (++on == is_interactive)
8536 return;
8537 is_interactive = on;
8538 setsignal(SIGINT);
8539 setsignal(SIGQUIT);
8540 setsignal(SIGTERM);
8541#if !ENABLE_FEATURE_SH_EXTRA_QUIET
8542 if (is_interactive > 1) {
8543 /* Looks like they want an interactive shell */
Denis Vlasenkoca525b42007-06-13 12:27:17 +00008544 static smallint did_banner;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008545
Denis Vlasenkoca525b42007-06-13 12:27:17 +00008546 if (!did_banner) {
Denys Vlasenkoc34c0332009-09-29 12:25:30 +02008547 /* note: ash and hush share this string */
8548 out1fmt("\n\n%s %s\n"
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008549 "Enter 'help' for a list of built-in commands."
8550 "\n\n",
Denys Vlasenkoc34c0332009-09-29 12:25:30 +02008551 bb_banner,
8552 "built-in shell (ash)"
8553 );
Denis Vlasenkoca525b42007-06-13 12:27:17 +00008554 did_banner = 1;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008555 }
8556 }
8557#endif
8558}
8559
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008560static void
8561optschanged(void)
8562{
8563#if DEBUG
8564 opentrace();
8565#endif
8566 setinteractive(iflag);
8567 setjobctl(mflag);
Denis Vlasenkob07a4962008-06-22 13:16:23 +00008568#if ENABLE_FEATURE_EDITING_VI
8569 if (viflag)
8570 line_input_state->flags |= VI_MODE;
8571 else
8572 line_input_state->flags &= ~VI_MODE;
8573#else
8574 viflag = 0; /* forcibly keep the option off */
8575#endif
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008576}
8577
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008578static struct localvar *localvars;
8579
8580/*
8581 * Called after a function returns.
8582 * Interrupts must be off.
8583 */
8584static void
8585poplocalvars(void)
8586{
8587 struct localvar *lvp;
8588 struct var *vp;
8589
8590 while ((lvp = localvars) != NULL) {
8591 localvars = lvp->next;
8592 vp = lvp->vp;
Denys Vlasenko883cea42009-07-11 15:31:59 +02008593 TRACE(("poplocalvar %s\n", vp ? vp->text : "-"));
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008594 if (vp == NULL) { /* $- saved */
8595 memcpy(optlist, lvp->text, sizeof(optlist));
8596 free((char*)lvp->text);
8597 optschanged();
8598 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
8599 unsetvar(vp->text);
8600 } else {
8601 if (vp->func)
8602 (*vp->func)(strchrnul(lvp->text, '=') + 1);
8603 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
8604 free((char*)vp->text);
8605 vp->flags = lvp->flags;
8606 vp->text = lvp->text;
8607 }
8608 free(lvp);
8609 }
8610}
8611
8612static int
8613evalfun(struct funcnode *func, int argc, char **argv, int flags)
8614{
8615 volatile struct shparam saveparam;
8616 struct localvar *volatile savelocalvars;
8617 struct jmploc *volatile savehandler;
8618 struct jmploc jmploc;
8619 int e;
8620
8621 saveparam = shellparam;
8622 savelocalvars = localvars;
8623 e = setjmp(jmploc.loc);
8624 if (e) {
8625 goto funcdone;
8626 }
8627 INT_OFF;
8628 savehandler = exception_handler;
8629 exception_handler = &jmploc;
8630 localvars = NULL;
Denis Vlasenko01631112007-12-16 17:20:38 +00008631 shellparam.malloced = 0;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008632 func->count++;
8633 funcnest++;
8634 INT_ON;
8635 shellparam.nparam = argc - 1;
8636 shellparam.p = argv + 1;
8637#if ENABLE_ASH_GETOPTS
8638 shellparam.optind = 1;
8639 shellparam.optoff = -1;
8640#endif
8641 evaltree(&func->n, flags & EV_TESTED);
Denis Vlasenko01631112007-12-16 17:20:38 +00008642 funcdone:
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008643 INT_OFF;
8644 funcnest--;
8645 freefunc(func);
8646 poplocalvars();
8647 localvars = savelocalvars;
8648 freeparam(&shellparam);
8649 shellparam = saveparam;
8650 exception_handler = savehandler;
8651 INT_ON;
8652 evalskip &= ~SKIPFUNC;
8653 return e;
8654}
8655
Denis Vlasenko131ae172007-02-18 13:00:19 +00008656#if ENABLE_ASH_CMDCMD
Denis Vlasenkoaa744452007-02-23 01:04:22 +00008657static char **
8658parse_command_args(char **argv, const char **path)
Eric Andersenc470f442003-07-28 09:56:35 +00008659{
8660 char *cp, c;
8661
8662 for (;;) {
8663 cp = *++argv;
8664 if (!cp)
8665 return 0;
8666 if (*cp++ != '-')
8667 break;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008668 c = *cp++;
8669 if (!c)
Eric Andersenc470f442003-07-28 09:56:35 +00008670 break;
8671 if (c == '-' && !*cp) {
8672 argv++;
8673 break;
8674 }
8675 do {
8676 switch (c) {
8677 case 'p':
Denis Vlasenkof5f75c52007-06-12 22:35:19 +00008678 *path = bb_default_path;
Eric Andersenc470f442003-07-28 09:56:35 +00008679 break;
8680 default:
8681 /* run 'typecmd' for other options */
8682 return 0;
8683 }
Denis Vlasenko9650f362007-02-23 01:04:37 +00008684 c = *cp++;
8685 } while (c);
Eric Andersenc470f442003-07-28 09:56:35 +00008686 }
8687 return argv;
8688}
8689#endif
8690
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008691/*
8692 * Make a variable a local variable. When a variable is made local, it's
8693 * value and flags are saved in a localvar structure. The saved values
8694 * will be restored when the shell function returns. We handle the name
8695 * "-" as a special case.
8696 */
8697static void
8698mklocal(char *name)
8699{
8700 struct localvar *lvp;
8701 struct var **vpp;
8702 struct var *vp;
8703
8704 INT_OFF;
Denis Vlasenko838ffd52008-02-21 04:32:08 +00008705 lvp = ckzalloc(sizeof(struct localvar));
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008706 if (LONE_DASH(name)) {
8707 char *p;
8708 p = ckmalloc(sizeof(optlist));
8709 lvp->text = memcpy(p, optlist, sizeof(optlist));
8710 vp = NULL;
8711 } else {
8712 char *eq;
8713
8714 vpp = hashvar(name);
8715 vp = *findvar(vpp, name);
8716 eq = strchr(name, '=');
8717 if (vp == NULL) {
8718 if (eq)
8719 setvareq(name, VSTRFIXED);
8720 else
8721 setvar(name, NULL, VSTRFIXED);
8722 vp = *vpp; /* the new variable */
8723 lvp->flags = VUNSET;
8724 } else {
8725 lvp->text = vp->text;
8726 lvp->flags = vp->flags;
8727 vp->flags |= VSTRFIXED|VTEXTFIXED;
8728 if (eq)
8729 setvareq(name, 0);
8730 }
8731 }
8732 lvp->vp = vp;
8733 lvp->next = localvars;
8734 localvars = lvp;
8735 INT_ON;
8736}
8737
8738/*
8739 * The "local" command.
8740 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008741static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008742localcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008743{
8744 char *name;
8745
8746 argv = argptr;
8747 while ((name = *argv++) != NULL) {
8748 mklocal(name);
8749 }
8750 return 0;
8751}
8752
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008753static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008754falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008755{
8756 return 1;
8757}
8758
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008759static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008760truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008761{
8762 return 0;
8763}
8764
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008765static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008766execcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008767{
Denis Vlasenko68404f12008-03-17 09:00:54 +00008768 if (argv[1]) {
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008769 iflag = 0; /* exit on error */
8770 mflag = 0;
8771 optschanged();
8772 shellexec(argv + 1, pathval(), 0);
8773 }
8774 return 0;
8775}
8776
8777/*
8778 * The return command.
8779 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008780static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008781returncmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008782{
8783 /*
8784 * If called outside a function, do what ksh does;
8785 * skip the rest of the file.
8786 */
8787 evalskip = funcnest ? SKIPFUNC : SKIPFILE;
8788 return argv[1] ? number(argv[1]) : exitstatus;
8789}
8790
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008791/* Forward declarations for builtintab[] */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008792static int breakcmd(int, char **) FAST_FUNC;
8793static int dotcmd(int, char **) FAST_FUNC;
8794static int evalcmd(int, char **) FAST_FUNC;
8795static int exitcmd(int, char **) FAST_FUNC;
8796static int exportcmd(int, char **) FAST_FUNC;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008797#if ENABLE_ASH_GETOPTS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008798static int getoptscmd(int, char **) FAST_FUNC;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008799#endif
Denis Vlasenko52764022007-02-24 13:42:56 +00008800#if !ENABLE_FEATURE_SH_EXTRA_QUIET
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008801static int helpcmd(int, char **) FAST_FUNC;
Denis Vlasenko52764022007-02-24 13:42:56 +00008802#endif
Mike Frysinger98c52642009-04-02 10:02:37 +00008803#if ENABLE_SH_MATH_SUPPORT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008804static int letcmd(int, char **) FAST_FUNC;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008805#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008806static int readcmd(int, char **) FAST_FUNC;
8807static int setcmd(int, char **) FAST_FUNC;
8808static int shiftcmd(int, char **) FAST_FUNC;
8809static int timescmd(int, char **) FAST_FUNC;
8810static int trapcmd(int, char **) FAST_FUNC;
8811static int umaskcmd(int, char **) FAST_FUNC;
8812static int unsetcmd(int, char **) FAST_FUNC;
8813static int ulimitcmd(int, char **) FAST_FUNC;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008814
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008815#define BUILTIN_NOSPEC "0"
8816#define BUILTIN_SPECIAL "1"
8817#define BUILTIN_REGULAR "2"
8818#define BUILTIN_SPEC_REG "3"
8819#define BUILTIN_ASSIGN "4"
8820#define BUILTIN_SPEC_ASSG "5"
8821#define BUILTIN_REG_ASSG "6"
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008822#define BUILTIN_SPEC_REG_ASSG "7"
8823
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008824/* Stubs for calling non-FAST_FUNC's */
Denys Vlasenko2634bf32009-06-09 18:40:07 +02008825#if ENABLE_ASH_BUILTIN_ECHO
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008826static int FAST_FUNC echocmd(int argc, char **argv) { return echo_main(argc, argv); }
Denys Vlasenko2634bf32009-06-09 18:40:07 +02008827#endif
8828#if ENABLE_ASH_BUILTIN_PRINTF
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008829static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
Denys Vlasenko2634bf32009-06-09 18:40:07 +02008830#endif
8831#if ENABLE_ASH_BUILTIN_TEST
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008832static int FAST_FUNC testcmd(int argc, char **argv) { return test_main(argc, argv); }
Denys Vlasenko2634bf32009-06-09 18:40:07 +02008833#endif
Denis Vlasenko468aea22008-04-01 14:47:57 +00008834
Denis Vlasenkof7d56652008-03-25 05:51:41 +00008835/* Keep these in proper order since it is searched via bsearch() */
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008836static const struct builtincmd builtintab[] = {
8837 { BUILTIN_SPEC_REG ".", dotcmd },
8838 { BUILTIN_SPEC_REG ":", truecmd },
8839#if ENABLE_ASH_BUILTIN_TEST
Denis Vlasenkocd2663f2008-06-01 22:36:39 +00008840 { BUILTIN_REGULAR "[", testcmd },
Denis Vlasenko80591b02008-03-25 07:49:43 +00008841#if ENABLE_ASH_BASH_COMPAT
Denis Vlasenkocd2663f2008-06-01 22:36:39 +00008842 { BUILTIN_REGULAR "[[", testcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008843#endif
Denis Vlasenko80591b02008-03-25 07:49:43 +00008844#endif
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008845#if ENABLE_ASH_ALIAS
8846 { BUILTIN_REG_ASSG "alias", aliascmd },
8847#endif
8848#if JOBS
8849 { BUILTIN_REGULAR "bg", fg_bgcmd },
8850#endif
8851 { BUILTIN_SPEC_REG "break", breakcmd },
8852 { BUILTIN_REGULAR "cd", cdcmd },
8853 { BUILTIN_NOSPEC "chdir", cdcmd },
8854#if ENABLE_ASH_CMDCMD
8855 { BUILTIN_REGULAR "command", commandcmd },
8856#endif
8857 { BUILTIN_SPEC_REG "continue", breakcmd },
8858#if ENABLE_ASH_BUILTIN_ECHO
8859 { BUILTIN_REGULAR "echo", echocmd },
8860#endif
8861 { BUILTIN_SPEC_REG "eval", evalcmd },
8862 { BUILTIN_SPEC_REG "exec", execcmd },
8863 { BUILTIN_SPEC_REG "exit", exitcmd },
8864 { BUILTIN_SPEC_REG_ASSG "export", exportcmd },
8865 { BUILTIN_REGULAR "false", falsecmd },
8866#if JOBS
8867 { BUILTIN_REGULAR "fg", fg_bgcmd },
8868#endif
8869#if ENABLE_ASH_GETOPTS
8870 { BUILTIN_REGULAR "getopts", getoptscmd },
8871#endif
8872 { BUILTIN_NOSPEC "hash", hashcmd },
8873#if !ENABLE_FEATURE_SH_EXTRA_QUIET
8874 { BUILTIN_NOSPEC "help", helpcmd },
8875#endif
8876#if JOBS
8877 { BUILTIN_REGULAR "jobs", jobscmd },
8878 { BUILTIN_REGULAR "kill", killcmd },
8879#endif
Mike Frysinger98c52642009-04-02 10:02:37 +00008880#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008881 { BUILTIN_NOSPEC "let", letcmd },
8882#endif
8883 { BUILTIN_ASSIGN "local", localcmd },
Denis Vlasenkocd2663f2008-06-01 22:36:39 +00008884#if ENABLE_ASH_BUILTIN_PRINTF
8885 { BUILTIN_REGULAR "printf", printfcmd },
8886#endif
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008887 { BUILTIN_NOSPEC "pwd", pwdcmd },
8888 { BUILTIN_REGULAR "read", readcmd },
8889 { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
8890 { BUILTIN_SPEC_REG "return", returncmd },
8891 { BUILTIN_SPEC_REG "set", setcmd },
8892 { BUILTIN_SPEC_REG "shift", shiftcmd },
8893 { BUILTIN_SPEC_REG "source", dotcmd },
8894#if ENABLE_ASH_BUILTIN_TEST
Denis Vlasenkocd2663f2008-06-01 22:36:39 +00008895 { BUILTIN_REGULAR "test", testcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008896#endif
8897 { BUILTIN_SPEC_REG "times", timescmd },
8898 { BUILTIN_SPEC_REG "trap", trapcmd },
8899 { BUILTIN_REGULAR "true", truecmd },
8900 { BUILTIN_NOSPEC "type", typecmd },
8901 { BUILTIN_NOSPEC "ulimit", ulimitcmd },
8902 { BUILTIN_REGULAR "umask", umaskcmd },
8903#if ENABLE_ASH_ALIAS
8904 { BUILTIN_REGULAR "unalias", unaliascmd },
8905#endif
8906 { BUILTIN_SPEC_REG "unset", unsetcmd },
8907 { BUILTIN_REGULAR "wait", waitcmd },
8908};
8909
Denis Vlasenko80591b02008-03-25 07:49:43 +00008910/* Should match the above table! */
8911#define COMMANDCMD (builtintab + \
8912 2 + \
8913 1 * ENABLE_ASH_BUILTIN_TEST + \
8914 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
8915 1 * ENABLE_ASH_ALIAS + \
8916 1 * ENABLE_ASH_JOB_CONTROL + \
8917 3)
8918#define EXECCMD (builtintab + \
8919 2 + \
8920 1 * ENABLE_ASH_BUILTIN_TEST + \
8921 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
8922 1 * ENABLE_ASH_ALIAS + \
8923 1 * ENABLE_ASH_JOB_CONTROL + \
8924 3 + \
8925 1 * ENABLE_ASH_CMDCMD + \
8926 1 + \
8927 ENABLE_ASH_BUILTIN_ECHO + \
8928 1)
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008929
8930/*
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008931 * Search the table of builtin commands.
8932 */
8933static struct builtincmd *
8934find_builtin(const char *name)
8935{
8936 struct builtincmd *bp;
8937
8938 bp = bsearch(
Denis Vlasenko80b8b392007-06-25 10:55:35 +00008939 name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008940 pstrcmp
8941 );
8942 return bp;
8943}
8944
8945/*
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008946 * Execute a simple command.
8947 */
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008948static int
8949isassignment(const char *p)
Paul Foxc3850c82005-07-20 18:23:39 +00008950{
8951 const char *q = endofname(p);
8952 if (p == q)
8953 return 0;
8954 return *q == '=';
8955}
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008956static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008957bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008958{
8959 /* Preserve exitstatus of a previous possible redirection
8960 * as POSIX mandates */
8961 return back_exitstatus;
8962}
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008963static void
Eric Andersenc470f442003-07-28 09:56:35 +00008964evalcommand(union node *cmd, int flags)
8965{
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00008966 static const struct builtincmd null_bltin = {
8967 "\0\0", bltincmd /* why three NULs? */
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008968 };
Eric Andersenc470f442003-07-28 09:56:35 +00008969 struct stackmark smark;
8970 union node *argp;
8971 struct arglist arglist;
8972 struct arglist varlist;
8973 char **argv;
8974 int argc;
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00008975 const struct strlist *sp;
Eric Andersenc470f442003-07-28 09:56:35 +00008976 struct cmdentry cmdentry;
8977 struct job *jp;
8978 char *lastarg;
8979 const char *path;
8980 int spclbltin;
Eric Andersenc470f442003-07-28 09:56:35 +00008981 int status;
8982 char **nargv;
Paul Foxc3850c82005-07-20 18:23:39 +00008983 struct builtincmd *bcmd;
Denis Vlasenko34c73c42008-08-16 11:48:02 +00008984 smallint cmd_is_exec;
8985 smallint pseudovarflag = 0;
Eric Andersenc470f442003-07-28 09:56:35 +00008986
8987 /* First expand the arguments. */
8988 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
8989 setstackmark(&smark);
8990 back_exitstatus = 0;
8991
8992 cmdentry.cmdtype = CMDBUILTIN;
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00008993 cmdentry.u.cmd = &null_bltin;
Eric Andersenc470f442003-07-28 09:56:35 +00008994 varlist.lastp = &varlist.list;
8995 *varlist.lastp = NULL;
8996 arglist.lastp = &arglist.list;
8997 *arglist.lastp = NULL;
8998
8999 argc = 0;
Denis Vlasenkob012b102007-02-19 22:43:01 +00009000 if (cmd->ncmd.args) {
Paul Foxc3850c82005-07-20 18:23:39 +00009001 bcmd = find_builtin(cmd->ncmd.args->narg.text);
9002 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
9003 }
9004
Eric Andersenc470f442003-07-28 09:56:35 +00009005 for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
9006 struct strlist **spp;
9007
9008 spp = arglist.lastp;
"Vladimir N. Oleynik"bef14d72005-09-05 13:25:11 +00009009 if (pseudovarflag && isassignment(argp->narg.text))
Paul Foxc3850c82005-07-20 18:23:39 +00009010 expandarg(argp, &arglist, EXP_VARTILDE);
9011 else
9012 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
9013
Eric Andersenc470f442003-07-28 09:56:35 +00009014 for (sp = *spp; sp; sp = sp->next)
9015 argc++;
9016 }
9017
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +00009018 argv = nargv = stalloc(sizeof(char *) * (argc + 1));
Denis Vlasenko2da584f2007-02-19 22:44:05 +00009019 for (sp = arglist.list; sp; sp = sp->next) {
Eric Andersenc470f442003-07-28 09:56:35 +00009020 TRACE(("evalcommand arg: %s\n", sp->text));
9021 *nargv++ = sp->text;
9022 }
9023 *nargv = NULL;
9024
9025 lastarg = NULL;
9026 if (iflag && funcnest == 0 && argc > 0)
9027 lastarg = nargv[-1];
9028
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009029 preverrout_fd = 2;
Eric Andersenc470f442003-07-28 09:56:35 +00009030 expredir(cmd->ncmd.redirect);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009031 status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
Eric Andersenc470f442003-07-28 09:56:35 +00009032
9033 path = vpath.text;
9034 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
9035 struct strlist **spp;
9036 char *p;
9037
9038 spp = varlist.lastp;
9039 expandarg(argp, &varlist, EXP_VARTILDE);
9040
9041 /*
9042 * Modify the command lookup path, if a PATH= assignment
9043 * is present
9044 */
9045 p = (*spp)->text;
9046 if (varequal(p, path))
9047 path = p;
9048 }
9049
9050 /* Print the command if xflag is set. */
9051 if (xflag) {
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009052 int n;
9053 const char *p = " %s";
Eric Andersenc470f442003-07-28 09:56:35 +00009054
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009055 p++;
Denis Vlasenko0de37e12007-10-17 11:08:53 +00009056 fdprintf(preverrout_fd, p, expandstr(ps4val()));
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009057
9058 sp = varlist.list;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +00009059 for (n = 0; n < 2; n++) {
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009060 while (sp) {
Denis Vlasenko0de37e12007-10-17 11:08:53 +00009061 fdprintf(preverrout_fd, p, sp->text);
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009062 sp = sp->next;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +00009063 if (*p == '%') {
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009064 p--;
9065 }
9066 }
9067 sp = arglist.list;
9068 }
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00009069 safe_write(preverrout_fd, "\n", 1);
Eric Andersenc470f442003-07-28 09:56:35 +00009070 }
9071
9072 cmd_is_exec = 0;
9073 spclbltin = -1;
9074
9075 /* Now locate the command. */
9076 if (argc) {
9077 const char *oldpath;
9078 int cmd_flag = DO_ERR;
9079
9080 path += 5;
9081 oldpath = path;
9082 for (;;) {
9083 find_command(argv[0], &cmdentry, cmd_flag, path);
9084 if (cmdentry.cmdtype == CMDUNKNOWN) {
Denys Vlasenko8131eea2009-11-02 14:19:51 +01009085 flush_stdout_stderr();
Denis Vlasenko6514c5e2008-07-24 13:41:37 +00009086 status = 127;
Eric Andersenc470f442003-07-28 09:56:35 +00009087 goto bail;
9088 }
9089
9090 /* implement bltin and command here */
9091 if (cmdentry.cmdtype != CMDBUILTIN)
9092 break;
9093 if (spclbltin < 0)
9094 spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
9095 if (cmdentry.u.cmd == EXECCMD)
Denis Vlasenko34c73c42008-08-16 11:48:02 +00009096 cmd_is_exec = 1;
Denis Vlasenko131ae172007-02-18 13:00:19 +00009097#if ENABLE_ASH_CMDCMD
Eric Andersenc470f442003-07-28 09:56:35 +00009098 if (cmdentry.u.cmd == COMMANDCMD) {
Eric Andersenc470f442003-07-28 09:56:35 +00009099 path = oldpath;
9100 nargv = parse_command_args(argv, &path);
9101 if (!nargv)
9102 break;
9103 argc -= nargv - argv;
9104 argv = nargv;
9105 cmd_flag |= DO_NOFUNC;
9106 } else
9107#endif
9108 break;
9109 }
9110 }
9111
9112 if (status) {
9113 /* We have a redirection error. */
9114 if (spclbltin > 0)
Denis Vlasenkob012b102007-02-19 22:43:01 +00009115 raise_exception(EXERROR);
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009116 bail:
Eric Andersenc470f442003-07-28 09:56:35 +00009117 exitstatus = status;
9118 goto out;
9119 }
9120
9121 /* Execute the command. */
9122 switch (cmdentry.cmdtype) {
9123 default:
Denis Vlasenkobe54d6b2008-10-27 14:25:52 +00009124
Denis Vlasenko9bc80d72008-04-12 20:07:53 +00009125#if ENABLE_FEATURE_SH_NOFORK
Denis Vlasenkobe54d6b2008-10-27 14:25:52 +00009126/* Hmmm... shouldn't it happen somewhere in forkshell() instead?
9127 * Why "fork off a child process if necessary" doesn't apply to NOFORK? */
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00009128 {
9129 /* find_command() encodes applet_no as (-2 - applet_no) */
9130 int applet_no = (- cmdentry.u.index - 2);
Denis Vlasenko9bc80d72008-04-12 20:07:53 +00009131 if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
Denis Vlasenko9bc80d72008-04-12 20:07:53 +00009132 listsetvar(varlist.list, VEXPORT|VSTACK);
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00009133 /* run <applet>_main() */
9134 exitstatus = run_nofork_applet(applet_no, argv);
Denis Vlasenko9bc80d72008-04-12 20:07:53 +00009135 break;
9136 }
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00009137 }
Denis Vlasenko9bc80d72008-04-12 20:07:53 +00009138#endif
Eric Andersenc470f442003-07-28 09:56:35 +00009139 /* Fork off a child process if necessary. */
9140 if (!(flags & EV_EXIT) || trap[0]) {
Denis Vlasenkob012b102007-02-19 22:43:01 +00009141 INT_OFF;
Denis Vlasenko68404f12008-03-17 09:00:54 +00009142 jp = makejob(/*cmd,*/ 1);
Eric Andersenc470f442003-07-28 09:56:35 +00009143 if (forkshell(jp, cmd, FORK_FG) != 0) {
9144 exitstatus = waitforjob(jp);
Denis Vlasenkob012b102007-02-19 22:43:01 +00009145 INT_ON;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00009146 TRACE(("forked child exited with %d\n", exitstatus));
Eric Andersenc470f442003-07-28 09:56:35 +00009147 break;
9148 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00009149 FORCE_INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00009150 }
9151 listsetvar(varlist.list, VEXPORT|VSTACK);
9152 shellexec(argv, path, cmdentry.u.index);
9153 /* NOTREACHED */
9154
9155 case CMDBUILTIN:
9156 cmdenviron = varlist.list;
9157 if (cmdenviron) {
9158 struct strlist *list = cmdenviron;
9159 int i = VNOSET;
9160 if (spclbltin > 0 || argc == 0) {
9161 i = 0;
9162 if (cmd_is_exec && argc > 1)
9163 i = VEXPORT;
9164 }
9165 listsetvar(list, i);
9166 }
Denis Vlasenkobe54d6b2008-10-27 14:25:52 +00009167 /* Tight loop with builtins only:
9168 * "while kill -0 $child; do true; done"
9169 * will never exit even if $child died, unless we do this
9170 * to reap the zombie and make kill detect that it's gone: */
9171 dowait(DOWAIT_NONBLOCK, NULL);
9172
Eric Andersenc470f442003-07-28 09:56:35 +00009173 if (evalbltin(cmdentry.u.cmd, argc, argv)) {
9174 int exit_status;
Denis Vlasenko7f88e342009-03-19 03:36:18 +00009175 int i = exception_type;
Eric Andersenc470f442003-07-28 09:56:35 +00009176 if (i == EXEXIT)
9177 goto raise;
Eric Andersenc470f442003-07-28 09:56:35 +00009178 exit_status = 2;
Eric Andersenc470f442003-07-28 09:56:35 +00009179 if (i == EXINT)
Denis Vlasenko991a1da2008-02-10 19:02:53 +00009180 exit_status = 128 + SIGINT;
Eric Andersenc470f442003-07-28 09:56:35 +00009181 if (i == EXSIG)
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02009182 exit_status = 128 + pending_sig;
Eric Andersenc470f442003-07-28 09:56:35 +00009183 exitstatus = exit_status;
Eric Andersenc470f442003-07-28 09:56:35 +00009184 if (i == EXINT || spclbltin > 0) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009185 raise:
Denis Vlasenko2da584f2007-02-19 22:44:05 +00009186 longjmp(exception_handler->loc, 1);
Eric Andersenc470f442003-07-28 09:56:35 +00009187 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00009188 FORCE_INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00009189 }
9190 break;
9191
9192 case CMDFUNCTION:
9193 listsetvar(varlist.list, 0);
Denis Vlasenkobe54d6b2008-10-27 14:25:52 +00009194 /* See above for the rationale */
9195 dowait(DOWAIT_NONBLOCK, NULL);
Eric Andersenc470f442003-07-28 09:56:35 +00009196 if (evalfun(cmdentry.u.func, argc, argv, flags))
9197 goto raise;
9198 break;
9199 }
9200
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009201 out:
Denis Vlasenko34c73c42008-08-16 11:48:02 +00009202 popredir(/*drop:*/ cmd_is_exec, /*restore:*/ cmd_is_exec);
Denis Vlasenko6514c5e2008-07-24 13:41:37 +00009203 if (lastarg) {
Eric Andersenc470f442003-07-28 09:56:35 +00009204 /* dsl: I think this is intended to be used to support
9205 * '_' in 'vi' command mode during line editing...
9206 * However I implemented that within libedit itself.
9207 */
9208 setvar("_", lastarg, 0);
Denis Vlasenko6514c5e2008-07-24 13:41:37 +00009209 }
Eric Andersenc470f442003-07-28 09:56:35 +00009210 popstackmark(&smark);
9211}
9212
9213static int
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009214evalbltin(const struct builtincmd *cmd, int argc, char **argv)
9215{
Eric Andersenc470f442003-07-28 09:56:35 +00009216 char *volatile savecmdname;
9217 struct jmploc *volatile savehandler;
9218 struct jmploc jmploc;
9219 int i;
9220
9221 savecmdname = commandname;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009222 i = setjmp(jmploc.loc);
9223 if (i)
Eric Andersenc470f442003-07-28 09:56:35 +00009224 goto cmddone;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00009225 savehandler = exception_handler;
9226 exception_handler = &jmploc;
Eric Andersenc470f442003-07-28 09:56:35 +00009227 commandname = argv[0];
9228 argptr = argv + 1;
9229 optptr = NULL; /* initialize nextopt */
9230 exitstatus = (*cmd->builtin)(argc, argv);
Denis Vlasenkob012b102007-02-19 22:43:01 +00009231 flush_stdout_stderr();
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009232 cmddone:
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009233 exitstatus |= ferror(stdout);
Rob Landleyf296f0b2006-07-06 01:09:21 +00009234 clearerr(stdout);
Eric Andersenc470f442003-07-28 09:56:35 +00009235 commandname = savecmdname;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00009236 exception_handler = savehandler;
Eric Andersenc470f442003-07-28 09:56:35 +00009237
9238 return i;
9239}
9240
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009241static int
9242goodname(const char *p)
Glenn L McGrath16e45d72004-02-04 08:24:39 +00009243{
9244 return !*endofname(p);
9245}
9246
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009247
Glenn L McGrath50812ff2002-08-23 13:14:48 +00009248/*
9249 * Search for a command. This is called before we fork so that the
9250 * location of the command will be available in the parent as well as
Glenn L McGrath16e45d72004-02-04 08:24:39 +00009251 * the child. The check for "goodname" is an overly conservative
9252 * check that the name will not be subject to expansion.
Glenn L McGrath50812ff2002-08-23 13:14:48 +00009253 */
Eric Andersenc470f442003-07-28 09:56:35 +00009254static void
9255prehash(union node *n)
Glenn L McGrath50812ff2002-08-23 13:14:48 +00009256{
9257 struct cmdentry entry;
9258
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +00009259 if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
9260 find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
Glenn L McGrath50812ff2002-08-23 13:14:48 +00009261}
9262
Eric Andersencb57d552001-06-28 07:25:16 +00009263
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00009264/* ============ Builtin commands
9265 *
9266 * Builtin commands whose functions are closely tied to evaluation
9267 * are implemented here.
Eric Andersencb57d552001-06-28 07:25:16 +00009268 */
9269
9270/*
Eric Andersencb57d552001-06-28 07:25:16 +00009271 * Handle break and continue commands. Break, continue, and return are
9272 * all handled by setting the evalskip flag. The evaluation routines
9273 * above all check this flag, and if it is set they start skipping
9274 * commands rather than executing them. The variable skipcount is
9275 * the number of loops to break/continue, or the number of function
9276 * levels to return. (The latter is always 1.) It should probably
9277 * be an error to break out of more loops than exist, but it isn't
9278 * in the standard shell so we don't make it one here.
9279 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009280static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00009281breakcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +00009282{
Denis Vlasenko68404f12008-03-17 09:00:54 +00009283 int n = argv[1] ? number(argv[1]) : 1;
Eric Andersencb57d552001-06-28 07:25:16 +00009284
Aaron Lehmann2aef3a62001-12-31 06:03:12 +00009285 if (n <= 0)
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02009286 ash_msg_and_raise_error(msg_illnum, argv[1]);
Eric Andersencb57d552001-06-28 07:25:16 +00009287 if (n > loopnest)
9288 n = loopnest;
9289 if (n > 0) {
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00009290 evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
Eric Andersencb57d552001-06-28 07:25:16 +00009291 skipcount = n;
9292 }
9293 return 0;
9294}
9295
Eric Andersenc470f442003-07-28 09:56:35 +00009296
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009297/* ============ input.c
9298 *
Eric Andersen90898442003-08-06 11:20:52 +00009299 * This implements the input routines used by the parser.
Eric Andersencb57d552001-06-28 07:25:16 +00009300 */
Denis Vlasenko99eb8502007-02-23 21:09:49 +00009301
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009302enum {
9303 INPUT_PUSH_FILE = 1,
9304 INPUT_NOFILE_OK = 2,
9305};
Eric Andersencb57d552001-06-28 07:25:16 +00009306
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009307static smallint checkkwd;
Denis Vlasenko99eb8502007-02-23 21:09:49 +00009308/* values of checkkwd variable */
9309#define CHKALIAS 0x1
9310#define CHKKWD 0x2
9311#define CHKNL 0x4
9312
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009313/*
9314 * Push a string back onto the input at this current parsefile level.
9315 * We handle aliases this way.
9316 */
9317#if !ENABLE_ASH_ALIAS
9318#define pushstring(s, ap) pushstring(s)
9319#endif
9320static void
9321pushstring(char *s, struct alias *ap)
9322{
9323 struct strpush *sp;
9324 int len;
9325
9326 len = strlen(s);
9327 INT_OFF;
9328 if (g_parsefile->strpush) {
9329 sp = ckzalloc(sizeof(*sp));
9330 sp->prev = g_parsefile->strpush;
9331 } else {
9332 sp = &(g_parsefile->basestrpush);
9333 }
9334 g_parsefile->strpush = sp;
9335 sp->prev_string = g_parsefile->next_to_pgetc;
9336 sp->prev_left_in_line = g_parsefile->left_in_line;
9337#if ENABLE_ASH_ALIAS
9338 sp->ap = ap;
9339 if (ap) {
9340 ap->flag |= ALIASINUSE;
9341 sp->string = s;
9342 }
9343#endif
9344 g_parsefile->next_to_pgetc = s;
9345 g_parsefile->left_in_line = len;
9346 INT_ON;
9347}
9348
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009349static void
9350popstring(void)
Eric Andersenc470f442003-07-28 09:56:35 +00009351{
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009352 struct strpush *sp = g_parsefile->strpush;
Eric Andersenc470f442003-07-28 09:56:35 +00009353
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009354 INT_OFF;
Denis Vlasenko131ae172007-02-18 13:00:19 +00009355#if ENABLE_ASH_ALIAS
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009356 if (sp->ap) {
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009357 if (g_parsefile->next_to_pgetc[-1] == ' '
9358 || g_parsefile->next_to_pgetc[-1] == '\t'
9359 ) {
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009360 checkkwd |= CHKALIAS;
Glenn L McGrath28939ad2004-07-21 10:20:19 +00009361 }
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009362 if (sp->string != sp->ap->val) {
9363 free(sp->string);
9364 }
9365 sp->ap->flag &= ~ALIASINUSE;
9366 if (sp->ap->flag & ALIASDEAD) {
9367 unalias(sp->ap->name);
9368 }
Glenn L McGrath28939ad2004-07-21 10:20:19 +00009369 }
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009370#endif
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009371 g_parsefile->next_to_pgetc = sp->prev_string;
9372 g_parsefile->left_in_line = sp->prev_left_in_line;
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009373 g_parsefile->strpush = sp->prev;
9374 if (sp != &(g_parsefile->basestrpush))
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009375 free(sp);
9376 INT_ON;
9377}
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009378
Denis Vlasenkoe27dafd2008-11-28 04:01:03 +00009379//FIXME: BASH_COMPAT with "...&" does TWO pungetc():
9380//it peeks whether it is &>, and then pushes back both chars.
9381//This function needs to save last *next_to_pgetc to buf[0]
9382//to make two pungetc() reliable. Currently,
9383// pgetc (out of buf: does preadfd), pgetc, pungetc, pungetc won't work...
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009384static int
9385preadfd(void)
Eric Andersencb57d552001-06-28 07:25:16 +00009386{
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00009387 int nr;
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00009388 char *buf = g_parsefile->buf;
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00009389
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009390 g_parsefile->next_to_pgetc = buf;
Denis Vlasenko38f63192007-01-22 09:03:07 +00009391#if ENABLE_FEATURE_EDITING
Denis Vlasenko85c24712008-03-17 09:04:04 +00009392 retry:
Denis Vlasenko727752d2008-11-28 03:41:47 +00009393 if (!iflag || g_parsefile->fd != STDIN_FILENO)
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009394 nr = nonblock_safe_read(g_parsefile->fd, buf, BUFSIZ - 1);
Eric Andersenc470f442003-07-28 09:56:35 +00009395 else {
Denis Vlasenko38f63192007-01-22 09:03:07 +00009396#if ENABLE_FEATURE_TAB_COMPLETION
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009397 line_input_state->path_lookup = pathval();
Eric Andersen4a79c0e2004-09-08 10:01:07 +00009398#endif
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009399 nr = read_line_input(cmdedit_prompt, buf, BUFSIZ, line_input_state);
9400 if (nr == 0) {
9401 /* Ctrl+C pressed */
9402 if (trap[SIGINT]) {
Glenn L McGrath16e45d72004-02-04 08:24:39 +00009403 buf[0] = '\n';
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009404 buf[1] = '\0';
Glenn L McGrath16e45d72004-02-04 08:24:39 +00009405 raise(SIGINT);
9406 return 1;
9407 }
Eric Andersenc470f442003-07-28 09:56:35 +00009408 goto retry;
9409 }
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009410 if (nr < 0 && errno == 0) {
Denis Vlasenko9cb220b2007-12-09 10:03:28 +00009411 /* Ctrl+D pressed */
Eric Andersenc470f442003-07-28 09:56:35 +00009412 nr = 0;
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00009413 }
Eric Andersencb57d552001-06-28 07:25:16 +00009414 }
9415#else
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +00009416 nr = nonblock_safe_read(g_parsefile->fd, buf, BUFSIZ - 1);
Eric Andersencb57d552001-06-28 07:25:16 +00009417#endif
9418
Denis Vlasenkoe376d452008-02-20 22:23:24 +00009419#if 0
9420/* nonblock_safe_read() handles this problem */
Eric Andersencb57d552001-06-28 07:25:16 +00009421 if (nr < 0) {
Eric Andersencb57d552001-06-28 07:25:16 +00009422 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
Denis Vlasenkod37f2222007-08-19 13:42:08 +00009423 int flags = fcntl(0, F_GETFL);
Denis Vlasenko9cb220b2007-12-09 10:03:28 +00009424 if (flags >= 0 && (flags & O_NONBLOCK)) {
9425 flags &= ~O_NONBLOCK;
Eric Andersencb57d552001-06-28 07:25:16 +00009426 if (fcntl(0, F_SETFL, flags) >= 0) {
9427 out2str("sh: turning off NDELAY mode\n");
9428 goto retry;
9429 }
9430 }
9431 }
9432 }
Denis Vlasenkoe376d452008-02-20 22:23:24 +00009433#endif
Eric Andersencb57d552001-06-28 07:25:16 +00009434 return nr;
9435}
9436
9437/*
9438 * Refill the input buffer and return the next input character:
9439 *
9440 * 1) If a string was pushed back on the input, pop it;
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009441 * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
9442 * or we are reading from a string so we can't refill the buffer,
9443 * return EOF.
Denys Vlasenko883cea42009-07-11 15:31:59 +02009444 * 3) If there is more stuff in this buffer, use it else call read to fill it.
Eric Andersencb57d552001-06-28 07:25:16 +00009445 * 4) Process input up to the next newline, deleting nul characters.
9446 */
Denis Vlasenko727752d2008-11-28 03:41:47 +00009447//#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
9448#define pgetc_debug(...) ((void)0)
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009449static int
Eric Andersenc470f442003-07-28 09:56:35 +00009450preadbuffer(void)
Eric Andersencb57d552001-06-28 07:25:16 +00009451{
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009452 char *q;
Eric Andersencb57d552001-06-28 07:25:16 +00009453 int more;
Eric Andersencb57d552001-06-28 07:25:16 +00009454
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009455 while (g_parsefile->strpush) {
Denis Vlasenko131ae172007-02-18 13:00:19 +00009456#if ENABLE_ASH_ALIAS
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009457 if (g_parsefile->left_in_line == -1
9458 && g_parsefile->strpush->ap
9459 && g_parsefile->next_to_pgetc[-1] != ' '
9460 && g_parsefile->next_to_pgetc[-1] != '\t'
Denis Vlasenko16898402008-11-25 01:34:52 +00009461 ) {
Denis Vlasenko727752d2008-11-28 03:41:47 +00009462 pgetc_debug("preadbuffer PEOA");
Eric Andersencb57d552001-06-28 07:25:16 +00009463 return PEOA;
9464 }
Eric Andersen2870d962001-07-02 17:27:21 +00009465#endif
Eric Andersencb57d552001-06-28 07:25:16 +00009466 popstring();
Denis Vlasenko727752d2008-11-28 03:41:47 +00009467 /* try "pgetc" now: */
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009468 pgetc_debug("preadbuffer internal pgetc at %d:%p'%s'",
9469 g_parsefile->left_in_line,
9470 g_parsefile->next_to_pgetc,
9471 g_parsefile->next_to_pgetc);
9472 if (--g_parsefile->left_in_line >= 0)
9473 return (unsigned char)(*g_parsefile->next_to_pgetc++);
Eric Andersencb57d552001-06-28 07:25:16 +00009474 }
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009475 /* on both branches above g_parsefile->left_in_line < 0.
Denis Vlasenko727752d2008-11-28 03:41:47 +00009476 * "pgetc" needs refilling.
9477 */
9478
Denis Vlasenkoe27dafd2008-11-28 04:01:03 +00009479 /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009480 * pungetc() may increment it a few times.
Denis Vlasenkoe27dafd2008-11-28 04:01:03 +00009481 * Assuming it won't increment it to less than -90.
Denis Vlasenko727752d2008-11-28 03:41:47 +00009482 */
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009483 if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
Denis Vlasenko727752d2008-11-28 03:41:47 +00009484 pgetc_debug("preadbuffer PEOF1");
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009485 /* even in failure keep left_in_line and next_to_pgetc
9486 * in lock step, for correct multi-layer pungetc.
9487 * left_in_line was decremented before preadbuffer(),
9488 * must inc next_to_pgetc: */
9489 g_parsefile->next_to_pgetc++;
Eric Andersencb57d552001-06-28 07:25:16 +00009490 return PEOF;
Denis Vlasenko727752d2008-11-28 03:41:47 +00009491 }
Eric Andersencb57d552001-06-28 07:25:16 +00009492
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009493 more = g_parsefile->left_in_buffer;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009494 if (more <= 0) {
Denis Vlasenko727752d2008-11-28 03:41:47 +00009495 flush_stdout_stderr();
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009496 again:
9497 more = preadfd();
9498 if (more <= 0) {
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009499 /* don't try reading again */
9500 g_parsefile->left_in_line = -99;
Denis Vlasenko727752d2008-11-28 03:41:47 +00009501 pgetc_debug("preadbuffer PEOF2");
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009502 g_parsefile->next_to_pgetc++;
Eric Andersencb57d552001-06-28 07:25:16 +00009503 return PEOF;
9504 }
9505 }
9506
Denis Vlasenko727752d2008-11-28 03:41:47 +00009507 /* Find out where's the end of line.
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009508 * Set g_parsefile->left_in_line
9509 * and g_parsefile->left_in_buffer acordingly.
Denis Vlasenko727752d2008-11-28 03:41:47 +00009510 * NUL chars are deleted.
9511 */
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009512 q = g_parsefile->next_to_pgetc;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009513 for (;;) {
Denis Vlasenko727752d2008-11-28 03:41:47 +00009514 char c;
Eric Andersencb57d552001-06-28 07:25:16 +00009515
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009516 more--;
Eric Andersenc470f442003-07-28 09:56:35 +00009517
Denis Vlasenko727752d2008-11-28 03:41:47 +00009518 c = *q;
9519 if (c == '\0') {
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009520 memmove(q, q + 1, more);
Denis Vlasenko727752d2008-11-28 03:41:47 +00009521 } else {
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009522 q++;
9523 if (c == '\n') {
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009524 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009525 break;
9526 }
Eric Andersencb57d552001-06-28 07:25:16 +00009527 }
9528
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009529 if (more <= 0) {
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009530 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9531 if (g_parsefile->left_in_line < 0)
Eric Andersencb57d552001-06-28 07:25:16 +00009532 goto again;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009533 break;
Eric Andersencb57d552001-06-28 07:25:16 +00009534 }
9535 }
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009536 g_parsefile->left_in_buffer = more;
Eric Andersencb57d552001-06-28 07:25:16 +00009537
Eric Andersencb57d552001-06-28 07:25:16 +00009538 if (vflag) {
Denis Vlasenko727752d2008-11-28 03:41:47 +00009539 char save = *q;
9540 *q = '\0';
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009541 out2str(g_parsefile->next_to_pgetc);
Denis Vlasenko727752d2008-11-28 03:41:47 +00009542 *q = save;
Eric Andersencb57d552001-06-28 07:25:16 +00009543 }
9544
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009545 pgetc_debug("preadbuffer at %d:%p'%s'",
9546 g_parsefile->left_in_line,
9547 g_parsefile->next_to_pgetc,
9548 g_parsefile->next_to_pgetc);
Denys Vlasenkocd716832009-11-28 22:14:02 +01009549 return (unsigned char)*g_parsefile->next_to_pgetc++;
Eric Andersencb57d552001-06-28 07:25:16 +00009550}
9551
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009552#define pgetc_as_macro() \
9553 (--g_parsefile->left_in_line >= 0 \
Denys Vlasenkocd716832009-11-28 22:14:02 +01009554 ? (unsigned char)*g_parsefile->next_to_pgetc++ \
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009555 : preadbuffer() \
9556 )
Denis Vlasenko727752d2008-11-28 03:41:47 +00009557
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009558static int
9559pgetc(void)
9560{
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009561 pgetc_debug("pgetc_fast at %d:%p'%s'",
9562 g_parsefile->left_in_line,
9563 g_parsefile->next_to_pgetc,
9564 g_parsefile->next_to_pgetc);
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009565 return pgetc_as_macro();
9566}
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00009567
9568#if ENABLE_ASH_OPTIMIZE_FOR_SIZE
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01009569# define pgetc_fast() pgetc()
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009570#else
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01009571# define pgetc_fast() pgetc_as_macro()
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009572#endif
9573
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009574#if ENABLE_ASH_ALIAS
9575static int
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01009576pgetc_without_PEOA(void)
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009577{
9578 int c;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009579 do {
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009580 pgetc_debug("pgetc_fast at %d:%p'%s'",
9581 g_parsefile->left_in_line,
9582 g_parsefile->next_to_pgetc,
9583 g_parsefile->next_to_pgetc);
Denis Vlasenko834dee72008-10-07 09:18:30 +00009584 c = pgetc_fast();
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009585 } while (c == PEOA);
9586 return c;
9587}
9588#else
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01009589# define pgetc_without_PEOA() pgetc()
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009590#endif
9591
9592/*
9593 * Read a line from the script.
9594 */
9595static char *
9596pfgets(char *line, int len)
9597{
9598 char *p = line;
9599 int nleft = len;
9600 int c;
9601
9602 while (--nleft > 0) {
Denys Vlasenko2ce42e92009-11-29 02:18:13 +01009603 c = pgetc_without_PEOA();
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009604 if (c == PEOF) {
9605 if (p == line)
9606 return NULL;
9607 break;
9608 }
9609 *p++ = c;
9610 if (c == '\n')
9611 break;
9612 }
9613 *p = '\0';
9614 return line;
9615}
9616
Eric Andersenc470f442003-07-28 09:56:35 +00009617/*
9618 * Undo the last call to pgetc. Only one character may be pushed back.
9619 * PEOF may be pushed back.
9620 */
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009621static void
Eric Andersenc470f442003-07-28 09:56:35 +00009622pungetc(void)
9623{
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009624 g_parsefile->left_in_line++;
9625 g_parsefile->next_to_pgetc--;
9626 pgetc_debug("pushed back to %d:%p'%s'",
9627 g_parsefile->left_in_line,
9628 g_parsefile->next_to_pgetc,
9629 g_parsefile->next_to_pgetc);
Eric Andersencb57d552001-06-28 07:25:16 +00009630}
9631
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009632/*
9633 * To handle the "." command, a stack of input files is used. Pushfile
9634 * adds a new entry to the stack and popfile restores the previous level.
9635 */
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009636static void
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009637pushfile(void)
Eric Andersenc470f442003-07-28 09:56:35 +00009638{
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009639 struct parsefile *pf;
9640
Denis Vlasenko597906c2008-02-20 16:38:54 +00009641 pf = ckzalloc(sizeof(*pf));
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009642 pf->prev = g_parsefile;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009643 pf->fd = -1;
Denis Vlasenko597906c2008-02-20 16:38:54 +00009644 /*pf->strpush = NULL; - ckzalloc did it */
9645 /*pf->basestrpush.prev = NULL;*/
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009646 g_parsefile = pf;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009647}
9648
9649static void
9650popfile(void)
9651{
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009652 struct parsefile *pf = g_parsefile;
Eric Andersenc470f442003-07-28 09:56:35 +00009653
Denis Vlasenkob012b102007-02-19 22:43:01 +00009654 INT_OFF;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009655 if (pf->fd >= 0)
9656 close(pf->fd);
Denis Vlasenko60818682007-09-28 22:07:23 +00009657 free(pf->buf);
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009658 while (pf->strpush)
9659 popstring();
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009660 g_parsefile = pf->prev;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009661 free(pf);
Denis Vlasenkob012b102007-02-19 22:43:01 +00009662 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00009663}
9664
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009665/*
9666 * Return to top level.
9667 */
9668static void
9669popallfiles(void)
9670{
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009671 while (g_parsefile != &basepf)
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009672 popfile();
9673}
9674
9675/*
9676 * Close the file(s) that the shell is reading commands from. Called
9677 * after a fork is done.
9678 */
9679static void
9680closescript(void)
9681{
9682 popallfiles();
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009683 if (g_parsefile->fd > 0) {
9684 close(g_parsefile->fd);
9685 g_parsefile->fd = 0;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009686 }
9687}
9688
9689/*
9690 * Like setinputfile, but takes an open file descriptor. Call this with
9691 * interrupts off.
9692 */
9693static void
9694setinputfd(int fd, int push)
9695{
Denis Vlasenko96e1b382007-09-30 23:50:48 +00009696 close_on_exec_on(fd);
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009697 if (push) {
9698 pushfile();
Denis Vlasenko727752d2008-11-28 03:41:47 +00009699 g_parsefile->buf = NULL;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009700 }
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009701 g_parsefile->fd = fd;
9702 if (g_parsefile->buf == NULL)
9703 g_parsefile->buf = ckmalloc(IBUFSIZ);
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009704 g_parsefile->left_in_buffer = 0;
9705 g_parsefile->left_in_line = 0;
9706 g_parsefile->linno = 1;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009707}
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009708
Eric Andersenc470f442003-07-28 09:56:35 +00009709/*
9710 * Set the input to take input from a file. If push is set, push the
9711 * old input onto the stack first.
9712 */
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009713static int
9714setinputfile(const char *fname, int flags)
Eric Andersenc470f442003-07-28 09:56:35 +00009715{
9716 int fd;
9717 int fd2;
9718
Denis Vlasenkob012b102007-02-19 22:43:01 +00009719 INT_OFF;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009720 fd = open(fname, O_RDONLY);
9721 if (fd < 0) {
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009722 if (flags & INPUT_NOFILE_OK)
9723 goto out;
Denis Vlasenko9604e1b2009-03-03 18:47:56 +00009724 ash_msg_and_raise_error("can't open '%s'", fname);
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009725 }
Eric Andersenc470f442003-07-28 09:56:35 +00009726 if (fd < 10) {
9727 fd2 = copyfd(fd, 10);
9728 close(fd);
9729 if (fd2 < 0)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00009730 ash_msg_and_raise_error("out of file descriptors");
Eric Andersenc470f442003-07-28 09:56:35 +00009731 fd = fd2;
9732 }
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009733 setinputfd(fd, flags & INPUT_PUSH_FILE);
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009734 out:
Denis Vlasenkob012b102007-02-19 22:43:01 +00009735 INT_ON;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009736 return fd;
Eric Andersenc470f442003-07-28 09:56:35 +00009737}
9738
Eric Andersencb57d552001-06-28 07:25:16 +00009739/*
9740 * Like setinputfile, but takes input from a string.
9741 */
Eric Andersenc470f442003-07-28 09:56:35 +00009742static void
9743setinputstring(char *string)
Eric Andersen62483552001-07-10 06:09:16 +00009744{
Denis Vlasenkob012b102007-02-19 22:43:01 +00009745 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +00009746 pushfile();
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009747 g_parsefile->next_to_pgetc = string;
9748 g_parsefile->left_in_line = strlen(string);
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009749 g_parsefile->buf = NULL;
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009750 g_parsefile->linno = 1;
Denis Vlasenkob012b102007-02-19 22:43:01 +00009751 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00009752}
9753
9754
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00009755/* ============ mail.c
9756 *
9757 * Routines to check for mail.
Eric Andersencb57d552001-06-28 07:25:16 +00009758 */
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00009759
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00009760#if ENABLE_ASH_MAIL
Eric Andersencb57d552001-06-28 07:25:16 +00009761
Eric Andersencb57d552001-06-28 07:25:16 +00009762#define MAXMBOXES 10
9763
Eric Andersenc470f442003-07-28 09:56:35 +00009764/* times of mailboxes */
9765static time_t mailtime[MAXMBOXES];
9766/* Set if MAIL or MAILPATH is changed. */
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +00009767static smallint mail_var_path_changed;
Eric Andersencb57d552001-06-28 07:25:16 +00009768
Eric Andersencb57d552001-06-28 07:25:16 +00009769/*
Eric Andersenc470f442003-07-28 09:56:35 +00009770 * Print appropriate message(s) if mail has arrived.
9771 * If mail_var_path_changed is set,
9772 * then the value of MAIL has mail_var_path_changed,
9773 * so we just update the values.
Eric Andersencb57d552001-06-28 07:25:16 +00009774 */
Eric Andersenc470f442003-07-28 09:56:35 +00009775static void
9776chkmail(void)
Eric Andersencb57d552001-06-28 07:25:16 +00009777{
Eric Andersencb57d552001-06-28 07:25:16 +00009778 const char *mpath;
9779 char *p;
9780 char *q;
Eric Andersenc470f442003-07-28 09:56:35 +00009781 time_t *mtp;
Eric Andersencb57d552001-06-28 07:25:16 +00009782 struct stackmark smark;
9783 struct stat statb;
9784
Eric Andersencb57d552001-06-28 07:25:16 +00009785 setstackmark(&smark);
Eric Andersenc470f442003-07-28 09:56:35 +00009786 mpath = mpathset() ? mpathval() : mailval();
9787 for (mtp = mailtime; mtp < mailtime + MAXMBOXES; mtp++) {
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02009788 p = path_advance(&mpath, nullstr);
Eric Andersencb57d552001-06-28 07:25:16 +00009789 if (p == NULL)
9790 break;
9791 if (*p == '\0')
9792 continue;
Denis Vlasenkof7d56652008-03-25 05:51:41 +00009793 for (q = p; *q; q++)
9794 continue;
Denis Vlasenkoa7189f02006-11-17 20:29:00 +00009795#if DEBUG
Eric Andersencb57d552001-06-28 07:25:16 +00009796 if (q[-1] != '/')
9797 abort();
9798#endif
Eric Andersenc470f442003-07-28 09:56:35 +00009799 q[-1] = '\0'; /* delete trailing '/' */
9800 if (stat(p, &statb) < 0) {
9801 *mtp = 0;
9802 continue;
Eric Andersencb57d552001-06-28 07:25:16 +00009803 }
Eric Andersenc470f442003-07-28 09:56:35 +00009804 if (!mail_var_path_changed && statb.st_mtime != *mtp) {
9805 fprintf(
9806 stderr, snlfmt,
9807 pathopt ? pathopt : "you have mail"
9808 );
9809 }
9810 *mtp = statb.st_mtime;
Eric Andersencb57d552001-06-28 07:25:16 +00009811 }
Eric Andersenc470f442003-07-28 09:56:35 +00009812 mail_var_path_changed = 0;
Eric Andersencb57d552001-06-28 07:25:16 +00009813 popstackmark(&smark);
9814}
Eric Andersencb57d552001-06-28 07:25:16 +00009815
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009816static void FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00009817changemail(const char *val UNUSED_PARAM)
Eric Andersenc470f442003-07-28 09:56:35 +00009818{
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +00009819 mail_var_path_changed = 1;
Eric Andersenc470f442003-07-28 09:56:35 +00009820}
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00009821
Denis Vlasenko131ae172007-02-18 13:00:19 +00009822#endif /* ASH_MAIL */
Eric Andersenc470f442003-07-28 09:56:35 +00009823
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00009824
9825/* ============ ??? */
9826
Eric Andersencb57d552001-06-28 07:25:16 +00009827/*
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009828 * Set the shell parameters.
Eric Andersencb57d552001-06-28 07:25:16 +00009829 */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009830static void
9831setparam(char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +00009832{
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009833 char **newparam;
9834 char **ap;
9835 int nparam;
Eric Andersencb57d552001-06-28 07:25:16 +00009836
Denis Vlasenkof7d56652008-03-25 05:51:41 +00009837 for (nparam = 0; argv[nparam]; nparam++)
9838 continue;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009839 ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
9840 while (*argv) {
9841 *ap++ = ckstrdup(*argv++);
Eric Andersencb57d552001-06-28 07:25:16 +00009842 }
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009843 *ap = NULL;
9844 freeparam(&shellparam);
Denis Vlasenko01631112007-12-16 17:20:38 +00009845 shellparam.malloced = 1;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009846 shellparam.nparam = nparam;
9847 shellparam.p = newparam;
9848#if ENABLE_ASH_GETOPTS
9849 shellparam.optind = 1;
9850 shellparam.optoff = -1;
9851#endif
Eric Andersencb57d552001-06-28 07:25:16 +00009852}
9853
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00009854/*
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009855 * Process shell options. The global variable argptr contains a pointer
9856 * to the argument list; we advance it past the options.
Denis Vlasenko94e87bc2008-02-14 16:51:58 +00009857 *
9858 * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
9859 * For a non-interactive shell, an error condition encountered
9860 * by a special built-in ... shall cause the shell to write a diagnostic message
9861 * to standard error and exit as shown in the following table:
Denis Vlasenko56244732008-02-17 15:14:04 +00009862 * Error Special Built-In
Denis Vlasenko94e87bc2008-02-14 16:51:58 +00009863 * ...
9864 * Utility syntax error (option or operand error) Shall exit
9865 * ...
9866 * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
9867 * we see that bash does not do that (set "finishes" with error code 1 instead,
9868 * and shell continues), and people rely on this behavior!
9869 * Testcase:
9870 * set -o barfoo 2>/dev/null
9871 * echo $?
9872 *
9873 * Oh well. Let's mimic that.
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00009874 */
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009875static int
Denis Vlasenkodddfaff2008-05-06 15:30:27 +00009876plus_minus_o(char *name, int val)
Eric Andersen62483552001-07-10 06:09:16 +00009877{
9878 int i;
9879
Denis Vlasenkoa624c112007-02-19 22:45:43 +00009880 if (name) {
9881 for (i = 0; i < NOPTS; i++) {
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00009882 if (strcmp(name, optnames(i)) == 0) {
Eric Andersenc470f442003-07-28 09:56:35 +00009883 optlist[i] = val;
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009884 return 0;
Eric Andersen62483552001-07-10 06:09:16 +00009885 }
Denis Vlasenkoa624c112007-02-19 22:45:43 +00009886 }
Denis Vlasenkodddfaff2008-05-06 15:30:27 +00009887 ash_msg("illegal option %co %s", val ? '-' : '+', name);
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009888 return 1;
Eric Andersen62483552001-07-10 06:09:16 +00009889 }
Denis Vlasenko6b06cb82008-05-15 21:30:45 +00009890 for (i = 0; i < NOPTS; i++) {
Denis Vlasenkodddfaff2008-05-06 15:30:27 +00009891 if (val) {
9892 out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
9893 } else {
9894 out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
9895 }
Denis Vlasenko6b06cb82008-05-15 21:30:45 +00009896 }
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009897 return 0;
Eric Andersen62483552001-07-10 06:09:16 +00009898}
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009899static void
9900setoption(int flag, int val)
9901{
9902 int i;
9903
9904 for (i = 0; i < NOPTS; i++) {
9905 if (optletters(i) == flag) {
9906 optlist[i] = val;
9907 return;
9908 }
9909 }
Denis Vlasenkodddfaff2008-05-06 15:30:27 +00009910 ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009911 /* NOTREACHED */
9912}
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009913static int
Eric Andersenc470f442003-07-28 09:56:35 +00009914options(int cmdline)
Eric Andersencb57d552001-06-28 07:25:16 +00009915{
9916 char *p;
9917 int val;
9918 int c;
9919
9920 if (cmdline)
9921 minusc = NULL;
9922 while ((p = *argptr) != NULL) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009923 c = *p++;
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +00009924 if (c != '-' && c != '+')
9925 break;
9926 argptr++;
9927 val = 0; /* val = 0 if c == '+' */
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009928 if (c == '-') {
Eric Andersencb57d552001-06-28 07:25:16 +00009929 val = 1;
Denis Vlasenko9f739442006-12-16 23:49:13 +00009930 if (p[0] == '\0' || LONE_DASH(p)) {
Eric Andersen2870d962001-07-02 17:27:21 +00009931 if (!cmdline) {
9932 /* "-" means turn off -x and -v */
9933 if (p[0] == '\0')
9934 xflag = vflag = 0;
9935 /* "--" means reset params */
9936 else if (*argptr == NULL)
Eric Andersencb57d552001-06-28 07:25:16 +00009937 setparam(argptr);
Eric Andersen2870d962001-07-02 17:27:21 +00009938 }
Eric Andersenc470f442003-07-28 09:56:35 +00009939 break; /* "-" or "--" terminates options */
Eric Andersencb57d552001-06-28 07:25:16 +00009940 }
Eric Andersencb57d552001-06-28 07:25:16 +00009941 }
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +00009942 /* first char was + or - */
Eric Andersencb57d552001-06-28 07:25:16 +00009943 while ((c = *p++) != '\0') {
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +00009944 /* bash 3.2 indeed handles -c CMD and +c CMD the same */
Eric Andersencb57d552001-06-28 07:25:16 +00009945 if (c == 'c' && cmdline) {
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +00009946 minusc = p; /* command is after shell args */
Eric Andersencb57d552001-06-28 07:25:16 +00009947 } else if (c == 'o') {
Denis Vlasenkodddfaff2008-05-06 15:30:27 +00009948 if (plus_minus_o(*argptr, val)) {
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009949 /* it already printed err message */
9950 return 1; /* error */
9951 }
Eric Andersencb57d552001-06-28 07:25:16 +00009952 if (*argptr)
9953 argptr++;
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +00009954 } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
9955 isloginsh = 1;
9956 /* bash does not accept +-login, we also won't */
9957 } else if (cmdline && val && (c == '-')) { /* long options */
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00009958 if (strcmp(p, "login") == 0)
Robert Griebl64f70cc2002-05-14 23:22:06 +00009959 isloginsh = 1;
9960 break;
Eric Andersencb57d552001-06-28 07:25:16 +00009961 } else {
9962 setoption(c, val);
9963 }
9964 }
9965 }
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009966 return 0;
Eric Andersencb57d552001-06-28 07:25:16 +00009967}
9968
Eric Andersencb57d552001-06-28 07:25:16 +00009969/*
Eric Andersencb57d552001-06-28 07:25:16 +00009970 * The shift builtin command.
9971 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009972static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00009973shiftcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +00009974{
9975 int n;
9976 char **ap1, **ap2;
9977
9978 n = 1;
Denis Vlasenko68404f12008-03-17 09:00:54 +00009979 if (argv[1])
Eric Andersencb57d552001-06-28 07:25:16 +00009980 n = number(argv[1]);
9981 if (n > shellparam.nparam)
Denis Vlasenkoc90e1be2008-07-30 15:35:05 +00009982 n = 0; /* bash compat, was = shellparam.nparam; */
Denis Vlasenkob012b102007-02-19 22:43:01 +00009983 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +00009984 shellparam.nparam -= n;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00009985 for (ap1 = shellparam.p; --n >= 0; ap1++) {
Denis Vlasenko01631112007-12-16 17:20:38 +00009986 if (shellparam.malloced)
Denis Vlasenkob012b102007-02-19 22:43:01 +00009987 free(*ap1);
Eric Andersencb57d552001-06-28 07:25:16 +00009988 }
9989 ap2 = shellparam.p;
Denis Vlasenkof7d56652008-03-25 05:51:41 +00009990 while ((*ap2++ = *ap1++) != NULL)
9991 continue;
Denis Vlasenko131ae172007-02-18 13:00:19 +00009992#if ENABLE_ASH_GETOPTS
Eric Andersencb57d552001-06-28 07:25:16 +00009993 shellparam.optind = 1;
9994 shellparam.optoff = -1;
Eric Andersenc470f442003-07-28 09:56:35 +00009995#endif
Denis Vlasenkob012b102007-02-19 22:43:01 +00009996 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00009997 return 0;
9998}
9999
Eric Andersencb57d552001-06-28 07:25:16 +000010000/*
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010001 * POSIX requires that 'set' (but not export or readonly) output the
10002 * variables in lexicographic order - by the locale's collating order (sigh).
10003 * Maybe we could keep them in an ordered balanced binary tree
10004 * instead of hashed lists.
10005 * For now just roll 'em through qsort for printing...
10006 */
10007static int
10008showvars(const char *sep_prefix, int on, int off)
10009{
10010 const char *sep;
10011 char **ep, **epend;
10012
10013 ep = listvars(on, off, &epend);
10014 qsort(ep, epend - ep, sizeof(char *), vpcmp);
10015
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +000010016 sep = *sep_prefix ? " " : sep_prefix;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010017
10018 for (; ep < epend; ep++) {
10019 const char *p;
10020 const char *q;
10021
10022 p = strchrnul(*ep, '=');
10023 q = nullstr;
10024 if (*p)
10025 q = single_quote(++p);
10026 out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
10027 }
10028 return 0;
10029}
10030
10031/*
Eric Andersencb57d552001-06-28 07:25:16 +000010032 * The set command builtin.
10033 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010034static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000010035setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersencb57d552001-06-28 07:25:16 +000010036{
Denis Vlasenko28bf6712008-02-14 15:01:47 +000010037 int retval;
10038
Denis Vlasenko68404f12008-03-17 09:00:54 +000010039 if (!argv[1])
Eric Andersenc470f442003-07-28 09:56:35 +000010040 return showvars(nullstr, 0, VUNSET);
Denis Vlasenkob012b102007-02-19 22:43:01 +000010041 INT_OFF;
Denis Vlasenko28bf6712008-02-14 15:01:47 +000010042 retval = 1;
10043 if (!options(0)) { /* if no parse error... */
10044 retval = 0;
10045 optschanged();
10046 if (*argptr != NULL) {
10047 setparam(argptr);
10048 }
Eric Andersencb57d552001-06-28 07:25:16 +000010049 }
Denis Vlasenkob012b102007-02-19 22:43:01 +000010050 INT_ON;
Denis Vlasenko28bf6712008-02-14 15:01:47 +000010051 return retval;
Eric Andersencb57d552001-06-28 07:25:16 +000010052}
10053
Denis Vlasenko131ae172007-02-18 13:00:19 +000010054#if ENABLE_ASH_RANDOM_SUPPORT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010055static void FAST_FUNC
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000010056change_random(const char *value)
Eric Andersenef02f822004-03-11 13:34:24 +000010057{
Denys Vlasenko3ea2e822009-10-09 20:59:04 +020010058 uint32_t t;
10059
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010060 if (value == NULL) {
Eric Andersen16767e22004-03-16 05:14:10 +000010061 /* "get", generate */
Denys Vlasenko3ea2e822009-10-09 20:59:04 +020010062 t = next_random(&random_gen);
Eric Andersen16767e22004-03-16 05:14:10 +000010063 /* set without recursion */
Denis Vlasenko448d30e2008-06-27 00:24:11 +000010064 setvar(vrandom.text, utoa(t), VNOFUNC);
Eric Andersen16767e22004-03-16 05:14:10 +000010065 vrandom.flags &= ~VNOFUNC;
10066 } else {
10067 /* set/reset */
Denys Vlasenko3ea2e822009-10-09 20:59:04 +020010068 t = strtoul(value, NULL, 10);
10069 INIT_RANDOM_T(&random_gen, (t ? t : 1), t);
Eric Andersen16767e22004-03-16 05:14:10 +000010070 }
Eric Andersenef02f822004-03-11 13:34:24 +000010071}
Eric Andersen16767e22004-03-16 05:14:10 +000010072#endif
10073
Denis Vlasenko131ae172007-02-18 13:00:19 +000010074#if ENABLE_ASH_GETOPTS
Eric Andersencb57d552001-06-28 07:25:16 +000010075static int
Eric Andersenc470f442003-07-28 09:56:35 +000010076getopts(char *optstr, char *optvar, char **optfirst, int *param_optind, int *optoff)
Eric Andersencb57d552001-06-28 07:25:16 +000010077{
10078 char *p, *q;
10079 char c = '?';
10080 int done = 0;
10081 int err = 0;
Eric Andersena48b0a32003-10-22 10:56:47 +000010082 char s[12];
10083 char **optnext;
Eric Andersencb57d552001-06-28 07:25:16 +000010084
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010085 if (*param_optind < 1)
Eric Andersena48b0a32003-10-22 10:56:47 +000010086 return 1;
10087 optnext = optfirst + *param_optind - 1;
10088
Denis Vlasenko6b06cb82008-05-15 21:30:45 +000010089 if (*param_optind <= 1 || *optoff < 0 || (int)strlen(optnext[-1]) < *optoff)
Eric Andersencb57d552001-06-28 07:25:16 +000010090 p = NULL;
10091 else
Eric Andersena48b0a32003-10-22 10:56:47 +000010092 p = optnext[-1] + *optoff;
Eric Andersencb57d552001-06-28 07:25:16 +000010093 if (p == NULL || *p == '\0') {
10094 /* Current word is done, advance */
Eric Andersencb57d552001-06-28 07:25:16 +000010095 p = *optnext;
10096 if (p == NULL || *p != '-' || *++p == '\0') {
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010097 atend:
Eric Andersencb57d552001-06-28 07:25:16 +000010098 p = NULL;
10099 done = 1;
10100 goto out;
10101 }
10102 optnext++;
Denis Vlasenko9f739442006-12-16 23:49:13 +000010103 if (LONE_DASH(p)) /* check for "--" */
Eric Andersencb57d552001-06-28 07:25:16 +000010104 goto atend;
10105 }
10106
10107 c = *p++;
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +000010108 for (q = optstr; *q != c;) {
Eric Andersencb57d552001-06-28 07:25:16 +000010109 if (*q == '\0') {
10110 if (optstr[0] == ':') {
10111 s[0] = c;
10112 s[1] = '\0';
10113 err |= setvarsafe("OPTARG", s, 0);
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010114 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000010115 fprintf(stderr, "Illegal option -%c\n", c);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010116 unsetvar("OPTARG");
Eric Andersencb57d552001-06-28 07:25:16 +000010117 }
10118 c = '?';
Eric Andersenc470f442003-07-28 09:56:35 +000010119 goto out;
Eric Andersencb57d552001-06-28 07:25:16 +000010120 }
10121 if (*++q == ':')
10122 q++;
10123 }
10124
10125 if (*++q == ':') {
10126 if (*p == '\0' && (p = *optnext) == NULL) {
10127 if (optstr[0] == ':') {
10128 s[0] = c;
10129 s[1] = '\0';
10130 err |= setvarsafe("OPTARG", s, 0);
10131 c = ':';
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010132 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000010133 fprintf(stderr, "No arg for -%c option\n", c);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010134 unsetvar("OPTARG");
Eric Andersencb57d552001-06-28 07:25:16 +000010135 c = '?';
10136 }
Eric Andersenc470f442003-07-28 09:56:35 +000010137 goto out;
Eric Andersencb57d552001-06-28 07:25:16 +000010138 }
10139
10140 if (p == *optnext)
10141 optnext++;
Eric Andersenc470f442003-07-28 09:56:35 +000010142 err |= setvarsafe("OPTARG", p, 0);
Eric Andersencb57d552001-06-28 07:25:16 +000010143 p = NULL;
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010144 } else
Eric Andersenc470f442003-07-28 09:56:35 +000010145 err |= setvarsafe("OPTARG", nullstr, 0);
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010146 out:
Eric Andersencb57d552001-06-28 07:25:16 +000010147 *optoff = p ? p - *(optnext - 1) : -1;
Eric Andersenc470f442003-07-28 09:56:35 +000010148 *param_optind = optnext - optfirst + 1;
10149 fmtstr(s, sizeof(s), "%d", *param_optind);
Eric Andersencb57d552001-06-28 07:25:16 +000010150 err |= setvarsafe("OPTIND", s, VNOFUNC);
10151 s[0] = c;
10152 s[1] = '\0';
10153 err |= setvarsafe(optvar, s, 0);
10154 if (err) {
Eric Andersenc470f442003-07-28 09:56:35 +000010155 *param_optind = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010156 *optoff = -1;
Denis Vlasenkob012b102007-02-19 22:43:01 +000010157 flush_stdout_stderr();
10158 raise_exception(EXERROR);
Eric Andersencb57d552001-06-28 07:25:16 +000010159 }
10160 return done;
10161}
Eric Andersenc470f442003-07-28 09:56:35 +000010162
10163/*
10164 * The getopts builtin. Shellparam.optnext points to the next argument
10165 * to be processed. Shellparam.optptr points to the next character to
10166 * be processed in the current argument. If shellparam.optnext is NULL,
10167 * then it's the first time getopts has been called.
10168 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010169static int FAST_FUNC
Eric Andersenc470f442003-07-28 09:56:35 +000010170getoptscmd(int argc, char **argv)
10171{
10172 char **optbase;
10173
10174 if (argc < 3)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +000010175 ash_msg_and_raise_error("usage: getopts optstring var [arg]");
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010176 if (argc == 3) {
Eric Andersenc470f442003-07-28 09:56:35 +000010177 optbase = shellparam.p;
10178 if (shellparam.optind > shellparam.nparam + 1) {
10179 shellparam.optind = 1;
10180 shellparam.optoff = -1;
10181 }
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010182 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000010183 optbase = &argv[3];
10184 if (shellparam.optind > argc - 2) {
10185 shellparam.optind = 1;
10186 shellparam.optoff = -1;
10187 }
10188 }
10189
10190 return getopts(argv[1], argv[2], optbase, &shellparam.optind,
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010191 &shellparam.optoff);
Eric Andersenc470f442003-07-28 09:56:35 +000010192}
Denis Vlasenko131ae172007-02-18 13:00:19 +000010193#endif /* ASH_GETOPTS */
Eric Andersencb57d552001-06-28 07:25:16 +000010194
Eric Andersencb57d552001-06-28 07:25:16 +000010195
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010196/* ============ Shell parser */
Eric Andersencb57d552001-06-28 07:25:16 +000010197
Denis Vlasenkob07a4962008-06-22 13:16:23 +000010198struct heredoc {
10199 struct heredoc *next; /* next here document in list */
10200 union node *here; /* redirection node */
10201 char *eofmark; /* string indicating end of input */
10202 smallint striptabs; /* if set, strip leading tabs */
10203};
10204
10205static smallint tokpushback; /* last token pushed back */
10206static smallint parsebackquote; /* nonzero if we are inside backquotes */
10207static smallint quoteflag; /* set if (part of) last token was quoted */
10208static token_id_t lasttoken; /* last token read (integer id Txxx) */
10209static struct heredoc *heredoclist; /* list of here documents to read */
10210static char *wordtext; /* text of last word returned by readtoken */
10211static struct nodelist *backquotelist;
10212static union node *redirnode;
10213static struct heredoc *heredoc;
Denis Vlasenko99eb8502007-02-23 21:09:49 +000010214
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010215/*
10216 * Called when an unexpected token is read during the parse. The argument
10217 * is the token that is expected, or -1 if more than one type of token can
10218 * occur at this point.
10219 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000010220static void raise_error_unexpected_syntax(int) NORETURN;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010221static void
10222raise_error_unexpected_syntax(int token)
10223{
10224 char msg[64];
10225 int l;
10226
Denis Vlasenko7b2294e2008-11-28 03:50:46 +000010227 l = sprintf(msg, "unexpected %s", tokname(lasttoken));
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010228 if (token >= 0)
10229 sprintf(msg + l, " (expecting %s)", tokname(token));
10230 raise_error_syntax(msg);
10231 /* NOTREACHED */
10232}
Eric Andersencb57d552001-06-28 07:25:16 +000010233
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010234#define EOFMARKLEN 79
Eric Andersencb57d552001-06-28 07:25:16 +000010235
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010236/* parsing is heavily cross-recursive, need these forward decls */
10237static union node *andor(void);
10238static union node *pipeline(void);
10239static union node *parse_command(void);
10240static void parseheredoc(void);
10241static char peektoken(void);
10242static int readtoken(void);
Eric Andersencb57d552001-06-28 07:25:16 +000010243
Eric Andersenc470f442003-07-28 09:56:35 +000010244static union node *
10245list(int nlflag)
Eric Andersencb57d552001-06-28 07:25:16 +000010246{
10247 union node *n1, *n2, *n3;
10248 int tok;
10249
Eric Andersenc470f442003-07-28 09:56:35 +000010250 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10251 if (nlflag == 2 && peektoken())
Eric Andersencb57d552001-06-28 07:25:16 +000010252 return NULL;
10253 n1 = NULL;
10254 for (;;) {
10255 n2 = andor();
10256 tok = readtoken();
10257 if (tok == TBACKGND) {
Eric Andersenc470f442003-07-28 09:56:35 +000010258 if (n2->type == NPIPE) {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +000010259 n2->npipe.pipe_backgnd = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010260 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000010261 if (n2->type != NREDIR) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010262 n3 = stzalloc(sizeof(struct nredir));
Eric Andersenc470f442003-07-28 09:56:35 +000010263 n3->nredir.n = n2;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010264 /*n3->nredir.redirect = NULL; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000010265 n2 = n3;
10266 }
10267 n2->type = NBACKGND;
Eric Andersencb57d552001-06-28 07:25:16 +000010268 }
10269 }
10270 if (n1 == NULL) {
10271 n1 = n2;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010272 } else {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010273 n3 = stzalloc(sizeof(struct nbinary));
Eric Andersencb57d552001-06-28 07:25:16 +000010274 n3->type = NSEMI;
10275 n3->nbinary.ch1 = n1;
10276 n3->nbinary.ch2 = n2;
10277 n1 = n3;
10278 }
10279 switch (tok) {
10280 case TBACKGND:
10281 case TSEMI:
10282 tok = readtoken();
10283 /* fall through */
10284 case TNL:
10285 if (tok == TNL) {
10286 parseheredoc();
Eric Andersenc470f442003-07-28 09:56:35 +000010287 if (nlflag == 1)
Eric Andersencb57d552001-06-28 07:25:16 +000010288 return n1;
10289 } else {
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010290 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010291 }
Eric Andersenc470f442003-07-28 09:56:35 +000010292 checkkwd = CHKNL | CHKKWD | CHKALIAS;
Manuel Novoa III 16815d42001-08-10 19:36:07 +000010293 if (peektoken())
Eric Andersencb57d552001-06-28 07:25:16 +000010294 return n1;
10295 break;
10296 case TEOF:
10297 if (heredoclist)
10298 parseheredoc();
10299 else
Eric Andersenc470f442003-07-28 09:56:35 +000010300 pungetc(); /* push back EOF on input */
Eric Andersencb57d552001-06-28 07:25:16 +000010301 return n1;
10302 default:
Eric Andersenc470f442003-07-28 09:56:35 +000010303 if (nlflag == 1)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010304 raise_error_unexpected_syntax(-1);
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010305 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010306 return n1;
10307 }
10308 }
10309}
10310
Eric Andersenc470f442003-07-28 09:56:35 +000010311static union node *
10312andor(void)
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010313{
Eric Andersencb57d552001-06-28 07:25:16 +000010314 union node *n1, *n2, *n3;
10315 int t;
10316
Eric Andersencb57d552001-06-28 07:25:16 +000010317 n1 = pipeline();
10318 for (;;) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010319 t = readtoken();
10320 if (t == TAND) {
Eric Andersencb57d552001-06-28 07:25:16 +000010321 t = NAND;
10322 } else if (t == TOR) {
10323 t = NOR;
10324 } else {
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010325 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010326 return n1;
10327 }
Eric Andersenc470f442003-07-28 09:56:35 +000010328 checkkwd = CHKNL | CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010329 n2 = pipeline();
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010330 n3 = stzalloc(sizeof(struct nbinary));
Eric Andersencb57d552001-06-28 07:25:16 +000010331 n3->type = t;
10332 n3->nbinary.ch1 = n1;
10333 n3->nbinary.ch2 = n2;
10334 n1 = n3;
10335 }
10336}
10337
Eric Andersenc470f442003-07-28 09:56:35 +000010338static union node *
10339pipeline(void)
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010340{
Eric Andersencb57d552001-06-28 07:25:16 +000010341 union node *n1, *n2, *pipenode;
10342 struct nodelist *lp, *prev;
10343 int negate;
10344
10345 negate = 0;
10346 TRACE(("pipeline: entered\n"));
10347 if (readtoken() == TNOT) {
10348 negate = !negate;
Eric Andersenc470f442003-07-28 09:56:35 +000010349 checkkwd = CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010350 } else
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010351 tokpushback = 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010352 n1 = parse_command();
Eric Andersencb57d552001-06-28 07:25:16 +000010353 if (readtoken() == TPIPE) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010354 pipenode = stzalloc(sizeof(struct npipe));
Eric Andersencb57d552001-06-28 07:25:16 +000010355 pipenode->type = NPIPE;
Denis Vlasenko2dc240c2008-07-24 06:07:50 +000010356 /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010357 lp = stzalloc(sizeof(struct nodelist));
Eric Andersencb57d552001-06-28 07:25:16 +000010358 pipenode->npipe.cmdlist = lp;
10359 lp->n = n1;
10360 do {
10361 prev = lp;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010362 lp = stzalloc(sizeof(struct nodelist));
Eric Andersenc470f442003-07-28 09:56:35 +000010363 checkkwd = CHKNL | CHKKWD | CHKALIAS;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010364 lp->n = parse_command();
Eric Andersencb57d552001-06-28 07:25:16 +000010365 prev->next = lp;
10366 } while (readtoken() == TPIPE);
10367 lp->next = NULL;
10368 n1 = pipenode;
10369 }
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010370 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010371 if (negate) {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010372 n2 = stzalloc(sizeof(struct nnot));
Eric Andersencb57d552001-06-28 07:25:16 +000010373 n2->type = NNOT;
10374 n2->nnot.com = n1;
10375 return n2;
Denis Vlasenko2da584f2007-02-19 22:44:05 +000010376 }
10377 return n1;
Eric Andersencb57d552001-06-28 07:25:16 +000010378}
10379
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010380static union node *
10381makename(void)
10382{
10383 union node *n;
10384
Denis Vlasenko597906c2008-02-20 16:38:54 +000010385 n = stzalloc(sizeof(struct narg));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010386 n->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010387 /*n->narg.next = NULL; - stzalloc did it */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010388 n->narg.text = wordtext;
10389 n->narg.backquote = backquotelist;
10390 return n;
10391}
10392
10393static void
10394fixredir(union node *n, const char *text, int err)
10395{
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000010396 int fd;
10397
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010398 TRACE(("Fix redir %s %d\n", text, err));
10399 if (!err)
10400 n->ndup.vname = NULL;
10401
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000010402 fd = bb_strtou(text, NULL, 10);
10403 if (!errno && fd >= 0)
10404 n->ndup.dupfd = fd;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010405 else if (LONE_DASH(text))
10406 n->ndup.dupfd = -1;
10407 else {
10408 if (err)
Denis Vlasenko559691a2008-10-05 18:39:31 +000010409 raise_error_syntax("bad fd number");
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010410 n->ndup.vname = makename();
10411 }
10412}
10413
10414/*
10415 * Returns true if the text contains nothing to expand (no dollar signs
10416 * or backquotes).
10417 */
10418static int
Denis Vlasenko68819d12008-12-15 11:26:36 +000010419noexpand(const char *text)
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010420{
Denys Vlasenkocd716832009-11-28 22:14:02 +010010421 unsigned char c;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010422
Denys Vlasenkocd716832009-11-28 22:14:02 +010010423 while ((c = *text++) != '\0') {
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010424 if (c == CTLQUOTEMARK)
10425 continue;
10426 if (c == CTLESC)
Denys Vlasenkocd716832009-11-28 22:14:02 +010010427 text++;
Denys Vlasenko76bc2d62009-11-29 01:37:46 +010010428 else if (SIT(c, BASESYNTAX) == CCTL)
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010429 return 0;
10430 }
10431 return 1;
10432}
10433
10434static void
10435parsefname(void)
10436{
10437 union node *n = redirnode;
10438
10439 if (readtoken() != TWORD)
10440 raise_error_unexpected_syntax(-1);
10441 if (n->type == NHERE) {
10442 struct heredoc *here = heredoc;
10443 struct heredoc *p;
10444 int i;
10445
10446 if (quoteflag == 0)
10447 n->type = NXHERE;
10448 TRACE(("Here document %d\n", n->type));
10449 if (!noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
Denis Vlasenko559691a2008-10-05 18:39:31 +000010450 raise_error_syntax("illegal eof marker for << redirection");
Denys Vlasenkob6c84342009-08-29 20:23:20 +020010451 rmescapes(wordtext, 0);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010452 here->eofmark = wordtext;
10453 here->next = NULL;
10454 if (heredoclist == NULL)
10455 heredoclist = here;
10456 else {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010457 for (p = heredoclist; p->next; p = p->next)
10458 continue;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010459 p->next = here;
10460 }
10461 } else if (n->type == NTOFD || n->type == NFROMFD) {
10462 fixredir(n, wordtext, 0);
10463 } else {
10464 n->nfile.fname = makename();
10465 }
10466}
Eric Andersencb57d552001-06-28 07:25:16 +000010467
Eric Andersenc470f442003-07-28 09:56:35 +000010468static union node *
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010469simplecmd(void)
10470{
10471 union node *args, **app;
10472 union node *n = NULL;
10473 union node *vars, **vpp;
10474 union node **rpp, *redir;
10475 int savecheckkwd;
Denis Vlasenko80591b02008-03-25 07:49:43 +000010476#if ENABLE_ASH_BASH_COMPAT
10477 smallint double_brackets_flag = 0;
10478#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010479
10480 args = NULL;
10481 app = &args;
10482 vars = NULL;
10483 vpp = &vars;
10484 redir = NULL;
10485 rpp = &redir;
10486
10487 savecheckkwd = CHKALIAS;
10488 for (;;) {
Denis Vlasenko80591b02008-03-25 07:49:43 +000010489 int t;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010490 checkkwd = savecheckkwd;
Denis Vlasenko80591b02008-03-25 07:49:43 +000010491 t = readtoken();
10492 switch (t) {
10493#if ENABLE_ASH_BASH_COMPAT
10494 case TAND: /* "&&" */
10495 case TOR: /* "||" */
10496 if (!double_brackets_flag) {
10497 tokpushback = 1;
10498 goto out;
10499 }
10500 wordtext = (char *) (t == TAND ? "-a" : "-o");
10501#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010502 case TWORD:
Denis Vlasenko597906c2008-02-20 16:38:54 +000010503 n = stzalloc(sizeof(struct narg));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010504 n->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010505 /*n->narg.next = NULL; - stzalloc did it */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010506 n->narg.text = wordtext;
Denis Vlasenko80591b02008-03-25 07:49:43 +000010507#if ENABLE_ASH_BASH_COMPAT
10508 if (strcmp("[[", wordtext) == 0)
10509 double_brackets_flag = 1;
10510 else if (strcmp("]]", wordtext) == 0)
10511 double_brackets_flag = 0;
10512#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010513 n->narg.backquote = backquotelist;
10514 if (savecheckkwd && isassignment(wordtext)) {
10515 *vpp = n;
10516 vpp = &n->narg.next;
10517 } else {
10518 *app = n;
10519 app = &n->narg.next;
10520 savecheckkwd = 0;
10521 }
10522 break;
10523 case TREDIR:
10524 *rpp = n = redirnode;
10525 rpp = &n->nfile.next;
10526 parsefname(); /* read name of redirection file */
10527 break;
10528 case TLP:
10529 if (args && app == &args->narg.next
10530 && !vars && !redir
10531 ) {
10532 struct builtincmd *bcmd;
10533 const char *name;
10534
10535 /* We have a function */
10536 if (readtoken() != TRP)
10537 raise_error_unexpected_syntax(TRP);
10538 name = n->narg.text;
10539 if (!goodname(name)
10540 || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
10541 ) {
Denis Vlasenko559691a2008-10-05 18:39:31 +000010542 raise_error_syntax("bad function name");
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010543 }
10544 n->type = NDEFUN;
10545 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10546 n->narg.next = parse_command();
10547 return n;
10548 }
10549 /* fall through */
10550 default:
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010551 tokpushback = 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010552 goto out;
10553 }
10554 }
10555 out:
10556 *app = NULL;
10557 *vpp = NULL;
10558 *rpp = NULL;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010559 n = stzalloc(sizeof(struct ncmd));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010560 n->type = NCMD;
10561 n->ncmd.args = args;
10562 n->ncmd.assign = vars;
10563 n->ncmd.redirect = redir;
10564 return n;
10565}
10566
10567static union node *
10568parse_command(void)
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010569{
Eric Andersencb57d552001-06-28 07:25:16 +000010570 union node *n1, *n2;
10571 union node *ap, **app;
10572 union node *cp, **cpp;
10573 union node *redir, **rpp;
Eric Andersenc470f442003-07-28 09:56:35 +000010574 union node **rpp2;
Eric Andersencb57d552001-06-28 07:25:16 +000010575 int t;
10576
10577 redir = NULL;
Eric Andersenc470f442003-07-28 09:56:35 +000010578 rpp2 = &redir;
Eric Andersen88cec252001-09-06 17:35:20 +000010579
Eric Andersencb57d552001-06-28 07:25:16 +000010580 switch (readtoken()) {
Eric Andersenc470f442003-07-28 09:56:35 +000010581 default:
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010582 raise_error_unexpected_syntax(-1);
Eric Andersenc470f442003-07-28 09:56:35 +000010583 /* NOTREACHED */
Eric Andersencb57d552001-06-28 07:25:16 +000010584 case TIF:
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010585 n1 = stzalloc(sizeof(struct nif));
Eric Andersencb57d552001-06-28 07:25:16 +000010586 n1->type = NIF;
10587 n1->nif.test = list(0);
10588 if (readtoken() != TTHEN)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010589 raise_error_unexpected_syntax(TTHEN);
Eric Andersencb57d552001-06-28 07:25:16 +000010590 n1->nif.ifpart = list(0);
10591 n2 = n1;
10592 while (readtoken() == TELIF) {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010593 n2->nif.elsepart = stzalloc(sizeof(struct nif));
Eric Andersencb57d552001-06-28 07:25:16 +000010594 n2 = n2->nif.elsepart;
10595 n2->type = NIF;
10596 n2->nif.test = list(0);
10597 if (readtoken() != TTHEN)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010598 raise_error_unexpected_syntax(TTHEN);
Eric Andersencb57d552001-06-28 07:25:16 +000010599 n2->nif.ifpart = list(0);
10600 }
10601 if (lasttoken == TELSE)
10602 n2->nif.elsepart = list(0);
10603 else {
10604 n2->nif.elsepart = NULL;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010605 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010606 }
Eric Andersenc470f442003-07-28 09:56:35 +000010607 t = TFI;
Eric Andersencb57d552001-06-28 07:25:16 +000010608 break;
10609 case TWHILE:
Eric Andersenc470f442003-07-28 09:56:35 +000010610 case TUNTIL: {
Eric Andersencb57d552001-06-28 07:25:16 +000010611 int got;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010612 n1 = stzalloc(sizeof(struct nbinary));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010613 n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
Eric Andersencb57d552001-06-28 07:25:16 +000010614 n1->nbinary.ch1 = list(0);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010615 got = readtoken();
10616 if (got != TDO) {
Denis Vlasenko131ae172007-02-18 13:00:19 +000010617 TRACE(("expecting DO got %s %s\n", tokname(got),
10618 got == TWORD ? wordtext : ""));
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010619 raise_error_unexpected_syntax(TDO);
Eric Andersencb57d552001-06-28 07:25:16 +000010620 }
10621 n1->nbinary.ch2 = list(0);
Eric Andersenc470f442003-07-28 09:56:35 +000010622 t = TDONE;
Eric Andersencb57d552001-06-28 07:25:16 +000010623 break;
10624 }
10625 case TFOR:
Denis Vlasenko2dc240c2008-07-24 06:07:50 +000010626 if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
Denis Vlasenko559691a2008-10-05 18:39:31 +000010627 raise_error_syntax("bad for loop variable");
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010628 n1 = stzalloc(sizeof(struct nfor));
Eric Andersencb57d552001-06-28 07:25:16 +000010629 n1->type = NFOR;
10630 n1->nfor.var = wordtext;
Eric Andersenc470f442003-07-28 09:56:35 +000010631 checkkwd = CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010632 if (readtoken() == TIN) {
10633 app = &ap;
10634 while (readtoken() == TWORD) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010635 n2 = stzalloc(sizeof(struct narg));
Eric Andersencb57d552001-06-28 07:25:16 +000010636 n2->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010637 /*n2->narg.next = NULL; - stzalloc did it */
Eric Andersencb57d552001-06-28 07:25:16 +000010638 n2->narg.text = wordtext;
10639 n2->narg.backquote = backquotelist;
10640 *app = n2;
10641 app = &n2->narg.next;
10642 }
10643 *app = NULL;
10644 n1->nfor.args = ap;
10645 if (lasttoken != TNL && lasttoken != TSEMI)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010646 raise_error_unexpected_syntax(-1);
Eric Andersencb57d552001-06-28 07:25:16 +000010647 } else {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010648 n2 = stzalloc(sizeof(struct narg));
Eric Andersencb57d552001-06-28 07:25:16 +000010649 n2->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010650 /*n2->narg.next = NULL; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000010651 n2->narg.text = (char *)dolatstr;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010652 /*n2->narg.backquote = NULL;*/
Eric Andersencb57d552001-06-28 07:25:16 +000010653 n1->nfor.args = n2;
10654 /*
10655 * Newline or semicolon here is optional (but note
10656 * that the original Bourne shell only allowed NL).
10657 */
10658 if (lasttoken != TNL && lasttoken != TSEMI)
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010659 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010660 }
Eric Andersenc470f442003-07-28 09:56:35 +000010661 checkkwd = CHKNL | CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010662 if (readtoken() != TDO)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010663 raise_error_unexpected_syntax(TDO);
Eric Andersencb57d552001-06-28 07:25:16 +000010664 n1->nfor.body = list(0);
Eric Andersenc470f442003-07-28 09:56:35 +000010665 t = TDONE;
Eric Andersencb57d552001-06-28 07:25:16 +000010666 break;
10667 case TCASE:
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010668 n1 = stzalloc(sizeof(struct ncase));
Eric Andersencb57d552001-06-28 07:25:16 +000010669 n1->type = NCASE;
10670 if (readtoken() != TWORD)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010671 raise_error_unexpected_syntax(TWORD);
Denis Vlasenko597906c2008-02-20 16:38:54 +000010672 n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
Eric Andersencb57d552001-06-28 07:25:16 +000010673 n2->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010674 /*n2->narg.next = NULL; - stzalloc did it */
Eric Andersencb57d552001-06-28 07:25:16 +000010675 n2->narg.text = wordtext;
10676 n2->narg.backquote = backquotelist;
Eric Andersencb57d552001-06-28 07:25:16 +000010677 do {
Eric Andersenc470f442003-07-28 09:56:35 +000010678 checkkwd = CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010679 } while (readtoken() == TNL);
10680 if (lasttoken != TIN)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010681 raise_error_unexpected_syntax(TIN);
Eric Andersencb57d552001-06-28 07:25:16 +000010682 cpp = &n1->ncase.cases;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010683 next_case:
Eric Andersenc470f442003-07-28 09:56:35 +000010684 checkkwd = CHKNL | CHKKWD;
10685 t = readtoken();
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010686 while (t != TESAC) {
Eric Andersencb57d552001-06-28 07:25:16 +000010687 if (lasttoken == TLP)
10688 readtoken();
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010689 *cpp = cp = stzalloc(sizeof(struct nclist));
Eric Andersencb57d552001-06-28 07:25:16 +000010690 cp->type = NCLIST;
10691 app = &cp->nclist.pattern;
10692 for (;;) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010693 *app = ap = stzalloc(sizeof(struct narg));
Eric Andersencb57d552001-06-28 07:25:16 +000010694 ap->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010695 /*ap->narg.next = NULL; - stzalloc did it */
Eric Andersencb57d552001-06-28 07:25:16 +000010696 ap->narg.text = wordtext;
10697 ap->narg.backquote = backquotelist;
Eric Andersenc470f442003-07-28 09:56:35 +000010698 if (readtoken() != TPIPE)
Eric Andersencb57d552001-06-28 07:25:16 +000010699 break;
10700 app = &ap->narg.next;
10701 readtoken();
10702 }
Denis Vlasenko597906c2008-02-20 16:38:54 +000010703 //ap->narg.next = NULL;
Eric Andersencb57d552001-06-28 07:25:16 +000010704 if (lasttoken != TRP)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010705 raise_error_unexpected_syntax(TRP);
Eric Andersenc470f442003-07-28 09:56:35 +000010706 cp->nclist.body = list(2);
Eric Andersencb57d552001-06-28 07:25:16 +000010707
Eric Andersenc470f442003-07-28 09:56:35 +000010708 cpp = &cp->nclist.next;
10709
10710 checkkwd = CHKNL | CHKKWD;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010711 t = readtoken();
10712 if (t != TESAC) {
Eric Andersencb57d552001-06-28 07:25:16 +000010713 if (t != TENDCASE)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010714 raise_error_unexpected_syntax(TENDCASE);
10715 goto next_case;
Eric Andersencb57d552001-06-28 07:25:16 +000010716 }
Eric Andersenc470f442003-07-28 09:56:35 +000010717 }
Eric Andersencb57d552001-06-28 07:25:16 +000010718 *cpp = NULL;
Eric Andersenc470f442003-07-28 09:56:35 +000010719 goto redir;
Eric Andersencb57d552001-06-28 07:25:16 +000010720 case TLP:
Denis Vlasenko597906c2008-02-20 16:38:54 +000010721 n1 = stzalloc(sizeof(struct nredir));
Eric Andersencb57d552001-06-28 07:25:16 +000010722 n1->type = NSUBSHELL;
10723 n1->nredir.n = list(0);
Denis Vlasenko597906c2008-02-20 16:38:54 +000010724 /*n1->nredir.redirect = NULL; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000010725 t = TRP;
Eric Andersencb57d552001-06-28 07:25:16 +000010726 break;
10727 case TBEGIN:
10728 n1 = list(0);
Eric Andersenc470f442003-07-28 09:56:35 +000010729 t = TEND;
Eric Andersencb57d552001-06-28 07:25:16 +000010730 break;
Eric Andersencb57d552001-06-28 07:25:16 +000010731 case TWORD:
Eric Andersenc470f442003-07-28 09:56:35 +000010732 case TREDIR:
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010733 tokpushback = 1;
Eric Andersenc470f442003-07-28 09:56:35 +000010734 return simplecmd();
Eric Andersencb57d552001-06-28 07:25:16 +000010735 }
10736
Eric Andersenc470f442003-07-28 09:56:35 +000010737 if (readtoken() != t)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010738 raise_error_unexpected_syntax(t);
Eric Andersenc470f442003-07-28 09:56:35 +000010739
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010740 redir:
Eric Andersencb57d552001-06-28 07:25:16 +000010741 /* Now check for redirection which may follow command */
Eric Andersenc470f442003-07-28 09:56:35 +000010742 checkkwd = CHKKWD | CHKALIAS;
10743 rpp = rpp2;
Eric Andersencb57d552001-06-28 07:25:16 +000010744 while (readtoken() == TREDIR) {
10745 *rpp = n2 = redirnode;
10746 rpp = &n2->nfile.next;
10747 parsefname();
10748 }
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010749 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010750 *rpp = NULL;
10751 if (redir) {
10752 if (n1->type != NSUBSHELL) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010753 n2 = stzalloc(sizeof(struct nredir));
Eric Andersencb57d552001-06-28 07:25:16 +000010754 n2->type = NREDIR;
10755 n2->nredir.n = n1;
10756 n1 = n2;
10757 }
10758 n1->nredir.redirect = redir;
10759 }
Eric Andersencb57d552001-06-28 07:25:16 +000010760 return n1;
10761}
10762
Denis Vlasenkoef527f52008-06-23 01:52:30 +000010763#if ENABLE_ASH_BASH_COMPAT
10764static int decode_dollar_squote(void)
10765{
10766 static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
10767 int c, cnt;
10768 char *p;
10769 char buf[4];
10770
10771 c = pgetc();
10772 p = strchr(C_escapes, c);
10773 if (p) {
10774 buf[0] = c;
10775 p = buf;
10776 cnt = 3;
10777 if ((unsigned char)(c - '0') <= 7) { /* \ooo */
10778 do {
10779 c = pgetc();
10780 *++p = c;
10781 } while ((unsigned char)(c - '0') <= 7 && --cnt);
10782 pungetc();
10783 } else if (c == 'x') { /* \xHH */
10784 do {
10785 c = pgetc();
10786 *++p = c;
10787 } while (isxdigit(c) && --cnt);
10788 pungetc();
10789 if (cnt == 3) { /* \x but next char is "bad" */
10790 c = 'x';
10791 goto unrecognized;
10792 }
10793 } else { /* simple seq like \\ or \t */
10794 p++;
10795 }
10796 *p = '\0';
10797 p = buf;
10798 c = bb_process_escape_sequence((void*)&p);
10799 } else { /* unrecognized "\z": print both chars unless ' or " */
10800 if (c != '\'' && c != '"') {
10801 unrecognized:
10802 c |= 0x100; /* "please encode \, then me" */
10803 }
10804 }
10805 return c;
10806}
10807#endif
10808
Eric Andersencb57d552001-06-28 07:25:16 +000010809/*
10810 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
10811 * is not NULL, read a here document. In the latter case, eofmark is the
10812 * word which marks the end of the document and striptabs is true if
Denys Vlasenkocd716832009-11-28 22:14:02 +010010813 * leading tabs should be stripped from the document. The argument c
Eric Andersencb57d552001-06-28 07:25:16 +000010814 * is the first character of the input token or document.
10815 *
10816 * Because C does not have internal subroutines, I have simulated them
10817 * using goto's to implement the subroutine linkage. The following macros
10818 * will run code that appears at the end of readtoken1.
10819 */
Eric Andersen2870d962001-07-02 17:27:21 +000010820#define CHECKEND() {goto checkend; checkend_return:;}
10821#define PARSEREDIR() {goto parseredir; parseredir_return:;}
10822#define PARSESUB() {goto parsesub; parsesub_return:;}
10823#define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
10824#define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
10825#define PARSEARITH() {goto parsearith; parsearith_return:;}
Eric Andersencb57d552001-06-28 07:25:16 +000010826static int
Denys Vlasenkocd716832009-11-28 22:14:02 +010010827readtoken1(int c, int syntax, char *eofmark, int striptabs)
Manuel Novoa III 16815d42001-08-10 19:36:07 +000010828{
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010829 /* NB: syntax parameter fits into smallint */
Denys Vlasenkocd716832009-11-28 22:14:02 +010010830 /* c parameter is an unsigned char or PEOF or PEOA */
Eric Andersencb57d552001-06-28 07:25:16 +000010831 char *out;
10832 int len;
10833 char line[EOFMARKLEN + 1];
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010834 struct nodelist *bqlist;
10835 smallint quotef;
10836 smallint dblquote;
10837 smallint oldstyle;
10838 smallint prevsyntax; /* syntax before arithmetic */
Denis Vlasenko46a53062007-09-24 18:30:02 +000010839#if ENABLE_ASH_EXPAND_PRMT
10840 smallint pssyntax; /* we are expanding a prompt string */
10841#endif
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010842 int varnest; /* levels of variables expansion */
10843 int arinest; /* levels of arithmetic expansion */
10844 int parenlevel; /* levels of parens in arithmetic */
10845 int dqvarnest; /* levels of variables expansion within double quotes */
10846
Denis Vlasenko5e34ff22009-04-21 11:09:40 +000010847 IF_ASH_BASH_COMPAT(smallint bash_dollar_squote = 0;)
Denis Vlasenkoef527f52008-06-23 01:52:30 +000010848
Eric Andersencb57d552001-06-28 07:25:16 +000010849#if __GNUC__
10850 /* Avoid longjmp clobbering */
10851 (void) &out;
10852 (void) &quotef;
10853 (void) &dblquote;
10854 (void) &varnest;
10855 (void) &arinest;
10856 (void) &parenlevel;
10857 (void) &dqvarnest;
10858 (void) &oldstyle;
10859 (void) &prevsyntax;
10860 (void) &syntax;
10861#endif
Denis Vlasenko41eb3002008-11-28 03:42:31 +000010862 startlinno = g_parsefile->linno;
Eric Andersencb57d552001-06-28 07:25:16 +000010863 bqlist = NULL;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010864 quotef = 0;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010865 oldstyle = 0;
10866 prevsyntax = 0;
Denis Vlasenko46a53062007-09-24 18:30:02 +000010867#if ENABLE_ASH_EXPAND_PRMT
10868 pssyntax = (syntax == PSSYNTAX);
10869 if (pssyntax)
10870 syntax = DQSYNTAX;
10871#endif
10872 dblquote = (syntax == DQSYNTAX);
Eric Andersencb57d552001-06-28 07:25:16 +000010873 varnest = 0;
10874 arinest = 0;
10875 parenlevel = 0;
10876 dqvarnest = 0;
10877
10878 STARTSTACKSTR(out);
Denis Vlasenko176d49d2008-10-06 09:51:47 +000010879 loop:
10880 /* For each line, until end of word */
10881 {
Eric Andersenc470f442003-07-28 09:56:35 +000010882 CHECKEND(); /* set c to PEOF if at end of here document */
10883 for (;;) { /* until end of line or end of word */
10884 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
Denis Vlasenkobf0a2012006-12-26 10:42:51 +000010885 switch (SIT(c, syntax)) {
Eric Andersenc470f442003-07-28 09:56:35 +000010886 case CNL: /* '\n' */
Eric Andersencb57d552001-06-28 07:25:16 +000010887 if (syntax == BASESYNTAX)
Eric Andersenc470f442003-07-28 09:56:35 +000010888 goto endword; /* exit outer loop */
Eric Andersencb57d552001-06-28 07:25:16 +000010889 USTPUTC(c, out);
Denis Vlasenko41eb3002008-11-28 03:42:31 +000010890 g_parsefile->linno++;
Eric Andersencb57d552001-06-28 07:25:16 +000010891 if (doprompt)
10892 setprompt(2);
Eric Andersencb57d552001-06-28 07:25:16 +000010893 c = pgetc();
Eric Andersenc470f442003-07-28 09:56:35 +000010894 goto loop; /* continue outer loop */
Eric Andersencb57d552001-06-28 07:25:16 +000010895 case CWORD:
10896 USTPUTC(c, out);
10897 break;
10898 case CCTL:
Eric Andersenc470f442003-07-28 09:56:35 +000010899 if (eofmark == NULL || dblquote)
Eric Andersencb57d552001-06-28 07:25:16 +000010900 USTPUTC(CTLESC, out);
Denis Vlasenkoef527f52008-06-23 01:52:30 +000010901#if ENABLE_ASH_BASH_COMPAT
10902 if (c == '\\' && bash_dollar_squote) {
10903 c = decode_dollar_squote();
10904 if (c & 0x100) {
10905 USTPUTC('\\', out);
10906 c = (unsigned char)c;
10907 }
10908 }
10909#endif
Eric Andersencb57d552001-06-28 07:25:16 +000010910 USTPUTC(c, out);
10911 break;
Eric Andersenc470f442003-07-28 09:56:35 +000010912 case CBACK: /* backslash */
Denys Vlasenko2ce42e92009-11-29 02:18:13 +010010913 c = pgetc_without_PEOA();
Eric Andersencb57d552001-06-28 07:25:16 +000010914 if (c == PEOF) {
Eric Andersenc470f442003-07-28 09:56:35 +000010915 USTPUTC(CTLESC, out);
Eric Andersencb57d552001-06-28 07:25:16 +000010916 USTPUTC('\\', out);
10917 pungetc();
10918 } else if (c == '\n') {
10919 if (doprompt)
10920 setprompt(2);
Eric Andersencb57d552001-06-28 07:25:16 +000010921 } else {
Denis Vlasenko46a53062007-09-24 18:30:02 +000010922#if ENABLE_ASH_EXPAND_PRMT
10923 if (c == '$' && pssyntax) {
10924 USTPUTC(CTLESC, out);
10925 USTPUTC('\\', out);
10926 }
10927#endif
Denis Vlasenkoef527f52008-06-23 01:52:30 +000010928 if (dblquote && c != '\\'
10929 && c != '`' && c != '$'
10930 && (c != '"' || eofmark != NULL)
Eric Andersenc470f442003-07-28 09:56:35 +000010931 ) {
10932 USTPUTC(CTLESC, out);
Eric Andersencb57d552001-06-28 07:25:16 +000010933 USTPUTC('\\', out);
Eric Andersenc470f442003-07-28 09:56:35 +000010934 }
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010935 if (SIT(c, SQSYNTAX) == CCTL)
Eric Andersencb57d552001-06-28 07:25:16 +000010936 USTPUTC(CTLESC, out);
Eric Andersencb57d552001-06-28 07:25:16 +000010937 USTPUTC(c, out);
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010938 quotef = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010939 }
10940 break;
10941 case CSQUOTE:
Eric Andersencb57d552001-06-28 07:25:16 +000010942 syntax = SQSYNTAX;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010943 quotemark:
Eric Andersenc470f442003-07-28 09:56:35 +000010944 if (eofmark == NULL) {
10945 USTPUTC(CTLQUOTEMARK, out);
10946 }
Eric Andersencb57d552001-06-28 07:25:16 +000010947 break;
10948 case CDQUOTE:
Eric Andersencb57d552001-06-28 07:25:16 +000010949 syntax = DQSYNTAX;
10950 dblquote = 1;
Eric Andersenc470f442003-07-28 09:56:35 +000010951 goto quotemark;
Eric Andersencb57d552001-06-28 07:25:16 +000010952 case CENDQUOTE:
Denis Vlasenko5e34ff22009-04-21 11:09:40 +000010953 IF_ASH_BASH_COMPAT(bash_dollar_squote = 0;)
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010954 if (eofmark != NULL && arinest == 0
10955 && varnest == 0
10956 ) {
Eric Andersencb57d552001-06-28 07:25:16 +000010957 USTPUTC(c, out);
10958 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000010959 if (dqvarnest == 0) {
Eric Andersencb57d552001-06-28 07:25:16 +000010960 syntax = BASESYNTAX;
10961 dblquote = 0;
10962 }
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010963 quotef = 1;
Eric Andersenc470f442003-07-28 09:56:35 +000010964 goto quotemark;
Eric Andersencb57d552001-06-28 07:25:16 +000010965 }
10966 break;
Eric Andersenc470f442003-07-28 09:56:35 +000010967 case CVAR: /* '$' */
10968 PARSESUB(); /* parse substitution */
Eric Andersencb57d552001-06-28 07:25:16 +000010969 break;
Eric Andersenc470f442003-07-28 09:56:35 +000010970 case CENDVAR: /* '}' */
Eric Andersencb57d552001-06-28 07:25:16 +000010971 if (varnest > 0) {
10972 varnest--;
10973 if (dqvarnest > 0) {
10974 dqvarnest--;
10975 }
10976 USTPUTC(CTLENDVAR, out);
10977 } else {
10978 USTPUTC(c, out);
10979 }
10980 break;
Mike Frysinger98c52642009-04-02 10:02:37 +000010981#if ENABLE_SH_MATH_SUPPORT
Eric Andersenc470f442003-07-28 09:56:35 +000010982 case CLP: /* '(' in arithmetic */
Eric Andersencb57d552001-06-28 07:25:16 +000010983 parenlevel++;
10984 USTPUTC(c, out);
10985 break;
Eric Andersenc470f442003-07-28 09:56:35 +000010986 case CRP: /* ')' in arithmetic */
Eric Andersencb57d552001-06-28 07:25:16 +000010987 if (parenlevel > 0) {
10988 USTPUTC(c, out);
10989 --parenlevel;
10990 } else {
10991 if (pgetc() == ')') {
10992 if (--arinest == 0) {
10993 USTPUTC(CTLENDARI, out);
10994 syntax = prevsyntax;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010995 dblquote = (syntax == DQSYNTAX);
Eric Andersencb57d552001-06-28 07:25:16 +000010996 } else
10997 USTPUTC(')', out);
10998 } else {
10999 /*
11000 * unbalanced parens
11001 * (don't 2nd guess - no error)
11002 */
11003 pungetc();
11004 USTPUTC(')', out);
11005 }
11006 }
11007 break;
11008#endif
Eric Andersenc470f442003-07-28 09:56:35 +000011009 case CBQUOTE: /* '`' */
Eric Andersencb57d552001-06-28 07:25:16 +000011010 PARSEBACKQOLD();
11011 break;
Eric Andersen2870d962001-07-02 17:27:21 +000011012 case CENDFILE:
Eric Andersenc470f442003-07-28 09:56:35 +000011013 goto endword; /* exit outer loop */
Eric Andersencb57d552001-06-28 07:25:16 +000011014 case CIGN:
11015 break;
11016 default:
Denis Vlasenko834dee72008-10-07 09:18:30 +000011017 if (varnest == 0) {
11018#if ENABLE_ASH_BASH_COMPAT
11019 if (c == '&') {
11020 if (pgetc() == '>')
11021 c = 0x100 + '>'; /* flag &> */
11022 pungetc();
11023 }
11024#endif
Eric Andersenc470f442003-07-28 09:56:35 +000011025 goto endword; /* exit outer loop */
Denis Vlasenko834dee72008-10-07 09:18:30 +000011026 }
Denys Vlasenko2ce42e92009-11-29 02:18:13 +010011027 IF_ASH_ALIAS(if (c != PEOA))
Eric Andersencb57d552001-06-28 07:25:16 +000011028 USTPUTC(c, out);
Eric Andersen3102ac42001-07-06 04:26:23 +000011029
Eric Andersencb57d552001-06-28 07:25:16 +000011030 }
Denis Vlasenko834dee72008-10-07 09:18:30 +000011031 c = pgetc_fast();
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000011032 } /* for (;;) */
Eric Andersencb57d552001-06-28 07:25:16 +000011033 }
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011034 endword:
Mike Frysinger98c52642009-04-02 10:02:37 +000011035#if ENABLE_SH_MATH_SUPPORT
Eric Andersencb57d552001-06-28 07:25:16 +000011036 if (syntax == ARISYNTAX)
Denis Vlasenko559691a2008-10-05 18:39:31 +000011037 raise_error_syntax("missing '))'");
Eric Andersenc470f442003-07-28 09:56:35 +000011038#endif
Denis Vlasenko99eb8502007-02-23 21:09:49 +000011039 if (syntax != BASESYNTAX && !parsebackquote && eofmark == NULL)
Denis Vlasenko559691a2008-10-05 18:39:31 +000011040 raise_error_syntax("unterminated quoted string");
Eric Andersencb57d552001-06-28 07:25:16 +000011041 if (varnest != 0) {
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011042 startlinno = g_parsefile->linno;
Eric Andersenc470f442003-07-28 09:56:35 +000011043 /* { */
Denis Vlasenko559691a2008-10-05 18:39:31 +000011044 raise_error_syntax("missing '}'");
Eric Andersencb57d552001-06-28 07:25:16 +000011045 }
11046 USTPUTC('\0', out);
Eric Andersenc470f442003-07-28 09:56:35 +000011047 len = out - (char *)stackblock();
Eric Andersencb57d552001-06-28 07:25:16 +000011048 out = stackblock();
11049 if (eofmark == NULL) {
Denis Vlasenko5e34ff22009-04-21 11:09:40 +000011050 if ((c == '>' || c == '<' IF_ASH_BASH_COMPAT( || c == 0x100 + '>'))
Denis Vlasenko834dee72008-10-07 09:18:30 +000011051 && quotef == 0
11052 ) {
Denis Vlasenko559691a2008-10-05 18:39:31 +000011053 if (isdigit_str9(out)) {
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000011054 PARSEREDIR(); /* passed as params: out, c */
11055 lasttoken = TREDIR;
11056 return lasttoken;
11057 }
11058 /* else: non-number X seen, interpret it
11059 * as "NNNX>file" = "NNNX >file" */
Eric Andersencb57d552001-06-28 07:25:16 +000011060 }
Denis Vlasenkoef527f52008-06-23 01:52:30 +000011061 pungetc();
Eric Andersencb57d552001-06-28 07:25:16 +000011062 }
11063 quoteflag = quotef;
11064 backquotelist = bqlist;
11065 grabstackblock(len);
11066 wordtext = out;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011067 lasttoken = TWORD;
11068 return lasttoken;
Eric Andersencb57d552001-06-28 07:25:16 +000011069/* end of readtoken routine */
11070
Eric Andersencb57d552001-06-28 07:25:16 +000011071/*
11072 * Check to see whether we are at the end of the here document. When this
11073 * is called, c is set to the first character of the next input line. If
11074 * we are at the end of the here document, this routine sets the c to PEOF.
11075 */
Eric Andersenc470f442003-07-28 09:56:35 +000011076checkend: {
11077 if (eofmark) {
Denis Vlasenko131ae172007-02-18 13:00:19 +000011078#if ENABLE_ASH_ALIAS
Denys Vlasenko2ce42e92009-11-29 02:18:13 +010011079 if (c == PEOA)
11080 c = pgetc_without_PEOA();
Eric Andersenc470f442003-07-28 09:56:35 +000011081#endif
11082 if (striptabs) {
11083 while (c == '\t') {
Denys Vlasenko2ce42e92009-11-29 02:18:13 +010011084 c = pgetc_without_PEOA();
Eric Andersencb57d552001-06-28 07:25:16 +000011085 }
Eric Andersenc470f442003-07-28 09:56:35 +000011086 }
11087 if (c == *eofmark) {
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011088 if (pfgets(line, sizeof(line)) != NULL) {
Eric Andersenc470f442003-07-28 09:56:35 +000011089 char *p, *q;
Eric Andersencb57d552001-06-28 07:25:16 +000011090
Eric Andersenc470f442003-07-28 09:56:35 +000011091 p = line;
Denis Vlasenkof7d56652008-03-25 05:51:41 +000011092 for (q = eofmark + 1; *q && *p == *q; p++, q++)
11093 continue;
Eric Andersenc470f442003-07-28 09:56:35 +000011094 if (*p == '\n' && *q == '\0') {
11095 c = PEOF;
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011096 g_parsefile->linno++;
Eric Andersenc470f442003-07-28 09:56:35 +000011097 needprompt = doprompt;
11098 } else {
11099 pushstring(line, NULL);
Eric Andersencb57d552001-06-28 07:25:16 +000011100 }
11101 }
11102 }
11103 }
Eric Andersenc470f442003-07-28 09:56:35 +000011104 goto checkend_return;
11105}
Eric Andersencb57d552001-06-28 07:25:16 +000011106
Eric Andersencb57d552001-06-28 07:25:16 +000011107/*
11108 * Parse a redirection operator. The variable "out" points to a string
11109 * specifying the fd to be redirected. The variable "c" contains the
11110 * first character of the redirection operator.
11111 */
Eric Andersenc470f442003-07-28 09:56:35 +000011112parseredir: {
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000011113 /* out is already checked to be a valid number or "" */
11114 int fd = (*out == '\0' ? -1 : atoi(out));
Eric Andersenc470f442003-07-28 09:56:35 +000011115 union node *np;
Eric Andersencb57d552001-06-28 07:25:16 +000011116
Denis Vlasenko597906c2008-02-20 16:38:54 +000011117 np = stzalloc(sizeof(struct nfile));
Eric Andersenc470f442003-07-28 09:56:35 +000011118 if (c == '>') {
11119 np->nfile.fd = 1;
11120 c = pgetc();
11121 if (c == '>')
11122 np->type = NAPPEND;
11123 else if (c == '|')
11124 np->type = NCLOBBER;
11125 else if (c == '&')
11126 np->type = NTOFD;
Denis Vlasenko559691a2008-10-05 18:39:31 +000011127 /* it also can be NTO2 (>&file), but we can't figure it out yet */
Eric Andersenc470f442003-07-28 09:56:35 +000011128 else {
11129 np->type = NTO;
11130 pungetc();
Eric Andersencb57d552001-06-28 07:25:16 +000011131 }
Denis Vlasenko834dee72008-10-07 09:18:30 +000011132 }
11133#if ENABLE_ASH_BASH_COMPAT
11134 else if (c == 0x100 + '>') { /* this flags &> redirection */
11135 np->nfile.fd = 1;
11136 pgetc(); /* this is '>', no need to check */
11137 np->type = NTO2;
11138 }
11139#endif
11140 else { /* c == '<' */
Denis Vlasenko597906c2008-02-20 16:38:54 +000011141 /*np->nfile.fd = 0; - stzalloc did it */
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011142 c = pgetc();
11143 switch (c) {
Eric Andersenc470f442003-07-28 09:56:35 +000011144 case '<':
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011145 if (sizeof(struct nfile) != sizeof(struct nhere)) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000011146 np = stzalloc(sizeof(struct nhere));
11147 /*np->nfile.fd = 0; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000011148 }
11149 np->type = NHERE;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000011150 heredoc = stzalloc(sizeof(struct heredoc));
Eric Andersenc470f442003-07-28 09:56:35 +000011151 heredoc->here = np;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011152 c = pgetc();
11153 if (c == '-') {
Eric Andersenc470f442003-07-28 09:56:35 +000011154 heredoc->striptabs = 1;
11155 } else {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000011156 /*heredoc->striptabs = 0; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000011157 pungetc();
11158 }
11159 break;
11160
11161 case '&':
11162 np->type = NFROMFD;
11163 break;
11164
11165 case '>':
11166 np->type = NFROMTO;
11167 break;
11168
11169 default:
11170 np->type = NFROM;
11171 pungetc();
11172 break;
11173 }
Eric Andersencb57d552001-06-28 07:25:16 +000011174 }
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000011175 if (fd >= 0)
11176 np->nfile.fd = fd;
Eric Andersenc470f442003-07-28 09:56:35 +000011177 redirnode = np;
11178 goto parseredir_return;
11179}
Eric Andersencb57d552001-06-28 07:25:16 +000011180
Eric Andersencb57d552001-06-28 07:25:16 +000011181/*
11182 * Parse a substitution. At this point, we have read the dollar sign
11183 * and nothing else.
11184 */
Denis Vlasenkocc571512007-02-23 21:10:35 +000011185
11186/* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
11187 * (assuming ascii char codes, as the original implementation did) */
11188#define is_special(c) \
Denis Vlasenkoef527f52008-06-23 01:52:30 +000011189 (((unsigned)(c) - 33 < 32) \
11190 && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
Eric Andersenc470f442003-07-28 09:56:35 +000011191parsesub: {
Denys Vlasenkocd716832009-11-28 22:14:02 +010011192 unsigned char subtype;
Eric Andersenc470f442003-07-28 09:56:35 +000011193 int typeloc;
11194 int flags;
11195 char *p;
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011196 static const char types[] ALIGN1 = "}-+?=";
Eric Andersencb57d552001-06-28 07:25:16 +000011197
Eric Andersenc470f442003-07-28 09:56:35 +000011198 c = pgetc();
Denys Vlasenkocd716832009-11-28 22:14:02 +010011199 if (c > 255 /* PEOA or PEOF */
Denis Vlasenkoef527f52008-06-23 01:52:30 +000011200 || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
Eric Andersenc470f442003-07-28 09:56:35 +000011201 ) {
Denis Vlasenkoef527f52008-06-23 01:52:30 +000011202#if ENABLE_ASH_BASH_COMPAT
11203 if (c == '\'')
11204 bash_dollar_squote = 1;
11205 else
11206#endif
11207 USTPUTC('$', out);
Eric Andersenc470f442003-07-28 09:56:35 +000011208 pungetc();
11209 } else if (c == '(') { /* $(command) or $((arith)) */
11210 if (pgetc() == '(') {
Mike Frysinger98c52642009-04-02 10:02:37 +000011211#if ENABLE_SH_MATH_SUPPORT
Eric Andersenc470f442003-07-28 09:56:35 +000011212 PARSEARITH();
11213#else
Mike Frysinger98a6f562008-06-09 09:38:45 +000011214 raise_error_syntax("you disabled math support for $((arith)) syntax");
Eric Andersenc470f442003-07-28 09:56:35 +000011215#endif
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000011216 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000011217 pungetc();
11218 PARSEBACKQNEW();
11219 }
11220 } else {
11221 USTPUTC(CTLVAR, out);
11222 typeloc = out - (char *)stackblock();
11223 USTPUTC(VSNORMAL, out);
11224 subtype = VSNORMAL;
11225 if (c == '{') {
11226 c = pgetc();
11227 if (c == '#') {
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011228 c = pgetc();
11229 if (c == '}')
Eric Andersenc470f442003-07-28 09:56:35 +000011230 c = '#';
11231 else
11232 subtype = VSLENGTH;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011233 } else
Eric Andersenc470f442003-07-28 09:56:35 +000011234 subtype = 0;
11235 }
Denys Vlasenkocd716832009-11-28 22:14:02 +010011236 if (c <= 255 /* not PEOA or PEOF */ && is_name(c)) {
Eric Andersenc470f442003-07-28 09:56:35 +000011237 do {
11238 STPUTC(c, out);
Eric Andersencb57d552001-06-28 07:25:16 +000011239 c = pgetc();
Denys Vlasenkocd716832009-11-28 22:14:02 +010011240 } while (c <= 255 /* not PEOA or PEOF */ && is_in_name(c));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011241 } else if (isdigit(c)) {
Eric Andersenc470f442003-07-28 09:56:35 +000011242 do {
11243 STPUTC(c, out);
11244 c = pgetc();
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011245 } while (isdigit(c));
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011246 } else if (is_special(c)) {
Eric Andersenc470f442003-07-28 09:56:35 +000011247 USTPUTC(c, out);
11248 c = pgetc();
Denis Vlasenko559691a2008-10-05 18:39:31 +000011249 } else {
11250 badsub:
11251 raise_error_syntax("bad substitution");
11252 }
Cristian Ionescu-Idbohrn301f5ec2009-10-05 02:07:23 +020011253 if (c != '}' && subtype == VSLENGTH)
11254 goto badsub;
Eric Andersencb57d552001-06-28 07:25:16 +000011255
Eric Andersenc470f442003-07-28 09:56:35 +000011256 STPUTC('=', out);
11257 flags = 0;
11258 if (subtype == 0) {
11259 switch (c) {
11260 case ':':
Eric Andersenc470f442003-07-28 09:56:35 +000011261 c = pgetc();
Denis Vlasenko92e13c22008-03-25 01:17:40 +000011262#if ENABLE_ASH_BASH_COMPAT
11263 if (c == ':' || c == '$' || isdigit(c)) {
11264 pungetc();
11265 subtype = VSSUBSTR;
11266 break;
11267 }
11268#endif
11269 flags = VSNUL;
Eric Andersenc470f442003-07-28 09:56:35 +000011270 /*FALLTHROUGH*/
11271 default:
11272 p = strchr(types, c);
11273 if (p == NULL)
11274 goto badsub;
11275 subtype = p - types + VSNORMAL;
11276 break;
11277 case '%':
Denis Vlasenko92e13c22008-03-25 01:17:40 +000011278 case '#': {
11279 int cc = c;
11280 subtype = c == '#' ? VSTRIMLEFT : VSTRIMRIGHT;
11281 c = pgetc();
11282 if (c == cc)
11283 subtype++;
11284 else
11285 pungetc();
11286 break;
11287 }
11288#if ENABLE_ASH_BASH_COMPAT
11289 case '/':
11290 subtype = VSREPLACE;
11291 c = pgetc();
11292 if (c == '/')
11293 subtype++; /* VSREPLACEALL */
11294 else
11295 pungetc();
11296 break;
11297#endif
Eric Andersencb57d552001-06-28 07:25:16 +000011298 }
Eric Andersenc470f442003-07-28 09:56:35 +000011299 } else {
11300 pungetc();
11301 }
11302 if (dblquote || arinest)
11303 flags |= VSQUOTE;
Denys Vlasenkocd716832009-11-28 22:14:02 +010011304 ((unsigned char *)stackblock())[typeloc] = subtype | flags;
Eric Andersenc470f442003-07-28 09:56:35 +000011305 if (subtype != VSNORMAL) {
11306 varnest++;
11307 if (dblquote || arinest) {
11308 dqvarnest++;
Eric Andersencb57d552001-06-28 07:25:16 +000011309 }
11310 }
11311 }
Eric Andersenc470f442003-07-28 09:56:35 +000011312 goto parsesub_return;
11313}
Eric Andersencb57d552001-06-28 07:25:16 +000011314
Eric Andersencb57d552001-06-28 07:25:16 +000011315/*
11316 * Called to parse command substitutions. Newstyle is set if the command
11317 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
11318 * list of commands (passed by reference), and savelen is the number of
11319 * characters on the top of the stack which must be preserved.
11320 */
Eric Andersenc470f442003-07-28 09:56:35 +000011321parsebackq: {
11322 struct nodelist **nlpp;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011323 smallint savepbq;
Eric Andersenc470f442003-07-28 09:56:35 +000011324 union node *n;
11325 char *volatile str;
11326 struct jmploc jmploc;
11327 struct jmploc *volatile savehandler;
11328 size_t savelen;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011329 smallint saveprompt = 0;
11330
Eric Andersencb57d552001-06-28 07:25:16 +000011331#ifdef __GNUC__
Eric Andersenc470f442003-07-28 09:56:35 +000011332 (void) &saveprompt;
Eric Andersencb57d552001-06-28 07:25:16 +000011333#endif
Eric Andersenc470f442003-07-28 09:56:35 +000011334 savepbq = parsebackquote;
11335 if (setjmp(jmploc.loc)) {
Denis Vlasenko60818682007-09-28 22:07:23 +000011336 free(str);
Eric Andersenc470f442003-07-28 09:56:35 +000011337 parsebackquote = 0;
Denis Vlasenko2da584f2007-02-19 22:44:05 +000011338 exception_handler = savehandler;
11339 longjmp(exception_handler->loc, 1);
Eric Andersenc470f442003-07-28 09:56:35 +000011340 }
Denis Vlasenkob012b102007-02-19 22:43:01 +000011341 INT_OFF;
Eric Andersenc470f442003-07-28 09:56:35 +000011342 str = NULL;
11343 savelen = out - (char *)stackblock();
11344 if (savelen > 0) {
11345 str = ckmalloc(savelen);
11346 memcpy(str, stackblock(), savelen);
11347 }
Denis Vlasenko2da584f2007-02-19 22:44:05 +000011348 savehandler = exception_handler;
11349 exception_handler = &jmploc;
Denis Vlasenkob012b102007-02-19 22:43:01 +000011350 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +000011351 if (oldstyle) {
11352 /* We must read until the closing backquote, giving special
11353 treatment to some slashes, and then push the string and
11354 reread it as input, interpreting it normally. */
11355 char *pout;
11356 int pc;
11357 size_t psavelen;
11358 char *pstr;
11359
11360
11361 STARTSTACKSTR(pout);
11362 for (;;) {
11363 if (needprompt) {
11364 setprompt(2);
Eric Andersenc470f442003-07-28 09:56:35 +000011365 }
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011366 pc = pgetc();
11367 switch (pc) {
Eric Andersenc470f442003-07-28 09:56:35 +000011368 case '`':
11369 goto done;
11370
11371 case '\\':
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011372 pc = pgetc();
11373 if (pc == '\n') {
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011374 g_parsefile->linno++;
Eric Andersenc470f442003-07-28 09:56:35 +000011375 if (doprompt)
11376 setprompt(2);
11377 /*
11378 * If eating a newline, avoid putting
11379 * the newline into the new character
11380 * stream (via the STPUTC after the
11381 * switch).
11382 */
11383 continue;
11384 }
11385 if (pc != '\\' && pc != '`' && pc != '$'
Denys Vlasenko76bc2d62009-11-29 01:37:46 +010011386 && (!dblquote || pc != '"')
11387 ) {
Eric Andersenc470f442003-07-28 09:56:35 +000011388 STPUTC('\\', pout);
Denys Vlasenko76bc2d62009-11-29 01:37:46 +010011389 }
Denys Vlasenkocd716832009-11-28 22:14:02 +010011390 if (pc <= 255 /* not PEOA or PEOF */) {
Eric Andersenc470f442003-07-28 09:56:35 +000011391 break;
11392 }
11393 /* fall through */
11394
11395 case PEOF:
Denys Vlasenko2ce42e92009-11-29 02:18:13 +010011396 IF_ASH_ALIAS(case PEOA:)
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011397 startlinno = g_parsefile->linno;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000011398 raise_error_syntax("EOF in backquote substitution");
Eric Andersenc470f442003-07-28 09:56:35 +000011399
11400 case '\n':
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011401 g_parsefile->linno++;
Eric Andersenc470f442003-07-28 09:56:35 +000011402 needprompt = doprompt;
11403 break;
11404
11405 default:
11406 break;
11407 }
11408 STPUTC(pc, pout);
11409 }
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011410 done:
Eric Andersenc470f442003-07-28 09:56:35 +000011411 STPUTC('\0', pout);
11412 psavelen = pout - (char *)stackblock();
11413 if (psavelen > 0) {
11414 pstr = grabstackstr(pout);
11415 setinputstring(pstr);
11416 }
11417 }
11418 nlpp = &bqlist;
11419 while (*nlpp)
11420 nlpp = &(*nlpp)->next;
Denis Vlasenko597906c2008-02-20 16:38:54 +000011421 *nlpp = stzalloc(sizeof(**nlpp));
11422 /* (*nlpp)->next = NULL; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000011423 parsebackquote = oldstyle;
11424
11425 if (oldstyle) {
11426 saveprompt = doprompt;
11427 doprompt = 0;
Eric Andersencb57d552001-06-28 07:25:16 +000011428 }
11429
Eric Andersenc470f442003-07-28 09:56:35 +000011430 n = list(2);
11431
11432 if (oldstyle)
11433 doprompt = saveprompt;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011434 else if (readtoken() != TRP)
11435 raise_error_unexpected_syntax(TRP);
Eric Andersenc470f442003-07-28 09:56:35 +000011436
11437 (*nlpp)->n = n;
11438 if (oldstyle) {
11439 /*
11440 * Start reading from old file again, ignoring any pushed back
11441 * tokens left from the backquote parsing
11442 */
11443 popfile();
11444 tokpushback = 0;
11445 }
11446 while (stackblocksize() <= savelen)
11447 growstackblock();
11448 STARTSTACKSTR(out);
11449 if (str) {
11450 memcpy(out, str, savelen);
11451 STADJUST(savelen, out);
Denis Vlasenkob012b102007-02-19 22:43:01 +000011452 INT_OFF;
11453 free(str);
Eric Andersenc470f442003-07-28 09:56:35 +000011454 str = NULL;
Denis Vlasenkob012b102007-02-19 22:43:01 +000011455 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +000011456 }
11457 parsebackquote = savepbq;
Denis Vlasenko2da584f2007-02-19 22:44:05 +000011458 exception_handler = savehandler;
Eric Andersenc470f442003-07-28 09:56:35 +000011459 if (arinest || dblquote)
11460 USTPUTC(CTLBACKQ | CTLQUOTE, out);
11461 else
11462 USTPUTC(CTLBACKQ, out);
11463 if (oldstyle)
11464 goto parsebackq_oldreturn;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000011465 goto parsebackq_newreturn;
Eric Andersenc470f442003-07-28 09:56:35 +000011466}
11467
Mike Frysinger98c52642009-04-02 10:02:37 +000011468#if ENABLE_SH_MATH_SUPPORT
Eric Andersencb57d552001-06-28 07:25:16 +000011469/*
11470 * Parse an arithmetic expansion (indicate start of one and set state)
11471 */
Eric Andersenc470f442003-07-28 09:56:35 +000011472parsearith: {
Eric Andersenc470f442003-07-28 09:56:35 +000011473 if (++arinest == 1) {
11474 prevsyntax = syntax;
11475 syntax = ARISYNTAX;
11476 USTPUTC(CTLARI, out);
11477 if (dblquote)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000011478 USTPUTC('"', out);
Eric Andersenc470f442003-07-28 09:56:35 +000011479 else
Denis Vlasenkoa624c112007-02-19 22:45:43 +000011480 USTPUTC(' ', out);
Eric Andersenc470f442003-07-28 09:56:35 +000011481 } else {
11482 /*
11483 * we collapse embedded arithmetic expansion to
11484 * parenthesis, which should be equivalent
11485 */
11486 USTPUTC('(', out);
Eric Andersencb57d552001-06-28 07:25:16 +000011487 }
Eric Andersenc470f442003-07-28 09:56:35 +000011488 goto parsearith_return;
11489}
11490#endif
Eric Andersencb57d552001-06-28 07:25:16 +000011491
Eric Andersenc470f442003-07-28 09:56:35 +000011492} /* end of readtoken */
11493
Eric Andersencb57d552001-06-28 07:25:16 +000011494/*
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011495 * Read the next input token.
11496 * If the token is a word, we set backquotelist to the list of cmds in
11497 * backquotes. We set quoteflag to true if any part of the word was
11498 * quoted.
11499 * If the token is TREDIR, then we set redirnode to a structure containing
11500 * the redirection.
11501 * In all cases, the variable startlinno is set to the number of the line
11502 * on which the token starts.
11503 *
11504 * [Change comment: here documents and internal procedures]
11505 * [Readtoken shouldn't have any arguments. Perhaps we should make the
11506 * word parsing code into a separate routine. In this case, readtoken
11507 * doesn't need to have any internal procedures, but parseword does.
11508 * We could also make parseoperator in essence the main routine, and
11509 * have parseword (readtoken1?) handle both words and redirection.]
Eric Andersencb57d552001-06-28 07:25:16 +000011510 */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011511#define NEW_xxreadtoken
11512#ifdef NEW_xxreadtoken
11513/* singles must be first! */
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011514static const char xxreadtoken_chars[7] ALIGN1 = {
Denis Vlasenko834dee72008-10-07 09:18:30 +000011515 '\n', '(', ')', /* singles */
11516 '&', '|', ';', /* doubles */
11517 0
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011518};
Eric Andersencb57d552001-06-28 07:25:16 +000011519
Denis Vlasenko834dee72008-10-07 09:18:30 +000011520#define xxreadtoken_singles 3
11521#define xxreadtoken_doubles 3
11522
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011523static const char xxreadtoken_tokens[] ALIGN1 = {
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011524 TNL, TLP, TRP, /* only single occurrence allowed */
11525 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
11526 TEOF, /* corresponds to trailing nul */
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011527 TAND, TOR, TENDCASE /* if double occurrence */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011528};
11529
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011530static int
11531xxreadtoken(void)
11532{
11533 int c;
11534
11535 if (tokpushback) {
11536 tokpushback = 0;
11537 return lasttoken;
Eric Andersencb57d552001-06-28 07:25:16 +000011538 }
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011539 if (needprompt) {
11540 setprompt(2);
11541 }
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011542 startlinno = g_parsefile->linno;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011543 for (;;) { /* until token or start of word found */
Denis Vlasenko834dee72008-10-07 09:18:30 +000011544 c = pgetc_fast();
Denis Vlasenko5e34ff22009-04-21 11:09:40 +000011545 if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011546 continue;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011547
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011548 if (c == '#') {
11549 while ((c = pgetc()) != '\n' && c != PEOF)
11550 continue;
11551 pungetc();
11552 } else if (c == '\\') {
11553 if (pgetc() != '\n') {
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011554 pungetc();
Denis Vlasenko834dee72008-10-07 09:18:30 +000011555 break; /* return readtoken1(...) */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011556 }
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011557 startlinno = ++g_parsefile->linno;
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011558 if (doprompt)
11559 setprompt(2);
11560 } else {
11561 const char *p;
11562
11563 p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
11564 if (c != PEOF) {
11565 if (c == '\n') {
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011566 g_parsefile->linno++;
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011567 needprompt = doprompt;
11568 }
11569
11570 p = strchr(xxreadtoken_chars, c);
Denis Vlasenko834dee72008-10-07 09:18:30 +000011571 if (p == NULL)
11572 break; /* return readtoken1(...) */
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011573
Denis Vlasenko834dee72008-10-07 09:18:30 +000011574 if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
11575 int cc = pgetc();
11576 if (cc == c) { /* double occurrence? */
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011577 p += xxreadtoken_doubles + 1;
11578 } else {
11579 pungetc();
Denis Vlasenko834dee72008-10-07 09:18:30 +000011580#if ENABLE_ASH_BASH_COMPAT
11581 if (c == '&' && cc == '>') /* &> */
11582 break; /* return readtoken1(...) */
11583#endif
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011584 }
11585 }
11586 }
11587 lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
11588 return lasttoken;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011589 }
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011590 } /* for (;;) */
Denis Vlasenko834dee72008-10-07 09:18:30 +000011591
11592 return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011593}
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011594#else /* old xxreadtoken */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011595#define RETURN(token) return lasttoken = token
11596static int
11597xxreadtoken(void)
11598{
11599 int c;
11600
11601 if (tokpushback) {
11602 tokpushback = 0;
11603 return lasttoken;
11604 }
11605 if (needprompt) {
11606 setprompt(2);
11607 }
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011608 startlinno = g_parsefile->linno;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011609 for (;;) { /* until token or start of word found */
Denis Vlasenko834dee72008-10-07 09:18:30 +000011610 c = pgetc_fast();
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011611 switch (c) {
11612 case ' ': case '\t':
Denys Vlasenko2ce42e92009-11-29 02:18:13 +010011613 IF_ASH_ALIAS(case PEOA:)
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011614 continue;
11615 case '#':
Denis Vlasenkof7d56652008-03-25 05:51:41 +000011616 while ((c = pgetc()) != '\n' && c != PEOF)
11617 continue;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011618 pungetc();
11619 continue;
11620 case '\\':
11621 if (pgetc() == '\n') {
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011622 startlinno = ++g_parsefile->linno;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011623 if (doprompt)
11624 setprompt(2);
11625 continue;
11626 }
11627 pungetc();
11628 goto breakloop;
11629 case '\n':
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011630 g_parsefile->linno++;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011631 needprompt = doprompt;
11632 RETURN(TNL);
11633 case PEOF:
11634 RETURN(TEOF);
11635 case '&':
11636 if (pgetc() == '&')
11637 RETURN(TAND);
11638 pungetc();
11639 RETURN(TBACKGND);
11640 case '|':
11641 if (pgetc() == '|')
11642 RETURN(TOR);
11643 pungetc();
11644 RETURN(TPIPE);
11645 case ';':
11646 if (pgetc() == ';')
11647 RETURN(TENDCASE);
11648 pungetc();
11649 RETURN(TSEMI);
11650 case '(':
11651 RETURN(TLP);
11652 case ')':
11653 RETURN(TRP);
11654 default:
11655 goto breakloop;
11656 }
11657 }
11658 breakloop:
11659 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
11660#undef RETURN
11661}
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011662#endif /* old xxreadtoken */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011663
11664static int
11665readtoken(void)
11666{
11667 int t;
11668#if DEBUG
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011669 smallint alreadyseen = tokpushback;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011670#endif
11671
11672#if ENABLE_ASH_ALIAS
11673 top:
11674#endif
11675
11676 t = xxreadtoken();
11677
11678 /*
11679 * eat newlines
11680 */
11681 if (checkkwd & CHKNL) {
11682 while (t == TNL) {
11683 parseheredoc();
11684 t = xxreadtoken();
11685 }
11686 }
11687
11688 if (t != TWORD || quoteflag) {
11689 goto out;
11690 }
11691
11692 /*
11693 * check for keywords
11694 */
11695 if (checkkwd & CHKKWD) {
11696 const char *const *pp;
11697
11698 pp = findkwd(wordtext);
11699 if (pp) {
11700 lasttoken = t = pp - tokname_array;
11701 TRACE(("keyword %s recognized\n", tokname(t)));
11702 goto out;
11703 }
11704 }
11705
11706 if (checkkwd & CHKALIAS) {
11707#if ENABLE_ASH_ALIAS
11708 struct alias *ap;
11709 ap = lookupalias(wordtext, 1);
11710 if (ap != NULL) {
11711 if (*ap->val) {
11712 pushstring(ap->val, ap);
11713 }
11714 goto top;
11715 }
11716#endif
11717 }
11718 out:
11719 checkkwd = 0;
11720#if DEBUG
11721 if (!alreadyseen)
11722 TRACE(("token %s %s\n", tokname(t), t == TWORD ? wordtext : ""));
11723 else
11724 TRACE(("reread token %s %s\n", tokname(t), t == TWORD ? wordtext : ""));
11725#endif
11726 return t;
Eric Andersencb57d552001-06-28 07:25:16 +000011727}
11728
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011729static char
11730peektoken(void)
11731{
11732 int t;
11733
11734 t = readtoken();
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011735 tokpushback = 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011736 return tokname_array[t][0];
11737}
Eric Andersencb57d552001-06-28 07:25:16 +000011738
11739/*
Denys Vlasenko86e83ec2009-07-23 22:07:07 +020011740 * Read and parse a command. Returns NODE_EOF on end of file.
11741 * (NULL is a valid parse tree indicating a blank line.)
Eric Andersencb57d552001-06-28 07:25:16 +000011742 */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011743static union node *
11744parsecmd(int interact)
Eric Andersen90898442003-08-06 11:20:52 +000011745{
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011746 int t;
Eric Andersencb57d552001-06-28 07:25:16 +000011747
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011748 tokpushback = 0;
11749 doprompt = interact;
11750 if (doprompt)
11751 setprompt(doprompt);
11752 needprompt = 0;
11753 t = readtoken();
11754 if (t == TEOF)
Denys Vlasenko86e83ec2009-07-23 22:07:07 +020011755 return NODE_EOF;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011756 if (t == TNL)
11757 return NULL;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011758 tokpushback = 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011759 return list(1);
11760}
11761
11762/*
11763 * Input any here documents.
11764 */
11765static void
11766parseheredoc(void)
11767{
11768 struct heredoc *here;
11769 union node *n;
11770
11771 here = heredoclist;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000011772 heredoclist = NULL;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011773
11774 while (here) {
11775 if (needprompt) {
11776 setprompt(2);
11777 }
11778 readtoken1(pgetc(), here->here->type == NHERE? SQSYNTAX : DQSYNTAX,
11779 here->eofmark, here->striptabs);
Denis Vlasenko597906c2008-02-20 16:38:54 +000011780 n = stzalloc(sizeof(struct narg));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011781 n->narg.type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000011782 /*n->narg.next = NULL; - stzalloc did it */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011783 n->narg.text = wordtext;
11784 n->narg.backquote = backquotelist;
11785 here->here->nhere.doc = n;
11786 here = here->next;
Eric Andersencb57d552001-06-28 07:25:16 +000011787 }
Eric Andersencb57d552001-06-28 07:25:16 +000011788}
11789
11790
11791/*
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +000011792 * called by editline -- any expansions to the prompt should be added here.
Eric Andersencb57d552001-06-28 07:25:16 +000011793 */
Denis Vlasenko131ae172007-02-18 13:00:19 +000011794#if ENABLE_ASH_EXPAND_PRMT
"Vladimir N. Oleynik"bef14d72005-09-05 13:25:11 +000011795static const char *
11796expandstr(const char *ps)
11797{
11798 union node n;
11799
Denis Vlasenko5c2b8142009-03-19 01:59:59 +000011800 /* XXX Fix (char *) cast. It _is_ a bug. ps is variable's value,
11801 * and token processing _can_ alter it (delete NULs etc). */
"Vladimir N. Oleynik"bef14d72005-09-05 13:25:11 +000011802 setinputstring((char *)ps);
Denis Vlasenko46a53062007-09-24 18:30:02 +000011803 readtoken1(pgetc(), PSSYNTAX, nullstr, 0);
"Vladimir N. Oleynik"bef14d72005-09-05 13:25:11 +000011804 popfile();
11805
11806 n.narg.type = NARG;
11807 n.narg.next = NULL;
11808 n.narg.text = wordtext;
11809 n.narg.backquote = backquotelist;
11810
11811 expandarg(&n, NULL, 0);
11812 return stackblock();
11813}
11814#endif
11815
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011816/*
11817 * Execute a command or commands contained in a string.
11818 */
11819static int
11820evalstring(char *s, int mask)
Eric Andersenc470f442003-07-28 09:56:35 +000011821{
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011822 union node *n;
11823 struct stackmark smark;
11824 int skip;
11825
11826 setinputstring(s);
11827 setstackmark(&smark);
11828
11829 skip = 0;
Denys Vlasenko86e83ec2009-07-23 22:07:07 +020011830 while ((n = parsecmd(0)) != NODE_EOF) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011831 evaltree(n, 0);
11832 popstackmark(&smark);
11833 skip = evalskip;
11834 if (skip)
11835 break;
11836 }
11837 popfile();
11838
11839 skip &= mask;
11840 evalskip = skip;
11841 return skip;
Eric Andersenc470f442003-07-28 09:56:35 +000011842}
11843
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011844/*
11845 * The eval command.
11846 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011847static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000011848evalcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011849{
11850 char *p;
11851 char *concat;
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011852
Denis Vlasenko68404f12008-03-17 09:00:54 +000011853 if (argv[1]) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011854 p = argv[1];
Denis Vlasenko68404f12008-03-17 09:00:54 +000011855 argv += 2;
11856 if (argv[0]) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011857 STARTSTACKSTR(concat);
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011858 for (;;) {
11859 concat = stack_putstr(p, concat);
Denis Vlasenko68404f12008-03-17 09:00:54 +000011860 p = *argv++;
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011861 if (p == NULL)
11862 break;
11863 STPUTC(' ', concat);
11864 }
11865 STPUTC('\0', concat);
11866 p = grabstackstr(concat);
11867 }
11868 evalstring(p, ~SKIPEVAL);
11869
11870 }
11871 return exitstatus;
11872}
11873
11874/*
Denys Vlasenko285ad152009-12-04 23:02:27 +010011875 * Read and execute commands.
11876 * "Top" is nonzero for the top level command loop;
11877 * it turns on prompting if the shell is interactive.
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011878 */
11879static int
11880cmdloop(int top)
11881{
11882 union node *n;
11883 struct stackmark smark;
11884 int inter;
11885 int numeof = 0;
11886
11887 TRACE(("cmdloop(%d) called\n", top));
11888 for (;;) {
11889 int skip;
11890
11891 setstackmark(&smark);
11892#if JOBS
Denis Vlasenkob07a4962008-06-22 13:16:23 +000011893 if (doing_jobctl)
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011894 showjobs(stderr, SHOW_CHANGED);
11895#endif
11896 inter = 0;
11897 if (iflag && top) {
11898 inter++;
11899#if ENABLE_ASH_MAIL
11900 chkmail();
11901#endif
11902 }
11903 n = parsecmd(inter);
Denys Vlasenko7cee00e2009-07-24 01:08:03 +020011904#if DEBUG
11905 if (DEBUG > 2 && debug && (n != NODE_EOF))
Denys Vlasenko883cea42009-07-11 15:31:59 +020011906 showtree(n);
Denis Vlasenko135cecb2009-04-12 00:00:57 +000011907#endif
Denys Vlasenko86e83ec2009-07-23 22:07:07 +020011908 if (n == NODE_EOF) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011909 if (!top || numeof >= 50)
11910 break;
11911 if (!stoppedjobs()) {
11912 if (!Iflag)
11913 break;
11914 out2str("\nUse \"exit\" to leave shell.\n");
11915 }
11916 numeof++;
11917 } else if (nflag == 0) {
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +000011918 /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
11919 job_warning >>= 1;
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011920 numeof = 0;
11921 evaltree(n, 0);
11922 }
11923 popstackmark(&smark);
11924 skip = evalskip;
11925
11926 if (skip) {
11927 evalskip = 0;
11928 return skip & SKIPEVAL;
11929 }
11930 }
11931 return 0;
11932}
11933
Denis Vlasenko0dec6de2007-02-23 21:10:47 +000011934/*
11935 * Take commands from a file. To be compatible we should do a path
11936 * search for the file, which is necessary to find sub-commands.
11937 */
11938static char *
11939find_dot_file(char *name)
11940{
11941 char *fullname;
11942 const char *path = pathval();
11943 struct stat statb;
11944
11945 /* don't try this for absolute or relative paths */
11946 if (strchr(name, '/'))
11947 return name;
11948
Denis Vlasenko8ad78e12009-02-15 12:40:30 +000011949 /* IIRC standards do not say whether . is to be searched.
11950 * And it is even smaller this way, making it unconditional for now:
11951 */
11952 if (1) { /* ENABLE_ASH_BASH_COMPAT */
11953 fullname = name;
11954 goto try_cur_dir;
11955 }
11956
Denys Vlasenko82a6fb32009-06-14 19:42:12 +020011957 while ((fullname = path_advance(&path, name)) != NULL) {
Denis Vlasenko8ad78e12009-02-15 12:40:30 +000011958 try_cur_dir:
Denis Vlasenko0dec6de2007-02-23 21:10:47 +000011959 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
11960 /*
11961 * Don't bother freeing here, since it will
11962 * be freed by the caller.
11963 */
11964 return fullname;
11965 }
Denys Vlasenko82a6fb32009-06-14 19:42:12 +020011966 if (fullname != name)
11967 stunalloc(fullname);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +000011968 }
11969
11970 /* not found in the PATH */
11971 ash_msg_and_raise_error("%s: not found", name);
11972 /* NOTREACHED */
11973}
11974
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011975static int FAST_FUNC
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011976dotcmd(int argc, char **argv)
11977{
11978 struct strlist *sp;
11979 volatile struct shparam saveparam;
11980 int status = 0;
11981
11982 for (sp = cmdenviron; sp; sp = sp->next)
Denis Vlasenko4222ae42007-02-25 02:37:49 +000011983 setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011984
Denis Vlasenko68404f12008-03-17 09:00:54 +000011985 if (argv[1]) { /* That's what SVR2 does */
11986 char *fullname = find_dot_file(argv[1]);
11987 argv += 2;
11988 argc -= 2;
11989 if (argc) { /* argc > 0, argv[0] != NULL */
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011990 saveparam = shellparam;
Denis Vlasenko01631112007-12-16 17:20:38 +000011991 shellparam.malloced = 0;
Denis Vlasenko68404f12008-03-17 09:00:54 +000011992 shellparam.nparam = argc;
11993 shellparam.p = argv;
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011994 };
11995
11996 setinputfile(fullname, INPUT_PUSH_FILE);
11997 commandname = fullname;
11998 cmdloop(0);
11999 popfile();
12000
Denis Vlasenko68404f12008-03-17 09:00:54 +000012001 if (argc) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012002 freeparam(&shellparam);
12003 shellparam = saveparam;
12004 };
12005 status = exitstatus;
12006 }
12007 return status;
12008}
12009
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012010static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012011exitcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012012{
12013 if (stoppedjobs())
12014 return 0;
Denis Vlasenko68404f12008-03-17 09:00:54 +000012015 if (argv[1])
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012016 exitstatus = number(argv[1]);
12017 raise_exception(EXEXIT);
12018 /* NOTREACHED */
12019}
12020
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012021/*
12022 * Read a file containing shell functions.
12023 */
12024static void
12025readcmdfile(char *name)
12026{
12027 setinputfile(name, INPUT_PUSH_FILE);
12028 cmdloop(0);
12029 popfile();
12030}
12031
12032
Denis Vlasenkocc571512007-02-23 21:10:35 +000012033/* ============ find_command inplementation */
12034
12035/*
12036 * Resolve a command name. If you change this routine, you may have to
12037 * change the shellexec routine as well.
12038 */
12039static void
12040find_command(char *name, struct cmdentry *entry, int act, const char *path)
12041{
12042 struct tblentry *cmdp;
12043 int idx;
12044 int prev;
12045 char *fullname;
12046 struct stat statb;
12047 int e;
12048 int updatetbl;
12049 struct builtincmd *bcmd;
12050
12051 /* If name contains a slash, don't use PATH or hash table */
12052 if (strchr(name, '/') != NULL) {
12053 entry->u.index = -1;
12054 if (act & DO_ABS) {
12055 while (stat(name, &statb) < 0) {
12056#ifdef SYSV
12057 if (errno == EINTR)
12058 continue;
12059#endif
12060 entry->cmdtype = CMDUNKNOWN;
12061 return;
12062 }
12063 }
12064 entry->cmdtype = CMDNORMAL;
12065 return;
12066 }
12067
Denis Vlasenkof20de5b2007-04-29 23:42:54 +000012068/* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
Denis Vlasenkocc571512007-02-23 21:10:35 +000012069
12070 updatetbl = (path == pathval());
12071 if (!updatetbl) {
12072 act |= DO_ALTPATH;
12073 if (strstr(path, "%builtin") != NULL)
12074 act |= DO_ALTBLTIN;
12075 }
12076
12077 /* If name is in the table, check answer will be ok */
12078 cmdp = cmdlookup(name, 0);
12079 if (cmdp != NULL) {
12080 int bit;
12081
12082 switch (cmdp->cmdtype) {
12083 default:
12084#if DEBUG
12085 abort();
12086#endif
12087 case CMDNORMAL:
12088 bit = DO_ALTPATH;
12089 break;
12090 case CMDFUNCTION:
12091 bit = DO_NOFUNC;
12092 break;
12093 case CMDBUILTIN:
12094 bit = DO_ALTBLTIN;
12095 break;
12096 }
12097 if (act & bit) {
12098 updatetbl = 0;
12099 cmdp = NULL;
12100 } else if (cmdp->rehash == 0)
12101 /* if not invalidated by cd, we're done */
12102 goto success;
12103 }
12104
12105 /* If %builtin not in path, check for builtin next */
12106 bcmd = find_builtin(name);
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +000012107 if (bcmd) {
12108 if (IS_BUILTIN_REGULAR(bcmd))
12109 goto builtin_success;
12110 if (act & DO_ALTPATH) {
12111 if (!(act & DO_ALTBLTIN))
12112 goto builtin_success;
12113 } else if (builtinloc <= 0) {
12114 goto builtin_success;
Denis Vlasenko8e858e22007-03-07 09:35:43 +000012115 }
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +000012116 }
Denis Vlasenkocc571512007-02-23 21:10:35 +000012117
Denis Vlasenkof20de5b2007-04-29 23:42:54 +000012118#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko7465dbc2008-04-13 02:25:53 +000012119 {
12120 int applet_no = find_applet_by_name(name);
12121 if (applet_no >= 0) {
12122 entry->cmdtype = CMDNORMAL;
12123 entry->u.index = -2 - applet_no;
12124 return;
12125 }
Denis Vlasenkof20de5b2007-04-29 23:42:54 +000012126 }
12127#endif
12128
Denis Vlasenkocc571512007-02-23 21:10:35 +000012129 /* We have to search path. */
12130 prev = -1; /* where to start */
12131 if (cmdp && cmdp->rehash) { /* doing a rehash */
12132 if (cmdp->cmdtype == CMDBUILTIN)
12133 prev = builtinloc;
12134 else
12135 prev = cmdp->param.index;
12136 }
12137
12138 e = ENOENT;
12139 idx = -1;
12140 loop:
Denys Vlasenko82a6fb32009-06-14 19:42:12 +020012141 while ((fullname = path_advance(&path, name)) != NULL) {
Denis Vlasenkocc571512007-02-23 21:10:35 +000012142 stunalloc(fullname);
Denis Vlasenkodee82b62007-07-29 14:05:27 +000012143 /* NB: code below will still use fullname
12144 * despite it being "unallocated" */
Denis Vlasenkocc571512007-02-23 21:10:35 +000012145 idx++;
12146 if (pathopt) {
12147 if (prefix(pathopt, "builtin")) {
12148 if (bcmd)
12149 goto builtin_success;
12150 continue;
Denis Vlasenko4a9ca132008-04-12 20:07:08 +000012151 }
12152 if ((act & DO_NOFUNC)
12153 || !prefix(pathopt, "func")
12154 ) { /* ignore unimplemented options */
Denis Vlasenkocc571512007-02-23 21:10:35 +000012155 continue;
12156 }
12157 }
12158 /* if rehash, don't redo absolute path names */
12159 if (fullname[0] == '/' && idx <= prev) {
12160 if (idx < prev)
12161 continue;
12162 TRACE(("searchexec \"%s\": no change\n", name));
12163 goto success;
12164 }
12165 while (stat(fullname, &statb) < 0) {
12166#ifdef SYSV
12167 if (errno == EINTR)
12168 continue;
12169#endif
12170 if (errno != ENOENT && errno != ENOTDIR)
12171 e = errno;
12172 goto loop;
12173 }
12174 e = EACCES; /* if we fail, this will be the error */
12175 if (!S_ISREG(statb.st_mode))
12176 continue;
12177 if (pathopt) { /* this is a %func directory */
12178 stalloc(strlen(fullname) + 1);
Denis Vlasenkodee82b62007-07-29 14:05:27 +000012179 /* NB: stalloc will return space pointed by fullname
12180 * (because we don't have any intervening allocations
12181 * between stunalloc above and this stalloc) */
Denis Vlasenkocc571512007-02-23 21:10:35 +000012182 readcmdfile(fullname);
12183 cmdp = cmdlookup(name, 0);
12184 if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
12185 ash_msg_and_raise_error("%s not defined in %s", name, fullname);
12186 stunalloc(fullname);
12187 goto success;
12188 }
12189 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
12190 if (!updatetbl) {
12191 entry->cmdtype = CMDNORMAL;
12192 entry->u.index = idx;
12193 return;
12194 }
12195 INT_OFF;
12196 cmdp = cmdlookup(name, 1);
12197 cmdp->cmdtype = CMDNORMAL;
12198 cmdp->param.index = idx;
12199 INT_ON;
12200 goto success;
12201 }
12202
12203 /* We failed. If there was an entry for this command, delete it */
12204 if (cmdp && updatetbl)
12205 delete_cmd_entry();
12206 if (act & DO_ERR)
12207 ash_msg("%s: %s", name, errmsg(e, "not found"));
12208 entry->cmdtype = CMDUNKNOWN;
12209 return;
12210
12211 builtin_success:
12212 if (!updatetbl) {
12213 entry->cmdtype = CMDBUILTIN;
12214 entry->u.cmd = bcmd;
12215 return;
12216 }
12217 INT_OFF;
12218 cmdp = cmdlookup(name, 1);
12219 cmdp->cmdtype = CMDBUILTIN;
12220 cmdp->param.cmd = bcmd;
12221 INT_ON;
12222 success:
12223 cmdp->rehash = 0;
12224 entry->cmdtype = cmdp->cmdtype;
12225 entry->u = cmdp->param;
12226}
12227
12228
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012229/* ============ trap.c */
Eric Andersenc470f442003-07-28 09:56:35 +000012230
Eric Andersencb57d552001-06-28 07:25:16 +000012231/*
Eric Andersencb57d552001-06-28 07:25:16 +000012232 * The trap builtin.
12233 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012234static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012235trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersencb57d552001-06-28 07:25:16 +000012236{
12237 char *action;
12238 char **ap;
12239 int signo;
12240
Eric Andersenc470f442003-07-28 09:56:35 +000012241 nextopt(nullstr);
12242 ap = argptr;
12243 if (!*ap) {
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012244 for (signo = 0; signo < NSIG; signo++) {
Denys Vlasenko21d87d42009-09-25 00:06:51 +020012245 char *tr = trap_ptr[signo];
12246 if (tr) {
Denys Vlasenkoe74aaf92009-09-27 02:05:45 +020012247 /* note: bash adds "SIG", but only if invoked
12248 * as "bash". If called as "sh", or if set -o posix,
12249 * then it prints short signal names.
12250 * We are printing short names: */
12251 out1fmt("trap -- %s %s\n",
Denys Vlasenko21d87d42009-09-25 00:06:51 +020012252 single_quote(tr),
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +000012253 get_signame(signo));
Denys Vlasenko726e1a02009-09-25 02:58:20 +020012254 /* trap_ptr != trap only if we are in special-cased `trap` code.
12255 * In this case, we will exit very soon, no need to free(). */
Denys Vlasenkoe74aaf92009-09-27 02:05:45 +020012256 /* if (trap_ptr != trap && tp[0]) */
Denys Vlasenko726e1a02009-09-25 02:58:20 +020012257 /* free(tr); */
Eric Andersencb57d552001-06-28 07:25:16 +000012258 }
12259 }
Denys Vlasenko726e1a02009-09-25 02:58:20 +020012260 /*
Denys Vlasenko21d87d42009-09-25 00:06:51 +020012261 if (trap_ptr != trap) {
12262 free(trap_ptr);
12263 trap_ptr = trap;
12264 }
Denys Vlasenko726e1a02009-09-25 02:58:20 +020012265 */
Eric Andersencb57d552001-06-28 07:25:16 +000012266 return 0;
12267 }
Denys Vlasenko21d87d42009-09-25 00:06:51 +020012268
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +000012269 action = NULL;
12270 if (ap[1])
Eric Andersencb57d552001-06-28 07:25:16 +000012271 action = *ap++;
12272 while (*ap) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +000012273 signo = get_signum(*ap);
12274 if (signo < 0)
Denis Vlasenkob012b102007-02-19 22:43:01 +000012275 ash_msg_and_raise_error("%s: bad trap", *ap);
12276 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +000012277 if (action) {
Denis Vlasenko9f739442006-12-16 23:49:13 +000012278 if (LONE_DASH(action))
Eric Andersencb57d552001-06-28 07:25:16 +000012279 action = NULL;
12280 else
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012281 action = ckstrdup(action);
Eric Andersencb57d552001-06-28 07:25:16 +000012282 }
Denis Vlasenko60818682007-09-28 22:07:23 +000012283 free(trap[signo]);
Eric Andersencb57d552001-06-28 07:25:16 +000012284 trap[signo] = action;
12285 if (signo != 0)
12286 setsignal(signo);
Denis Vlasenkob012b102007-02-19 22:43:01 +000012287 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +000012288 ap++;
12289 }
12290 return 0;
12291}
12292
Eric Andersenc470f442003-07-28 09:56:35 +000012293
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012294/* ============ Builtins */
Eric Andersenc470f442003-07-28 09:56:35 +000012295
Denis Vlasenko8e1c7152007-01-22 07:21:38 +000012296#if !ENABLE_FEATURE_SH_EXTRA_QUIET
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012297/*
12298 * Lists available builtins
12299 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012300static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012301helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersenc470f442003-07-28 09:56:35 +000012302{
Denis Vlasenko6b06cb82008-05-15 21:30:45 +000012303 unsigned col;
12304 unsigned i;
Eric Andersenc470f442003-07-28 09:56:35 +000012305
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +020012306 out1fmt(
Denis Vlasenko34d4d892009-04-04 20:24:37 +000012307 "Built-in commands:\n"
12308 "------------------\n");
Denis Vlasenkob71c6682007-07-21 15:08:09 +000012309 for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
Eric Andersenc470f442003-07-28 09:56:35 +000012310 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
Denis Vlasenko52764022007-02-24 13:42:56 +000012311 builtintab[i].name + 1);
Eric Andersenc470f442003-07-28 09:56:35 +000012312 if (col > 60) {
12313 out1fmt("\n");
12314 col = 0;
12315 }
12316 }
Denis Vlasenko80d14be2007-04-10 23:03:30 +000012317#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko1aa7e472007-11-28 06:49:03 +000012318 {
12319 const char *a = applet_names;
12320 while (*a) {
12321 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
12322 if (col > 60) {
12323 out1fmt("\n");
12324 col = 0;
12325 }
12326 a += strlen(a) + 1;
Eric Andersenc470f442003-07-28 09:56:35 +000012327 }
12328 }
12329#endif
12330 out1fmt("\n\n");
12331 return EXIT_SUCCESS;
12332}
Denis Vlasenko131ae172007-02-18 13:00:19 +000012333#endif /* FEATURE_SH_EXTRA_QUIET */
Eric Andersenc470f442003-07-28 09:56:35 +000012334
Eric Andersencb57d552001-06-28 07:25:16 +000012335/*
Eric Andersencb57d552001-06-28 07:25:16 +000012336 * The export and readonly commands.
12337 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012338static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012339exportcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +000012340{
12341 struct var *vp;
12342 char *name;
12343 const char *p;
Eric Andersenc470f442003-07-28 09:56:35 +000012344 char **aptr;
Denis Vlasenkob7304742008-10-20 08:15:51 +000012345 int flag = argv[0][0] == 'r' ? VREADONLY : VEXPORT;
Eric Andersencb57d552001-06-28 07:25:16 +000012346
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012347 if (nextopt("p") != 'p') {
12348 aptr = argptr;
12349 name = *aptr;
12350 if (name) {
12351 do {
12352 p = strchr(name, '=');
12353 if (p != NULL) {
12354 p++;
12355 } else {
12356 vp = *findvar(hashvar(name), name);
12357 if (vp) {
12358 vp->flags |= flag;
12359 continue;
12360 }
Eric Andersencb57d552001-06-28 07:25:16 +000012361 }
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012362 setvar(name, p, flag);
12363 } while ((name = *++aptr) != NULL);
12364 return 0;
12365 }
Eric Andersencb57d552001-06-28 07:25:16 +000012366 }
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012367 showvars(argv[0], flag, 0);
Eric Andersencb57d552001-06-28 07:25:16 +000012368 return 0;
12369}
12370
Eric Andersencb57d552001-06-28 07:25:16 +000012371/*
Denis Vlasenko5651bfc2007-02-23 21:08:58 +000012372 * Delete a function if it exists.
Eric Andersencb57d552001-06-28 07:25:16 +000012373 */
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012374static void
Denis Vlasenko5651bfc2007-02-23 21:08:58 +000012375unsetfunc(const char *name)
Aaron Lehmannb6ecbdc2001-12-06 03:37:38 +000012376{
Denis Vlasenko5651bfc2007-02-23 21:08:58 +000012377 struct tblentry *cmdp;
Eric Andersencb57d552001-06-28 07:25:16 +000012378
Denis Vlasenko5651bfc2007-02-23 21:08:58 +000012379 cmdp = cmdlookup(name, 0);
12380 if (cmdp!= NULL && cmdp->cmdtype == CMDFUNCTION)
12381 delete_cmd_entry();
Eric Andersenc470f442003-07-28 09:56:35 +000012382}
12383
Eric Andersencb57d552001-06-28 07:25:16 +000012384/*
Eric Andersencb57d552001-06-28 07:25:16 +000012385 * The unset builtin command. We unset the function before we unset the
12386 * variable to allow a function to be unset when there is a readonly variable
12387 * with the same name.
12388 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012389static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012390unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersencb57d552001-06-28 07:25:16 +000012391{
12392 char **ap;
12393 int i;
Eric Andersenc470f442003-07-28 09:56:35 +000012394 int flag = 0;
Eric Andersencb57d552001-06-28 07:25:16 +000012395 int ret = 0;
12396
12397 while ((i = nextopt("vf")) != '\0') {
Eric Andersenc470f442003-07-28 09:56:35 +000012398 flag = i;
Eric Andersencb57d552001-06-28 07:25:16 +000012399 }
Eric Andersencb57d552001-06-28 07:25:16 +000012400
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012401 for (ap = argptr; *ap; ap++) {
Eric Andersenc470f442003-07-28 09:56:35 +000012402 if (flag != 'f') {
12403 i = unsetvar(*ap);
12404 ret |= i;
12405 if (!(i & 2))
12406 continue;
12407 }
12408 if (flag != 'v')
Eric Andersencb57d552001-06-28 07:25:16 +000012409 unsetfunc(*ap);
Eric Andersencb57d552001-06-28 07:25:16 +000012410 }
Eric Andersenc470f442003-07-28 09:56:35 +000012411 return ret & 1;
Eric Andersencb57d552001-06-28 07:25:16 +000012412}
12413
12414
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +000012415/* setmode.c */
Eric Andersencb57d552001-06-28 07:25:16 +000012416
Eric Andersenc470f442003-07-28 09:56:35 +000012417#include <sys/times.h>
12418
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000012419static const unsigned char timescmd_str[] ALIGN1 = {
Manuel Novoa III 4456f252003-08-13 17:48:47 +000012420 ' ', offsetof(struct tms, tms_utime),
12421 '\n', offsetof(struct tms, tms_stime),
12422 ' ', offsetof(struct tms, tms_cutime),
12423 '\n', offsetof(struct tms, tms_cstime),
12424 0
12425};
Eric Andersencb57d552001-06-28 07:25:16 +000012426
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012427static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012428timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Manuel Novoa III 4456f252003-08-13 17:48:47 +000012429{
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012430 long clk_tck, s, t;
Manuel Novoa III 4456f252003-08-13 17:48:47 +000012431 const unsigned char *p;
12432 struct tms buf;
12433
12434 clk_tck = sysconf(_SC_CLK_TCK);
Eric Andersencb57d552001-06-28 07:25:16 +000012435 times(&buf);
Manuel Novoa III 4456f252003-08-13 17:48:47 +000012436
12437 p = timescmd_str;
12438 do {
12439 t = *(clock_t *)(((char *) &buf) + p[1]);
12440 s = t / clk_tck;
12441 out1fmt("%ldm%ld.%.3lds%c",
12442 s/60, s%60,
12443 ((t - s * clk_tck) * 1000) / clk_tck,
12444 p[0]);
12445 } while (*(p += 2));
12446
Eric Andersencb57d552001-06-28 07:25:16 +000012447 return 0;
12448}
12449
Mike Frysinger98c52642009-04-02 10:02:37 +000012450#if ENABLE_SH_MATH_SUPPORT
Eric Andersenc470f442003-07-28 09:56:35 +000012451/*
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +000012452 * The let builtin. partial stolen from GNU Bash, the Bourne Again SHell.
12453 * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
Eric Andersen90898442003-08-06 11:20:52 +000012454 *
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +000012455 * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
Eric Andersenc470f442003-07-28 09:56:35 +000012456 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012457static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012458letcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersenc470f442003-07-28 09:56:35 +000012459{
Denis Vlasenko68404f12008-03-17 09:00:54 +000012460 arith_t i;
Eric Andersenc470f442003-07-28 09:56:35 +000012461
Denis Vlasenko68404f12008-03-17 09:00:54 +000012462 argv++;
12463 if (!*argv)
Denis Vlasenkob012b102007-02-19 22:43:01 +000012464 ash_msg_and_raise_error("expression expected");
Denis Vlasenko68404f12008-03-17 09:00:54 +000012465 do {
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +000012466 i = ash_arith(*argv);
Denis Vlasenko68404f12008-03-17 09:00:54 +000012467 } while (*++argv);
Eric Andersenc470f442003-07-28 09:56:35 +000012468
Denis Vlasenkod9e15f22006-11-27 16:49:55 +000012469 return !i;
Eric Andersenc470f442003-07-28 09:56:35 +000012470}
Mike Frysinger98c52642009-04-02 10:02:37 +000012471#endif /* SH_MATH_SUPPORT */
Eric Andersenc470f442003-07-28 09:56:35 +000012472
Eric Andersenc470f442003-07-28 09:56:35 +000012473
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012474/* ============ miscbltin.c
12475 *
Eric Andersenaff114c2004-04-14 17:51:38 +000012476 * Miscellaneous builtins.
Eric Andersenc470f442003-07-28 09:56:35 +000012477 */
12478
12479#undef rflag
12480
Denis Vlasenko83e5d6f2006-12-18 21:49:06 +000012481#if defined(__GLIBC__) && __GLIBC__ == 2 && __GLIBC_MINOR__ < 1
Eric Andersenc470f442003-07-28 09:56:35 +000012482typedef enum __rlimit_resource rlim_t;
12483#endif
Eric Andersen74bcd162001-07-30 21:41:37 +000012484
Eric Andersenc470f442003-07-28 09:56:35 +000012485/*
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012486 * The read builtin. Options:
12487 * -r Do not interpret '\' specially
12488 * -s Turn off echo (tty only)
12489 * -n NCHARS Read NCHARS max
12490 * -p PROMPT Display PROMPT on stderr (if input is from tty)
12491 * -t SECONDS Timeout after SECONDS (tty or pipe only)
12492 * -u FD Read from given FD instead of fd 0
Eric Andersenc470f442003-07-28 09:56:35 +000012493 * This uses unbuffered input, which may be avoidable in some cases.
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012494 * TODO: bash also has:
12495 * -a ARRAY Read into array[0],[1],etc
12496 * -d DELIM End on DELIM char, not newline
12497 * -e Use line editing (tty only)
Eric Andersenc470f442003-07-28 09:56:35 +000012498 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012499static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012500readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersenc470f442003-07-28 09:56:35 +000012501{
Denis Vlasenko9cd4c762008-06-18 19:22:19 +000012502 static const char *const arg_REPLY[] = { "REPLY", NULL };
12503
Eric Andersenc470f442003-07-28 09:56:35 +000012504 char **ap;
12505 int backslash;
12506 char c;
12507 int rflag;
12508 char *prompt;
12509 const char *ifs;
12510 char *p;
12511 int startword;
12512 int status;
12513 int i;
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012514 int fd = 0;
Denis Vlasenko131ae172007-02-18 13:00:19 +000012515#if ENABLE_ASH_READ_NCHARS
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012516 int nchars = 0; /* if != 0, -n is in effect */
Paul Fox02eb9342005-09-07 16:56:02 +000012517 int silent = 0;
12518 struct termios tty, old_tty;
12519#endif
Denis Vlasenko131ae172007-02-18 13:00:19 +000012520#if ENABLE_ASH_READ_TIMEOUT
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012521 unsigned end_ms = 0;
12522 unsigned timeout = 0;
Paul Fox02eb9342005-09-07 16:56:02 +000012523#endif
Eric Andersenc470f442003-07-28 09:56:35 +000012524
12525 rflag = 0;
12526 prompt = NULL;
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012527 while ((i = nextopt("p:u:r"
Denis Vlasenko5e34ff22009-04-21 11:09:40 +000012528 IF_ASH_READ_TIMEOUT("t:")
12529 IF_ASH_READ_NCHARS("n:s")
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012530 )) != '\0') {
Denis Vlasenkobf0a2012006-12-26 10:42:51 +000012531 switch (i) {
Paul Fox02eb9342005-09-07 16:56:02 +000012532 case 'p':
Eric Andersenc470f442003-07-28 09:56:35 +000012533 prompt = optionarg;
Paul Fox02eb9342005-09-07 16:56:02 +000012534 break;
Denis Vlasenko131ae172007-02-18 13:00:19 +000012535#if ENABLE_ASH_READ_NCHARS
Paul Fox02eb9342005-09-07 16:56:02 +000012536 case 'n':
Denis Vlasenko037576d2007-10-20 18:30:38 +000012537 nchars = bb_strtou(optionarg, NULL, 10);
12538 if (nchars < 0 || errno)
Denis Vlasenkob012b102007-02-19 22:43:01 +000012539 ash_msg_and_raise_error("invalid count");
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012540 /* nchars == 0: off (bash 3.2 does this too) */
Paul Fox02eb9342005-09-07 16:56:02 +000012541 break;
12542 case 's':
12543 silent = 1;
12544 break;
Ned Ludd2123b7c2005-02-09 21:07:23 +000012545#endif
Denis Vlasenko131ae172007-02-18 13:00:19 +000012546#if ENABLE_ASH_READ_TIMEOUT
Paul Fox02eb9342005-09-07 16:56:02 +000012547 case 't':
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012548 timeout = bb_strtou(optionarg, NULL, 10);
12549 if (errno || timeout > UINT_MAX / 2048)
12550 ash_msg_and_raise_error("invalid timeout");
12551 timeout *= 1000;
12552#if 0 /* even bash have no -t N.NNN support */
Denis Vlasenko037576d2007-10-20 18:30:38 +000012553 ts.tv_sec = bb_strtou(optionarg, &p, 10);
Paul Fox02eb9342005-09-07 16:56:02 +000012554 ts.tv_usec = 0;
Denis Vlasenko037576d2007-10-20 18:30:38 +000012555 /* EINVAL means number is ok, but not terminated by NUL */
12556 if (*p == '.' && errno == EINVAL) {
Paul Fox02eb9342005-09-07 16:56:02 +000012557 char *p2;
12558 if (*++p) {
12559 int scale;
Denis Vlasenko037576d2007-10-20 18:30:38 +000012560 ts.tv_usec = bb_strtou(p, &p2, 10);
12561 if (errno)
Denis Vlasenkob012b102007-02-19 22:43:01 +000012562 ash_msg_and_raise_error("invalid timeout");
Paul Fox02eb9342005-09-07 16:56:02 +000012563 scale = p2 - p;
12564 /* normalize to usec */
12565 if (scale > 6)
Denis Vlasenkob012b102007-02-19 22:43:01 +000012566 ash_msg_and_raise_error("invalid timeout");
Paul Fox02eb9342005-09-07 16:56:02 +000012567 while (scale++ < 6)
12568 ts.tv_usec *= 10;
12569 }
Denis Vlasenko037576d2007-10-20 18:30:38 +000012570 } else if (ts.tv_sec < 0 || errno) {
Denis Vlasenkob012b102007-02-19 22:43:01 +000012571 ash_msg_and_raise_error("invalid timeout");
Paul Fox02eb9342005-09-07 16:56:02 +000012572 }
Denis Vlasenko037576d2007-10-20 18:30:38 +000012573 if (!(ts.tv_sec | ts.tv_usec)) { /* both are 0? */
Denis Vlasenkob012b102007-02-19 22:43:01 +000012574 ash_msg_and_raise_error("invalid timeout");
Denis Vlasenko037576d2007-10-20 18:30:38 +000012575 }
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012576#endif /* if 0 */
Paul Fox02eb9342005-09-07 16:56:02 +000012577 break;
12578#endif
12579 case 'r':
12580 rflag = 1;
12581 break;
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012582 case 'u':
12583 fd = bb_strtou(optionarg, NULL, 10);
12584 if (fd < 0 || errno)
12585 ash_msg_and_raise_error("invalid file descriptor");
12586 break;
Paul Fox02eb9342005-09-07 16:56:02 +000012587 default:
12588 break;
12589 }
Eric Andersenc470f442003-07-28 09:56:35 +000012590 }
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012591 if (prompt && isatty(fd)) {
Eric Andersenc470f442003-07-28 09:56:35 +000012592 out2str(prompt);
Eric Andersenc470f442003-07-28 09:56:35 +000012593 }
Denis Vlasenko5cedb752007-02-18 19:56:41 +000012594 ap = argptr;
12595 if (*ap == NULL)
Denis Vlasenko9cd4c762008-06-18 19:22:19 +000012596 ap = (char**)arg_REPLY;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000012597 ifs = bltinlookup("IFS");
12598 if (ifs == NULL)
Eric Andersenc470f442003-07-28 09:56:35 +000012599 ifs = defifs;
Denis Vlasenko131ae172007-02-18 13:00:19 +000012600#if ENABLE_ASH_READ_NCHARS
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012601 tcgetattr(fd, &tty);
12602 old_tty = tty;
12603 if (nchars || silent) {
12604 if (nchars) {
12605 tty.c_lflag &= ~ICANON;
12606 tty.c_cc[VMIN] = nchars < 256 ? nchars : 255;
Paul Fox02eb9342005-09-07 16:56:02 +000012607 }
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012608 if (silent) {
12609 tty.c_lflag &= ~(ECHO | ECHOK | ECHONL);
12610 }
12611 /* if tcgetattr failed, tcsetattr will fail too.
12612 * Ignoring, it's harmless. */
12613 tcsetattr(fd, TCSANOW, &tty);
Paul Fox02eb9342005-09-07 16:56:02 +000012614 }
12615#endif
Paul Fox02eb9342005-09-07 16:56:02 +000012616
Eric Andersenc470f442003-07-28 09:56:35 +000012617 status = 0;
Denys Vlasenko8cd04d12010-01-08 15:44:07 +010012618 startword = 1;
Eric Andersenc470f442003-07-28 09:56:35 +000012619 backslash = 0;
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012620#if ENABLE_ASH_READ_TIMEOUT
12621 if (timeout) /* NB: ensuring end_ms is nonzero */
12622 end_ms = ((unsigned)(monotonic_us() / 1000) + timeout) | 1;
12623#endif
Eric Andersenc470f442003-07-28 09:56:35 +000012624 STARTSTACKSTR(p);
Denis Vlasenko037576d2007-10-20 18:30:38 +000012625 do {
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012626 const char *is_ifs;
12627
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012628#if ENABLE_ASH_READ_TIMEOUT
12629 if (end_ms) {
12630 struct pollfd pfd[1];
12631 pfd[0].fd = fd;
12632 pfd[0].events = POLLIN;
12633 timeout = end_ms - (unsigned)(monotonic_us() / 1000);
12634 if ((int)timeout <= 0 /* already late? */
12635 || safe_poll(pfd, 1, timeout) != 1 /* no? wait... */
12636 ) { /* timed out! */
12637#if ENABLE_ASH_READ_NCHARS
12638 tcsetattr(fd, TCSANOW, &old_tty);
12639#endif
12640 return 1;
12641 }
12642 }
12643#endif
12644 if (nonblock_safe_read(fd, &c, 1) != 1) {
Eric Andersenc470f442003-07-28 09:56:35 +000012645 status = 1;
12646 break;
12647 }
12648 if (c == '\0')
12649 continue;
12650 if (backslash) {
12651 backslash = 0;
12652 if (c != '\n')
12653 goto put;
12654 continue;
12655 }
12656 if (!rflag && c == '\\') {
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012657 backslash = 1;
Eric Andersenc470f442003-07-28 09:56:35 +000012658 continue;
12659 }
12660 if (c == '\n')
12661 break;
Denis Vlasenkof6fbd622009-03-31 19:36:58 +000012662 /* $IFS splitting */
Denis Vlasenko551ffdc2009-04-01 19:48:05 +000012663/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_05 */
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012664 is_ifs = strchr(ifs, c);
12665 if (startword && is_ifs) {
12666 if (isspace(c))
12667 continue;
Denis Vlasenkof6fbd622009-03-31 19:36:58 +000012668 /* it is a non-space ifs char */
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012669 startword--;
12670 if (startword == 1) /* first one? */
Denis Vlasenkof6fbd622009-03-31 19:36:58 +000012671 continue; /* yes, it is not next word yet */
Eric Andersenc470f442003-07-28 09:56:35 +000012672 }
12673 startword = 0;
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012674 if (ap[1] != NULL && is_ifs) {
12675 const char *beg;
Eric Andersenc470f442003-07-28 09:56:35 +000012676 STACKSTRNUL(p);
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012677 beg = stackblock();
12678 setvar(*ap, beg, 0);
Eric Andersenc470f442003-07-28 09:56:35 +000012679 ap++;
Denis Vlasenkof6fbd622009-03-31 19:36:58 +000012680 /* can we skip one non-space ifs char? (2: yes) */
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012681 startword = isspace(c) ? 2 : 1;
Eric Andersenc470f442003-07-28 09:56:35 +000012682 STARTSTACKSTR(p);
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012683 continue;
Eric Andersenc470f442003-07-28 09:56:35 +000012684 }
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012685 put:
12686 STPUTC(c, p);
Eric Andersenc470f442003-07-28 09:56:35 +000012687 }
Denis Vlasenko037576d2007-10-20 18:30:38 +000012688/* end of do {} while: */
Denis Vlasenko131ae172007-02-18 13:00:19 +000012689#if ENABLE_ASH_READ_NCHARS
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012690 while (--nchars);
Denis Vlasenko037576d2007-10-20 18:30:38 +000012691#else
12692 while (1);
12693#endif
12694
12695#if ENABLE_ASH_READ_NCHARS
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012696 tcsetattr(fd, TCSANOW, &old_tty);
Paul Fox02eb9342005-09-07 16:56:02 +000012697#endif
12698
Eric Andersenc470f442003-07-28 09:56:35 +000012699 STACKSTRNUL(p);
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012700 /* Remove trailing space ifs chars */
12701 while ((char *)stackblock() <= --p && isspace(*p) && strchr(ifs, *p) != NULL)
Eric Andersenc470f442003-07-28 09:56:35 +000012702 *p = '\0';
12703 setvar(*ap, stackblock(), 0);
12704 while (*++ap != NULL)
12705 setvar(*ap, nullstr, 0);
12706 return status;
12707}
12708
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012709static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012710umaskcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersenc470f442003-07-28 09:56:35 +000012711{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000012712 static const char permuser[3] ALIGN1 = "ugo";
12713 static const char permmode[3] ALIGN1 = "rwx";
12714 static const short permmask[] ALIGN2 = {
Eric Andersenc470f442003-07-28 09:56:35 +000012715 S_IRUSR, S_IWUSR, S_IXUSR,
12716 S_IRGRP, S_IWGRP, S_IXGRP,
12717 S_IROTH, S_IWOTH, S_IXOTH
12718 };
12719
Denis Vlasenkoeb858492009-04-18 02:06:54 +000012720 /* TODO: use bb_parse_mode() instead */
12721
Eric Andersenc470f442003-07-28 09:56:35 +000012722 char *ap;
12723 mode_t mask;
12724 int i;
12725 int symbolic_mode = 0;
12726
12727 while (nextopt("S") != '\0') {
12728 symbolic_mode = 1;
12729 }
12730
Denis Vlasenkob012b102007-02-19 22:43:01 +000012731 INT_OFF;
Eric Andersenc470f442003-07-28 09:56:35 +000012732 mask = umask(0);
12733 umask(mask);
Denis Vlasenkob012b102007-02-19 22:43:01 +000012734 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +000012735
Denis Vlasenko5cedb752007-02-18 19:56:41 +000012736 ap = *argptr;
12737 if (ap == NULL) {
Eric Andersenc470f442003-07-28 09:56:35 +000012738 if (symbolic_mode) {
12739 char buf[18];
12740 char *p = buf;
12741
12742 for (i = 0; i < 3; i++) {
12743 int j;
12744
12745 *p++ = permuser[i];
12746 *p++ = '=';
12747 for (j = 0; j < 3; j++) {
12748 if ((mask & permmask[3 * i + j]) == 0) {
12749 *p++ = permmode[j];
12750 }
12751 }
12752 *p++ = ',';
12753 }
12754 *--p = 0;
12755 puts(buf);
12756 } else {
12757 out1fmt("%.4o\n", mask);
12758 }
12759 } else {
Denis Vlasenkoaa744452007-02-23 01:04:22 +000012760 if (isdigit((unsigned char) *ap)) {
Eric Andersenc470f442003-07-28 09:56:35 +000012761 mask = 0;
12762 do {
12763 if (*ap >= '8' || *ap < '0')
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +020012764 ash_msg_and_raise_error(msg_illnum, argv[1]);
Eric Andersenc470f442003-07-28 09:56:35 +000012765 mask = (mask << 3) + (*ap - '0');
12766 } while (*++ap != '\0');
12767 umask(mask);
12768 } else {
12769 mask = ~mask & 0777;
12770 if (!bb_parse_mode(ap, &mask)) {
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +000012771 ash_msg_and_raise_error("illegal mode: %s", ap);
Eric Andersenc470f442003-07-28 09:56:35 +000012772 }
12773 umask(~mask & 0777);
12774 }
12775 }
12776 return 0;
12777}
12778
12779/*
12780 * ulimit builtin
12781 *
12782 * This code, originally by Doug Gwyn, Doug Kingston, Eric Gisin, and
12783 * Michael Rendell was ripped from pdksh 5.0.8 and hacked for use with
12784 * ash by J.T. Conklin.
12785 *
12786 * Public domain.
12787 */
Eric Andersenc470f442003-07-28 09:56:35 +000012788struct limits {
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012789 uint8_t cmd; /* RLIMIT_xxx fit into it */
12790 uint8_t factor_shift; /* shift by to get rlim_{cur,max} values */
Eric Andersenc470f442003-07-28 09:56:35 +000012791 char option;
12792};
12793
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012794static const struct limits limits_tbl[] = {
Eric Andersenc470f442003-07-28 09:56:35 +000012795#ifdef RLIMIT_CPU
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012796 { RLIMIT_CPU, 0, 't' },
Eric Andersenc470f442003-07-28 09:56:35 +000012797#endif
12798#ifdef RLIMIT_FSIZE
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012799 { RLIMIT_FSIZE, 9, 'f' },
Eric Andersenc470f442003-07-28 09:56:35 +000012800#endif
12801#ifdef RLIMIT_DATA
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012802 { RLIMIT_DATA, 10, 'd' },
Eric Andersenc470f442003-07-28 09:56:35 +000012803#endif
12804#ifdef RLIMIT_STACK
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012805 { RLIMIT_STACK, 10, 's' },
Eric Andersenc470f442003-07-28 09:56:35 +000012806#endif
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012807#ifdef RLIMIT_CORE
12808 { RLIMIT_CORE, 9, 'c' },
Eric Andersenc470f442003-07-28 09:56:35 +000012809#endif
12810#ifdef RLIMIT_RSS
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012811 { RLIMIT_RSS, 10, 'm' },
Eric Andersenc470f442003-07-28 09:56:35 +000012812#endif
12813#ifdef RLIMIT_MEMLOCK
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012814 { RLIMIT_MEMLOCK, 10, 'l' },
Eric Andersenc470f442003-07-28 09:56:35 +000012815#endif
12816#ifdef RLIMIT_NPROC
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012817 { RLIMIT_NPROC, 0, 'p' },
Eric Andersenc470f442003-07-28 09:56:35 +000012818#endif
12819#ifdef RLIMIT_NOFILE
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012820 { RLIMIT_NOFILE, 0, 'n' },
Eric Andersenc470f442003-07-28 09:56:35 +000012821#endif
Glenn L McGrath76620622004-01-13 10:19:37 +000012822#ifdef RLIMIT_AS
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012823 { RLIMIT_AS, 10, 'v' },
Eric Andersenc470f442003-07-28 09:56:35 +000012824#endif
Glenn L McGrath76620622004-01-13 10:19:37 +000012825#ifdef RLIMIT_LOCKS
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012826 { RLIMIT_LOCKS, 0, 'w' },
Eric Andersenc470f442003-07-28 09:56:35 +000012827#endif
Eric Andersenc470f442003-07-28 09:56:35 +000012828};
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012829static const char limits_name[] =
12830#ifdef RLIMIT_CPU
12831 "time(seconds)" "\0"
12832#endif
12833#ifdef RLIMIT_FSIZE
12834 "file(blocks)" "\0"
12835#endif
12836#ifdef RLIMIT_DATA
12837 "data(kb)" "\0"
12838#endif
12839#ifdef RLIMIT_STACK
12840 "stack(kb)" "\0"
12841#endif
12842#ifdef RLIMIT_CORE
12843 "coredump(blocks)" "\0"
12844#endif
12845#ifdef RLIMIT_RSS
12846 "memory(kb)" "\0"
12847#endif
12848#ifdef RLIMIT_MEMLOCK
12849 "locked memory(kb)" "\0"
12850#endif
12851#ifdef RLIMIT_NPROC
12852 "process" "\0"
12853#endif
12854#ifdef RLIMIT_NOFILE
12855 "nofiles" "\0"
12856#endif
12857#ifdef RLIMIT_AS
12858 "vmemory(kb)" "\0"
12859#endif
12860#ifdef RLIMIT_LOCKS
12861 "locks" "\0"
12862#endif
12863;
Eric Andersenc470f442003-07-28 09:56:35 +000012864
Glenn L McGrath76620622004-01-13 10:19:37 +000012865enum limtype { SOFT = 0x1, HARD = 0x2 };
12866
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012867static void
12868printlim(enum limtype how, const struct rlimit *limit,
Glenn L McGrath76620622004-01-13 10:19:37 +000012869 const struct limits *l)
12870{
12871 rlim_t val;
12872
12873 val = limit->rlim_max;
12874 if (how & SOFT)
12875 val = limit->rlim_cur;
12876
12877 if (val == RLIM_INFINITY)
12878 out1fmt("unlimited\n");
12879 else {
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012880 val >>= l->factor_shift;
Glenn L McGrath76620622004-01-13 10:19:37 +000012881 out1fmt("%lld\n", (long long) val);
12882 }
12883}
12884
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012885static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012886ulimitcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersenc470f442003-07-28 09:56:35 +000012887{
Denys Vlasenko76622db2009-10-04 01:14:19 +020012888 rlim_t val;
Glenn L McGrath76620622004-01-13 10:19:37 +000012889 enum limtype how = SOFT | HARD;
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012890 const struct limits *l;
12891 int set, all = 0;
12892 int optc, what;
12893 struct rlimit limit;
Eric Andersenc470f442003-07-28 09:56:35 +000012894
12895 what = 'f';
Glenn L McGrath16e45d72004-02-04 08:24:39 +000012896 while ((optc = nextopt("HSa"
12897#ifdef RLIMIT_CPU
12898 "t"
12899#endif
12900#ifdef RLIMIT_FSIZE
12901 "f"
12902#endif
12903#ifdef RLIMIT_DATA
12904 "d"
12905#endif
12906#ifdef RLIMIT_STACK
12907 "s"
12908#endif
12909#ifdef RLIMIT_CORE
12910 "c"
12911#endif
12912#ifdef RLIMIT_RSS
12913 "m"
12914#endif
12915#ifdef RLIMIT_MEMLOCK
12916 "l"
12917#endif
12918#ifdef RLIMIT_NPROC
12919 "p"
12920#endif
12921#ifdef RLIMIT_NOFILE
12922 "n"
12923#endif
12924#ifdef RLIMIT_AS
12925 "v"
12926#endif
12927#ifdef RLIMIT_LOCKS
12928 "w"
12929#endif
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000012930 )) != '\0')
Eric Andersenc470f442003-07-28 09:56:35 +000012931 switch (optc) {
12932 case 'H':
12933 how = HARD;
12934 break;
12935 case 'S':
12936 how = SOFT;
12937 break;
12938 case 'a':
12939 all = 1;
12940 break;
12941 default:
12942 what = optc;
12943 }
12944
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012945 for (l = limits_tbl; l->option != what; l++)
12946 continue;
Eric Andersenc470f442003-07-28 09:56:35 +000012947
12948 set = *argptr ? 1 : 0;
Denys Vlasenko76622db2009-10-04 01:14:19 +020012949 val = 0;
Eric Andersenc470f442003-07-28 09:56:35 +000012950 if (set) {
12951 char *p = *argptr;
12952
12953 if (all || argptr[1])
Denis Vlasenkob012b102007-02-19 22:43:01 +000012954 ash_msg_and_raise_error("too many arguments");
Eric Andersen81fe1232003-07-29 06:38:40 +000012955 if (strncmp(p, "unlimited\n", 9) == 0)
Eric Andersenc470f442003-07-28 09:56:35 +000012956 val = RLIM_INFINITY;
12957 else {
Denys Vlasenko76622db2009-10-04 01:14:19 +020012958 if (sizeof(val) == sizeof(int))
12959 val = bb_strtou(p, NULL, 10);
12960 else if (sizeof(val) == sizeof(long))
12961 val = bb_strtoul(p, NULL, 10);
12962 else
12963 val = bb_strtoull(p, NULL, 10);
12964 if (errno)
Denis Vlasenkob012b102007-02-19 22:43:01 +000012965 ash_msg_and_raise_error("bad number");
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012966 val <<= l->factor_shift;
Eric Andersenc470f442003-07-28 09:56:35 +000012967 }
12968 }
12969 if (all) {
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012970 const char *lname = limits_name;
12971 for (l = limits_tbl; l != &limits_tbl[ARRAY_SIZE(limits_tbl)]; l++) {
Eric Andersenc470f442003-07-28 09:56:35 +000012972 getrlimit(l->cmd, &limit);
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012973 out1fmt("%-20s ", lname);
12974 lname += strlen(lname) + 1;
Glenn L McGrath76620622004-01-13 10:19:37 +000012975 printlim(how, &limit, l);
Eric Andersenc470f442003-07-28 09:56:35 +000012976 }
12977 return 0;
12978 }
12979
12980 getrlimit(l->cmd, &limit);
12981 if (set) {
12982 if (how & HARD)
12983 limit.rlim_max = val;
12984 if (how & SOFT)
12985 limit.rlim_cur = val;
12986 if (setrlimit(l->cmd, &limit) < 0)
Denis Vlasenkob012b102007-02-19 22:43:01 +000012987 ash_msg_and_raise_error("error setting limit (%m)");
Eric Andersenc470f442003-07-28 09:56:35 +000012988 } else {
Glenn L McGrath76620622004-01-13 10:19:37 +000012989 printlim(how, &limit, l);
Eric Andersenc470f442003-07-28 09:56:35 +000012990 }
12991 return 0;
12992}
12993
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012994/* ============ main() and helpers */
12995
12996/*
12997 * Called to exit the shell.
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012998 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012999static void exitshell(void) NORETURN;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000013000static void
13001exitshell(void)
13002{
13003 struct jmploc loc;
13004 char *p;
13005 int status;
13006
13007 status = exitstatus;
13008 TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
13009 if (setjmp(loc.loc)) {
Denis Vlasenko7f88e342009-03-19 03:36:18 +000013010 if (exception_type == EXEXIT)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000013011/* dash bug: it just does _exit(exitstatus) here
13012 * but we have to do setjobctl(0) first!
13013 * (bug is still not fixed in dash-0.5.3 - if you run dash
13014 * under Midnight Commander, on exit from dash MC is backgrounded) */
13015 status = exitstatus;
13016 goto out;
13017 }
13018 exception_handler = &loc;
13019 p = trap[0];
13020 if (p) {
13021 trap[0] = NULL;
13022 evalstring(p, 0);
Denys Vlasenko0800e3a2009-09-24 03:09:26 +020013023 free(p);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000013024 }
13025 flush_stdout_stderr();
13026 out:
13027 setjobctl(0);
13028 _exit(status);
13029 /* NOTREACHED */
13030}
13031
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000013032static void
13033init(void)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013034{
13035 /* from input.c: */
Denis Vlasenko41eb3002008-11-28 03:42:31 +000013036 basepf.next_to_pgetc = basepf.buf = basebuf;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013037
13038 /* from trap.c: */
13039 signal(SIGCHLD, SIG_DFL);
Denys Vlasenko7a7b0342009-12-04 04:18:31 +010013040 /* bash re-enables SIGHUP which is SIG_IGNed on entry.
13041 * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
13042 */
13043 signal(SIGHUP, SIG_DFL);
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013044
13045 /* from var.c: */
13046 {
13047 char **envp;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013048 const char *p;
13049 struct stat st1, st2;
13050
13051 initvar();
13052 for (envp = environ; envp && *envp; envp++) {
13053 if (strchr(*envp, '=')) {
13054 setvareq(*envp, VEXPORT|VTEXTFIXED);
13055 }
13056 }
13057
Denys Vlasenko7bb346f2009-10-06 22:09:50 +020013058 setvar("PPID", utoa(getppid()), 0);
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013059
13060 p = lookupvar("PWD");
13061 if (p)
13062 if (*p != '/' || stat(p, &st1) || stat(".", &st2)
13063 || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino)
13064 p = '\0';
13065 setpwd(p, 0);
13066 }
13067}
13068
13069/*
13070 * Process the shell command line arguments.
13071 */
13072static void
Denis Vlasenko68404f12008-03-17 09:00:54 +000013073procargs(char **argv)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013074{
13075 int i;
13076 const char *xminusc;
13077 char **xargv;
13078
13079 xargv = argv;
13080 arg0 = xargv[0];
Denis Vlasenko68404f12008-03-17 09:00:54 +000013081 /* if (xargv[0]) - mmm, this is always true! */
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013082 xargv++;
13083 for (i = 0; i < NOPTS; i++)
13084 optlist[i] = 2;
13085 argptr = xargv;
Denis Vlasenko28bf6712008-02-14 15:01:47 +000013086 if (options(1)) {
13087 /* it already printed err message */
13088 raise_exception(EXERROR);
13089 }
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013090 xargv = argptr;
13091 xminusc = minusc;
13092 if (*xargv == NULL) {
13093 if (xminusc)
13094 ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
13095 sflag = 1;
13096 }
13097 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
13098 iflag = 1;
13099 if (mflag == 2)
13100 mflag = iflag;
13101 for (i = 0; i < NOPTS; i++)
13102 if (optlist[i] == 2)
13103 optlist[i] = 0;
13104#if DEBUG == 2
13105 debug = 1;
13106#endif
13107 /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
13108 if (xminusc) {
13109 minusc = *xargv++;
13110 if (*xargv)
13111 goto setarg0;
13112 } else if (!sflag) {
13113 setinputfile(*xargv, 0);
13114 setarg0:
13115 arg0 = *xargv++;
13116 commandname = arg0;
13117 }
13118
13119 shellparam.p = xargv;
13120#if ENABLE_ASH_GETOPTS
13121 shellparam.optind = 1;
13122 shellparam.optoff = -1;
13123#endif
Denis Vlasenko01631112007-12-16 17:20:38 +000013124 /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013125 while (*xargv) {
13126 shellparam.nparam++;
13127 xargv++;
13128 }
13129 optschanged();
13130}
13131
13132/*
13133 * Read /etc/profile or .profile.
13134 */
13135static void
13136read_profile(const char *name)
13137{
13138 int skip;
13139
13140 if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
13141 return;
13142 skip = cmdloop(0);
13143 popfile();
13144 if (skip)
13145 exitshell();
13146}
13147
Denis Vlasenko0c032a42007-02-23 01:03:40 +000013148/*
13149 * This routine is called when an error or an interrupt occurs in an
13150 * interactive shell and control is returned to the main command loop.
13151 */
13152static void
13153reset(void)
13154{
13155 /* from eval.c: */
13156 evalskip = 0;
13157 loopnest = 0;
13158 /* from input.c: */
Denis Vlasenko41eb3002008-11-28 03:42:31 +000013159 g_parsefile->left_in_buffer = 0;
13160 g_parsefile->left_in_line = 0; /* clear input buffer */
Denis Vlasenko0c032a42007-02-23 01:03:40 +000013161 popallfiles();
13162 /* from parser.c: */
13163 tokpushback = 0;
13164 checkkwd = 0;
13165 /* from redir.c: */
Denis Vlasenko34c73c42008-08-16 11:48:02 +000013166 clearredir(/*drop:*/ 0);
Denis Vlasenko0c032a42007-02-23 01:03:40 +000013167}
13168
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013169#if PROFILE
13170static short profile_buf[16384];
13171extern int etext();
13172#endif
13173
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000013174/*
13175 * Main routine. We initialize things, parse the arguments, execute
13176 * profiles if we're a login shell, and then call cmdloop to execute
13177 * commands. The setjmp call sets up the location to jump to when an
13178 * exception occurs. When an exception occurs the variable "state"
13179 * is used to figure out how far we had gotten.
13180 */
Denis Vlasenko9b49a5e2007-10-11 10:05:36 +000013181int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000013182int ash_main(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013183{
Mike Frysinger98c52642009-04-02 10:02:37 +000013184 const char *shinit;
Denis Vlasenko4e12b1a2008-12-23 23:36:47 +000013185 volatile smallint state;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013186 struct jmploc jmploc;
13187 struct stackmark smark;
13188
Denis Vlasenko01631112007-12-16 17:20:38 +000013189 /* Initialize global data */
13190 INIT_G_misc();
13191 INIT_G_memstack();
13192 INIT_G_var();
Denis Vlasenkoee87ebf2007-12-21 22:18:16 +000013193#if ENABLE_ASH_ALIAS
Denis Vlasenko01631112007-12-16 17:20:38 +000013194 INIT_G_alias();
Denis Vlasenkoee87ebf2007-12-21 22:18:16 +000013195#endif
Denis Vlasenko01631112007-12-16 17:20:38 +000013196 INIT_G_cmdtable();
13197
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013198#if PROFILE
13199 monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
13200#endif
13201
13202#if ENABLE_FEATURE_EDITING
13203 line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
13204#endif
13205 state = 0;
13206 if (setjmp(jmploc.loc)) {
Denis Vlasenko7f88e342009-03-19 03:36:18 +000013207 smallint e;
Denis Vlasenko4e12b1a2008-12-23 23:36:47 +000013208 smallint s;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013209
13210 reset();
13211
Denis Vlasenko7f88e342009-03-19 03:36:18 +000013212 e = exception_type;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013213 if (e == EXERROR)
13214 exitstatus = 2;
13215 s = state;
13216 if (e == EXEXIT || s == 0 || iflag == 0 || shlvl)
13217 exitshell();
Denis Vlasenko7f88e342009-03-19 03:36:18 +000013218 if (e == EXINT)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013219 outcslow('\n', stderr);
Denis Vlasenko7f88e342009-03-19 03:36:18 +000013220
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013221 popstackmark(&smark);
13222 FORCE_INT_ON; /* enable interrupts */
13223 if (s == 1)
13224 goto state1;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000013225 if (s == 2)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013226 goto state2;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000013227 if (s == 3)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013228 goto state3;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000013229 goto state4;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013230 }
13231 exception_handler = &jmploc;
13232#if DEBUG
13233 opentrace();
Denis Vlasenko653d8e72009-03-19 21:59:35 +000013234 TRACE(("Shell args: "));
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000013235 trace_puts_args(argv);
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013236#endif
13237 rootpid = getpid();
13238
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013239 init();
13240 setstackmark(&smark);
Denis Vlasenko68404f12008-03-17 09:00:54 +000013241 procargs(argv);
13242
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013243#if ENABLE_FEATURE_EDITING_SAVEHISTORY
13244 if (iflag) {
13245 const char *hp = lookupvar("HISTFILE");
13246
13247 if (hp == NULL) {
13248 hp = lookupvar("HOME");
13249 if (hp != NULL) {
13250 char *defhp = concat_path_file(hp, ".ash_history");
13251 setvar("HISTFILE", defhp, 0);
13252 free(defhp);
13253 }
13254 }
13255 }
13256#endif
Denis Vlasenko4e12b1a2008-12-23 23:36:47 +000013257 if (/* argv[0] && */ argv[0][0] == '-')
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013258 isloginsh = 1;
13259 if (isloginsh) {
13260 state = 1;
13261 read_profile("/etc/profile");
13262 state1:
13263 state = 2;
13264 read_profile(".profile");
13265 }
13266 state2:
13267 state = 3;
13268 if (
13269#ifndef linux
Denis Vlasenko0c032a42007-02-23 01:03:40 +000013270 getuid() == geteuid() && getgid() == getegid() &&
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013271#endif
Denis Vlasenko0c032a42007-02-23 01:03:40 +000013272 iflag
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013273 ) {
13274 shinit = lookupvar("ENV");
13275 if (shinit != NULL && *shinit != '\0') {
13276 read_profile(shinit);
13277 }
13278 }
13279 state3:
13280 state = 4;
Denis Vlasenko5c2b8142009-03-19 01:59:59 +000013281 if (minusc) {
13282 /* evalstring pushes parsefile stack.
13283 * Ensure we don't falsely claim that 0 (stdin)
Denis Vlasenko5368ad52009-03-20 10:20:08 +000013284 * is one of stacked source fds.
13285 * Testcase: ash -c 'exec 1>&0' must not complain. */
Denis Vlasenko5c2b8142009-03-19 01:59:59 +000013286 if (!sflag)
13287 g_parsefile->fd = -1;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013288 evalstring(minusc, 0);
Denis Vlasenko5c2b8142009-03-19 01:59:59 +000013289 }
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013290
13291 if (sflag || minusc == NULL) {
Denys Vlasenko0337e032009-11-29 00:12:30 +010013292#if defined MAX_HISTORY && MAX_HISTORY > 0 && ENABLE_FEATURE_EDITING_SAVEHISTORY
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +000013293 if (iflag) {
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013294 const char *hp = lookupvar("HISTFILE");
Denis Vlasenko5c2b8142009-03-19 01:59:59 +000013295 if (hp)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013296 line_input_state->hist_file = hp;
13297 }
13298#endif
13299 state4: /* XXX ??? - why isn't this before the "if" statement */
13300 cmdloop(1);
13301 }
13302#if PROFILE
13303 monitor(0);
13304#endif
13305#ifdef GPROF
13306 {
13307 extern void _mcleanup(void);
13308 _mcleanup();
13309 }
13310#endif
13311 exitshell();
13312 /* NOTREACHED */
13313}
13314
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013315
Eric Andersendf82f612001-06-28 07:46:40 +000013316/*-
13317 * Copyright (c) 1989, 1991, 1993, 1994
Eric Andersen2870d962001-07-02 17:27:21 +000013318 * The Regents of the University of California. All rights reserved.
Eric Andersendf82f612001-06-28 07:46:40 +000013319 *
13320 * This code is derived from software contributed to Berkeley by
13321 * Kenneth Almquist.
13322 *
13323 * Redistribution and use in source and binary forms, with or without
13324 * modification, are permitted provided that the following conditions
13325 * are met:
13326 * 1. Redistributions of source code must retain the above copyright
13327 * notice, this list of conditions and the following disclaimer.
13328 * 2. Redistributions in binary form must reproduce the above copyright
13329 * notice, this list of conditions and the following disclaimer in the
13330 * documentation and/or other materials provided with the distribution.
"Vladimir N. Oleynik"ddc280e2005-12-15 12:01:49 +000013331 * 3. Neither the name of the University nor the names of its contributors
Eric Andersendf82f612001-06-28 07:46:40 +000013332 * may be used to endorse or promote products derived from this software
13333 * without specific prior written permission.
13334 *
13335 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
13336 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
13337 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
13338 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
13339 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
13340 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
13341 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
13342 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
13343 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
13344 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
13345 * SUCH DAMAGE.
13346 */