blob: 597bc2808b1c86546d53086850de7588067038a9 [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"
Denis Vlasenko61befda2008-11-25 01:36:03 +000054
55#if defined SINGLE_APPLET_MAIN
56/* STANDALONE does not make sense, and won't compile */
57#undef CONFIG_FEATURE_SH_STANDALONE
58#undef ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko5e34ff22009-04-21 11:09:40 +000059#undef IF_FEATURE_SH_STANDALONE
60#undef IF_NOT_FEATURE_SH_STANDALONE(...)
Denis Vlasenko61befda2008-11-25 01:36:03 +000061#define ENABLE_FEATURE_SH_STANDALONE 0
Denis Vlasenko5e34ff22009-04-21 11:09:40 +000062#define IF_FEATURE_SH_STANDALONE(...)
63#define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
Eric Andersencb57d552001-06-28 07:25:16 +000064#endif
65
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000066#ifndef PIPE_BUF
Denis Vlasenko653d8e72009-03-19 21:59:35 +000067# define PIPE_BUF 4096 /* amount of buffering in a pipe */
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000068#endif
69
Denis Vlasenkob012b102007-02-19 22:43:01 +000070#if defined(__uClinux__)
Denis Vlasenko653d8e72009-03-19 21:59:35 +000071# error "Do not even bother, ash will not run on NOMMU machine"
Denis Vlasenkob012b102007-02-19 22:43:01 +000072#endif
73
Denis Vlasenkob012b102007-02-19 22:43:01 +000074
Denis Vlasenko01631112007-12-16 17:20:38 +000075/* ============ Hash table sizes. Configurable. */
76
77#define VTABSIZE 39
78#define ATABSIZE 39
79#define CMDTABLESIZE 31 /* should be prime */
80
81
Denis Vlasenkob012b102007-02-19 22:43:01 +000082/* ============ Shell options */
83
84static const char *const optletters_optnames[] = {
85 "e" "errexit",
86 "f" "noglob",
87 "I" "ignoreeof",
88 "i" "interactive",
89 "m" "monitor",
90 "n" "noexec",
91 "s" "stdin",
92 "x" "xtrace",
93 "v" "verbose",
94 "C" "noclobber",
95 "a" "allexport",
96 "b" "notify",
97 "u" "nounset",
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000098 "\0" "vi"
Denis Vlasenkob012b102007-02-19 22:43:01 +000099#if DEBUG
Denis Vlasenko6ca409e2007-08-12 20:58:27 +0000100 ,"\0" "nolog"
101 ,"\0" "debug"
Denis Vlasenkob012b102007-02-19 22:43:01 +0000102#endif
103};
104
105#define optletters(n) optletters_optnames[(n)][0]
106#define optnames(n) (&optletters_optnames[(n)][1])
107
Denis Vlasenko80b8b392007-06-25 10:55:35 +0000108enum { NOPTS = ARRAY_SIZE(optletters_optnames) };
Denis Vlasenkob012b102007-02-19 22:43:01 +0000109
Eric Andersenc470f442003-07-28 09:56:35 +0000110
Denis Vlasenkob012b102007-02-19 22:43:01 +0000111/* ============ Misc data */
Eric Andersenc470f442003-07-28 09:56:35 +0000112
Denis Vlasenko6ca409e2007-08-12 20:58:27 +0000113static const char homestr[] ALIGN1 = "HOME";
114static const char snlfmt[] ALIGN1 = "%s\n";
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200115static const char msg_illnum[] ALIGN1 = "Illegal number: %s";
Denis Vlasenkoaa744452007-02-23 01:04:22 +0000116
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +0000117/*
Eric Andersenc470f442003-07-28 09:56:35 +0000118 * We enclose jmp_buf in a structure so that we can declare pointers to
119 * jump locations. The global variable handler contains the location to
Denis Vlasenkof1733952009-03-19 23:21:55 +0000120 * jump to when an exception occurs, and the global variable exception_type
Eric Andersenaff114c2004-04-14 17:51:38 +0000121 * contains a code identifying the exception. To implement nested
Eric Andersenc470f442003-07-28 09:56:35 +0000122 * exception handlers, the user should save the value of handler on entry
123 * to an inner scope, set handler to point to a jmploc structure for the
124 * inner scope, and restore handler on exit from the scope.
125 */
Eric Andersenc470f442003-07-28 09:56:35 +0000126struct jmploc {
127 jmp_buf loc;
128};
Denis Vlasenko01631112007-12-16 17:20:38 +0000129
130struct globals_misc {
131 /* pid of main shell */
132 int rootpid;
133 /* shell level: 0 for the main shell, 1 for its children, and so on */
134 int shlvl;
135#define rootshell (!shlvl)
136 char *minusc; /* argument to -c option */
137
138 char *curdir; // = nullstr; /* current working directory */
139 char *physdir; // = nullstr; /* physical working directory */
140
141 char *arg0; /* value of $0 */
142
143 struct jmploc *exception_handler;
Denis Vlasenko991a1da2008-02-10 19:02:53 +0000144
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200145 volatile int suppress_int; /* counter */
146 volatile /*sig_atomic_t*/ smallint pending_int; /* 1 = got SIGINT */
Denis Vlasenko991a1da2008-02-10 19:02:53 +0000147 /* last pending signal */
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200148 volatile /*sig_atomic_t*/ smallint pending_sig;
Denis Vlasenko7f88e342009-03-19 03:36:18 +0000149 smallint exception_type; /* kind of exception (0..5) */
Denis Vlasenko01631112007-12-16 17:20:38 +0000150 /* exceptions */
Eric Andersenc470f442003-07-28 09:56:35 +0000151#define EXINT 0 /* SIGINT received */
152#define EXERROR 1 /* a generic error */
153#define EXSHELLPROC 2 /* execute a shell procedure */
154#define EXEXEC 3 /* command execution failed */
155#define EXEXIT 4 /* exit the shell */
156#define EXSIG 5 /* trapped signal in wait(1) */
Eric Andersen2870d962001-07-02 17:27:21 +0000157
Denis Vlasenko01631112007-12-16 17:20:38 +0000158 smallint isloginsh;
Denis Vlasenkob07a4962008-06-22 13:16:23 +0000159 char nullstr[1]; /* zero length string */
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000160
161 char optlist[NOPTS];
162#define eflag optlist[0]
163#define fflag optlist[1]
164#define Iflag optlist[2]
165#define iflag optlist[3]
166#define mflag optlist[4]
167#define nflag optlist[5]
168#define sflag optlist[6]
169#define xflag optlist[7]
170#define vflag optlist[8]
171#define Cflag optlist[9]
172#define aflag optlist[10]
173#define bflag optlist[11]
174#define uflag optlist[12]
175#define viflag optlist[13]
176#if DEBUG
177#define nolog optlist[14]
178#define debug optlist[15]
179#endif
180
181 /* trap handler commands */
Denis Vlasenko01631112007-12-16 17:20:38 +0000182 /*
183 * Sigmode records the current value of the signal handlers for the various
184 * modes. A value of zero means that the current handler is not known.
Denis Vlasenkof8535cc2008-12-03 10:36:26 +0000185 * S_HARD_IGN indicates that the signal was ignored on entry to the shell.
Denis Vlasenko01631112007-12-16 17:20:38 +0000186 */
187 char sigmode[NSIG - 1];
Denis Vlasenkof8535cc2008-12-03 10:36:26 +0000188#define S_DFL 1 /* default signal handling (SIG_DFL) */
189#define S_CATCH 2 /* signal is caught */
190#define S_IGN 3 /* signal is ignored (SIG_IGN) */
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +0000191#define S_HARD_IGN 4 /* signal is ignored permenantly */
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +0000192
Denis Vlasenko01631112007-12-16 17:20:38 +0000193 /* indicates specified signal received */
Denis Vlasenko4b875702009-03-19 13:30:04 +0000194 uint8_t gotsig[NSIG - 1]; /* offset by 1: "signal" 0 is meaningless */
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000195 char *trap[NSIG];
Denis Vlasenko448d30e2008-06-27 00:24:11 +0000196
197 /* Rarely referenced stuff */
198#if ENABLE_ASH_RANDOM_SUPPORT
Denis Vlasenko26bc57d2008-06-27 00:29:34 +0000199 /* Random number generators */
200 int32_t random_galois_LFSR; /* Galois LFSR (fast but weak). signed! */
201 uint32_t random_LCG; /* LCG (fast but weak) */
Denis Vlasenko448d30e2008-06-27 00:24:11 +0000202#endif
203 pid_t backgndpid; /* pid of last background process */
204 smallint job_warning; /* user was warned about stopped jobs (can be 2, 1 or 0). */
Denis Vlasenko01631112007-12-16 17:20:38 +0000205};
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000206extern struct globals_misc *const ash_ptr_to_globals_misc;
207#define G_misc (*ash_ptr_to_globals_misc)
Denis Vlasenko26bc57d2008-06-27 00:29:34 +0000208#define rootpid (G_misc.rootpid )
209#define shlvl (G_misc.shlvl )
210#define minusc (G_misc.minusc )
211#define curdir (G_misc.curdir )
212#define physdir (G_misc.physdir )
213#define arg0 (G_misc.arg0 )
Denis Vlasenko01631112007-12-16 17:20:38 +0000214#define exception_handler (G_misc.exception_handler)
Denis Vlasenko7f88e342009-03-19 03:36:18 +0000215#define exception_type (G_misc.exception_type )
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200216#define suppress_int (G_misc.suppress_int )
217#define pending_int (G_misc.pending_int )
218#define pending_sig (G_misc.pending_sig )
Denis Vlasenko26bc57d2008-06-27 00:29:34 +0000219#define isloginsh (G_misc.isloginsh )
220#define nullstr (G_misc.nullstr )
221#define optlist (G_misc.optlist )
222#define sigmode (G_misc.sigmode )
223#define gotsig (G_misc.gotsig )
224#define trap (G_misc.trap )
Denis Vlasenko448d30e2008-06-27 00:24:11 +0000225#define random_galois_LFSR (G_misc.random_galois_LFSR)
226#define random_LCG (G_misc.random_LCG )
227#define backgndpid (G_misc.backgndpid )
228#define job_warning (G_misc.job_warning)
Denis Vlasenko01631112007-12-16 17:20:38 +0000229#define INIT_G_misc() do { \
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000230 (*(struct globals_misc**)&ash_ptr_to_globals_misc) = xzalloc(sizeof(G_misc)); \
231 barrier(); \
Denis Vlasenko01631112007-12-16 17:20:38 +0000232 curdir = nullstr; \
233 physdir = nullstr; \
234} while (0)
235
236
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000237/* ============ DEBUG */
238#if DEBUG
239static void trace_printf(const char *fmt, ...);
240static void trace_vprintf(const char *fmt, va_list va);
241# define TRACE(param) trace_printf param
242# define TRACEV(param) trace_vprintf param
Denis Vlasenko1bb3d7e2009-03-20 07:45:36 +0000243# define close(fd) do { \
244 int dfd = (fd); \
Denis Vlasenkob9e70dd2009-03-20 01:24:08 +0000245 if (close(dfd) < 0) \
Denys Vlasenko883cea42009-07-11 15:31:59 +0200246 bb_error_msg("bug on %d: closing %d(0x%x)", \
Denis Vlasenko1bb3d7e2009-03-20 07:45:36 +0000247 __LINE__, dfd, dfd); \
Denis Vlasenkob9e70dd2009-03-20 01:24:08 +0000248} while (0)
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000249#else
250# define TRACE(param)
251# define TRACEV(param)
252#endif
253
254
Denis Vlasenko559691a2008-10-05 18:39:31 +0000255/* ============ Utility functions */
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000256#define xbarrier() do { __asm__ __volatile__ ("": : :"memory"); } while (0)
257
Denys Vlasenko7cee00e2009-07-24 01:08:03 +0200258/* C99 says: "char" declaration may be signed or unsigned by default */
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000259#define signed_char2int(sc) ((int)(signed char)(sc))
260
Denis Vlasenko559691a2008-10-05 18:39:31 +0000261static int isdigit_str9(const char *str)
262{
263 int maxlen = 9 + 1; /* max 9 digits: 999999999 */
264 while (--maxlen && isdigit(*str))
265 str++;
266 return (*str == '\0');
267}
Denis Vlasenko01631112007-12-16 17:20:38 +0000268
Denis Vlasenko559691a2008-10-05 18:39:31 +0000269
270/* ============ Interrupts / exceptions */
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +0000271/*
Eric Andersen2870d962001-07-02 17:27:21 +0000272 * These macros allow the user to suspend the handling of interrupt signals
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +0000273 * over a period of time. This is similar to SIGHOLD or to sigblock, but
Eric Andersen2870d962001-07-02 17:27:21 +0000274 * much more efficient and portable. (But hacking the kernel is so much
275 * more fun than worrying about efficiency and portability. :-))
276 */
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000277#define INT_OFF do { \
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200278 suppress_int++; \
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000279 xbarrier(); \
280} while (0)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000281
282/*
283 * Called to raise an exception. Since C doesn't include exceptions, we
284 * just do a longjmp to the exception handler. The type of exception is
Denis Vlasenko4b875702009-03-19 13:30:04 +0000285 * stored in the global variable "exception_type".
Denis Vlasenkob012b102007-02-19 22:43:01 +0000286 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +0000287static void raise_exception(int) NORETURN;
Denis Vlasenkob012b102007-02-19 22:43:01 +0000288static void
289raise_exception(int e)
290{
291#if DEBUG
Denis Vlasenko2da584f2007-02-19 22:44:05 +0000292 if (exception_handler == NULL)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000293 abort();
294#endif
295 INT_OFF;
Denis Vlasenko7f88e342009-03-19 03:36:18 +0000296 exception_type = e;
Denis Vlasenko2da584f2007-02-19 22:44:05 +0000297 longjmp(exception_handler->loc, 1);
Denis Vlasenkob012b102007-02-19 22:43:01 +0000298}
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000299#if DEBUG
300#define raise_exception(e) do { \
301 TRACE(("raising exception %d on line %d\n", (e), __LINE__)); \
302 raise_exception(e); \
303} while (0)
304#endif
Denis Vlasenkob012b102007-02-19 22:43:01 +0000305
306/*
307 * Called from trap.c when a SIGINT is received. (If the user specifies
308 * that SIGINT is to be trapped or ignored using the trap builtin, then
309 * this routine is not called.) Suppressint is nonzero when interrupts
310 * are held using the INT_OFF macro. (The test for iflag is just
311 * defensive programming.)
312 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +0000313static void raise_interrupt(void) NORETURN;
Denis Vlasenkob012b102007-02-19 22:43:01 +0000314static void
315raise_interrupt(void)
316{
Denis Vlasenko4b875702009-03-19 13:30:04 +0000317 int ex_type;
Denis Vlasenkob012b102007-02-19 22:43:01 +0000318
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200319 pending_int = 0;
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +0000320 /* Signal is not automatically unmasked after it is raised,
321 * do it ourself - unmask all signals */
Denis Vlasenko3f165fa2008-03-17 08:29:08 +0000322 sigprocmask_allsigs(SIG_UNBLOCK);
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200323 /* pending_sig = 0; - now done in onsig() */
Denis Vlasenko7c139b42007-03-21 20:17:27 +0000324
Denis Vlasenko4b875702009-03-19 13:30:04 +0000325 ex_type = EXSIG;
Denis Vlasenkob012b102007-02-19 22:43:01 +0000326 if (gotsig[SIGINT - 1] && !trap[SIGINT]) {
327 if (!(rootshell && iflag)) {
Denis Vlasenko991a1da2008-02-10 19:02:53 +0000328 /* Kill ourself with SIGINT */
Denis Vlasenkob012b102007-02-19 22:43:01 +0000329 signal(SIGINT, SIG_DFL);
330 raise(SIGINT);
331 }
Denis Vlasenko4b875702009-03-19 13:30:04 +0000332 ex_type = EXINT;
Denis Vlasenkob012b102007-02-19 22:43:01 +0000333 }
Denis Vlasenko4b875702009-03-19 13:30:04 +0000334 raise_exception(ex_type);
Denis Vlasenkob012b102007-02-19 22:43:01 +0000335 /* NOTREACHED */
336}
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000337#if DEBUG
338#define raise_interrupt() do { \
339 TRACE(("raising interrupt on line %d\n", __LINE__)); \
340 raise_interrupt(); \
341} while (0)
342#endif
Denis Vlasenkob012b102007-02-19 22:43:01 +0000343
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000344static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000345int_on(void)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000346{
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +0000347 xbarrier();
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200348 if (--suppress_int == 0 && pending_int) {
Denis Vlasenkob012b102007-02-19 22:43:01 +0000349 raise_interrupt();
350 }
351}
352#define INT_ON int_on()
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000353static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000354force_int_on(void)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000355{
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +0000356 xbarrier();
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200357 suppress_int = 0;
358 if (pending_int)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000359 raise_interrupt();
360}
361#define FORCE_INT_ON force_int_on()
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000362
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200363#define SAVE_INT(v) ((v) = suppress_int)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000364
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000365#define RESTORE_INT(v) do { \
366 xbarrier(); \
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200367 suppress_int = (v); \
368 if (suppress_int == 0 && pending_int) \
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000369 raise_interrupt(); \
370} while (0)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000371
Glenn L McGrath9fef17d2002-08-22 18:41:20 +0000372
Denis Vlasenkobc54cff2007-02-23 01:05:52 +0000373/* ============ Stdout/stderr output */
Eric Andersenc470f442003-07-28 09:56:35 +0000374
Eric Andersenc470f442003-07-28 09:56:35 +0000375static void
Denis Vlasenkob012b102007-02-19 22:43:01 +0000376outstr(const char *p, FILE *file)
Denis Vlasenkoe5570da2007-02-19 22:41:55 +0000377{
Denis Vlasenkob012b102007-02-19 22:43:01 +0000378 INT_OFF;
379 fputs(p, file);
380 INT_ON;
381}
382
383static void
384flush_stdout_stderr(void)
385{
386 INT_OFF;
387 fflush(stdout);
388 fflush(stderr);
389 INT_ON;
390}
391
392static void
393flush_stderr(void)
394{
395 INT_OFF;
396 fflush(stderr);
397 INT_ON;
398}
399
400static void
401outcslow(int c, FILE *dest)
402{
403 INT_OFF;
404 putc(c, dest);
405 fflush(dest);
406 INT_ON;
407}
408
409static int out1fmt(const char *, ...) __attribute__((__format__(__printf__,1,2)));
410static int
411out1fmt(const char *fmt, ...)
412{
413 va_list ap;
414 int r;
415
416 INT_OFF;
417 va_start(ap, fmt);
418 r = vprintf(fmt, ap);
419 va_end(ap);
420 INT_ON;
421 return r;
422}
423
424static int fmtstr(char *, size_t, const char *, ...) __attribute__((__format__(__printf__,3,4)));
425static int
426fmtstr(char *outbuf, size_t length, const char *fmt, ...)
427{
428 va_list ap;
429 int ret;
430
431 va_start(ap, fmt);
432 INT_OFF;
433 ret = vsnprintf(outbuf, length, fmt, ap);
434 va_end(ap);
435 INT_ON;
436 return ret;
437}
438
439static void
440out1str(const char *p)
441{
442 outstr(p, stdout);
443}
444
445static void
446out2str(const char *p)
447{
448 outstr(p, stderr);
449 flush_stderr();
450}
451
452
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +0000453/* ============ Parser structures */
Denis Vlasenko4d2183b2007-02-23 01:05:38 +0000454
Denis Vlasenko5651bfc2007-02-23 21:08:58 +0000455/* control characters in argument strings */
Denys Vlasenkob6c84342009-08-29 20:23:20 +0200456#define CTLESC ((unsigned char)'\201') /* escape next character */
457#define CTLVAR ((unsigned char)'\202') /* variable defn */
458#define CTLENDVAR ((unsigned char)'\203')
459#define CTLBACKQ ((unsigned char)'\204')
Denis Vlasenko5651bfc2007-02-23 21:08:58 +0000460#define CTLQUOTE 01 /* ored with CTLBACKQ code if in quotes */
461/* CTLBACKQ | CTLQUOTE == '\205' */
Denys Vlasenkob6c84342009-08-29 20:23:20 +0200462#define CTLARI ((unsigned char)'\206') /* arithmetic expression */
463#define CTLENDARI ((unsigned char)'\207')
464#define CTLQUOTEMARK ((unsigned char)'\210')
Denis Vlasenko5651bfc2007-02-23 21:08:58 +0000465
466/* variable substitution byte (follows CTLVAR) */
467#define VSTYPE 0x0f /* type of variable substitution */
468#define VSNUL 0x10 /* colon--treat the empty string as unset */
469#define VSQUOTE 0x80 /* inside double quotes--suppress splitting */
470
471/* values of VSTYPE field */
Denis Vlasenko92e13c22008-03-25 01:17:40 +0000472#define VSNORMAL 0x1 /* normal variable: $var or ${var} */
473#define VSMINUS 0x2 /* ${var-text} */
474#define VSPLUS 0x3 /* ${var+text} */
475#define VSQUESTION 0x4 /* ${var?message} */
476#define VSASSIGN 0x5 /* ${var=text} */
477#define VSTRIMRIGHT 0x6 /* ${var%pattern} */
478#define VSTRIMRIGHTMAX 0x7 /* ${var%%pattern} */
479#define VSTRIMLEFT 0x8 /* ${var#pattern} */
480#define VSTRIMLEFTMAX 0x9 /* ${var##pattern} */
481#define VSLENGTH 0xa /* ${#var} */
482#if ENABLE_ASH_BASH_COMPAT
483#define VSSUBSTR 0xc /* ${var:position:length} */
484#define VSREPLACE 0xd /* ${var/pattern/replacement} */
485#define VSREPLACEALL 0xe /* ${var//pattern/replacement} */
486#endif
Denis Vlasenko5651bfc2007-02-23 21:08:58 +0000487
Denis Vlasenko6ca409e2007-08-12 20:58:27 +0000488static const char dolatstr[] ALIGN1 = {
489 CTLVAR, VSNORMAL|VSQUOTE, '@', '=', '\0'
490};
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +0000491
Denis Vlasenko559691a2008-10-05 18:39:31 +0000492#define NCMD 0
493#define NPIPE 1
494#define NREDIR 2
495#define NBACKGND 3
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000496#define NSUBSHELL 4
Denis Vlasenko559691a2008-10-05 18:39:31 +0000497#define NAND 5
498#define NOR 6
499#define NSEMI 7
500#define NIF 8
501#define NWHILE 9
502#define NUNTIL 10
503#define NFOR 11
504#define NCASE 12
505#define NCLIST 13
506#define NDEFUN 14
507#define NARG 15
508#define NTO 16
509#if ENABLE_ASH_BASH_COMPAT
510#define NTO2 17
511#endif
512#define NCLOBBER 18
513#define NFROM 19
514#define NFROMTO 20
515#define NAPPEND 21
516#define NTOFD 22
517#define NFROMFD 23
518#define NHERE 24
519#define NXHERE 25
520#define NNOT 26
Denis Vlasenko340299a2008-11-21 10:36:36 +0000521#define N_NUMBER 27
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000522
523union node;
524
525struct ncmd {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000526 smallint type; /* Nxxxx */
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000527 union node *assign;
528 union node *args;
529 union node *redirect;
530};
531
532struct npipe {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000533 smallint type;
534 smallint pipe_backgnd;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000535 struct nodelist *cmdlist;
536};
537
538struct nredir {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000539 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000540 union node *n;
541 union node *redirect;
542};
543
544struct nbinary {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000545 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000546 union node *ch1;
547 union node *ch2;
548};
549
550struct nif {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000551 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000552 union node *test;
553 union node *ifpart;
554 union node *elsepart;
555};
556
557struct nfor {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000558 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000559 union node *args;
560 union node *body;
561 char *var;
562};
563
564struct ncase {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000565 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000566 union node *expr;
567 union node *cases;
568};
569
570struct nclist {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000571 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000572 union node *next;
573 union node *pattern;
574 union node *body;
575};
576
577struct narg {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000578 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000579 union node *next;
580 char *text;
581 struct nodelist *backquote;
582};
583
Denis Vlasenko559691a2008-10-05 18:39:31 +0000584/* nfile and ndup layout must match!
585 * NTOFD (>&fdnum) uses ndup structure, but we may discover mid-flight
586 * that it is actually NTO2 (>&file), and change its type.
587 */
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000588struct nfile {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000589 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000590 union node *next;
591 int fd;
Denis Vlasenko559691a2008-10-05 18:39:31 +0000592 int _unused_dupfd;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000593 union node *fname;
594 char *expfname;
595};
596
597struct ndup {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000598 smallint type;
Denis Vlasenko559691a2008-10-05 18:39:31 +0000599 union node *next;
600 int fd;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000601 int dupfd;
602 union node *vname;
Denis Vlasenko559691a2008-10-05 18:39:31 +0000603 char *_unused_expfname;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000604};
605
606struct nhere {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000607 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000608 union node *next;
609 int fd;
610 union node *doc;
611};
612
613struct nnot {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000614 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000615 union node *com;
616};
617
618union node {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000619 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000620 struct ncmd ncmd;
621 struct npipe npipe;
622 struct nredir nredir;
623 struct nbinary nbinary;
624 struct nif nif;
625 struct nfor nfor;
626 struct ncase ncase;
627 struct nclist nclist;
628 struct narg narg;
629 struct nfile nfile;
630 struct ndup ndup;
631 struct nhere nhere;
632 struct nnot nnot;
633};
634
Denys Vlasenko86e83ec2009-07-23 22:07:07 +0200635/*
636 * NODE_EOF is returned by parsecmd when it encounters an end of file.
637 * It must be distinct from NULL.
638 */
639#define NODE_EOF ((union node *) -1L)
640
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000641struct nodelist {
642 struct nodelist *next;
643 union node *n;
644};
645
646struct funcnode {
647 int count;
648 union node n;
649};
650
Denis Vlasenko5651bfc2007-02-23 21:08:58 +0000651/*
652 * Free a parse tree.
653 */
654static void
655freefunc(struct funcnode *f)
656{
657 if (f && --f->count < 0)
658 free(f);
659}
660
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000661
662/* ============ Debugging output */
663
664#if DEBUG
665
666static FILE *tracefile;
667
668static void
669trace_printf(const char *fmt, ...)
670{
671 va_list va;
672
673 if (debug != 1)
674 return;
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000675 if (DEBUG_TIME)
676 fprintf(tracefile, "%u ", (int) time(NULL));
677 if (DEBUG_PID)
678 fprintf(tracefile, "[%u] ", (int) getpid());
679 if (DEBUG_SIG)
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200680 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000681 va_start(va, fmt);
682 vfprintf(tracefile, fmt, va);
683 va_end(va);
684}
685
686static void
687trace_vprintf(const char *fmt, va_list va)
688{
689 if (debug != 1)
690 return;
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000691 if (DEBUG_TIME)
692 fprintf(tracefile, "%u ", (int) time(NULL));
693 if (DEBUG_PID)
694 fprintf(tracefile, "[%u] ", (int) getpid());
695 if (DEBUG_SIG)
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200696 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000697 vfprintf(tracefile, fmt, va);
698}
699
700static void
701trace_puts(const char *s)
702{
703 if (debug != 1)
704 return;
705 fputs(s, tracefile);
706}
707
708static void
709trace_puts_quoted(char *s)
710{
711 char *p;
712 char c;
713
714 if (debug != 1)
715 return;
716 putc('"', tracefile);
717 for (p = s; *p; p++) {
718 switch (*p) {
719 case '\n': c = 'n'; goto backslash;
720 case '\t': c = 't'; goto backslash;
721 case '\r': c = 'r'; goto backslash;
722 case '"': c = '"'; goto backslash;
723 case '\\': c = '\\'; goto backslash;
724 case CTLESC: c = 'e'; goto backslash;
725 case CTLVAR: c = 'v'; goto backslash;
726 case CTLVAR+CTLQUOTE: c = 'V'; goto backslash;
727 case CTLBACKQ: c = 'q'; goto backslash;
728 case CTLBACKQ+CTLQUOTE: c = 'Q'; goto backslash;
729 backslash:
730 putc('\\', tracefile);
731 putc(c, tracefile);
732 break;
733 default:
734 if (*p >= ' ' && *p <= '~')
735 putc(*p, tracefile);
736 else {
737 putc('\\', tracefile);
738 putc(*p >> 6 & 03, tracefile);
739 putc(*p >> 3 & 07, tracefile);
740 putc(*p & 07, tracefile);
741 }
742 break;
743 }
744 }
745 putc('"', tracefile);
746}
747
748static void
749trace_puts_args(char **ap)
750{
751 if (debug != 1)
752 return;
753 if (!*ap)
754 return;
755 while (1) {
756 trace_puts_quoted(*ap);
757 if (!*++ap) {
758 putc('\n', tracefile);
759 break;
760 }
761 putc(' ', tracefile);
762 }
763}
764
765static void
766opentrace(void)
767{
768 char s[100];
769#ifdef O_APPEND
770 int flags;
771#endif
772
773 if (debug != 1) {
774 if (tracefile)
775 fflush(tracefile);
776 /* leave open because libedit might be using it */
777 return;
778 }
779 strcpy(s, "./trace");
780 if (tracefile) {
781 if (!freopen(s, "a", tracefile)) {
782 fprintf(stderr, "Can't re-open %s\n", s);
783 debug = 0;
784 return;
785 }
786 } else {
787 tracefile = fopen(s, "a");
788 if (tracefile == NULL) {
789 fprintf(stderr, "Can't open %s\n", s);
790 debug = 0;
791 return;
792 }
793 }
794#ifdef O_APPEND
Denis Vlasenkod37f2222007-08-19 13:42:08 +0000795 flags = fcntl(fileno(tracefile), F_GETFL);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000796 if (flags >= 0)
797 fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
798#endif
799 setlinebuf(tracefile);
800 fputs("\nTracing started.\n", tracefile);
801}
802
803static void
804indent(int amount, char *pfx, FILE *fp)
805{
806 int i;
807
808 for (i = 0; i < amount; i++) {
809 if (pfx && i == amount - 1)
810 fputs(pfx, fp);
811 putc('\t', fp);
812 }
813}
814
815/* little circular references here... */
816static void shtree(union node *n, int ind, char *pfx, FILE *fp);
817
818static void
819sharg(union node *arg, FILE *fp)
820{
821 char *p;
822 struct nodelist *bqlist;
823 int subtype;
824
825 if (arg->type != NARG) {
826 out1fmt("<node type %d>\n", arg->type);
827 abort();
828 }
829 bqlist = arg->narg.backquote;
830 for (p = arg->narg.text; *p; p++) {
831 switch (*p) {
832 case CTLESC:
833 putc(*++p, fp);
834 break;
835 case CTLVAR:
836 putc('$', fp);
837 putc('{', fp);
838 subtype = *++p;
839 if (subtype == VSLENGTH)
840 putc('#', fp);
841
842 while (*p != '=')
843 putc(*p++, fp);
844
845 if (subtype & VSNUL)
846 putc(':', fp);
847
848 switch (subtype & VSTYPE) {
849 case VSNORMAL:
850 putc('}', fp);
851 break;
852 case VSMINUS:
853 putc('-', fp);
854 break;
855 case VSPLUS:
856 putc('+', fp);
857 break;
858 case VSQUESTION:
859 putc('?', fp);
860 break;
861 case VSASSIGN:
862 putc('=', fp);
863 break;
864 case VSTRIMLEFT:
865 putc('#', fp);
866 break;
867 case VSTRIMLEFTMAX:
868 putc('#', fp);
869 putc('#', fp);
870 break;
871 case VSTRIMRIGHT:
872 putc('%', fp);
873 break;
874 case VSTRIMRIGHTMAX:
875 putc('%', fp);
876 putc('%', fp);
877 break;
878 case VSLENGTH:
879 break;
880 default:
881 out1fmt("<subtype %d>", subtype);
882 }
883 break;
884 case CTLENDVAR:
885 putc('}', fp);
886 break;
887 case CTLBACKQ:
888 case CTLBACKQ|CTLQUOTE:
889 putc('$', fp);
890 putc('(', fp);
891 shtree(bqlist->n, -1, NULL, fp);
892 putc(')', fp);
893 break;
894 default:
895 putc(*p, fp);
896 break;
897 }
898 }
899}
900
Denys Vlasenko641dd7b2009-06-11 19:30:19 +0200901static void
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000902shcmd(union node *cmd, FILE *fp)
903{
904 union node *np;
905 int first;
906 const char *s;
907 int dftfd;
908
909 first = 1;
910 for (np = cmd->ncmd.args; np; np = np->narg.next) {
Denis Vlasenko40ba9982007-07-14 00:48:29 +0000911 if (!first)
912 putc(' ', fp);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000913 sharg(np, fp);
914 first = 0;
915 }
916 for (np = cmd->ncmd.redirect; np; np = np->nfile.next) {
Denis Vlasenko40ba9982007-07-14 00:48:29 +0000917 if (!first)
918 putc(' ', fp);
919 dftfd = 0;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000920 switch (np->nfile.type) {
Denis Vlasenko40ba9982007-07-14 00:48:29 +0000921 case NTO: s = ">>"+1; dftfd = 1; break;
922 case NCLOBBER: s = ">|"; dftfd = 1; break;
923 case NAPPEND: s = ">>"; dftfd = 1; break;
Denis Vlasenko559691a2008-10-05 18:39:31 +0000924#if ENABLE_ASH_BASH_COMPAT
925 case NTO2:
926#endif
Denis Vlasenko40ba9982007-07-14 00:48:29 +0000927 case NTOFD: s = ">&"; dftfd = 1; break;
Denis Vlasenko559691a2008-10-05 18:39:31 +0000928 case NFROM: s = "<"; break;
Denis Vlasenko40ba9982007-07-14 00:48:29 +0000929 case NFROMFD: s = "<&"; break;
930 case NFROMTO: s = "<>"; break;
931 default: s = "*error*"; break;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000932 }
933 if (np->nfile.fd != dftfd)
934 fprintf(fp, "%d", np->nfile.fd);
935 fputs(s, fp);
936 if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
937 fprintf(fp, "%d", np->ndup.dupfd);
938 } else {
939 sharg(np->nfile.fname, fp);
940 }
941 first = 0;
942 }
943}
944
945static void
946shtree(union node *n, int ind, char *pfx, FILE *fp)
947{
948 struct nodelist *lp;
949 const char *s;
950
951 if (n == NULL)
952 return;
953
954 indent(ind, pfx, fp);
Denys Vlasenko86e83ec2009-07-23 22:07:07 +0200955
956 if (n == NODE_EOF) {
957 fputs("<EOF>", fp);
958 return;
959 }
960
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000961 switch (n->type) {
962 case NSEMI:
963 s = "; ";
964 goto binop;
965 case NAND:
966 s = " && ";
967 goto binop;
968 case NOR:
969 s = " || ";
970 binop:
971 shtree(n->nbinary.ch1, ind, NULL, fp);
972 /* if (ind < 0) */
973 fputs(s, fp);
974 shtree(n->nbinary.ch2, ind, NULL, fp);
975 break;
976 case NCMD:
977 shcmd(n, fp);
978 if (ind >= 0)
979 putc('\n', fp);
980 break;
981 case NPIPE:
982 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
Denys Vlasenko7cee00e2009-07-24 01:08:03 +0200983 shtree(lp->n, 0, NULL, fp);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000984 if (lp->next)
985 fputs(" | ", fp);
986 }
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000987 if (n->npipe.pipe_backgnd)
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000988 fputs(" &", fp);
989 if (ind >= 0)
990 putc('\n', fp);
991 break;
992 default:
993 fprintf(fp, "<node type %d>", n->type);
994 if (ind >= 0)
995 putc('\n', fp);
996 break;
997 }
998}
999
1000static void
1001showtree(union node *n)
1002{
1003 trace_puts("showtree called\n");
Denys Vlasenko883cea42009-07-11 15:31:59 +02001004 shtree(n, 1, NULL, stderr);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00001005}
1006
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00001007#endif /* DEBUG */
1008
1009
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00001010/* ============ Parser data */
1011
1012/*
Denis Vlasenkob012b102007-02-19 22:43:01 +00001013 * ash_vmsg() needs parsefile->fd, hence parsefile definition is moved up.
1014 */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001015struct strlist {
1016 struct strlist *next;
1017 char *text;
1018};
1019
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00001020struct alias;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00001021
Denis Vlasenkob012b102007-02-19 22:43:01 +00001022struct strpush {
1023 struct strpush *prev; /* preceding string on stack */
Denis Vlasenko41eb3002008-11-28 03:42:31 +00001024 char *prev_string;
1025 int prev_left_in_line;
Denis Vlasenkob012b102007-02-19 22:43:01 +00001026#if ENABLE_ASH_ALIAS
1027 struct alias *ap; /* if push was associated with an alias */
1028#endif
1029 char *string; /* remember the string since it may change */
1030};
1031
1032struct parsefile {
1033 struct parsefile *prev; /* preceding file on stack */
1034 int linno; /* current line */
1035 int fd; /* file descriptor (or -1 if string) */
Denis Vlasenko41eb3002008-11-28 03:42:31 +00001036 int left_in_line; /* number of chars left in this line */
1037 int left_in_buffer; /* number of chars left in this buffer past the line */
1038 char *next_to_pgetc; /* next char in buffer */
Denis Vlasenkob012b102007-02-19 22:43:01 +00001039 char *buf; /* input buffer */
1040 struct strpush *strpush; /* for pushing strings at this level */
1041 struct strpush basestrpush; /* so pushing one is fast */
1042};
1043
Denis Vlasenko448d30e2008-06-27 00:24:11 +00001044static struct parsefile basepf; /* top level input file */
Denis Vlasenkob07a4962008-06-22 13:16:23 +00001045static struct parsefile *g_parsefile = &basepf; /* current input file */
Denis Vlasenkob012b102007-02-19 22:43:01 +00001046static int startlinno; /* line # where last token started */
1047static char *commandname; /* currently executing command */
1048static struct strlist *cmdenviron; /* environment for builtin command */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00001049static uint8_t exitstatus; /* exit status of last command */
Denis Vlasenkob012b102007-02-19 22:43:01 +00001050
1051
1052/* ============ Message printing */
1053
1054static void
1055ash_vmsg(const char *msg, va_list ap)
1056{
1057 fprintf(stderr, "%s: ", arg0);
1058 if (commandname) {
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00001059 if (strcmp(arg0, commandname))
1060 fprintf(stderr, "%s: ", commandname);
Denis Vlasenkob07a4962008-06-22 13:16:23 +00001061 if (!iflag || g_parsefile->fd)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00001062 fprintf(stderr, "line %d: ", startlinno);
Eric Andersenc470f442003-07-28 09:56:35 +00001063 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00001064 vfprintf(stderr, msg, ap);
1065 outcslow('\n', stderr);
Eric Andersenc470f442003-07-28 09:56:35 +00001066}
Denis Vlasenkob012b102007-02-19 22:43:01 +00001067
1068/*
1069 * Exverror is called to raise the error exception. If the second argument
1070 * is not NULL then error prints an error message using printf style
1071 * formatting. It then raises the error exception.
1072 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001073static void ash_vmsg_and_raise(int, const char *, va_list) NORETURN;
Denis Vlasenkob012b102007-02-19 22:43:01 +00001074static void
1075ash_vmsg_and_raise(int cond, const char *msg, va_list ap)
Eric Andersenc470f442003-07-28 09:56:35 +00001076{
Denis Vlasenkob012b102007-02-19 22:43:01 +00001077#if DEBUG
1078 if (msg) {
1079 TRACE(("ash_vmsg_and_raise(%d, \"", cond));
1080 TRACEV((msg, ap));
1081 TRACE(("\") pid=%d\n", getpid()));
1082 } else
1083 TRACE(("ash_vmsg_and_raise(%d, NULL) pid=%d\n", cond, getpid()));
1084 if (msg)
1085#endif
1086 ash_vmsg(msg, ap);
1087
1088 flush_stdout_stderr();
1089 raise_exception(cond);
1090 /* NOTREACHED */
Eric Andersenc470f442003-07-28 09:56:35 +00001091}
Denis Vlasenkob012b102007-02-19 22:43:01 +00001092
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001093static void ash_msg_and_raise_error(const char *, ...) NORETURN;
Denis Vlasenkob012b102007-02-19 22:43:01 +00001094static void
1095ash_msg_and_raise_error(const char *msg, ...)
1096{
1097 va_list ap;
1098
1099 va_start(ap, msg);
1100 ash_vmsg_and_raise(EXERROR, msg, ap);
1101 /* NOTREACHED */
1102 va_end(ap);
1103}
1104
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00001105static void raise_error_syntax(const char *) NORETURN;
1106static void
1107raise_error_syntax(const char *msg)
1108{
1109 ash_msg_and_raise_error("syntax error: %s", msg);
1110 /* NOTREACHED */
1111}
1112
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001113static void ash_msg_and_raise(int, const char *, ...) NORETURN;
Denis Vlasenkob012b102007-02-19 22:43:01 +00001114static void
1115ash_msg_and_raise(int cond, const char *msg, ...)
1116{
1117 va_list ap;
1118
1119 va_start(ap, msg);
1120 ash_vmsg_and_raise(cond, msg, ap);
1121 /* NOTREACHED */
1122 va_end(ap);
1123}
1124
1125/*
1126 * error/warning routines for external builtins
1127 */
1128static void
1129ash_msg(const char *fmt, ...)
1130{
1131 va_list ap;
1132
1133 va_start(ap, fmt);
1134 ash_vmsg(fmt, ap);
1135 va_end(ap);
1136}
1137
1138/*
1139 * Return a string describing an error. The returned string may be a
1140 * pointer to a static buffer that will be overwritten on the next call.
1141 * Action describes the operation that got the error.
1142 */
1143static const char *
1144errmsg(int e, const char *em)
1145{
1146 if (e == ENOENT || e == ENOTDIR) {
1147 return em;
1148 }
1149 return strerror(e);
1150}
1151
1152
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001153/* ============ Memory allocation */
1154
1155/*
1156 * It appears that grabstackstr() will barf with such alignments
1157 * because stalloc() will return a string allocated in a new stackblock.
1158 */
1159#define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
1160enum {
1161 /* Most machines require the value returned from malloc to be aligned
1162 * in some way. The following macro will get this right
1163 * on many machines. */
1164 SHELL_SIZE = sizeof(union {int i; char *cp; double d; }) - 1,
1165 /* Minimum size of a block */
Denis Vlasenko01631112007-12-16 17:20:38 +00001166 MINSIZE = SHELL_ALIGN(504),
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001167};
1168
1169struct stack_block {
1170 struct stack_block *prev;
1171 char space[MINSIZE];
1172};
1173
1174struct stackmark {
1175 struct stack_block *stackp;
1176 char *stacknxt;
1177 size_t stacknleft;
1178 struct stackmark *marknext;
1179};
1180
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001181
Denis Vlasenko01631112007-12-16 17:20:38 +00001182struct globals_memstack {
1183 struct stack_block *g_stackp; // = &stackbase;
1184 struct stackmark *markp;
1185 char *g_stacknxt; // = stackbase.space;
1186 char *sstrend; // = stackbase.space + MINSIZE;
1187 size_t g_stacknleft; // = MINSIZE;
1188 int herefd; // = -1;
1189 struct stack_block stackbase;
1190};
Denis Vlasenko574f2f42008-02-27 18:41:59 +00001191extern struct globals_memstack *const ash_ptr_to_globals_memstack;
1192#define G_memstack (*ash_ptr_to_globals_memstack)
Denis Vlasenko01631112007-12-16 17:20:38 +00001193#define g_stackp (G_memstack.g_stackp )
1194#define markp (G_memstack.markp )
1195#define g_stacknxt (G_memstack.g_stacknxt )
1196#define sstrend (G_memstack.sstrend )
1197#define g_stacknleft (G_memstack.g_stacknleft)
1198#define herefd (G_memstack.herefd )
1199#define stackbase (G_memstack.stackbase )
1200#define INIT_G_memstack() do { \
Denis Vlasenko574f2f42008-02-27 18:41:59 +00001201 (*(struct globals_memstack**)&ash_ptr_to_globals_memstack) = xzalloc(sizeof(G_memstack)); \
1202 barrier(); \
Denis Vlasenko01631112007-12-16 17:20:38 +00001203 g_stackp = &stackbase; \
1204 g_stacknxt = stackbase.space; \
1205 g_stacknleft = MINSIZE; \
1206 sstrend = stackbase.space + MINSIZE; \
1207 herefd = -1; \
1208} while (0)
1209
1210#define stackblock() ((void *)g_stacknxt)
1211#define stackblocksize() g_stacknleft
1212
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001213
1214static void *
1215ckrealloc(void * p, size_t nbytes)
1216{
1217 p = realloc(p, nbytes);
1218 if (!p)
1219 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1220 return p;
1221}
1222
1223static void *
1224ckmalloc(size_t nbytes)
1225{
1226 return ckrealloc(NULL, nbytes);
1227}
1228
Denis Vlasenko597906c2008-02-20 16:38:54 +00001229static void *
1230ckzalloc(size_t nbytes)
1231{
1232 return memset(ckmalloc(nbytes), 0, nbytes);
1233}
1234
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001235/*
1236 * Make a copy of a string in safe storage.
1237 */
1238static char *
1239ckstrdup(const char *s)
1240{
1241 char *p = strdup(s);
1242 if (!p)
1243 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1244 return p;
1245}
1246
1247/*
1248 * Parse trees for commands are allocated in lifo order, so we use a stack
1249 * to make this more efficient, and also to avoid all sorts of exception
1250 * handling code to handle interrupts in the middle of a parse.
1251 *
1252 * The size 504 was chosen because the Ultrix malloc handles that size
1253 * well.
1254 */
1255static void *
1256stalloc(size_t nbytes)
1257{
1258 char *p;
1259 size_t aligned;
1260
1261 aligned = SHELL_ALIGN(nbytes);
Denis Vlasenko01631112007-12-16 17:20:38 +00001262 if (aligned > g_stacknleft) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001263 size_t len;
1264 size_t blocksize;
1265 struct stack_block *sp;
1266
1267 blocksize = aligned;
1268 if (blocksize < MINSIZE)
1269 blocksize = MINSIZE;
1270 len = sizeof(struct stack_block) - MINSIZE + blocksize;
1271 if (len < blocksize)
1272 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1273 INT_OFF;
1274 sp = ckmalloc(len);
Denis Vlasenko01631112007-12-16 17:20:38 +00001275 sp->prev = g_stackp;
1276 g_stacknxt = sp->space;
1277 g_stacknleft = blocksize;
1278 sstrend = g_stacknxt + blocksize;
1279 g_stackp = sp;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001280 INT_ON;
1281 }
Denis Vlasenko01631112007-12-16 17:20:38 +00001282 p = g_stacknxt;
1283 g_stacknxt += aligned;
1284 g_stacknleft -= aligned;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001285 return p;
1286}
1287
Denis Vlasenko597906c2008-02-20 16:38:54 +00001288static void *
1289stzalloc(size_t nbytes)
1290{
1291 return memset(stalloc(nbytes), 0, nbytes);
1292}
1293
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001294static void
1295stunalloc(void *p)
1296{
1297#if DEBUG
Denis Vlasenko01631112007-12-16 17:20:38 +00001298 if (!p || (g_stacknxt < (char *)p) || ((char *)p < g_stackp->space)) {
Bernhard Reutner-Fischer5e25ddb2008-05-19 09:48:17 +00001299 write(STDERR_FILENO, "stunalloc\n", 10);
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001300 abort();
1301 }
1302#endif
Denis Vlasenko01631112007-12-16 17:20:38 +00001303 g_stacknleft += g_stacknxt - (char *)p;
1304 g_stacknxt = p;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001305}
1306
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001307/*
1308 * Like strdup but works with the ash stack.
1309 */
1310static char *
1311ststrdup(const char *p)
1312{
1313 size_t len = strlen(p) + 1;
1314 return memcpy(stalloc(len), p, len);
1315}
1316
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001317static void
1318setstackmark(struct stackmark *mark)
1319{
Denis Vlasenko01631112007-12-16 17:20:38 +00001320 mark->stackp = g_stackp;
1321 mark->stacknxt = g_stacknxt;
1322 mark->stacknleft = g_stacknleft;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001323 mark->marknext = markp;
1324 markp = mark;
1325}
1326
1327static void
1328popstackmark(struct stackmark *mark)
1329{
1330 struct stack_block *sp;
1331
Denis Vlasenko93ebd4f2007-03-13 20:55:36 +00001332 if (!mark->stackp)
1333 return;
1334
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001335 INT_OFF;
1336 markp = mark->marknext;
Denis Vlasenko01631112007-12-16 17:20:38 +00001337 while (g_stackp != mark->stackp) {
1338 sp = g_stackp;
1339 g_stackp = sp->prev;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001340 free(sp);
1341 }
Denis Vlasenko01631112007-12-16 17:20:38 +00001342 g_stacknxt = mark->stacknxt;
1343 g_stacknleft = mark->stacknleft;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001344 sstrend = mark->stacknxt + mark->stacknleft;
1345 INT_ON;
1346}
1347
1348/*
1349 * When the parser reads in a string, it wants to stick the string on the
1350 * stack and only adjust the stack pointer when it knows how big the
1351 * string is. Stackblock (defined in stack.h) returns a pointer to a block
1352 * of space on top of the stack and stackblocklen returns the length of
1353 * this block. Growstackblock will grow this space by at least one byte,
1354 * possibly moving it (like realloc). Grabstackblock actually allocates the
1355 * part of the block that has been used.
1356 */
1357static void
1358growstackblock(void)
1359{
1360 size_t newlen;
1361
Denis Vlasenko01631112007-12-16 17:20:38 +00001362 newlen = g_stacknleft * 2;
1363 if (newlen < g_stacknleft)
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001364 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1365 if (newlen < 128)
1366 newlen += 128;
1367
Denis Vlasenko01631112007-12-16 17:20:38 +00001368 if (g_stacknxt == g_stackp->space && g_stackp != &stackbase) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001369 struct stack_block *oldstackp;
1370 struct stackmark *xmark;
1371 struct stack_block *sp;
1372 struct stack_block *prevstackp;
1373 size_t grosslen;
1374
1375 INT_OFF;
Denis Vlasenko01631112007-12-16 17:20:38 +00001376 oldstackp = g_stackp;
1377 sp = g_stackp;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001378 prevstackp = sp->prev;
1379 grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
1380 sp = ckrealloc(sp, grosslen);
1381 sp->prev = prevstackp;
Denis Vlasenko01631112007-12-16 17:20:38 +00001382 g_stackp = sp;
1383 g_stacknxt = sp->space;
1384 g_stacknleft = newlen;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001385 sstrend = sp->space + newlen;
1386
1387 /*
1388 * Stack marks pointing to the start of the old block
1389 * must be relocated to point to the new block
1390 */
1391 xmark = markp;
1392 while (xmark != NULL && xmark->stackp == oldstackp) {
Denis Vlasenko01631112007-12-16 17:20:38 +00001393 xmark->stackp = g_stackp;
1394 xmark->stacknxt = g_stacknxt;
1395 xmark->stacknleft = g_stacknleft;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001396 xmark = xmark->marknext;
1397 }
1398 INT_ON;
1399 } else {
Denis Vlasenko01631112007-12-16 17:20:38 +00001400 char *oldspace = g_stacknxt;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00001401 size_t oldlen = g_stacknleft;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001402 char *p = stalloc(newlen);
1403
1404 /* free the space we just allocated */
Denis Vlasenko01631112007-12-16 17:20:38 +00001405 g_stacknxt = memcpy(p, oldspace, oldlen);
1406 g_stacknleft += newlen;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001407 }
1408}
1409
1410static void
1411grabstackblock(size_t len)
1412{
1413 len = SHELL_ALIGN(len);
Denis Vlasenko01631112007-12-16 17:20:38 +00001414 g_stacknxt += len;
1415 g_stacknleft -= len;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001416}
1417
1418/*
1419 * The following routines are somewhat easier to use than the above.
1420 * The user declares a variable of type STACKSTR, which may be declared
1421 * to be a register. The macro STARTSTACKSTR initializes things. Then
1422 * the user uses the macro STPUTC to add characters to the string. In
1423 * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
1424 * grown as necessary. When the user is done, she can just leave the
1425 * string there and refer to it using stackblock(). Or she can allocate
1426 * the space for it using grabstackstr(). If it is necessary to allow
1427 * someone else to use the stack temporarily and then continue to grow
1428 * the string, the user should use grabstack to allocate the space, and
1429 * then call ungrabstr(p) to return to the previous mode of operation.
1430 *
1431 * USTPUTC is like STPUTC except that it doesn't check for overflow.
1432 * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
1433 * is space for at least one character.
1434 */
1435static void *
1436growstackstr(void)
1437{
1438 size_t len = stackblocksize();
1439 if (herefd >= 0 && len >= 1024) {
1440 full_write(herefd, stackblock(), len);
1441 return stackblock();
1442 }
1443 growstackblock();
Denis Vlasenko29eb3592008-05-18 14:06:08 +00001444 return (char *)stackblock() + len;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001445}
1446
1447/*
1448 * Called from CHECKSTRSPACE.
1449 */
1450static char *
1451makestrspace(size_t newlen, char *p)
1452{
Denis Vlasenko01631112007-12-16 17:20:38 +00001453 size_t len = p - g_stacknxt;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001454 size_t size = stackblocksize();
1455
1456 for (;;) {
1457 size_t nleft;
1458
1459 size = stackblocksize();
1460 nleft = size - len;
1461 if (nleft >= newlen)
1462 break;
1463 growstackblock();
1464 }
Denis Vlasenko29eb3592008-05-18 14:06:08 +00001465 return (char *)stackblock() + len;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001466}
1467
1468static char *
1469stack_nputstr(const char *s, size_t n, char *p)
1470{
1471 p = makestrspace(n, p);
Denis Vlasenko29eb3592008-05-18 14:06:08 +00001472 p = (char *)memcpy(p, s, n) + n;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001473 return p;
1474}
1475
1476static char *
1477stack_putstr(const char *s, char *p)
1478{
1479 return stack_nputstr(s, strlen(s), p);
1480}
1481
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001482static char *
1483_STPUTC(int c, char *p)
1484{
1485 if (p == sstrend)
1486 p = growstackstr();
1487 *p++ = c;
1488 return p;
1489}
1490
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00001491#define STARTSTACKSTR(p) ((p) = stackblock())
1492#define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
Denis Vlasenko843cbd52008-06-27 00:23:18 +00001493#define CHECKSTRSPACE(n, p) do { \
1494 char *q = (p); \
1495 size_t l = (n); \
1496 size_t m = sstrend - q; \
1497 if (l > m) \
1498 (p) = makestrspace(l, q); \
1499} while (0)
Denis Vlasenkoef527f52008-06-23 01:52:30 +00001500#define USTPUTC(c, p) (*(p)++ = (c))
Denis Vlasenko843cbd52008-06-27 00:23:18 +00001501#define STACKSTRNUL(p) do { \
1502 if ((p) == sstrend) \
1503 (p) = growstackstr(); \
1504 *(p) = '\0'; \
1505} while (0)
Denis Vlasenkoef527f52008-06-23 01:52:30 +00001506#define STUNPUTC(p) (--(p))
1507#define STTOPC(p) ((p)[-1])
1508#define STADJUST(amount, p) ((p) += (amount))
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001509
1510#define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
Denis Vlasenkoef527f52008-06-23 01:52:30 +00001511#define ungrabstackstr(s, p) stunalloc(s)
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001512#define stackstrend() ((void *)sstrend)
1513
1514
1515/* ============ String helpers */
1516
1517/*
1518 * prefix -- see if pfx is a prefix of string.
1519 */
1520static char *
1521prefix(const char *string, const char *pfx)
1522{
1523 while (*pfx) {
1524 if (*pfx++ != *string++)
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00001525 return NULL;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001526 }
1527 return (char *) string;
1528}
1529
1530/*
1531 * Check for a valid number. This should be elsewhere.
1532 */
1533static int
1534is_number(const char *p)
1535{
1536 do {
1537 if (!isdigit(*p))
1538 return 0;
1539 } while (*++p != '\0');
1540 return 1;
1541}
1542
1543/*
1544 * Convert a string of digits to an integer, printing an error message on
1545 * failure.
1546 */
1547static int
1548number(const char *s)
1549{
1550 if (!is_number(s))
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02001551 ash_msg_and_raise_error(msg_illnum, s);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001552 return atoi(s);
1553}
1554
1555/*
1556 * Produce a possibly single quoted string suitable as input to the shell.
1557 * The return string is allocated on the stack.
1558 */
1559static char *
1560single_quote(const char *s)
1561{
1562 char *p;
1563
1564 STARTSTACKSTR(p);
1565
1566 do {
1567 char *q;
1568 size_t len;
1569
1570 len = strchrnul(s, '\'') - s;
1571
1572 q = p = makestrspace(len + 3, p);
1573
1574 *q++ = '\'';
Denis Vlasenko29eb3592008-05-18 14:06:08 +00001575 q = (char *)memcpy(q, s, len) + len;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001576 *q++ = '\'';
1577 s += len;
1578
1579 STADJUST(q - p, p);
1580
1581 len = strspn(s, "'");
1582 if (!len)
1583 break;
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 } while (*s);
1594
1595 USTPUTC(0, p);
1596
1597 return stackblock();
1598}
1599
1600
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00001601/* ============ nextopt */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001602
1603static char **argptr; /* argument list for builtin commands */
1604static char *optionarg; /* set by nextopt (like getopt) */
1605static char *optptr; /* used by nextopt */
1606
1607/*
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001608 * XXX - should get rid of. Have all builtins use getopt(3).
1609 * The library getopt must have the BSD extension static variable
1610 * "optreset", otherwise it can't be used within the shell safely.
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001611 *
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001612 * Standard option processing (a la getopt) for builtin routines.
1613 * The only argument that is passed to nextopt is the option string;
1614 * the other arguments are unnecessary. It returns the character,
1615 * or '\0' on end of input.
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001616 */
1617static int
1618nextopt(const char *optstring)
1619{
1620 char *p;
1621 const char *q;
1622 char c;
1623
1624 p = optptr;
1625 if (p == NULL || *p == '\0') {
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001626 /* We ate entire "-param", take next one */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001627 p = *argptr;
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001628 if (p == NULL)
1629 return '\0';
1630 if (*p != '-')
1631 return '\0';
1632 if (*++p == '\0') /* just "-" ? */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001633 return '\0';
1634 argptr++;
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001635 if (LONE_DASH(p)) /* "--" ? */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001636 return '\0';
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001637 /* p => next "-param" */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001638 }
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001639 /* p => some option char in the middle of a "-param" */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001640 c = *p++;
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +00001641 for (q = optstring; *q != c;) {
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001642 if (*q == '\0')
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00001643 ash_msg_and_raise_error("illegal option -%c", c);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001644 if (*++q == ':')
1645 q++;
1646 }
1647 if (*++q == ':') {
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001648 if (*p == '\0') {
1649 p = *argptr++;
1650 if (p == NULL)
1651 ash_msg_and_raise_error("no arg for -%c option", c);
1652 }
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001653 optionarg = p;
1654 p = NULL;
1655 }
1656 optptr = p;
1657 return c;
1658}
1659
1660
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00001661/* ============ Shell variables */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001662
Denis Vlasenko01631112007-12-16 17:20:38 +00001663/*
1664 * The parsefile structure pointed to by the global variable parsefile
1665 * contains information about the current file being read.
1666 */
Denis Vlasenko01631112007-12-16 17:20:38 +00001667struct shparam {
1668 int nparam; /* # of positional parameters (without $0) */
1669#if ENABLE_ASH_GETOPTS
1670 int optind; /* next parameter to be processed by getopts */
1671 int optoff; /* used by getopts */
1672#endif
1673 unsigned char malloced; /* if parameter list dynamically allocated */
1674 char **p; /* parameter list */
1675};
1676
1677/*
1678 * Free the list of positional parameters.
1679 */
1680static void
1681freeparam(volatile struct shparam *param)
1682{
Denis Vlasenko01631112007-12-16 17:20:38 +00001683 if (param->malloced) {
Denis Vlasenko3177ba02008-07-13 20:39:23 +00001684 char **ap, **ap1;
1685 ap = ap1 = param->p;
1686 while (*ap)
1687 free(*ap++);
1688 free(ap1);
Denis Vlasenko01631112007-12-16 17:20:38 +00001689 }
1690}
1691
1692#if ENABLE_ASH_GETOPTS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001693static void FAST_FUNC getoptsreset(const char *value);
Denis Vlasenko01631112007-12-16 17:20:38 +00001694#endif
1695
1696struct var {
1697 struct var *next; /* next entry in hash list */
1698 int flags; /* flags are defined above */
1699 const char *text; /* name=value */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001700 void (*func)(const char *) FAST_FUNC; /* function to be called when */
Denis Vlasenko01631112007-12-16 17:20:38 +00001701 /* the variable gets set/unset */
1702};
1703
1704struct localvar {
1705 struct localvar *next; /* next local variable in list */
1706 struct var *vp; /* the variable that was made local */
1707 int flags; /* saved flags */
1708 const char *text; /* saved text */
1709};
1710
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001711/* flags */
1712#define VEXPORT 0x01 /* variable is exported */
1713#define VREADONLY 0x02 /* variable cannot be modified */
1714#define VSTRFIXED 0x04 /* variable struct is statically allocated */
1715#define VTEXTFIXED 0x08 /* text is statically allocated */
1716#define VSTACK 0x10 /* text is allocated on the stack */
1717#define VUNSET 0x20 /* the variable is not set */
1718#define VNOFUNC 0x40 /* don't call the callback function */
1719#define VNOSET 0x80 /* do not set variable - just readonly test */
1720#define VNOSAVE 0x100 /* when text is on the heap before setvareq */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00001721#if ENABLE_ASH_RANDOM_SUPPORT
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00001722# define VDYNAMIC 0x200 /* dynamic variable */
1723#else
1724# define VDYNAMIC 0
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001725#endif
1726
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001727#ifdef IFS_BROKEN
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00001728static const char defifsvar[] ALIGN1 = "IFS= \t\n";
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001729#define defifs (defifsvar + 4)
1730#else
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00001731static const char defifs[] ALIGN1 = " \t\n";
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001732#endif
1733
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00001734
Denis Vlasenko01631112007-12-16 17:20:38 +00001735/* Need to be before varinit_data[] */
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00001736#if ENABLE_LOCALE_SUPPORT
Denys Vlasenko2634bf32009-06-09 18:40:07 +02001737static void FAST_FUNC
Denis Vlasenkoa8915072007-02-23 21:10:06 +00001738change_lc_all(const char *value)
1739{
1740 if (value && *value != '\0')
1741 setlocale(LC_ALL, value);
1742}
Denys Vlasenko2634bf32009-06-09 18:40:07 +02001743static void FAST_FUNC
Denis Vlasenkoa8915072007-02-23 21:10:06 +00001744change_lc_ctype(const char *value)
1745{
1746 if (value && *value != '\0')
1747 setlocale(LC_CTYPE, value);
1748}
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00001749#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001750#if ENABLE_ASH_MAIL
1751static void chkmail(void);
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001752static void changemail(const char *) FAST_FUNC;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001753#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001754static void changepath(const char *) FAST_FUNC;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001755#if ENABLE_ASH_RANDOM_SUPPORT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001756static void change_random(const char *) FAST_FUNC;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001757#endif
1758
Denis Vlasenko01631112007-12-16 17:20:38 +00001759static const struct {
1760 int flags;
1761 const char *text;
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001762 void (*func)(const char *) FAST_FUNC;
Denis Vlasenko01631112007-12-16 17:20:38 +00001763} varinit_data[] = {
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001764#ifdef IFS_BROKEN
Denis Vlasenko01631112007-12-16 17:20:38 +00001765 { VSTRFIXED|VTEXTFIXED , defifsvar , NULL },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001766#else
Denis Vlasenko01631112007-12-16 17:20:38 +00001767 { VSTRFIXED|VTEXTFIXED|VUNSET, "IFS\0" , NULL },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001768#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001769#if ENABLE_ASH_MAIL
Denis Vlasenko01631112007-12-16 17:20:38 +00001770 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL\0" , changemail },
1771 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH\0", changemail },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001772#endif
Denis Vlasenko01631112007-12-16 17:20:38 +00001773 { VSTRFIXED|VTEXTFIXED , bb_PATH_root_path, changepath },
1774 { VSTRFIXED|VTEXTFIXED , "PS1=$ " , NULL },
1775 { VSTRFIXED|VTEXTFIXED , "PS2=> " , NULL },
1776 { VSTRFIXED|VTEXTFIXED , "PS4=+ " , NULL },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001777#if ENABLE_ASH_GETOPTS
Denis Vlasenko01631112007-12-16 17:20:38 +00001778 { VSTRFIXED|VTEXTFIXED , "OPTIND=1" , getoptsreset },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001779#endif
1780#if ENABLE_ASH_RANDOM_SUPPORT
Denis Vlasenko01631112007-12-16 17:20:38 +00001781 { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM\0", change_random },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001782#endif
1783#if ENABLE_LOCALE_SUPPORT
Denis Vlasenko01631112007-12-16 17:20:38 +00001784 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL\0" , change_lc_all },
1785 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE\0", change_lc_ctype },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001786#endif
1787#if ENABLE_FEATURE_EDITING_SAVEHISTORY
Denis Vlasenko01631112007-12-16 17:20:38 +00001788 { VSTRFIXED|VTEXTFIXED|VUNSET, "HISTFILE\0", NULL },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001789#endif
1790};
1791
Denis Vlasenko0b769642008-07-24 07:54:57 +00001792struct redirtab;
Denis Vlasenko01631112007-12-16 17:20:38 +00001793
1794struct globals_var {
1795 struct shparam shellparam; /* $@ current positional parameters */
1796 struct redirtab *redirlist;
1797 int g_nullredirs;
1798 int preverrout_fd; /* save fd2 before print debug if xflag is set. */
1799 struct var *vartab[VTABSIZE];
1800 struct var varinit[ARRAY_SIZE(varinit_data)];
1801};
Denis Vlasenko574f2f42008-02-27 18:41:59 +00001802extern struct globals_var *const ash_ptr_to_globals_var;
1803#define G_var (*ash_ptr_to_globals_var)
Denis Vlasenko01631112007-12-16 17:20:38 +00001804#define shellparam (G_var.shellparam )
Denis Vlasenko0b769642008-07-24 07:54:57 +00001805//#define redirlist (G_var.redirlist )
Denis Vlasenko01631112007-12-16 17:20:38 +00001806#define g_nullredirs (G_var.g_nullredirs )
1807#define preverrout_fd (G_var.preverrout_fd)
1808#define vartab (G_var.vartab )
1809#define varinit (G_var.varinit )
1810#define INIT_G_var() do { \
Denis Vlasenko6b06cb82008-05-15 21:30:45 +00001811 unsigned i; \
Denis Vlasenko574f2f42008-02-27 18:41:59 +00001812 (*(struct globals_var**)&ash_ptr_to_globals_var) = xzalloc(sizeof(G_var)); \
1813 barrier(); \
Denis Vlasenko01631112007-12-16 17:20:38 +00001814 for (i = 0; i < ARRAY_SIZE(varinit_data); i++) { \
1815 varinit[i].flags = varinit_data[i].flags; \
1816 varinit[i].text = varinit_data[i].text; \
1817 varinit[i].func = varinit_data[i].func; \
1818 } \
1819} while (0)
1820
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001821#define vifs varinit[0]
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001822#if ENABLE_ASH_MAIL
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001823# define vmail (&vifs)[1]
1824# define vmpath (&vmail)[1]
1825# define vpath (&vmpath)[1]
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001826#else
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001827# define vpath (&vifs)[1]
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001828#endif
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001829#define vps1 (&vpath)[1]
1830#define vps2 (&vps1)[1]
1831#define vps4 (&vps2)[1]
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001832#if ENABLE_ASH_GETOPTS
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001833# define voptind (&vps4)[1]
1834# if ENABLE_ASH_RANDOM_SUPPORT
1835# define vrandom (&voptind)[1]
1836# endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001837#else
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001838# if ENABLE_ASH_RANDOM_SUPPORT
1839# define vrandom (&vps4)[1]
1840# endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001841#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001842
1843/*
1844 * The following macros access the values of the above variables.
1845 * They have to skip over the name. They return the null string
1846 * for unset variables.
1847 */
1848#define ifsval() (vifs.text + 4)
1849#define ifsset() ((vifs.flags & VUNSET) == 0)
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001850#if ENABLE_ASH_MAIL
1851# define mailval() (vmail.text + 5)
1852# define mpathval() (vmpath.text + 9)
1853# define mpathset() ((vmpath.flags & VUNSET) == 0)
1854#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001855#define pathval() (vpath.text + 5)
1856#define ps1val() (vps1.text + 4)
1857#define ps2val() (vps2.text + 4)
1858#define ps4val() (vps4.text + 4)
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001859#if ENABLE_ASH_GETOPTS
1860# define optindval() (voptind.text + 7)
1861#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001862
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001863
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001864#define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
1865#define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
1866
Denis Vlasenko01631112007-12-16 17:20:38 +00001867#if ENABLE_ASH_GETOPTS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001868static void FAST_FUNC
Denis Vlasenko01631112007-12-16 17:20:38 +00001869getoptsreset(const char *value)
1870{
1871 shellparam.optind = number(value);
1872 shellparam.optoff = -1;
1873}
1874#endif
1875
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001876/*
1877 * Return of a legal variable name (a letter or underscore followed by zero or
1878 * more letters, underscores, and digits).
1879 */
1880static char *
1881endofname(const char *name)
1882{
1883 char *p;
1884
1885 p = (char *) name;
1886 if (!is_name(*p))
1887 return p;
1888 while (*++p) {
1889 if (!is_in_name(*p))
1890 break;
1891 }
1892 return p;
1893}
1894
1895/*
1896 * Compares two strings up to the first = or '\0'. The first
1897 * string must be terminated by '='; the second may be terminated by
1898 * either '=' or '\0'.
1899 */
1900static int
1901varcmp(const char *p, const char *q)
1902{
1903 int c, d;
1904
1905 while ((c = *p) == (d = *q)) {
1906 if (!c || c == '=')
1907 goto out;
1908 p++;
1909 q++;
1910 }
1911 if (c == '=')
Denis Vlasenko9650f362007-02-23 01:04:37 +00001912 c = '\0';
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001913 if (d == '=')
Denis Vlasenko9650f362007-02-23 01:04:37 +00001914 d = '\0';
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001915 out:
1916 return c - d;
1917}
1918
1919static int
1920varequal(const char *a, const char *b)
1921{
1922 return !varcmp(a, b);
1923}
1924
1925/*
1926 * Find the appropriate entry in the hash table from the name.
1927 */
1928static struct var **
1929hashvar(const char *p)
1930{
1931 unsigned hashval;
1932
1933 hashval = ((unsigned char) *p) << 4;
1934 while (*p && *p != '=')
1935 hashval += (unsigned char) *p++;
1936 return &vartab[hashval % VTABSIZE];
1937}
1938
1939static int
1940vpcmp(const void *a, const void *b)
1941{
1942 return varcmp(*(const char **)a, *(const char **)b);
1943}
1944
1945/*
1946 * This routine initializes the builtin variables.
1947 */
1948static void
1949initvar(void)
1950{
1951 struct var *vp;
1952 struct var *end;
1953 struct var **vpp;
1954
1955 /*
1956 * PS1 depends on uid
1957 */
1958#if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
1959 vps1.text = "PS1=\\w \\$ ";
1960#else
1961 if (!geteuid())
1962 vps1.text = "PS1=# ";
1963#endif
1964 vp = varinit;
Denis Vlasenko80b8b392007-06-25 10:55:35 +00001965 end = vp + ARRAY_SIZE(varinit);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001966 do {
1967 vpp = hashvar(vp->text);
1968 vp->next = *vpp;
1969 *vpp = vp;
1970 } while (++vp < end);
1971}
1972
1973static struct var **
1974findvar(struct var **vpp, const char *name)
1975{
1976 for (; *vpp; vpp = &(*vpp)->next) {
1977 if (varequal((*vpp)->text, name)) {
1978 break;
1979 }
1980 }
1981 return vpp;
1982}
1983
1984/*
1985 * Find the value of a variable. Returns NULL if not set.
1986 */
Mike Frysinger98c52642009-04-02 10:02:37 +00001987static const char *
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001988lookupvar(const char *name)
1989{
1990 struct var *v;
1991
1992 v = *findvar(hashvar(name), name);
1993 if (v) {
Denis Vlasenko448d30e2008-06-27 00:24:11 +00001994#if ENABLE_ASH_RANDOM_SUPPORT
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001995 /*
1996 * Dynamic variables are implemented roughly the same way they are
1997 * in bash. Namely, they're "special" so long as they aren't unset.
1998 * As soon as they're unset, they're no longer dynamic, and dynamic
1999 * lookup will no longer happen at that point. -- PFM.
2000 */
2001 if ((v->flags & VDYNAMIC))
2002 (*v->func)(NULL);
2003#endif
2004 if (!(v->flags & VUNSET))
2005 return strchrnul(v->text, '=') + 1;
2006 }
2007 return NULL;
2008}
2009
2010/*
2011 * Search the environment of a builtin command.
2012 */
Mike Frysinger98c52642009-04-02 10:02:37 +00002013static const char *
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002014bltinlookup(const char *name)
2015{
2016 struct strlist *sp;
2017
2018 for (sp = cmdenviron; sp; sp = sp->next) {
2019 if (varequal(sp->text, name))
2020 return strchrnul(sp->text, '=') + 1;
2021 }
2022 return lookupvar(name);
2023}
2024
2025/*
2026 * Same as setvar except that the variable and value are passed in
2027 * the first argument as name=value. Since the first argument will
2028 * be actually stored in the table, it should not be a string that
2029 * will go away.
2030 * Called with interrupts off.
2031 */
2032static void
2033setvareq(char *s, int flags)
2034{
2035 struct var *vp, **vpp;
2036
2037 vpp = hashvar(s);
2038 flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
2039 vp = *findvar(vpp, s);
2040 if (vp) {
2041 if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
2042 const char *n;
2043
2044 if (flags & VNOSAVE)
2045 free(s);
2046 n = vp->text;
2047 ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
2048 }
2049
2050 if (flags & VNOSET)
2051 return;
2052
2053 if (vp->func && (flags & VNOFUNC) == 0)
2054 (*vp->func)(strchrnul(s, '=') + 1);
2055
2056 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
2057 free((char*)vp->text);
2058
2059 flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
2060 } else {
2061 if (flags & VNOSET)
2062 return;
2063 /* not found */
Denis Vlasenko597906c2008-02-20 16:38:54 +00002064 vp = ckzalloc(sizeof(*vp));
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002065 vp->next = *vpp;
Denis Vlasenko597906c2008-02-20 16:38:54 +00002066 /*vp->func = NULL; - ckzalloc did it */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002067 *vpp = vp;
2068 }
2069 if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
2070 s = ckstrdup(s);
2071 vp->text = s;
2072 vp->flags = flags;
2073}
2074
2075/*
2076 * Set the value of a variable. The flags argument is ored with the
2077 * flags of the variable. If val is NULL, the variable is unset.
2078 */
2079static void
2080setvar(const char *name, const char *val, int flags)
2081{
2082 char *p, *q;
2083 size_t namelen;
2084 char *nameeq;
2085 size_t vallen;
2086
2087 q = endofname(name);
2088 p = strchrnul(q, '=');
2089 namelen = p - name;
2090 if (!namelen || p != q)
2091 ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
2092 vallen = 0;
2093 if (val == NULL) {
2094 flags |= VUNSET;
2095 } else {
2096 vallen = strlen(val);
2097 }
2098 INT_OFF;
2099 nameeq = ckmalloc(namelen + vallen + 2);
Denis Vlasenko29eb3592008-05-18 14:06:08 +00002100 p = (char *)memcpy(nameeq, name, namelen) + namelen;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002101 if (val) {
2102 *p++ = '=';
Denis Vlasenko29eb3592008-05-18 14:06:08 +00002103 p = (char *)memcpy(p, val, vallen) + vallen;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002104 }
2105 *p = '\0';
2106 setvareq(nameeq, flags | VNOSAVE);
2107 INT_ON;
2108}
2109
2110#if ENABLE_ASH_GETOPTS
2111/*
2112 * Safe version of setvar, returns 1 on success 0 on failure.
2113 */
2114static int
2115setvarsafe(const char *name, const char *val, int flags)
2116{
2117 int err;
2118 volatile int saveint;
2119 struct jmploc *volatile savehandler = exception_handler;
2120 struct jmploc jmploc;
2121
2122 SAVE_INT(saveint);
2123 if (setjmp(jmploc.loc))
2124 err = 1;
2125 else {
2126 exception_handler = &jmploc;
2127 setvar(name, val, flags);
2128 err = 0;
2129 }
2130 exception_handler = savehandler;
2131 RESTORE_INT(saveint);
2132 return err;
2133}
2134#endif
2135
2136/*
2137 * Unset the specified variable.
2138 */
2139static int
2140unsetvar(const char *s)
2141{
2142 struct var **vpp;
2143 struct var *vp;
2144 int retval;
2145
2146 vpp = findvar(hashvar(s), s);
2147 vp = *vpp;
2148 retval = 2;
2149 if (vp) {
2150 int flags = vp->flags;
2151
2152 retval = 1;
2153 if (flags & VREADONLY)
2154 goto out;
Denis Vlasenko448d30e2008-06-27 00:24:11 +00002155#if ENABLE_ASH_RANDOM_SUPPORT
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002156 vp->flags &= ~VDYNAMIC;
2157#endif
2158 if (flags & VUNSET)
2159 goto ok;
2160 if ((flags & VSTRFIXED) == 0) {
2161 INT_OFF;
2162 if ((flags & (VTEXTFIXED|VSTACK)) == 0)
2163 free((char*)vp->text);
2164 *vpp = vp->next;
2165 free(vp);
2166 INT_ON;
2167 } else {
2168 setvar(s, 0, 0);
2169 vp->flags &= ~VEXPORT;
2170 }
2171 ok:
2172 retval = 0;
2173 }
2174 out:
2175 return retval;
2176}
2177
2178/*
2179 * Process a linked list of variable assignments.
2180 */
2181static void
2182listsetvar(struct strlist *list_set_var, int flags)
2183{
2184 struct strlist *lp = list_set_var;
2185
2186 if (!lp)
2187 return;
2188 INT_OFF;
2189 do {
2190 setvareq(lp->text, flags);
Denis Vlasenko9650f362007-02-23 01:04:37 +00002191 lp = lp->next;
2192 } while (lp);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002193 INT_ON;
2194}
2195
2196/*
2197 * Generate a list of variables satisfying the given conditions.
2198 */
2199static char **
2200listvars(int on, int off, char ***end)
2201{
2202 struct var **vpp;
2203 struct var *vp;
2204 char **ep;
2205 int mask;
2206
2207 STARTSTACKSTR(ep);
2208 vpp = vartab;
2209 mask = on | off;
2210 do {
2211 for (vp = *vpp; vp; vp = vp->next) {
2212 if ((vp->flags & mask) == on) {
2213 if (ep == stackstrend())
2214 ep = growstackstr();
2215 *ep++ = (char *) vp->text;
2216 }
2217 }
2218 } while (++vpp < vartab + VTABSIZE);
2219 if (ep == stackstrend())
2220 ep = growstackstr();
2221 if (end)
2222 *end = ep;
2223 *ep++ = NULL;
2224 return grabstackstr(ep);
2225}
2226
2227
2228/* ============ Path search helper
2229 *
2230 * The variable path (passed by reference) should be set to the start
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02002231 * of the path before the first call; path_advance will update
2232 * this value as it proceeds. Successive calls to path_advance will return
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002233 * the possible path expansions in sequence. If an option (indicated by
2234 * a percent sign) appears in the path entry then the global variable
2235 * pathopt will be set to point to it; otherwise pathopt will be set to
2236 * NULL.
2237 */
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02002238static const char *pathopt; /* set by path_advance */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002239
2240static char *
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02002241path_advance(const char **path, const char *name)
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002242{
2243 const char *p;
2244 char *q;
2245 const char *start;
2246 size_t len;
2247
2248 if (*path == NULL)
2249 return NULL;
2250 start = *path;
Denis Vlasenkof7d56652008-03-25 05:51:41 +00002251 for (p = start; *p && *p != ':' && *p != '%'; p++)
2252 continue;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002253 len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
2254 while (stackblocksize() < len)
2255 growstackblock();
2256 q = stackblock();
2257 if (p != start) {
2258 memcpy(q, start, p - start);
2259 q += p - start;
2260 *q++ = '/';
2261 }
2262 strcpy(q, name);
2263 pathopt = NULL;
2264 if (*p == '%') {
2265 pathopt = ++p;
Denis Vlasenkof7d56652008-03-25 05:51:41 +00002266 while (*p && *p != ':')
2267 p++;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002268 }
2269 if (*p == ':')
2270 *path = p + 1;
2271 else
2272 *path = NULL;
2273 return stalloc(len);
2274}
2275
2276
2277/* ============ Prompt */
2278
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +00002279static smallint doprompt; /* if set, prompt the user */
2280static smallint needprompt; /* true if interactive and at start of line */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002281
2282#if ENABLE_FEATURE_EDITING
2283static line_input_t *line_input_state;
2284static const char *cmdedit_prompt;
2285static void
2286putprompt(const char *s)
2287{
2288 if (ENABLE_ASH_EXPAND_PRMT) {
2289 free((char*)cmdedit_prompt);
Denis Vlasenko4222ae42007-02-25 02:37:49 +00002290 cmdedit_prompt = ckstrdup(s);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002291 return;
2292 }
2293 cmdedit_prompt = s;
2294}
2295#else
2296static void
2297putprompt(const char *s)
2298{
2299 out2str(s);
2300}
2301#endif
2302
2303#if ENABLE_ASH_EXPAND_PRMT
2304/* expandstr() needs parsing machinery, so it is far away ahead... */
2305static const char *expandstr(const char *ps);
2306#else
2307#define expandstr(s) s
2308#endif
2309
2310static void
2311setprompt(int whichprompt)
2312{
2313 const char *prompt;
2314#if ENABLE_ASH_EXPAND_PRMT
2315 struct stackmark smark;
2316#endif
2317
2318 needprompt = 0;
2319
2320 switch (whichprompt) {
2321 case 1:
2322 prompt = ps1val();
2323 break;
2324 case 2:
2325 prompt = ps2val();
2326 break;
2327 default: /* 0 */
2328 prompt = nullstr;
2329 }
2330#if ENABLE_ASH_EXPAND_PRMT
2331 setstackmark(&smark);
2332 stalloc(stackblocksize());
2333#endif
2334 putprompt(expandstr(prompt));
2335#if ENABLE_ASH_EXPAND_PRMT
2336 popstackmark(&smark);
2337#endif
2338}
2339
2340
2341/* ============ The cd and pwd commands */
2342
2343#define CD_PHYSICAL 1
2344#define CD_PRINT 2
2345
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002346static int
2347cdopt(void)
2348{
2349 int flags = 0;
2350 int i, j;
2351
2352 j = 'L';
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02002353 while ((i = nextopt("LP")) != '\0') {
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002354 if (i != j) {
2355 flags ^= CD_PHYSICAL;
2356 j = i;
2357 }
2358 }
2359
2360 return flags;
2361}
2362
2363/*
2364 * Update curdir (the name of the current directory) in response to a
2365 * cd command.
2366 */
2367static const char *
2368updatepwd(const char *dir)
2369{
2370 char *new;
2371 char *p;
2372 char *cdcomppath;
2373 const char *lim;
2374
2375 cdcomppath = ststrdup(dir);
2376 STARTSTACKSTR(new);
2377 if (*dir != '/') {
2378 if (curdir == nullstr)
2379 return 0;
2380 new = stack_putstr(curdir, new);
2381 }
2382 new = makestrspace(strlen(dir) + 2, new);
Denis Vlasenko29eb3592008-05-18 14:06:08 +00002383 lim = (char *)stackblock() + 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002384 if (*dir != '/') {
2385 if (new[-1] != '/')
2386 USTPUTC('/', new);
2387 if (new > lim && *lim == '/')
2388 lim++;
2389 } else {
2390 USTPUTC('/', new);
2391 cdcomppath++;
2392 if (dir[1] == '/' && dir[2] != '/') {
2393 USTPUTC('/', new);
2394 cdcomppath++;
2395 lim++;
2396 }
2397 }
2398 p = strtok(cdcomppath, "/");
2399 while (p) {
2400 switch (*p) {
2401 case '.':
2402 if (p[1] == '.' && p[2] == '\0') {
2403 while (new > lim) {
2404 STUNPUTC(new);
2405 if (new[-1] == '/')
2406 break;
2407 }
2408 break;
Denis Vlasenko16abcd92007-04-13 23:59:52 +00002409 }
2410 if (p[1] == '\0')
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002411 break;
2412 /* fall through */
2413 default:
2414 new = stack_putstr(p, new);
2415 USTPUTC('/', new);
2416 }
2417 p = strtok(0, "/");
2418 }
2419 if (new > lim)
2420 STUNPUTC(new);
2421 *new = 0;
2422 return stackblock();
2423}
2424
2425/*
2426 * Find out what the current directory is. If we already know the current
2427 * directory, this routine returns immediately.
2428 */
2429static char *
2430getpwd(void)
2431{
Denis Vlasenko01631112007-12-16 17:20:38 +00002432 char *dir = getcwd(NULL, 0); /* huh, using glibc extension? */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002433 return dir ? dir : nullstr;
2434}
2435
2436static void
2437setpwd(const char *val, int setold)
2438{
2439 char *oldcur, *dir;
2440
2441 oldcur = dir = curdir;
2442
2443 if (setold) {
2444 setvar("OLDPWD", oldcur, VEXPORT);
2445 }
2446 INT_OFF;
2447 if (physdir != nullstr) {
2448 if (physdir != oldcur)
2449 free(physdir);
2450 physdir = nullstr;
2451 }
2452 if (oldcur == val || !val) {
2453 char *s = getpwd();
2454 physdir = s;
2455 if (!val)
2456 dir = s;
2457 } else
2458 dir = ckstrdup(val);
2459 if (oldcur != dir && oldcur != nullstr) {
2460 free(oldcur);
2461 }
2462 curdir = dir;
2463 INT_ON;
2464 setvar("PWD", dir, VEXPORT);
2465}
2466
2467static void hashcd(void);
2468
2469/*
2470 * Actually do the chdir. We also call hashcd to let the routines in exec.c
2471 * know that the current directory has changed.
2472 */
2473static int
2474docd(const char *dest, int flags)
2475{
2476 const char *dir = 0;
2477 int err;
2478
2479 TRACE(("docd(\"%s\", %d) called\n", dest, flags));
2480
2481 INT_OFF;
2482 if (!(flags & CD_PHYSICAL)) {
2483 dir = updatepwd(dest);
2484 if (dir)
2485 dest = dir;
2486 }
2487 err = chdir(dest);
2488 if (err)
2489 goto out;
2490 setpwd(dir, 1);
2491 hashcd();
2492 out:
2493 INT_ON;
2494 return err;
2495}
2496
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02002497static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00002498cdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002499{
2500 const char *dest;
2501 const char *path;
2502 const char *p;
2503 char c;
2504 struct stat statb;
2505 int flags;
2506
2507 flags = cdopt();
2508 dest = *argptr;
2509 if (!dest)
2510 dest = bltinlookup(homestr);
2511 else if (LONE_DASH(dest)) {
2512 dest = bltinlookup("OLDPWD");
2513 flags |= CD_PRINT;
2514 }
2515 if (!dest)
2516 dest = nullstr;
2517 if (*dest == '/')
2518 goto step7;
2519 if (*dest == '.') {
2520 c = dest[1];
2521 dotdot:
2522 switch (c) {
2523 case '\0':
2524 case '/':
2525 goto step6;
2526 case '.':
2527 c = dest[2];
2528 if (c != '.')
2529 goto dotdot;
2530 }
2531 }
2532 if (!*dest)
2533 dest = ".";
2534 path = bltinlookup("CDPATH");
2535 if (!path) {
2536 step6:
2537 step7:
2538 p = dest;
2539 goto docd;
2540 }
2541 do {
2542 c = *path;
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02002543 p = path_advance(&path, dest);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002544 if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
2545 if (c && c != ':')
2546 flags |= CD_PRINT;
2547 docd:
2548 if (!docd(p, flags))
2549 goto out;
2550 break;
2551 }
2552 } while (path);
2553 ash_msg_and_raise_error("can't cd to %s", dest);
2554 /* NOTREACHED */
2555 out:
2556 if (flags & CD_PRINT)
2557 out1fmt(snlfmt, curdir);
2558 return 0;
2559}
2560
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02002561static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00002562pwdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002563{
2564 int flags;
2565 const char *dir = curdir;
2566
2567 flags = cdopt();
2568 if (flags) {
2569 if (physdir == nullstr)
2570 setpwd(dir, 0);
2571 dir = physdir;
2572 }
2573 out1fmt(snlfmt, dir);
2574 return 0;
2575}
2576
Denis Vlasenko0c032a42007-02-23 01:03:40 +00002577
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00002578/* ============ ... */
Eric Andersenc470f442003-07-28 09:56:35 +00002579
Denis Vlasenko834dee72008-10-07 09:18:30 +00002580
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +00002581#define IBUFSIZ COMMON_BUFSIZE
Denis Vlasenko834dee72008-10-07 09:18:30 +00002582/* buffer for top level input file */
2583#define basebuf bb_common_bufsiz1
Eric Andersenc470f442003-07-28 09:56:35 +00002584
Eric Andersenc470f442003-07-28 09:56:35 +00002585/* Syntax classes */
Denis Vlasenko834dee72008-10-07 09:18:30 +00002586#define CWORD 0 /* character is nothing special */
2587#define CNL 1 /* newline character */
2588#define CBACK 2 /* a backslash character */
2589#define CSQUOTE 3 /* single quote */
2590#define CDQUOTE 4 /* double quote */
Eric Andersenc470f442003-07-28 09:56:35 +00002591#define CENDQUOTE 5 /* a terminating quote */
Denis Vlasenko834dee72008-10-07 09:18:30 +00002592#define CBQUOTE 6 /* backwards single quote */
2593#define CVAR 7 /* a dollar sign */
2594#define CENDVAR 8 /* a '}' character */
2595#define CLP 9 /* a left paren in arithmetic */
2596#define CRP 10 /* a right paren in arithmetic */
Eric Andersenc470f442003-07-28 09:56:35 +00002597#define CENDFILE 11 /* end of file */
Denis Vlasenko834dee72008-10-07 09:18:30 +00002598#define CCTL 12 /* like CWORD, except it must be escaped */
2599#define CSPCL 13 /* these terminate a word */
2600#define CIGN 14 /* character should be ignored */
Eric Andersenc470f442003-07-28 09:56:35 +00002601
Denis Vlasenko131ae172007-02-18 13:00:19 +00002602#if ENABLE_ASH_ALIAS
Denis Vlasenko834dee72008-10-07 09:18:30 +00002603#define SYNBASE 130
2604#define PEOF -130
2605#define PEOA -129
Eric Andersenc470f442003-07-28 09:56:35 +00002606#define PEOA_OR_PEOF PEOA
2607#else
Denis Vlasenko834dee72008-10-07 09:18:30 +00002608#define SYNBASE 129
2609#define PEOF -129
Eric Andersenc470f442003-07-28 09:56:35 +00002610#define PEOA_OR_PEOF PEOF
2611#endif
2612
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00002613/* number syntax index */
2614#define BASESYNTAX 0 /* not in quotes */
2615#define DQSYNTAX 1 /* in double quotes */
2616#define SQSYNTAX 2 /* in single quotes */
2617#define ARISYNTAX 3 /* in arithmetic */
Denis Vlasenko46a53062007-09-24 18:30:02 +00002618#define PSSYNTAX 4 /* prompt */
Eric Andersenc470f442003-07-28 09:56:35 +00002619
Denis Vlasenko131ae172007-02-18 13:00:19 +00002620#if ENABLE_ASH_OPTIMIZE_FOR_SIZE
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002621#define USE_SIT_FUNCTION
2622#endif
2623
Mike Frysinger98c52642009-04-02 10:02:37 +00002624#if ENABLE_SH_MATH_SUPPORT
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002625static const char S_I_T[][4] = {
Denis Vlasenko131ae172007-02-18 13:00:19 +00002626#if ENABLE_ASH_ALIAS
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00002627 { CSPCL, CIGN, CIGN, CIGN }, /* 0, PEOA */
Eric Andersenc470f442003-07-28 09:56:35 +00002628#endif
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00002629 { CSPCL, CWORD, CWORD, CWORD }, /* 1, ' ' */
2630 { CNL, CNL, CNL, CNL }, /* 2, \n */
2631 { CWORD, CCTL, CCTL, CWORD }, /* 3, !*-/:=?[]~ */
2632 { CDQUOTE, CENDQUOTE, CWORD, CWORD }, /* 4, '"' */
2633 { CVAR, CVAR, CWORD, CVAR }, /* 5, $ */
2634 { CSQUOTE, CWORD, CENDQUOTE, CWORD }, /* 6, "'" */
2635 { CSPCL, CWORD, CWORD, CLP }, /* 7, ( */
2636 { CSPCL, CWORD, CWORD, CRP }, /* 8, ) */
2637 { CBACK, CBACK, CCTL, CBACK }, /* 9, \ */
2638 { CBQUOTE, CBQUOTE, CWORD, CBQUOTE }, /* 10, ` */
2639 { CENDVAR, CENDVAR, CWORD, CENDVAR }, /* 11, } */
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002640#ifndef USE_SIT_FUNCTION
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00002641 { CENDFILE, CENDFILE, CENDFILE, CENDFILE }, /* 12, PEOF */
2642 { CWORD, CWORD, CWORD, CWORD }, /* 13, 0-9A-Za-z */
2643 { CCTL, CCTL, CCTL, CCTL } /* 14, CTLESC ... */
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002644#endif
Eric Andersen2870d962001-07-02 17:27:21 +00002645};
Eric Andersenc470f442003-07-28 09:56:35 +00002646#else
2647static const char S_I_T[][3] = {
Denis Vlasenko131ae172007-02-18 13:00:19 +00002648#if ENABLE_ASH_ALIAS
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00002649 { CSPCL, CIGN, CIGN }, /* 0, PEOA */
Eric Andersenc470f442003-07-28 09:56:35 +00002650#endif
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00002651 { CSPCL, CWORD, CWORD }, /* 1, ' ' */
2652 { CNL, CNL, CNL }, /* 2, \n */
2653 { CWORD, CCTL, CCTL }, /* 3, !*-/:=?[]~ */
2654 { CDQUOTE, CENDQUOTE, CWORD }, /* 4, '"' */
2655 { CVAR, CVAR, CWORD }, /* 5, $ */
2656 { CSQUOTE, CWORD, CENDQUOTE }, /* 6, "'" */
2657 { CSPCL, CWORD, CWORD }, /* 7, ( */
2658 { CSPCL, CWORD, CWORD }, /* 8, ) */
2659 { CBACK, CBACK, CCTL }, /* 9, \ */
2660 { CBQUOTE, CBQUOTE, CWORD }, /* 10, ` */
2661 { CENDVAR, CENDVAR, CWORD }, /* 11, } */
Eric Andersenc470f442003-07-28 09:56:35 +00002662#ifndef USE_SIT_FUNCTION
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00002663 { CENDFILE, CENDFILE, CENDFILE }, /* 12, PEOF */
2664 { CWORD, CWORD, CWORD }, /* 13, 0-9A-Za-z */
2665 { CCTL, CCTL, CCTL } /* 14, CTLESC ... */
Eric Andersenc470f442003-07-28 09:56:35 +00002666#endif
2667};
Mike Frysinger98c52642009-04-02 10:02:37 +00002668#endif /* SH_MATH_SUPPORT */
Eric Andersen2870d962001-07-02 17:27:21 +00002669
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002670#ifdef USE_SIT_FUNCTION
2671
Denis Vlasenko0c032a42007-02-23 01:03:40 +00002672static int
2673SIT(int c, int syntax)
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002674{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00002675 static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-/:;<=>?[\\]`|}~";
Denis Vlasenko131ae172007-02-18 13:00:19 +00002676#if ENABLE_ASH_ALIAS
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00002677 static const char syntax_index_table[] ALIGN1 = {
Eric Andersenc470f442003-07-28 09:56:35 +00002678 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
2679 7, 8, 3, 3, 3, 3, 1, 1, /* "()*-/:;<" */
2680 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
2681 11, 3 /* "}~" */
2682 };
2683#else
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00002684 static const char syntax_index_table[] ALIGN1 = {
Eric Andersenc470f442003-07-28 09:56:35 +00002685 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
2686 6, 7, 2, 2, 2, 2, 0, 0, /* "()*-/:;<" */
2687 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
2688 10, 2 /* "}~" */
2689 };
2690#endif
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002691 const char *s;
2692 int indx;
2693
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +00002694 if (c == PEOF) { /* 2^8+2 */
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002695 return CENDFILE;
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002696 }
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +00002697#if ENABLE_ASH_ALIAS
2698 if (c == PEOA) { /* 2^8+1 */
2699 indx = 0;
2700 } else
2701#endif
2702 {
Denys Vlasenkob0d63382009-09-16 16:18:32 +02002703 if ((unsigned char)c >= CTLESC
2704 && (unsigned char)c <= CTLQUOTEMARK
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +00002705 ) {
2706 return CCTL;
2707 }
2708 s = strchrnul(spec_symbls, c);
2709 if (*s == '\0') {
2710 return CWORD;
2711 }
2712 indx = syntax_index_table[s - spec_symbls];
2713 }
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002714 return S_I_T[indx][syntax];
2715}
2716
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00002717#else /* !USE_SIT_FUNCTION */
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002718
Denis Vlasenko131ae172007-02-18 13:00:19 +00002719#if ENABLE_ASH_ALIAS
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00002720#define CSPCL_CIGN_CIGN_CIGN 0
2721#define CSPCL_CWORD_CWORD_CWORD 1
2722#define CNL_CNL_CNL_CNL 2
2723#define CWORD_CCTL_CCTL_CWORD 3
2724#define CDQUOTE_CENDQUOTE_CWORD_CWORD 4
2725#define CVAR_CVAR_CWORD_CVAR 5
2726#define CSQUOTE_CWORD_CENDQUOTE_CWORD 6
2727#define CSPCL_CWORD_CWORD_CLP 7
2728#define CSPCL_CWORD_CWORD_CRP 8
2729#define CBACK_CBACK_CCTL_CBACK 9
2730#define CBQUOTE_CBQUOTE_CWORD_CBQUOTE 10
2731#define CENDVAR_CENDVAR_CWORD_CENDVAR 11
2732#define CENDFILE_CENDFILE_CENDFILE_CENDFILE 12
2733#define CWORD_CWORD_CWORD_CWORD 13
2734#define CCTL_CCTL_CCTL_CCTL 14
Eric Andersenc470f442003-07-28 09:56:35 +00002735#else
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00002736#define CSPCL_CWORD_CWORD_CWORD 0
2737#define CNL_CNL_CNL_CNL 1
2738#define CWORD_CCTL_CCTL_CWORD 2
2739#define CDQUOTE_CENDQUOTE_CWORD_CWORD 3
2740#define CVAR_CVAR_CWORD_CVAR 4
2741#define CSQUOTE_CWORD_CENDQUOTE_CWORD 5
2742#define CSPCL_CWORD_CWORD_CLP 6
2743#define CSPCL_CWORD_CWORD_CRP 7
2744#define CBACK_CBACK_CCTL_CBACK 8
2745#define CBQUOTE_CBQUOTE_CWORD_CBQUOTE 9
2746#define CENDVAR_CENDVAR_CWORD_CENDVAR 10
2747#define CENDFILE_CENDFILE_CENDFILE_CENDFILE 11
2748#define CWORD_CWORD_CWORD_CWORD 12
2749#define CCTL_CCTL_CCTL_CCTL 13
Eric Andersenc470f442003-07-28 09:56:35 +00002750#endif
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002751
2752static const char syntax_index_table[258] = {
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00002753 /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
Eric Andersenc470f442003-07-28 09:56:35 +00002754 /* 0 PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
Denis Vlasenko131ae172007-02-18 13:00:19 +00002755#if ENABLE_ASH_ALIAS
Eric Andersenc470f442003-07-28 09:56:35 +00002756 /* 1 PEOA */ CSPCL_CIGN_CIGN_CIGN,
2757#endif
2758 /* 2 -128 0x80 */ CWORD_CWORD_CWORD_CWORD,
2759 /* 3 -127 CTLESC */ CCTL_CCTL_CCTL_CCTL,
2760 /* 4 -126 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
2761 /* 5 -125 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
2762 /* 6 -124 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
2763 /* 7 -123 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
2764 /* 8 -122 CTLARI */ CCTL_CCTL_CCTL_CCTL,
2765 /* 9 -121 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
2766 /* 10 -120 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00002767 /* 11 -119 */ CWORD_CWORD_CWORD_CWORD,
2768 /* 12 -118 */ CWORD_CWORD_CWORD_CWORD,
2769 /* 13 -117 */ CWORD_CWORD_CWORD_CWORD,
2770 /* 14 -116 */ CWORD_CWORD_CWORD_CWORD,
2771 /* 15 -115 */ CWORD_CWORD_CWORD_CWORD,
2772 /* 16 -114 */ CWORD_CWORD_CWORD_CWORD,
2773 /* 17 -113 */ CWORD_CWORD_CWORD_CWORD,
2774 /* 18 -112 */ CWORD_CWORD_CWORD_CWORD,
2775 /* 19 -111 */ CWORD_CWORD_CWORD_CWORD,
2776 /* 20 -110 */ CWORD_CWORD_CWORD_CWORD,
2777 /* 21 -109 */ CWORD_CWORD_CWORD_CWORD,
2778 /* 22 -108 */ CWORD_CWORD_CWORD_CWORD,
2779 /* 23 -107 */ CWORD_CWORD_CWORD_CWORD,
2780 /* 24 -106 */ CWORD_CWORD_CWORD_CWORD,
2781 /* 25 -105 */ CWORD_CWORD_CWORD_CWORD,
2782 /* 26 -104 */ CWORD_CWORD_CWORD_CWORD,
2783 /* 27 -103 */ CWORD_CWORD_CWORD_CWORD,
2784 /* 28 -102 */ CWORD_CWORD_CWORD_CWORD,
2785 /* 29 -101 */ CWORD_CWORD_CWORD_CWORD,
2786 /* 30 -100 */ CWORD_CWORD_CWORD_CWORD,
2787 /* 31 -99 */ CWORD_CWORD_CWORD_CWORD,
2788 /* 32 -98 */ CWORD_CWORD_CWORD_CWORD,
2789 /* 33 -97 */ CWORD_CWORD_CWORD_CWORD,
2790 /* 34 -96 */ CWORD_CWORD_CWORD_CWORD,
2791 /* 35 -95 */ CWORD_CWORD_CWORD_CWORD,
2792 /* 36 -94 */ CWORD_CWORD_CWORD_CWORD,
2793 /* 37 -93 */ CWORD_CWORD_CWORD_CWORD,
2794 /* 38 -92 */ CWORD_CWORD_CWORD_CWORD,
2795 /* 39 -91 */ CWORD_CWORD_CWORD_CWORD,
2796 /* 40 -90 */ CWORD_CWORD_CWORD_CWORD,
2797 /* 41 -89 */ CWORD_CWORD_CWORD_CWORD,
2798 /* 42 -88 */ CWORD_CWORD_CWORD_CWORD,
2799 /* 43 -87 */ CWORD_CWORD_CWORD_CWORD,
2800 /* 44 -86 */ CWORD_CWORD_CWORD_CWORD,
2801 /* 45 -85 */ CWORD_CWORD_CWORD_CWORD,
2802 /* 46 -84 */ CWORD_CWORD_CWORD_CWORD,
2803 /* 47 -83 */ CWORD_CWORD_CWORD_CWORD,
2804 /* 48 -82 */ CWORD_CWORD_CWORD_CWORD,
2805 /* 49 -81 */ CWORD_CWORD_CWORD_CWORD,
2806 /* 50 -80 */ CWORD_CWORD_CWORD_CWORD,
2807 /* 51 -79 */ CWORD_CWORD_CWORD_CWORD,
2808 /* 52 -78 */ CWORD_CWORD_CWORD_CWORD,
2809 /* 53 -77 */ CWORD_CWORD_CWORD_CWORD,
2810 /* 54 -76 */ CWORD_CWORD_CWORD_CWORD,
2811 /* 55 -75 */ CWORD_CWORD_CWORD_CWORD,
2812 /* 56 -74 */ CWORD_CWORD_CWORD_CWORD,
2813 /* 57 -73 */ CWORD_CWORD_CWORD_CWORD,
2814 /* 58 -72 */ CWORD_CWORD_CWORD_CWORD,
2815 /* 59 -71 */ CWORD_CWORD_CWORD_CWORD,
2816 /* 60 -70 */ CWORD_CWORD_CWORD_CWORD,
2817 /* 61 -69 */ CWORD_CWORD_CWORD_CWORD,
2818 /* 62 -68 */ CWORD_CWORD_CWORD_CWORD,
2819 /* 63 -67 */ CWORD_CWORD_CWORD_CWORD,
2820 /* 64 -66 */ CWORD_CWORD_CWORD_CWORD,
2821 /* 65 -65 */ CWORD_CWORD_CWORD_CWORD,
2822 /* 66 -64 */ CWORD_CWORD_CWORD_CWORD,
2823 /* 67 -63 */ CWORD_CWORD_CWORD_CWORD,
2824 /* 68 -62 */ CWORD_CWORD_CWORD_CWORD,
2825 /* 69 -61 */ CWORD_CWORD_CWORD_CWORD,
2826 /* 70 -60 */ CWORD_CWORD_CWORD_CWORD,
2827 /* 71 -59 */ CWORD_CWORD_CWORD_CWORD,
2828 /* 72 -58 */ CWORD_CWORD_CWORD_CWORD,
2829 /* 73 -57 */ CWORD_CWORD_CWORD_CWORD,
2830 /* 74 -56 */ CWORD_CWORD_CWORD_CWORD,
2831 /* 75 -55 */ CWORD_CWORD_CWORD_CWORD,
2832 /* 76 -54 */ CWORD_CWORD_CWORD_CWORD,
2833 /* 77 -53 */ CWORD_CWORD_CWORD_CWORD,
2834 /* 78 -52 */ CWORD_CWORD_CWORD_CWORD,
2835 /* 79 -51 */ CWORD_CWORD_CWORD_CWORD,
2836 /* 80 -50 */ CWORD_CWORD_CWORD_CWORD,
2837 /* 81 -49 */ CWORD_CWORD_CWORD_CWORD,
2838 /* 82 -48 */ CWORD_CWORD_CWORD_CWORD,
2839 /* 83 -47 */ CWORD_CWORD_CWORD_CWORD,
2840 /* 84 -46 */ CWORD_CWORD_CWORD_CWORD,
2841 /* 85 -45 */ CWORD_CWORD_CWORD_CWORD,
2842 /* 86 -44 */ CWORD_CWORD_CWORD_CWORD,
2843 /* 87 -43 */ CWORD_CWORD_CWORD_CWORD,
2844 /* 88 -42 */ CWORD_CWORD_CWORD_CWORD,
2845 /* 89 -41 */ CWORD_CWORD_CWORD_CWORD,
2846 /* 90 -40 */ CWORD_CWORD_CWORD_CWORD,
2847 /* 91 -39 */ CWORD_CWORD_CWORD_CWORD,
2848 /* 92 -38 */ CWORD_CWORD_CWORD_CWORD,
2849 /* 93 -37 */ CWORD_CWORD_CWORD_CWORD,
2850 /* 94 -36 */ CWORD_CWORD_CWORD_CWORD,
2851 /* 95 -35 */ CWORD_CWORD_CWORD_CWORD,
2852 /* 96 -34 */ CWORD_CWORD_CWORD_CWORD,
2853 /* 97 -33 */ CWORD_CWORD_CWORD_CWORD,
2854 /* 98 -32 */ CWORD_CWORD_CWORD_CWORD,
2855 /* 99 -31 */ CWORD_CWORD_CWORD_CWORD,
2856 /* 100 -30 */ CWORD_CWORD_CWORD_CWORD,
2857 /* 101 -29 */ CWORD_CWORD_CWORD_CWORD,
2858 /* 102 -28 */ CWORD_CWORD_CWORD_CWORD,
2859 /* 103 -27 */ CWORD_CWORD_CWORD_CWORD,
2860 /* 104 -26 */ CWORD_CWORD_CWORD_CWORD,
2861 /* 105 -25 */ CWORD_CWORD_CWORD_CWORD,
2862 /* 106 -24 */ CWORD_CWORD_CWORD_CWORD,
2863 /* 107 -23 */ CWORD_CWORD_CWORD_CWORD,
2864 /* 108 -22 */ CWORD_CWORD_CWORD_CWORD,
2865 /* 109 -21 */ CWORD_CWORD_CWORD_CWORD,
2866 /* 110 -20 */ CWORD_CWORD_CWORD_CWORD,
2867 /* 111 -19 */ CWORD_CWORD_CWORD_CWORD,
2868 /* 112 -18 */ CWORD_CWORD_CWORD_CWORD,
2869 /* 113 -17 */ CWORD_CWORD_CWORD_CWORD,
2870 /* 114 -16 */ CWORD_CWORD_CWORD_CWORD,
2871 /* 115 -15 */ CWORD_CWORD_CWORD_CWORD,
2872 /* 116 -14 */ CWORD_CWORD_CWORD_CWORD,
2873 /* 117 -13 */ CWORD_CWORD_CWORD_CWORD,
2874 /* 118 -12 */ CWORD_CWORD_CWORD_CWORD,
2875 /* 119 -11 */ CWORD_CWORD_CWORD_CWORD,
2876 /* 120 -10 */ CWORD_CWORD_CWORD_CWORD,
2877 /* 121 -9 */ CWORD_CWORD_CWORD_CWORD,
2878 /* 122 -8 */ CWORD_CWORD_CWORD_CWORD,
2879 /* 123 -7 */ CWORD_CWORD_CWORD_CWORD,
2880 /* 124 -6 */ CWORD_CWORD_CWORD_CWORD,
2881 /* 125 -5 */ CWORD_CWORD_CWORD_CWORD,
2882 /* 126 -4 */ CWORD_CWORD_CWORD_CWORD,
2883 /* 127 -3 */ CWORD_CWORD_CWORD_CWORD,
2884 /* 128 -2 */ CWORD_CWORD_CWORD_CWORD,
2885 /* 129 -1 */ CWORD_CWORD_CWORD_CWORD,
2886 /* 130 0 */ CWORD_CWORD_CWORD_CWORD,
2887 /* 131 1 */ CWORD_CWORD_CWORD_CWORD,
2888 /* 132 2 */ CWORD_CWORD_CWORD_CWORD,
2889 /* 133 3 */ CWORD_CWORD_CWORD_CWORD,
2890 /* 134 4 */ CWORD_CWORD_CWORD_CWORD,
2891 /* 135 5 */ CWORD_CWORD_CWORD_CWORD,
2892 /* 136 6 */ CWORD_CWORD_CWORD_CWORD,
2893 /* 137 7 */ CWORD_CWORD_CWORD_CWORD,
2894 /* 138 8 */ CWORD_CWORD_CWORD_CWORD,
2895 /* 139 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
2896 /* 140 10 "\n" */ CNL_CNL_CNL_CNL,
2897 /* 141 11 */ CWORD_CWORD_CWORD_CWORD,
2898 /* 142 12 */ CWORD_CWORD_CWORD_CWORD,
2899 /* 143 13 */ CWORD_CWORD_CWORD_CWORD,
2900 /* 144 14 */ CWORD_CWORD_CWORD_CWORD,
2901 /* 145 15 */ CWORD_CWORD_CWORD_CWORD,
2902 /* 146 16 */ CWORD_CWORD_CWORD_CWORD,
2903 /* 147 17 */ CWORD_CWORD_CWORD_CWORD,
2904 /* 148 18 */ CWORD_CWORD_CWORD_CWORD,
2905 /* 149 19 */ CWORD_CWORD_CWORD_CWORD,
2906 /* 150 20 */ CWORD_CWORD_CWORD_CWORD,
2907 /* 151 21 */ CWORD_CWORD_CWORD_CWORD,
2908 /* 152 22 */ CWORD_CWORD_CWORD_CWORD,
2909 /* 153 23 */ CWORD_CWORD_CWORD_CWORD,
2910 /* 154 24 */ CWORD_CWORD_CWORD_CWORD,
2911 /* 155 25 */ CWORD_CWORD_CWORD_CWORD,
2912 /* 156 26 */ CWORD_CWORD_CWORD_CWORD,
2913 /* 157 27 */ CWORD_CWORD_CWORD_CWORD,
2914 /* 158 28 */ CWORD_CWORD_CWORD_CWORD,
2915 /* 159 29 */ CWORD_CWORD_CWORD_CWORD,
2916 /* 160 30 */ CWORD_CWORD_CWORD_CWORD,
2917 /* 161 31 */ CWORD_CWORD_CWORD_CWORD,
2918 /* 162 32 " " */ CSPCL_CWORD_CWORD_CWORD,
2919 /* 163 33 "!" */ CWORD_CCTL_CCTL_CWORD,
Eric Andersenc470f442003-07-28 09:56:35 +00002920 /* 164 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00002921 /* 165 35 "#" */ CWORD_CWORD_CWORD_CWORD,
2922 /* 166 36 "$" */ CVAR_CVAR_CWORD_CVAR,
2923 /* 167 37 "%" */ CWORD_CWORD_CWORD_CWORD,
2924 /* 168 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
Eric Andersenc470f442003-07-28 09:56:35 +00002925 /* 169 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00002926 /* 170 40 "(" */ CSPCL_CWORD_CWORD_CLP,
2927 /* 171 41 ")" */ CSPCL_CWORD_CWORD_CRP,
2928 /* 172 42 "*" */ CWORD_CCTL_CCTL_CWORD,
2929 /* 173 43 "+" */ CWORD_CWORD_CWORD_CWORD,
2930 /* 174 44 "," */ CWORD_CWORD_CWORD_CWORD,
2931 /* 175 45 "-" */ CWORD_CCTL_CCTL_CWORD,
2932 /* 176 46 "." */ CWORD_CWORD_CWORD_CWORD,
2933 /* 177 47 "/" */ CWORD_CCTL_CCTL_CWORD,
2934 /* 178 48 "0" */ CWORD_CWORD_CWORD_CWORD,
2935 /* 179 49 "1" */ CWORD_CWORD_CWORD_CWORD,
2936 /* 180 50 "2" */ CWORD_CWORD_CWORD_CWORD,
2937 /* 181 51 "3" */ CWORD_CWORD_CWORD_CWORD,
2938 /* 182 52 "4" */ CWORD_CWORD_CWORD_CWORD,
2939 /* 183 53 "5" */ CWORD_CWORD_CWORD_CWORD,
2940 /* 184 54 "6" */ CWORD_CWORD_CWORD_CWORD,
2941 /* 185 55 "7" */ CWORD_CWORD_CWORD_CWORD,
2942 /* 186 56 "8" */ CWORD_CWORD_CWORD_CWORD,
2943 /* 187 57 "9" */ CWORD_CWORD_CWORD_CWORD,
2944 /* 188 58 ":" */ CWORD_CCTL_CCTL_CWORD,
2945 /* 189 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
2946 /* 190 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
2947 /* 191 61 "=" */ CWORD_CCTL_CCTL_CWORD,
2948 /* 192 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
2949 /* 193 63 "?" */ CWORD_CCTL_CCTL_CWORD,
2950 /* 194 64 "@" */ CWORD_CWORD_CWORD_CWORD,
2951 /* 195 65 "A" */ CWORD_CWORD_CWORD_CWORD,
2952 /* 196 66 "B" */ CWORD_CWORD_CWORD_CWORD,
2953 /* 197 67 "C" */ CWORD_CWORD_CWORD_CWORD,
2954 /* 198 68 "D" */ CWORD_CWORD_CWORD_CWORD,
2955 /* 199 69 "E" */ CWORD_CWORD_CWORD_CWORD,
2956 /* 200 70 "F" */ CWORD_CWORD_CWORD_CWORD,
2957 /* 201 71 "G" */ CWORD_CWORD_CWORD_CWORD,
2958 /* 202 72 "H" */ CWORD_CWORD_CWORD_CWORD,
2959 /* 203 73 "I" */ CWORD_CWORD_CWORD_CWORD,
2960 /* 204 74 "J" */ CWORD_CWORD_CWORD_CWORD,
2961 /* 205 75 "K" */ CWORD_CWORD_CWORD_CWORD,
2962 /* 206 76 "L" */ CWORD_CWORD_CWORD_CWORD,
2963 /* 207 77 "M" */ CWORD_CWORD_CWORD_CWORD,
2964 /* 208 78 "N" */ CWORD_CWORD_CWORD_CWORD,
2965 /* 209 79 "O" */ CWORD_CWORD_CWORD_CWORD,
2966 /* 210 80 "P" */ CWORD_CWORD_CWORD_CWORD,
2967 /* 211 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
2968 /* 212 82 "R" */ CWORD_CWORD_CWORD_CWORD,
2969 /* 213 83 "S" */ CWORD_CWORD_CWORD_CWORD,
2970 /* 214 84 "T" */ CWORD_CWORD_CWORD_CWORD,
2971 /* 215 85 "U" */ CWORD_CWORD_CWORD_CWORD,
2972 /* 216 86 "V" */ CWORD_CWORD_CWORD_CWORD,
2973 /* 217 87 "W" */ CWORD_CWORD_CWORD_CWORD,
2974 /* 218 88 "X" */ CWORD_CWORD_CWORD_CWORD,
2975 /* 219 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
2976 /* 220 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
2977 /* 221 91 "[" */ CWORD_CCTL_CCTL_CWORD,
2978 /* 222 92 "\" */ CBACK_CBACK_CCTL_CBACK,
2979 /* 223 93 "]" */ CWORD_CCTL_CCTL_CWORD,
2980 /* 224 94 "^" */ CWORD_CWORD_CWORD_CWORD,
2981 /* 225 95 "_" */ CWORD_CWORD_CWORD_CWORD,
2982 /* 226 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
2983 /* 227 97 "a" */ CWORD_CWORD_CWORD_CWORD,
2984 /* 228 98 "b" */ CWORD_CWORD_CWORD_CWORD,
2985 /* 229 99 "c" */ CWORD_CWORD_CWORD_CWORD,
2986 /* 230 100 "d" */ CWORD_CWORD_CWORD_CWORD,
2987 /* 231 101 "e" */ CWORD_CWORD_CWORD_CWORD,
2988 /* 232 102 "f" */ CWORD_CWORD_CWORD_CWORD,
2989 /* 233 103 "g" */ CWORD_CWORD_CWORD_CWORD,
2990 /* 234 104 "h" */ CWORD_CWORD_CWORD_CWORD,
2991 /* 235 105 "i" */ CWORD_CWORD_CWORD_CWORD,
2992 /* 236 106 "j" */ CWORD_CWORD_CWORD_CWORD,
2993 /* 237 107 "k" */ CWORD_CWORD_CWORD_CWORD,
2994 /* 238 108 "l" */ CWORD_CWORD_CWORD_CWORD,
2995 /* 239 109 "m" */ CWORD_CWORD_CWORD_CWORD,
2996 /* 240 110 "n" */ CWORD_CWORD_CWORD_CWORD,
2997 /* 241 111 "o" */ CWORD_CWORD_CWORD_CWORD,
2998 /* 242 112 "p" */ CWORD_CWORD_CWORD_CWORD,
2999 /* 243 113 "q" */ CWORD_CWORD_CWORD_CWORD,
3000 /* 244 114 "r" */ CWORD_CWORD_CWORD_CWORD,
3001 /* 245 115 "s" */ CWORD_CWORD_CWORD_CWORD,
3002 /* 246 116 "t" */ CWORD_CWORD_CWORD_CWORD,
3003 /* 247 117 "u" */ CWORD_CWORD_CWORD_CWORD,
3004 /* 248 118 "v" */ CWORD_CWORD_CWORD_CWORD,
3005 /* 249 119 "w" */ CWORD_CWORD_CWORD_CWORD,
3006 /* 250 120 "x" */ CWORD_CWORD_CWORD_CWORD,
3007 /* 251 121 "y" */ CWORD_CWORD_CWORD_CWORD,
3008 /* 252 122 "z" */ CWORD_CWORD_CWORD_CWORD,
3009 /* 253 123 "{" */ CWORD_CWORD_CWORD_CWORD,
3010 /* 254 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
3011 /* 255 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
3012 /* 256 126 "~" */ CWORD_CCTL_CCTL_CWORD,
3013 /* 257 127 */ CWORD_CWORD_CWORD_CWORD,
Eric Andersen2870d962001-07-02 17:27:21 +00003014};
3015
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +00003016#define SIT(c, syntax) (S_I_T[(int)syntax_index_table[(int)(c) + SYNBASE]][syntax])
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00003017
"Vladimir N. Oleynik"fdb871c2006-01-25 11:53:47 +00003018#endif /* USE_SIT_FUNCTION */
Eric Andersenc470f442003-07-28 09:56:35 +00003019
Eric Andersen2870d962001-07-02 17:27:21 +00003020
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00003021/* ============ Alias handling */
Denis Vlasenkofc06f292007-02-23 21:09:35 +00003022
Denis Vlasenko131ae172007-02-18 13:00:19 +00003023#if ENABLE_ASH_ALIAS
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00003024
3025#define ALIASINUSE 1
3026#define ALIASDEAD 2
3027
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00003028struct alias {
3029 struct alias *next;
3030 char *name;
3031 char *val;
3032 int flag;
3033};
3034
Denis Vlasenko01631112007-12-16 17:20:38 +00003035
3036static struct alias **atab; // [ATABSIZE];
3037#define INIT_G_alias() do { \
3038 atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
3039} while (0)
3040
Eric Andersen2870d962001-07-02 17:27:21 +00003041
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00003042static struct alias **
3043__lookupalias(const char *name) {
3044 unsigned int hashval;
3045 struct alias **app;
3046 const char *p;
3047 unsigned int ch;
3048
3049 p = name;
3050
3051 ch = (unsigned char)*p;
3052 hashval = ch << 4;
3053 while (ch) {
3054 hashval += ch;
3055 ch = (unsigned char)*++p;
3056 }
3057 app = &atab[hashval % ATABSIZE];
3058
3059 for (; *app; app = &(*app)->next) {
3060 if (strcmp(name, (*app)->name) == 0) {
3061 break;
3062 }
3063 }
3064
3065 return app;
3066}
3067
3068static struct alias *
3069lookupalias(const char *name, int check)
3070{
3071 struct alias *ap = *__lookupalias(name);
3072
3073 if (check && ap && (ap->flag & ALIASINUSE))
3074 return NULL;
3075 return ap;
3076}
3077
3078static struct alias *
3079freealias(struct alias *ap)
3080{
3081 struct alias *next;
3082
3083 if (ap->flag & ALIASINUSE) {
3084 ap->flag |= ALIASDEAD;
3085 return ap;
3086 }
3087
3088 next = ap->next;
3089 free(ap->name);
3090 free(ap->val);
3091 free(ap);
3092 return next;
3093}
Eric Andersencb57d552001-06-28 07:25:16 +00003094
Eric Andersenc470f442003-07-28 09:56:35 +00003095static void
3096setalias(const char *name, const char *val)
Eric Andersencb57d552001-06-28 07:25:16 +00003097{
3098 struct alias *ap, **app;
3099
3100 app = __lookupalias(name);
3101 ap = *app;
Denis Vlasenkob012b102007-02-19 22:43:01 +00003102 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +00003103 if (ap) {
3104 if (!(ap->flag & ALIASINUSE)) {
Denis Vlasenkob012b102007-02-19 22:43:01 +00003105 free(ap->val);
Eric Andersencb57d552001-06-28 07:25:16 +00003106 }
Denis Vlasenko0c032a42007-02-23 01:03:40 +00003107 ap->val = ckstrdup(val);
Eric Andersencb57d552001-06-28 07:25:16 +00003108 ap->flag &= ~ALIASDEAD;
3109 } else {
3110 /* not found */
Denis Vlasenko597906c2008-02-20 16:38:54 +00003111 ap = ckzalloc(sizeof(struct alias));
Denis Vlasenko0c032a42007-02-23 01:03:40 +00003112 ap->name = ckstrdup(name);
3113 ap->val = ckstrdup(val);
Denis Vlasenko597906c2008-02-20 16:38:54 +00003114 /*ap->flag = 0; - ckzalloc did it */
3115 /*ap->next = NULL;*/
Eric Andersencb57d552001-06-28 07:25:16 +00003116 *app = ap;
3117 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00003118 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00003119}
3120
Eric Andersenc470f442003-07-28 09:56:35 +00003121static int
3122unalias(const char *name)
Eric Andersen2870d962001-07-02 17:27:21 +00003123{
Eric Andersencb57d552001-06-28 07:25:16 +00003124 struct alias **app;
3125
3126 app = __lookupalias(name);
3127
3128 if (*app) {
Denis Vlasenkob012b102007-02-19 22:43:01 +00003129 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +00003130 *app = freealias(*app);
Denis Vlasenkob012b102007-02-19 22:43:01 +00003131 INT_ON;
Denis Vlasenko079f8af2006-11-27 16:49:31 +00003132 return 0;
Eric Andersencb57d552001-06-28 07:25:16 +00003133 }
3134
Denis Vlasenko079f8af2006-11-27 16:49:31 +00003135 return 1;
Eric Andersencb57d552001-06-28 07:25:16 +00003136}
3137
Eric Andersenc470f442003-07-28 09:56:35 +00003138static void
3139rmaliases(void)
Eric Andersen2870d962001-07-02 17:27:21 +00003140{
Eric Andersencb57d552001-06-28 07:25:16 +00003141 struct alias *ap, **app;
3142 int i;
3143
Denis Vlasenkob012b102007-02-19 22:43:01 +00003144 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +00003145 for (i = 0; i < ATABSIZE; i++) {
3146 app = &atab[i];
3147 for (ap = *app; ap; ap = *app) {
3148 *app = freealias(*app);
3149 if (ap == *app) {
3150 app = &ap->next;
3151 }
3152 }
3153 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00003154 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00003155}
3156
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00003157static void
3158printalias(const struct alias *ap)
3159{
3160 out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
3161}
3162
Eric Andersencb57d552001-06-28 07:25:16 +00003163/*
3164 * TODO - sort output
3165 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02003166static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00003167aliascmd(int argc UNUSED_PARAM, char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +00003168{
3169 char *n, *v;
3170 int ret = 0;
3171 struct alias *ap;
3172
Denis Vlasenko68404f12008-03-17 09:00:54 +00003173 if (!argv[1]) {
Eric Andersencb57d552001-06-28 07:25:16 +00003174 int i;
3175
Denis Vlasenko68404f12008-03-17 09:00:54 +00003176 for (i = 0; i < ATABSIZE; i++) {
Eric Andersencb57d552001-06-28 07:25:16 +00003177 for (ap = atab[i]; ap; ap = ap->next) {
3178 printalias(ap);
3179 }
Denis Vlasenko68404f12008-03-17 09:00:54 +00003180 }
Denis Vlasenko079f8af2006-11-27 16:49:31 +00003181 return 0;
Eric Andersencb57d552001-06-28 07:25:16 +00003182 }
3183 while ((n = *++argv) != NULL) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00003184 v = strchr(n+1, '=');
3185 if (v == NULL) { /* n+1: funny ksh stuff */
3186 ap = *__lookupalias(n);
3187 if (ap == NULL) {
Eric Andersenc470f442003-07-28 09:56:35 +00003188 fprintf(stderr, "%s: %s not found\n", "alias", n);
Eric Andersencb57d552001-06-28 07:25:16 +00003189 ret = 1;
3190 } else
3191 printalias(ap);
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00003192 } else {
Eric Andersencb57d552001-06-28 07:25:16 +00003193 *v++ = '\0';
3194 setalias(n, v);
3195 }
3196 }
3197
Denis Vlasenkod9e15f22006-11-27 16:49:55 +00003198 return ret;
Eric Andersencb57d552001-06-28 07:25:16 +00003199}
3200
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02003201static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00003202unaliascmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersencb57d552001-06-28 07:25:16 +00003203{
3204 int i;
3205
3206 while ((i = nextopt("a")) != '\0') {
3207 if (i == 'a') {
3208 rmaliases();
Denis Vlasenko079f8af2006-11-27 16:49:31 +00003209 return 0;
Eric Andersencb57d552001-06-28 07:25:16 +00003210 }
3211 }
3212 for (i = 0; *argptr; argptr++) {
3213 if (unalias(*argptr)) {
Eric Andersenc470f442003-07-28 09:56:35 +00003214 fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
Eric Andersencb57d552001-06-28 07:25:16 +00003215 i = 1;
3216 }
3217 }
3218
Denis Vlasenkod9e15f22006-11-27 16:49:55 +00003219 return i;
Eric Andersencb57d552001-06-28 07:25:16 +00003220}
Denis Vlasenkofc06f292007-02-23 21:09:35 +00003221
Denis Vlasenko131ae172007-02-18 13:00:19 +00003222#endif /* ASH_ALIAS */
Eric Andersencb57d552001-06-28 07:25:16 +00003223
Eric Andersenc470f442003-07-28 09:56:35 +00003224
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003225/* ============ jobs.c */
3226
3227/* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
3228#define FORK_FG 0
3229#define FORK_BG 1
3230#define FORK_NOJOB 2
3231
3232/* mode flags for showjob(s) */
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003233#define SHOW_ONLY_PGID 0x01 /* show only pgid (jobs -p) */
3234#define SHOW_PIDS 0x02 /* show individual pids, not just one line per job */
3235#define SHOW_CHANGED 0x04 /* only jobs whose state has changed */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003236
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003237/*
3238 * A job structure contains information about a job. A job is either a
3239 * single process or a set of processes contained in a pipeline. In the
3240 * latter case, pidlist will be non-NULL, and will point to a -1 terminated
3241 * array of pids.
3242 */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003243struct procstat {
3244 pid_t pid; /* process id */
3245 int status; /* last process status from wait() */
3246 char *cmd; /* text of command being run */
3247};
3248
3249struct job {
3250 struct procstat ps0; /* status of process */
3251 struct procstat *ps; /* status or processes when more than one */
3252#if JOBS
3253 int stopstatus; /* status of a stopped job */
3254#endif
3255 uint32_t
3256 nprocs: 16, /* number of processes */
3257 state: 8,
3258#define JOBRUNNING 0 /* at least one proc running */
3259#define JOBSTOPPED 1 /* all procs are stopped */
3260#define JOBDONE 2 /* all procs are completed */
3261#if JOBS
3262 sigint: 1, /* job was killed by SIGINT */
3263 jobctl: 1, /* job running under job control */
3264#endif
3265 waited: 1, /* true if this entry has been waited for */
3266 used: 1, /* true if this entry is in used */
3267 changed: 1; /* true if status has changed */
3268 struct job *prev_job; /* previous job */
3269};
3270
Denis Vlasenko68404f12008-03-17 09:00:54 +00003271static struct job *makejob(/*union node *,*/ int);
Denis Vlasenko85c24712008-03-17 09:04:04 +00003272#if !JOBS
3273#define forkshell(job, node, mode) forkshell(job, mode)
3274#endif
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003275static int forkshell(struct job *, union node *, int);
3276static int waitforjob(struct job *);
3277
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003278#if !JOBS
Denis Vlasenkob07a4962008-06-22 13:16:23 +00003279enum { doing_jobctl = 0 };
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003280#define setjobctl(on) do {} while (0)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003281#else
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003282static smallint doing_jobctl; //references:8
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003283static void setjobctl(int);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003284#endif
3285
3286/*
Denis Vlasenko4b875702009-03-19 13:30:04 +00003287 * Ignore a signal.
3288 */
3289static void
3290ignoresig(int signo)
3291{
3292 /* Avoid unnecessary system calls. Is it already SIG_IGNed? */
3293 if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
3294 /* No, need to do it */
3295 signal(signo, SIG_IGN);
3296 }
3297 sigmode[signo - 1] = S_HARD_IGN;
3298}
3299
3300/*
3301 * Signal handler. Only one usage site - in setsignal()
3302 */
3303static void
3304onsig(int signo)
3305{
3306 gotsig[signo - 1] = 1;
3307
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02003308 if (signo == SIGINT && !trap[SIGINT]) {
3309 if (!suppress_int) {
3310 pending_sig = 0;
Denis Vlasenko4b875702009-03-19 13:30:04 +00003311 raise_interrupt(); /* does not return */
3312 }
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02003313 pending_int = 1;
Denis Vlasenko4b875702009-03-19 13:30:04 +00003314 } else {
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02003315 pending_sig = signo;
Denis Vlasenko4b875702009-03-19 13:30:04 +00003316 }
3317}
3318
3319/*
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003320 * Set the signal handler for the specified signal. The routine figures
3321 * out what it should be set to.
3322 */
3323static void
3324setsignal(int signo)
3325{
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003326 char *t;
3327 char cur_act, new_act;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003328 struct sigaction act;
3329
3330 t = trap[signo];
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003331 new_act = S_DFL;
3332 if (t != NULL) { /* trap for this sig is set */
3333 new_act = S_CATCH;
3334 if (t[0] == '\0') /* trap is "": ignore this sig */
3335 new_act = S_IGN;
3336 }
3337
3338 if (rootshell && new_act == S_DFL) {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003339 switch (signo) {
3340 case SIGINT:
3341 if (iflag || minusc || sflag == 0)
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003342 new_act = S_CATCH;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003343 break;
3344 case SIGQUIT:
3345#if DEBUG
3346 if (debug)
3347 break;
3348#endif
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003349 /* man bash:
3350 * "In all cases, bash ignores SIGQUIT. Non-builtin
3351 * commands run by bash have signal handlers
3352 * set to the values inherited by the shell
3353 * from its parent". */
3354 new_act = S_IGN;
3355 break;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003356 case SIGTERM:
3357 if (iflag)
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003358 new_act = S_IGN;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003359 break;
3360#if JOBS
3361 case SIGTSTP:
3362 case SIGTTOU:
3363 if (mflag)
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003364 new_act = S_IGN;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003365 break;
3366#endif
3367 }
3368 }
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003369//TODO: if !rootshell, we reset SIGQUIT to DFL,
3370//whereas we have to restore it to what shell got on entry
3371//from the parent. See comment above
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003372
3373 t = &sigmode[signo - 1];
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003374 cur_act = *t;
3375 if (cur_act == 0) {
3376 /* current setting is not yet known */
3377 if (sigaction(signo, NULL, &act)) {
3378 /* pretend it worked; maybe we should give a warning,
3379 * but other shells don't. We don't alter sigmode,
3380 * so we retry every time.
3381 * btw, in Linux it never fails. --vda */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003382 return;
3383 }
3384 if (act.sa_handler == SIG_IGN) {
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003385 cur_act = S_HARD_IGN;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003386 if (mflag
3387 && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
3388 ) {
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003389 cur_act = S_IGN; /* don't hard ignore these */
Denis Vlasenko991a1da2008-02-10 19:02:53 +00003390 }
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003391 }
3392 }
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003393 if (cur_act == S_HARD_IGN || cur_act == new_act)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003394 return;
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003395
Denis Vlasenko991a1da2008-02-10 19:02:53 +00003396 act.sa_handler = SIG_DFL;
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003397 switch (new_act) {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003398 case S_CATCH:
3399 act.sa_handler = onsig;
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003400 act.sa_flags = 0; /* matters only if !DFL and !IGN */
3401 sigfillset(&act.sa_mask); /* ditto */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003402 break;
3403 case S_IGN:
3404 act.sa_handler = SIG_IGN;
3405 break;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003406 }
Denis Vlasenko8e2cfec2008-03-12 23:19:35 +00003407 sigaction_set(signo, &act);
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003408
3409 *t = new_act;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003410}
3411
3412/* mode flags for set_curjob */
3413#define CUR_DELETE 2
3414#define CUR_RUNNING 1
3415#define CUR_STOPPED 0
3416
3417/* mode flags for dowait */
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00003418#define DOWAIT_NONBLOCK WNOHANG
3419#define DOWAIT_BLOCK 0
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003420
3421#if JOBS
3422/* pgrp of shell on invocation */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003423static int initialpgrp; //references:2
3424static int ttyfd = -1; //5
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003425#endif
3426/* array of jobs */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003427static struct job *jobtab; //5
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003428/* size of array */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003429static unsigned njobs; //4
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003430/* current job */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003431static struct job *curjob; //lots
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003432/* number of presumed living untracked jobs */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003433static int jobless; //4
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003434
3435static void
3436set_curjob(struct job *jp, unsigned mode)
3437{
3438 struct job *jp1;
3439 struct job **jpp, **curp;
3440
3441 /* first remove from list */
3442 jpp = curp = &curjob;
3443 do {
3444 jp1 = *jpp;
3445 if (jp1 == jp)
3446 break;
3447 jpp = &jp1->prev_job;
3448 } while (1);
3449 *jpp = jp1->prev_job;
3450
3451 /* Then re-insert in correct position */
3452 jpp = curp;
3453 switch (mode) {
3454 default:
3455#if DEBUG
3456 abort();
3457#endif
3458 case CUR_DELETE:
3459 /* job being deleted */
3460 break;
3461 case CUR_RUNNING:
3462 /* newly created job or backgrounded job,
3463 put after all stopped jobs. */
3464 do {
3465 jp1 = *jpp;
3466#if JOBS
3467 if (!jp1 || jp1->state != JOBSTOPPED)
3468#endif
3469 break;
3470 jpp = &jp1->prev_job;
3471 } while (1);
3472 /* FALLTHROUGH */
3473#if JOBS
3474 case CUR_STOPPED:
3475#endif
3476 /* newly stopped job - becomes curjob */
3477 jp->prev_job = *jpp;
3478 *jpp = jp;
3479 break;
3480 }
3481}
3482
3483#if JOBS || DEBUG
3484static int
3485jobno(const struct job *jp)
3486{
3487 return jp - jobtab + 1;
3488}
3489#endif
3490
3491/*
3492 * Convert a job name to a job structure.
3493 */
Denis Vlasenko85c24712008-03-17 09:04:04 +00003494#if !JOBS
3495#define getjob(name, getctl) getjob(name)
3496#endif
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003497static struct job *
3498getjob(const char *name, int getctl)
3499{
3500 struct job *jp;
3501 struct job *found;
Denys Vlasenkoffc39202009-08-17 02:12:20 +02003502 const char *err_msg = "%s: no such job";
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003503 unsigned num;
3504 int c;
3505 const char *p;
3506 char *(*match)(const char *, const char *);
3507
3508 jp = curjob;
3509 p = name;
3510 if (!p)
3511 goto currentjob;
3512
3513 if (*p != '%')
3514 goto err;
3515
3516 c = *++p;
3517 if (!c)
3518 goto currentjob;
3519
3520 if (!p[1]) {
3521 if (c == '+' || c == '%') {
3522 currentjob:
3523 err_msg = "No current job";
3524 goto check;
3525 }
3526 if (c == '-') {
3527 if (jp)
3528 jp = jp->prev_job;
3529 err_msg = "No previous job";
3530 check:
3531 if (!jp)
3532 goto err;
3533 goto gotit;
3534 }
3535 }
3536
3537 if (is_number(p)) {
3538 num = atoi(p);
3539 if (num < njobs) {
3540 jp = jobtab + num - 1;
3541 if (jp->used)
3542 goto gotit;
3543 goto err;
3544 }
3545 }
3546
3547 match = prefix;
3548 if (*p == '?') {
3549 match = strstr;
3550 p++;
3551 }
3552
Denys Vlasenkoffc39202009-08-17 02:12:20 +02003553 found = NULL;
3554 while (jp) {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003555 if (match(jp->ps[0].cmd, p)) {
3556 if (found)
3557 goto err;
3558 found = jp;
3559 err_msg = "%s: ambiguous";
3560 }
3561 jp = jp->prev_job;
3562 }
Denys Vlasenkoffc39202009-08-17 02:12:20 +02003563 if (!found)
3564 goto err;
3565 jp = found;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003566
3567 gotit:
3568#if JOBS
3569 err_msg = "job %s not created under job control";
3570 if (getctl && jp->jobctl == 0)
3571 goto err;
3572#endif
3573 return jp;
3574 err:
3575 ash_msg_and_raise_error(err_msg, name);
3576}
3577
3578/*
3579 * Mark a job structure as unused.
3580 */
3581static void
3582freejob(struct job *jp)
3583{
3584 struct procstat *ps;
3585 int i;
3586
3587 INT_OFF;
3588 for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
3589 if (ps->cmd != nullstr)
3590 free(ps->cmd);
3591 }
3592 if (jp->ps != &jp->ps0)
3593 free(jp->ps);
3594 jp->used = 0;
3595 set_curjob(jp, CUR_DELETE);
3596 INT_ON;
3597}
3598
3599#if JOBS
3600static void
3601xtcsetpgrp(int fd, pid_t pgrp)
3602{
3603 if (tcsetpgrp(fd, pgrp))
Bernhard Reutner-Fischera53de7f2008-07-21 13:46:54 +00003604 ash_msg_and_raise_error("can't set tty process group (%m)");
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003605}
3606
3607/*
3608 * Turn job control on and off.
3609 *
3610 * Note: This code assumes that the third arg to ioctl is a character
3611 * pointer, which is true on Berkeley systems but not System V. Since
3612 * System V doesn't have job control yet, this isn't a problem now.
3613 *
3614 * Called with interrupts off.
3615 */
3616static void
3617setjobctl(int on)
3618{
3619 int fd;
3620 int pgrp;
3621
Denis Vlasenkob07a4962008-06-22 13:16:23 +00003622 if (on == doing_jobctl || rootshell == 0)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003623 return;
3624 if (on) {
3625 int ofd;
3626 ofd = fd = open(_PATH_TTY, O_RDWR);
3627 if (fd < 0) {
3628 /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
3629 * That sometimes helps to acquire controlling tty.
3630 * Obviously, a workaround for bugs when someone
3631 * failed to provide a controlling tty to bash! :) */
Denis Vlasenkoed270a52007-11-26 05:37:07 +00003632 fd = 2;
3633 while (!isatty(fd))
3634 if (--fd < 0)
3635 goto out;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003636 }
3637 fd = fcntl(fd, F_DUPFD, 10);
Denis Vlasenkoed270a52007-11-26 05:37:07 +00003638 if (ofd >= 0)
3639 close(ofd);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003640 if (fd < 0)
3641 goto out;
Denis Vlasenkoed270a52007-11-26 05:37:07 +00003642 /* fd is a tty at this point */
Denis Vlasenko96e1b382007-09-30 23:50:48 +00003643 close_on_exec_on(fd);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003644 do { /* while we are in the background */
3645 pgrp = tcgetpgrp(fd);
3646 if (pgrp < 0) {
3647 out:
3648 ash_msg("can't access tty; job control turned off");
3649 mflag = on = 0;
3650 goto close;
3651 }
3652 if (pgrp == getpgrp())
3653 break;
3654 killpg(0, SIGTTIN);
3655 } while (1);
3656 initialpgrp = pgrp;
3657
3658 setsignal(SIGTSTP);
3659 setsignal(SIGTTOU);
3660 setsignal(SIGTTIN);
3661 pgrp = rootpid;
3662 setpgid(0, pgrp);
3663 xtcsetpgrp(fd, pgrp);
3664 } else {
3665 /* turning job control off */
3666 fd = ttyfd;
3667 pgrp = initialpgrp;
Denis Vlasenko08c8c1d2007-04-28 22:39:02 +00003668 /* was xtcsetpgrp, but this can make exiting ash
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00003669 * loop forever if pty is already deleted */
Denis Vlasenko08c8c1d2007-04-28 22:39:02 +00003670 tcsetpgrp(fd, pgrp);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003671 setpgid(0, pgrp);
3672 setsignal(SIGTSTP);
3673 setsignal(SIGTTOU);
3674 setsignal(SIGTTIN);
3675 close:
Denis Vlasenkoed270a52007-11-26 05:37:07 +00003676 if (fd >= 0)
3677 close(fd);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003678 fd = -1;
3679 }
3680 ttyfd = fd;
Denis Vlasenkob07a4962008-06-22 13:16:23 +00003681 doing_jobctl = on;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003682}
3683
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02003684static int FAST_FUNC
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003685killcmd(int argc, char **argv)
3686{
Denis Vlasenko68404f12008-03-17 09:00:54 +00003687 int i = 1;
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003688 if (argv[1] && strcmp(argv[1], "-l") != 0) {
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003689 do {
3690 if (argv[i][0] == '%') {
3691 struct job *jp = getjob(argv[i], 0);
3692 unsigned pid = jp->ps[0].pid;
3693 /* Enough space for ' -NNN<nul>' */
3694 argv[i] = alloca(sizeof(int)*3 + 3);
3695 /* kill_main has matching code to expect
3696 * leading space. Needed to not confuse
3697 * negative pids with "kill -SIGNAL_NO" syntax */
3698 sprintf(argv[i], " -%u", pid);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003699 }
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003700 } while (argv[++i]);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003701 }
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003702 return kill_main(argc, argv);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003703}
3704
3705static void
3706showpipe(struct job *jp, FILE *out)
3707{
3708 struct procstat *sp;
3709 struct procstat *spend;
3710
3711 spend = jp->ps + jp->nprocs;
3712 for (sp = jp->ps + 1; sp < spend; sp++)
3713 fprintf(out, " | %s", sp->cmd);
3714 outcslow('\n', out);
3715 flush_stdout_stderr();
3716}
3717
3718
3719static int
3720restartjob(struct job *jp, int mode)
3721{
3722 struct procstat *ps;
3723 int i;
3724 int status;
3725 pid_t pgid;
3726
3727 INT_OFF;
3728 if (jp->state == JOBDONE)
3729 goto out;
3730 jp->state = JOBRUNNING;
3731 pgid = jp->ps->pid;
3732 if (mode == FORK_FG)
3733 xtcsetpgrp(ttyfd, pgid);
3734 killpg(pgid, SIGCONT);
3735 ps = jp->ps;
3736 i = jp->nprocs;
3737 do {
3738 if (WIFSTOPPED(ps->status)) {
3739 ps->status = -1;
3740 }
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003741 ps++;
3742 } while (--i);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003743 out:
3744 status = (mode == FORK_FG) ? waitforjob(jp) : 0;
3745 INT_ON;
3746 return status;
3747}
3748
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02003749static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00003750fg_bgcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003751{
3752 struct job *jp;
3753 FILE *out;
3754 int mode;
3755 int retval;
3756
3757 mode = (**argv == 'f') ? FORK_FG : FORK_BG;
3758 nextopt(nullstr);
3759 argv = argptr;
3760 out = stdout;
3761 do {
3762 jp = getjob(*argv, 1);
3763 if (mode == FORK_BG) {
3764 set_curjob(jp, CUR_RUNNING);
3765 fprintf(out, "[%d] ", jobno(jp));
3766 }
3767 outstr(jp->ps->cmd, out);
3768 showpipe(jp, out);
3769 retval = restartjob(jp, mode);
3770 } while (*argv && *++argv);
3771 return retval;
3772}
3773#endif
3774
3775static int
3776sprint_status(char *s, int status, int sigonly)
3777{
3778 int col;
3779 int st;
3780
3781 col = 0;
3782 if (!WIFEXITED(status)) {
3783#if JOBS
3784 if (WIFSTOPPED(status))
3785 st = WSTOPSIG(status);
3786 else
3787#endif
3788 st = WTERMSIG(status);
3789 if (sigonly) {
3790 if (st == SIGINT || st == SIGPIPE)
3791 goto out;
3792#if JOBS
3793 if (WIFSTOPPED(status))
3794 goto out;
3795#endif
3796 }
3797 st &= 0x7f;
3798 col = fmtstr(s, 32, strsignal(st));
3799 if (WCOREDUMP(status)) {
3800 col += fmtstr(s + col, 16, " (core dumped)");
3801 }
3802 } else if (!sigonly) {
3803 st = WEXITSTATUS(status);
3804 if (st)
3805 col = fmtstr(s, 16, "Done(%d)", st);
3806 else
3807 col = fmtstr(s, 16, "Done");
3808 }
3809 out:
3810 return col;
3811}
3812
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003813static int
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00003814dowait(int wait_flags, struct job *job)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003815{
3816 int pid;
3817 int status;
3818 struct job *jp;
3819 struct job *thisjob;
3820 int state;
3821
Denis Vlasenkobe54d6b2008-10-27 14:25:52 +00003822 TRACE(("dowait(0x%x) called\n", wait_flags));
3823
3824 /* Do a wait system call. If job control is compiled in, we accept
3825 * stopped processes. wait_flags may have WNOHANG, preventing blocking.
3826 * NB: _not_ safe_waitpid, we need to detect EINTR */
3827 pid = waitpid(-1, &status,
3828 (doing_jobctl ? (wait_flags | WUNTRACED) : wait_flags));
Denis Vlasenkob21f3792009-03-19 23:09:58 +00003829 TRACE(("wait returns pid=%d, status=0x%x, errno=%d(%s)\n",
3830 pid, status, errno, strerror(errno)));
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003831 if (pid <= 0)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003832 return pid;
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003833
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003834 INT_OFF;
3835 thisjob = NULL;
3836 for (jp = curjob; jp; jp = jp->prev_job) {
3837 struct procstat *sp;
3838 struct procstat *spend;
3839 if (jp->state == JOBDONE)
3840 continue;
3841 state = JOBDONE;
3842 spend = jp->ps + jp->nprocs;
3843 sp = jp->ps;
3844 do {
3845 if (sp->pid == pid) {
3846 TRACE(("Job %d: changing status of proc %d "
3847 "from 0x%x to 0x%x\n",
3848 jobno(jp), pid, sp->status, status));
3849 sp->status = status;
3850 thisjob = jp;
3851 }
3852 if (sp->status == -1)
3853 state = JOBRUNNING;
3854#if JOBS
3855 if (state == JOBRUNNING)
3856 continue;
3857 if (WIFSTOPPED(sp->status)) {
3858 jp->stopstatus = sp->status;
3859 state = JOBSTOPPED;
3860 }
3861#endif
3862 } while (++sp < spend);
3863 if (thisjob)
3864 goto gotjob;
3865 }
3866#if JOBS
3867 if (!WIFSTOPPED(status))
3868#endif
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003869 jobless--;
3870 goto out;
3871
3872 gotjob:
3873 if (state != JOBRUNNING) {
3874 thisjob->changed = 1;
3875
3876 if (thisjob->state != state) {
3877 TRACE(("Job %d: changing state from %d to %d\n",
3878 jobno(thisjob), thisjob->state, state));
3879 thisjob->state = state;
3880#if JOBS
3881 if (state == JOBSTOPPED) {
3882 set_curjob(thisjob, CUR_STOPPED);
3883 }
3884#endif
3885 }
3886 }
3887
3888 out:
3889 INT_ON;
3890
3891 if (thisjob && thisjob == job) {
3892 char s[48 + 1];
3893 int len;
3894
3895 len = sprint_status(s, status, 1);
3896 if (len) {
3897 s[len] = '\n';
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00003898 s[len + 1] = '\0';
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003899 out2str(s);
3900 }
3901 }
3902 return pid;
3903}
3904
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003905static int
3906blocking_wait_with_raise_on_sig(struct job *job)
3907{
3908 pid_t pid = dowait(DOWAIT_BLOCK, job);
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02003909 if (pid <= 0 && pending_sig)
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003910 raise_exception(EXSIG);
3911 return pid;
3912}
3913
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003914#if JOBS
3915static void
3916showjob(FILE *out, struct job *jp, int mode)
3917{
3918 struct procstat *ps;
3919 struct procstat *psend;
3920 int col;
Denis Vlasenko40ba9982007-07-14 00:48:29 +00003921 int indent_col;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003922 char s[80];
3923
3924 ps = jp->ps;
3925
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003926 if (mode & SHOW_ONLY_PGID) { /* jobs -p */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003927 /* just output process (group) id of pipeline */
3928 fprintf(out, "%d\n", ps->pid);
3929 return;
3930 }
3931
3932 col = fmtstr(s, 16, "[%d] ", jobno(jp));
Denis Vlasenko40ba9982007-07-14 00:48:29 +00003933 indent_col = col;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003934
3935 if (jp == curjob)
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003936 s[col - 3] = '+';
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003937 else if (curjob && jp == curjob->prev_job)
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003938 s[col - 3] = '-';
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003939
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003940 if (mode & SHOW_PIDS)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003941 col += fmtstr(s + col, 16, "%d ", ps->pid);
3942
3943 psend = ps + jp->nprocs;
3944
3945 if (jp->state == JOBRUNNING) {
3946 strcpy(s + col, "Running");
3947 col += sizeof("Running") - 1;
3948 } else {
3949 int status = psend[-1].status;
3950 if (jp->state == JOBSTOPPED)
3951 status = jp->stopstatus;
3952 col += sprint_status(s + col, status, 0);
3953 }
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003954 /* By now, "[JOBID]* [maybe PID] STATUS" is printed */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003955
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003956 /* This loop either prints "<cmd1> | <cmd2> | <cmd3>" line
3957 * or prints several "PID | <cmdN>" lines,
3958 * depending on SHOW_PIDS bit.
3959 * We do not print status of individual processes
3960 * between PID and <cmdN>. bash does it, but not very well:
3961 * first line shows overall job status, not process status,
3962 * making it impossible to know 1st process status.
3963 */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003964 goto start;
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003965 while (1) {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003966 /* for each process */
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003967 s[0] = '\0';
3968 col = 33;
3969 if (mode & SHOW_PIDS)
3970 col = fmtstr(s, 48, "\n%*c%d ", indent_col, ' ', ps->pid) - 1;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003971 start:
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003972 fprintf(out, "%s%*c", s, 33 - col >= 0 ? 33 - col : 0, ' ');
3973 if (ps != jp->ps)
3974 fprintf(out, "| ");
3975 fprintf(out, "%s", ps->cmd);
3976 if (++ps == psend)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003977 break;
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003978 }
3979 outcslow('\n', out);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003980
3981 jp->changed = 0;
3982
3983 if (jp->state == JOBDONE) {
3984 TRACE(("showjob: freeing job %d\n", jobno(jp)));
3985 freejob(jp);
3986 }
3987}
3988
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003989/*
3990 * Print a list of jobs. If "change" is nonzero, only print jobs whose
3991 * statuses have changed since the last call to showjobs.
3992 */
3993static void
3994showjobs(FILE *out, int mode)
3995{
3996 struct job *jp;
3997
Denys Vlasenko883cea42009-07-11 15:31:59 +02003998 TRACE(("showjobs(0x%x) called\n", mode));
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003999
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004000 /* Handle all finished jobs */
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00004001 while (dowait(DOWAIT_NONBLOCK, NULL) > 0)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004002 continue;
4003
4004 for (jp = curjob; jp; jp = jp->prev_job) {
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00004005 if (!(mode & SHOW_CHANGED) || jp->changed) {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004006 showjob(out, jp, mode);
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00004007 }
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004008 }
4009}
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00004010
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02004011static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00004012jobscmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00004013{
4014 int mode, m;
4015
4016 mode = 0;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02004017 while ((m = nextopt("lp")) != '\0') {
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00004018 if (m == 'l')
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02004019 mode |= SHOW_PIDS;
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00004020 else
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02004021 mode |= SHOW_ONLY_PGID;
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00004022 }
4023
4024 argv = argptr;
4025 if (*argv) {
4026 do
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02004027 showjob(stdout, getjob(*argv, 0), mode);
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00004028 while (*++argv);
4029 } else
4030 showjobs(stdout, mode);
4031
4032 return 0;
4033}
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004034#endif /* JOBS */
4035
4036static int
4037getstatus(struct job *job)
4038{
4039 int status;
4040 int retval;
4041
4042 status = job->ps[job->nprocs - 1].status;
4043 retval = WEXITSTATUS(status);
4044 if (!WIFEXITED(status)) {
4045#if JOBS
4046 retval = WSTOPSIG(status);
4047 if (!WIFSTOPPED(status))
4048#endif
4049 {
4050 /* XXX: limits number of signals */
4051 retval = WTERMSIG(status);
4052#if JOBS
4053 if (retval == SIGINT)
4054 job->sigint = 1;
4055#endif
4056 }
4057 retval += 128;
4058 }
Denys Vlasenko883cea42009-07-11 15:31:59 +02004059 TRACE(("getstatus: job %d, nproc %d, status 0x%x, retval 0x%x\n",
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004060 jobno(job), job->nprocs, status, retval));
4061 return retval;
4062}
4063
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02004064static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00004065waitcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004066{
4067 struct job *job;
4068 int retval;
4069 struct job *jp;
4070
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02004071 if (pending_sig)
Denis Vlasenko991a1da2008-02-10 19:02:53 +00004072 raise_exception(EXSIG);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004073
4074 nextopt(nullstr);
4075 retval = 0;
4076
4077 argv = argptr;
4078 if (!*argv) {
4079 /* wait for all jobs */
4080 for (;;) {
4081 jp = curjob;
4082 while (1) {
Denis Vlasenko991a1da2008-02-10 19:02:53 +00004083 if (!jp) /* no running procs */
4084 goto ret;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004085 if (jp->state == JOBRUNNING)
4086 break;
4087 jp->waited = 1;
4088 jp = jp->prev_job;
4089 }
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004090 /* man bash:
4091 * "When bash is waiting for an asynchronous command via
4092 * the wait builtin, the reception of a signal for which a trap
4093 * has been set will cause the wait builtin to return immediately
4094 * with an exit status greater than 128, immediately after which
4095 * the trap is executed."
4096 * Do we do it that way? */
4097 blocking_wait_with_raise_on_sig(NULL);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004098 }
4099 }
4100
4101 retval = 127;
4102 do {
4103 if (**argv != '%') {
4104 pid_t pid = number(*argv);
4105 job = curjob;
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00004106 while (1) {
4107 if (!job)
4108 goto repeat;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004109 if (job->ps[job->nprocs - 1].pid == pid)
4110 break;
4111 job = job->prev_job;
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00004112 }
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004113 } else
4114 job = getjob(*argv, 0);
4115 /* loop until process terminated or stopped */
4116 while (job->state == JOBRUNNING)
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004117 blocking_wait_with_raise_on_sig(NULL);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004118 job->waited = 1;
4119 retval = getstatus(job);
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004120 repeat: ;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004121 } while (*++argv);
4122
Denis Vlasenko991a1da2008-02-10 19:02:53 +00004123 ret:
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004124 return retval;
4125}
4126
4127static struct job *
4128growjobtab(void)
4129{
4130 size_t len;
4131 ptrdiff_t offset;
4132 struct job *jp, *jq;
4133
4134 len = njobs * sizeof(*jp);
4135 jq = jobtab;
4136 jp = ckrealloc(jq, len + 4 * sizeof(*jp));
4137
4138 offset = (char *)jp - (char *)jq;
4139 if (offset) {
4140 /* Relocate pointers */
4141 size_t l = len;
4142
4143 jq = (struct job *)((char *)jq + l);
4144 while (l) {
4145 l -= sizeof(*jp);
4146 jq--;
4147#define joff(p) ((struct job *)((char *)(p) + l))
4148#define jmove(p) (p) = (void *)((char *)(p) + offset)
4149 if (joff(jp)->ps == &jq->ps0)
4150 jmove(joff(jp)->ps);
4151 if (joff(jp)->prev_job)
4152 jmove(joff(jp)->prev_job);
4153 }
4154 if (curjob)
4155 jmove(curjob);
4156#undef joff
4157#undef jmove
4158 }
4159
4160 njobs += 4;
4161 jobtab = jp;
4162 jp = (struct job *)((char *)jp + len);
4163 jq = jp + 3;
4164 do {
4165 jq->used = 0;
4166 } while (--jq >= jp);
4167 return jp;
4168}
4169
4170/*
4171 * Return a new job structure.
4172 * Called with interrupts off.
4173 */
4174static struct job *
Denis Vlasenko68404f12008-03-17 09:00:54 +00004175makejob(/*union node *node,*/ int nprocs)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004176{
4177 int i;
4178 struct job *jp;
4179
4180 for (i = njobs, jp = jobtab; ; jp++) {
4181 if (--i < 0) {
4182 jp = growjobtab();
4183 break;
4184 }
4185 if (jp->used == 0)
4186 break;
4187 if (jp->state != JOBDONE || !jp->waited)
4188 continue;
4189#if JOBS
Denis Vlasenkob07a4962008-06-22 13:16:23 +00004190 if (doing_jobctl)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004191 continue;
4192#endif
4193 freejob(jp);
4194 break;
4195 }
4196 memset(jp, 0, sizeof(*jp));
4197#if JOBS
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00004198 /* jp->jobctl is a bitfield.
4199 * "jp->jobctl |= jobctl" likely to give awful code */
Denis Vlasenkob07a4962008-06-22 13:16:23 +00004200 if (doing_jobctl)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004201 jp->jobctl = 1;
4202#endif
4203 jp->prev_job = curjob;
4204 curjob = jp;
4205 jp->used = 1;
4206 jp->ps = &jp->ps0;
4207 if (nprocs > 1) {
4208 jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
4209 }
Denis Vlasenko68404f12008-03-17 09:00:54 +00004210 TRACE(("makejob(%d) returns %%%d\n", nprocs,
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004211 jobno(jp)));
4212 return jp;
4213}
4214
4215#if JOBS
4216/*
4217 * Return a string identifying a command (to be printed by the
4218 * jobs command).
4219 */
4220static char *cmdnextc;
4221
4222static void
4223cmdputs(const char *s)
4224{
Denis Vlasenko92e13c22008-03-25 01:17:40 +00004225 static const char vstype[VSTYPE + 1][3] = {
4226 "", "}", "-", "+", "?", "=",
4227 "%", "%%", "#", "##"
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00004228 IF_ASH_BASH_COMPAT(, ":", "/", "//")
Denis Vlasenko92e13c22008-03-25 01:17:40 +00004229 };
4230
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004231 const char *p, *str;
4232 char c, cc[2] = " ";
4233 char *nextc;
4234 int subtype = 0;
4235 int quoted = 0;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004236
4237 nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
4238 p = s;
4239 while ((c = *p++) != 0) {
Denis Vlasenkoef527f52008-06-23 01:52:30 +00004240 str = NULL;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004241 switch (c) {
4242 case CTLESC:
4243 c = *p++;
4244 break;
4245 case CTLVAR:
4246 subtype = *p++;
4247 if ((subtype & VSTYPE) == VSLENGTH)
4248 str = "${#";
4249 else
4250 str = "${";
4251 if (!(subtype & VSQUOTE) == !(quoted & 1))
4252 goto dostr;
4253 quoted ^= 1;
4254 c = '"';
4255 break;
4256 case CTLENDVAR:
4257 str = "\"}" + !(quoted & 1);
4258 quoted >>= 1;
4259 subtype = 0;
4260 goto dostr;
4261 case CTLBACKQ:
4262 str = "$(...)";
4263 goto dostr;
4264 case CTLBACKQ+CTLQUOTE:
4265 str = "\"$(...)\"";
4266 goto dostr;
Mike Frysinger98c52642009-04-02 10:02:37 +00004267#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004268 case CTLARI:
4269 str = "$((";
4270 goto dostr;
4271 case CTLENDARI:
4272 str = "))";
4273 goto dostr;
4274#endif
4275 case CTLQUOTEMARK:
4276 quoted ^= 1;
4277 c = '"';
4278 break;
4279 case '=':
4280 if (subtype == 0)
4281 break;
4282 if ((subtype & VSTYPE) != VSNORMAL)
4283 quoted <<= 1;
4284 str = vstype[subtype & VSTYPE];
4285 if (subtype & VSNUL)
4286 c = ':';
4287 else
4288 goto checkstr;
4289 break;
4290 case '\'':
4291 case '\\':
4292 case '"':
4293 case '$':
4294 /* These can only happen inside quotes */
4295 cc[0] = c;
4296 str = cc;
4297 c = '\\';
4298 break;
4299 default:
4300 break;
4301 }
4302 USTPUTC(c, nextc);
4303 checkstr:
4304 if (!str)
4305 continue;
4306 dostr:
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02004307 while ((c = *str++) != '\0') {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004308 USTPUTC(c, nextc);
4309 }
4310 }
4311 if (quoted & 1) {
4312 USTPUTC('"', nextc);
4313 }
4314 *nextc = 0;
4315 cmdnextc = nextc;
4316}
4317
4318/* cmdtxt() and cmdlist() call each other */
4319static void cmdtxt(union node *n);
4320
4321static void
4322cmdlist(union node *np, int sep)
4323{
4324 for (; np; np = np->narg.next) {
4325 if (!sep)
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00004326 cmdputs(" ");
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004327 cmdtxt(np);
4328 if (sep && np->narg.next)
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00004329 cmdputs(" ");
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004330 }
4331}
4332
4333static void
4334cmdtxt(union node *n)
4335{
4336 union node *np;
4337 struct nodelist *lp;
4338 const char *p;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004339
4340 if (!n)
4341 return;
4342 switch (n->type) {
4343 default:
4344#if DEBUG
4345 abort();
4346#endif
4347 case NPIPE:
4348 lp = n->npipe.cmdlist;
4349 for (;;) {
4350 cmdtxt(lp->n);
4351 lp = lp->next;
4352 if (!lp)
4353 break;
4354 cmdputs(" | ");
4355 }
4356 break;
4357 case NSEMI:
4358 p = "; ";
4359 goto binop;
4360 case NAND:
4361 p = " && ";
4362 goto binop;
4363 case NOR:
4364 p = " || ";
4365 binop:
4366 cmdtxt(n->nbinary.ch1);
4367 cmdputs(p);
4368 n = n->nbinary.ch2;
4369 goto donode;
4370 case NREDIR:
4371 case NBACKGND:
4372 n = n->nredir.n;
4373 goto donode;
4374 case NNOT:
4375 cmdputs("!");
4376 n = n->nnot.com;
4377 donode:
4378 cmdtxt(n);
4379 break;
4380 case NIF:
4381 cmdputs("if ");
4382 cmdtxt(n->nif.test);
4383 cmdputs("; then ");
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004384 if (n->nif.elsepart) {
Denys Vlasenko7cee00e2009-07-24 01:08:03 +02004385 cmdtxt(n->nif.ifpart);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004386 cmdputs("; else ");
4387 n = n->nif.elsepart;
Denys Vlasenko7cee00e2009-07-24 01:08:03 +02004388 } else {
4389 n = n->nif.ifpart;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004390 }
4391 p = "; fi";
4392 goto dotail;
4393 case NSUBSHELL:
4394 cmdputs("(");
4395 n = n->nredir.n;
4396 p = ")";
4397 goto dotail;
4398 case NWHILE:
4399 p = "while ";
4400 goto until;
4401 case NUNTIL:
4402 p = "until ";
4403 until:
4404 cmdputs(p);
4405 cmdtxt(n->nbinary.ch1);
4406 n = n->nbinary.ch2;
4407 p = "; done";
4408 dodo:
4409 cmdputs("; do ");
4410 dotail:
4411 cmdtxt(n);
4412 goto dotail2;
4413 case NFOR:
4414 cmdputs("for ");
4415 cmdputs(n->nfor.var);
4416 cmdputs(" in ");
4417 cmdlist(n->nfor.args, 1);
4418 n = n->nfor.body;
4419 p = "; done";
4420 goto dodo;
4421 case NDEFUN:
4422 cmdputs(n->narg.text);
4423 p = "() { ... }";
4424 goto dotail2;
4425 case NCMD:
4426 cmdlist(n->ncmd.args, 1);
4427 cmdlist(n->ncmd.redirect, 0);
4428 break;
4429 case NARG:
4430 p = n->narg.text;
4431 dotail2:
4432 cmdputs(p);
4433 break;
4434 case NHERE:
4435 case NXHERE:
4436 p = "<<...";
4437 goto dotail2;
4438 case NCASE:
4439 cmdputs("case ");
4440 cmdputs(n->ncase.expr->narg.text);
4441 cmdputs(" in ");
4442 for (np = n->ncase.cases; np; np = np->nclist.next) {
4443 cmdtxt(np->nclist.pattern);
4444 cmdputs(") ");
4445 cmdtxt(np->nclist.body);
4446 cmdputs(";; ");
4447 }
4448 p = "esac";
4449 goto dotail2;
4450 case NTO:
4451 p = ">";
4452 goto redir;
4453 case NCLOBBER:
4454 p = ">|";
4455 goto redir;
4456 case NAPPEND:
4457 p = ">>";
4458 goto redir;
Denis Vlasenko559691a2008-10-05 18:39:31 +00004459#if ENABLE_ASH_BASH_COMPAT
4460 case NTO2:
4461#endif
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004462 case NTOFD:
4463 p = ">&";
4464 goto redir;
4465 case NFROM:
4466 p = "<";
4467 goto redir;
4468 case NFROMFD:
4469 p = "<&";
4470 goto redir;
4471 case NFROMTO:
4472 p = "<>";
4473 redir:
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00004474 cmdputs(utoa(n->nfile.fd));
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004475 cmdputs(p);
4476 if (n->type == NTOFD || n->type == NFROMFD) {
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00004477 cmdputs(utoa(n->ndup.dupfd));
4478 break;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004479 }
4480 n = n->nfile.fname;
4481 goto donode;
4482 }
4483}
4484
4485static char *
4486commandtext(union node *n)
4487{
4488 char *name;
4489
4490 STARTSTACKSTR(cmdnextc);
4491 cmdtxt(n);
4492 name = stackblock();
4493 TRACE(("commandtext: name %p, end %p\n\t\"%s\"\n",
4494 name, cmdnextc, cmdnextc));
4495 return ckstrdup(name);
4496}
4497#endif /* JOBS */
4498
4499/*
4500 * Fork off a subshell. If we are doing job control, give the subshell its
4501 * own process group. Jp is a job structure that the job is to be added to.
4502 * N is the command that will be evaluated by the child. Both jp and n may
4503 * be NULL. The mode parameter can be one of the following:
4504 * FORK_FG - Fork off a foreground process.
4505 * FORK_BG - Fork off a background process.
4506 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
4507 * process group even if job control is on.
4508 *
4509 * When job control is turned off, background processes have their standard
4510 * input redirected to /dev/null (except for the second and later processes
4511 * in a pipeline).
4512 *
4513 * Called with interrupts off.
4514 */
4515/*
4516 * Clear traps on a fork.
4517 */
4518static void
4519clear_traps(void)
4520{
4521 char **tp;
4522
4523 for (tp = trap; tp < &trap[NSIG]; tp++) {
Denis Vlasenko991a1da2008-02-10 19:02:53 +00004524 if (*tp && **tp) { /* trap not NULL or "" (SIG_IGN) */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004525 INT_OFF;
4526 free(*tp);
4527 *tp = NULL;
4528 if (tp != &trap[0])
4529 setsignal(tp - trap);
4530 INT_ON;
4531 }
4532 }
4533}
Denis Vlasenkobdc406d2007-07-15 01:13:25 +00004534
4535/* Lives far away from here, needed for forkchild */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004536static void closescript(void);
Denis Vlasenko41770222007-10-07 18:02:52 +00004537
Denis Vlasenkobdc406d2007-07-15 01:13:25 +00004538/* Called after fork(), in child */
Denys Vlasenkoe56f22a2009-07-24 00:16:59 +02004539#if !JOBS
4540# define forkchild(jp, n, mode) forkchild(jp, mode)
4541#endif
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004542static void
Denys Vlasenkoe56f22a2009-07-24 00:16:59 +02004543forkchild(struct job *jp, union node *n, int mode)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004544{
4545 int oldlvl;
4546
4547 TRACE(("Child shell %d\n", getpid()));
4548 oldlvl = shlvl;
4549 shlvl++;
4550
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004551 /* man bash: "Non-builtin commands run by bash have signal handlers
4552 * set to the values inherited by the shell from its parent".
4553 * Do we do it correctly? */
4554
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004555 closescript();
Denys Vlasenko844f9902009-09-23 03:25:52 +02004556
4557 if (mode == FORK_NOJOB /* is it `xxx` ? */
4558 && n && n->type == NCMD /* is it single cmd? */
4559 /* && n->ncmd.args->type == NARG - always true? */
4560 && strcmp(n->ncmd.args->narg.text, "trap") == 0
4561 && n->ncmd.args->narg.next == NULL /* "trap" with no arguments */
4562 /* && n->ncmd.args->narg.backquote == NULL - do we need to check this? */
4563 ) {
4564 TRACE(("Trap hack\n"));
4565 /* Awful hack for `trap` or $(trap).
4566 *
4567 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
4568 * contains an example where "trap" is executed in a subshell:
4569 *
4570 * save_traps=$(trap)
4571 * ...
4572 * eval "$save_traps"
4573 *
4574 * Standard does not say that "trap" in subshell shall print
4575 * parent shell's traps. It only says that its output
4576 * must have suitable form, but then, in the above example
4577 * (which is not supposed to be normative), it implies that.
4578 *
4579 * bash (and probably other shell) does implement it
4580 * (traps are reset to defaults, but "trap" still shows them),
4581 * but as a result, "trap" logic is hopelessly messed up:
4582 *
4583 * # trap
4584 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
4585 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
4586 * # true | trap <--- trap is in subshell - no output (ditto)
4587 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
4588 * trap -- 'echo Ho' SIGWINCH
4589 * # echo `(trap)` <--- in subshell in subshell - output
4590 * trap -- 'echo Ho' SIGWINCH
4591 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
4592 * trap -- 'echo Ho' SIGWINCH
4593 *
4594 * The rules when to forget and when to not forget traps
4595 * get really complex and nonsensical.
4596 *
4597 * Our solution: ONLY bare $(trap) or `trap` is special.
4598 */
4599 } else {
4600 clear_traps();
4601 }
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004602#if JOBS
4603 /* do job control only in root shell */
Denis Vlasenkob07a4962008-06-22 13:16:23 +00004604 doing_jobctl = 0;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004605 if (mode != FORK_NOJOB && jp->jobctl && !oldlvl) {
4606 pid_t pgrp;
4607
4608 if (jp->nprocs == 0)
4609 pgrp = getpid();
4610 else
4611 pgrp = jp->ps[0].pid;
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004612 /* this can fail because we are doing it in the parent also */
4613 setpgid(0, pgrp);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004614 if (mode == FORK_FG)
4615 xtcsetpgrp(ttyfd, pgrp);
4616 setsignal(SIGTSTP);
4617 setsignal(SIGTTOU);
4618 } else
4619#endif
4620 if (mode == FORK_BG) {
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004621 /* man bash: "When job control is not in effect,
4622 * asynchronous commands ignore SIGINT and SIGQUIT" */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004623 ignoresig(SIGINT);
4624 ignoresig(SIGQUIT);
4625 if (jp->nprocs == 0) {
4626 close(0);
4627 if (open(bb_dev_null, O_RDONLY) != 0)
Denis Vlasenko9604e1b2009-03-03 18:47:56 +00004628 ash_msg_and_raise_error("can't open '%s'", bb_dev_null);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004629 }
4630 }
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004631 if (!oldlvl) {
4632 if (iflag) { /* why if iflag only? */
4633 setsignal(SIGINT);
4634 setsignal(SIGTERM);
4635 }
4636 /* man bash:
4637 * "In all cases, bash ignores SIGQUIT. Non-builtin
4638 * commands run by bash have signal handlers
4639 * set to the values inherited by the shell
4640 * from its parent".
4641 * Take care of the second rule: */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004642 setsignal(SIGQUIT);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004643 }
Denys Vlasenkoe56f22a2009-07-24 00:16:59 +02004644#if JOBS
Denys Vlasenko844f9902009-09-23 03:25:52 +02004645 if (n && n->type == NCMD
4646 && strcmp(n->ncmd.args->narg.text, "jobs") == 0
4647 ) {
Denys Vlasenkoe56f22a2009-07-24 00:16:59 +02004648 TRACE(("Job hack\n"));
Denys Vlasenko844f9902009-09-23 03:25:52 +02004649 /* "jobs": we do not want to clear job list for it,
4650 * instead we remove only _its_ own_ job from job list.
4651 * This makes "jobs .... | cat" more useful.
4652 */
Denys Vlasenkoe56f22a2009-07-24 00:16:59 +02004653 freejob(curjob);
4654 return;
4655 }
4656#endif
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004657 for (jp = curjob; jp; jp = jp->prev_job)
4658 freejob(jp);
4659 jobless = 0;
4660}
4661
Denis Vlasenkobdc406d2007-07-15 01:13:25 +00004662/* Called after fork(), in parent */
Denis Vlasenko85c24712008-03-17 09:04:04 +00004663#if !JOBS
4664#define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
4665#endif
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004666static void
4667forkparent(struct job *jp, union node *n, int mode, pid_t pid)
4668{
4669 TRACE(("In parent shell: child = %d\n", pid));
4670 if (!jp) {
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00004671 while (jobless && dowait(DOWAIT_NONBLOCK, NULL) > 0)
4672 continue;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004673 jobless++;
4674 return;
4675 }
4676#if JOBS
4677 if (mode != FORK_NOJOB && jp->jobctl) {
4678 int pgrp;
4679
4680 if (jp->nprocs == 0)
4681 pgrp = pid;
4682 else
4683 pgrp = jp->ps[0].pid;
4684 /* This can fail because we are doing it in the child also */
4685 setpgid(pid, pgrp);
4686 }
4687#endif
4688 if (mode == FORK_BG) {
4689 backgndpid = pid; /* set $! */
4690 set_curjob(jp, CUR_RUNNING);
4691 }
4692 if (jp) {
4693 struct procstat *ps = &jp->ps[jp->nprocs++];
4694 ps->pid = pid;
4695 ps->status = -1;
4696 ps->cmd = nullstr;
4697#if JOBS
Denis Vlasenkob07a4962008-06-22 13:16:23 +00004698 if (doing_jobctl && n)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004699 ps->cmd = commandtext(n);
4700#endif
4701 }
4702}
4703
4704static int
4705forkshell(struct job *jp, union node *n, int mode)
4706{
4707 int pid;
4708
4709 TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
4710 pid = fork();
4711 if (pid < 0) {
4712 TRACE(("Fork failed, errno=%d", errno));
4713 if (jp)
4714 freejob(jp);
Denis Vlasenkofa0b56d2008-07-01 16:09:07 +00004715 ash_msg_and_raise_error("can't fork");
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004716 }
4717 if (pid == 0)
Denys Vlasenkoe56f22a2009-07-24 00:16:59 +02004718 forkchild(jp, n, mode);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004719 else
4720 forkparent(jp, n, mode, pid);
4721 return pid;
4722}
4723
4724/*
4725 * Wait for job to finish.
4726 *
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004727 * Under job control we have the problem that while a child process
4728 * is running interrupts generated by the user are sent to the child
4729 * but not to the shell. This means that an infinite loop started by
4730 * an interactive user may be hard to kill. With job control turned off,
4731 * an interactive user may place an interactive program inside a loop.
4732 * If the interactive program catches interrupts, the user doesn't want
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004733 * these interrupts to also abort the loop. The approach we take here
4734 * is to have the shell ignore interrupt signals while waiting for a
4735 * foreground process to terminate, and then send itself an interrupt
4736 * signal if the child process was terminated by an interrupt signal.
4737 * Unfortunately, some programs want to do a bit of cleanup and then
4738 * exit on interrupt; unless these processes terminate themselves by
4739 * sending a signal to themselves (instead of calling exit) they will
4740 * confuse this approach.
4741 *
4742 * Called with interrupts off.
4743 */
4744static int
4745waitforjob(struct job *jp)
4746{
4747 int st;
4748
4749 TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004750
4751 INT_OFF;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004752 while (jp->state == JOBRUNNING) {
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004753 /* In non-interactive shells, we _can_ get
4754 * a keyboard signal here and be EINTRed,
4755 * but we just loop back, waiting for command to complete.
4756 *
4757 * man bash:
4758 * "If bash is waiting for a command to complete and receives
4759 * a signal for which a trap has been set, the trap
4760 * will not be executed until the command completes."
4761 *
4762 * Reality is that even if trap is not set, bash
4763 * will not act on the signal until command completes.
4764 * Try this. sleep5intoff.c:
4765 * #include <signal.h>
4766 * #include <unistd.h>
4767 * int main() {
4768 * sigset_t set;
4769 * sigemptyset(&set);
4770 * sigaddset(&set, SIGINT);
4771 * sigaddset(&set, SIGQUIT);
4772 * sigprocmask(SIG_BLOCK, &set, NULL);
4773 * sleep(5);
4774 * return 0;
4775 * }
4776 * $ bash -c './sleep5intoff; echo hi'
4777 * ^C^C^C^C <--- pressing ^C once a second
4778 * $ _
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004779 * $ bash -c './sleep5intoff; echo hi'
4780 * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
4781 * $ _
4782 */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004783 dowait(DOWAIT_BLOCK, jp);
4784 }
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004785 INT_ON;
4786
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004787 st = getstatus(jp);
4788#if JOBS
4789 if (jp->jobctl) {
4790 xtcsetpgrp(ttyfd, rootpid);
4791 /*
4792 * This is truly gross.
4793 * If we're doing job control, then we did a TIOCSPGRP which
4794 * caused us (the shell) to no longer be in the controlling
4795 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
4796 * intuit from the subprocess exit status whether a SIGINT
4797 * occurred, and if so interrupt ourselves. Yuck. - mycroft
4798 */
Denis Vlasenko991a1da2008-02-10 19:02:53 +00004799 if (jp->sigint) /* TODO: do the same with all signals */
4800 raise(SIGINT); /* ... by raise(jp->sig) instead? */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004801 }
4802 if (jp->state == JOBDONE)
4803#endif
4804 freejob(jp);
4805 return st;
4806}
4807
4808/*
4809 * return 1 if there are stopped jobs, otherwise 0
4810 */
4811static int
4812stoppedjobs(void)
4813{
4814 struct job *jp;
4815 int retval;
4816
4817 retval = 0;
4818 if (job_warning)
4819 goto out;
4820 jp = curjob;
4821 if (jp && jp->state == JOBSTOPPED) {
4822 out2str("You have stopped jobs.\n");
4823 job_warning = 2;
4824 retval++;
4825 }
4826 out:
4827 return retval;
4828}
4829
4830
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004831/* ============ redir.c
4832 *
4833 * Code for dealing with input/output redirection.
4834 */
4835
4836#define EMPTY -2 /* marks an unused slot in redirtab */
Denis Vlasenko7d75a962007-11-22 08:16:57 +00004837#define CLOSED -3 /* marks a slot of previously-closed fd */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004838
4839/*
4840 * Open a file in noclobber mode.
4841 * The code was copied from bash.
4842 */
4843static int
4844noclobberopen(const char *fname)
4845{
4846 int r, fd;
4847 struct stat finfo, finfo2;
4848
4849 /*
4850 * If the file exists and is a regular file, return an error
4851 * immediately.
4852 */
4853 r = stat(fname, &finfo);
4854 if (r == 0 && S_ISREG(finfo.st_mode)) {
4855 errno = EEXIST;
4856 return -1;
4857 }
4858
4859 /*
4860 * If the file was not present (r != 0), make sure we open it
4861 * exclusively so that if it is created before we open it, our open
4862 * will fail. Make sure that we do not truncate an existing file.
4863 * Note that we don't turn on O_EXCL unless the stat failed -- if the
4864 * file was not a regular file, we leave O_EXCL off.
4865 */
4866 if (r != 0)
4867 return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
4868 fd = open(fname, O_WRONLY|O_CREAT, 0666);
4869
4870 /* If the open failed, return the file descriptor right away. */
4871 if (fd < 0)
4872 return fd;
4873
4874 /*
4875 * OK, the open succeeded, but the file may have been changed from a
4876 * non-regular file to a regular file between the stat and the open.
4877 * We are assuming that the O_EXCL open handles the case where FILENAME
4878 * did not exist and is symlinked to an existing file between the stat
4879 * and open.
4880 */
4881
4882 /*
4883 * If we can open it and fstat the file descriptor, and neither check
4884 * revealed that it was a regular file, and the file has not been
4885 * replaced, return the file descriptor.
4886 */
4887 if (fstat(fd, &finfo2) == 0 && !S_ISREG(finfo2.st_mode)
4888 && finfo.st_dev == finfo2.st_dev && finfo.st_ino == finfo2.st_ino)
4889 return fd;
4890
4891 /* The file has been replaced. badness. */
4892 close(fd);
4893 errno = EEXIST;
4894 return -1;
4895}
4896
4897/*
4898 * Handle here documents. Normally we fork off a process to write the
4899 * data to a pipe. If the document is short, we can stuff the data in
4900 * the pipe without forking.
4901 */
4902/* openhere needs this forward reference */
4903static void expandhere(union node *arg, int fd);
4904static int
4905openhere(union node *redir)
4906{
4907 int pip[2];
4908 size_t len = 0;
4909
4910 if (pipe(pip) < 0)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00004911 ash_msg_and_raise_error("pipe call failed");
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004912 if (redir->type == NHERE) {
4913 len = strlen(redir->nhere.doc->narg.text);
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00004914 if (len <= PIPE_BUF) {
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004915 full_write(pip[1], redir->nhere.doc->narg.text, len);
4916 goto out;
4917 }
4918 }
4919 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
Denis Vlasenko0b769642008-07-24 07:54:57 +00004920 /* child */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004921 close(pip[0]);
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004922 ignoresig(SIGINT); //signal(SIGINT, SIG_IGN);
4923 ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
4924 ignoresig(SIGHUP); //signal(SIGHUP, SIG_IGN);
4925 ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004926 signal(SIGPIPE, SIG_DFL);
4927 if (redir->type == NHERE)
4928 full_write(pip[1], redir->nhere.doc->narg.text, len);
Denis Vlasenko0b769642008-07-24 07:54:57 +00004929 else /* NXHERE */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004930 expandhere(redir->nhere.doc, pip[1]);
Bernhard Reutner-Fischer636a1f82008-05-19 09:29:47 +00004931 _exit(EXIT_SUCCESS);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004932 }
4933 out:
4934 close(pip[1]);
4935 return pip[0];
4936}
4937
4938static int
4939openredirect(union node *redir)
4940{
4941 char *fname;
4942 int f;
4943
4944 switch (redir->nfile.type) {
4945 case NFROM:
4946 fname = redir->nfile.expfname;
4947 f = open(fname, O_RDONLY);
4948 if (f < 0)
4949 goto eopen;
4950 break;
4951 case NFROMTO:
4952 fname = redir->nfile.expfname;
4953 f = open(fname, O_RDWR|O_CREAT|O_TRUNC, 0666);
4954 if (f < 0)
4955 goto ecreate;
4956 break;
4957 case NTO:
Denis Vlasenko559691a2008-10-05 18:39:31 +00004958#if ENABLE_ASH_BASH_COMPAT
4959 case NTO2:
4960#endif
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004961 /* Take care of noclobber mode. */
4962 if (Cflag) {
4963 fname = redir->nfile.expfname;
4964 f = noclobberopen(fname);
4965 if (f < 0)
4966 goto ecreate;
4967 break;
4968 }
4969 /* FALLTHROUGH */
4970 case NCLOBBER:
4971 fname = redir->nfile.expfname;
4972 f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
4973 if (f < 0)
4974 goto ecreate;
4975 break;
4976 case NAPPEND:
4977 fname = redir->nfile.expfname;
4978 f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
4979 if (f < 0)
4980 goto ecreate;
4981 break;
4982 default:
4983#if DEBUG
4984 abort();
4985#endif
4986 /* Fall through to eliminate warning. */
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00004987/* Our single caller does this itself */
Denis Vlasenko0b769642008-07-24 07:54:57 +00004988// case NTOFD:
4989// case NFROMFD:
4990// f = -1;
4991// break;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004992 case NHERE:
4993 case NXHERE:
4994 f = openhere(redir);
4995 break;
4996 }
4997
4998 return f;
4999 ecreate:
Bernhard Reutner-Fischera53de7f2008-07-21 13:46:54 +00005000 ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005001 eopen:
Bernhard Reutner-Fischera53de7f2008-07-21 13:46:54 +00005002 ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005003}
5004
5005/*
5006 * Copy a file descriptor to be >= to. Returns -1
5007 * if the source file descriptor is closed, EMPTY if there are no unused
5008 * file descriptors left.
5009 */
Denis Vlasenko5a867312008-07-24 19:46:38 +00005010/* 0x800..00: bit to set in "to" to request dup2 instead of fcntl(F_DUPFD).
5011 * old code was doing close(to) prior to copyfd() to achieve the same */
Denis Vlasenko22f74142008-07-24 22:34:43 +00005012enum {
5013 COPYFD_EXACT = (int)~(INT_MAX),
5014 COPYFD_RESTORE = (int)((unsigned)COPYFD_EXACT >> 1),
5015};
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005016static int
5017copyfd(int from, int to)
5018{
5019 int newfd;
5020
Denis Vlasenko5a867312008-07-24 19:46:38 +00005021 if (to & COPYFD_EXACT) {
5022 to &= ~COPYFD_EXACT;
5023 /*if (from != to)*/
5024 newfd = dup2(from, to);
5025 } else {
5026 newfd = fcntl(from, F_DUPFD, to);
5027 }
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005028 if (newfd < 0) {
5029 if (errno == EMFILE)
5030 return EMPTY;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005031 /* Happens when source fd is not open: try "echo >&99" */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005032 ash_msg_and_raise_error("%d: %m", from);
5033 }
5034 return newfd;
5035}
5036
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005037/* Struct def and variable are moved down to the first usage site */
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005038struct two_fd_t {
5039 int orig, copy;
5040};
Denis Vlasenko0b769642008-07-24 07:54:57 +00005041struct redirtab {
5042 struct redirtab *next;
Denis Vlasenko0b769642008-07-24 07:54:57 +00005043 int nullredirs;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005044 int pair_count;
Denys Vlasenko606291b2009-09-23 23:15:43 +02005045 struct two_fd_t two_fd[];
Denis Vlasenko0b769642008-07-24 07:54:57 +00005046};
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005047#define redirlist (G_var.redirlist)
Denis Vlasenko0b769642008-07-24 07:54:57 +00005048
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005049static int need_to_remember(struct redirtab *rp, int fd)
5050{
5051 int i;
5052
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005053 if (!rp) /* remembering was not requested */
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005054 return 0;
5055
5056 for (i = 0; i < rp->pair_count; i++) {
5057 if (rp->two_fd[i].orig == fd) {
5058 /* already remembered */
5059 return 0;
5060 }
5061 }
5062 return 1;
5063}
5064
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005065/* "hidden" fd is a fd used to read scripts, or a copy of such */
5066static int is_hidden_fd(struct redirtab *rp, int fd)
5067{
5068 int i;
Denis Vlasenko34c73c42008-08-16 11:48:02 +00005069 struct parsefile *pf;
5070
5071 if (fd == -1)
5072 return 0;
5073 pf = g_parsefile;
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005074 while (pf) {
5075 if (fd == pf->fd) {
5076 return 1;
5077 }
5078 pf = pf->prev;
5079 }
5080 if (!rp)
5081 return 0;
5082 fd |= COPYFD_RESTORE;
5083 for (i = 0; i < rp->pair_count; i++) {
5084 if (rp->two_fd[i].copy == fd) {
5085 return 1;
5086 }
5087 }
5088 return 0;
5089}
5090
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005091/*
5092 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
5093 * old file descriptors are stashed away so that the redirection can be
5094 * undone by calling popredir. If the REDIR_BACKQ flag is set, then the
5095 * standard output, and the standard error if it becomes a duplicate of
5096 * stdout, is saved in memory.
5097 */
5098/* flags passed to redirect */
5099#define REDIR_PUSH 01 /* save previous values of file descriptors */
5100#define REDIR_SAVEFD2 03 /* set preverrout */
5101static void
5102redirect(union node *redir, int flags)
5103{
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005104 struct redirtab *sv;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005105 int sv_pos;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005106 int i;
5107 int fd;
5108 int newfd;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005109 int copied_fd2 = -1;
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005110
Denis Vlasenko01631112007-12-16 17:20:38 +00005111 g_nullredirs++;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005112 if (!redir) {
5113 return;
5114 }
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005115
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005116 sv = NULL;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005117 sv_pos = 0;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005118 INT_OFF;
5119 if (flags & REDIR_PUSH) {
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005120 union node *tmp = redir;
5121 do {
5122 sv_pos++;
Denis Vlasenko559691a2008-10-05 18:39:31 +00005123#if ENABLE_ASH_BASH_COMPAT
5124 if (redir->nfile.type == NTO2)
5125 sv_pos++;
5126#endif
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005127 tmp = tmp->nfile.next;
5128 } while (tmp);
5129 sv = ckmalloc(sizeof(*sv) + sv_pos * sizeof(sv->two_fd[0]));
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005130 sv->next = redirlist;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005131 sv->pair_count = sv_pos;
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005132 redirlist = sv;
Denis Vlasenko01631112007-12-16 17:20:38 +00005133 sv->nullredirs = g_nullredirs - 1;
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005134 g_nullredirs = 0;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005135 while (sv_pos > 0) {
5136 sv_pos--;
5137 sv->two_fd[sv_pos].orig = sv->two_fd[sv_pos].copy = EMPTY;
5138 }
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005139 }
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005140
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005141 do {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00005142 fd = redir->nfile.fd;
Denis Vlasenko0b769642008-07-24 07:54:57 +00005143 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005144 int right_fd = redir->ndup.dupfd;
5145 /* redirect from/to same file descriptor? */
5146 if (right_fd == fd)
5147 continue;
5148 /* echo >&10 and 10 is a fd opened to the sh script? */
5149 if (is_hidden_fd(sv, right_fd)) {
5150 errno = EBADF; /* as if it is closed */
5151 ash_msg_and_raise_error("%d: %m", right_fd);
5152 }
Denis Vlasenko0b769642008-07-24 07:54:57 +00005153 newfd = -1;
5154 } else {
5155 newfd = openredirect(redir); /* always >= 0 */
5156 if (fd == newfd) {
5157 /* Descriptor wasn't open before redirect.
5158 * Mark it for close in the future */
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005159 if (need_to_remember(sv, fd)) {
Denis Vlasenko5a867312008-07-24 19:46:38 +00005160 goto remember_to_close;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005161 }
Denis Vlasenko0b769642008-07-24 07:54:57 +00005162 continue;
5163 }
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005164 }
Denis Vlasenko559691a2008-10-05 18:39:31 +00005165#if ENABLE_ASH_BASH_COMPAT
5166 redirect_more:
5167#endif
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005168 if (need_to_remember(sv, fd)) {
Denis Vlasenko0b769642008-07-24 07:54:57 +00005169 /* Copy old descriptor */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005170 i = fcntl(fd, F_DUPFD, 10);
Denis Vlasenko5a867312008-07-24 19:46:38 +00005171/* You'd expect copy to be CLOEXECed. Currently these extra "saved" fds
5172 * are closed in popredir() in the child, preventing them from leaking
5173 * into child. (popredir() also cleans up the mess in case of failures)
5174 */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005175 if (i == -1) {
5176 i = errno;
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005177 if (i != EBADF) {
5178 /* Strange error (e.g. "too many files" EMFILE?) */
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005179 if (newfd >= 0)
5180 close(newfd);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005181 errno = i;
5182 ash_msg_and_raise_error("%d: %m", fd);
5183 /* NOTREACHED */
5184 }
Denis Vlasenko5a867312008-07-24 19:46:38 +00005185 /* EBADF: it is not open - good, remember to close it */
5186 remember_to_close:
5187 i = CLOSED;
Denis Vlasenko22f74142008-07-24 22:34:43 +00005188 } else { /* fd is open, save its copy */
5189 /* "exec fd>&-" should not close fds
5190 * which point to script file(s).
5191 * Force them to be restored afterwards */
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005192 if (is_hidden_fd(sv, fd))
5193 i |= COPYFD_RESTORE;
Denis Vlasenko22f74142008-07-24 22:34:43 +00005194 }
Denis Vlasenko5a867312008-07-24 19:46:38 +00005195 if (fd == 2)
5196 copied_fd2 = i;
5197 sv->two_fd[sv_pos].orig = fd;
5198 sv->two_fd[sv_pos].copy = i;
5199 sv_pos++;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005200 }
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005201 if (newfd < 0) {
5202 /* NTOFD/NFROMFD: copy redir->ndup.dupfd to fd */
Denis Vlasenko22f74142008-07-24 22:34:43 +00005203 if (redir->ndup.dupfd < 0) { /* "fd>&-" */
Denis Vlasenkob9e70dd2009-03-20 01:24:08 +00005204 /* Don't want to trigger debugging */
5205 if (fd != -1)
5206 close(fd);
Denis Vlasenko5a867312008-07-24 19:46:38 +00005207 } else {
5208 copyfd(redir->ndup.dupfd, fd | COPYFD_EXACT);
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005209 }
Denis Vlasenko5a867312008-07-24 19:46:38 +00005210 } else if (fd != newfd) { /* move newfd to fd */
5211 copyfd(newfd, fd | COPYFD_EXACT);
Denis Vlasenko559691a2008-10-05 18:39:31 +00005212#if ENABLE_ASH_BASH_COMPAT
5213 if (!(redir->nfile.type == NTO2 && fd == 2))
5214#endif
5215 close(newfd);
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005216 }
Denis Vlasenko559691a2008-10-05 18:39:31 +00005217#if ENABLE_ASH_BASH_COMPAT
5218 if (redir->nfile.type == NTO2 && fd == 1) {
5219 /* We already redirected it to fd 1, now copy it to 2 */
5220 newfd = 1;
5221 fd = 2;
5222 goto redirect_more;
5223 }
5224#endif
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00005225 } while ((redir = redir->nfile.next) != NULL);
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005226
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005227 INT_ON;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005228 if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
5229 preverrout_fd = copied_fd2;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005230}
5231
5232/*
5233 * Undo the effects of the last redirection.
5234 */
5235static void
Denis Vlasenko34c73c42008-08-16 11:48:02 +00005236popredir(int drop, int restore)
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005237{
5238 struct redirtab *rp;
5239 int i;
5240
Denis Vlasenko01631112007-12-16 17:20:38 +00005241 if (--g_nullredirs >= 0)
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005242 return;
5243 INT_OFF;
5244 rp = redirlist;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005245 for (i = 0; i < rp->pair_count; i++) {
5246 int fd = rp->two_fd[i].orig;
Denis Vlasenko22f74142008-07-24 22:34:43 +00005247 int copy = rp->two_fd[i].copy;
5248 if (copy == CLOSED) {
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005249 if (!drop)
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005250 close(fd);
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005251 continue;
5252 }
Denis Vlasenko22f74142008-07-24 22:34:43 +00005253 if (copy != EMPTY) {
Denis Vlasenko34c73c42008-08-16 11:48:02 +00005254 if (!drop || (restore && (copy & COPYFD_RESTORE))) {
Denis Vlasenko22f74142008-07-24 22:34:43 +00005255 copy &= ~COPYFD_RESTORE;
Denis Vlasenko5a867312008-07-24 19:46:38 +00005256 /*close(fd);*/
Denis Vlasenko22f74142008-07-24 22:34:43 +00005257 copyfd(copy, fd | COPYFD_EXACT);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005258 }
Denis Vlasenkob9e70dd2009-03-20 01:24:08 +00005259 close(copy & ~COPYFD_RESTORE);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005260 }
5261 }
5262 redirlist = rp->next;
Denis Vlasenko01631112007-12-16 17:20:38 +00005263 g_nullredirs = rp->nullredirs;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005264 free(rp);
5265 INT_ON;
5266}
5267
5268/*
5269 * Undo all redirections. Called on error or interrupt.
5270 */
5271
5272/*
5273 * Discard all saved file descriptors.
5274 */
5275static void
5276clearredir(int drop)
5277{
5278 for (;;) {
Denis Vlasenko01631112007-12-16 17:20:38 +00005279 g_nullredirs = 0;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005280 if (!redirlist)
5281 break;
Denis Vlasenko34c73c42008-08-16 11:48:02 +00005282 popredir(drop, /*restore:*/ 0);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005283 }
5284}
5285
5286static int
5287redirectsafe(union node *redir, int flags)
5288{
5289 int err;
5290 volatile int saveint;
5291 struct jmploc *volatile savehandler = exception_handler;
5292 struct jmploc jmploc;
5293
5294 SAVE_INT(saveint);
Denis Vlasenko5a867312008-07-24 19:46:38 +00005295 /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
5296 err = setjmp(jmploc.loc); // huh?? was = setjmp(jmploc.loc) * 2;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005297 if (!err) {
5298 exception_handler = &jmploc;
5299 redirect(redir, flags);
5300 }
5301 exception_handler = savehandler;
Denis Vlasenko7f88e342009-03-19 03:36:18 +00005302 if (err && exception_type != EXERROR)
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005303 longjmp(exception_handler->loc, 1);
5304 RESTORE_INT(saveint);
5305 return err;
5306}
5307
5308
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005309/* ============ Routines to expand arguments to commands
5310 *
5311 * We have to deal with backquotes, shell variables, and file metacharacters.
5312 */
5313
Mike Frysinger98c52642009-04-02 10:02:37 +00005314#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00005315static arith_t
5316ash_arith(const char *s)
5317{
5318 arith_eval_hooks_t math_hooks;
5319 arith_t result;
5320 int errcode = 0;
5321
5322 math_hooks.lookupvar = lookupvar;
5323 math_hooks.setvar = setvar;
5324 math_hooks.endofname = endofname;
5325
5326 INT_OFF;
5327 result = arith(s, &errcode, &math_hooks);
5328 if (errcode < 0) {
5329 if (errcode == -3)
5330 ash_msg_and_raise_error("exponent less than 0");
5331 if (errcode == -2)
5332 ash_msg_and_raise_error("divide by zero");
5333 if (errcode == -5)
5334 ash_msg_and_raise_error("expression recursion loop detected");
5335 raise_error_syntax(s);
5336 }
5337 INT_ON;
5338
5339 return result;
5340}
Denis Vlasenko448d30e2008-06-27 00:24:11 +00005341#endif
5342
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005343/*
5344 * expandarg flags
5345 */
5346#define EXP_FULL 0x1 /* perform word splitting & file globbing */
5347#define EXP_TILDE 0x2 /* do normal tilde expansion */
5348#define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
5349#define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
5350#define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
5351#define EXP_RECORD 0x20 /* need to record arguments for ifs breakup */
5352#define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
5353#define EXP_WORD 0x80 /* expand word in parameter expansion */
5354#define EXP_QWORD 0x100 /* expand word in quoted parameter expansion */
5355/*
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005356 * rmescape() flags
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005357 */
5358#define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
5359#define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
5360#define RMESCAPE_QUOTED 0x4 /* Remove CTLESC unless in quotes */
5361#define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
5362#define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
5363
5364/*
5365 * Structure specifying which parts of the string should be searched
5366 * for IFS characters.
5367 */
5368struct ifsregion {
5369 struct ifsregion *next; /* next region in list */
5370 int begoff; /* offset of start of region */
5371 int endoff; /* offset of end of region */
5372 int nulonly; /* search for nul bytes only */
5373};
5374
5375struct arglist {
5376 struct strlist *list;
5377 struct strlist **lastp;
5378};
5379
5380/* output of current string */
5381static char *expdest;
5382/* list of back quote expressions */
5383static struct nodelist *argbackq;
5384/* first struct in list of ifs regions */
5385static struct ifsregion ifsfirst;
5386/* last struct in list */
5387static struct ifsregion *ifslastp;
5388/* holds expanded arg list */
5389static struct arglist exparg;
5390
5391/*
5392 * Our own itoa().
5393 */
5394static int
5395cvtnum(arith_t num)
5396{
5397 int len;
5398
5399 expdest = makestrspace(32, expdest);
Mike Frysinger98c52642009-04-02 10:02:37 +00005400 len = fmtstr(expdest, 32, arith_t_fmt, num);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005401 STADJUST(len, expdest);
5402 return len;
5403}
5404
5405static size_t
5406esclen(const char *start, const char *p)
5407{
5408 size_t esc = 0;
5409
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005410 while (p > start && (unsigned char)*--p == CTLESC) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005411 esc++;
5412 }
5413 return esc;
5414}
5415
5416/*
5417 * Remove any CTLESC characters from a string.
5418 */
5419static char *
Denys Vlasenkob6c84342009-08-29 20:23:20 +02005420rmescapes(char *str, int flag)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005421{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00005422 static const char qchars[] ALIGN1 = { CTLESC, CTLQUOTEMARK, '\0' };
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00005423
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005424 char *p, *q, *r;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005425 unsigned inquotes;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005426 unsigned protect_against_glob;
5427 unsigned globbing;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005428
5429 p = strpbrk(str, qchars);
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005430 if (!p)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005431 return str;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005432
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005433 q = p;
5434 r = str;
5435 if (flag & RMESCAPE_ALLOC) {
5436 size_t len = p - str;
5437 size_t fulllen = len + strlen(p) + 1;
5438
5439 if (flag & RMESCAPE_GROW) {
5440 r = makestrspace(fulllen, expdest);
5441 } else if (flag & RMESCAPE_HEAP) {
5442 r = ckmalloc(fulllen);
5443 } else {
5444 r = stalloc(fulllen);
5445 }
5446 q = r;
5447 if (len > 0) {
Denis Vlasenko29eb3592008-05-18 14:06:08 +00005448 q = (char *)memcpy(q, str, len) + len;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005449 }
5450 }
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005451
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005452 inquotes = (flag & RMESCAPE_QUOTED) ^ RMESCAPE_QUOTED;
5453 globbing = flag & RMESCAPE_GLOB;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005454 protect_against_glob = globbing;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005455 while (*p) {
5456 if (*p == CTLQUOTEMARK) {
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005457// TODO: if no RMESCAPE_QUOTED in flags, inquotes never becomes 0
5458// (alternates between RMESCAPE_QUOTED and ~RMESCAPE_QUOTED). Is it ok?
5459// Note: both inquotes and protect_against_glob only affect whether
5460// CTLESC,<ch> gets converted to <ch> or to \<ch>
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005461 inquotes = ~inquotes;
5462 p++;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005463 protect_against_glob = globbing;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005464 continue;
5465 }
5466 if (*p == '\\') {
5467 /* naked back slash */
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005468 protect_against_glob = 0;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005469 goto copy;
5470 }
5471 if (*p == CTLESC) {
5472 p++;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005473 if (protect_against_glob && inquotes && *p != '/') {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005474 *q++ = '\\';
5475 }
5476 }
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005477 protect_against_glob = globbing;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005478 copy:
5479 *q++ = *p++;
5480 }
5481 *q = '\0';
5482 if (flag & RMESCAPE_GROW) {
5483 expdest = r;
5484 STADJUST(q - r + 1, expdest);
5485 }
5486 return r;
5487}
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005488#define pmatch(a, b) !fnmatch((a), (b), 0)
5489
5490/*
5491 * Prepare a pattern for a expmeta (internal glob(3)) call.
5492 *
5493 * Returns an stalloced string.
5494 */
5495static char *
5496preglob(const char *pattern, int quoted, int flag)
5497{
5498 flag |= RMESCAPE_GLOB;
5499 if (quoted) {
5500 flag |= RMESCAPE_QUOTED;
5501 }
Denys Vlasenkob6c84342009-08-29 20:23:20 +02005502 return rmescapes((char *)pattern, flag);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005503}
5504
5505/*
5506 * Put a string on the stack.
5507 */
5508static void
5509memtodest(const char *p, size_t len, int syntax, int quotes)
5510{
5511 char *q = expdest;
5512
Denys Vlasenkob6c84342009-08-29 20:23:20 +02005513 q = makestrspace(quotes ? len * 2 : len, q);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005514
5515 while (len--) {
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00005516 int c = signed_char2int(*p++);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005517 if (!c)
5518 continue;
Denys Vlasenkob6c84342009-08-29 20:23:20 +02005519 if (quotes) {
5520 int n = SIT(c, syntax);
5521 if (n == CCTL || n == CBACK)
5522 USTPUTC(CTLESC, q);
5523 }
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005524 USTPUTC(c, q);
5525 }
5526
5527 expdest = q;
5528}
5529
5530static void
5531strtodest(const char *p, int syntax, int quotes)
5532{
5533 memtodest(p, strlen(p), syntax, quotes);
5534}
5535
5536/*
5537 * Record the fact that we have to scan this region of the
5538 * string for IFS characters.
5539 */
5540static void
5541recordregion(int start, int end, int nulonly)
5542{
5543 struct ifsregion *ifsp;
5544
5545 if (ifslastp == NULL) {
5546 ifsp = &ifsfirst;
5547 } else {
5548 INT_OFF;
Denis Vlasenko597906c2008-02-20 16:38:54 +00005549 ifsp = ckzalloc(sizeof(*ifsp));
5550 /*ifsp->next = NULL; - ckzalloc did it */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005551 ifslastp->next = ifsp;
5552 INT_ON;
5553 }
5554 ifslastp = ifsp;
5555 ifslastp->begoff = start;
5556 ifslastp->endoff = end;
5557 ifslastp->nulonly = nulonly;
5558}
5559
5560static void
5561removerecordregions(int endoff)
5562{
5563 if (ifslastp == NULL)
5564 return;
5565
5566 if (ifsfirst.endoff > endoff) {
5567 while (ifsfirst.next != NULL) {
5568 struct ifsregion *ifsp;
5569 INT_OFF;
5570 ifsp = ifsfirst.next->next;
5571 free(ifsfirst.next);
5572 ifsfirst.next = ifsp;
5573 INT_ON;
5574 }
5575 if (ifsfirst.begoff > endoff)
5576 ifslastp = NULL;
5577 else {
5578 ifslastp = &ifsfirst;
5579 ifsfirst.endoff = endoff;
5580 }
5581 return;
5582 }
5583
5584 ifslastp = &ifsfirst;
5585 while (ifslastp->next && ifslastp->next->begoff < endoff)
5586 ifslastp=ifslastp->next;
5587 while (ifslastp->next != NULL) {
5588 struct ifsregion *ifsp;
5589 INT_OFF;
5590 ifsp = ifslastp->next->next;
5591 free(ifslastp->next);
5592 ifslastp->next = ifsp;
5593 INT_ON;
5594 }
5595 if (ifslastp->endoff > endoff)
5596 ifslastp->endoff = endoff;
5597}
5598
5599static char *
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005600exptilde(char *startp, char *p, int flags)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005601{
5602 char c;
5603 char *name;
5604 struct passwd *pw;
5605 const char *home;
Denys Vlasenko1166d7b2009-09-16 16:20:31 +02005606 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005607 int startloc;
5608
5609 name = p + 1;
5610
5611 while ((c = *++p) != '\0') {
5612 switch (c) {
5613 case CTLESC:
5614 return startp;
5615 case CTLQUOTEMARK:
5616 return startp;
5617 case ':':
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005618 if (flags & EXP_VARTILDE)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005619 goto done;
5620 break;
5621 case '/':
5622 case CTLENDVAR:
5623 goto done;
5624 }
5625 }
5626 done:
5627 *p = '\0';
5628 if (*name == '\0') {
5629 home = lookupvar(homestr);
5630 } else {
5631 pw = getpwnam(name);
5632 if (pw == NULL)
5633 goto lose;
5634 home = pw->pw_dir;
5635 }
5636 if (!home || !*home)
5637 goto lose;
5638 *p = c;
5639 startloc = expdest - (char *)stackblock();
5640 strtodest(home, SQSYNTAX, quotes);
5641 recordregion(startloc, expdest - (char *)stackblock(), 0);
5642 return p;
5643 lose:
5644 *p = c;
5645 return startp;
5646}
5647
5648/*
5649 * Execute a command inside back quotes. If it's a builtin command, we
5650 * want to save its output in a block obtained from malloc. Otherwise
5651 * we fork off a subprocess and get the output of the command via a pipe.
5652 * Should be called with interrupts off.
5653 */
5654struct backcmd { /* result of evalbackcmd */
5655 int fd; /* file descriptor to read from */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005656 int nleft; /* number of chars in buffer */
Denis Vlasenkob07a4962008-06-22 13:16:23 +00005657 char *buf; /* buffer */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005658 struct job *jp; /* job structure for command */
5659};
5660
5661/* These forward decls are needed to use "eval" code for backticks handling: */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00005662static uint8_t back_exitstatus; /* exit status of backquoted command */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005663#define EV_EXIT 01 /* exit after evaluating tree */
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02005664static void evaltree(union node *, int);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005665
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02005666static void FAST_FUNC
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005667evalbackcmd(union node *n, struct backcmd *result)
5668{
5669 int saveherefd;
5670
5671 result->fd = -1;
5672 result->buf = NULL;
5673 result->nleft = 0;
5674 result->jp = NULL;
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00005675 if (n == NULL)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005676 goto out;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005677
5678 saveherefd = herefd;
5679 herefd = -1;
5680
5681 {
5682 int pip[2];
5683 struct job *jp;
5684
5685 if (pipe(pip) < 0)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00005686 ash_msg_and_raise_error("pipe call failed");
Denis Vlasenko68404f12008-03-17 09:00:54 +00005687 jp = makejob(/*n,*/ 1);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005688 if (forkshell(jp, n, FORK_NOJOB) == 0) {
5689 FORCE_INT_ON;
5690 close(pip[0]);
5691 if (pip[1] != 1) {
Denis Vlasenko5a867312008-07-24 19:46:38 +00005692 /*close(1);*/
5693 copyfd(pip[1], 1 | COPYFD_EXACT);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005694 close(pip[1]);
5695 }
5696 eflag = 0;
5697 evaltree(n, EV_EXIT); /* actually evaltreenr... */
5698 /* NOTREACHED */
5699 }
5700 close(pip[1]);
5701 result->fd = pip[0];
5702 result->jp = jp;
5703 }
5704 herefd = saveherefd;
5705 out:
5706 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
5707 result->fd, result->buf, result->nleft, result->jp));
5708}
5709
5710/*
5711 * Expand stuff in backwards quotes.
5712 */
5713static void
5714expbackq(union node *cmd, int quoted, int quotes)
5715{
5716 struct backcmd in;
5717 int i;
5718 char buf[128];
5719 char *p;
5720 char *dest;
5721 int startloc;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00005722 int syntax = quoted ? DQSYNTAX : BASESYNTAX;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005723 struct stackmark smark;
5724
5725 INT_OFF;
5726 setstackmark(&smark);
5727 dest = expdest;
5728 startloc = dest - (char *)stackblock();
5729 grabstackstr(dest);
5730 evalbackcmd(cmd, &in);
5731 popstackmark(&smark);
5732
5733 p = in.buf;
5734 i = in.nleft;
5735 if (i == 0)
5736 goto read;
5737 for (;;) {
5738 memtodest(p, i, syntax, quotes);
5739 read:
5740 if (in.fd < 0)
5741 break;
Denis Vlasenkoe376d452008-02-20 22:23:24 +00005742 i = nonblock_safe_read(in.fd, buf, sizeof(buf));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005743 TRACE(("expbackq: read returns %d\n", i));
5744 if (i <= 0)
5745 break;
5746 p = buf;
5747 }
5748
Denis Vlasenko60818682007-09-28 22:07:23 +00005749 free(in.buf);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005750 if (in.fd >= 0) {
5751 close(in.fd);
5752 back_exitstatus = waitforjob(in.jp);
5753 }
5754 INT_ON;
5755
5756 /* Eat all trailing newlines */
5757 dest = expdest;
5758 for (; dest > (char *)stackblock() && dest[-1] == '\n';)
5759 STUNPUTC(dest);
5760 expdest = dest;
5761
5762 if (quoted == 0)
5763 recordregion(startloc, dest - (char *)stackblock(), 0);
5764 TRACE(("evalbackq: size=%d: \"%.*s\"\n",
5765 (dest - (char *)stackblock()) - startloc,
5766 (dest - (char *)stackblock()) - startloc,
5767 stackblock() + startloc));
5768}
5769
Mike Frysinger98c52642009-04-02 10:02:37 +00005770#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005771/*
5772 * Expand arithmetic expression. Backup to start of expression,
5773 * evaluate, place result in (backed up) result, adjust string position.
5774 */
5775static void
5776expari(int quotes)
5777{
5778 char *p, *start;
5779 int begoff;
5780 int flag;
5781 int len;
5782
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00005783 /* ifsfree(); */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005784
5785 /*
5786 * This routine is slightly over-complicated for
5787 * efficiency. Next we scan backwards looking for the
5788 * start of arithmetic.
5789 */
5790 start = stackblock();
5791 p = expdest - 1;
5792 *p = '\0';
5793 p--;
5794 do {
5795 int esc;
5796
5797 while (*p != CTLARI) {
5798 p--;
5799#if DEBUG
5800 if (p < start) {
5801 ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
5802 }
5803#endif
5804 }
5805
5806 esc = esclen(start, p);
5807 if (!(esc % 2)) {
5808 break;
5809 }
5810
5811 p -= esc + 1;
5812 } while (1);
5813
5814 begoff = p - start;
5815
5816 removerecordregions(begoff);
5817
5818 flag = p[1];
5819
5820 expdest = p;
5821
5822 if (quotes)
Denys Vlasenkob6c84342009-08-29 20:23:20 +02005823 rmescapes(p + 2, 0);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005824
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00005825 len = cvtnum(ash_arith(p + 2));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005826
5827 if (flag != '"')
5828 recordregion(begoff, begoff + len, 0);
5829}
5830#endif
5831
5832/* argstr needs it */
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005833static char *evalvar(char *p, int flags, struct strlist *var_str_list);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005834
5835/*
5836 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
5837 * characters to allow for further processing. Otherwise treat
5838 * $@ like $* since no splitting will be performed.
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00005839 *
5840 * var_str_list (can be NULL) is a list of "VAR=val" strings which take precedence
5841 * over shell varables. Needed for "A=a B=$A; echo $B" case - we use it
5842 * for correct expansion of "B=$A" word.
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005843 */
5844static void
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005845argstr(char *p, int flags, struct strlist *var_str_list)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005846{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00005847 static const char spclchars[] ALIGN1 = {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005848 '=',
5849 ':',
5850 CTLQUOTEMARK,
5851 CTLENDVAR,
5852 CTLESC,
5853 CTLVAR,
5854 CTLBACKQ,
5855 CTLBACKQ | CTLQUOTE,
Mike Frysinger98c52642009-04-02 10:02:37 +00005856#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005857 CTLENDARI,
5858#endif
5859 0
5860 };
5861 const char *reject = spclchars;
5862 int c;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005863 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR); /* do CTLESC */
5864 int breakall = flags & EXP_WORD;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005865 int inquotes;
5866 size_t length;
5867 int startloc;
5868
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005869 if (!(flags & EXP_VARTILDE)) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005870 reject += 2;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005871 } else if (flags & EXP_VARTILDE2) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005872 reject++;
5873 }
5874 inquotes = 0;
5875 length = 0;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005876 if (flags & EXP_TILDE) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005877 char *q;
5878
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005879 flags &= ~EXP_TILDE;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005880 tilde:
5881 q = p;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005882 if (*q == CTLESC && (flags & EXP_QWORD))
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005883 q++;
5884 if (*q == '~')
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005885 p = exptilde(p, q, flags);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005886 }
5887 start:
5888 startloc = expdest - (char *)stackblock();
5889 for (;;) {
5890 length += strcspn(p + length, reject);
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005891 c = (unsigned char) p[length];
5892 if (c) {
5893 if (!(c & 0x80)
Mike Frysinger98c52642009-04-02 10:02:37 +00005894#if ENABLE_SH_MATH_SUPPORT
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005895 || c == CTLENDARI
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005896#endif
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005897 ) {
5898 /* c == '=' || c == ':' || c == CTLENDARI */
5899 length++;
5900 }
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005901 }
5902 if (length > 0) {
5903 int newloc;
5904 expdest = stack_nputstr(p, length, expdest);
5905 newloc = expdest - (char *)stackblock();
5906 if (breakall && !inquotes && newloc > startloc) {
5907 recordregion(startloc, newloc, 0);
5908 }
5909 startloc = newloc;
5910 }
5911 p += length + 1;
5912 length = 0;
5913
5914 switch (c) {
5915 case '\0':
5916 goto breakloop;
5917 case '=':
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005918 if (flags & EXP_VARTILDE2) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005919 p--;
5920 continue;
5921 }
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005922 flags |= EXP_VARTILDE2;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005923 reject++;
5924 /* fall through */
5925 case ':':
5926 /*
5927 * sort of a hack - expand tildes in variable
5928 * assignments (after the first '=' and after ':'s).
5929 */
5930 if (*--p == '~') {
5931 goto tilde;
5932 }
5933 continue;
5934 }
5935
5936 switch (c) {
5937 case CTLENDVAR: /* ??? */
5938 goto breakloop;
5939 case CTLQUOTEMARK:
5940 /* "$@" syntax adherence hack */
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005941 if (!inquotes
5942 && memcmp(p, dolatstr, 4) == 0
5943 && ( p[4] == CTLQUOTEMARK
5944 || (p[4] == CTLENDVAR && p[5] == CTLQUOTEMARK)
5945 )
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005946 ) {
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005947 p = evalvar(p + 1, flags, /* var_str_list: */ NULL) + 1;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005948 goto start;
5949 }
5950 inquotes = !inquotes;
5951 addquote:
5952 if (quotes) {
5953 p--;
5954 length++;
5955 startloc++;
5956 }
5957 break;
5958 case CTLESC:
5959 startloc++;
5960 length++;
5961 goto addquote;
5962 case CTLVAR:
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005963 p = evalvar(p, flags, var_str_list);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005964 goto start;
5965 case CTLBACKQ:
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005966 c = '\0';
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005967 case CTLBACKQ|CTLQUOTE:
5968 expbackq(argbackq->n, c, quotes);
5969 argbackq = argbackq->next;
5970 goto start;
Mike Frysinger98c52642009-04-02 10:02:37 +00005971#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005972 case CTLENDARI:
5973 p--;
5974 expari(quotes);
5975 goto start;
5976#endif
5977 }
5978 }
5979 breakloop:
5980 ;
5981}
5982
5983static char *
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00005984scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM, char *str, int quotes,
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005985 int zero)
5986{
Denis Vlasenkoc7131c32008-04-14 01:59:53 +00005987// This commented out code was added by James Simmons <jsimmons@infradead.org>
5988// as part of a larger change when he added support for ${var/a/b}.
5989// However, it broke # and % operators:
5990//
5991//var=ababcdcd
5992// ok bad
5993//echo ${var#ab} abcdcd abcdcd
5994//echo ${var##ab} abcdcd abcdcd
5995//echo ${var#a*b} abcdcd ababcdcd (!)
5996//echo ${var##a*b} cdcd cdcd
5997//echo ${var#?} babcdcd ababcdcd (!)
5998//echo ${var##?} babcdcd babcdcd
5999//echo ${var#*} ababcdcd babcdcd (!)
6000//echo ${var##*}
6001//echo ${var%cd} ababcd ababcd
6002//echo ${var%%cd} ababcd abab (!)
6003//echo ${var%c*d} ababcd ababcd
6004//echo ${var%%c*d} abab ababcdcd (!)
6005//echo ${var%?} ababcdc ababcdc
6006//echo ${var%%?} ababcdc ababcdcd (!)
6007//echo ${var%*} ababcdcd ababcdcd
6008//echo ${var%%*}
6009//
6010// Commenting it back out helped. Remove it completely if it really
6011// is not needed.
6012
6013 char *loc, *loc2; //, *full;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006014 char c;
6015
6016 loc = startp;
6017 loc2 = rmesc;
6018 do {
Denis Vlasenkoc7131c32008-04-14 01:59:53 +00006019 int match; // = strlen(str);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006020 const char *s = loc2;
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006021
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006022 c = *loc2;
6023 if (zero) {
6024 *loc2 = '\0';
6025 s = rmesc;
6026 }
Denis Vlasenkoc7131c32008-04-14 01:59:53 +00006027 match = pmatch(str, s); // this line was deleted
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006028
Denis Vlasenkoc7131c32008-04-14 01:59:53 +00006029// // chop off end if its '*'
6030// full = strrchr(str, '*');
6031// if (full && full != str)
6032// match--;
6033//
6034// // If str starts with '*' replace with s.
6035// if ((*str == '*') && strlen(s) >= match) {
6036// full = xstrdup(s);
6037// strncpy(full+strlen(s)-match+1, str+1, match-1);
6038// } else
6039// full = xstrndup(str, match);
6040// match = strncmp(s, full, strlen(full));
6041// free(full);
6042//
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006043 *loc2 = c;
Denis Vlasenkoc7131c32008-04-14 01:59:53 +00006044 if (match) // if (!match)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006045 return loc;
6046 if (quotes && *loc == CTLESC)
6047 loc++;
6048 loc++;
6049 loc2++;
6050 } while (c);
6051 return 0;
6052}
6053
6054static char *
6055scanright(char *startp, char *rmesc, char *rmescend, char *str, int quotes,
6056 int zero)
6057{
6058 int esc = 0;
6059 char *loc;
6060 char *loc2;
6061
6062 for (loc = str - 1, loc2 = rmescend; loc >= startp; loc2--) {
6063 int match;
6064 char c = *loc2;
6065 const char *s = loc2;
6066 if (zero) {
6067 *loc2 = '\0';
6068 s = rmesc;
6069 }
6070 match = pmatch(str, s);
6071 *loc2 = c;
6072 if (match)
6073 return loc;
6074 loc--;
6075 if (quotes) {
6076 if (--esc < 0) {
6077 esc = esclen(startp, loc);
6078 }
6079 if (esc % 2) {
6080 esc--;
6081 loc--;
6082 }
6083 }
6084 }
6085 return 0;
6086}
6087
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00006088static void varunset(const char *, const char *, const char *, int) NORETURN;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006089static void
6090varunset(const char *end, const char *var, const char *umsg, int varflags)
6091{
6092 const char *msg;
6093 const char *tail;
6094
6095 tail = nullstr;
6096 msg = "parameter not set";
6097 if (umsg) {
6098 if (*end == CTLENDVAR) {
6099 if (varflags & VSNUL)
6100 tail = " or null";
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00006101 } else {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006102 msg = umsg;
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00006103 }
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006104 }
6105 ash_msg_and_raise_error("%.*s: %s%s", end - var - 1, var, msg, tail);
6106}
6107
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006108#if ENABLE_ASH_BASH_COMPAT
6109static char *
6110parse_sub_pattern(char *arg, int inquotes)
6111{
6112 char *idx, *repl = NULL;
6113 unsigned char c;
6114
Denis Vlasenko2659c632008-06-14 06:04:59 +00006115 idx = arg;
6116 while (1) {
6117 c = *arg;
6118 if (!c)
6119 break;
6120 if (c == '/') {
6121 /* Only the first '/' seen is our separator */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006122 if (!repl) {
Denis Vlasenko2659c632008-06-14 06:04:59 +00006123 repl = idx + 1;
6124 c = '\0';
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006125 }
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006126 }
Denis Vlasenko2659c632008-06-14 06:04:59 +00006127 *idx++ = c;
6128 if (!inquotes && c == '\\' && arg[1] == '\\')
6129 arg++; /* skip both \\, not just first one */
6130 arg++;
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006131 }
Denis Vlasenko29038c02008-06-14 06:14:02 +00006132 *idx = c; /* NUL */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006133
6134 return repl;
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006135}
6136#endif /* ENABLE_ASH_BASH_COMPAT */
6137
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006138static const char *
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006139subevalvar(char *p, char *str, int strloc, int subtype,
6140 int startloc, int varflags, int quotes, struct strlist *var_str_list)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006141{
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006142 struct nodelist *saveargbackq = argbackq;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006143 char *startp;
6144 char *loc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006145 char *rmesc, *rmescend;
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00006146 IF_ASH_BASH_COMPAT(char *repl = NULL;)
6147 IF_ASH_BASH_COMPAT(char null = '\0';)
6148 IF_ASH_BASH_COMPAT(int pos, len, orig_len;)
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006149 int saveherefd = herefd;
6150 int amount, workloc, resetloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006151 int zero;
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006152 char *(*scan)(char*, char*, char*, char*, int, int);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006153
6154 herefd = -1;
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006155 argstr(p, (subtype != VSASSIGN && subtype != VSQUESTION) ? EXP_CASE : 0,
6156 var_str_list);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006157 STPUTC('\0', expdest);
6158 herefd = saveherefd;
6159 argbackq = saveargbackq;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00006160 startp = (char *)stackblock() + startloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006161
6162 switch (subtype) {
6163 case VSASSIGN:
6164 setvar(str, startp, 0);
6165 amount = startp - expdest;
6166 STADJUST(amount, expdest);
6167 return startp;
6168
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006169#if ENABLE_ASH_BASH_COMPAT
6170 case VSSUBSTR:
6171 loc = str = stackblock() + strloc;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006172 /* Read POS in ${var:POS:LEN} */
6173 pos = atoi(loc); /* number(loc) errors out on "1:4" */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006174 len = str - startp - 1;
6175
6176 /* *loc != '\0', guaranteed by parser */
6177 if (quotes) {
6178 char *ptr;
6179
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006180 /* Adjust the length by the number of escapes */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006181 for (ptr = startp; ptr < (str - 1); ptr++) {
Denis Vlasenkod6855d12008-09-27 14:03:25 +00006182 if (*ptr == CTLESC) {
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006183 len--;
6184 ptr++;
6185 }
6186 }
6187 }
6188 orig_len = len;
6189
6190 if (*loc++ == ':') {
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006191 /* ${var::LEN} */
6192 len = number(loc);
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006193 } else {
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006194 /* Skip POS in ${var:POS:LEN} */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006195 len = orig_len;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006196 while (*loc && *loc != ':') {
6197 /* TODO?
6198 * bash complains on: var=qwe; echo ${var:1a:123}
6199 if (!isdigit(*loc))
6200 ash_msg_and_raise_error(msg_illnum, str);
6201 */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006202 loc++;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006203 }
6204 if (*loc++ == ':') {
6205 len = number(loc);
6206 }
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006207 }
6208 if (pos >= orig_len) {
6209 pos = 0;
6210 len = 0;
6211 }
6212 if (len > (orig_len - pos))
6213 len = orig_len - pos;
6214
6215 for (str = startp; pos; str++, pos--) {
6216 if (quotes && *str == CTLESC)
6217 str++;
6218 }
6219 for (loc = startp; len; len--) {
6220 if (quotes && *str == CTLESC)
6221 *loc++ = *str++;
6222 *loc++ = *str++;
6223 }
6224 *loc = '\0';
6225 amount = loc - expdest;
6226 STADJUST(amount, expdest);
6227 return loc;
6228#endif
6229
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006230 case VSQUESTION:
6231 varunset(p, str, startp, varflags);
6232 /* NOTREACHED */
6233 }
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006234 resetloc = expdest - (char *)stackblock();
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006235
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006236 /* We'll comeback here if we grow the stack while handling
6237 * a VSREPLACE or VSREPLACEALL, since our pointers into the
6238 * stack will need rebasing, and we'll need to remove our work
6239 * areas each time
6240 */
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00006241 IF_ASH_BASH_COMPAT(restart:)
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006242
6243 amount = expdest - ((char *)stackblock() + resetloc);
6244 STADJUST(-amount, expdest);
Denis Vlasenko29eb3592008-05-18 14:06:08 +00006245 startp = (char *)stackblock() + startloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006246
6247 rmesc = startp;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00006248 rmescend = (char *)stackblock() + strloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006249 if (quotes) {
Denys Vlasenkob6c84342009-08-29 20:23:20 +02006250 rmesc = rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006251 if (rmesc != startp) {
6252 rmescend = expdest;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00006253 startp = (char *)stackblock() + startloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006254 }
6255 }
6256 rmescend--;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00006257 str = (char *)stackblock() + strloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006258 preglob(str, varflags & VSQUOTE, 0);
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006259 workloc = expdest - (char *)stackblock();
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006260
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006261#if ENABLE_ASH_BASH_COMPAT
6262 if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
6263 char *idx, *end, *restart_detect;
6264
Denis Vlasenkod6855d12008-09-27 14:03:25 +00006265 if (!repl) {
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006266 repl = parse_sub_pattern(str, varflags & VSQUOTE);
6267 if (!repl)
6268 repl = &null;
6269 }
6270
6271 /* If there's no pattern to match, return the expansion unmolested */
6272 if (*str == '\0')
6273 return 0;
6274
6275 len = 0;
6276 idx = startp;
6277 end = str - 1;
6278 while (idx < end) {
6279 loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
6280 if (!loc) {
6281 /* No match, advance */
6282 restart_detect = stackblock();
6283 STPUTC(*idx, expdest);
6284 if (quotes && *idx == CTLESC) {
6285 idx++;
6286 len++;
6287 STPUTC(*idx, expdest);
6288 }
6289 if (stackblock() != restart_detect)
6290 goto restart;
6291 idx++;
6292 len++;
6293 rmesc++;
6294 continue;
6295 }
6296
6297 if (subtype == VSREPLACEALL) {
6298 while (idx < loc) {
6299 if (quotes && *idx == CTLESC)
6300 idx++;
6301 idx++;
6302 rmesc++;
6303 }
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00006304 } else {
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006305 idx = loc;
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00006306 }
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006307
6308 for (loc = repl; *loc; loc++) {
6309 restart_detect = stackblock();
6310 STPUTC(*loc, expdest);
6311 if (stackblock() != restart_detect)
6312 goto restart;
6313 len++;
6314 }
6315
6316 if (subtype == VSREPLACE) {
6317 while (*idx) {
6318 restart_detect = stackblock();
6319 STPUTC(*idx, expdest);
6320 if (stackblock() != restart_detect)
6321 goto restart;
6322 len++;
6323 idx++;
6324 }
6325 break;
6326 }
6327 }
6328
6329 /* We've put the replaced text into a buffer at workloc, now
6330 * move it to the right place and adjust the stack.
6331 */
6332 startp = stackblock() + startloc;
6333 STPUTC('\0', expdest);
6334 memmove(startp, stackblock() + workloc, len);
6335 startp[len++] = '\0';
6336 amount = expdest - ((char *)stackblock() + startloc + len - 1);
6337 STADJUST(-amount, expdest);
6338 return startp;
6339 }
6340#endif /* ENABLE_ASH_BASH_COMPAT */
6341
6342 subtype -= VSTRIMRIGHT;
6343#if DEBUG
6344 if (subtype < 0 || subtype > 7)
6345 abort();
6346#endif
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006347 /* zero = subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX */
6348 zero = subtype >> 1;
6349 /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
6350 scan = (subtype & 1) ^ zero ? scanleft : scanright;
6351
6352 loc = scan(startp, rmesc, rmescend, str, quotes, zero);
6353 if (loc) {
6354 if (zero) {
6355 memmove(startp, loc, str - loc);
6356 loc = startp + (str - loc) - 1;
6357 }
6358 *loc = '\0';
6359 amount = loc - expdest;
6360 STADJUST(amount, expdest);
6361 }
6362 return loc;
6363}
6364
6365/*
6366 * Add the value of a specialized variable to the stack string.
6367 */
6368static ssize_t
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006369varvalue(char *name, int varflags, int flags, struct strlist *var_str_list)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006370{
6371 int num;
Mike Frysinger98c52642009-04-02 10:02:37 +00006372 const char *p;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006373 int i;
6374 int sep = 0;
6375 int sepq = 0;
6376 ssize_t len = 0;
6377 char **ap;
6378 int syntax;
6379 int quoted = varflags & VSQUOTE;
6380 int subtype = varflags & VSTYPE;
Denys Vlasenko1166d7b2009-09-16 16:20:31 +02006381 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006382
6383 if (quoted && (flags & EXP_FULL))
6384 sep = 1 << CHAR_BIT;
6385
6386 syntax = quoted ? DQSYNTAX : BASESYNTAX;
6387 switch (*name) {
6388 case '$':
6389 num = rootpid;
6390 goto numvar;
6391 case '?':
6392 num = exitstatus;
6393 goto numvar;
6394 case '#':
6395 num = shellparam.nparam;
6396 goto numvar;
6397 case '!':
6398 num = backgndpid;
6399 if (num == 0)
6400 return -1;
6401 numvar:
6402 len = cvtnum(num);
6403 break;
6404 case '-':
Mike Frysinger98c52642009-04-02 10:02:37 +00006405 expdest = makestrspace(NOPTS, expdest);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006406 for (i = NOPTS - 1; i >= 0; i--) {
6407 if (optlist[i]) {
Mike Frysinger98c52642009-04-02 10:02:37 +00006408 USTPUTC(optletters(i), expdest);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006409 len++;
6410 }
6411 }
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006412 break;
6413 case '@':
6414 if (sep)
6415 goto param;
6416 /* fall through */
6417 case '*':
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00006418 sep = ifsset() ? signed_char2int(ifsval()[0]) : ' ';
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006419 if (quotes && (SIT(sep, syntax) == CCTL || SIT(sep, syntax) == CBACK))
6420 sepq = 1;
6421 param:
6422 ap = shellparam.p;
6423 if (!ap)
6424 return -1;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006425 while ((p = *ap++) != NULL) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006426 size_t partlen;
6427
6428 partlen = strlen(p);
6429 len += partlen;
6430
6431 if (!(subtype == VSPLUS || subtype == VSLENGTH))
6432 memtodest(p, partlen, syntax, quotes);
6433
6434 if (*ap && sep) {
6435 char *q;
6436
6437 len++;
6438 if (subtype == VSPLUS || subtype == VSLENGTH) {
6439 continue;
6440 }
6441 q = expdest;
6442 if (sepq)
6443 STPUTC(CTLESC, q);
6444 STPUTC(sep, q);
6445 expdest = q;
6446 }
6447 }
6448 return len;
6449 case '0':
6450 case '1':
6451 case '2':
6452 case '3':
6453 case '4':
6454 case '5':
6455 case '6':
6456 case '7':
6457 case '8':
6458 case '9':
Denys Vlasenkoa00329c2009-08-30 20:05:10 +02006459 num = atoi(name); /* number(name) fails on ${N#str} etc */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006460 if (num < 0 || num > shellparam.nparam)
6461 return -1;
6462 p = num ? shellparam.p[num - 1] : arg0;
6463 goto value;
6464 default:
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006465 /* NB: name has form "VAR=..." */
6466
6467 /* "A=a B=$A" case: var_str_list is a list of "A=a" strings
6468 * which should be considered before we check variables. */
6469 if (var_str_list) {
6470 unsigned name_len = (strchrnul(name, '=') - name) + 1;
6471 p = NULL;
6472 do {
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00006473 char *str, *eq;
6474 str = var_str_list->text;
6475 eq = strchr(str, '=');
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006476 if (!eq) /* stop at first non-assignment */
6477 break;
6478 eq++;
Denis Vlasenko6b06cb82008-05-15 21:30:45 +00006479 if (name_len == (unsigned)(eq - str)
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006480 && strncmp(str, name, name_len) == 0) {
6481 p = eq;
6482 /* goto value; - WRONG! */
6483 /* think "A=1 A=2 B=$A" */
6484 }
6485 var_str_list = var_str_list->next;
6486 } while (var_str_list);
6487 if (p)
6488 goto value;
6489 }
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006490 p = lookupvar(name);
6491 value:
6492 if (!p)
6493 return -1;
6494
6495 len = strlen(p);
6496 if (!(subtype == VSPLUS || subtype == VSLENGTH))
6497 memtodest(p, len, syntax, quotes);
6498 return len;
6499 }
6500
6501 if (subtype == VSPLUS || subtype == VSLENGTH)
6502 STADJUST(-len, expdest);
6503 return len;
6504}
6505
6506/*
6507 * Expand a variable, and return a pointer to the next character in the
6508 * input string.
6509 */
6510static char *
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006511evalvar(char *p, int flags, struct strlist *var_str_list)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006512{
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006513 char varflags;
6514 char subtype;
6515 char quoted;
6516 char easy;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006517 char *var;
6518 int patloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006519 int startloc;
6520 ssize_t varlen;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006521
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006522 varflags = (unsigned char) *p++;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006523 subtype = varflags & VSTYPE;
6524 quoted = varflags & VSQUOTE;
6525 var = p;
6526 easy = (!quoted || (*var == '@' && shellparam.nparam));
6527 startloc = expdest - (char *)stackblock();
6528 p = strchr(p, '=') + 1;
6529
6530 again:
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006531 varlen = varvalue(var, varflags, flags, var_str_list);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006532 if (varflags & VSNUL)
6533 varlen--;
6534
6535 if (subtype == VSPLUS) {
6536 varlen = -1 - varlen;
6537 goto vsplus;
6538 }
6539
6540 if (subtype == VSMINUS) {
6541 vsplus:
6542 if (varlen < 0) {
6543 argstr(
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006544 p, flags | EXP_TILDE |
6545 (quoted ? EXP_QWORD : EXP_WORD),
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006546 var_str_list
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006547 );
6548 goto end;
6549 }
6550 if (easy)
6551 goto record;
6552 goto end;
6553 }
6554
6555 if (subtype == VSASSIGN || subtype == VSQUESTION) {
6556 if (varlen < 0) {
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006557 if (subevalvar(p, var, /* strloc: */ 0,
6558 subtype, startloc, varflags,
6559 /* quotes: */ 0,
6560 var_str_list)
6561 ) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006562 varflags &= ~VSNUL;
6563 /*
6564 * Remove any recorded regions beyond
6565 * start of variable
6566 */
6567 removerecordregions(startloc);
6568 goto again;
6569 }
6570 goto end;
6571 }
6572 if (easy)
6573 goto record;
6574 goto end;
6575 }
6576
6577 if (varlen < 0 && uflag)
6578 varunset(p, var, 0, 0);
6579
6580 if (subtype == VSLENGTH) {
6581 cvtnum(varlen > 0 ? varlen : 0);
6582 goto record;
6583 }
6584
6585 if (subtype == VSNORMAL) {
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006586 if (easy)
6587 goto record;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006588 goto end;
6589 }
6590
6591#if DEBUG
6592 switch (subtype) {
6593 case VSTRIMLEFT:
6594 case VSTRIMLEFTMAX:
6595 case VSTRIMRIGHT:
6596 case VSTRIMRIGHTMAX:
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006597#if ENABLE_ASH_BASH_COMPAT
6598 case VSSUBSTR:
6599 case VSREPLACE:
6600 case VSREPLACEALL:
6601#endif
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006602 break;
6603 default:
6604 abort();
6605 }
6606#endif
6607
6608 if (varlen >= 0) {
6609 /*
6610 * Terminate the string and start recording the pattern
6611 * right after it
6612 */
6613 STPUTC('\0', expdest);
6614 patloc = expdest - (char *)stackblock();
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006615 if (0 == subevalvar(p, /* str: */ NULL, patloc, subtype,
6616 startloc, varflags,
Denys Vlasenko1166d7b2009-09-16 16:20:31 +02006617//TODO: | EXP_REDIR too? All other such places do it too
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006618 /* quotes: */ flags & (EXP_FULL | EXP_CASE),
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006619 var_str_list)
6620 ) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006621 int amount = expdest - (
6622 (char *)stackblock() + patloc - 1
6623 );
6624 STADJUST(-amount, expdest);
6625 }
6626 /* Remove any recorded regions beyond start of variable */
6627 removerecordregions(startloc);
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006628 record:
6629 recordregion(startloc, expdest - (char *)stackblock(), quoted);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006630 }
6631
6632 end:
6633 if (subtype != VSNORMAL) { /* skip to end of alternative */
6634 int nesting = 1;
6635 for (;;) {
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006636 char c = *p++;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006637 if (c == CTLESC)
6638 p++;
6639 else if (c == CTLBACKQ || c == (CTLBACKQ|CTLQUOTE)) {
6640 if (varlen >= 0)
6641 argbackq = argbackq->next;
6642 } else if (c == CTLVAR) {
6643 if ((*p++ & VSTYPE) != VSNORMAL)
6644 nesting++;
6645 } else if (c == CTLENDVAR) {
6646 if (--nesting == 0)
6647 break;
6648 }
6649 }
6650 }
6651 return p;
6652}
6653
6654/*
6655 * Break the argument string into pieces based upon IFS and add the
6656 * strings to the argument list. The regions of the string to be
6657 * searched for IFS characters have been stored by recordregion.
6658 */
6659static void
6660ifsbreakup(char *string, struct arglist *arglist)
6661{
6662 struct ifsregion *ifsp;
6663 struct strlist *sp;
6664 char *start;
6665 char *p;
6666 char *q;
6667 const char *ifs, *realifs;
6668 int ifsspc;
6669 int nulonly;
6670
6671 start = string;
6672 if (ifslastp != NULL) {
6673 ifsspc = 0;
6674 nulonly = 0;
6675 realifs = ifsset() ? ifsval() : defifs;
6676 ifsp = &ifsfirst;
6677 do {
6678 p = string + ifsp->begoff;
6679 nulonly = ifsp->nulonly;
6680 ifs = nulonly ? nullstr : realifs;
6681 ifsspc = 0;
6682 while (p < string + ifsp->endoff) {
6683 q = p;
6684 if (*p == CTLESC)
6685 p++;
6686 if (!strchr(ifs, *p)) {
6687 p++;
6688 continue;
6689 }
6690 if (!nulonly)
6691 ifsspc = (strchr(defifs, *p) != NULL);
6692 /* Ignore IFS whitespace at start */
6693 if (q == start && ifsspc) {
6694 p++;
6695 start = p;
6696 continue;
6697 }
6698 *q = '\0';
Denis Vlasenko597906c2008-02-20 16:38:54 +00006699 sp = stzalloc(sizeof(*sp));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006700 sp->text = start;
6701 *arglist->lastp = sp;
6702 arglist->lastp = &sp->next;
6703 p++;
6704 if (!nulonly) {
6705 for (;;) {
6706 if (p >= string + ifsp->endoff) {
6707 break;
6708 }
6709 q = p;
6710 if (*p == CTLESC)
6711 p++;
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +00006712 if (strchr(ifs, *p) == NULL) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006713 p = q;
6714 break;
Denis Vlasenko597906c2008-02-20 16:38:54 +00006715 }
6716 if (strchr(defifs, *p) == NULL) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006717 if (ifsspc) {
6718 p++;
6719 ifsspc = 0;
6720 } else {
6721 p = q;
6722 break;
6723 }
6724 } else
6725 p++;
6726 }
6727 }
6728 start = p;
6729 } /* while */
6730 ifsp = ifsp->next;
6731 } while (ifsp != NULL);
6732 if (nulonly)
6733 goto add;
6734 }
6735
6736 if (!*start)
6737 return;
6738
6739 add:
Denis Vlasenko597906c2008-02-20 16:38:54 +00006740 sp = stzalloc(sizeof(*sp));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006741 sp->text = start;
6742 *arglist->lastp = sp;
6743 arglist->lastp = &sp->next;
6744}
6745
6746static void
6747ifsfree(void)
6748{
6749 struct ifsregion *p;
6750
6751 INT_OFF;
6752 p = ifsfirst.next;
6753 do {
6754 struct ifsregion *ifsp;
6755 ifsp = p->next;
6756 free(p);
6757 p = ifsp;
6758 } while (p);
6759 ifslastp = NULL;
6760 ifsfirst.next = NULL;
6761 INT_ON;
6762}
6763
6764/*
6765 * Add a file name to the list.
6766 */
6767static void
6768addfname(const char *name)
6769{
6770 struct strlist *sp;
6771
Denis Vlasenko597906c2008-02-20 16:38:54 +00006772 sp = stzalloc(sizeof(*sp));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006773 sp->text = ststrdup(name);
6774 *exparg.lastp = sp;
6775 exparg.lastp = &sp->next;
6776}
6777
6778static char *expdir;
6779
6780/*
6781 * Do metacharacter (i.e. *, ?, [...]) expansion.
6782 */
6783static void
6784expmeta(char *enddir, char *name)
6785{
6786 char *p;
6787 const char *cp;
6788 char *start;
6789 char *endname;
6790 int metaflag;
6791 struct stat statb;
6792 DIR *dirp;
6793 struct dirent *dp;
6794 int atend;
6795 int matchdot;
6796
6797 metaflag = 0;
6798 start = name;
6799 for (p = name; *p; p++) {
6800 if (*p == '*' || *p == '?')
6801 metaflag = 1;
6802 else if (*p == '[') {
6803 char *q = p + 1;
6804 if (*q == '!')
6805 q++;
6806 for (;;) {
6807 if (*q == '\\')
6808 q++;
6809 if (*q == '/' || *q == '\0')
6810 break;
6811 if (*++q == ']') {
6812 metaflag = 1;
6813 break;
6814 }
6815 }
6816 } else if (*p == '\\')
6817 p++;
6818 else if (*p == '/') {
6819 if (metaflag)
6820 goto out;
6821 start = p + 1;
6822 }
6823 }
6824 out:
6825 if (metaflag == 0) { /* we've reached the end of the file name */
6826 if (enddir != expdir)
6827 metaflag++;
6828 p = name;
6829 do {
6830 if (*p == '\\')
6831 p++;
6832 *enddir++ = *p;
6833 } while (*p++);
6834 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
6835 addfname(expdir);
6836 return;
6837 }
6838 endname = p;
6839 if (name < start) {
6840 p = name;
6841 do {
6842 if (*p == '\\')
6843 p++;
6844 *enddir++ = *p++;
6845 } while (p < start);
6846 }
6847 if (enddir == expdir) {
6848 cp = ".";
6849 } else if (enddir == expdir + 1 && *expdir == '/') {
6850 cp = "/";
6851 } else {
6852 cp = expdir;
6853 enddir[-1] = '\0';
6854 }
6855 dirp = opendir(cp);
6856 if (dirp == NULL)
6857 return;
6858 if (enddir != expdir)
6859 enddir[-1] = '/';
6860 if (*endname == 0) {
6861 atend = 1;
6862 } else {
6863 atend = 0;
6864 *endname++ = '\0';
6865 }
6866 matchdot = 0;
6867 p = start;
6868 if (*p == '\\')
6869 p++;
6870 if (*p == '.')
6871 matchdot++;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006872 while (!pending_int && (dp = readdir(dirp)) != NULL) {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00006873 if (dp->d_name[0] == '.' && !matchdot)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006874 continue;
6875 if (pmatch(start, dp->d_name)) {
6876 if (atend) {
6877 strcpy(enddir, dp->d_name);
6878 addfname(expdir);
6879 } else {
6880 for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
6881 continue;
6882 p[-1] = '/';
6883 expmeta(p, endname);
6884 }
6885 }
6886 }
6887 closedir(dirp);
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00006888 if (!atend)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006889 endname[-1] = '/';
6890}
6891
6892static struct strlist *
6893msort(struct strlist *list, int len)
6894{
6895 struct strlist *p, *q = NULL;
6896 struct strlist **lpp;
6897 int half;
6898 int n;
6899
6900 if (len <= 1)
6901 return list;
6902 half = len >> 1;
6903 p = list;
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +00006904 for (n = half; --n >= 0;) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006905 q = p;
6906 p = p->next;
6907 }
6908 q->next = NULL; /* terminate first half of list */
6909 q = msort(list, half); /* sort first half of list */
6910 p = msort(p, len - half); /* sort second half */
6911 lpp = &list;
6912 for (;;) {
6913#if ENABLE_LOCALE_SUPPORT
6914 if (strcoll(p->text, q->text) < 0)
6915#else
6916 if (strcmp(p->text, q->text) < 0)
6917#endif
6918 {
6919 *lpp = p;
6920 lpp = &p->next;
6921 p = *lpp;
6922 if (p == NULL) {
6923 *lpp = q;
6924 break;
6925 }
6926 } else {
6927 *lpp = q;
6928 lpp = &q->next;
6929 q = *lpp;
6930 if (q == NULL) {
6931 *lpp = p;
6932 break;
6933 }
6934 }
6935 }
6936 return list;
6937}
6938
6939/*
6940 * Sort the results of file name expansion. It calculates the number of
6941 * strings to sort and then calls msort (short for merge sort) to do the
6942 * work.
6943 */
6944static struct strlist *
6945expsort(struct strlist *str)
6946{
6947 int len;
6948 struct strlist *sp;
6949
6950 len = 0;
6951 for (sp = str; sp; sp = sp->next)
6952 len++;
6953 return msort(str, len);
6954}
6955
6956static void
Denis Vlasenko68404f12008-03-17 09:00:54 +00006957expandmeta(struct strlist *str /*, int flag*/)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006958{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00006959 static const char metachars[] ALIGN1 = {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006960 '*', '?', '[', 0
6961 };
6962 /* TODO - EXP_REDIR */
6963
6964 while (str) {
6965 struct strlist **savelastp;
6966 struct strlist *sp;
6967 char *p;
6968
6969 if (fflag)
6970 goto nometa;
6971 if (!strpbrk(str->text, metachars))
6972 goto nometa;
6973 savelastp = exparg.lastp;
6974
6975 INT_OFF;
6976 p = preglob(str->text, 0, RMESCAPE_ALLOC | RMESCAPE_HEAP);
6977 {
6978 int i = strlen(str->text);
6979 expdir = ckmalloc(i < 2048 ? 2048 : i); /* XXX */
6980 }
6981
6982 expmeta(expdir, p);
6983 free(expdir);
6984 if (p != str->text)
6985 free(p);
6986 INT_ON;
6987 if (exparg.lastp == savelastp) {
6988 /*
6989 * no matches
6990 */
6991 nometa:
6992 *exparg.lastp = str;
Denys Vlasenkob6c84342009-08-29 20:23:20 +02006993 rmescapes(str->text, 0);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006994 exparg.lastp = &str->next;
6995 } else {
6996 *exparg.lastp = NULL;
6997 *savelastp = sp = expsort(*savelastp);
6998 while (sp->next != NULL)
6999 sp = sp->next;
7000 exparg.lastp = &sp->next;
7001 }
7002 str = str->next;
7003 }
7004}
7005
7006/*
7007 * Perform variable substitution and command substitution on an argument,
7008 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
7009 * perform splitting and file name expansion. When arglist is NULL, perform
7010 * here document expansion.
7011 */
7012static void
7013expandarg(union node *arg, struct arglist *arglist, int flag)
7014{
7015 struct strlist *sp;
7016 char *p;
7017
7018 argbackq = arg->narg.backquote;
7019 STARTSTACKSTR(expdest);
7020 ifsfirst.next = NULL;
7021 ifslastp = NULL;
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00007022 argstr(arg->narg.text, flag,
7023 /* var_str_list: */ arglist ? arglist->list : NULL);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007024 p = _STPUTC('\0', expdest);
7025 expdest = p - 1;
7026 if (arglist == NULL) {
7027 return; /* here document expanded */
7028 }
7029 p = grabstackstr(p);
7030 exparg.lastp = &exparg.list;
7031 /*
7032 * TODO - EXP_REDIR
7033 */
7034 if (flag & EXP_FULL) {
7035 ifsbreakup(p, &exparg);
7036 *exparg.lastp = NULL;
7037 exparg.lastp = &exparg.list;
Denis Vlasenko68404f12008-03-17 09:00:54 +00007038 expandmeta(exparg.list /*, flag*/);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007039 } else {
7040 if (flag & EXP_REDIR) /*XXX - for now, just remove escapes */
Denys Vlasenkob6c84342009-08-29 20:23:20 +02007041 rmescapes(p, 0);
Denis Vlasenko597906c2008-02-20 16:38:54 +00007042 sp = stzalloc(sizeof(*sp));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007043 sp->text = p;
7044 *exparg.lastp = sp;
7045 exparg.lastp = &sp->next;
7046 }
7047 if (ifsfirst.next)
7048 ifsfree();
7049 *exparg.lastp = NULL;
7050 if (exparg.list) {
7051 *arglist->lastp = exparg.list;
7052 arglist->lastp = exparg.lastp;
7053 }
7054}
7055
7056/*
7057 * Expand shell variables and backquotes inside a here document.
7058 */
7059static void
7060expandhere(union node *arg, int fd)
7061{
7062 herefd = fd;
7063 expandarg(arg, (struct arglist *)NULL, 0);
7064 full_write(fd, stackblock(), expdest - (char *)stackblock());
7065}
7066
7067/*
7068 * Returns true if the pattern matches the string.
7069 */
7070static int
7071patmatch(char *pattern, const char *string)
7072{
7073 return pmatch(preglob(pattern, 0, 0), string);
7074}
7075
7076/*
7077 * See if a pattern matches in a case statement.
7078 */
7079static int
7080casematch(union node *pattern, char *val)
7081{
7082 struct stackmark smark;
7083 int result;
7084
7085 setstackmark(&smark);
7086 argbackq = pattern->narg.backquote;
7087 STARTSTACKSTR(expdest);
7088 ifslastp = NULL;
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00007089 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE,
7090 /* var_str_list: */ NULL);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007091 STACKSTRNUL(expdest);
7092 result = patmatch(stackblock(), val);
7093 popstackmark(&smark);
7094 return result;
7095}
7096
7097
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007098/* ============ find_command */
7099
7100struct builtincmd {
7101 const char *name;
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007102 int (*builtin)(int, char **) FAST_FUNC;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007103 /* unsigned flags; */
7104};
7105#define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
Denis Vlasenkoe26b2782008-02-12 07:40:29 +00007106/* "regular" builtins always take precedence over commands,
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007107 * regardless of PATH=....%builtin... position */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007108#define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007109#define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007110
7111struct cmdentry {
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00007112 smallint cmdtype; /* CMDxxx */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007113 union param {
7114 int index;
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00007115 /* index >= 0 for commands without path (slashes) */
7116 /* (TODO: what exactly does the value mean? PATH position?) */
7117 /* index == -1 for commands with slashes */
7118 /* index == (-2 - applet_no) for NOFORK applets */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007119 const struct builtincmd *cmd;
7120 struct funcnode *func;
7121 } u;
7122};
7123/* values of cmdtype */
7124#define CMDUNKNOWN -1 /* no entry in table for command */
7125#define CMDNORMAL 0 /* command is an executable program */
7126#define CMDFUNCTION 1 /* command is a shell function */
7127#define CMDBUILTIN 2 /* command is a shell builtin */
7128
7129/* action to find_command() */
7130#define DO_ERR 0x01 /* prints errors */
7131#define DO_ABS 0x02 /* checks absolute paths */
7132#define DO_NOFUNC 0x04 /* don't return shell functions, for command */
7133#define DO_ALTPATH 0x08 /* using alternate path */
7134#define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
7135
7136static void find_command(char *, struct cmdentry *, int, const char *);
7137
7138
7139/* ============ Hashing commands */
7140
7141/*
7142 * When commands are first encountered, they are entered in a hash table.
7143 * This ensures that a full path search will not have to be done for them
7144 * on each invocation.
7145 *
7146 * We should investigate converting to a linear search, even though that
7147 * would make the command name "hash" a misnomer.
7148 */
7149
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007150struct tblentry {
7151 struct tblentry *next; /* next entry in hash chain */
7152 union param param; /* definition of builtin function */
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00007153 smallint cmdtype; /* CMDxxx */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007154 char rehash; /* if set, cd done since entry created */
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007155 char cmdname[1]; /* name of command */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007156};
7157
Denis Vlasenko01631112007-12-16 17:20:38 +00007158static struct tblentry **cmdtable;
7159#define INIT_G_cmdtable() do { \
7160 cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
7161} while (0)
7162
7163static int builtinloc = -1; /* index in path of %builtin, or -1 */
7164
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007165
7166static void
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00007167tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) char *cmd, char **argv, char **envp)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007168{
7169 int repeated = 0;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007170
Denis Vlasenko80d14be2007-04-10 23:03:30 +00007171#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007172 if (applet_no >= 0) {
Denis Vlasenkob7304742008-10-20 08:15:51 +00007173 if (APPLET_IS_NOEXEC(applet_no)) {
7174 while (*envp)
7175 putenv(*envp++);
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007176 run_applet_no_and_exit(applet_no, argv);
Denis Vlasenkob7304742008-10-20 08:15:51 +00007177 }
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007178 /* re-exec ourselves with the new arguments */
7179 execve(bb_busybox_exec_path, argv, envp);
7180 /* If they called chroot or otherwise made the binary no longer
7181 * executable, fall through */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007182 }
7183#endif
7184
7185 repeat:
7186#ifdef SYSV
7187 do {
7188 execve(cmd, argv, envp);
7189 } while (errno == EINTR);
7190#else
7191 execve(cmd, argv, envp);
7192#endif
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007193 if (repeated) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007194 free(argv);
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007195 return;
7196 }
7197 if (errno == ENOEXEC) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007198 char **ap;
7199 char **new;
7200
7201 for (ap = argv; *ap; ap++)
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007202 continue;
7203 ap = new = ckmalloc((ap - argv + 2) * sizeof(ap[0]));
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007204 ap[1] = cmd;
Denis Vlasenkoc44ab012007-04-09 03:11:58 +00007205 ap[0] = cmd = (char *)DEFAULT_SHELL;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007206 ap += 2;
7207 argv++;
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007208 while ((*ap++ = *argv++) != NULL)
Denis Vlasenko597906c2008-02-20 16:38:54 +00007209 continue;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007210 argv = new;
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007211 repeated++;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007212 goto repeat;
7213 }
7214}
7215
7216/*
7217 * Exec a program. Never returns. If you change this routine, you may
7218 * have to change the find_command routine as well.
7219 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00007220static void shellexec(char **, const char *, int) NORETURN;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007221static void
7222shellexec(char **argv, const char *path, int idx)
7223{
7224 char *cmdname;
7225 int e;
7226 char **envp;
7227 int exerrno;
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007228#if ENABLE_FEATURE_SH_STANDALONE
7229 int applet_no = -1;
7230#endif
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007231
Denis Vlasenko34c73c42008-08-16 11:48:02 +00007232 clearredir(/*drop:*/ 1);
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007233 envp = listvars(VEXPORT, VUNSET, 0);
7234 if (strchr(argv[0], '/') != NULL
Denis Vlasenko80d14be2007-04-10 23:03:30 +00007235#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007236 || (applet_no = find_applet_by_name(argv[0])) >= 0
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007237#endif
7238 ) {
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00007239 tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) argv[0], argv, envp);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007240 e = errno;
7241 } else {
7242 e = ENOENT;
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02007243 while ((cmdname = path_advance(&path, argv[0])) != NULL) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007244 if (--idx < 0 && pathopt == NULL) {
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00007245 tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007246 if (errno != ENOENT && errno != ENOTDIR)
7247 e = errno;
7248 }
7249 stunalloc(cmdname);
7250 }
7251 }
7252
7253 /* Map to POSIX errors */
7254 switch (e) {
7255 case EACCES:
7256 exerrno = 126;
7257 break;
7258 case ENOENT:
7259 exerrno = 127;
7260 break;
7261 default:
7262 exerrno = 2;
7263 break;
7264 }
7265 exitstatus = exerrno;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02007266 TRACE(("shellexec failed for %s, errno %d, suppress_int %d\n",
7267 argv[0], e, suppress_int));
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007268 ash_msg_and_raise(EXEXEC, "%s: %s", argv[0], errmsg(e, "not found"));
7269 /* NOTREACHED */
7270}
7271
7272static void
7273printentry(struct tblentry *cmdp)
7274{
7275 int idx;
7276 const char *path;
7277 char *name;
7278
7279 idx = cmdp->param.index;
7280 path = pathval();
7281 do {
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02007282 name = path_advance(&path, cmdp->cmdname);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007283 stunalloc(name);
7284 } while (--idx >= 0);
7285 out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
7286}
7287
7288/*
7289 * Clear out command entries. The argument specifies the first entry in
7290 * PATH which has changed.
7291 */
7292static void
7293clearcmdentry(int firstchange)
7294{
7295 struct tblentry **tblp;
7296 struct tblentry **pp;
7297 struct tblentry *cmdp;
7298
7299 INT_OFF;
7300 for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
7301 pp = tblp;
7302 while ((cmdp = *pp) != NULL) {
7303 if ((cmdp->cmdtype == CMDNORMAL &&
7304 cmdp->param.index >= firstchange)
7305 || (cmdp->cmdtype == CMDBUILTIN &&
7306 builtinloc >= firstchange)
7307 ) {
7308 *pp = cmdp->next;
7309 free(cmdp);
7310 } else {
7311 pp = &cmdp->next;
7312 }
7313 }
7314 }
7315 INT_ON;
7316}
7317
7318/*
7319 * Locate a command in the command hash table. If "add" is nonzero,
7320 * add the command to the table if it is not already present. The
7321 * variable "lastcmdentry" is set to point to the address of the link
7322 * pointing to the entry, so that delete_cmd_entry can delete the
7323 * entry.
7324 *
7325 * Interrupts must be off if called with add != 0.
7326 */
7327static struct tblentry **lastcmdentry;
7328
7329static struct tblentry *
7330cmdlookup(const char *name, int add)
7331{
7332 unsigned int hashval;
7333 const char *p;
7334 struct tblentry *cmdp;
7335 struct tblentry **pp;
7336
7337 p = name;
7338 hashval = (unsigned char)*p << 4;
7339 while (*p)
7340 hashval += (unsigned char)*p++;
7341 hashval &= 0x7FFF;
7342 pp = &cmdtable[hashval % CMDTABLESIZE];
7343 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7344 if (strcmp(cmdp->cmdname, name) == 0)
7345 break;
7346 pp = &cmdp->next;
7347 }
7348 if (add && cmdp == NULL) {
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007349 cmdp = *pp = ckzalloc(sizeof(struct tblentry)
7350 + strlen(name)
7351 /* + 1 - already done because
7352 * tblentry::cmdname is char[1] */);
Denis Vlasenko597906c2008-02-20 16:38:54 +00007353 /*cmdp->next = NULL; - ckzalloc did it */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007354 cmdp->cmdtype = CMDUNKNOWN;
7355 strcpy(cmdp->cmdname, name);
7356 }
7357 lastcmdentry = pp;
7358 return cmdp;
7359}
7360
7361/*
7362 * Delete the command entry returned on the last lookup.
7363 */
7364static void
7365delete_cmd_entry(void)
7366{
7367 struct tblentry *cmdp;
7368
7369 INT_OFF;
7370 cmdp = *lastcmdentry;
7371 *lastcmdentry = cmdp->next;
7372 if (cmdp->cmdtype == CMDFUNCTION)
7373 freefunc(cmdp->param.func);
7374 free(cmdp);
7375 INT_ON;
7376}
7377
7378/*
7379 * Add a new command entry, replacing any existing command entry for
7380 * the same name - except special builtins.
7381 */
7382static void
7383addcmdentry(char *name, struct cmdentry *entry)
7384{
7385 struct tblentry *cmdp;
7386
7387 cmdp = cmdlookup(name, 1);
7388 if (cmdp->cmdtype == CMDFUNCTION) {
7389 freefunc(cmdp->param.func);
7390 }
7391 cmdp->cmdtype = entry->cmdtype;
7392 cmdp->param = entry->u;
7393 cmdp->rehash = 0;
7394}
7395
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007396static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00007397hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007398{
7399 struct tblentry **pp;
7400 struct tblentry *cmdp;
7401 int c;
7402 struct cmdentry entry;
7403 char *name;
7404
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007405 if (nextopt("r") != '\0') {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007406 clearcmdentry(0);
7407 return 0;
7408 }
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007409
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007410 if (*argptr == NULL) {
7411 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7412 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7413 if (cmdp->cmdtype == CMDNORMAL)
7414 printentry(cmdp);
7415 }
7416 }
7417 return 0;
7418 }
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007419
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007420 c = 0;
7421 while ((name = *argptr) != NULL) {
7422 cmdp = cmdlookup(name, 0);
7423 if (cmdp != NULL
7424 && (cmdp->cmdtype == CMDNORMAL
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007425 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
7426 ) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007427 delete_cmd_entry();
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007428 }
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007429 find_command(name, &entry, DO_ERR, pathval());
7430 if (entry.cmdtype == CMDUNKNOWN)
7431 c = 1;
7432 argptr++;
7433 }
7434 return c;
7435}
7436
7437/*
7438 * Called when a cd is done. Marks all commands so the next time they
7439 * are executed they will be rehashed.
7440 */
7441static void
7442hashcd(void)
7443{
7444 struct tblentry **pp;
7445 struct tblentry *cmdp;
7446
7447 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7448 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007449 if (cmdp->cmdtype == CMDNORMAL
7450 || (cmdp->cmdtype == CMDBUILTIN
7451 && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
7452 && builtinloc > 0)
7453 ) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007454 cmdp->rehash = 1;
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007455 }
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007456 }
7457 }
7458}
7459
7460/*
7461 * Fix command hash table when PATH changed.
7462 * Called before PATH is changed. The argument is the new value of PATH;
7463 * pathval() still returns the old value at this point.
7464 * Called with interrupts off.
7465 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007466static void FAST_FUNC
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007467changepath(const char *new)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007468{
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007469 const char *old;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007470 int firstchange;
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007471 int idx;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007472 int idx_bltin;
7473
7474 old = pathval();
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007475 firstchange = 9999; /* assume no change */
7476 idx = 0;
7477 idx_bltin = -1;
7478 for (;;) {
7479 if (*old != *new) {
7480 firstchange = idx;
7481 if ((*old == '\0' && *new == ':')
7482 || (*old == ':' && *new == '\0'))
7483 firstchange++;
7484 old = new; /* ignore subsequent differences */
7485 }
7486 if (*new == '\0')
7487 break;
7488 if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
7489 idx_bltin = idx;
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007490 if (*new == ':')
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007491 idx++;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007492 new++, old++;
7493 }
7494 if (builtinloc < 0 && idx_bltin >= 0)
7495 builtinloc = idx_bltin; /* zap builtins */
7496 if (builtinloc >= 0 && idx_bltin < 0)
7497 firstchange = 0;
7498 clearcmdentry(firstchange);
7499 builtinloc = idx_bltin;
7500}
7501
7502#define TEOF 0
7503#define TNL 1
7504#define TREDIR 2
7505#define TWORD 3
7506#define TSEMI 4
7507#define TBACKGND 5
7508#define TAND 6
7509#define TOR 7
7510#define TPIPE 8
7511#define TLP 9
7512#define TRP 10
7513#define TENDCASE 11
7514#define TENDBQUOTE 12
7515#define TNOT 13
7516#define TCASE 14
7517#define TDO 15
7518#define TDONE 16
7519#define TELIF 17
7520#define TELSE 18
7521#define TESAC 19
7522#define TFI 20
7523#define TFOR 21
7524#define TIF 22
7525#define TIN 23
7526#define TTHEN 24
7527#define TUNTIL 25
7528#define TWHILE 26
7529#define TBEGIN 27
7530#define TEND 28
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007531typedef smallint token_id_t;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007532
7533/* first char is indicating which tokens mark the end of a list */
7534static const char *const tokname_array[] = {
7535 "\1end of file",
7536 "\0newline",
7537 "\0redirection",
7538 "\0word",
7539 "\0;",
7540 "\0&",
7541 "\0&&",
7542 "\0||",
7543 "\0|",
7544 "\0(",
7545 "\1)",
7546 "\1;;",
7547 "\1`",
7548#define KWDOFFSET 13
7549 /* the following are keywords */
7550 "\0!",
7551 "\0case",
7552 "\1do",
7553 "\1done",
7554 "\1elif",
7555 "\1else",
7556 "\1esac",
7557 "\1fi",
7558 "\0for",
7559 "\0if",
7560 "\0in",
7561 "\1then",
7562 "\0until",
7563 "\0while",
7564 "\0{",
7565 "\1}",
7566};
7567
7568static const char *
7569tokname(int tok)
7570{
7571 static char buf[16];
7572
Denis Vlasenko240a1cf2007-04-08 16:07:02 +00007573//try this:
7574//if (tok < TSEMI) return tokname_array[tok] + 1;
7575//sprintf(buf, "\"%s\"", tokname_array[tok] + 1);
7576//return buf;
7577
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007578 if (tok >= TSEMI)
7579 buf[0] = '"';
7580 sprintf(buf + (tok >= TSEMI), "%s%c",
7581 tokname_array[tok] + 1, (tok >= TSEMI ? '"' : 0));
7582 return buf;
7583}
7584
7585/* Wrapper around strcmp for qsort/bsearch/... */
7586static int
7587pstrcmp(const void *a, const void *b)
7588{
Denis Vlasenko240a1cf2007-04-08 16:07:02 +00007589 return strcmp((char*) a, (*(char**) b) + 1);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007590}
7591
7592static const char *const *
7593findkwd(const char *s)
7594{
7595 return bsearch(s, tokname_array + KWDOFFSET,
Denis Vlasenko80b8b392007-06-25 10:55:35 +00007596 ARRAY_SIZE(tokname_array) - KWDOFFSET,
7597 sizeof(tokname_array[0]), pstrcmp);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007598}
7599
7600/*
7601 * Locate and print what a word is...
7602 */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007603static int
7604describe_command(char *command, int describe_command_verbose)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007605{
7606 struct cmdentry entry;
7607 struct tblentry *cmdp;
7608#if ENABLE_ASH_ALIAS
7609 const struct alias *ap;
7610#endif
7611 const char *path = pathval();
7612
7613 if (describe_command_verbose) {
7614 out1str(command);
7615 }
7616
7617 /* First look at the keywords */
7618 if (findkwd(command)) {
7619 out1str(describe_command_verbose ? " is a shell keyword" : command);
7620 goto out;
7621 }
7622
7623#if ENABLE_ASH_ALIAS
7624 /* Then look at the aliases */
7625 ap = lookupalias(command, 0);
7626 if (ap != NULL) {
Denis Vlasenko46846e22007-05-20 13:08:31 +00007627 if (!describe_command_verbose) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007628 out1str("alias ");
7629 printalias(ap);
7630 return 0;
7631 }
Denis Vlasenko46846e22007-05-20 13:08:31 +00007632 out1fmt(" is an alias for %s", ap->val);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007633 goto out;
7634 }
7635#endif
7636 /* Then check if it is a tracked alias */
7637 cmdp = cmdlookup(command, 0);
7638 if (cmdp != NULL) {
7639 entry.cmdtype = cmdp->cmdtype;
7640 entry.u = cmdp->param;
7641 } else {
7642 /* Finally use brute force */
7643 find_command(command, &entry, DO_ABS, path);
7644 }
7645
7646 switch (entry.cmdtype) {
7647 case CMDNORMAL: {
7648 int j = entry.u.index;
7649 char *p;
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00007650 if (j < 0) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007651 p = command;
7652 } else {
7653 do {
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02007654 p = path_advance(&path, command);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007655 stunalloc(p);
7656 } while (--j >= 0);
7657 }
7658 if (describe_command_verbose) {
7659 out1fmt(" is%s %s",
7660 (cmdp ? " a tracked alias for" : nullstr), p
7661 );
7662 } else {
7663 out1str(p);
7664 }
7665 break;
7666 }
7667
7668 case CMDFUNCTION:
7669 if (describe_command_verbose) {
7670 out1str(" is a shell function");
7671 } else {
7672 out1str(command);
7673 }
7674 break;
7675
7676 case CMDBUILTIN:
7677 if (describe_command_verbose) {
7678 out1fmt(" is a %sshell builtin",
7679 IS_BUILTIN_SPECIAL(entry.u.cmd) ?
7680 "special " : nullstr
7681 );
7682 } else {
7683 out1str(command);
7684 }
7685 break;
7686
7687 default:
7688 if (describe_command_verbose) {
7689 out1str(": not found\n");
7690 }
7691 return 127;
7692 }
7693 out:
7694 outstr("\n", stdout);
7695 return 0;
7696}
7697
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007698static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00007699typecmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007700{
Denis Vlasenko46846e22007-05-20 13:08:31 +00007701 int i = 1;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007702 int err = 0;
Denis Vlasenko46846e22007-05-20 13:08:31 +00007703 int verbose = 1;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007704
Denis Vlasenko46846e22007-05-20 13:08:31 +00007705 /* type -p ... ? (we don't bother checking for 'p') */
Denis Vlasenko1fc62382007-06-25 22:55:34 +00007706 if (argv[1] && argv[1][0] == '-') {
Denis Vlasenko46846e22007-05-20 13:08:31 +00007707 i++;
7708 verbose = 0;
7709 }
Denis Vlasenko68404f12008-03-17 09:00:54 +00007710 while (argv[i]) {
Denis Vlasenko46846e22007-05-20 13:08:31 +00007711 err |= describe_command(argv[i++], verbose);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007712 }
7713 return err;
7714}
7715
7716#if ENABLE_ASH_CMDCMD
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007717static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00007718commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007719{
7720 int c;
7721 enum {
7722 VERIFY_BRIEF = 1,
7723 VERIFY_VERBOSE = 2,
7724 } verify = 0;
7725
7726 while ((c = nextopt("pvV")) != '\0')
7727 if (c == 'V')
7728 verify |= VERIFY_VERBOSE;
7729 else if (c == 'v')
7730 verify |= VERIFY_BRIEF;
7731#if DEBUG
7732 else if (c != 'p')
7733 abort();
7734#endif
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00007735 /* Mimic bash: just "command -v" doesn't complain, it's a nop */
7736 if (verify && (*argptr != NULL)) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007737 return describe_command(*argptr, verify - VERIFY_BRIEF);
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00007738 }
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007739
7740 return 0;
7741}
7742#endif
7743
7744
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007745/* ============ eval.c */
Eric Andersencb57d552001-06-28 07:25:16 +00007746
Denis Vlasenko340299a2008-11-21 10:36:36 +00007747static int funcblocksize; /* size of structures in function */
7748static int funcstringsize; /* size of strings in node */
7749static void *funcblock; /* block to allocate function from */
7750static char *funcstring; /* block to allocate strings from */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007751
Eric Andersencb57d552001-06-28 07:25:16 +00007752/* flags in argument to evaltree */
Denis Vlasenko340299a2008-11-21 10:36:36 +00007753#define EV_EXIT 01 /* exit after evaluating tree */
7754#define EV_TESTED 02 /* exit status is checked; ignore -e flag */
Eric Andersenc470f442003-07-28 09:56:35 +00007755#define EV_BACKCMD 04 /* command executing within back quotes */
Eric Andersencb57d552001-06-28 07:25:16 +00007756
Denis Vlasenko340299a2008-11-21 10:36:36 +00007757static const short nodesize[N_NUMBER] = {
7758 [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
7759 [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
7760 [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
7761 [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
7762 [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
7763 [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
7764 [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
7765 [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
7766 [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
7767 [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
7768 [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
7769 [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
7770 [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
7771 [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
7772 [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
7773 [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
7774 [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
Denis Vlasenkocc5feab2008-11-22 01:32:40 +00007775#if ENABLE_ASH_BASH_COMPAT
Denis Vlasenko340299a2008-11-21 10:36:36 +00007776 [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
Denis Vlasenkocc5feab2008-11-22 01:32:40 +00007777#endif
Denis Vlasenko340299a2008-11-21 10:36:36 +00007778 [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
7779 [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
7780 [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
7781 [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
7782 [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
7783 [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
7784 [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
7785 [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
7786 [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007787};
7788
7789static void calcsize(union node *n);
7790
7791static void
7792sizenodelist(struct nodelist *lp)
7793{
7794 while (lp) {
7795 funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
7796 calcsize(lp->n);
7797 lp = lp->next;
7798 }
7799}
7800
7801static void
7802calcsize(union node *n)
7803{
7804 if (n == NULL)
7805 return;
7806 funcblocksize += nodesize[n->type];
7807 switch (n->type) {
7808 case NCMD:
7809 calcsize(n->ncmd.redirect);
7810 calcsize(n->ncmd.args);
7811 calcsize(n->ncmd.assign);
7812 break;
7813 case NPIPE:
7814 sizenodelist(n->npipe.cmdlist);
7815 break;
7816 case NREDIR:
7817 case NBACKGND:
7818 case NSUBSHELL:
7819 calcsize(n->nredir.redirect);
7820 calcsize(n->nredir.n);
7821 break;
7822 case NAND:
7823 case NOR:
7824 case NSEMI:
7825 case NWHILE:
7826 case NUNTIL:
7827 calcsize(n->nbinary.ch2);
7828 calcsize(n->nbinary.ch1);
7829 break;
7830 case NIF:
7831 calcsize(n->nif.elsepart);
7832 calcsize(n->nif.ifpart);
7833 calcsize(n->nif.test);
7834 break;
7835 case NFOR:
7836 funcstringsize += strlen(n->nfor.var) + 1;
7837 calcsize(n->nfor.body);
7838 calcsize(n->nfor.args);
7839 break;
7840 case NCASE:
7841 calcsize(n->ncase.cases);
7842 calcsize(n->ncase.expr);
7843 break;
7844 case NCLIST:
7845 calcsize(n->nclist.body);
7846 calcsize(n->nclist.pattern);
7847 calcsize(n->nclist.next);
7848 break;
7849 case NDEFUN:
7850 case NARG:
7851 sizenodelist(n->narg.backquote);
7852 funcstringsize += strlen(n->narg.text) + 1;
7853 calcsize(n->narg.next);
7854 break;
7855 case NTO:
Denis Vlasenko559691a2008-10-05 18:39:31 +00007856#if ENABLE_ASH_BASH_COMPAT
7857 case NTO2:
7858#endif
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007859 case NCLOBBER:
7860 case NFROM:
7861 case NFROMTO:
7862 case NAPPEND:
7863 calcsize(n->nfile.fname);
7864 calcsize(n->nfile.next);
7865 break;
7866 case NTOFD:
7867 case NFROMFD:
7868 calcsize(n->ndup.vname);
7869 calcsize(n->ndup.next);
7870 break;
7871 case NHERE:
7872 case NXHERE:
7873 calcsize(n->nhere.doc);
7874 calcsize(n->nhere.next);
7875 break;
7876 case NNOT:
7877 calcsize(n->nnot.com);
7878 break;
7879 };
7880}
7881
7882static char *
7883nodeckstrdup(char *s)
7884{
7885 char *rtn = funcstring;
7886
7887 strcpy(funcstring, s);
7888 funcstring += strlen(s) + 1;
7889 return rtn;
7890}
7891
7892static union node *copynode(union node *);
7893
7894static struct nodelist *
7895copynodelist(struct nodelist *lp)
7896{
7897 struct nodelist *start;
7898 struct nodelist **lpp;
7899
7900 lpp = &start;
7901 while (lp) {
7902 *lpp = funcblock;
7903 funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
7904 (*lpp)->n = copynode(lp->n);
7905 lp = lp->next;
7906 lpp = &(*lpp)->next;
7907 }
7908 *lpp = NULL;
7909 return start;
7910}
7911
7912static union node *
7913copynode(union node *n)
7914{
7915 union node *new;
7916
7917 if (n == NULL)
7918 return NULL;
7919 new = funcblock;
7920 funcblock = (char *) funcblock + nodesize[n->type];
7921
7922 switch (n->type) {
7923 case NCMD:
7924 new->ncmd.redirect = copynode(n->ncmd.redirect);
7925 new->ncmd.args = copynode(n->ncmd.args);
7926 new->ncmd.assign = copynode(n->ncmd.assign);
7927 break;
7928 case NPIPE:
7929 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00007930 new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007931 break;
7932 case NREDIR:
7933 case NBACKGND:
7934 case NSUBSHELL:
7935 new->nredir.redirect = copynode(n->nredir.redirect);
7936 new->nredir.n = copynode(n->nredir.n);
7937 break;
7938 case NAND:
7939 case NOR:
7940 case NSEMI:
7941 case NWHILE:
7942 case NUNTIL:
7943 new->nbinary.ch2 = copynode(n->nbinary.ch2);
7944 new->nbinary.ch1 = copynode(n->nbinary.ch1);
7945 break;
7946 case NIF:
7947 new->nif.elsepart = copynode(n->nif.elsepart);
7948 new->nif.ifpart = copynode(n->nif.ifpart);
7949 new->nif.test = copynode(n->nif.test);
7950 break;
7951 case NFOR:
7952 new->nfor.var = nodeckstrdup(n->nfor.var);
7953 new->nfor.body = copynode(n->nfor.body);
7954 new->nfor.args = copynode(n->nfor.args);
7955 break;
7956 case NCASE:
7957 new->ncase.cases = copynode(n->ncase.cases);
7958 new->ncase.expr = copynode(n->ncase.expr);
7959 break;
7960 case NCLIST:
7961 new->nclist.body = copynode(n->nclist.body);
7962 new->nclist.pattern = copynode(n->nclist.pattern);
7963 new->nclist.next = copynode(n->nclist.next);
7964 break;
7965 case NDEFUN:
7966 case NARG:
7967 new->narg.backquote = copynodelist(n->narg.backquote);
7968 new->narg.text = nodeckstrdup(n->narg.text);
7969 new->narg.next = copynode(n->narg.next);
7970 break;
7971 case NTO:
Denis Vlasenko559691a2008-10-05 18:39:31 +00007972#if ENABLE_ASH_BASH_COMPAT
7973 case NTO2:
7974#endif
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007975 case NCLOBBER:
7976 case NFROM:
7977 case NFROMTO:
7978 case NAPPEND:
7979 new->nfile.fname = copynode(n->nfile.fname);
7980 new->nfile.fd = n->nfile.fd;
7981 new->nfile.next = copynode(n->nfile.next);
7982 break;
7983 case NTOFD:
7984 case NFROMFD:
7985 new->ndup.vname = copynode(n->ndup.vname);
7986 new->ndup.dupfd = n->ndup.dupfd;
7987 new->ndup.fd = n->ndup.fd;
7988 new->ndup.next = copynode(n->ndup.next);
7989 break;
7990 case NHERE:
7991 case NXHERE:
7992 new->nhere.doc = copynode(n->nhere.doc);
7993 new->nhere.fd = n->nhere.fd;
7994 new->nhere.next = copynode(n->nhere.next);
7995 break;
7996 case NNOT:
7997 new->nnot.com = copynode(n->nnot.com);
7998 break;
7999 };
8000 new->type = n->type;
8001 return new;
8002}
8003
8004/*
8005 * Make a copy of a parse tree.
8006 */
8007static struct funcnode *
8008copyfunc(union node *n)
8009{
8010 struct funcnode *f;
8011 size_t blocksize;
8012
8013 funcblocksize = offsetof(struct funcnode, n);
8014 funcstringsize = 0;
8015 calcsize(n);
8016 blocksize = funcblocksize;
8017 f = ckmalloc(blocksize + funcstringsize);
8018 funcblock = (char *) f + offsetof(struct funcnode, n);
8019 funcstring = (char *) f + blocksize;
8020 copynode(n);
8021 f->count = 0;
8022 return f;
8023}
8024
8025/*
8026 * Define a shell function.
8027 */
8028static void
8029defun(char *name, union node *func)
8030{
8031 struct cmdentry entry;
8032
8033 INT_OFF;
8034 entry.cmdtype = CMDFUNCTION;
8035 entry.u.func = copyfunc(func);
8036 addcmdentry(name, &entry);
8037 INT_ON;
8038}
8039
Denis Vlasenko4b875702009-03-19 13:30:04 +00008040/* Reasons for skipping commands (see comment on breakcmd routine) */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008041#define SKIPBREAK (1 << 0)
8042#define SKIPCONT (1 << 1)
8043#define SKIPFUNC (1 << 2)
8044#define SKIPFILE (1 << 3)
8045#define SKIPEVAL (1 << 4)
Denis Vlasenko4b875702009-03-19 13:30:04 +00008046static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008047static int skipcount; /* number of levels to skip */
8048static int funcnest; /* depth of function calls */
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +00008049static int loopnest; /* current loop nesting level */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008050
Denis Vlasenko4b875702009-03-19 13:30:04 +00008051/* Forward decl way out to parsing code - dotrap needs it */
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008052static int evalstring(char *s, int mask);
8053
Denis Vlasenko4b875702009-03-19 13:30:04 +00008054/* Called to execute a trap.
8055 * Single callsite - at the end of evaltree().
8056 * If we return non-zero, exaltree raises EXEXIT exception.
8057 *
8058 * Perhaps we should avoid entering new trap handlers
8059 * while we are executing a trap handler. [is it a TODO?]
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008060 */
8061static int
8062dotrap(void)
8063{
Denis Vlasenko4b875702009-03-19 13:30:04 +00008064 uint8_t *g;
8065 int sig;
8066 uint8_t savestatus;
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008067
8068 savestatus = exitstatus;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02008069 pending_sig = 0;
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008070 xbarrier();
8071
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008072 TRACE(("dotrap entered\n"));
Denis Vlasenko4b875702009-03-19 13:30:04 +00008073 for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
8074 int want_exexit;
8075 char *t;
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008076
Denis Vlasenko4b875702009-03-19 13:30:04 +00008077 if (*g == 0)
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008078 continue;
Denis Vlasenko4b875702009-03-19 13:30:04 +00008079 t = trap[sig];
8080 /* non-trapped SIGINT is handled separately by raise_interrupt,
8081 * don't upset it by resetting gotsig[SIGINT-1] */
8082 if (sig == SIGINT && !t)
8083 continue;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008084
8085 TRACE(("sig %d is active, will run handler '%s'\n", sig, t));
Denis Vlasenko4b875702009-03-19 13:30:04 +00008086 *g = 0;
8087 if (!t)
8088 continue;
8089 want_exexit = evalstring(t, SKIPEVAL);
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008090 exitstatus = savestatus;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008091 if (want_exexit) {
Denis Vlasenkob21f3792009-03-19 23:09:58 +00008092 TRACE(("dotrap returns %d\n", want_exexit));
Denis Vlasenko4b875702009-03-19 13:30:04 +00008093 return want_exexit;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008094 }
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008095 }
8096
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008097 TRACE(("dotrap returns 0\n"));
Denis Vlasenko991a1da2008-02-10 19:02:53 +00008098 return 0;
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008099}
8100
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00008101/* forward declarations - evaluation is fairly recursive business... */
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008102static void evalloop(union node *, int);
8103static void evalfor(union node *, int);
8104static void evalcase(union node *, int);
8105static void evalsubshell(union node *, int);
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00008106static void expredir(union node *);
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008107static void evalpipe(union node *, int);
8108static void evalcommand(union node *, int);
Eric Andersenc470f442003-07-28 09:56:35 +00008109static int evalbltin(const struct builtincmd *, int, char **);
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008110static void prehash(union node *);
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00008111
Eric Andersen62483552001-07-10 06:09:16 +00008112/*
Eric Andersenc470f442003-07-28 09:56:35 +00008113 * Evaluate a parse tree. The value is left in the global variable
8114 * exitstatus.
Eric Andersen62483552001-07-10 06:09:16 +00008115 */
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008116static void
Eric Andersenc470f442003-07-28 09:56:35 +00008117evaltree(union node *n, int flags)
Eric Andersen62483552001-07-10 06:09:16 +00008118{
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008119 struct jmploc *volatile savehandler = exception_handler;
8120 struct jmploc jmploc;
Eric Andersenc470f442003-07-28 09:56:35 +00008121 int checkexit = 0;
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008122 void (*evalfn)(union node *, int);
Eric Andersenc470f442003-07-28 09:56:35 +00008123 int status;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008124 int int_level;
8125
8126 SAVE_INT(int_level);
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008127
Eric Andersenc470f442003-07-28 09:56:35 +00008128 if (n == NULL) {
8129 TRACE(("evaltree(NULL) called\n"));
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008130 goto out1;
Eric Andersen62483552001-07-10 06:09:16 +00008131 }
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008132 TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008133
8134 exception_handler = &jmploc;
8135 {
8136 int err = setjmp(jmploc.loc);
8137 if (err) {
8138 /* if it was a signal, check for trap handlers */
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008139 if (exception_type == EXSIG) {
Denis Vlasenkob21f3792009-03-19 23:09:58 +00008140 TRACE(("exception %d (EXSIG) in evaltree, err=%d\n",
8141 exception_type, err));
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008142 goto out;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008143 }
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008144 /* continue on the way out */
Denis Vlasenkob21f3792009-03-19 23:09:58 +00008145 TRACE(("exception %d in evaltree, propagating err=%d\n",
8146 exception_type, err));
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008147 exception_handler = savehandler;
8148 longjmp(exception_handler->loc, err);
8149 }
8150 }
8151
Eric Andersenc470f442003-07-28 09:56:35 +00008152 switch (n->type) {
8153 default:
Denis Vlasenkoa7189f02006-11-17 20:29:00 +00008154#if DEBUG
Eric Andersenc470f442003-07-28 09:56:35 +00008155 out1fmt("Node type = %d\n", n->type);
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00008156 fflush(stdout);
Eric Andersenc470f442003-07-28 09:56:35 +00008157 break;
8158#endif
8159 case NNOT:
8160 evaltree(n->nnot.com, EV_TESTED);
8161 status = !exitstatus;
8162 goto setstatus;
8163 case NREDIR:
8164 expredir(n->nredir.redirect);
8165 status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
8166 if (!status) {
8167 evaltree(n->nredir.n, flags & EV_TESTED);
8168 status = exitstatus;
8169 }
Denis Vlasenko34c73c42008-08-16 11:48:02 +00008170 popredir(/*drop:*/ 0, /*restore:*/ 0 /* not sure */);
Eric Andersenc470f442003-07-28 09:56:35 +00008171 goto setstatus;
8172 case NCMD:
8173 evalfn = evalcommand;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008174 checkexit:
Eric Andersenc470f442003-07-28 09:56:35 +00008175 if (eflag && !(flags & EV_TESTED))
8176 checkexit = ~0;
8177 goto calleval;
8178 case NFOR:
8179 evalfn = evalfor;
8180 goto calleval;
8181 case NWHILE:
8182 case NUNTIL:
8183 evalfn = evalloop;
8184 goto calleval;
8185 case NSUBSHELL:
8186 case NBACKGND:
8187 evalfn = evalsubshell;
8188 goto calleval;
8189 case NPIPE:
8190 evalfn = evalpipe;
8191 goto checkexit;
8192 case NCASE:
8193 evalfn = evalcase;
8194 goto calleval;
8195 case NAND:
8196 case NOR:
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008197 case NSEMI: {
8198
Eric Andersenc470f442003-07-28 09:56:35 +00008199#if NAND + 1 != NOR
8200#error NAND + 1 != NOR
8201#endif
8202#if NOR + 1 != NSEMI
8203#error NOR + 1 != NSEMI
8204#endif
Denis Vlasenko87d5fd92008-07-26 13:48:35 +00008205 unsigned is_or = n->type - NAND;
Eric Andersenc470f442003-07-28 09:56:35 +00008206 evaltree(
8207 n->nbinary.ch1,
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008208 (flags | ((is_or >> 1) - 1)) & EV_TESTED
Eric Andersenc470f442003-07-28 09:56:35 +00008209 );
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008210 if (!exitstatus == is_or)
Eric Andersenc470f442003-07-28 09:56:35 +00008211 break;
8212 if (!evalskip) {
8213 n = n->nbinary.ch2;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008214 evaln:
Eric Andersenc470f442003-07-28 09:56:35 +00008215 evalfn = evaltree;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008216 calleval:
Eric Andersenc470f442003-07-28 09:56:35 +00008217 evalfn(n, flags);
8218 break;
8219 }
8220 break;
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008221 }
Eric Andersenc470f442003-07-28 09:56:35 +00008222 case NIF:
8223 evaltree(n->nif.test, EV_TESTED);
8224 if (evalskip)
8225 break;
8226 if (exitstatus == 0) {
8227 n = n->nif.ifpart;
8228 goto evaln;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008229 }
8230 if (n->nif.elsepart) {
Eric Andersenc470f442003-07-28 09:56:35 +00008231 n = n->nif.elsepart;
8232 goto evaln;
8233 }
8234 goto success;
8235 case NDEFUN:
8236 defun(n->narg.text, n->narg.next);
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008237 success:
Eric Andersenc470f442003-07-28 09:56:35 +00008238 status = 0;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008239 setstatus:
Eric Andersenc470f442003-07-28 09:56:35 +00008240 exitstatus = status;
8241 break;
8242 }
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008243
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008244 out:
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008245 exception_handler = savehandler;
8246 out1:
8247 if (checkexit & exitstatus)
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00008248 evalskip |= SKIPEVAL;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02008249 else if (pending_sig && dotrap())
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00008250 goto exexit;
8251
8252 if (flags & EV_EXIT) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008253 exexit:
Denis Vlasenkob012b102007-02-19 22:43:01 +00008254 raise_exception(EXEXIT);
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00008255 }
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008256
8257 RESTORE_INT(int_level);
8258 TRACE(("leaving evaltree (no interrupts)\n"));
Eric Andersen62483552001-07-10 06:09:16 +00008259}
8260
Eric Andersenc470f442003-07-28 09:56:35 +00008261#if !defined(__alpha__) || (defined(__GNUC__) && __GNUC__ >= 3)
8262static
8263#endif
8264void evaltreenr(union node *, int) __attribute__ ((alias("evaltree"),__noreturn__));
8265
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008266static void
Eric Andersenc470f442003-07-28 09:56:35 +00008267evalloop(union node *n, int flags)
Eric Andersencb57d552001-06-28 07:25:16 +00008268{
8269 int status;
8270
8271 loopnest++;
8272 status = 0;
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008273 flags &= EV_TESTED;
Eric Andersencb57d552001-06-28 07:25:16 +00008274 for (;;) {
Eric Andersenc470f442003-07-28 09:56:35 +00008275 int i;
8276
Eric Andersencb57d552001-06-28 07:25:16 +00008277 evaltree(n->nbinary.ch1, EV_TESTED);
8278 if (evalskip) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008279 skipping:
8280 if (evalskip == SKIPCONT && --skipcount <= 0) {
Eric Andersencb57d552001-06-28 07:25:16 +00008281 evalskip = 0;
8282 continue;
8283 }
8284 if (evalskip == SKIPBREAK && --skipcount <= 0)
8285 evalskip = 0;
8286 break;
8287 }
Eric Andersenc470f442003-07-28 09:56:35 +00008288 i = exitstatus;
8289 if (n->type != NWHILE)
8290 i = !i;
8291 if (i != 0)
8292 break;
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008293 evaltree(n->nbinary.ch2, flags);
Eric Andersencb57d552001-06-28 07:25:16 +00008294 status = exitstatus;
8295 if (evalskip)
8296 goto skipping;
8297 }
8298 loopnest--;
8299 exitstatus = status;
8300}
8301
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008302static void
Eric Andersenc470f442003-07-28 09:56:35 +00008303evalfor(union node *n, int flags)
Eric Andersencb57d552001-06-28 07:25:16 +00008304{
8305 struct arglist arglist;
8306 union node *argp;
8307 struct strlist *sp;
8308 struct stackmark smark;
8309
8310 setstackmark(&smark);
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00008311 arglist.list = NULL;
Eric Andersencb57d552001-06-28 07:25:16 +00008312 arglist.lastp = &arglist.list;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008313 for (argp = n->nfor.args; argp; argp = argp->narg.next) {
Eric Andersencb57d552001-06-28 07:25:16 +00008314 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE | EXP_RECORD);
Eric Andersenc470f442003-07-28 09:56:35 +00008315 /* XXX */
Eric Andersencb57d552001-06-28 07:25:16 +00008316 if (evalskip)
8317 goto out;
8318 }
8319 *arglist.lastp = NULL;
8320
8321 exitstatus = 0;
8322 loopnest++;
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008323 flags &= EV_TESTED;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008324 for (sp = arglist.list; sp; sp = sp->next) {
Eric Andersencb57d552001-06-28 07:25:16 +00008325 setvar(n->nfor.var, sp->text, 0);
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008326 evaltree(n->nfor.body, flags);
Eric Andersencb57d552001-06-28 07:25:16 +00008327 if (evalskip) {
8328 if (evalskip == SKIPCONT && --skipcount <= 0) {
8329 evalskip = 0;
8330 continue;
8331 }
8332 if (evalskip == SKIPBREAK && --skipcount <= 0)
8333 evalskip = 0;
8334 break;
8335 }
8336 }
8337 loopnest--;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008338 out:
Eric Andersencb57d552001-06-28 07:25:16 +00008339 popstackmark(&smark);
8340}
8341
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008342static void
Eric Andersenc470f442003-07-28 09:56:35 +00008343evalcase(union node *n, int flags)
Eric Andersencb57d552001-06-28 07:25:16 +00008344{
8345 union node *cp;
8346 union node *patp;
8347 struct arglist arglist;
8348 struct stackmark smark;
8349
8350 setstackmark(&smark);
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00008351 arglist.list = NULL;
Eric Andersencb57d552001-06-28 07:25:16 +00008352 arglist.lastp = &arglist.list;
Eric Andersencb57d552001-06-28 07:25:16 +00008353 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
Eric Andersenc470f442003-07-28 09:56:35 +00008354 exitstatus = 0;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008355 for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
8356 for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
Eric Andersencb57d552001-06-28 07:25:16 +00008357 if (casematch(patp, arglist.list->text)) {
8358 if (evalskip == 0) {
8359 evaltree(cp->nclist.body, flags);
8360 }
8361 goto out;
8362 }
8363 }
8364 }
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008365 out:
Eric Andersencb57d552001-06-28 07:25:16 +00008366 popstackmark(&smark);
8367}
8368
Eric Andersenc470f442003-07-28 09:56:35 +00008369/*
8370 * Kick off a subshell to evaluate a tree.
8371 */
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008372static void
Eric Andersenc470f442003-07-28 09:56:35 +00008373evalsubshell(union node *n, int flags)
8374{
8375 struct job *jp;
8376 int backgnd = (n->type == NBACKGND);
8377 int status;
8378
8379 expredir(n->nredir.redirect);
8380 if (!backgnd && flags & EV_EXIT && !trap[0])
8381 goto nofork;
Denis Vlasenkob012b102007-02-19 22:43:01 +00008382 INT_OFF;
Denis Vlasenko68404f12008-03-17 09:00:54 +00008383 jp = makejob(/*n,*/ 1);
Eric Andersenc470f442003-07-28 09:56:35 +00008384 if (forkshell(jp, n, backgnd) == 0) {
Denis Vlasenkob012b102007-02-19 22:43:01 +00008385 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00008386 flags |= EV_EXIT;
8387 if (backgnd)
8388 flags &=~ EV_TESTED;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00008389 nofork:
Eric Andersenc470f442003-07-28 09:56:35 +00008390 redirect(n->nredir.redirect, 0);
8391 evaltreenr(n->nredir.n, flags);
8392 /* never returns */
8393 }
8394 status = 0;
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00008395 if (!backgnd)
Eric Andersenc470f442003-07-28 09:56:35 +00008396 status = waitforjob(jp);
8397 exitstatus = status;
Denis Vlasenkob012b102007-02-19 22:43:01 +00008398 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00008399}
8400
Eric Andersenc470f442003-07-28 09:56:35 +00008401/*
8402 * Compute the names of the files in a redirection list.
8403 */
Denis Vlasenko99eb8502007-02-23 21:09:49 +00008404static void fixredir(union node *, const char *, int);
Eric Andersenc470f442003-07-28 09:56:35 +00008405static void
8406expredir(union node *n)
8407{
8408 union node *redir;
8409
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008410 for (redir = n; redir; redir = redir->nfile.next) {
Eric Andersenc470f442003-07-28 09:56:35 +00008411 struct arglist fn;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008412
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00008413 fn.list = NULL;
Eric Andersenc470f442003-07-28 09:56:35 +00008414 fn.lastp = &fn.list;
8415 switch (redir->type) {
8416 case NFROMTO:
8417 case NFROM:
8418 case NTO:
Denis Vlasenko559691a2008-10-05 18:39:31 +00008419#if ENABLE_ASH_BASH_COMPAT
8420 case NTO2:
8421#endif
Eric Andersenc470f442003-07-28 09:56:35 +00008422 case NCLOBBER:
8423 case NAPPEND:
8424 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
Denis Vlasenko559691a2008-10-05 18:39:31 +00008425#if ENABLE_ASH_BASH_COMPAT
8426 store_expfname:
8427#endif
Eric Andersenc470f442003-07-28 09:56:35 +00008428 redir->nfile.expfname = fn.list->text;
8429 break;
8430 case NFROMFD:
Denis Vlasenko559691a2008-10-05 18:39:31 +00008431 case NTOFD: /* >& */
Eric Andersenc470f442003-07-28 09:56:35 +00008432 if (redir->ndup.vname) {
8433 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008434 if (fn.list == NULL)
Denis Vlasenkob012b102007-02-19 22:43:01 +00008435 ash_msg_and_raise_error("redir error");
Denis Vlasenko559691a2008-10-05 18:39:31 +00008436#if ENABLE_ASH_BASH_COMPAT
8437//FIXME: we used expandarg with different args!
8438 if (!isdigit_str9(fn.list->text)) {
8439 /* >&file, not >&fd */
8440 if (redir->nfile.fd != 1) /* 123>&file - BAD */
8441 ash_msg_and_raise_error("redir error");
8442 redir->type = NTO2;
8443 goto store_expfname;
8444 }
8445#endif
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008446 fixredir(redir, fn.list->text, 1);
Eric Andersenc470f442003-07-28 09:56:35 +00008447 }
8448 break;
8449 }
8450 }
8451}
8452
Eric Andersencb57d552001-06-28 07:25:16 +00008453/*
Eric Andersencb57d552001-06-28 07:25:16 +00008454 * Evaluate a pipeline. All the processes in the pipeline are children
8455 * of the process creating the pipeline. (This differs from some versions
8456 * of the shell, which make the last process in a pipeline the parent
8457 * of all the rest.)
8458 */
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008459static void
Eric Andersenc470f442003-07-28 09:56:35 +00008460evalpipe(union node *n, int flags)
Eric Andersencb57d552001-06-28 07:25:16 +00008461{
8462 struct job *jp;
8463 struct nodelist *lp;
8464 int pipelen;
8465 int prevfd;
8466 int pip[2];
8467
Eric Andersenc470f442003-07-28 09:56:35 +00008468 TRACE(("evalpipe(0x%lx) called\n", (long)n));
Eric Andersencb57d552001-06-28 07:25:16 +00008469 pipelen = 0;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008470 for (lp = n->npipe.cmdlist; lp; lp = lp->next)
Eric Andersencb57d552001-06-28 07:25:16 +00008471 pipelen++;
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008472 flags |= EV_EXIT;
Denis Vlasenkob012b102007-02-19 22:43:01 +00008473 INT_OFF;
Denis Vlasenko68404f12008-03-17 09:00:54 +00008474 jp = makejob(/*n,*/ pipelen);
Eric Andersencb57d552001-06-28 07:25:16 +00008475 prevfd = -1;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008476 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008477 prehash(lp->n);
Eric Andersencb57d552001-06-28 07:25:16 +00008478 pip[1] = -1;
8479 if (lp->next) {
8480 if (pipe(pip) < 0) {
8481 close(prevfd);
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00008482 ash_msg_and_raise_error("pipe call failed");
Eric Andersencb57d552001-06-28 07:25:16 +00008483 }
8484 }
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00008485 if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
Denis Vlasenkob012b102007-02-19 22:43:01 +00008486 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00008487 if (pip[1] >= 0) {
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008488 close(pip[0]);
Eric Andersencb57d552001-06-28 07:25:16 +00008489 }
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008490 if (prevfd > 0) {
8491 dup2(prevfd, 0);
8492 close(prevfd);
8493 }
8494 if (pip[1] > 1) {
8495 dup2(pip[1], 1);
8496 close(pip[1]);
8497 }
Eric Andersenc470f442003-07-28 09:56:35 +00008498 evaltreenr(lp->n, flags);
8499 /* never returns */
Eric Andersencb57d552001-06-28 07:25:16 +00008500 }
8501 if (prevfd >= 0)
8502 close(prevfd);
8503 prevfd = pip[0];
Denis Vlasenkob9e70dd2009-03-20 01:24:08 +00008504 /* Don't want to trigger debugging */
8505 if (pip[1] != -1)
8506 close(pip[1]);
Eric Andersencb57d552001-06-28 07:25:16 +00008507 }
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00008508 if (n->npipe.pipe_backgnd == 0) {
Eric Andersencb57d552001-06-28 07:25:16 +00008509 exitstatus = waitforjob(jp);
8510 TRACE(("evalpipe: job done exit status %d\n", exitstatus));
Eric Andersencb57d552001-06-28 07:25:16 +00008511 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00008512 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00008513}
8514
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008515/*
8516 * Controls whether the shell is interactive or not.
8517 */
8518static void
8519setinteractive(int on)
8520{
Denis Vlasenkob07a4962008-06-22 13:16:23 +00008521 static smallint is_interactive;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008522
8523 if (++on == is_interactive)
8524 return;
8525 is_interactive = on;
8526 setsignal(SIGINT);
8527 setsignal(SIGQUIT);
8528 setsignal(SIGTERM);
8529#if !ENABLE_FEATURE_SH_EXTRA_QUIET
8530 if (is_interactive > 1) {
8531 /* Looks like they want an interactive shell */
Denis Vlasenkoca525b42007-06-13 12:27:17 +00008532 static smallint did_banner;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008533
Denis Vlasenkoca525b42007-06-13 12:27:17 +00008534 if (!did_banner) {
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008535 out1fmt(
8536 "\n\n"
Denis Vlasenkoca525b42007-06-13 12:27:17 +00008537 "%s built-in shell (ash)\n"
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008538 "Enter 'help' for a list of built-in commands."
8539 "\n\n",
Denis Vlasenkoca525b42007-06-13 12:27:17 +00008540 bb_banner);
8541 did_banner = 1;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008542 }
8543 }
8544#endif
8545}
8546
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008547static void
8548optschanged(void)
8549{
8550#if DEBUG
8551 opentrace();
8552#endif
8553 setinteractive(iflag);
8554 setjobctl(mflag);
Denis Vlasenkob07a4962008-06-22 13:16:23 +00008555#if ENABLE_FEATURE_EDITING_VI
8556 if (viflag)
8557 line_input_state->flags |= VI_MODE;
8558 else
8559 line_input_state->flags &= ~VI_MODE;
8560#else
8561 viflag = 0; /* forcibly keep the option off */
8562#endif
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008563}
8564
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008565static struct localvar *localvars;
8566
8567/*
8568 * Called after a function returns.
8569 * Interrupts must be off.
8570 */
8571static void
8572poplocalvars(void)
8573{
8574 struct localvar *lvp;
8575 struct var *vp;
8576
8577 while ((lvp = localvars) != NULL) {
8578 localvars = lvp->next;
8579 vp = lvp->vp;
Denys Vlasenko883cea42009-07-11 15:31:59 +02008580 TRACE(("poplocalvar %s\n", vp ? vp->text : "-"));
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008581 if (vp == NULL) { /* $- saved */
8582 memcpy(optlist, lvp->text, sizeof(optlist));
8583 free((char*)lvp->text);
8584 optschanged();
8585 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
8586 unsetvar(vp->text);
8587 } else {
8588 if (vp->func)
8589 (*vp->func)(strchrnul(lvp->text, '=') + 1);
8590 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
8591 free((char*)vp->text);
8592 vp->flags = lvp->flags;
8593 vp->text = lvp->text;
8594 }
8595 free(lvp);
8596 }
8597}
8598
8599static int
8600evalfun(struct funcnode *func, int argc, char **argv, int flags)
8601{
8602 volatile struct shparam saveparam;
8603 struct localvar *volatile savelocalvars;
8604 struct jmploc *volatile savehandler;
8605 struct jmploc jmploc;
8606 int e;
8607
8608 saveparam = shellparam;
8609 savelocalvars = localvars;
8610 e = setjmp(jmploc.loc);
8611 if (e) {
8612 goto funcdone;
8613 }
8614 INT_OFF;
8615 savehandler = exception_handler;
8616 exception_handler = &jmploc;
8617 localvars = NULL;
Denis Vlasenko01631112007-12-16 17:20:38 +00008618 shellparam.malloced = 0;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008619 func->count++;
8620 funcnest++;
8621 INT_ON;
8622 shellparam.nparam = argc - 1;
8623 shellparam.p = argv + 1;
8624#if ENABLE_ASH_GETOPTS
8625 shellparam.optind = 1;
8626 shellparam.optoff = -1;
8627#endif
8628 evaltree(&func->n, flags & EV_TESTED);
Denis Vlasenko01631112007-12-16 17:20:38 +00008629 funcdone:
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008630 INT_OFF;
8631 funcnest--;
8632 freefunc(func);
8633 poplocalvars();
8634 localvars = savelocalvars;
8635 freeparam(&shellparam);
8636 shellparam = saveparam;
8637 exception_handler = savehandler;
8638 INT_ON;
8639 evalskip &= ~SKIPFUNC;
8640 return e;
8641}
8642
Denis Vlasenko131ae172007-02-18 13:00:19 +00008643#if ENABLE_ASH_CMDCMD
Denis Vlasenkoaa744452007-02-23 01:04:22 +00008644static char **
8645parse_command_args(char **argv, const char **path)
Eric Andersenc470f442003-07-28 09:56:35 +00008646{
8647 char *cp, c;
8648
8649 for (;;) {
8650 cp = *++argv;
8651 if (!cp)
8652 return 0;
8653 if (*cp++ != '-')
8654 break;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008655 c = *cp++;
8656 if (!c)
Eric Andersenc470f442003-07-28 09:56:35 +00008657 break;
8658 if (c == '-' && !*cp) {
8659 argv++;
8660 break;
8661 }
8662 do {
8663 switch (c) {
8664 case 'p':
Denis Vlasenkof5f75c52007-06-12 22:35:19 +00008665 *path = bb_default_path;
Eric Andersenc470f442003-07-28 09:56:35 +00008666 break;
8667 default:
8668 /* run 'typecmd' for other options */
8669 return 0;
8670 }
Denis Vlasenko9650f362007-02-23 01:04:37 +00008671 c = *cp++;
8672 } while (c);
Eric Andersenc470f442003-07-28 09:56:35 +00008673 }
8674 return argv;
8675}
8676#endif
8677
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008678/*
8679 * Make a variable a local variable. When a variable is made local, it's
8680 * value and flags are saved in a localvar structure. The saved values
8681 * will be restored when the shell function returns. We handle the name
8682 * "-" as a special case.
8683 */
8684static void
8685mklocal(char *name)
8686{
8687 struct localvar *lvp;
8688 struct var **vpp;
8689 struct var *vp;
8690
8691 INT_OFF;
Denis Vlasenko838ffd52008-02-21 04:32:08 +00008692 lvp = ckzalloc(sizeof(struct localvar));
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008693 if (LONE_DASH(name)) {
8694 char *p;
8695 p = ckmalloc(sizeof(optlist));
8696 lvp->text = memcpy(p, optlist, sizeof(optlist));
8697 vp = NULL;
8698 } else {
8699 char *eq;
8700
8701 vpp = hashvar(name);
8702 vp = *findvar(vpp, name);
8703 eq = strchr(name, '=');
8704 if (vp == NULL) {
8705 if (eq)
8706 setvareq(name, VSTRFIXED);
8707 else
8708 setvar(name, NULL, VSTRFIXED);
8709 vp = *vpp; /* the new variable */
8710 lvp->flags = VUNSET;
8711 } else {
8712 lvp->text = vp->text;
8713 lvp->flags = vp->flags;
8714 vp->flags |= VSTRFIXED|VTEXTFIXED;
8715 if (eq)
8716 setvareq(name, 0);
8717 }
8718 }
8719 lvp->vp = vp;
8720 lvp->next = localvars;
8721 localvars = lvp;
8722 INT_ON;
8723}
8724
8725/*
8726 * The "local" command.
8727 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008728static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008729localcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008730{
8731 char *name;
8732
8733 argv = argptr;
8734 while ((name = *argv++) != NULL) {
8735 mklocal(name);
8736 }
8737 return 0;
8738}
8739
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008740static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008741falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008742{
8743 return 1;
8744}
8745
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008746static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008747truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008748{
8749 return 0;
8750}
8751
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008752static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008753execcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008754{
Denis Vlasenko68404f12008-03-17 09:00:54 +00008755 if (argv[1]) {
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008756 iflag = 0; /* exit on error */
8757 mflag = 0;
8758 optschanged();
8759 shellexec(argv + 1, pathval(), 0);
8760 }
8761 return 0;
8762}
8763
8764/*
8765 * The return command.
8766 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008767static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008768returncmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008769{
8770 /*
8771 * If called outside a function, do what ksh does;
8772 * skip the rest of the file.
8773 */
8774 evalskip = funcnest ? SKIPFUNC : SKIPFILE;
8775 return argv[1] ? number(argv[1]) : exitstatus;
8776}
8777
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008778/* Forward declarations for builtintab[] */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008779static int breakcmd(int, char **) FAST_FUNC;
8780static int dotcmd(int, char **) FAST_FUNC;
8781static int evalcmd(int, char **) FAST_FUNC;
8782static int exitcmd(int, char **) FAST_FUNC;
8783static int exportcmd(int, char **) FAST_FUNC;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008784#if ENABLE_ASH_GETOPTS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008785static int getoptscmd(int, char **) FAST_FUNC;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008786#endif
Denis Vlasenko52764022007-02-24 13:42:56 +00008787#if !ENABLE_FEATURE_SH_EXTRA_QUIET
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008788static int helpcmd(int, char **) FAST_FUNC;
Denis Vlasenko52764022007-02-24 13:42:56 +00008789#endif
Mike Frysinger98c52642009-04-02 10:02:37 +00008790#if ENABLE_SH_MATH_SUPPORT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008791static int letcmd(int, char **) FAST_FUNC;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008792#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008793static int readcmd(int, char **) FAST_FUNC;
8794static int setcmd(int, char **) FAST_FUNC;
8795static int shiftcmd(int, char **) FAST_FUNC;
8796static int timescmd(int, char **) FAST_FUNC;
8797static int trapcmd(int, char **) FAST_FUNC;
8798static int umaskcmd(int, char **) FAST_FUNC;
8799static int unsetcmd(int, char **) FAST_FUNC;
8800static int ulimitcmd(int, char **) FAST_FUNC;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008801
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008802#define BUILTIN_NOSPEC "0"
8803#define BUILTIN_SPECIAL "1"
8804#define BUILTIN_REGULAR "2"
8805#define BUILTIN_SPEC_REG "3"
8806#define BUILTIN_ASSIGN "4"
8807#define BUILTIN_SPEC_ASSG "5"
8808#define BUILTIN_REG_ASSG "6"
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008809#define BUILTIN_SPEC_REG_ASSG "7"
8810
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008811/* Stubs for calling non-FAST_FUNC's */
Denys Vlasenko2634bf32009-06-09 18:40:07 +02008812#if ENABLE_ASH_BUILTIN_ECHO
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008813static int FAST_FUNC echocmd(int argc, char **argv) { return echo_main(argc, argv); }
Denys Vlasenko2634bf32009-06-09 18:40:07 +02008814#endif
8815#if ENABLE_ASH_BUILTIN_PRINTF
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008816static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
Denys Vlasenko2634bf32009-06-09 18:40:07 +02008817#endif
8818#if ENABLE_ASH_BUILTIN_TEST
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008819static int FAST_FUNC testcmd(int argc, char **argv) { return test_main(argc, argv); }
Denys Vlasenko2634bf32009-06-09 18:40:07 +02008820#endif
Denis Vlasenko468aea22008-04-01 14:47:57 +00008821
Denis Vlasenkof7d56652008-03-25 05:51:41 +00008822/* Keep these in proper order since it is searched via bsearch() */
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008823static const struct builtincmd builtintab[] = {
8824 { BUILTIN_SPEC_REG ".", dotcmd },
8825 { BUILTIN_SPEC_REG ":", truecmd },
8826#if ENABLE_ASH_BUILTIN_TEST
Denis Vlasenkocd2663f2008-06-01 22:36:39 +00008827 { BUILTIN_REGULAR "[", testcmd },
Denis Vlasenko80591b02008-03-25 07:49:43 +00008828#if ENABLE_ASH_BASH_COMPAT
Denis Vlasenkocd2663f2008-06-01 22:36:39 +00008829 { BUILTIN_REGULAR "[[", testcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008830#endif
Denis Vlasenko80591b02008-03-25 07:49:43 +00008831#endif
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008832#if ENABLE_ASH_ALIAS
8833 { BUILTIN_REG_ASSG "alias", aliascmd },
8834#endif
8835#if JOBS
8836 { BUILTIN_REGULAR "bg", fg_bgcmd },
8837#endif
8838 { BUILTIN_SPEC_REG "break", breakcmd },
8839 { BUILTIN_REGULAR "cd", cdcmd },
8840 { BUILTIN_NOSPEC "chdir", cdcmd },
8841#if ENABLE_ASH_CMDCMD
8842 { BUILTIN_REGULAR "command", commandcmd },
8843#endif
8844 { BUILTIN_SPEC_REG "continue", breakcmd },
8845#if ENABLE_ASH_BUILTIN_ECHO
8846 { BUILTIN_REGULAR "echo", echocmd },
8847#endif
8848 { BUILTIN_SPEC_REG "eval", evalcmd },
8849 { BUILTIN_SPEC_REG "exec", execcmd },
8850 { BUILTIN_SPEC_REG "exit", exitcmd },
8851 { BUILTIN_SPEC_REG_ASSG "export", exportcmd },
8852 { BUILTIN_REGULAR "false", falsecmd },
8853#if JOBS
8854 { BUILTIN_REGULAR "fg", fg_bgcmd },
8855#endif
8856#if ENABLE_ASH_GETOPTS
8857 { BUILTIN_REGULAR "getopts", getoptscmd },
8858#endif
8859 { BUILTIN_NOSPEC "hash", hashcmd },
8860#if !ENABLE_FEATURE_SH_EXTRA_QUIET
8861 { BUILTIN_NOSPEC "help", helpcmd },
8862#endif
8863#if JOBS
8864 { BUILTIN_REGULAR "jobs", jobscmd },
8865 { BUILTIN_REGULAR "kill", killcmd },
8866#endif
Mike Frysinger98c52642009-04-02 10:02:37 +00008867#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008868 { BUILTIN_NOSPEC "let", letcmd },
8869#endif
8870 { BUILTIN_ASSIGN "local", localcmd },
Denis Vlasenkocd2663f2008-06-01 22:36:39 +00008871#if ENABLE_ASH_BUILTIN_PRINTF
8872 { BUILTIN_REGULAR "printf", printfcmd },
8873#endif
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008874 { BUILTIN_NOSPEC "pwd", pwdcmd },
8875 { BUILTIN_REGULAR "read", readcmd },
8876 { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
8877 { BUILTIN_SPEC_REG "return", returncmd },
8878 { BUILTIN_SPEC_REG "set", setcmd },
8879 { BUILTIN_SPEC_REG "shift", shiftcmd },
8880 { BUILTIN_SPEC_REG "source", dotcmd },
8881#if ENABLE_ASH_BUILTIN_TEST
Denis Vlasenkocd2663f2008-06-01 22:36:39 +00008882 { BUILTIN_REGULAR "test", testcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008883#endif
8884 { BUILTIN_SPEC_REG "times", timescmd },
8885 { BUILTIN_SPEC_REG "trap", trapcmd },
8886 { BUILTIN_REGULAR "true", truecmd },
8887 { BUILTIN_NOSPEC "type", typecmd },
8888 { BUILTIN_NOSPEC "ulimit", ulimitcmd },
8889 { BUILTIN_REGULAR "umask", umaskcmd },
8890#if ENABLE_ASH_ALIAS
8891 { BUILTIN_REGULAR "unalias", unaliascmd },
8892#endif
8893 { BUILTIN_SPEC_REG "unset", unsetcmd },
8894 { BUILTIN_REGULAR "wait", waitcmd },
8895};
8896
Denis Vlasenko80591b02008-03-25 07:49:43 +00008897/* Should match the above table! */
8898#define COMMANDCMD (builtintab + \
8899 2 + \
8900 1 * ENABLE_ASH_BUILTIN_TEST + \
8901 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
8902 1 * ENABLE_ASH_ALIAS + \
8903 1 * ENABLE_ASH_JOB_CONTROL + \
8904 3)
8905#define EXECCMD (builtintab + \
8906 2 + \
8907 1 * ENABLE_ASH_BUILTIN_TEST + \
8908 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
8909 1 * ENABLE_ASH_ALIAS + \
8910 1 * ENABLE_ASH_JOB_CONTROL + \
8911 3 + \
8912 1 * ENABLE_ASH_CMDCMD + \
8913 1 + \
8914 ENABLE_ASH_BUILTIN_ECHO + \
8915 1)
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008916
8917/*
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008918 * Search the table of builtin commands.
8919 */
8920static struct builtincmd *
8921find_builtin(const char *name)
8922{
8923 struct builtincmd *bp;
8924
8925 bp = bsearch(
Denis Vlasenko80b8b392007-06-25 10:55:35 +00008926 name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008927 pstrcmp
8928 );
8929 return bp;
8930}
8931
8932/*
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008933 * Execute a simple command.
8934 */
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008935static int
8936isassignment(const char *p)
Paul Foxc3850c82005-07-20 18:23:39 +00008937{
8938 const char *q = endofname(p);
8939 if (p == q)
8940 return 0;
8941 return *q == '=';
8942}
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008943static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008944bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008945{
8946 /* Preserve exitstatus of a previous possible redirection
8947 * as POSIX mandates */
8948 return back_exitstatus;
8949}
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008950static void
Eric Andersenc470f442003-07-28 09:56:35 +00008951evalcommand(union node *cmd, int flags)
8952{
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00008953 static const struct builtincmd null_bltin = {
8954 "\0\0", bltincmd /* why three NULs? */
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008955 };
Eric Andersenc470f442003-07-28 09:56:35 +00008956 struct stackmark smark;
8957 union node *argp;
8958 struct arglist arglist;
8959 struct arglist varlist;
8960 char **argv;
8961 int argc;
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00008962 const struct strlist *sp;
Eric Andersenc470f442003-07-28 09:56:35 +00008963 struct cmdentry cmdentry;
8964 struct job *jp;
8965 char *lastarg;
8966 const char *path;
8967 int spclbltin;
Eric Andersenc470f442003-07-28 09:56:35 +00008968 int status;
8969 char **nargv;
Paul Foxc3850c82005-07-20 18:23:39 +00008970 struct builtincmd *bcmd;
Denis Vlasenko34c73c42008-08-16 11:48:02 +00008971 smallint cmd_is_exec;
8972 smallint pseudovarflag = 0;
Eric Andersenc470f442003-07-28 09:56:35 +00008973
8974 /* First expand the arguments. */
8975 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
8976 setstackmark(&smark);
8977 back_exitstatus = 0;
8978
8979 cmdentry.cmdtype = CMDBUILTIN;
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00008980 cmdentry.u.cmd = &null_bltin;
Eric Andersenc470f442003-07-28 09:56:35 +00008981 varlist.lastp = &varlist.list;
8982 *varlist.lastp = NULL;
8983 arglist.lastp = &arglist.list;
8984 *arglist.lastp = NULL;
8985
8986 argc = 0;
Denis Vlasenkob012b102007-02-19 22:43:01 +00008987 if (cmd->ncmd.args) {
Paul Foxc3850c82005-07-20 18:23:39 +00008988 bcmd = find_builtin(cmd->ncmd.args->narg.text);
8989 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
8990 }
8991
Eric Andersenc470f442003-07-28 09:56:35 +00008992 for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
8993 struct strlist **spp;
8994
8995 spp = arglist.lastp;
"Vladimir N. Oleynik"bef14d72005-09-05 13:25:11 +00008996 if (pseudovarflag && isassignment(argp->narg.text))
Paul Foxc3850c82005-07-20 18:23:39 +00008997 expandarg(argp, &arglist, EXP_VARTILDE);
8998 else
8999 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
9000
Eric Andersenc470f442003-07-28 09:56:35 +00009001 for (sp = *spp; sp; sp = sp->next)
9002 argc++;
9003 }
9004
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +00009005 argv = nargv = stalloc(sizeof(char *) * (argc + 1));
Denis Vlasenko2da584f2007-02-19 22:44:05 +00009006 for (sp = arglist.list; sp; sp = sp->next) {
Eric Andersenc470f442003-07-28 09:56:35 +00009007 TRACE(("evalcommand arg: %s\n", sp->text));
9008 *nargv++ = sp->text;
9009 }
9010 *nargv = NULL;
9011
9012 lastarg = NULL;
9013 if (iflag && funcnest == 0 && argc > 0)
9014 lastarg = nargv[-1];
9015
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009016 preverrout_fd = 2;
Eric Andersenc470f442003-07-28 09:56:35 +00009017 expredir(cmd->ncmd.redirect);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009018 status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
Eric Andersenc470f442003-07-28 09:56:35 +00009019
9020 path = vpath.text;
9021 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
9022 struct strlist **spp;
9023 char *p;
9024
9025 spp = varlist.lastp;
9026 expandarg(argp, &varlist, EXP_VARTILDE);
9027
9028 /*
9029 * Modify the command lookup path, if a PATH= assignment
9030 * is present
9031 */
9032 p = (*spp)->text;
9033 if (varequal(p, path))
9034 path = p;
9035 }
9036
9037 /* Print the command if xflag is set. */
9038 if (xflag) {
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009039 int n;
9040 const char *p = " %s";
Eric Andersenc470f442003-07-28 09:56:35 +00009041
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009042 p++;
Denis Vlasenko0de37e12007-10-17 11:08:53 +00009043 fdprintf(preverrout_fd, p, expandstr(ps4val()));
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009044
9045 sp = varlist.list;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +00009046 for (n = 0; n < 2; n++) {
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009047 while (sp) {
Denis Vlasenko0de37e12007-10-17 11:08:53 +00009048 fdprintf(preverrout_fd, p, sp->text);
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009049 sp = sp->next;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +00009050 if (*p == '%') {
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009051 p--;
9052 }
9053 }
9054 sp = arglist.list;
9055 }
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00009056 safe_write(preverrout_fd, "\n", 1);
Eric Andersenc470f442003-07-28 09:56:35 +00009057 }
9058
9059 cmd_is_exec = 0;
9060 spclbltin = -1;
9061
9062 /* Now locate the command. */
9063 if (argc) {
9064 const char *oldpath;
9065 int cmd_flag = DO_ERR;
9066
9067 path += 5;
9068 oldpath = path;
9069 for (;;) {
9070 find_command(argv[0], &cmdentry, cmd_flag, path);
9071 if (cmdentry.cmdtype == CMDUNKNOWN) {
Denis Vlasenkob012b102007-02-19 22:43:01 +00009072 flush_stderr();
Denis Vlasenko6514c5e2008-07-24 13:41:37 +00009073 status = 127;
Eric Andersenc470f442003-07-28 09:56:35 +00009074 goto bail;
9075 }
9076
9077 /* implement bltin and command here */
9078 if (cmdentry.cmdtype != CMDBUILTIN)
9079 break;
9080 if (spclbltin < 0)
9081 spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
9082 if (cmdentry.u.cmd == EXECCMD)
Denis Vlasenko34c73c42008-08-16 11:48:02 +00009083 cmd_is_exec = 1;
Denis Vlasenko131ae172007-02-18 13:00:19 +00009084#if ENABLE_ASH_CMDCMD
Eric Andersenc470f442003-07-28 09:56:35 +00009085 if (cmdentry.u.cmd == COMMANDCMD) {
Eric Andersenc470f442003-07-28 09:56:35 +00009086 path = oldpath;
9087 nargv = parse_command_args(argv, &path);
9088 if (!nargv)
9089 break;
9090 argc -= nargv - argv;
9091 argv = nargv;
9092 cmd_flag |= DO_NOFUNC;
9093 } else
9094#endif
9095 break;
9096 }
9097 }
9098
9099 if (status) {
9100 /* We have a redirection error. */
9101 if (spclbltin > 0)
Denis Vlasenkob012b102007-02-19 22:43:01 +00009102 raise_exception(EXERROR);
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009103 bail:
Eric Andersenc470f442003-07-28 09:56:35 +00009104 exitstatus = status;
9105 goto out;
9106 }
9107
9108 /* Execute the command. */
9109 switch (cmdentry.cmdtype) {
9110 default:
Denis Vlasenkobe54d6b2008-10-27 14:25:52 +00009111
Denis Vlasenko9bc80d72008-04-12 20:07:53 +00009112#if ENABLE_FEATURE_SH_NOFORK
Denis Vlasenkobe54d6b2008-10-27 14:25:52 +00009113/* Hmmm... shouldn't it happen somewhere in forkshell() instead?
9114 * Why "fork off a child process if necessary" doesn't apply to NOFORK? */
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00009115 {
9116 /* find_command() encodes applet_no as (-2 - applet_no) */
9117 int applet_no = (- cmdentry.u.index - 2);
Denis Vlasenko9bc80d72008-04-12 20:07:53 +00009118 if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
Denis Vlasenko9bc80d72008-04-12 20:07:53 +00009119 listsetvar(varlist.list, VEXPORT|VSTACK);
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00009120 /* run <applet>_main() */
9121 exitstatus = run_nofork_applet(applet_no, argv);
Denis Vlasenko9bc80d72008-04-12 20:07:53 +00009122 break;
9123 }
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00009124 }
Denis Vlasenko9bc80d72008-04-12 20:07:53 +00009125#endif
Eric Andersenc470f442003-07-28 09:56:35 +00009126 /* Fork off a child process if necessary. */
9127 if (!(flags & EV_EXIT) || trap[0]) {
Denis Vlasenkob012b102007-02-19 22:43:01 +00009128 INT_OFF;
Denis Vlasenko68404f12008-03-17 09:00:54 +00009129 jp = makejob(/*cmd,*/ 1);
Eric Andersenc470f442003-07-28 09:56:35 +00009130 if (forkshell(jp, cmd, FORK_FG) != 0) {
9131 exitstatus = waitforjob(jp);
Denis Vlasenkob012b102007-02-19 22:43:01 +00009132 INT_ON;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00009133 TRACE(("forked child exited with %d\n", exitstatus));
Eric Andersenc470f442003-07-28 09:56:35 +00009134 break;
9135 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00009136 FORCE_INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00009137 }
9138 listsetvar(varlist.list, VEXPORT|VSTACK);
9139 shellexec(argv, path, cmdentry.u.index);
9140 /* NOTREACHED */
9141
9142 case CMDBUILTIN:
9143 cmdenviron = varlist.list;
9144 if (cmdenviron) {
9145 struct strlist *list = cmdenviron;
9146 int i = VNOSET;
9147 if (spclbltin > 0 || argc == 0) {
9148 i = 0;
9149 if (cmd_is_exec && argc > 1)
9150 i = VEXPORT;
9151 }
9152 listsetvar(list, i);
9153 }
Denis Vlasenkobe54d6b2008-10-27 14:25:52 +00009154 /* Tight loop with builtins only:
9155 * "while kill -0 $child; do true; done"
9156 * will never exit even if $child died, unless we do this
9157 * to reap the zombie and make kill detect that it's gone: */
9158 dowait(DOWAIT_NONBLOCK, NULL);
9159
Eric Andersenc470f442003-07-28 09:56:35 +00009160 if (evalbltin(cmdentry.u.cmd, argc, argv)) {
9161 int exit_status;
Denis Vlasenko7f88e342009-03-19 03:36:18 +00009162 int i = exception_type;
Eric Andersenc470f442003-07-28 09:56:35 +00009163 if (i == EXEXIT)
9164 goto raise;
Eric Andersenc470f442003-07-28 09:56:35 +00009165 exit_status = 2;
Eric Andersenc470f442003-07-28 09:56:35 +00009166 if (i == EXINT)
Denis Vlasenko991a1da2008-02-10 19:02:53 +00009167 exit_status = 128 + SIGINT;
Eric Andersenc470f442003-07-28 09:56:35 +00009168 if (i == EXSIG)
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02009169 exit_status = 128 + pending_sig;
Eric Andersenc470f442003-07-28 09:56:35 +00009170 exitstatus = exit_status;
Eric Andersenc470f442003-07-28 09:56:35 +00009171 if (i == EXINT || spclbltin > 0) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009172 raise:
Denis Vlasenko2da584f2007-02-19 22:44:05 +00009173 longjmp(exception_handler->loc, 1);
Eric Andersenc470f442003-07-28 09:56:35 +00009174 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00009175 FORCE_INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00009176 }
9177 break;
9178
9179 case CMDFUNCTION:
9180 listsetvar(varlist.list, 0);
Denis Vlasenkobe54d6b2008-10-27 14:25:52 +00009181 /* See above for the rationale */
9182 dowait(DOWAIT_NONBLOCK, NULL);
Eric Andersenc470f442003-07-28 09:56:35 +00009183 if (evalfun(cmdentry.u.func, argc, argv, flags))
9184 goto raise;
9185 break;
9186 }
9187
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009188 out:
Denis Vlasenko34c73c42008-08-16 11:48:02 +00009189 popredir(/*drop:*/ cmd_is_exec, /*restore:*/ cmd_is_exec);
Denis Vlasenko6514c5e2008-07-24 13:41:37 +00009190 if (lastarg) {
Eric Andersenc470f442003-07-28 09:56:35 +00009191 /* dsl: I think this is intended to be used to support
9192 * '_' in 'vi' command mode during line editing...
9193 * However I implemented that within libedit itself.
9194 */
9195 setvar("_", lastarg, 0);
Denis Vlasenko6514c5e2008-07-24 13:41:37 +00009196 }
Eric Andersenc470f442003-07-28 09:56:35 +00009197 popstackmark(&smark);
9198}
9199
9200static int
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009201evalbltin(const struct builtincmd *cmd, int argc, char **argv)
9202{
Eric Andersenc470f442003-07-28 09:56:35 +00009203 char *volatile savecmdname;
9204 struct jmploc *volatile savehandler;
9205 struct jmploc jmploc;
9206 int i;
9207
9208 savecmdname = commandname;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009209 i = setjmp(jmploc.loc);
9210 if (i)
Eric Andersenc470f442003-07-28 09:56:35 +00009211 goto cmddone;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00009212 savehandler = exception_handler;
9213 exception_handler = &jmploc;
Eric Andersenc470f442003-07-28 09:56:35 +00009214 commandname = argv[0];
9215 argptr = argv + 1;
9216 optptr = NULL; /* initialize nextopt */
9217 exitstatus = (*cmd->builtin)(argc, argv);
Denis Vlasenkob012b102007-02-19 22:43:01 +00009218 flush_stdout_stderr();
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009219 cmddone:
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009220 exitstatus |= ferror(stdout);
Rob Landleyf296f0b2006-07-06 01:09:21 +00009221 clearerr(stdout);
Eric Andersenc470f442003-07-28 09:56:35 +00009222 commandname = savecmdname;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00009223 exception_handler = savehandler;
Eric Andersenc470f442003-07-28 09:56:35 +00009224
9225 return i;
9226}
9227
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009228static int
9229goodname(const char *p)
Glenn L McGrath16e45d72004-02-04 08:24:39 +00009230{
9231 return !*endofname(p);
9232}
9233
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009234
Glenn L McGrath50812ff2002-08-23 13:14:48 +00009235/*
9236 * Search for a command. This is called before we fork so that the
9237 * location of the command will be available in the parent as well as
Glenn L McGrath16e45d72004-02-04 08:24:39 +00009238 * the child. The check for "goodname" is an overly conservative
9239 * check that the name will not be subject to expansion.
Glenn L McGrath50812ff2002-08-23 13:14:48 +00009240 */
Eric Andersenc470f442003-07-28 09:56:35 +00009241static void
9242prehash(union node *n)
Glenn L McGrath50812ff2002-08-23 13:14:48 +00009243{
9244 struct cmdentry entry;
9245
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +00009246 if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
9247 find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
Glenn L McGrath50812ff2002-08-23 13:14:48 +00009248}
9249
Eric Andersencb57d552001-06-28 07:25:16 +00009250
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00009251/* ============ Builtin commands
9252 *
9253 * Builtin commands whose functions are closely tied to evaluation
9254 * are implemented here.
Eric Andersencb57d552001-06-28 07:25:16 +00009255 */
9256
9257/*
Eric Andersencb57d552001-06-28 07:25:16 +00009258 * Handle break and continue commands. Break, continue, and return are
9259 * all handled by setting the evalskip flag. The evaluation routines
9260 * above all check this flag, and if it is set they start skipping
9261 * commands rather than executing them. The variable skipcount is
9262 * the number of loops to break/continue, or the number of function
9263 * levels to return. (The latter is always 1.) It should probably
9264 * be an error to break out of more loops than exist, but it isn't
9265 * in the standard shell so we don't make it one here.
9266 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009267static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00009268breakcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +00009269{
Denis Vlasenko68404f12008-03-17 09:00:54 +00009270 int n = argv[1] ? number(argv[1]) : 1;
Eric Andersencb57d552001-06-28 07:25:16 +00009271
Aaron Lehmann2aef3a62001-12-31 06:03:12 +00009272 if (n <= 0)
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02009273 ash_msg_and_raise_error(msg_illnum, argv[1]);
Eric Andersencb57d552001-06-28 07:25:16 +00009274 if (n > loopnest)
9275 n = loopnest;
9276 if (n > 0) {
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00009277 evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
Eric Andersencb57d552001-06-28 07:25:16 +00009278 skipcount = n;
9279 }
9280 return 0;
9281}
9282
Eric Andersenc470f442003-07-28 09:56:35 +00009283
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009284/* ============ input.c
9285 *
Eric Andersen90898442003-08-06 11:20:52 +00009286 * This implements the input routines used by the parser.
Eric Andersencb57d552001-06-28 07:25:16 +00009287 */
Denis Vlasenko99eb8502007-02-23 21:09:49 +00009288
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009289enum {
9290 INPUT_PUSH_FILE = 1,
9291 INPUT_NOFILE_OK = 2,
9292};
Eric Andersencb57d552001-06-28 07:25:16 +00009293
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009294static smallint checkkwd;
Denis Vlasenko99eb8502007-02-23 21:09:49 +00009295/* values of checkkwd variable */
9296#define CHKALIAS 0x1
9297#define CHKKWD 0x2
9298#define CHKNL 0x4
9299
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009300/*
9301 * Push a string back onto the input at this current parsefile level.
9302 * We handle aliases this way.
9303 */
9304#if !ENABLE_ASH_ALIAS
9305#define pushstring(s, ap) pushstring(s)
9306#endif
9307static void
9308pushstring(char *s, struct alias *ap)
9309{
9310 struct strpush *sp;
9311 int len;
9312
9313 len = strlen(s);
9314 INT_OFF;
9315 if (g_parsefile->strpush) {
9316 sp = ckzalloc(sizeof(*sp));
9317 sp->prev = g_parsefile->strpush;
9318 } else {
9319 sp = &(g_parsefile->basestrpush);
9320 }
9321 g_parsefile->strpush = sp;
9322 sp->prev_string = g_parsefile->next_to_pgetc;
9323 sp->prev_left_in_line = g_parsefile->left_in_line;
9324#if ENABLE_ASH_ALIAS
9325 sp->ap = ap;
9326 if (ap) {
9327 ap->flag |= ALIASINUSE;
9328 sp->string = s;
9329 }
9330#endif
9331 g_parsefile->next_to_pgetc = s;
9332 g_parsefile->left_in_line = len;
9333 INT_ON;
9334}
9335
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009336static void
9337popstring(void)
Eric Andersenc470f442003-07-28 09:56:35 +00009338{
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009339 struct strpush *sp = g_parsefile->strpush;
Eric Andersenc470f442003-07-28 09:56:35 +00009340
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009341 INT_OFF;
Denis Vlasenko131ae172007-02-18 13:00:19 +00009342#if ENABLE_ASH_ALIAS
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009343 if (sp->ap) {
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009344 if (g_parsefile->next_to_pgetc[-1] == ' '
9345 || g_parsefile->next_to_pgetc[-1] == '\t'
9346 ) {
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009347 checkkwd |= CHKALIAS;
Glenn L McGrath28939ad2004-07-21 10:20:19 +00009348 }
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009349 if (sp->string != sp->ap->val) {
9350 free(sp->string);
9351 }
9352 sp->ap->flag &= ~ALIASINUSE;
9353 if (sp->ap->flag & ALIASDEAD) {
9354 unalias(sp->ap->name);
9355 }
Glenn L McGrath28939ad2004-07-21 10:20:19 +00009356 }
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009357#endif
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009358 g_parsefile->next_to_pgetc = sp->prev_string;
9359 g_parsefile->left_in_line = sp->prev_left_in_line;
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009360 g_parsefile->strpush = sp->prev;
9361 if (sp != &(g_parsefile->basestrpush))
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009362 free(sp);
9363 INT_ON;
9364}
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009365
Denis Vlasenkoe27dafd2008-11-28 04:01:03 +00009366//FIXME: BASH_COMPAT with "...&" does TWO pungetc():
9367//it peeks whether it is &>, and then pushes back both chars.
9368//This function needs to save last *next_to_pgetc to buf[0]
9369//to make two pungetc() reliable. Currently,
9370// pgetc (out of buf: does preadfd), pgetc, pungetc, pungetc won't work...
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009371static int
9372preadfd(void)
Eric Andersencb57d552001-06-28 07:25:16 +00009373{
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00009374 int nr;
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00009375 char *buf = g_parsefile->buf;
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00009376
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009377 g_parsefile->next_to_pgetc = buf;
Denis Vlasenko38f63192007-01-22 09:03:07 +00009378#if ENABLE_FEATURE_EDITING
Denis Vlasenko85c24712008-03-17 09:04:04 +00009379 retry:
Denis Vlasenko727752d2008-11-28 03:41:47 +00009380 if (!iflag || g_parsefile->fd != STDIN_FILENO)
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009381 nr = nonblock_safe_read(g_parsefile->fd, buf, BUFSIZ - 1);
Eric Andersenc470f442003-07-28 09:56:35 +00009382 else {
Denis Vlasenko38f63192007-01-22 09:03:07 +00009383#if ENABLE_FEATURE_TAB_COMPLETION
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009384 line_input_state->path_lookup = pathval();
Eric Andersen4a79c0e2004-09-08 10:01:07 +00009385#endif
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009386 nr = read_line_input(cmdedit_prompt, buf, BUFSIZ, line_input_state);
9387 if (nr == 0) {
9388 /* Ctrl+C pressed */
9389 if (trap[SIGINT]) {
Glenn L McGrath16e45d72004-02-04 08:24:39 +00009390 buf[0] = '\n';
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009391 buf[1] = '\0';
Glenn L McGrath16e45d72004-02-04 08:24:39 +00009392 raise(SIGINT);
9393 return 1;
9394 }
Eric Andersenc470f442003-07-28 09:56:35 +00009395 goto retry;
9396 }
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009397 if (nr < 0 && errno == 0) {
Denis Vlasenko9cb220b2007-12-09 10:03:28 +00009398 /* Ctrl+D pressed */
Eric Andersenc470f442003-07-28 09:56:35 +00009399 nr = 0;
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00009400 }
Eric Andersencb57d552001-06-28 07:25:16 +00009401 }
9402#else
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +00009403 nr = nonblock_safe_read(g_parsefile->fd, buf, BUFSIZ - 1);
Eric Andersencb57d552001-06-28 07:25:16 +00009404#endif
9405
Denis Vlasenkoe376d452008-02-20 22:23:24 +00009406#if 0
9407/* nonblock_safe_read() handles this problem */
Eric Andersencb57d552001-06-28 07:25:16 +00009408 if (nr < 0) {
Eric Andersencb57d552001-06-28 07:25:16 +00009409 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
Denis Vlasenkod37f2222007-08-19 13:42:08 +00009410 int flags = fcntl(0, F_GETFL);
Denis Vlasenko9cb220b2007-12-09 10:03:28 +00009411 if (flags >= 0 && (flags & O_NONBLOCK)) {
9412 flags &= ~O_NONBLOCK;
Eric Andersencb57d552001-06-28 07:25:16 +00009413 if (fcntl(0, F_SETFL, flags) >= 0) {
9414 out2str("sh: turning off NDELAY mode\n");
9415 goto retry;
9416 }
9417 }
9418 }
9419 }
Denis Vlasenkoe376d452008-02-20 22:23:24 +00009420#endif
Eric Andersencb57d552001-06-28 07:25:16 +00009421 return nr;
9422}
9423
9424/*
9425 * Refill the input buffer and return the next input character:
9426 *
9427 * 1) If a string was pushed back on the input, pop it;
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009428 * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
9429 * or we are reading from a string so we can't refill the buffer,
9430 * return EOF.
Denys Vlasenko883cea42009-07-11 15:31:59 +02009431 * 3) If there is more stuff in this buffer, use it else call read to fill it.
Eric Andersencb57d552001-06-28 07:25:16 +00009432 * 4) Process input up to the next newline, deleting nul characters.
9433 */
Denis Vlasenko727752d2008-11-28 03:41:47 +00009434//#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
9435#define pgetc_debug(...) ((void)0)
Denis Vlasenko68819d12008-12-15 11:26:36 +00009436/*
9437 * NB: due to SIT(c) internals (syntax_index_table[] vector),
9438 * pgetc() and related functions must return chars SIGN-EXTENDED into ints,
9439 * not zero-extended. Seems fragile to me. Affects only !USE_SIT_FUNCTION case,
9440 * so we can fix it by ditching !USE_SIT_FUNCTION if Unicode requires that.
9441 */
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009442static int
Eric Andersenc470f442003-07-28 09:56:35 +00009443preadbuffer(void)
Eric Andersencb57d552001-06-28 07:25:16 +00009444{
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009445 char *q;
Eric Andersencb57d552001-06-28 07:25:16 +00009446 int more;
Eric Andersencb57d552001-06-28 07:25:16 +00009447
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009448 while (g_parsefile->strpush) {
Denis Vlasenko131ae172007-02-18 13:00:19 +00009449#if ENABLE_ASH_ALIAS
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009450 if (g_parsefile->left_in_line == -1
9451 && g_parsefile->strpush->ap
9452 && g_parsefile->next_to_pgetc[-1] != ' '
9453 && g_parsefile->next_to_pgetc[-1] != '\t'
Denis Vlasenko16898402008-11-25 01:34:52 +00009454 ) {
Denis Vlasenko727752d2008-11-28 03:41:47 +00009455 pgetc_debug("preadbuffer PEOA");
Eric Andersencb57d552001-06-28 07:25:16 +00009456 return PEOA;
9457 }
Eric Andersen2870d962001-07-02 17:27:21 +00009458#endif
Eric Andersencb57d552001-06-28 07:25:16 +00009459 popstring();
Denis Vlasenko727752d2008-11-28 03:41:47 +00009460 /* try "pgetc" now: */
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009461 pgetc_debug("preadbuffer internal pgetc at %d:%p'%s'",
9462 g_parsefile->left_in_line,
9463 g_parsefile->next_to_pgetc,
9464 g_parsefile->next_to_pgetc);
9465 if (--g_parsefile->left_in_line >= 0)
9466 return (unsigned char)(*g_parsefile->next_to_pgetc++);
Eric Andersencb57d552001-06-28 07:25:16 +00009467 }
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009468 /* on both branches above g_parsefile->left_in_line < 0.
Denis Vlasenko727752d2008-11-28 03:41:47 +00009469 * "pgetc" needs refilling.
9470 */
9471
Denis Vlasenkoe27dafd2008-11-28 04:01:03 +00009472 /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009473 * pungetc() may increment it a few times.
Denis Vlasenkoe27dafd2008-11-28 04:01:03 +00009474 * Assuming it won't increment it to less than -90.
Denis Vlasenko727752d2008-11-28 03:41:47 +00009475 */
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009476 if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
Denis Vlasenko727752d2008-11-28 03:41:47 +00009477 pgetc_debug("preadbuffer PEOF1");
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009478 /* even in failure keep left_in_line and next_to_pgetc
9479 * in lock step, for correct multi-layer pungetc.
9480 * left_in_line was decremented before preadbuffer(),
9481 * must inc next_to_pgetc: */
9482 g_parsefile->next_to_pgetc++;
Eric Andersencb57d552001-06-28 07:25:16 +00009483 return PEOF;
Denis Vlasenko727752d2008-11-28 03:41:47 +00009484 }
Eric Andersencb57d552001-06-28 07:25:16 +00009485
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009486 more = g_parsefile->left_in_buffer;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009487 if (more <= 0) {
Denis Vlasenko727752d2008-11-28 03:41:47 +00009488 flush_stdout_stderr();
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009489 again:
9490 more = preadfd();
9491 if (more <= 0) {
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009492 /* don't try reading again */
9493 g_parsefile->left_in_line = -99;
Denis Vlasenko727752d2008-11-28 03:41:47 +00009494 pgetc_debug("preadbuffer PEOF2");
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009495 g_parsefile->next_to_pgetc++;
Eric Andersencb57d552001-06-28 07:25:16 +00009496 return PEOF;
9497 }
9498 }
9499
Denis Vlasenko727752d2008-11-28 03:41:47 +00009500 /* Find out where's the end of line.
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009501 * Set g_parsefile->left_in_line
9502 * and g_parsefile->left_in_buffer acordingly.
Denis Vlasenko727752d2008-11-28 03:41:47 +00009503 * NUL chars are deleted.
9504 */
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009505 q = g_parsefile->next_to_pgetc;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009506 for (;;) {
Denis Vlasenko727752d2008-11-28 03:41:47 +00009507 char c;
Eric Andersencb57d552001-06-28 07:25:16 +00009508
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009509 more--;
Eric Andersenc470f442003-07-28 09:56:35 +00009510
Denis Vlasenko727752d2008-11-28 03:41:47 +00009511 c = *q;
9512 if (c == '\0') {
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009513 memmove(q, q + 1, more);
Denis Vlasenko727752d2008-11-28 03:41:47 +00009514 } else {
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009515 q++;
9516 if (c == '\n') {
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009517 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009518 break;
9519 }
Eric Andersencb57d552001-06-28 07:25:16 +00009520 }
9521
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009522 if (more <= 0) {
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009523 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9524 if (g_parsefile->left_in_line < 0)
Eric Andersencb57d552001-06-28 07:25:16 +00009525 goto again;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009526 break;
Eric Andersencb57d552001-06-28 07:25:16 +00009527 }
9528 }
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009529 g_parsefile->left_in_buffer = more;
Eric Andersencb57d552001-06-28 07:25:16 +00009530
Eric Andersencb57d552001-06-28 07:25:16 +00009531 if (vflag) {
Denis Vlasenko727752d2008-11-28 03:41:47 +00009532 char save = *q;
9533 *q = '\0';
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009534 out2str(g_parsefile->next_to_pgetc);
Denis Vlasenko727752d2008-11-28 03:41:47 +00009535 *q = save;
Eric Andersencb57d552001-06-28 07:25:16 +00009536 }
9537
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009538 pgetc_debug("preadbuffer at %d:%p'%s'",
9539 g_parsefile->left_in_line,
9540 g_parsefile->next_to_pgetc,
9541 g_parsefile->next_to_pgetc);
Denis Vlasenko68819d12008-12-15 11:26:36 +00009542 return signed_char2int(*g_parsefile->next_to_pgetc++);
Eric Andersencb57d552001-06-28 07:25:16 +00009543}
9544
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009545#define pgetc_as_macro() \
9546 (--g_parsefile->left_in_line >= 0 \
Denis Vlasenko68819d12008-12-15 11:26:36 +00009547 ? signed_char2int(*g_parsefile->next_to_pgetc++) \
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009548 : preadbuffer() \
9549 )
Denis Vlasenko727752d2008-11-28 03:41:47 +00009550
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009551static int
9552pgetc(void)
9553{
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009554 pgetc_debug("pgetc_fast at %d:%p'%s'",
9555 g_parsefile->left_in_line,
9556 g_parsefile->next_to_pgetc,
9557 g_parsefile->next_to_pgetc);
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009558 return pgetc_as_macro();
9559}
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00009560
9561#if ENABLE_ASH_OPTIMIZE_FOR_SIZE
Denis Vlasenko834dee72008-10-07 09:18:30 +00009562#define pgetc_fast() pgetc()
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009563#else
Denis Vlasenko834dee72008-10-07 09:18:30 +00009564#define pgetc_fast() pgetc_as_macro()
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009565#endif
9566
9567/*
9568 * Same as pgetc(), but ignores PEOA.
9569 */
9570#if ENABLE_ASH_ALIAS
9571static int
9572pgetc2(void)
9573{
9574 int c;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009575 do {
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009576 pgetc_debug("pgetc_fast at %d:%p'%s'",
9577 g_parsefile->left_in_line,
9578 g_parsefile->next_to_pgetc,
9579 g_parsefile->next_to_pgetc);
Denis Vlasenko834dee72008-10-07 09:18:30 +00009580 c = pgetc_fast();
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009581 } while (c == PEOA);
9582 return c;
9583}
9584#else
Denis Vlasenko834dee72008-10-07 09:18:30 +00009585#define pgetc2() pgetc()
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009586#endif
9587
9588/*
9589 * Read a line from the script.
9590 */
9591static char *
9592pfgets(char *line, int len)
9593{
9594 char *p = line;
9595 int nleft = len;
9596 int c;
9597
9598 while (--nleft > 0) {
9599 c = pgetc2();
9600 if (c == PEOF) {
9601 if (p == line)
9602 return NULL;
9603 break;
9604 }
9605 *p++ = c;
9606 if (c == '\n')
9607 break;
9608 }
9609 *p = '\0';
9610 return line;
9611}
9612
Eric Andersenc470f442003-07-28 09:56:35 +00009613/*
9614 * Undo the last call to pgetc. Only one character may be pushed back.
9615 * PEOF may be pushed back.
9616 */
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009617static void
Eric Andersenc470f442003-07-28 09:56:35 +00009618pungetc(void)
9619{
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009620 g_parsefile->left_in_line++;
9621 g_parsefile->next_to_pgetc--;
9622 pgetc_debug("pushed back to %d:%p'%s'",
9623 g_parsefile->left_in_line,
9624 g_parsefile->next_to_pgetc,
9625 g_parsefile->next_to_pgetc);
Eric Andersencb57d552001-06-28 07:25:16 +00009626}
9627
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009628/*
9629 * To handle the "." command, a stack of input files is used. Pushfile
9630 * adds a new entry to the stack and popfile restores the previous level.
9631 */
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009632static void
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009633pushfile(void)
Eric Andersenc470f442003-07-28 09:56:35 +00009634{
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009635 struct parsefile *pf;
9636
Denis Vlasenko597906c2008-02-20 16:38:54 +00009637 pf = ckzalloc(sizeof(*pf));
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009638 pf->prev = g_parsefile;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009639 pf->fd = -1;
Denis Vlasenko597906c2008-02-20 16:38:54 +00009640 /*pf->strpush = NULL; - ckzalloc did it */
9641 /*pf->basestrpush.prev = NULL;*/
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009642 g_parsefile = pf;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009643}
9644
9645static void
9646popfile(void)
9647{
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009648 struct parsefile *pf = g_parsefile;
Eric Andersenc470f442003-07-28 09:56:35 +00009649
Denis Vlasenkob012b102007-02-19 22:43:01 +00009650 INT_OFF;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009651 if (pf->fd >= 0)
9652 close(pf->fd);
Denis Vlasenko60818682007-09-28 22:07:23 +00009653 free(pf->buf);
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009654 while (pf->strpush)
9655 popstring();
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009656 g_parsefile = pf->prev;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009657 free(pf);
Denis Vlasenkob012b102007-02-19 22:43:01 +00009658 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00009659}
9660
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009661/*
9662 * Return to top level.
9663 */
9664static void
9665popallfiles(void)
9666{
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009667 while (g_parsefile != &basepf)
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009668 popfile();
9669}
9670
9671/*
9672 * Close the file(s) that the shell is reading commands from. Called
9673 * after a fork is done.
9674 */
9675static void
9676closescript(void)
9677{
9678 popallfiles();
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009679 if (g_parsefile->fd > 0) {
9680 close(g_parsefile->fd);
9681 g_parsefile->fd = 0;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009682 }
9683}
9684
9685/*
9686 * Like setinputfile, but takes an open file descriptor. Call this with
9687 * interrupts off.
9688 */
9689static void
9690setinputfd(int fd, int push)
9691{
Denis Vlasenko96e1b382007-09-30 23:50:48 +00009692 close_on_exec_on(fd);
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009693 if (push) {
9694 pushfile();
Denis Vlasenko727752d2008-11-28 03:41:47 +00009695 g_parsefile->buf = NULL;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009696 }
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009697 g_parsefile->fd = fd;
9698 if (g_parsefile->buf == NULL)
9699 g_parsefile->buf = ckmalloc(IBUFSIZ);
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009700 g_parsefile->left_in_buffer = 0;
9701 g_parsefile->left_in_line = 0;
9702 g_parsefile->linno = 1;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009703}
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009704
Eric Andersenc470f442003-07-28 09:56:35 +00009705/*
9706 * Set the input to take input from a file. If push is set, push the
9707 * old input onto the stack first.
9708 */
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009709static int
9710setinputfile(const char *fname, int flags)
Eric Andersenc470f442003-07-28 09:56:35 +00009711{
9712 int fd;
9713 int fd2;
9714
Denis Vlasenkob012b102007-02-19 22:43:01 +00009715 INT_OFF;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009716 fd = open(fname, O_RDONLY);
9717 if (fd < 0) {
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009718 if (flags & INPUT_NOFILE_OK)
9719 goto out;
Denis Vlasenko9604e1b2009-03-03 18:47:56 +00009720 ash_msg_and_raise_error("can't open '%s'", fname);
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009721 }
Eric Andersenc470f442003-07-28 09:56:35 +00009722 if (fd < 10) {
9723 fd2 = copyfd(fd, 10);
9724 close(fd);
9725 if (fd2 < 0)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00009726 ash_msg_and_raise_error("out of file descriptors");
Eric Andersenc470f442003-07-28 09:56:35 +00009727 fd = fd2;
9728 }
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009729 setinputfd(fd, flags & INPUT_PUSH_FILE);
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009730 out:
Denis Vlasenkob012b102007-02-19 22:43:01 +00009731 INT_ON;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009732 return fd;
Eric Andersenc470f442003-07-28 09:56:35 +00009733}
9734
Eric Andersencb57d552001-06-28 07:25:16 +00009735/*
9736 * Like setinputfile, but takes input from a string.
9737 */
Eric Andersenc470f442003-07-28 09:56:35 +00009738static void
9739setinputstring(char *string)
Eric Andersen62483552001-07-10 06:09:16 +00009740{
Denis Vlasenkob012b102007-02-19 22:43:01 +00009741 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +00009742 pushfile();
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009743 g_parsefile->next_to_pgetc = string;
9744 g_parsefile->left_in_line = strlen(string);
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009745 g_parsefile->buf = NULL;
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009746 g_parsefile->linno = 1;
Denis Vlasenkob012b102007-02-19 22:43:01 +00009747 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00009748}
9749
9750
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00009751/* ============ mail.c
9752 *
9753 * Routines to check for mail.
Eric Andersencb57d552001-06-28 07:25:16 +00009754 */
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00009755
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00009756#if ENABLE_ASH_MAIL
Eric Andersencb57d552001-06-28 07:25:16 +00009757
Eric Andersencb57d552001-06-28 07:25:16 +00009758#define MAXMBOXES 10
9759
Eric Andersenc470f442003-07-28 09:56:35 +00009760/* times of mailboxes */
9761static time_t mailtime[MAXMBOXES];
9762/* Set if MAIL or MAILPATH is changed. */
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +00009763static smallint mail_var_path_changed;
Eric Andersencb57d552001-06-28 07:25:16 +00009764
Eric Andersencb57d552001-06-28 07:25:16 +00009765/*
Eric Andersenc470f442003-07-28 09:56:35 +00009766 * Print appropriate message(s) if mail has arrived.
9767 * If mail_var_path_changed is set,
9768 * then the value of MAIL has mail_var_path_changed,
9769 * so we just update the values.
Eric Andersencb57d552001-06-28 07:25:16 +00009770 */
Eric Andersenc470f442003-07-28 09:56:35 +00009771static void
9772chkmail(void)
Eric Andersencb57d552001-06-28 07:25:16 +00009773{
Eric Andersencb57d552001-06-28 07:25:16 +00009774 const char *mpath;
9775 char *p;
9776 char *q;
Eric Andersenc470f442003-07-28 09:56:35 +00009777 time_t *mtp;
Eric Andersencb57d552001-06-28 07:25:16 +00009778 struct stackmark smark;
9779 struct stat statb;
9780
Eric Andersencb57d552001-06-28 07:25:16 +00009781 setstackmark(&smark);
Eric Andersenc470f442003-07-28 09:56:35 +00009782 mpath = mpathset() ? mpathval() : mailval();
9783 for (mtp = mailtime; mtp < mailtime + MAXMBOXES; mtp++) {
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02009784 p = path_advance(&mpath, nullstr);
Eric Andersencb57d552001-06-28 07:25:16 +00009785 if (p == NULL)
9786 break;
9787 if (*p == '\0')
9788 continue;
Denis Vlasenkof7d56652008-03-25 05:51:41 +00009789 for (q = p; *q; q++)
9790 continue;
Denis Vlasenkoa7189f02006-11-17 20:29:00 +00009791#if DEBUG
Eric Andersencb57d552001-06-28 07:25:16 +00009792 if (q[-1] != '/')
9793 abort();
9794#endif
Eric Andersenc470f442003-07-28 09:56:35 +00009795 q[-1] = '\0'; /* delete trailing '/' */
9796 if (stat(p, &statb) < 0) {
9797 *mtp = 0;
9798 continue;
Eric Andersencb57d552001-06-28 07:25:16 +00009799 }
Eric Andersenc470f442003-07-28 09:56:35 +00009800 if (!mail_var_path_changed && statb.st_mtime != *mtp) {
9801 fprintf(
9802 stderr, snlfmt,
9803 pathopt ? pathopt : "you have mail"
9804 );
9805 }
9806 *mtp = statb.st_mtime;
Eric Andersencb57d552001-06-28 07:25:16 +00009807 }
Eric Andersenc470f442003-07-28 09:56:35 +00009808 mail_var_path_changed = 0;
Eric Andersencb57d552001-06-28 07:25:16 +00009809 popstackmark(&smark);
9810}
Eric Andersencb57d552001-06-28 07:25:16 +00009811
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009812static void FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00009813changemail(const char *val UNUSED_PARAM)
Eric Andersenc470f442003-07-28 09:56:35 +00009814{
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +00009815 mail_var_path_changed = 1;
Eric Andersenc470f442003-07-28 09:56:35 +00009816}
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00009817
Denis Vlasenko131ae172007-02-18 13:00:19 +00009818#endif /* ASH_MAIL */
Eric Andersenc470f442003-07-28 09:56:35 +00009819
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00009820
9821/* ============ ??? */
9822
Eric Andersencb57d552001-06-28 07:25:16 +00009823/*
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009824 * Set the shell parameters.
Eric Andersencb57d552001-06-28 07:25:16 +00009825 */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009826static void
9827setparam(char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +00009828{
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009829 char **newparam;
9830 char **ap;
9831 int nparam;
Eric Andersencb57d552001-06-28 07:25:16 +00009832
Denis Vlasenkof7d56652008-03-25 05:51:41 +00009833 for (nparam = 0; argv[nparam]; nparam++)
9834 continue;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009835 ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
9836 while (*argv) {
9837 *ap++ = ckstrdup(*argv++);
Eric Andersencb57d552001-06-28 07:25:16 +00009838 }
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009839 *ap = NULL;
9840 freeparam(&shellparam);
Denis Vlasenko01631112007-12-16 17:20:38 +00009841 shellparam.malloced = 1;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009842 shellparam.nparam = nparam;
9843 shellparam.p = newparam;
9844#if ENABLE_ASH_GETOPTS
9845 shellparam.optind = 1;
9846 shellparam.optoff = -1;
9847#endif
Eric Andersencb57d552001-06-28 07:25:16 +00009848}
9849
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00009850/*
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009851 * Process shell options. The global variable argptr contains a pointer
9852 * to the argument list; we advance it past the options.
Denis Vlasenko94e87bc2008-02-14 16:51:58 +00009853 *
9854 * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
9855 * For a non-interactive shell, an error condition encountered
9856 * by a special built-in ... shall cause the shell to write a diagnostic message
9857 * to standard error and exit as shown in the following table:
Denis Vlasenko56244732008-02-17 15:14:04 +00009858 * Error Special Built-In
Denis Vlasenko94e87bc2008-02-14 16:51:58 +00009859 * ...
9860 * Utility syntax error (option or operand error) Shall exit
9861 * ...
9862 * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
9863 * we see that bash does not do that (set "finishes" with error code 1 instead,
9864 * and shell continues), and people rely on this behavior!
9865 * Testcase:
9866 * set -o barfoo 2>/dev/null
9867 * echo $?
9868 *
9869 * Oh well. Let's mimic that.
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00009870 */
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009871static int
Denis Vlasenkodddfaff2008-05-06 15:30:27 +00009872plus_minus_o(char *name, int val)
Eric Andersen62483552001-07-10 06:09:16 +00009873{
9874 int i;
9875
Denis Vlasenkoa624c112007-02-19 22:45:43 +00009876 if (name) {
9877 for (i = 0; i < NOPTS; i++) {
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00009878 if (strcmp(name, optnames(i)) == 0) {
Eric Andersenc470f442003-07-28 09:56:35 +00009879 optlist[i] = val;
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009880 return 0;
Eric Andersen62483552001-07-10 06:09:16 +00009881 }
Denis Vlasenkoa624c112007-02-19 22:45:43 +00009882 }
Denis Vlasenkodddfaff2008-05-06 15:30:27 +00009883 ash_msg("illegal option %co %s", val ? '-' : '+', name);
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009884 return 1;
Eric Andersen62483552001-07-10 06:09:16 +00009885 }
Denis Vlasenko6b06cb82008-05-15 21:30:45 +00009886 for (i = 0; i < NOPTS; i++) {
Denis Vlasenkodddfaff2008-05-06 15:30:27 +00009887 if (val) {
9888 out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
9889 } else {
9890 out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
9891 }
Denis Vlasenko6b06cb82008-05-15 21:30:45 +00009892 }
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009893 return 0;
Eric Andersen62483552001-07-10 06:09:16 +00009894}
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009895static void
9896setoption(int flag, int val)
9897{
9898 int i;
9899
9900 for (i = 0; i < NOPTS; i++) {
9901 if (optletters(i) == flag) {
9902 optlist[i] = val;
9903 return;
9904 }
9905 }
Denis Vlasenkodddfaff2008-05-06 15:30:27 +00009906 ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009907 /* NOTREACHED */
9908}
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009909static int
Eric Andersenc470f442003-07-28 09:56:35 +00009910options(int cmdline)
Eric Andersencb57d552001-06-28 07:25:16 +00009911{
9912 char *p;
9913 int val;
9914 int c;
9915
9916 if (cmdline)
9917 minusc = NULL;
9918 while ((p = *argptr) != NULL) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009919 c = *p++;
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +00009920 if (c != '-' && c != '+')
9921 break;
9922 argptr++;
9923 val = 0; /* val = 0 if c == '+' */
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009924 if (c == '-') {
Eric Andersencb57d552001-06-28 07:25:16 +00009925 val = 1;
Denis Vlasenko9f739442006-12-16 23:49:13 +00009926 if (p[0] == '\0' || LONE_DASH(p)) {
Eric Andersen2870d962001-07-02 17:27:21 +00009927 if (!cmdline) {
9928 /* "-" means turn off -x and -v */
9929 if (p[0] == '\0')
9930 xflag = vflag = 0;
9931 /* "--" means reset params */
9932 else if (*argptr == NULL)
Eric Andersencb57d552001-06-28 07:25:16 +00009933 setparam(argptr);
Eric Andersen2870d962001-07-02 17:27:21 +00009934 }
Eric Andersenc470f442003-07-28 09:56:35 +00009935 break; /* "-" or "--" terminates options */
Eric Andersencb57d552001-06-28 07:25:16 +00009936 }
Eric Andersencb57d552001-06-28 07:25:16 +00009937 }
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +00009938 /* first char was + or - */
Eric Andersencb57d552001-06-28 07:25:16 +00009939 while ((c = *p++) != '\0') {
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +00009940 /* bash 3.2 indeed handles -c CMD and +c CMD the same */
Eric Andersencb57d552001-06-28 07:25:16 +00009941 if (c == 'c' && cmdline) {
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +00009942 minusc = p; /* command is after shell args */
Eric Andersencb57d552001-06-28 07:25:16 +00009943 } else if (c == 'o') {
Denis Vlasenkodddfaff2008-05-06 15:30:27 +00009944 if (plus_minus_o(*argptr, val)) {
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009945 /* it already printed err message */
9946 return 1; /* error */
9947 }
Eric Andersencb57d552001-06-28 07:25:16 +00009948 if (*argptr)
9949 argptr++;
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +00009950 } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
9951 isloginsh = 1;
9952 /* bash does not accept +-login, we also won't */
9953 } else if (cmdline && val && (c == '-')) { /* long options */
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00009954 if (strcmp(p, "login") == 0)
Robert Griebl64f70cc2002-05-14 23:22:06 +00009955 isloginsh = 1;
9956 break;
Eric Andersencb57d552001-06-28 07:25:16 +00009957 } else {
9958 setoption(c, val);
9959 }
9960 }
9961 }
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009962 return 0;
Eric Andersencb57d552001-06-28 07:25:16 +00009963}
9964
Eric Andersencb57d552001-06-28 07:25:16 +00009965/*
Eric Andersencb57d552001-06-28 07:25:16 +00009966 * The shift builtin command.
9967 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009968static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00009969shiftcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +00009970{
9971 int n;
9972 char **ap1, **ap2;
9973
9974 n = 1;
Denis Vlasenko68404f12008-03-17 09:00:54 +00009975 if (argv[1])
Eric Andersencb57d552001-06-28 07:25:16 +00009976 n = number(argv[1]);
9977 if (n > shellparam.nparam)
Denis Vlasenkoc90e1be2008-07-30 15:35:05 +00009978 n = 0; /* bash compat, was = shellparam.nparam; */
Denis Vlasenkob012b102007-02-19 22:43:01 +00009979 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +00009980 shellparam.nparam -= n;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00009981 for (ap1 = shellparam.p; --n >= 0; ap1++) {
Denis Vlasenko01631112007-12-16 17:20:38 +00009982 if (shellparam.malloced)
Denis Vlasenkob012b102007-02-19 22:43:01 +00009983 free(*ap1);
Eric Andersencb57d552001-06-28 07:25:16 +00009984 }
9985 ap2 = shellparam.p;
Denis Vlasenkof7d56652008-03-25 05:51:41 +00009986 while ((*ap2++ = *ap1++) != NULL)
9987 continue;
Denis Vlasenko131ae172007-02-18 13:00:19 +00009988#if ENABLE_ASH_GETOPTS
Eric Andersencb57d552001-06-28 07:25:16 +00009989 shellparam.optind = 1;
9990 shellparam.optoff = -1;
Eric Andersenc470f442003-07-28 09:56:35 +00009991#endif
Denis Vlasenkob012b102007-02-19 22:43:01 +00009992 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00009993 return 0;
9994}
9995
Eric Andersencb57d552001-06-28 07:25:16 +00009996/*
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009997 * POSIX requires that 'set' (but not export or readonly) output the
9998 * variables in lexicographic order - by the locale's collating order (sigh).
9999 * Maybe we could keep them in an ordered balanced binary tree
10000 * instead of hashed lists.
10001 * For now just roll 'em through qsort for printing...
10002 */
10003static int
10004showvars(const char *sep_prefix, int on, int off)
10005{
10006 const char *sep;
10007 char **ep, **epend;
10008
10009 ep = listvars(on, off, &epend);
10010 qsort(ep, epend - ep, sizeof(char *), vpcmp);
10011
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +000010012 sep = *sep_prefix ? " " : sep_prefix;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010013
10014 for (; ep < epend; ep++) {
10015 const char *p;
10016 const char *q;
10017
10018 p = strchrnul(*ep, '=');
10019 q = nullstr;
10020 if (*p)
10021 q = single_quote(++p);
10022 out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
10023 }
10024 return 0;
10025}
10026
10027/*
Eric Andersencb57d552001-06-28 07:25:16 +000010028 * The set command builtin.
10029 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010030static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000010031setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersencb57d552001-06-28 07:25:16 +000010032{
Denis Vlasenko28bf6712008-02-14 15:01:47 +000010033 int retval;
10034
Denis Vlasenko68404f12008-03-17 09:00:54 +000010035 if (!argv[1])
Eric Andersenc470f442003-07-28 09:56:35 +000010036 return showvars(nullstr, 0, VUNSET);
Denis Vlasenkob012b102007-02-19 22:43:01 +000010037 INT_OFF;
Denis Vlasenko28bf6712008-02-14 15:01:47 +000010038 retval = 1;
10039 if (!options(0)) { /* if no parse error... */
10040 retval = 0;
10041 optschanged();
10042 if (*argptr != NULL) {
10043 setparam(argptr);
10044 }
Eric Andersencb57d552001-06-28 07:25:16 +000010045 }
Denis Vlasenkob012b102007-02-19 22:43:01 +000010046 INT_ON;
Denis Vlasenko28bf6712008-02-14 15:01:47 +000010047 return retval;
Eric Andersencb57d552001-06-28 07:25:16 +000010048}
10049
Denis Vlasenko131ae172007-02-18 13:00:19 +000010050#if ENABLE_ASH_RANDOM_SUPPORT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010051static void FAST_FUNC
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000010052change_random(const char *value)
Eric Andersenef02f822004-03-11 13:34:24 +000010053{
Denis Vlasenko448d30e2008-06-27 00:24:11 +000010054 /* Galois LFSR parameter */
10055 /* Taps at 32 31 29 1: */
10056 enum { MASK = 0x8000000b };
10057 /* Another example - taps at 32 31 30 10: */
10058 /* MASK = 0x00400007 */
10059
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010060 if (value == NULL) {
Eric Andersen16767e22004-03-16 05:14:10 +000010061 /* "get", generate */
Denis Vlasenko448d30e2008-06-27 00:24:11 +000010062 uint32_t t;
Eric Andersen16767e22004-03-16 05:14:10 +000010063
Denis Vlasenko448d30e2008-06-27 00:24:11 +000010064 /* LCG has period of 2^32 and alternating lowest bit */
10065 random_LCG = 1664525 * random_LCG + 1013904223;
10066 /* Galois LFSR has period of 2^32-1 = 3 * 5 * 17 * 257 * 65537 */
10067 t = (random_galois_LFSR << 1);
10068 if (random_galois_LFSR < 0) /* if we just shifted 1 out of msb... */
10069 t ^= MASK;
10070 random_galois_LFSR = t;
Denis Vlasenkoce13b762008-06-29 02:25:53 +000010071 /* Both are weak, combining them gives better randomness
Denis Vlasenko448d30e2008-06-27 00:24:11 +000010072 * and ~2^64 period. & 0x7fff is probably bash compat
Denis Vlasenkoce13b762008-06-29 02:25:53 +000010073 * for $RANDOM range. Combining with subtraction is
10074 * just for fun. + and ^ would work equally well. */
10075 t = (t - random_LCG) & 0x7fff;
Eric Andersen16767e22004-03-16 05:14:10 +000010076 /* set without recursion */
Denis Vlasenko448d30e2008-06-27 00:24:11 +000010077 setvar(vrandom.text, utoa(t), VNOFUNC);
Eric Andersen16767e22004-03-16 05:14:10 +000010078 vrandom.flags &= ~VNOFUNC;
10079 } else {
10080 /* set/reset */
Denys Vlasenko1f27ab02009-09-23 17:17:53 +020010081 random_galois_LFSR = random_LCG = strtoul(value, NULL, 10);
Eric Andersen16767e22004-03-16 05:14:10 +000010082 }
Eric Andersenef02f822004-03-11 13:34:24 +000010083}
Eric Andersen16767e22004-03-16 05:14:10 +000010084#endif
10085
Denis Vlasenko131ae172007-02-18 13:00:19 +000010086#if ENABLE_ASH_GETOPTS
Eric Andersencb57d552001-06-28 07:25:16 +000010087static int
Eric Andersenc470f442003-07-28 09:56:35 +000010088getopts(char *optstr, char *optvar, char **optfirst, int *param_optind, int *optoff)
Eric Andersencb57d552001-06-28 07:25:16 +000010089{
10090 char *p, *q;
10091 char c = '?';
10092 int done = 0;
10093 int err = 0;
Eric Andersena48b0a32003-10-22 10:56:47 +000010094 char s[12];
10095 char **optnext;
Eric Andersencb57d552001-06-28 07:25:16 +000010096
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010097 if (*param_optind < 1)
Eric Andersena48b0a32003-10-22 10:56:47 +000010098 return 1;
10099 optnext = optfirst + *param_optind - 1;
10100
Denis Vlasenko6b06cb82008-05-15 21:30:45 +000010101 if (*param_optind <= 1 || *optoff < 0 || (int)strlen(optnext[-1]) < *optoff)
Eric Andersencb57d552001-06-28 07:25:16 +000010102 p = NULL;
10103 else
Eric Andersena48b0a32003-10-22 10:56:47 +000010104 p = optnext[-1] + *optoff;
Eric Andersencb57d552001-06-28 07:25:16 +000010105 if (p == NULL || *p == '\0') {
10106 /* Current word is done, advance */
Eric Andersencb57d552001-06-28 07:25:16 +000010107 p = *optnext;
10108 if (p == NULL || *p != '-' || *++p == '\0') {
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010109 atend:
Eric Andersencb57d552001-06-28 07:25:16 +000010110 p = NULL;
10111 done = 1;
10112 goto out;
10113 }
10114 optnext++;
Denis Vlasenko9f739442006-12-16 23:49:13 +000010115 if (LONE_DASH(p)) /* check for "--" */
Eric Andersencb57d552001-06-28 07:25:16 +000010116 goto atend;
10117 }
10118
10119 c = *p++;
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +000010120 for (q = optstr; *q != c;) {
Eric Andersencb57d552001-06-28 07:25:16 +000010121 if (*q == '\0') {
10122 if (optstr[0] == ':') {
10123 s[0] = c;
10124 s[1] = '\0';
10125 err |= setvarsafe("OPTARG", s, 0);
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010126 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000010127 fprintf(stderr, "Illegal option -%c\n", c);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010128 unsetvar("OPTARG");
Eric Andersencb57d552001-06-28 07:25:16 +000010129 }
10130 c = '?';
Eric Andersenc470f442003-07-28 09:56:35 +000010131 goto out;
Eric Andersencb57d552001-06-28 07:25:16 +000010132 }
10133 if (*++q == ':')
10134 q++;
10135 }
10136
10137 if (*++q == ':') {
10138 if (*p == '\0' && (p = *optnext) == NULL) {
10139 if (optstr[0] == ':') {
10140 s[0] = c;
10141 s[1] = '\0';
10142 err |= setvarsafe("OPTARG", s, 0);
10143 c = ':';
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010144 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000010145 fprintf(stderr, "No arg for -%c option\n", c);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010146 unsetvar("OPTARG");
Eric Andersencb57d552001-06-28 07:25:16 +000010147 c = '?';
10148 }
Eric Andersenc470f442003-07-28 09:56:35 +000010149 goto out;
Eric Andersencb57d552001-06-28 07:25:16 +000010150 }
10151
10152 if (p == *optnext)
10153 optnext++;
Eric Andersenc470f442003-07-28 09:56:35 +000010154 err |= setvarsafe("OPTARG", p, 0);
Eric Andersencb57d552001-06-28 07:25:16 +000010155 p = NULL;
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010156 } else
Eric Andersenc470f442003-07-28 09:56:35 +000010157 err |= setvarsafe("OPTARG", nullstr, 0);
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010158 out:
Eric Andersencb57d552001-06-28 07:25:16 +000010159 *optoff = p ? p - *(optnext - 1) : -1;
Eric Andersenc470f442003-07-28 09:56:35 +000010160 *param_optind = optnext - optfirst + 1;
10161 fmtstr(s, sizeof(s), "%d", *param_optind);
Eric Andersencb57d552001-06-28 07:25:16 +000010162 err |= setvarsafe("OPTIND", s, VNOFUNC);
10163 s[0] = c;
10164 s[1] = '\0';
10165 err |= setvarsafe(optvar, s, 0);
10166 if (err) {
Eric Andersenc470f442003-07-28 09:56:35 +000010167 *param_optind = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010168 *optoff = -1;
Denis Vlasenkob012b102007-02-19 22:43:01 +000010169 flush_stdout_stderr();
10170 raise_exception(EXERROR);
Eric Andersencb57d552001-06-28 07:25:16 +000010171 }
10172 return done;
10173}
Eric Andersenc470f442003-07-28 09:56:35 +000010174
10175/*
10176 * The getopts builtin. Shellparam.optnext points to the next argument
10177 * to be processed. Shellparam.optptr points to the next character to
10178 * be processed in the current argument. If shellparam.optnext is NULL,
10179 * then it's the first time getopts has been called.
10180 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010181static int FAST_FUNC
Eric Andersenc470f442003-07-28 09:56:35 +000010182getoptscmd(int argc, char **argv)
10183{
10184 char **optbase;
10185
10186 if (argc < 3)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +000010187 ash_msg_and_raise_error("usage: getopts optstring var [arg]");
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010188 if (argc == 3) {
Eric Andersenc470f442003-07-28 09:56:35 +000010189 optbase = shellparam.p;
10190 if (shellparam.optind > shellparam.nparam + 1) {
10191 shellparam.optind = 1;
10192 shellparam.optoff = -1;
10193 }
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010194 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000010195 optbase = &argv[3];
10196 if (shellparam.optind > argc - 2) {
10197 shellparam.optind = 1;
10198 shellparam.optoff = -1;
10199 }
10200 }
10201
10202 return getopts(argv[1], argv[2], optbase, &shellparam.optind,
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010203 &shellparam.optoff);
Eric Andersenc470f442003-07-28 09:56:35 +000010204}
Denis Vlasenko131ae172007-02-18 13:00:19 +000010205#endif /* ASH_GETOPTS */
Eric Andersencb57d552001-06-28 07:25:16 +000010206
Eric Andersencb57d552001-06-28 07:25:16 +000010207
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010208/* ============ Shell parser */
Eric Andersencb57d552001-06-28 07:25:16 +000010209
Denis Vlasenkob07a4962008-06-22 13:16:23 +000010210struct heredoc {
10211 struct heredoc *next; /* next here document in list */
10212 union node *here; /* redirection node */
10213 char *eofmark; /* string indicating end of input */
10214 smallint striptabs; /* if set, strip leading tabs */
10215};
10216
10217static smallint tokpushback; /* last token pushed back */
10218static smallint parsebackquote; /* nonzero if we are inside backquotes */
10219static smallint quoteflag; /* set if (part of) last token was quoted */
10220static token_id_t lasttoken; /* last token read (integer id Txxx) */
10221static struct heredoc *heredoclist; /* list of here documents to read */
10222static char *wordtext; /* text of last word returned by readtoken */
10223static struct nodelist *backquotelist;
10224static union node *redirnode;
10225static struct heredoc *heredoc;
Denis Vlasenko99eb8502007-02-23 21:09:49 +000010226
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010227/*
10228 * Called when an unexpected token is read during the parse. The argument
10229 * is the token that is expected, or -1 if more than one type of token can
10230 * occur at this point.
10231 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000010232static void raise_error_unexpected_syntax(int) NORETURN;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010233static void
10234raise_error_unexpected_syntax(int token)
10235{
10236 char msg[64];
10237 int l;
10238
Denis Vlasenko7b2294e2008-11-28 03:50:46 +000010239 l = sprintf(msg, "unexpected %s", tokname(lasttoken));
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010240 if (token >= 0)
10241 sprintf(msg + l, " (expecting %s)", tokname(token));
10242 raise_error_syntax(msg);
10243 /* NOTREACHED */
10244}
Eric Andersencb57d552001-06-28 07:25:16 +000010245
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010246#define EOFMARKLEN 79
Eric Andersencb57d552001-06-28 07:25:16 +000010247
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010248/* parsing is heavily cross-recursive, need these forward decls */
10249static union node *andor(void);
10250static union node *pipeline(void);
10251static union node *parse_command(void);
10252static void parseheredoc(void);
10253static char peektoken(void);
10254static int readtoken(void);
Eric Andersencb57d552001-06-28 07:25:16 +000010255
Eric Andersenc470f442003-07-28 09:56:35 +000010256static union node *
10257list(int nlflag)
Eric Andersencb57d552001-06-28 07:25:16 +000010258{
10259 union node *n1, *n2, *n3;
10260 int tok;
10261
Eric Andersenc470f442003-07-28 09:56:35 +000010262 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10263 if (nlflag == 2 && peektoken())
Eric Andersencb57d552001-06-28 07:25:16 +000010264 return NULL;
10265 n1 = NULL;
10266 for (;;) {
10267 n2 = andor();
10268 tok = readtoken();
10269 if (tok == TBACKGND) {
Eric Andersenc470f442003-07-28 09:56:35 +000010270 if (n2->type == NPIPE) {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +000010271 n2->npipe.pipe_backgnd = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010272 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000010273 if (n2->type != NREDIR) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010274 n3 = stzalloc(sizeof(struct nredir));
Eric Andersenc470f442003-07-28 09:56:35 +000010275 n3->nredir.n = n2;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010276 /*n3->nredir.redirect = NULL; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000010277 n2 = n3;
10278 }
10279 n2->type = NBACKGND;
Eric Andersencb57d552001-06-28 07:25:16 +000010280 }
10281 }
10282 if (n1 == NULL) {
10283 n1 = n2;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010284 } else {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010285 n3 = stzalloc(sizeof(struct nbinary));
Eric Andersencb57d552001-06-28 07:25:16 +000010286 n3->type = NSEMI;
10287 n3->nbinary.ch1 = n1;
10288 n3->nbinary.ch2 = n2;
10289 n1 = n3;
10290 }
10291 switch (tok) {
10292 case TBACKGND:
10293 case TSEMI:
10294 tok = readtoken();
10295 /* fall through */
10296 case TNL:
10297 if (tok == TNL) {
10298 parseheredoc();
Eric Andersenc470f442003-07-28 09:56:35 +000010299 if (nlflag == 1)
Eric Andersencb57d552001-06-28 07:25:16 +000010300 return n1;
10301 } else {
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010302 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010303 }
Eric Andersenc470f442003-07-28 09:56:35 +000010304 checkkwd = CHKNL | CHKKWD | CHKALIAS;
Manuel Novoa III 16815d42001-08-10 19:36:07 +000010305 if (peektoken())
Eric Andersencb57d552001-06-28 07:25:16 +000010306 return n1;
10307 break;
10308 case TEOF:
10309 if (heredoclist)
10310 parseheredoc();
10311 else
Eric Andersenc470f442003-07-28 09:56:35 +000010312 pungetc(); /* push back EOF on input */
Eric Andersencb57d552001-06-28 07:25:16 +000010313 return n1;
10314 default:
Eric Andersenc470f442003-07-28 09:56:35 +000010315 if (nlflag == 1)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010316 raise_error_unexpected_syntax(-1);
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010317 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010318 return n1;
10319 }
10320 }
10321}
10322
Eric Andersenc470f442003-07-28 09:56:35 +000010323static union node *
10324andor(void)
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010325{
Eric Andersencb57d552001-06-28 07:25:16 +000010326 union node *n1, *n2, *n3;
10327 int t;
10328
Eric Andersencb57d552001-06-28 07:25:16 +000010329 n1 = pipeline();
10330 for (;;) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010331 t = readtoken();
10332 if (t == TAND) {
Eric Andersencb57d552001-06-28 07:25:16 +000010333 t = NAND;
10334 } else if (t == TOR) {
10335 t = NOR;
10336 } else {
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010337 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010338 return n1;
10339 }
Eric Andersenc470f442003-07-28 09:56:35 +000010340 checkkwd = CHKNL | CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010341 n2 = pipeline();
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010342 n3 = stzalloc(sizeof(struct nbinary));
Eric Andersencb57d552001-06-28 07:25:16 +000010343 n3->type = t;
10344 n3->nbinary.ch1 = n1;
10345 n3->nbinary.ch2 = n2;
10346 n1 = n3;
10347 }
10348}
10349
Eric Andersenc470f442003-07-28 09:56:35 +000010350static union node *
10351pipeline(void)
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010352{
Eric Andersencb57d552001-06-28 07:25:16 +000010353 union node *n1, *n2, *pipenode;
10354 struct nodelist *lp, *prev;
10355 int negate;
10356
10357 negate = 0;
10358 TRACE(("pipeline: entered\n"));
10359 if (readtoken() == TNOT) {
10360 negate = !negate;
Eric Andersenc470f442003-07-28 09:56:35 +000010361 checkkwd = CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010362 } else
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010363 tokpushback = 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010364 n1 = parse_command();
Eric Andersencb57d552001-06-28 07:25:16 +000010365 if (readtoken() == TPIPE) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010366 pipenode = stzalloc(sizeof(struct npipe));
Eric Andersencb57d552001-06-28 07:25:16 +000010367 pipenode->type = NPIPE;
Denis Vlasenko2dc240c2008-07-24 06:07:50 +000010368 /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010369 lp = stzalloc(sizeof(struct nodelist));
Eric Andersencb57d552001-06-28 07:25:16 +000010370 pipenode->npipe.cmdlist = lp;
10371 lp->n = n1;
10372 do {
10373 prev = lp;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010374 lp = stzalloc(sizeof(struct nodelist));
Eric Andersenc470f442003-07-28 09:56:35 +000010375 checkkwd = CHKNL | CHKKWD | CHKALIAS;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010376 lp->n = parse_command();
Eric Andersencb57d552001-06-28 07:25:16 +000010377 prev->next = lp;
10378 } while (readtoken() == TPIPE);
10379 lp->next = NULL;
10380 n1 = pipenode;
10381 }
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010382 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010383 if (negate) {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010384 n2 = stzalloc(sizeof(struct nnot));
Eric Andersencb57d552001-06-28 07:25:16 +000010385 n2->type = NNOT;
10386 n2->nnot.com = n1;
10387 return n2;
Denis Vlasenko2da584f2007-02-19 22:44:05 +000010388 }
10389 return n1;
Eric Andersencb57d552001-06-28 07:25:16 +000010390}
10391
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010392static union node *
10393makename(void)
10394{
10395 union node *n;
10396
Denis Vlasenko597906c2008-02-20 16:38:54 +000010397 n = stzalloc(sizeof(struct narg));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010398 n->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010399 /*n->narg.next = NULL; - stzalloc did it */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010400 n->narg.text = wordtext;
10401 n->narg.backquote = backquotelist;
10402 return n;
10403}
10404
10405static void
10406fixredir(union node *n, const char *text, int err)
10407{
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000010408 int fd;
10409
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010410 TRACE(("Fix redir %s %d\n", text, err));
10411 if (!err)
10412 n->ndup.vname = NULL;
10413
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000010414 fd = bb_strtou(text, NULL, 10);
10415 if (!errno && fd >= 0)
10416 n->ndup.dupfd = fd;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010417 else if (LONE_DASH(text))
10418 n->ndup.dupfd = -1;
10419 else {
10420 if (err)
Denis Vlasenko559691a2008-10-05 18:39:31 +000010421 raise_error_syntax("bad fd number");
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010422 n->ndup.vname = makename();
10423 }
10424}
10425
10426/*
10427 * Returns true if the text contains nothing to expand (no dollar signs
10428 * or backquotes).
10429 */
10430static int
Denis Vlasenko68819d12008-12-15 11:26:36 +000010431noexpand(const char *text)
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010432{
Denis Vlasenko68819d12008-12-15 11:26:36 +000010433 const char *p;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010434 char c;
10435
10436 p = text;
10437 while ((c = *p++) != '\0') {
10438 if (c == CTLQUOTEMARK)
10439 continue;
10440 if (c == CTLESC)
10441 p++;
Denis Vlasenko68819d12008-12-15 11:26:36 +000010442 else if (SIT((signed char)c, BASESYNTAX) == CCTL)
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010443 return 0;
10444 }
10445 return 1;
10446}
10447
10448static void
10449parsefname(void)
10450{
10451 union node *n = redirnode;
10452
10453 if (readtoken() != TWORD)
10454 raise_error_unexpected_syntax(-1);
10455 if (n->type == NHERE) {
10456 struct heredoc *here = heredoc;
10457 struct heredoc *p;
10458 int i;
10459
10460 if (quoteflag == 0)
10461 n->type = NXHERE;
10462 TRACE(("Here document %d\n", n->type));
10463 if (!noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
Denis Vlasenko559691a2008-10-05 18:39:31 +000010464 raise_error_syntax("illegal eof marker for << redirection");
Denys Vlasenkob6c84342009-08-29 20:23:20 +020010465 rmescapes(wordtext, 0);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010466 here->eofmark = wordtext;
10467 here->next = NULL;
10468 if (heredoclist == NULL)
10469 heredoclist = here;
10470 else {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010471 for (p = heredoclist; p->next; p = p->next)
10472 continue;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010473 p->next = here;
10474 }
10475 } else if (n->type == NTOFD || n->type == NFROMFD) {
10476 fixredir(n, wordtext, 0);
10477 } else {
10478 n->nfile.fname = makename();
10479 }
10480}
Eric Andersencb57d552001-06-28 07:25:16 +000010481
Eric Andersenc470f442003-07-28 09:56:35 +000010482static union node *
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010483simplecmd(void)
10484{
10485 union node *args, **app;
10486 union node *n = NULL;
10487 union node *vars, **vpp;
10488 union node **rpp, *redir;
10489 int savecheckkwd;
Denis Vlasenko80591b02008-03-25 07:49:43 +000010490#if ENABLE_ASH_BASH_COMPAT
10491 smallint double_brackets_flag = 0;
10492#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010493
10494 args = NULL;
10495 app = &args;
10496 vars = NULL;
10497 vpp = &vars;
10498 redir = NULL;
10499 rpp = &redir;
10500
10501 savecheckkwd = CHKALIAS;
10502 for (;;) {
Denis Vlasenko80591b02008-03-25 07:49:43 +000010503 int t;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010504 checkkwd = savecheckkwd;
Denis Vlasenko80591b02008-03-25 07:49:43 +000010505 t = readtoken();
10506 switch (t) {
10507#if ENABLE_ASH_BASH_COMPAT
10508 case TAND: /* "&&" */
10509 case TOR: /* "||" */
10510 if (!double_brackets_flag) {
10511 tokpushback = 1;
10512 goto out;
10513 }
10514 wordtext = (char *) (t == TAND ? "-a" : "-o");
10515#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010516 case TWORD:
Denis Vlasenko597906c2008-02-20 16:38:54 +000010517 n = stzalloc(sizeof(struct narg));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010518 n->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010519 /*n->narg.next = NULL; - stzalloc did it */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010520 n->narg.text = wordtext;
Denis Vlasenko80591b02008-03-25 07:49:43 +000010521#if ENABLE_ASH_BASH_COMPAT
10522 if (strcmp("[[", wordtext) == 0)
10523 double_brackets_flag = 1;
10524 else if (strcmp("]]", wordtext) == 0)
10525 double_brackets_flag = 0;
10526#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010527 n->narg.backquote = backquotelist;
10528 if (savecheckkwd && isassignment(wordtext)) {
10529 *vpp = n;
10530 vpp = &n->narg.next;
10531 } else {
10532 *app = n;
10533 app = &n->narg.next;
10534 savecheckkwd = 0;
10535 }
10536 break;
10537 case TREDIR:
10538 *rpp = n = redirnode;
10539 rpp = &n->nfile.next;
10540 parsefname(); /* read name of redirection file */
10541 break;
10542 case TLP:
10543 if (args && app == &args->narg.next
10544 && !vars && !redir
10545 ) {
10546 struct builtincmd *bcmd;
10547 const char *name;
10548
10549 /* We have a function */
10550 if (readtoken() != TRP)
10551 raise_error_unexpected_syntax(TRP);
10552 name = n->narg.text;
10553 if (!goodname(name)
10554 || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
10555 ) {
Denis Vlasenko559691a2008-10-05 18:39:31 +000010556 raise_error_syntax("bad function name");
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010557 }
10558 n->type = NDEFUN;
10559 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10560 n->narg.next = parse_command();
10561 return n;
10562 }
10563 /* fall through */
10564 default:
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010565 tokpushback = 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010566 goto out;
10567 }
10568 }
10569 out:
10570 *app = NULL;
10571 *vpp = NULL;
10572 *rpp = NULL;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010573 n = stzalloc(sizeof(struct ncmd));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010574 n->type = NCMD;
10575 n->ncmd.args = args;
10576 n->ncmd.assign = vars;
10577 n->ncmd.redirect = redir;
10578 return n;
10579}
10580
10581static union node *
10582parse_command(void)
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010583{
Eric Andersencb57d552001-06-28 07:25:16 +000010584 union node *n1, *n2;
10585 union node *ap, **app;
10586 union node *cp, **cpp;
10587 union node *redir, **rpp;
Eric Andersenc470f442003-07-28 09:56:35 +000010588 union node **rpp2;
Eric Andersencb57d552001-06-28 07:25:16 +000010589 int t;
10590
10591 redir = NULL;
Eric Andersenc470f442003-07-28 09:56:35 +000010592 rpp2 = &redir;
Eric Andersen88cec252001-09-06 17:35:20 +000010593
Eric Andersencb57d552001-06-28 07:25:16 +000010594 switch (readtoken()) {
Eric Andersenc470f442003-07-28 09:56:35 +000010595 default:
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010596 raise_error_unexpected_syntax(-1);
Eric Andersenc470f442003-07-28 09:56:35 +000010597 /* NOTREACHED */
Eric Andersencb57d552001-06-28 07:25:16 +000010598 case TIF:
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010599 n1 = stzalloc(sizeof(struct nif));
Eric Andersencb57d552001-06-28 07:25:16 +000010600 n1->type = NIF;
10601 n1->nif.test = list(0);
10602 if (readtoken() != TTHEN)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010603 raise_error_unexpected_syntax(TTHEN);
Eric Andersencb57d552001-06-28 07:25:16 +000010604 n1->nif.ifpart = list(0);
10605 n2 = n1;
10606 while (readtoken() == TELIF) {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010607 n2->nif.elsepart = stzalloc(sizeof(struct nif));
Eric Andersencb57d552001-06-28 07:25:16 +000010608 n2 = n2->nif.elsepart;
10609 n2->type = NIF;
10610 n2->nif.test = list(0);
10611 if (readtoken() != TTHEN)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010612 raise_error_unexpected_syntax(TTHEN);
Eric Andersencb57d552001-06-28 07:25:16 +000010613 n2->nif.ifpart = list(0);
10614 }
10615 if (lasttoken == TELSE)
10616 n2->nif.elsepart = list(0);
10617 else {
10618 n2->nif.elsepart = NULL;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010619 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010620 }
Eric Andersenc470f442003-07-28 09:56:35 +000010621 t = TFI;
Eric Andersencb57d552001-06-28 07:25:16 +000010622 break;
10623 case TWHILE:
Eric Andersenc470f442003-07-28 09:56:35 +000010624 case TUNTIL: {
Eric Andersencb57d552001-06-28 07:25:16 +000010625 int got;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010626 n1 = stzalloc(sizeof(struct nbinary));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010627 n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
Eric Andersencb57d552001-06-28 07:25:16 +000010628 n1->nbinary.ch1 = list(0);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010629 got = readtoken();
10630 if (got != TDO) {
Denis Vlasenko131ae172007-02-18 13:00:19 +000010631 TRACE(("expecting DO got %s %s\n", tokname(got),
10632 got == TWORD ? wordtext : ""));
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010633 raise_error_unexpected_syntax(TDO);
Eric Andersencb57d552001-06-28 07:25:16 +000010634 }
10635 n1->nbinary.ch2 = list(0);
Eric Andersenc470f442003-07-28 09:56:35 +000010636 t = TDONE;
Eric Andersencb57d552001-06-28 07:25:16 +000010637 break;
10638 }
10639 case TFOR:
Denis Vlasenko2dc240c2008-07-24 06:07:50 +000010640 if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
Denis Vlasenko559691a2008-10-05 18:39:31 +000010641 raise_error_syntax("bad for loop variable");
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010642 n1 = stzalloc(sizeof(struct nfor));
Eric Andersencb57d552001-06-28 07:25:16 +000010643 n1->type = NFOR;
10644 n1->nfor.var = wordtext;
Eric Andersenc470f442003-07-28 09:56:35 +000010645 checkkwd = CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010646 if (readtoken() == TIN) {
10647 app = &ap;
10648 while (readtoken() == TWORD) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010649 n2 = stzalloc(sizeof(struct narg));
Eric Andersencb57d552001-06-28 07:25:16 +000010650 n2->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010651 /*n2->narg.next = NULL; - stzalloc did it */
Eric Andersencb57d552001-06-28 07:25:16 +000010652 n2->narg.text = wordtext;
10653 n2->narg.backquote = backquotelist;
10654 *app = n2;
10655 app = &n2->narg.next;
10656 }
10657 *app = NULL;
10658 n1->nfor.args = ap;
10659 if (lasttoken != TNL && lasttoken != TSEMI)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010660 raise_error_unexpected_syntax(-1);
Eric Andersencb57d552001-06-28 07:25:16 +000010661 } else {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010662 n2 = stzalloc(sizeof(struct narg));
Eric Andersencb57d552001-06-28 07:25:16 +000010663 n2->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010664 /*n2->narg.next = NULL; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000010665 n2->narg.text = (char *)dolatstr;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010666 /*n2->narg.backquote = NULL;*/
Eric Andersencb57d552001-06-28 07:25:16 +000010667 n1->nfor.args = n2;
10668 /*
10669 * Newline or semicolon here is optional (but note
10670 * that the original Bourne shell only allowed NL).
10671 */
10672 if (lasttoken != TNL && lasttoken != TSEMI)
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010673 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010674 }
Eric Andersenc470f442003-07-28 09:56:35 +000010675 checkkwd = CHKNL | CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010676 if (readtoken() != TDO)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010677 raise_error_unexpected_syntax(TDO);
Eric Andersencb57d552001-06-28 07:25:16 +000010678 n1->nfor.body = list(0);
Eric Andersenc470f442003-07-28 09:56:35 +000010679 t = TDONE;
Eric Andersencb57d552001-06-28 07:25:16 +000010680 break;
10681 case TCASE:
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010682 n1 = stzalloc(sizeof(struct ncase));
Eric Andersencb57d552001-06-28 07:25:16 +000010683 n1->type = NCASE;
10684 if (readtoken() != TWORD)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010685 raise_error_unexpected_syntax(TWORD);
Denis Vlasenko597906c2008-02-20 16:38:54 +000010686 n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
Eric Andersencb57d552001-06-28 07:25:16 +000010687 n2->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010688 /*n2->narg.next = NULL; - stzalloc did it */
Eric Andersencb57d552001-06-28 07:25:16 +000010689 n2->narg.text = wordtext;
10690 n2->narg.backquote = backquotelist;
Eric Andersencb57d552001-06-28 07:25:16 +000010691 do {
Eric Andersenc470f442003-07-28 09:56:35 +000010692 checkkwd = CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010693 } while (readtoken() == TNL);
10694 if (lasttoken != TIN)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010695 raise_error_unexpected_syntax(TIN);
Eric Andersencb57d552001-06-28 07:25:16 +000010696 cpp = &n1->ncase.cases;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010697 next_case:
Eric Andersenc470f442003-07-28 09:56:35 +000010698 checkkwd = CHKNL | CHKKWD;
10699 t = readtoken();
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010700 while (t != TESAC) {
Eric Andersencb57d552001-06-28 07:25:16 +000010701 if (lasttoken == TLP)
10702 readtoken();
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010703 *cpp = cp = stzalloc(sizeof(struct nclist));
Eric Andersencb57d552001-06-28 07:25:16 +000010704 cp->type = NCLIST;
10705 app = &cp->nclist.pattern;
10706 for (;;) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010707 *app = ap = stzalloc(sizeof(struct narg));
Eric Andersencb57d552001-06-28 07:25:16 +000010708 ap->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010709 /*ap->narg.next = NULL; - stzalloc did it */
Eric Andersencb57d552001-06-28 07:25:16 +000010710 ap->narg.text = wordtext;
10711 ap->narg.backquote = backquotelist;
Eric Andersenc470f442003-07-28 09:56:35 +000010712 if (readtoken() != TPIPE)
Eric Andersencb57d552001-06-28 07:25:16 +000010713 break;
10714 app = &ap->narg.next;
10715 readtoken();
10716 }
Denis Vlasenko597906c2008-02-20 16:38:54 +000010717 //ap->narg.next = NULL;
Eric Andersencb57d552001-06-28 07:25:16 +000010718 if (lasttoken != TRP)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010719 raise_error_unexpected_syntax(TRP);
Eric Andersenc470f442003-07-28 09:56:35 +000010720 cp->nclist.body = list(2);
Eric Andersencb57d552001-06-28 07:25:16 +000010721
Eric Andersenc470f442003-07-28 09:56:35 +000010722 cpp = &cp->nclist.next;
10723
10724 checkkwd = CHKNL | CHKKWD;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010725 t = readtoken();
10726 if (t != TESAC) {
Eric Andersencb57d552001-06-28 07:25:16 +000010727 if (t != TENDCASE)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010728 raise_error_unexpected_syntax(TENDCASE);
10729 goto next_case;
Eric Andersencb57d552001-06-28 07:25:16 +000010730 }
Eric Andersenc470f442003-07-28 09:56:35 +000010731 }
Eric Andersencb57d552001-06-28 07:25:16 +000010732 *cpp = NULL;
Eric Andersenc470f442003-07-28 09:56:35 +000010733 goto redir;
Eric Andersencb57d552001-06-28 07:25:16 +000010734 case TLP:
Denis Vlasenko597906c2008-02-20 16:38:54 +000010735 n1 = stzalloc(sizeof(struct nredir));
Eric Andersencb57d552001-06-28 07:25:16 +000010736 n1->type = NSUBSHELL;
10737 n1->nredir.n = list(0);
Denis Vlasenko597906c2008-02-20 16:38:54 +000010738 /*n1->nredir.redirect = NULL; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000010739 t = TRP;
Eric Andersencb57d552001-06-28 07:25:16 +000010740 break;
10741 case TBEGIN:
10742 n1 = list(0);
Eric Andersenc470f442003-07-28 09:56:35 +000010743 t = TEND;
Eric Andersencb57d552001-06-28 07:25:16 +000010744 break;
Eric Andersencb57d552001-06-28 07:25:16 +000010745 case TWORD:
Eric Andersenc470f442003-07-28 09:56:35 +000010746 case TREDIR:
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010747 tokpushback = 1;
Eric Andersenc470f442003-07-28 09:56:35 +000010748 return simplecmd();
Eric Andersencb57d552001-06-28 07:25:16 +000010749 }
10750
Eric Andersenc470f442003-07-28 09:56:35 +000010751 if (readtoken() != t)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010752 raise_error_unexpected_syntax(t);
Eric Andersenc470f442003-07-28 09:56:35 +000010753
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010754 redir:
Eric Andersencb57d552001-06-28 07:25:16 +000010755 /* Now check for redirection which may follow command */
Eric Andersenc470f442003-07-28 09:56:35 +000010756 checkkwd = CHKKWD | CHKALIAS;
10757 rpp = rpp2;
Eric Andersencb57d552001-06-28 07:25:16 +000010758 while (readtoken() == TREDIR) {
10759 *rpp = n2 = redirnode;
10760 rpp = &n2->nfile.next;
10761 parsefname();
10762 }
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010763 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010764 *rpp = NULL;
10765 if (redir) {
10766 if (n1->type != NSUBSHELL) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010767 n2 = stzalloc(sizeof(struct nredir));
Eric Andersencb57d552001-06-28 07:25:16 +000010768 n2->type = NREDIR;
10769 n2->nredir.n = n1;
10770 n1 = n2;
10771 }
10772 n1->nredir.redirect = redir;
10773 }
Eric Andersencb57d552001-06-28 07:25:16 +000010774 return n1;
10775}
10776
Denis Vlasenkoef527f52008-06-23 01:52:30 +000010777#if ENABLE_ASH_BASH_COMPAT
10778static int decode_dollar_squote(void)
10779{
10780 static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
10781 int c, cnt;
10782 char *p;
10783 char buf[4];
10784
10785 c = pgetc();
10786 p = strchr(C_escapes, c);
10787 if (p) {
10788 buf[0] = c;
10789 p = buf;
10790 cnt = 3;
10791 if ((unsigned char)(c - '0') <= 7) { /* \ooo */
10792 do {
10793 c = pgetc();
10794 *++p = c;
10795 } while ((unsigned char)(c - '0') <= 7 && --cnt);
10796 pungetc();
10797 } else if (c == 'x') { /* \xHH */
10798 do {
10799 c = pgetc();
10800 *++p = c;
10801 } while (isxdigit(c) && --cnt);
10802 pungetc();
10803 if (cnt == 3) { /* \x but next char is "bad" */
10804 c = 'x';
10805 goto unrecognized;
10806 }
10807 } else { /* simple seq like \\ or \t */
10808 p++;
10809 }
10810 *p = '\0';
10811 p = buf;
10812 c = bb_process_escape_sequence((void*)&p);
10813 } else { /* unrecognized "\z": print both chars unless ' or " */
10814 if (c != '\'' && c != '"') {
10815 unrecognized:
10816 c |= 0x100; /* "please encode \, then me" */
10817 }
10818 }
10819 return c;
10820}
10821#endif
10822
Eric Andersencb57d552001-06-28 07:25:16 +000010823/*
10824 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
10825 * is not NULL, read a here document. In the latter case, eofmark is the
10826 * word which marks the end of the document and striptabs is true if
10827 * leading tabs should be stripped from the document. The argument firstc
10828 * is the first character of the input token or document.
10829 *
10830 * Because C does not have internal subroutines, I have simulated them
10831 * using goto's to implement the subroutine linkage. The following macros
10832 * will run code that appears at the end of readtoken1.
10833 */
Eric Andersen2870d962001-07-02 17:27:21 +000010834#define CHECKEND() {goto checkend; checkend_return:;}
10835#define PARSEREDIR() {goto parseredir; parseredir_return:;}
10836#define PARSESUB() {goto parsesub; parsesub_return:;}
10837#define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
10838#define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
10839#define PARSEARITH() {goto parsearith; parsearith_return:;}
Eric Andersencb57d552001-06-28 07:25:16 +000010840static int
Eric Andersenc470f442003-07-28 09:56:35 +000010841readtoken1(int firstc, int syntax, char *eofmark, int striptabs)
Manuel Novoa III 16815d42001-08-10 19:36:07 +000010842{
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010843 /* NB: syntax parameter fits into smallint */
Eric Andersencb57d552001-06-28 07:25:16 +000010844 int c = firstc;
10845 char *out;
10846 int len;
10847 char line[EOFMARKLEN + 1];
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010848 struct nodelist *bqlist;
10849 smallint quotef;
10850 smallint dblquote;
10851 smallint oldstyle;
10852 smallint prevsyntax; /* syntax before arithmetic */
Denis Vlasenko46a53062007-09-24 18:30:02 +000010853#if ENABLE_ASH_EXPAND_PRMT
10854 smallint pssyntax; /* we are expanding a prompt string */
10855#endif
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010856 int varnest; /* levels of variables expansion */
10857 int arinest; /* levels of arithmetic expansion */
10858 int parenlevel; /* levels of parens in arithmetic */
10859 int dqvarnest; /* levels of variables expansion within double quotes */
10860
Denis Vlasenko5e34ff22009-04-21 11:09:40 +000010861 IF_ASH_BASH_COMPAT(smallint bash_dollar_squote = 0;)
Denis Vlasenkoef527f52008-06-23 01:52:30 +000010862
Eric Andersencb57d552001-06-28 07:25:16 +000010863#if __GNUC__
10864 /* Avoid longjmp clobbering */
10865 (void) &out;
10866 (void) &quotef;
10867 (void) &dblquote;
10868 (void) &varnest;
10869 (void) &arinest;
10870 (void) &parenlevel;
10871 (void) &dqvarnest;
10872 (void) &oldstyle;
10873 (void) &prevsyntax;
10874 (void) &syntax;
10875#endif
Denis Vlasenko41eb3002008-11-28 03:42:31 +000010876 startlinno = g_parsefile->linno;
Eric Andersencb57d552001-06-28 07:25:16 +000010877 bqlist = NULL;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010878 quotef = 0;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010879 oldstyle = 0;
10880 prevsyntax = 0;
Denis Vlasenko46a53062007-09-24 18:30:02 +000010881#if ENABLE_ASH_EXPAND_PRMT
10882 pssyntax = (syntax == PSSYNTAX);
10883 if (pssyntax)
10884 syntax = DQSYNTAX;
10885#endif
10886 dblquote = (syntax == DQSYNTAX);
Eric Andersencb57d552001-06-28 07:25:16 +000010887 varnest = 0;
10888 arinest = 0;
10889 parenlevel = 0;
10890 dqvarnest = 0;
10891
10892 STARTSTACKSTR(out);
Denis Vlasenko176d49d2008-10-06 09:51:47 +000010893 loop:
10894 /* For each line, until end of word */
10895 {
Eric Andersenc470f442003-07-28 09:56:35 +000010896 CHECKEND(); /* set c to PEOF if at end of here document */
10897 for (;;) { /* until end of line or end of word */
10898 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
Denis Vlasenkobf0a2012006-12-26 10:42:51 +000010899 switch (SIT(c, syntax)) {
Eric Andersenc470f442003-07-28 09:56:35 +000010900 case CNL: /* '\n' */
Eric Andersencb57d552001-06-28 07:25:16 +000010901 if (syntax == BASESYNTAX)
Eric Andersenc470f442003-07-28 09:56:35 +000010902 goto endword; /* exit outer loop */
Eric Andersencb57d552001-06-28 07:25:16 +000010903 USTPUTC(c, out);
Denis Vlasenko41eb3002008-11-28 03:42:31 +000010904 g_parsefile->linno++;
Eric Andersencb57d552001-06-28 07:25:16 +000010905 if (doprompt)
10906 setprompt(2);
Eric Andersencb57d552001-06-28 07:25:16 +000010907 c = pgetc();
Eric Andersenc470f442003-07-28 09:56:35 +000010908 goto loop; /* continue outer loop */
Eric Andersencb57d552001-06-28 07:25:16 +000010909 case CWORD:
10910 USTPUTC(c, out);
10911 break;
10912 case CCTL:
Eric Andersenc470f442003-07-28 09:56:35 +000010913 if (eofmark == NULL || dblquote)
Eric Andersencb57d552001-06-28 07:25:16 +000010914 USTPUTC(CTLESC, out);
Denis Vlasenkoef527f52008-06-23 01:52:30 +000010915#if ENABLE_ASH_BASH_COMPAT
10916 if (c == '\\' && bash_dollar_squote) {
10917 c = decode_dollar_squote();
10918 if (c & 0x100) {
10919 USTPUTC('\\', out);
10920 c = (unsigned char)c;
10921 }
10922 }
10923#endif
Eric Andersencb57d552001-06-28 07:25:16 +000010924 USTPUTC(c, out);
10925 break;
Eric Andersenc470f442003-07-28 09:56:35 +000010926 case CBACK: /* backslash */
Eric Andersencb57d552001-06-28 07:25:16 +000010927 c = pgetc2();
10928 if (c == PEOF) {
Eric Andersenc470f442003-07-28 09:56:35 +000010929 USTPUTC(CTLESC, out);
Eric Andersencb57d552001-06-28 07:25:16 +000010930 USTPUTC('\\', out);
10931 pungetc();
10932 } else if (c == '\n') {
10933 if (doprompt)
10934 setprompt(2);
Eric Andersencb57d552001-06-28 07:25:16 +000010935 } else {
Denis Vlasenko46a53062007-09-24 18:30:02 +000010936#if ENABLE_ASH_EXPAND_PRMT
10937 if (c == '$' && pssyntax) {
10938 USTPUTC(CTLESC, out);
10939 USTPUTC('\\', out);
10940 }
10941#endif
Denis Vlasenkoef527f52008-06-23 01:52:30 +000010942 if (dblquote && c != '\\'
10943 && c != '`' && c != '$'
10944 && (c != '"' || eofmark != NULL)
Eric Andersenc470f442003-07-28 09:56:35 +000010945 ) {
10946 USTPUTC(CTLESC, out);
Eric Andersencb57d552001-06-28 07:25:16 +000010947 USTPUTC('\\', out);
Eric Andersenc470f442003-07-28 09:56:35 +000010948 }
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010949 if (SIT(c, SQSYNTAX) == CCTL)
Eric Andersencb57d552001-06-28 07:25:16 +000010950 USTPUTC(CTLESC, out);
Eric Andersencb57d552001-06-28 07:25:16 +000010951 USTPUTC(c, out);
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010952 quotef = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010953 }
10954 break;
10955 case CSQUOTE:
Eric Andersencb57d552001-06-28 07:25:16 +000010956 syntax = SQSYNTAX;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010957 quotemark:
Eric Andersenc470f442003-07-28 09:56:35 +000010958 if (eofmark == NULL) {
10959 USTPUTC(CTLQUOTEMARK, out);
10960 }
Eric Andersencb57d552001-06-28 07:25:16 +000010961 break;
10962 case CDQUOTE:
Eric Andersencb57d552001-06-28 07:25:16 +000010963 syntax = DQSYNTAX;
10964 dblquote = 1;
Eric Andersenc470f442003-07-28 09:56:35 +000010965 goto quotemark;
Eric Andersencb57d552001-06-28 07:25:16 +000010966 case CENDQUOTE:
Denis Vlasenko5e34ff22009-04-21 11:09:40 +000010967 IF_ASH_BASH_COMPAT(bash_dollar_squote = 0;)
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010968 if (eofmark != NULL && arinest == 0
10969 && varnest == 0
10970 ) {
Eric Andersencb57d552001-06-28 07:25:16 +000010971 USTPUTC(c, out);
10972 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000010973 if (dqvarnest == 0) {
Eric Andersencb57d552001-06-28 07:25:16 +000010974 syntax = BASESYNTAX;
10975 dblquote = 0;
10976 }
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010977 quotef = 1;
Eric Andersenc470f442003-07-28 09:56:35 +000010978 goto quotemark;
Eric Andersencb57d552001-06-28 07:25:16 +000010979 }
10980 break;
Eric Andersenc470f442003-07-28 09:56:35 +000010981 case CVAR: /* '$' */
10982 PARSESUB(); /* parse substitution */
Eric Andersencb57d552001-06-28 07:25:16 +000010983 break;
Eric Andersenc470f442003-07-28 09:56:35 +000010984 case CENDVAR: /* '}' */
Eric Andersencb57d552001-06-28 07:25:16 +000010985 if (varnest > 0) {
10986 varnest--;
10987 if (dqvarnest > 0) {
10988 dqvarnest--;
10989 }
10990 USTPUTC(CTLENDVAR, out);
10991 } else {
10992 USTPUTC(c, out);
10993 }
10994 break;
Mike Frysinger98c52642009-04-02 10:02:37 +000010995#if ENABLE_SH_MATH_SUPPORT
Eric Andersenc470f442003-07-28 09:56:35 +000010996 case CLP: /* '(' in arithmetic */
Eric Andersencb57d552001-06-28 07:25:16 +000010997 parenlevel++;
10998 USTPUTC(c, out);
10999 break;
Eric Andersenc470f442003-07-28 09:56:35 +000011000 case CRP: /* ')' in arithmetic */
Eric Andersencb57d552001-06-28 07:25:16 +000011001 if (parenlevel > 0) {
11002 USTPUTC(c, out);
11003 --parenlevel;
11004 } else {
11005 if (pgetc() == ')') {
11006 if (--arinest == 0) {
11007 USTPUTC(CTLENDARI, out);
11008 syntax = prevsyntax;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011009 dblquote = (syntax == DQSYNTAX);
Eric Andersencb57d552001-06-28 07:25:16 +000011010 } else
11011 USTPUTC(')', out);
11012 } else {
11013 /*
11014 * unbalanced parens
11015 * (don't 2nd guess - no error)
11016 */
11017 pungetc();
11018 USTPUTC(')', out);
11019 }
11020 }
11021 break;
11022#endif
Eric Andersenc470f442003-07-28 09:56:35 +000011023 case CBQUOTE: /* '`' */
Eric Andersencb57d552001-06-28 07:25:16 +000011024 PARSEBACKQOLD();
11025 break;
Eric Andersen2870d962001-07-02 17:27:21 +000011026 case CENDFILE:
Eric Andersenc470f442003-07-28 09:56:35 +000011027 goto endword; /* exit outer loop */
Eric Andersencb57d552001-06-28 07:25:16 +000011028 case CIGN:
11029 break;
11030 default:
Denis Vlasenko834dee72008-10-07 09:18:30 +000011031 if (varnest == 0) {
11032#if ENABLE_ASH_BASH_COMPAT
11033 if (c == '&') {
11034 if (pgetc() == '>')
11035 c = 0x100 + '>'; /* flag &> */
11036 pungetc();
11037 }
11038#endif
Eric Andersenc470f442003-07-28 09:56:35 +000011039 goto endword; /* exit outer loop */
Denis Vlasenko834dee72008-10-07 09:18:30 +000011040 }
Denis Vlasenko131ae172007-02-18 13:00:19 +000011041#if ENABLE_ASH_ALIAS
Eric Andersen3102ac42001-07-06 04:26:23 +000011042 if (c != PEOA)
11043#endif
Eric Andersencb57d552001-06-28 07:25:16 +000011044 USTPUTC(c, out);
Eric Andersen3102ac42001-07-06 04:26:23 +000011045
Eric Andersencb57d552001-06-28 07:25:16 +000011046 }
Denis Vlasenko834dee72008-10-07 09:18:30 +000011047 c = pgetc_fast();
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000011048 } /* for (;;) */
Eric Andersencb57d552001-06-28 07:25:16 +000011049 }
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011050 endword:
Mike Frysinger98c52642009-04-02 10:02:37 +000011051#if ENABLE_SH_MATH_SUPPORT
Eric Andersencb57d552001-06-28 07:25:16 +000011052 if (syntax == ARISYNTAX)
Denis Vlasenko559691a2008-10-05 18:39:31 +000011053 raise_error_syntax("missing '))'");
Eric Andersenc470f442003-07-28 09:56:35 +000011054#endif
Denis Vlasenko99eb8502007-02-23 21:09:49 +000011055 if (syntax != BASESYNTAX && !parsebackquote && eofmark == NULL)
Denis Vlasenko559691a2008-10-05 18:39:31 +000011056 raise_error_syntax("unterminated quoted string");
Eric Andersencb57d552001-06-28 07:25:16 +000011057 if (varnest != 0) {
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011058 startlinno = g_parsefile->linno;
Eric Andersenc470f442003-07-28 09:56:35 +000011059 /* { */
Denis Vlasenko559691a2008-10-05 18:39:31 +000011060 raise_error_syntax("missing '}'");
Eric Andersencb57d552001-06-28 07:25:16 +000011061 }
11062 USTPUTC('\0', out);
Eric Andersenc470f442003-07-28 09:56:35 +000011063 len = out - (char *)stackblock();
Eric Andersencb57d552001-06-28 07:25:16 +000011064 out = stackblock();
11065 if (eofmark == NULL) {
Denis Vlasenko5e34ff22009-04-21 11:09:40 +000011066 if ((c == '>' || c == '<' IF_ASH_BASH_COMPAT( || c == 0x100 + '>'))
Denis Vlasenko834dee72008-10-07 09:18:30 +000011067 && quotef == 0
11068 ) {
Denis Vlasenko559691a2008-10-05 18:39:31 +000011069 if (isdigit_str9(out)) {
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000011070 PARSEREDIR(); /* passed as params: out, c */
11071 lasttoken = TREDIR;
11072 return lasttoken;
11073 }
11074 /* else: non-number X seen, interpret it
11075 * as "NNNX>file" = "NNNX >file" */
Eric Andersencb57d552001-06-28 07:25:16 +000011076 }
Denis Vlasenkoef527f52008-06-23 01:52:30 +000011077 pungetc();
Eric Andersencb57d552001-06-28 07:25:16 +000011078 }
11079 quoteflag = quotef;
11080 backquotelist = bqlist;
11081 grabstackblock(len);
11082 wordtext = out;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011083 lasttoken = TWORD;
11084 return lasttoken;
Eric Andersencb57d552001-06-28 07:25:16 +000011085/* end of readtoken routine */
11086
Eric Andersencb57d552001-06-28 07:25:16 +000011087/*
11088 * Check to see whether we are at the end of the here document. When this
11089 * is called, c is set to the first character of the next input line. If
11090 * we are at the end of the here document, this routine sets the c to PEOF.
11091 */
Eric Andersenc470f442003-07-28 09:56:35 +000011092checkend: {
11093 if (eofmark) {
Denis Vlasenko131ae172007-02-18 13:00:19 +000011094#if ENABLE_ASH_ALIAS
Eric Andersenc470f442003-07-28 09:56:35 +000011095 if (c == PEOA) {
11096 c = pgetc2();
11097 }
11098#endif
11099 if (striptabs) {
11100 while (c == '\t') {
Eric Andersencb57d552001-06-28 07:25:16 +000011101 c = pgetc2();
11102 }
Eric Andersenc470f442003-07-28 09:56:35 +000011103 }
11104 if (c == *eofmark) {
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011105 if (pfgets(line, sizeof(line)) != NULL) {
Eric Andersenc470f442003-07-28 09:56:35 +000011106 char *p, *q;
Eric Andersencb57d552001-06-28 07:25:16 +000011107
Eric Andersenc470f442003-07-28 09:56:35 +000011108 p = line;
Denis Vlasenkof7d56652008-03-25 05:51:41 +000011109 for (q = eofmark + 1; *q && *p == *q; p++, q++)
11110 continue;
Eric Andersenc470f442003-07-28 09:56:35 +000011111 if (*p == '\n' && *q == '\0') {
11112 c = PEOF;
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011113 g_parsefile->linno++;
Eric Andersenc470f442003-07-28 09:56:35 +000011114 needprompt = doprompt;
11115 } else {
11116 pushstring(line, NULL);
Eric Andersencb57d552001-06-28 07:25:16 +000011117 }
11118 }
11119 }
11120 }
Eric Andersenc470f442003-07-28 09:56:35 +000011121 goto checkend_return;
11122}
Eric Andersencb57d552001-06-28 07:25:16 +000011123
Eric Andersencb57d552001-06-28 07:25:16 +000011124/*
11125 * Parse a redirection operator. The variable "out" points to a string
11126 * specifying the fd to be redirected. The variable "c" contains the
11127 * first character of the redirection operator.
11128 */
Eric Andersenc470f442003-07-28 09:56:35 +000011129parseredir: {
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000011130 /* out is already checked to be a valid number or "" */
11131 int fd = (*out == '\0' ? -1 : atoi(out));
Eric Andersenc470f442003-07-28 09:56:35 +000011132 union node *np;
Eric Andersencb57d552001-06-28 07:25:16 +000011133
Denis Vlasenko597906c2008-02-20 16:38:54 +000011134 np = stzalloc(sizeof(struct nfile));
Eric Andersenc470f442003-07-28 09:56:35 +000011135 if (c == '>') {
11136 np->nfile.fd = 1;
11137 c = pgetc();
11138 if (c == '>')
11139 np->type = NAPPEND;
11140 else if (c == '|')
11141 np->type = NCLOBBER;
11142 else if (c == '&')
11143 np->type = NTOFD;
Denis Vlasenko559691a2008-10-05 18:39:31 +000011144 /* it also can be NTO2 (>&file), but we can't figure it out yet */
Eric Andersenc470f442003-07-28 09:56:35 +000011145 else {
11146 np->type = NTO;
11147 pungetc();
Eric Andersencb57d552001-06-28 07:25:16 +000011148 }
Denis Vlasenko834dee72008-10-07 09:18:30 +000011149 }
11150#if ENABLE_ASH_BASH_COMPAT
11151 else if (c == 0x100 + '>') { /* this flags &> redirection */
11152 np->nfile.fd = 1;
11153 pgetc(); /* this is '>', no need to check */
11154 np->type = NTO2;
11155 }
11156#endif
11157 else { /* c == '<' */
Denis Vlasenko597906c2008-02-20 16:38:54 +000011158 /*np->nfile.fd = 0; - stzalloc did it */
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011159 c = pgetc();
11160 switch (c) {
Eric Andersenc470f442003-07-28 09:56:35 +000011161 case '<':
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011162 if (sizeof(struct nfile) != sizeof(struct nhere)) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000011163 np = stzalloc(sizeof(struct nhere));
11164 /*np->nfile.fd = 0; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000011165 }
11166 np->type = NHERE;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000011167 heredoc = stzalloc(sizeof(struct heredoc));
Eric Andersenc470f442003-07-28 09:56:35 +000011168 heredoc->here = np;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011169 c = pgetc();
11170 if (c == '-') {
Eric Andersenc470f442003-07-28 09:56:35 +000011171 heredoc->striptabs = 1;
11172 } else {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000011173 /*heredoc->striptabs = 0; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000011174 pungetc();
11175 }
11176 break;
11177
11178 case '&':
11179 np->type = NFROMFD;
11180 break;
11181
11182 case '>':
11183 np->type = NFROMTO;
11184 break;
11185
11186 default:
11187 np->type = NFROM;
11188 pungetc();
11189 break;
11190 }
Eric Andersencb57d552001-06-28 07:25:16 +000011191 }
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000011192 if (fd >= 0)
11193 np->nfile.fd = fd;
Eric Andersenc470f442003-07-28 09:56:35 +000011194 redirnode = np;
11195 goto parseredir_return;
11196}
Eric Andersencb57d552001-06-28 07:25:16 +000011197
Eric Andersencb57d552001-06-28 07:25:16 +000011198/*
11199 * Parse a substitution. At this point, we have read the dollar sign
11200 * and nothing else.
11201 */
Denis Vlasenkocc571512007-02-23 21:10:35 +000011202
11203/* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
11204 * (assuming ascii char codes, as the original implementation did) */
11205#define is_special(c) \
Denis Vlasenkoef527f52008-06-23 01:52:30 +000011206 (((unsigned)(c) - 33 < 32) \
11207 && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
Eric Andersenc470f442003-07-28 09:56:35 +000011208parsesub: {
11209 int subtype;
11210 int typeloc;
11211 int flags;
11212 char *p;
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011213 static const char types[] ALIGN1 = "}-+?=";
Eric Andersencb57d552001-06-28 07:25:16 +000011214
Eric Andersenc470f442003-07-28 09:56:35 +000011215 c = pgetc();
Denis Vlasenkoef527f52008-06-23 01:52:30 +000011216 if (c <= PEOA_OR_PEOF
11217 || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
Eric Andersenc470f442003-07-28 09:56:35 +000011218 ) {
Denis Vlasenkoef527f52008-06-23 01:52:30 +000011219#if ENABLE_ASH_BASH_COMPAT
11220 if (c == '\'')
11221 bash_dollar_squote = 1;
11222 else
11223#endif
11224 USTPUTC('$', out);
Eric Andersenc470f442003-07-28 09:56:35 +000011225 pungetc();
11226 } else if (c == '(') { /* $(command) or $((arith)) */
11227 if (pgetc() == '(') {
Mike Frysinger98c52642009-04-02 10:02:37 +000011228#if ENABLE_SH_MATH_SUPPORT
Eric Andersenc470f442003-07-28 09:56:35 +000011229 PARSEARITH();
11230#else
Mike Frysinger98a6f562008-06-09 09:38:45 +000011231 raise_error_syntax("you disabled math support for $((arith)) syntax");
Eric Andersenc470f442003-07-28 09:56:35 +000011232#endif
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000011233 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000011234 pungetc();
11235 PARSEBACKQNEW();
11236 }
11237 } else {
11238 USTPUTC(CTLVAR, out);
11239 typeloc = out - (char *)stackblock();
11240 USTPUTC(VSNORMAL, out);
11241 subtype = VSNORMAL;
11242 if (c == '{') {
11243 c = pgetc();
11244 if (c == '#') {
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011245 c = pgetc();
11246 if (c == '}')
Eric Andersenc470f442003-07-28 09:56:35 +000011247 c = '#';
11248 else
11249 subtype = VSLENGTH;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011250 } else
Eric Andersenc470f442003-07-28 09:56:35 +000011251 subtype = 0;
11252 }
11253 if (c > PEOA_OR_PEOF && is_name(c)) {
11254 do {
11255 STPUTC(c, out);
Eric Andersencb57d552001-06-28 07:25:16 +000011256 c = pgetc();
Eric Andersenc470f442003-07-28 09:56:35 +000011257 } while (c > PEOA_OR_PEOF && is_in_name(c));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011258 } else if (isdigit(c)) {
Eric Andersenc470f442003-07-28 09:56:35 +000011259 do {
11260 STPUTC(c, out);
11261 c = pgetc();
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011262 } while (isdigit(c));
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011263 } else if (is_special(c)) {
Eric Andersenc470f442003-07-28 09:56:35 +000011264 USTPUTC(c, out);
11265 c = pgetc();
Denis Vlasenko559691a2008-10-05 18:39:31 +000011266 } else {
11267 badsub:
11268 raise_error_syntax("bad substitution");
11269 }
Eric Andersencb57d552001-06-28 07:25:16 +000011270
Eric Andersenc470f442003-07-28 09:56:35 +000011271 STPUTC('=', out);
11272 flags = 0;
11273 if (subtype == 0) {
11274 switch (c) {
11275 case ':':
Eric Andersenc470f442003-07-28 09:56:35 +000011276 c = pgetc();
Denis Vlasenko92e13c22008-03-25 01:17:40 +000011277#if ENABLE_ASH_BASH_COMPAT
11278 if (c == ':' || c == '$' || isdigit(c)) {
11279 pungetc();
11280 subtype = VSSUBSTR;
11281 break;
11282 }
11283#endif
11284 flags = VSNUL;
Eric Andersenc470f442003-07-28 09:56:35 +000011285 /*FALLTHROUGH*/
11286 default:
11287 p = strchr(types, c);
11288 if (p == NULL)
11289 goto badsub;
11290 subtype = p - types + VSNORMAL;
11291 break;
11292 case '%':
Denis Vlasenko92e13c22008-03-25 01:17:40 +000011293 case '#': {
11294 int cc = c;
11295 subtype = c == '#' ? VSTRIMLEFT : VSTRIMRIGHT;
11296 c = pgetc();
11297 if (c == cc)
11298 subtype++;
11299 else
11300 pungetc();
11301 break;
11302 }
11303#if ENABLE_ASH_BASH_COMPAT
11304 case '/':
11305 subtype = VSREPLACE;
11306 c = pgetc();
11307 if (c == '/')
11308 subtype++; /* VSREPLACEALL */
11309 else
11310 pungetc();
11311 break;
11312#endif
Eric Andersencb57d552001-06-28 07:25:16 +000011313 }
Eric Andersenc470f442003-07-28 09:56:35 +000011314 } else {
11315 pungetc();
11316 }
11317 if (dblquote || arinest)
11318 flags |= VSQUOTE;
11319 *((char *)stackblock() + typeloc) = subtype | flags;
11320 if (subtype != VSNORMAL) {
11321 varnest++;
11322 if (dblquote || arinest) {
11323 dqvarnest++;
Eric Andersencb57d552001-06-28 07:25:16 +000011324 }
11325 }
11326 }
Eric Andersenc470f442003-07-28 09:56:35 +000011327 goto parsesub_return;
11328}
Eric Andersencb57d552001-06-28 07:25:16 +000011329
Eric Andersencb57d552001-06-28 07:25:16 +000011330/*
11331 * Called to parse command substitutions. Newstyle is set if the command
11332 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
11333 * list of commands (passed by reference), and savelen is the number of
11334 * characters on the top of the stack which must be preserved.
11335 */
Eric Andersenc470f442003-07-28 09:56:35 +000011336parsebackq: {
11337 struct nodelist **nlpp;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011338 smallint savepbq;
Eric Andersenc470f442003-07-28 09:56:35 +000011339 union node *n;
11340 char *volatile str;
11341 struct jmploc jmploc;
11342 struct jmploc *volatile savehandler;
11343 size_t savelen;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011344 smallint saveprompt = 0;
11345
Eric Andersencb57d552001-06-28 07:25:16 +000011346#ifdef __GNUC__
Eric Andersenc470f442003-07-28 09:56:35 +000011347 (void) &saveprompt;
Eric Andersencb57d552001-06-28 07:25:16 +000011348#endif
Eric Andersenc470f442003-07-28 09:56:35 +000011349 savepbq = parsebackquote;
11350 if (setjmp(jmploc.loc)) {
Denis Vlasenko60818682007-09-28 22:07:23 +000011351 free(str);
Eric Andersenc470f442003-07-28 09:56:35 +000011352 parsebackquote = 0;
Denis Vlasenko2da584f2007-02-19 22:44:05 +000011353 exception_handler = savehandler;
11354 longjmp(exception_handler->loc, 1);
Eric Andersenc470f442003-07-28 09:56:35 +000011355 }
Denis Vlasenkob012b102007-02-19 22:43:01 +000011356 INT_OFF;
Eric Andersenc470f442003-07-28 09:56:35 +000011357 str = NULL;
11358 savelen = out - (char *)stackblock();
11359 if (savelen > 0) {
11360 str = ckmalloc(savelen);
11361 memcpy(str, stackblock(), savelen);
11362 }
Denis Vlasenko2da584f2007-02-19 22:44:05 +000011363 savehandler = exception_handler;
11364 exception_handler = &jmploc;
Denis Vlasenkob012b102007-02-19 22:43:01 +000011365 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +000011366 if (oldstyle) {
11367 /* We must read until the closing backquote, giving special
11368 treatment to some slashes, and then push the string and
11369 reread it as input, interpreting it normally. */
11370 char *pout;
11371 int pc;
11372 size_t psavelen;
11373 char *pstr;
11374
11375
11376 STARTSTACKSTR(pout);
11377 for (;;) {
11378 if (needprompt) {
11379 setprompt(2);
Eric Andersenc470f442003-07-28 09:56:35 +000011380 }
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011381 pc = pgetc();
11382 switch (pc) {
Eric Andersenc470f442003-07-28 09:56:35 +000011383 case '`':
11384 goto done;
11385
11386 case '\\':
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011387 pc = pgetc();
11388 if (pc == '\n') {
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011389 g_parsefile->linno++;
Eric Andersenc470f442003-07-28 09:56:35 +000011390 if (doprompt)
11391 setprompt(2);
11392 /*
11393 * If eating a newline, avoid putting
11394 * the newline into the new character
11395 * stream (via the STPUTC after the
11396 * switch).
11397 */
11398 continue;
11399 }
11400 if (pc != '\\' && pc != '`' && pc != '$'
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011401 && (!dblquote || pc != '"'))
Eric Andersenc470f442003-07-28 09:56:35 +000011402 STPUTC('\\', pout);
11403 if (pc > PEOA_OR_PEOF) {
11404 break;
11405 }
11406 /* fall through */
11407
11408 case PEOF:
Denis Vlasenko131ae172007-02-18 13:00:19 +000011409#if ENABLE_ASH_ALIAS
Eric Andersenc470f442003-07-28 09:56:35 +000011410 case PEOA:
11411#endif
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011412 startlinno = g_parsefile->linno;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000011413 raise_error_syntax("EOF in backquote substitution");
Eric Andersenc470f442003-07-28 09:56:35 +000011414
11415 case '\n':
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011416 g_parsefile->linno++;
Eric Andersenc470f442003-07-28 09:56:35 +000011417 needprompt = doprompt;
11418 break;
11419
11420 default:
11421 break;
11422 }
11423 STPUTC(pc, pout);
11424 }
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011425 done:
Eric Andersenc470f442003-07-28 09:56:35 +000011426 STPUTC('\0', pout);
11427 psavelen = pout - (char *)stackblock();
11428 if (psavelen > 0) {
11429 pstr = grabstackstr(pout);
11430 setinputstring(pstr);
11431 }
11432 }
11433 nlpp = &bqlist;
11434 while (*nlpp)
11435 nlpp = &(*nlpp)->next;
Denis Vlasenko597906c2008-02-20 16:38:54 +000011436 *nlpp = stzalloc(sizeof(**nlpp));
11437 /* (*nlpp)->next = NULL; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000011438 parsebackquote = oldstyle;
11439
11440 if (oldstyle) {
11441 saveprompt = doprompt;
11442 doprompt = 0;
Eric Andersencb57d552001-06-28 07:25:16 +000011443 }
11444
Eric Andersenc470f442003-07-28 09:56:35 +000011445 n = list(2);
11446
11447 if (oldstyle)
11448 doprompt = saveprompt;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011449 else if (readtoken() != TRP)
11450 raise_error_unexpected_syntax(TRP);
Eric Andersenc470f442003-07-28 09:56:35 +000011451
11452 (*nlpp)->n = n;
11453 if (oldstyle) {
11454 /*
11455 * Start reading from old file again, ignoring any pushed back
11456 * tokens left from the backquote parsing
11457 */
11458 popfile();
11459 tokpushback = 0;
11460 }
11461 while (stackblocksize() <= savelen)
11462 growstackblock();
11463 STARTSTACKSTR(out);
11464 if (str) {
11465 memcpy(out, str, savelen);
11466 STADJUST(savelen, out);
Denis Vlasenkob012b102007-02-19 22:43:01 +000011467 INT_OFF;
11468 free(str);
Eric Andersenc470f442003-07-28 09:56:35 +000011469 str = NULL;
Denis Vlasenkob012b102007-02-19 22:43:01 +000011470 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +000011471 }
11472 parsebackquote = savepbq;
Denis Vlasenko2da584f2007-02-19 22:44:05 +000011473 exception_handler = savehandler;
Eric Andersenc470f442003-07-28 09:56:35 +000011474 if (arinest || dblquote)
11475 USTPUTC(CTLBACKQ | CTLQUOTE, out);
11476 else
11477 USTPUTC(CTLBACKQ, out);
11478 if (oldstyle)
11479 goto parsebackq_oldreturn;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000011480 goto parsebackq_newreturn;
Eric Andersenc470f442003-07-28 09:56:35 +000011481}
11482
Mike Frysinger98c52642009-04-02 10:02:37 +000011483#if ENABLE_SH_MATH_SUPPORT
Eric Andersencb57d552001-06-28 07:25:16 +000011484/*
11485 * Parse an arithmetic expansion (indicate start of one and set state)
11486 */
Eric Andersenc470f442003-07-28 09:56:35 +000011487parsearith: {
Eric Andersenc470f442003-07-28 09:56:35 +000011488 if (++arinest == 1) {
11489 prevsyntax = syntax;
11490 syntax = ARISYNTAX;
11491 USTPUTC(CTLARI, out);
11492 if (dblquote)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000011493 USTPUTC('"', out);
Eric Andersenc470f442003-07-28 09:56:35 +000011494 else
Denis Vlasenkoa624c112007-02-19 22:45:43 +000011495 USTPUTC(' ', out);
Eric Andersenc470f442003-07-28 09:56:35 +000011496 } else {
11497 /*
11498 * we collapse embedded arithmetic expansion to
11499 * parenthesis, which should be equivalent
11500 */
11501 USTPUTC('(', out);
Eric Andersencb57d552001-06-28 07:25:16 +000011502 }
Eric Andersenc470f442003-07-28 09:56:35 +000011503 goto parsearith_return;
11504}
11505#endif
Eric Andersencb57d552001-06-28 07:25:16 +000011506
Eric Andersenc470f442003-07-28 09:56:35 +000011507} /* end of readtoken */
11508
Eric Andersencb57d552001-06-28 07:25:16 +000011509/*
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011510 * Read the next input token.
11511 * If the token is a word, we set backquotelist to the list of cmds in
11512 * backquotes. We set quoteflag to true if any part of the word was
11513 * quoted.
11514 * If the token is TREDIR, then we set redirnode to a structure containing
11515 * the redirection.
11516 * In all cases, the variable startlinno is set to the number of the line
11517 * on which the token starts.
11518 *
11519 * [Change comment: here documents and internal procedures]
11520 * [Readtoken shouldn't have any arguments. Perhaps we should make the
11521 * word parsing code into a separate routine. In this case, readtoken
11522 * doesn't need to have any internal procedures, but parseword does.
11523 * We could also make parseoperator in essence the main routine, and
11524 * have parseword (readtoken1?) handle both words and redirection.]
Eric Andersencb57d552001-06-28 07:25:16 +000011525 */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011526#define NEW_xxreadtoken
11527#ifdef NEW_xxreadtoken
11528/* singles must be first! */
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011529static const char xxreadtoken_chars[7] ALIGN1 = {
Denis Vlasenko834dee72008-10-07 09:18:30 +000011530 '\n', '(', ')', /* singles */
11531 '&', '|', ';', /* doubles */
11532 0
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011533};
Eric Andersencb57d552001-06-28 07:25:16 +000011534
Denis Vlasenko834dee72008-10-07 09:18:30 +000011535#define xxreadtoken_singles 3
11536#define xxreadtoken_doubles 3
11537
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011538static const char xxreadtoken_tokens[] ALIGN1 = {
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011539 TNL, TLP, TRP, /* only single occurrence allowed */
11540 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
11541 TEOF, /* corresponds to trailing nul */
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011542 TAND, TOR, TENDCASE /* if double occurrence */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011543};
11544
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011545static int
11546xxreadtoken(void)
11547{
11548 int c;
11549
11550 if (tokpushback) {
11551 tokpushback = 0;
11552 return lasttoken;
Eric Andersencb57d552001-06-28 07:25:16 +000011553 }
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011554 if (needprompt) {
11555 setprompt(2);
11556 }
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011557 startlinno = g_parsefile->linno;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011558 for (;;) { /* until token or start of word found */
Denis Vlasenko834dee72008-10-07 09:18:30 +000011559 c = pgetc_fast();
Denis Vlasenko5e34ff22009-04-21 11:09:40 +000011560 if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011561 continue;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011562
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011563 if (c == '#') {
11564 while ((c = pgetc()) != '\n' && c != PEOF)
11565 continue;
11566 pungetc();
11567 } else if (c == '\\') {
11568 if (pgetc() != '\n') {
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011569 pungetc();
Denis Vlasenko834dee72008-10-07 09:18:30 +000011570 break; /* return readtoken1(...) */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011571 }
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011572 startlinno = ++g_parsefile->linno;
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011573 if (doprompt)
11574 setprompt(2);
11575 } else {
11576 const char *p;
11577
11578 p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
11579 if (c != PEOF) {
11580 if (c == '\n') {
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011581 g_parsefile->linno++;
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011582 needprompt = doprompt;
11583 }
11584
11585 p = strchr(xxreadtoken_chars, c);
Denis Vlasenko834dee72008-10-07 09:18:30 +000011586 if (p == NULL)
11587 break; /* return readtoken1(...) */
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011588
Denis Vlasenko834dee72008-10-07 09:18:30 +000011589 if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
11590 int cc = pgetc();
11591 if (cc == c) { /* double occurrence? */
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011592 p += xxreadtoken_doubles + 1;
11593 } else {
11594 pungetc();
Denis Vlasenko834dee72008-10-07 09:18:30 +000011595#if ENABLE_ASH_BASH_COMPAT
11596 if (c == '&' && cc == '>') /* &> */
11597 break; /* return readtoken1(...) */
11598#endif
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011599 }
11600 }
11601 }
11602 lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
11603 return lasttoken;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011604 }
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011605 } /* for (;;) */
Denis Vlasenko834dee72008-10-07 09:18:30 +000011606
11607 return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011608}
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011609#else /* old xxreadtoken */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011610#define RETURN(token) return lasttoken = token
11611static int
11612xxreadtoken(void)
11613{
11614 int c;
11615
11616 if (tokpushback) {
11617 tokpushback = 0;
11618 return lasttoken;
11619 }
11620 if (needprompt) {
11621 setprompt(2);
11622 }
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011623 startlinno = g_parsefile->linno;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011624 for (;;) { /* until token or start of word found */
Denis Vlasenko834dee72008-10-07 09:18:30 +000011625 c = pgetc_fast();
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011626 switch (c) {
11627 case ' ': case '\t':
11628#if ENABLE_ASH_ALIAS
11629 case PEOA:
11630#endif
11631 continue;
11632 case '#':
Denis Vlasenkof7d56652008-03-25 05:51:41 +000011633 while ((c = pgetc()) != '\n' && c != PEOF)
11634 continue;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011635 pungetc();
11636 continue;
11637 case '\\':
11638 if (pgetc() == '\n') {
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011639 startlinno = ++g_parsefile->linno;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011640 if (doprompt)
11641 setprompt(2);
11642 continue;
11643 }
11644 pungetc();
11645 goto breakloop;
11646 case '\n':
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011647 g_parsefile->linno++;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011648 needprompt = doprompt;
11649 RETURN(TNL);
11650 case PEOF:
11651 RETURN(TEOF);
11652 case '&':
11653 if (pgetc() == '&')
11654 RETURN(TAND);
11655 pungetc();
11656 RETURN(TBACKGND);
11657 case '|':
11658 if (pgetc() == '|')
11659 RETURN(TOR);
11660 pungetc();
11661 RETURN(TPIPE);
11662 case ';':
11663 if (pgetc() == ';')
11664 RETURN(TENDCASE);
11665 pungetc();
11666 RETURN(TSEMI);
11667 case '(':
11668 RETURN(TLP);
11669 case ')':
11670 RETURN(TRP);
11671 default:
11672 goto breakloop;
11673 }
11674 }
11675 breakloop:
11676 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
11677#undef RETURN
11678}
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011679#endif /* old xxreadtoken */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011680
11681static int
11682readtoken(void)
11683{
11684 int t;
11685#if DEBUG
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011686 smallint alreadyseen = tokpushback;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011687#endif
11688
11689#if ENABLE_ASH_ALIAS
11690 top:
11691#endif
11692
11693 t = xxreadtoken();
11694
11695 /*
11696 * eat newlines
11697 */
11698 if (checkkwd & CHKNL) {
11699 while (t == TNL) {
11700 parseheredoc();
11701 t = xxreadtoken();
11702 }
11703 }
11704
11705 if (t != TWORD || quoteflag) {
11706 goto out;
11707 }
11708
11709 /*
11710 * check for keywords
11711 */
11712 if (checkkwd & CHKKWD) {
11713 const char *const *pp;
11714
11715 pp = findkwd(wordtext);
11716 if (pp) {
11717 lasttoken = t = pp - tokname_array;
11718 TRACE(("keyword %s recognized\n", tokname(t)));
11719 goto out;
11720 }
11721 }
11722
11723 if (checkkwd & CHKALIAS) {
11724#if ENABLE_ASH_ALIAS
11725 struct alias *ap;
11726 ap = lookupalias(wordtext, 1);
11727 if (ap != NULL) {
11728 if (*ap->val) {
11729 pushstring(ap->val, ap);
11730 }
11731 goto top;
11732 }
11733#endif
11734 }
11735 out:
11736 checkkwd = 0;
11737#if DEBUG
11738 if (!alreadyseen)
11739 TRACE(("token %s %s\n", tokname(t), t == TWORD ? wordtext : ""));
11740 else
11741 TRACE(("reread token %s %s\n", tokname(t), t == TWORD ? wordtext : ""));
11742#endif
11743 return t;
Eric Andersencb57d552001-06-28 07:25:16 +000011744}
11745
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011746static char
11747peektoken(void)
11748{
11749 int t;
11750
11751 t = readtoken();
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011752 tokpushback = 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011753 return tokname_array[t][0];
11754}
Eric Andersencb57d552001-06-28 07:25:16 +000011755
11756/*
Denys Vlasenko86e83ec2009-07-23 22:07:07 +020011757 * Read and parse a command. Returns NODE_EOF on end of file.
11758 * (NULL is a valid parse tree indicating a blank line.)
Eric Andersencb57d552001-06-28 07:25:16 +000011759 */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011760static union node *
11761parsecmd(int interact)
Eric Andersen90898442003-08-06 11:20:52 +000011762{
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011763 int t;
Eric Andersencb57d552001-06-28 07:25:16 +000011764
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011765 tokpushback = 0;
11766 doprompt = interact;
11767 if (doprompt)
11768 setprompt(doprompt);
11769 needprompt = 0;
11770 t = readtoken();
11771 if (t == TEOF)
Denys Vlasenko86e83ec2009-07-23 22:07:07 +020011772 return NODE_EOF;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011773 if (t == TNL)
11774 return NULL;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011775 tokpushback = 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011776 return list(1);
11777}
11778
11779/*
11780 * Input any here documents.
11781 */
11782static void
11783parseheredoc(void)
11784{
11785 struct heredoc *here;
11786 union node *n;
11787
11788 here = heredoclist;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000011789 heredoclist = NULL;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011790
11791 while (here) {
11792 if (needprompt) {
11793 setprompt(2);
11794 }
11795 readtoken1(pgetc(), here->here->type == NHERE? SQSYNTAX : DQSYNTAX,
11796 here->eofmark, here->striptabs);
Denis Vlasenko597906c2008-02-20 16:38:54 +000011797 n = stzalloc(sizeof(struct narg));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011798 n->narg.type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000011799 /*n->narg.next = NULL; - stzalloc did it */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011800 n->narg.text = wordtext;
11801 n->narg.backquote = backquotelist;
11802 here->here->nhere.doc = n;
11803 here = here->next;
Eric Andersencb57d552001-06-28 07:25:16 +000011804 }
Eric Andersencb57d552001-06-28 07:25:16 +000011805}
11806
11807
11808/*
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +000011809 * called by editline -- any expansions to the prompt should be added here.
Eric Andersencb57d552001-06-28 07:25:16 +000011810 */
Denis Vlasenko131ae172007-02-18 13:00:19 +000011811#if ENABLE_ASH_EXPAND_PRMT
"Vladimir N. Oleynik"bef14d72005-09-05 13:25:11 +000011812static const char *
11813expandstr(const char *ps)
11814{
11815 union node n;
11816
Denis Vlasenko5c2b8142009-03-19 01:59:59 +000011817 /* XXX Fix (char *) cast. It _is_ a bug. ps is variable's value,
11818 * and token processing _can_ alter it (delete NULs etc). */
"Vladimir N. Oleynik"bef14d72005-09-05 13:25:11 +000011819 setinputstring((char *)ps);
Denis Vlasenko46a53062007-09-24 18:30:02 +000011820 readtoken1(pgetc(), PSSYNTAX, nullstr, 0);
"Vladimir N. Oleynik"bef14d72005-09-05 13:25:11 +000011821 popfile();
11822
11823 n.narg.type = NARG;
11824 n.narg.next = NULL;
11825 n.narg.text = wordtext;
11826 n.narg.backquote = backquotelist;
11827
11828 expandarg(&n, NULL, 0);
11829 return stackblock();
11830}
11831#endif
11832
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011833/*
11834 * Execute a command or commands contained in a string.
11835 */
11836static int
11837evalstring(char *s, int mask)
Eric Andersenc470f442003-07-28 09:56:35 +000011838{
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011839 union node *n;
11840 struct stackmark smark;
11841 int skip;
11842
11843 setinputstring(s);
11844 setstackmark(&smark);
11845
11846 skip = 0;
Denys Vlasenko86e83ec2009-07-23 22:07:07 +020011847 while ((n = parsecmd(0)) != NODE_EOF) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011848 evaltree(n, 0);
11849 popstackmark(&smark);
11850 skip = evalskip;
11851 if (skip)
11852 break;
11853 }
11854 popfile();
11855
11856 skip &= mask;
11857 evalskip = skip;
11858 return skip;
Eric Andersenc470f442003-07-28 09:56:35 +000011859}
11860
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011861/*
11862 * The eval command.
11863 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011864static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000011865evalcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011866{
11867 char *p;
11868 char *concat;
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011869
Denis Vlasenko68404f12008-03-17 09:00:54 +000011870 if (argv[1]) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011871 p = argv[1];
Denis Vlasenko68404f12008-03-17 09:00:54 +000011872 argv += 2;
11873 if (argv[0]) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011874 STARTSTACKSTR(concat);
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011875 for (;;) {
11876 concat = stack_putstr(p, concat);
Denis Vlasenko68404f12008-03-17 09:00:54 +000011877 p = *argv++;
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011878 if (p == NULL)
11879 break;
11880 STPUTC(' ', concat);
11881 }
11882 STPUTC('\0', concat);
11883 p = grabstackstr(concat);
11884 }
11885 evalstring(p, ~SKIPEVAL);
11886
11887 }
11888 return exitstatus;
11889}
11890
11891/*
11892 * Read and execute commands. "Top" is nonzero for the top level command
11893 * loop; it turns on prompting if the shell is interactive.
11894 */
11895static int
11896cmdloop(int top)
11897{
11898 union node *n;
11899 struct stackmark smark;
11900 int inter;
11901 int numeof = 0;
11902
11903 TRACE(("cmdloop(%d) called\n", top));
11904 for (;;) {
11905 int skip;
11906
11907 setstackmark(&smark);
11908#if JOBS
Denis Vlasenkob07a4962008-06-22 13:16:23 +000011909 if (doing_jobctl)
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011910 showjobs(stderr, SHOW_CHANGED);
11911#endif
11912 inter = 0;
11913 if (iflag && top) {
11914 inter++;
11915#if ENABLE_ASH_MAIL
11916 chkmail();
11917#endif
11918 }
11919 n = parsecmd(inter);
Denys Vlasenko7cee00e2009-07-24 01:08:03 +020011920#if DEBUG
11921 if (DEBUG > 2 && debug && (n != NODE_EOF))
Denys Vlasenko883cea42009-07-11 15:31:59 +020011922 showtree(n);
Denis Vlasenko135cecb2009-04-12 00:00:57 +000011923#endif
Denys Vlasenko86e83ec2009-07-23 22:07:07 +020011924 if (n == NODE_EOF) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011925 if (!top || numeof >= 50)
11926 break;
11927 if (!stoppedjobs()) {
11928 if (!Iflag)
11929 break;
11930 out2str("\nUse \"exit\" to leave shell.\n");
11931 }
11932 numeof++;
11933 } else if (nflag == 0) {
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +000011934 /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
11935 job_warning >>= 1;
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011936 numeof = 0;
11937 evaltree(n, 0);
11938 }
11939 popstackmark(&smark);
11940 skip = evalskip;
11941
11942 if (skip) {
11943 evalskip = 0;
11944 return skip & SKIPEVAL;
11945 }
11946 }
11947 return 0;
11948}
11949
Denis Vlasenko0dec6de2007-02-23 21:10:47 +000011950/*
11951 * Take commands from a file. To be compatible we should do a path
11952 * search for the file, which is necessary to find sub-commands.
11953 */
11954static char *
11955find_dot_file(char *name)
11956{
11957 char *fullname;
11958 const char *path = pathval();
11959 struct stat statb;
11960
11961 /* don't try this for absolute or relative paths */
11962 if (strchr(name, '/'))
11963 return name;
11964
Denis Vlasenko8ad78e12009-02-15 12:40:30 +000011965 /* IIRC standards do not say whether . is to be searched.
11966 * And it is even smaller this way, making it unconditional for now:
11967 */
11968 if (1) { /* ENABLE_ASH_BASH_COMPAT */
11969 fullname = name;
11970 goto try_cur_dir;
11971 }
11972
Denys Vlasenko82a6fb32009-06-14 19:42:12 +020011973 while ((fullname = path_advance(&path, name)) != NULL) {
Denis Vlasenko8ad78e12009-02-15 12:40:30 +000011974 try_cur_dir:
Denis Vlasenko0dec6de2007-02-23 21:10:47 +000011975 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
11976 /*
11977 * Don't bother freeing here, since it will
11978 * be freed by the caller.
11979 */
11980 return fullname;
11981 }
Denys Vlasenko82a6fb32009-06-14 19:42:12 +020011982 if (fullname != name)
11983 stunalloc(fullname);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +000011984 }
11985
11986 /* not found in the PATH */
11987 ash_msg_and_raise_error("%s: not found", name);
11988 /* NOTREACHED */
11989}
11990
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011991static int FAST_FUNC
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011992dotcmd(int argc, char **argv)
11993{
11994 struct strlist *sp;
11995 volatile struct shparam saveparam;
11996 int status = 0;
11997
11998 for (sp = cmdenviron; sp; sp = sp->next)
Denis Vlasenko4222ae42007-02-25 02:37:49 +000011999 setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012000
Denis Vlasenko68404f12008-03-17 09:00:54 +000012001 if (argv[1]) { /* That's what SVR2 does */
12002 char *fullname = find_dot_file(argv[1]);
12003 argv += 2;
12004 argc -= 2;
12005 if (argc) { /* argc > 0, argv[0] != NULL */
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012006 saveparam = shellparam;
Denis Vlasenko01631112007-12-16 17:20:38 +000012007 shellparam.malloced = 0;
Denis Vlasenko68404f12008-03-17 09:00:54 +000012008 shellparam.nparam = argc;
12009 shellparam.p = argv;
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012010 };
12011
12012 setinputfile(fullname, INPUT_PUSH_FILE);
12013 commandname = fullname;
12014 cmdloop(0);
12015 popfile();
12016
Denis Vlasenko68404f12008-03-17 09:00:54 +000012017 if (argc) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012018 freeparam(&shellparam);
12019 shellparam = saveparam;
12020 };
12021 status = exitstatus;
12022 }
12023 return status;
12024}
12025
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012026static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012027exitcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012028{
12029 if (stoppedjobs())
12030 return 0;
Denis Vlasenko68404f12008-03-17 09:00:54 +000012031 if (argv[1])
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012032 exitstatus = number(argv[1]);
12033 raise_exception(EXEXIT);
12034 /* NOTREACHED */
12035}
12036
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012037/*
12038 * Read a file containing shell functions.
12039 */
12040static void
12041readcmdfile(char *name)
12042{
12043 setinputfile(name, INPUT_PUSH_FILE);
12044 cmdloop(0);
12045 popfile();
12046}
12047
12048
Denis Vlasenkocc571512007-02-23 21:10:35 +000012049/* ============ find_command inplementation */
12050
12051/*
12052 * Resolve a command name. If you change this routine, you may have to
12053 * change the shellexec routine as well.
12054 */
12055static void
12056find_command(char *name, struct cmdentry *entry, int act, const char *path)
12057{
12058 struct tblentry *cmdp;
12059 int idx;
12060 int prev;
12061 char *fullname;
12062 struct stat statb;
12063 int e;
12064 int updatetbl;
12065 struct builtincmd *bcmd;
12066
12067 /* If name contains a slash, don't use PATH or hash table */
12068 if (strchr(name, '/') != NULL) {
12069 entry->u.index = -1;
12070 if (act & DO_ABS) {
12071 while (stat(name, &statb) < 0) {
12072#ifdef SYSV
12073 if (errno == EINTR)
12074 continue;
12075#endif
12076 entry->cmdtype = CMDUNKNOWN;
12077 return;
12078 }
12079 }
12080 entry->cmdtype = CMDNORMAL;
12081 return;
12082 }
12083
Denis Vlasenkof20de5b2007-04-29 23:42:54 +000012084/* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
Denis Vlasenkocc571512007-02-23 21:10:35 +000012085
12086 updatetbl = (path == pathval());
12087 if (!updatetbl) {
12088 act |= DO_ALTPATH;
12089 if (strstr(path, "%builtin") != NULL)
12090 act |= DO_ALTBLTIN;
12091 }
12092
12093 /* If name is in the table, check answer will be ok */
12094 cmdp = cmdlookup(name, 0);
12095 if (cmdp != NULL) {
12096 int bit;
12097
12098 switch (cmdp->cmdtype) {
12099 default:
12100#if DEBUG
12101 abort();
12102#endif
12103 case CMDNORMAL:
12104 bit = DO_ALTPATH;
12105 break;
12106 case CMDFUNCTION:
12107 bit = DO_NOFUNC;
12108 break;
12109 case CMDBUILTIN:
12110 bit = DO_ALTBLTIN;
12111 break;
12112 }
12113 if (act & bit) {
12114 updatetbl = 0;
12115 cmdp = NULL;
12116 } else if (cmdp->rehash == 0)
12117 /* if not invalidated by cd, we're done */
12118 goto success;
12119 }
12120
12121 /* If %builtin not in path, check for builtin next */
12122 bcmd = find_builtin(name);
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +000012123 if (bcmd) {
12124 if (IS_BUILTIN_REGULAR(bcmd))
12125 goto builtin_success;
12126 if (act & DO_ALTPATH) {
12127 if (!(act & DO_ALTBLTIN))
12128 goto builtin_success;
12129 } else if (builtinloc <= 0) {
12130 goto builtin_success;
Denis Vlasenko8e858e22007-03-07 09:35:43 +000012131 }
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +000012132 }
Denis Vlasenkocc571512007-02-23 21:10:35 +000012133
Denis Vlasenkof20de5b2007-04-29 23:42:54 +000012134#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko7465dbc2008-04-13 02:25:53 +000012135 {
12136 int applet_no = find_applet_by_name(name);
12137 if (applet_no >= 0) {
12138 entry->cmdtype = CMDNORMAL;
12139 entry->u.index = -2 - applet_no;
12140 return;
12141 }
Denis Vlasenkof20de5b2007-04-29 23:42:54 +000012142 }
12143#endif
12144
Denis Vlasenkocc571512007-02-23 21:10:35 +000012145 /* We have to search path. */
12146 prev = -1; /* where to start */
12147 if (cmdp && cmdp->rehash) { /* doing a rehash */
12148 if (cmdp->cmdtype == CMDBUILTIN)
12149 prev = builtinloc;
12150 else
12151 prev = cmdp->param.index;
12152 }
12153
12154 e = ENOENT;
12155 idx = -1;
12156 loop:
Denys Vlasenko82a6fb32009-06-14 19:42:12 +020012157 while ((fullname = path_advance(&path, name)) != NULL) {
Denis Vlasenkocc571512007-02-23 21:10:35 +000012158 stunalloc(fullname);
Denis Vlasenkodee82b62007-07-29 14:05:27 +000012159 /* NB: code below will still use fullname
12160 * despite it being "unallocated" */
Denis Vlasenkocc571512007-02-23 21:10:35 +000012161 idx++;
12162 if (pathopt) {
12163 if (prefix(pathopt, "builtin")) {
12164 if (bcmd)
12165 goto builtin_success;
12166 continue;
Denis Vlasenko4a9ca132008-04-12 20:07:08 +000012167 }
12168 if ((act & DO_NOFUNC)
12169 || !prefix(pathopt, "func")
12170 ) { /* ignore unimplemented options */
Denis Vlasenkocc571512007-02-23 21:10:35 +000012171 continue;
12172 }
12173 }
12174 /* if rehash, don't redo absolute path names */
12175 if (fullname[0] == '/' && idx <= prev) {
12176 if (idx < prev)
12177 continue;
12178 TRACE(("searchexec \"%s\": no change\n", name));
12179 goto success;
12180 }
12181 while (stat(fullname, &statb) < 0) {
12182#ifdef SYSV
12183 if (errno == EINTR)
12184 continue;
12185#endif
12186 if (errno != ENOENT && errno != ENOTDIR)
12187 e = errno;
12188 goto loop;
12189 }
12190 e = EACCES; /* if we fail, this will be the error */
12191 if (!S_ISREG(statb.st_mode))
12192 continue;
12193 if (pathopt) { /* this is a %func directory */
12194 stalloc(strlen(fullname) + 1);
Denis Vlasenkodee82b62007-07-29 14:05:27 +000012195 /* NB: stalloc will return space pointed by fullname
12196 * (because we don't have any intervening allocations
12197 * between stunalloc above and this stalloc) */
Denis Vlasenkocc571512007-02-23 21:10:35 +000012198 readcmdfile(fullname);
12199 cmdp = cmdlookup(name, 0);
12200 if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
12201 ash_msg_and_raise_error("%s not defined in %s", name, fullname);
12202 stunalloc(fullname);
12203 goto success;
12204 }
12205 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
12206 if (!updatetbl) {
12207 entry->cmdtype = CMDNORMAL;
12208 entry->u.index = idx;
12209 return;
12210 }
12211 INT_OFF;
12212 cmdp = cmdlookup(name, 1);
12213 cmdp->cmdtype = CMDNORMAL;
12214 cmdp->param.index = idx;
12215 INT_ON;
12216 goto success;
12217 }
12218
12219 /* We failed. If there was an entry for this command, delete it */
12220 if (cmdp && updatetbl)
12221 delete_cmd_entry();
12222 if (act & DO_ERR)
12223 ash_msg("%s: %s", name, errmsg(e, "not found"));
12224 entry->cmdtype = CMDUNKNOWN;
12225 return;
12226
12227 builtin_success:
12228 if (!updatetbl) {
12229 entry->cmdtype = CMDBUILTIN;
12230 entry->u.cmd = bcmd;
12231 return;
12232 }
12233 INT_OFF;
12234 cmdp = cmdlookup(name, 1);
12235 cmdp->cmdtype = CMDBUILTIN;
12236 cmdp->param.cmd = bcmd;
12237 INT_ON;
12238 success:
12239 cmdp->rehash = 0;
12240 entry->cmdtype = cmdp->cmdtype;
12241 entry->u = cmdp->param;
12242}
12243
12244
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012245/* ============ trap.c */
Eric Andersenc470f442003-07-28 09:56:35 +000012246
Eric Andersencb57d552001-06-28 07:25:16 +000012247/*
Eric Andersencb57d552001-06-28 07:25:16 +000012248 * The trap builtin.
12249 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012250static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012251trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersencb57d552001-06-28 07:25:16 +000012252{
12253 char *action;
12254 char **ap;
12255 int signo;
12256
Eric Andersenc470f442003-07-28 09:56:35 +000012257 nextopt(nullstr);
12258 ap = argptr;
12259 if (!*ap) {
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012260 for (signo = 0; signo < NSIG; signo++) {
Eric Andersencb57d552001-06-28 07:25:16 +000012261 if (trap[signo] != NULL) {
Denys Vlasenko2f7894b2009-09-24 01:43:21 +020012262 out1fmt("trap -- %s %s%s\n",
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +000012263 single_quote(trap[signo]),
Denys Vlasenko2f7894b2009-09-24 01:43:21 +020012264 (signo == 0 ? "" : "SIG"),
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +000012265 get_signame(signo));
Eric Andersencb57d552001-06-28 07:25:16 +000012266 }
12267 }
12268 return 0;
12269 }
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +000012270 action = NULL;
12271 if (ap[1])
Eric Andersencb57d552001-06-28 07:25:16 +000012272 action = *ap++;
12273 while (*ap) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +000012274 signo = get_signum(*ap);
12275 if (signo < 0)
Denis Vlasenkob012b102007-02-19 22:43:01 +000012276 ash_msg_and_raise_error("%s: bad trap", *ap);
12277 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +000012278 if (action) {
Denis Vlasenko9f739442006-12-16 23:49:13 +000012279 if (LONE_DASH(action))
Eric Andersencb57d552001-06-28 07:25:16 +000012280 action = NULL;
12281 else
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012282 action = ckstrdup(action);
Eric Andersencb57d552001-06-28 07:25:16 +000012283 }
Denis Vlasenko60818682007-09-28 22:07:23 +000012284 free(trap[signo]);
Eric Andersencb57d552001-06-28 07:25:16 +000012285 trap[signo] = action;
12286 if (signo != 0)
12287 setsignal(signo);
Denis Vlasenkob012b102007-02-19 22:43:01 +000012288 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +000012289 ap++;
12290 }
12291 return 0;
12292}
12293
Eric Andersenc470f442003-07-28 09:56:35 +000012294
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012295/* ============ Builtins */
Eric Andersenc470f442003-07-28 09:56:35 +000012296
Denis Vlasenko8e1c7152007-01-22 07:21:38 +000012297#if !ENABLE_FEATURE_SH_EXTRA_QUIET
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012298/*
12299 * Lists available builtins
12300 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012301static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012302helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersenc470f442003-07-28 09:56:35 +000012303{
Denis Vlasenko6b06cb82008-05-15 21:30:45 +000012304 unsigned col;
12305 unsigned i;
Eric Andersenc470f442003-07-28 09:56:35 +000012306
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +020012307 out1fmt(
Denis Vlasenko34d4d892009-04-04 20:24:37 +000012308 "Built-in commands:\n"
12309 "------------------\n");
Denis Vlasenkob71c6682007-07-21 15:08:09 +000012310 for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
Eric Andersenc470f442003-07-28 09:56:35 +000012311 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
Denis Vlasenko52764022007-02-24 13:42:56 +000012312 builtintab[i].name + 1);
Eric Andersenc470f442003-07-28 09:56:35 +000012313 if (col > 60) {
12314 out1fmt("\n");
12315 col = 0;
12316 }
12317 }
Denis Vlasenko80d14be2007-04-10 23:03:30 +000012318#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko1aa7e472007-11-28 06:49:03 +000012319 {
12320 const char *a = applet_names;
12321 while (*a) {
12322 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
12323 if (col > 60) {
12324 out1fmt("\n");
12325 col = 0;
12326 }
12327 a += strlen(a) + 1;
Eric Andersenc470f442003-07-28 09:56:35 +000012328 }
12329 }
12330#endif
12331 out1fmt("\n\n");
12332 return EXIT_SUCCESS;
12333}
Denis Vlasenko131ae172007-02-18 13:00:19 +000012334#endif /* FEATURE_SH_EXTRA_QUIET */
Eric Andersenc470f442003-07-28 09:56:35 +000012335
Eric Andersencb57d552001-06-28 07:25:16 +000012336/*
Eric Andersencb57d552001-06-28 07:25:16 +000012337 * The export and readonly commands.
12338 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012339static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012340exportcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +000012341{
12342 struct var *vp;
12343 char *name;
12344 const char *p;
Eric Andersenc470f442003-07-28 09:56:35 +000012345 char **aptr;
Denis Vlasenkob7304742008-10-20 08:15:51 +000012346 int flag = argv[0][0] == 'r' ? VREADONLY : VEXPORT;
Eric Andersencb57d552001-06-28 07:25:16 +000012347
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012348 if (nextopt("p") != 'p') {
12349 aptr = argptr;
12350 name = *aptr;
12351 if (name) {
12352 do {
12353 p = strchr(name, '=');
12354 if (p != NULL) {
12355 p++;
12356 } else {
12357 vp = *findvar(hashvar(name), name);
12358 if (vp) {
12359 vp->flags |= flag;
12360 continue;
12361 }
Eric Andersencb57d552001-06-28 07:25:16 +000012362 }
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012363 setvar(name, p, flag);
12364 } while ((name = *++aptr) != NULL);
12365 return 0;
12366 }
Eric Andersencb57d552001-06-28 07:25:16 +000012367 }
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012368 showvars(argv[0], flag, 0);
Eric Andersencb57d552001-06-28 07:25:16 +000012369 return 0;
12370}
12371
Eric Andersencb57d552001-06-28 07:25:16 +000012372/*
Denis Vlasenko5651bfc2007-02-23 21:08:58 +000012373 * Delete a function if it exists.
Eric Andersencb57d552001-06-28 07:25:16 +000012374 */
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012375static void
Denis Vlasenko5651bfc2007-02-23 21:08:58 +000012376unsetfunc(const char *name)
Aaron Lehmannb6ecbdc2001-12-06 03:37:38 +000012377{
Denis Vlasenko5651bfc2007-02-23 21:08:58 +000012378 struct tblentry *cmdp;
Eric Andersencb57d552001-06-28 07:25:16 +000012379
Denis Vlasenko5651bfc2007-02-23 21:08:58 +000012380 cmdp = cmdlookup(name, 0);
12381 if (cmdp!= NULL && cmdp->cmdtype == CMDFUNCTION)
12382 delete_cmd_entry();
Eric Andersenc470f442003-07-28 09:56:35 +000012383}
12384
Eric Andersencb57d552001-06-28 07:25:16 +000012385/*
Eric Andersencb57d552001-06-28 07:25:16 +000012386 * The unset builtin command. We unset the function before we unset the
12387 * variable to allow a function to be unset when there is a readonly variable
12388 * with the same name.
12389 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012390static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012391unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersencb57d552001-06-28 07:25:16 +000012392{
12393 char **ap;
12394 int i;
Eric Andersenc470f442003-07-28 09:56:35 +000012395 int flag = 0;
Eric Andersencb57d552001-06-28 07:25:16 +000012396 int ret = 0;
12397
12398 while ((i = nextopt("vf")) != '\0') {
Eric Andersenc470f442003-07-28 09:56:35 +000012399 flag = i;
Eric Andersencb57d552001-06-28 07:25:16 +000012400 }
Eric Andersencb57d552001-06-28 07:25:16 +000012401
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012402 for (ap = argptr; *ap; ap++) {
Eric Andersenc470f442003-07-28 09:56:35 +000012403 if (flag != 'f') {
12404 i = unsetvar(*ap);
12405 ret |= i;
12406 if (!(i & 2))
12407 continue;
12408 }
12409 if (flag != 'v')
Eric Andersencb57d552001-06-28 07:25:16 +000012410 unsetfunc(*ap);
Eric Andersencb57d552001-06-28 07:25:16 +000012411 }
Eric Andersenc470f442003-07-28 09:56:35 +000012412 return ret & 1;
Eric Andersencb57d552001-06-28 07:25:16 +000012413}
12414
12415
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +000012416/* setmode.c */
Eric Andersencb57d552001-06-28 07:25:16 +000012417
Eric Andersenc470f442003-07-28 09:56:35 +000012418#include <sys/times.h>
12419
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000012420static const unsigned char timescmd_str[] ALIGN1 = {
Manuel Novoa III 4456f252003-08-13 17:48:47 +000012421 ' ', offsetof(struct tms, tms_utime),
12422 '\n', offsetof(struct tms, tms_stime),
12423 ' ', offsetof(struct tms, tms_cutime),
12424 '\n', offsetof(struct tms, tms_cstime),
12425 0
12426};
Eric Andersencb57d552001-06-28 07:25:16 +000012427
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012428static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012429timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Manuel Novoa III 4456f252003-08-13 17:48:47 +000012430{
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012431 long clk_tck, s, t;
Manuel Novoa III 4456f252003-08-13 17:48:47 +000012432 const unsigned char *p;
12433 struct tms buf;
12434
12435 clk_tck = sysconf(_SC_CLK_TCK);
Eric Andersencb57d552001-06-28 07:25:16 +000012436 times(&buf);
Manuel Novoa III 4456f252003-08-13 17:48:47 +000012437
12438 p = timescmd_str;
12439 do {
12440 t = *(clock_t *)(((char *) &buf) + p[1]);
12441 s = t / clk_tck;
12442 out1fmt("%ldm%ld.%.3lds%c",
12443 s/60, s%60,
12444 ((t - s * clk_tck) * 1000) / clk_tck,
12445 p[0]);
12446 } while (*(p += 2));
12447
Eric Andersencb57d552001-06-28 07:25:16 +000012448 return 0;
12449}
12450
Mike Frysinger98c52642009-04-02 10:02:37 +000012451#if ENABLE_SH_MATH_SUPPORT
Eric Andersenc470f442003-07-28 09:56:35 +000012452/*
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +000012453 * The let builtin. partial stolen from GNU Bash, the Bourne Again SHell.
12454 * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
Eric Andersen90898442003-08-06 11:20:52 +000012455 *
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +000012456 * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
Eric Andersenc470f442003-07-28 09:56:35 +000012457 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012458static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012459letcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersenc470f442003-07-28 09:56:35 +000012460{
Denis Vlasenko68404f12008-03-17 09:00:54 +000012461 arith_t i;
Eric Andersenc470f442003-07-28 09:56:35 +000012462
Denis Vlasenko68404f12008-03-17 09:00:54 +000012463 argv++;
12464 if (!*argv)
Denis Vlasenkob012b102007-02-19 22:43:01 +000012465 ash_msg_and_raise_error("expression expected");
Denis Vlasenko68404f12008-03-17 09:00:54 +000012466 do {
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +000012467 i = ash_arith(*argv);
Denis Vlasenko68404f12008-03-17 09:00:54 +000012468 } while (*++argv);
Eric Andersenc470f442003-07-28 09:56:35 +000012469
Denis Vlasenkod9e15f22006-11-27 16:49:55 +000012470 return !i;
Eric Andersenc470f442003-07-28 09:56:35 +000012471}
Mike Frysinger98c52642009-04-02 10:02:37 +000012472#endif /* SH_MATH_SUPPORT */
Eric Andersenc470f442003-07-28 09:56:35 +000012473
Eric Andersenc470f442003-07-28 09:56:35 +000012474
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012475/* ============ miscbltin.c
12476 *
Eric Andersenaff114c2004-04-14 17:51:38 +000012477 * Miscellaneous builtins.
Eric Andersenc470f442003-07-28 09:56:35 +000012478 */
12479
12480#undef rflag
12481
Denis Vlasenko83e5d6f2006-12-18 21:49:06 +000012482#if defined(__GLIBC__) && __GLIBC__ == 2 && __GLIBC_MINOR__ < 1
Eric Andersenc470f442003-07-28 09:56:35 +000012483typedef enum __rlimit_resource rlim_t;
12484#endif
Eric Andersen74bcd162001-07-30 21:41:37 +000012485
Eric Andersenc470f442003-07-28 09:56:35 +000012486/*
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012487 * The read builtin. Options:
12488 * -r Do not interpret '\' specially
12489 * -s Turn off echo (tty only)
12490 * -n NCHARS Read NCHARS max
12491 * -p PROMPT Display PROMPT on stderr (if input is from tty)
12492 * -t SECONDS Timeout after SECONDS (tty or pipe only)
12493 * -u FD Read from given FD instead of fd 0
Eric Andersenc470f442003-07-28 09:56:35 +000012494 * This uses unbuffered input, which may be avoidable in some cases.
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012495 * TODO: bash also has:
12496 * -a ARRAY Read into array[0],[1],etc
12497 * -d DELIM End on DELIM char, not newline
12498 * -e Use line editing (tty only)
Eric Andersenc470f442003-07-28 09:56:35 +000012499 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012500static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012501readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersenc470f442003-07-28 09:56:35 +000012502{
Denis Vlasenko9cd4c762008-06-18 19:22:19 +000012503 static const char *const arg_REPLY[] = { "REPLY", NULL };
12504
Eric Andersenc470f442003-07-28 09:56:35 +000012505 char **ap;
12506 int backslash;
12507 char c;
12508 int rflag;
12509 char *prompt;
12510 const char *ifs;
12511 char *p;
12512 int startword;
12513 int status;
12514 int i;
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012515 int fd = 0;
Denis Vlasenko131ae172007-02-18 13:00:19 +000012516#if ENABLE_ASH_READ_NCHARS
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012517 int nchars = 0; /* if != 0, -n is in effect */
Paul Fox02eb9342005-09-07 16:56:02 +000012518 int silent = 0;
12519 struct termios tty, old_tty;
12520#endif
Denis Vlasenko131ae172007-02-18 13:00:19 +000012521#if ENABLE_ASH_READ_TIMEOUT
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012522 unsigned end_ms = 0;
12523 unsigned timeout = 0;
Paul Fox02eb9342005-09-07 16:56:02 +000012524#endif
Eric Andersenc470f442003-07-28 09:56:35 +000012525
12526 rflag = 0;
12527 prompt = NULL;
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012528 while ((i = nextopt("p:u:r"
Denis Vlasenko5e34ff22009-04-21 11:09:40 +000012529 IF_ASH_READ_TIMEOUT("t:")
12530 IF_ASH_READ_NCHARS("n:s")
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012531 )) != '\0') {
Denis Vlasenkobf0a2012006-12-26 10:42:51 +000012532 switch (i) {
Paul Fox02eb9342005-09-07 16:56:02 +000012533 case 'p':
Eric Andersenc470f442003-07-28 09:56:35 +000012534 prompt = optionarg;
Paul Fox02eb9342005-09-07 16:56:02 +000012535 break;
Denis Vlasenko131ae172007-02-18 13:00:19 +000012536#if ENABLE_ASH_READ_NCHARS
Paul Fox02eb9342005-09-07 16:56:02 +000012537 case 'n':
Denis Vlasenko037576d2007-10-20 18:30:38 +000012538 nchars = bb_strtou(optionarg, NULL, 10);
12539 if (nchars < 0 || errno)
Denis Vlasenkob012b102007-02-19 22:43:01 +000012540 ash_msg_and_raise_error("invalid count");
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012541 /* nchars == 0: off (bash 3.2 does this too) */
Paul Fox02eb9342005-09-07 16:56:02 +000012542 break;
12543 case 's':
12544 silent = 1;
12545 break;
Ned Ludd2123b7c2005-02-09 21:07:23 +000012546#endif
Denis Vlasenko131ae172007-02-18 13:00:19 +000012547#if ENABLE_ASH_READ_TIMEOUT
Paul Fox02eb9342005-09-07 16:56:02 +000012548 case 't':
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012549 timeout = bb_strtou(optionarg, NULL, 10);
12550 if (errno || timeout > UINT_MAX / 2048)
12551 ash_msg_and_raise_error("invalid timeout");
12552 timeout *= 1000;
12553#if 0 /* even bash have no -t N.NNN support */
Denis Vlasenko037576d2007-10-20 18:30:38 +000012554 ts.tv_sec = bb_strtou(optionarg, &p, 10);
Paul Fox02eb9342005-09-07 16:56:02 +000012555 ts.tv_usec = 0;
Denis Vlasenko037576d2007-10-20 18:30:38 +000012556 /* EINVAL means number is ok, but not terminated by NUL */
12557 if (*p == '.' && errno == EINVAL) {
Paul Fox02eb9342005-09-07 16:56:02 +000012558 char *p2;
12559 if (*++p) {
12560 int scale;
Denis Vlasenko037576d2007-10-20 18:30:38 +000012561 ts.tv_usec = bb_strtou(p, &p2, 10);
12562 if (errno)
Denis Vlasenkob012b102007-02-19 22:43:01 +000012563 ash_msg_and_raise_error("invalid timeout");
Paul Fox02eb9342005-09-07 16:56:02 +000012564 scale = p2 - p;
12565 /* normalize to usec */
12566 if (scale > 6)
Denis Vlasenkob012b102007-02-19 22:43:01 +000012567 ash_msg_and_raise_error("invalid timeout");
Paul Fox02eb9342005-09-07 16:56:02 +000012568 while (scale++ < 6)
12569 ts.tv_usec *= 10;
12570 }
Denis Vlasenko037576d2007-10-20 18:30:38 +000012571 } else if (ts.tv_sec < 0 || errno) {
Denis Vlasenkob012b102007-02-19 22:43:01 +000012572 ash_msg_and_raise_error("invalid timeout");
Paul Fox02eb9342005-09-07 16:56:02 +000012573 }
Denis Vlasenko037576d2007-10-20 18:30:38 +000012574 if (!(ts.tv_sec | ts.tv_usec)) { /* both are 0? */
Denis Vlasenkob012b102007-02-19 22:43:01 +000012575 ash_msg_and_raise_error("invalid timeout");
Denis Vlasenko037576d2007-10-20 18:30:38 +000012576 }
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012577#endif /* if 0 */
Paul Fox02eb9342005-09-07 16:56:02 +000012578 break;
12579#endif
12580 case 'r':
12581 rflag = 1;
12582 break;
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012583 case 'u':
12584 fd = bb_strtou(optionarg, NULL, 10);
12585 if (fd < 0 || errno)
12586 ash_msg_and_raise_error("invalid file descriptor");
12587 break;
Paul Fox02eb9342005-09-07 16:56:02 +000012588 default:
12589 break;
12590 }
Eric Andersenc470f442003-07-28 09:56:35 +000012591 }
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012592 if (prompt && isatty(fd)) {
Eric Andersenc470f442003-07-28 09:56:35 +000012593 out2str(prompt);
Eric Andersenc470f442003-07-28 09:56:35 +000012594 }
Denis Vlasenko5cedb752007-02-18 19:56:41 +000012595 ap = argptr;
12596 if (*ap == NULL)
Denis Vlasenko9cd4c762008-06-18 19:22:19 +000012597 ap = (char**)arg_REPLY;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000012598 ifs = bltinlookup("IFS");
12599 if (ifs == NULL)
Eric Andersenc470f442003-07-28 09:56:35 +000012600 ifs = defifs;
Denis Vlasenko131ae172007-02-18 13:00:19 +000012601#if ENABLE_ASH_READ_NCHARS
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012602 tcgetattr(fd, &tty);
12603 old_tty = tty;
12604 if (nchars || silent) {
12605 if (nchars) {
12606 tty.c_lflag &= ~ICANON;
12607 tty.c_cc[VMIN] = nchars < 256 ? nchars : 255;
Paul Fox02eb9342005-09-07 16:56:02 +000012608 }
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012609 if (silent) {
12610 tty.c_lflag &= ~(ECHO | ECHOK | ECHONL);
12611 }
12612 /* if tcgetattr failed, tcsetattr will fail too.
12613 * Ignoring, it's harmless. */
12614 tcsetattr(fd, TCSANOW, &tty);
Paul Fox02eb9342005-09-07 16:56:02 +000012615 }
12616#endif
Paul Fox02eb9342005-09-07 16:56:02 +000012617
Eric Andersenc470f442003-07-28 09:56:35 +000012618 status = 0;
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012619 startword = 2;
Eric Andersenc470f442003-07-28 09:56:35 +000012620 backslash = 0;
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012621#if ENABLE_ASH_READ_TIMEOUT
12622 if (timeout) /* NB: ensuring end_ms is nonzero */
12623 end_ms = ((unsigned)(monotonic_us() / 1000) + timeout) | 1;
12624#endif
Eric Andersenc470f442003-07-28 09:56:35 +000012625 STARTSTACKSTR(p);
Denis Vlasenko037576d2007-10-20 18:30:38 +000012626 do {
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012627 const char *is_ifs;
12628
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012629#if ENABLE_ASH_READ_TIMEOUT
12630 if (end_ms) {
12631 struct pollfd pfd[1];
12632 pfd[0].fd = fd;
12633 pfd[0].events = POLLIN;
12634 timeout = end_ms - (unsigned)(monotonic_us() / 1000);
12635 if ((int)timeout <= 0 /* already late? */
12636 || safe_poll(pfd, 1, timeout) != 1 /* no? wait... */
12637 ) { /* timed out! */
12638#if ENABLE_ASH_READ_NCHARS
12639 tcsetattr(fd, TCSANOW, &old_tty);
12640#endif
12641 return 1;
12642 }
12643 }
12644#endif
12645 if (nonblock_safe_read(fd, &c, 1) != 1) {
Eric Andersenc470f442003-07-28 09:56:35 +000012646 status = 1;
12647 break;
12648 }
12649 if (c == '\0')
12650 continue;
12651 if (backslash) {
12652 backslash = 0;
12653 if (c != '\n')
12654 goto put;
12655 continue;
12656 }
12657 if (!rflag && c == '\\') {
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012658 backslash = 1;
Eric Andersenc470f442003-07-28 09:56:35 +000012659 continue;
12660 }
12661 if (c == '\n')
12662 break;
Denis Vlasenkof6fbd622009-03-31 19:36:58 +000012663 /* $IFS splitting */
Denis Vlasenko551ffdc2009-04-01 19:48:05 +000012664/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_05 */
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012665 is_ifs = strchr(ifs, c);
12666 if (startword && is_ifs) {
12667 if (isspace(c))
12668 continue;
Denis Vlasenkof6fbd622009-03-31 19:36:58 +000012669 /* it is a non-space ifs char */
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012670 startword--;
12671 if (startword == 1) /* first one? */
Denis Vlasenkof6fbd622009-03-31 19:36:58 +000012672 continue; /* yes, it is not next word yet */
Eric Andersenc470f442003-07-28 09:56:35 +000012673 }
12674 startword = 0;
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012675 if (ap[1] != NULL && is_ifs) {
12676 const char *beg;
Eric Andersenc470f442003-07-28 09:56:35 +000012677 STACKSTRNUL(p);
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012678 beg = stackblock();
12679 setvar(*ap, beg, 0);
Eric Andersenc470f442003-07-28 09:56:35 +000012680 ap++;
Denis Vlasenkof6fbd622009-03-31 19:36:58 +000012681 /* can we skip one non-space ifs char? (2: yes) */
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012682 startword = isspace(c) ? 2 : 1;
Eric Andersenc470f442003-07-28 09:56:35 +000012683 STARTSTACKSTR(p);
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012684 continue;
Eric Andersenc470f442003-07-28 09:56:35 +000012685 }
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012686 put:
12687 STPUTC(c, p);
Eric Andersenc470f442003-07-28 09:56:35 +000012688 }
Denis Vlasenko037576d2007-10-20 18:30:38 +000012689/* end of do {} while: */
Denis Vlasenko131ae172007-02-18 13:00:19 +000012690#if ENABLE_ASH_READ_NCHARS
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012691 while (--nchars);
Denis Vlasenko037576d2007-10-20 18:30:38 +000012692#else
12693 while (1);
12694#endif
12695
12696#if ENABLE_ASH_READ_NCHARS
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012697 tcsetattr(fd, TCSANOW, &old_tty);
Paul Fox02eb9342005-09-07 16:56:02 +000012698#endif
12699
Eric Andersenc470f442003-07-28 09:56:35 +000012700 STACKSTRNUL(p);
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012701 /* Remove trailing space ifs chars */
12702 while ((char *)stackblock() <= --p && isspace(*p) && strchr(ifs, *p) != NULL)
Eric Andersenc470f442003-07-28 09:56:35 +000012703 *p = '\0';
12704 setvar(*ap, stackblock(), 0);
12705 while (*++ap != NULL)
12706 setvar(*ap, nullstr, 0);
12707 return status;
12708}
12709
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012710static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012711umaskcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersenc470f442003-07-28 09:56:35 +000012712{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000012713 static const char permuser[3] ALIGN1 = "ugo";
12714 static const char permmode[3] ALIGN1 = "rwx";
12715 static const short permmask[] ALIGN2 = {
Eric Andersenc470f442003-07-28 09:56:35 +000012716 S_IRUSR, S_IWUSR, S_IXUSR,
12717 S_IRGRP, S_IWGRP, S_IXGRP,
12718 S_IROTH, S_IWOTH, S_IXOTH
12719 };
12720
Denis Vlasenkoeb858492009-04-18 02:06:54 +000012721 /* TODO: use bb_parse_mode() instead */
12722
Eric Andersenc470f442003-07-28 09:56:35 +000012723 char *ap;
12724 mode_t mask;
12725 int i;
12726 int symbolic_mode = 0;
12727
12728 while (nextopt("S") != '\0') {
12729 symbolic_mode = 1;
12730 }
12731
Denis Vlasenkob012b102007-02-19 22:43:01 +000012732 INT_OFF;
Eric Andersenc470f442003-07-28 09:56:35 +000012733 mask = umask(0);
12734 umask(mask);
Denis Vlasenkob012b102007-02-19 22:43:01 +000012735 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +000012736
Denis Vlasenko5cedb752007-02-18 19:56:41 +000012737 ap = *argptr;
12738 if (ap == NULL) {
Eric Andersenc470f442003-07-28 09:56:35 +000012739 if (symbolic_mode) {
12740 char buf[18];
12741 char *p = buf;
12742
12743 for (i = 0; i < 3; i++) {
12744 int j;
12745
12746 *p++ = permuser[i];
12747 *p++ = '=';
12748 for (j = 0; j < 3; j++) {
12749 if ((mask & permmask[3 * i + j]) == 0) {
12750 *p++ = permmode[j];
12751 }
12752 }
12753 *p++ = ',';
12754 }
12755 *--p = 0;
12756 puts(buf);
12757 } else {
12758 out1fmt("%.4o\n", mask);
12759 }
12760 } else {
Denis Vlasenkoaa744452007-02-23 01:04:22 +000012761 if (isdigit((unsigned char) *ap)) {
Eric Andersenc470f442003-07-28 09:56:35 +000012762 mask = 0;
12763 do {
12764 if (*ap >= '8' || *ap < '0')
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +020012765 ash_msg_and_raise_error(msg_illnum, argv[1]);
Eric Andersenc470f442003-07-28 09:56:35 +000012766 mask = (mask << 3) + (*ap - '0');
12767 } while (*++ap != '\0');
12768 umask(mask);
12769 } else {
12770 mask = ~mask & 0777;
12771 if (!bb_parse_mode(ap, &mask)) {
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +000012772 ash_msg_and_raise_error("illegal mode: %s", ap);
Eric Andersenc470f442003-07-28 09:56:35 +000012773 }
12774 umask(~mask & 0777);
12775 }
12776 }
12777 return 0;
12778}
12779
12780/*
12781 * ulimit builtin
12782 *
12783 * This code, originally by Doug Gwyn, Doug Kingston, Eric Gisin, and
12784 * Michael Rendell was ripped from pdksh 5.0.8 and hacked for use with
12785 * ash by J.T. Conklin.
12786 *
12787 * Public domain.
12788 */
Eric Andersenc470f442003-07-28 09:56:35 +000012789struct limits {
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012790 uint8_t cmd; /* RLIMIT_xxx fit into it */
12791 uint8_t factor_shift; /* shift by to get rlim_{cur,max} values */
Eric Andersenc470f442003-07-28 09:56:35 +000012792 char option;
12793};
12794
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012795static const struct limits limits_tbl[] = {
Eric Andersenc470f442003-07-28 09:56:35 +000012796#ifdef RLIMIT_CPU
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012797 { RLIMIT_CPU, 0, 't' },
Eric Andersenc470f442003-07-28 09:56:35 +000012798#endif
12799#ifdef RLIMIT_FSIZE
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012800 { RLIMIT_FSIZE, 9, 'f' },
Eric Andersenc470f442003-07-28 09:56:35 +000012801#endif
12802#ifdef RLIMIT_DATA
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012803 { RLIMIT_DATA, 10, 'd' },
Eric Andersenc470f442003-07-28 09:56:35 +000012804#endif
12805#ifdef RLIMIT_STACK
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012806 { RLIMIT_STACK, 10, 's' },
Eric Andersenc470f442003-07-28 09:56:35 +000012807#endif
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012808#ifdef RLIMIT_CORE
12809 { RLIMIT_CORE, 9, 'c' },
Eric Andersenc470f442003-07-28 09:56:35 +000012810#endif
12811#ifdef RLIMIT_RSS
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012812 { RLIMIT_RSS, 10, 'm' },
Eric Andersenc470f442003-07-28 09:56:35 +000012813#endif
12814#ifdef RLIMIT_MEMLOCK
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012815 { RLIMIT_MEMLOCK, 10, 'l' },
Eric Andersenc470f442003-07-28 09:56:35 +000012816#endif
12817#ifdef RLIMIT_NPROC
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012818 { RLIMIT_NPROC, 0, 'p' },
Eric Andersenc470f442003-07-28 09:56:35 +000012819#endif
12820#ifdef RLIMIT_NOFILE
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012821 { RLIMIT_NOFILE, 0, 'n' },
Eric Andersenc470f442003-07-28 09:56:35 +000012822#endif
Glenn L McGrath76620622004-01-13 10:19:37 +000012823#ifdef RLIMIT_AS
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012824 { RLIMIT_AS, 10, 'v' },
Eric Andersenc470f442003-07-28 09:56:35 +000012825#endif
Glenn L McGrath76620622004-01-13 10:19:37 +000012826#ifdef RLIMIT_LOCKS
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012827 { RLIMIT_LOCKS, 0, 'w' },
Eric Andersenc470f442003-07-28 09:56:35 +000012828#endif
Eric Andersenc470f442003-07-28 09:56:35 +000012829};
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012830static const char limits_name[] =
12831#ifdef RLIMIT_CPU
12832 "time(seconds)" "\0"
12833#endif
12834#ifdef RLIMIT_FSIZE
12835 "file(blocks)" "\0"
12836#endif
12837#ifdef RLIMIT_DATA
12838 "data(kb)" "\0"
12839#endif
12840#ifdef RLIMIT_STACK
12841 "stack(kb)" "\0"
12842#endif
12843#ifdef RLIMIT_CORE
12844 "coredump(blocks)" "\0"
12845#endif
12846#ifdef RLIMIT_RSS
12847 "memory(kb)" "\0"
12848#endif
12849#ifdef RLIMIT_MEMLOCK
12850 "locked memory(kb)" "\0"
12851#endif
12852#ifdef RLIMIT_NPROC
12853 "process" "\0"
12854#endif
12855#ifdef RLIMIT_NOFILE
12856 "nofiles" "\0"
12857#endif
12858#ifdef RLIMIT_AS
12859 "vmemory(kb)" "\0"
12860#endif
12861#ifdef RLIMIT_LOCKS
12862 "locks" "\0"
12863#endif
12864;
Eric Andersenc470f442003-07-28 09:56:35 +000012865
Glenn L McGrath76620622004-01-13 10:19:37 +000012866enum limtype { SOFT = 0x1, HARD = 0x2 };
12867
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012868static void
12869printlim(enum limtype how, const struct rlimit *limit,
Glenn L McGrath76620622004-01-13 10:19:37 +000012870 const struct limits *l)
12871{
12872 rlim_t val;
12873
12874 val = limit->rlim_max;
12875 if (how & SOFT)
12876 val = limit->rlim_cur;
12877
12878 if (val == RLIM_INFINITY)
12879 out1fmt("unlimited\n");
12880 else {
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012881 val >>= l->factor_shift;
Glenn L McGrath76620622004-01-13 10:19:37 +000012882 out1fmt("%lld\n", (long long) val);
12883 }
12884}
12885
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012886static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012887ulimitcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersenc470f442003-07-28 09:56:35 +000012888{
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012889 int c;
Eric Andersenc470f442003-07-28 09:56:35 +000012890 rlim_t val = 0;
Glenn L McGrath76620622004-01-13 10:19:37 +000012891 enum limtype how = SOFT | HARD;
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012892 const struct limits *l;
12893 int set, all = 0;
12894 int optc, what;
12895 struct rlimit limit;
Eric Andersenc470f442003-07-28 09:56:35 +000012896
12897 what = 'f';
Glenn L McGrath16e45d72004-02-04 08:24:39 +000012898 while ((optc = nextopt("HSa"
12899#ifdef RLIMIT_CPU
12900 "t"
12901#endif
12902#ifdef RLIMIT_FSIZE
12903 "f"
12904#endif
12905#ifdef RLIMIT_DATA
12906 "d"
12907#endif
12908#ifdef RLIMIT_STACK
12909 "s"
12910#endif
12911#ifdef RLIMIT_CORE
12912 "c"
12913#endif
12914#ifdef RLIMIT_RSS
12915 "m"
12916#endif
12917#ifdef RLIMIT_MEMLOCK
12918 "l"
12919#endif
12920#ifdef RLIMIT_NPROC
12921 "p"
12922#endif
12923#ifdef RLIMIT_NOFILE
12924 "n"
12925#endif
12926#ifdef RLIMIT_AS
12927 "v"
12928#endif
12929#ifdef RLIMIT_LOCKS
12930 "w"
12931#endif
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000012932 )) != '\0')
Eric Andersenc470f442003-07-28 09:56:35 +000012933 switch (optc) {
12934 case 'H':
12935 how = HARD;
12936 break;
12937 case 'S':
12938 how = SOFT;
12939 break;
12940 case 'a':
12941 all = 1;
12942 break;
12943 default:
12944 what = optc;
12945 }
12946
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012947 for (l = limits_tbl; l->option != what; l++)
12948 continue;
Eric Andersenc470f442003-07-28 09:56:35 +000012949
12950 set = *argptr ? 1 : 0;
12951 if (set) {
12952 char *p = *argptr;
12953
12954 if (all || argptr[1])
Denis Vlasenkob012b102007-02-19 22:43:01 +000012955 ash_msg_and_raise_error("too many arguments");
Eric Andersen81fe1232003-07-29 06:38:40 +000012956 if (strncmp(p, "unlimited\n", 9) == 0)
Eric Andersenc470f442003-07-28 09:56:35 +000012957 val = RLIM_INFINITY;
12958 else {
12959 val = (rlim_t) 0;
12960
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000012961 while ((c = *p++) >= '0' && c <= '9') {
Eric Andersenc470f442003-07-28 09:56:35 +000012962 val = (val * 10) + (long)(c - '0');
Denis Vlasenko6b06cb82008-05-15 21:30:45 +000012963 // val is actually 'unsigned long int' and can't get < 0
Eric Andersenc470f442003-07-28 09:56:35 +000012964 if (val < (rlim_t) 0)
12965 break;
12966 }
12967 if (c)
Denis Vlasenkob012b102007-02-19 22:43:01 +000012968 ash_msg_and_raise_error("bad number");
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012969 val <<= l->factor_shift;
Eric Andersenc470f442003-07-28 09:56:35 +000012970 }
12971 }
12972 if (all) {
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012973 const char *lname = limits_name;
12974 for (l = limits_tbl; l != &limits_tbl[ARRAY_SIZE(limits_tbl)]; l++) {
Eric Andersenc470f442003-07-28 09:56:35 +000012975 getrlimit(l->cmd, &limit);
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012976 out1fmt("%-20s ", lname);
12977 lname += strlen(lname) + 1;
Glenn L McGrath76620622004-01-13 10:19:37 +000012978 printlim(how, &limit, l);
Eric Andersenc470f442003-07-28 09:56:35 +000012979 }
12980 return 0;
12981 }
12982
12983 getrlimit(l->cmd, &limit);
12984 if (set) {
12985 if (how & HARD)
12986 limit.rlim_max = val;
12987 if (how & SOFT)
12988 limit.rlim_cur = val;
12989 if (setrlimit(l->cmd, &limit) < 0)
Denis Vlasenkob012b102007-02-19 22:43:01 +000012990 ash_msg_and_raise_error("error setting limit (%m)");
Eric Andersenc470f442003-07-28 09:56:35 +000012991 } else {
Glenn L McGrath76620622004-01-13 10:19:37 +000012992 printlim(how, &limit, l);
Eric Andersenc470f442003-07-28 09:56:35 +000012993 }
12994 return 0;
12995}
12996
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012997/* ============ main() and helpers */
12998
12999/*
13000 * Called to exit the shell.
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013001 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000013002static void exitshell(void) NORETURN;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000013003static void
13004exitshell(void)
13005{
13006 struct jmploc loc;
13007 char *p;
13008 int status;
13009
13010 status = exitstatus;
13011 TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
13012 if (setjmp(loc.loc)) {
Denis Vlasenko7f88e342009-03-19 03:36:18 +000013013 if (exception_type == EXEXIT)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000013014/* dash bug: it just does _exit(exitstatus) here
13015 * but we have to do setjobctl(0) first!
13016 * (bug is still not fixed in dash-0.5.3 - if you run dash
13017 * under Midnight Commander, on exit from dash MC is backgrounded) */
13018 status = exitstatus;
13019 goto out;
13020 }
13021 exception_handler = &loc;
13022 p = trap[0];
13023 if (p) {
13024 trap[0] = NULL;
13025 evalstring(p, 0);
13026 }
13027 flush_stdout_stderr();
13028 out:
13029 setjobctl(0);
13030 _exit(status);
13031 /* NOTREACHED */
13032}
13033
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000013034static void
13035init(void)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013036{
13037 /* from input.c: */
Denis Vlasenko41eb3002008-11-28 03:42:31 +000013038 basepf.next_to_pgetc = basepf.buf = basebuf;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013039
13040 /* from trap.c: */
13041 signal(SIGCHLD, SIG_DFL);
13042
13043 /* from var.c: */
13044 {
13045 char **envp;
Denys Vlasenko6db47842009-09-05 20:15:17 +020013046 char ppid[sizeof(int)*3 + 2];
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013047 const char *p;
13048 struct stat st1, st2;
13049
13050 initvar();
13051 for (envp = environ; envp && *envp; envp++) {
13052 if (strchr(*envp, '=')) {
13053 setvareq(*envp, VEXPORT|VTEXTFIXED);
13054 }
13055 }
13056
Denys Vlasenko6db47842009-09-05 20:15:17 +020013057 sprintf(ppid, "%u", (unsigned) getppid());
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013058 setvar("PPID", ppid, 0);
13059
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
13239#if ENABLE_ASH_RANDOM_SUPPORT
Denis Vlasenkoce13b762008-06-29 02:25:53 +000013240 /* Can use monotonic_ns() for better randomness but for now it is
13241 * not used anywhere else in busybox... so avoid bloat */
13242 random_galois_LFSR = random_LCG = rootpid + monotonic_us();
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013243#endif
13244 init();
13245 setstackmark(&smark);
Denis Vlasenko68404f12008-03-17 09:00:54 +000013246 procargs(argv);
13247
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013248#if ENABLE_FEATURE_EDITING_SAVEHISTORY
13249 if (iflag) {
13250 const char *hp = lookupvar("HISTFILE");
13251
13252 if (hp == NULL) {
13253 hp = lookupvar("HOME");
13254 if (hp != NULL) {
13255 char *defhp = concat_path_file(hp, ".ash_history");
13256 setvar("HISTFILE", defhp, 0);
13257 free(defhp);
13258 }
13259 }
13260 }
13261#endif
Denis Vlasenko4e12b1a2008-12-23 23:36:47 +000013262 if (/* argv[0] && */ argv[0][0] == '-')
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013263 isloginsh = 1;
13264 if (isloginsh) {
13265 state = 1;
13266 read_profile("/etc/profile");
13267 state1:
13268 state = 2;
13269 read_profile(".profile");
13270 }
13271 state2:
13272 state = 3;
13273 if (
13274#ifndef linux
Denis Vlasenko0c032a42007-02-23 01:03:40 +000013275 getuid() == geteuid() && getgid() == getegid() &&
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013276#endif
Denis Vlasenko0c032a42007-02-23 01:03:40 +000013277 iflag
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013278 ) {
13279 shinit = lookupvar("ENV");
13280 if (shinit != NULL && *shinit != '\0') {
13281 read_profile(shinit);
13282 }
13283 }
13284 state3:
13285 state = 4;
Denis Vlasenko5c2b8142009-03-19 01:59:59 +000013286 if (minusc) {
13287 /* evalstring pushes parsefile stack.
13288 * Ensure we don't falsely claim that 0 (stdin)
Denis Vlasenko5368ad52009-03-20 10:20:08 +000013289 * is one of stacked source fds.
13290 * Testcase: ash -c 'exec 1>&0' must not complain. */
Denis Vlasenko5c2b8142009-03-19 01:59:59 +000013291 if (!sflag)
13292 g_parsefile->fd = -1;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013293 evalstring(minusc, 0);
Denis Vlasenko5c2b8142009-03-19 01:59:59 +000013294 }
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013295
13296 if (sflag || minusc == NULL) {
13297#if ENABLE_FEATURE_EDITING_SAVEHISTORY
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +000013298 if (iflag) {
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013299 const char *hp = lookupvar("HISTFILE");
Denis Vlasenko5c2b8142009-03-19 01:59:59 +000013300 if (hp)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013301 line_input_state->hist_file = hp;
13302 }
13303#endif
13304 state4: /* XXX ??? - why isn't this before the "if" statement */
13305 cmdloop(1);
13306 }
13307#if PROFILE
13308 monitor(0);
13309#endif
13310#ifdef GPROF
13311 {
13312 extern void _mcleanup(void);
13313 _mcleanup();
13314 }
13315#endif
13316 exitshell();
13317 /* NOTREACHED */
13318}
13319
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013320
Eric Andersendf82f612001-06-28 07:46:40 +000013321/*-
13322 * Copyright (c) 1989, 1991, 1993, 1994
Eric Andersen2870d962001-07-02 17:27:21 +000013323 * The Regents of the University of California. All rights reserved.
Eric Andersendf82f612001-06-28 07:46:40 +000013324 *
13325 * This code is derived from software contributed to Berkeley by
13326 * Kenneth Almquist.
13327 *
13328 * Redistribution and use in source and binary forms, with or without
13329 * modification, are permitted provided that the following conditions
13330 * are met:
13331 * 1. Redistributions of source code must retain the above copyright
13332 * notice, this list of conditions and the following disclaimer.
13333 * 2. Redistributions in binary form must reproduce the above copyright
13334 * notice, this list of conditions and the following disclaimer in the
13335 * documentation and/or other materials provided with the distribution.
"Vladimir N. Oleynik"ddc280e2005-12-15 12:01:49 +000013336 * 3. Neither the name of the University nor the names of its contributors
Eric Andersendf82f612001-06-28 07:46:40 +000013337 * may be used to endorse or promote products derived from this software
13338 * without specific prior written permission.
13339 *
13340 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
13341 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
13342 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
13343 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
13344 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
13345 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
13346 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
13347 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
13348 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
13349 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
13350 * SUCH DAMAGE.
13351 */