blob: 35d5cde5862f5631edd1c8ea87b0b6fce4cfd8be [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 {
2703 if ((unsigned char)c >= (unsigned char)(CTLESC)
2704 && (unsigned char)c <= (unsigned char)(CTLQUOTEMARK)
2705 ) {
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();
4556 clear_traps();
4557#if JOBS
4558 /* do job control only in root shell */
Denis Vlasenkob07a4962008-06-22 13:16:23 +00004559 doing_jobctl = 0;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004560 if (mode != FORK_NOJOB && jp->jobctl && !oldlvl) {
4561 pid_t pgrp;
4562
4563 if (jp->nprocs == 0)
4564 pgrp = getpid();
4565 else
4566 pgrp = jp->ps[0].pid;
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004567 /* this can fail because we are doing it in the parent also */
4568 setpgid(0, pgrp);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004569 if (mode == FORK_FG)
4570 xtcsetpgrp(ttyfd, pgrp);
4571 setsignal(SIGTSTP);
4572 setsignal(SIGTTOU);
4573 } else
4574#endif
4575 if (mode == FORK_BG) {
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004576 /* man bash: "When job control is not in effect,
4577 * asynchronous commands ignore SIGINT and SIGQUIT" */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004578 ignoresig(SIGINT);
4579 ignoresig(SIGQUIT);
4580 if (jp->nprocs == 0) {
4581 close(0);
4582 if (open(bb_dev_null, O_RDONLY) != 0)
Denis Vlasenko9604e1b2009-03-03 18:47:56 +00004583 ash_msg_and_raise_error("can't open '%s'", bb_dev_null);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004584 }
4585 }
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004586 if (!oldlvl) {
4587 if (iflag) { /* why if iflag only? */
4588 setsignal(SIGINT);
4589 setsignal(SIGTERM);
4590 }
4591 /* man bash:
4592 * "In all cases, bash ignores SIGQUIT. Non-builtin
4593 * commands run by bash have signal handlers
4594 * set to the values inherited by the shell
4595 * from its parent".
4596 * Take care of the second rule: */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004597 setsignal(SIGQUIT);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004598 }
Denys Vlasenkoe56f22a2009-07-24 00:16:59 +02004599#if JOBS
4600 if (n && n->type == NCMD && strcmp(n->ncmd.args->narg.text, "jobs") == 0) {
4601 TRACE(("Job hack\n"));
4602 freejob(curjob);
4603 return;
4604 }
4605#endif
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004606 for (jp = curjob; jp; jp = jp->prev_job)
4607 freejob(jp);
4608 jobless = 0;
4609}
4610
Denis Vlasenkobdc406d2007-07-15 01:13:25 +00004611/* Called after fork(), in parent */
Denis Vlasenko85c24712008-03-17 09:04:04 +00004612#if !JOBS
4613#define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
4614#endif
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004615static void
4616forkparent(struct job *jp, union node *n, int mode, pid_t pid)
4617{
4618 TRACE(("In parent shell: child = %d\n", pid));
4619 if (!jp) {
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00004620 while (jobless && dowait(DOWAIT_NONBLOCK, NULL) > 0)
4621 continue;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004622 jobless++;
4623 return;
4624 }
4625#if JOBS
4626 if (mode != FORK_NOJOB && jp->jobctl) {
4627 int pgrp;
4628
4629 if (jp->nprocs == 0)
4630 pgrp = pid;
4631 else
4632 pgrp = jp->ps[0].pid;
4633 /* This can fail because we are doing it in the child also */
4634 setpgid(pid, pgrp);
4635 }
4636#endif
4637 if (mode == FORK_BG) {
4638 backgndpid = pid; /* set $! */
4639 set_curjob(jp, CUR_RUNNING);
4640 }
4641 if (jp) {
4642 struct procstat *ps = &jp->ps[jp->nprocs++];
4643 ps->pid = pid;
4644 ps->status = -1;
4645 ps->cmd = nullstr;
4646#if JOBS
Denis Vlasenkob07a4962008-06-22 13:16:23 +00004647 if (doing_jobctl && n)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004648 ps->cmd = commandtext(n);
4649#endif
4650 }
4651}
4652
4653static int
4654forkshell(struct job *jp, union node *n, int mode)
4655{
4656 int pid;
4657
4658 TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
4659 pid = fork();
4660 if (pid < 0) {
4661 TRACE(("Fork failed, errno=%d", errno));
4662 if (jp)
4663 freejob(jp);
Denis Vlasenkofa0b56d2008-07-01 16:09:07 +00004664 ash_msg_and_raise_error("can't fork");
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004665 }
4666 if (pid == 0)
Denys Vlasenkoe56f22a2009-07-24 00:16:59 +02004667 forkchild(jp, n, mode);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004668 else
4669 forkparent(jp, n, mode, pid);
4670 return pid;
4671}
4672
4673/*
4674 * Wait for job to finish.
4675 *
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004676 * Under job control we have the problem that while a child process
4677 * is running interrupts generated by the user are sent to the child
4678 * but not to the shell. This means that an infinite loop started by
4679 * an interactive user may be hard to kill. With job control turned off,
4680 * an interactive user may place an interactive program inside a loop.
4681 * If the interactive program catches interrupts, the user doesn't want
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004682 * these interrupts to also abort the loop. The approach we take here
4683 * is to have the shell ignore interrupt signals while waiting for a
4684 * foreground process to terminate, and then send itself an interrupt
4685 * signal if the child process was terminated by an interrupt signal.
4686 * Unfortunately, some programs want to do a bit of cleanup and then
4687 * exit on interrupt; unless these processes terminate themselves by
4688 * sending a signal to themselves (instead of calling exit) they will
4689 * confuse this approach.
4690 *
4691 * Called with interrupts off.
4692 */
4693static int
4694waitforjob(struct job *jp)
4695{
4696 int st;
4697
4698 TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004699
4700 INT_OFF;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004701 while (jp->state == JOBRUNNING) {
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004702 /* In non-interactive shells, we _can_ get
4703 * a keyboard signal here and be EINTRed,
4704 * but we just loop back, waiting for command to complete.
4705 *
4706 * man bash:
4707 * "If bash is waiting for a command to complete and receives
4708 * a signal for which a trap has been set, the trap
4709 * will not be executed until the command completes."
4710 *
4711 * Reality is that even if trap is not set, bash
4712 * will not act on the signal until command completes.
4713 * Try this. sleep5intoff.c:
4714 * #include <signal.h>
4715 * #include <unistd.h>
4716 * int main() {
4717 * sigset_t set;
4718 * sigemptyset(&set);
4719 * sigaddset(&set, SIGINT);
4720 * sigaddset(&set, SIGQUIT);
4721 * sigprocmask(SIG_BLOCK, &set, NULL);
4722 * sleep(5);
4723 * return 0;
4724 * }
4725 * $ bash -c './sleep5intoff; echo hi'
4726 * ^C^C^C^C <--- pressing ^C once a second
4727 * $ _
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004728 * $ bash -c './sleep5intoff; echo hi'
4729 * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
4730 * $ _
4731 */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004732 dowait(DOWAIT_BLOCK, jp);
4733 }
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004734 INT_ON;
4735
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004736 st = getstatus(jp);
4737#if JOBS
4738 if (jp->jobctl) {
4739 xtcsetpgrp(ttyfd, rootpid);
4740 /*
4741 * This is truly gross.
4742 * If we're doing job control, then we did a TIOCSPGRP which
4743 * caused us (the shell) to no longer be in the controlling
4744 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
4745 * intuit from the subprocess exit status whether a SIGINT
4746 * occurred, and if so interrupt ourselves. Yuck. - mycroft
4747 */
Denis Vlasenko991a1da2008-02-10 19:02:53 +00004748 if (jp->sigint) /* TODO: do the same with all signals */
4749 raise(SIGINT); /* ... by raise(jp->sig) instead? */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004750 }
4751 if (jp->state == JOBDONE)
4752#endif
4753 freejob(jp);
4754 return st;
4755}
4756
4757/*
4758 * return 1 if there are stopped jobs, otherwise 0
4759 */
4760static int
4761stoppedjobs(void)
4762{
4763 struct job *jp;
4764 int retval;
4765
4766 retval = 0;
4767 if (job_warning)
4768 goto out;
4769 jp = curjob;
4770 if (jp && jp->state == JOBSTOPPED) {
4771 out2str("You have stopped jobs.\n");
4772 job_warning = 2;
4773 retval++;
4774 }
4775 out:
4776 return retval;
4777}
4778
4779
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004780/* ============ redir.c
4781 *
4782 * Code for dealing with input/output redirection.
4783 */
4784
4785#define EMPTY -2 /* marks an unused slot in redirtab */
Denis Vlasenko7d75a962007-11-22 08:16:57 +00004786#define CLOSED -3 /* marks a slot of previously-closed fd */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004787
4788/*
4789 * Open a file in noclobber mode.
4790 * The code was copied from bash.
4791 */
4792static int
4793noclobberopen(const char *fname)
4794{
4795 int r, fd;
4796 struct stat finfo, finfo2;
4797
4798 /*
4799 * If the file exists and is a regular file, return an error
4800 * immediately.
4801 */
4802 r = stat(fname, &finfo);
4803 if (r == 0 && S_ISREG(finfo.st_mode)) {
4804 errno = EEXIST;
4805 return -1;
4806 }
4807
4808 /*
4809 * If the file was not present (r != 0), make sure we open it
4810 * exclusively so that if it is created before we open it, our open
4811 * will fail. Make sure that we do not truncate an existing file.
4812 * Note that we don't turn on O_EXCL unless the stat failed -- if the
4813 * file was not a regular file, we leave O_EXCL off.
4814 */
4815 if (r != 0)
4816 return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
4817 fd = open(fname, O_WRONLY|O_CREAT, 0666);
4818
4819 /* If the open failed, return the file descriptor right away. */
4820 if (fd < 0)
4821 return fd;
4822
4823 /*
4824 * OK, the open succeeded, but the file may have been changed from a
4825 * non-regular file to a regular file between the stat and the open.
4826 * We are assuming that the O_EXCL open handles the case where FILENAME
4827 * did not exist and is symlinked to an existing file between the stat
4828 * and open.
4829 */
4830
4831 /*
4832 * If we can open it and fstat the file descriptor, and neither check
4833 * revealed that it was a regular file, and the file has not been
4834 * replaced, return the file descriptor.
4835 */
4836 if (fstat(fd, &finfo2) == 0 && !S_ISREG(finfo2.st_mode)
4837 && finfo.st_dev == finfo2.st_dev && finfo.st_ino == finfo2.st_ino)
4838 return fd;
4839
4840 /* The file has been replaced. badness. */
4841 close(fd);
4842 errno = EEXIST;
4843 return -1;
4844}
4845
4846/*
4847 * Handle here documents. Normally we fork off a process to write the
4848 * data to a pipe. If the document is short, we can stuff the data in
4849 * the pipe without forking.
4850 */
4851/* openhere needs this forward reference */
4852static void expandhere(union node *arg, int fd);
4853static int
4854openhere(union node *redir)
4855{
4856 int pip[2];
4857 size_t len = 0;
4858
4859 if (pipe(pip) < 0)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00004860 ash_msg_and_raise_error("pipe call failed");
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004861 if (redir->type == NHERE) {
4862 len = strlen(redir->nhere.doc->narg.text);
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00004863 if (len <= PIPE_BUF) {
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004864 full_write(pip[1], redir->nhere.doc->narg.text, len);
4865 goto out;
4866 }
4867 }
4868 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
Denis Vlasenko0b769642008-07-24 07:54:57 +00004869 /* child */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004870 close(pip[0]);
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004871 ignoresig(SIGINT); //signal(SIGINT, SIG_IGN);
4872 ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
4873 ignoresig(SIGHUP); //signal(SIGHUP, SIG_IGN);
4874 ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004875 signal(SIGPIPE, SIG_DFL);
4876 if (redir->type == NHERE)
4877 full_write(pip[1], redir->nhere.doc->narg.text, len);
Denis Vlasenko0b769642008-07-24 07:54:57 +00004878 else /* NXHERE */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004879 expandhere(redir->nhere.doc, pip[1]);
Bernhard Reutner-Fischer636a1f82008-05-19 09:29:47 +00004880 _exit(EXIT_SUCCESS);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004881 }
4882 out:
4883 close(pip[1]);
4884 return pip[0];
4885}
4886
4887static int
4888openredirect(union node *redir)
4889{
4890 char *fname;
4891 int f;
4892
4893 switch (redir->nfile.type) {
4894 case NFROM:
4895 fname = redir->nfile.expfname;
4896 f = open(fname, O_RDONLY);
4897 if (f < 0)
4898 goto eopen;
4899 break;
4900 case NFROMTO:
4901 fname = redir->nfile.expfname;
4902 f = open(fname, O_RDWR|O_CREAT|O_TRUNC, 0666);
4903 if (f < 0)
4904 goto ecreate;
4905 break;
4906 case NTO:
Denis Vlasenko559691a2008-10-05 18:39:31 +00004907#if ENABLE_ASH_BASH_COMPAT
4908 case NTO2:
4909#endif
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004910 /* Take care of noclobber mode. */
4911 if (Cflag) {
4912 fname = redir->nfile.expfname;
4913 f = noclobberopen(fname);
4914 if (f < 0)
4915 goto ecreate;
4916 break;
4917 }
4918 /* FALLTHROUGH */
4919 case NCLOBBER:
4920 fname = redir->nfile.expfname;
4921 f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
4922 if (f < 0)
4923 goto ecreate;
4924 break;
4925 case NAPPEND:
4926 fname = redir->nfile.expfname;
4927 f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
4928 if (f < 0)
4929 goto ecreate;
4930 break;
4931 default:
4932#if DEBUG
4933 abort();
4934#endif
4935 /* Fall through to eliminate warning. */
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00004936/* Our single caller does this itself */
Denis Vlasenko0b769642008-07-24 07:54:57 +00004937// case NTOFD:
4938// case NFROMFD:
4939// f = -1;
4940// break;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004941 case NHERE:
4942 case NXHERE:
4943 f = openhere(redir);
4944 break;
4945 }
4946
4947 return f;
4948 ecreate:
Bernhard Reutner-Fischera53de7f2008-07-21 13:46:54 +00004949 ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004950 eopen:
Bernhard Reutner-Fischera53de7f2008-07-21 13:46:54 +00004951 ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004952}
4953
4954/*
4955 * Copy a file descriptor to be >= to. Returns -1
4956 * if the source file descriptor is closed, EMPTY if there are no unused
4957 * file descriptors left.
4958 */
Denis Vlasenko5a867312008-07-24 19:46:38 +00004959/* 0x800..00: bit to set in "to" to request dup2 instead of fcntl(F_DUPFD).
4960 * old code was doing close(to) prior to copyfd() to achieve the same */
Denis Vlasenko22f74142008-07-24 22:34:43 +00004961enum {
4962 COPYFD_EXACT = (int)~(INT_MAX),
4963 COPYFD_RESTORE = (int)((unsigned)COPYFD_EXACT >> 1),
4964};
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004965static int
4966copyfd(int from, int to)
4967{
4968 int newfd;
4969
Denis Vlasenko5a867312008-07-24 19:46:38 +00004970 if (to & COPYFD_EXACT) {
4971 to &= ~COPYFD_EXACT;
4972 /*if (from != to)*/
4973 newfd = dup2(from, to);
4974 } else {
4975 newfd = fcntl(from, F_DUPFD, to);
4976 }
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004977 if (newfd < 0) {
4978 if (errno == EMFILE)
4979 return EMPTY;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00004980 /* Happens when source fd is not open: try "echo >&99" */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004981 ash_msg_and_raise_error("%d: %m", from);
4982 }
4983 return newfd;
4984}
4985
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00004986/* Struct def and variable are moved down to the first usage site */
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00004987struct two_fd_t {
4988 int orig, copy;
4989};
Denis Vlasenko0b769642008-07-24 07:54:57 +00004990struct redirtab {
4991 struct redirtab *next;
Denis Vlasenko0b769642008-07-24 07:54:57 +00004992 int nullredirs;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00004993 int pair_count;
4994 struct two_fd_t two_fd[0];
Denis Vlasenko0b769642008-07-24 07:54:57 +00004995};
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00004996#define redirlist (G_var.redirlist)
Denis Vlasenko0b769642008-07-24 07:54:57 +00004997
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00004998static int need_to_remember(struct redirtab *rp, int fd)
4999{
5000 int i;
5001
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005002 if (!rp) /* remembering was not requested */
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005003 return 0;
5004
5005 for (i = 0; i < rp->pair_count; i++) {
5006 if (rp->two_fd[i].orig == fd) {
5007 /* already remembered */
5008 return 0;
5009 }
5010 }
5011 return 1;
5012}
5013
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005014/* "hidden" fd is a fd used to read scripts, or a copy of such */
5015static int is_hidden_fd(struct redirtab *rp, int fd)
5016{
5017 int i;
Denis Vlasenko34c73c42008-08-16 11:48:02 +00005018 struct parsefile *pf;
5019
5020 if (fd == -1)
5021 return 0;
5022 pf = g_parsefile;
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005023 while (pf) {
5024 if (fd == pf->fd) {
5025 return 1;
5026 }
5027 pf = pf->prev;
5028 }
5029 if (!rp)
5030 return 0;
5031 fd |= COPYFD_RESTORE;
5032 for (i = 0; i < rp->pair_count; i++) {
5033 if (rp->two_fd[i].copy == fd) {
5034 return 1;
5035 }
5036 }
5037 return 0;
5038}
5039
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005040/*
5041 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
5042 * old file descriptors are stashed away so that the redirection can be
5043 * undone by calling popredir. If the REDIR_BACKQ flag is set, then the
5044 * standard output, and the standard error if it becomes a duplicate of
5045 * stdout, is saved in memory.
5046 */
5047/* flags passed to redirect */
5048#define REDIR_PUSH 01 /* save previous values of file descriptors */
5049#define REDIR_SAVEFD2 03 /* set preverrout */
5050static void
5051redirect(union node *redir, int flags)
5052{
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005053 struct redirtab *sv;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005054 int sv_pos;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005055 int i;
5056 int fd;
5057 int newfd;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005058 int copied_fd2 = -1;
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005059
Denis Vlasenko01631112007-12-16 17:20:38 +00005060 g_nullredirs++;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005061 if (!redir) {
5062 return;
5063 }
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005064
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005065 sv = NULL;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005066 sv_pos = 0;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005067 INT_OFF;
5068 if (flags & REDIR_PUSH) {
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005069 union node *tmp = redir;
5070 do {
5071 sv_pos++;
Denis Vlasenko559691a2008-10-05 18:39:31 +00005072#if ENABLE_ASH_BASH_COMPAT
5073 if (redir->nfile.type == NTO2)
5074 sv_pos++;
5075#endif
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005076 tmp = tmp->nfile.next;
5077 } while (tmp);
5078 sv = ckmalloc(sizeof(*sv) + sv_pos * sizeof(sv->two_fd[0]));
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005079 sv->next = redirlist;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005080 sv->pair_count = sv_pos;
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005081 redirlist = sv;
Denis Vlasenko01631112007-12-16 17:20:38 +00005082 sv->nullredirs = g_nullredirs - 1;
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005083 g_nullredirs = 0;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005084 while (sv_pos > 0) {
5085 sv_pos--;
5086 sv->two_fd[sv_pos].orig = sv->two_fd[sv_pos].copy = EMPTY;
5087 }
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005088 }
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005089
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005090 do {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00005091 fd = redir->nfile.fd;
Denis Vlasenko0b769642008-07-24 07:54:57 +00005092 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005093 int right_fd = redir->ndup.dupfd;
5094 /* redirect from/to same file descriptor? */
5095 if (right_fd == fd)
5096 continue;
5097 /* echo >&10 and 10 is a fd opened to the sh script? */
5098 if (is_hidden_fd(sv, right_fd)) {
5099 errno = EBADF; /* as if it is closed */
5100 ash_msg_and_raise_error("%d: %m", right_fd);
5101 }
Denis Vlasenko0b769642008-07-24 07:54:57 +00005102 newfd = -1;
5103 } else {
5104 newfd = openredirect(redir); /* always >= 0 */
5105 if (fd == newfd) {
5106 /* Descriptor wasn't open before redirect.
5107 * Mark it for close in the future */
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005108 if (need_to_remember(sv, fd)) {
Denis Vlasenko5a867312008-07-24 19:46:38 +00005109 goto remember_to_close;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005110 }
Denis Vlasenko0b769642008-07-24 07:54:57 +00005111 continue;
5112 }
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005113 }
Denis Vlasenko559691a2008-10-05 18:39:31 +00005114#if ENABLE_ASH_BASH_COMPAT
5115 redirect_more:
5116#endif
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005117 if (need_to_remember(sv, fd)) {
Denis Vlasenko0b769642008-07-24 07:54:57 +00005118 /* Copy old descriptor */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005119 i = fcntl(fd, F_DUPFD, 10);
Denis Vlasenko5a867312008-07-24 19:46:38 +00005120/* You'd expect copy to be CLOEXECed. Currently these extra "saved" fds
5121 * are closed in popredir() in the child, preventing them from leaking
5122 * into child. (popredir() also cleans up the mess in case of failures)
5123 */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005124 if (i == -1) {
5125 i = errno;
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005126 if (i != EBADF) {
5127 /* Strange error (e.g. "too many files" EMFILE?) */
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005128 if (newfd >= 0)
5129 close(newfd);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005130 errno = i;
5131 ash_msg_and_raise_error("%d: %m", fd);
5132 /* NOTREACHED */
5133 }
Denis Vlasenko5a867312008-07-24 19:46:38 +00005134 /* EBADF: it is not open - good, remember to close it */
5135 remember_to_close:
5136 i = CLOSED;
Denis Vlasenko22f74142008-07-24 22:34:43 +00005137 } else { /* fd is open, save its copy */
5138 /* "exec fd>&-" should not close fds
5139 * which point to script file(s).
5140 * Force them to be restored afterwards */
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005141 if (is_hidden_fd(sv, fd))
5142 i |= COPYFD_RESTORE;
Denis Vlasenko22f74142008-07-24 22:34:43 +00005143 }
Denis Vlasenko5a867312008-07-24 19:46:38 +00005144 if (fd == 2)
5145 copied_fd2 = i;
5146 sv->two_fd[sv_pos].orig = fd;
5147 sv->two_fd[sv_pos].copy = i;
5148 sv_pos++;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005149 }
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005150 if (newfd < 0) {
5151 /* NTOFD/NFROMFD: copy redir->ndup.dupfd to fd */
Denis Vlasenko22f74142008-07-24 22:34:43 +00005152 if (redir->ndup.dupfd < 0) { /* "fd>&-" */
Denis Vlasenkob9e70dd2009-03-20 01:24:08 +00005153 /* Don't want to trigger debugging */
5154 if (fd != -1)
5155 close(fd);
Denis Vlasenko5a867312008-07-24 19:46:38 +00005156 } else {
5157 copyfd(redir->ndup.dupfd, fd | COPYFD_EXACT);
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005158 }
Denis Vlasenko5a867312008-07-24 19:46:38 +00005159 } else if (fd != newfd) { /* move newfd to fd */
5160 copyfd(newfd, fd | COPYFD_EXACT);
Denis Vlasenko559691a2008-10-05 18:39:31 +00005161#if ENABLE_ASH_BASH_COMPAT
5162 if (!(redir->nfile.type == NTO2 && fd == 2))
5163#endif
5164 close(newfd);
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005165 }
Denis Vlasenko559691a2008-10-05 18:39:31 +00005166#if ENABLE_ASH_BASH_COMPAT
5167 if (redir->nfile.type == NTO2 && fd == 1) {
5168 /* We already redirected it to fd 1, now copy it to 2 */
5169 newfd = 1;
5170 fd = 2;
5171 goto redirect_more;
5172 }
5173#endif
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00005174 } while ((redir = redir->nfile.next) != NULL);
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005175
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005176 INT_ON;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005177 if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
5178 preverrout_fd = copied_fd2;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005179}
5180
5181/*
5182 * Undo the effects of the last redirection.
5183 */
5184static void
Denis Vlasenko34c73c42008-08-16 11:48:02 +00005185popredir(int drop, int restore)
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005186{
5187 struct redirtab *rp;
5188 int i;
5189
Denis Vlasenko01631112007-12-16 17:20:38 +00005190 if (--g_nullredirs >= 0)
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005191 return;
5192 INT_OFF;
5193 rp = redirlist;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005194 for (i = 0; i < rp->pair_count; i++) {
5195 int fd = rp->two_fd[i].orig;
Denis Vlasenko22f74142008-07-24 22:34:43 +00005196 int copy = rp->two_fd[i].copy;
5197 if (copy == CLOSED) {
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005198 if (!drop)
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005199 close(fd);
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005200 continue;
5201 }
Denis Vlasenko22f74142008-07-24 22:34:43 +00005202 if (copy != EMPTY) {
Denis Vlasenko34c73c42008-08-16 11:48:02 +00005203 if (!drop || (restore && (copy & COPYFD_RESTORE))) {
Denis Vlasenko22f74142008-07-24 22:34:43 +00005204 copy &= ~COPYFD_RESTORE;
Denis Vlasenko5a867312008-07-24 19:46:38 +00005205 /*close(fd);*/
Denis Vlasenko22f74142008-07-24 22:34:43 +00005206 copyfd(copy, fd | COPYFD_EXACT);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005207 }
Denis Vlasenkob9e70dd2009-03-20 01:24:08 +00005208 close(copy & ~COPYFD_RESTORE);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005209 }
5210 }
5211 redirlist = rp->next;
Denis Vlasenko01631112007-12-16 17:20:38 +00005212 g_nullredirs = rp->nullredirs;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005213 free(rp);
5214 INT_ON;
5215}
5216
5217/*
5218 * Undo all redirections. Called on error or interrupt.
5219 */
5220
5221/*
5222 * Discard all saved file descriptors.
5223 */
5224static void
5225clearredir(int drop)
5226{
5227 for (;;) {
Denis Vlasenko01631112007-12-16 17:20:38 +00005228 g_nullredirs = 0;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005229 if (!redirlist)
5230 break;
Denis Vlasenko34c73c42008-08-16 11:48:02 +00005231 popredir(drop, /*restore:*/ 0);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005232 }
5233}
5234
5235static int
5236redirectsafe(union node *redir, int flags)
5237{
5238 int err;
5239 volatile int saveint;
5240 struct jmploc *volatile savehandler = exception_handler;
5241 struct jmploc jmploc;
5242
5243 SAVE_INT(saveint);
Denis Vlasenko5a867312008-07-24 19:46:38 +00005244 /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
5245 err = setjmp(jmploc.loc); // huh?? was = setjmp(jmploc.loc) * 2;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005246 if (!err) {
5247 exception_handler = &jmploc;
5248 redirect(redir, flags);
5249 }
5250 exception_handler = savehandler;
Denis Vlasenko7f88e342009-03-19 03:36:18 +00005251 if (err && exception_type != EXERROR)
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005252 longjmp(exception_handler->loc, 1);
5253 RESTORE_INT(saveint);
5254 return err;
5255}
5256
5257
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005258/* ============ Routines to expand arguments to commands
5259 *
5260 * We have to deal with backquotes, shell variables, and file metacharacters.
5261 */
5262
Mike Frysinger98c52642009-04-02 10:02:37 +00005263#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00005264static arith_t
5265ash_arith(const char *s)
5266{
5267 arith_eval_hooks_t math_hooks;
5268 arith_t result;
5269 int errcode = 0;
5270
5271 math_hooks.lookupvar = lookupvar;
5272 math_hooks.setvar = setvar;
5273 math_hooks.endofname = endofname;
5274
5275 INT_OFF;
5276 result = arith(s, &errcode, &math_hooks);
5277 if (errcode < 0) {
5278 if (errcode == -3)
5279 ash_msg_and_raise_error("exponent less than 0");
5280 if (errcode == -2)
5281 ash_msg_and_raise_error("divide by zero");
5282 if (errcode == -5)
5283 ash_msg_and_raise_error("expression recursion loop detected");
5284 raise_error_syntax(s);
5285 }
5286 INT_ON;
5287
5288 return result;
5289}
Denis Vlasenko448d30e2008-06-27 00:24:11 +00005290#endif
5291
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005292/*
5293 * expandarg flags
5294 */
5295#define EXP_FULL 0x1 /* perform word splitting & file globbing */
5296#define EXP_TILDE 0x2 /* do normal tilde expansion */
5297#define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
5298#define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
5299#define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
5300#define EXP_RECORD 0x20 /* need to record arguments for ifs breakup */
5301#define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
5302#define EXP_WORD 0x80 /* expand word in parameter expansion */
5303#define EXP_QWORD 0x100 /* expand word in quoted parameter expansion */
5304/*
5305 * _rmescape() flags
5306 */
5307#define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
5308#define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
5309#define RMESCAPE_QUOTED 0x4 /* Remove CTLESC unless in quotes */
5310#define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
5311#define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
5312
5313/*
5314 * Structure specifying which parts of the string should be searched
5315 * for IFS characters.
5316 */
5317struct ifsregion {
5318 struct ifsregion *next; /* next region in list */
5319 int begoff; /* offset of start of region */
5320 int endoff; /* offset of end of region */
5321 int nulonly; /* search for nul bytes only */
5322};
5323
5324struct arglist {
5325 struct strlist *list;
5326 struct strlist **lastp;
5327};
5328
5329/* output of current string */
5330static char *expdest;
5331/* list of back quote expressions */
5332static struct nodelist *argbackq;
5333/* first struct in list of ifs regions */
5334static struct ifsregion ifsfirst;
5335/* last struct in list */
5336static struct ifsregion *ifslastp;
5337/* holds expanded arg list */
5338static struct arglist exparg;
5339
5340/*
5341 * Our own itoa().
5342 */
5343static int
5344cvtnum(arith_t num)
5345{
5346 int len;
5347
5348 expdest = makestrspace(32, expdest);
Mike Frysinger98c52642009-04-02 10:02:37 +00005349 len = fmtstr(expdest, 32, arith_t_fmt, num);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005350 STADJUST(len, expdest);
5351 return len;
5352}
5353
5354static size_t
5355esclen(const char *start, const char *p)
5356{
5357 size_t esc = 0;
5358
5359 while (p > start && *--p == CTLESC) {
5360 esc++;
5361 }
5362 return esc;
5363}
5364
5365/*
5366 * Remove any CTLESC characters from a string.
5367 */
5368static char *
Denys Vlasenkob6c84342009-08-29 20:23:20 +02005369rmescapes(char *str, int flag)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005370{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00005371 static const char qchars[] ALIGN1 = { CTLESC, CTLQUOTEMARK, '\0' };
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00005372
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005373 char *p, *q, *r;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005374 unsigned inquotes;
5375 int notescaped;
5376 int globbing;
5377
5378 p = strpbrk(str, qchars);
5379 if (!p) {
5380 return str;
5381 }
5382 q = p;
5383 r = str;
5384 if (flag & RMESCAPE_ALLOC) {
5385 size_t len = p - str;
5386 size_t fulllen = len + strlen(p) + 1;
5387
5388 if (flag & RMESCAPE_GROW) {
5389 r = makestrspace(fulllen, expdest);
5390 } else if (flag & RMESCAPE_HEAP) {
5391 r = ckmalloc(fulllen);
5392 } else {
5393 r = stalloc(fulllen);
5394 }
5395 q = r;
5396 if (len > 0) {
Denis Vlasenko29eb3592008-05-18 14:06:08 +00005397 q = (char *)memcpy(q, str, len) + len;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005398 }
5399 }
5400 inquotes = (flag & RMESCAPE_QUOTED) ^ RMESCAPE_QUOTED;
5401 globbing = flag & RMESCAPE_GLOB;
5402 notescaped = globbing;
5403 while (*p) {
5404 if (*p == CTLQUOTEMARK) {
5405 inquotes = ~inquotes;
5406 p++;
5407 notescaped = globbing;
5408 continue;
5409 }
5410 if (*p == '\\') {
5411 /* naked back slash */
5412 notescaped = 0;
5413 goto copy;
5414 }
5415 if (*p == CTLESC) {
5416 p++;
5417 if (notescaped && inquotes && *p != '/') {
5418 *q++ = '\\';
5419 }
5420 }
5421 notescaped = globbing;
5422 copy:
5423 *q++ = *p++;
5424 }
5425 *q = '\0';
5426 if (flag & RMESCAPE_GROW) {
5427 expdest = r;
5428 STADJUST(q - r + 1, expdest);
5429 }
5430 return r;
5431}
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005432#define pmatch(a, b) !fnmatch((a), (b), 0)
5433
5434/*
5435 * Prepare a pattern for a expmeta (internal glob(3)) call.
5436 *
5437 * Returns an stalloced string.
5438 */
5439static char *
5440preglob(const char *pattern, int quoted, int flag)
5441{
5442 flag |= RMESCAPE_GLOB;
5443 if (quoted) {
5444 flag |= RMESCAPE_QUOTED;
5445 }
Denys Vlasenkob6c84342009-08-29 20:23:20 +02005446 return rmescapes((char *)pattern, flag);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005447}
5448
5449/*
5450 * Put a string on the stack.
5451 */
5452static void
5453memtodest(const char *p, size_t len, int syntax, int quotes)
5454{
5455 char *q = expdest;
5456
Denys Vlasenkob6c84342009-08-29 20:23:20 +02005457 q = makestrspace(quotes ? len * 2 : len, q);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005458
5459 while (len--) {
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00005460 int c = signed_char2int(*p++);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005461 if (!c)
5462 continue;
Denys Vlasenkob6c84342009-08-29 20:23:20 +02005463 if (quotes) {
5464 int n = SIT(c, syntax);
5465 if (n == CCTL || n == CBACK)
5466 USTPUTC(CTLESC, q);
5467 }
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005468 USTPUTC(c, q);
5469 }
5470
5471 expdest = q;
5472}
5473
5474static void
5475strtodest(const char *p, int syntax, int quotes)
5476{
5477 memtodest(p, strlen(p), syntax, quotes);
5478}
5479
5480/*
5481 * Record the fact that we have to scan this region of the
5482 * string for IFS characters.
5483 */
5484static void
5485recordregion(int start, int end, int nulonly)
5486{
5487 struct ifsregion *ifsp;
5488
5489 if (ifslastp == NULL) {
5490 ifsp = &ifsfirst;
5491 } else {
5492 INT_OFF;
Denis Vlasenko597906c2008-02-20 16:38:54 +00005493 ifsp = ckzalloc(sizeof(*ifsp));
5494 /*ifsp->next = NULL; - ckzalloc did it */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005495 ifslastp->next = ifsp;
5496 INT_ON;
5497 }
5498 ifslastp = ifsp;
5499 ifslastp->begoff = start;
5500 ifslastp->endoff = end;
5501 ifslastp->nulonly = nulonly;
5502}
5503
5504static void
5505removerecordregions(int endoff)
5506{
5507 if (ifslastp == NULL)
5508 return;
5509
5510 if (ifsfirst.endoff > endoff) {
5511 while (ifsfirst.next != NULL) {
5512 struct ifsregion *ifsp;
5513 INT_OFF;
5514 ifsp = ifsfirst.next->next;
5515 free(ifsfirst.next);
5516 ifsfirst.next = ifsp;
5517 INT_ON;
5518 }
5519 if (ifsfirst.begoff > endoff)
5520 ifslastp = NULL;
5521 else {
5522 ifslastp = &ifsfirst;
5523 ifsfirst.endoff = endoff;
5524 }
5525 return;
5526 }
5527
5528 ifslastp = &ifsfirst;
5529 while (ifslastp->next && ifslastp->next->begoff < endoff)
5530 ifslastp=ifslastp->next;
5531 while (ifslastp->next != NULL) {
5532 struct ifsregion *ifsp;
5533 INT_OFF;
5534 ifsp = ifslastp->next->next;
5535 free(ifslastp->next);
5536 ifslastp->next = ifsp;
5537 INT_ON;
5538 }
5539 if (ifslastp->endoff > endoff)
5540 ifslastp->endoff = endoff;
5541}
5542
5543static char *
5544exptilde(char *startp, char *p, int flag)
5545{
5546 char c;
5547 char *name;
5548 struct passwd *pw;
5549 const char *home;
5550 int quotes = flag & (EXP_FULL | EXP_CASE);
5551 int startloc;
5552
5553 name = p + 1;
5554
5555 while ((c = *++p) != '\0') {
5556 switch (c) {
5557 case CTLESC:
5558 return startp;
5559 case CTLQUOTEMARK:
5560 return startp;
5561 case ':':
5562 if (flag & EXP_VARTILDE)
5563 goto done;
5564 break;
5565 case '/':
5566 case CTLENDVAR:
5567 goto done;
5568 }
5569 }
5570 done:
5571 *p = '\0';
5572 if (*name == '\0') {
5573 home = lookupvar(homestr);
5574 } else {
5575 pw = getpwnam(name);
5576 if (pw == NULL)
5577 goto lose;
5578 home = pw->pw_dir;
5579 }
5580 if (!home || !*home)
5581 goto lose;
5582 *p = c;
5583 startloc = expdest - (char *)stackblock();
5584 strtodest(home, SQSYNTAX, quotes);
5585 recordregion(startloc, expdest - (char *)stackblock(), 0);
5586 return p;
5587 lose:
5588 *p = c;
5589 return startp;
5590}
5591
5592/*
5593 * Execute a command inside back quotes. If it's a builtin command, we
5594 * want to save its output in a block obtained from malloc. Otherwise
5595 * we fork off a subprocess and get the output of the command via a pipe.
5596 * Should be called with interrupts off.
5597 */
5598struct backcmd { /* result of evalbackcmd */
5599 int fd; /* file descriptor to read from */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005600 int nleft; /* number of chars in buffer */
Denis Vlasenkob07a4962008-06-22 13:16:23 +00005601 char *buf; /* buffer */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005602 struct job *jp; /* job structure for command */
5603};
5604
5605/* These forward decls are needed to use "eval" code for backticks handling: */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00005606static uint8_t back_exitstatus; /* exit status of backquoted command */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005607#define EV_EXIT 01 /* exit after evaluating tree */
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02005608static void evaltree(union node *, int);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005609
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02005610static void FAST_FUNC
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005611evalbackcmd(union node *n, struct backcmd *result)
5612{
5613 int saveherefd;
5614
5615 result->fd = -1;
5616 result->buf = NULL;
5617 result->nleft = 0;
5618 result->jp = NULL;
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00005619 if (n == NULL)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005620 goto out;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005621
5622 saveherefd = herefd;
5623 herefd = -1;
5624
5625 {
5626 int pip[2];
5627 struct job *jp;
5628
5629 if (pipe(pip) < 0)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00005630 ash_msg_and_raise_error("pipe call failed");
Denis Vlasenko68404f12008-03-17 09:00:54 +00005631 jp = makejob(/*n,*/ 1);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005632 if (forkshell(jp, n, FORK_NOJOB) == 0) {
5633 FORCE_INT_ON;
5634 close(pip[0]);
5635 if (pip[1] != 1) {
Denis Vlasenko5a867312008-07-24 19:46:38 +00005636 /*close(1);*/
5637 copyfd(pip[1], 1 | COPYFD_EXACT);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005638 close(pip[1]);
5639 }
5640 eflag = 0;
5641 evaltree(n, EV_EXIT); /* actually evaltreenr... */
5642 /* NOTREACHED */
5643 }
5644 close(pip[1]);
5645 result->fd = pip[0];
5646 result->jp = jp;
5647 }
5648 herefd = saveherefd;
5649 out:
5650 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
5651 result->fd, result->buf, result->nleft, result->jp));
5652}
5653
5654/*
5655 * Expand stuff in backwards quotes.
5656 */
5657static void
5658expbackq(union node *cmd, int quoted, int quotes)
5659{
5660 struct backcmd in;
5661 int i;
5662 char buf[128];
5663 char *p;
5664 char *dest;
5665 int startloc;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00005666 int syntax = quoted ? DQSYNTAX : BASESYNTAX;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005667 struct stackmark smark;
5668
5669 INT_OFF;
5670 setstackmark(&smark);
5671 dest = expdest;
5672 startloc = dest - (char *)stackblock();
5673 grabstackstr(dest);
5674 evalbackcmd(cmd, &in);
5675 popstackmark(&smark);
5676
5677 p = in.buf;
5678 i = in.nleft;
5679 if (i == 0)
5680 goto read;
5681 for (;;) {
5682 memtodest(p, i, syntax, quotes);
5683 read:
5684 if (in.fd < 0)
5685 break;
Denis Vlasenkoe376d452008-02-20 22:23:24 +00005686 i = nonblock_safe_read(in.fd, buf, sizeof(buf));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005687 TRACE(("expbackq: read returns %d\n", i));
5688 if (i <= 0)
5689 break;
5690 p = buf;
5691 }
5692
Denis Vlasenko60818682007-09-28 22:07:23 +00005693 free(in.buf);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005694 if (in.fd >= 0) {
5695 close(in.fd);
5696 back_exitstatus = waitforjob(in.jp);
5697 }
5698 INT_ON;
5699
5700 /* Eat all trailing newlines */
5701 dest = expdest;
5702 for (; dest > (char *)stackblock() && dest[-1] == '\n';)
5703 STUNPUTC(dest);
5704 expdest = dest;
5705
5706 if (quoted == 0)
5707 recordregion(startloc, dest - (char *)stackblock(), 0);
5708 TRACE(("evalbackq: size=%d: \"%.*s\"\n",
5709 (dest - (char *)stackblock()) - startloc,
5710 (dest - (char *)stackblock()) - startloc,
5711 stackblock() + startloc));
5712}
5713
Mike Frysinger98c52642009-04-02 10:02:37 +00005714#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005715/*
5716 * Expand arithmetic expression. Backup to start of expression,
5717 * evaluate, place result in (backed up) result, adjust string position.
5718 */
5719static void
5720expari(int quotes)
5721{
5722 char *p, *start;
5723 int begoff;
5724 int flag;
5725 int len;
5726
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00005727 /* ifsfree(); */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005728
5729 /*
5730 * This routine is slightly over-complicated for
5731 * efficiency. Next we scan backwards looking for the
5732 * start of arithmetic.
5733 */
5734 start = stackblock();
5735 p = expdest - 1;
5736 *p = '\0';
5737 p--;
5738 do {
5739 int esc;
5740
5741 while (*p != CTLARI) {
5742 p--;
5743#if DEBUG
5744 if (p < start) {
5745 ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
5746 }
5747#endif
5748 }
5749
5750 esc = esclen(start, p);
5751 if (!(esc % 2)) {
5752 break;
5753 }
5754
5755 p -= esc + 1;
5756 } while (1);
5757
5758 begoff = p - start;
5759
5760 removerecordregions(begoff);
5761
5762 flag = p[1];
5763
5764 expdest = p;
5765
5766 if (quotes)
Denys Vlasenkob6c84342009-08-29 20:23:20 +02005767 rmescapes(p + 2, 0);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005768
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00005769 len = cvtnum(ash_arith(p + 2));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005770
5771 if (flag != '"')
5772 recordregion(begoff, begoff + len, 0);
5773}
5774#endif
5775
5776/* argstr needs it */
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00005777static char *evalvar(char *p, int flag, struct strlist *var_str_list);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005778
5779/*
5780 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
5781 * characters to allow for further processing. Otherwise treat
5782 * $@ like $* since no splitting will be performed.
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00005783 *
5784 * var_str_list (can be NULL) is a list of "VAR=val" strings which take precedence
5785 * over shell varables. Needed for "A=a B=$A; echo $B" case - we use it
5786 * for correct expansion of "B=$A" word.
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005787 */
5788static void
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00005789argstr(char *p, int flag, struct strlist *var_str_list)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005790{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00005791 static const char spclchars[] ALIGN1 = {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005792 '=',
5793 ':',
5794 CTLQUOTEMARK,
5795 CTLENDVAR,
5796 CTLESC,
5797 CTLVAR,
5798 CTLBACKQ,
5799 CTLBACKQ | CTLQUOTE,
Mike Frysinger98c52642009-04-02 10:02:37 +00005800#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005801 CTLENDARI,
5802#endif
5803 0
5804 };
5805 const char *reject = spclchars;
5806 int c;
Denys Vlasenkoc8334a42009-08-29 20:24:12 +02005807 int quotes = flag & (EXP_FULL | EXP_CASE | EXP_REDIR); /* do CTLESC */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005808 int breakall = flag & EXP_WORD;
5809 int inquotes;
5810 size_t length;
5811 int startloc;
5812
5813 if (!(flag & EXP_VARTILDE)) {
5814 reject += 2;
5815 } else if (flag & EXP_VARTILDE2) {
5816 reject++;
5817 }
5818 inquotes = 0;
5819 length = 0;
5820 if (flag & EXP_TILDE) {
5821 char *q;
5822
5823 flag &= ~EXP_TILDE;
5824 tilde:
5825 q = p;
5826 if (*q == CTLESC && (flag & EXP_QWORD))
5827 q++;
5828 if (*q == '~')
5829 p = exptilde(p, q, flag);
5830 }
5831 start:
5832 startloc = expdest - (char *)stackblock();
5833 for (;;) {
5834 length += strcspn(p + length, reject);
5835 c = p[length];
5836 if (c && (!(c & 0x80)
Mike Frysinger98c52642009-04-02 10:02:37 +00005837#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005838 || c == CTLENDARI
5839#endif
5840 )) {
5841 /* c == '=' || c == ':' || c == CTLENDARI */
5842 length++;
5843 }
5844 if (length > 0) {
5845 int newloc;
5846 expdest = stack_nputstr(p, length, expdest);
5847 newloc = expdest - (char *)stackblock();
5848 if (breakall && !inquotes && newloc > startloc) {
5849 recordregion(startloc, newloc, 0);
5850 }
5851 startloc = newloc;
5852 }
5853 p += length + 1;
5854 length = 0;
5855
5856 switch (c) {
5857 case '\0':
5858 goto breakloop;
5859 case '=':
5860 if (flag & EXP_VARTILDE2) {
5861 p--;
5862 continue;
5863 }
5864 flag |= EXP_VARTILDE2;
5865 reject++;
5866 /* fall through */
5867 case ':':
5868 /*
5869 * sort of a hack - expand tildes in variable
5870 * assignments (after the first '=' and after ':'s).
5871 */
5872 if (*--p == '~') {
5873 goto tilde;
5874 }
5875 continue;
5876 }
5877
5878 switch (c) {
5879 case CTLENDVAR: /* ??? */
5880 goto breakloop;
5881 case CTLQUOTEMARK:
5882 /* "$@" syntax adherence hack */
5883 if (
5884 !inquotes &&
5885 !memcmp(p, dolatstr, 4) &&
5886 (p[4] == CTLQUOTEMARK || (
5887 p[4] == CTLENDVAR &&
5888 p[5] == CTLQUOTEMARK
5889 ))
5890 ) {
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00005891 p = evalvar(p + 1, flag, /* var_str_list: */ NULL) + 1;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005892 goto start;
5893 }
5894 inquotes = !inquotes;
5895 addquote:
5896 if (quotes) {
5897 p--;
5898 length++;
5899 startloc++;
5900 }
5901 break;
5902 case CTLESC:
5903 startloc++;
5904 length++;
5905 goto addquote;
5906 case CTLVAR:
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00005907 p = evalvar(p, flag, var_str_list);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005908 goto start;
5909 case CTLBACKQ:
5910 c = 0;
5911 case CTLBACKQ|CTLQUOTE:
5912 expbackq(argbackq->n, c, quotes);
5913 argbackq = argbackq->next;
5914 goto start;
Mike Frysinger98c52642009-04-02 10:02:37 +00005915#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005916 case CTLENDARI:
5917 p--;
5918 expari(quotes);
5919 goto start;
5920#endif
5921 }
5922 }
5923 breakloop:
5924 ;
5925}
5926
5927static char *
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00005928scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM, char *str, int quotes,
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005929 int zero)
5930{
Denis Vlasenkoc7131c32008-04-14 01:59:53 +00005931// This commented out code was added by James Simmons <jsimmons@infradead.org>
5932// as part of a larger change when he added support for ${var/a/b}.
5933// However, it broke # and % operators:
5934//
5935//var=ababcdcd
5936// ok bad
5937//echo ${var#ab} abcdcd abcdcd
5938//echo ${var##ab} abcdcd abcdcd
5939//echo ${var#a*b} abcdcd ababcdcd (!)
5940//echo ${var##a*b} cdcd cdcd
5941//echo ${var#?} babcdcd ababcdcd (!)
5942//echo ${var##?} babcdcd babcdcd
5943//echo ${var#*} ababcdcd babcdcd (!)
5944//echo ${var##*}
5945//echo ${var%cd} ababcd ababcd
5946//echo ${var%%cd} ababcd abab (!)
5947//echo ${var%c*d} ababcd ababcd
5948//echo ${var%%c*d} abab ababcdcd (!)
5949//echo ${var%?} ababcdc ababcdc
5950//echo ${var%%?} ababcdc ababcdcd (!)
5951//echo ${var%*} ababcdcd ababcdcd
5952//echo ${var%%*}
5953//
5954// Commenting it back out helped. Remove it completely if it really
5955// is not needed.
5956
5957 char *loc, *loc2; //, *full;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005958 char c;
5959
5960 loc = startp;
5961 loc2 = rmesc;
5962 do {
Denis Vlasenkoc7131c32008-04-14 01:59:53 +00005963 int match; // = strlen(str);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005964 const char *s = loc2;
Denis Vlasenko92e13c22008-03-25 01:17:40 +00005965
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005966 c = *loc2;
5967 if (zero) {
5968 *loc2 = '\0';
5969 s = rmesc;
5970 }
Denis Vlasenkoc7131c32008-04-14 01:59:53 +00005971 match = pmatch(str, s); // this line was deleted
Denis Vlasenko92e13c22008-03-25 01:17:40 +00005972
Denis Vlasenkoc7131c32008-04-14 01:59:53 +00005973// // chop off end if its '*'
5974// full = strrchr(str, '*');
5975// if (full && full != str)
5976// match--;
5977//
5978// // If str starts with '*' replace with s.
5979// if ((*str == '*') && strlen(s) >= match) {
5980// full = xstrdup(s);
5981// strncpy(full+strlen(s)-match+1, str+1, match-1);
5982// } else
5983// full = xstrndup(str, match);
5984// match = strncmp(s, full, strlen(full));
5985// free(full);
5986//
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005987 *loc2 = c;
Denis Vlasenkoc7131c32008-04-14 01:59:53 +00005988 if (match) // if (!match)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005989 return loc;
5990 if (quotes && *loc == CTLESC)
5991 loc++;
5992 loc++;
5993 loc2++;
5994 } while (c);
5995 return 0;
5996}
5997
5998static char *
5999scanright(char *startp, char *rmesc, char *rmescend, char *str, int quotes,
6000 int zero)
6001{
6002 int esc = 0;
6003 char *loc;
6004 char *loc2;
6005
6006 for (loc = str - 1, loc2 = rmescend; loc >= startp; loc2--) {
6007 int match;
6008 char c = *loc2;
6009 const char *s = loc2;
6010 if (zero) {
6011 *loc2 = '\0';
6012 s = rmesc;
6013 }
6014 match = pmatch(str, s);
6015 *loc2 = c;
6016 if (match)
6017 return loc;
6018 loc--;
6019 if (quotes) {
6020 if (--esc < 0) {
6021 esc = esclen(startp, loc);
6022 }
6023 if (esc % 2) {
6024 esc--;
6025 loc--;
6026 }
6027 }
6028 }
6029 return 0;
6030}
6031
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00006032static void varunset(const char *, const char *, const char *, int) NORETURN;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006033static void
6034varunset(const char *end, const char *var, const char *umsg, int varflags)
6035{
6036 const char *msg;
6037 const char *tail;
6038
6039 tail = nullstr;
6040 msg = "parameter not set";
6041 if (umsg) {
6042 if (*end == CTLENDVAR) {
6043 if (varflags & VSNUL)
6044 tail = " or null";
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00006045 } else {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006046 msg = umsg;
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00006047 }
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006048 }
6049 ash_msg_and_raise_error("%.*s: %s%s", end - var - 1, var, msg, tail);
6050}
6051
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006052#if ENABLE_ASH_BASH_COMPAT
6053static char *
6054parse_sub_pattern(char *arg, int inquotes)
6055{
6056 char *idx, *repl = NULL;
6057 unsigned char c;
6058
Denis Vlasenko2659c632008-06-14 06:04:59 +00006059 idx = arg;
6060 while (1) {
6061 c = *arg;
6062 if (!c)
6063 break;
6064 if (c == '/') {
6065 /* Only the first '/' seen is our separator */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006066 if (!repl) {
Denis Vlasenko2659c632008-06-14 06:04:59 +00006067 repl = idx + 1;
6068 c = '\0';
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006069 }
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006070 }
Denis Vlasenko2659c632008-06-14 06:04:59 +00006071 *idx++ = c;
6072 if (!inquotes && c == '\\' && arg[1] == '\\')
6073 arg++; /* skip both \\, not just first one */
6074 arg++;
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006075 }
Denis Vlasenko29038c02008-06-14 06:14:02 +00006076 *idx = c; /* NUL */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006077
6078 return repl;
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006079}
6080#endif /* ENABLE_ASH_BASH_COMPAT */
6081
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006082static const char *
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006083subevalvar(char *p, char *str, int strloc, int subtype,
6084 int startloc, int varflags, int quotes, struct strlist *var_str_list)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006085{
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006086 struct nodelist *saveargbackq = argbackq;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006087 char *startp;
6088 char *loc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006089 char *rmesc, *rmescend;
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00006090 IF_ASH_BASH_COMPAT(char *repl = NULL;)
6091 IF_ASH_BASH_COMPAT(char null = '\0';)
6092 IF_ASH_BASH_COMPAT(int pos, len, orig_len;)
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006093 int saveherefd = herefd;
6094 int amount, workloc, resetloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006095 int zero;
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006096 char *(*scan)(char*, char*, char*, char*, int, int);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006097
6098 herefd = -1;
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006099 argstr(p, (subtype != VSASSIGN && subtype != VSQUESTION) ? EXP_CASE : 0,
6100 var_str_list);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006101 STPUTC('\0', expdest);
6102 herefd = saveherefd;
6103 argbackq = saveargbackq;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00006104 startp = (char *)stackblock() + startloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006105
6106 switch (subtype) {
6107 case VSASSIGN:
6108 setvar(str, startp, 0);
6109 amount = startp - expdest;
6110 STADJUST(amount, expdest);
6111 return startp;
6112
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006113#if ENABLE_ASH_BASH_COMPAT
6114 case VSSUBSTR:
6115 loc = str = stackblock() + strloc;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006116 /* Read POS in ${var:POS:LEN} */
6117 pos = atoi(loc); /* number(loc) errors out on "1:4" */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006118 len = str - startp - 1;
6119
6120 /* *loc != '\0', guaranteed by parser */
6121 if (quotes) {
6122 char *ptr;
6123
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006124 /* Adjust the length by the number of escapes */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006125 for (ptr = startp; ptr < (str - 1); ptr++) {
Denis Vlasenkod6855d12008-09-27 14:03:25 +00006126 if (*ptr == CTLESC) {
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006127 len--;
6128 ptr++;
6129 }
6130 }
6131 }
6132 orig_len = len;
6133
6134 if (*loc++ == ':') {
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006135 /* ${var::LEN} */
6136 len = number(loc);
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006137 } else {
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006138 /* Skip POS in ${var:POS:LEN} */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006139 len = orig_len;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006140 while (*loc && *loc != ':') {
6141 /* TODO?
6142 * bash complains on: var=qwe; echo ${var:1a:123}
6143 if (!isdigit(*loc))
6144 ash_msg_and_raise_error(msg_illnum, str);
6145 */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006146 loc++;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006147 }
6148 if (*loc++ == ':') {
6149 len = number(loc);
6150 }
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006151 }
6152 if (pos >= orig_len) {
6153 pos = 0;
6154 len = 0;
6155 }
6156 if (len > (orig_len - pos))
6157 len = orig_len - pos;
6158
6159 for (str = startp; pos; str++, pos--) {
6160 if (quotes && *str == CTLESC)
6161 str++;
6162 }
6163 for (loc = startp; len; len--) {
6164 if (quotes && *str == CTLESC)
6165 *loc++ = *str++;
6166 *loc++ = *str++;
6167 }
6168 *loc = '\0';
6169 amount = loc - expdest;
6170 STADJUST(amount, expdest);
6171 return loc;
6172#endif
6173
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006174 case VSQUESTION:
6175 varunset(p, str, startp, varflags);
6176 /* NOTREACHED */
6177 }
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006178 resetloc = expdest - (char *)stackblock();
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006179
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006180 /* We'll comeback here if we grow the stack while handling
6181 * a VSREPLACE or VSREPLACEALL, since our pointers into the
6182 * stack will need rebasing, and we'll need to remove our work
6183 * areas each time
6184 */
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00006185 IF_ASH_BASH_COMPAT(restart:)
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006186
6187 amount = expdest - ((char *)stackblock() + resetloc);
6188 STADJUST(-amount, expdest);
Denis Vlasenko29eb3592008-05-18 14:06:08 +00006189 startp = (char *)stackblock() + startloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006190
6191 rmesc = startp;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00006192 rmescend = (char *)stackblock() + strloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006193 if (quotes) {
Denys Vlasenkob6c84342009-08-29 20:23:20 +02006194 rmesc = rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006195 if (rmesc != startp) {
6196 rmescend = expdest;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00006197 startp = (char *)stackblock() + startloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006198 }
6199 }
6200 rmescend--;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00006201 str = (char *)stackblock() + strloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006202 preglob(str, varflags & VSQUOTE, 0);
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006203 workloc = expdest - (char *)stackblock();
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006204
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006205#if ENABLE_ASH_BASH_COMPAT
6206 if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
6207 char *idx, *end, *restart_detect;
6208
Denis Vlasenkod6855d12008-09-27 14:03:25 +00006209 if (!repl) {
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006210 repl = parse_sub_pattern(str, varflags & VSQUOTE);
6211 if (!repl)
6212 repl = &null;
6213 }
6214
6215 /* If there's no pattern to match, return the expansion unmolested */
6216 if (*str == '\0')
6217 return 0;
6218
6219 len = 0;
6220 idx = startp;
6221 end = str - 1;
6222 while (idx < end) {
6223 loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
6224 if (!loc) {
6225 /* No match, advance */
6226 restart_detect = stackblock();
6227 STPUTC(*idx, expdest);
6228 if (quotes && *idx == CTLESC) {
6229 idx++;
6230 len++;
6231 STPUTC(*idx, expdest);
6232 }
6233 if (stackblock() != restart_detect)
6234 goto restart;
6235 idx++;
6236 len++;
6237 rmesc++;
6238 continue;
6239 }
6240
6241 if (subtype == VSREPLACEALL) {
6242 while (idx < loc) {
6243 if (quotes && *idx == CTLESC)
6244 idx++;
6245 idx++;
6246 rmesc++;
6247 }
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00006248 } else {
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006249 idx = loc;
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00006250 }
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006251
6252 for (loc = repl; *loc; loc++) {
6253 restart_detect = stackblock();
6254 STPUTC(*loc, expdest);
6255 if (stackblock() != restart_detect)
6256 goto restart;
6257 len++;
6258 }
6259
6260 if (subtype == VSREPLACE) {
6261 while (*idx) {
6262 restart_detect = stackblock();
6263 STPUTC(*idx, expdest);
6264 if (stackblock() != restart_detect)
6265 goto restart;
6266 len++;
6267 idx++;
6268 }
6269 break;
6270 }
6271 }
6272
6273 /* We've put the replaced text into a buffer at workloc, now
6274 * move it to the right place and adjust the stack.
6275 */
6276 startp = stackblock() + startloc;
6277 STPUTC('\0', expdest);
6278 memmove(startp, stackblock() + workloc, len);
6279 startp[len++] = '\0';
6280 amount = expdest - ((char *)stackblock() + startloc + len - 1);
6281 STADJUST(-amount, expdest);
6282 return startp;
6283 }
6284#endif /* ENABLE_ASH_BASH_COMPAT */
6285
6286 subtype -= VSTRIMRIGHT;
6287#if DEBUG
6288 if (subtype < 0 || subtype > 7)
6289 abort();
6290#endif
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006291 /* zero = subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX */
6292 zero = subtype >> 1;
6293 /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
6294 scan = (subtype & 1) ^ zero ? scanleft : scanright;
6295
6296 loc = scan(startp, rmesc, rmescend, str, quotes, zero);
6297 if (loc) {
6298 if (zero) {
6299 memmove(startp, loc, str - loc);
6300 loc = startp + (str - loc) - 1;
6301 }
6302 *loc = '\0';
6303 amount = loc - expdest;
6304 STADJUST(amount, expdest);
6305 }
6306 return loc;
6307}
6308
6309/*
6310 * Add the value of a specialized variable to the stack string.
6311 */
6312static ssize_t
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006313varvalue(char *name, int varflags, int flags, struct strlist *var_str_list)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006314{
6315 int num;
Mike Frysinger98c52642009-04-02 10:02:37 +00006316 const char *p;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006317 int i;
6318 int sep = 0;
6319 int sepq = 0;
6320 ssize_t len = 0;
6321 char **ap;
6322 int syntax;
6323 int quoted = varflags & VSQUOTE;
6324 int subtype = varflags & VSTYPE;
6325 int quotes = flags & (EXP_FULL | EXP_CASE);
6326
6327 if (quoted && (flags & EXP_FULL))
6328 sep = 1 << CHAR_BIT;
6329
6330 syntax = quoted ? DQSYNTAX : BASESYNTAX;
6331 switch (*name) {
6332 case '$':
6333 num = rootpid;
6334 goto numvar;
6335 case '?':
6336 num = exitstatus;
6337 goto numvar;
6338 case '#':
6339 num = shellparam.nparam;
6340 goto numvar;
6341 case '!':
6342 num = backgndpid;
6343 if (num == 0)
6344 return -1;
6345 numvar:
6346 len = cvtnum(num);
6347 break;
6348 case '-':
Mike Frysinger98c52642009-04-02 10:02:37 +00006349 expdest = makestrspace(NOPTS, expdest);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006350 for (i = NOPTS - 1; i >= 0; i--) {
6351 if (optlist[i]) {
Mike Frysinger98c52642009-04-02 10:02:37 +00006352 USTPUTC(optletters(i), expdest);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006353 len++;
6354 }
6355 }
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006356 break;
6357 case '@':
6358 if (sep)
6359 goto param;
6360 /* fall through */
6361 case '*':
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00006362 sep = ifsset() ? signed_char2int(ifsval()[0]) : ' ';
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006363 if (quotes && (SIT(sep, syntax) == CCTL || SIT(sep, syntax) == CBACK))
6364 sepq = 1;
6365 param:
6366 ap = shellparam.p;
6367 if (!ap)
6368 return -1;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006369 while ((p = *ap++) != NULL) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006370 size_t partlen;
6371
6372 partlen = strlen(p);
6373 len += partlen;
6374
6375 if (!(subtype == VSPLUS || subtype == VSLENGTH))
6376 memtodest(p, partlen, syntax, quotes);
6377
6378 if (*ap && sep) {
6379 char *q;
6380
6381 len++;
6382 if (subtype == VSPLUS || subtype == VSLENGTH) {
6383 continue;
6384 }
6385 q = expdest;
6386 if (sepq)
6387 STPUTC(CTLESC, q);
6388 STPUTC(sep, q);
6389 expdest = q;
6390 }
6391 }
6392 return len;
6393 case '0':
6394 case '1':
6395 case '2':
6396 case '3':
6397 case '4':
6398 case '5':
6399 case '6':
6400 case '7':
6401 case '8':
6402 case '9':
Denys Vlasenkoa00329c2009-08-30 20:05:10 +02006403 num = atoi(name); /* number(name) fails on ${N#str} etc */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006404 if (num < 0 || num > shellparam.nparam)
6405 return -1;
6406 p = num ? shellparam.p[num - 1] : arg0;
6407 goto value;
6408 default:
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006409 /* NB: name has form "VAR=..." */
6410
6411 /* "A=a B=$A" case: var_str_list is a list of "A=a" strings
6412 * which should be considered before we check variables. */
6413 if (var_str_list) {
6414 unsigned name_len = (strchrnul(name, '=') - name) + 1;
6415 p = NULL;
6416 do {
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00006417 char *str, *eq;
6418 str = var_str_list->text;
6419 eq = strchr(str, '=');
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006420 if (!eq) /* stop at first non-assignment */
6421 break;
6422 eq++;
Denis Vlasenko6b06cb82008-05-15 21:30:45 +00006423 if (name_len == (unsigned)(eq - str)
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006424 && strncmp(str, name, name_len) == 0) {
6425 p = eq;
6426 /* goto value; - WRONG! */
6427 /* think "A=1 A=2 B=$A" */
6428 }
6429 var_str_list = var_str_list->next;
6430 } while (var_str_list);
6431 if (p)
6432 goto value;
6433 }
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006434 p = lookupvar(name);
6435 value:
6436 if (!p)
6437 return -1;
6438
6439 len = strlen(p);
6440 if (!(subtype == VSPLUS || subtype == VSLENGTH))
6441 memtodest(p, len, syntax, quotes);
6442 return len;
6443 }
6444
6445 if (subtype == VSPLUS || subtype == VSLENGTH)
6446 STADJUST(-len, expdest);
6447 return len;
6448}
6449
6450/*
6451 * Expand a variable, and return a pointer to the next character in the
6452 * input string.
6453 */
6454static char *
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006455evalvar(char *p, int flag, struct strlist *var_str_list)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006456{
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006457 char varflags;
6458 char subtype;
6459 char quoted;
6460 char easy;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006461 char *var;
6462 int patloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006463 int startloc;
6464 ssize_t varlen;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006465
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006466 varflags = *p++;
6467 subtype = varflags & VSTYPE;
6468 quoted = varflags & VSQUOTE;
6469 var = p;
6470 easy = (!quoted || (*var == '@' && shellparam.nparam));
6471 startloc = expdest - (char *)stackblock();
6472 p = strchr(p, '=') + 1;
6473
6474 again:
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006475 varlen = varvalue(var, varflags, flag, var_str_list);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006476 if (varflags & VSNUL)
6477 varlen--;
6478
6479 if (subtype == VSPLUS) {
6480 varlen = -1 - varlen;
6481 goto vsplus;
6482 }
6483
6484 if (subtype == VSMINUS) {
6485 vsplus:
6486 if (varlen < 0) {
6487 argstr(
6488 p, flag | EXP_TILDE |
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006489 (quoted ? EXP_QWORD : EXP_WORD),
6490 var_str_list
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006491 );
6492 goto end;
6493 }
6494 if (easy)
6495 goto record;
6496 goto end;
6497 }
6498
6499 if (subtype == VSASSIGN || subtype == VSQUESTION) {
6500 if (varlen < 0) {
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006501 if (subevalvar(p, var, /* strloc: */ 0,
6502 subtype, startloc, varflags,
6503 /* quotes: */ 0,
6504 var_str_list)
6505 ) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006506 varflags &= ~VSNUL;
6507 /*
6508 * Remove any recorded regions beyond
6509 * start of variable
6510 */
6511 removerecordregions(startloc);
6512 goto again;
6513 }
6514 goto end;
6515 }
6516 if (easy)
6517 goto record;
6518 goto end;
6519 }
6520
6521 if (varlen < 0 && uflag)
6522 varunset(p, var, 0, 0);
6523
6524 if (subtype == VSLENGTH) {
6525 cvtnum(varlen > 0 ? varlen : 0);
6526 goto record;
6527 }
6528
6529 if (subtype == VSNORMAL) {
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006530 if (easy)
6531 goto record;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006532 goto end;
6533 }
6534
6535#if DEBUG
6536 switch (subtype) {
6537 case VSTRIMLEFT:
6538 case VSTRIMLEFTMAX:
6539 case VSTRIMRIGHT:
6540 case VSTRIMRIGHTMAX:
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006541#if ENABLE_ASH_BASH_COMPAT
6542 case VSSUBSTR:
6543 case VSREPLACE:
6544 case VSREPLACEALL:
6545#endif
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006546 break;
6547 default:
6548 abort();
6549 }
6550#endif
6551
6552 if (varlen >= 0) {
6553 /*
6554 * Terminate the string and start recording the pattern
6555 * right after it
6556 */
6557 STPUTC('\0', expdest);
6558 patloc = expdest - (char *)stackblock();
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006559 if (0 == subevalvar(p, /* str: */ NULL, patloc, subtype,
6560 startloc, varflags,
6561 /* quotes: */ flag & (EXP_FULL | EXP_CASE),
6562 var_str_list)
6563 ) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006564 int amount = expdest - (
6565 (char *)stackblock() + patloc - 1
6566 );
6567 STADJUST(-amount, expdest);
6568 }
6569 /* Remove any recorded regions beyond start of variable */
6570 removerecordregions(startloc);
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006571 record:
6572 recordregion(startloc, expdest - (char *)stackblock(), quoted);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006573 }
6574
6575 end:
6576 if (subtype != VSNORMAL) { /* skip to end of alternative */
6577 int nesting = 1;
6578 for (;;) {
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006579 char c = *p++;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006580 if (c == CTLESC)
6581 p++;
6582 else if (c == CTLBACKQ || c == (CTLBACKQ|CTLQUOTE)) {
6583 if (varlen >= 0)
6584 argbackq = argbackq->next;
6585 } else if (c == CTLVAR) {
6586 if ((*p++ & VSTYPE) != VSNORMAL)
6587 nesting++;
6588 } else if (c == CTLENDVAR) {
6589 if (--nesting == 0)
6590 break;
6591 }
6592 }
6593 }
6594 return p;
6595}
6596
6597/*
6598 * Break the argument string into pieces based upon IFS and add the
6599 * strings to the argument list. The regions of the string to be
6600 * searched for IFS characters have been stored by recordregion.
6601 */
6602static void
6603ifsbreakup(char *string, struct arglist *arglist)
6604{
6605 struct ifsregion *ifsp;
6606 struct strlist *sp;
6607 char *start;
6608 char *p;
6609 char *q;
6610 const char *ifs, *realifs;
6611 int ifsspc;
6612 int nulonly;
6613
6614 start = string;
6615 if (ifslastp != NULL) {
6616 ifsspc = 0;
6617 nulonly = 0;
6618 realifs = ifsset() ? ifsval() : defifs;
6619 ifsp = &ifsfirst;
6620 do {
6621 p = string + ifsp->begoff;
6622 nulonly = ifsp->nulonly;
6623 ifs = nulonly ? nullstr : realifs;
6624 ifsspc = 0;
6625 while (p < string + ifsp->endoff) {
6626 q = p;
6627 if (*p == CTLESC)
6628 p++;
6629 if (!strchr(ifs, *p)) {
6630 p++;
6631 continue;
6632 }
6633 if (!nulonly)
6634 ifsspc = (strchr(defifs, *p) != NULL);
6635 /* Ignore IFS whitespace at start */
6636 if (q == start && ifsspc) {
6637 p++;
6638 start = p;
6639 continue;
6640 }
6641 *q = '\0';
Denis Vlasenko597906c2008-02-20 16:38:54 +00006642 sp = stzalloc(sizeof(*sp));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006643 sp->text = start;
6644 *arglist->lastp = sp;
6645 arglist->lastp = &sp->next;
6646 p++;
6647 if (!nulonly) {
6648 for (;;) {
6649 if (p >= string + ifsp->endoff) {
6650 break;
6651 }
6652 q = p;
6653 if (*p == CTLESC)
6654 p++;
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +00006655 if (strchr(ifs, *p) == NULL) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006656 p = q;
6657 break;
Denis Vlasenko597906c2008-02-20 16:38:54 +00006658 }
6659 if (strchr(defifs, *p) == NULL) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006660 if (ifsspc) {
6661 p++;
6662 ifsspc = 0;
6663 } else {
6664 p = q;
6665 break;
6666 }
6667 } else
6668 p++;
6669 }
6670 }
6671 start = p;
6672 } /* while */
6673 ifsp = ifsp->next;
6674 } while (ifsp != NULL);
6675 if (nulonly)
6676 goto add;
6677 }
6678
6679 if (!*start)
6680 return;
6681
6682 add:
Denis Vlasenko597906c2008-02-20 16:38:54 +00006683 sp = stzalloc(sizeof(*sp));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006684 sp->text = start;
6685 *arglist->lastp = sp;
6686 arglist->lastp = &sp->next;
6687}
6688
6689static void
6690ifsfree(void)
6691{
6692 struct ifsregion *p;
6693
6694 INT_OFF;
6695 p = ifsfirst.next;
6696 do {
6697 struct ifsregion *ifsp;
6698 ifsp = p->next;
6699 free(p);
6700 p = ifsp;
6701 } while (p);
6702 ifslastp = NULL;
6703 ifsfirst.next = NULL;
6704 INT_ON;
6705}
6706
6707/*
6708 * Add a file name to the list.
6709 */
6710static void
6711addfname(const char *name)
6712{
6713 struct strlist *sp;
6714
Denis Vlasenko597906c2008-02-20 16:38:54 +00006715 sp = stzalloc(sizeof(*sp));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006716 sp->text = ststrdup(name);
6717 *exparg.lastp = sp;
6718 exparg.lastp = &sp->next;
6719}
6720
6721static char *expdir;
6722
6723/*
6724 * Do metacharacter (i.e. *, ?, [...]) expansion.
6725 */
6726static void
6727expmeta(char *enddir, char *name)
6728{
6729 char *p;
6730 const char *cp;
6731 char *start;
6732 char *endname;
6733 int metaflag;
6734 struct stat statb;
6735 DIR *dirp;
6736 struct dirent *dp;
6737 int atend;
6738 int matchdot;
6739
6740 metaflag = 0;
6741 start = name;
6742 for (p = name; *p; p++) {
6743 if (*p == '*' || *p == '?')
6744 metaflag = 1;
6745 else if (*p == '[') {
6746 char *q = p + 1;
6747 if (*q == '!')
6748 q++;
6749 for (;;) {
6750 if (*q == '\\')
6751 q++;
6752 if (*q == '/' || *q == '\0')
6753 break;
6754 if (*++q == ']') {
6755 metaflag = 1;
6756 break;
6757 }
6758 }
6759 } else if (*p == '\\')
6760 p++;
6761 else if (*p == '/') {
6762 if (metaflag)
6763 goto out;
6764 start = p + 1;
6765 }
6766 }
6767 out:
6768 if (metaflag == 0) { /* we've reached the end of the file name */
6769 if (enddir != expdir)
6770 metaflag++;
6771 p = name;
6772 do {
6773 if (*p == '\\')
6774 p++;
6775 *enddir++ = *p;
6776 } while (*p++);
6777 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
6778 addfname(expdir);
6779 return;
6780 }
6781 endname = p;
6782 if (name < start) {
6783 p = name;
6784 do {
6785 if (*p == '\\')
6786 p++;
6787 *enddir++ = *p++;
6788 } while (p < start);
6789 }
6790 if (enddir == expdir) {
6791 cp = ".";
6792 } else if (enddir == expdir + 1 && *expdir == '/') {
6793 cp = "/";
6794 } else {
6795 cp = expdir;
6796 enddir[-1] = '\0';
6797 }
6798 dirp = opendir(cp);
6799 if (dirp == NULL)
6800 return;
6801 if (enddir != expdir)
6802 enddir[-1] = '/';
6803 if (*endname == 0) {
6804 atend = 1;
6805 } else {
6806 atend = 0;
6807 *endname++ = '\0';
6808 }
6809 matchdot = 0;
6810 p = start;
6811 if (*p == '\\')
6812 p++;
6813 if (*p == '.')
6814 matchdot++;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006815 while (!pending_int && (dp = readdir(dirp)) != NULL) {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00006816 if (dp->d_name[0] == '.' && !matchdot)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006817 continue;
6818 if (pmatch(start, dp->d_name)) {
6819 if (atend) {
6820 strcpy(enddir, dp->d_name);
6821 addfname(expdir);
6822 } else {
6823 for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
6824 continue;
6825 p[-1] = '/';
6826 expmeta(p, endname);
6827 }
6828 }
6829 }
6830 closedir(dirp);
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00006831 if (!atend)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006832 endname[-1] = '/';
6833}
6834
6835static struct strlist *
6836msort(struct strlist *list, int len)
6837{
6838 struct strlist *p, *q = NULL;
6839 struct strlist **lpp;
6840 int half;
6841 int n;
6842
6843 if (len <= 1)
6844 return list;
6845 half = len >> 1;
6846 p = list;
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +00006847 for (n = half; --n >= 0;) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006848 q = p;
6849 p = p->next;
6850 }
6851 q->next = NULL; /* terminate first half of list */
6852 q = msort(list, half); /* sort first half of list */
6853 p = msort(p, len - half); /* sort second half */
6854 lpp = &list;
6855 for (;;) {
6856#if ENABLE_LOCALE_SUPPORT
6857 if (strcoll(p->text, q->text) < 0)
6858#else
6859 if (strcmp(p->text, q->text) < 0)
6860#endif
6861 {
6862 *lpp = p;
6863 lpp = &p->next;
6864 p = *lpp;
6865 if (p == NULL) {
6866 *lpp = q;
6867 break;
6868 }
6869 } else {
6870 *lpp = q;
6871 lpp = &q->next;
6872 q = *lpp;
6873 if (q == NULL) {
6874 *lpp = p;
6875 break;
6876 }
6877 }
6878 }
6879 return list;
6880}
6881
6882/*
6883 * Sort the results of file name expansion. It calculates the number of
6884 * strings to sort and then calls msort (short for merge sort) to do the
6885 * work.
6886 */
6887static struct strlist *
6888expsort(struct strlist *str)
6889{
6890 int len;
6891 struct strlist *sp;
6892
6893 len = 0;
6894 for (sp = str; sp; sp = sp->next)
6895 len++;
6896 return msort(str, len);
6897}
6898
6899static void
Denis Vlasenko68404f12008-03-17 09:00:54 +00006900expandmeta(struct strlist *str /*, int flag*/)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006901{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00006902 static const char metachars[] ALIGN1 = {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006903 '*', '?', '[', 0
6904 };
6905 /* TODO - EXP_REDIR */
6906
6907 while (str) {
6908 struct strlist **savelastp;
6909 struct strlist *sp;
6910 char *p;
6911
6912 if (fflag)
6913 goto nometa;
6914 if (!strpbrk(str->text, metachars))
6915 goto nometa;
6916 savelastp = exparg.lastp;
6917
6918 INT_OFF;
6919 p = preglob(str->text, 0, RMESCAPE_ALLOC | RMESCAPE_HEAP);
6920 {
6921 int i = strlen(str->text);
6922 expdir = ckmalloc(i < 2048 ? 2048 : i); /* XXX */
6923 }
6924
6925 expmeta(expdir, p);
6926 free(expdir);
6927 if (p != str->text)
6928 free(p);
6929 INT_ON;
6930 if (exparg.lastp == savelastp) {
6931 /*
6932 * no matches
6933 */
6934 nometa:
6935 *exparg.lastp = str;
Denys Vlasenkob6c84342009-08-29 20:23:20 +02006936 rmescapes(str->text, 0);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006937 exparg.lastp = &str->next;
6938 } else {
6939 *exparg.lastp = NULL;
6940 *savelastp = sp = expsort(*savelastp);
6941 while (sp->next != NULL)
6942 sp = sp->next;
6943 exparg.lastp = &sp->next;
6944 }
6945 str = str->next;
6946 }
6947}
6948
6949/*
6950 * Perform variable substitution and command substitution on an argument,
6951 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
6952 * perform splitting and file name expansion. When arglist is NULL, perform
6953 * here document expansion.
6954 */
6955static void
6956expandarg(union node *arg, struct arglist *arglist, int flag)
6957{
6958 struct strlist *sp;
6959 char *p;
6960
6961 argbackq = arg->narg.backquote;
6962 STARTSTACKSTR(expdest);
6963 ifsfirst.next = NULL;
6964 ifslastp = NULL;
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006965 argstr(arg->narg.text, flag,
6966 /* var_str_list: */ arglist ? arglist->list : NULL);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006967 p = _STPUTC('\0', expdest);
6968 expdest = p - 1;
6969 if (arglist == NULL) {
6970 return; /* here document expanded */
6971 }
6972 p = grabstackstr(p);
6973 exparg.lastp = &exparg.list;
6974 /*
6975 * TODO - EXP_REDIR
6976 */
6977 if (flag & EXP_FULL) {
6978 ifsbreakup(p, &exparg);
6979 *exparg.lastp = NULL;
6980 exparg.lastp = &exparg.list;
Denis Vlasenko68404f12008-03-17 09:00:54 +00006981 expandmeta(exparg.list /*, flag*/);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006982 } else {
6983 if (flag & EXP_REDIR) /*XXX - for now, just remove escapes */
Denys Vlasenkob6c84342009-08-29 20:23:20 +02006984 rmescapes(p, 0);
Denis Vlasenko597906c2008-02-20 16:38:54 +00006985 sp = stzalloc(sizeof(*sp));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006986 sp->text = p;
6987 *exparg.lastp = sp;
6988 exparg.lastp = &sp->next;
6989 }
6990 if (ifsfirst.next)
6991 ifsfree();
6992 *exparg.lastp = NULL;
6993 if (exparg.list) {
6994 *arglist->lastp = exparg.list;
6995 arglist->lastp = exparg.lastp;
6996 }
6997}
6998
6999/*
7000 * Expand shell variables and backquotes inside a here document.
7001 */
7002static void
7003expandhere(union node *arg, int fd)
7004{
7005 herefd = fd;
7006 expandarg(arg, (struct arglist *)NULL, 0);
7007 full_write(fd, stackblock(), expdest - (char *)stackblock());
7008}
7009
7010/*
7011 * Returns true if the pattern matches the string.
7012 */
7013static int
7014patmatch(char *pattern, const char *string)
7015{
7016 return pmatch(preglob(pattern, 0, 0), string);
7017}
7018
7019/*
7020 * See if a pattern matches in a case statement.
7021 */
7022static int
7023casematch(union node *pattern, char *val)
7024{
7025 struct stackmark smark;
7026 int result;
7027
7028 setstackmark(&smark);
7029 argbackq = pattern->narg.backquote;
7030 STARTSTACKSTR(expdest);
7031 ifslastp = NULL;
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00007032 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE,
7033 /* var_str_list: */ NULL);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007034 STACKSTRNUL(expdest);
7035 result = patmatch(stackblock(), val);
7036 popstackmark(&smark);
7037 return result;
7038}
7039
7040
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007041/* ============ find_command */
7042
7043struct builtincmd {
7044 const char *name;
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007045 int (*builtin)(int, char **) FAST_FUNC;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007046 /* unsigned flags; */
7047};
7048#define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
Denis Vlasenkoe26b2782008-02-12 07:40:29 +00007049/* "regular" builtins always take precedence over commands,
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007050 * regardless of PATH=....%builtin... position */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007051#define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007052#define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007053
7054struct cmdentry {
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00007055 smallint cmdtype; /* CMDxxx */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007056 union param {
7057 int index;
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00007058 /* index >= 0 for commands without path (slashes) */
7059 /* (TODO: what exactly does the value mean? PATH position?) */
7060 /* index == -1 for commands with slashes */
7061 /* index == (-2 - applet_no) for NOFORK applets */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007062 const struct builtincmd *cmd;
7063 struct funcnode *func;
7064 } u;
7065};
7066/* values of cmdtype */
7067#define CMDUNKNOWN -1 /* no entry in table for command */
7068#define CMDNORMAL 0 /* command is an executable program */
7069#define CMDFUNCTION 1 /* command is a shell function */
7070#define CMDBUILTIN 2 /* command is a shell builtin */
7071
7072/* action to find_command() */
7073#define DO_ERR 0x01 /* prints errors */
7074#define DO_ABS 0x02 /* checks absolute paths */
7075#define DO_NOFUNC 0x04 /* don't return shell functions, for command */
7076#define DO_ALTPATH 0x08 /* using alternate path */
7077#define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
7078
7079static void find_command(char *, struct cmdentry *, int, const char *);
7080
7081
7082/* ============ Hashing commands */
7083
7084/*
7085 * When commands are first encountered, they are entered in a hash table.
7086 * This ensures that a full path search will not have to be done for them
7087 * on each invocation.
7088 *
7089 * We should investigate converting to a linear search, even though that
7090 * would make the command name "hash" a misnomer.
7091 */
7092
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007093struct tblentry {
7094 struct tblentry *next; /* next entry in hash chain */
7095 union param param; /* definition of builtin function */
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00007096 smallint cmdtype; /* CMDxxx */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007097 char rehash; /* if set, cd done since entry created */
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007098 char cmdname[1]; /* name of command */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007099};
7100
Denis Vlasenko01631112007-12-16 17:20:38 +00007101static struct tblentry **cmdtable;
7102#define INIT_G_cmdtable() do { \
7103 cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
7104} while (0)
7105
7106static int builtinloc = -1; /* index in path of %builtin, or -1 */
7107
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007108
7109static void
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00007110tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) char *cmd, char **argv, char **envp)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007111{
7112 int repeated = 0;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007113
Denis Vlasenko80d14be2007-04-10 23:03:30 +00007114#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007115 if (applet_no >= 0) {
Denis Vlasenkob7304742008-10-20 08:15:51 +00007116 if (APPLET_IS_NOEXEC(applet_no)) {
7117 while (*envp)
7118 putenv(*envp++);
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007119 run_applet_no_and_exit(applet_no, argv);
Denis Vlasenkob7304742008-10-20 08:15:51 +00007120 }
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007121 /* re-exec ourselves with the new arguments */
7122 execve(bb_busybox_exec_path, argv, envp);
7123 /* If they called chroot or otherwise made the binary no longer
7124 * executable, fall through */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007125 }
7126#endif
7127
7128 repeat:
7129#ifdef SYSV
7130 do {
7131 execve(cmd, argv, envp);
7132 } while (errno == EINTR);
7133#else
7134 execve(cmd, argv, envp);
7135#endif
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007136 if (repeated) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007137 free(argv);
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007138 return;
7139 }
7140 if (errno == ENOEXEC) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007141 char **ap;
7142 char **new;
7143
7144 for (ap = argv; *ap; ap++)
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007145 continue;
7146 ap = new = ckmalloc((ap - argv + 2) * sizeof(ap[0]));
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007147 ap[1] = cmd;
Denis Vlasenkoc44ab012007-04-09 03:11:58 +00007148 ap[0] = cmd = (char *)DEFAULT_SHELL;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007149 ap += 2;
7150 argv++;
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007151 while ((*ap++ = *argv++) != NULL)
Denis Vlasenko597906c2008-02-20 16:38:54 +00007152 continue;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007153 argv = new;
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007154 repeated++;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007155 goto repeat;
7156 }
7157}
7158
7159/*
7160 * Exec a program. Never returns. If you change this routine, you may
7161 * have to change the find_command routine as well.
7162 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00007163static void shellexec(char **, const char *, int) NORETURN;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007164static void
7165shellexec(char **argv, const char *path, int idx)
7166{
7167 char *cmdname;
7168 int e;
7169 char **envp;
7170 int exerrno;
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007171#if ENABLE_FEATURE_SH_STANDALONE
7172 int applet_no = -1;
7173#endif
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007174
Denis Vlasenko34c73c42008-08-16 11:48:02 +00007175 clearredir(/*drop:*/ 1);
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007176 envp = listvars(VEXPORT, VUNSET, 0);
7177 if (strchr(argv[0], '/') != NULL
Denis Vlasenko80d14be2007-04-10 23:03:30 +00007178#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007179 || (applet_no = find_applet_by_name(argv[0])) >= 0
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007180#endif
7181 ) {
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00007182 tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) argv[0], argv, envp);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007183 e = errno;
7184 } else {
7185 e = ENOENT;
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02007186 while ((cmdname = path_advance(&path, argv[0])) != NULL) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007187 if (--idx < 0 && pathopt == NULL) {
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00007188 tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007189 if (errno != ENOENT && errno != ENOTDIR)
7190 e = errno;
7191 }
7192 stunalloc(cmdname);
7193 }
7194 }
7195
7196 /* Map to POSIX errors */
7197 switch (e) {
7198 case EACCES:
7199 exerrno = 126;
7200 break;
7201 case ENOENT:
7202 exerrno = 127;
7203 break;
7204 default:
7205 exerrno = 2;
7206 break;
7207 }
7208 exitstatus = exerrno;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02007209 TRACE(("shellexec failed for %s, errno %d, suppress_int %d\n",
7210 argv[0], e, suppress_int));
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007211 ash_msg_and_raise(EXEXEC, "%s: %s", argv[0], errmsg(e, "not found"));
7212 /* NOTREACHED */
7213}
7214
7215static void
7216printentry(struct tblentry *cmdp)
7217{
7218 int idx;
7219 const char *path;
7220 char *name;
7221
7222 idx = cmdp->param.index;
7223 path = pathval();
7224 do {
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02007225 name = path_advance(&path, cmdp->cmdname);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007226 stunalloc(name);
7227 } while (--idx >= 0);
7228 out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
7229}
7230
7231/*
7232 * Clear out command entries. The argument specifies the first entry in
7233 * PATH which has changed.
7234 */
7235static void
7236clearcmdentry(int firstchange)
7237{
7238 struct tblentry **tblp;
7239 struct tblentry **pp;
7240 struct tblentry *cmdp;
7241
7242 INT_OFF;
7243 for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
7244 pp = tblp;
7245 while ((cmdp = *pp) != NULL) {
7246 if ((cmdp->cmdtype == CMDNORMAL &&
7247 cmdp->param.index >= firstchange)
7248 || (cmdp->cmdtype == CMDBUILTIN &&
7249 builtinloc >= firstchange)
7250 ) {
7251 *pp = cmdp->next;
7252 free(cmdp);
7253 } else {
7254 pp = &cmdp->next;
7255 }
7256 }
7257 }
7258 INT_ON;
7259}
7260
7261/*
7262 * Locate a command in the command hash table. If "add" is nonzero,
7263 * add the command to the table if it is not already present. The
7264 * variable "lastcmdentry" is set to point to the address of the link
7265 * pointing to the entry, so that delete_cmd_entry can delete the
7266 * entry.
7267 *
7268 * Interrupts must be off if called with add != 0.
7269 */
7270static struct tblentry **lastcmdentry;
7271
7272static struct tblentry *
7273cmdlookup(const char *name, int add)
7274{
7275 unsigned int hashval;
7276 const char *p;
7277 struct tblentry *cmdp;
7278 struct tblentry **pp;
7279
7280 p = name;
7281 hashval = (unsigned char)*p << 4;
7282 while (*p)
7283 hashval += (unsigned char)*p++;
7284 hashval &= 0x7FFF;
7285 pp = &cmdtable[hashval % CMDTABLESIZE];
7286 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7287 if (strcmp(cmdp->cmdname, name) == 0)
7288 break;
7289 pp = &cmdp->next;
7290 }
7291 if (add && cmdp == NULL) {
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007292 cmdp = *pp = ckzalloc(sizeof(struct tblentry)
7293 + strlen(name)
7294 /* + 1 - already done because
7295 * tblentry::cmdname is char[1] */);
Denis Vlasenko597906c2008-02-20 16:38:54 +00007296 /*cmdp->next = NULL; - ckzalloc did it */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007297 cmdp->cmdtype = CMDUNKNOWN;
7298 strcpy(cmdp->cmdname, name);
7299 }
7300 lastcmdentry = pp;
7301 return cmdp;
7302}
7303
7304/*
7305 * Delete the command entry returned on the last lookup.
7306 */
7307static void
7308delete_cmd_entry(void)
7309{
7310 struct tblentry *cmdp;
7311
7312 INT_OFF;
7313 cmdp = *lastcmdentry;
7314 *lastcmdentry = cmdp->next;
7315 if (cmdp->cmdtype == CMDFUNCTION)
7316 freefunc(cmdp->param.func);
7317 free(cmdp);
7318 INT_ON;
7319}
7320
7321/*
7322 * Add a new command entry, replacing any existing command entry for
7323 * the same name - except special builtins.
7324 */
7325static void
7326addcmdentry(char *name, struct cmdentry *entry)
7327{
7328 struct tblentry *cmdp;
7329
7330 cmdp = cmdlookup(name, 1);
7331 if (cmdp->cmdtype == CMDFUNCTION) {
7332 freefunc(cmdp->param.func);
7333 }
7334 cmdp->cmdtype = entry->cmdtype;
7335 cmdp->param = entry->u;
7336 cmdp->rehash = 0;
7337}
7338
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007339static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00007340hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007341{
7342 struct tblentry **pp;
7343 struct tblentry *cmdp;
7344 int c;
7345 struct cmdentry entry;
7346 char *name;
7347
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007348 if (nextopt("r") != '\0') {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007349 clearcmdentry(0);
7350 return 0;
7351 }
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007352
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007353 if (*argptr == NULL) {
7354 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7355 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7356 if (cmdp->cmdtype == CMDNORMAL)
7357 printentry(cmdp);
7358 }
7359 }
7360 return 0;
7361 }
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007362
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007363 c = 0;
7364 while ((name = *argptr) != NULL) {
7365 cmdp = cmdlookup(name, 0);
7366 if (cmdp != NULL
7367 && (cmdp->cmdtype == CMDNORMAL
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007368 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
7369 ) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007370 delete_cmd_entry();
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007371 }
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007372 find_command(name, &entry, DO_ERR, pathval());
7373 if (entry.cmdtype == CMDUNKNOWN)
7374 c = 1;
7375 argptr++;
7376 }
7377 return c;
7378}
7379
7380/*
7381 * Called when a cd is done. Marks all commands so the next time they
7382 * are executed they will be rehashed.
7383 */
7384static void
7385hashcd(void)
7386{
7387 struct tblentry **pp;
7388 struct tblentry *cmdp;
7389
7390 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7391 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007392 if (cmdp->cmdtype == CMDNORMAL
7393 || (cmdp->cmdtype == CMDBUILTIN
7394 && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
7395 && builtinloc > 0)
7396 ) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007397 cmdp->rehash = 1;
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007398 }
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007399 }
7400 }
7401}
7402
7403/*
7404 * Fix command hash table when PATH changed.
7405 * Called before PATH is changed. The argument is the new value of PATH;
7406 * pathval() still returns the old value at this point.
7407 * Called with interrupts off.
7408 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007409static void FAST_FUNC
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007410changepath(const char *new)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007411{
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007412 const char *old;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007413 int firstchange;
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007414 int idx;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007415 int idx_bltin;
7416
7417 old = pathval();
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007418 firstchange = 9999; /* assume no change */
7419 idx = 0;
7420 idx_bltin = -1;
7421 for (;;) {
7422 if (*old != *new) {
7423 firstchange = idx;
7424 if ((*old == '\0' && *new == ':')
7425 || (*old == ':' && *new == '\0'))
7426 firstchange++;
7427 old = new; /* ignore subsequent differences */
7428 }
7429 if (*new == '\0')
7430 break;
7431 if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
7432 idx_bltin = idx;
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007433 if (*new == ':')
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007434 idx++;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007435 new++, old++;
7436 }
7437 if (builtinloc < 0 && idx_bltin >= 0)
7438 builtinloc = idx_bltin; /* zap builtins */
7439 if (builtinloc >= 0 && idx_bltin < 0)
7440 firstchange = 0;
7441 clearcmdentry(firstchange);
7442 builtinloc = idx_bltin;
7443}
7444
7445#define TEOF 0
7446#define TNL 1
7447#define TREDIR 2
7448#define TWORD 3
7449#define TSEMI 4
7450#define TBACKGND 5
7451#define TAND 6
7452#define TOR 7
7453#define TPIPE 8
7454#define TLP 9
7455#define TRP 10
7456#define TENDCASE 11
7457#define TENDBQUOTE 12
7458#define TNOT 13
7459#define TCASE 14
7460#define TDO 15
7461#define TDONE 16
7462#define TELIF 17
7463#define TELSE 18
7464#define TESAC 19
7465#define TFI 20
7466#define TFOR 21
7467#define TIF 22
7468#define TIN 23
7469#define TTHEN 24
7470#define TUNTIL 25
7471#define TWHILE 26
7472#define TBEGIN 27
7473#define TEND 28
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007474typedef smallint token_id_t;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007475
7476/* first char is indicating which tokens mark the end of a list */
7477static const char *const tokname_array[] = {
7478 "\1end of file",
7479 "\0newline",
7480 "\0redirection",
7481 "\0word",
7482 "\0;",
7483 "\0&",
7484 "\0&&",
7485 "\0||",
7486 "\0|",
7487 "\0(",
7488 "\1)",
7489 "\1;;",
7490 "\1`",
7491#define KWDOFFSET 13
7492 /* the following are keywords */
7493 "\0!",
7494 "\0case",
7495 "\1do",
7496 "\1done",
7497 "\1elif",
7498 "\1else",
7499 "\1esac",
7500 "\1fi",
7501 "\0for",
7502 "\0if",
7503 "\0in",
7504 "\1then",
7505 "\0until",
7506 "\0while",
7507 "\0{",
7508 "\1}",
7509};
7510
7511static const char *
7512tokname(int tok)
7513{
7514 static char buf[16];
7515
Denis Vlasenko240a1cf2007-04-08 16:07:02 +00007516//try this:
7517//if (tok < TSEMI) return tokname_array[tok] + 1;
7518//sprintf(buf, "\"%s\"", tokname_array[tok] + 1);
7519//return buf;
7520
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007521 if (tok >= TSEMI)
7522 buf[0] = '"';
7523 sprintf(buf + (tok >= TSEMI), "%s%c",
7524 tokname_array[tok] + 1, (tok >= TSEMI ? '"' : 0));
7525 return buf;
7526}
7527
7528/* Wrapper around strcmp for qsort/bsearch/... */
7529static int
7530pstrcmp(const void *a, const void *b)
7531{
Denis Vlasenko240a1cf2007-04-08 16:07:02 +00007532 return strcmp((char*) a, (*(char**) b) + 1);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007533}
7534
7535static const char *const *
7536findkwd(const char *s)
7537{
7538 return bsearch(s, tokname_array + KWDOFFSET,
Denis Vlasenko80b8b392007-06-25 10:55:35 +00007539 ARRAY_SIZE(tokname_array) - KWDOFFSET,
7540 sizeof(tokname_array[0]), pstrcmp);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007541}
7542
7543/*
7544 * Locate and print what a word is...
7545 */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007546static int
7547describe_command(char *command, int describe_command_verbose)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007548{
7549 struct cmdentry entry;
7550 struct tblentry *cmdp;
7551#if ENABLE_ASH_ALIAS
7552 const struct alias *ap;
7553#endif
7554 const char *path = pathval();
7555
7556 if (describe_command_verbose) {
7557 out1str(command);
7558 }
7559
7560 /* First look at the keywords */
7561 if (findkwd(command)) {
7562 out1str(describe_command_verbose ? " is a shell keyword" : command);
7563 goto out;
7564 }
7565
7566#if ENABLE_ASH_ALIAS
7567 /* Then look at the aliases */
7568 ap = lookupalias(command, 0);
7569 if (ap != NULL) {
Denis Vlasenko46846e22007-05-20 13:08:31 +00007570 if (!describe_command_verbose) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007571 out1str("alias ");
7572 printalias(ap);
7573 return 0;
7574 }
Denis Vlasenko46846e22007-05-20 13:08:31 +00007575 out1fmt(" is an alias for %s", ap->val);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007576 goto out;
7577 }
7578#endif
7579 /* Then check if it is a tracked alias */
7580 cmdp = cmdlookup(command, 0);
7581 if (cmdp != NULL) {
7582 entry.cmdtype = cmdp->cmdtype;
7583 entry.u = cmdp->param;
7584 } else {
7585 /* Finally use brute force */
7586 find_command(command, &entry, DO_ABS, path);
7587 }
7588
7589 switch (entry.cmdtype) {
7590 case CMDNORMAL: {
7591 int j = entry.u.index;
7592 char *p;
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00007593 if (j < 0) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007594 p = command;
7595 } else {
7596 do {
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02007597 p = path_advance(&path, command);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007598 stunalloc(p);
7599 } while (--j >= 0);
7600 }
7601 if (describe_command_verbose) {
7602 out1fmt(" is%s %s",
7603 (cmdp ? " a tracked alias for" : nullstr), p
7604 );
7605 } else {
7606 out1str(p);
7607 }
7608 break;
7609 }
7610
7611 case CMDFUNCTION:
7612 if (describe_command_verbose) {
7613 out1str(" is a shell function");
7614 } else {
7615 out1str(command);
7616 }
7617 break;
7618
7619 case CMDBUILTIN:
7620 if (describe_command_verbose) {
7621 out1fmt(" is a %sshell builtin",
7622 IS_BUILTIN_SPECIAL(entry.u.cmd) ?
7623 "special " : nullstr
7624 );
7625 } else {
7626 out1str(command);
7627 }
7628 break;
7629
7630 default:
7631 if (describe_command_verbose) {
7632 out1str(": not found\n");
7633 }
7634 return 127;
7635 }
7636 out:
7637 outstr("\n", stdout);
7638 return 0;
7639}
7640
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007641static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00007642typecmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007643{
Denis Vlasenko46846e22007-05-20 13:08:31 +00007644 int i = 1;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007645 int err = 0;
Denis Vlasenko46846e22007-05-20 13:08:31 +00007646 int verbose = 1;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007647
Denis Vlasenko46846e22007-05-20 13:08:31 +00007648 /* type -p ... ? (we don't bother checking for 'p') */
Denis Vlasenko1fc62382007-06-25 22:55:34 +00007649 if (argv[1] && argv[1][0] == '-') {
Denis Vlasenko46846e22007-05-20 13:08:31 +00007650 i++;
7651 verbose = 0;
7652 }
Denis Vlasenko68404f12008-03-17 09:00:54 +00007653 while (argv[i]) {
Denis Vlasenko46846e22007-05-20 13:08:31 +00007654 err |= describe_command(argv[i++], verbose);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007655 }
7656 return err;
7657}
7658
7659#if ENABLE_ASH_CMDCMD
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007660static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00007661commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007662{
7663 int c;
7664 enum {
7665 VERIFY_BRIEF = 1,
7666 VERIFY_VERBOSE = 2,
7667 } verify = 0;
7668
7669 while ((c = nextopt("pvV")) != '\0')
7670 if (c == 'V')
7671 verify |= VERIFY_VERBOSE;
7672 else if (c == 'v')
7673 verify |= VERIFY_BRIEF;
7674#if DEBUG
7675 else if (c != 'p')
7676 abort();
7677#endif
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00007678 /* Mimic bash: just "command -v" doesn't complain, it's a nop */
7679 if (verify && (*argptr != NULL)) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007680 return describe_command(*argptr, verify - VERIFY_BRIEF);
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00007681 }
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007682
7683 return 0;
7684}
7685#endif
7686
7687
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007688/* ============ eval.c */
Eric Andersencb57d552001-06-28 07:25:16 +00007689
Denis Vlasenko340299a2008-11-21 10:36:36 +00007690static int funcblocksize; /* size of structures in function */
7691static int funcstringsize; /* size of strings in node */
7692static void *funcblock; /* block to allocate function from */
7693static char *funcstring; /* block to allocate strings from */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007694
Eric Andersencb57d552001-06-28 07:25:16 +00007695/* flags in argument to evaltree */
Denis Vlasenko340299a2008-11-21 10:36:36 +00007696#define EV_EXIT 01 /* exit after evaluating tree */
7697#define EV_TESTED 02 /* exit status is checked; ignore -e flag */
Eric Andersenc470f442003-07-28 09:56:35 +00007698#define EV_BACKCMD 04 /* command executing within back quotes */
Eric Andersencb57d552001-06-28 07:25:16 +00007699
Denis Vlasenko340299a2008-11-21 10:36:36 +00007700static const short nodesize[N_NUMBER] = {
7701 [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
7702 [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
7703 [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
7704 [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
7705 [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
7706 [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
7707 [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
7708 [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
7709 [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
7710 [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
7711 [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
7712 [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
7713 [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
7714 [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
7715 [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
7716 [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
7717 [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
Denis Vlasenkocc5feab2008-11-22 01:32:40 +00007718#if ENABLE_ASH_BASH_COMPAT
Denis Vlasenko340299a2008-11-21 10:36:36 +00007719 [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
Denis Vlasenkocc5feab2008-11-22 01:32:40 +00007720#endif
Denis Vlasenko340299a2008-11-21 10:36:36 +00007721 [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
7722 [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
7723 [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
7724 [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
7725 [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
7726 [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
7727 [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
7728 [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
7729 [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007730};
7731
7732static void calcsize(union node *n);
7733
7734static void
7735sizenodelist(struct nodelist *lp)
7736{
7737 while (lp) {
7738 funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
7739 calcsize(lp->n);
7740 lp = lp->next;
7741 }
7742}
7743
7744static void
7745calcsize(union node *n)
7746{
7747 if (n == NULL)
7748 return;
7749 funcblocksize += nodesize[n->type];
7750 switch (n->type) {
7751 case NCMD:
7752 calcsize(n->ncmd.redirect);
7753 calcsize(n->ncmd.args);
7754 calcsize(n->ncmd.assign);
7755 break;
7756 case NPIPE:
7757 sizenodelist(n->npipe.cmdlist);
7758 break;
7759 case NREDIR:
7760 case NBACKGND:
7761 case NSUBSHELL:
7762 calcsize(n->nredir.redirect);
7763 calcsize(n->nredir.n);
7764 break;
7765 case NAND:
7766 case NOR:
7767 case NSEMI:
7768 case NWHILE:
7769 case NUNTIL:
7770 calcsize(n->nbinary.ch2);
7771 calcsize(n->nbinary.ch1);
7772 break;
7773 case NIF:
7774 calcsize(n->nif.elsepart);
7775 calcsize(n->nif.ifpart);
7776 calcsize(n->nif.test);
7777 break;
7778 case NFOR:
7779 funcstringsize += strlen(n->nfor.var) + 1;
7780 calcsize(n->nfor.body);
7781 calcsize(n->nfor.args);
7782 break;
7783 case NCASE:
7784 calcsize(n->ncase.cases);
7785 calcsize(n->ncase.expr);
7786 break;
7787 case NCLIST:
7788 calcsize(n->nclist.body);
7789 calcsize(n->nclist.pattern);
7790 calcsize(n->nclist.next);
7791 break;
7792 case NDEFUN:
7793 case NARG:
7794 sizenodelist(n->narg.backquote);
7795 funcstringsize += strlen(n->narg.text) + 1;
7796 calcsize(n->narg.next);
7797 break;
7798 case NTO:
Denis Vlasenko559691a2008-10-05 18:39:31 +00007799#if ENABLE_ASH_BASH_COMPAT
7800 case NTO2:
7801#endif
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007802 case NCLOBBER:
7803 case NFROM:
7804 case NFROMTO:
7805 case NAPPEND:
7806 calcsize(n->nfile.fname);
7807 calcsize(n->nfile.next);
7808 break;
7809 case NTOFD:
7810 case NFROMFD:
7811 calcsize(n->ndup.vname);
7812 calcsize(n->ndup.next);
7813 break;
7814 case NHERE:
7815 case NXHERE:
7816 calcsize(n->nhere.doc);
7817 calcsize(n->nhere.next);
7818 break;
7819 case NNOT:
7820 calcsize(n->nnot.com);
7821 break;
7822 };
7823}
7824
7825static char *
7826nodeckstrdup(char *s)
7827{
7828 char *rtn = funcstring;
7829
7830 strcpy(funcstring, s);
7831 funcstring += strlen(s) + 1;
7832 return rtn;
7833}
7834
7835static union node *copynode(union node *);
7836
7837static struct nodelist *
7838copynodelist(struct nodelist *lp)
7839{
7840 struct nodelist *start;
7841 struct nodelist **lpp;
7842
7843 lpp = &start;
7844 while (lp) {
7845 *lpp = funcblock;
7846 funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
7847 (*lpp)->n = copynode(lp->n);
7848 lp = lp->next;
7849 lpp = &(*lpp)->next;
7850 }
7851 *lpp = NULL;
7852 return start;
7853}
7854
7855static union node *
7856copynode(union node *n)
7857{
7858 union node *new;
7859
7860 if (n == NULL)
7861 return NULL;
7862 new = funcblock;
7863 funcblock = (char *) funcblock + nodesize[n->type];
7864
7865 switch (n->type) {
7866 case NCMD:
7867 new->ncmd.redirect = copynode(n->ncmd.redirect);
7868 new->ncmd.args = copynode(n->ncmd.args);
7869 new->ncmd.assign = copynode(n->ncmd.assign);
7870 break;
7871 case NPIPE:
7872 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00007873 new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007874 break;
7875 case NREDIR:
7876 case NBACKGND:
7877 case NSUBSHELL:
7878 new->nredir.redirect = copynode(n->nredir.redirect);
7879 new->nredir.n = copynode(n->nredir.n);
7880 break;
7881 case NAND:
7882 case NOR:
7883 case NSEMI:
7884 case NWHILE:
7885 case NUNTIL:
7886 new->nbinary.ch2 = copynode(n->nbinary.ch2);
7887 new->nbinary.ch1 = copynode(n->nbinary.ch1);
7888 break;
7889 case NIF:
7890 new->nif.elsepart = copynode(n->nif.elsepart);
7891 new->nif.ifpart = copynode(n->nif.ifpart);
7892 new->nif.test = copynode(n->nif.test);
7893 break;
7894 case NFOR:
7895 new->nfor.var = nodeckstrdup(n->nfor.var);
7896 new->nfor.body = copynode(n->nfor.body);
7897 new->nfor.args = copynode(n->nfor.args);
7898 break;
7899 case NCASE:
7900 new->ncase.cases = copynode(n->ncase.cases);
7901 new->ncase.expr = copynode(n->ncase.expr);
7902 break;
7903 case NCLIST:
7904 new->nclist.body = copynode(n->nclist.body);
7905 new->nclist.pattern = copynode(n->nclist.pattern);
7906 new->nclist.next = copynode(n->nclist.next);
7907 break;
7908 case NDEFUN:
7909 case NARG:
7910 new->narg.backquote = copynodelist(n->narg.backquote);
7911 new->narg.text = nodeckstrdup(n->narg.text);
7912 new->narg.next = copynode(n->narg.next);
7913 break;
7914 case NTO:
Denis Vlasenko559691a2008-10-05 18:39:31 +00007915#if ENABLE_ASH_BASH_COMPAT
7916 case NTO2:
7917#endif
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007918 case NCLOBBER:
7919 case NFROM:
7920 case NFROMTO:
7921 case NAPPEND:
7922 new->nfile.fname = copynode(n->nfile.fname);
7923 new->nfile.fd = n->nfile.fd;
7924 new->nfile.next = copynode(n->nfile.next);
7925 break;
7926 case NTOFD:
7927 case NFROMFD:
7928 new->ndup.vname = copynode(n->ndup.vname);
7929 new->ndup.dupfd = n->ndup.dupfd;
7930 new->ndup.fd = n->ndup.fd;
7931 new->ndup.next = copynode(n->ndup.next);
7932 break;
7933 case NHERE:
7934 case NXHERE:
7935 new->nhere.doc = copynode(n->nhere.doc);
7936 new->nhere.fd = n->nhere.fd;
7937 new->nhere.next = copynode(n->nhere.next);
7938 break;
7939 case NNOT:
7940 new->nnot.com = copynode(n->nnot.com);
7941 break;
7942 };
7943 new->type = n->type;
7944 return new;
7945}
7946
7947/*
7948 * Make a copy of a parse tree.
7949 */
7950static struct funcnode *
7951copyfunc(union node *n)
7952{
7953 struct funcnode *f;
7954 size_t blocksize;
7955
7956 funcblocksize = offsetof(struct funcnode, n);
7957 funcstringsize = 0;
7958 calcsize(n);
7959 blocksize = funcblocksize;
7960 f = ckmalloc(blocksize + funcstringsize);
7961 funcblock = (char *) f + offsetof(struct funcnode, n);
7962 funcstring = (char *) f + blocksize;
7963 copynode(n);
7964 f->count = 0;
7965 return f;
7966}
7967
7968/*
7969 * Define a shell function.
7970 */
7971static void
7972defun(char *name, union node *func)
7973{
7974 struct cmdentry entry;
7975
7976 INT_OFF;
7977 entry.cmdtype = CMDFUNCTION;
7978 entry.u.func = copyfunc(func);
7979 addcmdentry(name, &entry);
7980 INT_ON;
7981}
7982
Denis Vlasenko4b875702009-03-19 13:30:04 +00007983/* Reasons for skipping commands (see comment on breakcmd routine) */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007984#define SKIPBREAK (1 << 0)
7985#define SKIPCONT (1 << 1)
7986#define SKIPFUNC (1 << 2)
7987#define SKIPFILE (1 << 3)
7988#define SKIPEVAL (1 << 4)
Denis Vlasenko4b875702009-03-19 13:30:04 +00007989static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007990static int skipcount; /* number of levels to skip */
7991static int funcnest; /* depth of function calls */
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +00007992static int loopnest; /* current loop nesting level */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007993
Denis Vlasenko4b875702009-03-19 13:30:04 +00007994/* Forward decl way out to parsing code - dotrap needs it */
Denis Vlasenkofc06f292007-02-23 21:09:35 +00007995static int evalstring(char *s, int mask);
7996
Denis Vlasenko4b875702009-03-19 13:30:04 +00007997/* Called to execute a trap.
7998 * Single callsite - at the end of evaltree().
7999 * If we return non-zero, exaltree raises EXEXIT exception.
8000 *
8001 * Perhaps we should avoid entering new trap handlers
8002 * while we are executing a trap handler. [is it a TODO?]
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008003 */
8004static int
8005dotrap(void)
8006{
Denis Vlasenko4b875702009-03-19 13:30:04 +00008007 uint8_t *g;
8008 int sig;
8009 uint8_t savestatus;
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008010
8011 savestatus = exitstatus;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02008012 pending_sig = 0;
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008013 xbarrier();
8014
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008015 TRACE(("dotrap entered\n"));
Denis Vlasenko4b875702009-03-19 13:30:04 +00008016 for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
8017 int want_exexit;
8018 char *t;
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008019
Denis Vlasenko4b875702009-03-19 13:30:04 +00008020 if (*g == 0)
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008021 continue;
Denis Vlasenko4b875702009-03-19 13:30:04 +00008022 t = trap[sig];
8023 /* non-trapped SIGINT is handled separately by raise_interrupt,
8024 * don't upset it by resetting gotsig[SIGINT-1] */
8025 if (sig == SIGINT && !t)
8026 continue;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008027
8028 TRACE(("sig %d is active, will run handler '%s'\n", sig, t));
Denis Vlasenko4b875702009-03-19 13:30:04 +00008029 *g = 0;
8030 if (!t)
8031 continue;
8032 want_exexit = evalstring(t, SKIPEVAL);
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008033 exitstatus = savestatus;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008034 if (want_exexit) {
Denis Vlasenkob21f3792009-03-19 23:09:58 +00008035 TRACE(("dotrap returns %d\n", want_exexit));
Denis Vlasenko4b875702009-03-19 13:30:04 +00008036 return want_exexit;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008037 }
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008038 }
8039
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008040 TRACE(("dotrap returns 0\n"));
Denis Vlasenko991a1da2008-02-10 19:02:53 +00008041 return 0;
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008042}
8043
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00008044/* forward declarations - evaluation is fairly recursive business... */
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008045static void evalloop(union node *, int);
8046static void evalfor(union node *, int);
8047static void evalcase(union node *, int);
8048static void evalsubshell(union node *, int);
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00008049static void expredir(union node *);
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008050static void evalpipe(union node *, int);
8051static void evalcommand(union node *, int);
Eric Andersenc470f442003-07-28 09:56:35 +00008052static int evalbltin(const struct builtincmd *, int, char **);
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008053static void prehash(union node *);
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00008054
Eric Andersen62483552001-07-10 06:09:16 +00008055/*
Eric Andersenc470f442003-07-28 09:56:35 +00008056 * Evaluate a parse tree. The value is left in the global variable
8057 * exitstatus.
Eric Andersen62483552001-07-10 06:09:16 +00008058 */
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008059static void
Eric Andersenc470f442003-07-28 09:56:35 +00008060evaltree(union node *n, int flags)
Eric Andersen62483552001-07-10 06:09:16 +00008061{
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008062 struct jmploc *volatile savehandler = exception_handler;
8063 struct jmploc jmploc;
Eric Andersenc470f442003-07-28 09:56:35 +00008064 int checkexit = 0;
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008065 void (*evalfn)(union node *, int);
Eric Andersenc470f442003-07-28 09:56:35 +00008066 int status;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008067 int int_level;
8068
8069 SAVE_INT(int_level);
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008070
Eric Andersenc470f442003-07-28 09:56:35 +00008071 if (n == NULL) {
8072 TRACE(("evaltree(NULL) called\n"));
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008073 goto out1;
Eric Andersen62483552001-07-10 06:09:16 +00008074 }
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008075 TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008076
8077 exception_handler = &jmploc;
8078 {
8079 int err = setjmp(jmploc.loc);
8080 if (err) {
8081 /* if it was a signal, check for trap handlers */
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008082 if (exception_type == EXSIG) {
Denis Vlasenkob21f3792009-03-19 23:09:58 +00008083 TRACE(("exception %d (EXSIG) in evaltree, err=%d\n",
8084 exception_type, err));
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008085 goto out;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008086 }
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008087 /* continue on the way out */
Denis Vlasenkob21f3792009-03-19 23:09:58 +00008088 TRACE(("exception %d in evaltree, propagating err=%d\n",
8089 exception_type, err));
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008090 exception_handler = savehandler;
8091 longjmp(exception_handler->loc, err);
8092 }
8093 }
8094
Eric Andersenc470f442003-07-28 09:56:35 +00008095 switch (n->type) {
8096 default:
Denis Vlasenkoa7189f02006-11-17 20:29:00 +00008097#if DEBUG
Eric Andersenc470f442003-07-28 09:56:35 +00008098 out1fmt("Node type = %d\n", n->type);
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00008099 fflush(stdout);
Eric Andersenc470f442003-07-28 09:56:35 +00008100 break;
8101#endif
8102 case NNOT:
8103 evaltree(n->nnot.com, EV_TESTED);
8104 status = !exitstatus;
8105 goto setstatus;
8106 case NREDIR:
8107 expredir(n->nredir.redirect);
8108 status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
8109 if (!status) {
8110 evaltree(n->nredir.n, flags & EV_TESTED);
8111 status = exitstatus;
8112 }
Denis Vlasenko34c73c42008-08-16 11:48:02 +00008113 popredir(/*drop:*/ 0, /*restore:*/ 0 /* not sure */);
Eric Andersenc470f442003-07-28 09:56:35 +00008114 goto setstatus;
8115 case NCMD:
8116 evalfn = evalcommand;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008117 checkexit:
Eric Andersenc470f442003-07-28 09:56:35 +00008118 if (eflag && !(flags & EV_TESTED))
8119 checkexit = ~0;
8120 goto calleval;
8121 case NFOR:
8122 evalfn = evalfor;
8123 goto calleval;
8124 case NWHILE:
8125 case NUNTIL:
8126 evalfn = evalloop;
8127 goto calleval;
8128 case NSUBSHELL:
8129 case NBACKGND:
8130 evalfn = evalsubshell;
8131 goto calleval;
8132 case NPIPE:
8133 evalfn = evalpipe;
8134 goto checkexit;
8135 case NCASE:
8136 evalfn = evalcase;
8137 goto calleval;
8138 case NAND:
8139 case NOR:
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008140 case NSEMI: {
8141
Eric Andersenc470f442003-07-28 09:56:35 +00008142#if NAND + 1 != NOR
8143#error NAND + 1 != NOR
8144#endif
8145#if NOR + 1 != NSEMI
8146#error NOR + 1 != NSEMI
8147#endif
Denis Vlasenko87d5fd92008-07-26 13:48:35 +00008148 unsigned is_or = n->type - NAND;
Eric Andersenc470f442003-07-28 09:56:35 +00008149 evaltree(
8150 n->nbinary.ch1,
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008151 (flags | ((is_or >> 1) - 1)) & EV_TESTED
Eric Andersenc470f442003-07-28 09:56:35 +00008152 );
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008153 if (!exitstatus == is_or)
Eric Andersenc470f442003-07-28 09:56:35 +00008154 break;
8155 if (!evalskip) {
8156 n = n->nbinary.ch2;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008157 evaln:
Eric Andersenc470f442003-07-28 09:56:35 +00008158 evalfn = evaltree;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008159 calleval:
Eric Andersenc470f442003-07-28 09:56:35 +00008160 evalfn(n, flags);
8161 break;
8162 }
8163 break;
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008164 }
Eric Andersenc470f442003-07-28 09:56:35 +00008165 case NIF:
8166 evaltree(n->nif.test, EV_TESTED);
8167 if (evalskip)
8168 break;
8169 if (exitstatus == 0) {
8170 n = n->nif.ifpart;
8171 goto evaln;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008172 }
8173 if (n->nif.elsepart) {
Eric Andersenc470f442003-07-28 09:56:35 +00008174 n = n->nif.elsepart;
8175 goto evaln;
8176 }
8177 goto success;
8178 case NDEFUN:
8179 defun(n->narg.text, n->narg.next);
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008180 success:
Eric Andersenc470f442003-07-28 09:56:35 +00008181 status = 0;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008182 setstatus:
Eric Andersenc470f442003-07-28 09:56:35 +00008183 exitstatus = status;
8184 break;
8185 }
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008186
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008187 out:
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008188 exception_handler = savehandler;
8189 out1:
8190 if (checkexit & exitstatus)
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00008191 evalskip |= SKIPEVAL;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02008192 else if (pending_sig && dotrap())
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00008193 goto exexit;
8194
8195 if (flags & EV_EXIT) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008196 exexit:
Denis Vlasenkob012b102007-02-19 22:43:01 +00008197 raise_exception(EXEXIT);
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00008198 }
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008199
8200 RESTORE_INT(int_level);
8201 TRACE(("leaving evaltree (no interrupts)\n"));
Eric Andersen62483552001-07-10 06:09:16 +00008202}
8203
Eric Andersenc470f442003-07-28 09:56:35 +00008204#if !defined(__alpha__) || (defined(__GNUC__) && __GNUC__ >= 3)
8205static
8206#endif
8207void evaltreenr(union node *, int) __attribute__ ((alias("evaltree"),__noreturn__));
8208
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008209static void
Eric Andersenc470f442003-07-28 09:56:35 +00008210evalloop(union node *n, int flags)
Eric Andersencb57d552001-06-28 07:25:16 +00008211{
8212 int status;
8213
8214 loopnest++;
8215 status = 0;
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008216 flags &= EV_TESTED;
Eric Andersencb57d552001-06-28 07:25:16 +00008217 for (;;) {
Eric Andersenc470f442003-07-28 09:56:35 +00008218 int i;
8219
Eric Andersencb57d552001-06-28 07:25:16 +00008220 evaltree(n->nbinary.ch1, EV_TESTED);
8221 if (evalskip) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008222 skipping:
8223 if (evalskip == SKIPCONT && --skipcount <= 0) {
Eric Andersencb57d552001-06-28 07:25:16 +00008224 evalskip = 0;
8225 continue;
8226 }
8227 if (evalskip == SKIPBREAK && --skipcount <= 0)
8228 evalskip = 0;
8229 break;
8230 }
Eric Andersenc470f442003-07-28 09:56:35 +00008231 i = exitstatus;
8232 if (n->type != NWHILE)
8233 i = !i;
8234 if (i != 0)
8235 break;
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008236 evaltree(n->nbinary.ch2, flags);
Eric Andersencb57d552001-06-28 07:25:16 +00008237 status = exitstatus;
8238 if (evalskip)
8239 goto skipping;
8240 }
8241 loopnest--;
8242 exitstatus = status;
8243}
8244
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008245static void
Eric Andersenc470f442003-07-28 09:56:35 +00008246evalfor(union node *n, int flags)
Eric Andersencb57d552001-06-28 07:25:16 +00008247{
8248 struct arglist arglist;
8249 union node *argp;
8250 struct strlist *sp;
8251 struct stackmark smark;
8252
8253 setstackmark(&smark);
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00008254 arglist.list = NULL;
Eric Andersencb57d552001-06-28 07:25:16 +00008255 arglist.lastp = &arglist.list;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008256 for (argp = n->nfor.args; argp; argp = argp->narg.next) {
Eric Andersencb57d552001-06-28 07:25:16 +00008257 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE | EXP_RECORD);
Eric Andersenc470f442003-07-28 09:56:35 +00008258 /* XXX */
Eric Andersencb57d552001-06-28 07:25:16 +00008259 if (evalskip)
8260 goto out;
8261 }
8262 *arglist.lastp = NULL;
8263
8264 exitstatus = 0;
8265 loopnest++;
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008266 flags &= EV_TESTED;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008267 for (sp = arglist.list; sp; sp = sp->next) {
Eric Andersencb57d552001-06-28 07:25:16 +00008268 setvar(n->nfor.var, sp->text, 0);
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008269 evaltree(n->nfor.body, flags);
Eric Andersencb57d552001-06-28 07:25:16 +00008270 if (evalskip) {
8271 if (evalskip == SKIPCONT && --skipcount <= 0) {
8272 evalskip = 0;
8273 continue;
8274 }
8275 if (evalskip == SKIPBREAK && --skipcount <= 0)
8276 evalskip = 0;
8277 break;
8278 }
8279 }
8280 loopnest--;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008281 out:
Eric Andersencb57d552001-06-28 07:25:16 +00008282 popstackmark(&smark);
8283}
8284
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008285static void
Eric Andersenc470f442003-07-28 09:56:35 +00008286evalcase(union node *n, int flags)
Eric Andersencb57d552001-06-28 07:25:16 +00008287{
8288 union node *cp;
8289 union node *patp;
8290 struct arglist arglist;
8291 struct stackmark smark;
8292
8293 setstackmark(&smark);
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00008294 arglist.list = NULL;
Eric Andersencb57d552001-06-28 07:25:16 +00008295 arglist.lastp = &arglist.list;
Eric Andersencb57d552001-06-28 07:25:16 +00008296 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
Eric Andersenc470f442003-07-28 09:56:35 +00008297 exitstatus = 0;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008298 for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
8299 for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
Eric Andersencb57d552001-06-28 07:25:16 +00008300 if (casematch(patp, arglist.list->text)) {
8301 if (evalskip == 0) {
8302 evaltree(cp->nclist.body, flags);
8303 }
8304 goto out;
8305 }
8306 }
8307 }
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008308 out:
Eric Andersencb57d552001-06-28 07:25:16 +00008309 popstackmark(&smark);
8310}
8311
Eric Andersenc470f442003-07-28 09:56:35 +00008312/*
8313 * Kick off a subshell to evaluate a tree.
8314 */
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008315static void
Eric Andersenc470f442003-07-28 09:56:35 +00008316evalsubshell(union node *n, int flags)
8317{
8318 struct job *jp;
8319 int backgnd = (n->type == NBACKGND);
8320 int status;
8321
8322 expredir(n->nredir.redirect);
8323 if (!backgnd && flags & EV_EXIT && !trap[0])
8324 goto nofork;
Denis Vlasenkob012b102007-02-19 22:43:01 +00008325 INT_OFF;
Denis Vlasenko68404f12008-03-17 09:00:54 +00008326 jp = makejob(/*n,*/ 1);
Eric Andersenc470f442003-07-28 09:56:35 +00008327 if (forkshell(jp, n, backgnd) == 0) {
Denis Vlasenkob012b102007-02-19 22:43:01 +00008328 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00008329 flags |= EV_EXIT;
8330 if (backgnd)
8331 flags &=~ EV_TESTED;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00008332 nofork:
Eric Andersenc470f442003-07-28 09:56:35 +00008333 redirect(n->nredir.redirect, 0);
8334 evaltreenr(n->nredir.n, flags);
8335 /* never returns */
8336 }
8337 status = 0;
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00008338 if (!backgnd)
Eric Andersenc470f442003-07-28 09:56:35 +00008339 status = waitforjob(jp);
8340 exitstatus = status;
Denis Vlasenkob012b102007-02-19 22:43:01 +00008341 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00008342}
8343
Eric Andersenc470f442003-07-28 09:56:35 +00008344/*
8345 * Compute the names of the files in a redirection list.
8346 */
Denis Vlasenko99eb8502007-02-23 21:09:49 +00008347static void fixredir(union node *, const char *, int);
Eric Andersenc470f442003-07-28 09:56:35 +00008348static void
8349expredir(union node *n)
8350{
8351 union node *redir;
8352
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008353 for (redir = n; redir; redir = redir->nfile.next) {
Eric Andersenc470f442003-07-28 09:56:35 +00008354 struct arglist fn;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008355
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00008356 fn.list = NULL;
Eric Andersenc470f442003-07-28 09:56:35 +00008357 fn.lastp = &fn.list;
8358 switch (redir->type) {
8359 case NFROMTO:
8360 case NFROM:
8361 case NTO:
Denis Vlasenko559691a2008-10-05 18:39:31 +00008362#if ENABLE_ASH_BASH_COMPAT
8363 case NTO2:
8364#endif
Eric Andersenc470f442003-07-28 09:56:35 +00008365 case NCLOBBER:
8366 case NAPPEND:
8367 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
Denis Vlasenko559691a2008-10-05 18:39:31 +00008368#if ENABLE_ASH_BASH_COMPAT
8369 store_expfname:
8370#endif
Eric Andersenc470f442003-07-28 09:56:35 +00008371 redir->nfile.expfname = fn.list->text;
8372 break;
8373 case NFROMFD:
Denis Vlasenko559691a2008-10-05 18:39:31 +00008374 case NTOFD: /* >& */
Eric Andersenc470f442003-07-28 09:56:35 +00008375 if (redir->ndup.vname) {
8376 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008377 if (fn.list == NULL)
Denis Vlasenkob012b102007-02-19 22:43:01 +00008378 ash_msg_and_raise_error("redir error");
Denis Vlasenko559691a2008-10-05 18:39:31 +00008379#if ENABLE_ASH_BASH_COMPAT
8380//FIXME: we used expandarg with different args!
8381 if (!isdigit_str9(fn.list->text)) {
8382 /* >&file, not >&fd */
8383 if (redir->nfile.fd != 1) /* 123>&file - BAD */
8384 ash_msg_and_raise_error("redir error");
8385 redir->type = NTO2;
8386 goto store_expfname;
8387 }
8388#endif
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008389 fixredir(redir, fn.list->text, 1);
Eric Andersenc470f442003-07-28 09:56:35 +00008390 }
8391 break;
8392 }
8393 }
8394}
8395
Eric Andersencb57d552001-06-28 07:25:16 +00008396/*
Eric Andersencb57d552001-06-28 07:25:16 +00008397 * Evaluate a pipeline. All the processes in the pipeline are children
8398 * of the process creating the pipeline. (This differs from some versions
8399 * of the shell, which make the last process in a pipeline the parent
8400 * of all the rest.)
8401 */
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008402static void
Eric Andersenc470f442003-07-28 09:56:35 +00008403evalpipe(union node *n, int flags)
Eric Andersencb57d552001-06-28 07:25:16 +00008404{
8405 struct job *jp;
8406 struct nodelist *lp;
8407 int pipelen;
8408 int prevfd;
8409 int pip[2];
8410
Eric Andersenc470f442003-07-28 09:56:35 +00008411 TRACE(("evalpipe(0x%lx) called\n", (long)n));
Eric Andersencb57d552001-06-28 07:25:16 +00008412 pipelen = 0;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008413 for (lp = n->npipe.cmdlist; lp; lp = lp->next)
Eric Andersencb57d552001-06-28 07:25:16 +00008414 pipelen++;
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008415 flags |= EV_EXIT;
Denis Vlasenkob012b102007-02-19 22:43:01 +00008416 INT_OFF;
Denis Vlasenko68404f12008-03-17 09:00:54 +00008417 jp = makejob(/*n,*/ pipelen);
Eric Andersencb57d552001-06-28 07:25:16 +00008418 prevfd = -1;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008419 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008420 prehash(lp->n);
Eric Andersencb57d552001-06-28 07:25:16 +00008421 pip[1] = -1;
8422 if (lp->next) {
8423 if (pipe(pip) < 0) {
8424 close(prevfd);
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00008425 ash_msg_and_raise_error("pipe call failed");
Eric Andersencb57d552001-06-28 07:25:16 +00008426 }
8427 }
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00008428 if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
Denis Vlasenkob012b102007-02-19 22:43:01 +00008429 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00008430 if (pip[1] >= 0) {
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008431 close(pip[0]);
Eric Andersencb57d552001-06-28 07:25:16 +00008432 }
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008433 if (prevfd > 0) {
8434 dup2(prevfd, 0);
8435 close(prevfd);
8436 }
8437 if (pip[1] > 1) {
8438 dup2(pip[1], 1);
8439 close(pip[1]);
8440 }
Eric Andersenc470f442003-07-28 09:56:35 +00008441 evaltreenr(lp->n, flags);
8442 /* never returns */
Eric Andersencb57d552001-06-28 07:25:16 +00008443 }
8444 if (prevfd >= 0)
8445 close(prevfd);
8446 prevfd = pip[0];
Denis Vlasenkob9e70dd2009-03-20 01:24:08 +00008447 /* Don't want to trigger debugging */
8448 if (pip[1] != -1)
8449 close(pip[1]);
Eric Andersencb57d552001-06-28 07:25:16 +00008450 }
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00008451 if (n->npipe.pipe_backgnd == 0) {
Eric Andersencb57d552001-06-28 07:25:16 +00008452 exitstatus = waitforjob(jp);
8453 TRACE(("evalpipe: job done exit status %d\n", exitstatus));
Eric Andersencb57d552001-06-28 07:25:16 +00008454 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00008455 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00008456}
8457
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008458/*
8459 * Controls whether the shell is interactive or not.
8460 */
8461static void
8462setinteractive(int on)
8463{
Denis Vlasenkob07a4962008-06-22 13:16:23 +00008464 static smallint is_interactive;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008465
8466 if (++on == is_interactive)
8467 return;
8468 is_interactive = on;
8469 setsignal(SIGINT);
8470 setsignal(SIGQUIT);
8471 setsignal(SIGTERM);
8472#if !ENABLE_FEATURE_SH_EXTRA_QUIET
8473 if (is_interactive > 1) {
8474 /* Looks like they want an interactive shell */
Denis Vlasenkoca525b42007-06-13 12:27:17 +00008475 static smallint did_banner;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008476
Denis Vlasenkoca525b42007-06-13 12:27:17 +00008477 if (!did_banner) {
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008478 out1fmt(
8479 "\n\n"
Denis Vlasenkoca525b42007-06-13 12:27:17 +00008480 "%s built-in shell (ash)\n"
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008481 "Enter 'help' for a list of built-in commands."
8482 "\n\n",
Denis Vlasenkoca525b42007-06-13 12:27:17 +00008483 bb_banner);
8484 did_banner = 1;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008485 }
8486 }
8487#endif
8488}
8489
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008490static void
8491optschanged(void)
8492{
8493#if DEBUG
8494 opentrace();
8495#endif
8496 setinteractive(iflag);
8497 setjobctl(mflag);
Denis Vlasenkob07a4962008-06-22 13:16:23 +00008498#if ENABLE_FEATURE_EDITING_VI
8499 if (viflag)
8500 line_input_state->flags |= VI_MODE;
8501 else
8502 line_input_state->flags &= ~VI_MODE;
8503#else
8504 viflag = 0; /* forcibly keep the option off */
8505#endif
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008506}
8507
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008508static struct localvar *localvars;
8509
8510/*
8511 * Called after a function returns.
8512 * Interrupts must be off.
8513 */
8514static void
8515poplocalvars(void)
8516{
8517 struct localvar *lvp;
8518 struct var *vp;
8519
8520 while ((lvp = localvars) != NULL) {
8521 localvars = lvp->next;
8522 vp = lvp->vp;
Denys Vlasenko883cea42009-07-11 15:31:59 +02008523 TRACE(("poplocalvar %s\n", vp ? vp->text : "-"));
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008524 if (vp == NULL) { /* $- saved */
8525 memcpy(optlist, lvp->text, sizeof(optlist));
8526 free((char*)lvp->text);
8527 optschanged();
8528 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
8529 unsetvar(vp->text);
8530 } else {
8531 if (vp->func)
8532 (*vp->func)(strchrnul(lvp->text, '=') + 1);
8533 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
8534 free((char*)vp->text);
8535 vp->flags = lvp->flags;
8536 vp->text = lvp->text;
8537 }
8538 free(lvp);
8539 }
8540}
8541
8542static int
8543evalfun(struct funcnode *func, int argc, char **argv, int flags)
8544{
8545 volatile struct shparam saveparam;
8546 struct localvar *volatile savelocalvars;
8547 struct jmploc *volatile savehandler;
8548 struct jmploc jmploc;
8549 int e;
8550
8551 saveparam = shellparam;
8552 savelocalvars = localvars;
8553 e = setjmp(jmploc.loc);
8554 if (e) {
8555 goto funcdone;
8556 }
8557 INT_OFF;
8558 savehandler = exception_handler;
8559 exception_handler = &jmploc;
8560 localvars = NULL;
Denis Vlasenko01631112007-12-16 17:20:38 +00008561 shellparam.malloced = 0;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008562 func->count++;
8563 funcnest++;
8564 INT_ON;
8565 shellparam.nparam = argc - 1;
8566 shellparam.p = argv + 1;
8567#if ENABLE_ASH_GETOPTS
8568 shellparam.optind = 1;
8569 shellparam.optoff = -1;
8570#endif
8571 evaltree(&func->n, flags & EV_TESTED);
Denis Vlasenko01631112007-12-16 17:20:38 +00008572 funcdone:
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008573 INT_OFF;
8574 funcnest--;
8575 freefunc(func);
8576 poplocalvars();
8577 localvars = savelocalvars;
8578 freeparam(&shellparam);
8579 shellparam = saveparam;
8580 exception_handler = savehandler;
8581 INT_ON;
8582 evalskip &= ~SKIPFUNC;
8583 return e;
8584}
8585
Denis Vlasenko131ae172007-02-18 13:00:19 +00008586#if ENABLE_ASH_CMDCMD
Denis Vlasenkoaa744452007-02-23 01:04:22 +00008587static char **
8588parse_command_args(char **argv, const char **path)
Eric Andersenc470f442003-07-28 09:56:35 +00008589{
8590 char *cp, c;
8591
8592 for (;;) {
8593 cp = *++argv;
8594 if (!cp)
8595 return 0;
8596 if (*cp++ != '-')
8597 break;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008598 c = *cp++;
8599 if (!c)
Eric Andersenc470f442003-07-28 09:56:35 +00008600 break;
8601 if (c == '-' && !*cp) {
8602 argv++;
8603 break;
8604 }
8605 do {
8606 switch (c) {
8607 case 'p':
Denis Vlasenkof5f75c52007-06-12 22:35:19 +00008608 *path = bb_default_path;
Eric Andersenc470f442003-07-28 09:56:35 +00008609 break;
8610 default:
8611 /* run 'typecmd' for other options */
8612 return 0;
8613 }
Denis Vlasenko9650f362007-02-23 01:04:37 +00008614 c = *cp++;
8615 } while (c);
Eric Andersenc470f442003-07-28 09:56:35 +00008616 }
8617 return argv;
8618}
8619#endif
8620
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008621/*
8622 * Make a variable a local variable. When a variable is made local, it's
8623 * value and flags are saved in a localvar structure. The saved values
8624 * will be restored when the shell function returns. We handle the name
8625 * "-" as a special case.
8626 */
8627static void
8628mklocal(char *name)
8629{
8630 struct localvar *lvp;
8631 struct var **vpp;
8632 struct var *vp;
8633
8634 INT_OFF;
Denis Vlasenko838ffd52008-02-21 04:32:08 +00008635 lvp = ckzalloc(sizeof(struct localvar));
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008636 if (LONE_DASH(name)) {
8637 char *p;
8638 p = ckmalloc(sizeof(optlist));
8639 lvp->text = memcpy(p, optlist, sizeof(optlist));
8640 vp = NULL;
8641 } else {
8642 char *eq;
8643
8644 vpp = hashvar(name);
8645 vp = *findvar(vpp, name);
8646 eq = strchr(name, '=');
8647 if (vp == NULL) {
8648 if (eq)
8649 setvareq(name, VSTRFIXED);
8650 else
8651 setvar(name, NULL, VSTRFIXED);
8652 vp = *vpp; /* the new variable */
8653 lvp->flags = VUNSET;
8654 } else {
8655 lvp->text = vp->text;
8656 lvp->flags = vp->flags;
8657 vp->flags |= VSTRFIXED|VTEXTFIXED;
8658 if (eq)
8659 setvareq(name, 0);
8660 }
8661 }
8662 lvp->vp = vp;
8663 lvp->next = localvars;
8664 localvars = lvp;
8665 INT_ON;
8666}
8667
8668/*
8669 * The "local" command.
8670 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008671static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008672localcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008673{
8674 char *name;
8675
8676 argv = argptr;
8677 while ((name = *argv++) != NULL) {
8678 mklocal(name);
8679 }
8680 return 0;
8681}
8682
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008683static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008684falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008685{
8686 return 1;
8687}
8688
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008689static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008690truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008691{
8692 return 0;
8693}
8694
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008695static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008696execcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008697{
Denis Vlasenko68404f12008-03-17 09:00:54 +00008698 if (argv[1]) {
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008699 iflag = 0; /* exit on error */
8700 mflag = 0;
8701 optschanged();
8702 shellexec(argv + 1, pathval(), 0);
8703 }
8704 return 0;
8705}
8706
8707/*
8708 * The return command.
8709 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008710static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008711returncmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008712{
8713 /*
8714 * If called outside a function, do what ksh does;
8715 * skip the rest of the file.
8716 */
8717 evalskip = funcnest ? SKIPFUNC : SKIPFILE;
8718 return argv[1] ? number(argv[1]) : exitstatus;
8719}
8720
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008721/* Forward declarations for builtintab[] */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008722static int breakcmd(int, char **) FAST_FUNC;
8723static int dotcmd(int, char **) FAST_FUNC;
8724static int evalcmd(int, char **) FAST_FUNC;
8725static int exitcmd(int, char **) FAST_FUNC;
8726static int exportcmd(int, char **) FAST_FUNC;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008727#if ENABLE_ASH_GETOPTS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008728static int getoptscmd(int, char **) FAST_FUNC;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008729#endif
Denis Vlasenko52764022007-02-24 13:42:56 +00008730#if !ENABLE_FEATURE_SH_EXTRA_QUIET
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008731static int helpcmd(int, char **) FAST_FUNC;
Denis Vlasenko52764022007-02-24 13:42:56 +00008732#endif
Mike Frysinger98c52642009-04-02 10:02:37 +00008733#if ENABLE_SH_MATH_SUPPORT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008734static int letcmd(int, char **) FAST_FUNC;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008735#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008736static int readcmd(int, char **) FAST_FUNC;
8737static int setcmd(int, char **) FAST_FUNC;
8738static int shiftcmd(int, char **) FAST_FUNC;
8739static int timescmd(int, char **) FAST_FUNC;
8740static int trapcmd(int, char **) FAST_FUNC;
8741static int umaskcmd(int, char **) FAST_FUNC;
8742static int unsetcmd(int, char **) FAST_FUNC;
8743static int ulimitcmd(int, char **) FAST_FUNC;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008744
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008745#define BUILTIN_NOSPEC "0"
8746#define BUILTIN_SPECIAL "1"
8747#define BUILTIN_REGULAR "2"
8748#define BUILTIN_SPEC_REG "3"
8749#define BUILTIN_ASSIGN "4"
8750#define BUILTIN_SPEC_ASSG "5"
8751#define BUILTIN_REG_ASSG "6"
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008752#define BUILTIN_SPEC_REG_ASSG "7"
8753
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008754/* Stubs for calling non-FAST_FUNC's */
Denys Vlasenko2634bf32009-06-09 18:40:07 +02008755#if ENABLE_ASH_BUILTIN_ECHO
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008756static int FAST_FUNC echocmd(int argc, char **argv) { return echo_main(argc, argv); }
Denys Vlasenko2634bf32009-06-09 18:40:07 +02008757#endif
8758#if ENABLE_ASH_BUILTIN_PRINTF
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008759static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
Denys Vlasenko2634bf32009-06-09 18:40:07 +02008760#endif
8761#if ENABLE_ASH_BUILTIN_TEST
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008762static int FAST_FUNC testcmd(int argc, char **argv) { return test_main(argc, argv); }
Denys Vlasenko2634bf32009-06-09 18:40:07 +02008763#endif
Denis Vlasenko468aea22008-04-01 14:47:57 +00008764
Denis Vlasenkof7d56652008-03-25 05:51:41 +00008765/* Keep these in proper order since it is searched via bsearch() */
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008766static const struct builtincmd builtintab[] = {
8767 { BUILTIN_SPEC_REG ".", dotcmd },
8768 { BUILTIN_SPEC_REG ":", truecmd },
8769#if ENABLE_ASH_BUILTIN_TEST
Denis Vlasenkocd2663f2008-06-01 22:36:39 +00008770 { BUILTIN_REGULAR "[", testcmd },
Denis Vlasenko80591b02008-03-25 07:49:43 +00008771#if ENABLE_ASH_BASH_COMPAT
Denis Vlasenkocd2663f2008-06-01 22:36:39 +00008772 { BUILTIN_REGULAR "[[", testcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008773#endif
Denis Vlasenko80591b02008-03-25 07:49:43 +00008774#endif
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008775#if ENABLE_ASH_ALIAS
8776 { BUILTIN_REG_ASSG "alias", aliascmd },
8777#endif
8778#if JOBS
8779 { BUILTIN_REGULAR "bg", fg_bgcmd },
8780#endif
8781 { BUILTIN_SPEC_REG "break", breakcmd },
8782 { BUILTIN_REGULAR "cd", cdcmd },
8783 { BUILTIN_NOSPEC "chdir", cdcmd },
8784#if ENABLE_ASH_CMDCMD
8785 { BUILTIN_REGULAR "command", commandcmd },
8786#endif
8787 { BUILTIN_SPEC_REG "continue", breakcmd },
8788#if ENABLE_ASH_BUILTIN_ECHO
8789 { BUILTIN_REGULAR "echo", echocmd },
8790#endif
8791 { BUILTIN_SPEC_REG "eval", evalcmd },
8792 { BUILTIN_SPEC_REG "exec", execcmd },
8793 { BUILTIN_SPEC_REG "exit", exitcmd },
8794 { BUILTIN_SPEC_REG_ASSG "export", exportcmd },
8795 { BUILTIN_REGULAR "false", falsecmd },
8796#if JOBS
8797 { BUILTIN_REGULAR "fg", fg_bgcmd },
8798#endif
8799#if ENABLE_ASH_GETOPTS
8800 { BUILTIN_REGULAR "getopts", getoptscmd },
8801#endif
8802 { BUILTIN_NOSPEC "hash", hashcmd },
8803#if !ENABLE_FEATURE_SH_EXTRA_QUIET
8804 { BUILTIN_NOSPEC "help", helpcmd },
8805#endif
8806#if JOBS
8807 { BUILTIN_REGULAR "jobs", jobscmd },
8808 { BUILTIN_REGULAR "kill", killcmd },
8809#endif
Mike Frysinger98c52642009-04-02 10:02:37 +00008810#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008811 { BUILTIN_NOSPEC "let", letcmd },
8812#endif
8813 { BUILTIN_ASSIGN "local", localcmd },
Denis Vlasenkocd2663f2008-06-01 22:36:39 +00008814#if ENABLE_ASH_BUILTIN_PRINTF
8815 { BUILTIN_REGULAR "printf", printfcmd },
8816#endif
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008817 { BUILTIN_NOSPEC "pwd", pwdcmd },
8818 { BUILTIN_REGULAR "read", readcmd },
8819 { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
8820 { BUILTIN_SPEC_REG "return", returncmd },
8821 { BUILTIN_SPEC_REG "set", setcmd },
8822 { BUILTIN_SPEC_REG "shift", shiftcmd },
8823 { BUILTIN_SPEC_REG "source", dotcmd },
8824#if ENABLE_ASH_BUILTIN_TEST
Denis Vlasenkocd2663f2008-06-01 22:36:39 +00008825 { BUILTIN_REGULAR "test", testcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008826#endif
8827 { BUILTIN_SPEC_REG "times", timescmd },
8828 { BUILTIN_SPEC_REG "trap", trapcmd },
8829 { BUILTIN_REGULAR "true", truecmd },
8830 { BUILTIN_NOSPEC "type", typecmd },
8831 { BUILTIN_NOSPEC "ulimit", ulimitcmd },
8832 { BUILTIN_REGULAR "umask", umaskcmd },
8833#if ENABLE_ASH_ALIAS
8834 { BUILTIN_REGULAR "unalias", unaliascmd },
8835#endif
8836 { BUILTIN_SPEC_REG "unset", unsetcmd },
8837 { BUILTIN_REGULAR "wait", waitcmd },
8838};
8839
Denis Vlasenko80591b02008-03-25 07:49:43 +00008840/* Should match the above table! */
8841#define COMMANDCMD (builtintab + \
8842 2 + \
8843 1 * ENABLE_ASH_BUILTIN_TEST + \
8844 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
8845 1 * ENABLE_ASH_ALIAS + \
8846 1 * ENABLE_ASH_JOB_CONTROL + \
8847 3)
8848#define EXECCMD (builtintab + \
8849 2 + \
8850 1 * ENABLE_ASH_BUILTIN_TEST + \
8851 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
8852 1 * ENABLE_ASH_ALIAS + \
8853 1 * ENABLE_ASH_JOB_CONTROL + \
8854 3 + \
8855 1 * ENABLE_ASH_CMDCMD + \
8856 1 + \
8857 ENABLE_ASH_BUILTIN_ECHO + \
8858 1)
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008859
8860/*
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008861 * Search the table of builtin commands.
8862 */
8863static struct builtincmd *
8864find_builtin(const char *name)
8865{
8866 struct builtincmd *bp;
8867
8868 bp = bsearch(
Denis Vlasenko80b8b392007-06-25 10:55:35 +00008869 name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008870 pstrcmp
8871 );
8872 return bp;
8873}
8874
8875/*
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008876 * Execute a simple command.
8877 */
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008878static int
8879isassignment(const char *p)
Paul Foxc3850c82005-07-20 18:23:39 +00008880{
8881 const char *q = endofname(p);
8882 if (p == q)
8883 return 0;
8884 return *q == '=';
8885}
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008886static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008887bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008888{
8889 /* Preserve exitstatus of a previous possible redirection
8890 * as POSIX mandates */
8891 return back_exitstatus;
8892}
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008893static void
Eric Andersenc470f442003-07-28 09:56:35 +00008894evalcommand(union node *cmd, int flags)
8895{
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00008896 static const struct builtincmd null_bltin = {
8897 "\0\0", bltincmd /* why three NULs? */
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008898 };
Eric Andersenc470f442003-07-28 09:56:35 +00008899 struct stackmark smark;
8900 union node *argp;
8901 struct arglist arglist;
8902 struct arglist varlist;
8903 char **argv;
8904 int argc;
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00008905 const struct strlist *sp;
Eric Andersenc470f442003-07-28 09:56:35 +00008906 struct cmdentry cmdentry;
8907 struct job *jp;
8908 char *lastarg;
8909 const char *path;
8910 int spclbltin;
Eric Andersenc470f442003-07-28 09:56:35 +00008911 int status;
8912 char **nargv;
Paul Foxc3850c82005-07-20 18:23:39 +00008913 struct builtincmd *bcmd;
Denis Vlasenko34c73c42008-08-16 11:48:02 +00008914 smallint cmd_is_exec;
8915 smallint pseudovarflag = 0;
Eric Andersenc470f442003-07-28 09:56:35 +00008916
8917 /* First expand the arguments. */
8918 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
8919 setstackmark(&smark);
8920 back_exitstatus = 0;
8921
8922 cmdentry.cmdtype = CMDBUILTIN;
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00008923 cmdentry.u.cmd = &null_bltin;
Eric Andersenc470f442003-07-28 09:56:35 +00008924 varlist.lastp = &varlist.list;
8925 *varlist.lastp = NULL;
8926 arglist.lastp = &arglist.list;
8927 *arglist.lastp = NULL;
8928
8929 argc = 0;
Denis Vlasenkob012b102007-02-19 22:43:01 +00008930 if (cmd->ncmd.args) {
Paul Foxc3850c82005-07-20 18:23:39 +00008931 bcmd = find_builtin(cmd->ncmd.args->narg.text);
8932 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
8933 }
8934
Eric Andersenc470f442003-07-28 09:56:35 +00008935 for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
8936 struct strlist **spp;
8937
8938 spp = arglist.lastp;
"Vladimir N. Oleynik"bef14d72005-09-05 13:25:11 +00008939 if (pseudovarflag && isassignment(argp->narg.text))
Paul Foxc3850c82005-07-20 18:23:39 +00008940 expandarg(argp, &arglist, EXP_VARTILDE);
8941 else
8942 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
8943
Eric Andersenc470f442003-07-28 09:56:35 +00008944 for (sp = *spp; sp; sp = sp->next)
8945 argc++;
8946 }
8947
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +00008948 argv = nargv = stalloc(sizeof(char *) * (argc + 1));
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008949 for (sp = arglist.list; sp; sp = sp->next) {
Eric Andersenc470f442003-07-28 09:56:35 +00008950 TRACE(("evalcommand arg: %s\n", sp->text));
8951 *nargv++ = sp->text;
8952 }
8953 *nargv = NULL;
8954
8955 lastarg = NULL;
8956 if (iflag && funcnest == 0 && argc > 0)
8957 lastarg = nargv[-1];
8958
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00008959 preverrout_fd = 2;
Eric Andersenc470f442003-07-28 09:56:35 +00008960 expredir(cmd->ncmd.redirect);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008961 status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
Eric Andersenc470f442003-07-28 09:56:35 +00008962
8963 path = vpath.text;
8964 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
8965 struct strlist **spp;
8966 char *p;
8967
8968 spp = varlist.lastp;
8969 expandarg(argp, &varlist, EXP_VARTILDE);
8970
8971 /*
8972 * Modify the command lookup path, if a PATH= assignment
8973 * is present
8974 */
8975 p = (*spp)->text;
8976 if (varequal(p, path))
8977 path = p;
8978 }
8979
8980 /* Print the command if xflag is set. */
8981 if (xflag) {
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00008982 int n;
8983 const char *p = " %s";
Eric Andersenc470f442003-07-28 09:56:35 +00008984
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00008985 p++;
Denis Vlasenko0de37e12007-10-17 11:08:53 +00008986 fdprintf(preverrout_fd, p, expandstr(ps4val()));
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00008987
8988 sp = varlist.list;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +00008989 for (n = 0; n < 2; n++) {
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00008990 while (sp) {
Denis Vlasenko0de37e12007-10-17 11:08:53 +00008991 fdprintf(preverrout_fd, p, sp->text);
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00008992 sp = sp->next;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +00008993 if (*p == '%') {
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00008994 p--;
8995 }
8996 }
8997 sp = arglist.list;
8998 }
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00008999 safe_write(preverrout_fd, "\n", 1);
Eric Andersenc470f442003-07-28 09:56:35 +00009000 }
9001
9002 cmd_is_exec = 0;
9003 spclbltin = -1;
9004
9005 /* Now locate the command. */
9006 if (argc) {
9007 const char *oldpath;
9008 int cmd_flag = DO_ERR;
9009
9010 path += 5;
9011 oldpath = path;
9012 for (;;) {
9013 find_command(argv[0], &cmdentry, cmd_flag, path);
9014 if (cmdentry.cmdtype == CMDUNKNOWN) {
Denis Vlasenkob012b102007-02-19 22:43:01 +00009015 flush_stderr();
Denis Vlasenko6514c5e2008-07-24 13:41:37 +00009016 status = 127;
Eric Andersenc470f442003-07-28 09:56:35 +00009017 goto bail;
9018 }
9019
9020 /* implement bltin and command here */
9021 if (cmdentry.cmdtype != CMDBUILTIN)
9022 break;
9023 if (spclbltin < 0)
9024 spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
9025 if (cmdentry.u.cmd == EXECCMD)
Denis Vlasenko34c73c42008-08-16 11:48:02 +00009026 cmd_is_exec = 1;
Denis Vlasenko131ae172007-02-18 13:00:19 +00009027#if ENABLE_ASH_CMDCMD
Eric Andersenc470f442003-07-28 09:56:35 +00009028 if (cmdentry.u.cmd == COMMANDCMD) {
Eric Andersenc470f442003-07-28 09:56:35 +00009029 path = oldpath;
9030 nargv = parse_command_args(argv, &path);
9031 if (!nargv)
9032 break;
9033 argc -= nargv - argv;
9034 argv = nargv;
9035 cmd_flag |= DO_NOFUNC;
9036 } else
9037#endif
9038 break;
9039 }
9040 }
9041
9042 if (status) {
9043 /* We have a redirection error. */
9044 if (spclbltin > 0)
Denis Vlasenkob012b102007-02-19 22:43:01 +00009045 raise_exception(EXERROR);
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009046 bail:
Eric Andersenc470f442003-07-28 09:56:35 +00009047 exitstatus = status;
9048 goto out;
9049 }
9050
9051 /* Execute the command. */
9052 switch (cmdentry.cmdtype) {
9053 default:
Denis Vlasenkobe54d6b2008-10-27 14:25:52 +00009054
Denis Vlasenko9bc80d72008-04-12 20:07:53 +00009055#if ENABLE_FEATURE_SH_NOFORK
Denis Vlasenkobe54d6b2008-10-27 14:25:52 +00009056/* Hmmm... shouldn't it happen somewhere in forkshell() instead?
9057 * Why "fork off a child process if necessary" doesn't apply to NOFORK? */
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00009058 {
9059 /* find_command() encodes applet_no as (-2 - applet_no) */
9060 int applet_no = (- cmdentry.u.index - 2);
Denis Vlasenko9bc80d72008-04-12 20:07:53 +00009061 if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
Denis Vlasenko9bc80d72008-04-12 20:07:53 +00009062 listsetvar(varlist.list, VEXPORT|VSTACK);
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00009063 /* run <applet>_main() */
9064 exitstatus = run_nofork_applet(applet_no, argv);
Denis Vlasenko9bc80d72008-04-12 20:07:53 +00009065 break;
9066 }
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00009067 }
Denis Vlasenko9bc80d72008-04-12 20:07:53 +00009068#endif
Eric Andersenc470f442003-07-28 09:56:35 +00009069 /* Fork off a child process if necessary. */
9070 if (!(flags & EV_EXIT) || trap[0]) {
Denis Vlasenkob012b102007-02-19 22:43:01 +00009071 INT_OFF;
Denis Vlasenko68404f12008-03-17 09:00:54 +00009072 jp = makejob(/*cmd,*/ 1);
Eric Andersenc470f442003-07-28 09:56:35 +00009073 if (forkshell(jp, cmd, FORK_FG) != 0) {
9074 exitstatus = waitforjob(jp);
Denis Vlasenkob012b102007-02-19 22:43:01 +00009075 INT_ON;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00009076 TRACE(("forked child exited with %d\n", exitstatus));
Eric Andersenc470f442003-07-28 09:56:35 +00009077 break;
9078 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00009079 FORCE_INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00009080 }
9081 listsetvar(varlist.list, VEXPORT|VSTACK);
9082 shellexec(argv, path, cmdentry.u.index);
9083 /* NOTREACHED */
9084
9085 case CMDBUILTIN:
9086 cmdenviron = varlist.list;
9087 if (cmdenviron) {
9088 struct strlist *list = cmdenviron;
9089 int i = VNOSET;
9090 if (spclbltin > 0 || argc == 0) {
9091 i = 0;
9092 if (cmd_is_exec && argc > 1)
9093 i = VEXPORT;
9094 }
9095 listsetvar(list, i);
9096 }
Denis Vlasenkobe54d6b2008-10-27 14:25:52 +00009097 /* Tight loop with builtins only:
9098 * "while kill -0 $child; do true; done"
9099 * will never exit even if $child died, unless we do this
9100 * to reap the zombie and make kill detect that it's gone: */
9101 dowait(DOWAIT_NONBLOCK, NULL);
9102
Eric Andersenc470f442003-07-28 09:56:35 +00009103 if (evalbltin(cmdentry.u.cmd, argc, argv)) {
9104 int exit_status;
Denis Vlasenko7f88e342009-03-19 03:36:18 +00009105 int i = exception_type;
Eric Andersenc470f442003-07-28 09:56:35 +00009106 if (i == EXEXIT)
9107 goto raise;
Eric Andersenc470f442003-07-28 09:56:35 +00009108 exit_status = 2;
Eric Andersenc470f442003-07-28 09:56:35 +00009109 if (i == EXINT)
Denis Vlasenko991a1da2008-02-10 19:02:53 +00009110 exit_status = 128 + SIGINT;
Eric Andersenc470f442003-07-28 09:56:35 +00009111 if (i == EXSIG)
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02009112 exit_status = 128 + pending_sig;
Eric Andersenc470f442003-07-28 09:56:35 +00009113 exitstatus = exit_status;
Eric Andersenc470f442003-07-28 09:56:35 +00009114 if (i == EXINT || spclbltin > 0) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009115 raise:
Denis Vlasenko2da584f2007-02-19 22:44:05 +00009116 longjmp(exception_handler->loc, 1);
Eric Andersenc470f442003-07-28 09:56:35 +00009117 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00009118 FORCE_INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00009119 }
9120 break;
9121
9122 case CMDFUNCTION:
9123 listsetvar(varlist.list, 0);
Denis Vlasenkobe54d6b2008-10-27 14:25:52 +00009124 /* See above for the rationale */
9125 dowait(DOWAIT_NONBLOCK, NULL);
Eric Andersenc470f442003-07-28 09:56:35 +00009126 if (evalfun(cmdentry.u.func, argc, argv, flags))
9127 goto raise;
9128 break;
9129 }
9130
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009131 out:
Denis Vlasenko34c73c42008-08-16 11:48:02 +00009132 popredir(/*drop:*/ cmd_is_exec, /*restore:*/ cmd_is_exec);
Denis Vlasenko6514c5e2008-07-24 13:41:37 +00009133 if (lastarg) {
Eric Andersenc470f442003-07-28 09:56:35 +00009134 /* dsl: I think this is intended to be used to support
9135 * '_' in 'vi' command mode during line editing...
9136 * However I implemented that within libedit itself.
9137 */
9138 setvar("_", lastarg, 0);
Denis Vlasenko6514c5e2008-07-24 13:41:37 +00009139 }
Eric Andersenc470f442003-07-28 09:56:35 +00009140 popstackmark(&smark);
9141}
9142
9143static int
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009144evalbltin(const struct builtincmd *cmd, int argc, char **argv)
9145{
Eric Andersenc470f442003-07-28 09:56:35 +00009146 char *volatile savecmdname;
9147 struct jmploc *volatile savehandler;
9148 struct jmploc jmploc;
9149 int i;
9150
9151 savecmdname = commandname;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009152 i = setjmp(jmploc.loc);
9153 if (i)
Eric Andersenc470f442003-07-28 09:56:35 +00009154 goto cmddone;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00009155 savehandler = exception_handler;
9156 exception_handler = &jmploc;
Eric Andersenc470f442003-07-28 09:56:35 +00009157 commandname = argv[0];
9158 argptr = argv + 1;
9159 optptr = NULL; /* initialize nextopt */
9160 exitstatus = (*cmd->builtin)(argc, argv);
Denis Vlasenkob012b102007-02-19 22:43:01 +00009161 flush_stdout_stderr();
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009162 cmddone:
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009163 exitstatus |= ferror(stdout);
Rob Landleyf296f0b2006-07-06 01:09:21 +00009164 clearerr(stdout);
Eric Andersenc470f442003-07-28 09:56:35 +00009165 commandname = savecmdname;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00009166 exception_handler = savehandler;
Eric Andersenc470f442003-07-28 09:56:35 +00009167
9168 return i;
9169}
9170
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009171static int
9172goodname(const char *p)
Glenn L McGrath16e45d72004-02-04 08:24:39 +00009173{
9174 return !*endofname(p);
9175}
9176
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009177
Glenn L McGrath50812ff2002-08-23 13:14:48 +00009178/*
9179 * Search for a command. This is called before we fork so that the
9180 * location of the command will be available in the parent as well as
Glenn L McGrath16e45d72004-02-04 08:24:39 +00009181 * the child. The check for "goodname" is an overly conservative
9182 * check that the name will not be subject to expansion.
Glenn L McGrath50812ff2002-08-23 13:14:48 +00009183 */
Eric Andersenc470f442003-07-28 09:56:35 +00009184static void
9185prehash(union node *n)
Glenn L McGrath50812ff2002-08-23 13:14:48 +00009186{
9187 struct cmdentry entry;
9188
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +00009189 if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
9190 find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
Glenn L McGrath50812ff2002-08-23 13:14:48 +00009191}
9192
Eric Andersencb57d552001-06-28 07:25:16 +00009193
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00009194/* ============ Builtin commands
9195 *
9196 * Builtin commands whose functions are closely tied to evaluation
9197 * are implemented here.
Eric Andersencb57d552001-06-28 07:25:16 +00009198 */
9199
9200/*
Eric Andersencb57d552001-06-28 07:25:16 +00009201 * Handle break and continue commands. Break, continue, and return are
9202 * all handled by setting the evalskip flag. The evaluation routines
9203 * above all check this flag, and if it is set they start skipping
9204 * commands rather than executing them. The variable skipcount is
9205 * the number of loops to break/continue, or the number of function
9206 * levels to return. (The latter is always 1.) It should probably
9207 * be an error to break out of more loops than exist, but it isn't
9208 * in the standard shell so we don't make it one here.
9209 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009210static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00009211breakcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +00009212{
Denis Vlasenko68404f12008-03-17 09:00:54 +00009213 int n = argv[1] ? number(argv[1]) : 1;
Eric Andersencb57d552001-06-28 07:25:16 +00009214
Aaron Lehmann2aef3a62001-12-31 06:03:12 +00009215 if (n <= 0)
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02009216 ash_msg_and_raise_error(msg_illnum, argv[1]);
Eric Andersencb57d552001-06-28 07:25:16 +00009217 if (n > loopnest)
9218 n = loopnest;
9219 if (n > 0) {
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00009220 evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
Eric Andersencb57d552001-06-28 07:25:16 +00009221 skipcount = n;
9222 }
9223 return 0;
9224}
9225
Eric Andersenc470f442003-07-28 09:56:35 +00009226
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009227/* ============ input.c
9228 *
Eric Andersen90898442003-08-06 11:20:52 +00009229 * This implements the input routines used by the parser.
Eric Andersencb57d552001-06-28 07:25:16 +00009230 */
Denis Vlasenko99eb8502007-02-23 21:09:49 +00009231
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009232enum {
9233 INPUT_PUSH_FILE = 1,
9234 INPUT_NOFILE_OK = 2,
9235};
Eric Andersencb57d552001-06-28 07:25:16 +00009236
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009237static smallint checkkwd;
Denis Vlasenko99eb8502007-02-23 21:09:49 +00009238/* values of checkkwd variable */
9239#define CHKALIAS 0x1
9240#define CHKKWD 0x2
9241#define CHKNL 0x4
9242
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009243/*
9244 * Push a string back onto the input at this current parsefile level.
9245 * We handle aliases this way.
9246 */
9247#if !ENABLE_ASH_ALIAS
9248#define pushstring(s, ap) pushstring(s)
9249#endif
9250static void
9251pushstring(char *s, struct alias *ap)
9252{
9253 struct strpush *sp;
9254 int len;
9255
9256 len = strlen(s);
9257 INT_OFF;
9258 if (g_parsefile->strpush) {
9259 sp = ckzalloc(sizeof(*sp));
9260 sp->prev = g_parsefile->strpush;
9261 } else {
9262 sp = &(g_parsefile->basestrpush);
9263 }
9264 g_parsefile->strpush = sp;
9265 sp->prev_string = g_parsefile->next_to_pgetc;
9266 sp->prev_left_in_line = g_parsefile->left_in_line;
9267#if ENABLE_ASH_ALIAS
9268 sp->ap = ap;
9269 if (ap) {
9270 ap->flag |= ALIASINUSE;
9271 sp->string = s;
9272 }
9273#endif
9274 g_parsefile->next_to_pgetc = s;
9275 g_parsefile->left_in_line = len;
9276 INT_ON;
9277}
9278
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009279static void
9280popstring(void)
Eric Andersenc470f442003-07-28 09:56:35 +00009281{
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009282 struct strpush *sp = g_parsefile->strpush;
Eric Andersenc470f442003-07-28 09:56:35 +00009283
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009284 INT_OFF;
Denis Vlasenko131ae172007-02-18 13:00:19 +00009285#if ENABLE_ASH_ALIAS
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009286 if (sp->ap) {
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009287 if (g_parsefile->next_to_pgetc[-1] == ' '
9288 || g_parsefile->next_to_pgetc[-1] == '\t'
9289 ) {
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009290 checkkwd |= CHKALIAS;
Glenn L McGrath28939ad2004-07-21 10:20:19 +00009291 }
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009292 if (sp->string != sp->ap->val) {
9293 free(sp->string);
9294 }
9295 sp->ap->flag &= ~ALIASINUSE;
9296 if (sp->ap->flag & ALIASDEAD) {
9297 unalias(sp->ap->name);
9298 }
Glenn L McGrath28939ad2004-07-21 10:20:19 +00009299 }
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009300#endif
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009301 g_parsefile->next_to_pgetc = sp->prev_string;
9302 g_parsefile->left_in_line = sp->prev_left_in_line;
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009303 g_parsefile->strpush = sp->prev;
9304 if (sp != &(g_parsefile->basestrpush))
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009305 free(sp);
9306 INT_ON;
9307}
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009308
Denis Vlasenkoe27dafd2008-11-28 04:01:03 +00009309//FIXME: BASH_COMPAT with "...&" does TWO pungetc():
9310//it peeks whether it is &>, and then pushes back both chars.
9311//This function needs to save last *next_to_pgetc to buf[0]
9312//to make two pungetc() reliable. Currently,
9313// pgetc (out of buf: does preadfd), pgetc, pungetc, pungetc won't work...
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009314static int
9315preadfd(void)
Eric Andersencb57d552001-06-28 07:25:16 +00009316{
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00009317 int nr;
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00009318 char *buf = g_parsefile->buf;
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00009319
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009320 g_parsefile->next_to_pgetc = buf;
Denis Vlasenko38f63192007-01-22 09:03:07 +00009321#if ENABLE_FEATURE_EDITING
Denis Vlasenko85c24712008-03-17 09:04:04 +00009322 retry:
Denis Vlasenko727752d2008-11-28 03:41:47 +00009323 if (!iflag || g_parsefile->fd != STDIN_FILENO)
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009324 nr = nonblock_safe_read(g_parsefile->fd, buf, BUFSIZ - 1);
Eric Andersenc470f442003-07-28 09:56:35 +00009325 else {
Denis Vlasenko38f63192007-01-22 09:03:07 +00009326#if ENABLE_FEATURE_TAB_COMPLETION
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009327 line_input_state->path_lookup = pathval();
Eric Andersen4a79c0e2004-09-08 10:01:07 +00009328#endif
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009329 nr = read_line_input(cmdedit_prompt, buf, BUFSIZ, line_input_state);
9330 if (nr == 0) {
9331 /* Ctrl+C pressed */
9332 if (trap[SIGINT]) {
Glenn L McGrath16e45d72004-02-04 08:24:39 +00009333 buf[0] = '\n';
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009334 buf[1] = '\0';
Glenn L McGrath16e45d72004-02-04 08:24:39 +00009335 raise(SIGINT);
9336 return 1;
9337 }
Eric Andersenc470f442003-07-28 09:56:35 +00009338 goto retry;
9339 }
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009340 if (nr < 0 && errno == 0) {
Denis Vlasenko9cb220b2007-12-09 10:03:28 +00009341 /* Ctrl+D pressed */
Eric Andersenc470f442003-07-28 09:56:35 +00009342 nr = 0;
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00009343 }
Eric Andersencb57d552001-06-28 07:25:16 +00009344 }
9345#else
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +00009346 nr = nonblock_safe_read(g_parsefile->fd, buf, BUFSIZ - 1);
Eric Andersencb57d552001-06-28 07:25:16 +00009347#endif
9348
Denis Vlasenkoe376d452008-02-20 22:23:24 +00009349#if 0
9350/* nonblock_safe_read() handles this problem */
Eric Andersencb57d552001-06-28 07:25:16 +00009351 if (nr < 0) {
Eric Andersencb57d552001-06-28 07:25:16 +00009352 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
Denis Vlasenkod37f2222007-08-19 13:42:08 +00009353 int flags = fcntl(0, F_GETFL);
Denis Vlasenko9cb220b2007-12-09 10:03:28 +00009354 if (flags >= 0 && (flags & O_NONBLOCK)) {
9355 flags &= ~O_NONBLOCK;
Eric Andersencb57d552001-06-28 07:25:16 +00009356 if (fcntl(0, F_SETFL, flags) >= 0) {
9357 out2str("sh: turning off NDELAY mode\n");
9358 goto retry;
9359 }
9360 }
9361 }
9362 }
Denis Vlasenkoe376d452008-02-20 22:23:24 +00009363#endif
Eric Andersencb57d552001-06-28 07:25:16 +00009364 return nr;
9365}
9366
9367/*
9368 * Refill the input buffer and return the next input character:
9369 *
9370 * 1) If a string was pushed back on the input, pop it;
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009371 * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
9372 * or we are reading from a string so we can't refill the buffer,
9373 * return EOF.
Denys Vlasenko883cea42009-07-11 15:31:59 +02009374 * 3) If there is more stuff in this buffer, use it else call read to fill it.
Eric Andersencb57d552001-06-28 07:25:16 +00009375 * 4) Process input up to the next newline, deleting nul characters.
9376 */
Denis Vlasenko727752d2008-11-28 03:41:47 +00009377//#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
9378#define pgetc_debug(...) ((void)0)
Denis Vlasenko68819d12008-12-15 11:26:36 +00009379/*
9380 * NB: due to SIT(c) internals (syntax_index_table[] vector),
9381 * pgetc() and related functions must return chars SIGN-EXTENDED into ints,
9382 * not zero-extended. Seems fragile to me. Affects only !USE_SIT_FUNCTION case,
9383 * so we can fix it by ditching !USE_SIT_FUNCTION if Unicode requires that.
9384 */
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009385static int
Eric Andersenc470f442003-07-28 09:56:35 +00009386preadbuffer(void)
Eric Andersencb57d552001-06-28 07:25:16 +00009387{
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009388 char *q;
Eric Andersencb57d552001-06-28 07:25:16 +00009389 int more;
Eric Andersencb57d552001-06-28 07:25:16 +00009390
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009391 while (g_parsefile->strpush) {
Denis Vlasenko131ae172007-02-18 13:00:19 +00009392#if ENABLE_ASH_ALIAS
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009393 if (g_parsefile->left_in_line == -1
9394 && g_parsefile->strpush->ap
9395 && g_parsefile->next_to_pgetc[-1] != ' '
9396 && g_parsefile->next_to_pgetc[-1] != '\t'
Denis Vlasenko16898402008-11-25 01:34:52 +00009397 ) {
Denis Vlasenko727752d2008-11-28 03:41:47 +00009398 pgetc_debug("preadbuffer PEOA");
Eric Andersencb57d552001-06-28 07:25:16 +00009399 return PEOA;
9400 }
Eric Andersen2870d962001-07-02 17:27:21 +00009401#endif
Eric Andersencb57d552001-06-28 07:25:16 +00009402 popstring();
Denis Vlasenko727752d2008-11-28 03:41:47 +00009403 /* try "pgetc" now: */
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009404 pgetc_debug("preadbuffer internal pgetc at %d:%p'%s'",
9405 g_parsefile->left_in_line,
9406 g_parsefile->next_to_pgetc,
9407 g_parsefile->next_to_pgetc);
9408 if (--g_parsefile->left_in_line >= 0)
9409 return (unsigned char)(*g_parsefile->next_to_pgetc++);
Eric Andersencb57d552001-06-28 07:25:16 +00009410 }
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009411 /* on both branches above g_parsefile->left_in_line < 0.
Denis Vlasenko727752d2008-11-28 03:41:47 +00009412 * "pgetc" needs refilling.
9413 */
9414
Denis Vlasenkoe27dafd2008-11-28 04:01:03 +00009415 /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009416 * pungetc() may increment it a few times.
Denis Vlasenkoe27dafd2008-11-28 04:01:03 +00009417 * Assuming it won't increment it to less than -90.
Denis Vlasenko727752d2008-11-28 03:41:47 +00009418 */
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009419 if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
Denis Vlasenko727752d2008-11-28 03:41:47 +00009420 pgetc_debug("preadbuffer PEOF1");
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009421 /* even in failure keep left_in_line and next_to_pgetc
9422 * in lock step, for correct multi-layer pungetc.
9423 * left_in_line was decremented before preadbuffer(),
9424 * must inc next_to_pgetc: */
9425 g_parsefile->next_to_pgetc++;
Eric Andersencb57d552001-06-28 07:25:16 +00009426 return PEOF;
Denis Vlasenko727752d2008-11-28 03:41:47 +00009427 }
Eric Andersencb57d552001-06-28 07:25:16 +00009428
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009429 more = g_parsefile->left_in_buffer;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009430 if (more <= 0) {
Denis Vlasenko727752d2008-11-28 03:41:47 +00009431 flush_stdout_stderr();
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009432 again:
9433 more = preadfd();
9434 if (more <= 0) {
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009435 /* don't try reading again */
9436 g_parsefile->left_in_line = -99;
Denis Vlasenko727752d2008-11-28 03:41:47 +00009437 pgetc_debug("preadbuffer PEOF2");
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009438 g_parsefile->next_to_pgetc++;
Eric Andersencb57d552001-06-28 07:25:16 +00009439 return PEOF;
9440 }
9441 }
9442
Denis Vlasenko727752d2008-11-28 03:41:47 +00009443 /* Find out where's the end of line.
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009444 * Set g_parsefile->left_in_line
9445 * and g_parsefile->left_in_buffer acordingly.
Denis Vlasenko727752d2008-11-28 03:41:47 +00009446 * NUL chars are deleted.
9447 */
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009448 q = g_parsefile->next_to_pgetc;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009449 for (;;) {
Denis Vlasenko727752d2008-11-28 03:41:47 +00009450 char c;
Eric Andersencb57d552001-06-28 07:25:16 +00009451
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009452 more--;
Eric Andersenc470f442003-07-28 09:56:35 +00009453
Denis Vlasenko727752d2008-11-28 03:41:47 +00009454 c = *q;
9455 if (c == '\0') {
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009456 memmove(q, q + 1, more);
Denis Vlasenko727752d2008-11-28 03:41:47 +00009457 } else {
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009458 q++;
9459 if (c == '\n') {
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009460 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009461 break;
9462 }
Eric Andersencb57d552001-06-28 07:25:16 +00009463 }
9464
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009465 if (more <= 0) {
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009466 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9467 if (g_parsefile->left_in_line < 0)
Eric Andersencb57d552001-06-28 07:25:16 +00009468 goto again;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009469 break;
Eric Andersencb57d552001-06-28 07:25:16 +00009470 }
9471 }
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009472 g_parsefile->left_in_buffer = more;
Eric Andersencb57d552001-06-28 07:25:16 +00009473
Eric Andersencb57d552001-06-28 07:25:16 +00009474 if (vflag) {
Denis Vlasenko727752d2008-11-28 03:41:47 +00009475 char save = *q;
9476 *q = '\0';
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009477 out2str(g_parsefile->next_to_pgetc);
Denis Vlasenko727752d2008-11-28 03:41:47 +00009478 *q = save;
Eric Andersencb57d552001-06-28 07:25:16 +00009479 }
9480
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009481 pgetc_debug("preadbuffer at %d:%p'%s'",
9482 g_parsefile->left_in_line,
9483 g_parsefile->next_to_pgetc,
9484 g_parsefile->next_to_pgetc);
Denis Vlasenko68819d12008-12-15 11:26:36 +00009485 return signed_char2int(*g_parsefile->next_to_pgetc++);
Eric Andersencb57d552001-06-28 07:25:16 +00009486}
9487
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009488#define pgetc_as_macro() \
9489 (--g_parsefile->left_in_line >= 0 \
Denis Vlasenko68819d12008-12-15 11:26:36 +00009490 ? signed_char2int(*g_parsefile->next_to_pgetc++) \
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009491 : preadbuffer() \
9492 )
Denis Vlasenko727752d2008-11-28 03:41:47 +00009493
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009494static int
9495pgetc(void)
9496{
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009497 pgetc_debug("pgetc_fast at %d:%p'%s'",
9498 g_parsefile->left_in_line,
9499 g_parsefile->next_to_pgetc,
9500 g_parsefile->next_to_pgetc);
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009501 return pgetc_as_macro();
9502}
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00009503
9504#if ENABLE_ASH_OPTIMIZE_FOR_SIZE
Denis Vlasenko834dee72008-10-07 09:18:30 +00009505#define pgetc_fast() pgetc()
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009506#else
Denis Vlasenko834dee72008-10-07 09:18:30 +00009507#define pgetc_fast() pgetc_as_macro()
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009508#endif
9509
9510/*
9511 * Same as pgetc(), but ignores PEOA.
9512 */
9513#if ENABLE_ASH_ALIAS
9514static int
9515pgetc2(void)
9516{
9517 int c;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009518 do {
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009519 pgetc_debug("pgetc_fast at %d:%p'%s'",
9520 g_parsefile->left_in_line,
9521 g_parsefile->next_to_pgetc,
9522 g_parsefile->next_to_pgetc);
Denis Vlasenko834dee72008-10-07 09:18:30 +00009523 c = pgetc_fast();
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009524 } while (c == PEOA);
9525 return c;
9526}
9527#else
Denis Vlasenko834dee72008-10-07 09:18:30 +00009528#define pgetc2() pgetc()
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009529#endif
9530
9531/*
9532 * Read a line from the script.
9533 */
9534static char *
9535pfgets(char *line, int len)
9536{
9537 char *p = line;
9538 int nleft = len;
9539 int c;
9540
9541 while (--nleft > 0) {
9542 c = pgetc2();
9543 if (c == PEOF) {
9544 if (p == line)
9545 return NULL;
9546 break;
9547 }
9548 *p++ = c;
9549 if (c == '\n')
9550 break;
9551 }
9552 *p = '\0';
9553 return line;
9554}
9555
Eric Andersenc470f442003-07-28 09:56:35 +00009556/*
9557 * Undo the last call to pgetc. Only one character may be pushed back.
9558 * PEOF may be pushed back.
9559 */
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009560static void
Eric Andersenc470f442003-07-28 09:56:35 +00009561pungetc(void)
9562{
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009563 g_parsefile->left_in_line++;
9564 g_parsefile->next_to_pgetc--;
9565 pgetc_debug("pushed back to %d:%p'%s'",
9566 g_parsefile->left_in_line,
9567 g_parsefile->next_to_pgetc,
9568 g_parsefile->next_to_pgetc);
Eric Andersencb57d552001-06-28 07:25:16 +00009569}
9570
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009571/*
9572 * To handle the "." command, a stack of input files is used. Pushfile
9573 * adds a new entry to the stack and popfile restores the previous level.
9574 */
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009575static void
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009576pushfile(void)
Eric Andersenc470f442003-07-28 09:56:35 +00009577{
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009578 struct parsefile *pf;
9579
Denis Vlasenko597906c2008-02-20 16:38:54 +00009580 pf = ckzalloc(sizeof(*pf));
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009581 pf->prev = g_parsefile;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009582 pf->fd = -1;
Denis Vlasenko597906c2008-02-20 16:38:54 +00009583 /*pf->strpush = NULL; - ckzalloc did it */
9584 /*pf->basestrpush.prev = NULL;*/
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009585 g_parsefile = pf;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009586}
9587
9588static void
9589popfile(void)
9590{
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009591 struct parsefile *pf = g_parsefile;
Eric Andersenc470f442003-07-28 09:56:35 +00009592
Denis Vlasenkob012b102007-02-19 22:43:01 +00009593 INT_OFF;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009594 if (pf->fd >= 0)
9595 close(pf->fd);
Denis Vlasenko60818682007-09-28 22:07:23 +00009596 free(pf->buf);
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009597 while (pf->strpush)
9598 popstring();
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009599 g_parsefile = pf->prev;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009600 free(pf);
Denis Vlasenkob012b102007-02-19 22:43:01 +00009601 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00009602}
9603
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009604/*
9605 * Return to top level.
9606 */
9607static void
9608popallfiles(void)
9609{
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009610 while (g_parsefile != &basepf)
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009611 popfile();
9612}
9613
9614/*
9615 * Close the file(s) that the shell is reading commands from. Called
9616 * after a fork is done.
9617 */
9618static void
9619closescript(void)
9620{
9621 popallfiles();
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009622 if (g_parsefile->fd > 0) {
9623 close(g_parsefile->fd);
9624 g_parsefile->fd = 0;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009625 }
9626}
9627
9628/*
9629 * Like setinputfile, but takes an open file descriptor. Call this with
9630 * interrupts off.
9631 */
9632static void
9633setinputfd(int fd, int push)
9634{
Denis Vlasenko96e1b382007-09-30 23:50:48 +00009635 close_on_exec_on(fd);
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009636 if (push) {
9637 pushfile();
Denis Vlasenko727752d2008-11-28 03:41:47 +00009638 g_parsefile->buf = NULL;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009639 }
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009640 g_parsefile->fd = fd;
9641 if (g_parsefile->buf == NULL)
9642 g_parsefile->buf = ckmalloc(IBUFSIZ);
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009643 g_parsefile->left_in_buffer = 0;
9644 g_parsefile->left_in_line = 0;
9645 g_parsefile->linno = 1;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009646}
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009647
Eric Andersenc470f442003-07-28 09:56:35 +00009648/*
9649 * Set the input to take input from a file. If push is set, push the
9650 * old input onto the stack first.
9651 */
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009652static int
9653setinputfile(const char *fname, int flags)
Eric Andersenc470f442003-07-28 09:56:35 +00009654{
9655 int fd;
9656 int fd2;
9657
Denis Vlasenkob012b102007-02-19 22:43:01 +00009658 INT_OFF;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009659 fd = open(fname, O_RDONLY);
9660 if (fd < 0) {
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009661 if (flags & INPUT_NOFILE_OK)
9662 goto out;
Denis Vlasenko9604e1b2009-03-03 18:47:56 +00009663 ash_msg_and_raise_error("can't open '%s'", fname);
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009664 }
Eric Andersenc470f442003-07-28 09:56:35 +00009665 if (fd < 10) {
9666 fd2 = copyfd(fd, 10);
9667 close(fd);
9668 if (fd2 < 0)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00009669 ash_msg_and_raise_error("out of file descriptors");
Eric Andersenc470f442003-07-28 09:56:35 +00009670 fd = fd2;
9671 }
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009672 setinputfd(fd, flags & INPUT_PUSH_FILE);
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009673 out:
Denis Vlasenkob012b102007-02-19 22:43:01 +00009674 INT_ON;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009675 return fd;
Eric Andersenc470f442003-07-28 09:56:35 +00009676}
9677
Eric Andersencb57d552001-06-28 07:25:16 +00009678/*
9679 * Like setinputfile, but takes input from a string.
9680 */
Eric Andersenc470f442003-07-28 09:56:35 +00009681static void
9682setinputstring(char *string)
Eric Andersen62483552001-07-10 06:09:16 +00009683{
Denis Vlasenkob012b102007-02-19 22:43:01 +00009684 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +00009685 pushfile();
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009686 g_parsefile->next_to_pgetc = string;
9687 g_parsefile->left_in_line = strlen(string);
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009688 g_parsefile->buf = NULL;
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009689 g_parsefile->linno = 1;
Denis Vlasenkob012b102007-02-19 22:43:01 +00009690 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00009691}
9692
9693
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00009694/* ============ mail.c
9695 *
9696 * Routines to check for mail.
Eric Andersencb57d552001-06-28 07:25:16 +00009697 */
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00009698
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00009699#if ENABLE_ASH_MAIL
Eric Andersencb57d552001-06-28 07:25:16 +00009700
Eric Andersencb57d552001-06-28 07:25:16 +00009701#define MAXMBOXES 10
9702
Eric Andersenc470f442003-07-28 09:56:35 +00009703/* times of mailboxes */
9704static time_t mailtime[MAXMBOXES];
9705/* Set if MAIL or MAILPATH is changed. */
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +00009706static smallint mail_var_path_changed;
Eric Andersencb57d552001-06-28 07:25:16 +00009707
Eric Andersencb57d552001-06-28 07:25:16 +00009708/*
Eric Andersenc470f442003-07-28 09:56:35 +00009709 * Print appropriate message(s) if mail has arrived.
9710 * If mail_var_path_changed is set,
9711 * then the value of MAIL has mail_var_path_changed,
9712 * so we just update the values.
Eric Andersencb57d552001-06-28 07:25:16 +00009713 */
Eric Andersenc470f442003-07-28 09:56:35 +00009714static void
9715chkmail(void)
Eric Andersencb57d552001-06-28 07:25:16 +00009716{
Eric Andersencb57d552001-06-28 07:25:16 +00009717 const char *mpath;
9718 char *p;
9719 char *q;
Eric Andersenc470f442003-07-28 09:56:35 +00009720 time_t *mtp;
Eric Andersencb57d552001-06-28 07:25:16 +00009721 struct stackmark smark;
9722 struct stat statb;
9723
Eric Andersencb57d552001-06-28 07:25:16 +00009724 setstackmark(&smark);
Eric Andersenc470f442003-07-28 09:56:35 +00009725 mpath = mpathset() ? mpathval() : mailval();
9726 for (mtp = mailtime; mtp < mailtime + MAXMBOXES; mtp++) {
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02009727 p = path_advance(&mpath, nullstr);
Eric Andersencb57d552001-06-28 07:25:16 +00009728 if (p == NULL)
9729 break;
9730 if (*p == '\0')
9731 continue;
Denis Vlasenkof7d56652008-03-25 05:51:41 +00009732 for (q = p; *q; q++)
9733 continue;
Denis Vlasenkoa7189f02006-11-17 20:29:00 +00009734#if DEBUG
Eric Andersencb57d552001-06-28 07:25:16 +00009735 if (q[-1] != '/')
9736 abort();
9737#endif
Eric Andersenc470f442003-07-28 09:56:35 +00009738 q[-1] = '\0'; /* delete trailing '/' */
9739 if (stat(p, &statb) < 0) {
9740 *mtp = 0;
9741 continue;
Eric Andersencb57d552001-06-28 07:25:16 +00009742 }
Eric Andersenc470f442003-07-28 09:56:35 +00009743 if (!mail_var_path_changed && statb.st_mtime != *mtp) {
9744 fprintf(
9745 stderr, snlfmt,
9746 pathopt ? pathopt : "you have mail"
9747 );
9748 }
9749 *mtp = statb.st_mtime;
Eric Andersencb57d552001-06-28 07:25:16 +00009750 }
Eric Andersenc470f442003-07-28 09:56:35 +00009751 mail_var_path_changed = 0;
Eric Andersencb57d552001-06-28 07:25:16 +00009752 popstackmark(&smark);
9753}
Eric Andersencb57d552001-06-28 07:25:16 +00009754
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009755static void FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00009756changemail(const char *val UNUSED_PARAM)
Eric Andersenc470f442003-07-28 09:56:35 +00009757{
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +00009758 mail_var_path_changed = 1;
Eric Andersenc470f442003-07-28 09:56:35 +00009759}
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00009760
Denis Vlasenko131ae172007-02-18 13:00:19 +00009761#endif /* ASH_MAIL */
Eric Andersenc470f442003-07-28 09:56:35 +00009762
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00009763
9764/* ============ ??? */
9765
Eric Andersencb57d552001-06-28 07:25:16 +00009766/*
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009767 * Set the shell parameters.
Eric Andersencb57d552001-06-28 07:25:16 +00009768 */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009769static void
9770setparam(char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +00009771{
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009772 char **newparam;
9773 char **ap;
9774 int nparam;
Eric Andersencb57d552001-06-28 07:25:16 +00009775
Denis Vlasenkof7d56652008-03-25 05:51:41 +00009776 for (nparam = 0; argv[nparam]; nparam++)
9777 continue;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009778 ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
9779 while (*argv) {
9780 *ap++ = ckstrdup(*argv++);
Eric Andersencb57d552001-06-28 07:25:16 +00009781 }
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009782 *ap = NULL;
9783 freeparam(&shellparam);
Denis Vlasenko01631112007-12-16 17:20:38 +00009784 shellparam.malloced = 1;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009785 shellparam.nparam = nparam;
9786 shellparam.p = newparam;
9787#if ENABLE_ASH_GETOPTS
9788 shellparam.optind = 1;
9789 shellparam.optoff = -1;
9790#endif
Eric Andersencb57d552001-06-28 07:25:16 +00009791}
9792
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00009793/*
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009794 * Process shell options. The global variable argptr contains a pointer
9795 * to the argument list; we advance it past the options.
Denis Vlasenko94e87bc2008-02-14 16:51:58 +00009796 *
9797 * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
9798 * For a non-interactive shell, an error condition encountered
9799 * by a special built-in ... shall cause the shell to write a diagnostic message
9800 * to standard error and exit as shown in the following table:
Denis Vlasenko56244732008-02-17 15:14:04 +00009801 * Error Special Built-In
Denis Vlasenko94e87bc2008-02-14 16:51:58 +00009802 * ...
9803 * Utility syntax error (option or operand error) Shall exit
9804 * ...
9805 * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
9806 * we see that bash does not do that (set "finishes" with error code 1 instead,
9807 * and shell continues), and people rely on this behavior!
9808 * Testcase:
9809 * set -o barfoo 2>/dev/null
9810 * echo $?
9811 *
9812 * Oh well. Let's mimic that.
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00009813 */
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009814static int
Denis Vlasenkodddfaff2008-05-06 15:30:27 +00009815plus_minus_o(char *name, int val)
Eric Andersen62483552001-07-10 06:09:16 +00009816{
9817 int i;
9818
Denis Vlasenkoa624c112007-02-19 22:45:43 +00009819 if (name) {
9820 for (i = 0; i < NOPTS; i++) {
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00009821 if (strcmp(name, optnames(i)) == 0) {
Eric Andersenc470f442003-07-28 09:56:35 +00009822 optlist[i] = val;
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009823 return 0;
Eric Andersen62483552001-07-10 06:09:16 +00009824 }
Denis Vlasenkoa624c112007-02-19 22:45:43 +00009825 }
Denis Vlasenkodddfaff2008-05-06 15:30:27 +00009826 ash_msg("illegal option %co %s", val ? '-' : '+', name);
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009827 return 1;
Eric Andersen62483552001-07-10 06:09:16 +00009828 }
Denis Vlasenko6b06cb82008-05-15 21:30:45 +00009829 for (i = 0; i < NOPTS; i++) {
Denis Vlasenkodddfaff2008-05-06 15:30:27 +00009830 if (val) {
9831 out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
9832 } else {
9833 out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
9834 }
Denis Vlasenko6b06cb82008-05-15 21:30:45 +00009835 }
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009836 return 0;
Eric Andersen62483552001-07-10 06:09:16 +00009837}
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009838static void
9839setoption(int flag, int val)
9840{
9841 int i;
9842
9843 for (i = 0; i < NOPTS; i++) {
9844 if (optletters(i) == flag) {
9845 optlist[i] = val;
9846 return;
9847 }
9848 }
Denis Vlasenkodddfaff2008-05-06 15:30:27 +00009849 ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009850 /* NOTREACHED */
9851}
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009852static int
Eric Andersenc470f442003-07-28 09:56:35 +00009853options(int cmdline)
Eric Andersencb57d552001-06-28 07:25:16 +00009854{
9855 char *p;
9856 int val;
9857 int c;
9858
9859 if (cmdline)
9860 minusc = NULL;
9861 while ((p = *argptr) != NULL) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009862 c = *p++;
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +00009863 if (c != '-' && c != '+')
9864 break;
9865 argptr++;
9866 val = 0; /* val = 0 if c == '+' */
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009867 if (c == '-') {
Eric Andersencb57d552001-06-28 07:25:16 +00009868 val = 1;
Denis Vlasenko9f739442006-12-16 23:49:13 +00009869 if (p[0] == '\0' || LONE_DASH(p)) {
Eric Andersen2870d962001-07-02 17:27:21 +00009870 if (!cmdline) {
9871 /* "-" means turn off -x and -v */
9872 if (p[0] == '\0')
9873 xflag = vflag = 0;
9874 /* "--" means reset params */
9875 else if (*argptr == NULL)
Eric Andersencb57d552001-06-28 07:25:16 +00009876 setparam(argptr);
Eric Andersen2870d962001-07-02 17:27:21 +00009877 }
Eric Andersenc470f442003-07-28 09:56:35 +00009878 break; /* "-" or "--" terminates options */
Eric Andersencb57d552001-06-28 07:25:16 +00009879 }
Eric Andersencb57d552001-06-28 07:25:16 +00009880 }
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +00009881 /* first char was + or - */
Eric Andersencb57d552001-06-28 07:25:16 +00009882 while ((c = *p++) != '\0') {
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +00009883 /* bash 3.2 indeed handles -c CMD and +c CMD the same */
Eric Andersencb57d552001-06-28 07:25:16 +00009884 if (c == 'c' && cmdline) {
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +00009885 minusc = p; /* command is after shell args */
Eric Andersencb57d552001-06-28 07:25:16 +00009886 } else if (c == 'o') {
Denis Vlasenkodddfaff2008-05-06 15:30:27 +00009887 if (plus_minus_o(*argptr, val)) {
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009888 /* it already printed err message */
9889 return 1; /* error */
9890 }
Eric Andersencb57d552001-06-28 07:25:16 +00009891 if (*argptr)
9892 argptr++;
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +00009893 } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
9894 isloginsh = 1;
9895 /* bash does not accept +-login, we also won't */
9896 } else if (cmdline && val && (c == '-')) { /* long options */
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00009897 if (strcmp(p, "login") == 0)
Robert Griebl64f70cc2002-05-14 23:22:06 +00009898 isloginsh = 1;
9899 break;
Eric Andersencb57d552001-06-28 07:25:16 +00009900 } else {
9901 setoption(c, val);
9902 }
9903 }
9904 }
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009905 return 0;
Eric Andersencb57d552001-06-28 07:25:16 +00009906}
9907
Eric Andersencb57d552001-06-28 07:25:16 +00009908/*
Eric Andersencb57d552001-06-28 07:25:16 +00009909 * The shift builtin command.
9910 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009911static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00009912shiftcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +00009913{
9914 int n;
9915 char **ap1, **ap2;
9916
9917 n = 1;
Denis Vlasenko68404f12008-03-17 09:00:54 +00009918 if (argv[1])
Eric Andersencb57d552001-06-28 07:25:16 +00009919 n = number(argv[1]);
9920 if (n > shellparam.nparam)
Denis Vlasenkoc90e1be2008-07-30 15:35:05 +00009921 n = 0; /* bash compat, was = shellparam.nparam; */
Denis Vlasenkob012b102007-02-19 22:43:01 +00009922 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +00009923 shellparam.nparam -= n;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00009924 for (ap1 = shellparam.p; --n >= 0; ap1++) {
Denis Vlasenko01631112007-12-16 17:20:38 +00009925 if (shellparam.malloced)
Denis Vlasenkob012b102007-02-19 22:43:01 +00009926 free(*ap1);
Eric Andersencb57d552001-06-28 07:25:16 +00009927 }
9928 ap2 = shellparam.p;
Denis Vlasenkof7d56652008-03-25 05:51:41 +00009929 while ((*ap2++ = *ap1++) != NULL)
9930 continue;
Denis Vlasenko131ae172007-02-18 13:00:19 +00009931#if ENABLE_ASH_GETOPTS
Eric Andersencb57d552001-06-28 07:25:16 +00009932 shellparam.optind = 1;
9933 shellparam.optoff = -1;
Eric Andersenc470f442003-07-28 09:56:35 +00009934#endif
Denis Vlasenkob012b102007-02-19 22:43:01 +00009935 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00009936 return 0;
9937}
9938
Eric Andersencb57d552001-06-28 07:25:16 +00009939/*
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009940 * POSIX requires that 'set' (but not export or readonly) output the
9941 * variables in lexicographic order - by the locale's collating order (sigh).
9942 * Maybe we could keep them in an ordered balanced binary tree
9943 * instead of hashed lists.
9944 * For now just roll 'em through qsort for printing...
9945 */
9946static int
9947showvars(const char *sep_prefix, int on, int off)
9948{
9949 const char *sep;
9950 char **ep, **epend;
9951
9952 ep = listvars(on, off, &epend);
9953 qsort(ep, epend - ep, sizeof(char *), vpcmp);
9954
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00009955 sep = *sep_prefix ? " " : sep_prefix;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009956
9957 for (; ep < epend; ep++) {
9958 const char *p;
9959 const char *q;
9960
9961 p = strchrnul(*ep, '=');
9962 q = nullstr;
9963 if (*p)
9964 q = single_quote(++p);
9965 out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
9966 }
9967 return 0;
9968}
9969
9970/*
Eric Andersencb57d552001-06-28 07:25:16 +00009971 * The set command builtin.
9972 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009973static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00009974setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersencb57d552001-06-28 07:25:16 +00009975{
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009976 int retval;
9977
Denis Vlasenko68404f12008-03-17 09:00:54 +00009978 if (!argv[1])
Eric Andersenc470f442003-07-28 09:56:35 +00009979 return showvars(nullstr, 0, VUNSET);
Denis Vlasenkob012b102007-02-19 22:43:01 +00009980 INT_OFF;
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009981 retval = 1;
9982 if (!options(0)) { /* if no parse error... */
9983 retval = 0;
9984 optschanged();
9985 if (*argptr != NULL) {
9986 setparam(argptr);
9987 }
Eric Andersencb57d552001-06-28 07:25:16 +00009988 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00009989 INT_ON;
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009990 return retval;
Eric Andersencb57d552001-06-28 07:25:16 +00009991}
9992
Denis Vlasenko131ae172007-02-18 13:00:19 +00009993#if ENABLE_ASH_RANDOM_SUPPORT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009994static void FAST_FUNC
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00009995change_random(const char *value)
Eric Andersenef02f822004-03-11 13:34:24 +00009996{
Denis Vlasenko448d30e2008-06-27 00:24:11 +00009997 /* Galois LFSR parameter */
9998 /* Taps at 32 31 29 1: */
9999 enum { MASK = 0x8000000b };
10000 /* Another example - taps at 32 31 30 10: */
10001 /* MASK = 0x00400007 */
10002
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010003 if (value == NULL) {
Eric Andersen16767e22004-03-16 05:14:10 +000010004 /* "get", generate */
Denis Vlasenko448d30e2008-06-27 00:24:11 +000010005 uint32_t t;
Eric Andersen16767e22004-03-16 05:14:10 +000010006
Denis Vlasenko448d30e2008-06-27 00:24:11 +000010007 /* LCG has period of 2^32 and alternating lowest bit */
10008 random_LCG = 1664525 * random_LCG + 1013904223;
10009 /* Galois LFSR has period of 2^32-1 = 3 * 5 * 17 * 257 * 65537 */
10010 t = (random_galois_LFSR << 1);
10011 if (random_galois_LFSR < 0) /* if we just shifted 1 out of msb... */
10012 t ^= MASK;
10013 random_galois_LFSR = t;
Denis Vlasenkoce13b762008-06-29 02:25:53 +000010014 /* Both are weak, combining them gives better randomness
Denis Vlasenko448d30e2008-06-27 00:24:11 +000010015 * and ~2^64 period. & 0x7fff is probably bash compat
Denis Vlasenkoce13b762008-06-29 02:25:53 +000010016 * for $RANDOM range. Combining with subtraction is
10017 * just for fun. + and ^ would work equally well. */
10018 t = (t - random_LCG) & 0x7fff;
Eric Andersen16767e22004-03-16 05:14:10 +000010019 /* set without recursion */
Denis Vlasenko448d30e2008-06-27 00:24:11 +000010020 setvar(vrandom.text, utoa(t), VNOFUNC);
Eric Andersen16767e22004-03-16 05:14:10 +000010021 vrandom.flags &= ~VNOFUNC;
10022 } else {
10023 /* set/reset */
Denis Vlasenko448d30e2008-06-27 00:24:11 +000010024 random_galois_LFSR = random_LCG = strtoul(value, (char **)NULL, 10);
Eric Andersen16767e22004-03-16 05:14:10 +000010025 }
Eric Andersenef02f822004-03-11 13:34:24 +000010026}
Eric Andersen16767e22004-03-16 05:14:10 +000010027#endif
10028
Denis Vlasenko131ae172007-02-18 13:00:19 +000010029#if ENABLE_ASH_GETOPTS
Eric Andersencb57d552001-06-28 07:25:16 +000010030static int
Eric Andersenc470f442003-07-28 09:56:35 +000010031getopts(char *optstr, char *optvar, char **optfirst, int *param_optind, int *optoff)
Eric Andersencb57d552001-06-28 07:25:16 +000010032{
10033 char *p, *q;
10034 char c = '?';
10035 int done = 0;
10036 int err = 0;
Eric Andersena48b0a32003-10-22 10:56:47 +000010037 char s[12];
10038 char **optnext;
Eric Andersencb57d552001-06-28 07:25:16 +000010039
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010040 if (*param_optind < 1)
Eric Andersena48b0a32003-10-22 10:56:47 +000010041 return 1;
10042 optnext = optfirst + *param_optind - 1;
10043
Denis Vlasenko6b06cb82008-05-15 21:30:45 +000010044 if (*param_optind <= 1 || *optoff < 0 || (int)strlen(optnext[-1]) < *optoff)
Eric Andersencb57d552001-06-28 07:25:16 +000010045 p = NULL;
10046 else
Eric Andersena48b0a32003-10-22 10:56:47 +000010047 p = optnext[-1] + *optoff;
Eric Andersencb57d552001-06-28 07:25:16 +000010048 if (p == NULL || *p == '\0') {
10049 /* Current word is done, advance */
Eric Andersencb57d552001-06-28 07:25:16 +000010050 p = *optnext;
10051 if (p == NULL || *p != '-' || *++p == '\0') {
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010052 atend:
Eric Andersencb57d552001-06-28 07:25:16 +000010053 p = NULL;
10054 done = 1;
10055 goto out;
10056 }
10057 optnext++;
Denis Vlasenko9f739442006-12-16 23:49:13 +000010058 if (LONE_DASH(p)) /* check for "--" */
Eric Andersencb57d552001-06-28 07:25:16 +000010059 goto atend;
10060 }
10061
10062 c = *p++;
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +000010063 for (q = optstr; *q != c;) {
Eric Andersencb57d552001-06-28 07:25:16 +000010064 if (*q == '\0') {
10065 if (optstr[0] == ':') {
10066 s[0] = c;
10067 s[1] = '\0';
10068 err |= setvarsafe("OPTARG", s, 0);
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010069 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000010070 fprintf(stderr, "Illegal option -%c\n", c);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010071 unsetvar("OPTARG");
Eric Andersencb57d552001-06-28 07:25:16 +000010072 }
10073 c = '?';
Eric Andersenc470f442003-07-28 09:56:35 +000010074 goto out;
Eric Andersencb57d552001-06-28 07:25:16 +000010075 }
10076 if (*++q == ':')
10077 q++;
10078 }
10079
10080 if (*++q == ':') {
10081 if (*p == '\0' && (p = *optnext) == NULL) {
10082 if (optstr[0] == ':') {
10083 s[0] = c;
10084 s[1] = '\0';
10085 err |= setvarsafe("OPTARG", s, 0);
10086 c = ':';
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010087 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000010088 fprintf(stderr, "No arg for -%c option\n", c);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010089 unsetvar("OPTARG");
Eric Andersencb57d552001-06-28 07:25:16 +000010090 c = '?';
10091 }
Eric Andersenc470f442003-07-28 09:56:35 +000010092 goto out;
Eric Andersencb57d552001-06-28 07:25:16 +000010093 }
10094
10095 if (p == *optnext)
10096 optnext++;
Eric Andersenc470f442003-07-28 09:56:35 +000010097 err |= setvarsafe("OPTARG", p, 0);
Eric Andersencb57d552001-06-28 07:25:16 +000010098 p = NULL;
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010099 } else
Eric Andersenc470f442003-07-28 09:56:35 +000010100 err |= setvarsafe("OPTARG", nullstr, 0);
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010101 out:
Eric Andersencb57d552001-06-28 07:25:16 +000010102 *optoff = p ? p - *(optnext - 1) : -1;
Eric Andersenc470f442003-07-28 09:56:35 +000010103 *param_optind = optnext - optfirst + 1;
10104 fmtstr(s, sizeof(s), "%d", *param_optind);
Eric Andersencb57d552001-06-28 07:25:16 +000010105 err |= setvarsafe("OPTIND", s, VNOFUNC);
10106 s[0] = c;
10107 s[1] = '\0';
10108 err |= setvarsafe(optvar, s, 0);
10109 if (err) {
Eric Andersenc470f442003-07-28 09:56:35 +000010110 *param_optind = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010111 *optoff = -1;
Denis Vlasenkob012b102007-02-19 22:43:01 +000010112 flush_stdout_stderr();
10113 raise_exception(EXERROR);
Eric Andersencb57d552001-06-28 07:25:16 +000010114 }
10115 return done;
10116}
Eric Andersenc470f442003-07-28 09:56:35 +000010117
10118/*
10119 * The getopts builtin. Shellparam.optnext points to the next argument
10120 * to be processed. Shellparam.optptr points to the next character to
10121 * be processed in the current argument. If shellparam.optnext is NULL,
10122 * then it's the first time getopts has been called.
10123 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010124static int FAST_FUNC
Eric Andersenc470f442003-07-28 09:56:35 +000010125getoptscmd(int argc, char **argv)
10126{
10127 char **optbase;
10128
10129 if (argc < 3)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +000010130 ash_msg_and_raise_error("usage: getopts optstring var [arg]");
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010131 if (argc == 3) {
Eric Andersenc470f442003-07-28 09:56:35 +000010132 optbase = shellparam.p;
10133 if (shellparam.optind > shellparam.nparam + 1) {
10134 shellparam.optind = 1;
10135 shellparam.optoff = -1;
10136 }
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010137 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000010138 optbase = &argv[3];
10139 if (shellparam.optind > argc - 2) {
10140 shellparam.optind = 1;
10141 shellparam.optoff = -1;
10142 }
10143 }
10144
10145 return getopts(argv[1], argv[2], optbase, &shellparam.optind,
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010146 &shellparam.optoff);
Eric Andersenc470f442003-07-28 09:56:35 +000010147}
Denis Vlasenko131ae172007-02-18 13:00:19 +000010148#endif /* ASH_GETOPTS */
Eric Andersencb57d552001-06-28 07:25:16 +000010149
Eric Andersencb57d552001-06-28 07:25:16 +000010150
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010151/* ============ Shell parser */
Eric Andersencb57d552001-06-28 07:25:16 +000010152
Denis Vlasenkob07a4962008-06-22 13:16:23 +000010153struct heredoc {
10154 struct heredoc *next; /* next here document in list */
10155 union node *here; /* redirection node */
10156 char *eofmark; /* string indicating end of input */
10157 smallint striptabs; /* if set, strip leading tabs */
10158};
10159
10160static smallint tokpushback; /* last token pushed back */
10161static smallint parsebackquote; /* nonzero if we are inside backquotes */
10162static smallint quoteflag; /* set if (part of) last token was quoted */
10163static token_id_t lasttoken; /* last token read (integer id Txxx) */
10164static struct heredoc *heredoclist; /* list of here documents to read */
10165static char *wordtext; /* text of last word returned by readtoken */
10166static struct nodelist *backquotelist;
10167static union node *redirnode;
10168static struct heredoc *heredoc;
Denis Vlasenko99eb8502007-02-23 21:09:49 +000010169
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010170/*
10171 * Called when an unexpected token is read during the parse. The argument
10172 * is the token that is expected, or -1 if more than one type of token can
10173 * occur at this point.
10174 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000010175static void raise_error_unexpected_syntax(int) NORETURN;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010176static void
10177raise_error_unexpected_syntax(int token)
10178{
10179 char msg[64];
10180 int l;
10181
Denis Vlasenko7b2294e2008-11-28 03:50:46 +000010182 l = sprintf(msg, "unexpected %s", tokname(lasttoken));
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010183 if (token >= 0)
10184 sprintf(msg + l, " (expecting %s)", tokname(token));
10185 raise_error_syntax(msg);
10186 /* NOTREACHED */
10187}
Eric Andersencb57d552001-06-28 07:25:16 +000010188
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010189#define EOFMARKLEN 79
Eric Andersencb57d552001-06-28 07:25:16 +000010190
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010191/* parsing is heavily cross-recursive, need these forward decls */
10192static union node *andor(void);
10193static union node *pipeline(void);
10194static union node *parse_command(void);
10195static void parseheredoc(void);
10196static char peektoken(void);
10197static int readtoken(void);
Eric Andersencb57d552001-06-28 07:25:16 +000010198
Eric Andersenc470f442003-07-28 09:56:35 +000010199static union node *
10200list(int nlflag)
Eric Andersencb57d552001-06-28 07:25:16 +000010201{
10202 union node *n1, *n2, *n3;
10203 int tok;
10204
Eric Andersenc470f442003-07-28 09:56:35 +000010205 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10206 if (nlflag == 2 && peektoken())
Eric Andersencb57d552001-06-28 07:25:16 +000010207 return NULL;
10208 n1 = NULL;
10209 for (;;) {
10210 n2 = andor();
10211 tok = readtoken();
10212 if (tok == TBACKGND) {
Eric Andersenc470f442003-07-28 09:56:35 +000010213 if (n2->type == NPIPE) {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +000010214 n2->npipe.pipe_backgnd = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010215 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000010216 if (n2->type != NREDIR) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010217 n3 = stzalloc(sizeof(struct nredir));
Eric Andersenc470f442003-07-28 09:56:35 +000010218 n3->nredir.n = n2;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010219 /*n3->nredir.redirect = NULL; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000010220 n2 = n3;
10221 }
10222 n2->type = NBACKGND;
Eric Andersencb57d552001-06-28 07:25:16 +000010223 }
10224 }
10225 if (n1 == NULL) {
10226 n1 = n2;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010227 } else {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010228 n3 = stzalloc(sizeof(struct nbinary));
Eric Andersencb57d552001-06-28 07:25:16 +000010229 n3->type = NSEMI;
10230 n3->nbinary.ch1 = n1;
10231 n3->nbinary.ch2 = n2;
10232 n1 = n3;
10233 }
10234 switch (tok) {
10235 case TBACKGND:
10236 case TSEMI:
10237 tok = readtoken();
10238 /* fall through */
10239 case TNL:
10240 if (tok == TNL) {
10241 parseheredoc();
Eric Andersenc470f442003-07-28 09:56:35 +000010242 if (nlflag == 1)
Eric Andersencb57d552001-06-28 07:25:16 +000010243 return n1;
10244 } else {
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010245 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010246 }
Eric Andersenc470f442003-07-28 09:56:35 +000010247 checkkwd = CHKNL | CHKKWD | CHKALIAS;
Manuel Novoa III 16815d42001-08-10 19:36:07 +000010248 if (peektoken())
Eric Andersencb57d552001-06-28 07:25:16 +000010249 return n1;
10250 break;
10251 case TEOF:
10252 if (heredoclist)
10253 parseheredoc();
10254 else
Eric Andersenc470f442003-07-28 09:56:35 +000010255 pungetc(); /* push back EOF on input */
Eric Andersencb57d552001-06-28 07:25:16 +000010256 return n1;
10257 default:
Eric Andersenc470f442003-07-28 09:56:35 +000010258 if (nlflag == 1)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010259 raise_error_unexpected_syntax(-1);
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010260 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010261 return n1;
10262 }
10263 }
10264}
10265
Eric Andersenc470f442003-07-28 09:56:35 +000010266static union node *
10267andor(void)
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010268{
Eric Andersencb57d552001-06-28 07:25:16 +000010269 union node *n1, *n2, *n3;
10270 int t;
10271
Eric Andersencb57d552001-06-28 07:25:16 +000010272 n1 = pipeline();
10273 for (;;) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010274 t = readtoken();
10275 if (t == TAND) {
Eric Andersencb57d552001-06-28 07:25:16 +000010276 t = NAND;
10277 } else if (t == TOR) {
10278 t = NOR;
10279 } else {
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010280 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010281 return n1;
10282 }
Eric Andersenc470f442003-07-28 09:56:35 +000010283 checkkwd = CHKNL | CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010284 n2 = pipeline();
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010285 n3 = stzalloc(sizeof(struct nbinary));
Eric Andersencb57d552001-06-28 07:25:16 +000010286 n3->type = t;
10287 n3->nbinary.ch1 = n1;
10288 n3->nbinary.ch2 = n2;
10289 n1 = n3;
10290 }
10291}
10292
Eric Andersenc470f442003-07-28 09:56:35 +000010293static union node *
10294pipeline(void)
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010295{
Eric Andersencb57d552001-06-28 07:25:16 +000010296 union node *n1, *n2, *pipenode;
10297 struct nodelist *lp, *prev;
10298 int negate;
10299
10300 negate = 0;
10301 TRACE(("pipeline: entered\n"));
10302 if (readtoken() == TNOT) {
10303 negate = !negate;
Eric Andersenc470f442003-07-28 09:56:35 +000010304 checkkwd = CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010305 } else
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010306 tokpushback = 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010307 n1 = parse_command();
Eric Andersencb57d552001-06-28 07:25:16 +000010308 if (readtoken() == TPIPE) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010309 pipenode = stzalloc(sizeof(struct npipe));
Eric Andersencb57d552001-06-28 07:25:16 +000010310 pipenode->type = NPIPE;
Denis Vlasenko2dc240c2008-07-24 06:07:50 +000010311 /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010312 lp = stzalloc(sizeof(struct nodelist));
Eric Andersencb57d552001-06-28 07:25:16 +000010313 pipenode->npipe.cmdlist = lp;
10314 lp->n = n1;
10315 do {
10316 prev = lp;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010317 lp = stzalloc(sizeof(struct nodelist));
Eric Andersenc470f442003-07-28 09:56:35 +000010318 checkkwd = CHKNL | CHKKWD | CHKALIAS;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010319 lp->n = parse_command();
Eric Andersencb57d552001-06-28 07:25:16 +000010320 prev->next = lp;
10321 } while (readtoken() == TPIPE);
10322 lp->next = NULL;
10323 n1 = pipenode;
10324 }
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010325 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010326 if (negate) {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010327 n2 = stzalloc(sizeof(struct nnot));
Eric Andersencb57d552001-06-28 07:25:16 +000010328 n2->type = NNOT;
10329 n2->nnot.com = n1;
10330 return n2;
Denis Vlasenko2da584f2007-02-19 22:44:05 +000010331 }
10332 return n1;
Eric Andersencb57d552001-06-28 07:25:16 +000010333}
10334
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010335static union node *
10336makename(void)
10337{
10338 union node *n;
10339
Denis Vlasenko597906c2008-02-20 16:38:54 +000010340 n = stzalloc(sizeof(struct narg));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010341 n->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010342 /*n->narg.next = NULL; - stzalloc did it */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010343 n->narg.text = wordtext;
10344 n->narg.backquote = backquotelist;
10345 return n;
10346}
10347
10348static void
10349fixredir(union node *n, const char *text, int err)
10350{
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000010351 int fd;
10352
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010353 TRACE(("Fix redir %s %d\n", text, err));
10354 if (!err)
10355 n->ndup.vname = NULL;
10356
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000010357 fd = bb_strtou(text, NULL, 10);
10358 if (!errno && fd >= 0)
10359 n->ndup.dupfd = fd;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010360 else if (LONE_DASH(text))
10361 n->ndup.dupfd = -1;
10362 else {
10363 if (err)
Denis Vlasenko559691a2008-10-05 18:39:31 +000010364 raise_error_syntax("bad fd number");
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010365 n->ndup.vname = makename();
10366 }
10367}
10368
10369/*
10370 * Returns true if the text contains nothing to expand (no dollar signs
10371 * or backquotes).
10372 */
10373static int
Denis Vlasenko68819d12008-12-15 11:26:36 +000010374noexpand(const char *text)
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010375{
Denis Vlasenko68819d12008-12-15 11:26:36 +000010376 const char *p;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010377 char c;
10378
10379 p = text;
10380 while ((c = *p++) != '\0') {
10381 if (c == CTLQUOTEMARK)
10382 continue;
10383 if (c == CTLESC)
10384 p++;
Denis Vlasenko68819d12008-12-15 11:26:36 +000010385 else if (SIT((signed char)c, BASESYNTAX) == CCTL)
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010386 return 0;
10387 }
10388 return 1;
10389}
10390
10391static void
10392parsefname(void)
10393{
10394 union node *n = redirnode;
10395
10396 if (readtoken() != TWORD)
10397 raise_error_unexpected_syntax(-1);
10398 if (n->type == NHERE) {
10399 struct heredoc *here = heredoc;
10400 struct heredoc *p;
10401 int i;
10402
10403 if (quoteflag == 0)
10404 n->type = NXHERE;
10405 TRACE(("Here document %d\n", n->type));
10406 if (!noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
Denis Vlasenko559691a2008-10-05 18:39:31 +000010407 raise_error_syntax("illegal eof marker for << redirection");
Denys Vlasenkob6c84342009-08-29 20:23:20 +020010408 rmescapes(wordtext, 0);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010409 here->eofmark = wordtext;
10410 here->next = NULL;
10411 if (heredoclist == NULL)
10412 heredoclist = here;
10413 else {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010414 for (p = heredoclist; p->next; p = p->next)
10415 continue;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010416 p->next = here;
10417 }
10418 } else if (n->type == NTOFD || n->type == NFROMFD) {
10419 fixredir(n, wordtext, 0);
10420 } else {
10421 n->nfile.fname = makename();
10422 }
10423}
Eric Andersencb57d552001-06-28 07:25:16 +000010424
Eric Andersenc470f442003-07-28 09:56:35 +000010425static union node *
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010426simplecmd(void)
10427{
10428 union node *args, **app;
10429 union node *n = NULL;
10430 union node *vars, **vpp;
10431 union node **rpp, *redir;
10432 int savecheckkwd;
Denis Vlasenko80591b02008-03-25 07:49:43 +000010433#if ENABLE_ASH_BASH_COMPAT
10434 smallint double_brackets_flag = 0;
10435#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010436
10437 args = NULL;
10438 app = &args;
10439 vars = NULL;
10440 vpp = &vars;
10441 redir = NULL;
10442 rpp = &redir;
10443
10444 savecheckkwd = CHKALIAS;
10445 for (;;) {
Denis Vlasenko80591b02008-03-25 07:49:43 +000010446 int t;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010447 checkkwd = savecheckkwd;
Denis Vlasenko80591b02008-03-25 07:49:43 +000010448 t = readtoken();
10449 switch (t) {
10450#if ENABLE_ASH_BASH_COMPAT
10451 case TAND: /* "&&" */
10452 case TOR: /* "||" */
10453 if (!double_brackets_flag) {
10454 tokpushback = 1;
10455 goto out;
10456 }
10457 wordtext = (char *) (t == TAND ? "-a" : "-o");
10458#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010459 case TWORD:
Denis Vlasenko597906c2008-02-20 16:38:54 +000010460 n = stzalloc(sizeof(struct narg));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010461 n->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010462 /*n->narg.next = NULL; - stzalloc did it */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010463 n->narg.text = wordtext;
Denis Vlasenko80591b02008-03-25 07:49:43 +000010464#if ENABLE_ASH_BASH_COMPAT
10465 if (strcmp("[[", wordtext) == 0)
10466 double_brackets_flag = 1;
10467 else if (strcmp("]]", wordtext) == 0)
10468 double_brackets_flag = 0;
10469#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010470 n->narg.backquote = backquotelist;
10471 if (savecheckkwd && isassignment(wordtext)) {
10472 *vpp = n;
10473 vpp = &n->narg.next;
10474 } else {
10475 *app = n;
10476 app = &n->narg.next;
10477 savecheckkwd = 0;
10478 }
10479 break;
10480 case TREDIR:
10481 *rpp = n = redirnode;
10482 rpp = &n->nfile.next;
10483 parsefname(); /* read name of redirection file */
10484 break;
10485 case TLP:
10486 if (args && app == &args->narg.next
10487 && !vars && !redir
10488 ) {
10489 struct builtincmd *bcmd;
10490 const char *name;
10491
10492 /* We have a function */
10493 if (readtoken() != TRP)
10494 raise_error_unexpected_syntax(TRP);
10495 name = n->narg.text;
10496 if (!goodname(name)
10497 || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
10498 ) {
Denis Vlasenko559691a2008-10-05 18:39:31 +000010499 raise_error_syntax("bad function name");
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010500 }
10501 n->type = NDEFUN;
10502 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10503 n->narg.next = parse_command();
10504 return n;
10505 }
10506 /* fall through */
10507 default:
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010508 tokpushback = 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010509 goto out;
10510 }
10511 }
10512 out:
10513 *app = NULL;
10514 *vpp = NULL;
10515 *rpp = NULL;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010516 n = stzalloc(sizeof(struct ncmd));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010517 n->type = NCMD;
10518 n->ncmd.args = args;
10519 n->ncmd.assign = vars;
10520 n->ncmd.redirect = redir;
10521 return n;
10522}
10523
10524static union node *
10525parse_command(void)
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010526{
Eric Andersencb57d552001-06-28 07:25:16 +000010527 union node *n1, *n2;
10528 union node *ap, **app;
10529 union node *cp, **cpp;
10530 union node *redir, **rpp;
Eric Andersenc470f442003-07-28 09:56:35 +000010531 union node **rpp2;
Eric Andersencb57d552001-06-28 07:25:16 +000010532 int t;
10533
10534 redir = NULL;
Eric Andersenc470f442003-07-28 09:56:35 +000010535 rpp2 = &redir;
Eric Andersen88cec252001-09-06 17:35:20 +000010536
Eric Andersencb57d552001-06-28 07:25:16 +000010537 switch (readtoken()) {
Eric Andersenc470f442003-07-28 09:56:35 +000010538 default:
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010539 raise_error_unexpected_syntax(-1);
Eric Andersenc470f442003-07-28 09:56:35 +000010540 /* NOTREACHED */
Eric Andersencb57d552001-06-28 07:25:16 +000010541 case TIF:
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010542 n1 = stzalloc(sizeof(struct nif));
Eric Andersencb57d552001-06-28 07:25:16 +000010543 n1->type = NIF;
10544 n1->nif.test = list(0);
10545 if (readtoken() != TTHEN)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010546 raise_error_unexpected_syntax(TTHEN);
Eric Andersencb57d552001-06-28 07:25:16 +000010547 n1->nif.ifpart = list(0);
10548 n2 = n1;
10549 while (readtoken() == TELIF) {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010550 n2->nif.elsepart = stzalloc(sizeof(struct nif));
Eric Andersencb57d552001-06-28 07:25:16 +000010551 n2 = n2->nif.elsepart;
10552 n2->type = NIF;
10553 n2->nif.test = list(0);
10554 if (readtoken() != TTHEN)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010555 raise_error_unexpected_syntax(TTHEN);
Eric Andersencb57d552001-06-28 07:25:16 +000010556 n2->nif.ifpart = list(0);
10557 }
10558 if (lasttoken == TELSE)
10559 n2->nif.elsepart = list(0);
10560 else {
10561 n2->nif.elsepart = NULL;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010562 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010563 }
Eric Andersenc470f442003-07-28 09:56:35 +000010564 t = TFI;
Eric Andersencb57d552001-06-28 07:25:16 +000010565 break;
10566 case TWHILE:
Eric Andersenc470f442003-07-28 09:56:35 +000010567 case TUNTIL: {
Eric Andersencb57d552001-06-28 07:25:16 +000010568 int got;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010569 n1 = stzalloc(sizeof(struct nbinary));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010570 n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
Eric Andersencb57d552001-06-28 07:25:16 +000010571 n1->nbinary.ch1 = list(0);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010572 got = readtoken();
10573 if (got != TDO) {
Denis Vlasenko131ae172007-02-18 13:00:19 +000010574 TRACE(("expecting DO got %s %s\n", tokname(got),
10575 got == TWORD ? wordtext : ""));
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010576 raise_error_unexpected_syntax(TDO);
Eric Andersencb57d552001-06-28 07:25:16 +000010577 }
10578 n1->nbinary.ch2 = list(0);
Eric Andersenc470f442003-07-28 09:56:35 +000010579 t = TDONE;
Eric Andersencb57d552001-06-28 07:25:16 +000010580 break;
10581 }
10582 case TFOR:
Denis Vlasenko2dc240c2008-07-24 06:07:50 +000010583 if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
Denis Vlasenko559691a2008-10-05 18:39:31 +000010584 raise_error_syntax("bad for loop variable");
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010585 n1 = stzalloc(sizeof(struct nfor));
Eric Andersencb57d552001-06-28 07:25:16 +000010586 n1->type = NFOR;
10587 n1->nfor.var = wordtext;
Eric Andersenc470f442003-07-28 09:56:35 +000010588 checkkwd = CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010589 if (readtoken() == TIN) {
10590 app = &ap;
10591 while (readtoken() == TWORD) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010592 n2 = stzalloc(sizeof(struct narg));
Eric Andersencb57d552001-06-28 07:25:16 +000010593 n2->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010594 /*n2->narg.next = NULL; - stzalloc did it */
Eric Andersencb57d552001-06-28 07:25:16 +000010595 n2->narg.text = wordtext;
10596 n2->narg.backquote = backquotelist;
10597 *app = n2;
10598 app = &n2->narg.next;
10599 }
10600 *app = NULL;
10601 n1->nfor.args = ap;
10602 if (lasttoken != TNL && lasttoken != TSEMI)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010603 raise_error_unexpected_syntax(-1);
Eric Andersencb57d552001-06-28 07:25:16 +000010604 } else {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010605 n2 = stzalloc(sizeof(struct narg));
Eric Andersencb57d552001-06-28 07:25:16 +000010606 n2->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010607 /*n2->narg.next = NULL; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000010608 n2->narg.text = (char *)dolatstr;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010609 /*n2->narg.backquote = NULL;*/
Eric Andersencb57d552001-06-28 07:25:16 +000010610 n1->nfor.args = n2;
10611 /*
10612 * Newline or semicolon here is optional (but note
10613 * that the original Bourne shell only allowed NL).
10614 */
10615 if (lasttoken != TNL && lasttoken != TSEMI)
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010616 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010617 }
Eric Andersenc470f442003-07-28 09:56:35 +000010618 checkkwd = CHKNL | CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010619 if (readtoken() != TDO)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010620 raise_error_unexpected_syntax(TDO);
Eric Andersencb57d552001-06-28 07:25:16 +000010621 n1->nfor.body = list(0);
Eric Andersenc470f442003-07-28 09:56:35 +000010622 t = TDONE;
Eric Andersencb57d552001-06-28 07:25:16 +000010623 break;
10624 case TCASE:
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010625 n1 = stzalloc(sizeof(struct ncase));
Eric Andersencb57d552001-06-28 07:25:16 +000010626 n1->type = NCASE;
10627 if (readtoken() != TWORD)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010628 raise_error_unexpected_syntax(TWORD);
Denis Vlasenko597906c2008-02-20 16:38:54 +000010629 n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
Eric Andersencb57d552001-06-28 07:25:16 +000010630 n2->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010631 /*n2->narg.next = NULL; - stzalloc did it */
Eric Andersencb57d552001-06-28 07:25:16 +000010632 n2->narg.text = wordtext;
10633 n2->narg.backquote = backquotelist;
Eric Andersencb57d552001-06-28 07:25:16 +000010634 do {
Eric Andersenc470f442003-07-28 09:56:35 +000010635 checkkwd = CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010636 } while (readtoken() == TNL);
10637 if (lasttoken != TIN)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010638 raise_error_unexpected_syntax(TIN);
Eric Andersencb57d552001-06-28 07:25:16 +000010639 cpp = &n1->ncase.cases;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010640 next_case:
Eric Andersenc470f442003-07-28 09:56:35 +000010641 checkkwd = CHKNL | CHKKWD;
10642 t = readtoken();
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010643 while (t != TESAC) {
Eric Andersencb57d552001-06-28 07:25:16 +000010644 if (lasttoken == TLP)
10645 readtoken();
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010646 *cpp = cp = stzalloc(sizeof(struct nclist));
Eric Andersencb57d552001-06-28 07:25:16 +000010647 cp->type = NCLIST;
10648 app = &cp->nclist.pattern;
10649 for (;;) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010650 *app = ap = stzalloc(sizeof(struct narg));
Eric Andersencb57d552001-06-28 07:25:16 +000010651 ap->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010652 /*ap->narg.next = NULL; - stzalloc did it */
Eric Andersencb57d552001-06-28 07:25:16 +000010653 ap->narg.text = wordtext;
10654 ap->narg.backquote = backquotelist;
Eric Andersenc470f442003-07-28 09:56:35 +000010655 if (readtoken() != TPIPE)
Eric Andersencb57d552001-06-28 07:25:16 +000010656 break;
10657 app = &ap->narg.next;
10658 readtoken();
10659 }
Denis Vlasenko597906c2008-02-20 16:38:54 +000010660 //ap->narg.next = NULL;
Eric Andersencb57d552001-06-28 07:25:16 +000010661 if (lasttoken != TRP)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010662 raise_error_unexpected_syntax(TRP);
Eric Andersenc470f442003-07-28 09:56:35 +000010663 cp->nclist.body = list(2);
Eric Andersencb57d552001-06-28 07:25:16 +000010664
Eric Andersenc470f442003-07-28 09:56:35 +000010665 cpp = &cp->nclist.next;
10666
10667 checkkwd = CHKNL | CHKKWD;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010668 t = readtoken();
10669 if (t != TESAC) {
Eric Andersencb57d552001-06-28 07:25:16 +000010670 if (t != TENDCASE)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010671 raise_error_unexpected_syntax(TENDCASE);
10672 goto next_case;
Eric Andersencb57d552001-06-28 07:25:16 +000010673 }
Eric Andersenc470f442003-07-28 09:56:35 +000010674 }
Eric Andersencb57d552001-06-28 07:25:16 +000010675 *cpp = NULL;
Eric Andersenc470f442003-07-28 09:56:35 +000010676 goto redir;
Eric Andersencb57d552001-06-28 07:25:16 +000010677 case TLP:
Denis Vlasenko597906c2008-02-20 16:38:54 +000010678 n1 = stzalloc(sizeof(struct nredir));
Eric Andersencb57d552001-06-28 07:25:16 +000010679 n1->type = NSUBSHELL;
10680 n1->nredir.n = list(0);
Denis Vlasenko597906c2008-02-20 16:38:54 +000010681 /*n1->nredir.redirect = NULL; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000010682 t = TRP;
Eric Andersencb57d552001-06-28 07:25:16 +000010683 break;
10684 case TBEGIN:
10685 n1 = list(0);
Eric Andersenc470f442003-07-28 09:56:35 +000010686 t = TEND;
Eric Andersencb57d552001-06-28 07:25:16 +000010687 break;
Eric Andersencb57d552001-06-28 07:25:16 +000010688 case TWORD:
Eric Andersenc470f442003-07-28 09:56:35 +000010689 case TREDIR:
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010690 tokpushback = 1;
Eric Andersenc470f442003-07-28 09:56:35 +000010691 return simplecmd();
Eric Andersencb57d552001-06-28 07:25:16 +000010692 }
10693
Eric Andersenc470f442003-07-28 09:56:35 +000010694 if (readtoken() != t)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010695 raise_error_unexpected_syntax(t);
Eric Andersenc470f442003-07-28 09:56:35 +000010696
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010697 redir:
Eric Andersencb57d552001-06-28 07:25:16 +000010698 /* Now check for redirection which may follow command */
Eric Andersenc470f442003-07-28 09:56:35 +000010699 checkkwd = CHKKWD | CHKALIAS;
10700 rpp = rpp2;
Eric Andersencb57d552001-06-28 07:25:16 +000010701 while (readtoken() == TREDIR) {
10702 *rpp = n2 = redirnode;
10703 rpp = &n2->nfile.next;
10704 parsefname();
10705 }
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010706 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010707 *rpp = NULL;
10708 if (redir) {
10709 if (n1->type != NSUBSHELL) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010710 n2 = stzalloc(sizeof(struct nredir));
Eric Andersencb57d552001-06-28 07:25:16 +000010711 n2->type = NREDIR;
10712 n2->nredir.n = n1;
10713 n1 = n2;
10714 }
10715 n1->nredir.redirect = redir;
10716 }
Eric Andersencb57d552001-06-28 07:25:16 +000010717 return n1;
10718}
10719
Denis Vlasenkoef527f52008-06-23 01:52:30 +000010720#if ENABLE_ASH_BASH_COMPAT
10721static int decode_dollar_squote(void)
10722{
10723 static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
10724 int c, cnt;
10725 char *p;
10726 char buf[4];
10727
10728 c = pgetc();
10729 p = strchr(C_escapes, c);
10730 if (p) {
10731 buf[0] = c;
10732 p = buf;
10733 cnt = 3;
10734 if ((unsigned char)(c - '0') <= 7) { /* \ooo */
10735 do {
10736 c = pgetc();
10737 *++p = c;
10738 } while ((unsigned char)(c - '0') <= 7 && --cnt);
10739 pungetc();
10740 } else if (c == 'x') { /* \xHH */
10741 do {
10742 c = pgetc();
10743 *++p = c;
10744 } while (isxdigit(c) && --cnt);
10745 pungetc();
10746 if (cnt == 3) { /* \x but next char is "bad" */
10747 c = 'x';
10748 goto unrecognized;
10749 }
10750 } else { /* simple seq like \\ or \t */
10751 p++;
10752 }
10753 *p = '\0';
10754 p = buf;
10755 c = bb_process_escape_sequence((void*)&p);
10756 } else { /* unrecognized "\z": print both chars unless ' or " */
10757 if (c != '\'' && c != '"') {
10758 unrecognized:
10759 c |= 0x100; /* "please encode \, then me" */
10760 }
10761 }
10762 return c;
10763}
10764#endif
10765
Eric Andersencb57d552001-06-28 07:25:16 +000010766/*
10767 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
10768 * is not NULL, read a here document. In the latter case, eofmark is the
10769 * word which marks the end of the document and striptabs is true if
10770 * leading tabs should be stripped from the document. The argument firstc
10771 * is the first character of the input token or document.
10772 *
10773 * Because C does not have internal subroutines, I have simulated them
10774 * using goto's to implement the subroutine linkage. The following macros
10775 * will run code that appears at the end of readtoken1.
10776 */
Eric Andersen2870d962001-07-02 17:27:21 +000010777#define CHECKEND() {goto checkend; checkend_return:;}
10778#define PARSEREDIR() {goto parseredir; parseredir_return:;}
10779#define PARSESUB() {goto parsesub; parsesub_return:;}
10780#define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
10781#define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
10782#define PARSEARITH() {goto parsearith; parsearith_return:;}
Eric Andersencb57d552001-06-28 07:25:16 +000010783static int
Eric Andersenc470f442003-07-28 09:56:35 +000010784readtoken1(int firstc, int syntax, char *eofmark, int striptabs)
Manuel Novoa III 16815d42001-08-10 19:36:07 +000010785{
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010786 /* NB: syntax parameter fits into smallint */
Eric Andersencb57d552001-06-28 07:25:16 +000010787 int c = firstc;
10788 char *out;
10789 int len;
10790 char line[EOFMARKLEN + 1];
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010791 struct nodelist *bqlist;
10792 smallint quotef;
10793 smallint dblquote;
10794 smallint oldstyle;
10795 smallint prevsyntax; /* syntax before arithmetic */
Denis Vlasenko46a53062007-09-24 18:30:02 +000010796#if ENABLE_ASH_EXPAND_PRMT
10797 smallint pssyntax; /* we are expanding a prompt string */
10798#endif
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010799 int varnest; /* levels of variables expansion */
10800 int arinest; /* levels of arithmetic expansion */
10801 int parenlevel; /* levels of parens in arithmetic */
10802 int dqvarnest; /* levels of variables expansion within double quotes */
10803
Denis Vlasenko5e34ff22009-04-21 11:09:40 +000010804 IF_ASH_BASH_COMPAT(smallint bash_dollar_squote = 0;)
Denis Vlasenkoef527f52008-06-23 01:52:30 +000010805
Eric Andersencb57d552001-06-28 07:25:16 +000010806#if __GNUC__
10807 /* Avoid longjmp clobbering */
10808 (void) &out;
10809 (void) &quotef;
10810 (void) &dblquote;
10811 (void) &varnest;
10812 (void) &arinest;
10813 (void) &parenlevel;
10814 (void) &dqvarnest;
10815 (void) &oldstyle;
10816 (void) &prevsyntax;
10817 (void) &syntax;
10818#endif
Denis Vlasenko41eb3002008-11-28 03:42:31 +000010819 startlinno = g_parsefile->linno;
Eric Andersencb57d552001-06-28 07:25:16 +000010820 bqlist = NULL;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010821 quotef = 0;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010822 oldstyle = 0;
10823 prevsyntax = 0;
Denis Vlasenko46a53062007-09-24 18:30:02 +000010824#if ENABLE_ASH_EXPAND_PRMT
10825 pssyntax = (syntax == PSSYNTAX);
10826 if (pssyntax)
10827 syntax = DQSYNTAX;
10828#endif
10829 dblquote = (syntax == DQSYNTAX);
Eric Andersencb57d552001-06-28 07:25:16 +000010830 varnest = 0;
10831 arinest = 0;
10832 parenlevel = 0;
10833 dqvarnest = 0;
10834
10835 STARTSTACKSTR(out);
Denis Vlasenko176d49d2008-10-06 09:51:47 +000010836 loop:
10837 /* For each line, until end of word */
10838 {
Eric Andersenc470f442003-07-28 09:56:35 +000010839 CHECKEND(); /* set c to PEOF if at end of here document */
10840 for (;;) { /* until end of line or end of word */
10841 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
Denis Vlasenkobf0a2012006-12-26 10:42:51 +000010842 switch (SIT(c, syntax)) {
Eric Andersenc470f442003-07-28 09:56:35 +000010843 case CNL: /* '\n' */
Eric Andersencb57d552001-06-28 07:25:16 +000010844 if (syntax == BASESYNTAX)
Eric Andersenc470f442003-07-28 09:56:35 +000010845 goto endword; /* exit outer loop */
Eric Andersencb57d552001-06-28 07:25:16 +000010846 USTPUTC(c, out);
Denis Vlasenko41eb3002008-11-28 03:42:31 +000010847 g_parsefile->linno++;
Eric Andersencb57d552001-06-28 07:25:16 +000010848 if (doprompt)
10849 setprompt(2);
Eric Andersencb57d552001-06-28 07:25:16 +000010850 c = pgetc();
Eric Andersenc470f442003-07-28 09:56:35 +000010851 goto loop; /* continue outer loop */
Eric Andersencb57d552001-06-28 07:25:16 +000010852 case CWORD:
10853 USTPUTC(c, out);
10854 break;
10855 case CCTL:
Eric Andersenc470f442003-07-28 09:56:35 +000010856 if (eofmark == NULL || dblquote)
Eric Andersencb57d552001-06-28 07:25:16 +000010857 USTPUTC(CTLESC, out);
Denis Vlasenkoef527f52008-06-23 01:52:30 +000010858#if ENABLE_ASH_BASH_COMPAT
10859 if (c == '\\' && bash_dollar_squote) {
10860 c = decode_dollar_squote();
10861 if (c & 0x100) {
10862 USTPUTC('\\', out);
10863 c = (unsigned char)c;
10864 }
10865 }
10866#endif
Eric Andersencb57d552001-06-28 07:25:16 +000010867 USTPUTC(c, out);
10868 break;
Eric Andersenc470f442003-07-28 09:56:35 +000010869 case CBACK: /* backslash */
Eric Andersencb57d552001-06-28 07:25:16 +000010870 c = pgetc2();
10871 if (c == PEOF) {
Eric Andersenc470f442003-07-28 09:56:35 +000010872 USTPUTC(CTLESC, out);
Eric Andersencb57d552001-06-28 07:25:16 +000010873 USTPUTC('\\', out);
10874 pungetc();
10875 } else if (c == '\n') {
10876 if (doprompt)
10877 setprompt(2);
Eric Andersencb57d552001-06-28 07:25:16 +000010878 } else {
Denis Vlasenko46a53062007-09-24 18:30:02 +000010879#if ENABLE_ASH_EXPAND_PRMT
10880 if (c == '$' && pssyntax) {
10881 USTPUTC(CTLESC, out);
10882 USTPUTC('\\', out);
10883 }
10884#endif
Denis Vlasenkoef527f52008-06-23 01:52:30 +000010885 if (dblquote && c != '\\'
10886 && c != '`' && c != '$'
10887 && (c != '"' || eofmark != NULL)
Eric Andersenc470f442003-07-28 09:56:35 +000010888 ) {
10889 USTPUTC(CTLESC, out);
Eric Andersencb57d552001-06-28 07:25:16 +000010890 USTPUTC('\\', out);
Eric Andersenc470f442003-07-28 09:56:35 +000010891 }
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010892 if (SIT(c, SQSYNTAX) == CCTL)
Eric Andersencb57d552001-06-28 07:25:16 +000010893 USTPUTC(CTLESC, out);
Eric Andersencb57d552001-06-28 07:25:16 +000010894 USTPUTC(c, out);
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010895 quotef = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010896 }
10897 break;
10898 case CSQUOTE:
Eric Andersencb57d552001-06-28 07:25:16 +000010899 syntax = SQSYNTAX;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010900 quotemark:
Eric Andersenc470f442003-07-28 09:56:35 +000010901 if (eofmark == NULL) {
10902 USTPUTC(CTLQUOTEMARK, out);
10903 }
Eric Andersencb57d552001-06-28 07:25:16 +000010904 break;
10905 case CDQUOTE:
Eric Andersencb57d552001-06-28 07:25:16 +000010906 syntax = DQSYNTAX;
10907 dblquote = 1;
Eric Andersenc470f442003-07-28 09:56:35 +000010908 goto quotemark;
Eric Andersencb57d552001-06-28 07:25:16 +000010909 case CENDQUOTE:
Denis Vlasenko5e34ff22009-04-21 11:09:40 +000010910 IF_ASH_BASH_COMPAT(bash_dollar_squote = 0;)
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010911 if (eofmark != NULL && arinest == 0
10912 && varnest == 0
10913 ) {
Eric Andersencb57d552001-06-28 07:25:16 +000010914 USTPUTC(c, out);
10915 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000010916 if (dqvarnest == 0) {
Eric Andersencb57d552001-06-28 07:25:16 +000010917 syntax = BASESYNTAX;
10918 dblquote = 0;
10919 }
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010920 quotef = 1;
Eric Andersenc470f442003-07-28 09:56:35 +000010921 goto quotemark;
Eric Andersencb57d552001-06-28 07:25:16 +000010922 }
10923 break;
Eric Andersenc470f442003-07-28 09:56:35 +000010924 case CVAR: /* '$' */
10925 PARSESUB(); /* parse substitution */
Eric Andersencb57d552001-06-28 07:25:16 +000010926 break;
Eric Andersenc470f442003-07-28 09:56:35 +000010927 case CENDVAR: /* '}' */
Eric Andersencb57d552001-06-28 07:25:16 +000010928 if (varnest > 0) {
10929 varnest--;
10930 if (dqvarnest > 0) {
10931 dqvarnest--;
10932 }
10933 USTPUTC(CTLENDVAR, out);
10934 } else {
10935 USTPUTC(c, out);
10936 }
10937 break;
Mike Frysinger98c52642009-04-02 10:02:37 +000010938#if ENABLE_SH_MATH_SUPPORT
Eric Andersenc470f442003-07-28 09:56:35 +000010939 case CLP: /* '(' in arithmetic */
Eric Andersencb57d552001-06-28 07:25:16 +000010940 parenlevel++;
10941 USTPUTC(c, out);
10942 break;
Eric Andersenc470f442003-07-28 09:56:35 +000010943 case CRP: /* ')' in arithmetic */
Eric Andersencb57d552001-06-28 07:25:16 +000010944 if (parenlevel > 0) {
10945 USTPUTC(c, out);
10946 --parenlevel;
10947 } else {
10948 if (pgetc() == ')') {
10949 if (--arinest == 0) {
10950 USTPUTC(CTLENDARI, out);
10951 syntax = prevsyntax;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010952 dblquote = (syntax == DQSYNTAX);
Eric Andersencb57d552001-06-28 07:25:16 +000010953 } else
10954 USTPUTC(')', out);
10955 } else {
10956 /*
10957 * unbalanced parens
10958 * (don't 2nd guess - no error)
10959 */
10960 pungetc();
10961 USTPUTC(')', out);
10962 }
10963 }
10964 break;
10965#endif
Eric Andersenc470f442003-07-28 09:56:35 +000010966 case CBQUOTE: /* '`' */
Eric Andersencb57d552001-06-28 07:25:16 +000010967 PARSEBACKQOLD();
10968 break;
Eric Andersen2870d962001-07-02 17:27:21 +000010969 case CENDFILE:
Eric Andersenc470f442003-07-28 09:56:35 +000010970 goto endword; /* exit outer loop */
Eric Andersencb57d552001-06-28 07:25:16 +000010971 case CIGN:
10972 break;
10973 default:
Denis Vlasenko834dee72008-10-07 09:18:30 +000010974 if (varnest == 0) {
10975#if ENABLE_ASH_BASH_COMPAT
10976 if (c == '&') {
10977 if (pgetc() == '>')
10978 c = 0x100 + '>'; /* flag &> */
10979 pungetc();
10980 }
10981#endif
Eric Andersenc470f442003-07-28 09:56:35 +000010982 goto endword; /* exit outer loop */
Denis Vlasenko834dee72008-10-07 09:18:30 +000010983 }
Denis Vlasenko131ae172007-02-18 13:00:19 +000010984#if ENABLE_ASH_ALIAS
Eric Andersen3102ac42001-07-06 04:26:23 +000010985 if (c != PEOA)
10986#endif
Eric Andersencb57d552001-06-28 07:25:16 +000010987 USTPUTC(c, out);
Eric Andersen3102ac42001-07-06 04:26:23 +000010988
Eric Andersencb57d552001-06-28 07:25:16 +000010989 }
Denis Vlasenko834dee72008-10-07 09:18:30 +000010990 c = pgetc_fast();
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000010991 } /* for (;;) */
Eric Andersencb57d552001-06-28 07:25:16 +000010992 }
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010993 endword:
Mike Frysinger98c52642009-04-02 10:02:37 +000010994#if ENABLE_SH_MATH_SUPPORT
Eric Andersencb57d552001-06-28 07:25:16 +000010995 if (syntax == ARISYNTAX)
Denis Vlasenko559691a2008-10-05 18:39:31 +000010996 raise_error_syntax("missing '))'");
Eric Andersenc470f442003-07-28 09:56:35 +000010997#endif
Denis Vlasenko99eb8502007-02-23 21:09:49 +000010998 if (syntax != BASESYNTAX && !parsebackquote && eofmark == NULL)
Denis Vlasenko559691a2008-10-05 18:39:31 +000010999 raise_error_syntax("unterminated quoted string");
Eric Andersencb57d552001-06-28 07:25:16 +000011000 if (varnest != 0) {
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011001 startlinno = g_parsefile->linno;
Eric Andersenc470f442003-07-28 09:56:35 +000011002 /* { */
Denis Vlasenko559691a2008-10-05 18:39:31 +000011003 raise_error_syntax("missing '}'");
Eric Andersencb57d552001-06-28 07:25:16 +000011004 }
11005 USTPUTC('\0', out);
Eric Andersenc470f442003-07-28 09:56:35 +000011006 len = out - (char *)stackblock();
Eric Andersencb57d552001-06-28 07:25:16 +000011007 out = stackblock();
11008 if (eofmark == NULL) {
Denis Vlasenko5e34ff22009-04-21 11:09:40 +000011009 if ((c == '>' || c == '<' IF_ASH_BASH_COMPAT( || c == 0x100 + '>'))
Denis Vlasenko834dee72008-10-07 09:18:30 +000011010 && quotef == 0
11011 ) {
Denis Vlasenko559691a2008-10-05 18:39:31 +000011012 if (isdigit_str9(out)) {
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000011013 PARSEREDIR(); /* passed as params: out, c */
11014 lasttoken = TREDIR;
11015 return lasttoken;
11016 }
11017 /* else: non-number X seen, interpret it
11018 * as "NNNX>file" = "NNNX >file" */
Eric Andersencb57d552001-06-28 07:25:16 +000011019 }
Denis Vlasenkoef527f52008-06-23 01:52:30 +000011020 pungetc();
Eric Andersencb57d552001-06-28 07:25:16 +000011021 }
11022 quoteflag = quotef;
11023 backquotelist = bqlist;
11024 grabstackblock(len);
11025 wordtext = out;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011026 lasttoken = TWORD;
11027 return lasttoken;
Eric Andersencb57d552001-06-28 07:25:16 +000011028/* end of readtoken routine */
11029
Eric Andersencb57d552001-06-28 07:25:16 +000011030/*
11031 * Check to see whether we are at the end of the here document. When this
11032 * is called, c is set to the first character of the next input line. If
11033 * we are at the end of the here document, this routine sets the c to PEOF.
11034 */
Eric Andersenc470f442003-07-28 09:56:35 +000011035checkend: {
11036 if (eofmark) {
Denis Vlasenko131ae172007-02-18 13:00:19 +000011037#if ENABLE_ASH_ALIAS
Eric Andersenc470f442003-07-28 09:56:35 +000011038 if (c == PEOA) {
11039 c = pgetc2();
11040 }
11041#endif
11042 if (striptabs) {
11043 while (c == '\t') {
Eric Andersencb57d552001-06-28 07:25:16 +000011044 c = pgetc2();
11045 }
Eric Andersenc470f442003-07-28 09:56:35 +000011046 }
11047 if (c == *eofmark) {
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011048 if (pfgets(line, sizeof(line)) != NULL) {
Eric Andersenc470f442003-07-28 09:56:35 +000011049 char *p, *q;
Eric Andersencb57d552001-06-28 07:25:16 +000011050
Eric Andersenc470f442003-07-28 09:56:35 +000011051 p = line;
Denis Vlasenkof7d56652008-03-25 05:51:41 +000011052 for (q = eofmark + 1; *q && *p == *q; p++, q++)
11053 continue;
Eric Andersenc470f442003-07-28 09:56:35 +000011054 if (*p == '\n' && *q == '\0') {
11055 c = PEOF;
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011056 g_parsefile->linno++;
Eric Andersenc470f442003-07-28 09:56:35 +000011057 needprompt = doprompt;
11058 } else {
11059 pushstring(line, NULL);
Eric Andersencb57d552001-06-28 07:25:16 +000011060 }
11061 }
11062 }
11063 }
Eric Andersenc470f442003-07-28 09:56:35 +000011064 goto checkend_return;
11065}
Eric Andersencb57d552001-06-28 07:25:16 +000011066
Eric Andersencb57d552001-06-28 07:25:16 +000011067/*
11068 * Parse a redirection operator. The variable "out" points to a string
11069 * specifying the fd to be redirected. The variable "c" contains the
11070 * first character of the redirection operator.
11071 */
Eric Andersenc470f442003-07-28 09:56:35 +000011072parseredir: {
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000011073 /* out is already checked to be a valid number or "" */
11074 int fd = (*out == '\0' ? -1 : atoi(out));
Eric Andersenc470f442003-07-28 09:56:35 +000011075 union node *np;
Eric Andersencb57d552001-06-28 07:25:16 +000011076
Denis Vlasenko597906c2008-02-20 16:38:54 +000011077 np = stzalloc(sizeof(struct nfile));
Eric Andersenc470f442003-07-28 09:56:35 +000011078 if (c == '>') {
11079 np->nfile.fd = 1;
11080 c = pgetc();
11081 if (c == '>')
11082 np->type = NAPPEND;
11083 else if (c == '|')
11084 np->type = NCLOBBER;
11085 else if (c == '&')
11086 np->type = NTOFD;
Denis Vlasenko559691a2008-10-05 18:39:31 +000011087 /* it also can be NTO2 (>&file), but we can't figure it out yet */
Eric Andersenc470f442003-07-28 09:56:35 +000011088 else {
11089 np->type = NTO;
11090 pungetc();
Eric Andersencb57d552001-06-28 07:25:16 +000011091 }
Denis Vlasenko834dee72008-10-07 09:18:30 +000011092 }
11093#if ENABLE_ASH_BASH_COMPAT
11094 else if (c == 0x100 + '>') { /* this flags &> redirection */
11095 np->nfile.fd = 1;
11096 pgetc(); /* this is '>', no need to check */
11097 np->type = NTO2;
11098 }
11099#endif
11100 else { /* c == '<' */
Denis Vlasenko597906c2008-02-20 16:38:54 +000011101 /*np->nfile.fd = 0; - stzalloc did it */
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011102 c = pgetc();
11103 switch (c) {
Eric Andersenc470f442003-07-28 09:56:35 +000011104 case '<':
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011105 if (sizeof(struct nfile) != sizeof(struct nhere)) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000011106 np = stzalloc(sizeof(struct nhere));
11107 /*np->nfile.fd = 0; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000011108 }
11109 np->type = NHERE;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000011110 heredoc = stzalloc(sizeof(struct heredoc));
Eric Andersenc470f442003-07-28 09:56:35 +000011111 heredoc->here = np;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011112 c = pgetc();
11113 if (c == '-') {
Eric Andersenc470f442003-07-28 09:56:35 +000011114 heredoc->striptabs = 1;
11115 } else {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000011116 /*heredoc->striptabs = 0; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000011117 pungetc();
11118 }
11119 break;
11120
11121 case '&':
11122 np->type = NFROMFD;
11123 break;
11124
11125 case '>':
11126 np->type = NFROMTO;
11127 break;
11128
11129 default:
11130 np->type = NFROM;
11131 pungetc();
11132 break;
11133 }
Eric Andersencb57d552001-06-28 07:25:16 +000011134 }
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000011135 if (fd >= 0)
11136 np->nfile.fd = fd;
Eric Andersenc470f442003-07-28 09:56:35 +000011137 redirnode = np;
11138 goto parseredir_return;
11139}
Eric Andersencb57d552001-06-28 07:25:16 +000011140
Eric Andersencb57d552001-06-28 07:25:16 +000011141/*
11142 * Parse a substitution. At this point, we have read the dollar sign
11143 * and nothing else.
11144 */
Denis Vlasenkocc571512007-02-23 21:10:35 +000011145
11146/* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
11147 * (assuming ascii char codes, as the original implementation did) */
11148#define is_special(c) \
Denis Vlasenkoef527f52008-06-23 01:52:30 +000011149 (((unsigned)(c) - 33 < 32) \
11150 && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
Eric Andersenc470f442003-07-28 09:56:35 +000011151parsesub: {
11152 int subtype;
11153 int typeloc;
11154 int flags;
11155 char *p;
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011156 static const char types[] ALIGN1 = "}-+?=";
Eric Andersencb57d552001-06-28 07:25:16 +000011157
Eric Andersenc470f442003-07-28 09:56:35 +000011158 c = pgetc();
Denis Vlasenkoef527f52008-06-23 01:52:30 +000011159 if (c <= PEOA_OR_PEOF
11160 || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
Eric Andersenc470f442003-07-28 09:56:35 +000011161 ) {
Denis Vlasenkoef527f52008-06-23 01:52:30 +000011162#if ENABLE_ASH_BASH_COMPAT
11163 if (c == '\'')
11164 bash_dollar_squote = 1;
11165 else
11166#endif
11167 USTPUTC('$', out);
Eric Andersenc470f442003-07-28 09:56:35 +000011168 pungetc();
11169 } else if (c == '(') { /* $(command) or $((arith)) */
11170 if (pgetc() == '(') {
Mike Frysinger98c52642009-04-02 10:02:37 +000011171#if ENABLE_SH_MATH_SUPPORT
Eric Andersenc470f442003-07-28 09:56:35 +000011172 PARSEARITH();
11173#else
Mike Frysinger98a6f562008-06-09 09:38:45 +000011174 raise_error_syntax("you disabled math support for $((arith)) syntax");
Eric Andersenc470f442003-07-28 09:56:35 +000011175#endif
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000011176 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000011177 pungetc();
11178 PARSEBACKQNEW();
11179 }
11180 } else {
11181 USTPUTC(CTLVAR, out);
11182 typeloc = out - (char *)stackblock();
11183 USTPUTC(VSNORMAL, out);
11184 subtype = VSNORMAL;
11185 if (c == '{') {
11186 c = pgetc();
11187 if (c == '#') {
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011188 c = pgetc();
11189 if (c == '}')
Eric Andersenc470f442003-07-28 09:56:35 +000011190 c = '#';
11191 else
11192 subtype = VSLENGTH;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011193 } else
Eric Andersenc470f442003-07-28 09:56:35 +000011194 subtype = 0;
11195 }
11196 if (c > PEOA_OR_PEOF && is_name(c)) {
11197 do {
11198 STPUTC(c, out);
Eric Andersencb57d552001-06-28 07:25:16 +000011199 c = pgetc();
Eric Andersenc470f442003-07-28 09:56:35 +000011200 } while (c > PEOA_OR_PEOF && is_in_name(c));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011201 } else if (isdigit(c)) {
Eric Andersenc470f442003-07-28 09:56:35 +000011202 do {
11203 STPUTC(c, out);
11204 c = pgetc();
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011205 } while (isdigit(c));
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011206 } else if (is_special(c)) {
Eric Andersenc470f442003-07-28 09:56:35 +000011207 USTPUTC(c, out);
11208 c = pgetc();
Denis Vlasenko559691a2008-10-05 18:39:31 +000011209 } else {
11210 badsub:
11211 raise_error_syntax("bad substitution");
11212 }
Eric Andersencb57d552001-06-28 07:25:16 +000011213
Eric Andersenc470f442003-07-28 09:56:35 +000011214 STPUTC('=', out);
11215 flags = 0;
11216 if (subtype == 0) {
11217 switch (c) {
11218 case ':':
Eric Andersenc470f442003-07-28 09:56:35 +000011219 c = pgetc();
Denis Vlasenko92e13c22008-03-25 01:17:40 +000011220#if ENABLE_ASH_BASH_COMPAT
11221 if (c == ':' || c == '$' || isdigit(c)) {
11222 pungetc();
11223 subtype = VSSUBSTR;
11224 break;
11225 }
11226#endif
11227 flags = VSNUL;
Eric Andersenc470f442003-07-28 09:56:35 +000011228 /*FALLTHROUGH*/
11229 default:
11230 p = strchr(types, c);
11231 if (p == NULL)
11232 goto badsub;
11233 subtype = p - types + VSNORMAL;
11234 break;
11235 case '%':
Denis Vlasenko92e13c22008-03-25 01:17:40 +000011236 case '#': {
11237 int cc = c;
11238 subtype = c == '#' ? VSTRIMLEFT : VSTRIMRIGHT;
11239 c = pgetc();
11240 if (c == cc)
11241 subtype++;
11242 else
11243 pungetc();
11244 break;
11245 }
11246#if ENABLE_ASH_BASH_COMPAT
11247 case '/':
11248 subtype = VSREPLACE;
11249 c = pgetc();
11250 if (c == '/')
11251 subtype++; /* VSREPLACEALL */
11252 else
11253 pungetc();
11254 break;
11255#endif
Eric Andersencb57d552001-06-28 07:25:16 +000011256 }
Eric Andersenc470f442003-07-28 09:56:35 +000011257 } else {
11258 pungetc();
11259 }
11260 if (dblquote || arinest)
11261 flags |= VSQUOTE;
11262 *((char *)stackblock() + typeloc) = subtype | flags;
11263 if (subtype != VSNORMAL) {
11264 varnest++;
11265 if (dblquote || arinest) {
11266 dqvarnest++;
Eric Andersencb57d552001-06-28 07:25:16 +000011267 }
11268 }
11269 }
Eric Andersenc470f442003-07-28 09:56:35 +000011270 goto parsesub_return;
11271}
Eric Andersencb57d552001-06-28 07:25:16 +000011272
Eric Andersencb57d552001-06-28 07:25:16 +000011273/*
11274 * Called to parse command substitutions. Newstyle is set if the command
11275 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
11276 * list of commands (passed by reference), and savelen is the number of
11277 * characters on the top of the stack which must be preserved.
11278 */
Eric Andersenc470f442003-07-28 09:56:35 +000011279parsebackq: {
11280 struct nodelist **nlpp;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011281 smallint savepbq;
Eric Andersenc470f442003-07-28 09:56:35 +000011282 union node *n;
11283 char *volatile str;
11284 struct jmploc jmploc;
11285 struct jmploc *volatile savehandler;
11286 size_t savelen;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011287 smallint saveprompt = 0;
11288
Eric Andersencb57d552001-06-28 07:25:16 +000011289#ifdef __GNUC__
Eric Andersenc470f442003-07-28 09:56:35 +000011290 (void) &saveprompt;
Eric Andersencb57d552001-06-28 07:25:16 +000011291#endif
Eric Andersenc470f442003-07-28 09:56:35 +000011292 savepbq = parsebackquote;
11293 if (setjmp(jmploc.loc)) {
Denis Vlasenko60818682007-09-28 22:07:23 +000011294 free(str);
Eric Andersenc470f442003-07-28 09:56:35 +000011295 parsebackquote = 0;
Denis Vlasenko2da584f2007-02-19 22:44:05 +000011296 exception_handler = savehandler;
11297 longjmp(exception_handler->loc, 1);
Eric Andersenc470f442003-07-28 09:56:35 +000011298 }
Denis Vlasenkob012b102007-02-19 22:43:01 +000011299 INT_OFF;
Eric Andersenc470f442003-07-28 09:56:35 +000011300 str = NULL;
11301 savelen = out - (char *)stackblock();
11302 if (savelen > 0) {
11303 str = ckmalloc(savelen);
11304 memcpy(str, stackblock(), savelen);
11305 }
Denis Vlasenko2da584f2007-02-19 22:44:05 +000011306 savehandler = exception_handler;
11307 exception_handler = &jmploc;
Denis Vlasenkob012b102007-02-19 22:43:01 +000011308 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +000011309 if (oldstyle) {
11310 /* We must read until the closing backquote, giving special
11311 treatment to some slashes, and then push the string and
11312 reread it as input, interpreting it normally. */
11313 char *pout;
11314 int pc;
11315 size_t psavelen;
11316 char *pstr;
11317
11318
11319 STARTSTACKSTR(pout);
11320 for (;;) {
11321 if (needprompt) {
11322 setprompt(2);
Eric Andersenc470f442003-07-28 09:56:35 +000011323 }
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011324 pc = pgetc();
11325 switch (pc) {
Eric Andersenc470f442003-07-28 09:56:35 +000011326 case '`':
11327 goto done;
11328
11329 case '\\':
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011330 pc = pgetc();
11331 if (pc == '\n') {
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011332 g_parsefile->linno++;
Eric Andersenc470f442003-07-28 09:56:35 +000011333 if (doprompt)
11334 setprompt(2);
11335 /*
11336 * If eating a newline, avoid putting
11337 * the newline into the new character
11338 * stream (via the STPUTC after the
11339 * switch).
11340 */
11341 continue;
11342 }
11343 if (pc != '\\' && pc != '`' && pc != '$'
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011344 && (!dblquote || pc != '"'))
Eric Andersenc470f442003-07-28 09:56:35 +000011345 STPUTC('\\', pout);
11346 if (pc > PEOA_OR_PEOF) {
11347 break;
11348 }
11349 /* fall through */
11350
11351 case PEOF:
Denis Vlasenko131ae172007-02-18 13:00:19 +000011352#if ENABLE_ASH_ALIAS
Eric Andersenc470f442003-07-28 09:56:35 +000011353 case PEOA:
11354#endif
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011355 startlinno = g_parsefile->linno;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000011356 raise_error_syntax("EOF in backquote substitution");
Eric Andersenc470f442003-07-28 09:56:35 +000011357
11358 case '\n':
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011359 g_parsefile->linno++;
Eric Andersenc470f442003-07-28 09:56:35 +000011360 needprompt = doprompt;
11361 break;
11362
11363 default:
11364 break;
11365 }
11366 STPUTC(pc, pout);
11367 }
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011368 done:
Eric Andersenc470f442003-07-28 09:56:35 +000011369 STPUTC('\0', pout);
11370 psavelen = pout - (char *)stackblock();
11371 if (psavelen > 0) {
11372 pstr = grabstackstr(pout);
11373 setinputstring(pstr);
11374 }
11375 }
11376 nlpp = &bqlist;
11377 while (*nlpp)
11378 nlpp = &(*nlpp)->next;
Denis Vlasenko597906c2008-02-20 16:38:54 +000011379 *nlpp = stzalloc(sizeof(**nlpp));
11380 /* (*nlpp)->next = NULL; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000011381 parsebackquote = oldstyle;
11382
11383 if (oldstyle) {
11384 saveprompt = doprompt;
11385 doprompt = 0;
Eric Andersencb57d552001-06-28 07:25:16 +000011386 }
11387
Eric Andersenc470f442003-07-28 09:56:35 +000011388 n = list(2);
11389
11390 if (oldstyle)
11391 doprompt = saveprompt;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011392 else if (readtoken() != TRP)
11393 raise_error_unexpected_syntax(TRP);
Eric Andersenc470f442003-07-28 09:56:35 +000011394
11395 (*nlpp)->n = n;
11396 if (oldstyle) {
11397 /*
11398 * Start reading from old file again, ignoring any pushed back
11399 * tokens left from the backquote parsing
11400 */
11401 popfile();
11402 tokpushback = 0;
11403 }
11404 while (stackblocksize() <= savelen)
11405 growstackblock();
11406 STARTSTACKSTR(out);
11407 if (str) {
11408 memcpy(out, str, savelen);
11409 STADJUST(savelen, out);
Denis Vlasenkob012b102007-02-19 22:43:01 +000011410 INT_OFF;
11411 free(str);
Eric Andersenc470f442003-07-28 09:56:35 +000011412 str = NULL;
Denis Vlasenkob012b102007-02-19 22:43:01 +000011413 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +000011414 }
11415 parsebackquote = savepbq;
Denis Vlasenko2da584f2007-02-19 22:44:05 +000011416 exception_handler = savehandler;
Eric Andersenc470f442003-07-28 09:56:35 +000011417 if (arinest || dblquote)
11418 USTPUTC(CTLBACKQ | CTLQUOTE, out);
11419 else
11420 USTPUTC(CTLBACKQ, out);
11421 if (oldstyle)
11422 goto parsebackq_oldreturn;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000011423 goto parsebackq_newreturn;
Eric Andersenc470f442003-07-28 09:56:35 +000011424}
11425
Mike Frysinger98c52642009-04-02 10:02:37 +000011426#if ENABLE_SH_MATH_SUPPORT
Eric Andersencb57d552001-06-28 07:25:16 +000011427/*
11428 * Parse an arithmetic expansion (indicate start of one and set state)
11429 */
Eric Andersenc470f442003-07-28 09:56:35 +000011430parsearith: {
Eric Andersenc470f442003-07-28 09:56:35 +000011431 if (++arinest == 1) {
11432 prevsyntax = syntax;
11433 syntax = ARISYNTAX;
11434 USTPUTC(CTLARI, out);
11435 if (dblquote)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000011436 USTPUTC('"', out);
Eric Andersenc470f442003-07-28 09:56:35 +000011437 else
Denis Vlasenkoa624c112007-02-19 22:45:43 +000011438 USTPUTC(' ', out);
Eric Andersenc470f442003-07-28 09:56:35 +000011439 } else {
11440 /*
11441 * we collapse embedded arithmetic expansion to
11442 * parenthesis, which should be equivalent
11443 */
11444 USTPUTC('(', out);
Eric Andersencb57d552001-06-28 07:25:16 +000011445 }
Eric Andersenc470f442003-07-28 09:56:35 +000011446 goto parsearith_return;
11447}
11448#endif
Eric Andersencb57d552001-06-28 07:25:16 +000011449
Eric Andersenc470f442003-07-28 09:56:35 +000011450} /* end of readtoken */
11451
Eric Andersencb57d552001-06-28 07:25:16 +000011452/*
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011453 * Read the next input token.
11454 * If the token is a word, we set backquotelist to the list of cmds in
11455 * backquotes. We set quoteflag to true if any part of the word was
11456 * quoted.
11457 * If the token is TREDIR, then we set redirnode to a structure containing
11458 * the redirection.
11459 * In all cases, the variable startlinno is set to the number of the line
11460 * on which the token starts.
11461 *
11462 * [Change comment: here documents and internal procedures]
11463 * [Readtoken shouldn't have any arguments. Perhaps we should make the
11464 * word parsing code into a separate routine. In this case, readtoken
11465 * doesn't need to have any internal procedures, but parseword does.
11466 * We could also make parseoperator in essence the main routine, and
11467 * have parseword (readtoken1?) handle both words and redirection.]
Eric Andersencb57d552001-06-28 07:25:16 +000011468 */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011469#define NEW_xxreadtoken
11470#ifdef NEW_xxreadtoken
11471/* singles must be first! */
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011472static const char xxreadtoken_chars[7] ALIGN1 = {
Denis Vlasenko834dee72008-10-07 09:18:30 +000011473 '\n', '(', ')', /* singles */
11474 '&', '|', ';', /* doubles */
11475 0
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011476};
Eric Andersencb57d552001-06-28 07:25:16 +000011477
Denis Vlasenko834dee72008-10-07 09:18:30 +000011478#define xxreadtoken_singles 3
11479#define xxreadtoken_doubles 3
11480
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011481static const char xxreadtoken_tokens[] ALIGN1 = {
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011482 TNL, TLP, TRP, /* only single occurrence allowed */
11483 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
11484 TEOF, /* corresponds to trailing nul */
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011485 TAND, TOR, TENDCASE /* if double occurrence */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011486};
11487
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011488static int
11489xxreadtoken(void)
11490{
11491 int c;
11492
11493 if (tokpushback) {
11494 tokpushback = 0;
11495 return lasttoken;
Eric Andersencb57d552001-06-28 07:25:16 +000011496 }
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011497 if (needprompt) {
11498 setprompt(2);
11499 }
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011500 startlinno = g_parsefile->linno;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011501 for (;;) { /* until token or start of word found */
Denis Vlasenko834dee72008-10-07 09:18:30 +000011502 c = pgetc_fast();
Denis Vlasenko5e34ff22009-04-21 11:09:40 +000011503 if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011504 continue;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011505
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011506 if (c == '#') {
11507 while ((c = pgetc()) != '\n' && c != PEOF)
11508 continue;
11509 pungetc();
11510 } else if (c == '\\') {
11511 if (pgetc() != '\n') {
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011512 pungetc();
Denis Vlasenko834dee72008-10-07 09:18:30 +000011513 break; /* return readtoken1(...) */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011514 }
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011515 startlinno = ++g_parsefile->linno;
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011516 if (doprompt)
11517 setprompt(2);
11518 } else {
11519 const char *p;
11520
11521 p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
11522 if (c != PEOF) {
11523 if (c == '\n') {
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011524 g_parsefile->linno++;
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011525 needprompt = doprompt;
11526 }
11527
11528 p = strchr(xxreadtoken_chars, c);
Denis Vlasenko834dee72008-10-07 09:18:30 +000011529 if (p == NULL)
11530 break; /* return readtoken1(...) */
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011531
Denis Vlasenko834dee72008-10-07 09:18:30 +000011532 if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
11533 int cc = pgetc();
11534 if (cc == c) { /* double occurrence? */
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011535 p += xxreadtoken_doubles + 1;
11536 } else {
11537 pungetc();
Denis Vlasenko834dee72008-10-07 09:18:30 +000011538#if ENABLE_ASH_BASH_COMPAT
11539 if (c == '&' && cc == '>') /* &> */
11540 break; /* return readtoken1(...) */
11541#endif
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011542 }
11543 }
11544 }
11545 lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
11546 return lasttoken;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011547 }
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011548 } /* for (;;) */
Denis Vlasenko834dee72008-10-07 09:18:30 +000011549
11550 return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011551}
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011552#else /* old xxreadtoken */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011553#define RETURN(token) return lasttoken = token
11554static int
11555xxreadtoken(void)
11556{
11557 int c;
11558
11559 if (tokpushback) {
11560 tokpushback = 0;
11561 return lasttoken;
11562 }
11563 if (needprompt) {
11564 setprompt(2);
11565 }
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011566 startlinno = g_parsefile->linno;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011567 for (;;) { /* until token or start of word found */
Denis Vlasenko834dee72008-10-07 09:18:30 +000011568 c = pgetc_fast();
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011569 switch (c) {
11570 case ' ': case '\t':
11571#if ENABLE_ASH_ALIAS
11572 case PEOA:
11573#endif
11574 continue;
11575 case '#':
Denis Vlasenkof7d56652008-03-25 05:51:41 +000011576 while ((c = pgetc()) != '\n' && c != PEOF)
11577 continue;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011578 pungetc();
11579 continue;
11580 case '\\':
11581 if (pgetc() == '\n') {
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011582 startlinno = ++g_parsefile->linno;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011583 if (doprompt)
11584 setprompt(2);
11585 continue;
11586 }
11587 pungetc();
11588 goto breakloop;
11589 case '\n':
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011590 g_parsefile->linno++;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011591 needprompt = doprompt;
11592 RETURN(TNL);
11593 case PEOF:
11594 RETURN(TEOF);
11595 case '&':
11596 if (pgetc() == '&')
11597 RETURN(TAND);
11598 pungetc();
11599 RETURN(TBACKGND);
11600 case '|':
11601 if (pgetc() == '|')
11602 RETURN(TOR);
11603 pungetc();
11604 RETURN(TPIPE);
11605 case ';':
11606 if (pgetc() == ';')
11607 RETURN(TENDCASE);
11608 pungetc();
11609 RETURN(TSEMI);
11610 case '(':
11611 RETURN(TLP);
11612 case ')':
11613 RETURN(TRP);
11614 default:
11615 goto breakloop;
11616 }
11617 }
11618 breakloop:
11619 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
11620#undef RETURN
11621}
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011622#endif /* old xxreadtoken */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011623
11624static int
11625readtoken(void)
11626{
11627 int t;
11628#if DEBUG
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011629 smallint alreadyseen = tokpushback;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011630#endif
11631
11632#if ENABLE_ASH_ALIAS
11633 top:
11634#endif
11635
11636 t = xxreadtoken();
11637
11638 /*
11639 * eat newlines
11640 */
11641 if (checkkwd & CHKNL) {
11642 while (t == TNL) {
11643 parseheredoc();
11644 t = xxreadtoken();
11645 }
11646 }
11647
11648 if (t != TWORD || quoteflag) {
11649 goto out;
11650 }
11651
11652 /*
11653 * check for keywords
11654 */
11655 if (checkkwd & CHKKWD) {
11656 const char *const *pp;
11657
11658 pp = findkwd(wordtext);
11659 if (pp) {
11660 lasttoken = t = pp - tokname_array;
11661 TRACE(("keyword %s recognized\n", tokname(t)));
11662 goto out;
11663 }
11664 }
11665
11666 if (checkkwd & CHKALIAS) {
11667#if ENABLE_ASH_ALIAS
11668 struct alias *ap;
11669 ap = lookupalias(wordtext, 1);
11670 if (ap != NULL) {
11671 if (*ap->val) {
11672 pushstring(ap->val, ap);
11673 }
11674 goto top;
11675 }
11676#endif
11677 }
11678 out:
11679 checkkwd = 0;
11680#if DEBUG
11681 if (!alreadyseen)
11682 TRACE(("token %s %s\n", tokname(t), t == TWORD ? wordtext : ""));
11683 else
11684 TRACE(("reread token %s %s\n", tokname(t), t == TWORD ? wordtext : ""));
11685#endif
11686 return t;
Eric Andersencb57d552001-06-28 07:25:16 +000011687}
11688
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011689static char
11690peektoken(void)
11691{
11692 int t;
11693
11694 t = readtoken();
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011695 tokpushback = 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011696 return tokname_array[t][0];
11697}
Eric Andersencb57d552001-06-28 07:25:16 +000011698
11699/*
Denys Vlasenko86e83ec2009-07-23 22:07:07 +020011700 * Read and parse a command. Returns NODE_EOF on end of file.
11701 * (NULL is a valid parse tree indicating a blank line.)
Eric Andersencb57d552001-06-28 07:25:16 +000011702 */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011703static union node *
11704parsecmd(int interact)
Eric Andersen90898442003-08-06 11:20:52 +000011705{
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011706 int t;
Eric Andersencb57d552001-06-28 07:25:16 +000011707
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011708 tokpushback = 0;
11709 doprompt = interact;
11710 if (doprompt)
11711 setprompt(doprompt);
11712 needprompt = 0;
11713 t = readtoken();
11714 if (t == TEOF)
Denys Vlasenko86e83ec2009-07-23 22:07:07 +020011715 return NODE_EOF;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011716 if (t == TNL)
11717 return NULL;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011718 tokpushback = 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011719 return list(1);
11720}
11721
11722/*
11723 * Input any here documents.
11724 */
11725static void
11726parseheredoc(void)
11727{
11728 struct heredoc *here;
11729 union node *n;
11730
11731 here = heredoclist;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000011732 heredoclist = NULL;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011733
11734 while (here) {
11735 if (needprompt) {
11736 setprompt(2);
11737 }
11738 readtoken1(pgetc(), here->here->type == NHERE? SQSYNTAX : DQSYNTAX,
11739 here->eofmark, here->striptabs);
Denis Vlasenko597906c2008-02-20 16:38:54 +000011740 n = stzalloc(sizeof(struct narg));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011741 n->narg.type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000011742 /*n->narg.next = NULL; - stzalloc did it */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011743 n->narg.text = wordtext;
11744 n->narg.backquote = backquotelist;
11745 here->here->nhere.doc = n;
11746 here = here->next;
Eric Andersencb57d552001-06-28 07:25:16 +000011747 }
Eric Andersencb57d552001-06-28 07:25:16 +000011748}
11749
11750
11751/*
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +000011752 * called by editline -- any expansions to the prompt should be added here.
Eric Andersencb57d552001-06-28 07:25:16 +000011753 */
Denis Vlasenko131ae172007-02-18 13:00:19 +000011754#if ENABLE_ASH_EXPAND_PRMT
"Vladimir N. Oleynik"bef14d72005-09-05 13:25:11 +000011755static const char *
11756expandstr(const char *ps)
11757{
11758 union node n;
11759
Denis Vlasenko5c2b8142009-03-19 01:59:59 +000011760 /* XXX Fix (char *) cast. It _is_ a bug. ps is variable's value,
11761 * and token processing _can_ alter it (delete NULs etc). */
"Vladimir N. Oleynik"bef14d72005-09-05 13:25:11 +000011762 setinputstring((char *)ps);
Denis Vlasenko46a53062007-09-24 18:30:02 +000011763 readtoken1(pgetc(), PSSYNTAX, nullstr, 0);
"Vladimir N. Oleynik"bef14d72005-09-05 13:25:11 +000011764 popfile();
11765
11766 n.narg.type = NARG;
11767 n.narg.next = NULL;
11768 n.narg.text = wordtext;
11769 n.narg.backquote = backquotelist;
11770
11771 expandarg(&n, NULL, 0);
11772 return stackblock();
11773}
11774#endif
11775
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011776/*
11777 * Execute a command or commands contained in a string.
11778 */
11779static int
11780evalstring(char *s, int mask)
Eric Andersenc470f442003-07-28 09:56:35 +000011781{
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011782 union node *n;
11783 struct stackmark smark;
11784 int skip;
11785
11786 setinputstring(s);
11787 setstackmark(&smark);
11788
11789 skip = 0;
Denys Vlasenko86e83ec2009-07-23 22:07:07 +020011790 while ((n = parsecmd(0)) != NODE_EOF) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011791 evaltree(n, 0);
11792 popstackmark(&smark);
11793 skip = evalskip;
11794 if (skip)
11795 break;
11796 }
11797 popfile();
11798
11799 skip &= mask;
11800 evalskip = skip;
11801 return skip;
Eric Andersenc470f442003-07-28 09:56:35 +000011802}
11803
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011804/*
11805 * The eval command.
11806 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011807static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000011808evalcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011809{
11810 char *p;
11811 char *concat;
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011812
Denis Vlasenko68404f12008-03-17 09:00:54 +000011813 if (argv[1]) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011814 p = argv[1];
Denis Vlasenko68404f12008-03-17 09:00:54 +000011815 argv += 2;
11816 if (argv[0]) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011817 STARTSTACKSTR(concat);
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011818 for (;;) {
11819 concat = stack_putstr(p, concat);
Denis Vlasenko68404f12008-03-17 09:00:54 +000011820 p = *argv++;
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011821 if (p == NULL)
11822 break;
11823 STPUTC(' ', concat);
11824 }
11825 STPUTC('\0', concat);
11826 p = grabstackstr(concat);
11827 }
11828 evalstring(p, ~SKIPEVAL);
11829
11830 }
11831 return exitstatus;
11832}
11833
11834/*
11835 * Read and execute commands. "Top" is nonzero for the top level command
11836 * loop; it turns on prompting if the shell is interactive.
11837 */
11838static int
11839cmdloop(int top)
11840{
11841 union node *n;
11842 struct stackmark smark;
11843 int inter;
11844 int numeof = 0;
11845
11846 TRACE(("cmdloop(%d) called\n", top));
11847 for (;;) {
11848 int skip;
11849
11850 setstackmark(&smark);
11851#if JOBS
Denis Vlasenkob07a4962008-06-22 13:16:23 +000011852 if (doing_jobctl)
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011853 showjobs(stderr, SHOW_CHANGED);
11854#endif
11855 inter = 0;
11856 if (iflag && top) {
11857 inter++;
11858#if ENABLE_ASH_MAIL
11859 chkmail();
11860#endif
11861 }
11862 n = parsecmd(inter);
Denys Vlasenko7cee00e2009-07-24 01:08:03 +020011863#if DEBUG
11864 if (DEBUG > 2 && debug && (n != NODE_EOF))
Denys Vlasenko883cea42009-07-11 15:31:59 +020011865 showtree(n);
Denis Vlasenko135cecb2009-04-12 00:00:57 +000011866#endif
Denys Vlasenko86e83ec2009-07-23 22:07:07 +020011867 if (n == NODE_EOF) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011868 if (!top || numeof >= 50)
11869 break;
11870 if (!stoppedjobs()) {
11871 if (!Iflag)
11872 break;
11873 out2str("\nUse \"exit\" to leave shell.\n");
11874 }
11875 numeof++;
11876 } else if (nflag == 0) {
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +000011877 /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
11878 job_warning >>= 1;
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011879 numeof = 0;
11880 evaltree(n, 0);
11881 }
11882 popstackmark(&smark);
11883 skip = evalskip;
11884
11885 if (skip) {
11886 evalskip = 0;
11887 return skip & SKIPEVAL;
11888 }
11889 }
11890 return 0;
11891}
11892
Denis Vlasenko0dec6de2007-02-23 21:10:47 +000011893/*
11894 * Take commands from a file. To be compatible we should do a path
11895 * search for the file, which is necessary to find sub-commands.
11896 */
11897static char *
11898find_dot_file(char *name)
11899{
11900 char *fullname;
11901 const char *path = pathval();
11902 struct stat statb;
11903
11904 /* don't try this for absolute or relative paths */
11905 if (strchr(name, '/'))
11906 return name;
11907
Denis Vlasenko8ad78e12009-02-15 12:40:30 +000011908 /* IIRC standards do not say whether . is to be searched.
11909 * And it is even smaller this way, making it unconditional for now:
11910 */
11911 if (1) { /* ENABLE_ASH_BASH_COMPAT */
11912 fullname = name;
11913 goto try_cur_dir;
11914 }
11915
Denys Vlasenko82a6fb32009-06-14 19:42:12 +020011916 while ((fullname = path_advance(&path, name)) != NULL) {
Denis Vlasenko8ad78e12009-02-15 12:40:30 +000011917 try_cur_dir:
Denis Vlasenko0dec6de2007-02-23 21:10:47 +000011918 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
11919 /*
11920 * Don't bother freeing here, since it will
11921 * be freed by the caller.
11922 */
11923 return fullname;
11924 }
Denys Vlasenko82a6fb32009-06-14 19:42:12 +020011925 if (fullname != name)
11926 stunalloc(fullname);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +000011927 }
11928
11929 /* not found in the PATH */
11930 ash_msg_and_raise_error("%s: not found", name);
11931 /* NOTREACHED */
11932}
11933
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011934static int FAST_FUNC
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011935dotcmd(int argc, char **argv)
11936{
11937 struct strlist *sp;
11938 volatile struct shparam saveparam;
11939 int status = 0;
11940
11941 for (sp = cmdenviron; sp; sp = sp->next)
Denis Vlasenko4222ae42007-02-25 02:37:49 +000011942 setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011943
Denis Vlasenko68404f12008-03-17 09:00:54 +000011944 if (argv[1]) { /* That's what SVR2 does */
11945 char *fullname = find_dot_file(argv[1]);
11946 argv += 2;
11947 argc -= 2;
11948 if (argc) { /* argc > 0, argv[0] != NULL */
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011949 saveparam = shellparam;
Denis Vlasenko01631112007-12-16 17:20:38 +000011950 shellparam.malloced = 0;
Denis Vlasenko68404f12008-03-17 09:00:54 +000011951 shellparam.nparam = argc;
11952 shellparam.p = argv;
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011953 };
11954
11955 setinputfile(fullname, INPUT_PUSH_FILE);
11956 commandname = fullname;
11957 cmdloop(0);
11958 popfile();
11959
Denis Vlasenko68404f12008-03-17 09:00:54 +000011960 if (argc) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011961 freeparam(&shellparam);
11962 shellparam = saveparam;
11963 };
11964 status = exitstatus;
11965 }
11966 return status;
11967}
11968
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011969static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000011970exitcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011971{
11972 if (stoppedjobs())
11973 return 0;
Denis Vlasenko68404f12008-03-17 09:00:54 +000011974 if (argv[1])
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011975 exitstatus = number(argv[1]);
11976 raise_exception(EXEXIT);
11977 /* NOTREACHED */
11978}
11979
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011980/*
11981 * Read a file containing shell functions.
11982 */
11983static void
11984readcmdfile(char *name)
11985{
11986 setinputfile(name, INPUT_PUSH_FILE);
11987 cmdloop(0);
11988 popfile();
11989}
11990
11991
Denis Vlasenkocc571512007-02-23 21:10:35 +000011992/* ============ find_command inplementation */
11993
11994/*
11995 * Resolve a command name. If you change this routine, you may have to
11996 * change the shellexec routine as well.
11997 */
11998static void
11999find_command(char *name, struct cmdentry *entry, int act, const char *path)
12000{
12001 struct tblentry *cmdp;
12002 int idx;
12003 int prev;
12004 char *fullname;
12005 struct stat statb;
12006 int e;
12007 int updatetbl;
12008 struct builtincmd *bcmd;
12009
12010 /* If name contains a slash, don't use PATH or hash table */
12011 if (strchr(name, '/') != NULL) {
12012 entry->u.index = -1;
12013 if (act & DO_ABS) {
12014 while (stat(name, &statb) < 0) {
12015#ifdef SYSV
12016 if (errno == EINTR)
12017 continue;
12018#endif
12019 entry->cmdtype = CMDUNKNOWN;
12020 return;
12021 }
12022 }
12023 entry->cmdtype = CMDNORMAL;
12024 return;
12025 }
12026
Denis Vlasenkof20de5b2007-04-29 23:42:54 +000012027/* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
Denis Vlasenkocc571512007-02-23 21:10:35 +000012028
12029 updatetbl = (path == pathval());
12030 if (!updatetbl) {
12031 act |= DO_ALTPATH;
12032 if (strstr(path, "%builtin") != NULL)
12033 act |= DO_ALTBLTIN;
12034 }
12035
12036 /* If name is in the table, check answer will be ok */
12037 cmdp = cmdlookup(name, 0);
12038 if (cmdp != NULL) {
12039 int bit;
12040
12041 switch (cmdp->cmdtype) {
12042 default:
12043#if DEBUG
12044 abort();
12045#endif
12046 case CMDNORMAL:
12047 bit = DO_ALTPATH;
12048 break;
12049 case CMDFUNCTION:
12050 bit = DO_NOFUNC;
12051 break;
12052 case CMDBUILTIN:
12053 bit = DO_ALTBLTIN;
12054 break;
12055 }
12056 if (act & bit) {
12057 updatetbl = 0;
12058 cmdp = NULL;
12059 } else if (cmdp->rehash == 0)
12060 /* if not invalidated by cd, we're done */
12061 goto success;
12062 }
12063
12064 /* If %builtin not in path, check for builtin next */
12065 bcmd = find_builtin(name);
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +000012066 if (bcmd) {
12067 if (IS_BUILTIN_REGULAR(bcmd))
12068 goto builtin_success;
12069 if (act & DO_ALTPATH) {
12070 if (!(act & DO_ALTBLTIN))
12071 goto builtin_success;
12072 } else if (builtinloc <= 0) {
12073 goto builtin_success;
Denis Vlasenko8e858e22007-03-07 09:35:43 +000012074 }
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +000012075 }
Denis Vlasenkocc571512007-02-23 21:10:35 +000012076
Denis Vlasenkof20de5b2007-04-29 23:42:54 +000012077#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko7465dbc2008-04-13 02:25:53 +000012078 {
12079 int applet_no = find_applet_by_name(name);
12080 if (applet_no >= 0) {
12081 entry->cmdtype = CMDNORMAL;
12082 entry->u.index = -2 - applet_no;
12083 return;
12084 }
Denis Vlasenkof20de5b2007-04-29 23:42:54 +000012085 }
12086#endif
12087
Denis Vlasenkocc571512007-02-23 21:10:35 +000012088 /* We have to search path. */
12089 prev = -1; /* where to start */
12090 if (cmdp && cmdp->rehash) { /* doing a rehash */
12091 if (cmdp->cmdtype == CMDBUILTIN)
12092 prev = builtinloc;
12093 else
12094 prev = cmdp->param.index;
12095 }
12096
12097 e = ENOENT;
12098 idx = -1;
12099 loop:
Denys Vlasenko82a6fb32009-06-14 19:42:12 +020012100 while ((fullname = path_advance(&path, name)) != NULL) {
Denis Vlasenkocc571512007-02-23 21:10:35 +000012101 stunalloc(fullname);
Denis Vlasenkodee82b62007-07-29 14:05:27 +000012102 /* NB: code below will still use fullname
12103 * despite it being "unallocated" */
Denis Vlasenkocc571512007-02-23 21:10:35 +000012104 idx++;
12105 if (pathopt) {
12106 if (prefix(pathopt, "builtin")) {
12107 if (bcmd)
12108 goto builtin_success;
12109 continue;
Denis Vlasenko4a9ca132008-04-12 20:07:08 +000012110 }
12111 if ((act & DO_NOFUNC)
12112 || !prefix(pathopt, "func")
12113 ) { /* ignore unimplemented options */
Denis Vlasenkocc571512007-02-23 21:10:35 +000012114 continue;
12115 }
12116 }
12117 /* if rehash, don't redo absolute path names */
12118 if (fullname[0] == '/' && idx <= prev) {
12119 if (idx < prev)
12120 continue;
12121 TRACE(("searchexec \"%s\": no change\n", name));
12122 goto success;
12123 }
12124 while (stat(fullname, &statb) < 0) {
12125#ifdef SYSV
12126 if (errno == EINTR)
12127 continue;
12128#endif
12129 if (errno != ENOENT && errno != ENOTDIR)
12130 e = errno;
12131 goto loop;
12132 }
12133 e = EACCES; /* if we fail, this will be the error */
12134 if (!S_ISREG(statb.st_mode))
12135 continue;
12136 if (pathopt) { /* this is a %func directory */
12137 stalloc(strlen(fullname) + 1);
Denis Vlasenkodee82b62007-07-29 14:05:27 +000012138 /* NB: stalloc will return space pointed by fullname
12139 * (because we don't have any intervening allocations
12140 * between stunalloc above and this stalloc) */
Denis Vlasenkocc571512007-02-23 21:10:35 +000012141 readcmdfile(fullname);
12142 cmdp = cmdlookup(name, 0);
12143 if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
12144 ash_msg_and_raise_error("%s not defined in %s", name, fullname);
12145 stunalloc(fullname);
12146 goto success;
12147 }
12148 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
12149 if (!updatetbl) {
12150 entry->cmdtype = CMDNORMAL;
12151 entry->u.index = idx;
12152 return;
12153 }
12154 INT_OFF;
12155 cmdp = cmdlookup(name, 1);
12156 cmdp->cmdtype = CMDNORMAL;
12157 cmdp->param.index = idx;
12158 INT_ON;
12159 goto success;
12160 }
12161
12162 /* We failed. If there was an entry for this command, delete it */
12163 if (cmdp && updatetbl)
12164 delete_cmd_entry();
12165 if (act & DO_ERR)
12166 ash_msg("%s: %s", name, errmsg(e, "not found"));
12167 entry->cmdtype = CMDUNKNOWN;
12168 return;
12169
12170 builtin_success:
12171 if (!updatetbl) {
12172 entry->cmdtype = CMDBUILTIN;
12173 entry->u.cmd = bcmd;
12174 return;
12175 }
12176 INT_OFF;
12177 cmdp = cmdlookup(name, 1);
12178 cmdp->cmdtype = CMDBUILTIN;
12179 cmdp->param.cmd = bcmd;
12180 INT_ON;
12181 success:
12182 cmdp->rehash = 0;
12183 entry->cmdtype = cmdp->cmdtype;
12184 entry->u = cmdp->param;
12185}
12186
12187
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012188/* ============ trap.c */
Eric Andersenc470f442003-07-28 09:56:35 +000012189
Eric Andersencb57d552001-06-28 07:25:16 +000012190/*
Eric Andersencb57d552001-06-28 07:25:16 +000012191 * The trap builtin.
12192 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012193static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012194trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersencb57d552001-06-28 07:25:16 +000012195{
12196 char *action;
12197 char **ap;
12198 int signo;
12199
Eric Andersenc470f442003-07-28 09:56:35 +000012200 nextopt(nullstr);
12201 ap = argptr;
12202 if (!*ap) {
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012203 for (signo = 0; signo < NSIG; signo++) {
Eric Andersencb57d552001-06-28 07:25:16 +000012204 if (trap[signo] != NULL) {
Eric Andersenc470f442003-07-28 09:56:35 +000012205 out1fmt("trap -- %s %s\n",
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +000012206 single_quote(trap[signo]),
12207 get_signame(signo));
Eric Andersencb57d552001-06-28 07:25:16 +000012208 }
12209 }
12210 return 0;
12211 }
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +000012212 action = NULL;
12213 if (ap[1])
Eric Andersencb57d552001-06-28 07:25:16 +000012214 action = *ap++;
12215 while (*ap) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +000012216 signo = get_signum(*ap);
12217 if (signo < 0)
Denis Vlasenkob012b102007-02-19 22:43:01 +000012218 ash_msg_and_raise_error("%s: bad trap", *ap);
12219 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +000012220 if (action) {
Denis Vlasenko9f739442006-12-16 23:49:13 +000012221 if (LONE_DASH(action))
Eric Andersencb57d552001-06-28 07:25:16 +000012222 action = NULL;
12223 else
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012224 action = ckstrdup(action);
Eric Andersencb57d552001-06-28 07:25:16 +000012225 }
Denis Vlasenko60818682007-09-28 22:07:23 +000012226 free(trap[signo]);
Eric Andersencb57d552001-06-28 07:25:16 +000012227 trap[signo] = action;
12228 if (signo != 0)
12229 setsignal(signo);
Denis Vlasenkob012b102007-02-19 22:43:01 +000012230 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +000012231 ap++;
12232 }
12233 return 0;
12234}
12235
Eric Andersenc470f442003-07-28 09:56:35 +000012236
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012237/* ============ Builtins */
Eric Andersenc470f442003-07-28 09:56:35 +000012238
Denis Vlasenko8e1c7152007-01-22 07:21:38 +000012239#if !ENABLE_FEATURE_SH_EXTRA_QUIET
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012240/*
12241 * Lists available builtins
12242 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012243static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012244helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersenc470f442003-07-28 09:56:35 +000012245{
Denis Vlasenko6b06cb82008-05-15 21:30:45 +000012246 unsigned col;
12247 unsigned i;
Eric Andersenc470f442003-07-28 09:56:35 +000012248
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +020012249 out1fmt(
Denis Vlasenko34d4d892009-04-04 20:24:37 +000012250 "Built-in commands:\n"
12251 "------------------\n");
Denis Vlasenkob71c6682007-07-21 15:08:09 +000012252 for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
Eric Andersenc470f442003-07-28 09:56:35 +000012253 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
Denis Vlasenko52764022007-02-24 13:42:56 +000012254 builtintab[i].name + 1);
Eric Andersenc470f442003-07-28 09:56:35 +000012255 if (col > 60) {
12256 out1fmt("\n");
12257 col = 0;
12258 }
12259 }
Denis Vlasenko80d14be2007-04-10 23:03:30 +000012260#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko1aa7e472007-11-28 06:49:03 +000012261 {
12262 const char *a = applet_names;
12263 while (*a) {
12264 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
12265 if (col > 60) {
12266 out1fmt("\n");
12267 col = 0;
12268 }
12269 a += strlen(a) + 1;
Eric Andersenc470f442003-07-28 09:56:35 +000012270 }
12271 }
12272#endif
12273 out1fmt("\n\n");
12274 return EXIT_SUCCESS;
12275}
Denis Vlasenko131ae172007-02-18 13:00:19 +000012276#endif /* FEATURE_SH_EXTRA_QUIET */
Eric Andersenc470f442003-07-28 09:56:35 +000012277
Eric Andersencb57d552001-06-28 07:25:16 +000012278/*
Eric Andersencb57d552001-06-28 07:25:16 +000012279 * The export and readonly commands.
12280 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012281static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012282exportcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +000012283{
12284 struct var *vp;
12285 char *name;
12286 const char *p;
Eric Andersenc470f442003-07-28 09:56:35 +000012287 char **aptr;
Denis Vlasenkob7304742008-10-20 08:15:51 +000012288 int flag = argv[0][0] == 'r' ? VREADONLY : VEXPORT;
Eric Andersencb57d552001-06-28 07:25:16 +000012289
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012290 if (nextopt("p") != 'p') {
12291 aptr = argptr;
12292 name = *aptr;
12293 if (name) {
12294 do {
12295 p = strchr(name, '=');
12296 if (p != NULL) {
12297 p++;
12298 } else {
12299 vp = *findvar(hashvar(name), name);
12300 if (vp) {
12301 vp->flags |= flag;
12302 continue;
12303 }
Eric Andersencb57d552001-06-28 07:25:16 +000012304 }
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012305 setvar(name, p, flag);
12306 } while ((name = *++aptr) != NULL);
12307 return 0;
12308 }
Eric Andersencb57d552001-06-28 07:25:16 +000012309 }
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012310 showvars(argv[0], flag, 0);
Eric Andersencb57d552001-06-28 07:25:16 +000012311 return 0;
12312}
12313
Eric Andersencb57d552001-06-28 07:25:16 +000012314/*
Denis Vlasenko5651bfc2007-02-23 21:08:58 +000012315 * Delete a function if it exists.
Eric Andersencb57d552001-06-28 07:25:16 +000012316 */
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012317static void
Denis Vlasenko5651bfc2007-02-23 21:08:58 +000012318unsetfunc(const char *name)
Aaron Lehmannb6ecbdc2001-12-06 03:37:38 +000012319{
Denis Vlasenko5651bfc2007-02-23 21:08:58 +000012320 struct tblentry *cmdp;
Eric Andersencb57d552001-06-28 07:25:16 +000012321
Denis Vlasenko5651bfc2007-02-23 21:08:58 +000012322 cmdp = cmdlookup(name, 0);
12323 if (cmdp!= NULL && cmdp->cmdtype == CMDFUNCTION)
12324 delete_cmd_entry();
Eric Andersenc470f442003-07-28 09:56:35 +000012325}
12326
Eric Andersencb57d552001-06-28 07:25:16 +000012327/*
Eric Andersencb57d552001-06-28 07:25:16 +000012328 * The unset builtin command. We unset the function before we unset the
12329 * variable to allow a function to be unset when there is a readonly variable
12330 * with the same name.
12331 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012332static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012333unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersencb57d552001-06-28 07:25:16 +000012334{
12335 char **ap;
12336 int i;
Eric Andersenc470f442003-07-28 09:56:35 +000012337 int flag = 0;
Eric Andersencb57d552001-06-28 07:25:16 +000012338 int ret = 0;
12339
12340 while ((i = nextopt("vf")) != '\0') {
Eric Andersenc470f442003-07-28 09:56:35 +000012341 flag = i;
Eric Andersencb57d552001-06-28 07:25:16 +000012342 }
Eric Andersencb57d552001-06-28 07:25:16 +000012343
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012344 for (ap = argptr; *ap; ap++) {
Eric Andersenc470f442003-07-28 09:56:35 +000012345 if (flag != 'f') {
12346 i = unsetvar(*ap);
12347 ret |= i;
12348 if (!(i & 2))
12349 continue;
12350 }
12351 if (flag != 'v')
Eric Andersencb57d552001-06-28 07:25:16 +000012352 unsetfunc(*ap);
Eric Andersencb57d552001-06-28 07:25:16 +000012353 }
Eric Andersenc470f442003-07-28 09:56:35 +000012354 return ret & 1;
Eric Andersencb57d552001-06-28 07:25:16 +000012355}
12356
12357
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +000012358/* setmode.c */
Eric Andersencb57d552001-06-28 07:25:16 +000012359
Eric Andersenc470f442003-07-28 09:56:35 +000012360#include <sys/times.h>
12361
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000012362static const unsigned char timescmd_str[] ALIGN1 = {
Manuel Novoa III 4456f252003-08-13 17:48:47 +000012363 ' ', offsetof(struct tms, tms_utime),
12364 '\n', offsetof(struct tms, tms_stime),
12365 ' ', offsetof(struct tms, tms_cutime),
12366 '\n', offsetof(struct tms, tms_cstime),
12367 0
12368};
Eric Andersencb57d552001-06-28 07:25:16 +000012369
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012370static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012371timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Manuel Novoa III 4456f252003-08-13 17:48:47 +000012372{
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012373 long clk_tck, s, t;
Manuel Novoa III 4456f252003-08-13 17:48:47 +000012374 const unsigned char *p;
12375 struct tms buf;
12376
12377 clk_tck = sysconf(_SC_CLK_TCK);
Eric Andersencb57d552001-06-28 07:25:16 +000012378 times(&buf);
Manuel Novoa III 4456f252003-08-13 17:48:47 +000012379
12380 p = timescmd_str;
12381 do {
12382 t = *(clock_t *)(((char *) &buf) + p[1]);
12383 s = t / clk_tck;
12384 out1fmt("%ldm%ld.%.3lds%c",
12385 s/60, s%60,
12386 ((t - s * clk_tck) * 1000) / clk_tck,
12387 p[0]);
12388 } while (*(p += 2));
12389
Eric Andersencb57d552001-06-28 07:25:16 +000012390 return 0;
12391}
12392
Mike Frysinger98c52642009-04-02 10:02:37 +000012393#if ENABLE_SH_MATH_SUPPORT
Eric Andersenc470f442003-07-28 09:56:35 +000012394/*
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +000012395 * The let builtin. partial stolen from GNU Bash, the Bourne Again SHell.
12396 * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
Eric Andersen90898442003-08-06 11:20:52 +000012397 *
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +000012398 * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
Eric Andersenc470f442003-07-28 09:56:35 +000012399 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012400static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012401letcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersenc470f442003-07-28 09:56:35 +000012402{
Denis Vlasenko68404f12008-03-17 09:00:54 +000012403 arith_t i;
Eric Andersenc470f442003-07-28 09:56:35 +000012404
Denis Vlasenko68404f12008-03-17 09:00:54 +000012405 argv++;
12406 if (!*argv)
Denis Vlasenkob012b102007-02-19 22:43:01 +000012407 ash_msg_and_raise_error("expression expected");
Denis Vlasenko68404f12008-03-17 09:00:54 +000012408 do {
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +000012409 i = ash_arith(*argv);
Denis Vlasenko68404f12008-03-17 09:00:54 +000012410 } while (*++argv);
Eric Andersenc470f442003-07-28 09:56:35 +000012411
Denis Vlasenkod9e15f22006-11-27 16:49:55 +000012412 return !i;
Eric Andersenc470f442003-07-28 09:56:35 +000012413}
Mike Frysinger98c52642009-04-02 10:02:37 +000012414#endif /* SH_MATH_SUPPORT */
Eric Andersenc470f442003-07-28 09:56:35 +000012415
Eric Andersenc470f442003-07-28 09:56:35 +000012416
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012417/* ============ miscbltin.c
12418 *
Eric Andersenaff114c2004-04-14 17:51:38 +000012419 * Miscellaneous builtins.
Eric Andersenc470f442003-07-28 09:56:35 +000012420 */
12421
12422#undef rflag
12423
Denis Vlasenko83e5d6f2006-12-18 21:49:06 +000012424#if defined(__GLIBC__) && __GLIBC__ == 2 && __GLIBC_MINOR__ < 1
Eric Andersenc470f442003-07-28 09:56:35 +000012425typedef enum __rlimit_resource rlim_t;
12426#endif
Eric Andersen74bcd162001-07-30 21:41:37 +000012427
Eric Andersenc470f442003-07-28 09:56:35 +000012428/*
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012429 * The read builtin. Options:
12430 * -r Do not interpret '\' specially
12431 * -s Turn off echo (tty only)
12432 * -n NCHARS Read NCHARS max
12433 * -p PROMPT Display PROMPT on stderr (if input is from tty)
12434 * -t SECONDS Timeout after SECONDS (tty or pipe only)
12435 * -u FD Read from given FD instead of fd 0
Eric Andersenc470f442003-07-28 09:56:35 +000012436 * This uses unbuffered input, which may be avoidable in some cases.
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012437 * TODO: bash also has:
12438 * -a ARRAY Read into array[0],[1],etc
12439 * -d DELIM End on DELIM char, not newline
12440 * -e Use line editing (tty only)
Eric Andersenc470f442003-07-28 09:56:35 +000012441 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012442static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012443readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersenc470f442003-07-28 09:56:35 +000012444{
Denis Vlasenko9cd4c762008-06-18 19:22:19 +000012445 static const char *const arg_REPLY[] = { "REPLY", NULL };
12446
Eric Andersenc470f442003-07-28 09:56:35 +000012447 char **ap;
12448 int backslash;
12449 char c;
12450 int rflag;
12451 char *prompt;
12452 const char *ifs;
12453 char *p;
12454 int startword;
12455 int status;
12456 int i;
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012457 int fd = 0;
Denis Vlasenko131ae172007-02-18 13:00:19 +000012458#if ENABLE_ASH_READ_NCHARS
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012459 int nchars = 0; /* if != 0, -n is in effect */
Paul Fox02eb9342005-09-07 16:56:02 +000012460 int silent = 0;
12461 struct termios tty, old_tty;
12462#endif
Denis Vlasenko131ae172007-02-18 13:00:19 +000012463#if ENABLE_ASH_READ_TIMEOUT
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012464 unsigned end_ms = 0;
12465 unsigned timeout = 0;
Paul Fox02eb9342005-09-07 16:56:02 +000012466#endif
Eric Andersenc470f442003-07-28 09:56:35 +000012467
12468 rflag = 0;
12469 prompt = NULL;
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012470 while ((i = nextopt("p:u:r"
Denis Vlasenko5e34ff22009-04-21 11:09:40 +000012471 IF_ASH_READ_TIMEOUT("t:")
12472 IF_ASH_READ_NCHARS("n:s")
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012473 )) != '\0') {
Denis Vlasenkobf0a2012006-12-26 10:42:51 +000012474 switch (i) {
Paul Fox02eb9342005-09-07 16:56:02 +000012475 case 'p':
Eric Andersenc470f442003-07-28 09:56:35 +000012476 prompt = optionarg;
Paul Fox02eb9342005-09-07 16:56:02 +000012477 break;
Denis Vlasenko131ae172007-02-18 13:00:19 +000012478#if ENABLE_ASH_READ_NCHARS
Paul Fox02eb9342005-09-07 16:56:02 +000012479 case 'n':
Denis Vlasenko037576d2007-10-20 18:30:38 +000012480 nchars = bb_strtou(optionarg, NULL, 10);
12481 if (nchars < 0 || errno)
Denis Vlasenkob012b102007-02-19 22:43:01 +000012482 ash_msg_and_raise_error("invalid count");
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012483 /* nchars == 0: off (bash 3.2 does this too) */
Paul Fox02eb9342005-09-07 16:56:02 +000012484 break;
12485 case 's':
12486 silent = 1;
12487 break;
Ned Ludd2123b7c2005-02-09 21:07:23 +000012488#endif
Denis Vlasenko131ae172007-02-18 13:00:19 +000012489#if ENABLE_ASH_READ_TIMEOUT
Paul Fox02eb9342005-09-07 16:56:02 +000012490 case 't':
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012491 timeout = bb_strtou(optionarg, NULL, 10);
12492 if (errno || timeout > UINT_MAX / 2048)
12493 ash_msg_and_raise_error("invalid timeout");
12494 timeout *= 1000;
12495#if 0 /* even bash have no -t N.NNN support */
Denis Vlasenko037576d2007-10-20 18:30:38 +000012496 ts.tv_sec = bb_strtou(optionarg, &p, 10);
Paul Fox02eb9342005-09-07 16:56:02 +000012497 ts.tv_usec = 0;
Denis Vlasenko037576d2007-10-20 18:30:38 +000012498 /* EINVAL means number is ok, but not terminated by NUL */
12499 if (*p == '.' && errno == EINVAL) {
Paul Fox02eb9342005-09-07 16:56:02 +000012500 char *p2;
12501 if (*++p) {
12502 int scale;
Denis Vlasenko037576d2007-10-20 18:30:38 +000012503 ts.tv_usec = bb_strtou(p, &p2, 10);
12504 if (errno)
Denis Vlasenkob012b102007-02-19 22:43:01 +000012505 ash_msg_and_raise_error("invalid timeout");
Paul Fox02eb9342005-09-07 16:56:02 +000012506 scale = p2 - p;
12507 /* normalize to usec */
12508 if (scale > 6)
Denis Vlasenkob012b102007-02-19 22:43:01 +000012509 ash_msg_and_raise_error("invalid timeout");
Paul Fox02eb9342005-09-07 16:56:02 +000012510 while (scale++ < 6)
12511 ts.tv_usec *= 10;
12512 }
Denis Vlasenko037576d2007-10-20 18:30:38 +000012513 } else if (ts.tv_sec < 0 || errno) {
Denis Vlasenkob012b102007-02-19 22:43:01 +000012514 ash_msg_and_raise_error("invalid timeout");
Paul Fox02eb9342005-09-07 16:56:02 +000012515 }
Denis Vlasenko037576d2007-10-20 18:30:38 +000012516 if (!(ts.tv_sec | ts.tv_usec)) { /* both are 0? */
Denis Vlasenkob012b102007-02-19 22:43:01 +000012517 ash_msg_and_raise_error("invalid timeout");
Denis Vlasenko037576d2007-10-20 18:30:38 +000012518 }
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012519#endif /* if 0 */
Paul Fox02eb9342005-09-07 16:56:02 +000012520 break;
12521#endif
12522 case 'r':
12523 rflag = 1;
12524 break;
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012525 case 'u':
12526 fd = bb_strtou(optionarg, NULL, 10);
12527 if (fd < 0 || errno)
12528 ash_msg_and_raise_error("invalid file descriptor");
12529 break;
Paul Fox02eb9342005-09-07 16:56:02 +000012530 default:
12531 break;
12532 }
Eric Andersenc470f442003-07-28 09:56:35 +000012533 }
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012534 if (prompt && isatty(fd)) {
Eric Andersenc470f442003-07-28 09:56:35 +000012535 out2str(prompt);
Eric Andersenc470f442003-07-28 09:56:35 +000012536 }
Denis Vlasenko5cedb752007-02-18 19:56:41 +000012537 ap = argptr;
12538 if (*ap == NULL)
Denis Vlasenko9cd4c762008-06-18 19:22:19 +000012539 ap = (char**)arg_REPLY;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000012540 ifs = bltinlookup("IFS");
12541 if (ifs == NULL)
Eric Andersenc470f442003-07-28 09:56:35 +000012542 ifs = defifs;
Denis Vlasenko131ae172007-02-18 13:00:19 +000012543#if ENABLE_ASH_READ_NCHARS
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012544 tcgetattr(fd, &tty);
12545 old_tty = tty;
12546 if (nchars || silent) {
12547 if (nchars) {
12548 tty.c_lflag &= ~ICANON;
12549 tty.c_cc[VMIN] = nchars < 256 ? nchars : 255;
Paul Fox02eb9342005-09-07 16:56:02 +000012550 }
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012551 if (silent) {
12552 tty.c_lflag &= ~(ECHO | ECHOK | ECHONL);
12553 }
12554 /* if tcgetattr failed, tcsetattr will fail too.
12555 * Ignoring, it's harmless. */
12556 tcsetattr(fd, TCSANOW, &tty);
Paul Fox02eb9342005-09-07 16:56:02 +000012557 }
12558#endif
Paul Fox02eb9342005-09-07 16:56:02 +000012559
Eric Andersenc470f442003-07-28 09:56:35 +000012560 status = 0;
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012561 startword = 2;
Eric Andersenc470f442003-07-28 09:56:35 +000012562 backslash = 0;
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012563#if ENABLE_ASH_READ_TIMEOUT
12564 if (timeout) /* NB: ensuring end_ms is nonzero */
12565 end_ms = ((unsigned)(monotonic_us() / 1000) + timeout) | 1;
12566#endif
Eric Andersenc470f442003-07-28 09:56:35 +000012567 STARTSTACKSTR(p);
Denis Vlasenko037576d2007-10-20 18:30:38 +000012568 do {
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012569 const char *is_ifs;
12570
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012571#if ENABLE_ASH_READ_TIMEOUT
12572 if (end_ms) {
12573 struct pollfd pfd[1];
12574 pfd[0].fd = fd;
12575 pfd[0].events = POLLIN;
12576 timeout = end_ms - (unsigned)(monotonic_us() / 1000);
12577 if ((int)timeout <= 0 /* already late? */
12578 || safe_poll(pfd, 1, timeout) != 1 /* no? wait... */
12579 ) { /* timed out! */
12580#if ENABLE_ASH_READ_NCHARS
12581 tcsetattr(fd, TCSANOW, &old_tty);
12582#endif
12583 return 1;
12584 }
12585 }
12586#endif
12587 if (nonblock_safe_read(fd, &c, 1) != 1) {
Eric Andersenc470f442003-07-28 09:56:35 +000012588 status = 1;
12589 break;
12590 }
12591 if (c == '\0')
12592 continue;
12593 if (backslash) {
12594 backslash = 0;
12595 if (c != '\n')
12596 goto put;
12597 continue;
12598 }
12599 if (!rflag && c == '\\') {
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012600 backslash = 1;
Eric Andersenc470f442003-07-28 09:56:35 +000012601 continue;
12602 }
12603 if (c == '\n')
12604 break;
Denis Vlasenkof6fbd622009-03-31 19:36:58 +000012605 /* $IFS splitting */
Denis Vlasenko551ffdc2009-04-01 19:48:05 +000012606/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_05 */
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012607 is_ifs = strchr(ifs, c);
12608 if (startword && is_ifs) {
12609 if (isspace(c))
12610 continue;
Denis Vlasenkof6fbd622009-03-31 19:36:58 +000012611 /* it is a non-space ifs char */
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012612 startword--;
12613 if (startword == 1) /* first one? */
Denis Vlasenkof6fbd622009-03-31 19:36:58 +000012614 continue; /* yes, it is not next word yet */
Eric Andersenc470f442003-07-28 09:56:35 +000012615 }
12616 startword = 0;
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012617 if (ap[1] != NULL && is_ifs) {
12618 const char *beg;
Eric Andersenc470f442003-07-28 09:56:35 +000012619 STACKSTRNUL(p);
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012620 beg = stackblock();
12621 setvar(*ap, beg, 0);
Eric Andersenc470f442003-07-28 09:56:35 +000012622 ap++;
Denis Vlasenkof6fbd622009-03-31 19:36:58 +000012623 /* can we skip one non-space ifs char? (2: yes) */
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012624 startword = isspace(c) ? 2 : 1;
Eric Andersenc470f442003-07-28 09:56:35 +000012625 STARTSTACKSTR(p);
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012626 continue;
Eric Andersenc470f442003-07-28 09:56:35 +000012627 }
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012628 put:
12629 STPUTC(c, p);
Eric Andersenc470f442003-07-28 09:56:35 +000012630 }
Denis Vlasenko037576d2007-10-20 18:30:38 +000012631/* end of do {} while: */
Denis Vlasenko131ae172007-02-18 13:00:19 +000012632#if ENABLE_ASH_READ_NCHARS
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012633 while (--nchars);
Denis Vlasenko037576d2007-10-20 18:30:38 +000012634#else
12635 while (1);
12636#endif
12637
12638#if ENABLE_ASH_READ_NCHARS
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012639 tcsetattr(fd, TCSANOW, &old_tty);
Paul Fox02eb9342005-09-07 16:56:02 +000012640#endif
12641
Eric Andersenc470f442003-07-28 09:56:35 +000012642 STACKSTRNUL(p);
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012643 /* Remove trailing space ifs chars */
12644 while ((char *)stackblock() <= --p && isspace(*p) && strchr(ifs, *p) != NULL)
Eric Andersenc470f442003-07-28 09:56:35 +000012645 *p = '\0';
12646 setvar(*ap, stackblock(), 0);
12647 while (*++ap != NULL)
12648 setvar(*ap, nullstr, 0);
12649 return status;
12650}
12651
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012652static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012653umaskcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersenc470f442003-07-28 09:56:35 +000012654{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000012655 static const char permuser[3] ALIGN1 = "ugo";
12656 static const char permmode[3] ALIGN1 = "rwx";
12657 static const short permmask[] ALIGN2 = {
Eric Andersenc470f442003-07-28 09:56:35 +000012658 S_IRUSR, S_IWUSR, S_IXUSR,
12659 S_IRGRP, S_IWGRP, S_IXGRP,
12660 S_IROTH, S_IWOTH, S_IXOTH
12661 };
12662
Denis Vlasenkoeb858492009-04-18 02:06:54 +000012663 /* TODO: use bb_parse_mode() instead */
12664
Eric Andersenc470f442003-07-28 09:56:35 +000012665 char *ap;
12666 mode_t mask;
12667 int i;
12668 int symbolic_mode = 0;
12669
12670 while (nextopt("S") != '\0') {
12671 symbolic_mode = 1;
12672 }
12673
Denis Vlasenkob012b102007-02-19 22:43:01 +000012674 INT_OFF;
Eric Andersenc470f442003-07-28 09:56:35 +000012675 mask = umask(0);
12676 umask(mask);
Denis Vlasenkob012b102007-02-19 22:43:01 +000012677 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +000012678
Denis Vlasenko5cedb752007-02-18 19:56:41 +000012679 ap = *argptr;
12680 if (ap == NULL) {
Eric Andersenc470f442003-07-28 09:56:35 +000012681 if (symbolic_mode) {
12682 char buf[18];
12683 char *p = buf;
12684
12685 for (i = 0; i < 3; i++) {
12686 int j;
12687
12688 *p++ = permuser[i];
12689 *p++ = '=';
12690 for (j = 0; j < 3; j++) {
12691 if ((mask & permmask[3 * i + j]) == 0) {
12692 *p++ = permmode[j];
12693 }
12694 }
12695 *p++ = ',';
12696 }
12697 *--p = 0;
12698 puts(buf);
12699 } else {
12700 out1fmt("%.4o\n", mask);
12701 }
12702 } else {
Denis Vlasenkoaa744452007-02-23 01:04:22 +000012703 if (isdigit((unsigned char) *ap)) {
Eric Andersenc470f442003-07-28 09:56:35 +000012704 mask = 0;
12705 do {
12706 if (*ap >= '8' || *ap < '0')
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +020012707 ash_msg_and_raise_error(msg_illnum, argv[1]);
Eric Andersenc470f442003-07-28 09:56:35 +000012708 mask = (mask << 3) + (*ap - '0');
12709 } while (*++ap != '\0');
12710 umask(mask);
12711 } else {
12712 mask = ~mask & 0777;
12713 if (!bb_parse_mode(ap, &mask)) {
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +000012714 ash_msg_and_raise_error("illegal mode: %s", ap);
Eric Andersenc470f442003-07-28 09:56:35 +000012715 }
12716 umask(~mask & 0777);
12717 }
12718 }
12719 return 0;
12720}
12721
12722/*
12723 * ulimit builtin
12724 *
12725 * This code, originally by Doug Gwyn, Doug Kingston, Eric Gisin, and
12726 * Michael Rendell was ripped from pdksh 5.0.8 and hacked for use with
12727 * ash by J.T. Conklin.
12728 *
12729 * Public domain.
12730 */
Eric Andersenc470f442003-07-28 09:56:35 +000012731struct limits {
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012732 uint8_t cmd; /* RLIMIT_xxx fit into it */
12733 uint8_t factor_shift; /* shift by to get rlim_{cur,max} values */
Eric Andersenc470f442003-07-28 09:56:35 +000012734 char option;
12735};
12736
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012737static const struct limits limits_tbl[] = {
Eric Andersenc470f442003-07-28 09:56:35 +000012738#ifdef RLIMIT_CPU
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012739 { RLIMIT_CPU, 0, 't' },
Eric Andersenc470f442003-07-28 09:56:35 +000012740#endif
12741#ifdef RLIMIT_FSIZE
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012742 { RLIMIT_FSIZE, 9, 'f' },
Eric Andersenc470f442003-07-28 09:56:35 +000012743#endif
12744#ifdef RLIMIT_DATA
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012745 { RLIMIT_DATA, 10, 'd' },
Eric Andersenc470f442003-07-28 09:56:35 +000012746#endif
12747#ifdef RLIMIT_STACK
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012748 { RLIMIT_STACK, 10, 's' },
Eric Andersenc470f442003-07-28 09:56:35 +000012749#endif
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012750#ifdef RLIMIT_CORE
12751 { RLIMIT_CORE, 9, 'c' },
Eric Andersenc470f442003-07-28 09:56:35 +000012752#endif
12753#ifdef RLIMIT_RSS
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012754 { RLIMIT_RSS, 10, 'm' },
Eric Andersenc470f442003-07-28 09:56:35 +000012755#endif
12756#ifdef RLIMIT_MEMLOCK
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012757 { RLIMIT_MEMLOCK, 10, 'l' },
Eric Andersenc470f442003-07-28 09:56:35 +000012758#endif
12759#ifdef RLIMIT_NPROC
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012760 { RLIMIT_NPROC, 0, 'p' },
Eric Andersenc470f442003-07-28 09:56:35 +000012761#endif
12762#ifdef RLIMIT_NOFILE
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012763 { RLIMIT_NOFILE, 0, 'n' },
Eric Andersenc470f442003-07-28 09:56:35 +000012764#endif
Glenn L McGrath76620622004-01-13 10:19:37 +000012765#ifdef RLIMIT_AS
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012766 { RLIMIT_AS, 10, 'v' },
Eric Andersenc470f442003-07-28 09:56:35 +000012767#endif
Glenn L McGrath76620622004-01-13 10:19:37 +000012768#ifdef RLIMIT_LOCKS
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012769 { RLIMIT_LOCKS, 0, 'w' },
Eric Andersenc470f442003-07-28 09:56:35 +000012770#endif
Eric Andersenc470f442003-07-28 09:56:35 +000012771};
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012772static const char limits_name[] =
12773#ifdef RLIMIT_CPU
12774 "time(seconds)" "\0"
12775#endif
12776#ifdef RLIMIT_FSIZE
12777 "file(blocks)" "\0"
12778#endif
12779#ifdef RLIMIT_DATA
12780 "data(kb)" "\0"
12781#endif
12782#ifdef RLIMIT_STACK
12783 "stack(kb)" "\0"
12784#endif
12785#ifdef RLIMIT_CORE
12786 "coredump(blocks)" "\0"
12787#endif
12788#ifdef RLIMIT_RSS
12789 "memory(kb)" "\0"
12790#endif
12791#ifdef RLIMIT_MEMLOCK
12792 "locked memory(kb)" "\0"
12793#endif
12794#ifdef RLIMIT_NPROC
12795 "process" "\0"
12796#endif
12797#ifdef RLIMIT_NOFILE
12798 "nofiles" "\0"
12799#endif
12800#ifdef RLIMIT_AS
12801 "vmemory(kb)" "\0"
12802#endif
12803#ifdef RLIMIT_LOCKS
12804 "locks" "\0"
12805#endif
12806;
Eric Andersenc470f442003-07-28 09:56:35 +000012807
Glenn L McGrath76620622004-01-13 10:19:37 +000012808enum limtype { SOFT = 0x1, HARD = 0x2 };
12809
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012810static void
12811printlim(enum limtype how, const struct rlimit *limit,
Glenn L McGrath76620622004-01-13 10:19:37 +000012812 const struct limits *l)
12813{
12814 rlim_t val;
12815
12816 val = limit->rlim_max;
12817 if (how & SOFT)
12818 val = limit->rlim_cur;
12819
12820 if (val == RLIM_INFINITY)
12821 out1fmt("unlimited\n");
12822 else {
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012823 val >>= l->factor_shift;
Glenn L McGrath76620622004-01-13 10:19:37 +000012824 out1fmt("%lld\n", (long long) val);
12825 }
12826}
12827
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012828static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012829ulimitcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersenc470f442003-07-28 09:56:35 +000012830{
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012831 int c;
Eric Andersenc470f442003-07-28 09:56:35 +000012832 rlim_t val = 0;
Glenn L McGrath76620622004-01-13 10:19:37 +000012833 enum limtype how = SOFT | HARD;
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012834 const struct limits *l;
12835 int set, all = 0;
12836 int optc, what;
12837 struct rlimit limit;
Eric Andersenc470f442003-07-28 09:56:35 +000012838
12839 what = 'f';
Glenn L McGrath16e45d72004-02-04 08:24:39 +000012840 while ((optc = nextopt("HSa"
12841#ifdef RLIMIT_CPU
12842 "t"
12843#endif
12844#ifdef RLIMIT_FSIZE
12845 "f"
12846#endif
12847#ifdef RLIMIT_DATA
12848 "d"
12849#endif
12850#ifdef RLIMIT_STACK
12851 "s"
12852#endif
12853#ifdef RLIMIT_CORE
12854 "c"
12855#endif
12856#ifdef RLIMIT_RSS
12857 "m"
12858#endif
12859#ifdef RLIMIT_MEMLOCK
12860 "l"
12861#endif
12862#ifdef RLIMIT_NPROC
12863 "p"
12864#endif
12865#ifdef RLIMIT_NOFILE
12866 "n"
12867#endif
12868#ifdef RLIMIT_AS
12869 "v"
12870#endif
12871#ifdef RLIMIT_LOCKS
12872 "w"
12873#endif
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000012874 )) != '\0')
Eric Andersenc470f442003-07-28 09:56:35 +000012875 switch (optc) {
12876 case 'H':
12877 how = HARD;
12878 break;
12879 case 'S':
12880 how = SOFT;
12881 break;
12882 case 'a':
12883 all = 1;
12884 break;
12885 default:
12886 what = optc;
12887 }
12888
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012889 for (l = limits_tbl; l->option != what; l++)
12890 continue;
Eric Andersenc470f442003-07-28 09:56:35 +000012891
12892 set = *argptr ? 1 : 0;
12893 if (set) {
12894 char *p = *argptr;
12895
12896 if (all || argptr[1])
Denis Vlasenkob012b102007-02-19 22:43:01 +000012897 ash_msg_and_raise_error("too many arguments");
Eric Andersen81fe1232003-07-29 06:38:40 +000012898 if (strncmp(p, "unlimited\n", 9) == 0)
Eric Andersenc470f442003-07-28 09:56:35 +000012899 val = RLIM_INFINITY;
12900 else {
12901 val = (rlim_t) 0;
12902
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000012903 while ((c = *p++) >= '0' && c <= '9') {
Eric Andersenc470f442003-07-28 09:56:35 +000012904 val = (val * 10) + (long)(c - '0');
Denis Vlasenko6b06cb82008-05-15 21:30:45 +000012905 // val is actually 'unsigned long int' and can't get < 0
Eric Andersenc470f442003-07-28 09:56:35 +000012906 if (val < (rlim_t) 0)
12907 break;
12908 }
12909 if (c)
Denis Vlasenkob012b102007-02-19 22:43:01 +000012910 ash_msg_and_raise_error("bad number");
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012911 val <<= l->factor_shift;
Eric Andersenc470f442003-07-28 09:56:35 +000012912 }
12913 }
12914 if (all) {
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012915 const char *lname = limits_name;
12916 for (l = limits_tbl; l != &limits_tbl[ARRAY_SIZE(limits_tbl)]; l++) {
Eric Andersenc470f442003-07-28 09:56:35 +000012917 getrlimit(l->cmd, &limit);
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012918 out1fmt("%-20s ", lname);
12919 lname += strlen(lname) + 1;
Glenn L McGrath76620622004-01-13 10:19:37 +000012920 printlim(how, &limit, l);
Eric Andersenc470f442003-07-28 09:56:35 +000012921 }
12922 return 0;
12923 }
12924
12925 getrlimit(l->cmd, &limit);
12926 if (set) {
12927 if (how & HARD)
12928 limit.rlim_max = val;
12929 if (how & SOFT)
12930 limit.rlim_cur = val;
12931 if (setrlimit(l->cmd, &limit) < 0)
Denis Vlasenkob012b102007-02-19 22:43:01 +000012932 ash_msg_and_raise_error("error setting limit (%m)");
Eric Andersenc470f442003-07-28 09:56:35 +000012933 } else {
Glenn L McGrath76620622004-01-13 10:19:37 +000012934 printlim(how, &limit, l);
Eric Andersenc470f442003-07-28 09:56:35 +000012935 }
12936 return 0;
12937}
12938
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012939/* ============ main() and helpers */
12940
12941/*
12942 * Called to exit the shell.
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012943 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012944static void exitshell(void) NORETURN;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012945static void
12946exitshell(void)
12947{
12948 struct jmploc loc;
12949 char *p;
12950 int status;
12951
12952 status = exitstatus;
12953 TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
12954 if (setjmp(loc.loc)) {
Denis Vlasenko7f88e342009-03-19 03:36:18 +000012955 if (exception_type == EXEXIT)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012956/* dash bug: it just does _exit(exitstatus) here
12957 * but we have to do setjobctl(0) first!
12958 * (bug is still not fixed in dash-0.5.3 - if you run dash
12959 * under Midnight Commander, on exit from dash MC is backgrounded) */
12960 status = exitstatus;
12961 goto out;
12962 }
12963 exception_handler = &loc;
12964 p = trap[0];
12965 if (p) {
12966 trap[0] = NULL;
12967 evalstring(p, 0);
12968 }
12969 flush_stdout_stderr();
12970 out:
12971 setjobctl(0);
12972 _exit(status);
12973 /* NOTREACHED */
12974}
12975
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012976static void
12977init(void)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012978{
12979 /* from input.c: */
Denis Vlasenko41eb3002008-11-28 03:42:31 +000012980 basepf.next_to_pgetc = basepf.buf = basebuf;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012981
12982 /* from trap.c: */
12983 signal(SIGCHLD, SIG_DFL);
12984
12985 /* from var.c: */
12986 {
12987 char **envp;
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012988 char ppid[sizeof(int)*3 + 1];
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012989 const char *p;
12990 struct stat st1, st2;
12991
12992 initvar();
12993 for (envp = environ; envp && *envp; envp++) {
12994 if (strchr(*envp, '=')) {
12995 setvareq(*envp, VEXPORT|VTEXTFIXED);
12996 }
12997 }
12998
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012999 snprintf(ppid, sizeof(ppid), "%u", (unsigned) getppid());
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013000 setvar("PPID", ppid, 0);
13001
13002 p = lookupvar("PWD");
13003 if (p)
13004 if (*p != '/' || stat(p, &st1) || stat(".", &st2)
13005 || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino)
13006 p = '\0';
13007 setpwd(p, 0);
13008 }
13009}
13010
13011/*
13012 * Process the shell command line arguments.
13013 */
13014static void
Denis Vlasenko68404f12008-03-17 09:00:54 +000013015procargs(char **argv)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013016{
13017 int i;
13018 const char *xminusc;
13019 char **xargv;
13020
13021 xargv = argv;
13022 arg0 = xargv[0];
Denis Vlasenko68404f12008-03-17 09:00:54 +000013023 /* if (xargv[0]) - mmm, this is always true! */
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013024 xargv++;
13025 for (i = 0; i < NOPTS; i++)
13026 optlist[i] = 2;
13027 argptr = xargv;
Denis Vlasenko28bf6712008-02-14 15:01:47 +000013028 if (options(1)) {
13029 /* it already printed err message */
13030 raise_exception(EXERROR);
13031 }
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013032 xargv = argptr;
13033 xminusc = minusc;
13034 if (*xargv == NULL) {
13035 if (xminusc)
13036 ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
13037 sflag = 1;
13038 }
13039 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
13040 iflag = 1;
13041 if (mflag == 2)
13042 mflag = iflag;
13043 for (i = 0; i < NOPTS; i++)
13044 if (optlist[i] == 2)
13045 optlist[i] = 0;
13046#if DEBUG == 2
13047 debug = 1;
13048#endif
13049 /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
13050 if (xminusc) {
13051 minusc = *xargv++;
13052 if (*xargv)
13053 goto setarg0;
13054 } else if (!sflag) {
13055 setinputfile(*xargv, 0);
13056 setarg0:
13057 arg0 = *xargv++;
13058 commandname = arg0;
13059 }
13060
13061 shellparam.p = xargv;
13062#if ENABLE_ASH_GETOPTS
13063 shellparam.optind = 1;
13064 shellparam.optoff = -1;
13065#endif
Denis Vlasenko01631112007-12-16 17:20:38 +000013066 /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013067 while (*xargv) {
13068 shellparam.nparam++;
13069 xargv++;
13070 }
13071 optschanged();
13072}
13073
13074/*
13075 * Read /etc/profile or .profile.
13076 */
13077static void
13078read_profile(const char *name)
13079{
13080 int skip;
13081
13082 if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
13083 return;
13084 skip = cmdloop(0);
13085 popfile();
13086 if (skip)
13087 exitshell();
13088}
13089
Denis Vlasenko0c032a42007-02-23 01:03:40 +000013090/*
13091 * This routine is called when an error or an interrupt occurs in an
13092 * interactive shell and control is returned to the main command loop.
13093 */
13094static void
13095reset(void)
13096{
13097 /* from eval.c: */
13098 evalskip = 0;
13099 loopnest = 0;
13100 /* from input.c: */
Denis Vlasenko41eb3002008-11-28 03:42:31 +000013101 g_parsefile->left_in_buffer = 0;
13102 g_parsefile->left_in_line = 0; /* clear input buffer */
Denis Vlasenko0c032a42007-02-23 01:03:40 +000013103 popallfiles();
13104 /* from parser.c: */
13105 tokpushback = 0;
13106 checkkwd = 0;
13107 /* from redir.c: */
Denis Vlasenko34c73c42008-08-16 11:48:02 +000013108 clearredir(/*drop:*/ 0);
Denis Vlasenko0c032a42007-02-23 01:03:40 +000013109}
13110
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013111#if PROFILE
13112static short profile_buf[16384];
13113extern int etext();
13114#endif
13115
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000013116/*
13117 * Main routine. We initialize things, parse the arguments, execute
13118 * profiles if we're a login shell, and then call cmdloop to execute
13119 * commands. The setjmp call sets up the location to jump to when an
13120 * exception occurs. When an exception occurs the variable "state"
13121 * is used to figure out how far we had gotten.
13122 */
Denis Vlasenko9b49a5e2007-10-11 10:05:36 +000013123int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000013124int ash_main(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013125{
Mike Frysinger98c52642009-04-02 10:02:37 +000013126 const char *shinit;
Denis Vlasenko4e12b1a2008-12-23 23:36:47 +000013127 volatile smallint state;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013128 struct jmploc jmploc;
13129 struct stackmark smark;
13130
Denis Vlasenko01631112007-12-16 17:20:38 +000013131 /* Initialize global data */
13132 INIT_G_misc();
13133 INIT_G_memstack();
13134 INIT_G_var();
Denis Vlasenkoee87ebf2007-12-21 22:18:16 +000013135#if ENABLE_ASH_ALIAS
Denis Vlasenko01631112007-12-16 17:20:38 +000013136 INIT_G_alias();
Denis Vlasenkoee87ebf2007-12-21 22:18:16 +000013137#endif
Denis Vlasenko01631112007-12-16 17:20:38 +000013138 INIT_G_cmdtable();
13139
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013140#if PROFILE
13141 monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
13142#endif
13143
13144#if ENABLE_FEATURE_EDITING
13145 line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
13146#endif
13147 state = 0;
13148 if (setjmp(jmploc.loc)) {
Denis Vlasenko7f88e342009-03-19 03:36:18 +000013149 smallint e;
Denis Vlasenko4e12b1a2008-12-23 23:36:47 +000013150 smallint s;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013151
13152 reset();
13153
Denis Vlasenko7f88e342009-03-19 03:36:18 +000013154 e = exception_type;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013155 if (e == EXERROR)
13156 exitstatus = 2;
13157 s = state;
13158 if (e == EXEXIT || s == 0 || iflag == 0 || shlvl)
13159 exitshell();
Denis Vlasenko7f88e342009-03-19 03:36:18 +000013160 if (e == EXINT)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013161 outcslow('\n', stderr);
Denis Vlasenko7f88e342009-03-19 03:36:18 +000013162
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013163 popstackmark(&smark);
13164 FORCE_INT_ON; /* enable interrupts */
13165 if (s == 1)
13166 goto state1;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000013167 if (s == 2)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013168 goto state2;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000013169 if (s == 3)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013170 goto state3;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000013171 goto state4;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013172 }
13173 exception_handler = &jmploc;
13174#if DEBUG
13175 opentrace();
Denis Vlasenko653d8e72009-03-19 21:59:35 +000013176 TRACE(("Shell args: "));
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000013177 trace_puts_args(argv);
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013178#endif
13179 rootpid = getpid();
13180
13181#if ENABLE_ASH_RANDOM_SUPPORT
Denis Vlasenkoce13b762008-06-29 02:25:53 +000013182 /* Can use monotonic_ns() for better randomness but for now it is
13183 * not used anywhere else in busybox... so avoid bloat */
13184 random_galois_LFSR = random_LCG = rootpid + monotonic_us();
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013185#endif
13186 init();
13187 setstackmark(&smark);
Denis Vlasenko68404f12008-03-17 09:00:54 +000013188 procargs(argv);
13189
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013190#if ENABLE_FEATURE_EDITING_SAVEHISTORY
13191 if (iflag) {
13192 const char *hp = lookupvar("HISTFILE");
13193
13194 if (hp == NULL) {
13195 hp = lookupvar("HOME");
13196 if (hp != NULL) {
13197 char *defhp = concat_path_file(hp, ".ash_history");
13198 setvar("HISTFILE", defhp, 0);
13199 free(defhp);
13200 }
13201 }
13202 }
13203#endif
Denis Vlasenko4e12b1a2008-12-23 23:36:47 +000013204 if (/* argv[0] && */ argv[0][0] == '-')
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013205 isloginsh = 1;
13206 if (isloginsh) {
13207 state = 1;
13208 read_profile("/etc/profile");
13209 state1:
13210 state = 2;
13211 read_profile(".profile");
13212 }
13213 state2:
13214 state = 3;
13215 if (
13216#ifndef linux
Denis Vlasenko0c032a42007-02-23 01:03:40 +000013217 getuid() == geteuid() && getgid() == getegid() &&
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013218#endif
Denis Vlasenko0c032a42007-02-23 01:03:40 +000013219 iflag
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013220 ) {
13221 shinit = lookupvar("ENV");
13222 if (shinit != NULL && *shinit != '\0') {
13223 read_profile(shinit);
13224 }
13225 }
13226 state3:
13227 state = 4;
Denis Vlasenko5c2b8142009-03-19 01:59:59 +000013228 if (minusc) {
13229 /* evalstring pushes parsefile stack.
13230 * Ensure we don't falsely claim that 0 (stdin)
Denis Vlasenko5368ad52009-03-20 10:20:08 +000013231 * is one of stacked source fds.
13232 * Testcase: ash -c 'exec 1>&0' must not complain. */
Denis Vlasenko5c2b8142009-03-19 01:59:59 +000013233 if (!sflag)
13234 g_parsefile->fd = -1;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013235 evalstring(minusc, 0);
Denis Vlasenko5c2b8142009-03-19 01:59:59 +000013236 }
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013237
13238 if (sflag || minusc == NULL) {
13239#if ENABLE_FEATURE_EDITING_SAVEHISTORY
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +000013240 if (iflag) {
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013241 const char *hp = lookupvar("HISTFILE");
Denis Vlasenko5c2b8142009-03-19 01:59:59 +000013242 if (hp)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013243 line_input_state->hist_file = hp;
13244 }
13245#endif
13246 state4: /* XXX ??? - why isn't this before the "if" statement */
13247 cmdloop(1);
13248 }
13249#if PROFILE
13250 monitor(0);
13251#endif
13252#ifdef GPROF
13253 {
13254 extern void _mcleanup(void);
13255 _mcleanup();
13256 }
13257#endif
13258 exitshell();
13259 /* NOTREACHED */
13260}
13261
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013262
Eric Andersendf82f612001-06-28 07:46:40 +000013263/*-
13264 * Copyright (c) 1989, 1991, 1993, 1994
Eric Andersen2870d962001-07-02 17:27:21 +000013265 * The Regents of the University of California. All rights reserved.
Eric Andersendf82f612001-06-28 07:46:40 +000013266 *
13267 * This code is derived from software contributed to Berkeley by
13268 * Kenneth Almquist.
13269 *
13270 * Redistribution and use in source and binary forms, with or without
13271 * modification, are permitted provided that the following conditions
13272 * are met:
13273 * 1. Redistributions of source code must retain the above copyright
13274 * notice, this list of conditions and the following disclaimer.
13275 * 2. Redistributions in binary form must reproduce the above copyright
13276 * notice, this list of conditions and the following disclaimer in the
13277 * documentation and/or other materials provided with the distribution.
"Vladimir N. Oleynik"ddc280e2005-12-15 12:01:49 +000013278 * 3. Neither the name of the University nor the names of its contributors
Eric Andersendf82f612001-06-28 07:46:40 +000013279 * may be used to endorse or promote products derived from this software
13280 * without specific prior written permission.
13281 *
13282 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
13283 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
13284 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
13285 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
13286 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
13287 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
13288 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
13289 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
13290 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
13291 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
13292 * SUCH DAMAGE.
13293 */