blob: 481b84138dbed7da9286ca525934f34097d3fa08 [file] [log] [blame]
Eric Andersendf82f612001-06-28 07:46:40 +00001/* vi: set sw=4 ts=4: */
2/*
3 * ash shell port for busybox
4 *
5 * Copyright (c) 1989, 1991, 1993, 1994
Eric Andersen2870d962001-07-02 17:27:21 +00006 * The Regents of the University of California. All rights reserved.
Eric Andersencb57d552001-06-28 07:25:16 +00007 *
"Vladimir N. Oleynik"ddc280e2005-12-15 12:01:49 +00008 * Copyright (c) 1997-2005 Herbert Xu <herbert@gondor.apana.org.au>
Eric Andersen81fe1232003-07-29 06:38:40 +00009 * was re-ported from NetBSD and debianized.
10 *
Eric Andersencb57d552001-06-28 07:25:16 +000011 * This code is derived from software contributed to Berkeley by
12 * Kenneth Almquist.
13 *
Bernhard Reutner-Fischer86f5c992006-01-22 22:55:11 +000014 * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
Eric Andersendf82f612001-06-28 07:46:40 +000015 *
Eric Andersen81fe1232003-07-29 06:38:40 +000016 * Original BSD copyright notice is retained at the end of this file.
Eric Andersencb57d552001-06-28 07:25:16 +000017 */
18
Eric Andersenc470f442003-07-28 09:56:35 +000019/*
Denis Vlasenko653d8e72009-03-19 21:59:35 +000020 * The following should be set to reflect the type of system you have:
Eric Andersenc470f442003-07-28 09:56:35 +000021 * JOBS -> 1 if you have Berkeley job control, 0 otherwise.
22 * define SYSV if you are running under System V.
23 * define DEBUG=1 to compile in debugging ('set -o debug' to turn on)
24 * define DEBUG=2 to compile in and turn on debugging.
25 *
26 * When debugging is on, debugging info will be written to ./trace and
27 * a quit signal will generate a core dump.
28 */
Denis Vlasenkof1733952009-03-19 23:21:55 +000029#define DEBUG 0
Denis Vlasenko653d8e72009-03-19 21:59:35 +000030/* Tweak debug output verbosity here */
31#define DEBUG_TIME 0
32#define DEBUG_PID 1
33#define DEBUG_SIG 1
34
Eric Andersenc470f442003-07-28 09:56:35 +000035#define PROFILE 0
Denis Vlasenko0e6f6612008-02-15 15:02:15 +000036
37#define IFS_BROKEN
38
39#define JOBS ENABLE_ASH_JOB_CONTROL
Eric Andersenc470f442003-07-28 09:56:35 +000040
Denis Vlasenkob012b102007-02-19 22:43:01 +000041#if DEBUG
Denis Vlasenko653d8e72009-03-19 21:59:35 +000042# ifndef _GNU_SOURCE
43# define _GNU_SOURCE
44# endif
Denis Vlasenkoe26b2782008-02-12 07:40:29 +000045#endif
Denis Vlasenko0e6f6612008-02-15 15:02:15 +000046
Denis Vlasenko1aa7e472007-11-28 06:49:03 +000047#include "busybox.h" /* for applet_names */
Denis Vlasenko61befda2008-11-25 01:36:03 +000048//TODO: pull in some .h and find out do we have SINGLE_APPLET_MAIN?
49//#include "applet_tables.h" doesn't work
Denis Vlasenkob012b102007-02-19 22:43:01 +000050#include <paths.h>
51#include <setjmp.h>
52#include <fnmatch.h>
Mike Frysinger98c52642009-04-02 10:02:37 +000053#include "math.h"
Denys Vlasenko3ea2e822009-10-09 20:59:04 +020054#if ENABLE_ASH_RANDOM_SUPPORT
55# include "random.h"
Denys Vlasenko36df0482009-10-19 16:07:28 +020056#else
57# define CLEAR_RANDOM_T(rnd) ((void)0)
Denys Vlasenko3ea2e822009-10-09 20:59:04 +020058#endif
Denis Vlasenko61befda2008-11-25 01:36:03 +000059
60#if defined SINGLE_APPLET_MAIN
61/* STANDALONE does not make sense, and won't compile */
Denys Vlasenko3ea2e822009-10-09 20:59:04 +020062# undef CONFIG_FEATURE_SH_STANDALONE
63# undef ENABLE_FEATURE_SH_STANDALONE
64# undef IF_FEATURE_SH_STANDALONE
65# undef IF_NOT_FEATURE_SH_STANDALONE(...)
66# define ENABLE_FEATURE_SH_STANDALONE 0
67# define IF_FEATURE_SH_STANDALONE(...)
68# define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
Eric Andersencb57d552001-06-28 07:25:16 +000069#endif
70
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000071#ifndef PIPE_BUF
Denis Vlasenko653d8e72009-03-19 21:59:35 +000072# define PIPE_BUF 4096 /* amount of buffering in a pipe */
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000073#endif
74
Denis Vlasenkob012b102007-02-19 22:43:01 +000075#if defined(__uClinux__)
Denis Vlasenko653d8e72009-03-19 21:59:35 +000076# error "Do not even bother, ash will not run on NOMMU machine"
Denis Vlasenkob012b102007-02-19 22:43:01 +000077#endif
78
Denis Vlasenkob012b102007-02-19 22:43:01 +000079
Denis Vlasenko01631112007-12-16 17:20:38 +000080/* ============ Hash table sizes. Configurable. */
81
82#define VTABSIZE 39
83#define ATABSIZE 39
84#define CMDTABLESIZE 31 /* should be prime */
85
86
Denis Vlasenkob012b102007-02-19 22:43:01 +000087/* ============ Shell options */
88
89static const char *const optletters_optnames[] = {
90 "e" "errexit",
91 "f" "noglob",
92 "I" "ignoreeof",
93 "i" "interactive",
94 "m" "monitor",
95 "n" "noexec",
96 "s" "stdin",
97 "x" "xtrace",
98 "v" "verbose",
99 "C" "noclobber",
100 "a" "allexport",
101 "b" "notify",
102 "u" "nounset",
Denis Vlasenko6ca409e2007-08-12 20:58:27 +0000103 "\0" "vi"
Denis Vlasenkob012b102007-02-19 22:43:01 +0000104#if DEBUG
Denis Vlasenko6ca409e2007-08-12 20:58:27 +0000105 ,"\0" "nolog"
106 ,"\0" "debug"
Denis Vlasenkob012b102007-02-19 22:43:01 +0000107#endif
108};
109
110#define optletters(n) optletters_optnames[(n)][0]
111#define optnames(n) (&optletters_optnames[(n)][1])
112
Denis Vlasenko80b8b392007-06-25 10:55:35 +0000113enum { NOPTS = ARRAY_SIZE(optletters_optnames) };
Denis Vlasenkob012b102007-02-19 22:43:01 +0000114
Eric Andersenc470f442003-07-28 09:56:35 +0000115
Denis Vlasenkob012b102007-02-19 22:43:01 +0000116/* ============ Misc data */
Eric Andersenc470f442003-07-28 09:56:35 +0000117
Denis Vlasenko6ca409e2007-08-12 20:58:27 +0000118static const char homestr[] ALIGN1 = "HOME";
119static const char snlfmt[] ALIGN1 = "%s\n";
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200120static const char msg_illnum[] ALIGN1 = "Illegal number: %s";
Denis Vlasenkoaa744452007-02-23 01:04:22 +0000121
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +0000122/*
Eric Andersenc470f442003-07-28 09:56:35 +0000123 * We enclose jmp_buf in a structure so that we can declare pointers to
124 * jump locations. The global variable handler contains the location to
Denis Vlasenkof1733952009-03-19 23:21:55 +0000125 * jump to when an exception occurs, and the global variable exception_type
Eric Andersenaff114c2004-04-14 17:51:38 +0000126 * contains a code identifying the exception. To implement nested
Eric Andersenc470f442003-07-28 09:56:35 +0000127 * exception handlers, the user should save the value of handler on entry
128 * to an inner scope, set handler to point to a jmploc structure for the
129 * inner scope, and restore handler on exit from the scope.
130 */
Eric Andersenc470f442003-07-28 09:56:35 +0000131struct jmploc {
132 jmp_buf loc;
133};
Denis Vlasenko01631112007-12-16 17:20:38 +0000134
135struct globals_misc {
136 /* pid of main shell */
137 int rootpid;
138 /* shell level: 0 for the main shell, 1 for its children, and so on */
139 int shlvl;
140#define rootshell (!shlvl)
141 char *minusc; /* argument to -c option */
142
143 char *curdir; // = nullstr; /* current working directory */
144 char *physdir; // = nullstr; /* physical working directory */
145
146 char *arg0; /* value of $0 */
147
148 struct jmploc *exception_handler;
Denis Vlasenko991a1da2008-02-10 19:02:53 +0000149
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200150 volatile int suppress_int; /* counter */
151 volatile /*sig_atomic_t*/ smallint pending_int; /* 1 = got SIGINT */
Denis Vlasenko991a1da2008-02-10 19:02:53 +0000152 /* last pending signal */
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200153 volatile /*sig_atomic_t*/ smallint pending_sig;
Denis Vlasenko7f88e342009-03-19 03:36:18 +0000154 smallint exception_type; /* kind of exception (0..5) */
Denis Vlasenko01631112007-12-16 17:20:38 +0000155 /* exceptions */
Eric Andersenc470f442003-07-28 09:56:35 +0000156#define EXINT 0 /* SIGINT received */
157#define EXERROR 1 /* a generic error */
158#define EXSHELLPROC 2 /* execute a shell procedure */
159#define EXEXEC 3 /* command execution failed */
160#define EXEXIT 4 /* exit the shell */
161#define EXSIG 5 /* trapped signal in wait(1) */
Eric Andersen2870d962001-07-02 17:27:21 +0000162
Denis Vlasenko01631112007-12-16 17:20:38 +0000163 smallint isloginsh;
Denis Vlasenkob07a4962008-06-22 13:16:23 +0000164 char nullstr[1]; /* zero length string */
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000165
166 char optlist[NOPTS];
167#define eflag optlist[0]
168#define fflag optlist[1]
169#define Iflag optlist[2]
170#define iflag optlist[3]
171#define mflag optlist[4]
172#define nflag optlist[5]
173#define sflag optlist[6]
174#define xflag optlist[7]
175#define vflag optlist[8]
176#define Cflag optlist[9]
177#define aflag optlist[10]
178#define bflag optlist[11]
179#define uflag optlist[12]
180#define viflag optlist[13]
181#if DEBUG
182#define nolog optlist[14]
183#define debug optlist[15]
184#endif
185
186 /* trap handler commands */
Denis Vlasenko01631112007-12-16 17:20:38 +0000187 /*
188 * Sigmode records the current value of the signal handlers for the various
189 * modes. A value of zero means that the current handler is not known.
Denis Vlasenkof8535cc2008-12-03 10:36:26 +0000190 * S_HARD_IGN indicates that the signal was ignored on entry to the shell.
Denis Vlasenko01631112007-12-16 17:20:38 +0000191 */
192 char sigmode[NSIG - 1];
Denis Vlasenkof8535cc2008-12-03 10:36:26 +0000193#define S_DFL 1 /* default signal handling (SIG_DFL) */
194#define S_CATCH 2 /* signal is caught */
195#define S_IGN 3 /* signal is ignored (SIG_IGN) */
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +0000196#define S_HARD_IGN 4 /* signal is ignored permenantly */
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +0000197
Denis Vlasenko01631112007-12-16 17:20:38 +0000198 /* indicates specified signal received */
Denis Vlasenko4b875702009-03-19 13:30:04 +0000199 uint8_t gotsig[NSIG - 1]; /* offset by 1: "signal" 0 is meaningless */
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000200 char *trap[NSIG];
Denys Vlasenko21d87d42009-09-25 00:06:51 +0200201 char **trap_ptr; /* used only by "trap hack" */
Denis Vlasenko448d30e2008-06-27 00:24:11 +0000202
203 /* Rarely referenced stuff */
204#if ENABLE_ASH_RANDOM_SUPPORT
Denys Vlasenko3ea2e822009-10-09 20:59:04 +0200205 random_t random_gen;
Denis Vlasenko448d30e2008-06-27 00:24:11 +0000206#endif
207 pid_t backgndpid; /* pid of last background process */
208 smallint job_warning; /* user was warned about stopped jobs (can be 2, 1 or 0). */
Denis Vlasenko01631112007-12-16 17:20:38 +0000209};
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000210extern struct globals_misc *const ash_ptr_to_globals_misc;
211#define G_misc (*ash_ptr_to_globals_misc)
Denis Vlasenko26bc57d2008-06-27 00:29:34 +0000212#define rootpid (G_misc.rootpid )
213#define shlvl (G_misc.shlvl )
214#define minusc (G_misc.minusc )
215#define curdir (G_misc.curdir )
216#define physdir (G_misc.physdir )
217#define arg0 (G_misc.arg0 )
Denis Vlasenko01631112007-12-16 17:20:38 +0000218#define exception_handler (G_misc.exception_handler)
Denis Vlasenko7f88e342009-03-19 03:36:18 +0000219#define exception_type (G_misc.exception_type )
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200220#define suppress_int (G_misc.suppress_int )
221#define pending_int (G_misc.pending_int )
222#define pending_sig (G_misc.pending_sig )
Denis Vlasenko26bc57d2008-06-27 00:29:34 +0000223#define isloginsh (G_misc.isloginsh )
224#define nullstr (G_misc.nullstr )
225#define optlist (G_misc.optlist )
226#define sigmode (G_misc.sigmode )
227#define gotsig (G_misc.gotsig )
228#define trap (G_misc.trap )
Denys Vlasenko21d87d42009-09-25 00:06:51 +0200229#define trap_ptr (G_misc.trap_ptr )
Denys Vlasenko3ea2e822009-10-09 20:59:04 +0200230#define random_gen (G_misc.random_gen )
Denis Vlasenko448d30e2008-06-27 00:24:11 +0000231#define backgndpid (G_misc.backgndpid )
232#define job_warning (G_misc.job_warning)
Denis Vlasenko01631112007-12-16 17:20:38 +0000233#define INIT_G_misc() do { \
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000234 (*(struct globals_misc**)&ash_ptr_to_globals_misc) = xzalloc(sizeof(G_misc)); \
235 barrier(); \
Denis Vlasenko01631112007-12-16 17:20:38 +0000236 curdir = nullstr; \
237 physdir = nullstr; \
Denys Vlasenko21d87d42009-09-25 00:06:51 +0200238 trap_ptr = trap; \
Denis Vlasenko01631112007-12-16 17:20:38 +0000239} while (0)
240
241
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000242/* ============ DEBUG */
243#if DEBUG
244static void trace_printf(const char *fmt, ...);
245static void trace_vprintf(const char *fmt, va_list va);
246# define TRACE(param) trace_printf param
247# define TRACEV(param) trace_vprintf param
Denis Vlasenko1bb3d7e2009-03-20 07:45:36 +0000248# define close(fd) do { \
249 int dfd = (fd); \
Denis Vlasenkob9e70dd2009-03-20 01:24:08 +0000250 if (close(dfd) < 0) \
Denys Vlasenko883cea42009-07-11 15:31:59 +0200251 bb_error_msg("bug on %d: closing %d(0x%x)", \
Denis Vlasenko1bb3d7e2009-03-20 07:45:36 +0000252 __LINE__, dfd, dfd); \
Denis Vlasenkob9e70dd2009-03-20 01:24:08 +0000253} while (0)
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000254#else
255# define TRACE(param)
256# define TRACEV(param)
257#endif
258
259
Denis Vlasenko559691a2008-10-05 18:39:31 +0000260/* ============ Utility functions */
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000261#define xbarrier() do { __asm__ __volatile__ ("": : :"memory"); } while (0)
262
Denys Vlasenko7cee00e2009-07-24 01:08:03 +0200263/* C99 says: "char" declaration may be signed or unsigned by default */
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000264#define signed_char2int(sc) ((int)(signed char)(sc))
265
Denis Vlasenko559691a2008-10-05 18:39:31 +0000266static int isdigit_str9(const char *str)
267{
268 int maxlen = 9 + 1; /* max 9 digits: 999999999 */
269 while (--maxlen && isdigit(*str))
270 str++;
271 return (*str == '\0');
272}
Denis Vlasenko01631112007-12-16 17:20:38 +0000273
Denis Vlasenko559691a2008-10-05 18:39:31 +0000274
275/* ============ Interrupts / exceptions */
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +0000276/*
Eric Andersen2870d962001-07-02 17:27:21 +0000277 * These macros allow the user to suspend the handling of interrupt signals
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +0000278 * over a period of time. This is similar to SIGHOLD or to sigblock, but
Eric Andersen2870d962001-07-02 17:27:21 +0000279 * much more efficient and portable. (But hacking the kernel is so much
280 * more fun than worrying about efficiency and portability. :-))
281 */
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000282#define INT_OFF do { \
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200283 suppress_int++; \
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000284 xbarrier(); \
285} while (0)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000286
287/*
288 * Called to raise an exception. Since C doesn't include exceptions, we
289 * just do a longjmp to the exception handler. The type of exception is
Denis Vlasenko4b875702009-03-19 13:30:04 +0000290 * stored in the global variable "exception_type".
Denis Vlasenkob012b102007-02-19 22:43:01 +0000291 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +0000292static void raise_exception(int) NORETURN;
Denis Vlasenkob012b102007-02-19 22:43:01 +0000293static void
294raise_exception(int e)
295{
296#if DEBUG
Denis Vlasenko2da584f2007-02-19 22:44:05 +0000297 if (exception_handler == NULL)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000298 abort();
299#endif
300 INT_OFF;
Denis Vlasenko7f88e342009-03-19 03:36:18 +0000301 exception_type = e;
Denis Vlasenko2da584f2007-02-19 22:44:05 +0000302 longjmp(exception_handler->loc, 1);
Denis Vlasenkob012b102007-02-19 22:43:01 +0000303}
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000304#if DEBUG
305#define raise_exception(e) do { \
306 TRACE(("raising exception %d on line %d\n", (e), __LINE__)); \
307 raise_exception(e); \
308} while (0)
309#endif
Denis Vlasenkob012b102007-02-19 22:43:01 +0000310
311/*
312 * Called from trap.c when a SIGINT is received. (If the user specifies
313 * that SIGINT is to be trapped or ignored using the trap builtin, then
314 * this routine is not called.) Suppressint is nonzero when interrupts
315 * are held using the INT_OFF macro. (The test for iflag is just
316 * defensive programming.)
317 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +0000318static void raise_interrupt(void) NORETURN;
Denis Vlasenkob012b102007-02-19 22:43:01 +0000319static void
320raise_interrupt(void)
321{
Denis Vlasenko4b875702009-03-19 13:30:04 +0000322 int ex_type;
Denis Vlasenkob012b102007-02-19 22:43:01 +0000323
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200324 pending_int = 0;
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +0000325 /* Signal is not automatically unmasked after it is raised,
326 * do it ourself - unmask all signals */
Denis Vlasenko3f165fa2008-03-17 08:29:08 +0000327 sigprocmask_allsigs(SIG_UNBLOCK);
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200328 /* pending_sig = 0; - now done in onsig() */
Denis Vlasenko7c139b42007-03-21 20:17:27 +0000329
Denis Vlasenko4b875702009-03-19 13:30:04 +0000330 ex_type = EXSIG;
Denis Vlasenkob012b102007-02-19 22:43:01 +0000331 if (gotsig[SIGINT - 1] && !trap[SIGINT]) {
332 if (!(rootshell && iflag)) {
Denis Vlasenko991a1da2008-02-10 19:02:53 +0000333 /* Kill ourself with SIGINT */
Denis Vlasenkob012b102007-02-19 22:43:01 +0000334 signal(SIGINT, SIG_DFL);
335 raise(SIGINT);
336 }
Denis Vlasenko4b875702009-03-19 13:30:04 +0000337 ex_type = EXINT;
Denis Vlasenkob012b102007-02-19 22:43:01 +0000338 }
Denis Vlasenko4b875702009-03-19 13:30:04 +0000339 raise_exception(ex_type);
Denis Vlasenkob012b102007-02-19 22:43:01 +0000340 /* NOTREACHED */
341}
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000342#if DEBUG
343#define raise_interrupt() do { \
344 TRACE(("raising interrupt on line %d\n", __LINE__)); \
345 raise_interrupt(); \
346} while (0)
347#endif
Denis Vlasenkob012b102007-02-19 22:43:01 +0000348
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000349static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000350int_on(void)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000351{
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +0000352 xbarrier();
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200353 if (--suppress_int == 0 && pending_int) {
Denis Vlasenkob012b102007-02-19 22:43:01 +0000354 raise_interrupt();
355 }
356}
357#define INT_ON int_on()
Denis Vlasenko5e34ff22009-04-21 11:09:40 +0000358static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000359force_int_on(void)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000360{
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +0000361 xbarrier();
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200362 suppress_int = 0;
363 if (pending_int)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000364 raise_interrupt();
365}
366#define FORCE_INT_ON force_int_on()
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000367
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200368#define SAVE_INT(v) ((v) = suppress_int)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000369
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000370#define RESTORE_INT(v) do { \
371 xbarrier(); \
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200372 suppress_int = (v); \
373 if (suppress_int == 0 && pending_int) \
Denis Vlasenko843cbd52008-06-27 00:23:18 +0000374 raise_interrupt(); \
375} while (0)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000376
Glenn L McGrath9fef17d2002-08-22 18:41:20 +0000377
Denis Vlasenkobc54cff2007-02-23 01:05:52 +0000378/* ============ Stdout/stderr output */
Eric Andersenc470f442003-07-28 09:56:35 +0000379
Eric Andersenc470f442003-07-28 09:56:35 +0000380static void
Denis Vlasenkob012b102007-02-19 22:43:01 +0000381outstr(const char *p, FILE *file)
Denis Vlasenkoe5570da2007-02-19 22:41:55 +0000382{
Denis Vlasenkob012b102007-02-19 22:43:01 +0000383 INT_OFF;
384 fputs(p, file);
385 INT_ON;
386}
387
388static void
389flush_stdout_stderr(void)
390{
391 INT_OFF;
392 fflush(stdout);
393 fflush(stderr);
394 INT_ON;
395}
396
397static void
398flush_stderr(void)
399{
400 INT_OFF;
401 fflush(stderr);
402 INT_ON;
403}
404
405static void
406outcslow(int c, FILE *dest)
407{
408 INT_OFF;
409 putc(c, dest);
410 fflush(dest);
411 INT_ON;
412}
413
414static int out1fmt(const char *, ...) __attribute__((__format__(__printf__,1,2)));
415static int
416out1fmt(const char *fmt, ...)
417{
418 va_list ap;
419 int r;
420
421 INT_OFF;
422 va_start(ap, fmt);
423 r = vprintf(fmt, ap);
424 va_end(ap);
425 INT_ON;
426 return r;
427}
428
429static int fmtstr(char *, size_t, const char *, ...) __attribute__((__format__(__printf__,3,4)));
430static int
431fmtstr(char *outbuf, size_t length, const char *fmt, ...)
432{
433 va_list ap;
434 int ret;
435
436 va_start(ap, fmt);
437 INT_OFF;
438 ret = vsnprintf(outbuf, length, fmt, ap);
439 va_end(ap);
440 INT_ON;
441 return ret;
442}
443
444static void
445out1str(const char *p)
446{
447 outstr(p, stdout);
448}
449
450static void
451out2str(const char *p)
452{
453 outstr(p, stderr);
454 flush_stderr();
455}
456
457
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +0000458/* ============ Parser structures */
Denis Vlasenko4d2183b2007-02-23 01:05:38 +0000459
Denis Vlasenko5651bfc2007-02-23 21:08:58 +0000460/* control characters in argument strings */
Denys Vlasenkob6c84342009-08-29 20:23:20 +0200461#define CTLESC ((unsigned char)'\201') /* escape next character */
462#define CTLVAR ((unsigned char)'\202') /* variable defn */
463#define CTLENDVAR ((unsigned char)'\203')
464#define CTLBACKQ ((unsigned char)'\204')
Denis Vlasenko5651bfc2007-02-23 21:08:58 +0000465#define CTLQUOTE 01 /* ored with CTLBACKQ code if in quotes */
466/* CTLBACKQ | CTLQUOTE == '\205' */
Denys Vlasenkob6c84342009-08-29 20:23:20 +0200467#define CTLARI ((unsigned char)'\206') /* arithmetic expression */
468#define CTLENDARI ((unsigned char)'\207')
469#define CTLQUOTEMARK ((unsigned char)'\210')
Denis Vlasenko5651bfc2007-02-23 21:08:58 +0000470
471/* variable substitution byte (follows CTLVAR) */
472#define VSTYPE 0x0f /* type of variable substitution */
473#define VSNUL 0x10 /* colon--treat the empty string as unset */
474#define VSQUOTE 0x80 /* inside double quotes--suppress splitting */
475
476/* values of VSTYPE field */
Denis Vlasenko92e13c22008-03-25 01:17:40 +0000477#define VSNORMAL 0x1 /* normal variable: $var or ${var} */
478#define VSMINUS 0x2 /* ${var-text} */
479#define VSPLUS 0x3 /* ${var+text} */
480#define VSQUESTION 0x4 /* ${var?message} */
481#define VSASSIGN 0x5 /* ${var=text} */
482#define VSTRIMRIGHT 0x6 /* ${var%pattern} */
483#define VSTRIMRIGHTMAX 0x7 /* ${var%%pattern} */
484#define VSTRIMLEFT 0x8 /* ${var#pattern} */
485#define VSTRIMLEFTMAX 0x9 /* ${var##pattern} */
486#define VSLENGTH 0xa /* ${#var} */
487#if ENABLE_ASH_BASH_COMPAT
488#define VSSUBSTR 0xc /* ${var:position:length} */
489#define VSREPLACE 0xd /* ${var/pattern/replacement} */
490#define VSREPLACEALL 0xe /* ${var//pattern/replacement} */
491#endif
Denis Vlasenko5651bfc2007-02-23 21:08:58 +0000492
Denis Vlasenko6ca409e2007-08-12 20:58:27 +0000493static const char dolatstr[] ALIGN1 = {
494 CTLVAR, VSNORMAL|VSQUOTE, '@', '=', '\0'
495};
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +0000496
Denis Vlasenko559691a2008-10-05 18:39:31 +0000497#define NCMD 0
498#define NPIPE 1
499#define NREDIR 2
500#define NBACKGND 3
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000501#define NSUBSHELL 4
Denis Vlasenko559691a2008-10-05 18:39:31 +0000502#define NAND 5
503#define NOR 6
504#define NSEMI 7
505#define NIF 8
506#define NWHILE 9
507#define NUNTIL 10
508#define NFOR 11
509#define NCASE 12
510#define NCLIST 13
511#define NDEFUN 14
512#define NARG 15
513#define NTO 16
514#if ENABLE_ASH_BASH_COMPAT
515#define NTO2 17
516#endif
517#define NCLOBBER 18
518#define NFROM 19
519#define NFROMTO 20
520#define NAPPEND 21
521#define NTOFD 22
522#define NFROMFD 23
523#define NHERE 24
524#define NXHERE 25
525#define NNOT 26
Denis Vlasenko340299a2008-11-21 10:36:36 +0000526#define N_NUMBER 27
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000527
528union node;
529
530struct ncmd {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000531 smallint type; /* Nxxxx */
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000532 union node *assign;
533 union node *args;
534 union node *redirect;
535};
536
537struct npipe {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000538 smallint type;
539 smallint pipe_backgnd;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000540 struct nodelist *cmdlist;
541};
542
543struct nredir {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000544 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000545 union node *n;
546 union node *redirect;
547};
548
549struct nbinary {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000550 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000551 union node *ch1;
552 union node *ch2;
553};
554
555struct nif {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000556 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000557 union node *test;
558 union node *ifpart;
559 union node *elsepart;
560};
561
562struct nfor {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000563 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000564 union node *args;
565 union node *body;
566 char *var;
567};
568
569struct ncase {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000570 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000571 union node *expr;
572 union node *cases;
573};
574
575struct nclist {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000576 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000577 union node *next;
578 union node *pattern;
579 union node *body;
580};
581
582struct narg {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000583 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000584 union node *next;
585 char *text;
586 struct nodelist *backquote;
587};
588
Denis Vlasenko559691a2008-10-05 18:39:31 +0000589/* nfile and ndup layout must match!
590 * NTOFD (>&fdnum) uses ndup structure, but we may discover mid-flight
591 * that it is actually NTO2 (>&file), and change its type.
592 */
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000593struct nfile {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000594 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000595 union node *next;
596 int fd;
Denis Vlasenko559691a2008-10-05 18:39:31 +0000597 int _unused_dupfd;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000598 union node *fname;
599 char *expfname;
600};
601
602struct ndup {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000603 smallint type;
Denis Vlasenko559691a2008-10-05 18:39:31 +0000604 union node *next;
605 int fd;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000606 int dupfd;
607 union node *vname;
Denis Vlasenko559691a2008-10-05 18:39:31 +0000608 char *_unused_expfname;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000609};
610
611struct nhere {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000612 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000613 union node *next;
614 int fd;
615 union node *doc;
616};
617
618struct nnot {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000619 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000620 union node *com;
621};
622
623union node {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000624 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000625 struct ncmd ncmd;
626 struct npipe npipe;
627 struct nredir nredir;
628 struct nbinary nbinary;
629 struct nif nif;
630 struct nfor nfor;
631 struct ncase ncase;
632 struct nclist nclist;
633 struct narg narg;
634 struct nfile nfile;
635 struct ndup ndup;
636 struct nhere nhere;
637 struct nnot nnot;
638};
639
Denys Vlasenko86e83ec2009-07-23 22:07:07 +0200640/*
641 * NODE_EOF is returned by parsecmd when it encounters an end of file.
642 * It must be distinct from NULL.
643 */
644#define NODE_EOF ((union node *) -1L)
645
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000646struct nodelist {
647 struct nodelist *next;
648 union node *n;
649};
650
651struct funcnode {
652 int count;
653 union node n;
654};
655
Denis Vlasenko5651bfc2007-02-23 21:08:58 +0000656/*
657 * Free a parse tree.
658 */
659static void
660freefunc(struct funcnode *f)
661{
662 if (f && --f->count < 0)
663 free(f);
664}
665
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000666
667/* ============ Debugging output */
668
669#if DEBUG
670
671static FILE *tracefile;
672
673static void
674trace_printf(const char *fmt, ...)
675{
676 va_list va;
677
678 if (debug != 1)
679 return;
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000680 if (DEBUG_TIME)
681 fprintf(tracefile, "%u ", (int) time(NULL));
682 if (DEBUG_PID)
683 fprintf(tracefile, "[%u] ", (int) getpid());
684 if (DEBUG_SIG)
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200685 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000686 va_start(va, fmt);
687 vfprintf(tracefile, fmt, va);
688 va_end(va);
689}
690
691static void
692trace_vprintf(const char *fmt, va_list va)
693{
694 if (debug != 1)
695 return;
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000696 if (DEBUG_TIME)
697 fprintf(tracefile, "%u ", (int) time(NULL));
698 if (DEBUG_PID)
699 fprintf(tracefile, "[%u] ", (int) getpid());
700 if (DEBUG_SIG)
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200701 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000702 vfprintf(tracefile, fmt, va);
703}
704
705static void
706trace_puts(const char *s)
707{
708 if (debug != 1)
709 return;
710 fputs(s, tracefile);
711}
712
713static void
714trace_puts_quoted(char *s)
715{
716 char *p;
717 char c;
718
719 if (debug != 1)
720 return;
721 putc('"', tracefile);
722 for (p = s; *p; p++) {
723 switch (*p) {
724 case '\n': c = 'n'; goto backslash;
725 case '\t': c = 't'; goto backslash;
726 case '\r': c = 'r'; goto backslash;
727 case '"': c = '"'; goto backslash;
728 case '\\': c = '\\'; goto backslash;
729 case CTLESC: c = 'e'; goto backslash;
730 case CTLVAR: c = 'v'; goto backslash;
731 case CTLVAR+CTLQUOTE: c = 'V'; goto backslash;
732 case CTLBACKQ: c = 'q'; goto backslash;
733 case CTLBACKQ+CTLQUOTE: c = 'Q'; goto backslash;
734 backslash:
735 putc('\\', tracefile);
736 putc(c, tracefile);
737 break;
738 default:
739 if (*p >= ' ' && *p <= '~')
740 putc(*p, tracefile);
741 else {
742 putc('\\', tracefile);
743 putc(*p >> 6 & 03, tracefile);
744 putc(*p >> 3 & 07, tracefile);
745 putc(*p & 07, tracefile);
746 }
747 break;
748 }
749 }
750 putc('"', tracefile);
751}
752
753static void
754trace_puts_args(char **ap)
755{
756 if (debug != 1)
757 return;
758 if (!*ap)
759 return;
760 while (1) {
761 trace_puts_quoted(*ap);
762 if (!*++ap) {
763 putc('\n', tracefile);
764 break;
765 }
766 putc(' ', tracefile);
767 }
768}
769
770static void
771opentrace(void)
772{
773 char s[100];
774#ifdef O_APPEND
775 int flags;
776#endif
777
778 if (debug != 1) {
779 if (tracefile)
780 fflush(tracefile);
781 /* leave open because libedit might be using it */
782 return;
783 }
784 strcpy(s, "./trace");
785 if (tracefile) {
786 if (!freopen(s, "a", tracefile)) {
787 fprintf(stderr, "Can't re-open %s\n", s);
788 debug = 0;
789 return;
790 }
791 } else {
792 tracefile = fopen(s, "a");
793 if (tracefile == NULL) {
794 fprintf(stderr, "Can't open %s\n", s);
795 debug = 0;
796 return;
797 }
798 }
799#ifdef O_APPEND
Denis Vlasenkod37f2222007-08-19 13:42:08 +0000800 flags = fcntl(fileno(tracefile), F_GETFL);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000801 if (flags >= 0)
802 fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
803#endif
804 setlinebuf(tracefile);
805 fputs("\nTracing started.\n", tracefile);
806}
807
808static void
809indent(int amount, char *pfx, FILE *fp)
810{
811 int i;
812
813 for (i = 0; i < amount; i++) {
814 if (pfx && i == amount - 1)
815 fputs(pfx, fp);
816 putc('\t', fp);
817 }
818}
819
820/* little circular references here... */
821static void shtree(union node *n, int ind, char *pfx, FILE *fp);
822
823static void
824sharg(union node *arg, FILE *fp)
825{
826 char *p;
827 struct nodelist *bqlist;
828 int subtype;
829
830 if (arg->type != NARG) {
831 out1fmt("<node type %d>\n", arg->type);
832 abort();
833 }
834 bqlist = arg->narg.backquote;
835 for (p = arg->narg.text; *p; p++) {
836 switch (*p) {
837 case CTLESC:
838 putc(*++p, fp);
839 break;
840 case CTLVAR:
841 putc('$', fp);
842 putc('{', fp);
843 subtype = *++p;
844 if (subtype == VSLENGTH)
845 putc('#', fp);
846
847 while (*p != '=')
848 putc(*p++, fp);
849
850 if (subtype & VSNUL)
851 putc(':', fp);
852
853 switch (subtype & VSTYPE) {
854 case VSNORMAL:
855 putc('}', fp);
856 break;
857 case VSMINUS:
858 putc('-', fp);
859 break;
860 case VSPLUS:
861 putc('+', fp);
862 break;
863 case VSQUESTION:
864 putc('?', fp);
865 break;
866 case VSASSIGN:
867 putc('=', fp);
868 break;
869 case VSTRIMLEFT:
870 putc('#', fp);
871 break;
872 case VSTRIMLEFTMAX:
873 putc('#', fp);
874 putc('#', fp);
875 break;
876 case VSTRIMRIGHT:
877 putc('%', fp);
878 break;
879 case VSTRIMRIGHTMAX:
880 putc('%', fp);
881 putc('%', fp);
882 break;
883 case VSLENGTH:
884 break;
885 default:
886 out1fmt("<subtype %d>", subtype);
887 }
888 break;
889 case CTLENDVAR:
890 putc('}', fp);
891 break;
892 case CTLBACKQ:
893 case CTLBACKQ|CTLQUOTE:
894 putc('$', fp);
895 putc('(', fp);
896 shtree(bqlist->n, -1, NULL, fp);
897 putc(')', fp);
898 break;
899 default:
900 putc(*p, fp);
901 break;
902 }
903 }
904}
905
Denys Vlasenko641dd7b2009-06-11 19:30:19 +0200906static void
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000907shcmd(union node *cmd, FILE *fp)
908{
909 union node *np;
910 int first;
911 const char *s;
912 int dftfd;
913
914 first = 1;
915 for (np = cmd->ncmd.args; np; np = np->narg.next) {
Denis Vlasenko40ba9982007-07-14 00:48:29 +0000916 if (!first)
917 putc(' ', fp);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000918 sharg(np, fp);
919 first = 0;
920 }
921 for (np = cmd->ncmd.redirect; np; np = np->nfile.next) {
Denis Vlasenko40ba9982007-07-14 00:48:29 +0000922 if (!first)
923 putc(' ', fp);
924 dftfd = 0;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000925 switch (np->nfile.type) {
Denis Vlasenko40ba9982007-07-14 00:48:29 +0000926 case NTO: s = ">>"+1; dftfd = 1; break;
927 case NCLOBBER: s = ">|"; dftfd = 1; break;
928 case NAPPEND: s = ">>"; dftfd = 1; break;
Denis Vlasenko559691a2008-10-05 18:39:31 +0000929#if ENABLE_ASH_BASH_COMPAT
930 case NTO2:
931#endif
Denis Vlasenko40ba9982007-07-14 00:48:29 +0000932 case NTOFD: s = ">&"; dftfd = 1; break;
Denis Vlasenko559691a2008-10-05 18:39:31 +0000933 case NFROM: s = "<"; break;
Denis Vlasenko40ba9982007-07-14 00:48:29 +0000934 case NFROMFD: s = "<&"; break;
935 case NFROMTO: s = "<>"; break;
936 default: s = "*error*"; break;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000937 }
938 if (np->nfile.fd != dftfd)
939 fprintf(fp, "%d", np->nfile.fd);
940 fputs(s, fp);
941 if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
942 fprintf(fp, "%d", np->ndup.dupfd);
943 } else {
944 sharg(np->nfile.fname, fp);
945 }
946 first = 0;
947 }
948}
949
950static void
951shtree(union node *n, int ind, char *pfx, FILE *fp)
952{
953 struct nodelist *lp;
954 const char *s;
955
956 if (n == NULL)
957 return;
958
959 indent(ind, pfx, fp);
Denys Vlasenko86e83ec2009-07-23 22:07:07 +0200960
961 if (n == NODE_EOF) {
962 fputs("<EOF>", fp);
963 return;
964 }
965
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000966 switch (n->type) {
967 case NSEMI:
968 s = "; ";
969 goto binop;
970 case NAND:
971 s = " && ";
972 goto binop;
973 case NOR:
974 s = " || ";
975 binop:
976 shtree(n->nbinary.ch1, ind, NULL, fp);
977 /* if (ind < 0) */
978 fputs(s, fp);
979 shtree(n->nbinary.ch2, ind, NULL, fp);
980 break;
981 case NCMD:
982 shcmd(n, fp);
983 if (ind >= 0)
984 putc('\n', fp);
985 break;
986 case NPIPE:
987 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
Denys Vlasenko7cee00e2009-07-24 01:08:03 +0200988 shtree(lp->n, 0, NULL, fp);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000989 if (lp->next)
990 fputs(" | ", fp);
991 }
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000992 if (n->npipe.pipe_backgnd)
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000993 fputs(" &", fp);
994 if (ind >= 0)
995 putc('\n', fp);
996 break;
997 default:
998 fprintf(fp, "<node type %d>", n->type);
999 if (ind >= 0)
1000 putc('\n', fp);
1001 break;
1002 }
1003}
1004
1005static void
1006showtree(union node *n)
1007{
1008 trace_puts("showtree called\n");
Denys Vlasenko883cea42009-07-11 15:31:59 +02001009 shtree(n, 1, NULL, stderr);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00001010}
1011
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00001012#endif /* DEBUG */
1013
1014
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00001015/* ============ Parser data */
1016
1017/*
Denis Vlasenkob012b102007-02-19 22:43:01 +00001018 * ash_vmsg() needs parsefile->fd, hence parsefile definition is moved up.
1019 */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001020struct strlist {
1021 struct strlist *next;
1022 char *text;
1023};
1024
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00001025struct alias;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00001026
Denis Vlasenkob012b102007-02-19 22:43:01 +00001027struct strpush {
1028 struct strpush *prev; /* preceding string on stack */
Denis Vlasenko41eb3002008-11-28 03:42:31 +00001029 char *prev_string;
1030 int prev_left_in_line;
Denis Vlasenkob012b102007-02-19 22:43:01 +00001031#if ENABLE_ASH_ALIAS
1032 struct alias *ap; /* if push was associated with an alias */
1033#endif
1034 char *string; /* remember the string since it may change */
1035};
1036
1037struct parsefile {
1038 struct parsefile *prev; /* preceding file on stack */
1039 int linno; /* current line */
1040 int fd; /* file descriptor (or -1 if string) */
Denis Vlasenko41eb3002008-11-28 03:42:31 +00001041 int left_in_line; /* number of chars left in this line */
1042 int left_in_buffer; /* number of chars left in this buffer past the line */
1043 char *next_to_pgetc; /* next char in buffer */
Denis Vlasenkob012b102007-02-19 22:43:01 +00001044 char *buf; /* input buffer */
1045 struct strpush *strpush; /* for pushing strings at this level */
1046 struct strpush basestrpush; /* so pushing one is fast */
1047};
1048
Denis Vlasenko448d30e2008-06-27 00:24:11 +00001049static struct parsefile basepf; /* top level input file */
Denis Vlasenkob07a4962008-06-22 13:16:23 +00001050static struct parsefile *g_parsefile = &basepf; /* current input file */
Denis Vlasenkob012b102007-02-19 22:43:01 +00001051static int startlinno; /* line # where last token started */
1052static char *commandname; /* currently executing command */
1053static struct strlist *cmdenviron; /* environment for builtin command */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00001054static uint8_t exitstatus; /* exit status of last command */
Denis Vlasenkob012b102007-02-19 22:43:01 +00001055
1056
1057/* ============ Message printing */
1058
1059static void
1060ash_vmsg(const char *msg, va_list ap)
1061{
1062 fprintf(stderr, "%s: ", arg0);
1063 if (commandname) {
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00001064 if (strcmp(arg0, commandname))
1065 fprintf(stderr, "%s: ", commandname);
Denis Vlasenkob07a4962008-06-22 13:16:23 +00001066 if (!iflag || g_parsefile->fd)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00001067 fprintf(stderr, "line %d: ", startlinno);
Eric Andersenc470f442003-07-28 09:56:35 +00001068 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00001069 vfprintf(stderr, msg, ap);
1070 outcslow('\n', stderr);
Eric Andersenc470f442003-07-28 09:56:35 +00001071}
Denis Vlasenkob012b102007-02-19 22:43:01 +00001072
1073/*
1074 * Exverror is called to raise the error exception. If the second argument
1075 * is not NULL then error prints an error message using printf style
1076 * formatting. It then raises the error exception.
1077 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001078static void ash_vmsg_and_raise(int, const char *, va_list) NORETURN;
Denis Vlasenkob012b102007-02-19 22:43:01 +00001079static void
1080ash_vmsg_and_raise(int cond, const char *msg, va_list ap)
Eric Andersenc470f442003-07-28 09:56:35 +00001081{
Denis Vlasenkob012b102007-02-19 22:43:01 +00001082#if DEBUG
1083 if (msg) {
1084 TRACE(("ash_vmsg_and_raise(%d, \"", cond));
1085 TRACEV((msg, ap));
1086 TRACE(("\") pid=%d\n", getpid()));
1087 } else
1088 TRACE(("ash_vmsg_and_raise(%d, NULL) pid=%d\n", cond, getpid()));
1089 if (msg)
1090#endif
1091 ash_vmsg(msg, ap);
1092
1093 flush_stdout_stderr();
1094 raise_exception(cond);
1095 /* NOTREACHED */
Eric Andersenc470f442003-07-28 09:56:35 +00001096}
Denis Vlasenkob012b102007-02-19 22:43:01 +00001097
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001098static void ash_msg_and_raise_error(const char *, ...) NORETURN;
Denis Vlasenkob012b102007-02-19 22:43:01 +00001099static void
1100ash_msg_and_raise_error(const char *msg, ...)
1101{
1102 va_list ap;
1103
1104 va_start(ap, msg);
1105 ash_vmsg_and_raise(EXERROR, msg, ap);
1106 /* NOTREACHED */
1107 va_end(ap);
1108}
1109
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00001110static void raise_error_syntax(const char *) NORETURN;
1111static void
1112raise_error_syntax(const char *msg)
1113{
1114 ash_msg_and_raise_error("syntax error: %s", msg);
1115 /* NOTREACHED */
1116}
1117
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001118static void ash_msg_and_raise(int, const char *, ...) NORETURN;
Denis Vlasenkob012b102007-02-19 22:43:01 +00001119static void
1120ash_msg_and_raise(int cond, const char *msg, ...)
1121{
1122 va_list ap;
1123
1124 va_start(ap, msg);
1125 ash_vmsg_and_raise(cond, msg, ap);
1126 /* NOTREACHED */
1127 va_end(ap);
1128}
1129
1130/*
1131 * error/warning routines for external builtins
1132 */
1133static void
1134ash_msg(const char *fmt, ...)
1135{
1136 va_list ap;
1137
1138 va_start(ap, fmt);
1139 ash_vmsg(fmt, ap);
1140 va_end(ap);
1141}
1142
1143/*
1144 * Return a string describing an error. The returned string may be a
1145 * pointer to a static buffer that will be overwritten on the next call.
1146 * Action describes the operation that got the error.
1147 */
1148static const char *
1149errmsg(int e, const char *em)
1150{
1151 if (e == ENOENT || e == ENOTDIR) {
1152 return em;
1153 }
1154 return strerror(e);
1155}
1156
1157
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001158/* ============ Memory allocation */
1159
Denys Vlasenkoe7670ff2009-10-11 00:45:25 +02001160#if 0
1161/* I consider these wrappers nearly useless:
1162 * ok, they return you to nearest exception handler, but
1163 * how much memory do you leak in the process, making
1164 * memory starvation worse?
1165 */
1166static void *
1167ckrealloc(void * p, size_t nbytes)
1168{
1169 p = realloc(p, nbytes);
1170 if (!p)
1171 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1172 return p;
1173}
1174
1175static void *
1176ckmalloc(size_t nbytes)
1177{
1178 return ckrealloc(NULL, nbytes);
1179}
1180
1181static void *
1182ckzalloc(size_t nbytes)
1183{
1184 return memset(ckmalloc(nbytes), 0, nbytes);
1185}
1186
1187static char *
1188ckstrdup(const char *s)
1189{
1190 char *p = strdup(s);
1191 if (!p)
1192 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1193 return p;
1194}
1195#else
1196/* Using bbox equivalents. They exit if out of memory */
1197# define ckrealloc xrealloc
1198# define ckmalloc xmalloc
1199# define ckzalloc xzalloc
1200# define ckstrdup xstrdup
1201#endif
1202
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001203/*
1204 * It appears that grabstackstr() will barf with such alignments
1205 * because stalloc() will return a string allocated in a new stackblock.
1206 */
1207#define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
1208enum {
1209 /* Most machines require the value returned from malloc to be aligned
1210 * in some way. The following macro will get this right
1211 * on many machines. */
Denys Vlasenko0e5e4ea2009-10-11 00:36:20 +02001212 SHELL_SIZE = sizeof(union { int i; char *cp; double d; }) - 1,
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001213 /* Minimum size of a block */
Denis Vlasenko01631112007-12-16 17:20:38 +00001214 MINSIZE = SHELL_ALIGN(504),
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001215};
1216
1217struct stack_block {
1218 struct stack_block *prev;
1219 char space[MINSIZE];
1220};
1221
1222struct stackmark {
1223 struct stack_block *stackp;
1224 char *stacknxt;
1225 size_t stacknleft;
1226 struct stackmark *marknext;
1227};
1228
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001229
Denis Vlasenko01631112007-12-16 17:20:38 +00001230struct globals_memstack {
1231 struct stack_block *g_stackp; // = &stackbase;
1232 struct stackmark *markp;
1233 char *g_stacknxt; // = stackbase.space;
1234 char *sstrend; // = stackbase.space + MINSIZE;
1235 size_t g_stacknleft; // = MINSIZE;
1236 int herefd; // = -1;
1237 struct stack_block stackbase;
1238};
Denis Vlasenko574f2f42008-02-27 18:41:59 +00001239extern struct globals_memstack *const ash_ptr_to_globals_memstack;
1240#define G_memstack (*ash_ptr_to_globals_memstack)
Denis Vlasenko01631112007-12-16 17:20:38 +00001241#define g_stackp (G_memstack.g_stackp )
1242#define markp (G_memstack.markp )
1243#define g_stacknxt (G_memstack.g_stacknxt )
1244#define sstrend (G_memstack.sstrend )
1245#define g_stacknleft (G_memstack.g_stacknleft)
1246#define herefd (G_memstack.herefd )
1247#define stackbase (G_memstack.stackbase )
1248#define INIT_G_memstack() do { \
Denis Vlasenko574f2f42008-02-27 18:41:59 +00001249 (*(struct globals_memstack**)&ash_ptr_to_globals_memstack) = xzalloc(sizeof(G_memstack)); \
1250 barrier(); \
Denis Vlasenko01631112007-12-16 17:20:38 +00001251 g_stackp = &stackbase; \
1252 g_stacknxt = stackbase.space; \
1253 g_stacknleft = MINSIZE; \
1254 sstrend = stackbase.space + MINSIZE; \
1255 herefd = -1; \
1256} while (0)
1257
Denys Vlasenkoe7670ff2009-10-11 00:45:25 +02001258
Denis Vlasenko01631112007-12-16 17:20:38 +00001259#define stackblock() ((void *)g_stacknxt)
1260#define stackblocksize() g_stacknleft
1261
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001262/*
1263 * Parse trees for commands are allocated in lifo order, so we use a stack
1264 * to make this more efficient, and also to avoid all sorts of exception
1265 * handling code to handle interrupts in the middle of a parse.
1266 *
1267 * The size 504 was chosen because the Ultrix malloc handles that size
1268 * well.
1269 */
1270static void *
1271stalloc(size_t nbytes)
1272{
1273 char *p;
1274 size_t aligned;
1275
1276 aligned = SHELL_ALIGN(nbytes);
Denis Vlasenko01631112007-12-16 17:20:38 +00001277 if (aligned > g_stacknleft) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001278 size_t len;
1279 size_t blocksize;
1280 struct stack_block *sp;
1281
1282 blocksize = aligned;
1283 if (blocksize < MINSIZE)
1284 blocksize = MINSIZE;
1285 len = sizeof(struct stack_block) - MINSIZE + blocksize;
1286 if (len < blocksize)
1287 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1288 INT_OFF;
1289 sp = ckmalloc(len);
Denis Vlasenko01631112007-12-16 17:20:38 +00001290 sp->prev = g_stackp;
1291 g_stacknxt = sp->space;
1292 g_stacknleft = blocksize;
1293 sstrend = g_stacknxt + blocksize;
1294 g_stackp = sp;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001295 INT_ON;
1296 }
Denis Vlasenko01631112007-12-16 17:20:38 +00001297 p = g_stacknxt;
1298 g_stacknxt += aligned;
1299 g_stacknleft -= aligned;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001300 return p;
1301}
1302
Denis Vlasenko597906c2008-02-20 16:38:54 +00001303static void *
1304stzalloc(size_t nbytes)
1305{
1306 return memset(stalloc(nbytes), 0, nbytes);
1307}
1308
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001309static void
1310stunalloc(void *p)
1311{
1312#if DEBUG
Denis Vlasenko01631112007-12-16 17:20:38 +00001313 if (!p || (g_stacknxt < (char *)p) || ((char *)p < g_stackp->space)) {
Bernhard Reutner-Fischer5e25ddb2008-05-19 09:48:17 +00001314 write(STDERR_FILENO, "stunalloc\n", 10);
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001315 abort();
1316 }
1317#endif
Denis Vlasenko01631112007-12-16 17:20:38 +00001318 g_stacknleft += g_stacknxt - (char *)p;
1319 g_stacknxt = p;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001320}
1321
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001322/*
1323 * Like strdup but works with the ash stack.
1324 */
1325static char *
1326ststrdup(const char *p)
1327{
1328 size_t len = strlen(p) + 1;
1329 return memcpy(stalloc(len), p, len);
1330}
1331
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001332static void
1333setstackmark(struct stackmark *mark)
1334{
Denis Vlasenko01631112007-12-16 17:20:38 +00001335 mark->stackp = g_stackp;
1336 mark->stacknxt = g_stacknxt;
1337 mark->stacknleft = g_stacknleft;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001338 mark->marknext = markp;
1339 markp = mark;
1340}
1341
1342static void
1343popstackmark(struct stackmark *mark)
1344{
1345 struct stack_block *sp;
1346
Denis Vlasenko93ebd4f2007-03-13 20:55:36 +00001347 if (!mark->stackp)
1348 return;
1349
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001350 INT_OFF;
1351 markp = mark->marknext;
Denis Vlasenko01631112007-12-16 17:20:38 +00001352 while (g_stackp != mark->stackp) {
1353 sp = g_stackp;
1354 g_stackp = sp->prev;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001355 free(sp);
1356 }
Denis Vlasenko01631112007-12-16 17:20:38 +00001357 g_stacknxt = mark->stacknxt;
1358 g_stacknleft = mark->stacknleft;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001359 sstrend = mark->stacknxt + mark->stacknleft;
1360 INT_ON;
1361}
1362
1363/*
1364 * When the parser reads in a string, it wants to stick the string on the
1365 * stack and only adjust the stack pointer when it knows how big the
1366 * string is. Stackblock (defined in stack.h) returns a pointer to a block
1367 * of space on top of the stack and stackblocklen returns the length of
1368 * this block. Growstackblock will grow this space by at least one byte,
1369 * possibly moving it (like realloc). Grabstackblock actually allocates the
1370 * part of the block that has been used.
1371 */
1372static void
1373growstackblock(void)
1374{
1375 size_t newlen;
1376
Denis Vlasenko01631112007-12-16 17:20:38 +00001377 newlen = g_stacknleft * 2;
1378 if (newlen < g_stacknleft)
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001379 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1380 if (newlen < 128)
1381 newlen += 128;
1382
Denis Vlasenko01631112007-12-16 17:20:38 +00001383 if (g_stacknxt == g_stackp->space && g_stackp != &stackbase) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001384 struct stack_block *oldstackp;
1385 struct stackmark *xmark;
1386 struct stack_block *sp;
1387 struct stack_block *prevstackp;
1388 size_t grosslen;
1389
1390 INT_OFF;
Denis Vlasenko01631112007-12-16 17:20:38 +00001391 oldstackp = g_stackp;
1392 sp = g_stackp;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001393 prevstackp = sp->prev;
1394 grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
1395 sp = ckrealloc(sp, grosslen);
1396 sp->prev = prevstackp;
Denis Vlasenko01631112007-12-16 17:20:38 +00001397 g_stackp = sp;
1398 g_stacknxt = sp->space;
1399 g_stacknleft = newlen;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001400 sstrend = sp->space + newlen;
1401
1402 /*
1403 * Stack marks pointing to the start of the old block
1404 * must be relocated to point to the new block
1405 */
1406 xmark = markp;
1407 while (xmark != NULL && xmark->stackp == oldstackp) {
Denis Vlasenko01631112007-12-16 17:20:38 +00001408 xmark->stackp = g_stackp;
1409 xmark->stacknxt = g_stacknxt;
1410 xmark->stacknleft = g_stacknleft;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001411 xmark = xmark->marknext;
1412 }
1413 INT_ON;
1414 } else {
Denis Vlasenko01631112007-12-16 17:20:38 +00001415 char *oldspace = g_stacknxt;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00001416 size_t oldlen = g_stacknleft;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001417 char *p = stalloc(newlen);
1418
1419 /* free the space we just allocated */
Denis Vlasenko01631112007-12-16 17:20:38 +00001420 g_stacknxt = memcpy(p, oldspace, oldlen);
1421 g_stacknleft += newlen;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001422 }
1423}
1424
1425static void
1426grabstackblock(size_t len)
1427{
1428 len = SHELL_ALIGN(len);
Denis Vlasenko01631112007-12-16 17:20:38 +00001429 g_stacknxt += len;
1430 g_stacknleft -= len;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001431}
1432
1433/*
1434 * The following routines are somewhat easier to use than the above.
1435 * The user declares a variable of type STACKSTR, which may be declared
1436 * to be a register. The macro STARTSTACKSTR initializes things. Then
1437 * the user uses the macro STPUTC to add characters to the string. In
1438 * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
1439 * grown as necessary. When the user is done, she can just leave the
1440 * string there and refer to it using stackblock(). Or she can allocate
1441 * the space for it using grabstackstr(). If it is necessary to allow
1442 * someone else to use the stack temporarily and then continue to grow
1443 * the string, the user should use grabstack to allocate the space, and
1444 * then call ungrabstr(p) to return to the previous mode of operation.
1445 *
1446 * USTPUTC is like STPUTC except that it doesn't check for overflow.
1447 * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
1448 * is space for at least one character.
1449 */
1450static void *
1451growstackstr(void)
1452{
1453 size_t len = stackblocksize();
1454 if (herefd >= 0 && len >= 1024) {
1455 full_write(herefd, stackblock(), len);
1456 return stackblock();
1457 }
1458 growstackblock();
Denis Vlasenko29eb3592008-05-18 14:06:08 +00001459 return (char *)stackblock() + len;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001460}
1461
1462/*
1463 * Called from CHECKSTRSPACE.
1464 */
1465static char *
1466makestrspace(size_t newlen, char *p)
1467{
Denis Vlasenko01631112007-12-16 17:20:38 +00001468 size_t len = p - g_stacknxt;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001469 size_t size = stackblocksize();
1470
1471 for (;;) {
1472 size_t nleft;
1473
1474 size = stackblocksize();
1475 nleft = size - len;
1476 if (nleft >= newlen)
1477 break;
1478 growstackblock();
1479 }
Denis Vlasenko29eb3592008-05-18 14:06:08 +00001480 return (char *)stackblock() + len;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001481}
1482
1483static char *
1484stack_nputstr(const char *s, size_t n, char *p)
1485{
1486 p = makestrspace(n, p);
Denis Vlasenko29eb3592008-05-18 14:06:08 +00001487 p = (char *)memcpy(p, s, n) + n;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001488 return p;
1489}
1490
1491static char *
1492stack_putstr(const char *s, char *p)
1493{
1494 return stack_nputstr(s, strlen(s), p);
1495}
1496
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001497static char *
1498_STPUTC(int c, char *p)
1499{
1500 if (p == sstrend)
1501 p = growstackstr();
1502 *p++ = c;
1503 return p;
1504}
1505
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00001506#define STARTSTACKSTR(p) ((p) = stackblock())
1507#define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
Denis Vlasenko843cbd52008-06-27 00:23:18 +00001508#define CHECKSTRSPACE(n, p) do { \
1509 char *q = (p); \
1510 size_t l = (n); \
1511 size_t m = sstrend - q; \
1512 if (l > m) \
1513 (p) = makestrspace(l, q); \
1514} while (0)
Denis Vlasenkoef527f52008-06-23 01:52:30 +00001515#define USTPUTC(c, p) (*(p)++ = (c))
Denis Vlasenko843cbd52008-06-27 00:23:18 +00001516#define STACKSTRNUL(p) do { \
1517 if ((p) == sstrend) \
1518 (p) = growstackstr(); \
1519 *(p) = '\0'; \
1520} while (0)
Denis Vlasenkoef527f52008-06-23 01:52:30 +00001521#define STUNPUTC(p) (--(p))
1522#define STTOPC(p) ((p)[-1])
1523#define STADJUST(amount, p) ((p) += (amount))
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001524
1525#define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
Denis Vlasenkoef527f52008-06-23 01:52:30 +00001526#define ungrabstackstr(s, p) stunalloc(s)
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001527#define stackstrend() ((void *)sstrend)
1528
1529
1530/* ============ String helpers */
1531
1532/*
1533 * prefix -- see if pfx is a prefix of string.
1534 */
1535static char *
1536prefix(const char *string, const char *pfx)
1537{
1538 while (*pfx) {
1539 if (*pfx++ != *string++)
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00001540 return NULL;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001541 }
1542 return (char *) string;
1543}
1544
1545/*
1546 * Check for a valid number. This should be elsewhere.
1547 */
1548static int
1549is_number(const char *p)
1550{
1551 do {
1552 if (!isdigit(*p))
1553 return 0;
1554 } while (*++p != '\0');
1555 return 1;
1556}
1557
1558/*
1559 * Convert a string of digits to an integer, printing an error message on
1560 * failure.
1561 */
1562static int
1563number(const char *s)
1564{
1565 if (!is_number(s))
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02001566 ash_msg_and_raise_error(msg_illnum, s);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001567 return atoi(s);
1568}
1569
1570/*
1571 * Produce a possibly single quoted string suitable as input to the shell.
1572 * The return string is allocated on the stack.
1573 */
1574static char *
1575single_quote(const char *s)
1576{
1577 char *p;
1578
1579 STARTSTACKSTR(p);
1580
1581 do {
1582 char *q;
1583 size_t len;
1584
1585 len = strchrnul(s, '\'') - s;
1586
1587 q = p = makestrspace(len + 3, p);
1588
1589 *q++ = '\'';
Denis Vlasenko29eb3592008-05-18 14:06:08 +00001590 q = (char *)memcpy(q, s, len) + len;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001591 *q++ = '\'';
1592 s += len;
1593
1594 STADJUST(q - p, p);
1595
1596 len = strspn(s, "'");
1597 if (!len)
1598 break;
1599
1600 q = p = makestrspace(len + 3, p);
1601
1602 *q++ = '"';
Denis Vlasenko29eb3592008-05-18 14:06:08 +00001603 q = (char *)memcpy(q, s, len) + len;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001604 *q++ = '"';
1605 s += len;
1606
1607 STADJUST(q - p, p);
1608 } while (*s);
1609
1610 USTPUTC(0, p);
1611
1612 return stackblock();
1613}
1614
1615
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00001616/* ============ nextopt */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001617
1618static char **argptr; /* argument list for builtin commands */
1619static char *optionarg; /* set by nextopt (like getopt) */
1620static char *optptr; /* used by nextopt */
1621
1622/*
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001623 * XXX - should get rid of. Have all builtins use getopt(3).
1624 * The library getopt must have the BSD extension static variable
1625 * "optreset", otherwise it can't be used within the shell safely.
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001626 *
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001627 * Standard option processing (a la getopt) for builtin routines.
1628 * The only argument that is passed to nextopt is the option string;
1629 * the other arguments are unnecessary. It returns the character,
1630 * or '\0' on end of input.
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001631 */
1632static int
1633nextopt(const char *optstring)
1634{
1635 char *p;
1636 const char *q;
1637 char c;
1638
1639 p = optptr;
1640 if (p == NULL || *p == '\0') {
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001641 /* We ate entire "-param", take next one */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001642 p = *argptr;
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001643 if (p == NULL)
1644 return '\0';
1645 if (*p != '-')
1646 return '\0';
1647 if (*++p == '\0') /* just "-" ? */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001648 return '\0';
1649 argptr++;
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001650 if (LONE_DASH(p)) /* "--" ? */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001651 return '\0';
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001652 /* p => next "-param" */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001653 }
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001654 /* p => some option char in the middle of a "-param" */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001655 c = *p++;
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +00001656 for (q = optstring; *q != c;) {
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001657 if (*q == '\0')
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00001658 ash_msg_and_raise_error("illegal option -%c", c);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001659 if (*++q == ':')
1660 q++;
1661 }
1662 if (*++q == ':') {
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001663 if (*p == '\0') {
1664 p = *argptr++;
1665 if (p == NULL)
1666 ash_msg_and_raise_error("no arg for -%c option", c);
1667 }
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001668 optionarg = p;
1669 p = NULL;
1670 }
1671 optptr = p;
1672 return c;
1673}
1674
1675
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00001676/* ============ Shell variables */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001677
Denis Vlasenko01631112007-12-16 17:20:38 +00001678/*
1679 * The parsefile structure pointed to by the global variable parsefile
1680 * contains information about the current file being read.
1681 */
Denis Vlasenko01631112007-12-16 17:20:38 +00001682struct shparam {
1683 int nparam; /* # of positional parameters (without $0) */
1684#if ENABLE_ASH_GETOPTS
1685 int optind; /* next parameter to be processed by getopts */
1686 int optoff; /* used by getopts */
1687#endif
1688 unsigned char malloced; /* if parameter list dynamically allocated */
1689 char **p; /* parameter list */
1690};
1691
1692/*
1693 * Free the list of positional parameters.
1694 */
1695static void
1696freeparam(volatile struct shparam *param)
1697{
Denis Vlasenko01631112007-12-16 17:20:38 +00001698 if (param->malloced) {
Denis Vlasenko3177ba02008-07-13 20:39:23 +00001699 char **ap, **ap1;
1700 ap = ap1 = param->p;
1701 while (*ap)
1702 free(*ap++);
1703 free(ap1);
Denis Vlasenko01631112007-12-16 17:20:38 +00001704 }
1705}
1706
1707#if ENABLE_ASH_GETOPTS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001708static void FAST_FUNC getoptsreset(const char *value);
Denis Vlasenko01631112007-12-16 17:20:38 +00001709#endif
1710
1711struct var {
1712 struct var *next; /* next entry in hash list */
1713 int flags; /* flags are defined above */
1714 const char *text; /* name=value */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001715 void (*func)(const char *) FAST_FUNC; /* function to be called when */
Denis Vlasenko01631112007-12-16 17:20:38 +00001716 /* the variable gets set/unset */
1717};
1718
1719struct localvar {
1720 struct localvar *next; /* next local variable in list */
1721 struct var *vp; /* the variable that was made local */
1722 int flags; /* saved flags */
1723 const char *text; /* saved text */
1724};
1725
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001726/* flags */
1727#define VEXPORT 0x01 /* variable is exported */
1728#define VREADONLY 0x02 /* variable cannot be modified */
1729#define VSTRFIXED 0x04 /* variable struct is statically allocated */
1730#define VTEXTFIXED 0x08 /* text is statically allocated */
1731#define VSTACK 0x10 /* text is allocated on the stack */
1732#define VUNSET 0x20 /* the variable is not set */
1733#define VNOFUNC 0x40 /* don't call the callback function */
1734#define VNOSET 0x80 /* do not set variable - just readonly test */
1735#define VNOSAVE 0x100 /* when text is on the heap before setvareq */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00001736#if ENABLE_ASH_RANDOM_SUPPORT
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00001737# define VDYNAMIC 0x200 /* dynamic variable */
1738#else
1739# define VDYNAMIC 0
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001740#endif
1741
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001742#ifdef IFS_BROKEN
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00001743static const char defifsvar[] ALIGN1 = "IFS= \t\n";
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001744#define defifs (defifsvar + 4)
1745#else
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00001746static const char defifs[] ALIGN1 = " \t\n";
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001747#endif
1748
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00001749
Denis Vlasenko01631112007-12-16 17:20:38 +00001750/* Need to be before varinit_data[] */
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00001751#if ENABLE_LOCALE_SUPPORT
Denys Vlasenko2634bf32009-06-09 18:40:07 +02001752static void FAST_FUNC
Denis Vlasenkoa8915072007-02-23 21:10:06 +00001753change_lc_all(const char *value)
1754{
1755 if (value && *value != '\0')
1756 setlocale(LC_ALL, value);
1757}
Denys Vlasenko2634bf32009-06-09 18:40:07 +02001758static void FAST_FUNC
Denis Vlasenkoa8915072007-02-23 21:10:06 +00001759change_lc_ctype(const char *value)
1760{
1761 if (value && *value != '\0')
1762 setlocale(LC_CTYPE, value);
1763}
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00001764#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001765#if ENABLE_ASH_MAIL
1766static void chkmail(void);
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001767static void changemail(const char *) FAST_FUNC;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001768#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001769static void changepath(const char *) FAST_FUNC;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001770#if ENABLE_ASH_RANDOM_SUPPORT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001771static void change_random(const char *) FAST_FUNC;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001772#endif
1773
Denis Vlasenko01631112007-12-16 17:20:38 +00001774static const struct {
1775 int flags;
1776 const char *text;
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001777 void (*func)(const char *) FAST_FUNC;
Denis Vlasenko01631112007-12-16 17:20:38 +00001778} varinit_data[] = {
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001779#ifdef IFS_BROKEN
Denis Vlasenko01631112007-12-16 17:20:38 +00001780 { VSTRFIXED|VTEXTFIXED , defifsvar , NULL },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001781#else
Denis Vlasenko01631112007-12-16 17:20:38 +00001782 { VSTRFIXED|VTEXTFIXED|VUNSET, "IFS\0" , NULL },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001783#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001784#if ENABLE_ASH_MAIL
Denis Vlasenko01631112007-12-16 17:20:38 +00001785 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL\0" , changemail },
1786 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH\0", changemail },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001787#endif
Denis Vlasenko01631112007-12-16 17:20:38 +00001788 { VSTRFIXED|VTEXTFIXED , bb_PATH_root_path, changepath },
1789 { VSTRFIXED|VTEXTFIXED , "PS1=$ " , NULL },
1790 { VSTRFIXED|VTEXTFIXED , "PS2=> " , NULL },
1791 { VSTRFIXED|VTEXTFIXED , "PS4=+ " , NULL },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001792#if ENABLE_ASH_GETOPTS
Denis Vlasenko01631112007-12-16 17:20:38 +00001793 { VSTRFIXED|VTEXTFIXED , "OPTIND=1" , getoptsreset },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001794#endif
1795#if ENABLE_ASH_RANDOM_SUPPORT
Denis Vlasenko01631112007-12-16 17:20:38 +00001796 { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM\0", change_random },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001797#endif
1798#if ENABLE_LOCALE_SUPPORT
Denis Vlasenko01631112007-12-16 17:20:38 +00001799 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL\0" , change_lc_all },
1800 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE\0", change_lc_ctype },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001801#endif
1802#if ENABLE_FEATURE_EDITING_SAVEHISTORY
Denis Vlasenko01631112007-12-16 17:20:38 +00001803 { VSTRFIXED|VTEXTFIXED|VUNSET, "HISTFILE\0", NULL },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001804#endif
1805};
1806
Denis Vlasenko0b769642008-07-24 07:54:57 +00001807struct redirtab;
Denis Vlasenko01631112007-12-16 17:20:38 +00001808
1809struct globals_var {
1810 struct shparam shellparam; /* $@ current positional parameters */
1811 struct redirtab *redirlist;
1812 int g_nullredirs;
1813 int preverrout_fd; /* save fd2 before print debug if xflag is set. */
1814 struct var *vartab[VTABSIZE];
1815 struct var varinit[ARRAY_SIZE(varinit_data)];
1816};
Denis Vlasenko574f2f42008-02-27 18:41:59 +00001817extern struct globals_var *const ash_ptr_to_globals_var;
1818#define G_var (*ash_ptr_to_globals_var)
Denis Vlasenko01631112007-12-16 17:20:38 +00001819#define shellparam (G_var.shellparam )
Denis Vlasenko0b769642008-07-24 07:54:57 +00001820//#define redirlist (G_var.redirlist )
Denis Vlasenko01631112007-12-16 17:20:38 +00001821#define g_nullredirs (G_var.g_nullredirs )
1822#define preverrout_fd (G_var.preverrout_fd)
1823#define vartab (G_var.vartab )
1824#define varinit (G_var.varinit )
1825#define INIT_G_var() do { \
Denis Vlasenko6b06cb82008-05-15 21:30:45 +00001826 unsigned i; \
Denis Vlasenko574f2f42008-02-27 18:41:59 +00001827 (*(struct globals_var**)&ash_ptr_to_globals_var) = xzalloc(sizeof(G_var)); \
1828 barrier(); \
Denis Vlasenko01631112007-12-16 17:20:38 +00001829 for (i = 0; i < ARRAY_SIZE(varinit_data); i++) { \
1830 varinit[i].flags = varinit_data[i].flags; \
1831 varinit[i].text = varinit_data[i].text; \
1832 varinit[i].func = varinit_data[i].func; \
1833 } \
1834} while (0)
1835
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001836#define vifs varinit[0]
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001837#if ENABLE_ASH_MAIL
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001838# define vmail (&vifs)[1]
1839# define vmpath (&vmail)[1]
1840# define vpath (&vmpath)[1]
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001841#else
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001842# define vpath (&vifs)[1]
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001843#endif
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001844#define vps1 (&vpath)[1]
1845#define vps2 (&vps1)[1]
1846#define vps4 (&vps2)[1]
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001847#if ENABLE_ASH_GETOPTS
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001848# define voptind (&vps4)[1]
1849# if ENABLE_ASH_RANDOM_SUPPORT
1850# define vrandom (&voptind)[1]
1851# endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001852#else
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001853# if ENABLE_ASH_RANDOM_SUPPORT
1854# define vrandom (&vps4)[1]
1855# endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001856#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001857
1858/*
1859 * The following macros access the values of the above variables.
1860 * They have to skip over the name. They return the null string
1861 * for unset variables.
1862 */
1863#define ifsval() (vifs.text + 4)
1864#define ifsset() ((vifs.flags & VUNSET) == 0)
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001865#if ENABLE_ASH_MAIL
1866# define mailval() (vmail.text + 5)
1867# define mpathval() (vmpath.text + 9)
1868# define mpathset() ((vmpath.flags & VUNSET) == 0)
1869#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001870#define pathval() (vpath.text + 5)
1871#define ps1val() (vps1.text + 4)
1872#define ps2val() (vps2.text + 4)
1873#define ps4val() (vps4.text + 4)
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001874#if ENABLE_ASH_GETOPTS
1875# define optindval() (voptind.text + 7)
1876#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001877
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001878
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001879#define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
1880#define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
1881
Denis Vlasenko01631112007-12-16 17:20:38 +00001882#if ENABLE_ASH_GETOPTS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001883static void FAST_FUNC
Denis Vlasenko01631112007-12-16 17:20:38 +00001884getoptsreset(const char *value)
1885{
1886 shellparam.optind = number(value);
1887 shellparam.optoff = -1;
1888}
1889#endif
1890
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001891/*
1892 * Return of a legal variable name (a letter or underscore followed by zero or
1893 * more letters, underscores, and digits).
1894 */
1895static char *
1896endofname(const char *name)
1897{
1898 char *p;
1899
1900 p = (char *) name;
1901 if (!is_name(*p))
1902 return p;
1903 while (*++p) {
1904 if (!is_in_name(*p))
1905 break;
1906 }
1907 return p;
1908}
1909
1910/*
1911 * Compares two strings up to the first = or '\0'. The first
1912 * string must be terminated by '='; the second may be terminated by
1913 * either '=' or '\0'.
1914 */
1915static int
1916varcmp(const char *p, const char *q)
1917{
1918 int c, d;
1919
1920 while ((c = *p) == (d = *q)) {
1921 if (!c || c == '=')
1922 goto out;
1923 p++;
1924 q++;
1925 }
1926 if (c == '=')
Denis Vlasenko9650f362007-02-23 01:04:37 +00001927 c = '\0';
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001928 if (d == '=')
Denis Vlasenko9650f362007-02-23 01:04:37 +00001929 d = '\0';
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001930 out:
1931 return c - d;
1932}
1933
1934static int
1935varequal(const char *a, const char *b)
1936{
1937 return !varcmp(a, b);
1938}
1939
1940/*
1941 * Find the appropriate entry in the hash table from the name.
1942 */
1943static struct var **
1944hashvar(const char *p)
1945{
1946 unsigned hashval;
1947
1948 hashval = ((unsigned char) *p) << 4;
1949 while (*p && *p != '=')
1950 hashval += (unsigned char) *p++;
1951 return &vartab[hashval % VTABSIZE];
1952}
1953
1954static int
1955vpcmp(const void *a, const void *b)
1956{
1957 return varcmp(*(const char **)a, *(const char **)b);
1958}
1959
1960/*
1961 * This routine initializes the builtin variables.
1962 */
1963static void
1964initvar(void)
1965{
1966 struct var *vp;
1967 struct var *end;
1968 struct var **vpp;
1969
1970 /*
1971 * PS1 depends on uid
1972 */
1973#if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
1974 vps1.text = "PS1=\\w \\$ ";
1975#else
1976 if (!geteuid())
1977 vps1.text = "PS1=# ";
1978#endif
1979 vp = varinit;
Denis Vlasenko80b8b392007-06-25 10:55:35 +00001980 end = vp + ARRAY_SIZE(varinit);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001981 do {
1982 vpp = hashvar(vp->text);
1983 vp->next = *vpp;
1984 *vpp = vp;
1985 } while (++vp < end);
1986}
1987
1988static struct var **
1989findvar(struct var **vpp, const char *name)
1990{
1991 for (; *vpp; vpp = &(*vpp)->next) {
1992 if (varequal((*vpp)->text, name)) {
1993 break;
1994 }
1995 }
1996 return vpp;
1997}
1998
1999/*
2000 * Find the value of a variable. Returns NULL if not set.
2001 */
Mike Frysinger98c52642009-04-02 10:02:37 +00002002static const char *
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002003lookupvar(const char *name)
2004{
2005 struct var *v;
2006
2007 v = *findvar(hashvar(name), name);
2008 if (v) {
Denis Vlasenko448d30e2008-06-27 00:24:11 +00002009#if ENABLE_ASH_RANDOM_SUPPORT
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002010 /*
2011 * Dynamic variables are implemented roughly the same way they are
2012 * in bash. Namely, they're "special" so long as they aren't unset.
2013 * As soon as they're unset, they're no longer dynamic, and dynamic
2014 * lookup will no longer happen at that point. -- PFM.
2015 */
2016 if ((v->flags & VDYNAMIC))
2017 (*v->func)(NULL);
2018#endif
2019 if (!(v->flags & VUNSET))
2020 return strchrnul(v->text, '=') + 1;
2021 }
2022 return NULL;
2023}
2024
2025/*
2026 * Search the environment of a builtin command.
2027 */
Mike Frysinger98c52642009-04-02 10:02:37 +00002028static const char *
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002029bltinlookup(const char *name)
2030{
2031 struct strlist *sp;
2032
2033 for (sp = cmdenviron; sp; sp = sp->next) {
2034 if (varequal(sp->text, name))
2035 return strchrnul(sp->text, '=') + 1;
2036 }
2037 return lookupvar(name);
2038}
2039
2040/*
2041 * Same as setvar except that the variable and value are passed in
2042 * the first argument as name=value. Since the first argument will
2043 * be actually stored in the table, it should not be a string that
2044 * will go away.
2045 * Called with interrupts off.
2046 */
2047static void
2048setvareq(char *s, int flags)
2049{
2050 struct var *vp, **vpp;
2051
2052 vpp = hashvar(s);
2053 flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
2054 vp = *findvar(vpp, s);
2055 if (vp) {
2056 if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
2057 const char *n;
2058
2059 if (flags & VNOSAVE)
2060 free(s);
2061 n = vp->text;
2062 ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
2063 }
2064
2065 if (flags & VNOSET)
2066 return;
2067
2068 if (vp->func && (flags & VNOFUNC) == 0)
2069 (*vp->func)(strchrnul(s, '=') + 1);
2070
2071 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
2072 free((char*)vp->text);
2073
2074 flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
2075 } else {
2076 if (flags & VNOSET)
2077 return;
2078 /* not found */
Denis Vlasenko597906c2008-02-20 16:38:54 +00002079 vp = ckzalloc(sizeof(*vp));
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002080 vp->next = *vpp;
Denis Vlasenko597906c2008-02-20 16:38:54 +00002081 /*vp->func = NULL; - ckzalloc did it */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002082 *vpp = vp;
2083 }
2084 if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
2085 s = ckstrdup(s);
2086 vp->text = s;
2087 vp->flags = flags;
2088}
2089
2090/*
2091 * Set the value of a variable. The flags argument is ored with the
2092 * flags of the variable. If val is NULL, the variable is unset.
2093 */
2094static void
2095setvar(const char *name, const char *val, int flags)
2096{
2097 char *p, *q;
2098 size_t namelen;
2099 char *nameeq;
2100 size_t vallen;
2101
2102 q = endofname(name);
2103 p = strchrnul(q, '=');
2104 namelen = p - name;
2105 if (!namelen || p != q)
2106 ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
2107 vallen = 0;
2108 if (val == NULL) {
2109 flags |= VUNSET;
2110 } else {
2111 vallen = strlen(val);
2112 }
2113 INT_OFF;
2114 nameeq = ckmalloc(namelen + vallen + 2);
Denis Vlasenko29eb3592008-05-18 14:06:08 +00002115 p = (char *)memcpy(nameeq, name, namelen) + namelen;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002116 if (val) {
2117 *p++ = '=';
Denis Vlasenko29eb3592008-05-18 14:06:08 +00002118 p = (char *)memcpy(p, val, vallen) + vallen;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002119 }
2120 *p = '\0';
2121 setvareq(nameeq, flags | VNOSAVE);
2122 INT_ON;
2123}
2124
2125#if ENABLE_ASH_GETOPTS
2126/*
2127 * Safe version of setvar, returns 1 on success 0 on failure.
2128 */
2129static int
2130setvarsafe(const char *name, const char *val, int flags)
2131{
2132 int err;
2133 volatile int saveint;
2134 struct jmploc *volatile savehandler = exception_handler;
2135 struct jmploc jmploc;
2136
2137 SAVE_INT(saveint);
2138 if (setjmp(jmploc.loc))
2139 err = 1;
2140 else {
2141 exception_handler = &jmploc;
2142 setvar(name, val, flags);
2143 err = 0;
2144 }
2145 exception_handler = savehandler;
2146 RESTORE_INT(saveint);
2147 return err;
2148}
2149#endif
2150
2151/*
2152 * Unset the specified variable.
2153 */
2154static int
2155unsetvar(const char *s)
2156{
2157 struct var **vpp;
2158 struct var *vp;
2159 int retval;
2160
2161 vpp = findvar(hashvar(s), s);
2162 vp = *vpp;
2163 retval = 2;
2164 if (vp) {
2165 int flags = vp->flags;
2166
2167 retval = 1;
2168 if (flags & VREADONLY)
2169 goto out;
Denis Vlasenko448d30e2008-06-27 00:24:11 +00002170#if ENABLE_ASH_RANDOM_SUPPORT
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002171 vp->flags &= ~VDYNAMIC;
2172#endif
2173 if (flags & VUNSET)
2174 goto ok;
2175 if ((flags & VSTRFIXED) == 0) {
2176 INT_OFF;
2177 if ((flags & (VTEXTFIXED|VSTACK)) == 0)
2178 free((char*)vp->text);
2179 *vpp = vp->next;
2180 free(vp);
2181 INT_ON;
2182 } else {
2183 setvar(s, 0, 0);
2184 vp->flags &= ~VEXPORT;
2185 }
2186 ok:
2187 retval = 0;
2188 }
2189 out:
2190 return retval;
2191}
2192
2193/*
2194 * Process a linked list of variable assignments.
2195 */
2196static void
2197listsetvar(struct strlist *list_set_var, int flags)
2198{
2199 struct strlist *lp = list_set_var;
2200
2201 if (!lp)
2202 return;
2203 INT_OFF;
2204 do {
2205 setvareq(lp->text, flags);
Denis Vlasenko9650f362007-02-23 01:04:37 +00002206 lp = lp->next;
2207 } while (lp);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002208 INT_ON;
2209}
2210
2211/*
2212 * Generate a list of variables satisfying the given conditions.
2213 */
2214static char **
2215listvars(int on, int off, char ***end)
2216{
2217 struct var **vpp;
2218 struct var *vp;
2219 char **ep;
2220 int mask;
2221
2222 STARTSTACKSTR(ep);
2223 vpp = vartab;
2224 mask = on | off;
2225 do {
2226 for (vp = *vpp; vp; vp = vp->next) {
2227 if ((vp->flags & mask) == on) {
2228 if (ep == stackstrend())
2229 ep = growstackstr();
2230 *ep++ = (char *) vp->text;
2231 }
2232 }
2233 } while (++vpp < vartab + VTABSIZE);
2234 if (ep == stackstrend())
2235 ep = growstackstr();
2236 if (end)
2237 *end = ep;
2238 *ep++ = NULL;
2239 return grabstackstr(ep);
2240}
2241
2242
2243/* ============ Path search helper
2244 *
2245 * The variable path (passed by reference) should be set to the start
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02002246 * of the path before the first call; path_advance will update
2247 * this value as it proceeds. Successive calls to path_advance will return
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002248 * the possible path expansions in sequence. If an option (indicated by
2249 * a percent sign) appears in the path entry then the global variable
2250 * pathopt will be set to point to it; otherwise pathopt will be set to
2251 * NULL.
2252 */
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02002253static const char *pathopt; /* set by path_advance */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002254
2255static char *
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02002256path_advance(const char **path, const char *name)
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002257{
2258 const char *p;
2259 char *q;
2260 const char *start;
2261 size_t len;
2262
2263 if (*path == NULL)
2264 return NULL;
2265 start = *path;
Denis Vlasenkof7d56652008-03-25 05:51:41 +00002266 for (p = start; *p && *p != ':' && *p != '%'; p++)
2267 continue;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002268 len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
2269 while (stackblocksize() < len)
2270 growstackblock();
2271 q = stackblock();
2272 if (p != start) {
2273 memcpy(q, start, p - start);
2274 q += p - start;
2275 *q++ = '/';
2276 }
2277 strcpy(q, name);
2278 pathopt = NULL;
2279 if (*p == '%') {
2280 pathopt = ++p;
Denis Vlasenkof7d56652008-03-25 05:51:41 +00002281 while (*p && *p != ':')
2282 p++;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002283 }
2284 if (*p == ':')
2285 *path = p + 1;
2286 else
2287 *path = NULL;
2288 return stalloc(len);
2289}
2290
2291
2292/* ============ Prompt */
2293
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +00002294static smallint doprompt; /* if set, prompt the user */
2295static smallint needprompt; /* true if interactive and at start of line */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002296
2297#if ENABLE_FEATURE_EDITING
2298static line_input_t *line_input_state;
2299static const char *cmdedit_prompt;
2300static void
2301putprompt(const char *s)
2302{
2303 if (ENABLE_ASH_EXPAND_PRMT) {
2304 free((char*)cmdedit_prompt);
Denis Vlasenko4222ae42007-02-25 02:37:49 +00002305 cmdedit_prompt = ckstrdup(s);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002306 return;
2307 }
2308 cmdedit_prompt = s;
2309}
2310#else
2311static void
2312putprompt(const char *s)
2313{
2314 out2str(s);
2315}
2316#endif
2317
2318#if ENABLE_ASH_EXPAND_PRMT
2319/* expandstr() needs parsing machinery, so it is far away ahead... */
2320static const char *expandstr(const char *ps);
2321#else
2322#define expandstr(s) s
2323#endif
2324
2325static void
2326setprompt(int whichprompt)
2327{
2328 const char *prompt;
2329#if ENABLE_ASH_EXPAND_PRMT
2330 struct stackmark smark;
2331#endif
2332
2333 needprompt = 0;
2334
2335 switch (whichprompt) {
2336 case 1:
2337 prompt = ps1val();
2338 break;
2339 case 2:
2340 prompt = ps2val();
2341 break;
2342 default: /* 0 */
2343 prompt = nullstr;
2344 }
2345#if ENABLE_ASH_EXPAND_PRMT
2346 setstackmark(&smark);
2347 stalloc(stackblocksize());
2348#endif
2349 putprompt(expandstr(prompt));
2350#if ENABLE_ASH_EXPAND_PRMT
2351 popstackmark(&smark);
2352#endif
2353}
2354
2355
2356/* ============ The cd and pwd commands */
2357
2358#define CD_PHYSICAL 1
2359#define CD_PRINT 2
2360
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002361static int
2362cdopt(void)
2363{
2364 int flags = 0;
2365 int i, j;
2366
2367 j = 'L';
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02002368 while ((i = nextopt("LP")) != '\0') {
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002369 if (i != j) {
2370 flags ^= CD_PHYSICAL;
2371 j = i;
2372 }
2373 }
2374
2375 return flags;
2376}
2377
2378/*
2379 * Update curdir (the name of the current directory) in response to a
2380 * cd command.
2381 */
2382static const char *
2383updatepwd(const char *dir)
2384{
2385 char *new;
2386 char *p;
2387 char *cdcomppath;
2388 const char *lim;
2389
2390 cdcomppath = ststrdup(dir);
2391 STARTSTACKSTR(new);
2392 if (*dir != '/') {
2393 if (curdir == nullstr)
2394 return 0;
2395 new = stack_putstr(curdir, new);
2396 }
2397 new = makestrspace(strlen(dir) + 2, new);
Denis Vlasenko29eb3592008-05-18 14:06:08 +00002398 lim = (char *)stackblock() + 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002399 if (*dir != '/') {
2400 if (new[-1] != '/')
2401 USTPUTC('/', new);
2402 if (new > lim && *lim == '/')
2403 lim++;
2404 } else {
2405 USTPUTC('/', new);
2406 cdcomppath++;
2407 if (dir[1] == '/' && dir[2] != '/') {
2408 USTPUTC('/', new);
2409 cdcomppath++;
2410 lim++;
2411 }
2412 }
2413 p = strtok(cdcomppath, "/");
2414 while (p) {
2415 switch (*p) {
2416 case '.':
2417 if (p[1] == '.' && p[2] == '\0') {
2418 while (new > lim) {
2419 STUNPUTC(new);
2420 if (new[-1] == '/')
2421 break;
2422 }
2423 break;
Denis Vlasenko16abcd92007-04-13 23:59:52 +00002424 }
2425 if (p[1] == '\0')
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002426 break;
2427 /* fall through */
2428 default:
2429 new = stack_putstr(p, new);
2430 USTPUTC('/', new);
2431 }
2432 p = strtok(0, "/");
2433 }
2434 if (new > lim)
2435 STUNPUTC(new);
2436 *new = 0;
2437 return stackblock();
2438}
2439
2440/*
2441 * Find out what the current directory is. If we already know the current
2442 * directory, this routine returns immediately.
2443 */
2444static char *
2445getpwd(void)
2446{
Denis Vlasenko01631112007-12-16 17:20:38 +00002447 char *dir = getcwd(NULL, 0); /* huh, using glibc extension? */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002448 return dir ? dir : nullstr;
2449}
2450
2451static void
2452setpwd(const char *val, int setold)
2453{
2454 char *oldcur, *dir;
2455
2456 oldcur = dir = curdir;
2457
2458 if (setold) {
2459 setvar("OLDPWD", oldcur, VEXPORT);
2460 }
2461 INT_OFF;
2462 if (physdir != nullstr) {
2463 if (physdir != oldcur)
2464 free(physdir);
2465 physdir = nullstr;
2466 }
2467 if (oldcur == val || !val) {
2468 char *s = getpwd();
2469 physdir = s;
2470 if (!val)
2471 dir = s;
2472 } else
2473 dir = ckstrdup(val);
2474 if (oldcur != dir && oldcur != nullstr) {
2475 free(oldcur);
2476 }
2477 curdir = dir;
2478 INT_ON;
2479 setvar("PWD", dir, VEXPORT);
2480}
2481
2482static void hashcd(void);
2483
2484/*
2485 * Actually do the chdir. We also call hashcd to let the routines in exec.c
2486 * know that the current directory has changed.
2487 */
2488static int
2489docd(const char *dest, int flags)
2490{
2491 const char *dir = 0;
2492 int err;
2493
2494 TRACE(("docd(\"%s\", %d) called\n", dest, flags));
2495
2496 INT_OFF;
2497 if (!(flags & CD_PHYSICAL)) {
2498 dir = updatepwd(dest);
2499 if (dir)
2500 dest = dir;
2501 }
2502 err = chdir(dest);
2503 if (err)
2504 goto out;
2505 setpwd(dir, 1);
2506 hashcd();
2507 out:
2508 INT_ON;
2509 return err;
2510}
2511
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02002512static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00002513cdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002514{
2515 const char *dest;
2516 const char *path;
2517 const char *p;
2518 char c;
2519 struct stat statb;
2520 int flags;
2521
2522 flags = cdopt();
2523 dest = *argptr;
2524 if (!dest)
2525 dest = bltinlookup(homestr);
2526 else if (LONE_DASH(dest)) {
2527 dest = bltinlookup("OLDPWD");
2528 flags |= CD_PRINT;
2529 }
2530 if (!dest)
2531 dest = nullstr;
2532 if (*dest == '/')
2533 goto step7;
2534 if (*dest == '.') {
2535 c = dest[1];
2536 dotdot:
2537 switch (c) {
2538 case '\0':
2539 case '/':
2540 goto step6;
2541 case '.':
2542 c = dest[2];
2543 if (c != '.')
2544 goto dotdot;
2545 }
2546 }
2547 if (!*dest)
2548 dest = ".";
2549 path = bltinlookup("CDPATH");
2550 if (!path) {
2551 step6:
2552 step7:
2553 p = dest;
2554 goto docd;
2555 }
2556 do {
2557 c = *path;
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02002558 p = path_advance(&path, dest);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002559 if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
2560 if (c && c != ':')
2561 flags |= CD_PRINT;
2562 docd:
2563 if (!docd(p, flags))
2564 goto out;
2565 break;
2566 }
2567 } while (path);
2568 ash_msg_and_raise_error("can't cd to %s", dest);
2569 /* NOTREACHED */
2570 out:
2571 if (flags & CD_PRINT)
2572 out1fmt(snlfmt, curdir);
2573 return 0;
2574}
2575
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02002576static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00002577pwdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002578{
2579 int flags;
2580 const char *dir = curdir;
2581
2582 flags = cdopt();
2583 if (flags) {
2584 if (physdir == nullstr)
2585 setpwd(dir, 0);
2586 dir = physdir;
2587 }
2588 out1fmt(snlfmt, dir);
2589 return 0;
2590}
2591
Denis Vlasenko0c032a42007-02-23 01:03:40 +00002592
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00002593/* ============ ... */
Eric Andersenc470f442003-07-28 09:56:35 +00002594
Denis Vlasenko834dee72008-10-07 09:18:30 +00002595
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +00002596#define IBUFSIZ COMMON_BUFSIZE
Denis Vlasenko834dee72008-10-07 09:18:30 +00002597/* buffer for top level input file */
2598#define basebuf bb_common_bufsiz1
Eric Andersenc470f442003-07-28 09:56:35 +00002599
Eric Andersenc470f442003-07-28 09:56:35 +00002600/* Syntax classes */
Denis Vlasenko834dee72008-10-07 09:18:30 +00002601#define CWORD 0 /* character is nothing special */
2602#define CNL 1 /* newline character */
2603#define CBACK 2 /* a backslash character */
2604#define CSQUOTE 3 /* single quote */
2605#define CDQUOTE 4 /* double quote */
Eric Andersenc470f442003-07-28 09:56:35 +00002606#define CENDQUOTE 5 /* a terminating quote */
Denis Vlasenko834dee72008-10-07 09:18:30 +00002607#define CBQUOTE 6 /* backwards single quote */
2608#define CVAR 7 /* a dollar sign */
2609#define CENDVAR 8 /* a '}' character */
2610#define CLP 9 /* a left paren in arithmetic */
2611#define CRP 10 /* a right paren in arithmetic */
Eric Andersenc470f442003-07-28 09:56:35 +00002612#define CENDFILE 11 /* end of file */
Denis Vlasenko834dee72008-10-07 09:18:30 +00002613#define CCTL 12 /* like CWORD, except it must be escaped */
2614#define CSPCL 13 /* these terminate a word */
2615#define CIGN 14 /* character should be ignored */
Eric Andersenc470f442003-07-28 09:56:35 +00002616
Denis Vlasenko131ae172007-02-18 13:00:19 +00002617#if ENABLE_ASH_ALIAS
Denis Vlasenko834dee72008-10-07 09:18:30 +00002618#define SYNBASE 130
2619#define PEOF -130
2620#define PEOA -129
Eric Andersenc470f442003-07-28 09:56:35 +00002621#define PEOA_OR_PEOF PEOA
2622#else
Denis Vlasenko834dee72008-10-07 09:18:30 +00002623#define SYNBASE 129
2624#define PEOF -129
Eric Andersenc470f442003-07-28 09:56:35 +00002625#define PEOA_OR_PEOF PEOF
2626#endif
2627
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00002628/* number syntax index */
2629#define BASESYNTAX 0 /* not in quotes */
2630#define DQSYNTAX 1 /* in double quotes */
2631#define SQSYNTAX 2 /* in single quotes */
2632#define ARISYNTAX 3 /* in arithmetic */
Denis Vlasenko46a53062007-09-24 18:30:02 +00002633#define PSSYNTAX 4 /* prompt */
Eric Andersenc470f442003-07-28 09:56:35 +00002634
Denis Vlasenko131ae172007-02-18 13:00:19 +00002635#if ENABLE_ASH_OPTIMIZE_FOR_SIZE
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002636#define USE_SIT_FUNCTION
2637#endif
2638
Mike Frysinger98c52642009-04-02 10:02:37 +00002639#if ENABLE_SH_MATH_SUPPORT
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002640static const char S_I_T[][4] = {
Denis Vlasenko131ae172007-02-18 13:00:19 +00002641#if ENABLE_ASH_ALIAS
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00002642 { CSPCL, CIGN, CIGN, CIGN }, /* 0, PEOA */
Eric Andersenc470f442003-07-28 09:56:35 +00002643#endif
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00002644 { CSPCL, CWORD, CWORD, CWORD }, /* 1, ' ' */
2645 { CNL, CNL, CNL, CNL }, /* 2, \n */
2646 { CWORD, CCTL, CCTL, CWORD }, /* 3, !*-/:=?[]~ */
2647 { CDQUOTE, CENDQUOTE, CWORD, CWORD }, /* 4, '"' */
2648 { CVAR, CVAR, CWORD, CVAR }, /* 5, $ */
2649 { CSQUOTE, CWORD, CENDQUOTE, CWORD }, /* 6, "'" */
2650 { CSPCL, CWORD, CWORD, CLP }, /* 7, ( */
2651 { CSPCL, CWORD, CWORD, CRP }, /* 8, ) */
2652 { CBACK, CBACK, CCTL, CBACK }, /* 9, \ */
2653 { CBQUOTE, CBQUOTE, CWORD, CBQUOTE }, /* 10, ` */
2654 { CENDVAR, CENDVAR, CWORD, CENDVAR }, /* 11, } */
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002655#ifndef USE_SIT_FUNCTION
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00002656 { CENDFILE, CENDFILE, CENDFILE, CENDFILE }, /* 12, PEOF */
2657 { CWORD, CWORD, CWORD, CWORD }, /* 13, 0-9A-Za-z */
2658 { CCTL, CCTL, CCTL, CCTL } /* 14, CTLESC ... */
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002659#endif
Eric Andersen2870d962001-07-02 17:27:21 +00002660};
Eric Andersenc470f442003-07-28 09:56:35 +00002661#else
2662static const char S_I_T[][3] = {
Denis Vlasenko131ae172007-02-18 13:00:19 +00002663#if ENABLE_ASH_ALIAS
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00002664 { CSPCL, CIGN, CIGN }, /* 0, PEOA */
Eric Andersenc470f442003-07-28 09:56:35 +00002665#endif
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00002666 { CSPCL, CWORD, CWORD }, /* 1, ' ' */
2667 { CNL, CNL, CNL }, /* 2, \n */
2668 { CWORD, CCTL, CCTL }, /* 3, !*-/:=?[]~ */
2669 { CDQUOTE, CENDQUOTE, CWORD }, /* 4, '"' */
2670 { CVAR, CVAR, CWORD }, /* 5, $ */
2671 { CSQUOTE, CWORD, CENDQUOTE }, /* 6, "'" */
2672 { CSPCL, CWORD, CWORD }, /* 7, ( */
2673 { CSPCL, CWORD, CWORD }, /* 8, ) */
2674 { CBACK, CBACK, CCTL }, /* 9, \ */
2675 { CBQUOTE, CBQUOTE, CWORD }, /* 10, ` */
2676 { CENDVAR, CENDVAR, CWORD }, /* 11, } */
Eric Andersenc470f442003-07-28 09:56:35 +00002677#ifndef USE_SIT_FUNCTION
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00002678 { CENDFILE, CENDFILE, CENDFILE }, /* 12, PEOF */
2679 { CWORD, CWORD, CWORD }, /* 13, 0-9A-Za-z */
2680 { CCTL, CCTL, CCTL } /* 14, CTLESC ... */
Eric Andersenc470f442003-07-28 09:56:35 +00002681#endif
2682};
Mike Frysinger98c52642009-04-02 10:02:37 +00002683#endif /* SH_MATH_SUPPORT */
Eric Andersen2870d962001-07-02 17:27:21 +00002684
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002685#ifdef USE_SIT_FUNCTION
2686
Denis Vlasenko0c032a42007-02-23 01:03:40 +00002687static int
2688SIT(int c, int syntax)
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002689{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00002690 static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-/:;<=>?[\\]`|}~";
Denis Vlasenko131ae172007-02-18 13:00:19 +00002691#if ENABLE_ASH_ALIAS
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00002692 static const char syntax_index_table[] ALIGN1 = {
Eric Andersenc470f442003-07-28 09:56:35 +00002693 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
2694 7, 8, 3, 3, 3, 3, 1, 1, /* "()*-/:;<" */
2695 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
2696 11, 3 /* "}~" */
2697 };
2698#else
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00002699 static const char syntax_index_table[] ALIGN1 = {
Eric Andersenc470f442003-07-28 09:56:35 +00002700 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
2701 6, 7, 2, 2, 2, 2, 0, 0, /* "()*-/:;<" */
2702 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
2703 10, 2 /* "}~" */
2704 };
2705#endif
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002706 const char *s;
2707 int indx;
2708
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +00002709 if (c == PEOF) { /* 2^8+2 */
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002710 return CENDFILE;
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002711 }
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +00002712#if ENABLE_ASH_ALIAS
2713 if (c == PEOA) { /* 2^8+1 */
2714 indx = 0;
2715 } else
2716#endif
2717 {
Denys Vlasenkob0d63382009-09-16 16:18:32 +02002718 if ((unsigned char)c >= CTLESC
2719 && (unsigned char)c <= CTLQUOTEMARK
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +00002720 ) {
2721 return CCTL;
2722 }
2723 s = strchrnul(spec_symbls, c);
2724 if (*s == '\0') {
2725 return CWORD;
2726 }
2727 indx = syntax_index_table[s - spec_symbls];
2728 }
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002729 return S_I_T[indx][syntax];
2730}
2731
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00002732#else /* !USE_SIT_FUNCTION */
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002733
Denis Vlasenko131ae172007-02-18 13:00:19 +00002734#if ENABLE_ASH_ALIAS
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00002735#define CSPCL_CIGN_CIGN_CIGN 0
2736#define CSPCL_CWORD_CWORD_CWORD 1
2737#define CNL_CNL_CNL_CNL 2
2738#define CWORD_CCTL_CCTL_CWORD 3
2739#define CDQUOTE_CENDQUOTE_CWORD_CWORD 4
2740#define CVAR_CVAR_CWORD_CVAR 5
2741#define CSQUOTE_CWORD_CENDQUOTE_CWORD 6
2742#define CSPCL_CWORD_CWORD_CLP 7
2743#define CSPCL_CWORD_CWORD_CRP 8
2744#define CBACK_CBACK_CCTL_CBACK 9
2745#define CBQUOTE_CBQUOTE_CWORD_CBQUOTE 10
2746#define CENDVAR_CENDVAR_CWORD_CENDVAR 11
2747#define CENDFILE_CENDFILE_CENDFILE_CENDFILE 12
2748#define CWORD_CWORD_CWORD_CWORD 13
2749#define CCTL_CCTL_CCTL_CCTL 14
Eric Andersenc470f442003-07-28 09:56:35 +00002750#else
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00002751#define CSPCL_CWORD_CWORD_CWORD 0
2752#define CNL_CNL_CNL_CNL 1
2753#define CWORD_CCTL_CCTL_CWORD 2
2754#define CDQUOTE_CENDQUOTE_CWORD_CWORD 3
2755#define CVAR_CVAR_CWORD_CVAR 4
2756#define CSQUOTE_CWORD_CENDQUOTE_CWORD 5
2757#define CSPCL_CWORD_CWORD_CLP 6
2758#define CSPCL_CWORD_CWORD_CRP 7
2759#define CBACK_CBACK_CCTL_CBACK 8
2760#define CBQUOTE_CBQUOTE_CWORD_CBQUOTE 9
2761#define CENDVAR_CENDVAR_CWORD_CENDVAR 10
2762#define CENDFILE_CENDFILE_CENDFILE_CENDFILE 11
2763#define CWORD_CWORD_CWORD_CWORD 12
2764#define CCTL_CCTL_CCTL_CCTL 13
Eric Andersenc470f442003-07-28 09:56:35 +00002765#endif
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002766
2767static const char syntax_index_table[258] = {
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00002768 /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
Eric Andersenc470f442003-07-28 09:56:35 +00002769 /* 0 PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
Denis Vlasenko131ae172007-02-18 13:00:19 +00002770#if ENABLE_ASH_ALIAS
Eric Andersenc470f442003-07-28 09:56:35 +00002771 /* 1 PEOA */ CSPCL_CIGN_CIGN_CIGN,
2772#endif
2773 /* 2 -128 0x80 */ CWORD_CWORD_CWORD_CWORD,
2774 /* 3 -127 CTLESC */ CCTL_CCTL_CCTL_CCTL,
2775 /* 4 -126 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
2776 /* 5 -125 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
2777 /* 6 -124 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
2778 /* 7 -123 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
2779 /* 8 -122 CTLARI */ CCTL_CCTL_CCTL_CCTL,
2780 /* 9 -121 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
2781 /* 10 -120 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00002782 /* 11 -119 */ CWORD_CWORD_CWORD_CWORD,
2783 /* 12 -118 */ CWORD_CWORD_CWORD_CWORD,
2784 /* 13 -117 */ CWORD_CWORD_CWORD_CWORD,
2785 /* 14 -116 */ CWORD_CWORD_CWORD_CWORD,
2786 /* 15 -115 */ CWORD_CWORD_CWORD_CWORD,
2787 /* 16 -114 */ CWORD_CWORD_CWORD_CWORD,
2788 /* 17 -113 */ CWORD_CWORD_CWORD_CWORD,
2789 /* 18 -112 */ CWORD_CWORD_CWORD_CWORD,
2790 /* 19 -111 */ CWORD_CWORD_CWORD_CWORD,
2791 /* 20 -110 */ CWORD_CWORD_CWORD_CWORD,
2792 /* 21 -109 */ CWORD_CWORD_CWORD_CWORD,
2793 /* 22 -108 */ CWORD_CWORD_CWORD_CWORD,
2794 /* 23 -107 */ CWORD_CWORD_CWORD_CWORD,
2795 /* 24 -106 */ CWORD_CWORD_CWORD_CWORD,
2796 /* 25 -105 */ CWORD_CWORD_CWORD_CWORD,
2797 /* 26 -104 */ CWORD_CWORD_CWORD_CWORD,
2798 /* 27 -103 */ CWORD_CWORD_CWORD_CWORD,
2799 /* 28 -102 */ CWORD_CWORD_CWORD_CWORD,
2800 /* 29 -101 */ CWORD_CWORD_CWORD_CWORD,
2801 /* 30 -100 */ CWORD_CWORD_CWORD_CWORD,
2802 /* 31 -99 */ CWORD_CWORD_CWORD_CWORD,
2803 /* 32 -98 */ CWORD_CWORD_CWORD_CWORD,
2804 /* 33 -97 */ CWORD_CWORD_CWORD_CWORD,
2805 /* 34 -96 */ CWORD_CWORD_CWORD_CWORD,
2806 /* 35 -95 */ CWORD_CWORD_CWORD_CWORD,
2807 /* 36 -94 */ CWORD_CWORD_CWORD_CWORD,
2808 /* 37 -93 */ CWORD_CWORD_CWORD_CWORD,
2809 /* 38 -92 */ CWORD_CWORD_CWORD_CWORD,
2810 /* 39 -91 */ CWORD_CWORD_CWORD_CWORD,
2811 /* 40 -90 */ CWORD_CWORD_CWORD_CWORD,
2812 /* 41 -89 */ CWORD_CWORD_CWORD_CWORD,
2813 /* 42 -88 */ CWORD_CWORD_CWORD_CWORD,
2814 /* 43 -87 */ CWORD_CWORD_CWORD_CWORD,
2815 /* 44 -86 */ CWORD_CWORD_CWORD_CWORD,
2816 /* 45 -85 */ CWORD_CWORD_CWORD_CWORD,
2817 /* 46 -84 */ CWORD_CWORD_CWORD_CWORD,
2818 /* 47 -83 */ CWORD_CWORD_CWORD_CWORD,
2819 /* 48 -82 */ CWORD_CWORD_CWORD_CWORD,
2820 /* 49 -81 */ CWORD_CWORD_CWORD_CWORD,
2821 /* 50 -80 */ CWORD_CWORD_CWORD_CWORD,
2822 /* 51 -79 */ CWORD_CWORD_CWORD_CWORD,
2823 /* 52 -78 */ CWORD_CWORD_CWORD_CWORD,
2824 /* 53 -77 */ CWORD_CWORD_CWORD_CWORD,
2825 /* 54 -76 */ CWORD_CWORD_CWORD_CWORD,
2826 /* 55 -75 */ CWORD_CWORD_CWORD_CWORD,
2827 /* 56 -74 */ CWORD_CWORD_CWORD_CWORD,
2828 /* 57 -73 */ CWORD_CWORD_CWORD_CWORD,
2829 /* 58 -72 */ CWORD_CWORD_CWORD_CWORD,
2830 /* 59 -71 */ CWORD_CWORD_CWORD_CWORD,
2831 /* 60 -70 */ CWORD_CWORD_CWORD_CWORD,
2832 /* 61 -69 */ CWORD_CWORD_CWORD_CWORD,
2833 /* 62 -68 */ CWORD_CWORD_CWORD_CWORD,
2834 /* 63 -67 */ CWORD_CWORD_CWORD_CWORD,
2835 /* 64 -66 */ CWORD_CWORD_CWORD_CWORD,
2836 /* 65 -65 */ CWORD_CWORD_CWORD_CWORD,
2837 /* 66 -64 */ CWORD_CWORD_CWORD_CWORD,
2838 /* 67 -63 */ CWORD_CWORD_CWORD_CWORD,
2839 /* 68 -62 */ CWORD_CWORD_CWORD_CWORD,
2840 /* 69 -61 */ CWORD_CWORD_CWORD_CWORD,
2841 /* 70 -60 */ CWORD_CWORD_CWORD_CWORD,
2842 /* 71 -59 */ CWORD_CWORD_CWORD_CWORD,
2843 /* 72 -58 */ CWORD_CWORD_CWORD_CWORD,
2844 /* 73 -57 */ CWORD_CWORD_CWORD_CWORD,
2845 /* 74 -56 */ CWORD_CWORD_CWORD_CWORD,
2846 /* 75 -55 */ CWORD_CWORD_CWORD_CWORD,
2847 /* 76 -54 */ CWORD_CWORD_CWORD_CWORD,
2848 /* 77 -53 */ CWORD_CWORD_CWORD_CWORD,
2849 /* 78 -52 */ CWORD_CWORD_CWORD_CWORD,
2850 /* 79 -51 */ CWORD_CWORD_CWORD_CWORD,
2851 /* 80 -50 */ CWORD_CWORD_CWORD_CWORD,
2852 /* 81 -49 */ CWORD_CWORD_CWORD_CWORD,
2853 /* 82 -48 */ CWORD_CWORD_CWORD_CWORD,
2854 /* 83 -47 */ CWORD_CWORD_CWORD_CWORD,
2855 /* 84 -46 */ CWORD_CWORD_CWORD_CWORD,
2856 /* 85 -45 */ CWORD_CWORD_CWORD_CWORD,
2857 /* 86 -44 */ CWORD_CWORD_CWORD_CWORD,
2858 /* 87 -43 */ CWORD_CWORD_CWORD_CWORD,
2859 /* 88 -42 */ CWORD_CWORD_CWORD_CWORD,
2860 /* 89 -41 */ CWORD_CWORD_CWORD_CWORD,
2861 /* 90 -40 */ CWORD_CWORD_CWORD_CWORD,
2862 /* 91 -39 */ CWORD_CWORD_CWORD_CWORD,
2863 /* 92 -38 */ CWORD_CWORD_CWORD_CWORD,
2864 /* 93 -37 */ CWORD_CWORD_CWORD_CWORD,
2865 /* 94 -36 */ CWORD_CWORD_CWORD_CWORD,
2866 /* 95 -35 */ CWORD_CWORD_CWORD_CWORD,
2867 /* 96 -34 */ CWORD_CWORD_CWORD_CWORD,
2868 /* 97 -33 */ CWORD_CWORD_CWORD_CWORD,
2869 /* 98 -32 */ CWORD_CWORD_CWORD_CWORD,
2870 /* 99 -31 */ CWORD_CWORD_CWORD_CWORD,
2871 /* 100 -30 */ CWORD_CWORD_CWORD_CWORD,
2872 /* 101 -29 */ CWORD_CWORD_CWORD_CWORD,
2873 /* 102 -28 */ CWORD_CWORD_CWORD_CWORD,
2874 /* 103 -27 */ CWORD_CWORD_CWORD_CWORD,
2875 /* 104 -26 */ CWORD_CWORD_CWORD_CWORD,
2876 /* 105 -25 */ CWORD_CWORD_CWORD_CWORD,
2877 /* 106 -24 */ CWORD_CWORD_CWORD_CWORD,
2878 /* 107 -23 */ CWORD_CWORD_CWORD_CWORD,
2879 /* 108 -22 */ CWORD_CWORD_CWORD_CWORD,
2880 /* 109 -21 */ CWORD_CWORD_CWORD_CWORD,
2881 /* 110 -20 */ CWORD_CWORD_CWORD_CWORD,
2882 /* 111 -19 */ CWORD_CWORD_CWORD_CWORD,
2883 /* 112 -18 */ CWORD_CWORD_CWORD_CWORD,
2884 /* 113 -17 */ CWORD_CWORD_CWORD_CWORD,
2885 /* 114 -16 */ CWORD_CWORD_CWORD_CWORD,
2886 /* 115 -15 */ CWORD_CWORD_CWORD_CWORD,
2887 /* 116 -14 */ CWORD_CWORD_CWORD_CWORD,
2888 /* 117 -13 */ CWORD_CWORD_CWORD_CWORD,
2889 /* 118 -12 */ CWORD_CWORD_CWORD_CWORD,
2890 /* 119 -11 */ CWORD_CWORD_CWORD_CWORD,
2891 /* 120 -10 */ CWORD_CWORD_CWORD_CWORD,
2892 /* 121 -9 */ CWORD_CWORD_CWORD_CWORD,
2893 /* 122 -8 */ CWORD_CWORD_CWORD_CWORD,
2894 /* 123 -7 */ CWORD_CWORD_CWORD_CWORD,
2895 /* 124 -6 */ CWORD_CWORD_CWORD_CWORD,
2896 /* 125 -5 */ CWORD_CWORD_CWORD_CWORD,
2897 /* 126 -4 */ CWORD_CWORD_CWORD_CWORD,
2898 /* 127 -3 */ CWORD_CWORD_CWORD_CWORD,
2899 /* 128 -2 */ CWORD_CWORD_CWORD_CWORD,
2900 /* 129 -1 */ CWORD_CWORD_CWORD_CWORD,
2901 /* 130 0 */ CWORD_CWORD_CWORD_CWORD,
2902 /* 131 1 */ CWORD_CWORD_CWORD_CWORD,
2903 /* 132 2 */ CWORD_CWORD_CWORD_CWORD,
2904 /* 133 3 */ CWORD_CWORD_CWORD_CWORD,
2905 /* 134 4 */ CWORD_CWORD_CWORD_CWORD,
2906 /* 135 5 */ CWORD_CWORD_CWORD_CWORD,
2907 /* 136 6 */ CWORD_CWORD_CWORD_CWORD,
2908 /* 137 7 */ CWORD_CWORD_CWORD_CWORD,
2909 /* 138 8 */ CWORD_CWORD_CWORD_CWORD,
2910 /* 139 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
2911 /* 140 10 "\n" */ CNL_CNL_CNL_CNL,
2912 /* 141 11 */ CWORD_CWORD_CWORD_CWORD,
2913 /* 142 12 */ CWORD_CWORD_CWORD_CWORD,
2914 /* 143 13 */ CWORD_CWORD_CWORD_CWORD,
2915 /* 144 14 */ CWORD_CWORD_CWORD_CWORD,
2916 /* 145 15 */ CWORD_CWORD_CWORD_CWORD,
2917 /* 146 16 */ CWORD_CWORD_CWORD_CWORD,
2918 /* 147 17 */ CWORD_CWORD_CWORD_CWORD,
2919 /* 148 18 */ CWORD_CWORD_CWORD_CWORD,
2920 /* 149 19 */ CWORD_CWORD_CWORD_CWORD,
2921 /* 150 20 */ CWORD_CWORD_CWORD_CWORD,
2922 /* 151 21 */ CWORD_CWORD_CWORD_CWORD,
2923 /* 152 22 */ CWORD_CWORD_CWORD_CWORD,
2924 /* 153 23 */ CWORD_CWORD_CWORD_CWORD,
2925 /* 154 24 */ CWORD_CWORD_CWORD_CWORD,
2926 /* 155 25 */ CWORD_CWORD_CWORD_CWORD,
2927 /* 156 26 */ CWORD_CWORD_CWORD_CWORD,
2928 /* 157 27 */ CWORD_CWORD_CWORD_CWORD,
2929 /* 158 28 */ CWORD_CWORD_CWORD_CWORD,
2930 /* 159 29 */ CWORD_CWORD_CWORD_CWORD,
2931 /* 160 30 */ CWORD_CWORD_CWORD_CWORD,
2932 /* 161 31 */ CWORD_CWORD_CWORD_CWORD,
2933 /* 162 32 " " */ CSPCL_CWORD_CWORD_CWORD,
2934 /* 163 33 "!" */ CWORD_CCTL_CCTL_CWORD,
Eric Andersenc470f442003-07-28 09:56:35 +00002935 /* 164 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00002936 /* 165 35 "#" */ CWORD_CWORD_CWORD_CWORD,
2937 /* 166 36 "$" */ CVAR_CVAR_CWORD_CVAR,
2938 /* 167 37 "%" */ CWORD_CWORD_CWORD_CWORD,
2939 /* 168 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
Eric Andersenc470f442003-07-28 09:56:35 +00002940 /* 169 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00002941 /* 170 40 "(" */ CSPCL_CWORD_CWORD_CLP,
2942 /* 171 41 ")" */ CSPCL_CWORD_CWORD_CRP,
2943 /* 172 42 "*" */ CWORD_CCTL_CCTL_CWORD,
2944 /* 173 43 "+" */ CWORD_CWORD_CWORD_CWORD,
2945 /* 174 44 "," */ CWORD_CWORD_CWORD_CWORD,
2946 /* 175 45 "-" */ CWORD_CCTL_CCTL_CWORD,
2947 /* 176 46 "." */ CWORD_CWORD_CWORD_CWORD,
2948 /* 177 47 "/" */ CWORD_CCTL_CCTL_CWORD,
2949 /* 178 48 "0" */ CWORD_CWORD_CWORD_CWORD,
2950 /* 179 49 "1" */ CWORD_CWORD_CWORD_CWORD,
2951 /* 180 50 "2" */ CWORD_CWORD_CWORD_CWORD,
2952 /* 181 51 "3" */ CWORD_CWORD_CWORD_CWORD,
2953 /* 182 52 "4" */ CWORD_CWORD_CWORD_CWORD,
2954 /* 183 53 "5" */ CWORD_CWORD_CWORD_CWORD,
2955 /* 184 54 "6" */ CWORD_CWORD_CWORD_CWORD,
2956 /* 185 55 "7" */ CWORD_CWORD_CWORD_CWORD,
2957 /* 186 56 "8" */ CWORD_CWORD_CWORD_CWORD,
2958 /* 187 57 "9" */ CWORD_CWORD_CWORD_CWORD,
2959 /* 188 58 ":" */ CWORD_CCTL_CCTL_CWORD,
2960 /* 189 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
2961 /* 190 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
2962 /* 191 61 "=" */ CWORD_CCTL_CCTL_CWORD,
2963 /* 192 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
2964 /* 193 63 "?" */ CWORD_CCTL_CCTL_CWORD,
2965 /* 194 64 "@" */ CWORD_CWORD_CWORD_CWORD,
2966 /* 195 65 "A" */ CWORD_CWORD_CWORD_CWORD,
2967 /* 196 66 "B" */ CWORD_CWORD_CWORD_CWORD,
2968 /* 197 67 "C" */ CWORD_CWORD_CWORD_CWORD,
2969 /* 198 68 "D" */ CWORD_CWORD_CWORD_CWORD,
2970 /* 199 69 "E" */ CWORD_CWORD_CWORD_CWORD,
2971 /* 200 70 "F" */ CWORD_CWORD_CWORD_CWORD,
2972 /* 201 71 "G" */ CWORD_CWORD_CWORD_CWORD,
2973 /* 202 72 "H" */ CWORD_CWORD_CWORD_CWORD,
2974 /* 203 73 "I" */ CWORD_CWORD_CWORD_CWORD,
2975 /* 204 74 "J" */ CWORD_CWORD_CWORD_CWORD,
2976 /* 205 75 "K" */ CWORD_CWORD_CWORD_CWORD,
2977 /* 206 76 "L" */ CWORD_CWORD_CWORD_CWORD,
2978 /* 207 77 "M" */ CWORD_CWORD_CWORD_CWORD,
2979 /* 208 78 "N" */ CWORD_CWORD_CWORD_CWORD,
2980 /* 209 79 "O" */ CWORD_CWORD_CWORD_CWORD,
2981 /* 210 80 "P" */ CWORD_CWORD_CWORD_CWORD,
2982 /* 211 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
2983 /* 212 82 "R" */ CWORD_CWORD_CWORD_CWORD,
2984 /* 213 83 "S" */ CWORD_CWORD_CWORD_CWORD,
2985 /* 214 84 "T" */ CWORD_CWORD_CWORD_CWORD,
2986 /* 215 85 "U" */ CWORD_CWORD_CWORD_CWORD,
2987 /* 216 86 "V" */ CWORD_CWORD_CWORD_CWORD,
2988 /* 217 87 "W" */ CWORD_CWORD_CWORD_CWORD,
2989 /* 218 88 "X" */ CWORD_CWORD_CWORD_CWORD,
2990 /* 219 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
2991 /* 220 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
2992 /* 221 91 "[" */ CWORD_CCTL_CCTL_CWORD,
2993 /* 222 92 "\" */ CBACK_CBACK_CCTL_CBACK,
2994 /* 223 93 "]" */ CWORD_CCTL_CCTL_CWORD,
2995 /* 224 94 "^" */ CWORD_CWORD_CWORD_CWORD,
2996 /* 225 95 "_" */ CWORD_CWORD_CWORD_CWORD,
2997 /* 226 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
2998 /* 227 97 "a" */ CWORD_CWORD_CWORD_CWORD,
2999 /* 228 98 "b" */ CWORD_CWORD_CWORD_CWORD,
3000 /* 229 99 "c" */ CWORD_CWORD_CWORD_CWORD,
3001 /* 230 100 "d" */ CWORD_CWORD_CWORD_CWORD,
3002 /* 231 101 "e" */ CWORD_CWORD_CWORD_CWORD,
3003 /* 232 102 "f" */ CWORD_CWORD_CWORD_CWORD,
3004 /* 233 103 "g" */ CWORD_CWORD_CWORD_CWORD,
3005 /* 234 104 "h" */ CWORD_CWORD_CWORD_CWORD,
3006 /* 235 105 "i" */ CWORD_CWORD_CWORD_CWORD,
3007 /* 236 106 "j" */ CWORD_CWORD_CWORD_CWORD,
3008 /* 237 107 "k" */ CWORD_CWORD_CWORD_CWORD,
3009 /* 238 108 "l" */ CWORD_CWORD_CWORD_CWORD,
3010 /* 239 109 "m" */ CWORD_CWORD_CWORD_CWORD,
3011 /* 240 110 "n" */ CWORD_CWORD_CWORD_CWORD,
3012 /* 241 111 "o" */ CWORD_CWORD_CWORD_CWORD,
3013 /* 242 112 "p" */ CWORD_CWORD_CWORD_CWORD,
3014 /* 243 113 "q" */ CWORD_CWORD_CWORD_CWORD,
3015 /* 244 114 "r" */ CWORD_CWORD_CWORD_CWORD,
3016 /* 245 115 "s" */ CWORD_CWORD_CWORD_CWORD,
3017 /* 246 116 "t" */ CWORD_CWORD_CWORD_CWORD,
3018 /* 247 117 "u" */ CWORD_CWORD_CWORD_CWORD,
3019 /* 248 118 "v" */ CWORD_CWORD_CWORD_CWORD,
3020 /* 249 119 "w" */ CWORD_CWORD_CWORD_CWORD,
3021 /* 250 120 "x" */ CWORD_CWORD_CWORD_CWORD,
3022 /* 251 121 "y" */ CWORD_CWORD_CWORD_CWORD,
3023 /* 252 122 "z" */ CWORD_CWORD_CWORD_CWORD,
3024 /* 253 123 "{" */ CWORD_CWORD_CWORD_CWORD,
3025 /* 254 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
3026 /* 255 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
3027 /* 256 126 "~" */ CWORD_CCTL_CCTL_CWORD,
3028 /* 257 127 */ CWORD_CWORD_CWORD_CWORD,
Eric Andersen2870d962001-07-02 17:27:21 +00003029};
3030
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +00003031#define SIT(c, syntax) (S_I_T[(int)syntax_index_table[(int)(c) + SYNBASE]][syntax])
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00003032
"Vladimir N. Oleynik"fdb871c2006-01-25 11:53:47 +00003033#endif /* USE_SIT_FUNCTION */
Eric Andersenc470f442003-07-28 09:56:35 +00003034
Eric Andersen2870d962001-07-02 17:27:21 +00003035
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00003036/* ============ Alias handling */
Denis Vlasenkofc06f292007-02-23 21:09:35 +00003037
Denis Vlasenko131ae172007-02-18 13:00:19 +00003038#if ENABLE_ASH_ALIAS
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00003039
3040#define ALIASINUSE 1
3041#define ALIASDEAD 2
3042
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00003043struct alias {
3044 struct alias *next;
3045 char *name;
3046 char *val;
3047 int flag;
3048};
3049
Denis Vlasenko01631112007-12-16 17:20:38 +00003050
3051static struct alias **atab; // [ATABSIZE];
3052#define INIT_G_alias() do { \
3053 atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
3054} while (0)
3055
Eric Andersen2870d962001-07-02 17:27:21 +00003056
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00003057static struct alias **
3058__lookupalias(const char *name) {
3059 unsigned int hashval;
3060 struct alias **app;
3061 const char *p;
3062 unsigned int ch;
3063
3064 p = name;
3065
3066 ch = (unsigned char)*p;
3067 hashval = ch << 4;
3068 while (ch) {
3069 hashval += ch;
3070 ch = (unsigned char)*++p;
3071 }
3072 app = &atab[hashval % ATABSIZE];
3073
3074 for (; *app; app = &(*app)->next) {
3075 if (strcmp(name, (*app)->name) == 0) {
3076 break;
3077 }
3078 }
3079
3080 return app;
3081}
3082
3083static struct alias *
3084lookupalias(const char *name, int check)
3085{
3086 struct alias *ap = *__lookupalias(name);
3087
3088 if (check && ap && (ap->flag & ALIASINUSE))
3089 return NULL;
3090 return ap;
3091}
3092
3093static struct alias *
3094freealias(struct alias *ap)
3095{
3096 struct alias *next;
3097
3098 if (ap->flag & ALIASINUSE) {
3099 ap->flag |= ALIASDEAD;
3100 return ap;
3101 }
3102
3103 next = ap->next;
3104 free(ap->name);
3105 free(ap->val);
3106 free(ap);
3107 return next;
3108}
Eric Andersencb57d552001-06-28 07:25:16 +00003109
Eric Andersenc470f442003-07-28 09:56:35 +00003110static void
3111setalias(const char *name, const char *val)
Eric Andersencb57d552001-06-28 07:25:16 +00003112{
3113 struct alias *ap, **app;
3114
3115 app = __lookupalias(name);
3116 ap = *app;
Denis Vlasenkob012b102007-02-19 22:43:01 +00003117 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +00003118 if (ap) {
3119 if (!(ap->flag & ALIASINUSE)) {
Denis Vlasenkob012b102007-02-19 22:43:01 +00003120 free(ap->val);
Eric Andersencb57d552001-06-28 07:25:16 +00003121 }
Denis Vlasenko0c032a42007-02-23 01:03:40 +00003122 ap->val = ckstrdup(val);
Eric Andersencb57d552001-06-28 07:25:16 +00003123 ap->flag &= ~ALIASDEAD;
3124 } else {
3125 /* not found */
Denis Vlasenko597906c2008-02-20 16:38:54 +00003126 ap = ckzalloc(sizeof(struct alias));
Denis Vlasenko0c032a42007-02-23 01:03:40 +00003127 ap->name = ckstrdup(name);
3128 ap->val = ckstrdup(val);
Denis Vlasenko597906c2008-02-20 16:38:54 +00003129 /*ap->flag = 0; - ckzalloc did it */
3130 /*ap->next = NULL;*/
Eric Andersencb57d552001-06-28 07:25:16 +00003131 *app = ap;
3132 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00003133 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00003134}
3135
Eric Andersenc470f442003-07-28 09:56:35 +00003136static int
3137unalias(const char *name)
Eric Andersen2870d962001-07-02 17:27:21 +00003138{
Eric Andersencb57d552001-06-28 07:25:16 +00003139 struct alias **app;
3140
3141 app = __lookupalias(name);
3142
3143 if (*app) {
Denis Vlasenkob012b102007-02-19 22:43:01 +00003144 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +00003145 *app = freealias(*app);
Denis Vlasenkob012b102007-02-19 22:43:01 +00003146 INT_ON;
Denis Vlasenko079f8af2006-11-27 16:49:31 +00003147 return 0;
Eric Andersencb57d552001-06-28 07:25:16 +00003148 }
3149
Denis Vlasenko079f8af2006-11-27 16:49:31 +00003150 return 1;
Eric Andersencb57d552001-06-28 07:25:16 +00003151}
3152
Eric Andersenc470f442003-07-28 09:56:35 +00003153static void
3154rmaliases(void)
Eric Andersen2870d962001-07-02 17:27:21 +00003155{
Eric Andersencb57d552001-06-28 07:25:16 +00003156 struct alias *ap, **app;
3157 int i;
3158
Denis Vlasenkob012b102007-02-19 22:43:01 +00003159 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +00003160 for (i = 0; i < ATABSIZE; i++) {
3161 app = &atab[i];
3162 for (ap = *app; ap; ap = *app) {
3163 *app = freealias(*app);
3164 if (ap == *app) {
3165 app = &ap->next;
3166 }
3167 }
3168 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00003169 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00003170}
3171
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00003172static void
3173printalias(const struct alias *ap)
3174{
3175 out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
3176}
3177
Eric Andersencb57d552001-06-28 07:25:16 +00003178/*
3179 * TODO - sort output
3180 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02003181static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00003182aliascmd(int argc UNUSED_PARAM, char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +00003183{
3184 char *n, *v;
3185 int ret = 0;
3186 struct alias *ap;
3187
Denis Vlasenko68404f12008-03-17 09:00:54 +00003188 if (!argv[1]) {
Eric Andersencb57d552001-06-28 07:25:16 +00003189 int i;
3190
Denis Vlasenko68404f12008-03-17 09:00:54 +00003191 for (i = 0; i < ATABSIZE; i++) {
Eric Andersencb57d552001-06-28 07:25:16 +00003192 for (ap = atab[i]; ap; ap = ap->next) {
3193 printalias(ap);
3194 }
Denis Vlasenko68404f12008-03-17 09:00:54 +00003195 }
Denis Vlasenko079f8af2006-11-27 16:49:31 +00003196 return 0;
Eric Andersencb57d552001-06-28 07:25:16 +00003197 }
3198 while ((n = *++argv) != NULL) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00003199 v = strchr(n+1, '=');
3200 if (v == NULL) { /* n+1: funny ksh stuff */
3201 ap = *__lookupalias(n);
3202 if (ap == NULL) {
Eric Andersenc470f442003-07-28 09:56:35 +00003203 fprintf(stderr, "%s: %s not found\n", "alias", n);
Eric Andersencb57d552001-06-28 07:25:16 +00003204 ret = 1;
3205 } else
3206 printalias(ap);
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00003207 } else {
Eric Andersencb57d552001-06-28 07:25:16 +00003208 *v++ = '\0';
3209 setalias(n, v);
3210 }
3211 }
3212
Denis Vlasenkod9e15f22006-11-27 16:49:55 +00003213 return ret;
Eric Andersencb57d552001-06-28 07:25:16 +00003214}
3215
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02003216static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00003217unaliascmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersencb57d552001-06-28 07:25:16 +00003218{
3219 int i;
3220
3221 while ((i = nextopt("a")) != '\0') {
3222 if (i == 'a') {
3223 rmaliases();
Denis Vlasenko079f8af2006-11-27 16:49:31 +00003224 return 0;
Eric Andersencb57d552001-06-28 07:25:16 +00003225 }
3226 }
3227 for (i = 0; *argptr; argptr++) {
3228 if (unalias(*argptr)) {
Eric Andersenc470f442003-07-28 09:56:35 +00003229 fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
Eric Andersencb57d552001-06-28 07:25:16 +00003230 i = 1;
3231 }
3232 }
3233
Denis Vlasenkod9e15f22006-11-27 16:49:55 +00003234 return i;
Eric Andersencb57d552001-06-28 07:25:16 +00003235}
Denis Vlasenkofc06f292007-02-23 21:09:35 +00003236
Denis Vlasenko131ae172007-02-18 13:00:19 +00003237#endif /* ASH_ALIAS */
Eric Andersencb57d552001-06-28 07:25:16 +00003238
Eric Andersenc470f442003-07-28 09:56:35 +00003239
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003240/* ============ jobs.c */
3241
3242/* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
3243#define FORK_FG 0
3244#define FORK_BG 1
3245#define FORK_NOJOB 2
3246
3247/* mode flags for showjob(s) */
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003248#define SHOW_ONLY_PGID 0x01 /* show only pgid (jobs -p) */
3249#define SHOW_PIDS 0x02 /* show individual pids, not just one line per job */
3250#define SHOW_CHANGED 0x04 /* only jobs whose state has changed */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003251
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003252/*
3253 * A job structure contains information about a job. A job is either a
3254 * single process or a set of processes contained in a pipeline. In the
3255 * latter case, pidlist will be non-NULL, and will point to a -1 terminated
3256 * array of pids.
3257 */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003258struct procstat {
3259 pid_t pid; /* process id */
3260 int status; /* last process status from wait() */
3261 char *cmd; /* text of command being run */
3262};
3263
3264struct job {
3265 struct procstat ps0; /* status of process */
3266 struct procstat *ps; /* status or processes when more than one */
3267#if JOBS
3268 int stopstatus; /* status of a stopped job */
3269#endif
3270 uint32_t
3271 nprocs: 16, /* number of processes */
3272 state: 8,
3273#define JOBRUNNING 0 /* at least one proc running */
3274#define JOBSTOPPED 1 /* all procs are stopped */
3275#define JOBDONE 2 /* all procs are completed */
3276#if JOBS
3277 sigint: 1, /* job was killed by SIGINT */
3278 jobctl: 1, /* job running under job control */
3279#endif
3280 waited: 1, /* true if this entry has been waited for */
3281 used: 1, /* true if this entry is in used */
3282 changed: 1; /* true if status has changed */
3283 struct job *prev_job; /* previous job */
3284};
3285
Denis Vlasenko68404f12008-03-17 09:00:54 +00003286static struct job *makejob(/*union node *,*/ int);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003287static int forkshell(struct job *, union node *, int);
3288static int waitforjob(struct job *);
3289
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003290#if !JOBS
Denis Vlasenkob07a4962008-06-22 13:16:23 +00003291enum { doing_jobctl = 0 };
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003292#define setjobctl(on) do {} while (0)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003293#else
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003294static smallint doing_jobctl; //references:8
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003295static void setjobctl(int);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003296#endif
3297
3298/*
Denis Vlasenko4b875702009-03-19 13:30:04 +00003299 * Ignore a signal.
3300 */
3301static void
3302ignoresig(int signo)
3303{
3304 /* Avoid unnecessary system calls. Is it already SIG_IGNed? */
3305 if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
3306 /* No, need to do it */
3307 signal(signo, SIG_IGN);
3308 }
3309 sigmode[signo - 1] = S_HARD_IGN;
3310}
3311
3312/*
3313 * Signal handler. Only one usage site - in setsignal()
3314 */
3315static void
3316onsig(int signo)
3317{
3318 gotsig[signo - 1] = 1;
3319
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02003320 if (signo == SIGINT && !trap[SIGINT]) {
3321 if (!suppress_int) {
3322 pending_sig = 0;
Denis Vlasenko4b875702009-03-19 13:30:04 +00003323 raise_interrupt(); /* does not return */
3324 }
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02003325 pending_int = 1;
Denis Vlasenko4b875702009-03-19 13:30:04 +00003326 } else {
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02003327 pending_sig = signo;
Denis Vlasenko4b875702009-03-19 13:30:04 +00003328 }
3329}
3330
3331/*
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003332 * Set the signal handler for the specified signal. The routine figures
3333 * out what it should be set to.
3334 */
3335static void
3336setsignal(int signo)
3337{
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003338 char *t;
3339 char cur_act, new_act;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003340 struct sigaction act;
3341
3342 t = trap[signo];
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003343 new_act = S_DFL;
3344 if (t != NULL) { /* trap for this sig is set */
3345 new_act = S_CATCH;
3346 if (t[0] == '\0') /* trap is "": ignore this sig */
3347 new_act = S_IGN;
3348 }
3349
3350 if (rootshell && new_act == S_DFL) {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003351 switch (signo) {
3352 case SIGINT:
3353 if (iflag || minusc || sflag == 0)
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003354 new_act = S_CATCH;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003355 break;
3356 case SIGQUIT:
3357#if DEBUG
3358 if (debug)
3359 break;
3360#endif
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003361 /* man bash:
3362 * "In all cases, bash ignores SIGQUIT. Non-builtin
3363 * commands run by bash have signal handlers
3364 * set to the values inherited by the shell
3365 * from its parent". */
3366 new_act = S_IGN;
3367 break;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003368 case SIGTERM:
3369 if (iflag)
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003370 new_act = S_IGN;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003371 break;
3372#if JOBS
3373 case SIGTSTP:
3374 case SIGTTOU:
3375 if (mflag)
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003376 new_act = S_IGN;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003377 break;
3378#endif
3379 }
3380 }
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003381//TODO: if !rootshell, we reset SIGQUIT to DFL,
3382//whereas we have to restore it to what shell got on entry
3383//from the parent. See comment above
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003384
3385 t = &sigmode[signo - 1];
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003386 cur_act = *t;
3387 if (cur_act == 0) {
3388 /* current setting is not yet known */
3389 if (sigaction(signo, NULL, &act)) {
3390 /* pretend it worked; maybe we should give a warning,
3391 * but other shells don't. We don't alter sigmode,
3392 * so we retry every time.
3393 * btw, in Linux it never fails. --vda */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003394 return;
3395 }
3396 if (act.sa_handler == SIG_IGN) {
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003397 cur_act = S_HARD_IGN;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003398 if (mflag
3399 && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
3400 ) {
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003401 cur_act = S_IGN; /* don't hard ignore these */
Denis Vlasenko991a1da2008-02-10 19:02:53 +00003402 }
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003403 }
3404 }
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003405 if (cur_act == S_HARD_IGN || cur_act == new_act)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003406 return;
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003407
Denis Vlasenko991a1da2008-02-10 19:02:53 +00003408 act.sa_handler = SIG_DFL;
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003409 switch (new_act) {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003410 case S_CATCH:
3411 act.sa_handler = onsig;
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003412 act.sa_flags = 0; /* matters only if !DFL and !IGN */
3413 sigfillset(&act.sa_mask); /* ditto */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003414 break;
3415 case S_IGN:
3416 act.sa_handler = SIG_IGN;
3417 break;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003418 }
Denis Vlasenko8e2cfec2008-03-12 23:19:35 +00003419 sigaction_set(signo, &act);
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003420
3421 *t = new_act;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003422}
3423
3424/* mode flags for set_curjob */
3425#define CUR_DELETE 2
3426#define CUR_RUNNING 1
3427#define CUR_STOPPED 0
3428
3429/* mode flags for dowait */
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00003430#define DOWAIT_NONBLOCK WNOHANG
3431#define DOWAIT_BLOCK 0
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003432
3433#if JOBS
3434/* pgrp of shell on invocation */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003435static int initialpgrp; //references:2
3436static int ttyfd = -1; //5
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003437#endif
3438/* array of jobs */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003439static struct job *jobtab; //5
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003440/* size of array */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003441static unsigned njobs; //4
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003442/* current job */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003443static struct job *curjob; //lots
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003444/* number of presumed living untracked jobs */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003445static int jobless; //4
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003446
3447static void
3448set_curjob(struct job *jp, unsigned mode)
3449{
3450 struct job *jp1;
3451 struct job **jpp, **curp;
3452
3453 /* first remove from list */
3454 jpp = curp = &curjob;
3455 do {
3456 jp1 = *jpp;
3457 if (jp1 == jp)
3458 break;
3459 jpp = &jp1->prev_job;
3460 } while (1);
3461 *jpp = jp1->prev_job;
3462
3463 /* Then re-insert in correct position */
3464 jpp = curp;
3465 switch (mode) {
3466 default:
3467#if DEBUG
3468 abort();
3469#endif
3470 case CUR_DELETE:
3471 /* job being deleted */
3472 break;
3473 case CUR_RUNNING:
3474 /* newly created job or backgrounded job,
3475 put after all stopped jobs. */
3476 do {
3477 jp1 = *jpp;
3478#if JOBS
3479 if (!jp1 || jp1->state != JOBSTOPPED)
3480#endif
3481 break;
3482 jpp = &jp1->prev_job;
3483 } while (1);
3484 /* FALLTHROUGH */
3485#if JOBS
3486 case CUR_STOPPED:
3487#endif
3488 /* newly stopped job - becomes curjob */
3489 jp->prev_job = *jpp;
3490 *jpp = jp;
3491 break;
3492 }
3493}
3494
3495#if JOBS || DEBUG
3496static int
3497jobno(const struct job *jp)
3498{
3499 return jp - jobtab + 1;
3500}
3501#endif
3502
3503/*
3504 * Convert a job name to a job structure.
3505 */
Denis Vlasenko85c24712008-03-17 09:04:04 +00003506#if !JOBS
3507#define getjob(name, getctl) getjob(name)
3508#endif
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003509static struct job *
3510getjob(const char *name, int getctl)
3511{
3512 struct job *jp;
3513 struct job *found;
Denys Vlasenkoffc39202009-08-17 02:12:20 +02003514 const char *err_msg = "%s: no such job";
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003515 unsigned num;
3516 int c;
3517 const char *p;
3518 char *(*match)(const char *, const char *);
3519
3520 jp = curjob;
3521 p = name;
3522 if (!p)
3523 goto currentjob;
3524
3525 if (*p != '%')
3526 goto err;
3527
3528 c = *++p;
3529 if (!c)
3530 goto currentjob;
3531
3532 if (!p[1]) {
3533 if (c == '+' || c == '%') {
3534 currentjob:
3535 err_msg = "No current job";
3536 goto check;
3537 }
3538 if (c == '-') {
3539 if (jp)
3540 jp = jp->prev_job;
3541 err_msg = "No previous job";
3542 check:
3543 if (!jp)
3544 goto err;
3545 goto gotit;
3546 }
3547 }
3548
3549 if (is_number(p)) {
3550 num = atoi(p);
3551 if (num < njobs) {
3552 jp = jobtab + num - 1;
3553 if (jp->used)
3554 goto gotit;
3555 goto err;
3556 }
3557 }
3558
3559 match = prefix;
3560 if (*p == '?') {
3561 match = strstr;
3562 p++;
3563 }
3564
Denys Vlasenkoffc39202009-08-17 02:12:20 +02003565 found = NULL;
3566 while (jp) {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003567 if (match(jp->ps[0].cmd, p)) {
3568 if (found)
3569 goto err;
3570 found = jp;
3571 err_msg = "%s: ambiguous";
3572 }
3573 jp = jp->prev_job;
3574 }
Denys Vlasenkoffc39202009-08-17 02:12:20 +02003575 if (!found)
3576 goto err;
3577 jp = found;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003578
3579 gotit:
3580#if JOBS
3581 err_msg = "job %s not created under job control";
3582 if (getctl && jp->jobctl == 0)
3583 goto err;
3584#endif
3585 return jp;
3586 err:
3587 ash_msg_and_raise_error(err_msg, name);
3588}
3589
3590/*
3591 * Mark a job structure as unused.
3592 */
3593static void
3594freejob(struct job *jp)
3595{
3596 struct procstat *ps;
3597 int i;
3598
3599 INT_OFF;
3600 for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
3601 if (ps->cmd != nullstr)
3602 free(ps->cmd);
3603 }
3604 if (jp->ps != &jp->ps0)
3605 free(jp->ps);
3606 jp->used = 0;
3607 set_curjob(jp, CUR_DELETE);
3608 INT_ON;
3609}
3610
3611#if JOBS
3612static void
3613xtcsetpgrp(int fd, pid_t pgrp)
3614{
3615 if (tcsetpgrp(fd, pgrp))
Bernhard Reutner-Fischera53de7f2008-07-21 13:46:54 +00003616 ash_msg_and_raise_error("can't set tty process group (%m)");
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003617}
3618
3619/*
3620 * Turn job control on and off.
3621 *
3622 * Note: This code assumes that the third arg to ioctl is a character
3623 * pointer, which is true on Berkeley systems but not System V. Since
3624 * System V doesn't have job control yet, this isn't a problem now.
3625 *
3626 * Called with interrupts off.
3627 */
3628static void
3629setjobctl(int on)
3630{
3631 int fd;
3632 int pgrp;
3633
Denis Vlasenkob07a4962008-06-22 13:16:23 +00003634 if (on == doing_jobctl || rootshell == 0)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003635 return;
3636 if (on) {
3637 int ofd;
3638 ofd = fd = open(_PATH_TTY, O_RDWR);
3639 if (fd < 0) {
3640 /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
3641 * That sometimes helps to acquire controlling tty.
3642 * Obviously, a workaround for bugs when someone
3643 * failed to provide a controlling tty to bash! :) */
Denis Vlasenkoed270a52007-11-26 05:37:07 +00003644 fd = 2;
3645 while (!isatty(fd))
3646 if (--fd < 0)
3647 goto out;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003648 }
3649 fd = fcntl(fd, F_DUPFD, 10);
Denis Vlasenkoed270a52007-11-26 05:37:07 +00003650 if (ofd >= 0)
3651 close(ofd);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003652 if (fd < 0)
3653 goto out;
Denis Vlasenkoed270a52007-11-26 05:37:07 +00003654 /* fd is a tty at this point */
Denis Vlasenko96e1b382007-09-30 23:50:48 +00003655 close_on_exec_on(fd);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003656 do { /* while we are in the background */
3657 pgrp = tcgetpgrp(fd);
3658 if (pgrp < 0) {
3659 out:
3660 ash_msg("can't access tty; job control turned off");
3661 mflag = on = 0;
3662 goto close;
3663 }
3664 if (pgrp == getpgrp())
3665 break;
3666 killpg(0, SIGTTIN);
3667 } while (1);
3668 initialpgrp = pgrp;
3669
3670 setsignal(SIGTSTP);
3671 setsignal(SIGTTOU);
3672 setsignal(SIGTTIN);
3673 pgrp = rootpid;
3674 setpgid(0, pgrp);
3675 xtcsetpgrp(fd, pgrp);
3676 } else {
3677 /* turning job control off */
3678 fd = ttyfd;
3679 pgrp = initialpgrp;
Denis Vlasenko08c8c1d2007-04-28 22:39:02 +00003680 /* was xtcsetpgrp, but this can make exiting ash
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00003681 * loop forever if pty is already deleted */
Denis Vlasenko08c8c1d2007-04-28 22:39:02 +00003682 tcsetpgrp(fd, pgrp);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003683 setpgid(0, pgrp);
3684 setsignal(SIGTSTP);
3685 setsignal(SIGTTOU);
3686 setsignal(SIGTTIN);
3687 close:
Denis Vlasenkoed270a52007-11-26 05:37:07 +00003688 if (fd >= 0)
3689 close(fd);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003690 fd = -1;
3691 }
3692 ttyfd = fd;
Denis Vlasenkob07a4962008-06-22 13:16:23 +00003693 doing_jobctl = on;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003694}
3695
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02003696static int FAST_FUNC
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003697killcmd(int argc, char **argv)
3698{
Denis Vlasenko68404f12008-03-17 09:00:54 +00003699 int i = 1;
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003700 if (argv[1] && strcmp(argv[1], "-l") != 0) {
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003701 do {
3702 if (argv[i][0] == '%') {
3703 struct job *jp = getjob(argv[i], 0);
3704 unsigned pid = jp->ps[0].pid;
3705 /* Enough space for ' -NNN<nul>' */
3706 argv[i] = alloca(sizeof(int)*3 + 3);
3707 /* kill_main has matching code to expect
3708 * leading space. Needed to not confuse
3709 * negative pids with "kill -SIGNAL_NO" syntax */
3710 sprintf(argv[i], " -%u", pid);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003711 }
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003712 } while (argv[++i]);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003713 }
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003714 return kill_main(argc, argv);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003715}
3716
3717static void
3718showpipe(struct job *jp, FILE *out)
3719{
3720 struct procstat *sp;
3721 struct procstat *spend;
3722
3723 spend = jp->ps + jp->nprocs;
3724 for (sp = jp->ps + 1; sp < spend; sp++)
3725 fprintf(out, " | %s", sp->cmd);
3726 outcslow('\n', out);
3727 flush_stdout_stderr();
3728}
3729
3730
3731static int
3732restartjob(struct job *jp, int mode)
3733{
3734 struct procstat *ps;
3735 int i;
3736 int status;
3737 pid_t pgid;
3738
3739 INT_OFF;
3740 if (jp->state == JOBDONE)
3741 goto out;
3742 jp->state = JOBRUNNING;
3743 pgid = jp->ps->pid;
3744 if (mode == FORK_FG)
3745 xtcsetpgrp(ttyfd, pgid);
3746 killpg(pgid, SIGCONT);
3747 ps = jp->ps;
3748 i = jp->nprocs;
3749 do {
3750 if (WIFSTOPPED(ps->status)) {
3751 ps->status = -1;
3752 }
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003753 ps++;
3754 } while (--i);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003755 out:
3756 status = (mode == FORK_FG) ? waitforjob(jp) : 0;
3757 INT_ON;
3758 return status;
3759}
3760
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02003761static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00003762fg_bgcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003763{
3764 struct job *jp;
3765 FILE *out;
3766 int mode;
3767 int retval;
3768
3769 mode = (**argv == 'f') ? FORK_FG : FORK_BG;
3770 nextopt(nullstr);
3771 argv = argptr;
3772 out = stdout;
3773 do {
3774 jp = getjob(*argv, 1);
3775 if (mode == FORK_BG) {
3776 set_curjob(jp, CUR_RUNNING);
3777 fprintf(out, "[%d] ", jobno(jp));
3778 }
3779 outstr(jp->ps->cmd, out);
3780 showpipe(jp, out);
3781 retval = restartjob(jp, mode);
3782 } while (*argv && *++argv);
3783 return retval;
3784}
3785#endif
3786
3787static int
3788sprint_status(char *s, int status, int sigonly)
3789{
3790 int col;
3791 int st;
3792
3793 col = 0;
3794 if (!WIFEXITED(status)) {
3795#if JOBS
3796 if (WIFSTOPPED(status))
3797 st = WSTOPSIG(status);
3798 else
3799#endif
3800 st = WTERMSIG(status);
3801 if (sigonly) {
3802 if (st == SIGINT || st == SIGPIPE)
3803 goto out;
3804#if JOBS
3805 if (WIFSTOPPED(status))
3806 goto out;
3807#endif
3808 }
3809 st &= 0x7f;
3810 col = fmtstr(s, 32, strsignal(st));
3811 if (WCOREDUMP(status)) {
3812 col += fmtstr(s + col, 16, " (core dumped)");
3813 }
3814 } else if (!sigonly) {
3815 st = WEXITSTATUS(status);
3816 if (st)
3817 col = fmtstr(s, 16, "Done(%d)", st);
3818 else
3819 col = fmtstr(s, 16, "Done");
3820 }
3821 out:
3822 return col;
3823}
3824
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003825static int
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00003826dowait(int wait_flags, struct job *job)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003827{
3828 int pid;
3829 int status;
3830 struct job *jp;
3831 struct job *thisjob;
3832 int state;
3833
Denis Vlasenkobe54d6b2008-10-27 14:25:52 +00003834 TRACE(("dowait(0x%x) called\n", wait_flags));
3835
3836 /* Do a wait system call. If job control is compiled in, we accept
3837 * stopped processes. wait_flags may have WNOHANG, preventing blocking.
3838 * NB: _not_ safe_waitpid, we need to detect EINTR */
3839 pid = waitpid(-1, &status,
3840 (doing_jobctl ? (wait_flags | WUNTRACED) : wait_flags));
Denis Vlasenkob21f3792009-03-19 23:09:58 +00003841 TRACE(("wait returns pid=%d, status=0x%x, errno=%d(%s)\n",
3842 pid, status, errno, strerror(errno)));
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003843 if (pid <= 0)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003844 return pid;
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003845
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003846 INT_OFF;
3847 thisjob = NULL;
3848 for (jp = curjob; jp; jp = jp->prev_job) {
3849 struct procstat *sp;
3850 struct procstat *spend;
3851 if (jp->state == JOBDONE)
3852 continue;
3853 state = JOBDONE;
3854 spend = jp->ps + jp->nprocs;
3855 sp = jp->ps;
3856 do {
3857 if (sp->pid == pid) {
3858 TRACE(("Job %d: changing status of proc %d "
3859 "from 0x%x to 0x%x\n",
3860 jobno(jp), pid, sp->status, status));
3861 sp->status = status;
3862 thisjob = jp;
3863 }
3864 if (sp->status == -1)
3865 state = JOBRUNNING;
3866#if JOBS
3867 if (state == JOBRUNNING)
3868 continue;
3869 if (WIFSTOPPED(sp->status)) {
3870 jp->stopstatus = sp->status;
3871 state = JOBSTOPPED;
3872 }
3873#endif
3874 } while (++sp < spend);
3875 if (thisjob)
3876 goto gotjob;
3877 }
3878#if JOBS
3879 if (!WIFSTOPPED(status))
3880#endif
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003881 jobless--;
3882 goto out;
3883
3884 gotjob:
3885 if (state != JOBRUNNING) {
3886 thisjob->changed = 1;
3887
3888 if (thisjob->state != state) {
3889 TRACE(("Job %d: changing state from %d to %d\n",
3890 jobno(thisjob), thisjob->state, state));
3891 thisjob->state = state;
3892#if JOBS
3893 if (state == JOBSTOPPED) {
3894 set_curjob(thisjob, CUR_STOPPED);
3895 }
3896#endif
3897 }
3898 }
3899
3900 out:
3901 INT_ON;
3902
3903 if (thisjob && thisjob == job) {
3904 char s[48 + 1];
3905 int len;
3906
3907 len = sprint_status(s, status, 1);
3908 if (len) {
3909 s[len] = '\n';
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00003910 s[len + 1] = '\0';
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003911 out2str(s);
3912 }
3913 }
3914 return pid;
3915}
3916
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003917static int
3918blocking_wait_with_raise_on_sig(struct job *job)
3919{
3920 pid_t pid = dowait(DOWAIT_BLOCK, job);
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02003921 if (pid <= 0 && pending_sig)
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003922 raise_exception(EXSIG);
3923 return pid;
3924}
3925
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003926#if JOBS
3927static void
3928showjob(FILE *out, struct job *jp, int mode)
3929{
3930 struct procstat *ps;
3931 struct procstat *psend;
3932 int col;
Denis Vlasenko40ba9982007-07-14 00:48:29 +00003933 int indent_col;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003934 char s[80];
3935
3936 ps = jp->ps;
3937
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003938 if (mode & SHOW_ONLY_PGID) { /* jobs -p */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003939 /* just output process (group) id of pipeline */
3940 fprintf(out, "%d\n", ps->pid);
3941 return;
3942 }
3943
3944 col = fmtstr(s, 16, "[%d] ", jobno(jp));
Denis Vlasenko40ba9982007-07-14 00:48:29 +00003945 indent_col = col;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003946
3947 if (jp == curjob)
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003948 s[col - 3] = '+';
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003949 else if (curjob && jp == curjob->prev_job)
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003950 s[col - 3] = '-';
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003951
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003952 if (mode & SHOW_PIDS)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003953 col += fmtstr(s + col, 16, "%d ", ps->pid);
3954
3955 psend = ps + jp->nprocs;
3956
3957 if (jp->state == JOBRUNNING) {
3958 strcpy(s + col, "Running");
3959 col += sizeof("Running") - 1;
3960 } else {
3961 int status = psend[-1].status;
3962 if (jp->state == JOBSTOPPED)
3963 status = jp->stopstatus;
3964 col += sprint_status(s + col, status, 0);
3965 }
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003966 /* By now, "[JOBID]* [maybe PID] STATUS" is printed */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003967
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003968 /* This loop either prints "<cmd1> | <cmd2> | <cmd3>" line
3969 * or prints several "PID | <cmdN>" lines,
3970 * depending on SHOW_PIDS bit.
3971 * We do not print status of individual processes
3972 * between PID and <cmdN>. bash does it, but not very well:
3973 * first line shows overall job status, not process status,
3974 * making it impossible to know 1st process status.
3975 */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003976 goto start;
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003977 while (1) {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003978 /* for each process */
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003979 s[0] = '\0';
3980 col = 33;
3981 if (mode & SHOW_PIDS)
3982 col = fmtstr(s, 48, "\n%*c%d ", indent_col, ' ', ps->pid) - 1;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003983 start:
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003984 fprintf(out, "%s%*c", s, 33 - col >= 0 ? 33 - col : 0, ' ');
3985 if (ps != jp->ps)
3986 fprintf(out, "| ");
3987 fprintf(out, "%s", ps->cmd);
3988 if (++ps == psend)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003989 break;
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003990 }
3991 outcslow('\n', out);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003992
3993 jp->changed = 0;
3994
3995 if (jp->state == JOBDONE) {
3996 TRACE(("showjob: freeing job %d\n", jobno(jp)));
3997 freejob(jp);
3998 }
3999}
4000
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004001/*
4002 * Print a list of jobs. If "change" is nonzero, only print jobs whose
4003 * statuses have changed since the last call to showjobs.
4004 */
4005static void
4006showjobs(FILE *out, int mode)
4007{
4008 struct job *jp;
4009
Denys Vlasenko883cea42009-07-11 15:31:59 +02004010 TRACE(("showjobs(0x%x) called\n", mode));
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004011
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004012 /* Handle all finished jobs */
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00004013 while (dowait(DOWAIT_NONBLOCK, NULL) > 0)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004014 continue;
4015
4016 for (jp = curjob; jp; jp = jp->prev_job) {
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00004017 if (!(mode & SHOW_CHANGED) || jp->changed) {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004018 showjob(out, jp, mode);
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00004019 }
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004020 }
4021}
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00004022
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02004023static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00004024jobscmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00004025{
4026 int mode, m;
4027
4028 mode = 0;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02004029 while ((m = nextopt("lp")) != '\0') {
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00004030 if (m == 'l')
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02004031 mode |= SHOW_PIDS;
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00004032 else
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02004033 mode |= SHOW_ONLY_PGID;
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00004034 }
4035
4036 argv = argptr;
4037 if (*argv) {
4038 do
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02004039 showjob(stdout, getjob(*argv, 0), mode);
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00004040 while (*++argv);
4041 } else
4042 showjobs(stdout, mode);
4043
4044 return 0;
4045}
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004046#endif /* JOBS */
4047
4048static int
4049getstatus(struct job *job)
4050{
4051 int status;
4052 int retval;
4053
4054 status = job->ps[job->nprocs - 1].status;
4055 retval = WEXITSTATUS(status);
4056 if (!WIFEXITED(status)) {
4057#if JOBS
4058 retval = WSTOPSIG(status);
4059 if (!WIFSTOPPED(status))
4060#endif
4061 {
4062 /* XXX: limits number of signals */
4063 retval = WTERMSIG(status);
4064#if JOBS
4065 if (retval == SIGINT)
4066 job->sigint = 1;
4067#endif
4068 }
4069 retval += 128;
4070 }
Denys Vlasenko883cea42009-07-11 15:31:59 +02004071 TRACE(("getstatus: job %d, nproc %d, status 0x%x, retval 0x%x\n",
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004072 jobno(job), job->nprocs, status, retval));
4073 return retval;
4074}
4075
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02004076static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00004077waitcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004078{
4079 struct job *job;
4080 int retval;
4081 struct job *jp;
4082
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02004083 if (pending_sig)
Denis Vlasenko991a1da2008-02-10 19:02:53 +00004084 raise_exception(EXSIG);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004085
4086 nextopt(nullstr);
4087 retval = 0;
4088
4089 argv = argptr;
4090 if (!*argv) {
4091 /* wait for all jobs */
4092 for (;;) {
4093 jp = curjob;
4094 while (1) {
Denis Vlasenko991a1da2008-02-10 19:02:53 +00004095 if (!jp) /* no running procs */
4096 goto ret;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004097 if (jp->state == JOBRUNNING)
4098 break;
4099 jp->waited = 1;
4100 jp = jp->prev_job;
4101 }
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004102 /* man bash:
4103 * "When bash is waiting for an asynchronous command via
4104 * the wait builtin, the reception of a signal for which a trap
4105 * has been set will cause the wait builtin to return immediately
4106 * with an exit status greater than 128, immediately after which
4107 * the trap is executed."
4108 * Do we do it that way? */
4109 blocking_wait_with_raise_on_sig(NULL);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004110 }
4111 }
4112
4113 retval = 127;
4114 do {
4115 if (**argv != '%') {
4116 pid_t pid = number(*argv);
4117 job = curjob;
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00004118 while (1) {
4119 if (!job)
4120 goto repeat;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004121 if (job->ps[job->nprocs - 1].pid == pid)
4122 break;
4123 job = job->prev_job;
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00004124 }
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004125 } else
4126 job = getjob(*argv, 0);
4127 /* loop until process terminated or stopped */
4128 while (job->state == JOBRUNNING)
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004129 blocking_wait_with_raise_on_sig(NULL);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004130 job->waited = 1;
4131 retval = getstatus(job);
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004132 repeat: ;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004133 } while (*++argv);
4134
Denis Vlasenko991a1da2008-02-10 19:02:53 +00004135 ret:
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004136 return retval;
4137}
4138
4139static struct job *
4140growjobtab(void)
4141{
4142 size_t len;
4143 ptrdiff_t offset;
4144 struct job *jp, *jq;
4145
4146 len = njobs * sizeof(*jp);
4147 jq = jobtab;
4148 jp = ckrealloc(jq, len + 4 * sizeof(*jp));
4149
4150 offset = (char *)jp - (char *)jq;
4151 if (offset) {
4152 /* Relocate pointers */
4153 size_t l = len;
4154
4155 jq = (struct job *)((char *)jq + l);
4156 while (l) {
4157 l -= sizeof(*jp);
4158 jq--;
4159#define joff(p) ((struct job *)((char *)(p) + l))
4160#define jmove(p) (p) = (void *)((char *)(p) + offset)
4161 if (joff(jp)->ps == &jq->ps0)
4162 jmove(joff(jp)->ps);
4163 if (joff(jp)->prev_job)
4164 jmove(joff(jp)->prev_job);
4165 }
4166 if (curjob)
4167 jmove(curjob);
4168#undef joff
4169#undef jmove
4170 }
4171
4172 njobs += 4;
4173 jobtab = jp;
4174 jp = (struct job *)((char *)jp + len);
4175 jq = jp + 3;
4176 do {
4177 jq->used = 0;
4178 } while (--jq >= jp);
4179 return jp;
4180}
4181
4182/*
4183 * Return a new job structure.
4184 * Called with interrupts off.
4185 */
4186static struct job *
Denis Vlasenko68404f12008-03-17 09:00:54 +00004187makejob(/*union node *node,*/ int nprocs)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004188{
4189 int i;
4190 struct job *jp;
4191
4192 for (i = njobs, jp = jobtab; ; jp++) {
4193 if (--i < 0) {
4194 jp = growjobtab();
4195 break;
4196 }
4197 if (jp->used == 0)
4198 break;
4199 if (jp->state != JOBDONE || !jp->waited)
4200 continue;
4201#if JOBS
Denis Vlasenkob07a4962008-06-22 13:16:23 +00004202 if (doing_jobctl)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004203 continue;
4204#endif
4205 freejob(jp);
4206 break;
4207 }
4208 memset(jp, 0, sizeof(*jp));
4209#if JOBS
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00004210 /* jp->jobctl is a bitfield.
4211 * "jp->jobctl |= jobctl" likely to give awful code */
Denis Vlasenkob07a4962008-06-22 13:16:23 +00004212 if (doing_jobctl)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004213 jp->jobctl = 1;
4214#endif
4215 jp->prev_job = curjob;
4216 curjob = jp;
4217 jp->used = 1;
4218 jp->ps = &jp->ps0;
4219 if (nprocs > 1) {
4220 jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
4221 }
Denis Vlasenko68404f12008-03-17 09:00:54 +00004222 TRACE(("makejob(%d) returns %%%d\n", nprocs,
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004223 jobno(jp)));
4224 return jp;
4225}
4226
4227#if JOBS
4228/*
4229 * Return a string identifying a command (to be printed by the
4230 * jobs command).
4231 */
4232static char *cmdnextc;
4233
4234static void
4235cmdputs(const char *s)
4236{
Denis Vlasenko92e13c22008-03-25 01:17:40 +00004237 static const char vstype[VSTYPE + 1][3] = {
4238 "", "}", "-", "+", "?", "=",
4239 "%", "%%", "#", "##"
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00004240 IF_ASH_BASH_COMPAT(, ":", "/", "//")
Denis Vlasenko92e13c22008-03-25 01:17:40 +00004241 };
4242
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004243 const char *p, *str;
4244 char c, cc[2] = " ";
4245 char *nextc;
4246 int subtype = 0;
4247 int quoted = 0;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004248
4249 nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
4250 p = s;
4251 while ((c = *p++) != 0) {
Denis Vlasenkoef527f52008-06-23 01:52:30 +00004252 str = NULL;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004253 switch (c) {
4254 case CTLESC:
4255 c = *p++;
4256 break;
4257 case CTLVAR:
4258 subtype = *p++;
4259 if ((subtype & VSTYPE) == VSLENGTH)
4260 str = "${#";
4261 else
4262 str = "${";
4263 if (!(subtype & VSQUOTE) == !(quoted & 1))
4264 goto dostr;
4265 quoted ^= 1;
4266 c = '"';
4267 break;
4268 case CTLENDVAR:
4269 str = "\"}" + !(quoted & 1);
4270 quoted >>= 1;
4271 subtype = 0;
4272 goto dostr;
4273 case CTLBACKQ:
4274 str = "$(...)";
4275 goto dostr;
4276 case CTLBACKQ+CTLQUOTE:
4277 str = "\"$(...)\"";
4278 goto dostr;
Mike Frysinger98c52642009-04-02 10:02:37 +00004279#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004280 case CTLARI:
4281 str = "$((";
4282 goto dostr;
4283 case CTLENDARI:
4284 str = "))";
4285 goto dostr;
4286#endif
4287 case CTLQUOTEMARK:
4288 quoted ^= 1;
4289 c = '"';
4290 break;
4291 case '=':
4292 if (subtype == 0)
4293 break;
4294 if ((subtype & VSTYPE) != VSNORMAL)
4295 quoted <<= 1;
4296 str = vstype[subtype & VSTYPE];
4297 if (subtype & VSNUL)
4298 c = ':';
4299 else
4300 goto checkstr;
4301 break;
4302 case '\'':
4303 case '\\':
4304 case '"':
4305 case '$':
4306 /* These can only happen inside quotes */
4307 cc[0] = c;
4308 str = cc;
4309 c = '\\';
4310 break;
4311 default:
4312 break;
4313 }
4314 USTPUTC(c, nextc);
4315 checkstr:
4316 if (!str)
4317 continue;
4318 dostr:
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02004319 while ((c = *str++) != '\0') {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004320 USTPUTC(c, nextc);
4321 }
4322 }
4323 if (quoted & 1) {
4324 USTPUTC('"', nextc);
4325 }
4326 *nextc = 0;
4327 cmdnextc = nextc;
4328}
4329
4330/* cmdtxt() and cmdlist() call each other */
4331static void cmdtxt(union node *n);
4332
4333static void
4334cmdlist(union node *np, int sep)
4335{
4336 for (; np; np = np->narg.next) {
4337 if (!sep)
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00004338 cmdputs(" ");
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004339 cmdtxt(np);
4340 if (sep && np->narg.next)
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00004341 cmdputs(" ");
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004342 }
4343}
4344
4345static void
4346cmdtxt(union node *n)
4347{
4348 union node *np;
4349 struct nodelist *lp;
4350 const char *p;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004351
4352 if (!n)
4353 return;
4354 switch (n->type) {
4355 default:
4356#if DEBUG
4357 abort();
4358#endif
4359 case NPIPE:
4360 lp = n->npipe.cmdlist;
4361 for (;;) {
4362 cmdtxt(lp->n);
4363 lp = lp->next;
4364 if (!lp)
4365 break;
4366 cmdputs(" | ");
4367 }
4368 break;
4369 case NSEMI:
4370 p = "; ";
4371 goto binop;
4372 case NAND:
4373 p = " && ";
4374 goto binop;
4375 case NOR:
4376 p = " || ";
4377 binop:
4378 cmdtxt(n->nbinary.ch1);
4379 cmdputs(p);
4380 n = n->nbinary.ch2;
4381 goto donode;
4382 case NREDIR:
4383 case NBACKGND:
4384 n = n->nredir.n;
4385 goto donode;
4386 case NNOT:
4387 cmdputs("!");
4388 n = n->nnot.com;
4389 donode:
4390 cmdtxt(n);
4391 break;
4392 case NIF:
4393 cmdputs("if ");
4394 cmdtxt(n->nif.test);
4395 cmdputs("; then ");
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004396 if (n->nif.elsepart) {
Denys Vlasenko7cee00e2009-07-24 01:08:03 +02004397 cmdtxt(n->nif.ifpart);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004398 cmdputs("; else ");
4399 n = n->nif.elsepart;
Denys Vlasenko7cee00e2009-07-24 01:08:03 +02004400 } else {
4401 n = n->nif.ifpart;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004402 }
4403 p = "; fi";
4404 goto dotail;
4405 case NSUBSHELL:
4406 cmdputs("(");
4407 n = n->nredir.n;
4408 p = ")";
4409 goto dotail;
4410 case NWHILE:
4411 p = "while ";
4412 goto until;
4413 case NUNTIL:
4414 p = "until ";
4415 until:
4416 cmdputs(p);
4417 cmdtxt(n->nbinary.ch1);
4418 n = n->nbinary.ch2;
4419 p = "; done";
4420 dodo:
4421 cmdputs("; do ");
4422 dotail:
4423 cmdtxt(n);
4424 goto dotail2;
4425 case NFOR:
4426 cmdputs("for ");
4427 cmdputs(n->nfor.var);
4428 cmdputs(" in ");
4429 cmdlist(n->nfor.args, 1);
4430 n = n->nfor.body;
4431 p = "; done";
4432 goto dodo;
4433 case NDEFUN:
4434 cmdputs(n->narg.text);
4435 p = "() { ... }";
4436 goto dotail2;
4437 case NCMD:
4438 cmdlist(n->ncmd.args, 1);
4439 cmdlist(n->ncmd.redirect, 0);
4440 break;
4441 case NARG:
4442 p = n->narg.text;
4443 dotail2:
4444 cmdputs(p);
4445 break;
4446 case NHERE:
4447 case NXHERE:
4448 p = "<<...";
4449 goto dotail2;
4450 case NCASE:
4451 cmdputs("case ");
4452 cmdputs(n->ncase.expr->narg.text);
4453 cmdputs(" in ");
4454 for (np = n->ncase.cases; np; np = np->nclist.next) {
4455 cmdtxt(np->nclist.pattern);
4456 cmdputs(") ");
4457 cmdtxt(np->nclist.body);
4458 cmdputs(";; ");
4459 }
4460 p = "esac";
4461 goto dotail2;
4462 case NTO:
4463 p = ">";
4464 goto redir;
4465 case NCLOBBER:
4466 p = ">|";
4467 goto redir;
4468 case NAPPEND:
4469 p = ">>";
4470 goto redir;
Denis Vlasenko559691a2008-10-05 18:39:31 +00004471#if ENABLE_ASH_BASH_COMPAT
4472 case NTO2:
4473#endif
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004474 case NTOFD:
4475 p = ">&";
4476 goto redir;
4477 case NFROM:
4478 p = "<";
4479 goto redir;
4480 case NFROMFD:
4481 p = "<&";
4482 goto redir;
4483 case NFROMTO:
4484 p = "<>";
4485 redir:
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00004486 cmdputs(utoa(n->nfile.fd));
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004487 cmdputs(p);
4488 if (n->type == NTOFD || n->type == NFROMFD) {
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00004489 cmdputs(utoa(n->ndup.dupfd));
4490 break;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004491 }
4492 n = n->nfile.fname;
4493 goto donode;
4494 }
4495}
4496
4497static char *
4498commandtext(union node *n)
4499{
4500 char *name;
4501
4502 STARTSTACKSTR(cmdnextc);
4503 cmdtxt(n);
4504 name = stackblock();
4505 TRACE(("commandtext: name %p, end %p\n\t\"%s\"\n",
4506 name, cmdnextc, cmdnextc));
4507 return ckstrdup(name);
4508}
4509#endif /* JOBS */
4510
4511/*
4512 * Fork off a subshell. If we are doing job control, give the subshell its
4513 * own process group. Jp is a job structure that the job is to be added to.
4514 * N is the command that will be evaluated by the child. Both jp and n may
4515 * be NULL. The mode parameter can be one of the following:
4516 * FORK_FG - Fork off a foreground process.
4517 * FORK_BG - Fork off a background process.
4518 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
4519 * process group even if job control is on.
4520 *
4521 * When job control is turned off, background processes have their standard
4522 * input redirected to /dev/null (except for the second and later processes
4523 * in a pipeline).
4524 *
4525 * Called with interrupts off.
4526 */
4527/*
4528 * Clear traps on a fork.
4529 */
4530static void
4531clear_traps(void)
4532{
4533 char **tp;
4534
4535 for (tp = trap; tp < &trap[NSIG]; tp++) {
Denis Vlasenko991a1da2008-02-10 19:02:53 +00004536 if (*tp && **tp) { /* trap not NULL or "" (SIG_IGN) */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004537 INT_OFF;
Denys Vlasenkoe305c282009-09-25 02:12:27 +02004538 if (trap_ptr == trap)
4539 free(*tp);
4540 /* else: it "belongs" to trap_ptr vector, don't free */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004541 *tp = NULL;
Denys Vlasenko0800e3a2009-09-24 03:09:26 +02004542 if ((tp - trap) != 0)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004543 setsignal(tp - trap);
4544 INT_ON;
4545 }
4546 }
4547}
Denis Vlasenkobdc406d2007-07-15 01:13:25 +00004548
4549/* Lives far away from here, needed for forkchild */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004550static void closescript(void);
Denis Vlasenko41770222007-10-07 18:02:52 +00004551
Denis Vlasenkobdc406d2007-07-15 01:13:25 +00004552/* Called after fork(), in child */
Denys Vlasenko21d87d42009-09-25 00:06:51 +02004553static NOINLINE void
Denys Vlasenkoe56f22a2009-07-24 00:16:59 +02004554forkchild(struct job *jp, union node *n, int mode)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004555{
4556 int oldlvl;
4557
4558 TRACE(("Child shell %d\n", getpid()));
4559 oldlvl = shlvl;
4560 shlvl++;
4561
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004562 /* man bash: "Non-builtin commands run by bash have signal handlers
4563 * set to the values inherited by the shell from its parent".
4564 * Do we do it correctly? */
4565
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004566 closescript();
Denys Vlasenko844f9902009-09-23 03:25:52 +02004567
4568 if (mode == FORK_NOJOB /* is it `xxx` ? */
4569 && n && n->type == NCMD /* is it single cmd? */
4570 /* && n->ncmd.args->type == NARG - always true? */
4571 && strcmp(n->ncmd.args->narg.text, "trap") == 0
4572 && n->ncmd.args->narg.next == NULL /* "trap" with no arguments */
4573 /* && n->ncmd.args->narg.backquote == NULL - do we need to check this? */
4574 ) {
4575 TRACE(("Trap hack\n"));
4576 /* Awful hack for `trap` or $(trap).
4577 *
4578 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
4579 * contains an example where "trap" is executed in a subshell:
4580 *
4581 * save_traps=$(trap)
4582 * ...
4583 * eval "$save_traps"
4584 *
4585 * Standard does not say that "trap" in subshell shall print
4586 * parent shell's traps. It only says that its output
4587 * must have suitable form, but then, in the above example
4588 * (which is not supposed to be normative), it implies that.
4589 *
4590 * bash (and probably other shell) does implement it
4591 * (traps are reset to defaults, but "trap" still shows them),
4592 * but as a result, "trap" logic is hopelessly messed up:
4593 *
4594 * # trap
4595 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
4596 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
4597 * # true | trap <--- trap is in subshell - no output (ditto)
4598 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
4599 * trap -- 'echo Ho' SIGWINCH
4600 * # echo `(trap)` <--- in subshell in subshell - output
4601 * trap -- 'echo Ho' SIGWINCH
4602 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
4603 * trap -- 'echo Ho' SIGWINCH
4604 *
4605 * The rules when to forget and when to not forget traps
4606 * get really complex and nonsensical.
4607 *
4608 * Our solution: ONLY bare $(trap) or `trap` is special.
4609 */
Denys Vlasenko8f88d852009-09-25 12:12:53 +02004610 /* Save trap handler strings for trap builtin to print */
Denys Vlasenko21d87d42009-09-25 00:06:51 +02004611 trap_ptr = memcpy(xmalloc(sizeof(trap)), trap, sizeof(trap));
Denys Vlasenko8f88d852009-09-25 12:12:53 +02004612 /* Fall through into clearing traps */
Denys Vlasenko844f9902009-09-23 03:25:52 +02004613 }
Denys Vlasenkoe305c282009-09-25 02:12:27 +02004614 clear_traps();
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004615#if JOBS
4616 /* do job control only in root shell */
Denis Vlasenkob07a4962008-06-22 13:16:23 +00004617 doing_jobctl = 0;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004618 if (mode != FORK_NOJOB && jp->jobctl && !oldlvl) {
4619 pid_t pgrp;
4620
4621 if (jp->nprocs == 0)
4622 pgrp = getpid();
4623 else
4624 pgrp = jp->ps[0].pid;
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004625 /* this can fail because we are doing it in the parent also */
4626 setpgid(0, pgrp);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004627 if (mode == FORK_FG)
4628 xtcsetpgrp(ttyfd, pgrp);
4629 setsignal(SIGTSTP);
4630 setsignal(SIGTTOU);
4631 } else
4632#endif
4633 if (mode == FORK_BG) {
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004634 /* man bash: "When job control is not in effect,
4635 * asynchronous commands ignore SIGINT and SIGQUIT" */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004636 ignoresig(SIGINT);
4637 ignoresig(SIGQUIT);
4638 if (jp->nprocs == 0) {
4639 close(0);
4640 if (open(bb_dev_null, O_RDONLY) != 0)
Denis Vlasenko9604e1b2009-03-03 18:47:56 +00004641 ash_msg_and_raise_error("can't open '%s'", bb_dev_null);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004642 }
4643 }
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004644 if (!oldlvl) {
4645 if (iflag) { /* why if iflag only? */
4646 setsignal(SIGINT);
4647 setsignal(SIGTERM);
4648 }
4649 /* man bash:
4650 * "In all cases, bash ignores SIGQUIT. Non-builtin
4651 * commands run by bash have signal handlers
4652 * set to the values inherited by the shell
4653 * from its parent".
4654 * Take care of the second rule: */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004655 setsignal(SIGQUIT);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004656 }
Denys Vlasenkoe56f22a2009-07-24 00:16:59 +02004657#if JOBS
Denys Vlasenko844f9902009-09-23 03:25:52 +02004658 if (n && n->type == NCMD
4659 && strcmp(n->ncmd.args->narg.text, "jobs") == 0
4660 ) {
Denys Vlasenkoe56f22a2009-07-24 00:16:59 +02004661 TRACE(("Job hack\n"));
Denys Vlasenko844f9902009-09-23 03:25:52 +02004662 /* "jobs": we do not want to clear job list for it,
4663 * instead we remove only _its_ own_ job from job list.
4664 * This makes "jobs .... | cat" more useful.
4665 */
Denys Vlasenkoe56f22a2009-07-24 00:16:59 +02004666 freejob(curjob);
4667 return;
4668 }
4669#endif
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004670 for (jp = curjob; jp; jp = jp->prev_job)
4671 freejob(jp);
4672 jobless = 0;
4673}
4674
Denis Vlasenkobdc406d2007-07-15 01:13:25 +00004675/* Called after fork(), in parent */
Denis Vlasenko85c24712008-03-17 09:04:04 +00004676#if !JOBS
4677#define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
4678#endif
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004679static void
4680forkparent(struct job *jp, union node *n, int mode, pid_t pid)
4681{
4682 TRACE(("In parent shell: child = %d\n", pid));
4683 if (!jp) {
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00004684 while (jobless && dowait(DOWAIT_NONBLOCK, NULL) > 0)
4685 continue;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004686 jobless++;
4687 return;
4688 }
4689#if JOBS
4690 if (mode != FORK_NOJOB && jp->jobctl) {
4691 int pgrp;
4692
4693 if (jp->nprocs == 0)
4694 pgrp = pid;
4695 else
4696 pgrp = jp->ps[0].pid;
4697 /* This can fail because we are doing it in the child also */
4698 setpgid(pid, pgrp);
4699 }
4700#endif
4701 if (mode == FORK_BG) {
4702 backgndpid = pid; /* set $! */
4703 set_curjob(jp, CUR_RUNNING);
4704 }
4705 if (jp) {
4706 struct procstat *ps = &jp->ps[jp->nprocs++];
4707 ps->pid = pid;
4708 ps->status = -1;
4709 ps->cmd = nullstr;
4710#if JOBS
Denis Vlasenkob07a4962008-06-22 13:16:23 +00004711 if (doing_jobctl && n)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004712 ps->cmd = commandtext(n);
4713#endif
4714 }
4715}
4716
4717static int
4718forkshell(struct job *jp, union node *n, int mode)
4719{
4720 int pid;
4721
4722 TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
4723 pid = fork();
4724 if (pid < 0) {
4725 TRACE(("Fork failed, errno=%d", errno));
4726 if (jp)
4727 freejob(jp);
Denis Vlasenkofa0b56d2008-07-01 16:09:07 +00004728 ash_msg_and_raise_error("can't fork");
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004729 }
Denys Vlasenko76ace252009-10-12 15:25:01 +02004730 if (pid == 0) {
4731 CLEAR_RANDOM_T(&random_gen); /* or else $RANDOM repeats in child */
Denys Vlasenkoe56f22a2009-07-24 00:16:59 +02004732 forkchild(jp, n, mode);
Denys Vlasenko76ace252009-10-12 15:25:01 +02004733 } else {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004734 forkparent(jp, n, mode, pid);
Denys Vlasenko76ace252009-10-12 15:25:01 +02004735 }
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004736 return pid;
4737}
4738
4739/*
4740 * Wait for job to finish.
4741 *
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004742 * Under job control we have the problem that while a child process
4743 * is running interrupts generated by the user are sent to the child
4744 * but not to the shell. This means that an infinite loop started by
4745 * an interactive user may be hard to kill. With job control turned off,
4746 * an interactive user may place an interactive program inside a loop.
4747 * If the interactive program catches interrupts, the user doesn't want
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004748 * these interrupts to also abort the loop. The approach we take here
4749 * is to have the shell ignore interrupt signals while waiting for a
4750 * foreground process to terminate, and then send itself an interrupt
4751 * signal if the child process was terminated by an interrupt signal.
4752 * Unfortunately, some programs want to do a bit of cleanup and then
4753 * exit on interrupt; unless these processes terminate themselves by
4754 * sending a signal to themselves (instead of calling exit) they will
4755 * confuse this approach.
4756 *
4757 * Called with interrupts off.
4758 */
4759static int
4760waitforjob(struct job *jp)
4761{
4762 int st;
4763
4764 TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004765
4766 INT_OFF;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004767 while (jp->state == JOBRUNNING) {
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004768 /* In non-interactive shells, we _can_ get
4769 * a keyboard signal here and be EINTRed,
4770 * but we just loop back, waiting for command to complete.
4771 *
4772 * man bash:
4773 * "If bash is waiting for a command to complete and receives
4774 * a signal for which a trap has been set, the trap
4775 * will not be executed until the command completes."
4776 *
4777 * Reality is that even if trap is not set, bash
4778 * will not act on the signal until command completes.
4779 * Try this. sleep5intoff.c:
4780 * #include <signal.h>
4781 * #include <unistd.h>
4782 * int main() {
4783 * sigset_t set;
4784 * sigemptyset(&set);
4785 * sigaddset(&set, SIGINT);
4786 * sigaddset(&set, SIGQUIT);
4787 * sigprocmask(SIG_BLOCK, &set, NULL);
4788 * sleep(5);
4789 * return 0;
4790 * }
4791 * $ bash -c './sleep5intoff; echo hi'
4792 * ^C^C^C^C <--- pressing ^C once a second
4793 * $ _
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004794 * $ bash -c './sleep5intoff; echo hi'
4795 * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
4796 * $ _
4797 */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004798 dowait(DOWAIT_BLOCK, jp);
4799 }
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004800 INT_ON;
4801
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004802 st = getstatus(jp);
4803#if JOBS
4804 if (jp->jobctl) {
4805 xtcsetpgrp(ttyfd, rootpid);
4806 /*
4807 * This is truly gross.
4808 * If we're doing job control, then we did a TIOCSPGRP which
4809 * caused us (the shell) to no longer be in the controlling
4810 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
4811 * intuit from the subprocess exit status whether a SIGINT
4812 * occurred, and if so interrupt ourselves. Yuck. - mycroft
4813 */
Denis Vlasenko991a1da2008-02-10 19:02:53 +00004814 if (jp->sigint) /* TODO: do the same with all signals */
4815 raise(SIGINT); /* ... by raise(jp->sig) instead? */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004816 }
4817 if (jp->state == JOBDONE)
4818#endif
4819 freejob(jp);
4820 return st;
4821}
4822
4823/*
4824 * return 1 if there are stopped jobs, otherwise 0
4825 */
4826static int
4827stoppedjobs(void)
4828{
4829 struct job *jp;
4830 int retval;
4831
4832 retval = 0;
4833 if (job_warning)
4834 goto out;
4835 jp = curjob;
4836 if (jp && jp->state == JOBSTOPPED) {
4837 out2str("You have stopped jobs.\n");
4838 job_warning = 2;
4839 retval++;
4840 }
4841 out:
4842 return retval;
4843}
4844
4845
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004846/* ============ redir.c
4847 *
4848 * Code for dealing with input/output redirection.
4849 */
4850
4851#define EMPTY -2 /* marks an unused slot in redirtab */
Denis Vlasenko7d75a962007-11-22 08:16:57 +00004852#define CLOSED -3 /* marks a slot of previously-closed fd */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004853
4854/*
4855 * Open a file in noclobber mode.
4856 * The code was copied from bash.
4857 */
4858static int
4859noclobberopen(const char *fname)
4860{
4861 int r, fd;
4862 struct stat finfo, finfo2;
4863
4864 /*
4865 * If the file exists and is a regular file, return an error
4866 * immediately.
4867 */
4868 r = stat(fname, &finfo);
4869 if (r == 0 && S_ISREG(finfo.st_mode)) {
4870 errno = EEXIST;
4871 return -1;
4872 }
4873
4874 /*
4875 * If the file was not present (r != 0), make sure we open it
4876 * exclusively so that if it is created before we open it, our open
4877 * will fail. Make sure that we do not truncate an existing file.
4878 * Note that we don't turn on O_EXCL unless the stat failed -- if the
4879 * file was not a regular file, we leave O_EXCL off.
4880 */
4881 if (r != 0)
4882 return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
4883 fd = open(fname, O_WRONLY|O_CREAT, 0666);
4884
4885 /* If the open failed, return the file descriptor right away. */
4886 if (fd < 0)
4887 return fd;
4888
4889 /*
4890 * OK, the open succeeded, but the file may have been changed from a
4891 * non-regular file to a regular file between the stat and the open.
4892 * We are assuming that the O_EXCL open handles the case where FILENAME
4893 * did not exist and is symlinked to an existing file between the stat
4894 * and open.
4895 */
4896
4897 /*
4898 * If we can open it and fstat the file descriptor, and neither check
4899 * revealed that it was a regular file, and the file has not been
4900 * replaced, return the file descriptor.
4901 */
4902 if (fstat(fd, &finfo2) == 0 && !S_ISREG(finfo2.st_mode)
4903 && finfo.st_dev == finfo2.st_dev && finfo.st_ino == finfo2.st_ino)
4904 return fd;
4905
4906 /* The file has been replaced. badness. */
4907 close(fd);
4908 errno = EEXIST;
4909 return -1;
4910}
4911
4912/*
4913 * Handle here documents. Normally we fork off a process to write the
4914 * data to a pipe. If the document is short, we can stuff the data in
4915 * the pipe without forking.
4916 */
4917/* openhere needs this forward reference */
4918static void expandhere(union node *arg, int fd);
4919static int
4920openhere(union node *redir)
4921{
4922 int pip[2];
4923 size_t len = 0;
4924
4925 if (pipe(pip) < 0)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00004926 ash_msg_and_raise_error("pipe call failed");
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004927 if (redir->type == NHERE) {
4928 len = strlen(redir->nhere.doc->narg.text);
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00004929 if (len <= PIPE_BUF) {
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004930 full_write(pip[1], redir->nhere.doc->narg.text, len);
4931 goto out;
4932 }
4933 }
4934 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
Denis Vlasenko0b769642008-07-24 07:54:57 +00004935 /* child */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004936 close(pip[0]);
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004937 ignoresig(SIGINT); //signal(SIGINT, SIG_IGN);
4938 ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
4939 ignoresig(SIGHUP); //signal(SIGHUP, SIG_IGN);
4940 ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004941 signal(SIGPIPE, SIG_DFL);
4942 if (redir->type == NHERE)
4943 full_write(pip[1], redir->nhere.doc->narg.text, len);
Denis Vlasenko0b769642008-07-24 07:54:57 +00004944 else /* NXHERE */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004945 expandhere(redir->nhere.doc, pip[1]);
Bernhard Reutner-Fischer636a1f82008-05-19 09:29:47 +00004946 _exit(EXIT_SUCCESS);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004947 }
4948 out:
4949 close(pip[1]);
4950 return pip[0];
4951}
4952
4953static int
4954openredirect(union node *redir)
4955{
4956 char *fname;
4957 int f;
4958
4959 switch (redir->nfile.type) {
4960 case NFROM:
4961 fname = redir->nfile.expfname;
4962 f = open(fname, O_RDONLY);
4963 if (f < 0)
4964 goto eopen;
4965 break;
4966 case NFROMTO:
4967 fname = redir->nfile.expfname;
4968 f = open(fname, O_RDWR|O_CREAT|O_TRUNC, 0666);
4969 if (f < 0)
4970 goto ecreate;
4971 break;
4972 case NTO:
Denis Vlasenko559691a2008-10-05 18:39:31 +00004973#if ENABLE_ASH_BASH_COMPAT
4974 case NTO2:
4975#endif
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004976 /* Take care of noclobber mode. */
4977 if (Cflag) {
4978 fname = redir->nfile.expfname;
4979 f = noclobberopen(fname);
4980 if (f < 0)
4981 goto ecreate;
4982 break;
4983 }
4984 /* FALLTHROUGH */
4985 case NCLOBBER:
4986 fname = redir->nfile.expfname;
4987 f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
4988 if (f < 0)
4989 goto ecreate;
4990 break;
4991 case NAPPEND:
4992 fname = redir->nfile.expfname;
4993 f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
4994 if (f < 0)
4995 goto ecreate;
4996 break;
4997 default:
4998#if DEBUG
4999 abort();
5000#endif
5001 /* Fall through to eliminate warning. */
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005002/* Our single caller does this itself */
Denis Vlasenko0b769642008-07-24 07:54:57 +00005003// case NTOFD:
5004// case NFROMFD:
5005// f = -1;
5006// break;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005007 case NHERE:
5008 case NXHERE:
5009 f = openhere(redir);
5010 break;
5011 }
5012
5013 return f;
5014 ecreate:
Bernhard Reutner-Fischera53de7f2008-07-21 13:46:54 +00005015 ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005016 eopen:
Bernhard Reutner-Fischera53de7f2008-07-21 13:46:54 +00005017 ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005018}
5019
5020/*
5021 * Copy a file descriptor to be >= to. Returns -1
5022 * if the source file descriptor is closed, EMPTY if there are no unused
5023 * file descriptors left.
5024 */
Denis Vlasenko5a867312008-07-24 19:46:38 +00005025/* 0x800..00: bit to set in "to" to request dup2 instead of fcntl(F_DUPFD).
5026 * old code was doing close(to) prior to copyfd() to achieve the same */
Denis Vlasenko22f74142008-07-24 22:34:43 +00005027enum {
5028 COPYFD_EXACT = (int)~(INT_MAX),
5029 COPYFD_RESTORE = (int)((unsigned)COPYFD_EXACT >> 1),
5030};
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005031static int
5032copyfd(int from, int to)
5033{
5034 int newfd;
5035
Denis Vlasenko5a867312008-07-24 19:46:38 +00005036 if (to & COPYFD_EXACT) {
5037 to &= ~COPYFD_EXACT;
5038 /*if (from != to)*/
5039 newfd = dup2(from, to);
5040 } else {
5041 newfd = fcntl(from, F_DUPFD, to);
5042 }
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005043 if (newfd < 0) {
5044 if (errno == EMFILE)
5045 return EMPTY;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005046 /* Happens when source fd is not open: try "echo >&99" */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005047 ash_msg_and_raise_error("%d: %m", from);
5048 }
5049 return newfd;
5050}
5051
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005052/* Struct def and variable are moved down to the first usage site */
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005053struct two_fd_t {
5054 int orig, copy;
5055};
Denis Vlasenko0b769642008-07-24 07:54:57 +00005056struct redirtab {
5057 struct redirtab *next;
Denis Vlasenko0b769642008-07-24 07:54:57 +00005058 int nullredirs;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005059 int pair_count;
Denys Vlasenko606291b2009-09-23 23:15:43 +02005060 struct two_fd_t two_fd[];
Denis Vlasenko0b769642008-07-24 07:54:57 +00005061};
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005062#define redirlist (G_var.redirlist)
Denis Vlasenko0b769642008-07-24 07:54:57 +00005063
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005064static int need_to_remember(struct redirtab *rp, int fd)
5065{
5066 int i;
5067
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005068 if (!rp) /* remembering was not requested */
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005069 return 0;
5070
5071 for (i = 0; i < rp->pair_count; i++) {
5072 if (rp->two_fd[i].orig == fd) {
5073 /* already remembered */
5074 return 0;
5075 }
5076 }
5077 return 1;
5078}
5079
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005080/* "hidden" fd is a fd used to read scripts, or a copy of such */
5081static int is_hidden_fd(struct redirtab *rp, int fd)
5082{
5083 int i;
Denis Vlasenko34c73c42008-08-16 11:48:02 +00005084 struct parsefile *pf;
5085
5086 if (fd == -1)
5087 return 0;
5088 pf = g_parsefile;
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005089 while (pf) {
5090 if (fd == pf->fd) {
5091 return 1;
5092 }
5093 pf = pf->prev;
5094 }
5095 if (!rp)
5096 return 0;
5097 fd |= COPYFD_RESTORE;
5098 for (i = 0; i < rp->pair_count; i++) {
5099 if (rp->two_fd[i].copy == fd) {
5100 return 1;
5101 }
5102 }
5103 return 0;
5104}
5105
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005106/*
5107 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
5108 * old file descriptors are stashed away so that the redirection can be
5109 * undone by calling popredir. If the REDIR_BACKQ flag is set, then the
5110 * standard output, and the standard error if it becomes a duplicate of
5111 * stdout, is saved in memory.
5112 */
5113/* flags passed to redirect */
5114#define REDIR_PUSH 01 /* save previous values of file descriptors */
5115#define REDIR_SAVEFD2 03 /* set preverrout */
5116static void
5117redirect(union node *redir, int flags)
5118{
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005119 struct redirtab *sv;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005120 int sv_pos;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005121 int i;
5122 int fd;
5123 int newfd;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005124 int copied_fd2 = -1;
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005125
Denis Vlasenko01631112007-12-16 17:20:38 +00005126 g_nullredirs++;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005127 if (!redir) {
5128 return;
5129 }
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005130
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005131 sv = NULL;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005132 sv_pos = 0;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005133 INT_OFF;
5134 if (flags & REDIR_PUSH) {
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005135 union node *tmp = redir;
5136 do {
5137 sv_pos++;
Denis Vlasenko559691a2008-10-05 18:39:31 +00005138#if ENABLE_ASH_BASH_COMPAT
5139 if (redir->nfile.type == NTO2)
5140 sv_pos++;
5141#endif
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005142 tmp = tmp->nfile.next;
5143 } while (tmp);
5144 sv = ckmalloc(sizeof(*sv) + sv_pos * sizeof(sv->two_fd[0]));
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005145 sv->next = redirlist;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005146 sv->pair_count = sv_pos;
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005147 redirlist = sv;
Denis Vlasenko01631112007-12-16 17:20:38 +00005148 sv->nullredirs = g_nullredirs - 1;
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005149 g_nullredirs = 0;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005150 while (sv_pos > 0) {
5151 sv_pos--;
5152 sv->two_fd[sv_pos].orig = sv->two_fd[sv_pos].copy = EMPTY;
5153 }
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005154 }
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005155
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005156 do {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00005157 fd = redir->nfile.fd;
Denis Vlasenko0b769642008-07-24 07:54:57 +00005158 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005159 int right_fd = redir->ndup.dupfd;
5160 /* redirect from/to same file descriptor? */
5161 if (right_fd == fd)
5162 continue;
5163 /* echo >&10 and 10 is a fd opened to the sh script? */
5164 if (is_hidden_fd(sv, right_fd)) {
5165 errno = EBADF; /* as if it is closed */
5166 ash_msg_and_raise_error("%d: %m", right_fd);
5167 }
Denis Vlasenko0b769642008-07-24 07:54:57 +00005168 newfd = -1;
5169 } else {
5170 newfd = openredirect(redir); /* always >= 0 */
5171 if (fd == newfd) {
5172 /* Descriptor wasn't open before redirect.
5173 * Mark it for close in the future */
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005174 if (need_to_remember(sv, fd)) {
Denis Vlasenko5a867312008-07-24 19:46:38 +00005175 goto remember_to_close;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005176 }
Denis Vlasenko0b769642008-07-24 07:54:57 +00005177 continue;
5178 }
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005179 }
Denis Vlasenko559691a2008-10-05 18:39:31 +00005180#if ENABLE_ASH_BASH_COMPAT
5181 redirect_more:
5182#endif
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005183 if (need_to_remember(sv, fd)) {
Denis Vlasenko0b769642008-07-24 07:54:57 +00005184 /* Copy old descriptor */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005185 i = fcntl(fd, F_DUPFD, 10);
Denis Vlasenko5a867312008-07-24 19:46:38 +00005186/* You'd expect copy to be CLOEXECed. Currently these extra "saved" fds
5187 * are closed in popredir() in the child, preventing them from leaking
5188 * into child. (popredir() also cleans up the mess in case of failures)
5189 */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005190 if (i == -1) {
5191 i = errno;
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005192 if (i != EBADF) {
5193 /* Strange error (e.g. "too many files" EMFILE?) */
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005194 if (newfd >= 0)
5195 close(newfd);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005196 errno = i;
5197 ash_msg_and_raise_error("%d: %m", fd);
5198 /* NOTREACHED */
5199 }
Denis Vlasenko5a867312008-07-24 19:46:38 +00005200 /* EBADF: it is not open - good, remember to close it */
5201 remember_to_close:
5202 i = CLOSED;
Denis Vlasenko22f74142008-07-24 22:34:43 +00005203 } else { /* fd is open, save its copy */
5204 /* "exec fd>&-" should not close fds
5205 * which point to script file(s).
5206 * Force them to be restored afterwards */
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005207 if (is_hidden_fd(sv, fd))
5208 i |= COPYFD_RESTORE;
Denis Vlasenko22f74142008-07-24 22:34:43 +00005209 }
Denis Vlasenko5a867312008-07-24 19:46:38 +00005210 if (fd == 2)
5211 copied_fd2 = i;
5212 sv->two_fd[sv_pos].orig = fd;
5213 sv->two_fd[sv_pos].copy = i;
5214 sv_pos++;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005215 }
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005216 if (newfd < 0) {
5217 /* NTOFD/NFROMFD: copy redir->ndup.dupfd to fd */
Denis Vlasenko22f74142008-07-24 22:34:43 +00005218 if (redir->ndup.dupfd < 0) { /* "fd>&-" */
Denis Vlasenkob9e70dd2009-03-20 01:24:08 +00005219 /* Don't want to trigger debugging */
5220 if (fd != -1)
5221 close(fd);
Denis Vlasenko5a867312008-07-24 19:46:38 +00005222 } else {
5223 copyfd(redir->ndup.dupfd, fd | COPYFD_EXACT);
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005224 }
Denis Vlasenko5a867312008-07-24 19:46:38 +00005225 } else if (fd != newfd) { /* move newfd to fd */
5226 copyfd(newfd, fd | COPYFD_EXACT);
Denis Vlasenko559691a2008-10-05 18:39:31 +00005227#if ENABLE_ASH_BASH_COMPAT
5228 if (!(redir->nfile.type == NTO2 && fd == 2))
5229#endif
5230 close(newfd);
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005231 }
Denis Vlasenko559691a2008-10-05 18:39:31 +00005232#if ENABLE_ASH_BASH_COMPAT
5233 if (redir->nfile.type == NTO2 && fd == 1) {
5234 /* We already redirected it to fd 1, now copy it to 2 */
5235 newfd = 1;
5236 fd = 2;
5237 goto redirect_more;
5238 }
5239#endif
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00005240 } while ((redir = redir->nfile.next) != NULL);
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005241
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005242 INT_ON;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005243 if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
5244 preverrout_fd = copied_fd2;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005245}
5246
5247/*
5248 * Undo the effects of the last redirection.
5249 */
5250static void
Denis Vlasenko34c73c42008-08-16 11:48:02 +00005251popredir(int drop, int restore)
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005252{
5253 struct redirtab *rp;
5254 int i;
5255
Denis Vlasenko01631112007-12-16 17:20:38 +00005256 if (--g_nullredirs >= 0)
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005257 return;
5258 INT_OFF;
5259 rp = redirlist;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005260 for (i = 0; i < rp->pair_count; i++) {
5261 int fd = rp->two_fd[i].orig;
Denis Vlasenko22f74142008-07-24 22:34:43 +00005262 int copy = rp->two_fd[i].copy;
5263 if (copy == CLOSED) {
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005264 if (!drop)
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005265 close(fd);
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005266 continue;
5267 }
Denis Vlasenko22f74142008-07-24 22:34:43 +00005268 if (copy != EMPTY) {
Denis Vlasenko34c73c42008-08-16 11:48:02 +00005269 if (!drop || (restore && (copy & COPYFD_RESTORE))) {
Denis Vlasenko22f74142008-07-24 22:34:43 +00005270 copy &= ~COPYFD_RESTORE;
Denis Vlasenko5a867312008-07-24 19:46:38 +00005271 /*close(fd);*/
Denis Vlasenko22f74142008-07-24 22:34:43 +00005272 copyfd(copy, fd | COPYFD_EXACT);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005273 }
Denis Vlasenkob9e70dd2009-03-20 01:24:08 +00005274 close(copy & ~COPYFD_RESTORE);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005275 }
5276 }
5277 redirlist = rp->next;
Denis Vlasenko01631112007-12-16 17:20:38 +00005278 g_nullredirs = rp->nullredirs;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005279 free(rp);
5280 INT_ON;
5281}
5282
5283/*
5284 * Undo all redirections. Called on error or interrupt.
5285 */
5286
5287/*
5288 * Discard all saved file descriptors.
5289 */
5290static void
5291clearredir(int drop)
5292{
5293 for (;;) {
Denis Vlasenko01631112007-12-16 17:20:38 +00005294 g_nullredirs = 0;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005295 if (!redirlist)
5296 break;
Denis Vlasenko34c73c42008-08-16 11:48:02 +00005297 popredir(drop, /*restore:*/ 0);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005298 }
5299}
5300
5301static int
5302redirectsafe(union node *redir, int flags)
5303{
5304 int err;
5305 volatile int saveint;
5306 struct jmploc *volatile savehandler = exception_handler;
5307 struct jmploc jmploc;
5308
5309 SAVE_INT(saveint);
Denis Vlasenko5a867312008-07-24 19:46:38 +00005310 /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
5311 err = setjmp(jmploc.loc); // huh?? was = setjmp(jmploc.loc) * 2;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005312 if (!err) {
5313 exception_handler = &jmploc;
5314 redirect(redir, flags);
5315 }
5316 exception_handler = savehandler;
Denis Vlasenko7f88e342009-03-19 03:36:18 +00005317 if (err && exception_type != EXERROR)
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005318 longjmp(exception_handler->loc, 1);
5319 RESTORE_INT(saveint);
5320 return err;
5321}
5322
5323
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005324/* ============ Routines to expand arguments to commands
5325 *
5326 * We have to deal with backquotes, shell variables, and file metacharacters.
5327 */
5328
Mike Frysinger98c52642009-04-02 10:02:37 +00005329#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00005330static arith_t
5331ash_arith(const char *s)
5332{
5333 arith_eval_hooks_t math_hooks;
5334 arith_t result;
5335 int errcode = 0;
5336
5337 math_hooks.lookupvar = lookupvar;
5338 math_hooks.setvar = setvar;
5339 math_hooks.endofname = endofname;
5340
5341 INT_OFF;
5342 result = arith(s, &errcode, &math_hooks);
5343 if (errcode < 0) {
5344 if (errcode == -3)
5345 ash_msg_and_raise_error("exponent less than 0");
5346 if (errcode == -2)
5347 ash_msg_and_raise_error("divide by zero");
5348 if (errcode == -5)
5349 ash_msg_and_raise_error("expression recursion loop detected");
5350 raise_error_syntax(s);
5351 }
5352 INT_ON;
5353
5354 return result;
5355}
Denis Vlasenko448d30e2008-06-27 00:24:11 +00005356#endif
5357
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005358/*
5359 * expandarg flags
5360 */
5361#define EXP_FULL 0x1 /* perform word splitting & file globbing */
5362#define EXP_TILDE 0x2 /* do normal tilde expansion */
5363#define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
5364#define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
5365#define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
5366#define EXP_RECORD 0x20 /* need to record arguments for ifs breakup */
5367#define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
5368#define EXP_WORD 0x80 /* expand word in parameter expansion */
5369#define EXP_QWORD 0x100 /* expand word in quoted parameter expansion */
5370/*
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005371 * rmescape() flags
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005372 */
5373#define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
5374#define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
5375#define RMESCAPE_QUOTED 0x4 /* Remove CTLESC unless in quotes */
5376#define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
5377#define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
5378
5379/*
5380 * Structure specifying which parts of the string should be searched
5381 * for IFS characters.
5382 */
5383struct ifsregion {
5384 struct ifsregion *next; /* next region in list */
5385 int begoff; /* offset of start of region */
5386 int endoff; /* offset of end of region */
5387 int nulonly; /* search for nul bytes only */
5388};
5389
5390struct arglist {
5391 struct strlist *list;
5392 struct strlist **lastp;
5393};
5394
5395/* output of current string */
5396static char *expdest;
5397/* list of back quote expressions */
5398static struct nodelist *argbackq;
5399/* first struct in list of ifs regions */
5400static struct ifsregion ifsfirst;
5401/* last struct in list */
5402static struct ifsregion *ifslastp;
5403/* holds expanded arg list */
5404static struct arglist exparg;
5405
5406/*
5407 * Our own itoa().
5408 */
5409static int
5410cvtnum(arith_t num)
5411{
5412 int len;
5413
5414 expdest = makestrspace(32, expdest);
Mike Frysinger98c52642009-04-02 10:02:37 +00005415 len = fmtstr(expdest, 32, arith_t_fmt, num);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005416 STADJUST(len, expdest);
5417 return len;
5418}
5419
5420static size_t
5421esclen(const char *start, const char *p)
5422{
5423 size_t esc = 0;
5424
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005425 while (p > start && (unsigned char)*--p == CTLESC) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005426 esc++;
5427 }
5428 return esc;
5429}
5430
5431/*
5432 * Remove any CTLESC characters from a string.
5433 */
5434static char *
Denys Vlasenkob6c84342009-08-29 20:23:20 +02005435rmescapes(char *str, int flag)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005436{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00005437 static const char qchars[] ALIGN1 = { CTLESC, CTLQUOTEMARK, '\0' };
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00005438
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005439 char *p, *q, *r;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005440 unsigned inquotes;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005441 unsigned protect_against_glob;
5442 unsigned globbing;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005443
5444 p = strpbrk(str, qchars);
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005445 if (!p)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005446 return str;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005447
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005448 q = p;
5449 r = str;
5450 if (flag & RMESCAPE_ALLOC) {
5451 size_t len = p - str;
5452 size_t fulllen = len + strlen(p) + 1;
5453
5454 if (flag & RMESCAPE_GROW) {
5455 r = makestrspace(fulllen, expdest);
5456 } else if (flag & RMESCAPE_HEAP) {
5457 r = ckmalloc(fulllen);
5458 } else {
5459 r = stalloc(fulllen);
5460 }
5461 q = r;
5462 if (len > 0) {
Denis Vlasenko29eb3592008-05-18 14:06:08 +00005463 q = (char *)memcpy(q, str, len) + len;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005464 }
5465 }
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005466
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005467 inquotes = (flag & RMESCAPE_QUOTED) ^ RMESCAPE_QUOTED;
5468 globbing = flag & RMESCAPE_GLOB;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005469 protect_against_glob = globbing;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005470 while (*p) {
5471 if (*p == CTLQUOTEMARK) {
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005472// TODO: if no RMESCAPE_QUOTED in flags, inquotes never becomes 0
5473// (alternates between RMESCAPE_QUOTED and ~RMESCAPE_QUOTED). Is it ok?
5474// Note: both inquotes and protect_against_glob only affect whether
5475// CTLESC,<ch> gets converted to <ch> or to \<ch>
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005476 inquotes = ~inquotes;
5477 p++;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005478 protect_against_glob = globbing;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005479 continue;
5480 }
5481 if (*p == '\\') {
5482 /* naked back slash */
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005483 protect_against_glob = 0;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005484 goto copy;
5485 }
5486 if (*p == CTLESC) {
5487 p++;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005488 if (protect_against_glob && inquotes && *p != '/') {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005489 *q++ = '\\';
5490 }
5491 }
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005492 protect_against_glob = globbing;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005493 copy:
5494 *q++ = *p++;
5495 }
5496 *q = '\0';
5497 if (flag & RMESCAPE_GROW) {
5498 expdest = r;
5499 STADJUST(q - r + 1, expdest);
5500 }
5501 return r;
5502}
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005503#define pmatch(a, b) !fnmatch((a), (b), 0)
5504
5505/*
5506 * Prepare a pattern for a expmeta (internal glob(3)) call.
5507 *
5508 * Returns an stalloced string.
5509 */
5510static char *
5511preglob(const char *pattern, int quoted, int flag)
5512{
5513 flag |= RMESCAPE_GLOB;
5514 if (quoted) {
5515 flag |= RMESCAPE_QUOTED;
5516 }
Denys Vlasenkob6c84342009-08-29 20:23:20 +02005517 return rmescapes((char *)pattern, flag);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005518}
5519
5520/*
5521 * Put a string on the stack.
5522 */
5523static void
5524memtodest(const char *p, size_t len, int syntax, int quotes)
5525{
5526 char *q = expdest;
5527
Denys Vlasenkob6c84342009-08-29 20:23:20 +02005528 q = makestrspace(quotes ? len * 2 : len, q);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005529
5530 while (len--) {
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00005531 int c = signed_char2int(*p++);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005532 if (!c)
5533 continue;
Denys Vlasenkob6c84342009-08-29 20:23:20 +02005534 if (quotes) {
5535 int n = SIT(c, syntax);
5536 if (n == CCTL || n == CBACK)
5537 USTPUTC(CTLESC, q);
5538 }
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005539 USTPUTC(c, q);
5540 }
5541
5542 expdest = q;
5543}
5544
5545static void
5546strtodest(const char *p, int syntax, int quotes)
5547{
5548 memtodest(p, strlen(p), syntax, quotes);
5549}
5550
5551/*
5552 * Record the fact that we have to scan this region of the
5553 * string for IFS characters.
5554 */
5555static void
5556recordregion(int start, int end, int nulonly)
5557{
5558 struct ifsregion *ifsp;
5559
5560 if (ifslastp == NULL) {
5561 ifsp = &ifsfirst;
5562 } else {
5563 INT_OFF;
Denis Vlasenko597906c2008-02-20 16:38:54 +00005564 ifsp = ckzalloc(sizeof(*ifsp));
5565 /*ifsp->next = NULL; - ckzalloc did it */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005566 ifslastp->next = ifsp;
5567 INT_ON;
5568 }
5569 ifslastp = ifsp;
5570 ifslastp->begoff = start;
5571 ifslastp->endoff = end;
5572 ifslastp->nulonly = nulonly;
5573}
5574
5575static void
5576removerecordregions(int endoff)
5577{
5578 if (ifslastp == NULL)
5579 return;
5580
5581 if (ifsfirst.endoff > endoff) {
5582 while (ifsfirst.next != NULL) {
5583 struct ifsregion *ifsp;
5584 INT_OFF;
5585 ifsp = ifsfirst.next->next;
5586 free(ifsfirst.next);
5587 ifsfirst.next = ifsp;
5588 INT_ON;
5589 }
5590 if (ifsfirst.begoff > endoff)
5591 ifslastp = NULL;
5592 else {
5593 ifslastp = &ifsfirst;
5594 ifsfirst.endoff = endoff;
5595 }
5596 return;
5597 }
5598
5599 ifslastp = &ifsfirst;
5600 while (ifslastp->next && ifslastp->next->begoff < endoff)
5601 ifslastp=ifslastp->next;
5602 while (ifslastp->next != NULL) {
5603 struct ifsregion *ifsp;
5604 INT_OFF;
5605 ifsp = ifslastp->next->next;
5606 free(ifslastp->next);
5607 ifslastp->next = ifsp;
5608 INT_ON;
5609 }
5610 if (ifslastp->endoff > endoff)
5611 ifslastp->endoff = endoff;
5612}
5613
5614static char *
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005615exptilde(char *startp, char *p, int flags)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005616{
5617 char c;
5618 char *name;
5619 struct passwd *pw;
5620 const char *home;
Denys Vlasenko1166d7b2009-09-16 16:20:31 +02005621 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005622 int startloc;
5623
5624 name = p + 1;
5625
5626 while ((c = *++p) != '\0') {
5627 switch (c) {
5628 case CTLESC:
5629 return startp;
5630 case CTLQUOTEMARK:
5631 return startp;
5632 case ':':
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005633 if (flags & EXP_VARTILDE)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005634 goto done;
5635 break;
5636 case '/':
5637 case CTLENDVAR:
5638 goto done;
5639 }
5640 }
5641 done:
5642 *p = '\0';
5643 if (*name == '\0') {
5644 home = lookupvar(homestr);
5645 } else {
5646 pw = getpwnam(name);
5647 if (pw == NULL)
5648 goto lose;
5649 home = pw->pw_dir;
5650 }
5651 if (!home || !*home)
5652 goto lose;
5653 *p = c;
5654 startloc = expdest - (char *)stackblock();
5655 strtodest(home, SQSYNTAX, quotes);
5656 recordregion(startloc, expdest - (char *)stackblock(), 0);
5657 return p;
5658 lose:
5659 *p = c;
5660 return startp;
5661}
5662
5663/*
5664 * Execute a command inside back quotes. If it's a builtin command, we
5665 * want to save its output in a block obtained from malloc. Otherwise
5666 * we fork off a subprocess and get the output of the command via a pipe.
5667 * Should be called with interrupts off.
5668 */
5669struct backcmd { /* result of evalbackcmd */
5670 int fd; /* file descriptor to read from */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005671 int nleft; /* number of chars in buffer */
Denis Vlasenkob07a4962008-06-22 13:16:23 +00005672 char *buf; /* buffer */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005673 struct job *jp; /* job structure for command */
5674};
5675
5676/* These forward decls are needed to use "eval" code for backticks handling: */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00005677static uint8_t back_exitstatus; /* exit status of backquoted command */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005678#define EV_EXIT 01 /* exit after evaluating tree */
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02005679static void evaltree(union node *, int);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005680
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02005681static void FAST_FUNC
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005682evalbackcmd(union node *n, struct backcmd *result)
5683{
5684 int saveherefd;
5685
5686 result->fd = -1;
5687 result->buf = NULL;
5688 result->nleft = 0;
5689 result->jp = NULL;
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00005690 if (n == NULL)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005691 goto out;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005692
5693 saveherefd = herefd;
5694 herefd = -1;
5695
5696 {
5697 int pip[2];
5698 struct job *jp;
5699
5700 if (pipe(pip) < 0)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00005701 ash_msg_and_raise_error("pipe call failed");
Denis Vlasenko68404f12008-03-17 09:00:54 +00005702 jp = makejob(/*n,*/ 1);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005703 if (forkshell(jp, n, FORK_NOJOB) == 0) {
5704 FORCE_INT_ON;
5705 close(pip[0]);
5706 if (pip[1] != 1) {
Denis Vlasenko5a867312008-07-24 19:46:38 +00005707 /*close(1);*/
5708 copyfd(pip[1], 1 | COPYFD_EXACT);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005709 close(pip[1]);
5710 }
5711 eflag = 0;
5712 evaltree(n, EV_EXIT); /* actually evaltreenr... */
5713 /* NOTREACHED */
5714 }
5715 close(pip[1]);
5716 result->fd = pip[0];
5717 result->jp = jp;
5718 }
5719 herefd = saveherefd;
5720 out:
5721 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
5722 result->fd, result->buf, result->nleft, result->jp));
5723}
5724
5725/*
5726 * Expand stuff in backwards quotes.
5727 */
5728static void
5729expbackq(union node *cmd, int quoted, int quotes)
5730{
5731 struct backcmd in;
5732 int i;
5733 char buf[128];
5734 char *p;
5735 char *dest;
5736 int startloc;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00005737 int syntax = quoted ? DQSYNTAX : BASESYNTAX;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005738 struct stackmark smark;
5739
5740 INT_OFF;
5741 setstackmark(&smark);
5742 dest = expdest;
5743 startloc = dest - (char *)stackblock();
5744 grabstackstr(dest);
5745 evalbackcmd(cmd, &in);
5746 popstackmark(&smark);
5747
5748 p = in.buf;
5749 i = in.nleft;
5750 if (i == 0)
5751 goto read;
5752 for (;;) {
5753 memtodest(p, i, syntax, quotes);
5754 read:
5755 if (in.fd < 0)
5756 break;
Denis Vlasenkoe376d452008-02-20 22:23:24 +00005757 i = nonblock_safe_read(in.fd, buf, sizeof(buf));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005758 TRACE(("expbackq: read returns %d\n", i));
5759 if (i <= 0)
5760 break;
5761 p = buf;
5762 }
5763
Denis Vlasenko60818682007-09-28 22:07:23 +00005764 free(in.buf);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005765 if (in.fd >= 0) {
5766 close(in.fd);
5767 back_exitstatus = waitforjob(in.jp);
5768 }
5769 INT_ON;
5770
5771 /* Eat all trailing newlines */
5772 dest = expdest;
5773 for (; dest > (char *)stackblock() && dest[-1] == '\n';)
5774 STUNPUTC(dest);
5775 expdest = dest;
5776
5777 if (quoted == 0)
5778 recordregion(startloc, dest - (char *)stackblock(), 0);
5779 TRACE(("evalbackq: size=%d: \"%.*s\"\n",
5780 (dest - (char *)stackblock()) - startloc,
5781 (dest - (char *)stackblock()) - startloc,
5782 stackblock() + startloc));
5783}
5784
Mike Frysinger98c52642009-04-02 10:02:37 +00005785#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005786/*
5787 * Expand arithmetic expression. Backup to start of expression,
5788 * evaluate, place result in (backed up) result, adjust string position.
5789 */
5790static void
5791expari(int quotes)
5792{
5793 char *p, *start;
5794 int begoff;
5795 int flag;
5796 int len;
5797
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00005798 /* ifsfree(); */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005799
5800 /*
5801 * This routine is slightly over-complicated for
5802 * efficiency. Next we scan backwards looking for the
5803 * start of arithmetic.
5804 */
5805 start = stackblock();
5806 p = expdest - 1;
5807 *p = '\0';
5808 p--;
5809 do {
5810 int esc;
5811
5812 while (*p != CTLARI) {
5813 p--;
5814#if DEBUG
5815 if (p < start) {
5816 ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
5817 }
5818#endif
5819 }
5820
5821 esc = esclen(start, p);
5822 if (!(esc % 2)) {
5823 break;
5824 }
5825
5826 p -= esc + 1;
5827 } while (1);
5828
5829 begoff = p - start;
5830
5831 removerecordregions(begoff);
5832
5833 flag = p[1];
5834
5835 expdest = p;
5836
5837 if (quotes)
Denys Vlasenkob6c84342009-08-29 20:23:20 +02005838 rmescapes(p + 2, 0);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005839
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00005840 len = cvtnum(ash_arith(p + 2));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005841
5842 if (flag != '"')
5843 recordregion(begoff, begoff + len, 0);
5844}
5845#endif
5846
5847/* argstr needs it */
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005848static char *evalvar(char *p, int flags, struct strlist *var_str_list);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005849
5850/*
5851 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
5852 * characters to allow for further processing. Otherwise treat
5853 * $@ like $* since no splitting will be performed.
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00005854 *
5855 * var_str_list (can be NULL) is a list of "VAR=val" strings which take precedence
5856 * over shell varables. Needed for "A=a B=$A; echo $B" case - we use it
5857 * for correct expansion of "B=$A" word.
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005858 */
5859static void
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005860argstr(char *p, int flags, struct strlist *var_str_list)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005861{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00005862 static const char spclchars[] ALIGN1 = {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005863 '=',
5864 ':',
5865 CTLQUOTEMARK,
5866 CTLENDVAR,
5867 CTLESC,
5868 CTLVAR,
5869 CTLBACKQ,
5870 CTLBACKQ | CTLQUOTE,
Mike Frysinger98c52642009-04-02 10:02:37 +00005871#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005872 CTLENDARI,
5873#endif
5874 0
5875 };
5876 const char *reject = spclchars;
5877 int c;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005878 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR); /* do CTLESC */
5879 int breakall = flags & EXP_WORD;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005880 int inquotes;
5881 size_t length;
5882 int startloc;
5883
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005884 if (!(flags & EXP_VARTILDE)) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005885 reject += 2;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005886 } else if (flags & EXP_VARTILDE2) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005887 reject++;
5888 }
5889 inquotes = 0;
5890 length = 0;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005891 if (flags & EXP_TILDE) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005892 char *q;
5893
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005894 flags &= ~EXP_TILDE;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005895 tilde:
5896 q = p;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005897 if (*q == CTLESC && (flags & EXP_QWORD))
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005898 q++;
5899 if (*q == '~')
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005900 p = exptilde(p, q, flags);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005901 }
5902 start:
5903 startloc = expdest - (char *)stackblock();
5904 for (;;) {
5905 length += strcspn(p + length, reject);
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005906 c = (unsigned char) p[length];
5907 if (c) {
5908 if (!(c & 0x80)
Mike Frysinger98c52642009-04-02 10:02:37 +00005909#if ENABLE_SH_MATH_SUPPORT
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005910 || c == CTLENDARI
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005911#endif
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005912 ) {
5913 /* c == '=' || c == ':' || c == CTLENDARI */
5914 length++;
5915 }
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005916 }
5917 if (length > 0) {
5918 int newloc;
5919 expdest = stack_nputstr(p, length, expdest);
5920 newloc = expdest - (char *)stackblock();
5921 if (breakall && !inquotes && newloc > startloc) {
5922 recordregion(startloc, newloc, 0);
5923 }
5924 startloc = newloc;
5925 }
5926 p += length + 1;
5927 length = 0;
5928
5929 switch (c) {
5930 case '\0':
5931 goto breakloop;
5932 case '=':
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005933 if (flags & EXP_VARTILDE2) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005934 p--;
5935 continue;
5936 }
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005937 flags |= EXP_VARTILDE2;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005938 reject++;
5939 /* fall through */
5940 case ':':
5941 /*
5942 * sort of a hack - expand tildes in variable
5943 * assignments (after the first '=' and after ':'s).
5944 */
5945 if (*--p == '~') {
5946 goto tilde;
5947 }
5948 continue;
5949 }
5950
5951 switch (c) {
5952 case CTLENDVAR: /* ??? */
5953 goto breakloop;
5954 case CTLQUOTEMARK:
5955 /* "$@" syntax adherence hack */
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005956 if (!inquotes
5957 && memcmp(p, dolatstr, 4) == 0
5958 && ( p[4] == CTLQUOTEMARK
5959 || (p[4] == CTLENDVAR && p[5] == CTLQUOTEMARK)
5960 )
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005961 ) {
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005962 p = evalvar(p + 1, flags, /* var_str_list: */ NULL) + 1;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005963 goto start;
5964 }
5965 inquotes = !inquotes;
5966 addquote:
5967 if (quotes) {
5968 p--;
5969 length++;
5970 startloc++;
5971 }
5972 break;
5973 case CTLESC:
5974 startloc++;
5975 length++;
5976 goto addquote;
5977 case CTLVAR:
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005978 p = evalvar(p, flags, var_str_list);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005979 goto start;
5980 case CTLBACKQ:
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005981 c = '\0';
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005982 case CTLBACKQ|CTLQUOTE:
5983 expbackq(argbackq->n, c, quotes);
5984 argbackq = argbackq->next;
5985 goto start;
Mike Frysinger98c52642009-04-02 10:02:37 +00005986#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005987 case CTLENDARI:
5988 p--;
5989 expari(quotes);
5990 goto start;
5991#endif
5992 }
5993 }
5994 breakloop:
5995 ;
5996}
5997
5998static char *
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00005999scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM, char *str, int quotes,
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006000 int zero)
6001{
Denis Vlasenkoc7131c32008-04-14 01:59:53 +00006002// This commented out code was added by James Simmons <jsimmons@infradead.org>
6003// as part of a larger change when he added support for ${var/a/b}.
6004// However, it broke # and % operators:
6005//
6006//var=ababcdcd
6007// ok bad
6008//echo ${var#ab} abcdcd abcdcd
6009//echo ${var##ab} abcdcd abcdcd
6010//echo ${var#a*b} abcdcd ababcdcd (!)
6011//echo ${var##a*b} cdcd cdcd
6012//echo ${var#?} babcdcd ababcdcd (!)
6013//echo ${var##?} babcdcd babcdcd
6014//echo ${var#*} ababcdcd babcdcd (!)
6015//echo ${var##*}
6016//echo ${var%cd} ababcd ababcd
6017//echo ${var%%cd} ababcd abab (!)
6018//echo ${var%c*d} ababcd ababcd
6019//echo ${var%%c*d} abab ababcdcd (!)
6020//echo ${var%?} ababcdc ababcdc
6021//echo ${var%%?} ababcdc ababcdcd (!)
6022//echo ${var%*} ababcdcd ababcdcd
6023//echo ${var%%*}
6024//
6025// Commenting it back out helped. Remove it completely if it really
6026// is not needed.
6027
6028 char *loc, *loc2; //, *full;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006029 char c;
6030
6031 loc = startp;
6032 loc2 = rmesc;
6033 do {
Denis Vlasenkoc7131c32008-04-14 01:59:53 +00006034 int match; // = strlen(str);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006035 const char *s = loc2;
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006036
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006037 c = *loc2;
6038 if (zero) {
6039 *loc2 = '\0';
6040 s = rmesc;
6041 }
Denis Vlasenkoc7131c32008-04-14 01:59:53 +00006042 match = pmatch(str, s); // this line was deleted
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006043
Denis Vlasenkoc7131c32008-04-14 01:59:53 +00006044// // chop off end if its '*'
6045// full = strrchr(str, '*');
6046// if (full && full != str)
6047// match--;
6048//
6049// // If str starts with '*' replace with s.
6050// if ((*str == '*') && strlen(s) >= match) {
6051// full = xstrdup(s);
6052// strncpy(full+strlen(s)-match+1, str+1, match-1);
6053// } else
6054// full = xstrndup(str, match);
6055// match = strncmp(s, full, strlen(full));
6056// free(full);
6057//
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006058 *loc2 = c;
Denis Vlasenkoc7131c32008-04-14 01:59:53 +00006059 if (match) // if (!match)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006060 return loc;
6061 if (quotes && *loc == CTLESC)
6062 loc++;
6063 loc++;
6064 loc2++;
6065 } while (c);
6066 return 0;
6067}
6068
6069static char *
6070scanright(char *startp, char *rmesc, char *rmescend, char *str, int quotes,
6071 int zero)
6072{
6073 int esc = 0;
6074 char *loc;
6075 char *loc2;
6076
6077 for (loc = str - 1, loc2 = rmescend; loc >= startp; loc2--) {
6078 int match;
6079 char c = *loc2;
6080 const char *s = loc2;
6081 if (zero) {
6082 *loc2 = '\0';
6083 s = rmesc;
6084 }
6085 match = pmatch(str, s);
6086 *loc2 = c;
6087 if (match)
6088 return loc;
6089 loc--;
6090 if (quotes) {
6091 if (--esc < 0) {
6092 esc = esclen(startp, loc);
6093 }
6094 if (esc % 2) {
6095 esc--;
6096 loc--;
6097 }
6098 }
6099 }
6100 return 0;
6101}
6102
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00006103static void varunset(const char *, const char *, const char *, int) NORETURN;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006104static void
6105varunset(const char *end, const char *var, const char *umsg, int varflags)
6106{
6107 const char *msg;
6108 const char *tail;
6109
6110 tail = nullstr;
6111 msg = "parameter not set";
6112 if (umsg) {
6113 if (*end == CTLENDVAR) {
6114 if (varflags & VSNUL)
6115 tail = " or null";
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00006116 } else {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006117 msg = umsg;
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00006118 }
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006119 }
6120 ash_msg_and_raise_error("%.*s: %s%s", end - var - 1, var, msg, tail);
6121}
6122
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006123#if ENABLE_ASH_BASH_COMPAT
6124static char *
6125parse_sub_pattern(char *arg, int inquotes)
6126{
6127 char *idx, *repl = NULL;
6128 unsigned char c;
6129
Denis Vlasenko2659c632008-06-14 06:04:59 +00006130 idx = arg;
6131 while (1) {
6132 c = *arg;
6133 if (!c)
6134 break;
6135 if (c == '/') {
6136 /* Only the first '/' seen is our separator */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006137 if (!repl) {
Denis Vlasenko2659c632008-06-14 06:04:59 +00006138 repl = idx + 1;
6139 c = '\0';
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006140 }
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006141 }
Denis Vlasenko2659c632008-06-14 06:04:59 +00006142 *idx++ = c;
6143 if (!inquotes && c == '\\' && arg[1] == '\\')
6144 arg++; /* skip both \\, not just first one */
6145 arg++;
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006146 }
Denis Vlasenko29038c02008-06-14 06:14:02 +00006147 *idx = c; /* NUL */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006148
6149 return repl;
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006150}
6151#endif /* ENABLE_ASH_BASH_COMPAT */
6152
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006153static const char *
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006154subevalvar(char *p, char *str, int strloc, int subtype,
6155 int startloc, int varflags, int quotes, struct strlist *var_str_list)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006156{
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006157 struct nodelist *saveargbackq = argbackq;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006158 char *startp;
6159 char *loc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006160 char *rmesc, *rmescend;
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00006161 IF_ASH_BASH_COMPAT(char *repl = NULL;)
6162 IF_ASH_BASH_COMPAT(char null = '\0';)
6163 IF_ASH_BASH_COMPAT(int pos, len, orig_len;)
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006164 int saveherefd = herefd;
6165 int amount, workloc, resetloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006166 int zero;
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006167 char *(*scan)(char*, char*, char*, char*, int, int);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006168
6169 herefd = -1;
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006170 argstr(p, (subtype != VSASSIGN && subtype != VSQUESTION) ? EXP_CASE : 0,
6171 var_str_list);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006172 STPUTC('\0', expdest);
6173 herefd = saveherefd;
6174 argbackq = saveargbackq;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00006175 startp = (char *)stackblock() + startloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006176
6177 switch (subtype) {
6178 case VSASSIGN:
6179 setvar(str, startp, 0);
6180 amount = startp - expdest;
6181 STADJUST(amount, expdest);
6182 return startp;
6183
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006184#if ENABLE_ASH_BASH_COMPAT
6185 case VSSUBSTR:
6186 loc = str = stackblock() + strloc;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006187 /* Read POS in ${var:POS:LEN} */
6188 pos = atoi(loc); /* number(loc) errors out on "1:4" */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006189 len = str - startp - 1;
6190
6191 /* *loc != '\0', guaranteed by parser */
6192 if (quotes) {
6193 char *ptr;
6194
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006195 /* Adjust the length by the number of escapes */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006196 for (ptr = startp; ptr < (str - 1); ptr++) {
Denis Vlasenkod6855d12008-09-27 14:03:25 +00006197 if (*ptr == CTLESC) {
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006198 len--;
6199 ptr++;
6200 }
6201 }
6202 }
6203 orig_len = len;
6204
6205 if (*loc++ == ':') {
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006206 /* ${var::LEN} */
6207 len = number(loc);
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006208 } else {
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006209 /* Skip POS in ${var:POS:LEN} */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006210 len = orig_len;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006211 while (*loc && *loc != ':') {
6212 /* TODO?
6213 * bash complains on: var=qwe; echo ${var:1a:123}
6214 if (!isdigit(*loc))
6215 ash_msg_and_raise_error(msg_illnum, str);
6216 */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006217 loc++;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006218 }
6219 if (*loc++ == ':') {
6220 len = number(loc);
6221 }
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006222 }
6223 if (pos >= orig_len) {
6224 pos = 0;
6225 len = 0;
6226 }
6227 if (len > (orig_len - pos))
6228 len = orig_len - pos;
6229
6230 for (str = startp; pos; str++, pos--) {
6231 if (quotes && *str == CTLESC)
6232 str++;
6233 }
6234 for (loc = startp; len; len--) {
6235 if (quotes && *str == CTLESC)
6236 *loc++ = *str++;
6237 *loc++ = *str++;
6238 }
6239 *loc = '\0';
6240 amount = loc - expdest;
6241 STADJUST(amount, expdest);
6242 return loc;
6243#endif
6244
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006245 case VSQUESTION:
6246 varunset(p, str, startp, varflags);
6247 /* NOTREACHED */
6248 }
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006249 resetloc = expdest - (char *)stackblock();
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006250
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006251 /* We'll comeback here if we grow the stack while handling
6252 * a VSREPLACE or VSREPLACEALL, since our pointers into the
6253 * stack will need rebasing, and we'll need to remove our work
6254 * areas each time
6255 */
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00006256 IF_ASH_BASH_COMPAT(restart:)
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006257
6258 amount = expdest - ((char *)stackblock() + resetloc);
6259 STADJUST(-amount, expdest);
Denis Vlasenko29eb3592008-05-18 14:06:08 +00006260 startp = (char *)stackblock() + startloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006261
6262 rmesc = startp;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00006263 rmescend = (char *)stackblock() + strloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006264 if (quotes) {
Denys Vlasenkob6c84342009-08-29 20:23:20 +02006265 rmesc = rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006266 if (rmesc != startp) {
6267 rmescend = expdest;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00006268 startp = (char *)stackblock() + startloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006269 }
6270 }
6271 rmescend--;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00006272 str = (char *)stackblock() + strloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006273 preglob(str, varflags & VSQUOTE, 0);
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006274 workloc = expdest - (char *)stackblock();
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006275
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006276#if ENABLE_ASH_BASH_COMPAT
6277 if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
6278 char *idx, *end, *restart_detect;
6279
Denis Vlasenkod6855d12008-09-27 14:03:25 +00006280 if (!repl) {
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006281 repl = parse_sub_pattern(str, varflags & VSQUOTE);
6282 if (!repl)
6283 repl = &null;
6284 }
6285
6286 /* If there's no pattern to match, return the expansion unmolested */
6287 if (*str == '\0')
6288 return 0;
6289
6290 len = 0;
6291 idx = startp;
6292 end = str - 1;
6293 while (idx < end) {
6294 loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
6295 if (!loc) {
6296 /* No match, advance */
6297 restart_detect = stackblock();
6298 STPUTC(*idx, expdest);
6299 if (quotes && *idx == CTLESC) {
6300 idx++;
6301 len++;
6302 STPUTC(*idx, expdest);
6303 }
6304 if (stackblock() != restart_detect)
6305 goto restart;
6306 idx++;
6307 len++;
6308 rmesc++;
6309 continue;
6310 }
6311
6312 if (subtype == VSREPLACEALL) {
6313 while (idx < loc) {
6314 if (quotes && *idx == CTLESC)
6315 idx++;
6316 idx++;
6317 rmesc++;
6318 }
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00006319 } else {
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006320 idx = loc;
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00006321 }
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006322
6323 for (loc = repl; *loc; loc++) {
6324 restart_detect = stackblock();
6325 STPUTC(*loc, expdest);
6326 if (stackblock() != restart_detect)
6327 goto restart;
6328 len++;
6329 }
6330
6331 if (subtype == VSREPLACE) {
6332 while (*idx) {
6333 restart_detect = stackblock();
6334 STPUTC(*idx, expdest);
6335 if (stackblock() != restart_detect)
6336 goto restart;
6337 len++;
6338 idx++;
6339 }
6340 break;
6341 }
6342 }
6343
6344 /* We've put the replaced text into a buffer at workloc, now
6345 * move it to the right place and adjust the stack.
6346 */
6347 startp = stackblock() + startloc;
6348 STPUTC('\0', expdest);
6349 memmove(startp, stackblock() + workloc, len);
6350 startp[len++] = '\0';
6351 amount = expdest - ((char *)stackblock() + startloc + len - 1);
6352 STADJUST(-amount, expdest);
6353 return startp;
6354 }
6355#endif /* ENABLE_ASH_BASH_COMPAT */
6356
6357 subtype -= VSTRIMRIGHT;
6358#if DEBUG
6359 if (subtype < 0 || subtype > 7)
6360 abort();
6361#endif
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006362 /* zero = subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX */
6363 zero = subtype >> 1;
6364 /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
6365 scan = (subtype & 1) ^ zero ? scanleft : scanright;
6366
6367 loc = scan(startp, rmesc, rmescend, str, quotes, zero);
6368 if (loc) {
6369 if (zero) {
6370 memmove(startp, loc, str - loc);
6371 loc = startp + (str - loc) - 1;
6372 }
6373 *loc = '\0';
6374 amount = loc - expdest;
6375 STADJUST(amount, expdest);
6376 }
6377 return loc;
6378}
6379
6380/*
6381 * Add the value of a specialized variable to the stack string.
Denys Vlasenko4d8873f2009-10-04 03:14:41 +02006382 * name parameter (examples):
6383 * ash -c 'echo $1' name:'1='
6384 * ash -c 'echo $qwe' name:'qwe='
6385 * ash -c 'echo $$' name:'$='
6386 * ash -c 'echo ${$}' name:'$='
6387 * ash -c 'echo ${$##q}' name:'$=q'
6388 * ash -c 'echo ${#$}' name:'$='
6389 * note: examples with bad shell syntax:
6390 * ash -c 'echo ${#$1}' name:'$=1'
6391 * ash -c 'echo ${#1#}' name:'1=#'
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006392 */
Denys Vlasenkoadf922e2009-10-08 14:35:37 +02006393static NOINLINE ssize_t
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006394varvalue(char *name, int varflags, int flags, struct strlist *var_str_list)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006395{
6396 int num;
Mike Frysinger98c52642009-04-02 10:02:37 +00006397 const char *p;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006398 int i;
6399 int sep = 0;
6400 int sepq = 0;
6401 ssize_t len = 0;
6402 char **ap;
6403 int syntax;
6404 int quoted = varflags & VSQUOTE;
6405 int subtype = varflags & VSTYPE;
Denys Vlasenko1166d7b2009-09-16 16:20:31 +02006406 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006407
6408 if (quoted && (flags & EXP_FULL))
6409 sep = 1 << CHAR_BIT;
6410
6411 syntax = quoted ? DQSYNTAX : BASESYNTAX;
6412 switch (*name) {
6413 case '$':
6414 num = rootpid;
6415 goto numvar;
6416 case '?':
6417 num = exitstatus;
6418 goto numvar;
6419 case '#':
6420 num = shellparam.nparam;
6421 goto numvar;
6422 case '!':
6423 num = backgndpid;
6424 if (num == 0)
6425 return -1;
6426 numvar:
6427 len = cvtnum(num);
Denys Vlasenko4d8873f2009-10-04 03:14:41 +02006428 goto check_1char_name;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006429 case '-':
Mike Frysinger98c52642009-04-02 10:02:37 +00006430 expdest = makestrspace(NOPTS, expdest);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006431 for (i = NOPTS - 1; i >= 0; i--) {
6432 if (optlist[i]) {
Mike Frysinger98c52642009-04-02 10:02:37 +00006433 USTPUTC(optletters(i), expdest);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006434 len++;
6435 }
6436 }
Denys Vlasenko4d8873f2009-10-04 03:14:41 +02006437 check_1char_name:
6438#if 0
6439 /* handles cases similar to ${#$1} */
6440 if (name[2] != '\0')
6441 raise_error_syntax("bad substitution");
6442#endif
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006443 break;
6444 case '@':
6445 if (sep)
6446 goto param;
6447 /* fall through */
6448 case '*':
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00006449 sep = ifsset() ? signed_char2int(ifsval()[0]) : ' ';
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006450 if (quotes && (SIT(sep, syntax) == CCTL || SIT(sep, syntax) == CBACK))
6451 sepq = 1;
6452 param:
6453 ap = shellparam.p;
6454 if (!ap)
6455 return -1;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006456 while ((p = *ap++) != NULL) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006457 size_t partlen;
6458
6459 partlen = strlen(p);
6460 len += partlen;
6461
6462 if (!(subtype == VSPLUS || subtype == VSLENGTH))
6463 memtodest(p, partlen, syntax, quotes);
6464
6465 if (*ap && sep) {
6466 char *q;
6467
6468 len++;
6469 if (subtype == VSPLUS || subtype == VSLENGTH) {
6470 continue;
6471 }
6472 q = expdest;
6473 if (sepq)
6474 STPUTC(CTLESC, q);
6475 STPUTC(sep, q);
6476 expdest = q;
6477 }
6478 }
6479 return len;
6480 case '0':
6481 case '1':
6482 case '2':
6483 case '3':
6484 case '4':
6485 case '5':
6486 case '6':
6487 case '7':
6488 case '8':
6489 case '9':
Denys Vlasenkoa00329c2009-08-30 20:05:10 +02006490 num = atoi(name); /* number(name) fails on ${N#str} etc */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006491 if (num < 0 || num > shellparam.nparam)
6492 return -1;
6493 p = num ? shellparam.p[num - 1] : arg0;
6494 goto value;
6495 default:
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006496 /* NB: name has form "VAR=..." */
6497
6498 /* "A=a B=$A" case: var_str_list is a list of "A=a" strings
6499 * which should be considered before we check variables. */
6500 if (var_str_list) {
6501 unsigned name_len = (strchrnul(name, '=') - name) + 1;
6502 p = NULL;
6503 do {
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00006504 char *str, *eq;
6505 str = var_str_list->text;
6506 eq = strchr(str, '=');
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006507 if (!eq) /* stop at first non-assignment */
6508 break;
6509 eq++;
Denis Vlasenko6b06cb82008-05-15 21:30:45 +00006510 if (name_len == (unsigned)(eq - str)
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006511 && strncmp(str, name, name_len) == 0) {
6512 p = eq;
6513 /* goto value; - WRONG! */
6514 /* think "A=1 A=2 B=$A" */
6515 }
6516 var_str_list = var_str_list->next;
6517 } while (var_str_list);
6518 if (p)
6519 goto value;
6520 }
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006521 p = lookupvar(name);
6522 value:
6523 if (!p)
6524 return -1;
6525
6526 len = strlen(p);
6527 if (!(subtype == VSPLUS || subtype == VSLENGTH))
6528 memtodest(p, len, syntax, quotes);
6529 return len;
6530 }
6531
6532 if (subtype == VSPLUS || subtype == VSLENGTH)
6533 STADJUST(-len, expdest);
6534 return len;
6535}
6536
6537/*
6538 * Expand a variable, and return a pointer to the next character in the
6539 * input string.
6540 */
6541static char *
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006542evalvar(char *p, int flags, struct strlist *var_str_list)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006543{
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006544 char varflags;
6545 char subtype;
6546 char quoted;
6547 char easy;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006548 char *var;
6549 int patloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006550 int startloc;
6551 ssize_t varlen;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006552
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006553 varflags = (unsigned char) *p++;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006554 subtype = varflags & VSTYPE;
6555 quoted = varflags & VSQUOTE;
6556 var = p;
6557 easy = (!quoted || (*var == '@' && shellparam.nparam));
6558 startloc = expdest - (char *)stackblock();
6559 p = strchr(p, '=') + 1;
6560
6561 again:
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006562 varlen = varvalue(var, varflags, flags, var_str_list);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006563 if (varflags & VSNUL)
6564 varlen--;
6565
6566 if (subtype == VSPLUS) {
6567 varlen = -1 - varlen;
6568 goto vsplus;
6569 }
6570
6571 if (subtype == VSMINUS) {
6572 vsplus:
6573 if (varlen < 0) {
6574 argstr(
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006575 p, flags | EXP_TILDE |
6576 (quoted ? EXP_QWORD : EXP_WORD),
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006577 var_str_list
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006578 );
6579 goto end;
6580 }
6581 if (easy)
6582 goto record;
6583 goto end;
6584 }
6585
6586 if (subtype == VSASSIGN || subtype == VSQUESTION) {
6587 if (varlen < 0) {
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006588 if (subevalvar(p, var, /* strloc: */ 0,
6589 subtype, startloc, varflags,
6590 /* quotes: */ 0,
6591 var_str_list)
6592 ) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006593 varflags &= ~VSNUL;
6594 /*
6595 * Remove any recorded regions beyond
6596 * start of variable
6597 */
6598 removerecordregions(startloc);
6599 goto again;
6600 }
6601 goto end;
6602 }
6603 if (easy)
6604 goto record;
6605 goto end;
6606 }
6607
6608 if (varlen < 0 && uflag)
6609 varunset(p, var, 0, 0);
6610
6611 if (subtype == VSLENGTH) {
6612 cvtnum(varlen > 0 ? varlen : 0);
6613 goto record;
6614 }
6615
6616 if (subtype == VSNORMAL) {
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006617 if (easy)
6618 goto record;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006619 goto end;
6620 }
6621
6622#if DEBUG
6623 switch (subtype) {
6624 case VSTRIMLEFT:
6625 case VSTRIMLEFTMAX:
6626 case VSTRIMRIGHT:
6627 case VSTRIMRIGHTMAX:
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006628#if ENABLE_ASH_BASH_COMPAT
6629 case VSSUBSTR:
6630 case VSREPLACE:
6631 case VSREPLACEALL:
6632#endif
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006633 break;
6634 default:
6635 abort();
6636 }
6637#endif
6638
6639 if (varlen >= 0) {
6640 /*
6641 * Terminate the string and start recording the pattern
6642 * right after it
6643 */
6644 STPUTC('\0', expdest);
6645 patloc = expdest - (char *)stackblock();
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006646 if (0 == subevalvar(p, /* str: */ NULL, patloc, subtype,
6647 startloc, varflags,
Denys Vlasenko1166d7b2009-09-16 16:20:31 +02006648//TODO: | EXP_REDIR too? All other such places do it too
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006649 /* quotes: */ flags & (EXP_FULL | EXP_CASE),
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006650 var_str_list)
6651 ) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006652 int amount = expdest - (
6653 (char *)stackblock() + patloc - 1
6654 );
6655 STADJUST(-amount, expdest);
6656 }
6657 /* Remove any recorded regions beyond start of variable */
6658 removerecordregions(startloc);
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006659 record:
6660 recordregion(startloc, expdest - (char *)stackblock(), quoted);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006661 }
6662
6663 end:
6664 if (subtype != VSNORMAL) { /* skip to end of alternative */
6665 int nesting = 1;
6666 for (;;) {
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006667 char c = *p++;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006668 if (c == CTLESC)
6669 p++;
6670 else if (c == CTLBACKQ || c == (CTLBACKQ|CTLQUOTE)) {
6671 if (varlen >= 0)
6672 argbackq = argbackq->next;
6673 } else if (c == CTLVAR) {
6674 if ((*p++ & VSTYPE) != VSNORMAL)
6675 nesting++;
6676 } else if (c == CTLENDVAR) {
6677 if (--nesting == 0)
6678 break;
6679 }
6680 }
6681 }
6682 return p;
6683}
6684
6685/*
6686 * Break the argument string into pieces based upon IFS and add the
6687 * strings to the argument list. The regions of the string to be
6688 * searched for IFS characters have been stored by recordregion.
6689 */
6690static void
6691ifsbreakup(char *string, struct arglist *arglist)
6692{
6693 struct ifsregion *ifsp;
6694 struct strlist *sp;
6695 char *start;
6696 char *p;
6697 char *q;
6698 const char *ifs, *realifs;
6699 int ifsspc;
6700 int nulonly;
6701
6702 start = string;
6703 if (ifslastp != NULL) {
6704 ifsspc = 0;
6705 nulonly = 0;
6706 realifs = ifsset() ? ifsval() : defifs;
6707 ifsp = &ifsfirst;
6708 do {
6709 p = string + ifsp->begoff;
6710 nulonly = ifsp->nulonly;
6711 ifs = nulonly ? nullstr : realifs;
6712 ifsspc = 0;
6713 while (p < string + ifsp->endoff) {
6714 q = p;
6715 if (*p == CTLESC)
6716 p++;
6717 if (!strchr(ifs, *p)) {
6718 p++;
6719 continue;
6720 }
6721 if (!nulonly)
6722 ifsspc = (strchr(defifs, *p) != NULL);
6723 /* Ignore IFS whitespace at start */
6724 if (q == start && ifsspc) {
6725 p++;
6726 start = p;
6727 continue;
6728 }
6729 *q = '\0';
Denis Vlasenko597906c2008-02-20 16:38:54 +00006730 sp = stzalloc(sizeof(*sp));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006731 sp->text = start;
6732 *arglist->lastp = sp;
6733 arglist->lastp = &sp->next;
6734 p++;
6735 if (!nulonly) {
6736 for (;;) {
6737 if (p >= string + ifsp->endoff) {
6738 break;
6739 }
6740 q = p;
6741 if (*p == CTLESC)
6742 p++;
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +00006743 if (strchr(ifs, *p) == NULL) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006744 p = q;
6745 break;
Denis Vlasenko597906c2008-02-20 16:38:54 +00006746 }
6747 if (strchr(defifs, *p) == NULL) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006748 if (ifsspc) {
6749 p++;
6750 ifsspc = 0;
6751 } else {
6752 p = q;
6753 break;
6754 }
6755 } else
6756 p++;
6757 }
6758 }
6759 start = p;
6760 } /* while */
6761 ifsp = ifsp->next;
6762 } while (ifsp != NULL);
6763 if (nulonly)
6764 goto add;
6765 }
6766
6767 if (!*start)
6768 return;
6769
6770 add:
Denis Vlasenko597906c2008-02-20 16:38:54 +00006771 sp = stzalloc(sizeof(*sp));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006772 sp->text = start;
6773 *arglist->lastp = sp;
6774 arglist->lastp = &sp->next;
6775}
6776
6777static void
6778ifsfree(void)
6779{
6780 struct ifsregion *p;
6781
6782 INT_OFF;
6783 p = ifsfirst.next;
6784 do {
6785 struct ifsregion *ifsp;
6786 ifsp = p->next;
6787 free(p);
6788 p = ifsp;
6789 } while (p);
6790 ifslastp = NULL;
6791 ifsfirst.next = NULL;
6792 INT_ON;
6793}
6794
6795/*
6796 * Add a file name to the list.
6797 */
6798static void
6799addfname(const char *name)
6800{
6801 struct strlist *sp;
6802
Denis Vlasenko597906c2008-02-20 16:38:54 +00006803 sp = stzalloc(sizeof(*sp));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006804 sp->text = ststrdup(name);
6805 *exparg.lastp = sp;
6806 exparg.lastp = &sp->next;
6807}
6808
6809static char *expdir;
6810
6811/*
6812 * Do metacharacter (i.e. *, ?, [...]) expansion.
6813 */
6814static void
6815expmeta(char *enddir, char *name)
6816{
6817 char *p;
6818 const char *cp;
6819 char *start;
6820 char *endname;
6821 int metaflag;
6822 struct stat statb;
6823 DIR *dirp;
6824 struct dirent *dp;
6825 int atend;
6826 int matchdot;
6827
6828 metaflag = 0;
6829 start = name;
6830 for (p = name; *p; p++) {
6831 if (*p == '*' || *p == '?')
6832 metaflag = 1;
6833 else if (*p == '[') {
6834 char *q = p + 1;
6835 if (*q == '!')
6836 q++;
6837 for (;;) {
6838 if (*q == '\\')
6839 q++;
6840 if (*q == '/' || *q == '\0')
6841 break;
6842 if (*++q == ']') {
6843 metaflag = 1;
6844 break;
6845 }
6846 }
6847 } else if (*p == '\\')
6848 p++;
6849 else if (*p == '/') {
6850 if (metaflag)
6851 goto out;
6852 start = p + 1;
6853 }
6854 }
6855 out:
6856 if (metaflag == 0) { /* we've reached the end of the file name */
6857 if (enddir != expdir)
6858 metaflag++;
6859 p = name;
6860 do {
6861 if (*p == '\\')
6862 p++;
6863 *enddir++ = *p;
6864 } while (*p++);
6865 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
6866 addfname(expdir);
6867 return;
6868 }
6869 endname = p;
6870 if (name < start) {
6871 p = name;
6872 do {
6873 if (*p == '\\')
6874 p++;
6875 *enddir++ = *p++;
6876 } while (p < start);
6877 }
6878 if (enddir == expdir) {
6879 cp = ".";
6880 } else if (enddir == expdir + 1 && *expdir == '/') {
6881 cp = "/";
6882 } else {
6883 cp = expdir;
6884 enddir[-1] = '\0';
6885 }
6886 dirp = opendir(cp);
6887 if (dirp == NULL)
6888 return;
6889 if (enddir != expdir)
6890 enddir[-1] = '/';
6891 if (*endname == 0) {
6892 atend = 1;
6893 } else {
6894 atend = 0;
6895 *endname++ = '\0';
6896 }
6897 matchdot = 0;
6898 p = start;
6899 if (*p == '\\')
6900 p++;
6901 if (*p == '.')
6902 matchdot++;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006903 while (!pending_int && (dp = readdir(dirp)) != NULL) {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00006904 if (dp->d_name[0] == '.' && !matchdot)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006905 continue;
6906 if (pmatch(start, dp->d_name)) {
6907 if (atend) {
6908 strcpy(enddir, dp->d_name);
6909 addfname(expdir);
6910 } else {
6911 for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
6912 continue;
6913 p[-1] = '/';
6914 expmeta(p, endname);
6915 }
6916 }
6917 }
6918 closedir(dirp);
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00006919 if (!atend)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006920 endname[-1] = '/';
6921}
6922
6923static struct strlist *
6924msort(struct strlist *list, int len)
6925{
6926 struct strlist *p, *q = NULL;
6927 struct strlist **lpp;
6928 int half;
6929 int n;
6930
6931 if (len <= 1)
6932 return list;
6933 half = len >> 1;
6934 p = list;
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +00006935 for (n = half; --n >= 0;) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006936 q = p;
6937 p = p->next;
6938 }
6939 q->next = NULL; /* terminate first half of list */
6940 q = msort(list, half); /* sort first half of list */
6941 p = msort(p, len - half); /* sort second half */
6942 lpp = &list;
6943 for (;;) {
6944#if ENABLE_LOCALE_SUPPORT
6945 if (strcoll(p->text, q->text) < 0)
6946#else
6947 if (strcmp(p->text, q->text) < 0)
6948#endif
6949 {
6950 *lpp = p;
6951 lpp = &p->next;
6952 p = *lpp;
6953 if (p == NULL) {
6954 *lpp = q;
6955 break;
6956 }
6957 } else {
6958 *lpp = q;
6959 lpp = &q->next;
6960 q = *lpp;
6961 if (q == NULL) {
6962 *lpp = p;
6963 break;
6964 }
6965 }
6966 }
6967 return list;
6968}
6969
6970/*
6971 * Sort the results of file name expansion. It calculates the number of
6972 * strings to sort and then calls msort (short for merge sort) to do the
6973 * work.
6974 */
6975static struct strlist *
6976expsort(struct strlist *str)
6977{
6978 int len;
6979 struct strlist *sp;
6980
6981 len = 0;
6982 for (sp = str; sp; sp = sp->next)
6983 len++;
6984 return msort(str, len);
6985}
6986
6987static void
Denis Vlasenko68404f12008-03-17 09:00:54 +00006988expandmeta(struct strlist *str /*, int flag*/)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006989{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00006990 static const char metachars[] ALIGN1 = {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006991 '*', '?', '[', 0
6992 };
6993 /* TODO - EXP_REDIR */
6994
6995 while (str) {
6996 struct strlist **savelastp;
6997 struct strlist *sp;
6998 char *p;
6999
7000 if (fflag)
7001 goto nometa;
7002 if (!strpbrk(str->text, metachars))
7003 goto nometa;
7004 savelastp = exparg.lastp;
7005
7006 INT_OFF;
7007 p = preglob(str->text, 0, RMESCAPE_ALLOC | RMESCAPE_HEAP);
7008 {
7009 int i = strlen(str->text);
7010 expdir = ckmalloc(i < 2048 ? 2048 : i); /* XXX */
7011 }
7012
7013 expmeta(expdir, p);
7014 free(expdir);
7015 if (p != str->text)
7016 free(p);
7017 INT_ON;
7018 if (exparg.lastp == savelastp) {
7019 /*
7020 * no matches
7021 */
7022 nometa:
7023 *exparg.lastp = str;
Denys Vlasenkob6c84342009-08-29 20:23:20 +02007024 rmescapes(str->text, 0);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007025 exparg.lastp = &str->next;
7026 } else {
7027 *exparg.lastp = NULL;
7028 *savelastp = sp = expsort(*savelastp);
7029 while (sp->next != NULL)
7030 sp = sp->next;
7031 exparg.lastp = &sp->next;
7032 }
7033 str = str->next;
7034 }
7035}
7036
7037/*
7038 * Perform variable substitution and command substitution on an argument,
7039 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
7040 * perform splitting and file name expansion. When arglist is NULL, perform
7041 * here document expansion.
7042 */
7043static void
7044expandarg(union node *arg, struct arglist *arglist, int flag)
7045{
7046 struct strlist *sp;
7047 char *p;
7048
7049 argbackq = arg->narg.backquote;
7050 STARTSTACKSTR(expdest);
7051 ifsfirst.next = NULL;
7052 ifslastp = NULL;
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00007053 argstr(arg->narg.text, flag,
7054 /* var_str_list: */ arglist ? arglist->list : NULL);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007055 p = _STPUTC('\0', expdest);
7056 expdest = p - 1;
7057 if (arglist == NULL) {
7058 return; /* here document expanded */
7059 }
7060 p = grabstackstr(p);
7061 exparg.lastp = &exparg.list;
7062 /*
7063 * TODO - EXP_REDIR
7064 */
7065 if (flag & EXP_FULL) {
7066 ifsbreakup(p, &exparg);
7067 *exparg.lastp = NULL;
7068 exparg.lastp = &exparg.list;
Denis Vlasenko68404f12008-03-17 09:00:54 +00007069 expandmeta(exparg.list /*, flag*/);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007070 } else {
7071 if (flag & EXP_REDIR) /*XXX - for now, just remove escapes */
Denys Vlasenkob6c84342009-08-29 20:23:20 +02007072 rmescapes(p, 0);
Denis Vlasenko597906c2008-02-20 16:38:54 +00007073 sp = stzalloc(sizeof(*sp));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007074 sp->text = p;
7075 *exparg.lastp = sp;
7076 exparg.lastp = &sp->next;
7077 }
7078 if (ifsfirst.next)
7079 ifsfree();
7080 *exparg.lastp = NULL;
7081 if (exparg.list) {
7082 *arglist->lastp = exparg.list;
7083 arglist->lastp = exparg.lastp;
7084 }
7085}
7086
7087/*
7088 * Expand shell variables and backquotes inside a here document.
7089 */
7090static void
7091expandhere(union node *arg, int fd)
7092{
7093 herefd = fd;
7094 expandarg(arg, (struct arglist *)NULL, 0);
7095 full_write(fd, stackblock(), expdest - (char *)stackblock());
7096}
7097
7098/*
7099 * Returns true if the pattern matches the string.
7100 */
7101static int
7102patmatch(char *pattern, const char *string)
7103{
7104 return pmatch(preglob(pattern, 0, 0), string);
7105}
7106
7107/*
7108 * See if a pattern matches in a case statement.
7109 */
7110static int
7111casematch(union node *pattern, char *val)
7112{
7113 struct stackmark smark;
7114 int result;
7115
7116 setstackmark(&smark);
7117 argbackq = pattern->narg.backquote;
7118 STARTSTACKSTR(expdest);
7119 ifslastp = NULL;
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00007120 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE,
7121 /* var_str_list: */ NULL);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007122 STACKSTRNUL(expdest);
7123 result = patmatch(stackblock(), val);
7124 popstackmark(&smark);
7125 return result;
7126}
7127
7128
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007129/* ============ find_command */
7130
7131struct builtincmd {
7132 const char *name;
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007133 int (*builtin)(int, char **) FAST_FUNC;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007134 /* unsigned flags; */
7135};
7136#define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
Denis Vlasenkoe26b2782008-02-12 07:40:29 +00007137/* "regular" builtins always take precedence over commands,
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007138 * regardless of PATH=....%builtin... position */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007139#define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007140#define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007141
7142struct cmdentry {
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00007143 smallint cmdtype; /* CMDxxx */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007144 union param {
7145 int index;
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00007146 /* index >= 0 for commands without path (slashes) */
7147 /* (TODO: what exactly does the value mean? PATH position?) */
7148 /* index == -1 for commands with slashes */
7149 /* index == (-2 - applet_no) for NOFORK applets */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007150 const struct builtincmd *cmd;
7151 struct funcnode *func;
7152 } u;
7153};
7154/* values of cmdtype */
7155#define CMDUNKNOWN -1 /* no entry in table for command */
7156#define CMDNORMAL 0 /* command is an executable program */
7157#define CMDFUNCTION 1 /* command is a shell function */
7158#define CMDBUILTIN 2 /* command is a shell builtin */
7159
7160/* action to find_command() */
7161#define DO_ERR 0x01 /* prints errors */
7162#define DO_ABS 0x02 /* checks absolute paths */
7163#define DO_NOFUNC 0x04 /* don't return shell functions, for command */
7164#define DO_ALTPATH 0x08 /* using alternate path */
7165#define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
7166
7167static void find_command(char *, struct cmdentry *, int, const char *);
7168
7169
7170/* ============ Hashing commands */
7171
7172/*
7173 * When commands are first encountered, they are entered in a hash table.
7174 * This ensures that a full path search will not have to be done for them
7175 * on each invocation.
7176 *
7177 * We should investigate converting to a linear search, even though that
7178 * would make the command name "hash" a misnomer.
7179 */
7180
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007181struct tblentry {
7182 struct tblentry *next; /* next entry in hash chain */
7183 union param param; /* definition of builtin function */
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00007184 smallint cmdtype; /* CMDxxx */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007185 char rehash; /* if set, cd done since entry created */
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007186 char cmdname[1]; /* name of command */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007187};
7188
Denis Vlasenko01631112007-12-16 17:20:38 +00007189static struct tblentry **cmdtable;
7190#define INIT_G_cmdtable() do { \
7191 cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
7192} while (0)
7193
7194static int builtinloc = -1; /* index in path of %builtin, or -1 */
7195
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007196
7197static void
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00007198tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) char *cmd, char **argv, char **envp)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007199{
7200 int repeated = 0;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007201
Denis Vlasenko80d14be2007-04-10 23:03:30 +00007202#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007203 if (applet_no >= 0) {
Denis Vlasenkob7304742008-10-20 08:15:51 +00007204 if (APPLET_IS_NOEXEC(applet_no)) {
7205 while (*envp)
7206 putenv(*envp++);
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007207 run_applet_no_and_exit(applet_no, argv);
Denis Vlasenkob7304742008-10-20 08:15:51 +00007208 }
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007209 /* re-exec ourselves with the new arguments */
7210 execve(bb_busybox_exec_path, argv, envp);
7211 /* If they called chroot or otherwise made the binary no longer
7212 * executable, fall through */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007213 }
7214#endif
7215
7216 repeat:
7217#ifdef SYSV
7218 do {
7219 execve(cmd, argv, envp);
7220 } while (errno == EINTR);
7221#else
7222 execve(cmd, argv, envp);
7223#endif
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007224 if (repeated) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007225 free(argv);
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007226 return;
7227 }
7228 if (errno == ENOEXEC) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007229 char **ap;
7230 char **new;
7231
7232 for (ap = argv; *ap; ap++)
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007233 continue;
7234 ap = new = ckmalloc((ap - argv + 2) * sizeof(ap[0]));
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007235 ap[1] = cmd;
Denis Vlasenkoc44ab012007-04-09 03:11:58 +00007236 ap[0] = cmd = (char *)DEFAULT_SHELL;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007237 ap += 2;
7238 argv++;
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007239 while ((*ap++ = *argv++) != NULL)
Denis Vlasenko597906c2008-02-20 16:38:54 +00007240 continue;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007241 argv = new;
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007242 repeated++;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007243 goto repeat;
7244 }
7245}
7246
7247/*
7248 * Exec a program. Never returns. If you change this routine, you may
7249 * have to change the find_command routine as well.
7250 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00007251static void shellexec(char **, const char *, int) NORETURN;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007252static void
7253shellexec(char **argv, const char *path, int idx)
7254{
7255 char *cmdname;
7256 int e;
7257 char **envp;
7258 int exerrno;
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007259#if ENABLE_FEATURE_SH_STANDALONE
7260 int applet_no = -1;
7261#endif
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007262
Denis Vlasenko34c73c42008-08-16 11:48:02 +00007263 clearredir(/*drop:*/ 1);
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007264 envp = listvars(VEXPORT, VUNSET, 0);
7265 if (strchr(argv[0], '/') != NULL
Denis Vlasenko80d14be2007-04-10 23:03:30 +00007266#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007267 || (applet_no = find_applet_by_name(argv[0])) >= 0
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007268#endif
7269 ) {
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00007270 tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) argv[0], argv, envp);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007271 e = errno;
7272 } else {
7273 e = ENOENT;
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02007274 while ((cmdname = path_advance(&path, argv[0])) != NULL) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007275 if (--idx < 0 && pathopt == NULL) {
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00007276 tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007277 if (errno != ENOENT && errno != ENOTDIR)
7278 e = errno;
7279 }
7280 stunalloc(cmdname);
7281 }
7282 }
7283
7284 /* Map to POSIX errors */
7285 switch (e) {
7286 case EACCES:
7287 exerrno = 126;
7288 break;
7289 case ENOENT:
7290 exerrno = 127;
7291 break;
7292 default:
7293 exerrno = 2;
7294 break;
7295 }
7296 exitstatus = exerrno;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02007297 TRACE(("shellexec failed for %s, errno %d, suppress_int %d\n",
7298 argv[0], e, suppress_int));
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007299 ash_msg_and_raise(EXEXEC, "%s: %s", argv[0], errmsg(e, "not found"));
7300 /* NOTREACHED */
7301}
7302
7303static void
7304printentry(struct tblentry *cmdp)
7305{
7306 int idx;
7307 const char *path;
7308 char *name;
7309
7310 idx = cmdp->param.index;
7311 path = pathval();
7312 do {
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02007313 name = path_advance(&path, cmdp->cmdname);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007314 stunalloc(name);
7315 } while (--idx >= 0);
7316 out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
7317}
7318
7319/*
7320 * Clear out command entries. The argument specifies the first entry in
7321 * PATH which has changed.
7322 */
7323static void
7324clearcmdentry(int firstchange)
7325{
7326 struct tblentry **tblp;
7327 struct tblentry **pp;
7328 struct tblentry *cmdp;
7329
7330 INT_OFF;
7331 for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
7332 pp = tblp;
7333 while ((cmdp = *pp) != NULL) {
7334 if ((cmdp->cmdtype == CMDNORMAL &&
7335 cmdp->param.index >= firstchange)
7336 || (cmdp->cmdtype == CMDBUILTIN &&
7337 builtinloc >= firstchange)
7338 ) {
7339 *pp = cmdp->next;
7340 free(cmdp);
7341 } else {
7342 pp = &cmdp->next;
7343 }
7344 }
7345 }
7346 INT_ON;
7347}
7348
7349/*
7350 * Locate a command in the command hash table. If "add" is nonzero,
7351 * add the command to the table if it is not already present. The
7352 * variable "lastcmdentry" is set to point to the address of the link
7353 * pointing to the entry, so that delete_cmd_entry can delete the
7354 * entry.
7355 *
7356 * Interrupts must be off if called with add != 0.
7357 */
7358static struct tblentry **lastcmdentry;
7359
7360static struct tblentry *
7361cmdlookup(const char *name, int add)
7362{
7363 unsigned int hashval;
7364 const char *p;
7365 struct tblentry *cmdp;
7366 struct tblentry **pp;
7367
7368 p = name;
7369 hashval = (unsigned char)*p << 4;
7370 while (*p)
7371 hashval += (unsigned char)*p++;
7372 hashval &= 0x7FFF;
7373 pp = &cmdtable[hashval % CMDTABLESIZE];
7374 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7375 if (strcmp(cmdp->cmdname, name) == 0)
7376 break;
7377 pp = &cmdp->next;
7378 }
7379 if (add && cmdp == NULL) {
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007380 cmdp = *pp = ckzalloc(sizeof(struct tblentry)
7381 + strlen(name)
7382 /* + 1 - already done because
7383 * tblentry::cmdname is char[1] */);
Denis Vlasenko597906c2008-02-20 16:38:54 +00007384 /*cmdp->next = NULL; - ckzalloc did it */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007385 cmdp->cmdtype = CMDUNKNOWN;
7386 strcpy(cmdp->cmdname, name);
7387 }
7388 lastcmdentry = pp;
7389 return cmdp;
7390}
7391
7392/*
7393 * Delete the command entry returned on the last lookup.
7394 */
7395static void
7396delete_cmd_entry(void)
7397{
7398 struct tblentry *cmdp;
7399
7400 INT_OFF;
7401 cmdp = *lastcmdentry;
7402 *lastcmdentry = cmdp->next;
7403 if (cmdp->cmdtype == CMDFUNCTION)
7404 freefunc(cmdp->param.func);
7405 free(cmdp);
7406 INT_ON;
7407}
7408
7409/*
7410 * Add a new command entry, replacing any existing command entry for
7411 * the same name - except special builtins.
7412 */
7413static void
7414addcmdentry(char *name, struct cmdentry *entry)
7415{
7416 struct tblentry *cmdp;
7417
7418 cmdp = cmdlookup(name, 1);
7419 if (cmdp->cmdtype == CMDFUNCTION) {
7420 freefunc(cmdp->param.func);
7421 }
7422 cmdp->cmdtype = entry->cmdtype;
7423 cmdp->param = entry->u;
7424 cmdp->rehash = 0;
7425}
7426
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007427static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00007428hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007429{
7430 struct tblentry **pp;
7431 struct tblentry *cmdp;
7432 int c;
7433 struct cmdentry entry;
7434 char *name;
7435
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007436 if (nextopt("r") != '\0') {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007437 clearcmdentry(0);
7438 return 0;
7439 }
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007440
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007441 if (*argptr == NULL) {
7442 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7443 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7444 if (cmdp->cmdtype == CMDNORMAL)
7445 printentry(cmdp);
7446 }
7447 }
7448 return 0;
7449 }
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007450
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007451 c = 0;
7452 while ((name = *argptr) != NULL) {
7453 cmdp = cmdlookup(name, 0);
7454 if (cmdp != NULL
7455 && (cmdp->cmdtype == CMDNORMAL
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007456 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
7457 ) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007458 delete_cmd_entry();
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007459 }
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007460 find_command(name, &entry, DO_ERR, pathval());
7461 if (entry.cmdtype == CMDUNKNOWN)
7462 c = 1;
7463 argptr++;
7464 }
7465 return c;
7466}
7467
7468/*
7469 * Called when a cd is done. Marks all commands so the next time they
7470 * are executed they will be rehashed.
7471 */
7472static void
7473hashcd(void)
7474{
7475 struct tblentry **pp;
7476 struct tblentry *cmdp;
7477
7478 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7479 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007480 if (cmdp->cmdtype == CMDNORMAL
7481 || (cmdp->cmdtype == CMDBUILTIN
7482 && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
7483 && builtinloc > 0)
7484 ) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007485 cmdp->rehash = 1;
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007486 }
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007487 }
7488 }
7489}
7490
7491/*
7492 * Fix command hash table when PATH changed.
7493 * Called before PATH is changed. The argument is the new value of PATH;
7494 * pathval() still returns the old value at this point.
7495 * Called with interrupts off.
7496 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007497static void FAST_FUNC
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007498changepath(const char *new)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007499{
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007500 const char *old;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007501 int firstchange;
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007502 int idx;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007503 int idx_bltin;
7504
7505 old = pathval();
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007506 firstchange = 9999; /* assume no change */
7507 idx = 0;
7508 idx_bltin = -1;
7509 for (;;) {
7510 if (*old != *new) {
7511 firstchange = idx;
7512 if ((*old == '\0' && *new == ':')
7513 || (*old == ':' && *new == '\0'))
7514 firstchange++;
7515 old = new; /* ignore subsequent differences */
7516 }
7517 if (*new == '\0')
7518 break;
7519 if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
7520 idx_bltin = idx;
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007521 if (*new == ':')
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007522 idx++;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007523 new++, old++;
7524 }
7525 if (builtinloc < 0 && idx_bltin >= 0)
7526 builtinloc = idx_bltin; /* zap builtins */
7527 if (builtinloc >= 0 && idx_bltin < 0)
7528 firstchange = 0;
7529 clearcmdentry(firstchange);
7530 builtinloc = idx_bltin;
7531}
7532
7533#define TEOF 0
7534#define TNL 1
7535#define TREDIR 2
7536#define TWORD 3
7537#define TSEMI 4
7538#define TBACKGND 5
7539#define TAND 6
7540#define TOR 7
7541#define TPIPE 8
7542#define TLP 9
7543#define TRP 10
7544#define TENDCASE 11
7545#define TENDBQUOTE 12
7546#define TNOT 13
7547#define TCASE 14
7548#define TDO 15
7549#define TDONE 16
7550#define TELIF 17
7551#define TELSE 18
7552#define TESAC 19
7553#define TFI 20
7554#define TFOR 21
7555#define TIF 22
7556#define TIN 23
7557#define TTHEN 24
7558#define TUNTIL 25
7559#define TWHILE 26
7560#define TBEGIN 27
7561#define TEND 28
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007562typedef smallint token_id_t;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007563
7564/* first char is indicating which tokens mark the end of a list */
7565static const char *const tokname_array[] = {
7566 "\1end of file",
7567 "\0newline",
7568 "\0redirection",
7569 "\0word",
7570 "\0;",
7571 "\0&",
7572 "\0&&",
7573 "\0||",
7574 "\0|",
7575 "\0(",
7576 "\1)",
7577 "\1;;",
7578 "\1`",
7579#define KWDOFFSET 13
7580 /* the following are keywords */
7581 "\0!",
7582 "\0case",
7583 "\1do",
7584 "\1done",
7585 "\1elif",
7586 "\1else",
7587 "\1esac",
7588 "\1fi",
7589 "\0for",
7590 "\0if",
7591 "\0in",
7592 "\1then",
7593 "\0until",
7594 "\0while",
7595 "\0{",
7596 "\1}",
7597};
7598
7599static const char *
7600tokname(int tok)
7601{
7602 static char buf[16];
7603
Denis Vlasenko240a1cf2007-04-08 16:07:02 +00007604//try this:
7605//if (tok < TSEMI) return tokname_array[tok] + 1;
7606//sprintf(buf, "\"%s\"", tokname_array[tok] + 1);
7607//return buf;
7608
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007609 if (tok >= TSEMI)
7610 buf[0] = '"';
7611 sprintf(buf + (tok >= TSEMI), "%s%c",
7612 tokname_array[tok] + 1, (tok >= TSEMI ? '"' : 0));
7613 return buf;
7614}
7615
7616/* Wrapper around strcmp for qsort/bsearch/... */
7617static int
7618pstrcmp(const void *a, const void *b)
7619{
Denis Vlasenko240a1cf2007-04-08 16:07:02 +00007620 return strcmp((char*) a, (*(char**) b) + 1);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007621}
7622
7623static const char *const *
7624findkwd(const char *s)
7625{
7626 return bsearch(s, tokname_array + KWDOFFSET,
Denis Vlasenko80b8b392007-06-25 10:55:35 +00007627 ARRAY_SIZE(tokname_array) - KWDOFFSET,
7628 sizeof(tokname_array[0]), pstrcmp);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007629}
7630
7631/*
7632 * Locate and print what a word is...
7633 */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007634static int
7635describe_command(char *command, int describe_command_verbose)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007636{
7637 struct cmdentry entry;
7638 struct tblentry *cmdp;
7639#if ENABLE_ASH_ALIAS
7640 const struct alias *ap;
7641#endif
7642 const char *path = pathval();
7643
7644 if (describe_command_verbose) {
7645 out1str(command);
7646 }
7647
7648 /* First look at the keywords */
7649 if (findkwd(command)) {
7650 out1str(describe_command_verbose ? " is a shell keyword" : command);
7651 goto out;
7652 }
7653
7654#if ENABLE_ASH_ALIAS
7655 /* Then look at the aliases */
7656 ap = lookupalias(command, 0);
7657 if (ap != NULL) {
Denis Vlasenko46846e22007-05-20 13:08:31 +00007658 if (!describe_command_verbose) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007659 out1str("alias ");
7660 printalias(ap);
7661 return 0;
7662 }
Denis Vlasenko46846e22007-05-20 13:08:31 +00007663 out1fmt(" is an alias for %s", ap->val);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007664 goto out;
7665 }
7666#endif
7667 /* Then check if it is a tracked alias */
7668 cmdp = cmdlookup(command, 0);
7669 if (cmdp != NULL) {
7670 entry.cmdtype = cmdp->cmdtype;
7671 entry.u = cmdp->param;
7672 } else {
7673 /* Finally use brute force */
7674 find_command(command, &entry, DO_ABS, path);
7675 }
7676
7677 switch (entry.cmdtype) {
7678 case CMDNORMAL: {
7679 int j = entry.u.index;
7680 char *p;
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00007681 if (j < 0) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007682 p = command;
7683 } else {
7684 do {
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02007685 p = path_advance(&path, command);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007686 stunalloc(p);
7687 } while (--j >= 0);
7688 }
7689 if (describe_command_verbose) {
7690 out1fmt(" is%s %s",
7691 (cmdp ? " a tracked alias for" : nullstr), p
7692 );
7693 } else {
7694 out1str(p);
7695 }
7696 break;
7697 }
7698
7699 case CMDFUNCTION:
7700 if (describe_command_verbose) {
7701 out1str(" is a shell function");
7702 } else {
7703 out1str(command);
7704 }
7705 break;
7706
7707 case CMDBUILTIN:
7708 if (describe_command_verbose) {
7709 out1fmt(" is a %sshell builtin",
7710 IS_BUILTIN_SPECIAL(entry.u.cmd) ?
7711 "special " : nullstr
7712 );
7713 } else {
7714 out1str(command);
7715 }
7716 break;
7717
7718 default:
7719 if (describe_command_verbose) {
7720 out1str(": not found\n");
7721 }
7722 return 127;
7723 }
7724 out:
7725 outstr("\n", stdout);
7726 return 0;
7727}
7728
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007729static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00007730typecmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007731{
Denis Vlasenko46846e22007-05-20 13:08:31 +00007732 int i = 1;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007733 int err = 0;
Denis Vlasenko46846e22007-05-20 13:08:31 +00007734 int verbose = 1;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007735
Denis Vlasenko46846e22007-05-20 13:08:31 +00007736 /* type -p ... ? (we don't bother checking for 'p') */
Denis Vlasenko1fc62382007-06-25 22:55:34 +00007737 if (argv[1] && argv[1][0] == '-') {
Denis Vlasenko46846e22007-05-20 13:08:31 +00007738 i++;
7739 verbose = 0;
7740 }
Denis Vlasenko68404f12008-03-17 09:00:54 +00007741 while (argv[i]) {
Denis Vlasenko46846e22007-05-20 13:08:31 +00007742 err |= describe_command(argv[i++], verbose);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007743 }
7744 return err;
7745}
7746
7747#if ENABLE_ASH_CMDCMD
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007748static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00007749commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007750{
7751 int c;
7752 enum {
7753 VERIFY_BRIEF = 1,
7754 VERIFY_VERBOSE = 2,
7755 } verify = 0;
7756
7757 while ((c = nextopt("pvV")) != '\0')
7758 if (c == 'V')
7759 verify |= VERIFY_VERBOSE;
7760 else if (c == 'v')
7761 verify |= VERIFY_BRIEF;
7762#if DEBUG
7763 else if (c != 'p')
7764 abort();
7765#endif
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00007766 /* Mimic bash: just "command -v" doesn't complain, it's a nop */
7767 if (verify && (*argptr != NULL)) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007768 return describe_command(*argptr, verify - VERIFY_BRIEF);
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00007769 }
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007770
7771 return 0;
7772}
7773#endif
7774
7775
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007776/* ============ eval.c */
Eric Andersencb57d552001-06-28 07:25:16 +00007777
Denis Vlasenko340299a2008-11-21 10:36:36 +00007778static int funcblocksize; /* size of structures in function */
7779static int funcstringsize; /* size of strings in node */
7780static void *funcblock; /* block to allocate function from */
7781static char *funcstring; /* block to allocate strings from */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007782
Eric Andersencb57d552001-06-28 07:25:16 +00007783/* flags in argument to evaltree */
Denis Vlasenko340299a2008-11-21 10:36:36 +00007784#define EV_EXIT 01 /* exit after evaluating tree */
7785#define EV_TESTED 02 /* exit status is checked; ignore -e flag */
Eric Andersenc470f442003-07-28 09:56:35 +00007786#define EV_BACKCMD 04 /* command executing within back quotes */
Eric Andersencb57d552001-06-28 07:25:16 +00007787
Denys Vlasenko0e5e4ea2009-10-11 00:36:20 +02007788static const uint8_t nodesize[N_NUMBER] = {
Denis Vlasenko340299a2008-11-21 10:36:36 +00007789 [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
7790 [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
7791 [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
7792 [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
7793 [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
7794 [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
7795 [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
7796 [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
7797 [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
7798 [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
7799 [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
7800 [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
7801 [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
7802 [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
7803 [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
7804 [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
7805 [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
Denis Vlasenkocc5feab2008-11-22 01:32:40 +00007806#if ENABLE_ASH_BASH_COMPAT
Denis Vlasenko340299a2008-11-21 10:36:36 +00007807 [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
Denis Vlasenkocc5feab2008-11-22 01:32:40 +00007808#endif
Denis Vlasenko340299a2008-11-21 10:36:36 +00007809 [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
7810 [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
7811 [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
7812 [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
7813 [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
7814 [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
7815 [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
7816 [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
7817 [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007818};
7819
7820static void calcsize(union node *n);
7821
7822static void
7823sizenodelist(struct nodelist *lp)
7824{
7825 while (lp) {
7826 funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
7827 calcsize(lp->n);
7828 lp = lp->next;
7829 }
7830}
7831
7832static void
7833calcsize(union node *n)
7834{
7835 if (n == NULL)
7836 return;
7837 funcblocksize += nodesize[n->type];
7838 switch (n->type) {
7839 case NCMD:
7840 calcsize(n->ncmd.redirect);
7841 calcsize(n->ncmd.args);
7842 calcsize(n->ncmd.assign);
7843 break;
7844 case NPIPE:
7845 sizenodelist(n->npipe.cmdlist);
7846 break;
7847 case NREDIR:
7848 case NBACKGND:
7849 case NSUBSHELL:
7850 calcsize(n->nredir.redirect);
7851 calcsize(n->nredir.n);
7852 break;
7853 case NAND:
7854 case NOR:
7855 case NSEMI:
7856 case NWHILE:
7857 case NUNTIL:
7858 calcsize(n->nbinary.ch2);
7859 calcsize(n->nbinary.ch1);
7860 break;
7861 case NIF:
7862 calcsize(n->nif.elsepart);
7863 calcsize(n->nif.ifpart);
7864 calcsize(n->nif.test);
7865 break;
7866 case NFOR:
7867 funcstringsize += strlen(n->nfor.var) + 1;
7868 calcsize(n->nfor.body);
7869 calcsize(n->nfor.args);
7870 break;
7871 case NCASE:
7872 calcsize(n->ncase.cases);
7873 calcsize(n->ncase.expr);
7874 break;
7875 case NCLIST:
7876 calcsize(n->nclist.body);
7877 calcsize(n->nclist.pattern);
7878 calcsize(n->nclist.next);
7879 break;
7880 case NDEFUN:
7881 case NARG:
7882 sizenodelist(n->narg.backquote);
7883 funcstringsize += strlen(n->narg.text) + 1;
7884 calcsize(n->narg.next);
7885 break;
7886 case NTO:
Denis Vlasenko559691a2008-10-05 18:39:31 +00007887#if ENABLE_ASH_BASH_COMPAT
7888 case NTO2:
7889#endif
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007890 case NCLOBBER:
7891 case NFROM:
7892 case NFROMTO:
7893 case NAPPEND:
7894 calcsize(n->nfile.fname);
7895 calcsize(n->nfile.next);
7896 break;
7897 case NTOFD:
7898 case NFROMFD:
7899 calcsize(n->ndup.vname);
7900 calcsize(n->ndup.next);
7901 break;
7902 case NHERE:
7903 case NXHERE:
7904 calcsize(n->nhere.doc);
7905 calcsize(n->nhere.next);
7906 break;
7907 case NNOT:
7908 calcsize(n->nnot.com);
7909 break;
7910 };
7911}
7912
7913static char *
7914nodeckstrdup(char *s)
7915{
7916 char *rtn = funcstring;
7917
7918 strcpy(funcstring, s);
7919 funcstring += strlen(s) + 1;
7920 return rtn;
7921}
7922
7923static union node *copynode(union node *);
7924
7925static struct nodelist *
7926copynodelist(struct nodelist *lp)
7927{
7928 struct nodelist *start;
7929 struct nodelist **lpp;
7930
7931 lpp = &start;
7932 while (lp) {
7933 *lpp = funcblock;
7934 funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
7935 (*lpp)->n = copynode(lp->n);
7936 lp = lp->next;
7937 lpp = &(*lpp)->next;
7938 }
7939 *lpp = NULL;
7940 return start;
7941}
7942
7943static union node *
7944copynode(union node *n)
7945{
7946 union node *new;
7947
7948 if (n == NULL)
7949 return NULL;
7950 new = funcblock;
7951 funcblock = (char *) funcblock + nodesize[n->type];
7952
7953 switch (n->type) {
7954 case NCMD:
7955 new->ncmd.redirect = copynode(n->ncmd.redirect);
7956 new->ncmd.args = copynode(n->ncmd.args);
7957 new->ncmd.assign = copynode(n->ncmd.assign);
7958 break;
7959 case NPIPE:
7960 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00007961 new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007962 break;
7963 case NREDIR:
7964 case NBACKGND:
7965 case NSUBSHELL:
7966 new->nredir.redirect = copynode(n->nredir.redirect);
7967 new->nredir.n = copynode(n->nredir.n);
7968 break;
7969 case NAND:
7970 case NOR:
7971 case NSEMI:
7972 case NWHILE:
7973 case NUNTIL:
7974 new->nbinary.ch2 = copynode(n->nbinary.ch2);
7975 new->nbinary.ch1 = copynode(n->nbinary.ch1);
7976 break;
7977 case NIF:
7978 new->nif.elsepart = copynode(n->nif.elsepart);
7979 new->nif.ifpart = copynode(n->nif.ifpart);
7980 new->nif.test = copynode(n->nif.test);
7981 break;
7982 case NFOR:
7983 new->nfor.var = nodeckstrdup(n->nfor.var);
7984 new->nfor.body = copynode(n->nfor.body);
7985 new->nfor.args = copynode(n->nfor.args);
7986 break;
7987 case NCASE:
7988 new->ncase.cases = copynode(n->ncase.cases);
7989 new->ncase.expr = copynode(n->ncase.expr);
7990 break;
7991 case NCLIST:
7992 new->nclist.body = copynode(n->nclist.body);
7993 new->nclist.pattern = copynode(n->nclist.pattern);
7994 new->nclist.next = copynode(n->nclist.next);
7995 break;
7996 case NDEFUN:
7997 case NARG:
7998 new->narg.backquote = copynodelist(n->narg.backquote);
7999 new->narg.text = nodeckstrdup(n->narg.text);
8000 new->narg.next = copynode(n->narg.next);
8001 break;
8002 case NTO:
Denis Vlasenko559691a2008-10-05 18:39:31 +00008003#if ENABLE_ASH_BASH_COMPAT
8004 case NTO2:
8005#endif
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008006 case NCLOBBER:
8007 case NFROM:
8008 case NFROMTO:
8009 case NAPPEND:
8010 new->nfile.fname = copynode(n->nfile.fname);
8011 new->nfile.fd = n->nfile.fd;
8012 new->nfile.next = copynode(n->nfile.next);
8013 break;
8014 case NTOFD:
8015 case NFROMFD:
8016 new->ndup.vname = copynode(n->ndup.vname);
8017 new->ndup.dupfd = n->ndup.dupfd;
8018 new->ndup.fd = n->ndup.fd;
8019 new->ndup.next = copynode(n->ndup.next);
8020 break;
8021 case NHERE:
8022 case NXHERE:
8023 new->nhere.doc = copynode(n->nhere.doc);
8024 new->nhere.fd = n->nhere.fd;
8025 new->nhere.next = copynode(n->nhere.next);
8026 break;
8027 case NNOT:
8028 new->nnot.com = copynode(n->nnot.com);
8029 break;
8030 };
8031 new->type = n->type;
8032 return new;
8033}
8034
8035/*
8036 * Make a copy of a parse tree.
8037 */
8038static struct funcnode *
8039copyfunc(union node *n)
8040{
8041 struct funcnode *f;
8042 size_t blocksize;
8043
8044 funcblocksize = offsetof(struct funcnode, n);
8045 funcstringsize = 0;
8046 calcsize(n);
8047 blocksize = funcblocksize;
8048 f = ckmalloc(blocksize + funcstringsize);
8049 funcblock = (char *) f + offsetof(struct funcnode, n);
8050 funcstring = (char *) f + blocksize;
8051 copynode(n);
8052 f->count = 0;
8053 return f;
8054}
8055
8056/*
8057 * Define a shell function.
8058 */
8059static void
8060defun(char *name, union node *func)
8061{
8062 struct cmdentry entry;
8063
8064 INT_OFF;
8065 entry.cmdtype = CMDFUNCTION;
8066 entry.u.func = copyfunc(func);
8067 addcmdentry(name, &entry);
8068 INT_ON;
8069}
8070
Denis Vlasenko4b875702009-03-19 13:30:04 +00008071/* Reasons for skipping commands (see comment on breakcmd routine) */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008072#define SKIPBREAK (1 << 0)
8073#define SKIPCONT (1 << 1)
8074#define SKIPFUNC (1 << 2)
8075#define SKIPFILE (1 << 3)
8076#define SKIPEVAL (1 << 4)
Denis Vlasenko4b875702009-03-19 13:30:04 +00008077static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008078static int skipcount; /* number of levels to skip */
8079static int funcnest; /* depth of function calls */
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +00008080static int loopnest; /* current loop nesting level */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008081
Denis Vlasenko4b875702009-03-19 13:30:04 +00008082/* Forward decl way out to parsing code - dotrap needs it */
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008083static int evalstring(char *s, int mask);
8084
Denis Vlasenko4b875702009-03-19 13:30:04 +00008085/* Called to execute a trap.
8086 * Single callsite - at the end of evaltree().
8087 * If we return non-zero, exaltree raises EXEXIT exception.
8088 *
8089 * Perhaps we should avoid entering new trap handlers
8090 * while we are executing a trap handler. [is it a TODO?]
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008091 */
8092static int
8093dotrap(void)
8094{
Denis Vlasenko4b875702009-03-19 13:30:04 +00008095 uint8_t *g;
8096 int sig;
8097 uint8_t savestatus;
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008098
8099 savestatus = exitstatus;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02008100 pending_sig = 0;
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008101 xbarrier();
8102
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008103 TRACE(("dotrap entered\n"));
Denis Vlasenko4b875702009-03-19 13:30:04 +00008104 for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
8105 int want_exexit;
8106 char *t;
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008107
Denis Vlasenko4b875702009-03-19 13:30:04 +00008108 if (*g == 0)
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008109 continue;
Denis Vlasenko4b875702009-03-19 13:30:04 +00008110 t = trap[sig];
8111 /* non-trapped SIGINT is handled separately by raise_interrupt,
8112 * don't upset it by resetting gotsig[SIGINT-1] */
8113 if (sig == SIGINT && !t)
8114 continue;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008115
8116 TRACE(("sig %d is active, will run handler '%s'\n", sig, t));
Denis Vlasenko4b875702009-03-19 13:30:04 +00008117 *g = 0;
8118 if (!t)
8119 continue;
8120 want_exexit = evalstring(t, SKIPEVAL);
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008121 exitstatus = savestatus;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008122 if (want_exexit) {
Denis Vlasenkob21f3792009-03-19 23:09:58 +00008123 TRACE(("dotrap returns %d\n", want_exexit));
Denis Vlasenko4b875702009-03-19 13:30:04 +00008124 return want_exexit;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008125 }
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008126 }
8127
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008128 TRACE(("dotrap returns 0\n"));
Denis Vlasenko991a1da2008-02-10 19:02:53 +00008129 return 0;
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008130}
8131
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00008132/* forward declarations - evaluation is fairly recursive business... */
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008133static void evalloop(union node *, int);
8134static void evalfor(union node *, int);
8135static void evalcase(union node *, int);
8136static void evalsubshell(union node *, int);
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00008137static void expredir(union node *);
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008138static void evalpipe(union node *, int);
8139static void evalcommand(union node *, int);
Eric Andersenc470f442003-07-28 09:56:35 +00008140static int evalbltin(const struct builtincmd *, int, char **);
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008141static void prehash(union node *);
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00008142
Eric Andersen62483552001-07-10 06:09:16 +00008143/*
Eric Andersenc470f442003-07-28 09:56:35 +00008144 * Evaluate a parse tree. The value is left in the global variable
8145 * exitstatus.
Eric Andersen62483552001-07-10 06:09:16 +00008146 */
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008147static void
Eric Andersenc470f442003-07-28 09:56:35 +00008148evaltree(union node *n, int flags)
Eric Andersen62483552001-07-10 06:09:16 +00008149{
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008150 struct jmploc *volatile savehandler = exception_handler;
8151 struct jmploc jmploc;
Eric Andersenc470f442003-07-28 09:56:35 +00008152 int checkexit = 0;
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008153 void (*evalfn)(union node *, int);
Eric Andersenc470f442003-07-28 09:56:35 +00008154 int status;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008155 int int_level;
8156
8157 SAVE_INT(int_level);
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008158
Eric Andersenc470f442003-07-28 09:56:35 +00008159 if (n == NULL) {
8160 TRACE(("evaltree(NULL) called\n"));
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008161 goto out1;
Eric Andersen62483552001-07-10 06:09:16 +00008162 }
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008163 TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008164
8165 exception_handler = &jmploc;
8166 {
8167 int err = setjmp(jmploc.loc);
8168 if (err) {
8169 /* if it was a signal, check for trap handlers */
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008170 if (exception_type == EXSIG) {
Denis Vlasenkob21f3792009-03-19 23:09:58 +00008171 TRACE(("exception %d (EXSIG) in evaltree, err=%d\n",
8172 exception_type, err));
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008173 goto out;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008174 }
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008175 /* continue on the way out */
Denis Vlasenkob21f3792009-03-19 23:09:58 +00008176 TRACE(("exception %d in evaltree, propagating err=%d\n",
8177 exception_type, err));
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008178 exception_handler = savehandler;
8179 longjmp(exception_handler->loc, err);
8180 }
8181 }
8182
Eric Andersenc470f442003-07-28 09:56:35 +00008183 switch (n->type) {
8184 default:
Denis Vlasenkoa7189f02006-11-17 20:29:00 +00008185#if DEBUG
Eric Andersenc470f442003-07-28 09:56:35 +00008186 out1fmt("Node type = %d\n", n->type);
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00008187 fflush(stdout);
Eric Andersenc470f442003-07-28 09:56:35 +00008188 break;
8189#endif
8190 case NNOT:
8191 evaltree(n->nnot.com, EV_TESTED);
8192 status = !exitstatus;
8193 goto setstatus;
8194 case NREDIR:
8195 expredir(n->nredir.redirect);
8196 status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
8197 if (!status) {
8198 evaltree(n->nredir.n, flags & EV_TESTED);
8199 status = exitstatus;
8200 }
Denis Vlasenko34c73c42008-08-16 11:48:02 +00008201 popredir(/*drop:*/ 0, /*restore:*/ 0 /* not sure */);
Eric Andersenc470f442003-07-28 09:56:35 +00008202 goto setstatus;
8203 case NCMD:
8204 evalfn = evalcommand;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008205 checkexit:
Eric Andersenc470f442003-07-28 09:56:35 +00008206 if (eflag && !(flags & EV_TESTED))
8207 checkexit = ~0;
8208 goto calleval;
8209 case NFOR:
8210 evalfn = evalfor;
8211 goto calleval;
8212 case NWHILE:
8213 case NUNTIL:
8214 evalfn = evalloop;
8215 goto calleval;
8216 case NSUBSHELL:
8217 case NBACKGND:
8218 evalfn = evalsubshell;
8219 goto calleval;
8220 case NPIPE:
8221 evalfn = evalpipe;
8222 goto checkexit;
8223 case NCASE:
8224 evalfn = evalcase;
8225 goto calleval;
8226 case NAND:
8227 case NOR:
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008228 case NSEMI: {
8229
Eric Andersenc470f442003-07-28 09:56:35 +00008230#if NAND + 1 != NOR
8231#error NAND + 1 != NOR
8232#endif
8233#if NOR + 1 != NSEMI
8234#error NOR + 1 != NSEMI
8235#endif
Denis Vlasenko87d5fd92008-07-26 13:48:35 +00008236 unsigned is_or = n->type - NAND;
Eric Andersenc470f442003-07-28 09:56:35 +00008237 evaltree(
8238 n->nbinary.ch1,
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008239 (flags | ((is_or >> 1) - 1)) & EV_TESTED
Eric Andersenc470f442003-07-28 09:56:35 +00008240 );
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008241 if (!exitstatus == is_or)
Eric Andersenc470f442003-07-28 09:56:35 +00008242 break;
8243 if (!evalskip) {
8244 n = n->nbinary.ch2;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008245 evaln:
Eric Andersenc470f442003-07-28 09:56:35 +00008246 evalfn = evaltree;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008247 calleval:
Eric Andersenc470f442003-07-28 09:56:35 +00008248 evalfn(n, flags);
8249 break;
8250 }
8251 break;
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008252 }
Eric Andersenc470f442003-07-28 09:56:35 +00008253 case NIF:
8254 evaltree(n->nif.test, EV_TESTED);
8255 if (evalskip)
8256 break;
8257 if (exitstatus == 0) {
8258 n = n->nif.ifpart;
8259 goto evaln;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008260 }
8261 if (n->nif.elsepart) {
Eric Andersenc470f442003-07-28 09:56:35 +00008262 n = n->nif.elsepart;
8263 goto evaln;
8264 }
8265 goto success;
8266 case NDEFUN:
8267 defun(n->narg.text, n->narg.next);
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008268 success:
Eric Andersenc470f442003-07-28 09:56:35 +00008269 status = 0;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008270 setstatus:
Eric Andersenc470f442003-07-28 09:56:35 +00008271 exitstatus = status;
8272 break;
8273 }
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008274
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008275 out:
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008276 exception_handler = savehandler;
8277 out1:
8278 if (checkexit & exitstatus)
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00008279 evalskip |= SKIPEVAL;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02008280 else if (pending_sig && dotrap())
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00008281 goto exexit;
8282
8283 if (flags & EV_EXIT) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008284 exexit:
Denis Vlasenkob012b102007-02-19 22:43:01 +00008285 raise_exception(EXEXIT);
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00008286 }
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008287
8288 RESTORE_INT(int_level);
8289 TRACE(("leaving evaltree (no interrupts)\n"));
Eric Andersen62483552001-07-10 06:09:16 +00008290}
8291
Eric Andersenc470f442003-07-28 09:56:35 +00008292#if !defined(__alpha__) || (defined(__GNUC__) && __GNUC__ >= 3)
8293static
8294#endif
8295void evaltreenr(union node *, int) __attribute__ ((alias("evaltree"),__noreturn__));
8296
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008297static void
Eric Andersenc470f442003-07-28 09:56:35 +00008298evalloop(union node *n, int flags)
Eric Andersencb57d552001-06-28 07:25:16 +00008299{
8300 int status;
8301
8302 loopnest++;
8303 status = 0;
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008304 flags &= EV_TESTED;
Eric Andersencb57d552001-06-28 07:25:16 +00008305 for (;;) {
Eric Andersenc470f442003-07-28 09:56:35 +00008306 int i;
8307
Eric Andersencb57d552001-06-28 07:25:16 +00008308 evaltree(n->nbinary.ch1, EV_TESTED);
8309 if (evalskip) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008310 skipping:
8311 if (evalskip == SKIPCONT && --skipcount <= 0) {
Eric Andersencb57d552001-06-28 07:25:16 +00008312 evalskip = 0;
8313 continue;
8314 }
8315 if (evalskip == SKIPBREAK && --skipcount <= 0)
8316 evalskip = 0;
8317 break;
8318 }
Eric Andersenc470f442003-07-28 09:56:35 +00008319 i = exitstatus;
8320 if (n->type != NWHILE)
8321 i = !i;
8322 if (i != 0)
8323 break;
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008324 evaltree(n->nbinary.ch2, flags);
Eric Andersencb57d552001-06-28 07:25:16 +00008325 status = exitstatus;
8326 if (evalskip)
8327 goto skipping;
8328 }
8329 loopnest--;
8330 exitstatus = status;
8331}
8332
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008333static void
Eric Andersenc470f442003-07-28 09:56:35 +00008334evalfor(union node *n, int flags)
Eric Andersencb57d552001-06-28 07:25:16 +00008335{
8336 struct arglist arglist;
8337 union node *argp;
8338 struct strlist *sp;
8339 struct stackmark smark;
8340
8341 setstackmark(&smark);
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00008342 arglist.list = NULL;
Eric Andersencb57d552001-06-28 07:25:16 +00008343 arglist.lastp = &arglist.list;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008344 for (argp = n->nfor.args; argp; argp = argp->narg.next) {
Eric Andersencb57d552001-06-28 07:25:16 +00008345 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE | EXP_RECORD);
Eric Andersenc470f442003-07-28 09:56:35 +00008346 /* XXX */
Eric Andersencb57d552001-06-28 07:25:16 +00008347 if (evalskip)
8348 goto out;
8349 }
8350 *arglist.lastp = NULL;
8351
8352 exitstatus = 0;
8353 loopnest++;
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008354 flags &= EV_TESTED;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008355 for (sp = arglist.list; sp; sp = sp->next) {
Eric Andersencb57d552001-06-28 07:25:16 +00008356 setvar(n->nfor.var, sp->text, 0);
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008357 evaltree(n->nfor.body, flags);
Eric Andersencb57d552001-06-28 07:25:16 +00008358 if (evalskip) {
8359 if (evalskip == SKIPCONT && --skipcount <= 0) {
8360 evalskip = 0;
8361 continue;
8362 }
8363 if (evalskip == SKIPBREAK && --skipcount <= 0)
8364 evalskip = 0;
8365 break;
8366 }
8367 }
8368 loopnest--;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008369 out:
Eric Andersencb57d552001-06-28 07:25:16 +00008370 popstackmark(&smark);
8371}
8372
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008373static void
Eric Andersenc470f442003-07-28 09:56:35 +00008374evalcase(union node *n, int flags)
Eric Andersencb57d552001-06-28 07:25:16 +00008375{
8376 union node *cp;
8377 union node *patp;
8378 struct arglist arglist;
8379 struct stackmark smark;
8380
8381 setstackmark(&smark);
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00008382 arglist.list = NULL;
Eric Andersencb57d552001-06-28 07:25:16 +00008383 arglist.lastp = &arglist.list;
Eric Andersencb57d552001-06-28 07:25:16 +00008384 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
Eric Andersenc470f442003-07-28 09:56:35 +00008385 exitstatus = 0;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008386 for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
8387 for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
Eric Andersencb57d552001-06-28 07:25:16 +00008388 if (casematch(patp, arglist.list->text)) {
8389 if (evalskip == 0) {
8390 evaltree(cp->nclist.body, flags);
8391 }
8392 goto out;
8393 }
8394 }
8395 }
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008396 out:
Eric Andersencb57d552001-06-28 07:25:16 +00008397 popstackmark(&smark);
8398}
8399
Eric Andersenc470f442003-07-28 09:56:35 +00008400/*
8401 * Kick off a subshell to evaluate a tree.
8402 */
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008403static void
Eric Andersenc470f442003-07-28 09:56:35 +00008404evalsubshell(union node *n, int flags)
8405{
8406 struct job *jp;
8407 int backgnd = (n->type == NBACKGND);
8408 int status;
8409
8410 expredir(n->nredir.redirect);
8411 if (!backgnd && flags & EV_EXIT && !trap[0])
8412 goto nofork;
Denis Vlasenkob012b102007-02-19 22:43:01 +00008413 INT_OFF;
Denis Vlasenko68404f12008-03-17 09:00:54 +00008414 jp = makejob(/*n,*/ 1);
Eric Andersenc470f442003-07-28 09:56:35 +00008415 if (forkshell(jp, n, backgnd) == 0) {
Denis Vlasenkob012b102007-02-19 22:43:01 +00008416 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00008417 flags |= EV_EXIT;
8418 if (backgnd)
8419 flags &=~ EV_TESTED;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00008420 nofork:
Eric Andersenc470f442003-07-28 09:56:35 +00008421 redirect(n->nredir.redirect, 0);
8422 evaltreenr(n->nredir.n, flags);
8423 /* never returns */
8424 }
8425 status = 0;
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00008426 if (!backgnd)
Eric Andersenc470f442003-07-28 09:56:35 +00008427 status = waitforjob(jp);
8428 exitstatus = status;
Denis Vlasenkob012b102007-02-19 22:43:01 +00008429 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00008430}
8431
Eric Andersenc470f442003-07-28 09:56:35 +00008432/*
8433 * Compute the names of the files in a redirection list.
8434 */
Denis Vlasenko99eb8502007-02-23 21:09:49 +00008435static void fixredir(union node *, const char *, int);
Eric Andersenc470f442003-07-28 09:56:35 +00008436static void
8437expredir(union node *n)
8438{
8439 union node *redir;
8440
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008441 for (redir = n; redir; redir = redir->nfile.next) {
Eric Andersenc470f442003-07-28 09:56:35 +00008442 struct arglist fn;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008443
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00008444 fn.list = NULL;
Eric Andersenc470f442003-07-28 09:56:35 +00008445 fn.lastp = &fn.list;
8446 switch (redir->type) {
8447 case NFROMTO:
8448 case NFROM:
8449 case NTO:
Denis Vlasenko559691a2008-10-05 18:39:31 +00008450#if ENABLE_ASH_BASH_COMPAT
8451 case NTO2:
8452#endif
Eric Andersenc470f442003-07-28 09:56:35 +00008453 case NCLOBBER:
8454 case NAPPEND:
8455 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
Denis Vlasenko559691a2008-10-05 18:39:31 +00008456#if ENABLE_ASH_BASH_COMPAT
8457 store_expfname:
8458#endif
Eric Andersenc470f442003-07-28 09:56:35 +00008459 redir->nfile.expfname = fn.list->text;
8460 break;
8461 case NFROMFD:
Denis Vlasenko559691a2008-10-05 18:39:31 +00008462 case NTOFD: /* >& */
Eric Andersenc470f442003-07-28 09:56:35 +00008463 if (redir->ndup.vname) {
8464 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008465 if (fn.list == NULL)
Denis Vlasenkob012b102007-02-19 22:43:01 +00008466 ash_msg_and_raise_error("redir error");
Denis Vlasenko559691a2008-10-05 18:39:31 +00008467#if ENABLE_ASH_BASH_COMPAT
8468//FIXME: we used expandarg with different args!
8469 if (!isdigit_str9(fn.list->text)) {
8470 /* >&file, not >&fd */
8471 if (redir->nfile.fd != 1) /* 123>&file - BAD */
8472 ash_msg_and_raise_error("redir error");
8473 redir->type = NTO2;
8474 goto store_expfname;
8475 }
8476#endif
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008477 fixredir(redir, fn.list->text, 1);
Eric Andersenc470f442003-07-28 09:56:35 +00008478 }
8479 break;
8480 }
8481 }
8482}
8483
Eric Andersencb57d552001-06-28 07:25:16 +00008484/*
Eric Andersencb57d552001-06-28 07:25:16 +00008485 * Evaluate a pipeline. All the processes in the pipeline are children
8486 * of the process creating the pipeline. (This differs from some versions
8487 * of the shell, which make the last process in a pipeline the parent
8488 * of all the rest.)
8489 */
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008490static void
Eric Andersenc470f442003-07-28 09:56:35 +00008491evalpipe(union node *n, int flags)
Eric Andersencb57d552001-06-28 07:25:16 +00008492{
8493 struct job *jp;
8494 struct nodelist *lp;
8495 int pipelen;
8496 int prevfd;
8497 int pip[2];
8498
Eric Andersenc470f442003-07-28 09:56:35 +00008499 TRACE(("evalpipe(0x%lx) called\n", (long)n));
Eric Andersencb57d552001-06-28 07:25:16 +00008500 pipelen = 0;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008501 for (lp = n->npipe.cmdlist; lp; lp = lp->next)
Eric Andersencb57d552001-06-28 07:25:16 +00008502 pipelen++;
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008503 flags |= EV_EXIT;
Denis Vlasenkob012b102007-02-19 22:43:01 +00008504 INT_OFF;
Denis Vlasenko68404f12008-03-17 09:00:54 +00008505 jp = makejob(/*n,*/ pipelen);
Eric Andersencb57d552001-06-28 07:25:16 +00008506 prevfd = -1;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008507 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008508 prehash(lp->n);
Eric Andersencb57d552001-06-28 07:25:16 +00008509 pip[1] = -1;
8510 if (lp->next) {
8511 if (pipe(pip) < 0) {
8512 close(prevfd);
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00008513 ash_msg_and_raise_error("pipe call failed");
Eric Andersencb57d552001-06-28 07:25:16 +00008514 }
8515 }
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00008516 if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
Denis Vlasenkob012b102007-02-19 22:43:01 +00008517 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00008518 if (pip[1] >= 0) {
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008519 close(pip[0]);
Eric Andersencb57d552001-06-28 07:25:16 +00008520 }
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008521 if (prevfd > 0) {
8522 dup2(prevfd, 0);
8523 close(prevfd);
8524 }
8525 if (pip[1] > 1) {
8526 dup2(pip[1], 1);
8527 close(pip[1]);
8528 }
Eric Andersenc470f442003-07-28 09:56:35 +00008529 evaltreenr(lp->n, flags);
8530 /* never returns */
Eric Andersencb57d552001-06-28 07:25:16 +00008531 }
8532 if (prevfd >= 0)
8533 close(prevfd);
8534 prevfd = pip[0];
Denis Vlasenkob9e70dd2009-03-20 01:24:08 +00008535 /* Don't want to trigger debugging */
8536 if (pip[1] != -1)
8537 close(pip[1]);
Eric Andersencb57d552001-06-28 07:25:16 +00008538 }
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00008539 if (n->npipe.pipe_backgnd == 0) {
Eric Andersencb57d552001-06-28 07:25:16 +00008540 exitstatus = waitforjob(jp);
8541 TRACE(("evalpipe: job done exit status %d\n", exitstatus));
Eric Andersencb57d552001-06-28 07:25:16 +00008542 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00008543 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00008544}
8545
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008546/*
8547 * Controls whether the shell is interactive or not.
8548 */
8549static void
8550setinteractive(int on)
8551{
Denis Vlasenkob07a4962008-06-22 13:16:23 +00008552 static smallint is_interactive;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008553
8554 if (++on == is_interactive)
8555 return;
8556 is_interactive = on;
8557 setsignal(SIGINT);
8558 setsignal(SIGQUIT);
8559 setsignal(SIGTERM);
8560#if !ENABLE_FEATURE_SH_EXTRA_QUIET
8561 if (is_interactive > 1) {
8562 /* Looks like they want an interactive shell */
Denis Vlasenkoca525b42007-06-13 12:27:17 +00008563 static smallint did_banner;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008564
Denis Vlasenkoca525b42007-06-13 12:27:17 +00008565 if (!did_banner) {
Denys Vlasenkoc34c0332009-09-29 12:25:30 +02008566 /* note: ash and hush share this string */
8567 out1fmt("\n\n%s %s\n"
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008568 "Enter 'help' for a list of built-in commands."
8569 "\n\n",
Denys Vlasenkoc34c0332009-09-29 12:25:30 +02008570 bb_banner,
8571 "built-in shell (ash)"
8572 );
Denis Vlasenkoca525b42007-06-13 12:27:17 +00008573 did_banner = 1;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008574 }
8575 }
8576#endif
8577}
8578
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008579static void
8580optschanged(void)
8581{
8582#if DEBUG
8583 opentrace();
8584#endif
8585 setinteractive(iflag);
8586 setjobctl(mflag);
Denis Vlasenkob07a4962008-06-22 13:16:23 +00008587#if ENABLE_FEATURE_EDITING_VI
8588 if (viflag)
8589 line_input_state->flags |= VI_MODE;
8590 else
8591 line_input_state->flags &= ~VI_MODE;
8592#else
8593 viflag = 0; /* forcibly keep the option off */
8594#endif
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008595}
8596
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008597static struct localvar *localvars;
8598
8599/*
8600 * Called after a function returns.
8601 * Interrupts must be off.
8602 */
8603static void
8604poplocalvars(void)
8605{
8606 struct localvar *lvp;
8607 struct var *vp;
8608
8609 while ((lvp = localvars) != NULL) {
8610 localvars = lvp->next;
8611 vp = lvp->vp;
Denys Vlasenko883cea42009-07-11 15:31:59 +02008612 TRACE(("poplocalvar %s\n", vp ? vp->text : "-"));
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008613 if (vp == NULL) { /* $- saved */
8614 memcpy(optlist, lvp->text, sizeof(optlist));
8615 free((char*)lvp->text);
8616 optschanged();
8617 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
8618 unsetvar(vp->text);
8619 } else {
8620 if (vp->func)
8621 (*vp->func)(strchrnul(lvp->text, '=') + 1);
8622 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
8623 free((char*)vp->text);
8624 vp->flags = lvp->flags;
8625 vp->text = lvp->text;
8626 }
8627 free(lvp);
8628 }
8629}
8630
8631static int
8632evalfun(struct funcnode *func, int argc, char **argv, int flags)
8633{
8634 volatile struct shparam saveparam;
8635 struct localvar *volatile savelocalvars;
8636 struct jmploc *volatile savehandler;
8637 struct jmploc jmploc;
8638 int e;
8639
8640 saveparam = shellparam;
8641 savelocalvars = localvars;
8642 e = setjmp(jmploc.loc);
8643 if (e) {
8644 goto funcdone;
8645 }
8646 INT_OFF;
8647 savehandler = exception_handler;
8648 exception_handler = &jmploc;
8649 localvars = NULL;
Denis Vlasenko01631112007-12-16 17:20:38 +00008650 shellparam.malloced = 0;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008651 func->count++;
8652 funcnest++;
8653 INT_ON;
8654 shellparam.nparam = argc - 1;
8655 shellparam.p = argv + 1;
8656#if ENABLE_ASH_GETOPTS
8657 shellparam.optind = 1;
8658 shellparam.optoff = -1;
8659#endif
8660 evaltree(&func->n, flags & EV_TESTED);
Denis Vlasenko01631112007-12-16 17:20:38 +00008661 funcdone:
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008662 INT_OFF;
8663 funcnest--;
8664 freefunc(func);
8665 poplocalvars();
8666 localvars = savelocalvars;
8667 freeparam(&shellparam);
8668 shellparam = saveparam;
8669 exception_handler = savehandler;
8670 INT_ON;
8671 evalskip &= ~SKIPFUNC;
8672 return e;
8673}
8674
Denis Vlasenko131ae172007-02-18 13:00:19 +00008675#if ENABLE_ASH_CMDCMD
Denis Vlasenkoaa744452007-02-23 01:04:22 +00008676static char **
8677parse_command_args(char **argv, const char **path)
Eric Andersenc470f442003-07-28 09:56:35 +00008678{
8679 char *cp, c;
8680
8681 for (;;) {
8682 cp = *++argv;
8683 if (!cp)
8684 return 0;
8685 if (*cp++ != '-')
8686 break;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008687 c = *cp++;
8688 if (!c)
Eric Andersenc470f442003-07-28 09:56:35 +00008689 break;
8690 if (c == '-' && !*cp) {
8691 argv++;
8692 break;
8693 }
8694 do {
8695 switch (c) {
8696 case 'p':
Denis Vlasenkof5f75c52007-06-12 22:35:19 +00008697 *path = bb_default_path;
Eric Andersenc470f442003-07-28 09:56:35 +00008698 break;
8699 default:
8700 /* run 'typecmd' for other options */
8701 return 0;
8702 }
Denis Vlasenko9650f362007-02-23 01:04:37 +00008703 c = *cp++;
8704 } while (c);
Eric Andersenc470f442003-07-28 09:56:35 +00008705 }
8706 return argv;
8707}
8708#endif
8709
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008710/*
8711 * Make a variable a local variable. When a variable is made local, it's
8712 * value and flags are saved in a localvar structure. The saved values
8713 * will be restored when the shell function returns. We handle the name
8714 * "-" as a special case.
8715 */
8716static void
8717mklocal(char *name)
8718{
8719 struct localvar *lvp;
8720 struct var **vpp;
8721 struct var *vp;
8722
8723 INT_OFF;
Denis Vlasenko838ffd52008-02-21 04:32:08 +00008724 lvp = ckzalloc(sizeof(struct localvar));
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008725 if (LONE_DASH(name)) {
8726 char *p;
8727 p = ckmalloc(sizeof(optlist));
8728 lvp->text = memcpy(p, optlist, sizeof(optlist));
8729 vp = NULL;
8730 } else {
8731 char *eq;
8732
8733 vpp = hashvar(name);
8734 vp = *findvar(vpp, name);
8735 eq = strchr(name, '=');
8736 if (vp == NULL) {
8737 if (eq)
8738 setvareq(name, VSTRFIXED);
8739 else
8740 setvar(name, NULL, VSTRFIXED);
8741 vp = *vpp; /* the new variable */
8742 lvp->flags = VUNSET;
8743 } else {
8744 lvp->text = vp->text;
8745 lvp->flags = vp->flags;
8746 vp->flags |= VSTRFIXED|VTEXTFIXED;
8747 if (eq)
8748 setvareq(name, 0);
8749 }
8750 }
8751 lvp->vp = vp;
8752 lvp->next = localvars;
8753 localvars = lvp;
8754 INT_ON;
8755}
8756
8757/*
8758 * The "local" command.
8759 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008760static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008761localcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008762{
8763 char *name;
8764
8765 argv = argptr;
8766 while ((name = *argv++) != NULL) {
8767 mklocal(name);
8768 }
8769 return 0;
8770}
8771
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008772static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008773falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008774{
8775 return 1;
8776}
8777
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008778static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008779truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008780{
8781 return 0;
8782}
8783
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008784static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008785execcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008786{
Denis Vlasenko68404f12008-03-17 09:00:54 +00008787 if (argv[1]) {
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008788 iflag = 0; /* exit on error */
8789 mflag = 0;
8790 optschanged();
8791 shellexec(argv + 1, pathval(), 0);
8792 }
8793 return 0;
8794}
8795
8796/*
8797 * The return command.
8798 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008799static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008800returncmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008801{
8802 /*
8803 * If called outside a function, do what ksh does;
8804 * skip the rest of the file.
8805 */
8806 evalskip = funcnest ? SKIPFUNC : SKIPFILE;
8807 return argv[1] ? number(argv[1]) : exitstatus;
8808}
8809
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008810/* Forward declarations for builtintab[] */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008811static int breakcmd(int, char **) FAST_FUNC;
8812static int dotcmd(int, char **) FAST_FUNC;
8813static int evalcmd(int, char **) FAST_FUNC;
8814static int exitcmd(int, char **) FAST_FUNC;
8815static int exportcmd(int, char **) FAST_FUNC;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008816#if ENABLE_ASH_GETOPTS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008817static int getoptscmd(int, char **) FAST_FUNC;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008818#endif
Denis Vlasenko52764022007-02-24 13:42:56 +00008819#if !ENABLE_FEATURE_SH_EXTRA_QUIET
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008820static int helpcmd(int, char **) FAST_FUNC;
Denis Vlasenko52764022007-02-24 13:42:56 +00008821#endif
Mike Frysinger98c52642009-04-02 10:02:37 +00008822#if ENABLE_SH_MATH_SUPPORT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008823static int letcmd(int, char **) FAST_FUNC;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008824#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008825static int readcmd(int, char **) FAST_FUNC;
8826static int setcmd(int, char **) FAST_FUNC;
8827static int shiftcmd(int, char **) FAST_FUNC;
8828static int timescmd(int, char **) FAST_FUNC;
8829static int trapcmd(int, char **) FAST_FUNC;
8830static int umaskcmd(int, char **) FAST_FUNC;
8831static int unsetcmd(int, char **) FAST_FUNC;
8832static int ulimitcmd(int, char **) FAST_FUNC;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008833
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008834#define BUILTIN_NOSPEC "0"
8835#define BUILTIN_SPECIAL "1"
8836#define BUILTIN_REGULAR "2"
8837#define BUILTIN_SPEC_REG "3"
8838#define BUILTIN_ASSIGN "4"
8839#define BUILTIN_SPEC_ASSG "5"
8840#define BUILTIN_REG_ASSG "6"
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008841#define BUILTIN_SPEC_REG_ASSG "7"
8842
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008843/* Stubs for calling non-FAST_FUNC's */
Denys Vlasenko2634bf32009-06-09 18:40:07 +02008844#if ENABLE_ASH_BUILTIN_ECHO
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008845static int FAST_FUNC echocmd(int argc, char **argv) { return echo_main(argc, argv); }
Denys Vlasenko2634bf32009-06-09 18:40:07 +02008846#endif
8847#if ENABLE_ASH_BUILTIN_PRINTF
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008848static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
Denys Vlasenko2634bf32009-06-09 18:40:07 +02008849#endif
8850#if ENABLE_ASH_BUILTIN_TEST
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008851static int FAST_FUNC testcmd(int argc, char **argv) { return test_main(argc, argv); }
Denys Vlasenko2634bf32009-06-09 18:40:07 +02008852#endif
Denis Vlasenko468aea22008-04-01 14:47:57 +00008853
Denis Vlasenkof7d56652008-03-25 05:51:41 +00008854/* Keep these in proper order since it is searched via bsearch() */
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008855static const struct builtincmd builtintab[] = {
8856 { BUILTIN_SPEC_REG ".", dotcmd },
8857 { BUILTIN_SPEC_REG ":", truecmd },
8858#if ENABLE_ASH_BUILTIN_TEST
Denis Vlasenkocd2663f2008-06-01 22:36:39 +00008859 { BUILTIN_REGULAR "[", testcmd },
Denis Vlasenko80591b02008-03-25 07:49:43 +00008860#if ENABLE_ASH_BASH_COMPAT
Denis Vlasenkocd2663f2008-06-01 22:36:39 +00008861 { BUILTIN_REGULAR "[[", testcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008862#endif
Denis Vlasenko80591b02008-03-25 07:49:43 +00008863#endif
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008864#if ENABLE_ASH_ALIAS
8865 { BUILTIN_REG_ASSG "alias", aliascmd },
8866#endif
8867#if JOBS
8868 { BUILTIN_REGULAR "bg", fg_bgcmd },
8869#endif
8870 { BUILTIN_SPEC_REG "break", breakcmd },
8871 { BUILTIN_REGULAR "cd", cdcmd },
8872 { BUILTIN_NOSPEC "chdir", cdcmd },
8873#if ENABLE_ASH_CMDCMD
8874 { BUILTIN_REGULAR "command", commandcmd },
8875#endif
8876 { BUILTIN_SPEC_REG "continue", breakcmd },
8877#if ENABLE_ASH_BUILTIN_ECHO
8878 { BUILTIN_REGULAR "echo", echocmd },
8879#endif
8880 { BUILTIN_SPEC_REG "eval", evalcmd },
8881 { BUILTIN_SPEC_REG "exec", execcmd },
8882 { BUILTIN_SPEC_REG "exit", exitcmd },
8883 { BUILTIN_SPEC_REG_ASSG "export", exportcmd },
8884 { BUILTIN_REGULAR "false", falsecmd },
8885#if JOBS
8886 { BUILTIN_REGULAR "fg", fg_bgcmd },
8887#endif
8888#if ENABLE_ASH_GETOPTS
8889 { BUILTIN_REGULAR "getopts", getoptscmd },
8890#endif
8891 { BUILTIN_NOSPEC "hash", hashcmd },
8892#if !ENABLE_FEATURE_SH_EXTRA_QUIET
8893 { BUILTIN_NOSPEC "help", helpcmd },
8894#endif
8895#if JOBS
8896 { BUILTIN_REGULAR "jobs", jobscmd },
8897 { BUILTIN_REGULAR "kill", killcmd },
8898#endif
Mike Frysinger98c52642009-04-02 10:02:37 +00008899#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008900 { BUILTIN_NOSPEC "let", letcmd },
8901#endif
8902 { BUILTIN_ASSIGN "local", localcmd },
Denis Vlasenkocd2663f2008-06-01 22:36:39 +00008903#if ENABLE_ASH_BUILTIN_PRINTF
8904 { BUILTIN_REGULAR "printf", printfcmd },
8905#endif
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008906 { BUILTIN_NOSPEC "pwd", pwdcmd },
8907 { BUILTIN_REGULAR "read", readcmd },
8908 { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
8909 { BUILTIN_SPEC_REG "return", returncmd },
8910 { BUILTIN_SPEC_REG "set", setcmd },
8911 { BUILTIN_SPEC_REG "shift", shiftcmd },
8912 { BUILTIN_SPEC_REG "source", dotcmd },
8913#if ENABLE_ASH_BUILTIN_TEST
Denis Vlasenkocd2663f2008-06-01 22:36:39 +00008914 { BUILTIN_REGULAR "test", testcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008915#endif
8916 { BUILTIN_SPEC_REG "times", timescmd },
8917 { BUILTIN_SPEC_REG "trap", trapcmd },
8918 { BUILTIN_REGULAR "true", truecmd },
8919 { BUILTIN_NOSPEC "type", typecmd },
8920 { BUILTIN_NOSPEC "ulimit", ulimitcmd },
8921 { BUILTIN_REGULAR "umask", umaskcmd },
8922#if ENABLE_ASH_ALIAS
8923 { BUILTIN_REGULAR "unalias", unaliascmd },
8924#endif
8925 { BUILTIN_SPEC_REG "unset", unsetcmd },
8926 { BUILTIN_REGULAR "wait", waitcmd },
8927};
8928
Denis Vlasenko80591b02008-03-25 07:49:43 +00008929/* Should match the above table! */
8930#define COMMANDCMD (builtintab + \
8931 2 + \
8932 1 * ENABLE_ASH_BUILTIN_TEST + \
8933 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
8934 1 * ENABLE_ASH_ALIAS + \
8935 1 * ENABLE_ASH_JOB_CONTROL + \
8936 3)
8937#define EXECCMD (builtintab + \
8938 2 + \
8939 1 * ENABLE_ASH_BUILTIN_TEST + \
8940 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
8941 1 * ENABLE_ASH_ALIAS + \
8942 1 * ENABLE_ASH_JOB_CONTROL + \
8943 3 + \
8944 1 * ENABLE_ASH_CMDCMD + \
8945 1 + \
8946 ENABLE_ASH_BUILTIN_ECHO + \
8947 1)
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008948
8949/*
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008950 * Search the table of builtin commands.
8951 */
8952static struct builtincmd *
8953find_builtin(const char *name)
8954{
8955 struct builtincmd *bp;
8956
8957 bp = bsearch(
Denis Vlasenko80b8b392007-06-25 10:55:35 +00008958 name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008959 pstrcmp
8960 );
8961 return bp;
8962}
8963
8964/*
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008965 * Execute a simple command.
8966 */
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008967static int
8968isassignment(const char *p)
Paul Foxc3850c82005-07-20 18:23:39 +00008969{
8970 const char *q = endofname(p);
8971 if (p == q)
8972 return 0;
8973 return *q == '=';
8974}
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008975static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008976bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008977{
8978 /* Preserve exitstatus of a previous possible redirection
8979 * as POSIX mandates */
8980 return back_exitstatus;
8981}
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008982static void
Eric Andersenc470f442003-07-28 09:56:35 +00008983evalcommand(union node *cmd, int flags)
8984{
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00008985 static const struct builtincmd null_bltin = {
8986 "\0\0", bltincmd /* why three NULs? */
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008987 };
Eric Andersenc470f442003-07-28 09:56:35 +00008988 struct stackmark smark;
8989 union node *argp;
8990 struct arglist arglist;
8991 struct arglist varlist;
8992 char **argv;
8993 int argc;
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00008994 const struct strlist *sp;
Eric Andersenc470f442003-07-28 09:56:35 +00008995 struct cmdentry cmdentry;
8996 struct job *jp;
8997 char *lastarg;
8998 const char *path;
8999 int spclbltin;
Eric Andersenc470f442003-07-28 09:56:35 +00009000 int status;
9001 char **nargv;
Paul Foxc3850c82005-07-20 18:23:39 +00009002 struct builtincmd *bcmd;
Denis Vlasenko34c73c42008-08-16 11:48:02 +00009003 smallint cmd_is_exec;
9004 smallint pseudovarflag = 0;
Eric Andersenc470f442003-07-28 09:56:35 +00009005
9006 /* First expand the arguments. */
9007 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
9008 setstackmark(&smark);
9009 back_exitstatus = 0;
9010
9011 cmdentry.cmdtype = CMDBUILTIN;
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00009012 cmdentry.u.cmd = &null_bltin;
Eric Andersenc470f442003-07-28 09:56:35 +00009013 varlist.lastp = &varlist.list;
9014 *varlist.lastp = NULL;
9015 arglist.lastp = &arglist.list;
9016 *arglist.lastp = NULL;
9017
9018 argc = 0;
Denis Vlasenkob012b102007-02-19 22:43:01 +00009019 if (cmd->ncmd.args) {
Paul Foxc3850c82005-07-20 18:23:39 +00009020 bcmd = find_builtin(cmd->ncmd.args->narg.text);
9021 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
9022 }
9023
Eric Andersenc470f442003-07-28 09:56:35 +00009024 for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
9025 struct strlist **spp;
9026
9027 spp = arglist.lastp;
"Vladimir N. Oleynik"bef14d72005-09-05 13:25:11 +00009028 if (pseudovarflag && isassignment(argp->narg.text))
Paul Foxc3850c82005-07-20 18:23:39 +00009029 expandarg(argp, &arglist, EXP_VARTILDE);
9030 else
9031 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
9032
Eric Andersenc470f442003-07-28 09:56:35 +00009033 for (sp = *spp; sp; sp = sp->next)
9034 argc++;
9035 }
9036
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +00009037 argv = nargv = stalloc(sizeof(char *) * (argc + 1));
Denis Vlasenko2da584f2007-02-19 22:44:05 +00009038 for (sp = arglist.list; sp; sp = sp->next) {
Eric Andersenc470f442003-07-28 09:56:35 +00009039 TRACE(("evalcommand arg: %s\n", sp->text));
9040 *nargv++ = sp->text;
9041 }
9042 *nargv = NULL;
9043
9044 lastarg = NULL;
9045 if (iflag && funcnest == 0 && argc > 0)
9046 lastarg = nargv[-1];
9047
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009048 preverrout_fd = 2;
Eric Andersenc470f442003-07-28 09:56:35 +00009049 expredir(cmd->ncmd.redirect);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009050 status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
Eric Andersenc470f442003-07-28 09:56:35 +00009051
9052 path = vpath.text;
9053 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
9054 struct strlist **spp;
9055 char *p;
9056
9057 spp = varlist.lastp;
9058 expandarg(argp, &varlist, EXP_VARTILDE);
9059
9060 /*
9061 * Modify the command lookup path, if a PATH= assignment
9062 * is present
9063 */
9064 p = (*spp)->text;
9065 if (varequal(p, path))
9066 path = p;
9067 }
9068
9069 /* Print the command if xflag is set. */
9070 if (xflag) {
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009071 int n;
9072 const char *p = " %s";
Eric Andersenc470f442003-07-28 09:56:35 +00009073
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009074 p++;
Denis Vlasenko0de37e12007-10-17 11:08:53 +00009075 fdprintf(preverrout_fd, p, expandstr(ps4val()));
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009076
9077 sp = varlist.list;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +00009078 for (n = 0; n < 2; n++) {
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009079 while (sp) {
Denis Vlasenko0de37e12007-10-17 11:08:53 +00009080 fdprintf(preverrout_fd, p, sp->text);
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009081 sp = sp->next;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +00009082 if (*p == '%') {
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009083 p--;
9084 }
9085 }
9086 sp = arglist.list;
9087 }
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00009088 safe_write(preverrout_fd, "\n", 1);
Eric Andersenc470f442003-07-28 09:56:35 +00009089 }
9090
9091 cmd_is_exec = 0;
9092 spclbltin = -1;
9093
9094 /* Now locate the command. */
9095 if (argc) {
9096 const char *oldpath;
9097 int cmd_flag = DO_ERR;
9098
9099 path += 5;
9100 oldpath = path;
9101 for (;;) {
9102 find_command(argv[0], &cmdentry, cmd_flag, path);
9103 if (cmdentry.cmdtype == CMDUNKNOWN) {
Denis Vlasenkob012b102007-02-19 22:43:01 +00009104 flush_stderr();
Denis Vlasenko6514c5e2008-07-24 13:41:37 +00009105 status = 127;
Eric Andersenc470f442003-07-28 09:56:35 +00009106 goto bail;
9107 }
9108
9109 /* implement bltin and command here */
9110 if (cmdentry.cmdtype != CMDBUILTIN)
9111 break;
9112 if (spclbltin < 0)
9113 spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
9114 if (cmdentry.u.cmd == EXECCMD)
Denis Vlasenko34c73c42008-08-16 11:48:02 +00009115 cmd_is_exec = 1;
Denis Vlasenko131ae172007-02-18 13:00:19 +00009116#if ENABLE_ASH_CMDCMD
Eric Andersenc470f442003-07-28 09:56:35 +00009117 if (cmdentry.u.cmd == COMMANDCMD) {
Eric Andersenc470f442003-07-28 09:56:35 +00009118 path = oldpath;
9119 nargv = parse_command_args(argv, &path);
9120 if (!nargv)
9121 break;
9122 argc -= nargv - argv;
9123 argv = nargv;
9124 cmd_flag |= DO_NOFUNC;
9125 } else
9126#endif
9127 break;
9128 }
9129 }
9130
9131 if (status) {
9132 /* We have a redirection error. */
9133 if (spclbltin > 0)
Denis Vlasenkob012b102007-02-19 22:43:01 +00009134 raise_exception(EXERROR);
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009135 bail:
Eric Andersenc470f442003-07-28 09:56:35 +00009136 exitstatus = status;
9137 goto out;
9138 }
9139
9140 /* Execute the command. */
9141 switch (cmdentry.cmdtype) {
9142 default:
Denis Vlasenkobe54d6b2008-10-27 14:25:52 +00009143
Denis Vlasenko9bc80d72008-04-12 20:07:53 +00009144#if ENABLE_FEATURE_SH_NOFORK
Denis Vlasenkobe54d6b2008-10-27 14:25:52 +00009145/* Hmmm... shouldn't it happen somewhere in forkshell() instead?
9146 * Why "fork off a child process if necessary" doesn't apply to NOFORK? */
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00009147 {
9148 /* find_command() encodes applet_no as (-2 - applet_no) */
9149 int applet_no = (- cmdentry.u.index - 2);
Denis Vlasenko9bc80d72008-04-12 20:07:53 +00009150 if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
Denis Vlasenko9bc80d72008-04-12 20:07:53 +00009151 listsetvar(varlist.list, VEXPORT|VSTACK);
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00009152 /* run <applet>_main() */
9153 exitstatus = run_nofork_applet(applet_no, argv);
Denis Vlasenko9bc80d72008-04-12 20:07:53 +00009154 break;
9155 }
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00009156 }
Denis Vlasenko9bc80d72008-04-12 20:07:53 +00009157#endif
Eric Andersenc470f442003-07-28 09:56:35 +00009158 /* Fork off a child process if necessary. */
9159 if (!(flags & EV_EXIT) || trap[0]) {
Denis Vlasenkob012b102007-02-19 22:43:01 +00009160 INT_OFF;
Denis Vlasenko68404f12008-03-17 09:00:54 +00009161 jp = makejob(/*cmd,*/ 1);
Eric Andersenc470f442003-07-28 09:56:35 +00009162 if (forkshell(jp, cmd, FORK_FG) != 0) {
9163 exitstatus = waitforjob(jp);
Denis Vlasenkob012b102007-02-19 22:43:01 +00009164 INT_ON;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00009165 TRACE(("forked child exited with %d\n", exitstatus));
Eric Andersenc470f442003-07-28 09:56:35 +00009166 break;
9167 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00009168 FORCE_INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00009169 }
9170 listsetvar(varlist.list, VEXPORT|VSTACK);
9171 shellexec(argv, path, cmdentry.u.index);
9172 /* NOTREACHED */
9173
9174 case CMDBUILTIN:
9175 cmdenviron = varlist.list;
9176 if (cmdenviron) {
9177 struct strlist *list = cmdenviron;
9178 int i = VNOSET;
9179 if (spclbltin > 0 || argc == 0) {
9180 i = 0;
9181 if (cmd_is_exec && argc > 1)
9182 i = VEXPORT;
9183 }
9184 listsetvar(list, i);
9185 }
Denis Vlasenkobe54d6b2008-10-27 14:25:52 +00009186 /* Tight loop with builtins only:
9187 * "while kill -0 $child; do true; done"
9188 * will never exit even if $child died, unless we do this
9189 * to reap the zombie and make kill detect that it's gone: */
9190 dowait(DOWAIT_NONBLOCK, NULL);
9191
Eric Andersenc470f442003-07-28 09:56:35 +00009192 if (evalbltin(cmdentry.u.cmd, argc, argv)) {
9193 int exit_status;
Denis Vlasenko7f88e342009-03-19 03:36:18 +00009194 int i = exception_type;
Eric Andersenc470f442003-07-28 09:56:35 +00009195 if (i == EXEXIT)
9196 goto raise;
Eric Andersenc470f442003-07-28 09:56:35 +00009197 exit_status = 2;
Eric Andersenc470f442003-07-28 09:56:35 +00009198 if (i == EXINT)
Denis Vlasenko991a1da2008-02-10 19:02:53 +00009199 exit_status = 128 + SIGINT;
Eric Andersenc470f442003-07-28 09:56:35 +00009200 if (i == EXSIG)
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02009201 exit_status = 128 + pending_sig;
Eric Andersenc470f442003-07-28 09:56:35 +00009202 exitstatus = exit_status;
Eric Andersenc470f442003-07-28 09:56:35 +00009203 if (i == EXINT || spclbltin > 0) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009204 raise:
Denis Vlasenko2da584f2007-02-19 22:44:05 +00009205 longjmp(exception_handler->loc, 1);
Eric Andersenc470f442003-07-28 09:56:35 +00009206 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00009207 FORCE_INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00009208 }
9209 break;
9210
9211 case CMDFUNCTION:
9212 listsetvar(varlist.list, 0);
Denis Vlasenkobe54d6b2008-10-27 14:25:52 +00009213 /* See above for the rationale */
9214 dowait(DOWAIT_NONBLOCK, NULL);
Eric Andersenc470f442003-07-28 09:56:35 +00009215 if (evalfun(cmdentry.u.func, argc, argv, flags))
9216 goto raise;
9217 break;
9218 }
9219
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009220 out:
Denis Vlasenko34c73c42008-08-16 11:48:02 +00009221 popredir(/*drop:*/ cmd_is_exec, /*restore:*/ cmd_is_exec);
Denis Vlasenko6514c5e2008-07-24 13:41:37 +00009222 if (lastarg) {
Eric Andersenc470f442003-07-28 09:56:35 +00009223 /* dsl: I think this is intended to be used to support
9224 * '_' in 'vi' command mode during line editing...
9225 * However I implemented that within libedit itself.
9226 */
9227 setvar("_", lastarg, 0);
Denis Vlasenko6514c5e2008-07-24 13:41:37 +00009228 }
Eric Andersenc470f442003-07-28 09:56:35 +00009229 popstackmark(&smark);
9230}
9231
9232static int
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009233evalbltin(const struct builtincmd *cmd, int argc, char **argv)
9234{
Eric Andersenc470f442003-07-28 09:56:35 +00009235 char *volatile savecmdname;
9236 struct jmploc *volatile savehandler;
9237 struct jmploc jmploc;
9238 int i;
9239
9240 savecmdname = commandname;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009241 i = setjmp(jmploc.loc);
9242 if (i)
Eric Andersenc470f442003-07-28 09:56:35 +00009243 goto cmddone;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00009244 savehandler = exception_handler;
9245 exception_handler = &jmploc;
Eric Andersenc470f442003-07-28 09:56:35 +00009246 commandname = argv[0];
9247 argptr = argv + 1;
9248 optptr = NULL; /* initialize nextopt */
9249 exitstatus = (*cmd->builtin)(argc, argv);
Denis Vlasenkob012b102007-02-19 22:43:01 +00009250 flush_stdout_stderr();
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009251 cmddone:
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009252 exitstatus |= ferror(stdout);
Rob Landleyf296f0b2006-07-06 01:09:21 +00009253 clearerr(stdout);
Eric Andersenc470f442003-07-28 09:56:35 +00009254 commandname = savecmdname;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00009255 exception_handler = savehandler;
Eric Andersenc470f442003-07-28 09:56:35 +00009256
9257 return i;
9258}
9259
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009260static int
9261goodname(const char *p)
Glenn L McGrath16e45d72004-02-04 08:24:39 +00009262{
9263 return !*endofname(p);
9264}
9265
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009266
Glenn L McGrath50812ff2002-08-23 13:14:48 +00009267/*
9268 * Search for a command. This is called before we fork so that the
9269 * location of the command will be available in the parent as well as
Glenn L McGrath16e45d72004-02-04 08:24:39 +00009270 * the child. The check for "goodname" is an overly conservative
9271 * check that the name will not be subject to expansion.
Glenn L McGrath50812ff2002-08-23 13:14:48 +00009272 */
Eric Andersenc470f442003-07-28 09:56:35 +00009273static void
9274prehash(union node *n)
Glenn L McGrath50812ff2002-08-23 13:14:48 +00009275{
9276 struct cmdentry entry;
9277
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +00009278 if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
9279 find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
Glenn L McGrath50812ff2002-08-23 13:14:48 +00009280}
9281
Eric Andersencb57d552001-06-28 07:25:16 +00009282
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00009283/* ============ Builtin commands
9284 *
9285 * Builtin commands whose functions are closely tied to evaluation
9286 * are implemented here.
Eric Andersencb57d552001-06-28 07:25:16 +00009287 */
9288
9289/*
Eric Andersencb57d552001-06-28 07:25:16 +00009290 * Handle break and continue commands. Break, continue, and return are
9291 * all handled by setting the evalskip flag. The evaluation routines
9292 * above all check this flag, and if it is set they start skipping
9293 * commands rather than executing them. The variable skipcount is
9294 * the number of loops to break/continue, or the number of function
9295 * levels to return. (The latter is always 1.) It should probably
9296 * be an error to break out of more loops than exist, but it isn't
9297 * in the standard shell so we don't make it one here.
9298 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009299static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00009300breakcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +00009301{
Denis Vlasenko68404f12008-03-17 09:00:54 +00009302 int n = argv[1] ? number(argv[1]) : 1;
Eric Andersencb57d552001-06-28 07:25:16 +00009303
Aaron Lehmann2aef3a62001-12-31 06:03:12 +00009304 if (n <= 0)
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02009305 ash_msg_and_raise_error(msg_illnum, argv[1]);
Eric Andersencb57d552001-06-28 07:25:16 +00009306 if (n > loopnest)
9307 n = loopnest;
9308 if (n > 0) {
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00009309 evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
Eric Andersencb57d552001-06-28 07:25:16 +00009310 skipcount = n;
9311 }
9312 return 0;
9313}
9314
Eric Andersenc470f442003-07-28 09:56:35 +00009315
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009316/* ============ input.c
9317 *
Eric Andersen90898442003-08-06 11:20:52 +00009318 * This implements the input routines used by the parser.
Eric Andersencb57d552001-06-28 07:25:16 +00009319 */
Denis Vlasenko99eb8502007-02-23 21:09:49 +00009320
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009321enum {
9322 INPUT_PUSH_FILE = 1,
9323 INPUT_NOFILE_OK = 2,
9324};
Eric Andersencb57d552001-06-28 07:25:16 +00009325
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009326static smallint checkkwd;
Denis Vlasenko99eb8502007-02-23 21:09:49 +00009327/* values of checkkwd variable */
9328#define CHKALIAS 0x1
9329#define CHKKWD 0x2
9330#define CHKNL 0x4
9331
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009332/*
9333 * Push a string back onto the input at this current parsefile level.
9334 * We handle aliases this way.
9335 */
9336#if !ENABLE_ASH_ALIAS
9337#define pushstring(s, ap) pushstring(s)
9338#endif
9339static void
9340pushstring(char *s, struct alias *ap)
9341{
9342 struct strpush *sp;
9343 int len;
9344
9345 len = strlen(s);
9346 INT_OFF;
9347 if (g_parsefile->strpush) {
9348 sp = ckzalloc(sizeof(*sp));
9349 sp->prev = g_parsefile->strpush;
9350 } else {
9351 sp = &(g_parsefile->basestrpush);
9352 }
9353 g_parsefile->strpush = sp;
9354 sp->prev_string = g_parsefile->next_to_pgetc;
9355 sp->prev_left_in_line = g_parsefile->left_in_line;
9356#if ENABLE_ASH_ALIAS
9357 sp->ap = ap;
9358 if (ap) {
9359 ap->flag |= ALIASINUSE;
9360 sp->string = s;
9361 }
9362#endif
9363 g_parsefile->next_to_pgetc = s;
9364 g_parsefile->left_in_line = len;
9365 INT_ON;
9366}
9367
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009368static void
9369popstring(void)
Eric Andersenc470f442003-07-28 09:56:35 +00009370{
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009371 struct strpush *sp = g_parsefile->strpush;
Eric Andersenc470f442003-07-28 09:56:35 +00009372
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009373 INT_OFF;
Denis Vlasenko131ae172007-02-18 13:00:19 +00009374#if ENABLE_ASH_ALIAS
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009375 if (sp->ap) {
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009376 if (g_parsefile->next_to_pgetc[-1] == ' '
9377 || g_parsefile->next_to_pgetc[-1] == '\t'
9378 ) {
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009379 checkkwd |= CHKALIAS;
Glenn L McGrath28939ad2004-07-21 10:20:19 +00009380 }
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009381 if (sp->string != sp->ap->val) {
9382 free(sp->string);
9383 }
9384 sp->ap->flag &= ~ALIASINUSE;
9385 if (sp->ap->flag & ALIASDEAD) {
9386 unalias(sp->ap->name);
9387 }
Glenn L McGrath28939ad2004-07-21 10:20:19 +00009388 }
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009389#endif
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009390 g_parsefile->next_to_pgetc = sp->prev_string;
9391 g_parsefile->left_in_line = sp->prev_left_in_line;
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009392 g_parsefile->strpush = sp->prev;
9393 if (sp != &(g_parsefile->basestrpush))
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009394 free(sp);
9395 INT_ON;
9396}
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009397
Denis Vlasenkoe27dafd2008-11-28 04:01:03 +00009398//FIXME: BASH_COMPAT with "...&" does TWO pungetc():
9399//it peeks whether it is &>, and then pushes back both chars.
9400//This function needs to save last *next_to_pgetc to buf[0]
9401//to make two pungetc() reliable. Currently,
9402// pgetc (out of buf: does preadfd), pgetc, pungetc, pungetc won't work...
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009403static int
9404preadfd(void)
Eric Andersencb57d552001-06-28 07:25:16 +00009405{
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00009406 int nr;
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00009407 char *buf = g_parsefile->buf;
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00009408
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009409 g_parsefile->next_to_pgetc = buf;
Denis Vlasenko38f63192007-01-22 09:03:07 +00009410#if ENABLE_FEATURE_EDITING
Denis Vlasenko85c24712008-03-17 09:04:04 +00009411 retry:
Denis Vlasenko727752d2008-11-28 03:41:47 +00009412 if (!iflag || g_parsefile->fd != STDIN_FILENO)
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009413 nr = nonblock_safe_read(g_parsefile->fd, buf, BUFSIZ - 1);
Eric Andersenc470f442003-07-28 09:56:35 +00009414 else {
Denis Vlasenko38f63192007-01-22 09:03:07 +00009415#if ENABLE_FEATURE_TAB_COMPLETION
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009416 line_input_state->path_lookup = pathval();
Eric Andersen4a79c0e2004-09-08 10:01:07 +00009417#endif
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009418 nr = read_line_input(cmdedit_prompt, buf, BUFSIZ, line_input_state);
9419 if (nr == 0) {
9420 /* Ctrl+C pressed */
9421 if (trap[SIGINT]) {
Glenn L McGrath16e45d72004-02-04 08:24:39 +00009422 buf[0] = '\n';
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009423 buf[1] = '\0';
Glenn L McGrath16e45d72004-02-04 08:24:39 +00009424 raise(SIGINT);
9425 return 1;
9426 }
Eric Andersenc470f442003-07-28 09:56:35 +00009427 goto retry;
9428 }
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009429 if (nr < 0 && errno == 0) {
Denis Vlasenko9cb220b2007-12-09 10:03:28 +00009430 /* Ctrl+D pressed */
Eric Andersenc470f442003-07-28 09:56:35 +00009431 nr = 0;
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00009432 }
Eric Andersencb57d552001-06-28 07:25:16 +00009433 }
9434#else
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +00009435 nr = nonblock_safe_read(g_parsefile->fd, buf, BUFSIZ - 1);
Eric Andersencb57d552001-06-28 07:25:16 +00009436#endif
9437
Denis Vlasenkoe376d452008-02-20 22:23:24 +00009438#if 0
9439/* nonblock_safe_read() handles this problem */
Eric Andersencb57d552001-06-28 07:25:16 +00009440 if (nr < 0) {
Eric Andersencb57d552001-06-28 07:25:16 +00009441 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
Denis Vlasenkod37f2222007-08-19 13:42:08 +00009442 int flags = fcntl(0, F_GETFL);
Denis Vlasenko9cb220b2007-12-09 10:03:28 +00009443 if (flags >= 0 && (flags & O_NONBLOCK)) {
9444 flags &= ~O_NONBLOCK;
Eric Andersencb57d552001-06-28 07:25:16 +00009445 if (fcntl(0, F_SETFL, flags) >= 0) {
9446 out2str("sh: turning off NDELAY mode\n");
9447 goto retry;
9448 }
9449 }
9450 }
9451 }
Denis Vlasenkoe376d452008-02-20 22:23:24 +00009452#endif
Eric Andersencb57d552001-06-28 07:25:16 +00009453 return nr;
9454}
9455
9456/*
9457 * Refill the input buffer and return the next input character:
9458 *
9459 * 1) If a string was pushed back on the input, pop it;
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009460 * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
9461 * or we are reading from a string so we can't refill the buffer,
9462 * return EOF.
Denys Vlasenko883cea42009-07-11 15:31:59 +02009463 * 3) If there is more stuff in this buffer, use it else call read to fill it.
Eric Andersencb57d552001-06-28 07:25:16 +00009464 * 4) Process input up to the next newline, deleting nul characters.
9465 */
Denis Vlasenko727752d2008-11-28 03:41:47 +00009466//#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
9467#define pgetc_debug(...) ((void)0)
Denis Vlasenko68819d12008-12-15 11:26:36 +00009468/*
9469 * NB: due to SIT(c) internals (syntax_index_table[] vector),
9470 * pgetc() and related functions must return chars SIGN-EXTENDED into ints,
9471 * not zero-extended. Seems fragile to me. Affects only !USE_SIT_FUNCTION case,
9472 * so we can fix it by ditching !USE_SIT_FUNCTION if Unicode requires that.
9473 */
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009474static int
Eric Andersenc470f442003-07-28 09:56:35 +00009475preadbuffer(void)
Eric Andersencb57d552001-06-28 07:25:16 +00009476{
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009477 char *q;
Eric Andersencb57d552001-06-28 07:25:16 +00009478 int more;
Eric Andersencb57d552001-06-28 07:25:16 +00009479
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009480 while (g_parsefile->strpush) {
Denis Vlasenko131ae172007-02-18 13:00:19 +00009481#if ENABLE_ASH_ALIAS
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009482 if (g_parsefile->left_in_line == -1
9483 && g_parsefile->strpush->ap
9484 && g_parsefile->next_to_pgetc[-1] != ' '
9485 && g_parsefile->next_to_pgetc[-1] != '\t'
Denis Vlasenko16898402008-11-25 01:34:52 +00009486 ) {
Denis Vlasenko727752d2008-11-28 03:41:47 +00009487 pgetc_debug("preadbuffer PEOA");
Eric Andersencb57d552001-06-28 07:25:16 +00009488 return PEOA;
9489 }
Eric Andersen2870d962001-07-02 17:27:21 +00009490#endif
Eric Andersencb57d552001-06-28 07:25:16 +00009491 popstring();
Denis Vlasenko727752d2008-11-28 03:41:47 +00009492 /* try "pgetc" now: */
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009493 pgetc_debug("preadbuffer internal pgetc at %d:%p'%s'",
9494 g_parsefile->left_in_line,
9495 g_parsefile->next_to_pgetc,
9496 g_parsefile->next_to_pgetc);
9497 if (--g_parsefile->left_in_line >= 0)
9498 return (unsigned char)(*g_parsefile->next_to_pgetc++);
Eric Andersencb57d552001-06-28 07:25:16 +00009499 }
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009500 /* on both branches above g_parsefile->left_in_line < 0.
Denis Vlasenko727752d2008-11-28 03:41:47 +00009501 * "pgetc" needs refilling.
9502 */
9503
Denis Vlasenkoe27dafd2008-11-28 04:01:03 +00009504 /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009505 * pungetc() may increment it a few times.
Denis Vlasenkoe27dafd2008-11-28 04:01:03 +00009506 * Assuming it won't increment it to less than -90.
Denis Vlasenko727752d2008-11-28 03:41:47 +00009507 */
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009508 if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
Denis Vlasenko727752d2008-11-28 03:41:47 +00009509 pgetc_debug("preadbuffer PEOF1");
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009510 /* even in failure keep left_in_line and next_to_pgetc
9511 * in lock step, for correct multi-layer pungetc.
9512 * left_in_line was decremented before preadbuffer(),
9513 * must inc next_to_pgetc: */
9514 g_parsefile->next_to_pgetc++;
Eric Andersencb57d552001-06-28 07:25:16 +00009515 return PEOF;
Denis Vlasenko727752d2008-11-28 03:41:47 +00009516 }
Eric Andersencb57d552001-06-28 07:25:16 +00009517
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009518 more = g_parsefile->left_in_buffer;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009519 if (more <= 0) {
Denis Vlasenko727752d2008-11-28 03:41:47 +00009520 flush_stdout_stderr();
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009521 again:
9522 more = preadfd();
9523 if (more <= 0) {
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009524 /* don't try reading again */
9525 g_parsefile->left_in_line = -99;
Denis Vlasenko727752d2008-11-28 03:41:47 +00009526 pgetc_debug("preadbuffer PEOF2");
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009527 g_parsefile->next_to_pgetc++;
Eric Andersencb57d552001-06-28 07:25:16 +00009528 return PEOF;
9529 }
9530 }
9531
Denis Vlasenko727752d2008-11-28 03:41:47 +00009532 /* Find out where's the end of line.
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009533 * Set g_parsefile->left_in_line
9534 * and g_parsefile->left_in_buffer acordingly.
Denis Vlasenko727752d2008-11-28 03:41:47 +00009535 * NUL chars are deleted.
9536 */
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009537 q = g_parsefile->next_to_pgetc;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009538 for (;;) {
Denis Vlasenko727752d2008-11-28 03:41:47 +00009539 char c;
Eric Andersencb57d552001-06-28 07:25:16 +00009540
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009541 more--;
Eric Andersenc470f442003-07-28 09:56:35 +00009542
Denis Vlasenko727752d2008-11-28 03:41:47 +00009543 c = *q;
9544 if (c == '\0') {
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009545 memmove(q, q + 1, more);
Denis Vlasenko727752d2008-11-28 03:41:47 +00009546 } else {
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009547 q++;
9548 if (c == '\n') {
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009549 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009550 break;
9551 }
Eric Andersencb57d552001-06-28 07:25:16 +00009552 }
9553
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009554 if (more <= 0) {
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009555 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9556 if (g_parsefile->left_in_line < 0)
Eric Andersencb57d552001-06-28 07:25:16 +00009557 goto again;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009558 break;
Eric Andersencb57d552001-06-28 07:25:16 +00009559 }
9560 }
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009561 g_parsefile->left_in_buffer = more;
Eric Andersencb57d552001-06-28 07:25:16 +00009562
Eric Andersencb57d552001-06-28 07:25:16 +00009563 if (vflag) {
Denis Vlasenko727752d2008-11-28 03:41:47 +00009564 char save = *q;
9565 *q = '\0';
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009566 out2str(g_parsefile->next_to_pgetc);
Denis Vlasenko727752d2008-11-28 03:41:47 +00009567 *q = save;
Eric Andersencb57d552001-06-28 07:25:16 +00009568 }
9569
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009570 pgetc_debug("preadbuffer at %d:%p'%s'",
9571 g_parsefile->left_in_line,
9572 g_parsefile->next_to_pgetc,
9573 g_parsefile->next_to_pgetc);
Denis Vlasenko68819d12008-12-15 11:26:36 +00009574 return signed_char2int(*g_parsefile->next_to_pgetc++);
Eric Andersencb57d552001-06-28 07:25:16 +00009575}
9576
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009577#define pgetc_as_macro() \
9578 (--g_parsefile->left_in_line >= 0 \
Denis Vlasenko68819d12008-12-15 11:26:36 +00009579 ? signed_char2int(*g_parsefile->next_to_pgetc++) \
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009580 : preadbuffer() \
9581 )
Denis Vlasenko727752d2008-11-28 03:41:47 +00009582
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009583static int
9584pgetc(void)
9585{
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009586 pgetc_debug("pgetc_fast at %d:%p'%s'",
9587 g_parsefile->left_in_line,
9588 g_parsefile->next_to_pgetc,
9589 g_parsefile->next_to_pgetc);
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009590 return pgetc_as_macro();
9591}
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00009592
9593#if ENABLE_ASH_OPTIMIZE_FOR_SIZE
Denis Vlasenko834dee72008-10-07 09:18:30 +00009594#define pgetc_fast() pgetc()
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009595#else
Denis Vlasenko834dee72008-10-07 09:18:30 +00009596#define pgetc_fast() pgetc_as_macro()
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009597#endif
9598
9599/*
9600 * Same as pgetc(), but ignores PEOA.
9601 */
9602#if ENABLE_ASH_ALIAS
9603static int
9604pgetc2(void)
9605{
9606 int c;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009607 do {
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009608 pgetc_debug("pgetc_fast at %d:%p'%s'",
9609 g_parsefile->left_in_line,
9610 g_parsefile->next_to_pgetc,
9611 g_parsefile->next_to_pgetc);
Denis Vlasenko834dee72008-10-07 09:18:30 +00009612 c = pgetc_fast();
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009613 } while (c == PEOA);
9614 return c;
9615}
9616#else
Denis Vlasenko834dee72008-10-07 09:18:30 +00009617#define pgetc2() pgetc()
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009618#endif
9619
9620/*
9621 * Read a line from the script.
9622 */
9623static char *
9624pfgets(char *line, int len)
9625{
9626 char *p = line;
9627 int nleft = len;
9628 int c;
9629
9630 while (--nleft > 0) {
9631 c = pgetc2();
9632 if (c == PEOF) {
9633 if (p == line)
9634 return NULL;
9635 break;
9636 }
9637 *p++ = c;
9638 if (c == '\n')
9639 break;
9640 }
9641 *p = '\0';
9642 return line;
9643}
9644
Eric Andersenc470f442003-07-28 09:56:35 +00009645/*
9646 * Undo the last call to pgetc. Only one character may be pushed back.
9647 * PEOF may be pushed back.
9648 */
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009649static void
Eric Andersenc470f442003-07-28 09:56:35 +00009650pungetc(void)
9651{
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009652 g_parsefile->left_in_line++;
9653 g_parsefile->next_to_pgetc--;
9654 pgetc_debug("pushed back to %d:%p'%s'",
9655 g_parsefile->left_in_line,
9656 g_parsefile->next_to_pgetc,
9657 g_parsefile->next_to_pgetc);
Eric Andersencb57d552001-06-28 07:25:16 +00009658}
9659
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009660/*
9661 * To handle the "." command, a stack of input files is used. Pushfile
9662 * adds a new entry to the stack and popfile restores the previous level.
9663 */
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009664static void
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009665pushfile(void)
Eric Andersenc470f442003-07-28 09:56:35 +00009666{
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009667 struct parsefile *pf;
9668
Denis Vlasenko597906c2008-02-20 16:38:54 +00009669 pf = ckzalloc(sizeof(*pf));
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009670 pf->prev = g_parsefile;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009671 pf->fd = -1;
Denis Vlasenko597906c2008-02-20 16:38:54 +00009672 /*pf->strpush = NULL; - ckzalloc did it */
9673 /*pf->basestrpush.prev = NULL;*/
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009674 g_parsefile = pf;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009675}
9676
9677static void
9678popfile(void)
9679{
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009680 struct parsefile *pf = g_parsefile;
Eric Andersenc470f442003-07-28 09:56:35 +00009681
Denis Vlasenkob012b102007-02-19 22:43:01 +00009682 INT_OFF;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009683 if (pf->fd >= 0)
9684 close(pf->fd);
Denis Vlasenko60818682007-09-28 22:07:23 +00009685 free(pf->buf);
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009686 while (pf->strpush)
9687 popstring();
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009688 g_parsefile = pf->prev;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009689 free(pf);
Denis Vlasenkob012b102007-02-19 22:43:01 +00009690 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00009691}
9692
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009693/*
9694 * Return to top level.
9695 */
9696static void
9697popallfiles(void)
9698{
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009699 while (g_parsefile != &basepf)
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009700 popfile();
9701}
9702
9703/*
9704 * Close the file(s) that the shell is reading commands from. Called
9705 * after a fork is done.
9706 */
9707static void
9708closescript(void)
9709{
9710 popallfiles();
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009711 if (g_parsefile->fd > 0) {
9712 close(g_parsefile->fd);
9713 g_parsefile->fd = 0;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009714 }
9715}
9716
9717/*
9718 * Like setinputfile, but takes an open file descriptor. Call this with
9719 * interrupts off.
9720 */
9721static void
9722setinputfd(int fd, int push)
9723{
Denis Vlasenko96e1b382007-09-30 23:50:48 +00009724 close_on_exec_on(fd);
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009725 if (push) {
9726 pushfile();
Denis Vlasenko727752d2008-11-28 03:41:47 +00009727 g_parsefile->buf = NULL;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009728 }
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009729 g_parsefile->fd = fd;
9730 if (g_parsefile->buf == NULL)
9731 g_parsefile->buf = ckmalloc(IBUFSIZ);
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009732 g_parsefile->left_in_buffer = 0;
9733 g_parsefile->left_in_line = 0;
9734 g_parsefile->linno = 1;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009735}
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009736
Eric Andersenc470f442003-07-28 09:56:35 +00009737/*
9738 * Set the input to take input from a file. If push is set, push the
9739 * old input onto the stack first.
9740 */
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009741static int
9742setinputfile(const char *fname, int flags)
Eric Andersenc470f442003-07-28 09:56:35 +00009743{
9744 int fd;
9745 int fd2;
9746
Denis Vlasenkob012b102007-02-19 22:43:01 +00009747 INT_OFF;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009748 fd = open(fname, O_RDONLY);
9749 if (fd < 0) {
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009750 if (flags & INPUT_NOFILE_OK)
9751 goto out;
Denis Vlasenko9604e1b2009-03-03 18:47:56 +00009752 ash_msg_and_raise_error("can't open '%s'", fname);
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009753 }
Eric Andersenc470f442003-07-28 09:56:35 +00009754 if (fd < 10) {
9755 fd2 = copyfd(fd, 10);
9756 close(fd);
9757 if (fd2 < 0)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00009758 ash_msg_and_raise_error("out of file descriptors");
Eric Andersenc470f442003-07-28 09:56:35 +00009759 fd = fd2;
9760 }
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009761 setinputfd(fd, flags & INPUT_PUSH_FILE);
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009762 out:
Denis Vlasenkob012b102007-02-19 22:43:01 +00009763 INT_ON;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009764 return fd;
Eric Andersenc470f442003-07-28 09:56:35 +00009765}
9766
Eric Andersencb57d552001-06-28 07:25:16 +00009767/*
9768 * Like setinputfile, but takes input from a string.
9769 */
Eric Andersenc470f442003-07-28 09:56:35 +00009770static void
9771setinputstring(char *string)
Eric Andersen62483552001-07-10 06:09:16 +00009772{
Denis Vlasenkob012b102007-02-19 22:43:01 +00009773 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +00009774 pushfile();
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009775 g_parsefile->next_to_pgetc = string;
9776 g_parsefile->left_in_line = strlen(string);
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009777 g_parsefile->buf = NULL;
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009778 g_parsefile->linno = 1;
Denis Vlasenkob012b102007-02-19 22:43:01 +00009779 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00009780}
9781
9782
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00009783/* ============ mail.c
9784 *
9785 * Routines to check for mail.
Eric Andersencb57d552001-06-28 07:25:16 +00009786 */
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00009787
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00009788#if ENABLE_ASH_MAIL
Eric Andersencb57d552001-06-28 07:25:16 +00009789
Eric Andersencb57d552001-06-28 07:25:16 +00009790#define MAXMBOXES 10
9791
Eric Andersenc470f442003-07-28 09:56:35 +00009792/* times of mailboxes */
9793static time_t mailtime[MAXMBOXES];
9794/* Set if MAIL or MAILPATH is changed. */
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +00009795static smallint mail_var_path_changed;
Eric Andersencb57d552001-06-28 07:25:16 +00009796
Eric Andersencb57d552001-06-28 07:25:16 +00009797/*
Eric Andersenc470f442003-07-28 09:56:35 +00009798 * Print appropriate message(s) if mail has arrived.
9799 * If mail_var_path_changed is set,
9800 * then the value of MAIL has mail_var_path_changed,
9801 * so we just update the values.
Eric Andersencb57d552001-06-28 07:25:16 +00009802 */
Eric Andersenc470f442003-07-28 09:56:35 +00009803static void
9804chkmail(void)
Eric Andersencb57d552001-06-28 07:25:16 +00009805{
Eric Andersencb57d552001-06-28 07:25:16 +00009806 const char *mpath;
9807 char *p;
9808 char *q;
Eric Andersenc470f442003-07-28 09:56:35 +00009809 time_t *mtp;
Eric Andersencb57d552001-06-28 07:25:16 +00009810 struct stackmark smark;
9811 struct stat statb;
9812
Eric Andersencb57d552001-06-28 07:25:16 +00009813 setstackmark(&smark);
Eric Andersenc470f442003-07-28 09:56:35 +00009814 mpath = mpathset() ? mpathval() : mailval();
9815 for (mtp = mailtime; mtp < mailtime + MAXMBOXES; mtp++) {
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02009816 p = path_advance(&mpath, nullstr);
Eric Andersencb57d552001-06-28 07:25:16 +00009817 if (p == NULL)
9818 break;
9819 if (*p == '\0')
9820 continue;
Denis Vlasenkof7d56652008-03-25 05:51:41 +00009821 for (q = p; *q; q++)
9822 continue;
Denis Vlasenkoa7189f02006-11-17 20:29:00 +00009823#if DEBUG
Eric Andersencb57d552001-06-28 07:25:16 +00009824 if (q[-1] != '/')
9825 abort();
9826#endif
Eric Andersenc470f442003-07-28 09:56:35 +00009827 q[-1] = '\0'; /* delete trailing '/' */
9828 if (stat(p, &statb) < 0) {
9829 *mtp = 0;
9830 continue;
Eric Andersencb57d552001-06-28 07:25:16 +00009831 }
Eric Andersenc470f442003-07-28 09:56:35 +00009832 if (!mail_var_path_changed && statb.st_mtime != *mtp) {
9833 fprintf(
9834 stderr, snlfmt,
9835 pathopt ? pathopt : "you have mail"
9836 );
9837 }
9838 *mtp = statb.st_mtime;
Eric Andersencb57d552001-06-28 07:25:16 +00009839 }
Eric Andersenc470f442003-07-28 09:56:35 +00009840 mail_var_path_changed = 0;
Eric Andersencb57d552001-06-28 07:25:16 +00009841 popstackmark(&smark);
9842}
Eric Andersencb57d552001-06-28 07:25:16 +00009843
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009844static void FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00009845changemail(const char *val UNUSED_PARAM)
Eric Andersenc470f442003-07-28 09:56:35 +00009846{
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +00009847 mail_var_path_changed = 1;
Eric Andersenc470f442003-07-28 09:56:35 +00009848}
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00009849
Denis Vlasenko131ae172007-02-18 13:00:19 +00009850#endif /* ASH_MAIL */
Eric Andersenc470f442003-07-28 09:56:35 +00009851
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00009852
9853/* ============ ??? */
9854
Eric Andersencb57d552001-06-28 07:25:16 +00009855/*
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009856 * Set the shell parameters.
Eric Andersencb57d552001-06-28 07:25:16 +00009857 */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009858static void
9859setparam(char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +00009860{
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009861 char **newparam;
9862 char **ap;
9863 int nparam;
Eric Andersencb57d552001-06-28 07:25:16 +00009864
Denis Vlasenkof7d56652008-03-25 05:51:41 +00009865 for (nparam = 0; argv[nparam]; nparam++)
9866 continue;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009867 ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
9868 while (*argv) {
9869 *ap++ = ckstrdup(*argv++);
Eric Andersencb57d552001-06-28 07:25:16 +00009870 }
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009871 *ap = NULL;
9872 freeparam(&shellparam);
Denis Vlasenko01631112007-12-16 17:20:38 +00009873 shellparam.malloced = 1;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009874 shellparam.nparam = nparam;
9875 shellparam.p = newparam;
9876#if ENABLE_ASH_GETOPTS
9877 shellparam.optind = 1;
9878 shellparam.optoff = -1;
9879#endif
Eric Andersencb57d552001-06-28 07:25:16 +00009880}
9881
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00009882/*
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009883 * Process shell options. The global variable argptr contains a pointer
9884 * to the argument list; we advance it past the options.
Denis Vlasenko94e87bc2008-02-14 16:51:58 +00009885 *
9886 * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
9887 * For a non-interactive shell, an error condition encountered
9888 * by a special built-in ... shall cause the shell to write a diagnostic message
9889 * to standard error and exit as shown in the following table:
Denis Vlasenko56244732008-02-17 15:14:04 +00009890 * Error Special Built-In
Denis Vlasenko94e87bc2008-02-14 16:51:58 +00009891 * ...
9892 * Utility syntax error (option or operand error) Shall exit
9893 * ...
9894 * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
9895 * we see that bash does not do that (set "finishes" with error code 1 instead,
9896 * and shell continues), and people rely on this behavior!
9897 * Testcase:
9898 * set -o barfoo 2>/dev/null
9899 * echo $?
9900 *
9901 * Oh well. Let's mimic that.
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00009902 */
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009903static int
Denis Vlasenkodddfaff2008-05-06 15:30:27 +00009904plus_minus_o(char *name, int val)
Eric Andersen62483552001-07-10 06:09:16 +00009905{
9906 int i;
9907
Denis Vlasenkoa624c112007-02-19 22:45:43 +00009908 if (name) {
9909 for (i = 0; i < NOPTS; i++) {
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00009910 if (strcmp(name, optnames(i)) == 0) {
Eric Andersenc470f442003-07-28 09:56:35 +00009911 optlist[i] = val;
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009912 return 0;
Eric Andersen62483552001-07-10 06:09:16 +00009913 }
Denis Vlasenkoa624c112007-02-19 22:45:43 +00009914 }
Denis Vlasenkodddfaff2008-05-06 15:30:27 +00009915 ash_msg("illegal option %co %s", val ? '-' : '+', name);
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009916 return 1;
Eric Andersen62483552001-07-10 06:09:16 +00009917 }
Denis Vlasenko6b06cb82008-05-15 21:30:45 +00009918 for (i = 0; i < NOPTS; i++) {
Denis Vlasenkodddfaff2008-05-06 15:30:27 +00009919 if (val) {
9920 out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
9921 } else {
9922 out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
9923 }
Denis Vlasenko6b06cb82008-05-15 21:30:45 +00009924 }
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009925 return 0;
Eric Andersen62483552001-07-10 06:09:16 +00009926}
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009927static void
9928setoption(int flag, int val)
9929{
9930 int i;
9931
9932 for (i = 0; i < NOPTS; i++) {
9933 if (optletters(i) == flag) {
9934 optlist[i] = val;
9935 return;
9936 }
9937 }
Denis Vlasenkodddfaff2008-05-06 15:30:27 +00009938 ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009939 /* NOTREACHED */
9940}
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009941static int
Eric Andersenc470f442003-07-28 09:56:35 +00009942options(int cmdline)
Eric Andersencb57d552001-06-28 07:25:16 +00009943{
9944 char *p;
9945 int val;
9946 int c;
9947
9948 if (cmdline)
9949 minusc = NULL;
9950 while ((p = *argptr) != NULL) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009951 c = *p++;
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +00009952 if (c != '-' && c != '+')
9953 break;
9954 argptr++;
9955 val = 0; /* val = 0 if c == '+' */
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009956 if (c == '-') {
Eric Andersencb57d552001-06-28 07:25:16 +00009957 val = 1;
Denis Vlasenko9f739442006-12-16 23:49:13 +00009958 if (p[0] == '\0' || LONE_DASH(p)) {
Eric Andersen2870d962001-07-02 17:27:21 +00009959 if (!cmdline) {
9960 /* "-" means turn off -x and -v */
9961 if (p[0] == '\0')
9962 xflag = vflag = 0;
9963 /* "--" means reset params */
9964 else if (*argptr == NULL)
Eric Andersencb57d552001-06-28 07:25:16 +00009965 setparam(argptr);
Eric Andersen2870d962001-07-02 17:27:21 +00009966 }
Eric Andersenc470f442003-07-28 09:56:35 +00009967 break; /* "-" or "--" terminates options */
Eric Andersencb57d552001-06-28 07:25:16 +00009968 }
Eric Andersencb57d552001-06-28 07:25:16 +00009969 }
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +00009970 /* first char was + or - */
Eric Andersencb57d552001-06-28 07:25:16 +00009971 while ((c = *p++) != '\0') {
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +00009972 /* bash 3.2 indeed handles -c CMD and +c CMD the same */
Eric Andersencb57d552001-06-28 07:25:16 +00009973 if (c == 'c' && cmdline) {
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +00009974 minusc = p; /* command is after shell args */
Eric Andersencb57d552001-06-28 07:25:16 +00009975 } else if (c == 'o') {
Denis Vlasenkodddfaff2008-05-06 15:30:27 +00009976 if (plus_minus_o(*argptr, val)) {
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009977 /* it already printed err message */
9978 return 1; /* error */
9979 }
Eric Andersencb57d552001-06-28 07:25:16 +00009980 if (*argptr)
9981 argptr++;
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +00009982 } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
9983 isloginsh = 1;
9984 /* bash does not accept +-login, we also won't */
9985 } else if (cmdline && val && (c == '-')) { /* long options */
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00009986 if (strcmp(p, "login") == 0)
Robert Griebl64f70cc2002-05-14 23:22:06 +00009987 isloginsh = 1;
9988 break;
Eric Andersencb57d552001-06-28 07:25:16 +00009989 } else {
9990 setoption(c, val);
9991 }
9992 }
9993 }
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009994 return 0;
Eric Andersencb57d552001-06-28 07:25:16 +00009995}
9996
Eric Andersencb57d552001-06-28 07:25:16 +00009997/*
Eric Andersencb57d552001-06-28 07:25:16 +00009998 * The shift builtin command.
9999 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010000static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000010001shiftcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +000010002{
10003 int n;
10004 char **ap1, **ap2;
10005
10006 n = 1;
Denis Vlasenko68404f12008-03-17 09:00:54 +000010007 if (argv[1])
Eric Andersencb57d552001-06-28 07:25:16 +000010008 n = number(argv[1]);
10009 if (n > shellparam.nparam)
Denis Vlasenkoc90e1be2008-07-30 15:35:05 +000010010 n = 0; /* bash compat, was = shellparam.nparam; */
Denis Vlasenkob012b102007-02-19 22:43:01 +000010011 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +000010012 shellparam.nparam -= n;
Denis Vlasenko2da584f2007-02-19 22:44:05 +000010013 for (ap1 = shellparam.p; --n >= 0; ap1++) {
Denis Vlasenko01631112007-12-16 17:20:38 +000010014 if (shellparam.malloced)
Denis Vlasenkob012b102007-02-19 22:43:01 +000010015 free(*ap1);
Eric Andersencb57d552001-06-28 07:25:16 +000010016 }
10017 ap2 = shellparam.p;
Denis Vlasenkof7d56652008-03-25 05:51:41 +000010018 while ((*ap2++ = *ap1++) != NULL)
10019 continue;
Denis Vlasenko131ae172007-02-18 13:00:19 +000010020#if ENABLE_ASH_GETOPTS
Eric Andersencb57d552001-06-28 07:25:16 +000010021 shellparam.optind = 1;
10022 shellparam.optoff = -1;
Eric Andersenc470f442003-07-28 09:56:35 +000010023#endif
Denis Vlasenkob012b102007-02-19 22:43:01 +000010024 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +000010025 return 0;
10026}
10027
Eric Andersencb57d552001-06-28 07:25:16 +000010028/*
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010029 * POSIX requires that 'set' (but not export or readonly) output the
10030 * variables in lexicographic order - by the locale's collating order (sigh).
10031 * Maybe we could keep them in an ordered balanced binary tree
10032 * instead of hashed lists.
10033 * For now just roll 'em through qsort for printing...
10034 */
10035static int
10036showvars(const char *sep_prefix, int on, int off)
10037{
10038 const char *sep;
10039 char **ep, **epend;
10040
10041 ep = listvars(on, off, &epend);
10042 qsort(ep, epend - ep, sizeof(char *), vpcmp);
10043
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +000010044 sep = *sep_prefix ? " " : sep_prefix;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010045
10046 for (; ep < epend; ep++) {
10047 const char *p;
10048 const char *q;
10049
10050 p = strchrnul(*ep, '=');
10051 q = nullstr;
10052 if (*p)
10053 q = single_quote(++p);
10054 out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
10055 }
10056 return 0;
10057}
10058
10059/*
Eric Andersencb57d552001-06-28 07:25:16 +000010060 * The set command builtin.
10061 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010062static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000010063setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersencb57d552001-06-28 07:25:16 +000010064{
Denis Vlasenko28bf6712008-02-14 15:01:47 +000010065 int retval;
10066
Denis Vlasenko68404f12008-03-17 09:00:54 +000010067 if (!argv[1])
Eric Andersenc470f442003-07-28 09:56:35 +000010068 return showvars(nullstr, 0, VUNSET);
Denis Vlasenkob012b102007-02-19 22:43:01 +000010069 INT_OFF;
Denis Vlasenko28bf6712008-02-14 15:01:47 +000010070 retval = 1;
10071 if (!options(0)) { /* if no parse error... */
10072 retval = 0;
10073 optschanged();
10074 if (*argptr != NULL) {
10075 setparam(argptr);
10076 }
Eric Andersencb57d552001-06-28 07:25:16 +000010077 }
Denis Vlasenkob012b102007-02-19 22:43:01 +000010078 INT_ON;
Denis Vlasenko28bf6712008-02-14 15:01:47 +000010079 return retval;
Eric Andersencb57d552001-06-28 07:25:16 +000010080}
10081
Denis Vlasenko131ae172007-02-18 13:00:19 +000010082#if ENABLE_ASH_RANDOM_SUPPORT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010083static void FAST_FUNC
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000010084change_random(const char *value)
Eric Andersenef02f822004-03-11 13:34:24 +000010085{
Denys Vlasenko3ea2e822009-10-09 20:59:04 +020010086 uint32_t t;
10087
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010088 if (value == NULL) {
Eric Andersen16767e22004-03-16 05:14:10 +000010089 /* "get", generate */
Denys Vlasenko3ea2e822009-10-09 20:59:04 +020010090 t = next_random(&random_gen);
Eric Andersen16767e22004-03-16 05:14:10 +000010091 /* set without recursion */
Denis Vlasenko448d30e2008-06-27 00:24:11 +000010092 setvar(vrandom.text, utoa(t), VNOFUNC);
Eric Andersen16767e22004-03-16 05:14:10 +000010093 vrandom.flags &= ~VNOFUNC;
10094 } else {
10095 /* set/reset */
Denys Vlasenko3ea2e822009-10-09 20:59:04 +020010096 t = strtoul(value, NULL, 10);
10097 INIT_RANDOM_T(&random_gen, (t ? t : 1), t);
Eric Andersen16767e22004-03-16 05:14:10 +000010098 }
Eric Andersenef02f822004-03-11 13:34:24 +000010099}
Eric Andersen16767e22004-03-16 05:14:10 +000010100#endif
10101
Denis Vlasenko131ae172007-02-18 13:00:19 +000010102#if ENABLE_ASH_GETOPTS
Eric Andersencb57d552001-06-28 07:25:16 +000010103static int
Eric Andersenc470f442003-07-28 09:56:35 +000010104getopts(char *optstr, char *optvar, char **optfirst, int *param_optind, int *optoff)
Eric Andersencb57d552001-06-28 07:25:16 +000010105{
10106 char *p, *q;
10107 char c = '?';
10108 int done = 0;
10109 int err = 0;
Eric Andersena48b0a32003-10-22 10:56:47 +000010110 char s[12];
10111 char **optnext;
Eric Andersencb57d552001-06-28 07:25:16 +000010112
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010113 if (*param_optind < 1)
Eric Andersena48b0a32003-10-22 10:56:47 +000010114 return 1;
10115 optnext = optfirst + *param_optind - 1;
10116
Denis Vlasenko6b06cb82008-05-15 21:30:45 +000010117 if (*param_optind <= 1 || *optoff < 0 || (int)strlen(optnext[-1]) < *optoff)
Eric Andersencb57d552001-06-28 07:25:16 +000010118 p = NULL;
10119 else
Eric Andersena48b0a32003-10-22 10:56:47 +000010120 p = optnext[-1] + *optoff;
Eric Andersencb57d552001-06-28 07:25:16 +000010121 if (p == NULL || *p == '\0') {
10122 /* Current word is done, advance */
Eric Andersencb57d552001-06-28 07:25:16 +000010123 p = *optnext;
10124 if (p == NULL || *p != '-' || *++p == '\0') {
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010125 atend:
Eric Andersencb57d552001-06-28 07:25:16 +000010126 p = NULL;
10127 done = 1;
10128 goto out;
10129 }
10130 optnext++;
Denis Vlasenko9f739442006-12-16 23:49:13 +000010131 if (LONE_DASH(p)) /* check for "--" */
Eric Andersencb57d552001-06-28 07:25:16 +000010132 goto atend;
10133 }
10134
10135 c = *p++;
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +000010136 for (q = optstr; *q != c;) {
Eric Andersencb57d552001-06-28 07:25:16 +000010137 if (*q == '\0') {
10138 if (optstr[0] == ':') {
10139 s[0] = c;
10140 s[1] = '\0';
10141 err |= setvarsafe("OPTARG", s, 0);
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010142 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000010143 fprintf(stderr, "Illegal option -%c\n", c);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010144 unsetvar("OPTARG");
Eric Andersencb57d552001-06-28 07:25:16 +000010145 }
10146 c = '?';
Eric Andersenc470f442003-07-28 09:56:35 +000010147 goto out;
Eric Andersencb57d552001-06-28 07:25:16 +000010148 }
10149 if (*++q == ':')
10150 q++;
10151 }
10152
10153 if (*++q == ':') {
10154 if (*p == '\0' && (p = *optnext) == NULL) {
10155 if (optstr[0] == ':') {
10156 s[0] = c;
10157 s[1] = '\0';
10158 err |= setvarsafe("OPTARG", s, 0);
10159 c = ':';
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010160 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000010161 fprintf(stderr, "No arg for -%c option\n", c);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010162 unsetvar("OPTARG");
Eric Andersencb57d552001-06-28 07:25:16 +000010163 c = '?';
10164 }
Eric Andersenc470f442003-07-28 09:56:35 +000010165 goto out;
Eric Andersencb57d552001-06-28 07:25:16 +000010166 }
10167
10168 if (p == *optnext)
10169 optnext++;
Eric Andersenc470f442003-07-28 09:56:35 +000010170 err |= setvarsafe("OPTARG", p, 0);
Eric Andersencb57d552001-06-28 07:25:16 +000010171 p = NULL;
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010172 } else
Eric Andersenc470f442003-07-28 09:56:35 +000010173 err |= setvarsafe("OPTARG", nullstr, 0);
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010174 out:
Eric Andersencb57d552001-06-28 07:25:16 +000010175 *optoff = p ? p - *(optnext - 1) : -1;
Eric Andersenc470f442003-07-28 09:56:35 +000010176 *param_optind = optnext - optfirst + 1;
10177 fmtstr(s, sizeof(s), "%d", *param_optind);
Eric Andersencb57d552001-06-28 07:25:16 +000010178 err |= setvarsafe("OPTIND", s, VNOFUNC);
10179 s[0] = c;
10180 s[1] = '\0';
10181 err |= setvarsafe(optvar, s, 0);
10182 if (err) {
Eric Andersenc470f442003-07-28 09:56:35 +000010183 *param_optind = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010184 *optoff = -1;
Denis Vlasenkob012b102007-02-19 22:43:01 +000010185 flush_stdout_stderr();
10186 raise_exception(EXERROR);
Eric Andersencb57d552001-06-28 07:25:16 +000010187 }
10188 return done;
10189}
Eric Andersenc470f442003-07-28 09:56:35 +000010190
10191/*
10192 * The getopts builtin. Shellparam.optnext points to the next argument
10193 * to be processed. Shellparam.optptr points to the next character to
10194 * be processed in the current argument. If shellparam.optnext is NULL,
10195 * then it's the first time getopts has been called.
10196 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010197static int FAST_FUNC
Eric Andersenc470f442003-07-28 09:56:35 +000010198getoptscmd(int argc, char **argv)
10199{
10200 char **optbase;
10201
10202 if (argc < 3)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +000010203 ash_msg_and_raise_error("usage: getopts optstring var [arg]");
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010204 if (argc == 3) {
Eric Andersenc470f442003-07-28 09:56:35 +000010205 optbase = shellparam.p;
10206 if (shellparam.optind > shellparam.nparam + 1) {
10207 shellparam.optind = 1;
10208 shellparam.optoff = -1;
10209 }
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010210 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000010211 optbase = &argv[3];
10212 if (shellparam.optind > argc - 2) {
10213 shellparam.optind = 1;
10214 shellparam.optoff = -1;
10215 }
10216 }
10217
10218 return getopts(argv[1], argv[2], optbase, &shellparam.optind,
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010219 &shellparam.optoff);
Eric Andersenc470f442003-07-28 09:56:35 +000010220}
Denis Vlasenko131ae172007-02-18 13:00:19 +000010221#endif /* ASH_GETOPTS */
Eric Andersencb57d552001-06-28 07:25:16 +000010222
Eric Andersencb57d552001-06-28 07:25:16 +000010223
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010224/* ============ Shell parser */
Eric Andersencb57d552001-06-28 07:25:16 +000010225
Denis Vlasenkob07a4962008-06-22 13:16:23 +000010226struct heredoc {
10227 struct heredoc *next; /* next here document in list */
10228 union node *here; /* redirection node */
10229 char *eofmark; /* string indicating end of input */
10230 smallint striptabs; /* if set, strip leading tabs */
10231};
10232
10233static smallint tokpushback; /* last token pushed back */
10234static smallint parsebackquote; /* nonzero if we are inside backquotes */
10235static smallint quoteflag; /* set if (part of) last token was quoted */
10236static token_id_t lasttoken; /* last token read (integer id Txxx) */
10237static struct heredoc *heredoclist; /* list of here documents to read */
10238static char *wordtext; /* text of last word returned by readtoken */
10239static struct nodelist *backquotelist;
10240static union node *redirnode;
10241static struct heredoc *heredoc;
Denis Vlasenko99eb8502007-02-23 21:09:49 +000010242
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010243/*
10244 * Called when an unexpected token is read during the parse. The argument
10245 * is the token that is expected, or -1 if more than one type of token can
10246 * occur at this point.
10247 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000010248static void raise_error_unexpected_syntax(int) NORETURN;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010249static void
10250raise_error_unexpected_syntax(int token)
10251{
10252 char msg[64];
10253 int l;
10254
Denis Vlasenko7b2294e2008-11-28 03:50:46 +000010255 l = sprintf(msg, "unexpected %s", tokname(lasttoken));
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010256 if (token >= 0)
10257 sprintf(msg + l, " (expecting %s)", tokname(token));
10258 raise_error_syntax(msg);
10259 /* NOTREACHED */
10260}
Eric Andersencb57d552001-06-28 07:25:16 +000010261
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010262#define EOFMARKLEN 79
Eric Andersencb57d552001-06-28 07:25:16 +000010263
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010264/* parsing is heavily cross-recursive, need these forward decls */
10265static union node *andor(void);
10266static union node *pipeline(void);
10267static union node *parse_command(void);
10268static void parseheredoc(void);
10269static char peektoken(void);
10270static int readtoken(void);
Eric Andersencb57d552001-06-28 07:25:16 +000010271
Eric Andersenc470f442003-07-28 09:56:35 +000010272static union node *
10273list(int nlflag)
Eric Andersencb57d552001-06-28 07:25:16 +000010274{
10275 union node *n1, *n2, *n3;
10276 int tok;
10277
Eric Andersenc470f442003-07-28 09:56:35 +000010278 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10279 if (nlflag == 2 && peektoken())
Eric Andersencb57d552001-06-28 07:25:16 +000010280 return NULL;
10281 n1 = NULL;
10282 for (;;) {
10283 n2 = andor();
10284 tok = readtoken();
10285 if (tok == TBACKGND) {
Eric Andersenc470f442003-07-28 09:56:35 +000010286 if (n2->type == NPIPE) {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +000010287 n2->npipe.pipe_backgnd = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010288 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000010289 if (n2->type != NREDIR) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010290 n3 = stzalloc(sizeof(struct nredir));
Eric Andersenc470f442003-07-28 09:56:35 +000010291 n3->nredir.n = n2;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010292 /*n3->nredir.redirect = NULL; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000010293 n2 = n3;
10294 }
10295 n2->type = NBACKGND;
Eric Andersencb57d552001-06-28 07:25:16 +000010296 }
10297 }
10298 if (n1 == NULL) {
10299 n1 = n2;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010300 } else {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010301 n3 = stzalloc(sizeof(struct nbinary));
Eric Andersencb57d552001-06-28 07:25:16 +000010302 n3->type = NSEMI;
10303 n3->nbinary.ch1 = n1;
10304 n3->nbinary.ch2 = n2;
10305 n1 = n3;
10306 }
10307 switch (tok) {
10308 case TBACKGND:
10309 case TSEMI:
10310 tok = readtoken();
10311 /* fall through */
10312 case TNL:
10313 if (tok == TNL) {
10314 parseheredoc();
Eric Andersenc470f442003-07-28 09:56:35 +000010315 if (nlflag == 1)
Eric Andersencb57d552001-06-28 07:25:16 +000010316 return n1;
10317 } else {
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010318 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010319 }
Eric Andersenc470f442003-07-28 09:56:35 +000010320 checkkwd = CHKNL | CHKKWD | CHKALIAS;
Manuel Novoa III 16815d42001-08-10 19:36:07 +000010321 if (peektoken())
Eric Andersencb57d552001-06-28 07:25:16 +000010322 return n1;
10323 break;
10324 case TEOF:
10325 if (heredoclist)
10326 parseheredoc();
10327 else
Eric Andersenc470f442003-07-28 09:56:35 +000010328 pungetc(); /* push back EOF on input */
Eric Andersencb57d552001-06-28 07:25:16 +000010329 return n1;
10330 default:
Eric Andersenc470f442003-07-28 09:56:35 +000010331 if (nlflag == 1)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010332 raise_error_unexpected_syntax(-1);
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010333 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010334 return n1;
10335 }
10336 }
10337}
10338
Eric Andersenc470f442003-07-28 09:56:35 +000010339static union node *
10340andor(void)
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010341{
Eric Andersencb57d552001-06-28 07:25:16 +000010342 union node *n1, *n2, *n3;
10343 int t;
10344
Eric Andersencb57d552001-06-28 07:25:16 +000010345 n1 = pipeline();
10346 for (;;) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010347 t = readtoken();
10348 if (t == TAND) {
Eric Andersencb57d552001-06-28 07:25:16 +000010349 t = NAND;
10350 } else if (t == TOR) {
10351 t = NOR;
10352 } else {
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010353 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010354 return n1;
10355 }
Eric Andersenc470f442003-07-28 09:56:35 +000010356 checkkwd = CHKNL | CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010357 n2 = pipeline();
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010358 n3 = stzalloc(sizeof(struct nbinary));
Eric Andersencb57d552001-06-28 07:25:16 +000010359 n3->type = t;
10360 n3->nbinary.ch1 = n1;
10361 n3->nbinary.ch2 = n2;
10362 n1 = n3;
10363 }
10364}
10365
Eric Andersenc470f442003-07-28 09:56:35 +000010366static union node *
10367pipeline(void)
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010368{
Eric Andersencb57d552001-06-28 07:25:16 +000010369 union node *n1, *n2, *pipenode;
10370 struct nodelist *lp, *prev;
10371 int negate;
10372
10373 negate = 0;
10374 TRACE(("pipeline: entered\n"));
10375 if (readtoken() == TNOT) {
10376 negate = !negate;
Eric Andersenc470f442003-07-28 09:56:35 +000010377 checkkwd = CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010378 } else
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010379 tokpushback = 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010380 n1 = parse_command();
Eric Andersencb57d552001-06-28 07:25:16 +000010381 if (readtoken() == TPIPE) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010382 pipenode = stzalloc(sizeof(struct npipe));
Eric Andersencb57d552001-06-28 07:25:16 +000010383 pipenode->type = NPIPE;
Denis Vlasenko2dc240c2008-07-24 06:07:50 +000010384 /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010385 lp = stzalloc(sizeof(struct nodelist));
Eric Andersencb57d552001-06-28 07:25:16 +000010386 pipenode->npipe.cmdlist = lp;
10387 lp->n = n1;
10388 do {
10389 prev = lp;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010390 lp = stzalloc(sizeof(struct nodelist));
Eric Andersenc470f442003-07-28 09:56:35 +000010391 checkkwd = CHKNL | CHKKWD | CHKALIAS;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010392 lp->n = parse_command();
Eric Andersencb57d552001-06-28 07:25:16 +000010393 prev->next = lp;
10394 } while (readtoken() == TPIPE);
10395 lp->next = NULL;
10396 n1 = pipenode;
10397 }
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010398 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010399 if (negate) {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010400 n2 = stzalloc(sizeof(struct nnot));
Eric Andersencb57d552001-06-28 07:25:16 +000010401 n2->type = NNOT;
10402 n2->nnot.com = n1;
10403 return n2;
Denis Vlasenko2da584f2007-02-19 22:44:05 +000010404 }
10405 return n1;
Eric Andersencb57d552001-06-28 07:25:16 +000010406}
10407
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010408static union node *
10409makename(void)
10410{
10411 union node *n;
10412
Denis Vlasenko597906c2008-02-20 16:38:54 +000010413 n = stzalloc(sizeof(struct narg));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010414 n->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010415 /*n->narg.next = NULL; - stzalloc did it */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010416 n->narg.text = wordtext;
10417 n->narg.backquote = backquotelist;
10418 return n;
10419}
10420
10421static void
10422fixredir(union node *n, const char *text, int err)
10423{
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000010424 int fd;
10425
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010426 TRACE(("Fix redir %s %d\n", text, err));
10427 if (!err)
10428 n->ndup.vname = NULL;
10429
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000010430 fd = bb_strtou(text, NULL, 10);
10431 if (!errno && fd >= 0)
10432 n->ndup.dupfd = fd;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010433 else if (LONE_DASH(text))
10434 n->ndup.dupfd = -1;
10435 else {
10436 if (err)
Denis Vlasenko559691a2008-10-05 18:39:31 +000010437 raise_error_syntax("bad fd number");
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010438 n->ndup.vname = makename();
10439 }
10440}
10441
10442/*
10443 * Returns true if the text contains nothing to expand (no dollar signs
10444 * or backquotes).
10445 */
10446static int
Denis Vlasenko68819d12008-12-15 11:26:36 +000010447noexpand(const char *text)
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010448{
Denis Vlasenko68819d12008-12-15 11:26:36 +000010449 const char *p;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010450 char c;
10451
10452 p = text;
10453 while ((c = *p++) != '\0') {
10454 if (c == CTLQUOTEMARK)
10455 continue;
10456 if (c == CTLESC)
10457 p++;
Denis Vlasenko68819d12008-12-15 11:26:36 +000010458 else if (SIT((signed char)c, BASESYNTAX) == CCTL)
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010459 return 0;
10460 }
10461 return 1;
10462}
10463
10464static void
10465parsefname(void)
10466{
10467 union node *n = redirnode;
10468
10469 if (readtoken() != TWORD)
10470 raise_error_unexpected_syntax(-1);
10471 if (n->type == NHERE) {
10472 struct heredoc *here = heredoc;
10473 struct heredoc *p;
10474 int i;
10475
10476 if (quoteflag == 0)
10477 n->type = NXHERE;
10478 TRACE(("Here document %d\n", n->type));
10479 if (!noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
Denis Vlasenko559691a2008-10-05 18:39:31 +000010480 raise_error_syntax("illegal eof marker for << redirection");
Denys Vlasenkob6c84342009-08-29 20:23:20 +020010481 rmescapes(wordtext, 0);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010482 here->eofmark = wordtext;
10483 here->next = NULL;
10484 if (heredoclist == NULL)
10485 heredoclist = here;
10486 else {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010487 for (p = heredoclist; p->next; p = p->next)
10488 continue;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010489 p->next = here;
10490 }
10491 } else if (n->type == NTOFD || n->type == NFROMFD) {
10492 fixredir(n, wordtext, 0);
10493 } else {
10494 n->nfile.fname = makename();
10495 }
10496}
Eric Andersencb57d552001-06-28 07:25:16 +000010497
Eric Andersenc470f442003-07-28 09:56:35 +000010498static union node *
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010499simplecmd(void)
10500{
10501 union node *args, **app;
10502 union node *n = NULL;
10503 union node *vars, **vpp;
10504 union node **rpp, *redir;
10505 int savecheckkwd;
Denis Vlasenko80591b02008-03-25 07:49:43 +000010506#if ENABLE_ASH_BASH_COMPAT
10507 smallint double_brackets_flag = 0;
10508#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010509
10510 args = NULL;
10511 app = &args;
10512 vars = NULL;
10513 vpp = &vars;
10514 redir = NULL;
10515 rpp = &redir;
10516
10517 savecheckkwd = CHKALIAS;
10518 for (;;) {
Denis Vlasenko80591b02008-03-25 07:49:43 +000010519 int t;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010520 checkkwd = savecheckkwd;
Denis Vlasenko80591b02008-03-25 07:49:43 +000010521 t = readtoken();
10522 switch (t) {
10523#if ENABLE_ASH_BASH_COMPAT
10524 case TAND: /* "&&" */
10525 case TOR: /* "||" */
10526 if (!double_brackets_flag) {
10527 tokpushback = 1;
10528 goto out;
10529 }
10530 wordtext = (char *) (t == TAND ? "-a" : "-o");
10531#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010532 case TWORD:
Denis Vlasenko597906c2008-02-20 16:38:54 +000010533 n = stzalloc(sizeof(struct narg));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010534 n->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010535 /*n->narg.next = NULL; - stzalloc did it */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010536 n->narg.text = wordtext;
Denis Vlasenko80591b02008-03-25 07:49:43 +000010537#if ENABLE_ASH_BASH_COMPAT
10538 if (strcmp("[[", wordtext) == 0)
10539 double_brackets_flag = 1;
10540 else if (strcmp("]]", wordtext) == 0)
10541 double_brackets_flag = 0;
10542#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010543 n->narg.backquote = backquotelist;
10544 if (savecheckkwd && isassignment(wordtext)) {
10545 *vpp = n;
10546 vpp = &n->narg.next;
10547 } else {
10548 *app = n;
10549 app = &n->narg.next;
10550 savecheckkwd = 0;
10551 }
10552 break;
10553 case TREDIR:
10554 *rpp = n = redirnode;
10555 rpp = &n->nfile.next;
10556 parsefname(); /* read name of redirection file */
10557 break;
10558 case TLP:
10559 if (args && app == &args->narg.next
10560 && !vars && !redir
10561 ) {
10562 struct builtincmd *bcmd;
10563 const char *name;
10564
10565 /* We have a function */
10566 if (readtoken() != TRP)
10567 raise_error_unexpected_syntax(TRP);
10568 name = n->narg.text;
10569 if (!goodname(name)
10570 || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
10571 ) {
Denis Vlasenko559691a2008-10-05 18:39:31 +000010572 raise_error_syntax("bad function name");
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010573 }
10574 n->type = NDEFUN;
10575 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10576 n->narg.next = parse_command();
10577 return n;
10578 }
10579 /* fall through */
10580 default:
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010581 tokpushback = 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010582 goto out;
10583 }
10584 }
10585 out:
10586 *app = NULL;
10587 *vpp = NULL;
10588 *rpp = NULL;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010589 n = stzalloc(sizeof(struct ncmd));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010590 n->type = NCMD;
10591 n->ncmd.args = args;
10592 n->ncmd.assign = vars;
10593 n->ncmd.redirect = redir;
10594 return n;
10595}
10596
10597static union node *
10598parse_command(void)
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010599{
Eric Andersencb57d552001-06-28 07:25:16 +000010600 union node *n1, *n2;
10601 union node *ap, **app;
10602 union node *cp, **cpp;
10603 union node *redir, **rpp;
Eric Andersenc470f442003-07-28 09:56:35 +000010604 union node **rpp2;
Eric Andersencb57d552001-06-28 07:25:16 +000010605 int t;
10606
10607 redir = NULL;
Eric Andersenc470f442003-07-28 09:56:35 +000010608 rpp2 = &redir;
Eric Andersen88cec252001-09-06 17:35:20 +000010609
Eric Andersencb57d552001-06-28 07:25:16 +000010610 switch (readtoken()) {
Eric Andersenc470f442003-07-28 09:56:35 +000010611 default:
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010612 raise_error_unexpected_syntax(-1);
Eric Andersenc470f442003-07-28 09:56:35 +000010613 /* NOTREACHED */
Eric Andersencb57d552001-06-28 07:25:16 +000010614 case TIF:
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010615 n1 = stzalloc(sizeof(struct nif));
Eric Andersencb57d552001-06-28 07:25:16 +000010616 n1->type = NIF;
10617 n1->nif.test = list(0);
10618 if (readtoken() != TTHEN)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010619 raise_error_unexpected_syntax(TTHEN);
Eric Andersencb57d552001-06-28 07:25:16 +000010620 n1->nif.ifpart = list(0);
10621 n2 = n1;
10622 while (readtoken() == TELIF) {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010623 n2->nif.elsepart = stzalloc(sizeof(struct nif));
Eric Andersencb57d552001-06-28 07:25:16 +000010624 n2 = n2->nif.elsepart;
10625 n2->type = NIF;
10626 n2->nif.test = list(0);
10627 if (readtoken() != TTHEN)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010628 raise_error_unexpected_syntax(TTHEN);
Eric Andersencb57d552001-06-28 07:25:16 +000010629 n2->nif.ifpart = list(0);
10630 }
10631 if (lasttoken == TELSE)
10632 n2->nif.elsepart = list(0);
10633 else {
10634 n2->nif.elsepart = NULL;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010635 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010636 }
Eric Andersenc470f442003-07-28 09:56:35 +000010637 t = TFI;
Eric Andersencb57d552001-06-28 07:25:16 +000010638 break;
10639 case TWHILE:
Eric Andersenc470f442003-07-28 09:56:35 +000010640 case TUNTIL: {
Eric Andersencb57d552001-06-28 07:25:16 +000010641 int got;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010642 n1 = stzalloc(sizeof(struct nbinary));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010643 n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
Eric Andersencb57d552001-06-28 07:25:16 +000010644 n1->nbinary.ch1 = list(0);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010645 got = readtoken();
10646 if (got != TDO) {
Denis Vlasenko131ae172007-02-18 13:00:19 +000010647 TRACE(("expecting DO got %s %s\n", tokname(got),
10648 got == TWORD ? wordtext : ""));
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010649 raise_error_unexpected_syntax(TDO);
Eric Andersencb57d552001-06-28 07:25:16 +000010650 }
10651 n1->nbinary.ch2 = list(0);
Eric Andersenc470f442003-07-28 09:56:35 +000010652 t = TDONE;
Eric Andersencb57d552001-06-28 07:25:16 +000010653 break;
10654 }
10655 case TFOR:
Denis Vlasenko2dc240c2008-07-24 06:07:50 +000010656 if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
Denis Vlasenko559691a2008-10-05 18:39:31 +000010657 raise_error_syntax("bad for loop variable");
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010658 n1 = stzalloc(sizeof(struct nfor));
Eric Andersencb57d552001-06-28 07:25:16 +000010659 n1->type = NFOR;
10660 n1->nfor.var = wordtext;
Eric Andersenc470f442003-07-28 09:56:35 +000010661 checkkwd = CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010662 if (readtoken() == TIN) {
10663 app = &ap;
10664 while (readtoken() == TWORD) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010665 n2 = stzalloc(sizeof(struct narg));
Eric Andersencb57d552001-06-28 07:25:16 +000010666 n2->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010667 /*n2->narg.next = NULL; - stzalloc did it */
Eric Andersencb57d552001-06-28 07:25:16 +000010668 n2->narg.text = wordtext;
10669 n2->narg.backquote = backquotelist;
10670 *app = n2;
10671 app = &n2->narg.next;
10672 }
10673 *app = NULL;
10674 n1->nfor.args = ap;
10675 if (lasttoken != TNL && lasttoken != TSEMI)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010676 raise_error_unexpected_syntax(-1);
Eric Andersencb57d552001-06-28 07:25:16 +000010677 } else {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010678 n2 = stzalloc(sizeof(struct narg));
Eric Andersencb57d552001-06-28 07:25:16 +000010679 n2->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010680 /*n2->narg.next = NULL; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000010681 n2->narg.text = (char *)dolatstr;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010682 /*n2->narg.backquote = NULL;*/
Eric Andersencb57d552001-06-28 07:25:16 +000010683 n1->nfor.args = n2;
10684 /*
10685 * Newline or semicolon here is optional (but note
10686 * that the original Bourne shell only allowed NL).
10687 */
10688 if (lasttoken != TNL && lasttoken != TSEMI)
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010689 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010690 }
Eric Andersenc470f442003-07-28 09:56:35 +000010691 checkkwd = CHKNL | CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010692 if (readtoken() != TDO)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010693 raise_error_unexpected_syntax(TDO);
Eric Andersencb57d552001-06-28 07:25:16 +000010694 n1->nfor.body = list(0);
Eric Andersenc470f442003-07-28 09:56:35 +000010695 t = TDONE;
Eric Andersencb57d552001-06-28 07:25:16 +000010696 break;
10697 case TCASE:
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010698 n1 = stzalloc(sizeof(struct ncase));
Eric Andersencb57d552001-06-28 07:25:16 +000010699 n1->type = NCASE;
10700 if (readtoken() != TWORD)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010701 raise_error_unexpected_syntax(TWORD);
Denis Vlasenko597906c2008-02-20 16:38:54 +000010702 n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
Eric Andersencb57d552001-06-28 07:25:16 +000010703 n2->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010704 /*n2->narg.next = NULL; - stzalloc did it */
Eric Andersencb57d552001-06-28 07:25:16 +000010705 n2->narg.text = wordtext;
10706 n2->narg.backquote = backquotelist;
Eric Andersencb57d552001-06-28 07:25:16 +000010707 do {
Eric Andersenc470f442003-07-28 09:56:35 +000010708 checkkwd = CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010709 } while (readtoken() == TNL);
10710 if (lasttoken != TIN)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010711 raise_error_unexpected_syntax(TIN);
Eric Andersencb57d552001-06-28 07:25:16 +000010712 cpp = &n1->ncase.cases;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010713 next_case:
Eric Andersenc470f442003-07-28 09:56:35 +000010714 checkkwd = CHKNL | CHKKWD;
10715 t = readtoken();
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010716 while (t != TESAC) {
Eric Andersencb57d552001-06-28 07:25:16 +000010717 if (lasttoken == TLP)
10718 readtoken();
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010719 *cpp = cp = stzalloc(sizeof(struct nclist));
Eric Andersencb57d552001-06-28 07:25:16 +000010720 cp->type = NCLIST;
10721 app = &cp->nclist.pattern;
10722 for (;;) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010723 *app = ap = stzalloc(sizeof(struct narg));
Eric Andersencb57d552001-06-28 07:25:16 +000010724 ap->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010725 /*ap->narg.next = NULL; - stzalloc did it */
Eric Andersencb57d552001-06-28 07:25:16 +000010726 ap->narg.text = wordtext;
10727 ap->narg.backquote = backquotelist;
Eric Andersenc470f442003-07-28 09:56:35 +000010728 if (readtoken() != TPIPE)
Eric Andersencb57d552001-06-28 07:25:16 +000010729 break;
10730 app = &ap->narg.next;
10731 readtoken();
10732 }
Denis Vlasenko597906c2008-02-20 16:38:54 +000010733 //ap->narg.next = NULL;
Eric Andersencb57d552001-06-28 07:25:16 +000010734 if (lasttoken != TRP)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010735 raise_error_unexpected_syntax(TRP);
Eric Andersenc470f442003-07-28 09:56:35 +000010736 cp->nclist.body = list(2);
Eric Andersencb57d552001-06-28 07:25:16 +000010737
Eric Andersenc470f442003-07-28 09:56:35 +000010738 cpp = &cp->nclist.next;
10739
10740 checkkwd = CHKNL | CHKKWD;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010741 t = readtoken();
10742 if (t != TESAC) {
Eric Andersencb57d552001-06-28 07:25:16 +000010743 if (t != TENDCASE)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010744 raise_error_unexpected_syntax(TENDCASE);
10745 goto next_case;
Eric Andersencb57d552001-06-28 07:25:16 +000010746 }
Eric Andersenc470f442003-07-28 09:56:35 +000010747 }
Eric Andersencb57d552001-06-28 07:25:16 +000010748 *cpp = NULL;
Eric Andersenc470f442003-07-28 09:56:35 +000010749 goto redir;
Eric Andersencb57d552001-06-28 07:25:16 +000010750 case TLP:
Denis Vlasenko597906c2008-02-20 16:38:54 +000010751 n1 = stzalloc(sizeof(struct nredir));
Eric Andersencb57d552001-06-28 07:25:16 +000010752 n1->type = NSUBSHELL;
10753 n1->nredir.n = list(0);
Denis Vlasenko597906c2008-02-20 16:38:54 +000010754 /*n1->nredir.redirect = NULL; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000010755 t = TRP;
Eric Andersencb57d552001-06-28 07:25:16 +000010756 break;
10757 case TBEGIN:
10758 n1 = list(0);
Eric Andersenc470f442003-07-28 09:56:35 +000010759 t = TEND;
Eric Andersencb57d552001-06-28 07:25:16 +000010760 break;
Eric Andersencb57d552001-06-28 07:25:16 +000010761 case TWORD:
Eric Andersenc470f442003-07-28 09:56:35 +000010762 case TREDIR:
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010763 tokpushback = 1;
Eric Andersenc470f442003-07-28 09:56:35 +000010764 return simplecmd();
Eric Andersencb57d552001-06-28 07:25:16 +000010765 }
10766
Eric Andersenc470f442003-07-28 09:56:35 +000010767 if (readtoken() != t)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010768 raise_error_unexpected_syntax(t);
Eric Andersenc470f442003-07-28 09:56:35 +000010769
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010770 redir:
Eric Andersencb57d552001-06-28 07:25:16 +000010771 /* Now check for redirection which may follow command */
Eric Andersenc470f442003-07-28 09:56:35 +000010772 checkkwd = CHKKWD | CHKALIAS;
10773 rpp = rpp2;
Eric Andersencb57d552001-06-28 07:25:16 +000010774 while (readtoken() == TREDIR) {
10775 *rpp = n2 = redirnode;
10776 rpp = &n2->nfile.next;
10777 parsefname();
10778 }
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010779 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010780 *rpp = NULL;
10781 if (redir) {
10782 if (n1->type != NSUBSHELL) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010783 n2 = stzalloc(sizeof(struct nredir));
Eric Andersencb57d552001-06-28 07:25:16 +000010784 n2->type = NREDIR;
10785 n2->nredir.n = n1;
10786 n1 = n2;
10787 }
10788 n1->nredir.redirect = redir;
10789 }
Eric Andersencb57d552001-06-28 07:25:16 +000010790 return n1;
10791}
10792
Denis Vlasenkoef527f52008-06-23 01:52:30 +000010793#if ENABLE_ASH_BASH_COMPAT
10794static int decode_dollar_squote(void)
10795{
10796 static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
10797 int c, cnt;
10798 char *p;
10799 char buf[4];
10800
10801 c = pgetc();
10802 p = strchr(C_escapes, c);
10803 if (p) {
10804 buf[0] = c;
10805 p = buf;
10806 cnt = 3;
10807 if ((unsigned char)(c - '0') <= 7) { /* \ooo */
10808 do {
10809 c = pgetc();
10810 *++p = c;
10811 } while ((unsigned char)(c - '0') <= 7 && --cnt);
10812 pungetc();
10813 } else if (c == 'x') { /* \xHH */
10814 do {
10815 c = pgetc();
10816 *++p = c;
10817 } while (isxdigit(c) && --cnt);
10818 pungetc();
10819 if (cnt == 3) { /* \x but next char is "bad" */
10820 c = 'x';
10821 goto unrecognized;
10822 }
10823 } else { /* simple seq like \\ or \t */
10824 p++;
10825 }
10826 *p = '\0';
10827 p = buf;
10828 c = bb_process_escape_sequence((void*)&p);
10829 } else { /* unrecognized "\z": print both chars unless ' or " */
10830 if (c != '\'' && c != '"') {
10831 unrecognized:
10832 c |= 0x100; /* "please encode \, then me" */
10833 }
10834 }
10835 return c;
10836}
10837#endif
10838
Eric Andersencb57d552001-06-28 07:25:16 +000010839/*
10840 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
10841 * is not NULL, read a here document. In the latter case, eofmark is the
10842 * word which marks the end of the document and striptabs is true if
10843 * leading tabs should be stripped from the document. The argument firstc
10844 * is the first character of the input token or document.
10845 *
10846 * Because C does not have internal subroutines, I have simulated them
10847 * using goto's to implement the subroutine linkage. The following macros
10848 * will run code that appears at the end of readtoken1.
10849 */
Eric Andersen2870d962001-07-02 17:27:21 +000010850#define CHECKEND() {goto checkend; checkend_return:;}
10851#define PARSEREDIR() {goto parseredir; parseredir_return:;}
10852#define PARSESUB() {goto parsesub; parsesub_return:;}
10853#define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
10854#define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
10855#define PARSEARITH() {goto parsearith; parsearith_return:;}
Eric Andersencb57d552001-06-28 07:25:16 +000010856static int
Eric Andersenc470f442003-07-28 09:56:35 +000010857readtoken1(int firstc, int syntax, char *eofmark, int striptabs)
Manuel Novoa III 16815d42001-08-10 19:36:07 +000010858{
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010859 /* NB: syntax parameter fits into smallint */
Eric Andersencb57d552001-06-28 07:25:16 +000010860 int c = firstc;
10861 char *out;
10862 int len;
10863 char line[EOFMARKLEN + 1];
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010864 struct nodelist *bqlist;
10865 smallint quotef;
10866 smallint dblquote;
10867 smallint oldstyle;
10868 smallint prevsyntax; /* syntax before arithmetic */
Denis Vlasenko46a53062007-09-24 18:30:02 +000010869#if ENABLE_ASH_EXPAND_PRMT
10870 smallint pssyntax; /* we are expanding a prompt string */
10871#endif
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010872 int varnest; /* levels of variables expansion */
10873 int arinest; /* levels of arithmetic expansion */
10874 int parenlevel; /* levels of parens in arithmetic */
10875 int dqvarnest; /* levels of variables expansion within double quotes */
10876
Denis Vlasenko5e34ff22009-04-21 11:09:40 +000010877 IF_ASH_BASH_COMPAT(smallint bash_dollar_squote = 0;)
Denis Vlasenkoef527f52008-06-23 01:52:30 +000010878
Eric Andersencb57d552001-06-28 07:25:16 +000010879#if __GNUC__
10880 /* Avoid longjmp clobbering */
10881 (void) &out;
10882 (void) &quotef;
10883 (void) &dblquote;
10884 (void) &varnest;
10885 (void) &arinest;
10886 (void) &parenlevel;
10887 (void) &dqvarnest;
10888 (void) &oldstyle;
10889 (void) &prevsyntax;
10890 (void) &syntax;
10891#endif
Denis Vlasenko41eb3002008-11-28 03:42:31 +000010892 startlinno = g_parsefile->linno;
Eric Andersencb57d552001-06-28 07:25:16 +000010893 bqlist = NULL;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010894 quotef = 0;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010895 oldstyle = 0;
10896 prevsyntax = 0;
Denis Vlasenko46a53062007-09-24 18:30:02 +000010897#if ENABLE_ASH_EXPAND_PRMT
10898 pssyntax = (syntax == PSSYNTAX);
10899 if (pssyntax)
10900 syntax = DQSYNTAX;
10901#endif
10902 dblquote = (syntax == DQSYNTAX);
Eric Andersencb57d552001-06-28 07:25:16 +000010903 varnest = 0;
10904 arinest = 0;
10905 parenlevel = 0;
10906 dqvarnest = 0;
10907
10908 STARTSTACKSTR(out);
Denis Vlasenko176d49d2008-10-06 09:51:47 +000010909 loop:
10910 /* For each line, until end of word */
10911 {
Eric Andersenc470f442003-07-28 09:56:35 +000010912 CHECKEND(); /* set c to PEOF if at end of here document */
10913 for (;;) { /* until end of line or end of word */
10914 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
Denis Vlasenkobf0a2012006-12-26 10:42:51 +000010915 switch (SIT(c, syntax)) {
Eric Andersenc470f442003-07-28 09:56:35 +000010916 case CNL: /* '\n' */
Eric Andersencb57d552001-06-28 07:25:16 +000010917 if (syntax == BASESYNTAX)
Eric Andersenc470f442003-07-28 09:56:35 +000010918 goto endword; /* exit outer loop */
Eric Andersencb57d552001-06-28 07:25:16 +000010919 USTPUTC(c, out);
Denis Vlasenko41eb3002008-11-28 03:42:31 +000010920 g_parsefile->linno++;
Eric Andersencb57d552001-06-28 07:25:16 +000010921 if (doprompt)
10922 setprompt(2);
Eric Andersencb57d552001-06-28 07:25:16 +000010923 c = pgetc();
Eric Andersenc470f442003-07-28 09:56:35 +000010924 goto loop; /* continue outer loop */
Eric Andersencb57d552001-06-28 07:25:16 +000010925 case CWORD:
10926 USTPUTC(c, out);
10927 break;
10928 case CCTL:
Eric Andersenc470f442003-07-28 09:56:35 +000010929 if (eofmark == NULL || dblquote)
Eric Andersencb57d552001-06-28 07:25:16 +000010930 USTPUTC(CTLESC, out);
Denis Vlasenkoef527f52008-06-23 01:52:30 +000010931#if ENABLE_ASH_BASH_COMPAT
10932 if (c == '\\' && bash_dollar_squote) {
10933 c = decode_dollar_squote();
10934 if (c & 0x100) {
10935 USTPUTC('\\', out);
10936 c = (unsigned char)c;
10937 }
10938 }
10939#endif
Eric Andersencb57d552001-06-28 07:25:16 +000010940 USTPUTC(c, out);
10941 break;
Eric Andersenc470f442003-07-28 09:56:35 +000010942 case CBACK: /* backslash */
Eric Andersencb57d552001-06-28 07:25:16 +000010943 c = pgetc2();
10944 if (c == PEOF) {
Eric Andersenc470f442003-07-28 09:56:35 +000010945 USTPUTC(CTLESC, out);
Eric Andersencb57d552001-06-28 07:25:16 +000010946 USTPUTC('\\', out);
10947 pungetc();
10948 } else if (c == '\n') {
10949 if (doprompt)
10950 setprompt(2);
Eric Andersencb57d552001-06-28 07:25:16 +000010951 } else {
Denis Vlasenko46a53062007-09-24 18:30:02 +000010952#if ENABLE_ASH_EXPAND_PRMT
10953 if (c == '$' && pssyntax) {
10954 USTPUTC(CTLESC, out);
10955 USTPUTC('\\', out);
10956 }
10957#endif
Denis Vlasenkoef527f52008-06-23 01:52:30 +000010958 if (dblquote && c != '\\'
10959 && c != '`' && c != '$'
10960 && (c != '"' || eofmark != NULL)
Eric Andersenc470f442003-07-28 09:56:35 +000010961 ) {
10962 USTPUTC(CTLESC, out);
Eric Andersencb57d552001-06-28 07:25:16 +000010963 USTPUTC('\\', out);
Eric Andersenc470f442003-07-28 09:56:35 +000010964 }
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010965 if (SIT(c, SQSYNTAX) == CCTL)
Eric Andersencb57d552001-06-28 07:25:16 +000010966 USTPUTC(CTLESC, out);
Eric Andersencb57d552001-06-28 07:25:16 +000010967 USTPUTC(c, out);
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010968 quotef = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010969 }
10970 break;
10971 case CSQUOTE:
Eric Andersencb57d552001-06-28 07:25:16 +000010972 syntax = SQSYNTAX;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010973 quotemark:
Eric Andersenc470f442003-07-28 09:56:35 +000010974 if (eofmark == NULL) {
10975 USTPUTC(CTLQUOTEMARK, out);
10976 }
Eric Andersencb57d552001-06-28 07:25:16 +000010977 break;
10978 case CDQUOTE:
Eric Andersencb57d552001-06-28 07:25:16 +000010979 syntax = DQSYNTAX;
10980 dblquote = 1;
Eric Andersenc470f442003-07-28 09:56:35 +000010981 goto quotemark;
Eric Andersencb57d552001-06-28 07:25:16 +000010982 case CENDQUOTE:
Denis Vlasenko5e34ff22009-04-21 11:09:40 +000010983 IF_ASH_BASH_COMPAT(bash_dollar_squote = 0;)
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010984 if (eofmark != NULL && arinest == 0
10985 && varnest == 0
10986 ) {
Eric Andersencb57d552001-06-28 07:25:16 +000010987 USTPUTC(c, out);
10988 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000010989 if (dqvarnest == 0) {
Eric Andersencb57d552001-06-28 07:25:16 +000010990 syntax = BASESYNTAX;
10991 dblquote = 0;
10992 }
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010993 quotef = 1;
Eric Andersenc470f442003-07-28 09:56:35 +000010994 goto quotemark;
Eric Andersencb57d552001-06-28 07:25:16 +000010995 }
10996 break;
Eric Andersenc470f442003-07-28 09:56:35 +000010997 case CVAR: /* '$' */
10998 PARSESUB(); /* parse substitution */
Eric Andersencb57d552001-06-28 07:25:16 +000010999 break;
Eric Andersenc470f442003-07-28 09:56:35 +000011000 case CENDVAR: /* '}' */
Eric Andersencb57d552001-06-28 07:25:16 +000011001 if (varnest > 0) {
11002 varnest--;
11003 if (dqvarnest > 0) {
11004 dqvarnest--;
11005 }
11006 USTPUTC(CTLENDVAR, out);
11007 } else {
11008 USTPUTC(c, out);
11009 }
11010 break;
Mike Frysinger98c52642009-04-02 10:02:37 +000011011#if ENABLE_SH_MATH_SUPPORT
Eric Andersenc470f442003-07-28 09:56:35 +000011012 case CLP: /* '(' in arithmetic */
Eric Andersencb57d552001-06-28 07:25:16 +000011013 parenlevel++;
11014 USTPUTC(c, out);
11015 break;
Eric Andersenc470f442003-07-28 09:56:35 +000011016 case CRP: /* ')' in arithmetic */
Eric Andersencb57d552001-06-28 07:25:16 +000011017 if (parenlevel > 0) {
11018 USTPUTC(c, out);
11019 --parenlevel;
11020 } else {
11021 if (pgetc() == ')') {
11022 if (--arinest == 0) {
11023 USTPUTC(CTLENDARI, out);
11024 syntax = prevsyntax;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011025 dblquote = (syntax == DQSYNTAX);
Eric Andersencb57d552001-06-28 07:25:16 +000011026 } else
11027 USTPUTC(')', out);
11028 } else {
11029 /*
11030 * unbalanced parens
11031 * (don't 2nd guess - no error)
11032 */
11033 pungetc();
11034 USTPUTC(')', out);
11035 }
11036 }
11037 break;
11038#endif
Eric Andersenc470f442003-07-28 09:56:35 +000011039 case CBQUOTE: /* '`' */
Eric Andersencb57d552001-06-28 07:25:16 +000011040 PARSEBACKQOLD();
11041 break;
Eric Andersen2870d962001-07-02 17:27:21 +000011042 case CENDFILE:
Eric Andersenc470f442003-07-28 09:56:35 +000011043 goto endword; /* exit outer loop */
Eric Andersencb57d552001-06-28 07:25:16 +000011044 case CIGN:
11045 break;
11046 default:
Denis Vlasenko834dee72008-10-07 09:18:30 +000011047 if (varnest == 0) {
11048#if ENABLE_ASH_BASH_COMPAT
11049 if (c == '&') {
11050 if (pgetc() == '>')
11051 c = 0x100 + '>'; /* flag &> */
11052 pungetc();
11053 }
11054#endif
Eric Andersenc470f442003-07-28 09:56:35 +000011055 goto endword; /* exit outer loop */
Denis Vlasenko834dee72008-10-07 09:18:30 +000011056 }
Denis Vlasenko131ae172007-02-18 13:00:19 +000011057#if ENABLE_ASH_ALIAS
Eric Andersen3102ac42001-07-06 04:26:23 +000011058 if (c != PEOA)
11059#endif
Eric Andersencb57d552001-06-28 07:25:16 +000011060 USTPUTC(c, out);
Eric Andersen3102ac42001-07-06 04:26:23 +000011061
Eric Andersencb57d552001-06-28 07:25:16 +000011062 }
Denis Vlasenko834dee72008-10-07 09:18:30 +000011063 c = pgetc_fast();
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000011064 } /* for (;;) */
Eric Andersencb57d552001-06-28 07:25:16 +000011065 }
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011066 endword:
Mike Frysinger98c52642009-04-02 10:02:37 +000011067#if ENABLE_SH_MATH_SUPPORT
Eric Andersencb57d552001-06-28 07:25:16 +000011068 if (syntax == ARISYNTAX)
Denis Vlasenko559691a2008-10-05 18:39:31 +000011069 raise_error_syntax("missing '))'");
Eric Andersenc470f442003-07-28 09:56:35 +000011070#endif
Denis Vlasenko99eb8502007-02-23 21:09:49 +000011071 if (syntax != BASESYNTAX && !parsebackquote && eofmark == NULL)
Denis Vlasenko559691a2008-10-05 18:39:31 +000011072 raise_error_syntax("unterminated quoted string");
Eric Andersencb57d552001-06-28 07:25:16 +000011073 if (varnest != 0) {
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011074 startlinno = g_parsefile->linno;
Eric Andersenc470f442003-07-28 09:56:35 +000011075 /* { */
Denis Vlasenko559691a2008-10-05 18:39:31 +000011076 raise_error_syntax("missing '}'");
Eric Andersencb57d552001-06-28 07:25:16 +000011077 }
11078 USTPUTC('\0', out);
Eric Andersenc470f442003-07-28 09:56:35 +000011079 len = out - (char *)stackblock();
Eric Andersencb57d552001-06-28 07:25:16 +000011080 out = stackblock();
11081 if (eofmark == NULL) {
Denis Vlasenko5e34ff22009-04-21 11:09:40 +000011082 if ((c == '>' || c == '<' IF_ASH_BASH_COMPAT( || c == 0x100 + '>'))
Denis Vlasenko834dee72008-10-07 09:18:30 +000011083 && quotef == 0
11084 ) {
Denis Vlasenko559691a2008-10-05 18:39:31 +000011085 if (isdigit_str9(out)) {
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000011086 PARSEREDIR(); /* passed as params: out, c */
11087 lasttoken = TREDIR;
11088 return lasttoken;
11089 }
11090 /* else: non-number X seen, interpret it
11091 * as "NNNX>file" = "NNNX >file" */
Eric Andersencb57d552001-06-28 07:25:16 +000011092 }
Denis Vlasenkoef527f52008-06-23 01:52:30 +000011093 pungetc();
Eric Andersencb57d552001-06-28 07:25:16 +000011094 }
11095 quoteflag = quotef;
11096 backquotelist = bqlist;
11097 grabstackblock(len);
11098 wordtext = out;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011099 lasttoken = TWORD;
11100 return lasttoken;
Eric Andersencb57d552001-06-28 07:25:16 +000011101/* end of readtoken routine */
11102
Eric Andersencb57d552001-06-28 07:25:16 +000011103/*
11104 * Check to see whether we are at the end of the here document. When this
11105 * is called, c is set to the first character of the next input line. If
11106 * we are at the end of the here document, this routine sets the c to PEOF.
11107 */
Eric Andersenc470f442003-07-28 09:56:35 +000011108checkend: {
11109 if (eofmark) {
Denis Vlasenko131ae172007-02-18 13:00:19 +000011110#if ENABLE_ASH_ALIAS
Eric Andersenc470f442003-07-28 09:56:35 +000011111 if (c == PEOA) {
11112 c = pgetc2();
11113 }
11114#endif
11115 if (striptabs) {
11116 while (c == '\t') {
Eric Andersencb57d552001-06-28 07:25:16 +000011117 c = pgetc2();
11118 }
Eric Andersenc470f442003-07-28 09:56:35 +000011119 }
11120 if (c == *eofmark) {
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011121 if (pfgets(line, sizeof(line)) != NULL) {
Eric Andersenc470f442003-07-28 09:56:35 +000011122 char *p, *q;
Eric Andersencb57d552001-06-28 07:25:16 +000011123
Eric Andersenc470f442003-07-28 09:56:35 +000011124 p = line;
Denis Vlasenkof7d56652008-03-25 05:51:41 +000011125 for (q = eofmark + 1; *q && *p == *q; p++, q++)
11126 continue;
Eric Andersenc470f442003-07-28 09:56:35 +000011127 if (*p == '\n' && *q == '\0') {
11128 c = PEOF;
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011129 g_parsefile->linno++;
Eric Andersenc470f442003-07-28 09:56:35 +000011130 needprompt = doprompt;
11131 } else {
11132 pushstring(line, NULL);
Eric Andersencb57d552001-06-28 07:25:16 +000011133 }
11134 }
11135 }
11136 }
Eric Andersenc470f442003-07-28 09:56:35 +000011137 goto checkend_return;
11138}
Eric Andersencb57d552001-06-28 07:25:16 +000011139
Eric Andersencb57d552001-06-28 07:25:16 +000011140/*
11141 * Parse a redirection operator. The variable "out" points to a string
11142 * specifying the fd to be redirected. The variable "c" contains the
11143 * first character of the redirection operator.
11144 */
Eric Andersenc470f442003-07-28 09:56:35 +000011145parseredir: {
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000011146 /* out is already checked to be a valid number or "" */
11147 int fd = (*out == '\0' ? -1 : atoi(out));
Eric Andersenc470f442003-07-28 09:56:35 +000011148 union node *np;
Eric Andersencb57d552001-06-28 07:25:16 +000011149
Denis Vlasenko597906c2008-02-20 16:38:54 +000011150 np = stzalloc(sizeof(struct nfile));
Eric Andersenc470f442003-07-28 09:56:35 +000011151 if (c == '>') {
11152 np->nfile.fd = 1;
11153 c = pgetc();
11154 if (c == '>')
11155 np->type = NAPPEND;
11156 else if (c == '|')
11157 np->type = NCLOBBER;
11158 else if (c == '&')
11159 np->type = NTOFD;
Denis Vlasenko559691a2008-10-05 18:39:31 +000011160 /* it also can be NTO2 (>&file), but we can't figure it out yet */
Eric Andersenc470f442003-07-28 09:56:35 +000011161 else {
11162 np->type = NTO;
11163 pungetc();
Eric Andersencb57d552001-06-28 07:25:16 +000011164 }
Denis Vlasenko834dee72008-10-07 09:18:30 +000011165 }
11166#if ENABLE_ASH_BASH_COMPAT
11167 else if (c == 0x100 + '>') { /* this flags &> redirection */
11168 np->nfile.fd = 1;
11169 pgetc(); /* this is '>', no need to check */
11170 np->type = NTO2;
11171 }
11172#endif
11173 else { /* c == '<' */
Denis Vlasenko597906c2008-02-20 16:38:54 +000011174 /*np->nfile.fd = 0; - stzalloc did it */
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011175 c = pgetc();
11176 switch (c) {
Eric Andersenc470f442003-07-28 09:56:35 +000011177 case '<':
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011178 if (sizeof(struct nfile) != sizeof(struct nhere)) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000011179 np = stzalloc(sizeof(struct nhere));
11180 /*np->nfile.fd = 0; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000011181 }
11182 np->type = NHERE;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000011183 heredoc = stzalloc(sizeof(struct heredoc));
Eric Andersenc470f442003-07-28 09:56:35 +000011184 heredoc->here = np;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011185 c = pgetc();
11186 if (c == '-') {
Eric Andersenc470f442003-07-28 09:56:35 +000011187 heredoc->striptabs = 1;
11188 } else {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000011189 /*heredoc->striptabs = 0; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000011190 pungetc();
11191 }
11192 break;
11193
11194 case '&':
11195 np->type = NFROMFD;
11196 break;
11197
11198 case '>':
11199 np->type = NFROMTO;
11200 break;
11201
11202 default:
11203 np->type = NFROM;
11204 pungetc();
11205 break;
11206 }
Eric Andersencb57d552001-06-28 07:25:16 +000011207 }
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000011208 if (fd >= 0)
11209 np->nfile.fd = fd;
Eric Andersenc470f442003-07-28 09:56:35 +000011210 redirnode = np;
11211 goto parseredir_return;
11212}
Eric Andersencb57d552001-06-28 07:25:16 +000011213
Eric Andersencb57d552001-06-28 07:25:16 +000011214/*
11215 * Parse a substitution. At this point, we have read the dollar sign
11216 * and nothing else.
11217 */
Denis Vlasenkocc571512007-02-23 21:10:35 +000011218
11219/* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
11220 * (assuming ascii char codes, as the original implementation did) */
11221#define is_special(c) \
Denis Vlasenkoef527f52008-06-23 01:52:30 +000011222 (((unsigned)(c) - 33 < 32) \
11223 && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
Eric Andersenc470f442003-07-28 09:56:35 +000011224parsesub: {
11225 int subtype;
11226 int typeloc;
11227 int flags;
11228 char *p;
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011229 static const char types[] ALIGN1 = "}-+?=";
Eric Andersencb57d552001-06-28 07:25:16 +000011230
Eric Andersenc470f442003-07-28 09:56:35 +000011231 c = pgetc();
Denis Vlasenkoef527f52008-06-23 01:52:30 +000011232 if (c <= PEOA_OR_PEOF
11233 || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
Eric Andersenc470f442003-07-28 09:56:35 +000011234 ) {
Denis Vlasenkoef527f52008-06-23 01:52:30 +000011235#if ENABLE_ASH_BASH_COMPAT
11236 if (c == '\'')
11237 bash_dollar_squote = 1;
11238 else
11239#endif
11240 USTPUTC('$', out);
Eric Andersenc470f442003-07-28 09:56:35 +000011241 pungetc();
11242 } else if (c == '(') { /* $(command) or $((arith)) */
11243 if (pgetc() == '(') {
Mike Frysinger98c52642009-04-02 10:02:37 +000011244#if ENABLE_SH_MATH_SUPPORT
Eric Andersenc470f442003-07-28 09:56:35 +000011245 PARSEARITH();
11246#else
Mike Frysinger98a6f562008-06-09 09:38:45 +000011247 raise_error_syntax("you disabled math support for $((arith)) syntax");
Eric Andersenc470f442003-07-28 09:56:35 +000011248#endif
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000011249 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000011250 pungetc();
11251 PARSEBACKQNEW();
11252 }
11253 } else {
11254 USTPUTC(CTLVAR, out);
11255 typeloc = out - (char *)stackblock();
11256 USTPUTC(VSNORMAL, out);
11257 subtype = VSNORMAL;
11258 if (c == '{') {
11259 c = pgetc();
11260 if (c == '#') {
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011261 c = pgetc();
11262 if (c == '}')
Eric Andersenc470f442003-07-28 09:56:35 +000011263 c = '#';
11264 else
11265 subtype = VSLENGTH;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011266 } else
Eric Andersenc470f442003-07-28 09:56:35 +000011267 subtype = 0;
11268 }
11269 if (c > PEOA_OR_PEOF && is_name(c)) {
11270 do {
11271 STPUTC(c, out);
Eric Andersencb57d552001-06-28 07:25:16 +000011272 c = pgetc();
Eric Andersenc470f442003-07-28 09:56:35 +000011273 } while (c > PEOA_OR_PEOF && is_in_name(c));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011274 } else if (isdigit(c)) {
Eric Andersenc470f442003-07-28 09:56:35 +000011275 do {
11276 STPUTC(c, out);
11277 c = pgetc();
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011278 } while (isdigit(c));
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011279 } else if (is_special(c)) {
Eric Andersenc470f442003-07-28 09:56:35 +000011280 USTPUTC(c, out);
11281 c = pgetc();
Denis Vlasenko559691a2008-10-05 18:39:31 +000011282 } else {
11283 badsub:
11284 raise_error_syntax("bad substitution");
11285 }
Cristian Ionescu-Idbohrn301f5ec2009-10-05 02:07:23 +020011286 if (c != '}' && subtype == VSLENGTH)
11287 goto badsub;
Eric Andersencb57d552001-06-28 07:25:16 +000011288
Eric Andersenc470f442003-07-28 09:56:35 +000011289 STPUTC('=', out);
11290 flags = 0;
11291 if (subtype == 0) {
11292 switch (c) {
11293 case ':':
Eric Andersenc470f442003-07-28 09:56:35 +000011294 c = pgetc();
Denis Vlasenko92e13c22008-03-25 01:17:40 +000011295#if ENABLE_ASH_BASH_COMPAT
11296 if (c == ':' || c == '$' || isdigit(c)) {
11297 pungetc();
11298 subtype = VSSUBSTR;
11299 break;
11300 }
11301#endif
11302 flags = VSNUL;
Eric Andersenc470f442003-07-28 09:56:35 +000011303 /*FALLTHROUGH*/
11304 default:
11305 p = strchr(types, c);
11306 if (p == NULL)
11307 goto badsub;
11308 subtype = p - types + VSNORMAL;
11309 break;
11310 case '%':
Denis Vlasenko92e13c22008-03-25 01:17:40 +000011311 case '#': {
11312 int cc = c;
11313 subtype = c == '#' ? VSTRIMLEFT : VSTRIMRIGHT;
11314 c = pgetc();
11315 if (c == cc)
11316 subtype++;
11317 else
11318 pungetc();
11319 break;
11320 }
11321#if ENABLE_ASH_BASH_COMPAT
11322 case '/':
11323 subtype = VSREPLACE;
11324 c = pgetc();
11325 if (c == '/')
11326 subtype++; /* VSREPLACEALL */
11327 else
11328 pungetc();
11329 break;
11330#endif
Eric Andersencb57d552001-06-28 07:25:16 +000011331 }
Eric Andersenc470f442003-07-28 09:56:35 +000011332 } else {
11333 pungetc();
11334 }
11335 if (dblquote || arinest)
11336 flags |= VSQUOTE;
11337 *((char *)stackblock() + typeloc) = subtype | flags;
11338 if (subtype != VSNORMAL) {
11339 varnest++;
11340 if (dblquote || arinest) {
11341 dqvarnest++;
Eric Andersencb57d552001-06-28 07:25:16 +000011342 }
11343 }
11344 }
Eric Andersenc470f442003-07-28 09:56:35 +000011345 goto parsesub_return;
11346}
Eric Andersencb57d552001-06-28 07:25:16 +000011347
Eric Andersencb57d552001-06-28 07:25:16 +000011348/*
11349 * Called to parse command substitutions. Newstyle is set if the command
11350 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
11351 * list of commands (passed by reference), and savelen is the number of
11352 * characters on the top of the stack which must be preserved.
11353 */
Eric Andersenc470f442003-07-28 09:56:35 +000011354parsebackq: {
11355 struct nodelist **nlpp;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011356 smallint savepbq;
Eric Andersenc470f442003-07-28 09:56:35 +000011357 union node *n;
11358 char *volatile str;
11359 struct jmploc jmploc;
11360 struct jmploc *volatile savehandler;
11361 size_t savelen;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011362 smallint saveprompt = 0;
11363
Eric Andersencb57d552001-06-28 07:25:16 +000011364#ifdef __GNUC__
Eric Andersenc470f442003-07-28 09:56:35 +000011365 (void) &saveprompt;
Eric Andersencb57d552001-06-28 07:25:16 +000011366#endif
Eric Andersenc470f442003-07-28 09:56:35 +000011367 savepbq = parsebackquote;
11368 if (setjmp(jmploc.loc)) {
Denis Vlasenko60818682007-09-28 22:07:23 +000011369 free(str);
Eric Andersenc470f442003-07-28 09:56:35 +000011370 parsebackquote = 0;
Denis Vlasenko2da584f2007-02-19 22:44:05 +000011371 exception_handler = savehandler;
11372 longjmp(exception_handler->loc, 1);
Eric Andersenc470f442003-07-28 09:56:35 +000011373 }
Denis Vlasenkob012b102007-02-19 22:43:01 +000011374 INT_OFF;
Eric Andersenc470f442003-07-28 09:56:35 +000011375 str = NULL;
11376 savelen = out - (char *)stackblock();
11377 if (savelen > 0) {
11378 str = ckmalloc(savelen);
11379 memcpy(str, stackblock(), savelen);
11380 }
Denis Vlasenko2da584f2007-02-19 22:44:05 +000011381 savehandler = exception_handler;
11382 exception_handler = &jmploc;
Denis Vlasenkob012b102007-02-19 22:43:01 +000011383 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +000011384 if (oldstyle) {
11385 /* We must read until the closing backquote, giving special
11386 treatment to some slashes, and then push the string and
11387 reread it as input, interpreting it normally. */
11388 char *pout;
11389 int pc;
11390 size_t psavelen;
11391 char *pstr;
11392
11393
11394 STARTSTACKSTR(pout);
11395 for (;;) {
11396 if (needprompt) {
11397 setprompt(2);
Eric Andersenc470f442003-07-28 09:56:35 +000011398 }
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011399 pc = pgetc();
11400 switch (pc) {
Eric Andersenc470f442003-07-28 09:56:35 +000011401 case '`':
11402 goto done;
11403
11404 case '\\':
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011405 pc = pgetc();
11406 if (pc == '\n') {
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011407 g_parsefile->linno++;
Eric Andersenc470f442003-07-28 09:56:35 +000011408 if (doprompt)
11409 setprompt(2);
11410 /*
11411 * If eating a newline, avoid putting
11412 * the newline into the new character
11413 * stream (via the STPUTC after the
11414 * switch).
11415 */
11416 continue;
11417 }
11418 if (pc != '\\' && pc != '`' && pc != '$'
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011419 && (!dblquote || pc != '"'))
Eric Andersenc470f442003-07-28 09:56:35 +000011420 STPUTC('\\', pout);
11421 if (pc > PEOA_OR_PEOF) {
11422 break;
11423 }
11424 /* fall through */
11425
11426 case PEOF:
Denis Vlasenko131ae172007-02-18 13:00:19 +000011427#if ENABLE_ASH_ALIAS
Eric Andersenc470f442003-07-28 09:56:35 +000011428 case PEOA:
11429#endif
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011430 startlinno = g_parsefile->linno;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000011431 raise_error_syntax("EOF in backquote substitution");
Eric Andersenc470f442003-07-28 09:56:35 +000011432
11433 case '\n':
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011434 g_parsefile->linno++;
Eric Andersenc470f442003-07-28 09:56:35 +000011435 needprompt = doprompt;
11436 break;
11437
11438 default:
11439 break;
11440 }
11441 STPUTC(pc, pout);
11442 }
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011443 done:
Eric Andersenc470f442003-07-28 09:56:35 +000011444 STPUTC('\0', pout);
11445 psavelen = pout - (char *)stackblock();
11446 if (psavelen > 0) {
11447 pstr = grabstackstr(pout);
11448 setinputstring(pstr);
11449 }
11450 }
11451 nlpp = &bqlist;
11452 while (*nlpp)
11453 nlpp = &(*nlpp)->next;
Denis Vlasenko597906c2008-02-20 16:38:54 +000011454 *nlpp = stzalloc(sizeof(**nlpp));
11455 /* (*nlpp)->next = NULL; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000011456 parsebackquote = oldstyle;
11457
11458 if (oldstyle) {
11459 saveprompt = doprompt;
11460 doprompt = 0;
Eric Andersencb57d552001-06-28 07:25:16 +000011461 }
11462
Eric Andersenc470f442003-07-28 09:56:35 +000011463 n = list(2);
11464
11465 if (oldstyle)
11466 doprompt = saveprompt;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011467 else if (readtoken() != TRP)
11468 raise_error_unexpected_syntax(TRP);
Eric Andersenc470f442003-07-28 09:56:35 +000011469
11470 (*nlpp)->n = n;
11471 if (oldstyle) {
11472 /*
11473 * Start reading from old file again, ignoring any pushed back
11474 * tokens left from the backquote parsing
11475 */
11476 popfile();
11477 tokpushback = 0;
11478 }
11479 while (stackblocksize() <= savelen)
11480 growstackblock();
11481 STARTSTACKSTR(out);
11482 if (str) {
11483 memcpy(out, str, savelen);
11484 STADJUST(savelen, out);
Denis Vlasenkob012b102007-02-19 22:43:01 +000011485 INT_OFF;
11486 free(str);
Eric Andersenc470f442003-07-28 09:56:35 +000011487 str = NULL;
Denis Vlasenkob012b102007-02-19 22:43:01 +000011488 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +000011489 }
11490 parsebackquote = savepbq;
Denis Vlasenko2da584f2007-02-19 22:44:05 +000011491 exception_handler = savehandler;
Eric Andersenc470f442003-07-28 09:56:35 +000011492 if (arinest || dblquote)
11493 USTPUTC(CTLBACKQ | CTLQUOTE, out);
11494 else
11495 USTPUTC(CTLBACKQ, out);
11496 if (oldstyle)
11497 goto parsebackq_oldreturn;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000011498 goto parsebackq_newreturn;
Eric Andersenc470f442003-07-28 09:56:35 +000011499}
11500
Mike Frysinger98c52642009-04-02 10:02:37 +000011501#if ENABLE_SH_MATH_SUPPORT
Eric Andersencb57d552001-06-28 07:25:16 +000011502/*
11503 * Parse an arithmetic expansion (indicate start of one and set state)
11504 */
Eric Andersenc470f442003-07-28 09:56:35 +000011505parsearith: {
Eric Andersenc470f442003-07-28 09:56:35 +000011506 if (++arinest == 1) {
11507 prevsyntax = syntax;
11508 syntax = ARISYNTAX;
11509 USTPUTC(CTLARI, out);
11510 if (dblquote)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000011511 USTPUTC('"', out);
Eric Andersenc470f442003-07-28 09:56:35 +000011512 else
Denis Vlasenkoa624c112007-02-19 22:45:43 +000011513 USTPUTC(' ', out);
Eric Andersenc470f442003-07-28 09:56:35 +000011514 } else {
11515 /*
11516 * we collapse embedded arithmetic expansion to
11517 * parenthesis, which should be equivalent
11518 */
11519 USTPUTC('(', out);
Eric Andersencb57d552001-06-28 07:25:16 +000011520 }
Eric Andersenc470f442003-07-28 09:56:35 +000011521 goto parsearith_return;
11522}
11523#endif
Eric Andersencb57d552001-06-28 07:25:16 +000011524
Eric Andersenc470f442003-07-28 09:56:35 +000011525} /* end of readtoken */
11526
Eric Andersencb57d552001-06-28 07:25:16 +000011527/*
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011528 * Read the next input token.
11529 * If the token is a word, we set backquotelist to the list of cmds in
11530 * backquotes. We set quoteflag to true if any part of the word was
11531 * quoted.
11532 * If the token is TREDIR, then we set redirnode to a structure containing
11533 * the redirection.
11534 * In all cases, the variable startlinno is set to the number of the line
11535 * on which the token starts.
11536 *
11537 * [Change comment: here documents and internal procedures]
11538 * [Readtoken shouldn't have any arguments. Perhaps we should make the
11539 * word parsing code into a separate routine. In this case, readtoken
11540 * doesn't need to have any internal procedures, but parseword does.
11541 * We could also make parseoperator in essence the main routine, and
11542 * have parseword (readtoken1?) handle both words and redirection.]
Eric Andersencb57d552001-06-28 07:25:16 +000011543 */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011544#define NEW_xxreadtoken
11545#ifdef NEW_xxreadtoken
11546/* singles must be first! */
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011547static const char xxreadtoken_chars[7] ALIGN1 = {
Denis Vlasenko834dee72008-10-07 09:18:30 +000011548 '\n', '(', ')', /* singles */
11549 '&', '|', ';', /* doubles */
11550 0
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011551};
Eric Andersencb57d552001-06-28 07:25:16 +000011552
Denis Vlasenko834dee72008-10-07 09:18:30 +000011553#define xxreadtoken_singles 3
11554#define xxreadtoken_doubles 3
11555
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011556static const char xxreadtoken_tokens[] ALIGN1 = {
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011557 TNL, TLP, TRP, /* only single occurrence allowed */
11558 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
11559 TEOF, /* corresponds to trailing nul */
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011560 TAND, TOR, TENDCASE /* if double occurrence */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011561};
11562
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011563static int
11564xxreadtoken(void)
11565{
11566 int c;
11567
11568 if (tokpushback) {
11569 tokpushback = 0;
11570 return lasttoken;
Eric Andersencb57d552001-06-28 07:25:16 +000011571 }
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011572 if (needprompt) {
11573 setprompt(2);
11574 }
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011575 startlinno = g_parsefile->linno;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011576 for (;;) { /* until token or start of word found */
Denis Vlasenko834dee72008-10-07 09:18:30 +000011577 c = pgetc_fast();
Denis Vlasenko5e34ff22009-04-21 11:09:40 +000011578 if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011579 continue;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011580
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011581 if (c == '#') {
11582 while ((c = pgetc()) != '\n' && c != PEOF)
11583 continue;
11584 pungetc();
11585 } else if (c == '\\') {
11586 if (pgetc() != '\n') {
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011587 pungetc();
Denis Vlasenko834dee72008-10-07 09:18:30 +000011588 break; /* return readtoken1(...) */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011589 }
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011590 startlinno = ++g_parsefile->linno;
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011591 if (doprompt)
11592 setprompt(2);
11593 } else {
11594 const char *p;
11595
11596 p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
11597 if (c != PEOF) {
11598 if (c == '\n') {
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011599 g_parsefile->linno++;
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011600 needprompt = doprompt;
11601 }
11602
11603 p = strchr(xxreadtoken_chars, c);
Denis Vlasenko834dee72008-10-07 09:18:30 +000011604 if (p == NULL)
11605 break; /* return readtoken1(...) */
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011606
Denis Vlasenko834dee72008-10-07 09:18:30 +000011607 if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
11608 int cc = pgetc();
11609 if (cc == c) { /* double occurrence? */
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011610 p += xxreadtoken_doubles + 1;
11611 } else {
11612 pungetc();
Denis Vlasenko834dee72008-10-07 09:18:30 +000011613#if ENABLE_ASH_BASH_COMPAT
11614 if (c == '&' && cc == '>') /* &> */
11615 break; /* return readtoken1(...) */
11616#endif
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011617 }
11618 }
11619 }
11620 lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
11621 return lasttoken;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011622 }
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011623 } /* for (;;) */
Denis Vlasenko834dee72008-10-07 09:18:30 +000011624
11625 return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011626}
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011627#else /* old xxreadtoken */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011628#define RETURN(token) return lasttoken = token
11629static int
11630xxreadtoken(void)
11631{
11632 int c;
11633
11634 if (tokpushback) {
11635 tokpushback = 0;
11636 return lasttoken;
11637 }
11638 if (needprompt) {
11639 setprompt(2);
11640 }
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011641 startlinno = g_parsefile->linno;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011642 for (;;) { /* until token or start of word found */
Denis Vlasenko834dee72008-10-07 09:18:30 +000011643 c = pgetc_fast();
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011644 switch (c) {
11645 case ' ': case '\t':
11646#if ENABLE_ASH_ALIAS
11647 case PEOA:
11648#endif
11649 continue;
11650 case '#':
Denis Vlasenkof7d56652008-03-25 05:51:41 +000011651 while ((c = pgetc()) != '\n' && c != PEOF)
11652 continue;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011653 pungetc();
11654 continue;
11655 case '\\':
11656 if (pgetc() == '\n') {
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011657 startlinno = ++g_parsefile->linno;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011658 if (doprompt)
11659 setprompt(2);
11660 continue;
11661 }
11662 pungetc();
11663 goto breakloop;
11664 case '\n':
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011665 g_parsefile->linno++;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011666 needprompt = doprompt;
11667 RETURN(TNL);
11668 case PEOF:
11669 RETURN(TEOF);
11670 case '&':
11671 if (pgetc() == '&')
11672 RETURN(TAND);
11673 pungetc();
11674 RETURN(TBACKGND);
11675 case '|':
11676 if (pgetc() == '|')
11677 RETURN(TOR);
11678 pungetc();
11679 RETURN(TPIPE);
11680 case ';':
11681 if (pgetc() == ';')
11682 RETURN(TENDCASE);
11683 pungetc();
11684 RETURN(TSEMI);
11685 case '(':
11686 RETURN(TLP);
11687 case ')':
11688 RETURN(TRP);
11689 default:
11690 goto breakloop;
11691 }
11692 }
11693 breakloop:
11694 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
11695#undef RETURN
11696}
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011697#endif /* old xxreadtoken */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011698
11699static int
11700readtoken(void)
11701{
11702 int t;
11703#if DEBUG
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011704 smallint alreadyseen = tokpushback;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011705#endif
11706
11707#if ENABLE_ASH_ALIAS
11708 top:
11709#endif
11710
11711 t = xxreadtoken();
11712
11713 /*
11714 * eat newlines
11715 */
11716 if (checkkwd & CHKNL) {
11717 while (t == TNL) {
11718 parseheredoc();
11719 t = xxreadtoken();
11720 }
11721 }
11722
11723 if (t != TWORD || quoteflag) {
11724 goto out;
11725 }
11726
11727 /*
11728 * check for keywords
11729 */
11730 if (checkkwd & CHKKWD) {
11731 const char *const *pp;
11732
11733 pp = findkwd(wordtext);
11734 if (pp) {
11735 lasttoken = t = pp - tokname_array;
11736 TRACE(("keyword %s recognized\n", tokname(t)));
11737 goto out;
11738 }
11739 }
11740
11741 if (checkkwd & CHKALIAS) {
11742#if ENABLE_ASH_ALIAS
11743 struct alias *ap;
11744 ap = lookupalias(wordtext, 1);
11745 if (ap != NULL) {
11746 if (*ap->val) {
11747 pushstring(ap->val, ap);
11748 }
11749 goto top;
11750 }
11751#endif
11752 }
11753 out:
11754 checkkwd = 0;
11755#if DEBUG
11756 if (!alreadyseen)
11757 TRACE(("token %s %s\n", tokname(t), t == TWORD ? wordtext : ""));
11758 else
11759 TRACE(("reread token %s %s\n", tokname(t), t == TWORD ? wordtext : ""));
11760#endif
11761 return t;
Eric Andersencb57d552001-06-28 07:25:16 +000011762}
11763
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011764static char
11765peektoken(void)
11766{
11767 int t;
11768
11769 t = readtoken();
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011770 tokpushback = 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011771 return tokname_array[t][0];
11772}
Eric Andersencb57d552001-06-28 07:25:16 +000011773
11774/*
Denys Vlasenko86e83ec2009-07-23 22:07:07 +020011775 * Read and parse a command. Returns NODE_EOF on end of file.
11776 * (NULL is a valid parse tree indicating a blank line.)
Eric Andersencb57d552001-06-28 07:25:16 +000011777 */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011778static union node *
11779parsecmd(int interact)
Eric Andersen90898442003-08-06 11:20:52 +000011780{
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011781 int t;
Eric Andersencb57d552001-06-28 07:25:16 +000011782
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011783 tokpushback = 0;
11784 doprompt = interact;
11785 if (doprompt)
11786 setprompt(doprompt);
11787 needprompt = 0;
11788 t = readtoken();
11789 if (t == TEOF)
Denys Vlasenko86e83ec2009-07-23 22:07:07 +020011790 return NODE_EOF;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011791 if (t == TNL)
11792 return NULL;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011793 tokpushback = 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011794 return list(1);
11795}
11796
11797/*
11798 * Input any here documents.
11799 */
11800static void
11801parseheredoc(void)
11802{
11803 struct heredoc *here;
11804 union node *n;
11805
11806 here = heredoclist;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000011807 heredoclist = NULL;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011808
11809 while (here) {
11810 if (needprompt) {
11811 setprompt(2);
11812 }
11813 readtoken1(pgetc(), here->here->type == NHERE? SQSYNTAX : DQSYNTAX,
11814 here->eofmark, here->striptabs);
Denis Vlasenko597906c2008-02-20 16:38:54 +000011815 n = stzalloc(sizeof(struct narg));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011816 n->narg.type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000011817 /*n->narg.next = NULL; - stzalloc did it */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011818 n->narg.text = wordtext;
11819 n->narg.backquote = backquotelist;
11820 here->here->nhere.doc = n;
11821 here = here->next;
Eric Andersencb57d552001-06-28 07:25:16 +000011822 }
Eric Andersencb57d552001-06-28 07:25:16 +000011823}
11824
11825
11826/*
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +000011827 * called by editline -- any expansions to the prompt should be added here.
Eric Andersencb57d552001-06-28 07:25:16 +000011828 */
Denis Vlasenko131ae172007-02-18 13:00:19 +000011829#if ENABLE_ASH_EXPAND_PRMT
"Vladimir N. Oleynik"bef14d72005-09-05 13:25:11 +000011830static const char *
11831expandstr(const char *ps)
11832{
11833 union node n;
11834
Denis Vlasenko5c2b8142009-03-19 01:59:59 +000011835 /* XXX Fix (char *) cast. It _is_ a bug. ps is variable's value,
11836 * and token processing _can_ alter it (delete NULs etc). */
"Vladimir N. Oleynik"bef14d72005-09-05 13:25:11 +000011837 setinputstring((char *)ps);
Denis Vlasenko46a53062007-09-24 18:30:02 +000011838 readtoken1(pgetc(), PSSYNTAX, nullstr, 0);
"Vladimir N. Oleynik"bef14d72005-09-05 13:25:11 +000011839 popfile();
11840
11841 n.narg.type = NARG;
11842 n.narg.next = NULL;
11843 n.narg.text = wordtext;
11844 n.narg.backquote = backquotelist;
11845
11846 expandarg(&n, NULL, 0);
11847 return stackblock();
11848}
11849#endif
11850
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011851/*
11852 * Execute a command or commands contained in a string.
11853 */
11854static int
11855evalstring(char *s, int mask)
Eric Andersenc470f442003-07-28 09:56:35 +000011856{
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011857 union node *n;
11858 struct stackmark smark;
11859 int skip;
11860
11861 setinputstring(s);
11862 setstackmark(&smark);
11863
11864 skip = 0;
Denys Vlasenko86e83ec2009-07-23 22:07:07 +020011865 while ((n = parsecmd(0)) != NODE_EOF) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011866 evaltree(n, 0);
11867 popstackmark(&smark);
11868 skip = evalskip;
11869 if (skip)
11870 break;
11871 }
11872 popfile();
11873
11874 skip &= mask;
11875 evalskip = skip;
11876 return skip;
Eric Andersenc470f442003-07-28 09:56:35 +000011877}
11878
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011879/*
11880 * The eval command.
11881 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011882static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000011883evalcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011884{
11885 char *p;
11886 char *concat;
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011887
Denis Vlasenko68404f12008-03-17 09:00:54 +000011888 if (argv[1]) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011889 p = argv[1];
Denis Vlasenko68404f12008-03-17 09:00:54 +000011890 argv += 2;
11891 if (argv[0]) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011892 STARTSTACKSTR(concat);
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011893 for (;;) {
11894 concat = stack_putstr(p, concat);
Denis Vlasenko68404f12008-03-17 09:00:54 +000011895 p = *argv++;
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011896 if (p == NULL)
11897 break;
11898 STPUTC(' ', concat);
11899 }
11900 STPUTC('\0', concat);
11901 p = grabstackstr(concat);
11902 }
11903 evalstring(p, ~SKIPEVAL);
11904
11905 }
11906 return exitstatus;
11907}
11908
11909/*
11910 * Read and execute commands. "Top" is nonzero for the top level command
11911 * loop; it turns on prompting if the shell is interactive.
11912 */
11913static int
11914cmdloop(int top)
11915{
11916 union node *n;
11917 struct stackmark smark;
11918 int inter;
11919 int numeof = 0;
11920
11921 TRACE(("cmdloop(%d) called\n", top));
11922 for (;;) {
11923 int skip;
11924
11925 setstackmark(&smark);
11926#if JOBS
Denis Vlasenkob07a4962008-06-22 13:16:23 +000011927 if (doing_jobctl)
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011928 showjobs(stderr, SHOW_CHANGED);
11929#endif
11930 inter = 0;
11931 if (iflag && top) {
11932 inter++;
11933#if ENABLE_ASH_MAIL
11934 chkmail();
11935#endif
11936 }
11937 n = parsecmd(inter);
Denys Vlasenko7cee00e2009-07-24 01:08:03 +020011938#if DEBUG
11939 if (DEBUG > 2 && debug && (n != NODE_EOF))
Denys Vlasenko883cea42009-07-11 15:31:59 +020011940 showtree(n);
Denis Vlasenko135cecb2009-04-12 00:00:57 +000011941#endif
Denys Vlasenko86e83ec2009-07-23 22:07:07 +020011942 if (n == NODE_EOF) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011943 if (!top || numeof >= 50)
11944 break;
11945 if (!stoppedjobs()) {
11946 if (!Iflag)
11947 break;
11948 out2str("\nUse \"exit\" to leave shell.\n");
11949 }
11950 numeof++;
11951 } else if (nflag == 0) {
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +000011952 /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
11953 job_warning >>= 1;
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011954 numeof = 0;
11955 evaltree(n, 0);
11956 }
11957 popstackmark(&smark);
11958 skip = evalskip;
11959
11960 if (skip) {
11961 evalskip = 0;
11962 return skip & SKIPEVAL;
11963 }
11964 }
11965 return 0;
11966}
11967
Denis Vlasenko0dec6de2007-02-23 21:10:47 +000011968/*
11969 * Take commands from a file. To be compatible we should do a path
11970 * search for the file, which is necessary to find sub-commands.
11971 */
11972static char *
11973find_dot_file(char *name)
11974{
11975 char *fullname;
11976 const char *path = pathval();
11977 struct stat statb;
11978
11979 /* don't try this for absolute or relative paths */
11980 if (strchr(name, '/'))
11981 return name;
11982
Denis Vlasenko8ad78e12009-02-15 12:40:30 +000011983 /* IIRC standards do not say whether . is to be searched.
11984 * And it is even smaller this way, making it unconditional for now:
11985 */
11986 if (1) { /* ENABLE_ASH_BASH_COMPAT */
11987 fullname = name;
11988 goto try_cur_dir;
11989 }
11990
Denys Vlasenko82a6fb32009-06-14 19:42:12 +020011991 while ((fullname = path_advance(&path, name)) != NULL) {
Denis Vlasenko8ad78e12009-02-15 12:40:30 +000011992 try_cur_dir:
Denis Vlasenko0dec6de2007-02-23 21:10:47 +000011993 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
11994 /*
11995 * Don't bother freeing here, since it will
11996 * be freed by the caller.
11997 */
11998 return fullname;
11999 }
Denys Vlasenko82a6fb32009-06-14 19:42:12 +020012000 if (fullname != name)
12001 stunalloc(fullname);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +000012002 }
12003
12004 /* not found in the PATH */
12005 ash_msg_and_raise_error("%s: not found", name);
12006 /* NOTREACHED */
12007}
12008
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012009static int FAST_FUNC
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012010dotcmd(int argc, char **argv)
12011{
12012 struct strlist *sp;
12013 volatile struct shparam saveparam;
12014 int status = 0;
12015
12016 for (sp = cmdenviron; sp; sp = sp->next)
Denis Vlasenko4222ae42007-02-25 02:37:49 +000012017 setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012018
Denis Vlasenko68404f12008-03-17 09:00:54 +000012019 if (argv[1]) { /* That's what SVR2 does */
12020 char *fullname = find_dot_file(argv[1]);
12021 argv += 2;
12022 argc -= 2;
12023 if (argc) { /* argc > 0, argv[0] != NULL */
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012024 saveparam = shellparam;
Denis Vlasenko01631112007-12-16 17:20:38 +000012025 shellparam.malloced = 0;
Denis Vlasenko68404f12008-03-17 09:00:54 +000012026 shellparam.nparam = argc;
12027 shellparam.p = argv;
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012028 };
12029
12030 setinputfile(fullname, INPUT_PUSH_FILE);
12031 commandname = fullname;
12032 cmdloop(0);
12033 popfile();
12034
Denis Vlasenko68404f12008-03-17 09:00:54 +000012035 if (argc) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012036 freeparam(&shellparam);
12037 shellparam = saveparam;
12038 };
12039 status = exitstatus;
12040 }
12041 return status;
12042}
12043
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012044static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012045exitcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012046{
12047 if (stoppedjobs())
12048 return 0;
Denis Vlasenko68404f12008-03-17 09:00:54 +000012049 if (argv[1])
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012050 exitstatus = number(argv[1]);
12051 raise_exception(EXEXIT);
12052 /* NOTREACHED */
12053}
12054
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012055/*
12056 * Read a file containing shell functions.
12057 */
12058static void
12059readcmdfile(char *name)
12060{
12061 setinputfile(name, INPUT_PUSH_FILE);
12062 cmdloop(0);
12063 popfile();
12064}
12065
12066
Denis Vlasenkocc571512007-02-23 21:10:35 +000012067/* ============ find_command inplementation */
12068
12069/*
12070 * Resolve a command name. If you change this routine, you may have to
12071 * change the shellexec routine as well.
12072 */
12073static void
12074find_command(char *name, struct cmdentry *entry, int act, const char *path)
12075{
12076 struct tblentry *cmdp;
12077 int idx;
12078 int prev;
12079 char *fullname;
12080 struct stat statb;
12081 int e;
12082 int updatetbl;
12083 struct builtincmd *bcmd;
12084
12085 /* If name contains a slash, don't use PATH or hash table */
12086 if (strchr(name, '/') != NULL) {
12087 entry->u.index = -1;
12088 if (act & DO_ABS) {
12089 while (stat(name, &statb) < 0) {
12090#ifdef SYSV
12091 if (errno == EINTR)
12092 continue;
12093#endif
12094 entry->cmdtype = CMDUNKNOWN;
12095 return;
12096 }
12097 }
12098 entry->cmdtype = CMDNORMAL;
12099 return;
12100 }
12101
Denis Vlasenkof20de5b2007-04-29 23:42:54 +000012102/* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
Denis Vlasenkocc571512007-02-23 21:10:35 +000012103
12104 updatetbl = (path == pathval());
12105 if (!updatetbl) {
12106 act |= DO_ALTPATH;
12107 if (strstr(path, "%builtin") != NULL)
12108 act |= DO_ALTBLTIN;
12109 }
12110
12111 /* If name is in the table, check answer will be ok */
12112 cmdp = cmdlookup(name, 0);
12113 if (cmdp != NULL) {
12114 int bit;
12115
12116 switch (cmdp->cmdtype) {
12117 default:
12118#if DEBUG
12119 abort();
12120#endif
12121 case CMDNORMAL:
12122 bit = DO_ALTPATH;
12123 break;
12124 case CMDFUNCTION:
12125 bit = DO_NOFUNC;
12126 break;
12127 case CMDBUILTIN:
12128 bit = DO_ALTBLTIN;
12129 break;
12130 }
12131 if (act & bit) {
12132 updatetbl = 0;
12133 cmdp = NULL;
12134 } else if (cmdp->rehash == 0)
12135 /* if not invalidated by cd, we're done */
12136 goto success;
12137 }
12138
12139 /* If %builtin not in path, check for builtin next */
12140 bcmd = find_builtin(name);
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +000012141 if (bcmd) {
12142 if (IS_BUILTIN_REGULAR(bcmd))
12143 goto builtin_success;
12144 if (act & DO_ALTPATH) {
12145 if (!(act & DO_ALTBLTIN))
12146 goto builtin_success;
12147 } else if (builtinloc <= 0) {
12148 goto builtin_success;
Denis Vlasenko8e858e22007-03-07 09:35:43 +000012149 }
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +000012150 }
Denis Vlasenkocc571512007-02-23 21:10:35 +000012151
Denis Vlasenkof20de5b2007-04-29 23:42:54 +000012152#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko7465dbc2008-04-13 02:25:53 +000012153 {
12154 int applet_no = find_applet_by_name(name);
12155 if (applet_no >= 0) {
12156 entry->cmdtype = CMDNORMAL;
12157 entry->u.index = -2 - applet_no;
12158 return;
12159 }
Denis Vlasenkof20de5b2007-04-29 23:42:54 +000012160 }
12161#endif
12162
Denis Vlasenkocc571512007-02-23 21:10:35 +000012163 /* We have to search path. */
12164 prev = -1; /* where to start */
12165 if (cmdp && cmdp->rehash) { /* doing a rehash */
12166 if (cmdp->cmdtype == CMDBUILTIN)
12167 prev = builtinloc;
12168 else
12169 prev = cmdp->param.index;
12170 }
12171
12172 e = ENOENT;
12173 idx = -1;
12174 loop:
Denys Vlasenko82a6fb32009-06-14 19:42:12 +020012175 while ((fullname = path_advance(&path, name)) != NULL) {
Denis Vlasenkocc571512007-02-23 21:10:35 +000012176 stunalloc(fullname);
Denis Vlasenkodee82b62007-07-29 14:05:27 +000012177 /* NB: code below will still use fullname
12178 * despite it being "unallocated" */
Denis Vlasenkocc571512007-02-23 21:10:35 +000012179 idx++;
12180 if (pathopt) {
12181 if (prefix(pathopt, "builtin")) {
12182 if (bcmd)
12183 goto builtin_success;
12184 continue;
Denis Vlasenko4a9ca132008-04-12 20:07:08 +000012185 }
12186 if ((act & DO_NOFUNC)
12187 || !prefix(pathopt, "func")
12188 ) { /* ignore unimplemented options */
Denis Vlasenkocc571512007-02-23 21:10:35 +000012189 continue;
12190 }
12191 }
12192 /* if rehash, don't redo absolute path names */
12193 if (fullname[0] == '/' && idx <= prev) {
12194 if (idx < prev)
12195 continue;
12196 TRACE(("searchexec \"%s\": no change\n", name));
12197 goto success;
12198 }
12199 while (stat(fullname, &statb) < 0) {
12200#ifdef SYSV
12201 if (errno == EINTR)
12202 continue;
12203#endif
12204 if (errno != ENOENT && errno != ENOTDIR)
12205 e = errno;
12206 goto loop;
12207 }
12208 e = EACCES; /* if we fail, this will be the error */
12209 if (!S_ISREG(statb.st_mode))
12210 continue;
12211 if (pathopt) { /* this is a %func directory */
12212 stalloc(strlen(fullname) + 1);
Denis Vlasenkodee82b62007-07-29 14:05:27 +000012213 /* NB: stalloc will return space pointed by fullname
12214 * (because we don't have any intervening allocations
12215 * between stunalloc above and this stalloc) */
Denis Vlasenkocc571512007-02-23 21:10:35 +000012216 readcmdfile(fullname);
12217 cmdp = cmdlookup(name, 0);
12218 if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
12219 ash_msg_and_raise_error("%s not defined in %s", name, fullname);
12220 stunalloc(fullname);
12221 goto success;
12222 }
12223 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
12224 if (!updatetbl) {
12225 entry->cmdtype = CMDNORMAL;
12226 entry->u.index = idx;
12227 return;
12228 }
12229 INT_OFF;
12230 cmdp = cmdlookup(name, 1);
12231 cmdp->cmdtype = CMDNORMAL;
12232 cmdp->param.index = idx;
12233 INT_ON;
12234 goto success;
12235 }
12236
12237 /* We failed. If there was an entry for this command, delete it */
12238 if (cmdp && updatetbl)
12239 delete_cmd_entry();
12240 if (act & DO_ERR)
12241 ash_msg("%s: %s", name, errmsg(e, "not found"));
12242 entry->cmdtype = CMDUNKNOWN;
12243 return;
12244
12245 builtin_success:
12246 if (!updatetbl) {
12247 entry->cmdtype = CMDBUILTIN;
12248 entry->u.cmd = bcmd;
12249 return;
12250 }
12251 INT_OFF;
12252 cmdp = cmdlookup(name, 1);
12253 cmdp->cmdtype = CMDBUILTIN;
12254 cmdp->param.cmd = bcmd;
12255 INT_ON;
12256 success:
12257 cmdp->rehash = 0;
12258 entry->cmdtype = cmdp->cmdtype;
12259 entry->u = cmdp->param;
12260}
12261
12262
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012263/* ============ trap.c */
Eric Andersenc470f442003-07-28 09:56:35 +000012264
Eric Andersencb57d552001-06-28 07:25:16 +000012265/*
Eric Andersencb57d552001-06-28 07:25:16 +000012266 * The trap builtin.
12267 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012268static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012269trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersencb57d552001-06-28 07:25:16 +000012270{
12271 char *action;
12272 char **ap;
12273 int signo;
12274
Eric Andersenc470f442003-07-28 09:56:35 +000012275 nextopt(nullstr);
12276 ap = argptr;
12277 if (!*ap) {
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012278 for (signo = 0; signo < NSIG; signo++) {
Denys Vlasenko21d87d42009-09-25 00:06:51 +020012279 char *tr = trap_ptr[signo];
12280 if (tr) {
Denys Vlasenkoe74aaf92009-09-27 02:05:45 +020012281 /* note: bash adds "SIG", but only if invoked
12282 * as "bash". If called as "sh", or if set -o posix,
12283 * then it prints short signal names.
12284 * We are printing short names: */
12285 out1fmt("trap -- %s %s\n",
Denys Vlasenko21d87d42009-09-25 00:06:51 +020012286 single_quote(tr),
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +000012287 get_signame(signo));
Denys Vlasenko726e1a02009-09-25 02:58:20 +020012288 /* trap_ptr != trap only if we are in special-cased `trap` code.
12289 * In this case, we will exit very soon, no need to free(). */
Denys Vlasenkoe74aaf92009-09-27 02:05:45 +020012290 /* if (trap_ptr != trap && tp[0]) */
Denys Vlasenko726e1a02009-09-25 02:58:20 +020012291 /* free(tr); */
Eric Andersencb57d552001-06-28 07:25:16 +000012292 }
12293 }
Denys Vlasenko726e1a02009-09-25 02:58:20 +020012294 /*
Denys Vlasenko21d87d42009-09-25 00:06:51 +020012295 if (trap_ptr != trap) {
12296 free(trap_ptr);
12297 trap_ptr = trap;
12298 }
Denys Vlasenko726e1a02009-09-25 02:58:20 +020012299 */
Eric Andersencb57d552001-06-28 07:25:16 +000012300 return 0;
12301 }
Denys Vlasenko21d87d42009-09-25 00:06:51 +020012302
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +000012303 action = NULL;
12304 if (ap[1])
Eric Andersencb57d552001-06-28 07:25:16 +000012305 action = *ap++;
12306 while (*ap) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +000012307 signo = get_signum(*ap);
12308 if (signo < 0)
Denis Vlasenkob012b102007-02-19 22:43:01 +000012309 ash_msg_and_raise_error("%s: bad trap", *ap);
12310 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +000012311 if (action) {
Denis Vlasenko9f739442006-12-16 23:49:13 +000012312 if (LONE_DASH(action))
Eric Andersencb57d552001-06-28 07:25:16 +000012313 action = NULL;
12314 else
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012315 action = ckstrdup(action);
Eric Andersencb57d552001-06-28 07:25:16 +000012316 }
Denis Vlasenko60818682007-09-28 22:07:23 +000012317 free(trap[signo]);
Eric Andersencb57d552001-06-28 07:25:16 +000012318 trap[signo] = action;
12319 if (signo != 0)
12320 setsignal(signo);
Denis Vlasenkob012b102007-02-19 22:43:01 +000012321 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +000012322 ap++;
12323 }
12324 return 0;
12325}
12326
Eric Andersenc470f442003-07-28 09:56:35 +000012327
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012328/* ============ Builtins */
Eric Andersenc470f442003-07-28 09:56:35 +000012329
Denis Vlasenko8e1c7152007-01-22 07:21:38 +000012330#if !ENABLE_FEATURE_SH_EXTRA_QUIET
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012331/*
12332 * Lists available builtins
12333 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012334static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012335helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersenc470f442003-07-28 09:56:35 +000012336{
Denis Vlasenko6b06cb82008-05-15 21:30:45 +000012337 unsigned col;
12338 unsigned i;
Eric Andersenc470f442003-07-28 09:56:35 +000012339
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +020012340 out1fmt(
Denis Vlasenko34d4d892009-04-04 20:24:37 +000012341 "Built-in commands:\n"
12342 "------------------\n");
Denis Vlasenkob71c6682007-07-21 15:08:09 +000012343 for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
Eric Andersenc470f442003-07-28 09:56:35 +000012344 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
Denis Vlasenko52764022007-02-24 13:42:56 +000012345 builtintab[i].name + 1);
Eric Andersenc470f442003-07-28 09:56:35 +000012346 if (col > 60) {
12347 out1fmt("\n");
12348 col = 0;
12349 }
12350 }
Denis Vlasenko80d14be2007-04-10 23:03:30 +000012351#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko1aa7e472007-11-28 06:49:03 +000012352 {
12353 const char *a = applet_names;
12354 while (*a) {
12355 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
12356 if (col > 60) {
12357 out1fmt("\n");
12358 col = 0;
12359 }
12360 a += strlen(a) + 1;
Eric Andersenc470f442003-07-28 09:56:35 +000012361 }
12362 }
12363#endif
12364 out1fmt("\n\n");
12365 return EXIT_SUCCESS;
12366}
Denis Vlasenko131ae172007-02-18 13:00:19 +000012367#endif /* FEATURE_SH_EXTRA_QUIET */
Eric Andersenc470f442003-07-28 09:56:35 +000012368
Eric Andersencb57d552001-06-28 07:25:16 +000012369/*
Eric Andersencb57d552001-06-28 07:25:16 +000012370 * The export and readonly commands.
12371 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012372static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012373exportcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +000012374{
12375 struct var *vp;
12376 char *name;
12377 const char *p;
Eric Andersenc470f442003-07-28 09:56:35 +000012378 char **aptr;
Denis Vlasenkob7304742008-10-20 08:15:51 +000012379 int flag = argv[0][0] == 'r' ? VREADONLY : VEXPORT;
Eric Andersencb57d552001-06-28 07:25:16 +000012380
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012381 if (nextopt("p") != 'p') {
12382 aptr = argptr;
12383 name = *aptr;
12384 if (name) {
12385 do {
12386 p = strchr(name, '=');
12387 if (p != NULL) {
12388 p++;
12389 } else {
12390 vp = *findvar(hashvar(name), name);
12391 if (vp) {
12392 vp->flags |= flag;
12393 continue;
12394 }
Eric Andersencb57d552001-06-28 07:25:16 +000012395 }
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012396 setvar(name, p, flag);
12397 } while ((name = *++aptr) != NULL);
12398 return 0;
12399 }
Eric Andersencb57d552001-06-28 07:25:16 +000012400 }
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012401 showvars(argv[0], flag, 0);
Eric Andersencb57d552001-06-28 07:25:16 +000012402 return 0;
12403}
12404
Eric Andersencb57d552001-06-28 07:25:16 +000012405/*
Denis Vlasenko5651bfc2007-02-23 21:08:58 +000012406 * Delete a function if it exists.
Eric Andersencb57d552001-06-28 07:25:16 +000012407 */
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012408static void
Denis Vlasenko5651bfc2007-02-23 21:08:58 +000012409unsetfunc(const char *name)
Aaron Lehmannb6ecbdc2001-12-06 03:37:38 +000012410{
Denis Vlasenko5651bfc2007-02-23 21:08:58 +000012411 struct tblentry *cmdp;
Eric Andersencb57d552001-06-28 07:25:16 +000012412
Denis Vlasenko5651bfc2007-02-23 21:08:58 +000012413 cmdp = cmdlookup(name, 0);
12414 if (cmdp!= NULL && cmdp->cmdtype == CMDFUNCTION)
12415 delete_cmd_entry();
Eric Andersenc470f442003-07-28 09:56:35 +000012416}
12417
Eric Andersencb57d552001-06-28 07:25:16 +000012418/*
Eric Andersencb57d552001-06-28 07:25:16 +000012419 * The unset builtin command. We unset the function before we unset the
12420 * variable to allow a function to be unset when there is a readonly variable
12421 * with the same name.
12422 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012423static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012424unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersencb57d552001-06-28 07:25:16 +000012425{
12426 char **ap;
12427 int i;
Eric Andersenc470f442003-07-28 09:56:35 +000012428 int flag = 0;
Eric Andersencb57d552001-06-28 07:25:16 +000012429 int ret = 0;
12430
12431 while ((i = nextopt("vf")) != '\0') {
Eric Andersenc470f442003-07-28 09:56:35 +000012432 flag = i;
Eric Andersencb57d552001-06-28 07:25:16 +000012433 }
Eric Andersencb57d552001-06-28 07:25:16 +000012434
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012435 for (ap = argptr; *ap; ap++) {
Eric Andersenc470f442003-07-28 09:56:35 +000012436 if (flag != 'f') {
12437 i = unsetvar(*ap);
12438 ret |= i;
12439 if (!(i & 2))
12440 continue;
12441 }
12442 if (flag != 'v')
Eric Andersencb57d552001-06-28 07:25:16 +000012443 unsetfunc(*ap);
Eric Andersencb57d552001-06-28 07:25:16 +000012444 }
Eric Andersenc470f442003-07-28 09:56:35 +000012445 return ret & 1;
Eric Andersencb57d552001-06-28 07:25:16 +000012446}
12447
12448
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +000012449/* setmode.c */
Eric Andersencb57d552001-06-28 07:25:16 +000012450
Eric Andersenc470f442003-07-28 09:56:35 +000012451#include <sys/times.h>
12452
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000012453static const unsigned char timescmd_str[] ALIGN1 = {
Manuel Novoa III 4456f252003-08-13 17:48:47 +000012454 ' ', offsetof(struct tms, tms_utime),
12455 '\n', offsetof(struct tms, tms_stime),
12456 ' ', offsetof(struct tms, tms_cutime),
12457 '\n', offsetof(struct tms, tms_cstime),
12458 0
12459};
Eric Andersencb57d552001-06-28 07:25:16 +000012460
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012461static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012462timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Manuel Novoa III 4456f252003-08-13 17:48:47 +000012463{
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012464 long clk_tck, s, t;
Manuel Novoa III 4456f252003-08-13 17:48:47 +000012465 const unsigned char *p;
12466 struct tms buf;
12467
12468 clk_tck = sysconf(_SC_CLK_TCK);
Eric Andersencb57d552001-06-28 07:25:16 +000012469 times(&buf);
Manuel Novoa III 4456f252003-08-13 17:48:47 +000012470
12471 p = timescmd_str;
12472 do {
12473 t = *(clock_t *)(((char *) &buf) + p[1]);
12474 s = t / clk_tck;
12475 out1fmt("%ldm%ld.%.3lds%c",
12476 s/60, s%60,
12477 ((t - s * clk_tck) * 1000) / clk_tck,
12478 p[0]);
12479 } while (*(p += 2));
12480
Eric Andersencb57d552001-06-28 07:25:16 +000012481 return 0;
12482}
12483
Mike Frysinger98c52642009-04-02 10:02:37 +000012484#if ENABLE_SH_MATH_SUPPORT
Eric Andersenc470f442003-07-28 09:56:35 +000012485/*
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +000012486 * The let builtin. partial stolen from GNU Bash, the Bourne Again SHell.
12487 * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
Eric Andersen90898442003-08-06 11:20:52 +000012488 *
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +000012489 * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
Eric Andersenc470f442003-07-28 09:56:35 +000012490 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012491static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012492letcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersenc470f442003-07-28 09:56:35 +000012493{
Denis Vlasenko68404f12008-03-17 09:00:54 +000012494 arith_t i;
Eric Andersenc470f442003-07-28 09:56:35 +000012495
Denis Vlasenko68404f12008-03-17 09:00:54 +000012496 argv++;
12497 if (!*argv)
Denis Vlasenkob012b102007-02-19 22:43:01 +000012498 ash_msg_and_raise_error("expression expected");
Denis Vlasenko68404f12008-03-17 09:00:54 +000012499 do {
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +000012500 i = ash_arith(*argv);
Denis Vlasenko68404f12008-03-17 09:00:54 +000012501 } while (*++argv);
Eric Andersenc470f442003-07-28 09:56:35 +000012502
Denis Vlasenkod9e15f22006-11-27 16:49:55 +000012503 return !i;
Eric Andersenc470f442003-07-28 09:56:35 +000012504}
Mike Frysinger98c52642009-04-02 10:02:37 +000012505#endif /* SH_MATH_SUPPORT */
Eric Andersenc470f442003-07-28 09:56:35 +000012506
Eric Andersenc470f442003-07-28 09:56:35 +000012507
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012508/* ============ miscbltin.c
12509 *
Eric Andersenaff114c2004-04-14 17:51:38 +000012510 * Miscellaneous builtins.
Eric Andersenc470f442003-07-28 09:56:35 +000012511 */
12512
12513#undef rflag
12514
Denis Vlasenko83e5d6f2006-12-18 21:49:06 +000012515#if defined(__GLIBC__) && __GLIBC__ == 2 && __GLIBC_MINOR__ < 1
Eric Andersenc470f442003-07-28 09:56:35 +000012516typedef enum __rlimit_resource rlim_t;
12517#endif
Eric Andersen74bcd162001-07-30 21:41:37 +000012518
Eric Andersenc470f442003-07-28 09:56:35 +000012519/*
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012520 * The read builtin. Options:
12521 * -r Do not interpret '\' specially
12522 * -s Turn off echo (tty only)
12523 * -n NCHARS Read NCHARS max
12524 * -p PROMPT Display PROMPT on stderr (if input is from tty)
12525 * -t SECONDS Timeout after SECONDS (tty or pipe only)
12526 * -u FD Read from given FD instead of fd 0
Eric Andersenc470f442003-07-28 09:56:35 +000012527 * This uses unbuffered input, which may be avoidable in some cases.
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012528 * TODO: bash also has:
12529 * -a ARRAY Read into array[0],[1],etc
12530 * -d DELIM End on DELIM char, not newline
12531 * -e Use line editing (tty only)
Eric Andersenc470f442003-07-28 09:56:35 +000012532 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012533static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012534readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersenc470f442003-07-28 09:56:35 +000012535{
Denis Vlasenko9cd4c762008-06-18 19:22:19 +000012536 static const char *const arg_REPLY[] = { "REPLY", NULL };
12537
Eric Andersenc470f442003-07-28 09:56:35 +000012538 char **ap;
12539 int backslash;
12540 char c;
12541 int rflag;
12542 char *prompt;
12543 const char *ifs;
12544 char *p;
12545 int startword;
12546 int status;
12547 int i;
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012548 int fd = 0;
Denis Vlasenko131ae172007-02-18 13:00:19 +000012549#if ENABLE_ASH_READ_NCHARS
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012550 int nchars = 0; /* if != 0, -n is in effect */
Paul Fox02eb9342005-09-07 16:56:02 +000012551 int silent = 0;
12552 struct termios tty, old_tty;
12553#endif
Denis Vlasenko131ae172007-02-18 13:00:19 +000012554#if ENABLE_ASH_READ_TIMEOUT
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012555 unsigned end_ms = 0;
12556 unsigned timeout = 0;
Paul Fox02eb9342005-09-07 16:56:02 +000012557#endif
Eric Andersenc470f442003-07-28 09:56:35 +000012558
12559 rflag = 0;
12560 prompt = NULL;
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012561 while ((i = nextopt("p:u:r"
Denis Vlasenko5e34ff22009-04-21 11:09:40 +000012562 IF_ASH_READ_TIMEOUT("t:")
12563 IF_ASH_READ_NCHARS("n:s")
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012564 )) != '\0') {
Denis Vlasenkobf0a2012006-12-26 10:42:51 +000012565 switch (i) {
Paul Fox02eb9342005-09-07 16:56:02 +000012566 case 'p':
Eric Andersenc470f442003-07-28 09:56:35 +000012567 prompt = optionarg;
Paul Fox02eb9342005-09-07 16:56:02 +000012568 break;
Denis Vlasenko131ae172007-02-18 13:00:19 +000012569#if ENABLE_ASH_READ_NCHARS
Paul Fox02eb9342005-09-07 16:56:02 +000012570 case 'n':
Denis Vlasenko037576d2007-10-20 18:30:38 +000012571 nchars = bb_strtou(optionarg, NULL, 10);
12572 if (nchars < 0 || errno)
Denis Vlasenkob012b102007-02-19 22:43:01 +000012573 ash_msg_and_raise_error("invalid count");
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012574 /* nchars == 0: off (bash 3.2 does this too) */
Paul Fox02eb9342005-09-07 16:56:02 +000012575 break;
12576 case 's':
12577 silent = 1;
12578 break;
Ned Ludd2123b7c2005-02-09 21:07:23 +000012579#endif
Denis Vlasenko131ae172007-02-18 13:00:19 +000012580#if ENABLE_ASH_READ_TIMEOUT
Paul Fox02eb9342005-09-07 16:56:02 +000012581 case 't':
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012582 timeout = bb_strtou(optionarg, NULL, 10);
12583 if (errno || timeout > UINT_MAX / 2048)
12584 ash_msg_and_raise_error("invalid timeout");
12585 timeout *= 1000;
12586#if 0 /* even bash have no -t N.NNN support */
Denis Vlasenko037576d2007-10-20 18:30:38 +000012587 ts.tv_sec = bb_strtou(optionarg, &p, 10);
Paul Fox02eb9342005-09-07 16:56:02 +000012588 ts.tv_usec = 0;
Denis Vlasenko037576d2007-10-20 18:30:38 +000012589 /* EINVAL means number is ok, but not terminated by NUL */
12590 if (*p == '.' && errno == EINVAL) {
Paul Fox02eb9342005-09-07 16:56:02 +000012591 char *p2;
12592 if (*++p) {
12593 int scale;
Denis Vlasenko037576d2007-10-20 18:30:38 +000012594 ts.tv_usec = bb_strtou(p, &p2, 10);
12595 if (errno)
Denis Vlasenkob012b102007-02-19 22:43:01 +000012596 ash_msg_and_raise_error("invalid timeout");
Paul Fox02eb9342005-09-07 16:56:02 +000012597 scale = p2 - p;
12598 /* normalize to usec */
12599 if (scale > 6)
Denis Vlasenkob012b102007-02-19 22:43:01 +000012600 ash_msg_and_raise_error("invalid timeout");
Paul Fox02eb9342005-09-07 16:56:02 +000012601 while (scale++ < 6)
12602 ts.tv_usec *= 10;
12603 }
Denis Vlasenko037576d2007-10-20 18:30:38 +000012604 } else if (ts.tv_sec < 0 || errno) {
Denis Vlasenkob012b102007-02-19 22:43:01 +000012605 ash_msg_and_raise_error("invalid timeout");
Paul Fox02eb9342005-09-07 16:56:02 +000012606 }
Denis Vlasenko037576d2007-10-20 18:30:38 +000012607 if (!(ts.tv_sec | ts.tv_usec)) { /* both are 0? */
Denis Vlasenkob012b102007-02-19 22:43:01 +000012608 ash_msg_and_raise_error("invalid timeout");
Denis Vlasenko037576d2007-10-20 18:30:38 +000012609 }
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012610#endif /* if 0 */
Paul Fox02eb9342005-09-07 16:56:02 +000012611 break;
12612#endif
12613 case 'r':
12614 rflag = 1;
12615 break;
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012616 case 'u':
12617 fd = bb_strtou(optionarg, NULL, 10);
12618 if (fd < 0 || errno)
12619 ash_msg_and_raise_error("invalid file descriptor");
12620 break;
Paul Fox02eb9342005-09-07 16:56:02 +000012621 default:
12622 break;
12623 }
Eric Andersenc470f442003-07-28 09:56:35 +000012624 }
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012625 if (prompt && isatty(fd)) {
Eric Andersenc470f442003-07-28 09:56:35 +000012626 out2str(prompt);
Eric Andersenc470f442003-07-28 09:56:35 +000012627 }
Denis Vlasenko5cedb752007-02-18 19:56:41 +000012628 ap = argptr;
12629 if (*ap == NULL)
Denis Vlasenko9cd4c762008-06-18 19:22:19 +000012630 ap = (char**)arg_REPLY;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000012631 ifs = bltinlookup("IFS");
12632 if (ifs == NULL)
Eric Andersenc470f442003-07-28 09:56:35 +000012633 ifs = defifs;
Denis Vlasenko131ae172007-02-18 13:00:19 +000012634#if ENABLE_ASH_READ_NCHARS
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012635 tcgetattr(fd, &tty);
12636 old_tty = tty;
12637 if (nchars || silent) {
12638 if (nchars) {
12639 tty.c_lflag &= ~ICANON;
12640 tty.c_cc[VMIN] = nchars < 256 ? nchars : 255;
Paul Fox02eb9342005-09-07 16:56:02 +000012641 }
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012642 if (silent) {
12643 tty.c_lflag &= ~(ECHO | ECHOK | ECHONL);
12644 }
12645 /* if tcgetattr failed, tcsetattr will fail too.
12646 * Ignoring, it's harmless. */
12647 tcsetattr(fd, TCSANOW, &tty);
Paul Fox02eb9342005-09-07 16:56:02 +000012648 }
12649#endif
Paul Fox02eb9342005-09-07 16:56:02 +000012650
Eric Andersenc470f442003-07-28 09:56:35 +000012651 status = 0;
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012652 startword = 2;
Eric Andersenc470f442003-07-28 09:56:35 +000012653 backslash = 0;
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012654#if ENABLE_ASH_READ_TIMEOUT
12655 if (timeout) /* NB: ensuring end_ms is nonzero */
12656 end_ms = ((unsigned)(monotonic_us() / 1000) + timeout) | 1;
12657#endif
Eric Andersenc470f442003-07-28 09:56:35 +000012658 STARTSTACKSTR(p);
Denis Vlasenko037576d2007-10-20 18:30:38 +000012659 do {
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012660 const char *is_ifs;
12661
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012662#if ENABLE_ASH_READ_TIMEOUT
12663 if (end_ms) {
12664 struct pollfd pfd[1];
12665 pfd[0].fd = fd;
12666 pfd[0].events = POLLIN;
12667 timeout = end_ms - (unsigned)(monotonic_us() / 1000);
12668 if ((int)timeout <= 0 /* already late? */
12669 || safe_poll(pfd, 1, timeout) != 1 /* no? wait... */
12670 ) { /* timed out! */
12671#if ENABLE_ASH_READ_NCHARS
12672 tcsetattr(fd, TCSANOW, &old_tty);
12673#endif
12674 return 1;
12675 }
12676 }
12677#endif
12678 if (nonblock_safe_read(fd, &c, 1) != 1) {
Eric Andersenc470f442003-07-28 09:56:35 +000012679 status = 1;
12680 break;
12681 }
12682 if (c == '\0')
12683 continue;
12684 if (backslash) {
12685 backslash = 0;
12686 if (c != '\n')
12687 goto put;
12688 continue;
12689 }
12690 if (!rflag && c == '\\') {
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012691 backslash = 1;
Eric Andersenc470f442003-07-28 09:56:35 +000012692 continue;
12693 }
12694 if (c == '\n')
12695 break;
Denis Vlasenkof6fbd622009-03-31 19:36:58 +000012696 /* $IFS splitting */
Denis Vlasenko551ffdc2009-04-01 19:48:05 +000012697/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_05 */
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012698 is_ifs = strchr(ifs, c);
12699 if (startword && is_ifs) {
12700 if (isspace(c))
12701 continue;
Denis Vlasenkof6fbd622009-03-31 19:36:58 +000012702 /* it is a non-space ifs char */
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012703 startword--;
12704 if (startword == 1) /* first one? */
Denis Vlasenkof6fbd622009-03-31 19:36:58 +000012705 continue; /* yes, it is not next word yet */
Eric Andersenc470f442003-07-28 09:56:35 +000012706 }
12707 startword = 0;
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012708 if (ap[1] != NULL && is_ifs) {
12709 const char *beg;
Eric Andersenc470f442003-07-28 09:56:35 +000012710 STACKSTRNUL(p);
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012711 beg = stackblock();
12712 setvar(*ap, beg, 0);
Eric Andersenc470f442003-07-28 09:56:35 +000012713 ap++;
Denis Vlasenkof6fbd622009-03-31 19:36:58 +000012714 /* can we skip one non-space ifs char? (2: yes) */
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012715 startword = isspace(c) ? 2 : 1;
Eric Andersenc470f442003-07-28 09:56:35 +000012716 STARTSTACKSTR(p);
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012717 continue;
Eric Andersenc470f442003-07-28 09:56:35 +000012718 }
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012719 put:
12720 STPUTC(c, p);
Eric Andersenc470f442003-07-28 09:56:35 +000012721 }
Denis Vlasenko037576d2007-10-20 18:30:38 +000012722/* end of do {} while: */
Denis Vlasenko131ae172007-02-18 13:00:19 +000012723#if ENABLE_ASH_READ_NCHARS
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012724 while (--nchars);
Denis Vlasenko037576d2007-10-20 18:30:38 +000012725#else
12726 while (1);
12727#endif
12728
12729#if ENABLE_ASH_READ_NCHARS
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012730 tcsetattr(fd, TCSANOW, &old_tty);
Paul Fox02eb9342005-09-07 16:56:02 +000012731#endif
12732
Eric Andersenc470f442003-07-28 09:56:35 +000012733 STACKSTRNUL(p);
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012734 /* Remove trailing space ifs chars */
12735 while ((char *)stackblock() <= --p && isspace(*p) && strchr(ifs, *p) != NULL)
Eric Andersenc470f442003-07-28 09:56:35 +000012736 *p = '\0';
12737 setvar(*ap, stackblock(), 0);
12738 while (*++ap != NULL)
12739 setvar(*ap, nullstr, 0);
12740 return status;
12741}
12742
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012743static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012744umaskcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersenc470f442003-07-28 09:56:35 +000012745{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000012746 static const char permuser[3] ALIGN1 = "ugo";
12747 static const char permmode[3] ALIGN1 = "rwx";
12748 static const short permmask[] ALIGN2 = {
Eric Andersenc470f442003-07-28 09:56:35 +000012749 S_IRUSR, S_IWUSR, S_IXUSR,
12750 S_IRGRP, S_IWGRP, S_IXGRP,
12751 S_IROTH, S_IWOTH, S_IXOTH
12752 };
12753
Denis Vlasenkoeb858492009-04-18 02:06:54 +000012754 /* TODO: use bb_parse_mode() instead */
12755
Eric Andersenc470f442003-07-28 09:56:35 +000012756 char *ap;
12757 mode_t mask;
12758 int i;
12759 int symbolic_mode = 0;
12760
12761 while (nextopt("S") != '\0') {
12762 symbolic_mode = 1;
12763 }
12764
Denis Vlasenkob012b102007-02-19 22:43:01 +000012765 INT_OFF;
Eric Andersenc470f442003-07-28 09:56:35 +000012766 mask = umask(0);
12767 umask(mask);
Denis Vlasenkob012b102007-02-19 22:43:01 +000012768 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +000012769
Denis Vlasenko5cedb752007-02-18 19:56:41 +000012770 ap = *argptr;
12771 if (ap == NULL) {
Eric Andersenc470f442003-07-28 09:56:35 +000012772 if (symbolic_mode) {
12773 char buf[18];
12774 char *p = buf;
12775
12776 for (i = 0; i < 3; i++) {
12777 int j;
12778
12779 *p++ = permuser[i];
12780 *p++ = '=';
12781 for (j = 0; j < 3; j++) {
12782 if ((mask & permmask[3 * i + j]) == 0) {
12783 *p++ = permmode[j];
12784 }
12785 }
12786 *p++ = ',';
12787 }
12788 *--p = 0;
12789 puts(buf);
12790 } else {
12791 out1fmt("%.4o\n", mask);
12792 }
12793 } else {
Denis Vlasenkoaa744452007-02-23 01:04:22 +000012794 if (isdigit((unsigned char) *ap)) {
Eric Andersenc470f442003-07-28 09:56:35 +000012795 mask = 0;
12796 do {
12797 if (*ap >= '8' || *ap < '0')
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +020012798 ash_msg_and_raise_error(msg_illnum, argv[1]);
Eric Andersenc470f442003-07-28 09:56:35 +000012799 mask = (mask << 3) + (*ap - '0');
12800 } while (*++ap != '\0');
12801 umask(mask);
12802 } else {
12803 mask = ~mask & 0777;
12804 if (!bb_parse_mode(ap, &mask)) {
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +000012805 ash_msg_and_raise_error("illegal mode: %s", ap);
Eric Andersenc470f442003-07-28 09:56:35 +000012806 }
12807 umask(~mask & 0777);
12808 }
12809 }
12810 return 0;
12811}
12812
12813/*
12814 * ulimit builtin
12815 *
12816 * This code, originally by Doug Gwyn, Doug Kingston, Eric Gisin, and
12817 * Michael Rendell was ripped from pdksh 5.0.8 and hacked for use with
12818 * ash by J.T. Conklin.
12819 *
12820 * Public domain.
12821 */
Eric Andersenc470f442003-07-28 09:56:35 +000012822struct limits {
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012823 uint8_t cmd; /* RLIMIT_xxx fit into it */
12824 uint8_t factor_shift; /* shift by to get rlim_{cur,max} values */
Eric Andersenc470f442003-07-28 09:56:35 +000012825 char option;
12826};
12827
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012828static const struct limits limits_tbl[] = {
Eric Andersenc470f442003-07-28 09:56:35 +000012829#ifdef RLIMIT_CPU
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012830 { RLIMIT_CPU, 0, 't' },
Eric Andersenc470f442003-07-28 09:56:35 +000012831#endif
12832#ifdef RLIMIT_FSIZE
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012833 { RLIMIT_FSIZE, 9, 'f' },
Eric Andersenc470f442003-07-28 09:56:35 +000012834#endif
12835#ifdef RLIMIT_DATA
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012836 { RLIMIT_DATA, 10, 'd' },
Eric Andersenc470f442003-07-28 09:56:35 +000012837#endif
12838#ifdef RLIMIT_STACK
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012839 { RLIMIT_STACK, 10, 's' },
Eric Andersenc470f442003-07-28 09:56:35 +000012840#endif
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012841#ifdef RLIMIT_CORE
12842 { RLIMIT_CORE, 9, 'c' },
Eric Andersenc470f442003-07-28 09:56:35 +000012843#endif
12844#ifdef RLIMIT_RSS
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012845 { RLIMIT_RSS, 10, 'm' },
Eric Andersenc470f442003-07-28 09:56:35 +000012846#endif
12847#ifdef RLIMIT_MEMLOCK
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012848 { RLIMIT_MEMLOCK, 10, 'l' },
Eric Andersenc470f442003-07-28 09:56:35 +000012849#endif
12850#ifdef RLIMIT_NPROC
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012851 { RLIMIT_NPROC, 0, 'p' },
Eric Andersenc470f442003-07-28 09:56:35 +000012852#endif
12853#ifdef RLIMIT_NOFILE
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012854 { RLIMIT_NOFILE, 0, 'n' },
Eric Andersenc470f442003-07-28 09:56:35 +000012855#endif
Glenn L McGrath76620622004-01-13 10:19:37 +000012856#ifdef RLIMIT_AS
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012857 { RLIMIT_AS, 10, 'v' },
Eric Andersenc470f442003-07-28 09:56:35 +000012858#endif
Glenn L McGrath76620622004-01-13 10:19:37 +000012859#ifdef RLIMIT_LOCKS
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012860 { RLIMIT_LOCKS, 0, 'w' },
Eric Andersenc470f442003-07-28 09:56:35 +000012861#endif
Eric Andersenc470f442003-07-28 09:56:35 +000012862};
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012863static const char limits_name[] =
12864#ifdef RLIMIT_CPU
12865 "time(seconds)" "\0"
12866#endif
12867#ifdef RLIMIT_FSIZE
12868 "file(blocks)" "\0"
12869#endif
12870#ifdef RLIMIT_DATA
12871 "data(kb)" "\0"
12872#endif
12873#ifdef RLIMIT_STACK
12874 "stack(kb)" "\0"
12875#endif
12876#ifdef RLIMIT_CORE
12877 "coredump(blocks)" "\0"
12878#endif
12879#ifdef RLIMIT_RSS
12880 "memory(kb)" "\0"
12881#endif
12882#ifdef RLIMIT_MEMLOCK
12883 "locked memory(kb)" "\0"
12884#endif
12885#ifdef RLIMIT_NPROC
12886 "process" "\0"
12887#endif
12888#ifdef RLIMIT_NOFILE
12889 "nofiles" "\0"
12890#endif
12891#ifdef RLIMIT_AS
12892 "vmemory(kb)" "\0"
12893#endif
12894#ifdef RLIMIT_LOCKS
12895 "locks" "\0"
12896#endif
12897;
Eric Andersenc470f442003-07-28 09:56:35 +000012898
Glenn L McGrath76620622004-01-13 10:19:37 +000012899enum limtype { SOFT = 0x1, HARD = 0x2 };
12900
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012901static void
12902printlim(enum limtype how, const struct rlimit *limit,
Glenn L McGrath76620622004-01-13 10:19:37 +000012903 const struct limits *l)
12904{
12905 rlim_t val;
12906
12907 val = limit->rlim_max;
12908 if (how & SOFT)
12909 val = limit->rlim_cur;
12910
12911 if (val == RLIM_INFINITY)
12912 out1fmt("unlimited\n");
12913 else {
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012914 val >>= l->factor_shift;
Glenn L McGrath76620622004-01-13 10:19:37 +000012915 out1fmt("%lld\n", (long long) val);
12916 }
12917}
12918
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012919static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012920ulimitcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersenc470f442003-07-28 09:56:35 +000012921{
Denys Vlasenko76622db2009-10-04 01:14:19 +020012922 rlim_t val;
Glenn L McGrath76620622004-01-13 10:19:37 +000012923 enum limtype how = SOFT | HARD;
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012924 const struct limits *l;
12925 int set, all = 0;
12926 int optc, what;
12927 struct rlimit limit;
Eric Andersenc470f442003-07-28 09:56:35 +000012928
12929 what = 'f';
Glenn L McGrath16e45d72004-02-04 08:24:39 +000012930 while ((optc = nextopt("HSa"
12931#ifdef RLIMIT_CPU
12932 "t"
12933#endif
12934#ifdef RLIMIT_FSIZE
12935 "f"
12936#endif
12937#ifdef RLIMIT_DATA
12938 "d"
12939#endif
12940#ifdef RLIMIT_STACK
12941 "s"
12942#endif
12943#ifdef RLIMIT_CORE
12944 "c"
12945#endif
12946#ifdef RLIMIT_RSS
12947 "m"
12948#endif
12949#ifdef RLIMIT_MEMLOCK
12950 "l"
12951#endif
12952#ifdef RLIMIT_NPROC
12953 "p"
12954#endif
12955#ifdef RLIMIT_NOFILE
12956 "n"
12957#endif
12958#ifdef RLIMIT_AS
12959 "v"
12960#endif
12961#ifdef RLIMIT_LOCKS
12962 "w"
12963#endif
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000012964 )) != '\0')
Eric Andersenc470f442003-07-28 09:56:35 +000012965 switch (optc) {
12966 case 'H':
12967 how = HARD;
12968 break;
12969 case 'S':
12970 how = SOFT;
12971 break;
12972 case 'a':
12973 all = 1;
12974 break;
12975 default:
12976 what = optc;
12977 }
12978
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012979 for (l = limits_tbl; l->option != what; l++)
12980 continue;
Eric Andersenc470f442003-07-28 09:56:35 +000012981
12982 set = *argptr ? 1 : 0;
Denys Vlasenko76622db2009-10-04 01:14:19 +020012983 val = 0;
Eric Andersenc470f442003-07-28 09:56:35 +000012984 if (set) {
12985 char *p = *argptr;
12986
12987 if (all || argptr[1])
Denis Vlasenkob012b102007-02-19 22:43:01 +000012988 ash_msg_and_raise_error("too many arguments");
Eric Andersen81fe1232003-07-29 06:38:40 +000012989 if (strncmp(p, "unlimited\n", 9) == 0)
Eric Andersenc470f442003-07-28 09:56:35 +000012990 val = RLIM_INFINITY;
12991 else {
Denys Vlasenko76622db2009-10-04 01:14:19 +020012992 if (sizeof(val) == sizeof(int))
12993 val = bb_strtou(p, NULL, 10);
12994 else if (sizeof(val) == sizeof(long))
12995 val = bb_strtoul(p, NULL, 10);
12996 else
12997 val = bb_strtoull(p, NULL, 10);
12998 if (errno)
Denis Vlasenkob012b102007-02-19 22:43:01 +000012999 ash_msg_and_raise_error("bad number");
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000013000 val <<= l->factor_shift;
Eric Andersenc470f442003-07-28 09:56:35 +000013001 }
13002 }
13003 if (all) {
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000013004 const char *lname = limits_name;
13005 for (l = limits_tbl; l != &limits_tbl[ARRAY_SIZE(limits_tbl)]; l++) {
Eric Andersenc470f442003-07-28 09:56:35 +000013006 getrlimit(l->cmd, &limit);
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000013007 out1fmt("%-20s ", lname);
13008 lname += strlen(lname) + 1;
Glenn L McGrath76620622004-01-13 10:19:37 +000013009 printlim(how, &limit, l);
Eric Andersenc470f442003-07-28 09:56:35 +000013010 }
13011 return 0;
13012 }
13013
13014 getrlimit(l->cmd, &limit);
13015 if (set) {
13016 if (how & HARD)
13017 limit.rlim_max = val;
13018 if (how & SOFT)
13019 limit.rlim_cur = val;
13020 if (setrlimit(l->cmd, &limit) < 0)
Denis Vlasenkob012b102007-02-19 22:43:01 +000013021 ash_msg_and_raise_error("error setting limit (%m)");
Eric Andersenc470f442003-07-28 09:56:35 +000013022 } else {
Glenn L McGrath76620622004-01-13 10:19:37 +000013023 printlim(how, &limit, l);
Eric Andersenc470f442003-07-28 09:56:35 +000013024 }
13025 return 0;
13026}
13027
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000013028/* ============ main() and helpers */
13029
13030/*
13031 * Called to exit the shell.
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013032 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000013033static void exitshell(void) NORETURN;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000013034static void
13035exitshell(void)
13036{
13037 struct jmploc loc;
13038 char *p;
13039 int status;
13040
13041 status = exitstatus;
13042 TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
13043 if (setjmp(loc.loc)) {
Denis Vlasenko7f88e342009-03-19 03:36:18 +000013044 if (exception_type == EXEXIT)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000013045/* dash bug: it just does _exit(exitstatus) here
13046 * but we have to do setjobctl(0) first!
13047 * (bug is still not fixed in dash-0.5.3 - if you run dash
13048 * under Midnight Commander, on exit from dash MC is backgrounded) */
13049 status = exitstatus;
13050 goto out;
13051 }
13052 exception_handler = &loc;
13053 p = trap[0];
13054 if (p) {
13055 trap[0] = NULL;
13056 evalstring(p, 0);
Denys Vlasenko0800e3a2009-09-24 03:09:26 +020013057 free(p);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000013058 }
13059 flush_stdout_stderr();
13060 out:
13061 setjobctl(0);
13062 _exit(status);
13063 /* NOTREACHED */
13064}
13065
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000013066static void
13067init(void)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013068{
13069 /* from input.c: */
Denis Vlasenko41eb3002008-11-28 03:42:31 +000013070 basepf.next_to_pgetc = basepf.buf = basebuf;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013071
13072 /* from trap.c: */
13073 signal(SIGCHLD, SIG_DFL);
13074
13075 /* from var.c: */
13076 {
13077 char **envp;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013078 const char *p;
13079 struct stat st1, st2;
13080
13081 initvar();
13082 for (envp = environ; envp && *envp; envp++) {
13083 if (strchr(*envp, '=')) {
13084 setvareq(*envp, VEXPORT|VTEXTFIXED);
13085 }
13086 }
13087
Denys Vlasenko7bb346f2009-10-06 22:09:50 +020013088 setvar("PPID", utoa(getppid()), 0);
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013089
13090 p = lookupvar("PWD");
13091 if (p)
13092 if (*p != '/' || stat(p, &st1) || stat(".", &st2)
13093 || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino)
13094 p = '\0';
13095 setpwd(p, 0);
13096 }
13097}
13098
13099/*
13100 * Process the shell command line arguments.
13101 */
13102static void
Denis Vlasenko68404f12008-03-17 09:00:54 +000013103procargs(char **argv)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013104{
13105 int i;
13106 const char *xminusc;
13107 char **xargv;
13108
13109 xargv = argv;
13110 arg0 = xargv[0];
Denis Vlasenko68404f12008-03-17 09:00:54 +000013111 /* if (xargv[0]) - mmm, this is always true! */
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013112 xargv++;
13113 for (i = 0; i < NOPTS; i++)
13114 optlist[i] = 2;
13115 argptr = xargv;
Denis Vlasenko28bf6712008-02-14 15:01:47 +000013116 if (options(1)) {
13117 /* it already printed err message */
13118 raise_exception(EXERROR);
13119 }
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013120 xargv = argptr;
13121 xminusc = minusc;
13122 if (*xargv == NULL) {
13123 if (xminusc)
13124 ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
13125 sflag = 1;
13126 }
13127 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
13128 iflag = 1;
13129 if (mflag == 2)
13130 mflag = iflag;
13131 for (i = 0; i < NOPTS; i++)
13132 if (optlist[i] == 2)
13133 optlist[i] = 0;
13134#if DEBUG == 2
13135 debug = 1;
13136#endif
13137 /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
13138 if (xminusc) {
13139 minusc = *xargv++;
13140 if (*xargv)
13141 goto setarg0;
13142 } else if (!sflag) {
13143 setinputfile(*xargv, 0);
13144 setarg0:
13145 arg0 = *xargv++;
13146 commandname = arg0;
13147 }
13148
13149 shellparam.p = xargv;
13150#if ENABLE_ASH_GETOPTS
13151 shellparam.optind = 1;
13152 shellparam.optoff = -1;
13153#endif
Denis Vlasenko01631112007-12-16 17:20:38 +000013154 /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013155 while (*xargv) {
13156 shellparam.nparam++;
13157 xargv++;
13158 }
13159 optschanged();
13160}
13161
13162/*
13163 * Read /etc/profile or .profile.
13164 */
13165static void
13166read_profile(const char *name)
13167{
13168 int skip;
13169
13170 if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
13171 return;
13172 skip = cmdloop(0);
13173 popfile();
13174 if (skip)
13175 exitshell();
13176}
13177
Denis Vlasenko0c032a42007-02-23 01:03:40 +000013178/*
13179 * This routine is called when an error or an interrupt occurs in an
13180 * interactive shell and control is returned to the main command loop.
13181 */
13182static void
13183reset(void)
13184{
13185 /* from eval.c: */
13186 evalskip = 0;
13187 loopnest = 0;
13188 /* from input.c: */
Denis Vlasenko41eb3002008-11-28 03:42:31 +000013189 g_parsefile->left_in_buffer = 0;
13190 g_parsefile->left_in_line = 0; /* clear input buffer */
Denis Vlasenko0c032a42007-02-23 01:03:40 +000013191 popallfiles();
13192 /* from parser.c: */
13193 tokpushback = 0;
13194 checkkwd = 0;
13195 /* from redir.c: */
Denis Vlasenko34c73c42008-08-16 11:48:02 +000013196 clearredir(/*drop:*/ 0);
Denis Vlasenko0c032a42007-02-23 01:03:40 +000013197}
13198
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013199#if PROFILE
13200static short profile_buf[16384];
13201extern int etext();
13202#endif
13203
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000013204/*
13205 * Main routine. We initialize things, parse the arguments, execute
13206 * profiles if we're a login shell, and then call cmdloop to execute
13207 * commands. The setjmp call sets up the location to jump to when an
13208 * exception occurs. When an exception occurs the variable "state"
13209 * is used to figure out how far we had gotten.
13210 */
Denis Vlasenko9b49a5e2007-10-11 10:05:36 +000013211int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000013212int ash_main(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013213{
Mike Frysinger98c52642009-04-02 10:02:37 +000013214 const char *shinit;
Denis Vlasenko4e12b1a2008-12-23 23:36:47 +000013215 volatile smallint state;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013216 struct jmploc jmploc;
13217 struct stackmark smark;
13218
Denis Vlasenko01631112007-12-16 17:20:38 +000013219 /* Initialize global data */
13220 INIT_G_misc();
13221 INIT_G_memstack();
13222 INIT_G_var();
Denis Vlasenkoee87ebf2007-12-21 22:18:16 +000013223#if ENABLE_ASH_ALIAS
Denis Vlasenko01631112007-12-16 17:20:38 +000013224 INIT_G_alias();
Denis Vlasenkoee87ebf2007-12-21 22:18:16 +000013225#endif
Denis Vlasenko01631112007-12-16 17:20:38 +000013226 INIT_G_cmdtable();
13227
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013228#if PROFILE
13229 monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
13230#endif
13231
13232#if ENABLE_FEATURE_EDITING
13233 line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
13234#endif
13235 state = 0;
13236 if (setjmp(jmploc.loc)) {
Denis Vlasenko7f88e342009-03-19 03:36:18 +000013237 smallint e;
Denis Vlasenko4e12b1a2008-12-23 23:36:47 +000013238 smallint s;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013239
13240 reset();
13241
Denis Vlasenko7f88e342009-03-19 03:36:18 +000013242 e = exception_type;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013243 if (e == EXERROR)
13244 exitstatus = 2;
13245 s = state;
13246 if (e == EXEXIT || s == 0 || iflag == 0 || shlvl)
13247 exitshell();
Denis Vlasenko7f88e342009-03-19 03:36:18 +000013248 if (e == EXINT)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013249 outcslow('\n', stderr);
Denis Vlasenko7f88e342009-03-19 03:36:18 +000013250
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013251 popstackmark(&smark);
13252 FORCE_INT_ON; /* enable interrupts */
13253 if (s == 1)
13254 goto state1;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000013255 if (s == 2)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013256 goto state2;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000013257 if (s == 3)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013258 goto state3;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000013259 goto state4;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013260 }
13261 exception_handler = &jmploc;
13262#if DEBUG
13263 opentrace();
Denis Vlasenko653d8e72009-03-19 21:59:35 +000013264 TRACE(("Shell args: "));
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000013265 trace_puts_args(argv);
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013266#endif
13267 rootpid = getpid();
13268
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013269 init();
13270 setstackmark(&smark);
Denis Vlasenko68404f12008-03-17 09:00:54 +000013271 procargs(argv);
13272
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013273#if ENABLE_FEATURE_EDITING_SAVEHISTORY
13274 if (iflag) {
13275 const char *hp = lookupvar("HISTFILE");
13276
13277 if (hp == NULL) {
13278 hp = lookupvar("HOME");
13279 if (hp != NULL) {
13280 char *defhp = concat_path_file(hp, ".ash_history");
13281 setvar("HISTFILE", defhp, 0);
13282 free(defhp);
13283 }
13284 }
13285 }
13286#endif
Denis Vlasenko4e12b1a2008-12-23 23:36:47 +000013287 if (/* argv[0] && */ argv[0][0] == '-')
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013288 isloginsh = 1;
13289 if (isloginsh) {
13290 state = 1;
13291 read_profile("/etc/profile");
13292 state1:
13293 state = 2;
13294 read_profile(".profile");
13295 }
13296 state2:
13297 state = 3;
13298 if (
13299#ifndef linux
Denis Vlasenko0c032a42007-02-23 01:03:40 +000013300 getuid() == geteuid() && getgid() == getegid() &&
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013301#endif
Denis Vlasenko0c032a42007-02-23 01:03:40 +000013302 iflag
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013303 ) {
13304 shinit = lookupvar("ENV");
13305 if (shinit != NULL && *shinit != '\0') {
13306 read_profile(shinit);
13307 }
13308 }
13309 state3:
13310 state = 4;
Denis Vlasenko5c2b8142009-03-19 01:59:59 +000013311 if (minusc) {
13312 /* evalstring pushes parsefile stack.
13313 * Ensure we don't falsely claim that 0 (stdin)
Denis Vlasenko5368ad52009-03-20 10:20:08 +000013314 * is one of stacked source fds.
13315 * Testcase: ash -c 'exec 1>&0' must not complain. */
Denis Vlasenko5c2b8142009-03-19 01:59:59 +000013316 if (!sflag)
13317 g_parsefile->fd = -1;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013318 evalstring(minusc, 0);
Denis Vlasenko5c2b8142009-03-19 01:59:59 +000013319 }
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013320
13321 if (sflag || minusc == NULL) {
Denys Vlasenkodb9c57e2009-09-27 02:48:53 +020013322#if MAX_HISTORY > 0 && ENABLE_FEATURE_EDITING_SAVEHISTORY
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +000013323 if (iflag) {
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013324 const char *hp = lookupvar("HISTFILE");
Denis Vlasenko5c2b8142009-03-19 01:59:59 +000013325 if (hp)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013326 line_input_state->hist_file = hp;
13327 }
13328#endif
13329 state4: /* XXX ??? - why isn't this before the "if" statement */
13330 cmdloop(1);
13331 }
13332#if PROFILE
13333 monitor(0);
13334#endif
13335#ifdef GPROF
13336 {
13337 extern void _mcleanup(void);
13338 _mcleanup();
13339 }
13340#endif
13341 exitshell();
13342 /* NOTREACHED */
13343}
13344
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013345
Eric Andersendf82f612001-06-28 07:46:40 +000013346/*-
13347 * Copyright (c) 1989, 1991, 1993, 1994
Eric Andersen2870d962001-07-02 17:27:21 +000013348 * The Regents of the University of California. All rights reserved.
Eric Andersendf82f612001-06-28 07:46:40 +000013349 *
13350 * This code is derived from software contributed to Berkeley by
13351 * Kenneth Almquist.
13352 *
13353 * Redistribution and use in source and binary forms, with or without
13354 * modification, are permitted provided that the following conditions
13355 * are met:
13356 * 1. Redistributions of source code must retain the above copyright
13357 * notice, this list of conditions and the following disclaimer.
13358 * 2. Redistributions in binary form must reproduce the above copyright
13359 * notice, this list of conditions and the following disclaimer in the
13360 * documentation and/or other materials provided with the distribution.
"Vladimir N. Oleynik"ddc280e2005-12-15 12:01:49 +000013361 * 3. Neither the name of the University nor the names of its contributors
Eric Andersendf82f612001-06-28 07:46:40 +000013362 * may be used to endorse or promote products derived from this software
13363 * without specific prior written permission.
13364 *
13365 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
13366 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
13367 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
13368 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
13369 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
13370 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
13371 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
13372 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
13373 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
13374 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
13375 * SUCH DAMAGE.
13376 */