blob: 6b985ad7c436d194bef842957b9a504072128c3c [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;
Denys Vlasenko8131eea2009-11-02 14:19:51 +0100392 fflush_all();
Denis Vlasenkob012b102007-02-19 22:43:01 +0000393 INT_ON;
394}
395
396static void
397outcslow(int c, FILE *dest)
398{
399 INT_OFF;
400 putc(c, dest);
401 fflush(dest);
402 INT_ON;
403}
404
405static int out1fmt(const char *, ...) __attribute__((__format__(__printf__,1,2)));
406static int
407out1fmt(const char *fmt, ...)
408{
409 va_list ap;
410 int r;
411
412 INT_OFF;
413 va_start(ap, fmt);
414 r = vprintf(fmt, ap);
415 va_end(ap);
416 INT_ON;
417 return r;
418}
419
420static int fmtstr(char *, size_t, const char *, ...) __attribute__((__format__(__printf__,3,4)));
421static int
422fmtstr(char *outbuf, size_t length, const char *fmt, ...)
423{
424 va_list ap;
425 int ret;
426
427 va_start(ap, fmt);
428 INT_OFF;
429 ret = vsnprintf(outbuf, length, fmt, ap);
430 va_end(ap);
431 INT_ON;
432 return ret;
433}
434
435static void
436out1str(const char *p)
437{
438 outstr(p, stdout);
439}
440
441static void
442out2str(const char *p)
443{
444 outstr(p, stderr);
Denys Vlasenko8131eea2009-11-02 14:19:51 +0100445 flush_stdout_stderr();
Denis Vlasenkob012b102007-02-19 22:43:01 +0000446}
447
448
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +0000449/* ============ Parser structures */
Denis Vlasenko4d2183b2007-02-23 01:05:38 +0000450
Denis Vlasenko5651bfc2007-02-23 21:08:58 +0000451/* control characters in argument strings */
Denys Vlasenkob6c84342009-08-29 20:23:20 +0200452#define CTLESC ((unsigned char)'\201') /* escape next character */
453#define CTLVAR ((unsigned char)'\202') /* variable defn */
454#define CTLENDVAR ((unsigned char)'\203')
455#define CTLBACKQ ((unsigned char)'\204')
Denis Vlasenko5651bfc2007-02-23 21:08:58 +0000456#define CTLQUOTE 01 /* ored with CTLBACKQ code if in quotes */
457/* CTLBACKQ | CTLQUOTE == '\205' */
Denys Vlasenkob6c84342009-08-29 20:23:20 +0200458#define CTLARI ((unsigned char)'\206') /* arithmetic expression */
459#define CTLENDARI ((unsigned char)'\207')
460#define CTLQUOTEMARK ((unsigned char)'\210')
Denis Vlasenko5651bfc2007-02-23 21:08:58 +0000461
462/* variable substitution byte (follows CTLVAR) */
463#define VSTYPE 0x0f /* type of variable substitution */
464#define VSNUL 0x10 /* colon--treat the empty string as unset */
465#define VSQUOTE 0x80 /* inside double quotes--suppress splitting */
466
467/* values of VSTYPE field */
Denis Vlasenko92e13c22008-03-25 01:17:40 +0000468#define VSNORMAL 0x1 /* normal variable: $var or ${var} */
469#define VSMINUS 0x2 /* ${var-text} */
470#define VSPLUS 0x3 /* ${var+text} */
471#define VSQUESTION 0x4 /* ${var?message} */
472#define VSASSIGN 0x5 /* ${var=text} */
473#define VSTRIMRIGHT 0x6 /* ${var%pattern} */
474#define VSTRIMRIGHTMAX 0x7 /* ${var%%pattern} */
475#define VSTRIMLEFT 0x8 /* ${var#pattern} */
476#define VSTRIMLEFTMAX 0x9 /* ${var##pattern} */
477#define VSLENGTH 0xa /* ${#var} */
478#if ENABLE_ASH_BASH_COMPAT
479#define VSSUBSTR 0xc /* ${var:position:length} */
480#define VSREPLACE 0xd /* ${var/pattern/replacement} */
481#define VSREPLACEALL 0xe /* ${var//pattern/replacement} */
482#endif
Denis Vlasenko5651bfc2007-02-23 21:08:58 +0000483
Denis Vlasenko6ca409e2007-08-12 20:58:27 +0000484static const char dolatstr[] ALIGN1 = {
485 CTLVAR, VSNORMAL|VSQUOTE, '@', '=', '\0'
486};
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +0000487
Denis Vlasenko559691a2008-10-05 18:39:31 +0000488#define NCMD 0
489#define NPIPE 1
490#define NREDIR 2
491#define NBACKGND 3
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000492#define NSUBSHELL 4
Denis Vlasenko559691a2008-10-05 18:39:31 +0000493#define NAND 5
494#define NOR 6
495#define NSEMI 7
496#define NIF 8
497#define NWHILE 9
498#define NUNTIL 10
499#define NFOR 11
500#define NCASE 12
501#define NCLIST 13
502#define NDEFUN 14
503#define NARG 15
504#define NTO 16
505#if ENABLE_ASH_BASH_COMPAT
506#define NTO2 17
507#endif
508#define NCLOBBER 18
509#define NFROM 19
510#define NFROMTO 20
511#define NAPPEND 21
512#define NTOFD 22
513#define NFROMFD 23
514#define NHERE 24
515#define NXHERE 25
516#define NNOT 26
Denis Vlasenko340299a2008-11-21 10:36:36 +0000517#define N_NUMBER 27
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000518
519union node;
520
521struct ncmd {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000522 smallint type; /* Nxxxx */
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000523 union node *assign;
524 union node *args;
525 union node *redirect;
526};
527
528struct npipe {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000529 smallint type;
530 smallint pipe_backgnd;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000531 struct nodelist *cmdlist;
532};
533
534struct nredir {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000535 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000536 union node *n;
537 union node *redirect;
538};
539
540struct nbinary {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000541 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000542 union node *ch1;
543 union node *ch2;
544};
545
546struct nif {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000547 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000548 union node *test;
549 union node *ifpart;
550 union node *elsepart;
551};
552
553struct nfor {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000554 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000555 union node *args;
556 union node *body;
557 char *var;
558};
559
560struct ncase {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000561 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000562 union node *expr;
563 union node *cases;
564};
565
566struct nclist {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000567 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000568 union node *next;
569 union node *pattern;
570 union node *body;
571};
572
573struct narg {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000574 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000575 union node *next;
576 char *text;
577 struct nodelist *backquote;
578};
579
Denis Vlasenko559691a2008-10-05 18:39:31 +0000580/* nfile and ndup layout must match!
581 * NTOFD (>&fdnum) uses ndup structure, but we may discover mid-flight
582 * that it is actually NTO2 (>&file), and change its type.
583 */
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000584struct nfile {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000585 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000586 union node *next;
587 int fd;
Denis Vlasenko559691a2008-10-05 18:39:31 +0000588 int _unused_dupfd;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000589 union node *fname;
590 char *expfname;
591};
592
593struct ndup {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000594 smallint type;
Denis Vlasenko559691a2008-10-05 18:39:31 +0000595 union node *next;
596 int fd;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000597 int dupfd;
598 union node *vname;
Denis Vlasenko559691a2008-10-05 18:39:31 +0000599 char *_unused_expfname;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000600};
601
602struct nhere {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000603 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000604 union node *next;
605 int fd;
606 union node *doc;
607};
608
609struct nnot {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000610 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000611 union node *com;
612};
613
614union node {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000615 smallint type;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000616 struct ncmd ncmd;
617 struct npipe npipe;
618 struct nredir nredir;
619 struct nbinary nbinary;
620 struct nif nif;
621 struct nfor nfor;
622 struct ncase ncase;
623 struct nclist nclist;
624 struct narg narg;
625 struct nfile nfile;
626 struct ndup ndup;
627 struct nhere nhere;
628 struct nnot nnot;
629};
630
Denys Vlasenko86e83ec2009-07-23 22:07:07 +0200631/*
632 * NODE_EOF is returned by parsecmd when it encounters an end of file.
633 * It must be distinct from NULL.
634 */
635#define NODE_EOF ((union node *) -1L)
636
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000637struct nodelist {
638 struct nodelist *next;
639 union node *n;
640};
641
642struct funcnode {
643 int count;
644 union node n;
645};
646
Denis Vlasenko5651bfc2007-02-23 21:08:58 +0000647/*
648 * Free a parse tree.
649 */
650static void
651freefunc(struct funcnode *f)
652{
653 if (f && --f->count < 0)
654 free(f);
655}
656
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000657
658/* ============ Debugging output */
659
660#if DEBUG
661
662static FILE *tracefile;
663
664static void
665trace_printf(const char *fmt, ...)
666{
667 va_list va;
668
669 if (debug != 1)
670 return;
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000671 if (DEBUG_TIME)
672 fprintf(tracefile, "%u ", (int) time(NULL));
673 if (DEBUG_PID)
674 fprintf(tracefile, "[%u] ", (int) getpid());
675 if (DEBUG_SIG)
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200676 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000677 va_start(va, fmt);
678 vfprintf(tracefile, fmt, va);
679 va_end(va);
680}
681
682static void
683trace_vprintf(const char *fmt, va_list va)
684{
685 if (debug != 1)
686 return;
Denis Vlasenko653d8e72009-03-19 21:59:35 +0000687 if (DEBUG_TIME)
688 fprintf(tracefile, "%u ", (int) time(NULL));
689 if (DEBUG_PID)
690 fprintf(tracefile, "[%u] ", (int) getpid());
691 if (DEBUG_SIG)
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +0200692 fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000693 vfprintf(tracefile, fmt, va);
694}
695
696static void
697trace_puts(const char *s)
698{
699 if (debug != 1)
700 return;
701 fputs(s, tracefile);
702}
703
704static void
705trace_puts_quoted(char *s)
706{
707 char *p;
708 char c;
709
710 if (debug != 1)
711 return;
712 putc('"', tracefile);
713 for (p = s; *p; p++) {
714 switch (*p) {
715 case '\n': c = 'n'; goto backslash;
716 case '\t': c = 't'; goto backslash;
717 case '\r': c = 'r'; goto backslash;
718 case '"': c = '"'; goto backslash;
719 case '\\': c = '\\'; goto backslash;
720 case CTLESC: c = 'e'; goto backslash;
721 case CTLVAR: c = 'v'; goto backslash;
722 case CTLVAR+CTLQUOTE: c = 'V'; goto backslash;
723 case CTLBACKQ: c = 'q'; goto backslash;
724 case CTLBACKQ+CTLQUOTE: c = 'Q'; goto backslash;
725 backslash:
726 putc('\\', tracefile);
727 putc(c, tracefile);
728 break;
729 default:
730 if (*p >= ' ' && *p <= '~')
731 putc(*p, tracefile);
732 else {
733 putc('\\', tracefile);
734 putc(*p >> 6 & 03, tracefile);
735 putc(*p >> 3 & 07, tracefile);
736 putc(*p & 07, tracefile);
737 }
738 break;
739 }
740 }
741 putc('"', tracefile);
742}
743
744static void
745trace_puts_args(char **ap)
746{
747 if (debug != 1)
748 return;
749 if (!*ap)
750 return;
751 while (1) {
752 trace_puts_quoted(*ap);
753 if (!*++ap) {
754 putc('\n', tracefile);
755 break;
756 }
757 putc(' ', tracefile);
758 }
759}
760
761static void
762opentrace(void)
763{
764 char s[100];
765#ifdef O_APPEND
766 int flags;
767#endif
768
769 if (debug != 1) {
770 if (tracefile)
771 fflush(tracefile);
772 /* leave open because libedit might be using it */
773 return;
774 }
775 strcpy(s, "./trace");
776 if (tracefile) {
777 if (!freopen(s, "a", tracefile)) {
778 fprintf(stderr, "Can't re-open %s\n", s);
779 debug = 0;
780 return;
781 }
782 } else {
783 tracefile = fopen(s, "a");
784 if (tracefile == NULL) {
785 fprintf(stderr, "Can't open %s\n", s);
786 debug = 0;
787 return;
788 }
789 }
790#ifdef O_APPEND
Denis Vlasenkod37f2222007-08-19 13:42:08 +0000791 flags = fcntl(fileno(tracefile), F_GETFL);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000792 if (flags >= 0)
793 fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
794#endif
795 setlinebuf(tracefile);
796 fputs("\nTracing started.\n", tracefile);
797}
798
799static void
800indent(int amount, char *pfx, FILE *fp)
801{
802 int i;
803
804 for (i = 0; i < amount; i++) {
805 if (pfx && i == amount - 1)
806 fputs(pfx, fp);
807 putc('\t', fp);
808 }
809}
810
811/* little circular references here... */
812static void shtree(union node *n, int ind, char *pfx, FILE *fp);
813
814static void
815sharg(union node *arg, FILE *fp)
816{
817 char *p;
818 struct nodelist *bqlist;
819 int subtype;
820
821 if (arg->type != NARG) {
822 out1fmt("<node type %d>\n", arg->type);
823 abort();
824 }
825 bqlist = arg->narg.backquote;
826 for (p = arg->narg.text; *p; p++) {
827 switch (*p) {
828 case CTLESC:
829 putc(*++p, fp);
830 break;
831 case CTLVAR:
832 putc('$', fp);
833 putc('{', fp);
834 subtype = *++p;
835 if (subtype == VSLENGTH)
836 putc('#', fp);
837
838 while (*p != '=')
839 putc(*p++, fp);
840
841 if (subtype & VSNUL)
842 putc(':', fp);
843
844 switch (subtype & VSTYPE) {
845 case VSNORMAL:
846 putc('}', fp);
847 break;
848 case VSMINUS:
849 putc('-', fp);
850 break;
851 case VSPLUS:
852 putc('+', fp);
853 break;
854 case VSQUESTION:
855 putc('?', fp);
856 break;
857 case VSASSIGN:
858 putc('=', fp);
859 break;
860 case VSTRIMLEFT:
861 putc('#', fp);
862 break;
863 case VSTRIMLEFTMAX:
864 putc('#', fp);
865 putc('#', fp);
866 break;
867 case VSTRIMRIGHT:
868 putc('%', fp);
869 break;
870 case VSTRIMRIGHTMAX:
871 putc('%', fp);
872 putc('%', fp);
873 break;
874 case VSLENGTH:
875 break;
876 default:
877 out1fmt("<subtype %d>", subtype);
878 }
879 break;
880 case CTLENDVAR:
881 putc('}', fp);
882 break;
883 case CTLBACKQ:
884 case CTLBACKQ|CTLQUOTE:
885 putc('$', fp);
886 putc('(', fp);
887 shtree(bqlist->n, -1, NULL, fp);
888 putc(')', fp);
889 break;
890 default:
891 putc(*p, fp);
892 break;
893 }
894 }
895}
896
Denys Vlasenko641dd7b2009-06-11 19:30:19 +0200897static void
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000898shcmd(union node *cmd, FILE *fp)
899{
900 union node *np;
901 int first;
902 const char *s;
903 int dftfd;
904
905 first = 1;
906 for (np = cmd->ncmd.args; np; np = np->narg.next) {
Denis Vlasenko40ba9982007-07-14 00:48:29 +0000907 if (!first)
908 putc(' ', fp);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000909 sharg(np, fp);
910 first = 0;
911 }
912 for (np = cmd->ncmd.redirect; np; np = np->nfile.next) {
Denis Vlasenko40ba9982007-07-14 00:48:29 +0000913 if (!first)
914 putc(' ', fp);
915 dftfd = 0;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000916 switch (np->nfile.type) {
Denis Vlasenko40ba9982007-07-14 00:48:29 +0000917 case NTO: s = ">>"+1; dftfd = 1; break;
918 case NCLOBBER: s = ">|"; dftfd = 1; break;
919 case NAPPEND: s = ">>"; dftfd = 1; break;
Denis Vlasenko559691a2008-10-05 18:39:31 +0000920#if ENABLE_ASH_BASH_COMPAT
921 case NTO2:
922#endif
Denis Vlasenko40ba9982007-07-14 00:48:29 +0000923 case NTOFD: s = ">&"; dftfd = 1; break;
Denis Vlasenko559691a2008-10-05 18:39:31 +0000924 case NFROM: s = "<"; break;
Denis Vlasenko40ba9982007-07-14 00:48:29 +0000925 case NFROMFD: s = "<&"; break;
926 case NFROMTO: s = "<>"; break;
927 default: s = "*error*"; break;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000928 }
929 if (np->nfile.fd != dftfd)
930 fprintf(fp, "%d", np->nfile.fd);
931 fputs(s, fp);
932 if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
933 fprintf(fp, "%d", np->ndup.dupfd);
934 } else {
935 sharg(np->nfile.fname, fp);
936 }
937 first = 0;
938 }
939}
940
941static void
942shtree(union node *n, int ind, char *pfx, FILE *fp)
943{
944 struct nodelist *lp;
945 const char *s;
946
947 if (n == NULL)
948 return;
949
950 indent(ind, pfx, fp);
Denys Vlasenko86e83ec2009-07-23 22:07:07 +0200951
952 if (n == NODE_EOF) {
953 fputs("<EOF>", fp);
954 return;
955 }
956
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000957 switch (n->type) {
958 case NSEMI:
959 s = "; ";
960 goto binop;
961 case NAND:
962 s = " && ";
963 goto binop;
964 case NOR:
965 s = " || ";
966 binop:
967 shtree(n->nbinary.ch1, ind, NULL, fp);
968 /* if (ind < 0) */
969 fputs(s, fp);
970 shtree(n->nbinary.ch2, ind, NULL, fp);
971 break;
972 case NCMD:
973 shcmd(n, fp);
974 if (ind >= 0)
975 putc('\n', fp);
976 break;
977 case NPIPE:
978 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
Denys Vlasenko7cee00e2009-07-24 01:08:03 +0200979 shtree(lp->n, 0, NULL, fp);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000980 if (lp->next)
981 fputs(" | ", fp);
982 }
Denis Vlasenko2dc240c2008-07-24 06:07:50 +0000983 if (n->npipe.pipe_backgnd)
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000984 fputs(" &", fp);
985 if (ind >= 0)
986 putc('\n', fp);
987 break;
988 default:
989 fprintf(fp, "<node type %d>", n->type);
990 if (ind >= 0)
991 putc('\n', fp);
992 break;
993 }
994}
995
996static void
997showtree(union node *n)
998{
999 trace_puts("showtree called\n");
Denys Vlasenko883cea42009-07-11 15:31:59 +02001000 shtree(n, 1, NULL, stderr);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00001001}
1002
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00001003#endif /* DEBUG */
1004
1005
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00001006/* ============ Parser data */
1007
1008/*
Denis Vlasenkob012b102007-02-19 22:43:01 +00001009 * ash_vmsg() needs parsefile->fd, hence parsefile definition is moved up.
1010 */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001011struct strlist {
1012 struct strlist *next;
1013 char *text;
1014};
1015
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00001016struct alias;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00001017
Denis Vlasenkob012b102007-02-19 22:43:01 +00001018struct strpush {
1019 struct strpush *prev; /* preceding string on stack */
Denis Vlasenko41eb3002008-11-28 03:42:31 +00001020 char *prev_string;
1021 int prev_left_in_line;
Denis Vlasenkob012b102007-02-19 22:43:01 +00001022#if ENABLE_ASH_ALIAS
1023 struct alias *ap; /* if push was associated with an alias */
1024#endif
1025 char *string; /* remember the string since it may change */
1026};
1027
1028struct parsefile {
1029 struct parsefile *prev; /* preceding file on stack */
1030 int linno; /* current line */
1031 int fd; /* file descriptor (or -1 if string) */
Denis Vlasenko41eb3002008-11-28 03:42:31 +00001032 int left_in_line; /* number of chars left in this line */
1033 int left_in_buffer; /* number of chars left in this buffer past the line */
1034 char *next_to_pgetc; /* next char in buffer */
Denis Vlasenkob012b102007-02-19 22:43:01 +00001035 char *buf; /* input buffer */
1036 struct strpush *strpush; /* for pushing strings at this level */
1037 struct strpush basestrpush; /* so pushing one is fast */
1038};
1039
Denis Vlasenko448d30e2008-06-27 00:24:11 +00001040static struct parsefile basepf; /* top level input file */
Denis Vlasenkob07a4962008-06-22 13:16:23 +00001041static struct parsefile *g_parsefile = &basepf; /* current input file */
Denis Vlasenkob012b102007-02-19 22:43:01 +00001042static int startlinno; /* line # where last token started */
1043static char *commandname; /* currently executing command */
1044static struct strlist *cmdenviron; /* environment for builtin command */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00001045static uint8_t exitstatus; /* exit status of last command */
Denis Vlasenkob012b102007-02-19 22:43:01 +00001046
1047
1048/* ============ Message printing */
1049
1050static void
1051ash_vmsg(const char *msg, va_list ap)
1052{
1053 fprintf(stderr, "%s: ", arg0);
1054 if (commandname) {
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00001055 if (strcmp(arg0, commandname))
1056 fprintf(stderr, "%s: ", commandname);
Denis Vlasenkob07a4962008-06-22 13:16:23 +00001057 if (!iflag || g_parsefile->fd)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00001058 fprintf(stderr, "line %d: ", startlinno);
Eric Andersenc470f442003-07-28 09:56:35 +00001059 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00001060 vfprintf(stderr, msg, ap);
1061 outcslow('\n', stderr);
Eric Andersenc470f442003-07-28 09:56:35 +00001062}
Denis Vlasenkob012b102007-02-19 22:43:01 +00001063
1064/*
1065 * Exverror is called to raise the error exception. If the second argument
1066 * is not NULL then error prints an error message using printf style
1067 * formatting. It then raises the error exception.
1068 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001069static void ash_vmsg_and_raise(int, const char *, va_list) NORETURN;
Denis Vlasenkob012b102007-02-19 22:43:01 +00001070static void
1071ash_vmsg_and_raise(int cond, const char *msg, va_list ap)
Eric Andersenc470f442003-07-28 09:56:35 +00001072{
Denis Vlasenkob012b102007-02-19 22:43:01 +00001073#if DEBUG
1074 if (msg) {
1075 TRACE(("ash_vmsg_and_raise(%d, \"", cond));
1076 TRACEV((msg, ap));
1077 TRACE(("\") pid=%d\n", getpid()));
1078 } else
1079 TRACE(("ash_vmsg_and_raise(%d, NULL) pid=%d\n", cond, getpid()));
1080 if (msg)
1081#endif
1082 ash_vmsg(msg, ap);
1083
1084 flush_stdout_stderr();
1085 raise_exception(cond);
1086 /* NOTREACHED */
Eric Andersenc470f442003-07-28 09:56:35 +00001087}
Denis Vlasenkob012b102007-02-19 22:43:01 +00001088
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001089static void ash_msg_and_raise_error(const char *, ...) NORETURN;
Denis Vlasenkob012b102007-02-19 22:43:01 +00001090static void
1091ash_msg_and_raise_error(const char *msg, ...)
1092{
1093 va_list ap;
1094
1095 va_start(ap, msg);
1096 ash_vmsg_and_raise(EXERROR, msg, ap);
1097 /* NOTREACHED */
1098 va_end(ap);
1099}
1100
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00001101static void raise_error_syntax(const char *) NORETURN;
1102static void
1103raise_error_syntax(const char *msg)
1104{
1105 ash_msg_and_raise_error("syntax error: %s", msg);
1106 /* NOTREACHED */
1107}
1108
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00001109static void ash_msg_and_raise(int, const char *, ...) NORETURN;
Denis Vlasenkob012b102007-02-19 22:43:01 +00001110static void
1111ash_msg_and_raise(int cond, const char *msg, ...)
1112{
1113 va_list ap;
1114
1115 va_start(ap, msg);
1116 ash_vmsg_and_raise(cond, msg, ap);
1117 /* NOTREACHED */
1118 va_end(ap);
1119}
1120
1121/*
1122 * error/warning routines for external builtins
1123 */
1124static void
1125ash_msg(const char *fmt, ...)
1126{
1127 va_list ap;
1128
1129 va_start(ap, fmt);
1130 ash_vmsg(fmt, ap);
1131 va_end(ap);
1132}
1133
1134/*
1135 * Return a string describing an error. The returned string may be a
1136 * pointer to a static buffer that will be overwritten on the next call.
1137 * Action describes the operation that got the error.
1138 */
1139static const char *
1140errmsg(int e, const char *em)
1141{
1142 if (e == ENOENT || e == ENOTDIR) {
1143 return em;
1144 }
1145 return strerror(e);
1146}
1147
1148
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001149/* ============ Memory allocation */
1150
Denys Vlasenkoe7670ff2009-10-11 00:45:25 +02001151#if 0
1152/* I consider these wrappers nearly useless:
1153 * ok, they return you to nearest exception handler, but
1154 * how much memory do you leak in the process, making
1155 * memory starvation worse?
1156 */
1157static void *
1158ckrealloc(void * p, size_t nbytes)
1159{
1160 p = realloc(p, nbytes);
1161 if (!p)
1162 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1163 return p;
1164}
1165
1166static void *
1167ckmalloc(size_t nbytes)
1168{
1169 return ckrealloc(NULL, nbytes);
1170}
1171
1172static void *
1173ckzalloc(size_t nbytes)
1174{
1175 return memset(ckmalloc(nbytes), 0, nbytes);
1176}
1177
1178static char *
1179ckstrdup(const char *s)
1180{
1181 char *p = strdup(s);
1182 if (!p)
1183 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1184 return p;
1185}
1186#else
1187/* Using bbox equivalents. They exit if out of memory */
1188# define ckrealloc xrealloc
1189# define ckmalloc xmalloc
1190# define ckzalloc xzalloc
1191# define ckstrdup xstrdup
1192#endif
1193
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001194/*
1195 * It appears that grabstackstr() will barf with such alignments
1196 * because stalloc() will return a string allocated in a new stackblock.
1197 */
1198#define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
1199enum {
1200 /* Most machines require the value returned from malloc to be aligned
1201 * in some way. The following macro will get this right
1202 * on many machines. */
Denys Vlasenko0e5e4ea2009-10-11 00:36:20 +02001203 SHELL_SIZE = sizeof(union { int i; char *cp; double d; }) - 1,
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001204 /* Minimum size of a block */
Denis Vlasenko01631112007-12-16 17:20:38 +00001205 MINSIZE = SHELL_ALIGN(504),
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001206};
1207
1208struct stack_block {
1209 struct stack_block *prev;
1210 char space[MINSIZE];
1211};
1212
1213struct stackmark {
1214 struct stack_block *stackp;
1215 char *stacknxt;
1216 size_t stacknleft;
1217 struct stackmark *marknext;
1218};
1219
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001220
Denis Vlasenko01631112007-12-16 17:20:38 +00001221struct globals_memstack {
1222 struct stack_block *g_stackp; // = &stackbase;
1223 struct stackmark *markp;
1224 char *g_stacknxt; // = stackbase.space;
1225 char *sstrend; // = stackbase.space + MINSIZE;
1226 size_t g_stacknleft; // = MINSIZE;
1227 int herefd; // = -1;
1228 struct stack_block stackbase;
1229};
Denis Vlasenko574f2f42008-02-27 18:41:59 +00001230extern struct globals_memstack *const ash_ptr_to_globals_memstack;
1231#define G_memstack (*ash_ptr_to_globals_memstack)
Denis Vlasenko01631112007-12-16 17:20:38 +00001232#define g_stackp (G_memstack.g_stackp )
1233#define markp (G_memstack.markp )
1234#define g_stacknxt (G_memstack.g_stacknxt )
1235#define sstrend (G_memstack.sstrend )
1236#define g_stacknleft (G_memstack.g_stacknleft)
1237#define herefd (G_memstack.herefd )
1238#define stackbase (G_memstack.stackbase )
1239#define INIT_G_memstack() do { \
Denis Vlasenko574f2f42008-02-27 18:41:59 +00001240 (*(struct globals_memstack**)&ash_ptr_to_globals_memstack) = xzalloc(sizeof(G_memstack)); \
1241 barrier(); \
Denis Vlasenko01631112007-12-16 17:20:38 +00001242 g_stackp = &stackbase; \
1243 g_stacknxt = stackbase.space; \
1244 g_stacknleft = MINSIZE; \
1245 sstrend = stackbase.space + MINSIZE; \
1246 herefd = -1; \
1247} while (0)
1248
Denys Vlasenkoe7670ff2009-10-11 00:45:25 +02001249
Denis Vlasenko01631112007-12-16 17:20:38 +00001250#define stackblock() ((void *)g_stacknxt)
1251#define stackblocksize() g_stacknleft
1252
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001253/*
1254 * Parse trees for commands are allocated in lifo order, so we use a stack
1255 * to make this more efficient, and also to avoid all sorts of exception
1256 * handling code to handle interrupts in the middle of a parse.
1257 *
1258 * The size 504 was chosen because the Ultrix malloc handles that size
1259 * well.
1260 */
1261static void *
1262stalloc(size_t nbytes)
1263{
1264 char *p;
1265 size_t aligned;
1266
1267 aligned = SHELL_ALIGN(nbytes);
Denis Vlasenko01631112007-12-16 17:20:38 +00001268 if (aligned > g_stacknleft) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001269 size_t len;
1270 size_t blocksize;
1271 struct stack_block *sp;
1272
1273 blocksize = aligned;
1274 if (blocksize < MINSIZE)
1275 blocksize = MINSIZE;
1276 len = sizeof(struct stack_block) - MINSIZE + blocksize;
1277 if (len < blocksize)
1278 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1279 INT_OFF;
1280 sp = ckmalloc(len);
Denis Vlasenko01631112007-12-16 17:20:38 +00001281 sp->prev = g_stackp;
1282 g_stacknxt = sp->space;
1283 g_stacknleft = blocksize;
1284 sstrend = g_stacknxt + blocksize;
1285 g_stackp = sp;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001286 INT_ON;
1287 }
Denis Vlasenko01631112007-12-16 17:20:38 +00001288 p = g_stacknxt;
1289 g_stacknxt += aligned;
1290 g_stacknleft -= aligned;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001291 return p;
1292}
1293
Denis Vlasenko597906c2008-02-20 16:38:54 +00001294static void *
1295stzalloc(size_t nbytes)
1296{
1297 return memset(stalloc(nbytes), 0, nbytes);
1298}
1299
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001300static void
1301stunalloc(void *p)
1302{
1303#if DEBUG
Denis Vlasenko01631112007-12-16 17:20:38 +00001304 if (!p || (g_stacknxt < (char *)p) || ((char *)p < g_stackp->space)) {
Bernhard Reutner-Fischer5e25ddb2008-05-19 09:48:17 +00001305 write(STDERR_FILENO, "stunalloc\n", 10);
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001306 abort();
1307 }
1308#endif
Denis Vlasenko01631112007-12-16 17:20:38 +00001309 g_stacknleft += g_stacknxt - (char *)p;
1310 g_stacknxt = p;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001311}
1312
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001313/*
1314 * Like strdup but works with the ash stack.
1315 */
1316static char *
1317ststrdup(const char *p)
1318{
1319 size_t len = strlen(p) + 1;
1320 return memcpy(stalloc(len), p, len);
1321}
1322
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001323static void
1324setstackmark(struct stackmark *mark)
1325{
Denis Vlasenko01631112007-12-16 17:20:38 +00001326 mark->stackp = g_stackp;
1327 mark->stacknxt = g_stacknxt;
1328 mark->stacknleft = g_stacknleft;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001329 mark->marknext = markp;
1330 markp = mark;
1331}
1332
1333static void
1334popstackmark(struct stackmark *mark)
1335{
1336 struct stack_block *sp;
1337
Denis Vlasenko93ebd4f2007-03-13 20:55:36 +00001338 if (!mark->stackp)
1339 return;
1340
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001341 INT_OFF;
1342 markp = mark->marknext;
Denis Vlasenko01631112007-12-16 17:20:38 +00001343 while (g_stackp != mark->stackp) {
1344 sp = g_stackp;
1345 g_stackp = sp->prev;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001346 free(sp);
1347 }
Denis Vlasenko01631112007-12-16 17:20:38 +00001348 g_stacknxt = mark->stacknxt;
1349 g_stacknleft = mark->stacknleft;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001350 sstrend = mark->stacknxt + mark->stacknleft;
1351 INT_ON;
1352}
1353
1354/*
1355 * When the parser reads in a string, it wants to stick the string on the
1356 * stack and only adjust the stack pointer when it knows how big the
1357 * string is. Stackblock (defined in stack.h) returns a pointer to a block
1358 * of space on top of the stack and stackblocklen returns the length of
1359 * this block. Growstackblock will grow this space by at least one byte,
1360 * possibly moving it (like realloc). Grabstackblock actually allocates the
1361 * part of the block that has been used.
1362 */
1363static void
1364growstackblock(void)
1365{
1366 size_t newlen;
1367
Denis Vlasenko01631112007-12-16 17:20:38 +00001368 newlen = g_stacknleft * 2;
1369 if (newlen < g_stacknleft)
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001370 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1371 if (newlen < 128)
1372 newlen += 128;
1373
Denis Vlasenko01631112007-12-16 17:20:38 +00001374 if (g_stacknxt == g_stackp->space && g_stackp != &stackbase) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001375 struct stack_block *oldstackp;
1376 struct stackmark *xmark;
1377 struct stack_block *sp;
1378 struct stack_block *prevstackp;
1379 size_t grosslen;
1380
1381 INT_OFF;
Denis Vlasenko01631112007-12-16 17:20:38 +00001382 oldstackp = g_stackp;
1383 sp = g_stackp;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001384 prevstackp = sp->prev;
1385 grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
1386 sp = ckrealloc(sp, grosslen);
1387 sp->prev = prevstackp;
Denis Vlasenko01631112007-12-16 17:20:38 +00001388 g_stackp = sp;
1389 g_stacknxt = sp->space;
1390 g_stacknleft = newlen;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001391 sstrend = sp->space + newlen;
1392
1393 /*
1394 * Stack marks pointing to the start of the old block
1395 * must be relocated to point to the new block
1396 */
1397 xmark = markp;
1398 while (xmark != NULL && xmark->stackp == oldstackp) {
Denis Vlasenko01631112007-12-16 17:20:38 +00001399 xmark->stackp = g_stackp;
1400 xmark->stacknxt = g_stacknxt;
1401 xmark->stacknleft = g_stacknleft;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001402 xmark = xmark->marknext;
1403 }
1404 INT_ON;
1405 } else {
Denis Vlasenko01631112007-12-16 17:20:38 +00001406 char *oldspace = g_stacknxt;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00001407 size_t oldlen = g_stacknleft;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001408 char *p = stalloc(newlen);
1409
1410 /* free the space we just allocated */
Denis Vlasenko01631112007-12-16 17:20:38 +00001411 g_stacknxt = memcpy(p, oldspace, oldlen);
1412 g_stacknleft += newlen;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001413 }
1414}
1415
1416static void
1417grabstackblock(size_t len)
1418{
1419 len = SHELL_ALIGN(len);
Denis Vlasenko01631112007-12-16 17:20:38 +00001420 g_stacknxt += len;
1421 g_stacknleft -= len;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001422}
1423
1424/*
1425 * The following routines are somewhat easier to use than the above.
1426 * The user declares a variable of type STACKSTR, which may be declared
1427 * to be a register. The macro STARTSTACKSTR initializes things. Then
1428 * the user uses the macro STPUTC to add characters to the string. In
1429 * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
1430 * grown as necessary. When the user is done, she can just leave the
1431 * string there and refer to it using stackblock(). Or she can allocate
1432 * the space for it using grabstackstr(). If it is necessary to allow
1433 * someone else to use the stack temporarily and then continue to grow
1434 * the string, the user should use grabstack to allocate the space, and
1435 * then call ungrabstr(p) to return to the previous mode of operation.
1436 *
1437 * USTPUTC is like STPUTC except that it doesn't check for overflow.
1438 * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
1439 * is space for at least one character.
1440 */
1441static void *
1442growstackstr(void)
1443{
1444 size_t len = stackblocksize();
1445 if (herefd >= 0 && len >= 1024) {
1446 full_write(herefd, stackblock(), len);
1447 return stackblock();
1448 }
1449 growstackblock();
Denis Vlasenko29eb3592008-05-18 14:06:08 +00001450 return (char *)stackblock() + len;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001451}
1452
1453/*
1454 * Called from CHECKSTRSPACE.
1455 */
1456static char *
1457makestrspace(size_t newlen, char *p)
1458{
Denis Vlasenko01631112007-12-16 17:20:38 +00001459 size_t len = p - g_stacknxt;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001460 size_t size = stackblocksize();
1461
1462 for (;;) {
1463 size_t nleft;
1464
1465 size = stackblocksize();
1466 nleft = size - len;
1467 if (nleft >= newlen)
1468 break;
1469 growstackblock();
1470 }
Denis Vlasenko29eb3592008-05-18 14:06:08 +00001471 return (char *)stackblock() + len;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001472}
1473
1474static char *
1475stack_nputstr(const char *s, size_t n, char *p)
1476{
1477 p = makestrspace(n, p);
Denis Vlasenko29eb3592008-05-18 14:06:08 +00001478 p = (char *)memcpy(p, s, n) + n;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001479 return p;
1480}
1481
1482static char *
1483stack_putstr(const char *s, char *p)
1484{
1485 return stack_nputstr(s, strlen(s), p);
1486}
1487
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001488static char *
1489_STPUTC(int c, char *p)
1490{
1491 if (p == sstrend)
1492 p = growstackstr();
1493 *p++ = c;
1494 return p;
1495}
1496
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00001497#define STARTSTACKSTR(p) ((p) = stackblock())
1498#define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
Denis Vlasenko843cbd52008-06-27 00:23:18 +00001499#define CHECKSTRSPACE(n, p) do { \
1500 char *q = (p); \
1501 size_t l = (n); \
1502 size_t m = sstrend - q; \
1503 if (l > m) \
1504 (p) = makestrspace(l, q); \
1505} while (0)
Denis Vlasenkoef527f52008-06-23 01:52:30 +00001506#define USTPUTC(c, p) (*(p)++ = (c))
Denis Vlasenko843cbd52008-06-27 00:23:18 +00001507#define STACKSTRNUL(p) do { \
1508 if ((p) == sstrend) \
1509 (p) = growstackstr(); \
1510 *(p) = '\0'; \
1511} while (0)
Denis Vlasenkoef527f52008-06-23 01:52:30 +00001512#define STUNPUTC(p) (--(p))
1513#define STTOPC(p) ((p)[-1])
1514#define STADJUST(amount, p) ((p) += (amount))
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001515
1516#define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
Denis Vlasenkoef527f52008-06-23 01:52:30 +00001517#define ungrabstackstr(s, p) stunalloc(s)
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001518#define stackstrend() ((void *)sstrend)
1519
1520
1521/* ============ String helpers */
1522
1523/*
1524 * prefix -- see if pfx is a prefix of string.
1525 */
1526static char *
1527prefix(const char *string, const char *pfx)
1528{
1529 while (*pfx) {
1530 if (*pfx++ != *string++)
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00001531 return NULL;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001532 }
1533 return (char *) string;
1534}
1535
1536/*
1537 * Check for a valid number. This should be elsewhere.
1538 */
1539static int
1540is_number(const char *p)
1541{
1542 do {
1543 if (!isdigit(*p))
1544 return 0;
1545 } while (*++p != '\0');
1546 return 1;
1547}
1548
1549/*
1550 * Convert a string of digits to an integer, printing an error message on
1551 * failure.
1552 */
1553static int
1554number(const char *s)
1555{
1556 if (!is_number(s))
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02001557 ash_msg_and_raise_error(msg_illnum, s);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001558 return atoi(s);
1559}
1560
1561/*
1562 * Produce a possibly single quoted string suitable as input to the shell.
1563 * The return string is allocated on the stack.
1564 */
1565static char *
1566single_quote(const char *s)
1567{
1568 char *p;
1569
1570 STARTSTACKSTR(p);
1571
1572 do {
1573 char *q;
1574 size_t len;
1575
1576 len = strchrnul(s, '\'') - s;
1577
1578 q = p = makestrspace(len + 3, p);
1579
1580 *q++ = '\'';
Denis Vlasenko29eb3592008-05-18 14:06:08 +00001581 q = (char *)memcpy(q, s, len) + len;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001582 *q++ = '\'';
1583 s += len;
1584
1585 STADJUST(q - p, p);
1586
1587 len = strspn(s, "'");
1588 if (!len)
1589 break;
1590
1591 q = p = makestrspace(len + 3, p);
1592
1593 *q++ = '"';
Denis Vlasenko29eb3592008-05-18 14:06:08 +00001594 q = (char *)memcpy(q, s, len) + len;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001595 *q++ = '"';
1596 s += len;
1597
1598 STADJUST(q - p, p);
1599 } while (*s);
1600
1601 USTPUTC(0, p);
1602
1603 return stackblock();
1604}
1605
1606
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00001607/* ============ nextopt */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001608
1609static char **argptr; /* argument list for builtin commands */
1610static char *optionarg; /* set by nextopt (like getopt) */
1611static char *optptr; /* used by nextopt */
1612
1613/*
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001614 * XXX - should get rid of. Have all builtins use getopt(3).
1615 * The library getopt must have the BSD extension static variable
1616 * "optreset", otherwise it can't be used within the shell safely.
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001617 *
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001618 * Standard option processing (a la getopt) for builtin routines.
1619 * The only argument that is passed to nextopt is the option string;
1620 * the other arguments are unnecessary. It returns the character,
1621 * or '\0' on end of input.
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001622 */
1623static int
1624nextopt(const char *optstring)
1625{
1626 char *p;
1627 const char *q;
1628 char c;
1629
1630 p = optptr;
1631 if (p == NULL || *p == '\0') {
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001632 /* We ate entire "-param", take next one */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001633 p = *argptr;
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001634 if (p == NULL)
1635 return '\0';
1636 if (*p != '-')
1637 return '\0';
1638 if (*++p == '\0') /* just "-" ? */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001639 return '\0';
1640 argptr++;
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001641 if (LONE_DASH(p)) /* "--" ? */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001642 return '\0';
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001643 /* p => next "-param" */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001644 }
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001645 /* p => some option char in the middle of a "-param" */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001646 c = *p++;
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +00001647 for (q = optstring; *q != c;) {
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001648 if (*q == '\0')
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00001649 ash_msg_and_raise_error("illegal option -%c", c);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001650 if (*++q == ':')
1651 q++;
1652 }
1653 if (*++q == ':') {
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00001654 if (*p == '\0') {
1655 p = *argptr++;
1656 if (p == NULL)
1657 ash_msg_and_raise_error("no arg for -%c option", c);
1658 }
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001659 optionarg = p;
1660 p = NULL;
1661 }
1662 optptr = p;
1663 return c;
1664}
1665
1666
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00001667/* ============ Shell variables */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001668
Denis Vlasenko01631112007-12-16 17:20:38 +00001669/*
1670 * The parsefile structure pointed to by the global variable parsefile
1671 * contains information about the current file being read.
1672 */
Denis Vlasenko01631112007-12-16 17:20:38 +00001673struct shparam {
1674 int nparam; /* # of positional parameters (without $0) */
1675#if ENABLE_ASH_GETOPTS
1676 int optind; /* next parameter to be processed by getopts */
1677 int optoff; /* used by getopts */
1678#endif
1679 unsigned char malloced; /* if parameter list dynamically allocated */
1680 char **p; /* parameter list */
1681};
1682
1683/*
1684 * Free the list of positional parameters.
1685 */
1686static void
1687freeparam(volatile struct shparam *param)
1688{
Denis Vlasenko01631112007-12-16 17:20:38 +00001689 if (param->malloced) {
Denis Vlasenko3177ba02008-07-13 20:39:23 +00001690 char **ap, **ap1;
1691 ap = ap1 = param->p;
1692 while (*ap)
1693 free(*ap++);
1694 free(ap1);
Denis Vlasenko01631112007-12-16 17:20:38 +00001695 }
1696}
1697
1698#if ENABLE_ASH_GETOPTS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001699static void FAST_FUNC getoptsreset(const char *value);
Denis Vlasenko01631112007-12-16 17:20:38 +00001700#endif
1701
1702struct var {
1703 struct var *next; /* next entry in hash list */
1704 int flags; /* flags are defined above */
1705 const char *text; /* name=value */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001706 void (*func)(const char *) FAST_FUNC; /* function to be called when */
Denis Vlasenko01631112007-12-16 17:20:38 +00001707 /* the variable gets set/unset */
1708};
1709
1710struct localvar {
1711 struct localvar *next; /* next local variable in list */
1712 struct var *vp; /* the variable that was made local */
1713 int flags; /* saved flags */
1714 const char *text; /* saved text */
1715};
1716
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001717/* flags */
1718#define VEXPORT 0x01 /* variable is exported */
1719#define VREADONLY 0x02 /* variable cannot be modified */
1720#define VSTRFIXED 0x04 /* variable struct is statically allocated */
1721#define VTEXTFIXED 0x08 /* text is statically allocated */
1722#define VSTACK 0x10 /* text is allocated on the stack */
1723#define VUNSET 0x20 /* the variable is not set */
1724#define VNOFUNC 0x40 /* don't call the callback function */
1725#define VNOSET 0x80 /* do not set variable - just readonly test */
1726#define VNOSAVE 0x100 /* when text is on the heap before setvareq */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00001727#if ENABLE_ASH_RANDOM_SUPPORT
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00001728# define VDYNAMIC 0x200 /* dynamic variable */
1729#else
1730# define VDYNAMIC 0
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001731#endif
1732
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001733#ifdef IFS_BROKEN
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00001734static const char defifsvar[] ALIGN1 = "IFS= \t\n";
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001735#define defifs (defifsvar + 4)
1736#else
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00001737static const char defifs[] ALIGN1 = " \t\n";
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001738#endif
1739
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00001740
Denis Vlasenko01631112007-12-16 17:20:38 +00001741/* Need to be before varinit_data[] */
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00001742#if ENABLE_LOCALE_SUPPORT
Denys Vlasenko2634bf32009-06-09 18:40:07 +02001743static void FAST_FUNC
Denis Vlasenkoa8915072007-02-23 21:10:06 +00001744change_lc_all(const char *value)
1745{
1746 if (value && *value != '\0')
1747 setlocale(LC_ALL, value);
1748}
Denys Vlasenko2634bf32009-06-09 18:40:07 +02001749static void FAST_FUNC
Denis Vlasenkoa8915072007-02-23 21:10:06 +00001750change_lc_ctype(const char *value)
1751{
1752 if (value && *value != '\0')
1753 setlocale(LC_CTYPE, value);
1754}
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00001755#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001756#if ENABLE_ASH_MAIL
1757static void chkmail(void);
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001758static void changemail(const char *) FAST_FUNC;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001759#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001760static void changepath(const char *) FAST_FUNC;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001761#if ENABLE_ASH_RANDOM_SUPPORT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001762static void change_random(const char *) FAST_FUNC;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001763#endif
1764
Denis Vlasenko01631112007-12-16 17:20:38 +00001765static const struct {
1766 int flags;
1767 const char *text;
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001768 void (*func)(const char *) FAST_FUNC;
Denis Vlasenko01631112007-12-16 17:20:38 +00001769} varinit_data[] = {
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001770#ifdef IFS_BROKEN
Denis Vlasenko01631112007-12-16 17:20:38 +00001771 { VSTRFIXED|VTEXTFIXED , defifsvar , NULL },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001772#else
Denis Vlasenko01631112007-12-16 17:20:38 +00001773 { VSTRFIXED|VTEXTFIXED|VUNSET, "IFS\0" , NULL },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001774#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001775#if ENABLE_ASH_MAIL
Denis Vlasenko01631112007-12-16 17:20:38 +00001776 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL\0" , changemail },
1777 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH\0", changemail },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001778#endif
Denis Vlasenko01631112007-12-16 17:20:38 +00001779 { VSTRFIXED|VTEXTFIXED , bb_PATH_root_path, changepath },
1780 { VSTRFIXED|VTEXTFIXED , "PS1=$ " , NULL },
1781 { VSTRFIXED|VTEXTFIXED , "PS2=> " , NULL },
1782 { VSTRFIXED|VTEXTFIXED , "PS4=+ " , NULL },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001783#if ENABLE_ASH_GETOPTS
Denis Vlasenko01631112007-12-16 17:20:38 +00001784 { VSTRFIXED|VTEXTFIXED , "OPTIND=1" , getoptsreset },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001785#endif
1786#if ENABLE_ASH_RANDOM_SUPPORT
Denis Vlasenko01631112007-12-16 17:20:38 +00001787 { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM\0", change_random },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001788#endif
1789#if ENABLE_LOCALE_SUPPORT
Denis Vlasenko01631112007-12-16 17:20:38 +00001790 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL\0" , change_lc_all },
1791 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE\0", change_lc_ctype },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001792#endif
1793#if ENABLE_FEATURE_EDITING_SAVEHISTORY
Denis Vlasenko01631112007-12-16 17:20:38 +00001794 { VSTRFIXED|VTEXTFIXED|VUNSET, "HISTFILE\0", NULL },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001795#endif
1796};
1797
Denis Vlasenko0b769642008-07-24 07:54:57 +00001798struct redirtab;
Denis Vlasenko01631112007-12-16 17:20:38 +00001799
1800struct globals_var {
1801 struct shparam shellparam; /* $@ current positional parameters */
1802 struct redirtab *redirlist;
1803 int g_nullredirs;
1804 int preverrout_fd; /* save fd2 before print debug if xflag is set. */
1805 struct var *vartab[VTABSIZE];
1806 struct var varinit[ARRAY_SIZE(varinit_data)];
1807};
Denis Vlasenko574f2f42008-02-27 18:41:59 +00001808extern struct globals_var *const ash_ptr_to_globals_var;
1809#define G_var (*ash_ptr_to_globals_var)
Denis Vlasenko01631112007-12-16 17:20:38 +00001810#define shellparam (G_var.shellparam )
Denis Vlasenko0b769642008-07-24 07:54:57 +00001811//#define redirlist (G_var.redirlist )
Denis Vlasenko01631112007-12-16 17:20:38 +00001812#define g_nullredirs (G_var.g_nullredirs )
1813#define preverrout_fd (G_var.preverrout_fd)
1814#define vartab (G_var.vartab )
1815#define varinit (G_var.varinit )
1816#define INIT_G_var() do { \
Denis Vlasenko6b06cb82008-05-15 21:30:45 +00001817 unsigned i; \
Denis Vlasenko574f2f42008-02-27 18:41:59 +00001818 (*(struct globals_var**)&ash_ptr_to_globals_var) = xzalloc(sizeof(G_var)); \
1819 barrier(); \
Denis Vlasenko01631112007-12-16 17:20:38 +00001820 for (i = 0; i < ARRAY_SIZE(varinit_data); i++) { \
1821 varinit[i].flags = varinit_data[i].flags; \
1822 varinit[i].text = varinit_data[i].text; \
1823 varinit[i].func = varinit_data[i].func; \
1824 } \
1825} while (0)
1826
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001827#define vifs varinit[0]
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001828#if ENABLE_ASH_MAIL
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001829# define vmail (&vifs)[1]
1830# define vmpath (&vmail)[1]
1831# define vpath (&vmpath)[1]
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001832#else
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001833# define vpath (&vifs)[1]
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001834#endif
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001835#define vps1 (&vpath)[1]
1836#define vps2 (&vps1)[1]
1837#define vps4 (&vps2)[1]
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001838#if ENABLE_ASH_GETOPTS
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001839# define voptind (&vps4)[1]
1840# if ENABLE_ASH_RANDOM_SUPPORT
1841# define vrandom (&voptind)[1]
1842# endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001843#else
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001844# if ENABLE_ASH_RANDOM_SUPPORT
1845# define vrandom (&vps4)[1]
1846# endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001847#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001848
1849/*
1850 * The following macros access the values of the above variables.
1851 * They have to skip over the name. They return the null string
1852 * for unset variables.
1853 */
1854#define ifsval() (vifs.text + 4)
1855#define ifsset() ((vifs.flags & VUNSET) == 0)
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001856#if ENABLE_ASH_MAIL
1857# define mailval() (vmail.text + 5)
1858# define mpathval() (vmpath.text + 9)
1859# define mpathset() ((vmpath.flags & VUNSET) == 0)
1860#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001861#define pathval() (vpath.text + 5)
1862#define ps1val() (vps1.text + 4)
1863#define ps2val() (vps2.text + 4)
1864#define ps4val() (vps4.text + 4)
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001865#if ENABLE_ASH_GETOPTS
1866# define optindval() (voptind.text + 7)
1867#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001868
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001869
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001870#define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
1871#define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
1872
Denis Vlasenko01631112007-12-16 17:20:38 +00001873#if ENABLE_ASH_GETOPTS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02001874static void FAST_FUNC
Denis Vlasenko01631112007-12-16 17:20:38 +00001875getoptsreset(const char *value)
1876{
1877 shellparam.optind = number(value);
1878 shellparam.optoff = -1;
1879}
1880#endif
1881
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001882/*
1883 * Return of a legal variable name (a letter or underscore followed by zero or
1884 * more letters, underscores, and digits).
1885 */
1886static char *
1887endofname(const char *name)
1888{
1889 char *p;
1890
1891 p = (char *) name;
1892 if (!is_name(*p))
1893 return p;
1894 while (*++p) {
1895 if (!is_in_name(*p))
1896 break;
1897 }
1898 return p;
1899}
1900
1901/*
1902 * Compares two strings up to the first = or '\0'. The first
1903 * string must be terminated by '='; the second may be terminated by
1904 * either '=' or '\0'.
1905 */
1906static int
1907varcmp(const char *p, const char *q)
1908{
1909 int c, d;
1910
1911 while ((c = *p) == (d = *q)) {
1912 if (!c || c == '=')
1913 goto out;
1914 p++;
1915 q++;
1916 }
1917 if (c == '=')
Denis Vlasenko9650f362007-02-23 01:04:37 +00001918 c = '\0';
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001919 if (d == '=')
Denis Vlasenko9650f362007-02-23 01:04:37 +00001920 d = '\0';
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001921 out:
1922 return c - d;
1923}
1924
1925static int
1926varequal(const char *a, const char *b)
1927{
1928 return !varcmp(a, b);
1929}
1930
1931/*
1932 * Find the appropriate entry in the hash table from the name.
1933 */
1934static struct var **
1935hashvar(const char *p)
1936{
1937 unsigned hashval;
1938
1939 hashval = ((unsigned char) *p) << 4;
1940 while (*p && *p != '=')
1941 hashval += (unsigned char) *p++;
1942 return &vartab[hashval % VTABSIZE];
1943}
1944
1945static int
1946vpcmp(const void *a, const void *b)
1947{
1948 return varcmp(*(const char **)a, *(const char **)b);
1949}
1950
1951/*
1952 * This routine initializes the builtin variables.
1953 */
1954static void
1955initvar(void)
1956{
1957 struct var *vp;
1958 struct var *end;
1959 struct var **vpp;
1960
1961 /*
1962 * PS1 depends on uid
1963 */
1964#if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
1965 vps1.text = "PS1=\\w \\$ ";
1966#else
1967 if (!geteuid())
1968 vps1.text = "PS1=# ";
1969#endif
1970 vp = varinit;
Denis Vlasenko80b8b392007-06-25 10:55:35 +00001971 end = vp + ARRAY_SIZE(varinit);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001972 do {
1973 vpp = hashvar(vp->text);
1974 vp->next = *vpp;
1975 *vpp = vp;
1976 } while (++vp < end);
1977}
1978
1979static struct var **
1980findvar(struct var **vpp, const char *name)
1981{
1982 for (; *vpp; vpp = &(*vpp)->next) {
1983 if (varequal((*vpp)->text, name)) {
1984 break;
1985 }
1986 }
1987 return vpp;
1988}
1989
1990/*
1991 * Find the value of a variable. Returns NULL if not set.
1992 */
Mike Frysinger98c52642009-04-02 10:02:37 +00001993static const char *
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001994lookupvar(const char *name)
1995{
1996 struct var *v;
1997
1998 v = *findvar(hashvar(name), name);
1999 if (v) {
Denis Vlasenko448d30e2008-06-27 00:24:11 +00002000#if ENABLE_ASH_RANDOM_SUPPORT
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002001 /*
2002 * Dynamic variables are implemented roughly the same way they are
2003 * in bash. Namely, they're "special" so long as they aren't unset.
2004 * As soon as they're unset, they're no longer dynamic, and dynamic
2005 * lookup will no longer happen at that point. -- PFM.
2006 */
2007 if ((v->flags & VDYNAMIC))
2008 (*v->func)(NULL);
2009#endif
2010 if (!(v->flags & VUNSET))
2011 return strchrnul(v->text, '=') + 1;
2012 }
2013 return NULL;
2014}
2015
2016/*
2017 * Search the environment of a builtin command.
2018 */
Mike Frysinger98c52642009-04-02 10:02:37 +00002019static const char *
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002020bltinlookup(const char *name)
2021{
2022 struct strlist *sp;
2023
2024 for (sp = cmdenviron; sp; sp = sp->next) {
2025 if (varequal(sp->text, name))
2026 return strchrnul(sp->text, '=') + 1;
2027 }
2028 return lookupvar(name);
2029}
2030
2031/*
2032 * Same as setvar except that the variable and value are passed in
2033 * the first argument as name=value. Since the first argument will
2034 * be actually stored in the table, it should not be a string that
2035 * will go away.
2036 * Called with interrupts off.
2037 */
2038static void
2039setvareq(char *s, int flags)
2040{
2041 struct var *vp, **vpp;
2042
2043 vpp = hashvar(s);
2044 flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
2045 vp = *findvar(vpp, s);
2046 if (vp) {
2047 if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
2048 const char *n;
2049
2050 if (flags & VNOSAVE)
2051 free(s);
2052 n = vp->text;
2053 ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
2054 }
2055
2056 if (flags & VNOSET)
2057 return;
2058
2059 if (vp->func && (flags & VNOFUNC) == 0)
2060 (*vp->func)(strchrnul(s, '=') + 1);
2061
2062 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
2063 free((char*)vp->text);
2064
2065 flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
2066 } else {
2067 if (flags & VNOSET)
2068 return;
2069 /* not found */
Denis Vlasenko597906c2008-02-20 16:38:54 +00002070 vp = ckzalloc(sizeof(*vp));
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002071 vp->next = *vpp;
Denis Vlasenko597906c2008-02-20 16:38:54 +00002072 /*vp->func = NULL; - ckzalloc did it */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002073 *vpp = vp;
2074 }
2075 if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
2076 s = ckstrdup(s);
2077 vp->text = s;
2078 vp->flags = flags;
2079}
2080
2081/*
2082 * Set the value of a variable. The flags argument is ored with the
2083 * flags of the variable. If val is NULL, the variable is unset.
2084 */
2085static void
2086setvar(const char *name, const char *val, int flags)
2087{
2088 char *p, *q;
2089 size_t namelen;
2090 char *nameeq;
2091 size_t vallen;
2092
2093 q = endofname(name);
2094 p = strchrnul(q, '=');
2095 namelen = p - name;
2096 if (!namelen || p != q)
2097 ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
2098 vallen = 0;
2099 if (val == NULL) {
2100 flags |= VUNSET;
2101 } else {
2102 vallen = strlen(val);
2103 }
2104 INT_OFF;
2105 nameeq = ckmalloc(namelen + vallen + 2);
Denis Vlasenko29eb3592008-05-18 14:06:08 +00002106 p = (char *)memcpy(nameeq, name, namelen) + namelen;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002107 if (val) {
2108 *p++ = '=';
Denis Vlasenko29eb3592008-05-18 14:06:08 +00002109 p = (char *)memcpy(p, val, vallen) + vallen;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002110 }
2111 *p = '\0';
2112 setvareq(nameeq, flags | VNOSAVE);
2113 INT_ON;
2114}
2115
2116#if ENABLE_ASH_GETOPTS
2117/*
2118 * Safe version of setvar, returns 1 on success 0 on failure.
2119 */
2120static int
2121setvarsafe(const char *name, const char *val, int flags)
2122{
2123 int err;
2124 volatile int saveint;
2125 struct jmploc *volatile savehandler = exception_handler;
2126 struct jmploc jmploc;
2127
2128 SAVE_INT(saveint);
2129 if (setjmp(jmploc.loc))
2130 err = 1;
2131 else {
2132 exception_handler = &jmploc;
2133 setvar(name, val, flags);
2134 err = 0;
2135 }
2136 exception_handler = savehandler;
2137 RESTORE_INT(saveint);
2138 return err;
2139}
2140#endif
2141
2142/*
2143 * Unset the specified variable.
2144 */
2145static int
2146unsetvar(const char *s)
2147{
2148 struct var **vpp;
2149 struct var *vp;
2150 int retval;
2151
2152 vpp = findvar(hashvar(s), s);
2153 vp = *vpp;
2154 retval = 2;
2155 if (vp) {
2156 int flags = vp->flags;
2157
2158 retval = 1;
2159 if (flags & VREADONLY)
2160 goto out;
Denis Vlasenko448d30e2008-06-27 00:24:11 +00002161#if ENABLE_ASH_RANDOM_SUPPORT
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002162 vp->flags &= ~VDYNAMIC;
2163#endif
2164 if (flags & VUNSET)
2165 goto ok;
2166 if ((flags & VSTRFIXED) == 0) {
2167 INT_OFF;
2168 if ((flags & (VTEXTFIXED|VSTACK)) == 0)
2169 free((char*)vp->text);
2170 *vpp = vp->next;
2171 free(vp);
2172 INT_ON;
2173 } else {
2174 setvar(s, 0, 0);
2175 vp->flags &= ~VEXPORT;
2176 }
2177 ok:
2178 retval = 0;
2179 }
2180 out:
2181 return retval;
2182}
2183
2184/*
2185 * Process a linked list of variable assignments.
2186 */
2187static void
2188listsetvar(struct strlist *list_set_var, int flags)
2189{
2190 struct strlist *lp = list_set_var;
2191
2192 if (!lp)
2193 return;
2194 INT_OFF;
2195 do {
2196 setvareq(lp->text, flags);
Denis Vlasenko9650f362007-02-23 01:04:37 +00002197 lp = lp->next;
2198 } while (lp);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002199 INT_ON;
2200}
2201
2202/*
2203 * Generate a list of variables satisfying the given conditions.
2204 */
2205static char **
2206listvars(int on, int off, char ***end)
2207{
2208 struct var **vpp;
2209 struct var *vp;
2210 char **ep;
2211 int mask;
2212
2213 STARTSTACKSTR(ep);
2214 vpp = vartab;
2215 mask = on | off;
2216 do {
2217 for (vp = *vpp; vp; vp = vp->next) {
2218 if ((vp->flags & mask) == on) {
2219 if (ep == stackstrend())
2220 ep = growstackstr();
2221 *ep++ = (char *) vp->text;
2222 }
2223 }
2224 } while (++vpp < vartab + VTABSIZE);
2225 if (ep == stackstrend())
2226 ep = growstackstr();
2227 if (end)
2228 *end = ep;
2229 *ep++ = NULL;
2230 return grabstackstr(ep);
2231}
2232
2233
2234/* ============ Path search helper
2235 *
2236 * The variable path (passed by reference) should be set to the start
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02002237 * of the path before the first call; path_advance will update
2238 * this value as it proceeds. Successive calls to path_advance will return
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002239 * the possible path expansions in sequence. If an option (indicated by
2240 * a percent sign) appears in the path entry then the global variable
2241 * pathopt will be set to point to it; otherwise pathopt will be set to
2242 * NULL.
2243 */
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02002244static const char *pathopt; /* set by path_advance */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002245
2246static char *
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02002247path_advance(const char **path, const char *name)
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002248{
2249 const char *p;
2250 char *q;
2251 const char *start;
2252 size_t len;
2253
2254 if (*path == NULL)
2255 return NULL;
2256 start = *path;
Denis Vlasenkof7d56652008-03-25 05:51:41 +00002257 for (p = start; *p && *p != ':' && *p != '%'; p++)
2258 continue;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002259 len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
2260 while (stackblocksize() < len)
2261 growstackblock();
2262 q = stackblock();
2263 if (p != start) {
2264 memcpy(q, start, p - start);
2265 q += p - start;
2266 *q++ = '/';
2267 }
2268 strcpy(q, name);
2269 pathopt = NULL;
2270 if (*p == '%') {
2271 pathopt = ++p;
Denis Vlasenkof7d56652008-03-25 05:51:41 +00002272 while (*p && *p != ':')
2273 p++;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002274 }
2275 if (*p == ':')
2276 *path = p + 1;
2277 else
2278 *path = NULL;
2279 return stalloc(len);
2280}
2281
2282
2283/* ============ Prompt */
2284
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +00002285static smallint doprompt; /* if set, prompt the user */
2286static smallint needprompt; /* true if interactive and at start of line */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002287
2288#if ENABLE_FEATURE_EDITING
2289static line_input_t *line_input_state;
2290static const char *cmdedit_prompt;
2291static void
2292putprompt(const char *s)
2293{
2294 if (ENABLE_ASH_EXPAND_PRMT) {
2295 free((char*)cmdedit_prompt);
Denis Vlasenko4222ae42007-02-25 02:37:49 +00002296 cmdedit_prompt = ckstrdup(s);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002297 return;
2298 }
2299 cmdedit_prompt = s;
2300}
2301#else
2302static void
2303putprompt(const char *s)
2304{
2305 out2str(s);
2306}
2307#endif
2308
2309#if ENABLE_ASH_EXPAND_PRMT
2310/* expandstr() needs parsing machinery, so it is far away ahead... */
2311static const char *expandstr(const char *ps);
2312#else
2313#define expandstr(s) s
2314#endif
2315
2316static void
2317setprompt(int whichprompt)
2318{
2319 const char *prompt;
2320#if ENABLE_ASH_EXPAND_PRMT
2321 struct stackmark smark;
2322#endif
2323
2324 needprompt = 0;
2325
2326 switch (whichprompt) {
2327 case 1:
2328 prompt = ps1val();
2329 break;
2330 case 2:
2331 prompt = ps2val();
2332 break;
2333 default: /* 0 */
2334 prompt = nullstr;
2335 }
2336#if ENABLE_ASH_EXPAND_PRMT
2337 setstackmark(&smark);
2338 stalloc(stackblocksize());
2339#endif
2340 putprompt(expandstr(prompt));
2341#if ENABLE_ASH_EXPAND_PRMT
2342 popstackmark(&smark);
2343#endif
2344}
2345
2346
2347/* ============ The cd and pwd commands */
2348
2349#define CD_PHYSICAL 1
2350#define CD_PRINT 2
2351
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002352static int
2353cdopt(void)
2354{
2355 int flags = 0;
2356 int i, j;
2357
2358 j = 'L';
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02002359 while ((i = nextopt("LP")) != '\0') {
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002360 if (i != j) {
2361 flags ^= CD_PHYSICAL;
2362 j = i;
2363 }
2364 }
2365
2366 return flags;
2367}
2368
2369/*
2370 * Update curdir (the name of the current directory) in response to a
2371 * cd command.
2372 */
2373static const char *
2374updatepwd(const char *dir)
2375{
2376 char *new;
2377 char *p;
2378 char *cdcomppath;
2379 const char *lim;
2380
2381 cdcomppath = ststrdup(dir);
2382 STARTSTACKSTR(new);
2383 if (*dir != '/') {
2384 if (curdir == nullstr)
2385 return 0;
2386 new = stack_putstr(curdir, new);
2387 }
2388 new = makestrspace(strlen(dir) + 2, new);
Denis Vlasenko29eb3592008-05-18 14:06:08 +00002389 lim = (char *)stackblock() + 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002390 if (*dir != '/') {
2391 if (new[-1] != '/')
2392 USTPUTC('/', new);
2393 if (new > lim && *lim == '/')
2394 lim++;
2395 } else {
2396 USTPUTC('/', new);
2397 cdcomppath++;
2398 if (dir[1] == '/' && dir[2] != '/') {
2399 USTPUTC('/', new);
2400 cdcomppath++;
2401 lim++;
2402 }
2403 }
2404 p = strtok(cdcomppath, "/");
2405 while (p) {
2406 switch (*p) {
2407 case '.':
2408 if (p[1] == '.' && p[2] == '\0') {
2409 while (new > lim) {
2410 STUNPUTC(new);
2411 if (new[-1] == '/')
2412 break;
2413 }
2414 break;
Denis Vlasenko16abcd92007-04-13 23:59:52 +00002415 }
2416 if (p[1] == '\0')
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002417 break;
2418 /* fall through */
2419 default:
2420 new = stack_putstr(p, new);
2421 USTPUTC('/', new);
2422 }
2423 p = strtok(0, "/");
2424 }
2425 if (new > lim)
2426 STUNPUTC(new);
2427 *new = 0;
2428 return stackblock();
2429}
2430
2431/*
2432 * Find out what the current directory is. If we already know the current
2433 * directory, this routine returns immediately.
2434 */
2435static char *
2436getpwd(void)
2437{
Denis Vlasenko01631112007-12-16 17:20:38 +00002438 char *dir = getcwd(NULL, 0); /* huh, using glibc extension? */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002439 return dir ? dir : nullstr;
2440}
2441
2442static void
2443setpwd(const char *val, int setold)
2444{
2445 char *oldcur, *dir;
2446
2447 oldcur = dir = curdir;
2448
2449 if (setold) {
2450 setvar("OLDPWD", oldcur, VEXPORT);
2451 }
2452 INT_OFF;
2453 if (physdir != nullstr) {
2454 if (physdir != oldcur)
2455 free(physdir);
2456 physdir = nullstr;
2457 }
2458 if (oldcur == val || !val) {
2459 char *s = getpwd();
2460 physdir = s;
2461 if (!val)
2462 dir = s;
2463 } else
2464 dir = ckstrdup(val);
2465 if (oldcur != dir && oldcur != nullstr) {
2466 free(oldcur);
2467 }
2468 curdir = dir;
2469 INT_ON;
2470 setvar("PWD", dir, VEXPORT);
2471}
2472
2473static void hashcd(void);
2474
2475/*
2476 * Actually do the chdir. We also call hashcd to let the routines in exec.c
2477 * know that the current directory has changed.
2478 */
2479static int
2480docd(const char *dest, int flags)
2481{
2482 const char *dir = 0;
2483 int err;
2484
2485 TRACE(("docd(\"%s\", %d) called\n", dest, flags));
2486
2487 INT_OFF;
2488 if (!(flags & CD_PHYSICAL)) {
2489 dir = updatepwd(dest);
2490 if (dir)
2491 dest = dir;
2492 }
2493 err = chdir(dest);
2494 if (err)
2495 goto out;
2496 setpwd(dir, 1);
2497 hashcd();
2498 out:
2499 INT_ON;
2500 return err;
2501}
2502
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02002503static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00002504cdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002505{
2506 const char *dest;
2507 const char *path;
2508 const char *p;
2509 char c;
2510 struct stat statb;
2511 int flags;
2512
2513 flags = cdopt();
2514 dest = *argptr;
2515 if (!dest)
2516 dest = bltinlookup(homestr);
2517 else if (LONE_DASH(dest)) {
2518 dest = bltinlookup("OLDPWD");
2519 flags |= CD_PRINT;
2520 }
2521 if (!dest)
2522 dest = nullstr;
2523 if (*dest == '/')
2524 goto step7;
2525 if (*dest == '.') {
2526 c = dest[1];
2527 dotdot:
2528 switch (c) {
2529 case '\0':
2530 case '/':
2531 goto step6;
2532 case '.':
2533 c = dest[2];
2534 if (c != '.')
2535 goto dotdot;
2536 }
2537 }
2538 if (!*dest)
2539 dest = ".";
2540 path = bltinlookup("CDPATH");
2541 if (!path) {
2542 step6:
2543 step7:
2544 p = dest;
2545 goto docd;
2546 }
2547 do {
2548 c = *path;
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02002549 p = path_advance(&path, dest);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002550 if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
2551 if (c && c != ':')
2552 flags |= CD_PRINT;
2553 docd:
2554 if (!docd(p, flags))
2555 goto out;
2556 break;
2557 }
2558 } while (path);
2559 ash_msg_and_raise_error("can't cd to %s", dest);
2560 /* NOTREACHED */
2561 out:
2562 if (flags & CD_PRINT)
2563 out1fmt(snlfmt, curdir);
2564 return 0;
2565}
2566
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02002567static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00002568pwdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002569{
2570 int flags;
2571 const char *dir = curdir;
2572
2573 flags = cdopt();
2574 if (flags) {
2575 if (physdir == nullstr)
2576 setpwd(dir, 0);
2577 dir = physdir;
2578 }
2579 out1fmt(snlfmt, dir);
2580 return 0;
2581}
2582
Denis Vlasenko0c032a42007-02-23 01:03:40 +00002583
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00002584/* ============ ... */
Eric Andersenc470f442003-07-28 09:56:35 +00002585
Denis Vlasenko834dee72008-10-07 09:18:30 +00002586
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +00002587#define IBUFSIZ COMMON_BUFSIZE
Denis Vlasenko834dee72008-10-07 09:18:30 +00002588/* buffer for top level input file */
2589#define basebuf bb_common_bufsiz1
Eric Andersenc470f442003-07-28 09:56:35 +00002590
Eric Andersenc470f442003-07-28 09:56:35 +00002591/* Syntax classes */
Denis Vlasenko834dee72008-10-07 09:18:30 +00002592#define CWORD 0 /* character is nothing special */
2593#define CNL 1 /* newline character */
2594#define CBACK 2 /* a backslash character */
2595#define CSQUOTE 3 /* single quote */
2596#define CDQUOTE 4 /* double quote */
Eric Andersenc470f442003-07-28 09:56:35 +00002597#define CENDQUOTE 5 /* a terminating quote */
Denis Vlasenko834dee72008-10-07 09:18:30 +00002598#define CBQUOTE 6 /* backwards single quote */
2599#define CVAR 7 /* a dollar sign */
2600#define CENDVAR 8 /* a '}' character */
2601#define CLP 9 /* a left paren in arithmetic */
2602#define CRP 10 /* a right paren in arithmetic */
Eric Andersenc470f442003-07-28 09:56:35 +00002603#define CENDFILE 11 /* end of file */
Denis Vlasenko834dee72008-10-07 09:18:30 +00002604#define CCTL 12 /* like CWORD, except it must be escaped */
2605#define CSPCL 13 /* these terminate a word */
2606#define CIGN 14 /* character should be ignored */
Eric Andersenc470f442003-07-28 09:56:35 +00002607
Denis Vlasenko131ae172007-02-18 13:00:19 +00002608#if ENABLE_ASH_ALIAS
Denis Vlasenko834dee72008-10-07 09:18:30 +00002609#define SYNBASE 130
2610#define PEOF -130
2611#define PEOA -129
Eric Andersenc470f442003-07-28 09:56:35 +00002612#define PEOA_OR_PEOF PEOA
2613#else
Denis Vlasenko834dee72008-10-07 09:18:30 +00002614#define SYNBASE 129
2615#define PEOF -129
Eric Andersenc470f442003-07-28 09:56:35 +00002616#define PEOA_OR_PEOF PEOF
2617#endif
2618
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00002619/* number syntax index */
2620#define BASESYNTAX 0 /* not in quotes */
2621#define DQSYNTAX 1 /* in double quotes */
2622#define SQSYNTAX 2 /* in single quotes */
2623#define ARISYNTAX 3 /* in arithmetic */
Denis Vlasenko46a53062007-09-24 18:30:02 +00002624#define PSSYNTAX 4 /* prompt */
Eric Andersenc470f442003-07-28 09:56:35 +00002625
Denis Vlasenko131ae172007-02-18 13:00:19 +00002626#if ENABLE_ASH_OPTIMIZE_FOR_SIZE
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002627#define USE_SIT_FUNCTION
2628#endif
2629
Mike Frysinger98c52642009-04-02 10:02:37 +00002630#if ENABLE_SH_MATH_SUPPORT
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002631static const char S_I_T[][4] = {
Denis Vlasenko131ae172007-02-18 13:00:19 +00002632#if ENABLE_ASH_ALIAS
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00002633 { CSPCL, CIGN, CIGN, CIGN }, /* 0, PEOA */
Eric Andersenc470f442003-07-28 09:56:35 +00002634#endif
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00002635 { CSPCL, CWORD, CWORD, CWORD }, /* 1, ' ' */
2636 { CNL, CNL, CNL, CNL }, /* 2, \n */
2637 { CWORD, CCTL, CCTL, CWORD }, /* 3, !*-/:=?[]~ */
2638 { CDQUOTE, CENDQUOTE, CWORD, CWORD }, /* 4, '"' */
2639 { CVAR, CVAR, CWORD, CVAR }, /* 5, $ */
2640 { CSQUOTE, CWORD, CENDQUOTE, CWORD }, /* 6, "'" */
2641 { CSPCL, CWORD, CWORD, CLP }, /* 7, ( */
2642 { CSPCL, CWORD, CWORD, CRP }, /* 8, ) */
2643 { CBACK, CBACK, CCTL, CBACK }, /* 9, \ */
2644 { CBQUOTE, CBQUOTE, CWORD, CBQUOTE }, /* 10, ` */
2645 { CENDVAR, CENDVAR, CWORD, CENDVAR }, /* 11, } */
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002646#ifndef USE_SIT_FUNCTION
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00002647 { CENDFILE, CENDFILE, CENDFILE, CENDFILE }, /* 12, PEOF */
2648 { CWORD, CWORD, CWORD, CWORD }, /* 13, 0-9A-Za-z */
2649 { CCTL, CCTL, CCTL, CCTL } /* 14, CTLESC ... */
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002650#endif
Eric Andersen2870d962001-07-02 17:27:21 +00002651};
Eric Andersenc470f442003-07-28 09:56:35 +00002652#else
2653static const char S_I_T[][3] = {
Denis Vlasenko131ae172007-02-18 13:00:19 +00002654#if ENABLE_ASH_ALIAS
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00002655 { CSPCL, CIGN, CIGN }, /* 0, PEOA */
Eric Andersenc470f442003-07-28 09:56:35 +00002656#endif
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00002657 { CSPCL, CWORD, CWORD }, /* 1, ' ' */
2658 { CNL, CNL, CNL }, /* 2, \n */
2659 { CWORD, CCTL, CCTL }, /* 3, !*-/:=?[]~ */
2660 { CDQUOTE, CENDQUOTE, CWORD }, /* 4, '"' */
2661 { CVAR, CVAR, CWORD }, /* 5, $ */
2662 { CSQUOTE, CWORD, CENDQUOTE }, /* 6, "'" */
2663 { CSPCL, CWORD, CWORD }, /* 7, ( */
2664 { CSPCL, CWORD, CWORD }, /* 8, ) */
2665 { CBACK, CBACK, CCTL }, /* 9, \ */
2666 { CBQUOTE, CBQUOTE, CWORD }, /* 10, ` */
2667 { CENDVAR, CENDVAR, CWORD }, /* 11, } */
Eric Andersenc470f442003-07-28 09:56:35 +00002668#ifndef USE_SIT_FUNCTION
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00002669 { CENDFILE, CENDFILE, CENDFILE }, /* 12, PEOF */
2670 { CWORD, CWORD, CWORD }, /* 13, 0-9A-Za-z */
2671 { CCTL, CCTL, CCTL } /* 14, CTLESC ... */
Eric Andersenc470f442003-07-28 09:56:35 +00002672#endif
2673};
Mike Frysinger98c52642009-04-02 10:02:37 +00002674#endif /* SH_MATH_SUPPORT */
Eric Andersen2870d962001-07-02 17:27:21 +00002675
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002676#ifdef USE_SIT_FUNCTION
2677
Denis Vlasenko0c032a42007-02-23 01:03:40 +00002678static int
2679SIT(int c, int syntax)
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002680{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00002681 static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-/:;<=>?[\\]`|}~";
Denis Vlasenko131ae172007-02-18 13:00:19 +00002682#if ENABLE_ASH_ALIAS
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00002683 static const char syntax_index_table[] ALIGN1 = {
Eric Andersenc470f442003-07-28 09:56:35 +00002684 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
2685 7, 8, 3, 3, 3, 3, 1, 1, /* "()*-/:;<" */
2686 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
2687 11, 3 /* "}~" */
2688 };
2689#else
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00002690 static const char syntax_index_table[] ALIGN1 = {
Eric Andersenc470f442003-07-28 09:56:35 +00002691 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
2692 6, 7, 2, 2, 2, 2, 0, 0, /* "()*-/:;<" */
2693 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
2694 10, 2 /* "}~" */
2695 };
2696#endif
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002697 const char *s;
2698 int indx;
2699
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +00002700 if (c == PEOF) { /* 2^8+2 */
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002701 return CENDFILE;
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002702 }
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +00002703#if ENABLE_ASH_ALIAS
2704 if (c == PEOA) { /* 2^8+1 */
2705 indx = 0;
2706 } else
2707#endif
2708 {
Denys Vlasenkob0d63382009-09-16 16:18:32 +02002709 if ((unsigned char)c >= CTLESC
2710 && (unsigned char)c <= CTLQUOTEMARK
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +00002711 ) {
2712 return CCTL;
2713 }
2714 s = strchrnul(spec_symbls, c);
2715 if (*s == '\0') {
2716 return CWORD;
2717 }
2718 indx = syntax_index_table[s - spec_symbls];
2719 }
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002720 return S_I_T[indx][syntax];
2721}
2722
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00002723#else /* !USE_SIT_FUNCTION */
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002724
Denis Vlasenko131ae172007-02-18 13:00:19 +00002725#if ENABLE_ASH_ALIAS
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00002726#define CSPCL_CIGN_CIGN_CIGN 0
2727#define CSPCL_CWORD_CWORD_CWORD 1
2728#define CNL_CNL_CNL_CNL 2
2729#define CWORD_CCTL_CCTL_CWORD 3
2730#define CDQUOTE_CENDQUOTE_CWORD_CWORD 4
2731#define CVAR_CVAR_CWORD_CVAR 5
2732#define CSQUOTE_CWORD_CENDQUOTE_CWORD 6
2733#define CSPCL_CWORD_CWORD_CLP 7
2734#define CSPCL_CWORD_CWORD_CRP 8
2735#define CBACK_CBACK_CCTL_CBACK 9
2736#define CBQUOTE_CBQUOTE_CWORD_CBQUOTE 10
2737#define CENDVAR_CENDVAR_CWORD_CENDVAR 11
2738#define CENDFILE_CENDFILE_CENDFILE_CENDFILE 12
2739#define CWORD_CWORD_CWORD_CWORD 13
2740#define CCTL_CCTL_CCTL_CCTL 14
Eric Andersenc470f442003-07-28 09:56:35 +00002741#else
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00002742#define CSPCL_CWORD_CWORD_CWORD 0
2743#define CNL_CNL_CNL_CNL 1
2744#define CWORD_CCTL_CCTL_CWORD 2
2745#define CDQUOTE_CENDQUOTE_CWORD_CWORD 3
2746#define CVAR_CVAR_CWORD_CVAR 4
2747#define CSQUOTE_CWORD_CENDQUOTE_CWORD 5
2748#define CSPCL_CWORD_CWORD_CLP 6
2749#define CSPCL_CWORD_CWORD_CRP 7
2750#define CBACK_CBACK_CCTL_CBACK 8
2751#define CBQUOTE_CBQUOTE_CWORD_CBQUOTE 9
2752#define CENDVAR_CENDVAR_CWORD_CENDVAR 10
2753#define CENDFILE_CENDFILE_CENDFILE_CENDFILE 11
2754#define CWORD_CWORD_CWORD_CWORD 12
2755#define CCTL_CCTL_CCTL_CCTL 13
Eric Andersenc470f442003-07-28 09:56:35 +00002756#endif
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002757
2758static const char syntax_index_table[258] = {
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00002759 /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
Eric Andersenc470f442003-07-28 09:56:35 +00002760 /* 0 PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
Denis Vlasenko131ae172007-02-18 13:00:19 +00002761#if ENABLE_ASH_ALIAS
Eric Andersenc470f442003-07-28 09:56:35 +00002762 /* 1 PEOA */ CSPCL_CIGN_CIGN_CIGN,
2763#endif
2764 /* 2 -128 0x80 */ CWORD_CWORD_CWORD_CWORD,
2765 /* 3 -127 CTLESC */ CCTL_CCTL_CCTL_CCTL,
2766 /* 4 -126 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
2767 /* 5 -125 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
2768 /* 6 -124 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
2769 /* 7 -123 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
2770 /* 8 -122 CTLARI */ CCTL_CCTL_CCTL_CCTL,
2771 /* 9 -121 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
2772 /* 10 -120 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00002773 /* 11 -119 */ CWORD_CWORD_CWORD_CWORD,
2774 /* 12 -118 */ CWORD_CWORD_CWORD_CWORD,
2775 /* 13 -117 */ CWORD_CWORD_CWORD_CWORD,
2776 /* 14 -116 */ CWORD_CWORD_CWORD_CWORD,
2777 /* 15 -115 */ CWORD_CWORD_CWORD_CWORD,
2778 /* 16 -114 */ CWORD_CWORD_CWORD_CWORD,
2779 /* 17 -113 */ CWORD_CWORD_CWORD_CWORD,
2780 /* 18 -112 */ CWORD_CWORD_CWORD_CWORD,
2781 /* 19 -111 */ CWORD_CWORD_CWORD_CWORD,
2782 /* 20 -110 */ CWORD_CWORD_CWORD_CWORD,
2783 /* 21 -109 */ CWORD_CWORD_CWORD_CWORD,
2784 /* 22 -108 */ CWORD_CWORD_CWORD_CWORD,
2785 /* 23 -107 */ CWORD_CWORD_CWORD_CWORD,
2786 /* 24 -106 */ CWORD_CWORD_CWORD_CWORD,
2787 /* 25 -105 */ CWORD_CWORD_CWORD_CWORD,
2788 /* 26 -104 */ CWORD_CWORD_CWORD_CWORD,
2789 /* 27 -103 */ CWORD_CWORD_CWORD_CWORD,
2790 /* 28 -102 */ CWORD_CWORD_CWORD_CWORD,
2791 /* 29 -101 */ CWORD_CWORD_CWORD_CWORD,
2792 /* 30 -100 */ CWORD_CWORD_CWORD_CWORD,
2793 /* 31 -99 */ CWORD_CWORD_CWORD_CWORD,
2794 /* 32 -98 */ CWORD_CWORD_CWORD_CWORD,
2795 /* 33 -97 */ CWORD_CWORD_CWORD_CWORD,
2796 /* 34 -96 */ CWORD_CWORD_CWORD_CWORD,
2797 /* 35 -95 */ CWORD_CWORD_CWORD_CWORD,
2798 /* 36 -94 */ CWORD_CWORD_CWORD_CWORD,
2799 /* 37 -93 */ CWORD_CWORD_CWORD_CWORD,
2800 /* 38 -92 */ CWORD_CWORD_CWORD_CWORD,
2801 /* 39 -91 */ CWORD_CWORD_CWORD_CWORD,
2802 /* 40 -90 */ CWORD_CWORD_CWORD_CWORD,
2803 /* 41 -89 */ CWORD_CWORD_CWORD_CWORD,
2804 /* 42 -88 */ CWORD_CWORD_CWORD_CWORD,
2805 /* 43 -87 */ CWORD_CWORD_CWORD_CWORD,
2806 /* 44 -86 */ CWORD_CWORD_CWORD_CWORD,
2807 /* 45 -85 */ CWORD_CWORD_CWORD_CWORD,
2808 /* 46 -84 */ CWORD_CWORD_CWORD_CWORD,
2809 /* 47 -83 */ CWORD_CWORD_CWORD_CWORD,
2810 /* 48 -82 */ CWORD_CWORD_CWORD_CWORD,
2811 /* 49 -81 */ CWORD_CWORD_CWORD_CWORD,
2812 /* 50 -80 */ CWORD_CWORD_CWORD_CWORD,
2813 /* 51 -79 */ CWORD_CWORD_CWORD_CWORD,
2814 /* 52 -78 */ CWORD_CWORD_CWORD_CWORD,
2815 /* 53 -77 */ CWORD_CWORD_CWORD_CWORD,
2816 /* 54 -76 */ CWORD_CWORD_CWORD_CWORD,
2817 /* 55 -75 */ CWORD_CWORD_CWORD_CWORD,
2818 /* 56 -74 */ CWORD_CWORD_CWORD_CWORD,
2819 /* 57 -73 */ CWORD_CWORD_CWORD_CWORD,
2820 /* 58 -72 */ CWORD_CWORD_CWORD_CWORD,
2821 /* 59 -71 */ CWORD_CWORD_CWORD_CWORD,
2822 /* 60 -70 */ CWORD_CWORD_CWORD_CWORD,
2823 /* 61 -69 */ CWORD_CWORD_CWORD_CWORD,
2824 /* 62 -68 */ CWORD_CWORD_CWORD_CWORD,
2825 /* 63 -67 */ CWORD_CWORD_CWORD_CWORD,
2826 /* 64 -66 */ CWORD_CWORD_CWORD_CWORD,
2827 /* 65 -65 */ CWORD_CWORD_CWORD_CWORD,
2828 /* 66 -64 */ CWORD_CWORD_CWORD_CWORD,
2829 /* 67 -63 */ CWORD_CWORD_CWORD_CWORD,
2830 /* 68 -62 */ CWORD_CWORD_CWORD_CWORD,
2831 /* 69 -61 */ CWORD_CWORD_CWORD_CWORD,
2832 /* 70 -60 */ CWORD_CWORD_CWORD_CWORD,
2833 /* 71 -59 */ CWORD_CWORD_CWORD_CWORD,
2834 /* 72 -58 */ CWORD_CWORD_CWORD_CWORD,
2835 /* 73 -57 */ CWORD_CWORD_CWORD_CWORD,
2836 /* 74 -56 */ CWORD_CWORD_CWORD_CWORD,
2837 /* 75 -55 */ CWORD_CWORD_CWORD_CWORD,
2838 /* 76 -54 */ CWORD_CWORD_CWORD_CWORD,
2839 /* 77 -53 */ CWORD_CWORD_CWORD_CWORD,
2840 /* 78 -52 */ CWORD_CWORD_CWORD_CWORD,
2841 /* 79 -51 */ CWORD_CWORD_CWORD_CWORD,
2842 /* 80 -50 */ CWORD_CWORD_CWORD_CWORD,
2843 /* 81 -49 */ CWORD_CWORD_CWORD_CWORD,
2844 /* 82 -48 */ CWORD_CWORD_CWORD_CWORD,
2845 /* 83 -47 */ CWORD_CWORD_CWORD_CWORD,
2846 /* 84 -46 */ CWORD_CWORD_CWORD_CWORD,
2847 /* 85 -45 */ CWORD_CWORD_CWORD_CWORD,
2848 /* 86 -44 */ CWORD_CWORD_CWORD_CWORD,
2849 /* 87 -43 */ CWORD_CWORD_CWORD_CWORD,
2850 /* 88 -42 */ CWORD_CWORD_CWORD_CWORD,
2851 /* 89 -41 */ CWORD_CWORD_CWORD_CWORD,
2852 /* 90 -40 */ CWORD_CWORD_CWORD_CWORD,
2853 /* 91 -39 */ CWORD_CWORD_CWORD_CWORD,
2854 /* 92 -38 */ CWORD_CWORD_CWORD_CWORD,
2855 /* 93 -37 */ CWORD_CWORD_CWORD_CWORD,
2856 /* 94 -36 */ CWORD_CWORD_CWORD_CWORD,
2857 /* 95 -35 */ CWORD_CWORD_CWORD_CWORD,
2858 /* 96 -34 */ CWORD_CWORD_CWORD_CWORD,
2859 /* 97 -33 */ CWORD_CWORD_CWORD_CWORD,
2860 /* 98 -32 */ CWORD_CWORD_CWORD_CWORD,
2861 /* 99 -31 */ CWORD_CWORD_CWORD_CWORD,
2862 /* 100 -30 */ CWORD_CWORD_CWORD_CWORD,
2863 /* 101 -29 */ CWORD_CWORD_CWORD_CWORD,
2864 /* 102 -28 */ CWORD_CWORD_CWORD_CWORD,
2865 /* 103 -27 */ CWORD_CWORD_CWORD_CWORD,
2866 /* 104 -26 */ CWORD_CWORD_CWORD_CWORD,
2867 /* 105 -25 */ CWORD_CWORD_CWORD_CWORD,
2868 /* 106 -24 */ CWORD_CWORD_CWORD_CWORD,
2869 /* 107 -23 */ CWORD_CWORD_CWORD_CWORD,
2870 /* 108 -22 */ CWORD_CWORD_CWORD_CWORD,
2871 /* 109 -21 */ CWORD_CWORD_CWORD_CWORD,
2872 /* 110 -20 */ CWORD_CWORD_CWORD_CWORD,
2873 /* 111 -19 */ CWORD_CWORD_CWORD_CWORD,
2874 /* 112 -18 */ CWORD_CWORD_CWORD_CWORD,
2875 /* 113 -17 */ CWORD_CWORD_CWORD_CWORD,
2876 /* 114 -16 */ CWORD_CWORD_CWORD_CWORD,
2877 /* 115 -15 */ CWORD_CWORD_CWORD_CWORD,
2878 /* 116 -14 */ CWORD_CWORD_CWORD_CWORD,
2879 /* 117 -13 */ CWORD_CWORD_CWORD_CWORD,
2880 /* 118 -12 */ CWORD_CWORD_CWORD_CWORD,
2881 /* 119 -11 */ CWORD_CWORD_CWORD_CWORD,
2882 /* 120 -10 */ CWORD_CWORD_CWORD_CWORD,
2883 /* 121 -9 */ CWORD_CWORD_CWORD_CWORD,
2884 /* 122 -8 */ CWORD_CWORD_CWORD_CWORD,
2885 /* 123 -7 */ CWORD_CWORD_CWORD_CWORD,
2886 /* 124 -6 */ CWORD_CWORD_CWORD_CWORD,
2887 /* 125 -5 */ CWORD_CWORD_CWORD_CWORD,
2888 /* 126 -4 */ CWORD_CWORD_CWORD_CWORD,
2889 /* 127 -3 */ CWORD_CWORD_CWORD_CWORD,
2890 /* 128 -2 */ CWORD_CWORD_CWORD_CWORD,
2891 /* 129 -1 */ CWORD_CWORD_CWORD_CWORD,
2892 /* 130 0 */ CWORD_CWORD_CWORD_CWORD,
2893 /* 131 1 */ CWORD_CWORD_CWORD_CWORD,
2894 /* 132 2 */ CWORD_CWORD_CWORD_CWORD,
2895 /* 133 3 */ CWORD_CWORD_CWORD_CWORD,
2896 /* 134 4 */ CWORD_CWORD_CWORD_CWORD,
2897 /* 135 5 */ CWORD_CWORD_CWORD_CWORD,
2898 /* 136 6 */ CWORD_CWORD_CWORD_CWORD,
2899 /* 137 7 */ CWORD_CWORD_CWORD_CWORD,
2900 /* 138 8 */ CWORD_CWORD_CWORD_CWORD,
2901 /* 139 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
2902 /* 140 10 "\n" */ CNL_CNL_CNL_CNL,
2903 /* 141 11 */ CWORD_CWORD_CWORD_CWORD,
2904 /* 142 12 */ CWORD_CWORD_CWORD_CWORD,
2905 /* 143 13 */ CWORD_CWORD_CWORD_CWORD,
2906 /* 144 14 */ CWORD_CWORD_CWORD_CWORD,
2907 /* 145 15 */ CWORD_CWORD_CWORD_CWORD,
2908 /* 146 16 */ CWORD_CWORD_CWORD_CWORD,
2909 /* 147 17 */ CWORD_CWORD_CWORD_CWORD,
2910 /* 148 18 */ CWORD_CWORD_CWORD_CWORD,
2911 /* 149 19 */ CWORD_CWORD_CWORD_CWORD,
2912 /* 150 20 */ CWORD_CWORD_CWORD_CWORD,
2913 /* 151 21 */ CWORD_CWORD_CWORD_CWORD,
2914 /* 152 22 */ CWORD_CWORD_CWORD_CWORD,
2915 /* 153 23 */ CWORD_CWORD_CWORD_CWORD,
2916 /* 154 24 */ CWORD_CWORD_CWORD_CWORD,
2917 /* 155 25 */ CWORD_CWORD_CWORD_CWORD,
2918 /* 156 26 */ CWORD_CWORD_CWORD_CWORD,
2919 /* 157 27 */ CWORD_CWORD_CWORD_CWORD,
2920 /* 158 28 */ CWORD_CWORD_CWORD_CWORD,
2921 /* 159 29 */ CWORD_CWORD_CWORD_CWORD,
2922 /* 160 30 */ CWORD_CWORD_CWORD_CWORD,
2923 /* 161 31 */ CWORD_CWORD_CWORD_CWORD,
2924 /* 162 32 " " */ CSPCL_CWORD_CWORD_CWORD,
2925 /* 163 33 "!" */ CWORD_CCTL_CCTL_CWORD,
Eric Andersenc470f442003-07-28 09:56:35 +00002926 /* 164 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00002927 /* 165 35 "#" */ CWORD_CWORD_CWORD_CWORD,
2928 /* 166 36 "$" */ CVAR_CVAR_CWORD_CVAR,
2929 /* 167 37 "%" */ CWORD_CWORD_CWORD_CWORD,
2930 /* 168 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
Eric Andersenc470f442003-07-28 09:56:35 +00002931 /* 169 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00002932 /* 170 40 "(" */ CSPCL_CWORD_CWORD_CLP,
2933 /* 171 41 ")" */ CSPCL_CWORD_CWORD_CRP,
2934 /* 172 42 "*" */ CWORD_CCTL_CCTL_CWORD,
2935 /* 173 43 "+" */ CWORD_CWORD_CWORD_CWORD,
2936 /* 174 44 "," */ CWORD_CWORD_CWORD_CWORD,
2937 /* 175 45 "-" */ CWORD_CCTL_CCTL_CWORD,
2938 /* 176 46 "." */ CWORD_CWORD_CWORD_CWORD,
2939 /* 177 47 "/" */ CWORD_CCTL_CCTL_CWORD,
2940 /* 178 48 "0" */ CWORD_CWORD_CWORD_CWORD,
2941 /* 179 49 "1" */ CWORD_CWORD_CWORD_CWORD,
2942 /* 180 50 "2" */ CWORD_CWORD_CWORD_CWORD,
2943 /* 181 51 "3" */ CWORD_CWORD_CWORD_CWORD,
2944 /* 182 52 "4" */ CWORD_CWORD_CWORD_CWORD,
2945 /* 183 53 "5" */ CWORD_CWORD_CWORD_CWORD,
2946 /* 184 54 "6" */ CWORD_CWORD_CWORD_CWORD,
2947 /* 185 55 "7" */ CWORD_CWORD_CWORD_CWORD,
2948 /* 186 56 "8" */ CWORD_CWORD_CWORD_CWORD,
2949 /* 187 57 "9" */ CWORD_CWORD_CWORD_CWORD,
2950 /* 188 58 ":" */ CWORD_CCTL_CCTL_CWORD,
2951 /* 189 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
2952 /* 190 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
2953 /* 191 61 "=" */ CWORD_CCTL_CCTL_CWORD,
2954 /* 192 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
2955 /* 193 63 "?" */ CWORD_CCTL_CCTL_CWORD,
2956 /* 194 64 "@" */ CWORD_CWORD_CWORD_CWORD,
2957 /* 195 65 "A" */ CWORD_CWORD_CWORD_CWORD,
2958 /* 196 66 "B" */ CWORD_CWORD_CWORD_CWORD,
2959 /* 197 67 "C" */ CWORD_CWORD_CWORD_CWORD,
2960 /* 198 68 "D" */ CWORD_CWORD_CWORD_CWORD,
2961 /* 199 69 "E" */ CWORD_CWORD_CWORD_CWORD,
2962 /* 200 70 "F" */ CWORD_CWORD_CWORD_CWORD,
2963 /* 201 71 "G" */ CWORD_CWORD_CWORD_CWORD,
2964 /* 202 72 "H" */ CWORD_CWORD_CWORD_CWORD,
2965 /* 203 73 "I" */ CWORD_CWORD_CWORD_CWORD,
2966 /* 204 74 "J" */ CWORD_CWORD_CWORD_CWORD,
2967 /* 205 75 "K" */ CWORD_CWORD_CWORD_CWORD,
2968 /* 206 76 "L" */ CWORD_CWORD_CWORD_CWORD,
2969 /* 207 77 "M" */ CWORD_CWORD_CWORD_CWORD,
2970 /* 208 78 "N" */ CWORD_CWORD_CWORD_CWORD,
2971 /* 209 79 "O" */ CWORD_CWORD_CWORD_CWORD,
2972 /* 210 80 "P" */ CWORD_CWORD_CWORD_CWORD,
2973 /* 211 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
2974 /* 212 82 "R" */ CWORD_CWORD_CWORD_CWORD,
2975 /* 213 83 "S" */ CWORD_CWORD_CWORD_CWORD,
2976 /* 214 84 "T" */ CWORD_CWORD_CWORD_CWORD,
2977 /* 215 85 "U" */ CWORD_CWORD_CWORD_CWORD,
2978 /* 216 86 "V" */ CWORD_CWORD_CWORD_CWORD,
2979 /* 217 87 "W" */ CWORD_CWORD_CWORD_CWORD,
2980 /* 218 88 "X" */ CWORD_CWORD_CWORD_CWORD,
2981 /* 219 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
2982 /* 220 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
2983 /* 221 91 "[" */ CWORD_CCTL_CCTL_CWORD,
2984 /* 222 92 "\" */ CBACK_CBACK_CCTL_CBACK,
2985 /* 223 93 "]" */ CWORD_CCTL_CCTL_CWORD,
2986 /* 224 94 "^" */ CWORD_CWORD_CWORD_CWORD,
2987 /* 225 95 "_" */ CWORD_CWORD_CWORD_CWORD,
2988 /* 226 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
2989 /* 227 97 "a" */ CWORD_CWORD_CWORD_CWORD,
2990 /* 228 98 "b" */ CWORD_CWORD_CWORD_CWORD,
2991 /* 229 99 "c" */ CWORD_CWORD_CWORD_CWORD,
2992 /* 230 100 "d" */ CWORD_CWORD_CWORD_CWORD,
2993 /* 231 101 "e" */ CWORD_CWORD_CWORD_CWORD,
2994 /* 232 102 "f" */ CWORD_CWORD_CWORD_CWORD,
2995 /* 233 103 "g" */ CWORD_CWORD_CWORD_CWORD,
2996 /* 234 104 "h" */ CWORD_CWORD_CWORD_CWORD,
2997 /* 235 105 "i" */ CWORD_CWORD_CWORD_CWORD,
2998 /* 236 106 "j" */ CWORD_CWORD_CWORD_CWORD,
2999 /* 237 107 "k" */ CWORD_CWORD_CWORD_CWORD,
3000 /* 238 108 "l" */ CWORD_CWORD_CWORD_CWORD,
3001 /* 239 109 "m" */ CWORD_CWORD_CWORD_CWORD,
3002 /* 240 110 "n" */ CWORD_CWORD_CWORD_CWORD,
3003 /* 241 111 "o" */ CWORD_CWORD_CWORD_CWORD,
3004 /* 242 112 "p" */ CWORD_CWORD_CWORD_CWORD,
3005 /* 243 113 "q" */ CWORD_CWORD_CWORD_CWORD,
3006 /* 244 114 "r" */ CWORD_CWORD_CWORD_CWORD,
3007 /* 245 115 "s" */ CWORD_CWORD_CWORD_CWORD,
3008 /* 246 116 "t" */ CWORD_CWORD_CWORD_CWORD,
3009 /* 247 117 "u" */ CWORD_CWORD_CWORD_CWORD,
3010 /* 248 118 "v" */ CWORD_CWORD_CWORD_CWORD,
3011 /* 249 119 "w" */ CWORD_CWORD_CWORD_CWORD,
3012 /* 250 120 "x" */ CWORD_CWORD_CWORD_CWORD,
3013 /* 251 121 "y" */ CWORD_CWORD_CWORD_CWORD,
3014 /* 252 122 "z" */ CWORD_CWORD_CWORD_CWORD,
3015 /* 253 123 "{" */ CWORD_CWORD_CWORD_CWORD,
3016 /* 254 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
3017 /* 255 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
3018 /* 256 126 "~" */ CWORD_CCTL_CCTL_CWORD,
3019 /* 257 127 */ CWORD_CWORD_CWORD_CWORD,
Eric Andersen2870d962001-07-02 17:27:21 +00003020};
3021
Denis Vlasenko0dfe1d22009-04-02 12:57:38 +00003022#define SIT(c, syntax) (S_I_T[(int)syntax_index_table[(int)(c) + SYNBASE]][syntax])
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00003023
"Vladimir N. Oleynik"fdb871c2006-01-25 11:53:47 +00003024#endif /* USE_SIT_FUNCTION */
Eric Andersenc470f442003-07-28 09:56:35 +00003025
Eric Andersen2870d962001-07-02 17:27:21 +00003026
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00003027/* ============ Alias handling */
Denis Vlasenkofc06f292007-02-23 21:09:35 +00003028
Denis Vlasenko131ae172007-02-18 13:00:19 +00003029#if ENABLE_ASH_ALIAS
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00003030
3031#define ALIASINUSE 1
3032#define ALIASDEAD 2
3033
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00003034struct alias {
3035 struct alias *next;
3036 char *name;
3037 char *val;
3038 int flag;
3039};
3040
Denis Vlasenko01631112007-12-16 17:20:38 +00003041
3042static struct alias **atab; // [ATABSIZE];
3043#define INIT_G_alias() do { \
3044 atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
3045} while (0)
3046
Eric Andersen2870d962001-07-02 17:27:21 +00003047
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00003048static struct alias **
3049__lookupalias(const char *name) {
3050 unsigned int hashval;
3051 struct alias **app;
3052 const char *p;
3053 unsigned int ch;
3054
3055 p = name;
3056
3057 ch = (unsigned char)*p;
3058 hashval = ch << 4;
3059 while (ch) {
3060 hashval += ch;
3061 ch = (unsigned char)*++p;
3062 }
3063 app = &atab[hashval % ATABSIZE];
3064
3065 for (; *app; app = &(*app)->next) {
3066 if (strcmp(name, (*app)->name) == 0) {
3067 break;
3068 }
3069 }
3070
3071 return app;
3072}
3073
3074static struct alias *
3075lookupalias(const char *name, int check)
3076{
3077 struct alias *ap = *__lookupalias(name);
3078
3079 if (check && ap && (ap->flag & ALIASINUSE))
3080 return NULL;
3081 return ap;
3082}
3083
3084static struct alias *
3085freealias(struct alias *ap)
3086{
3087 struct alias *next;
3088
3089 if (ap->flag & ALIASINUSE) {
3090 ap->flag |= ALIASDEAD;
3091 return ap;
3092 }
3093
3094 next = ap->next;
3095 free(ap->name);
3096 free(ap->val);
3097 free(ap);
3098 return next;
3099}
Eric Andersencb57d552001-06-28 07:25:16 +00003100
Eric Andersenc470f442003-07-28 09:56:35 +00003101static void
3102setalias(const char *name, const char *val)
Eric Andersencb57d552001-06-28 07:25:16 +00003103{
3104 struct alias *ap, **app;
3105
3106 app = __lookupalias(name);
3107 ap = *app;
Denis Vlasenkob012b102007-02-19 22:43:01 +00003108 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +00003109 if (ap) {
3110 if (!(ap->flag & ALIASINUSE)) {
Denis Vlasenkob012b102007-02-19 22:43:01 +00003111 free(ap->val);
Eric Andersencb57d552001-06-28 07:25:16 +00003112 }
Denis Vlasenko0c032a42007-02-23 01:03:40 +00003113 ap->val = ckstrdup(val);
Eric Andersencb57d552001-06-28 07:25:16 +00003114 ap->flag &= ~ALIASDEAD;
3115 } else {
3116 /* not found */
Denis Vlasenko597906c2008-02-20 16:38:54 +00003117 ap = ckzalloc(sizeof(struct alias));
Denis Vlasenko0c032a42007-02-23 01:03:40 +00003118 ap->name = ckstrdup(name);
3119 ap->val = ckstrdup(val);
Denis Vlasenko597906c2008-02-20 16:38:54 +00003120 /*ap->flag = 0; - ckzalloc did it */
3121 /*ap->next = NULL;*/
Eric Andersencb57d552001-06-28 07:25:16 +00003122 *app = ap;
3123 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00003124 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00003125}
3126
Eric Andersenc470f442003-07-28 09:56:35 +00003127static int
3128unalias(const char *name)
Eric Andersen2870d962001-07-02 17:27:21 +00003129{
Eric Andersencb57d552001-06-28 07:25:16 +00003130 struct alias **app;
3131
3132 app = __lookupalias(name);
3133
3134 if (*app) {
Denis Vlasenkob012b102007-02-19 22:43:01 +00003135 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +00003136 *app = freealias(*app);
Denis Vlasenkob012b102007-02-19 22:43:01 +00003137 INT_ON;
Denis Vlasenko079f8af2006-11-27 16:49:31 +00003138 return 0;
Eric Andersencb57d552001-06-28 07:25:16 +00003139 }
3140
Denis Vlasenko079f8af2006-11-27 16:49:31 +00003141 return 1;
Eric Andersencb57d552001-06-28 07:25:16 +00003142}
3143
Eric Andersenc470f442003-07-28 09:56:35 +00003144static void
3145rmaliases(void)
Eric Andersen2870d962001-07-02 17:27:21 +00003146{
Eric Andersencb57d552001-06-28 07:25:16 +00003147 struct alias *ap, **app;
3148 int i;
3149
Denis Vlasenkob012b102007-02-19 22:43:01 +00003150 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +00003151 for (i = 0; i < ATABSIZE; i++) {
3152 app = &atab[i];
3153 for (ap = *app; ap; ap = *app) {
3154 *app = freealias(*app);
3155 if (ap == *app) {
3156 app = &ap->next;
3157 }
3158 }
3159 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00003160 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00003161}
3162
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00003163static void
3164printalias(const struct alias *ap)
3165{
3166 out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
3167}
3168
Eric Andersencb57d552001-06-28 07:25:16 +00003169/*
3170 * TODO - sort output
3171 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02003172static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00003173aliascmd(int argc UNUSED_PARAM, char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +00003174{
3175 char *n, *v;
3176 int ret = 0;
3177 struct alias *ap;
3178
Denis Vlasenko68404f12008-03-17 09:00:54 +00003179 if (!argv[1]) {
Eric Andersencb57d552001-06-28 07:25:16 +00003180 int i;
3181
Denis Vlasenko68404f12008-03-17 09:00:54 +00003182 for (i = 0; i < ATABSIZE; i++) {
Eric Andersencb57d552001-06-28 07:25:16 +00003183 for (ap = atab[i]; ap; ap = ap->next) {
3184 printalias(ap);
3185 }
Denis Vlasenko68404f12008-03-17 09:00:54 +00003186 }
Denis Vlasenko079f8af2006-11-27 16:49:31 +00003187 return 0;
Eric Andersencb57d552001-06-28 07:25:16 +00003188 }
3189 while ((n = *++argv) != NULL) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00003190 v = strchr(n+1, '=');
3191 if (v == NULL) { /* n+1: funny ksh stuff */
3192 ap = *__lookupalias(n);
3193 if (ap == NULL) {
Eric Andersenc470f442003-07-28 09:56:35 +00003194 fprintf(stderr, "%s: %s not found\n", "alias", n);
Eric Andersencb57d552001-06-28 07:25:16 +00003195 ret = 1;
3196 } else
3197 printalias(ap);
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00003198 } else {
Eric Andersencb57d552001-06-28 07:25:16 +00003199 *v++ = '\0';
3200 setalias(n, v);
3201 }
3202 }
3203
Denis Vlasenkod9e15f22006-11-27 16:49:55 +00003204 return ret;
Eric Andersencb57d552001-06-28 07:25:16 +00003205}
3206
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02003207static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00003208unaliascmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersencb57d552001-06-28 07:25:16 +00003209{
3210 int i;
3211
3212 while ((i = nextopt("a")) != '\0') {
3213 if (i == 'a') {
3214 rmaliases();
Denis Vlasenko079f8af2006-11-27 16:49:31 +00003215 return 0;
Eric Andersencb57d552001-06-28 07:25:16 +00003216 }
3217 }
3218 for (i = 0; *argptr; argptr++) {
3219 if (unalias(*argptr)) {
Eric Andersenc470f442003-07-28 09:56:35 +00003220 fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
Eric Andersencb57d552001-06-28 07:25:16 +00003221 i = 1;
3222 }
3223 }
3224
Denis Vlasenkod9e15f22006-11-27 16:49:55 +00003225 return i;
Eric Andersencb57d552001-06-28 07:25:16 +00003226}
Denis Vlasenkofc06f292007-02-23 21:09:35 +00003227
Denis Vlasenko131ae172007-02-18 13:00:19 +00003228#endif /* ASH_ALIAS */
Eric Andersencb57d552001-06-28 07:25:16 +00003229
Eric Andersenc470f442003-07-28 09:56:35 +00003230
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003231/* ============ jobs.c */
3232
3233/* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
3234#define FORK_FG 0
3235#define FORK_BG 1
3236#define FORK_NOJOB 2
3237
3238/* mode flags for showjob(s) */
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003239#define SHOW_ONLY_PGID 0x01 /* show only pgid (jobs -p) */
3240#define SHOW_PIDS 0x02 /* show individual pids, not just one line per job */
3241#define SHOW_CHANGED 0x04 /* only jobs whose state has changed */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003242
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003243/*
3244 * A job structure contains information about a job. A job is either a
3245 * single process or a set of processes contained in a pipeline. In the
3246 * latter case, pidlist will be non-NULL, and will point to a -1 terminated
3247 * array of pids.
3248 */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003249struct procstat {
3250 pid_t pid; /* process id */
3251 int status; /* last process status from wait() */
3252 char *cmd; /* text of command being run */
3253};
3254
3255struct job {
3256 struct procstat ps0; /* status of process */
3257 struct procstat *ps; /* status or processes when more than one */
3258#if JOBS
3259 int stopstatus; /* status of a stopped job */
3260#endif
3261 uint32_t
3262 nprocs: 16, /* number of processes */
3263 state: 8,
3264#define JOBRUNNING 0 /* at least one proc running */
3265#define JOBSTOPPED 1 /* all procs are stopped */
3266#define JOBDONE 2 /* all procs are completed */
3267#if JOBS
3268 sigint: 1, /* job was killed by SIGINT */
3269 jobctl: 1, /* job running under job control */
3270#endif
3271 waited: 1, /* true if this entry has been waited for */
3272 used: 1, /* true if this entry is in used */
3273 changed: 1; /* true if status has changed */
3274 struct job *prev_job; /* previous job */
3275};
3276
Denis Vlasenko68404f12008-03-17 09:00:54 +00003277static struct job *makejob(/*union node *,*/ int);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003278static int forkshell(struct job *, union node *, int);
3279static int waitforjob(struct job *);
3280
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003281#if !JOBS
Denis Vlasenkob07a4962008-06-22 13:16:23 +00003282enum { doing_jobctl = 0 };
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003283#define setjobctl(on) do {} while (0)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003284#else
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003285static smallint doing_jobctl; //references:8
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003286static void setjobctl(int);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003287#endif
3288
3289/*
Denis Vlasenko4b875702009-03-19 13:30:04 +00003290 * Ignore a signal.
3291 */
3292static void
3293ignoresig(int signo)
3294{
3295 /* Avoid unnecessary system calls. Is it already SIG_IGNed? */
3296 if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
3297 /* No, need to do it */
3298 signal(signo, SIG_IGN);
3299 }
3300 sigmode[signo - 1] = S_HARD_IGN;
3301}
3302
3303/*
3304 * Signal handler. Only one usage site - in setsignal()
3305 */
3306static void
3307onsig(int signo)
3308{
3309 gotsig[signo - 1] = 1;
3310
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02003311 if (signo == SIGINT && !trap[SIGINT]) {
3312 if (!suppress_int) {
3313 pending_sig = 0;
Denis Vlasenko4b875702009-03-19 13:30:04 +00003314 raise_interrupt(); /* does not return */
3315 }
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02003316 pending_int = 1;
Denis Vlasenko4b875702009-03-19 13:30:04 +00003317 } else {
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02003318 pending_sig = signo;
Denis Vlasenko4b875702009-03-19 13:30:04 +00003319 }
3320}
3321
3322/*
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003323 * Set the signal handler for the specified signal. The routine figures
3324 * out what it should be set to.
3325 */
3326static void
3327setsignal(int signo)
3328{
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003329 char *t;
3330 char cur_act, new_act;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003331 struct sigaction act;
3332
3333 t = trap[signo];
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003334 new_act = S_DFL;
3335 if (t != NULL) { /* trap for this sig is set */
3336 new_act = S_CATCH;
3337 if (t[0] == '\0') /* trap is "": ignore this sig */
3338 new_act = S_IGN;
3339 }
3340
3341 if (rootshell && new_act == S_DFL) {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003342 switch (signo) {
3343 case SIGINT:
3344 if (iflag || minusc || sflag == 0)
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003345 new_act = S_CATCH;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003346 break;
3347 case SIGQUIT:
3348#if DEBUG
3349 if (debug)
3350 break;
3351#endif
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003352 /* man bash:
3353 * "In all cases, bash ignores SIGQUIT. Non-builtin
3354 * commands run by bash have signal handlers
3355 * set to the values inherited by the shell
3356 * from its parent". */
3357 new_act = S_IGN;
3358 break;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003359 case SIGTERM:
3360 if (iflag)
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003361 new_act = S_IGN;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003362 break;
3363#if JOBS
3364 case SIGTSTP:
3365 case SIGTTOU:
3366 if (mflag)
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003367 new_act = S_IGN;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003368 break;
3369#endif
3370 }
3371 }
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003372//TODO: if !rootshell, we reset SIGQUIT to DFL,
3373//whereas we have to restore it to what shell got on entry
3374//from the parent. See comment above
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003375
3376 t = &sigmode[signo - 1];
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003377 cur_act = *t;
3378 if (cur_act == 0) {
3379 /* current setting is not yet known */
3380 if (sigaction(signo, NULL, &act)) {
3381 /* pretend it worked; maybe we should give a warning,
3382 * but other shells don't. We don't alter sigmode,
3383 * so we retry every time.
3384 * btw, in Linux it never fails. --vda */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003385 return;
3386 }
3387 if (act.sa_handler == SIG_IGN) {
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003388 cur_act = S_HARD_IGN;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003389 if (mflag
3390 && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
3391 ) {
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003392 cur_act = S_IGN; /* don't hard ignore these */
Denis Vlasenko991a1da2008-02-10 19:02:53 +00003393 }
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003394 }
3395 }
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003396 if (cur_act == S_HARD_IGN || cur_act == new_act)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003397 return;
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003398
Denis Vlasenko991a1da2008-02-10 19:02:53 +00003399 act.sa_handler = SIG_DFL;
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003400 switch (new_act) {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003401 case S_CATCH:
3402 act.sa_handler = onsig;
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003403 act.sa_flags = 0; /* matters only if !DFL and !IGN */
3404 sigfillset(&act.sa_mask); /* ditto */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003405 break;
3406 case S_IGN:
3407 act.sa_handler = SIG_IGN;
3408 break;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003409 }
Denis Vlasenko8e2cfec2008-03-12 23:19:35 +00003410 sigaction_set(signo, &act);
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003411
3412 *t = new_act;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003413}
3414
3415/* mode flags for set_curjob */
3416#define CUR_DELETE 2
3417#define CUR_RUNNING 1
3418#define CUR_STOPPED 0
3419
3420/* mode flags for dowait */
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00003421#define DOWAIT_NONBLOCK WNOHANG
3422#define DOWAIT_BLOCK 0
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003423
3424#if JOBS
3425/* pgrp of shell on invocation */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003426static int initialpgrp; //references:2
3427static int ttyfd = -1; //5
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003428#endif
3429/* array of jobs */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003430static struct job *jobtab; //5
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003431/* size of array */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003432static unsigned njobs; //4
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003433/* current job */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003434static struct job *curjob; //lots
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003435/* number of presumed living untracked jobs */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00003436static int jobless; //4
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003437
3438static void
3439set_curjob(struct job *jp, unsigned mode)
3440{
3441 struct job *jp1;
3442 struct job **jpp, **curp;
3443
3444 /* first remove from list */
3445 jpp = curp = &curjob;
3446 do {
3447 jp1 = *jpp;
3448 if (jp1 == jp)
3449 break;
3450 jpp = &jp1->prev_job;
3451 } while (1);
3452 *jpp = jp1->prev_job;
3453
3454 /* Then re-insert in correct position */
3455 jpp = curp;
3456 switch (mode) {
3457 default:
3458#if DEBUG
3459 abort();
3460#endif
3461 case CUR_DELETE:
3462 /* job being deleted */
3463 break;
3464 case CUR_RUNNING:
3465 /* newly created job or backgrounded job,
3466 put after all stopped jobs. */
3467 do {
3468 jp1 = *jpp;
3469#if JOBS
3470 if (!jp1 || jp1->state != JOBSTOPPED)
3471#endif
3472 break;
3473 jpp = &jp1->prev_job;
3474 } while (1);
3475 /* FALLTHROUGH */
3476#if JOBS
3477 case CUR_STOPPED:
3478#endif
3479 /* newly stopped job - becomes curjob */
3480 jp->prev_job = *jpp;
3481 *jpp = jp;
3482 break;
3483 }
3484}
3485
3486#if JOBS || DEBUG
3487static int
3488jobno(const struct job *jp)
3489{
3490 return jp - jobtab + 1;
3491}
3492#endif
3493
3494/*
3495 * Convert a job name to a job structure.
3496 */
Denis Vlasenko85c24712008-03-17 09:04:04 +00003497#if !JOBS
3498#define getjob(name, getctl) getjob(name)
3499#endif
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003500static struct job *
3501getjob(const char *name, int getctl)
3502{
3503 struct job *jp;
3504 struct job *found;
Denys Vlasenkoffc39202009-08-17 02:12:20 +02003505 const char *err_msg = "%s: no such job";
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003506 unsigned num;
3507 int c;
3508 const char *p;
3509 char *(*match)(const char *, const char *);
3510
3511 jp = curjob;
3512 p = name;
3513 if (!p)
3514 goto currentjob;
3515
3516 if (*p != '%')
3517 goto err;
3518
3519 c = *++p;
3520 if (!c)
3521 goto currentjob;
3522
3523 if (!p[1]) {
3524 if (c == '+' || c == '%') {
3525 currentjob:
3526 err_msg = "No current job";
3527 goto check;
3528 }
3529 if (c == '-') {
3530 if (jp)
3531 jp = jp->prev_job;
3532 err_msg = "No previous job";
3533 check:
3534 if (!jp)
3535 goto err;
3536 goto gotit;
3537 }
3538 }
3539
3540 if (is_number(p)) {
3541 num = atoi(p);
3542 if (num < njobs) {
3543 jp = jobtab + num - 1;
3544 if (jp->used)
3545 goto gotit;
3546 goto err;
3547 }
3548 }
3549
3550 match = prefix;
3551 if (*p == '?') {
3552 match = strstr;
3553 p++;
3554 }
3555
Denys Vlasenkoffc39202009-08-17 02:12:20 +02003556 found = NULL;
3557 while (jp) {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003558 if (match(jp->ps[0].cmd, p)) {
3559 if (found)
3560 goto err;
3561 found = jp;
3562 err_msg = "%s: ambiguous";
3563 }
3564 jp = jp->prev_job;
3565 }
Denys Vlasenkoffc39202009-08-17 02:12:20 +02003566 if (!found)
3567 goto err;
3568 jp = found;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003569
3570 gotit:
3571#if JOBS
3572 err_msg = "job %s not created under job control";
3573 if (getctl && jp->jobctl == 0)
3574 goto err;
3575#endif
3576 return jp;
3577 err:
3578 ash_msg_and_raise_error(err_msg, name);
3579}
3580
3581/*
3582 * Mark a job structure as unused.
3583 */
3584static void
3585freejob(struct job *jp)
3586{
3587 struct procstat *ps;
3588 int i;
3589
3590 INT_OFF;
3591 for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
3592 if (ps->cmd != nullstr)
3593 free(ps->cmd);
3594 }
3595 if (jp->ps != &jp->ps0)
3596 free(jp->ps);
3597 jp->used = 0;
3598 set_curjob(jp, CUR_DELETE);
3599 INT_ON;
3600}
3601
3602#if JOBS
3603static void
3604xtcsetpgrp(int fd, pid_t pgrp)
3605{
3606 if (tcsetpgrp(fd, pgrp))
Bernhard Reutner-Fischera53de7f2008-07-21 13:46:54 +00003607 ash_msg_and_raise_error("can't set tty process group (%m)");
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003608}
3609
3610/*
3611 * Turn job control on and off.
3612 *
3613 * Note: This code assumes that the third arg to ioctl is a character
3614 * pointer, which is true on Berkeley systems but not System V. Since
3615 * System V doesn't have job control yet, this isn't a problem now.
3616 *
3617 * Called with interrupts off.
3618 */
3619static void
3620setjobctl(int on)
3621{
3622 int fd;
3623 int pgrp;
3624
Denis Vlasenkob07a4962008-06-22 13:16:23 +00003625 if (on == doing_jobctl || rootshell == 0)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003626 return;
3627 if (on) {
3628 int ofd;
3629 ofd = fd = open(_PATH_TTY, O_RDWR);
3630 if (fd < 0) {
3631 /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
3632 * That sometimes helps to acquire controlling tty.
3633 * Obviously, a workaround for bugs when someone
3634 * failed to provide a controlling tty to bash! :) */
Denis Vlasenkoed270a52007-11-26 05:37:07 +00003635 fd = 2;
3636 while (!isatty(fd))
3637 if (--fd < 0)
3638 goto out;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003639 }
3640 fd = fcntl(fd, F_DUPFD, 10);
Denis Vlasenkoed270a52007-11-26 05:37:07 +00003641 if (ofd >= 0)
3642 close(ofd);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003643 if (fd < 0)
3644 goto out;
Denis Vlasenkoed270a52007-11-26 05:37:07 +00003645 /* fd is a tty at this point */
Denis Vlasenko96e1b382007-09-30 23:50:48 +00003646 close_on_exec_on(fd);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003647 do { /* while we are in the background */
3648 pgrp = tcgetpgrp(fd);
3649 if (pgrp < 0) {
3650 out:
3651 ash_msg("can't access tty; job control turned off");
3652 mflag = on = 0;
3653 goto close;
3654 }
3655 if (pgrp == getpgrp())
3656 break;
3657 killpg(0, SIGTTIN);
3658 } while (1);
3659 initialpgrp = pgrp;
3660
3661 setsignal(SIGTSTP);
3662 setsignal(SIGTTOU);
3663 setsignal(SIGTTIN);
3664 pgrp = rootpid;
3665 setpgid(0, pgrp);
3666 xtcsetpgrp(fd, pgrp);
3667 } else {
3668 /* turning job control off */
3669 fd = ttyfd;
3670 pgrp = initialpgrp;
Denis Vlasenko08c8c1d2007-04-28 22:39:02 +00003671 /* was xtcsetpgrp, but this can make exiting ash
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00003672 * loop forever if pty is already deleted */
Denis Vlasenko08c8c1d2007-04-28 22:39:02 +00003673 tcsetpgrp(fd, pgrp);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003674 setpgid(0, pgrp);
3675 setsignal(SIGTSTP);
3676 setsignal(SIGTTOU);
3677 setsignal(SIGTTIN);
3678 close:
Denis Vlasenkoed270a52007-11-26 05:37:07 +00003679 if (fd >= 0)
3680 close(fd);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003681 fd = -1;
3682 }
3683 ttyfd = fd;
Denis Vlasenkob07a4962008-06-22 13:16:23 +00003684 doing_jobctl = on;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003685}
3686
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02003687static int FAST_FUNC
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003688killcmd(int argc, char **argv)
3689{
Denis Vlasenko68404f12008-03-17 09:00:54 +00003690 int i = 1;
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003691 if (argv[1] && strcmp(argv[1], "-l") != 0) {
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003692 do {
3693 if (argv[i][0] == '%') {
3694 struct job *jp = getjob(argv[i], 0);
3695 unsigned pid = jp->ps[0].pid;
3696 /* Enough space for ' -NNN<nul>' */
3697 argv[i] = alloca(sizeof(int)*3 + 3);
3698 /* kill_main has matching code to expect
3699 * leading space. Needed to not confuse
3700 * negative pids with "kill -SIGNAL_NO" syntax */
3701 sprintf(argv[i], " -%u", pid);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003702 }
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003703 } while (argv[++i]);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003704 }
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003705 return kill_main(argc, argv);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003706}
3707
3708static void
3709showpipe(struct job *jp, FILE *out)
3710{
3711 struct procstat *sp;
3712 struct procstat *spend;
3713
3714 spend = jp->ps + jp->nprocs;
3715 for (sp = jp->ps + 1; sp < spend; sp++)
3716 fprintf(out, " | %s", sp->cmd);
3717 outcslow('\n', out);
3718 flush_stdout_stderr();
3719}
3720
3721
3722static int
3723restartjob(struct job *jp, int mode)
3724{
3725 struct procstat *ps;
3726 int i;
3727 int status;
3728 pid_t pgid;
3729
3730 INT_OFF;
3731 if (jp->state == JOBDONE)
3732 goto out;
3733 jp->state = JOBRUNNING;
3734 pgid = jp->ps->pid;
3735 if (mode == FORK_FG)
3736 xtcsetpgrp(ttyfd, pgid);
3737 killpg(pgid, SIGCONT);
3738 ps = jp->ps;
3739 i = jp->nprocs;
3740 do {
3741 if (WIFSTOPPED(ps->status)) {
3742 ps->status = -1;
3743 }
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003744 ps++;
3745 } while (--i);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003746 out:
3747 status = (mode == FORK_FG) ? waitforjob(jp) : 0;
3748 INT_ON;
3749 return status;
3750}
3751
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02003752static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00003753fg_bgcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003754{
3755 struct job *jp;
3756 FILE *out;
3757 int mode;
3758 int retval;
3759
3760 mode = (**argv == 'f') ? FORK_FG : FORK_BG;
3761 nextopt(nullstr);
3762 argv = argptr;
3763 out = stdout;
3764 do {
3765 jp = getjob(*argv, 1);
3766 if (mode == FORK_BG) {
3767 set_curjob(jp, CUR_RUNNING);
3768 fprintf(out, "[%d] ", jobno(jp));
3769 }
3770 outstr(jp->ps->cmd, out);
3771 showpipe(jp, out);
3772 retval = restartjob(jp, mode);
3773 } while (*argv && *++argv);
3774 return retval;
3775}
3776#endif
3777
3778static int
3779sprint_status(char *s, int status, int sigonly)
3780{
3781 int col;
3782 int st;
3783
3784 col = 0;
3785 if (!WIFEXITED(status)) {
3786#if JOBS
3787 if (WIFSTOPPED(status))
3788 st = WSTOPSIG(status);
3789 else
3790#endif
3791 st = WTERMSIG(status);
3792 if (sigonly) {
3793 if (st == SIGINT || st == SIGPIPE)
3794 goto out;
3795#if JOBS
3796 if (WIFSTOPPED(status))
3797 goto out;
3798#endif
3799 }
3800 st &= 0x7f;
3801 col = fmtstr(s, 32, strsignal(st));
3802 if (WCOREDUMP(status)) {
3803 col += fmtstr(s + col, 16, " (core dumped)");
3804 }
3805 } else if (!sigonly) {
3806 st = WEXITSTATUS(status);
3807 if (st)
3808 col = fmtstr(s, 16, "Done(%d)", st);
3809 else
3810 col = fmtstr(s, 16, "Done");
3811 }
3812 out:
3813 return col;
3814}
3815
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003816static int
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00003817dowait(int wait_flags, struct job *job)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003818{
3819 int pid;
3820 int status;
3821 struct job *jp;
3822 struct job *thisjob;
3823 int state;
3824
Denis Vlasenkobe54d6b2008-10-27 14:25:52 +00003825 TRACE(("dowait(0x%x) called\n", wait_flags));
3826
3827 /* Do a wait system call. If job control is compiled in, we accept
3828 * stopped processes. wait_flags may have WNOHANG, preventing blocking.
3829 * NB: _not_ safe_waitpid, we need to detect EINTR */
3830 pid = waitpid(-1, &status,
3831 (doing_jobctl ? (wait_flags | WUNTRACED) : wait_flags));
Denis Vlasenkob21f3792009-03-19 23:09:58 +00003832 TRACE(("wait returns pid=%d, status=0x%x, errno=%d(%s)\n",
3833 pid, status, errno, strerror(errno)));
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003834 if (pid <= 0)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003835 return pid;
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003836
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003837 INT_OFF;
3838 thisjob = NULL;
3839 for (jp = curjob; jp; jp = jp->prev_job) {
3840 struct procstat *sp;
3841 struct procstat *spend;
3842 if (jp->state == JOBDONE)
3843 continue;
3844 state = JOBDONE;
3845 spend = jp->ps + jp->nprocs;
3846 sp = jp->ps;
3847 do {
3848 if (sp->pid == pid) {
3849 TRACE(("Job %d: changing status of proc %d "
3850 "from 0x%x to 0x%x\n",
3851 jobno(jp), pid, sp->status, status));
3852 sp->status = status;
3853 thisjob = jp;
3854 }
3855 if (sp->status == -1)
3856 state = JOBRUNNING;
3857#if JOBS
3858 if (state == JOBRUNNING)
3859 continue;
3860 if (WIFSTOPPED(sp->status)) {
3861 jp->stopstatus = sp->status;
3862 state = JOBSTOPPED;
3863 }
3864#endif
3865 } while (++sp < spend);
3866 if (thisjob)
3867 goto gotjob;
3868 }
3869#if JOBS
3870 if (!WIFSTOPPED(status))
3871#endif
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003872 jobless--;
3873 goto out;
3874
3875 gotjob:
3876 if (state != JOBRUNNING) {
3877 thisjob->changed = 1;
3878
3879 if (thisjob->state != state) {
3880 TRACE(("Job %d: changing state from %d to %d\n",
3881 jobno(thisjob), thisjob->state, state));
3882 thisjob->state = state;
3883#if JOBS
3884 if (state == JOBSTOPPED) {
3885 set_curjob(thisjob, CUR_STOPPED);
3886 }
3887#endif
3888 }
3889 }
3890
3891 out:
3892 INT_ON;
3893
3894 if (thisjob && thisjob == job) {
3895 char s[48 + 1];
3896 int len;
3897
3898 len = sprint_status(s, status, 1);
3899 if (len) {
3900 s[len] = '\n';
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00003901 s[len + 1] = '\0';
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003902 out2str(s);
3903 }
3904 }
3905 return pid;
3906}
3907
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003908static int
3909blocking_wait_with_raise_on_sig(struct job *job)
3910{
3911 pid_t pid = dowait(DOWAIT_BLOCK, job);
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02003912 if (pid <= 0 && pending_sig)
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00003913 raise_exception(EXSIG);
3914 return pid;
3915}
3916
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003917#if JOBS
3918static void
3919showjob(FILE *out, struct job *jp, int mode)
3920{
3921 struct procstat *ps;
3922 struct procstat *psend;
3923 int col;
Denis Vlasenko40ba9982007-07-14 00:48:29 +00003924 int indent_col;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003925 char s[80];
3926
3927 ps = jp->ps;
3928
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003929 if (mode & SHOW_ONLY_PGID) { /* jobs -p */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003930 /* just output process (group) id of pipeline */
3931 fprintf(out, "%d\n", ps->pid);
3932 return;
3933 }
3934
3935 col = fmtstr(s, 16, "[%d] ", jobno(jp));
Denis Vlasenko40ba9982007-07-14 00:48:29 +00003936 indent_col = col;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003937
3938 if (jp == curjob)
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003939 s[col - 3] = '+';
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003940 else if (curjob && jp == curjob->prev_job)
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003941 s[col - 3] = '-';
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003942
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003943 if (mode & SHOW_PIDS)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003944 col += fmtstr(s + col, 16, "%d ", ps->pid);
3945
3946 psend = ps + jp->nprocs;
3947
3948 if (jp->state == JOBRUNNING) {
3949 strcpy(s + col, "Running");
3950 col += sizeof("Running") - 1;
3951 } else {
3952 int status = psend[-1].status;
3953 if (jp->state == JOBSTOPPED)
3954 status = jp->stopstatus;
3955 col += sprint_status(s + col, status, 0);
3956 }
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003957 /* By now, "[JOBID]* [maybe PID] STATUS" is printed */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003958
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003959 /* This loop either prints "<cmd1> | <cmd2> | <cmd3>" line
3960 * or prints several "PID | <cmdN>" lines,
3961 * depending on SHOW_PIDS bit.
3962 * We do not print status of individual processes
3963 * between PID and <cmdN>. bash does it, but not very well:
3964 * first line shows overall job status, not process status,
3965 * making it impossible to know 1st process status.
3966 */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003967 goto start;
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003968 while (1) {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003969 /* for each process */
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003970 s[0] = '\0';
3971 col = 33;
3972 if (mode & SHOW_PIDS)
3973 col = fmtstr(s, 48, "\n%*c%d ", indent_col, ' ', ps->pid) - 1;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003974 start:
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003975 fprintf(out, "%s%*c", s, 33 - col >= 0 ? 33 - col : 0, ' ');
3976 if (ps != jp->ps)
3977 fprintf(out, "| ");
3978 fprintf(out, "%s", ps->cmd);
3979 if (++ps == psend)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003980 break;
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02003981 }
3982 outcslow('\n', out);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003983
3984 jp->changed = 0;
3985
3986 if (jp->state == JOBDONE) {
3987 TRACE(("showjob: freeing job %d\n", jobno(jp)));
3988 freejob(jp);
3989 }
3990}
3991
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003992/*
3993 * Print a list of jobs. If "change" is nonzero, only print jobs whose
3994 * statuses have changed since the last call to showjobs.
3995 */
3996static void
3997showjobs(FILE *out, int mode)
3998{
3999 struct job *jp;
4000
Denys Vlasenko883cea42009-07-11 15:31:59 +02004001 TRACE(("showjobs(0x%x) called\n", mode));
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004002
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004003 /* Handle all finished jobs */
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00004004 while (dowait(DOWAIT_NONBLOCK, NULL) > 0)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004005 continue;
4006
4007 for (jp = curjob; jp; jp = jp->prev_job) {
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00004008 if (!(mode & SHOW_CHANGED) || jp->changed) {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004009 showjob(out, jp, mode);
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00004010 }
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004011 }
4012}
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00004013
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02004014static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00004015jobscmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00004016{
4017 int mode, m;
4018
4019 mode = 0;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02004020 while ((m = nextopt("lp")) != '\0') {
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00004021 if (m == 'l')
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02004022 mode |= SHOW_PIDS;
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00004023 else
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02004024 mode |= SHOW_ONLY_PGID;
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00004025 }
4026
4027 argv = argptr;
4028 if (*argv) {
4029 do
Denys Vlasenkoa12af2d2009-08-23 22:10:04 +02004030 showjob(stdout, getjob(*argv, 0), mode);
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00004031 while (*++argv);
4032 } else
4033 showjobs(stdout, mode);
4034
4035 return 0;
4036}
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004037#endif /* JOBS */
4038
4039static int
4040getstatus(struct job *job)
4041{
4042 int status;
4043 int retval;
4044
4045 status = job->ps[job->nprocs - 1].status;
4046 retval = WEXITSTATUS(status);
4047 if (!WIFEXITED(status)) {
4048#if JOBS
4049 retval = WSTOPSIG(status);
4050 if (!WIFSTOPPED(status))
4051#endif
4052 {
4053 /* XXX: limits number of signals */
4054 retval = WTERMSIG(status);
4055#if JOBS
4056 if (retval == SIGINT)
4057 job->sigint = 1;
4058#endif
4059 }
4060 retval += 128;
4061 }
Denys Vlasenko883cea42009-07-11 15:31:59 +02004062 TRACE(("getstatus: job %d, nproc %d, status 0x%x, retval 0x%x\n",
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004063 jobno(job), job->nprocs, status, retval));
4064 return retval;
4065}
4066
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02004067static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00004068waitcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004069{
4070 struct job *job;
4071 int retval;
4072 struct job *jp;
4073
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02004074 if (pending_sig)
Denis Vlasenko991a1da2008-02-10 19:02:53 +00004075 raise_exception(EXSIG);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004076
4077 nextopt(nullstr);
4078 retval = 0;
4079
4080 argv = argptr;
4081 if (!*argv) {
4082 /* wait for all jobs */
4083 for (;;) {
4084 jp = curjob;
4085 while (1) {
Denis Vlasenko991a1da2008-02-10 19:02:53 +00004086 if (!jp) /* no running procs */
4087 goto ret;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004088 if (jp->state == JOBRUNNING)
4089 break;
4090 jp->waited = 1;
4091 jp = jp->prev_job;
4092 }
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004093 /* man bash:
4094 * "When bash is waiting for an asynchronous command via
4095 * the wait builtin, the reception of a signal for which a trap
4096 * has been set will cause the wait builtin to return immediately
4097 * with an exit status greater than 128, immediately after which
4098 * the trap is executed."
4099 * Do we do it that way? */
4100 blocking_wait_with_raise_on_sig(NULL);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004101 }
4102 }
4103
4104 retval = 127;
4105 do {
4106 if (**argv != '%') {
4107 pid_t pid = number(*argv);
4108 job = curjob;
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00004109 while (1) {
4110 if (!job)
4111 goto repeat;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004112 if (job->ps[job->nprocs - 1].pid == pid)
4113 break;
4114 job = job->prev_job;
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00004115 }
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004116 } else
4117 job = getjob(*argv, 0);
4118 /* loop until process terminated or stopped */
4119 while (job->state == JOBRUNNING)
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004120 blocking_wait_with_raise_on_sig(NULL);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004121 job->waited = 1;
4122 retval = getstatus(job);
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004123 repeat: ;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004124 } while (*++argv);
4125
Denis Vlasenko991a1da2008-02-10 19:02:53 +00004126 ret:
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004127 return retval;
4128}
4129
4130static struct job *
4131growjobtab(void)
4132{
4133 size_t len;
4134 ptrdiff_t offset;
4135 struct job *jp, *jq;
4136
4137 len = njobs * sizeof(*jp);
4138 jq = jobtab;
4139 jp = ckrealloc(jq, len + 4 * sizeof(*jp));
4140
4141 offset = (char *)jp - (char *)jq;
4142 if (offset) {
4143 /* Relocate pointers */
4144 size_t l = len;
4145
4146 jq = (struct job *)((char *)jq + l);
4147 while (l) {
4148 l -= sizeof(*jp);
4149 jq--;
4150#define joff(p) ((struct job *)((char *)(p) + l))
4151#define jmove(p) (p) = (void *)((char *)(p) + offset)
4152 if (joff(jp)->ps == &jq->ps0)
4153 jmove(joff(jp)->ps);
4154 if (joff(jp)->prev_job)
4155 jmove(joff(jp)->prev_job);
4156 }
4157 if (curjob)
4158 jmove(curjob);
4159#undef joff
4160#undef jmove
4161 }
4162
4163 njobs += 4;
4164 jobtab = jp;
4165 jp = (struct job *)((char *)jp + len);
4166 jq = jp + 3;
4167 do {
4168 jq->used = 0;
4169 } while (--jq >= jp);
4170 return jp;
4171}
4172
4173/*
4174 * Return a new job structure.
4175 * Called with interrupts off.
4176 */
4177static struct job *
Denis Vlasenko68404f12008-03-17 09:00:54 +00004178makejob(/*union node *node,*/ int nprocs)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004179{
4180 int i;
4181 struct job *jp;
4182
4183 for (i = njobs, jp = jobtab; ; jp++) {
4184 if (--i < 0) {
4185 jp = growjobtab();
4186 break;
4187 }
4188 if (jp->used == 0)
4189 break;
4190 if (jp->state != JOBDONE || !jp->waited)
4191 continue;
4192#if JOBS
Denis Vlasenkob07a4962008-06-22 13:16:23 +00004193 if (doing_jobctl)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004194 continue;
4195#endif
4196 freejob(jp);
4197 break;
4198 }
4199 memset(jp, 0, sizeof(*jp));
4200#if JOBS
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00004201 /* jp->jobctl is a bitfield.
4202 * "jp->jobctl |= jobctl" likely to give awful code */
Denis Vlasenkob07a4962008-06-22 13:16:23 +00004203 if (doing_jobctl)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004204 jp->jobctl = 1;
4205#endif
4206 jp->prev_job = curjob;
4207 curjob = jp;
4208 jp->used = 1;
4209 jp->ps = &jp->ps0;
4210 if (nprocs > 1) {
4211 jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
4212 }
Denis Vlasenko68404f12008-03-17 09:00:54 +00004213 TRACE(("makejob(%d) returns %%%d\n", nprocs,
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004214 jobno(jp)));
4215 return jp;
4216}
4217
4218#if JOBS
4219/*
4220 * Return a string identifying a command (to be printed by the
4221 * jobs command).
4222 */
4223static char *cmdnextc;
4224
4225static void
4226cmdputs(const char *s)
4227{
Denis Vlasenko92e13c22008-03-25 01:17:40 +00004228 static const char vstype[VSTYPE + 1][3] = {
4229 "", "}", "-", "+", "?", "=",
4230 "%", "%%", "#", "##"
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00004231 IF_ASH_BASH_COMPAT(, ":", "/", "//")
Denis Vlasenko92e13c22008-03-25 01:17:40 +00004232 };
4233
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004234 const char *p, *str;
4235 char c, cc[2] = " ";
4236 char *nextc;
4237 int subtype = 0;
4238 int quoted = 0;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004239
4240 nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
4241 p = s;
4242 while ((c = *p++) != 0) {
Denis Vlasenkoef527f52008-06-23 01:52:30 +00004243 str = NULL;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004244 switch (c) {
4245 case CTLESC:
4246 c = *p++;
4247 break;
4248 case CTLVAR:
4249 subtype = *p++;
4250 if ((subtype & VSTYPE) == VSLENGTH)
4251 str = "${#";
4252 else
4253 str = "${";
4254 if (!(subtype & VSQUOTE) == !(quoted & 1))
4255 goto dostr;
4256 quoted ^= 1;
4257 c = '"';
4258 break;
4259 case CTLENDVAR:
4260 str = "\"}" + !(quoted & 1);
4261 quoted >>= 1;
4262 subtype = 0;
4263 goto dostr;
4264 case CTLBACKQ:
4265 str = "$(...)";
4266 goto dostr;
4267 case CTLBACKQ+CTLQUOTE:
4268 str = "\"$(...)\"";
4269 goto dostr;
Mike Frysinger98c52642009-04-02 10:02:37 +00004270#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004271 case CTLARI:
4272 str = "$((";
4273 goto dostr;
4274 case CTLENDARI:
4275 str = "))";
4276 goto dostr;
4277#endif
4278 case CTLQUOTEMARK:
4279 quoted ^= 1;
4280 c = '"';
4281 break;
4282 case '=':
4283 if (subtype == 0)
4284 break;
4285 if ((subtype & VSTYPE) != VSNORMAL)
4286 quoted <<= 1;
4287 str = vstype[subtype & VSTYPE];
4288 if (subtype & VSNUL)
4289 c = ':';
4290 else
4291 goto checkstr;
4292 break;
4293 case '\'':
4294 case '\\':
4295 case '"':
4296 case '$':
4297 /* These can only happen inside quotes */
4298 cc[0] = c;
4299 str = cc;
4300 c = '\\';
4301 break;
4302 default:
4303 break;
4304 }
4305 USTPUTC(c, nextc);
4306 checkstr:
4307 if (!str)
4308 continue;
4309 dostr:
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02004310 while ((c = *str++) != '\0') {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004311 USTPUTC(c, nextc);
4312 }
4313 }
4314 if (quoted & 1) {
4315 USTPUTC('"', nextc);
4316 }
4317 *nextc = 0;
4318 cmdnextc = nextc;
4319}
4320
4321/* cmdtxt() and cmdlist() call each other */
4322static void cmdtxt(union node *n);
4323
4324static void
4325cmdlist(union node *np, int sep)
4326{
4327 for (; np; np = np->narg.next) {
4328 if (!sep)
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00004329 cmdputs(" ");
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004330 cmdtxt(np);
4331 if (sep && np->narg.next)
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00004332 cmdputs(" ");
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004333 }
4334}
4335
4336static void
4337cmdtxt(union node *n)
4338{
4339 union node *np;
4340 struct nodelist *lp;
4341 const char *p;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004342
4343 if (!n)
4344 return;
4345 switch (n->type) {
4346 default:
4347#if DEBUG
4348 abort();
4349#endif
4350 case NPIPE:
4351 lp = n->npipe.cmdlist;
4352 for (;;) {
4353 cmdtxt(lp->n);
4354 lp = lp->next;
4355 if (!lp)
4356 break;
4357 cmdputs(" | ");
4358 }
4359 break;
4360 case NSEMI:
4361 p = "; ";
4362 goto binop;
4363 case NAND:
4364 p = " && ";
4365 goto binop;
4366 case NOR:
4367 p = " || ";
4368 binop:
4369 cmdtxt(n->nbinary.ch1);
4370 cmdputs(p);
4371 n = n->nbinary.ch2;
4372 goto donode;
4373 case NREDIR:
4374 case NBACKGND:
4375 n = n->nredir.n;
4376 goto donode;
4377 case NNOT:
4378 cmdputs("!");
4379 n = n->nnot.com;
4380 donode:
4381 cmdtxt(n);
4382 break;
4383 case NIF:
4384 cmdputs("if ");
4385 cmdtxt(n->nif.test);
4386 cmdputs("; then ");
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004387 if (n->nif.elsepart) {
Denys Vlasenko7cee00e2009-07-24 01:08:03 +02004388 cmdtxt(n->nif.ifpart);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004389 cmdputs("; else ");
4390 n = n->nif.elsepart;
Denys Vlasenko7cee00e2009-07-24 01:08:03 +02004391 } else {
4392 n = n->nif.ifpart;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004393 }
4394 p = "; fi";
4395 goto dotail;
4396 case NSUBSHELL:
4397 cmdputs("(");
4398 n = n->nredir.n;
4399 p = ")";
4400 goto dotail;
4401 case NWHILE:
4402 p = "while ";
4403 goto until;
4404 case NUNTIL:
4405 p = "until ";
4406 until:
4407 cmdputs(p);
4408 cmdtxt(n->nbinary.ch1);
4409 n = n->nbinary.ch2;
4410 p = "; done";
4411 dodo:
4412 cmdputs("; do ");
4413 dotail:
4414 cmdtxt(n);
4415 goto dotail2;
4416 case NFOR:
4417 cmdputs("for ");
4418 cmdputs(n->nfor.var);
4419 cmdputs(" in ");
4420 cmdlist(n->nfor.args, 1);
4421 n = n->nfor.body;
4422 p = "; done";
4423 goto dodo;
4424 case NDEFUN:
4425 cmdputs(n->narg.text);
4426 p = "() { ... }";
4427 goto dotail2;
4428 case NCMD:
4429 cmdlist(n->ncmd.args, 1);
4430 cmdlist(n->ncmd.redirect, 0);
4431 break;
4432 case NARG:
4433 p = n->narg.text;
4434 dotail2:
4435 cmdputs(p);
4436 break;
4437 case NHERE:
4438 case NXHERE:
4439 p = "<<...";
4440 goto dotail2;
4441 case NCASE:
4442 cmdputs("case ");
4443 cmdputs(n->ncase.expr->narg.text);
4444 cmdputs(" in ");
4445 for (np = n->ncase.cases; np; np = np->nclist.next) {
4446 cmdtxt(np->nclist.pattern);
4447 cmdputs(") ");
4448 cmdtxt(np->nclist.body);
4449 cmdputs(";; ");
4450 }
4451 p = "esac";
4452 goto dotail2;
4453 case NTO:
4454 p = ">";
4455 goto redir;
4456 case NCLOBBER:
4457 p = ">|";
4458 goto redir;
4459 case NAPPEND:
4460 p = ">>";
4461 goto redir;
Denis Vlasenko559691a2008-10-05 18:39:31 +00004462#if ENABLE_ASH_BASH_COMPAT
4463 case NTO2:
4464#endif
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004465 case NTOFD:
4466 p = ">&";
4467 goto redir;
4468 case NFROM:
4469 p = "<";
4470 goto redir;
4471 case NFROMFD:
4472 p = "<&";
4473 goto redir;
4474 case NFROMTO:
4475 p = "<>";
4476 redir:
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00004477 cmdputs(utoa(n->nfile.fd));
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004478 cmdputs(p);
4479 if (n->type == NTOFD || n->type == NFROMFD) {
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00004480 cmdputs(utoa(n->ndup.dupfd));
4481 break;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004482 }
4483 n = n->nfile.fname;
4484 goto donode;
4485 }
4486}
4487
4488static char *
4489commandtext(union node *n)
4490{
4491 char *name;
4492
4493 STARTSTACKSTR(cmdnextc);
4494 cmdtxt(n);
4495 name = stackblock();
4496 TRACE(("commandtext: name %p, end %p\n\t\"%s\"\n",
4497 name, cmdnextc, cmdnextc));
4498 return ckstrdup(name);
4499}
4500#endif /* JOBS */
4501
4502/*
4503 * Fork off a subshell. If we are doing job control, give the subshell its
4504 * own process group. Jp is a job structure that the job is to be added to.
4505 * N is the command that will be evaluated by the child. Both jp and n may
4506 * be NULL. The mode parameter can be one of the following:
4507 * FORK_FG - Fork off a foreground process.
4508 * FORK_BG - Fork off a background process.
4509 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
4510 * process group even if job control is on.
4511 *
4512 * When job control is turned off, background processes have their standard
4513 * input redirected to /dev/null (except for the second and later processes
4514 * in a pipeline).
4515 *
4516 * Called with interrupts off.
4517 */
4518/*
4519 * Clear traps on a fork.
4520 */
4521static void
4522clear_traps(void)
4523{
4524 char **tp;
4525
4526 for (tp = trap; tp < &trap[NSIG]; tp++) {
Denis Vlasenko991a1da2008-02-10 19:02:53 +00004527 if (*tp && **tp) { /* trap not NULL or "" (SIG_IGN) */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004528 INT_OFF;
Denys Vlasenkoe305c282009-09-25 02:12:27 +02004529 if (trap_ptr == trap)
4530 free(*tp);
4531 /* else: it "belongs" to trap_ptr vector, don't free */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004532 *tp = NULL;
Denys Vlasenko0800e3a2009-09-24 03:09:26 +02004533 if ((tp - trap) != 0)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004534 setsignal(tp - trap);
4535 INT_ON;
4536 }
4537 }
4538}
Denis Vlasenkobdc406d2007-07-15 01:13:25 +00004539
4540/* Lives far away from here, needed for forkchild */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004541static void closescript(void);
Denis Vlasenko41770222007-10-07 18:02:52 +00004542
Denis Vlasenkobdc406d2007-07-15 01:13:25 +00004543/* Called after fork(), in child */
Denys Vlasenko21d87d42009-09-25 00:06:51 +02004544static NOINLINE void
Denys Vlasenkoe56f22a2009-07-24 00:16:59 +02004545forkchild(struct job *jp, union node *n, int mode)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004546{
4547 int oldlvl;
4548
4549 TRACE(("Child shell %d\n", getpid()));
4550 oldlvl = shlvl;
4551 shlvl++;
4552
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004553 /* man bash: "Non-builtin commands run by bash have signal handlers
4554 * set to the values inherited by the shell from its parent".
4555 * Do we do it correctly? */
4556
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004557 closescript();
Denys Vlasenko844f9902009-09-23 03:25:52 +02004558
4559 if (mode == FORK_NOJOB /* is it `xxx` ? */
4560 && n && n->type == NCMD /* is it single cmd? */
4561 /* && n->ncmd.args->type == NARG - always true? */
4562 && strcmp(n->ncmd.args->narg.text, "trap") == 0
4563 && n->ncmd.args->narg.next == NULL /* "trap" with no arguments */
4564 /* && n->ncmd.args->narg.backquote == NULL - do we need to check this? */
4565 ) {
4566 TRACE(("Trap hack\n"));
4567 /* Awful hack for `trap` or $(trap).
4568 *
4569 * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
4570 * contains an example where "trap" is executed in a subshell:
4571 *
4572 * save_traps=$(trap)
4573 * ...
4574 * eval "$save_traps"
4575 *
4576 * Standard does not say that "trap" in subshell shall print
4577 * parent shell's traps. It only says that its output
4578 * must have suitable form, but then, in the above example
4579 * (which is not supposed to be normative), it implies that.
4580 *
4581 * bash (and probably other shell) does implement it
4582 * (traps are reset to defaults, but "trap" still shows them),
4583 * but as a result, "trap" logic is hopelessly messed up:
4584 *
4585 * # trap
4586 * trap -- 'echo Ho' SIGWINCH <--- we have a handler
4587 * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
4588 * # true | trap <--- trap is in subshell - no output (ditto)
4589 * # echo `true | trap` <--- in subshell - output (but traps are reset!)
4590 * trap -- 'echo Ho' SIGWINCH
4591 * # echo `(trap)` <--- in subshell in subshell - output
4592 * trap -- 'echo Ho' SIGWINCH
4593 * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
4594 * trap -- 'echo Ho' SIGWINCH
4595 *
4596 * The rules when to forget and when to not forget traps
4597 * get really complex and nonsensical.
4598 *
4599 * Our solution: ONLY bare $(trap) or `trap` is special.
4600 */
Denys Vlasenko8f88d852009-09-25 12:12:53 +02004601 /* Save trap handler strings for trap builtin to print */
Denys Vlasenko21d87d42009-09-25 00:06:51 +02004602 trap_ptr = memcpy(xmalloc(sizeof(trap)), trap, sizeof(trap));
Denys Vlasenko8f88d852009-09-25 12:12:53 +02004603 /* Fall through into clearing traps */
Denys Vlasenko844f9902009-09-23 03:25:52 +02004604 }
Denys Vlasenkoe305c282009-09-25 02:12:27 +02004605 clear_traps();
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004606#if JOBS
4607 /* do job control only in root shell */
Denis Vlasenkob07a4962008-06-22 13:16:23 +00004608 doing_jobctl = 0;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004609 if (mode != FORK_NOJOB && jp->jobctl && !oldlvl) {
4610 pid_t pgrp;
4611
4612 if (jp->nprocs == 0)
4613 pgrp = getpid();
4614 else
4615 pgrp = jp->ps[0].pid;
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004616 /* this can fail because we are doing it in the parent also */
4617 setpgid(0, pgrp);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004618 if (mode == FORK_FG)
4619 xtcsetpgrp(ttyfd, pgrp);
4620 setsignal(SIGTSTP);
4621 setsignal(SIGTTOU);
4622 } else
4623#endif
4624 if (mode == FORK_BG) {
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004625 /* man bash: "When job control is not in effect,
4626 * asynchronous commands ignore SIGINT and SIGQUIT" */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004627 ignoresig(SIGINT);
4628 ignoresig(SIGQUIT);
4629 if (jp->nprocs == 0) {
4630 close(0);
4631 if (open(bb_dev_null, O_RDONLY) != 0)
Denis Vlasenko9604e1b2009-03-03 18:47:56 +00004632 ash_msg_and_raise_error("can't open '%s'", bb_dev_null);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004633 }
4634 }
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004635 if (!oldlvl) {
4636 if (iflag) { /* why if iflag only? */
4637 setsignal(SIGINT);
4638 setsignal(SIGTERM);
4639 }
4640 /* man bash:
4641 * "In all cases, bash ignores SIGQUIT. Non-builtin
4642 * commands run by bash have signal handlers
4643 * set to the values inherited by the shell
4644 * from its parent".
4645 * Take care of the second rule: */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004646 setsignal(SIGQUIT);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004647 }
Denys Vlasenkoe56f22a2009-07-24 00:16:59 +02004648#if JOBS
Denys Vlasenko844f9902009-09-23 03:25:52 +02004649 if (n && n->type == NCMD
4650 && strcmp(n->ncmd.args->narg.text, "jobs") == 0
4651 ) {
Denys Vlasenkoe56f22a2009-07-24 00:16:59 +02004652 TRACE(("Job hack\n"));
Denys Vlasenko844f9902009-09-23 03:25:52 +02004653 /* "jobs": we do not want to clear job list for it,
4654 * instead we remove only _its_ own_ job from job list.
4655 * This makes "jobs .... | cat" more useful.
4656 */
Denys Vlasenkoe56f22a2009-07-24 00:16:59 +02004657 freejob(curjob);
4658 return;
4659 }
4660#endif
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004661 for (jp = curjob; jp; jp = jp->prev_job)
4662 freejob(jp);
4663 jobless = 0;
4664}
4665
Denis Vlasenkobdc406d2007-07-15 01:13:25 +00004666/* Called after fork(), in parent */
Denis Vlasenko85c24712008-03-17 09:04:04 +00004667#if !JOBS
4668#define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
4669#endif
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004670static void
4671forkparent(struct job *jp, union node *n, int mode, pid_t pid)
4672{
4673 TRACE(("In parent shell: child = %d\n", pid));
4674 if (!jp) {
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00004675 while (jobless && dowait(DOWAIT_NONBLOCK, NULL) > 0)
4676 continue;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004677 jobless++;
4678 return;
4679 }
4680#if JOBS
4681 if (mode != FORK_NOJOB && jp->jobctl) {
4682 int pgrp;
4683
4684 if (jp->nprocs == 0)
4685 pgrp = pid;
4686 else
4687 pgrp = jp->ps[0].pid;
4688 /* This can fail because we are doing it in the child also */
4689 setpgid(pid, pgrp);
4690 }
4691#endif
4692 if (mode == FORK_BG) {
4693 backgndpid = pid; /* set $! */
4694 set_curjob(jp, CUR_RUNNING);
4695 }
4696 if (jp) {
4697 struct procstat *ps = &jp->ps[jp->nprocs++];
4698 ps->pid = pid;
4699 ps->status = -1;
4700 ps->cmd = nullstr;
4701#if JOBS
Denis Vlasenkob07a4962008-06-22 13:16:23 +00004702 if (doing_jobctl && n)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004703 ps->cmd = commandtext(n);
4704#endif
4705 }
4706}
4707
4708static int
4709forkshell(struct job *jp, union node *n, int mode)
4710{
4711 int pid;
4712
4713 TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
4714 pid = fork();
4715 if (pid < 0) {
4716 TRACE(("Fork failed, errno=%d", errno));
4717 if (jp)
4718 freejob(jp);
Denis Vlasenkofa0b56d2008-07-01 16:09:07 +00004719 ash_msg_and_raise_error("can't fork");
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004720 }
Denys Vlasenko76ace252009-10-12 15:25:01 +02004721 if (pid == 0) {
4722 CLEAR_RANDOM_T(&random_gen); /* or else $RANDOM repeats in child */
Denys Vlasenkoe56f22a2009-07-24 00:16:59 +02004723 forkchild(jp, n, mode);
Denys Vlasenko76ace252009-10-12 15:25:01 +02004724 } else {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004725 forkparent(jp, n, mode, pid);
Denys Vlasenko76ace252009-10-12 15:25:01 +02004726 }
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004727 return pid;
4728}
4729
4730/*
4731 * Wait for job to finish.
4732 *
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004733 * Under job control we have the problem that while a child process
4734 * is running interrupts generated by the user are sent to the child
4735 * but not to the shell. This means that an infinite loop started by
4736 * an interactive user may be hard to kill. With job control turned off,
4737 * an interactive user may place an interactive program inside a loop.
4738 * If the interactive program catches interrupts, the user doesn't want
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004739 * these interrupts to also abort the loop. The approach we take here
4740 * is to have the shell ignore interrupt signals while waiting for a
4741 * foreground process to terminate, and then send itself an interrupt
4742 * signal if the child process was terminated by an interrupt signal.
4743 * Unfortunately, some programs want to do a bit of cleanup and then
4744 * exit on interrupt; unless these processes terminate themselves by
4745 * sending a signal to themselves (instead of calling exit) they will
4746 * confuse this approach.
4747 *
4748 * Called with interrupts off.
4749 */
4750static int
4751waitforjob(struct job *jp)
4752{
4753 int st;
4754
4755 TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004756
4757 INT_OFF;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004758 while (jp->state == JOBRUNNING) {
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004759 /* In non-interactive shells, we _can_ get
4760 * a keyboard signal here and be EINTRed,
4761 * but we just loop back, waiting for command to complete.
4762 *
4763 * man bash:
4764 * "If bash is waiting for a command to complete and receives
4765 * a signal for which a trap has been set, the trap
4766 * will not be executed until the command completes."
4767 *
4768 * Reality is that even if trap is not set, bash
4769 * will not act on the signal until command completes.
4770 * Try this. sleep5intoff.c:
4771 * #include <signal.h>
4772 * #include <unistd.h>
4773 * int main() {
4774 * sigset_t set;
4775 * sigemptyset(&set);
4776 * sigaddset(&set, SIGINT);
4777 * sigaddset(&set, SIGQUIT);
4778 * sigprocmask(SIG_BLOCK, &set, NULL);
4779 * sleep(5);
4780 * return 0;
4781 * }
4782 * $ bash -c './sleep5intoff; echo hi'
4783 * ^C^C^C^C <--- pressing ^C once a second
4784 * $ _
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004785 * $ bash -c './sleep5intoff; echo hi'
4786 * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
4787 * $ _
4788 */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004789 dowait(DOWAIT_BLOCK, jp);
4790 }
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004791 INT_ON;
4792
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004793 st = getstatus(jp);
4794#if JOBS
4795 if (jp->jobctl) {
4796 xtcsetpgrp(ttyfd, rootpid);
4797 /*
4798 * This is truly gross.
4799 * If we're doing job control, then we did a TIOCSPGRP which
4800 * caused us (the shell) to no longer be in the controlling
4801 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
4802 * intuit from the subprocess exit status whether a SIGINT
4803 * occurred, and if so interrupt ourselves. Yuck. - mycroft
4804 */
Denis Vlasenko991a1da2008-02-10 19:02:53 +00004805 if (jp->sigint) /* TODO: do the same with all signals */
4806 raise(SIGINT); /* ... by raise(jp->sig) instead? */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004807 }
4808 if (jp->state == JOBDONE)
4809#endif
4810 freejob(jp);
4811 return st;
4812}
4813
4814/*
4815 * return 1 if there are stopped jobs, otherwise 0
4816 */
4817static int
4818stoppedjobs(void)
4819{
4820 struct job *jp;
4821 int retval;
4822
4823 retval = 0;
4824 if (job_warning)
4825 goto out;
4826 jp = curjob;
4827 if (jp && jp->state == JOBSTOPPED) {
4828 out2str("You have stopped jobs.\n");
4829 job_warning = 2;
4830 retval++;
4831 }
4832 out:
4833 return retval;
4834}
4835
4836
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004837/* ============ redir.c
4838 *
4839 * Code for dealing with input/output redirection.
4840 */
4841
4842#define EMPTY -2 /* marks an unused slot in redirtab */
Denis Vlasenko7d75a962007-11-22 08:16:57 +00004843#define CLOSED -3 /* marks a slot of previously-closed fd */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004844
4845/*
4846 * Open a file in noclobber mode.
4847 * The code was copied from bash.
4848 */
4849static int
4850noclobberopen(const char *fname)
4851{
4852 int r, fd;
4853 struct stat finfo, finfo2;
4854
4855 /*
4856 * If the file exists and is a regular file, return an error
4857 * immediately.
4858 */
4859 r = stat(fname, &finfo);
4860 if (r == 0 && S_ISREG(finfo.st_mode)) {
4861 errno = EEXIST;
4862 return -1;
4863 }
4864
4865 /*
4866 * If the file was not present (r != 0), make sure we open it
4867 * exclusively so that if it is created before we open it, our open
4868 * will fail. Make sure that we do not truncate an existing file.
4869 * Note that we don't turn on O_EXCL unless the stat failed -- if the
4870 * file was not a regular file, we leave O_EXCL off.
4871 */
4872 if (r != 0)
4873 return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
4874 fd = open(fname, O_WRONLY|O_CREAT, 0666);
4875
4876 /* If the open failed, return the file descriptor right away. */
4877 if (fd < 0)
4878 return fd;
4879
4880 /*
4881 * OK, the open succeeded, but the file may have been changed from a
4882 * non-regular file to a regular file between the stat and the open.
4883 * We are assuming that the O_EXCL open handles the case where FILENAME
4884 * did not exist and is symlinked to an existing file between the stat
4885 * and open.
4886 */
4887
4888 /*
4889 * If we can open it and fstat the file descriptor, and neither check
4890 * revealed that it was a regular file, and the file has not been
4891 * replaced, return the file descriptor.
4892 */
4893 if (fstat(fd, &finfo2) == 0 && !S_ISREG(finfo2.st_mode)
4894 && finfo.st_dev == finfo2.st_dev && finfo.st_ino == finfo2.st_ino)
4895 return fd;
4896
4897 /* The file has been replaced. badness. */
4898 close(fd);
4899 errno = EEXIST;
4900 return -1;
4901}
4902
4903/*
4904 * Handle here documents. Normally we fork off a process to write the
4905 * data to a pipe. If the document is short, we can stuff the data in
4906 * the pipe without forking.
4907 */
4908/* openhere needs this forward reference */
4909static void expandhere(union node *arg, int fd);
4910static int
4911openhere(union node *redir)
4912{
4913 int pip[2];
4914 size_t len = 0;
4915
4916 if (pipe(pip) < 0)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00004917 ash_msg_and_raise_error("pipe call failed");
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004918 if (redir->type == NHERE) {
4919 len = strlen(redir->nhere.doc->narg.text);
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00004920 if (len <= PIPE_BUF) {
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004921 full_write(pip[1], redir->nhere.doc->narg.text, len);
4922 goto out;
4923 }
4924 }
4925 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
Denis Vlasenko0b769642008-07-24 07:54:57 +00004926 /* child */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004927 close(pip[0]);
Denis Vlasenkof8535cc2008-12-03 10:36:26 +00004928 ignoresig(SIGINT); //signal(SIGINT, SIG_IGN);
4929 ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
4930 ignoresig(SIGHUP); //signal(SIGHUP, SIG_IGN);
4931 ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004932 signal(SIGPIPE, SIG_DFL);
4933 if (redir->type == NHERE)
4934 full_write(pip[1], redir->nhere.doc->narg.text, len);
Denis Vlasenko0b769642008-07-24 07:54:57 +00004935 else /* NXHERE */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004936 expandhere(redir->nhere.doc, pip[1]);
Bernhard Reutner-Fischer636a1f82008-05-19 09:29:47 +00004937 _exit(EXIT_SUCCESS);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004938 }
4939 out:
4940 close(pip[1]);
4941 return pip[0];
4942}
4943
4944static int
4945openredirect(union node *redir)
4946{
4947 char *fname;
4948 int f;
4949
4950 switch (redir->nfile.type) {
4951 case NFROM:
4952 fname = redir->nfile.expfname;
4953 f = open(fname, O_RDONLY);
4954 if (f < 0)
4955 goto eopen;
4956 break;
4957 case NFROMTO:
4958 fname = redir->nfile.expfname;
4959 f = open(fname, O_RDWR|O_CREAT|O_TRUNC, 0666);
4960 if (f < 0)
4961 goto ecreate;
4962 break;
4963 case NTO:
Denis Vlasenko559691a2008-10-05 18:39:31 +00004964#if ENABLE_ASH_BASH_COMPAT
4965 case NTO2:
4966#endif
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004967 /* Take care of noclobber mode. */
4968 if (Cflag) {
4969 fname = redir->nfile.expfname;
4970 f = noclobberopen(fname);
4971 if (f < 0)
4972 goto ecreate;
4973 break;
4974 }
4975 /* FALLTHROUGH */
4976 case NCLOBBER:
4977 fname = redir->nfile.expfname;
4978 f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
4979 if (f < 0)
4980 goto ecreate;
4981 break;
4982 case NAPPEND:
4983 fname = redir->nfile.expfname;
4984 f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
4985 if (f < 0)
4986 goto ecreate;
4987 break;
4988 default:
4989#if DEBUG
4990 abort();
4991#endif
4992 /* Fall through to eliminate warning. */
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00004993/* Our single caller does this itself */
Denis Vlasenko0b769642008-07-24 07:54:57 +00004994// case NTOFD:
4995// case NFROMFD:
4996// f = -1;
4997// break;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004998 case NHERE:
4999 case NXHERE:
5000 f = openhere(redir);
5001 break;
5002 }
5003
5004 return f;
5005 ecreate:
Bernhard Reutner-Fischera53de7f2008-07-21 13:46:54 +00005006 ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005007 eopen:
Bernhard Reutner-Fischera53de7f2008-07-21 13:46:54 +00005008 ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005009}
5010
5011/*
5012 * Copy a file descriptor to be >= to. Returns -1
5013 * if the source file descriptor is closed, EMPTY if there are no unused
5014 * file descriptors left.
5015 */
Denis Vlasenko5a867312008-07-24 19:46:38 +00005016/* 0x800..00: bit to set in "to" to request dup2 instead of fcntl(F_DUPFD).
5017 * old code was doing close(to) prior to copyfd() to achieve the same */
Denis Vlasenko22f74142008-07-24 22:34:43 +00005018enum {
5019 COPYFD_EXACT = (int)~(INT_MAX),
5020 COPYFD_RESTORE = (int)((unsigned)COPYFD_EXACT >> 1),
5021};
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005022static int
5023copyfd(int from, int to)
5024{
5025 int newfd;
5026
Denis Vlasenko5a867312008-07-24 19:46:38 +00005027 if (to & COPYFD_EXACT) {
5028 to &= ~COPYFD_EXACT;
5029 /*if (from != to)*/
5030 newfd = dup2(from, to);
5031 } else {
5032 newfd = fcntl(from, F_DUPFD, to);
5033 }
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005034 if (newfd < 0) {
5035 if (errno == EMFILE)
5036 return EMPTY;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005037 /* Happens when source fd is not open: try "echo >&99" */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005038 ash_msg_and_raise_error("%d: %m", from);
5039 }
5040 return newfd;
5041}
5042
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005043/* Struct def and variable are moved down to the first usage site */
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005044struct two_fd_t {
5045 int orig, copy;
5046};
Denis Vlasenko0b769642008-07-24 07:54:57 +00005047struct redirtab {
5048 struct redirtab *next;
Denis Vlasenko0b769642008-07-24 07:54:57 +00005049 int nullredirs;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005050 int pair_count;
Denys Vlasenko606291b2009-09-23 23:15:43 +02005051 struct two_fd_t two_fd[];
Denis Vlasenko0b769642008-07-24 07:54:57 +00005052};
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005053#define redirlist (G_var.redirlist)
Denis Vlasenko0b769642008-07-24 07:54:57 +00005054
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005055static int need_to_remember(struct redirtab *rp, int fd)
5056{
5057 int i;
5058
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005059 if (!rp) /* remembering was not requested */
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005060 return 0;
5061
5062 for (i = 0; i < rp->pair_count; i++) {
5063 if (rp->two_fd[i].orig == fd) {
5064 /* already remembered */
5065 return 0;
5066 }
5067 }
5068 return 1;
5069}
5070
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005071/* "hidden" fd is a fd used to read scripts, or a copy of such */
5072static int is_hidden_fd(struct redirtab *rp, int fd)
5073{
5074 int i;
Denis Vlasenko34c73c42008-08-16 11:48:02 +00005075 struct parsefile *pf;
5076
5077 if (fd == -1)
5078 return 0;
5079 pf = g_parsefile;
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005080 while (pf) {
5081 if (fd == pf->fd) {
5082 return 1;
5083 }
5084 pf = pf->prev;
5085 }
5086 if (!rp)
5087 return 0;
5088 fd |= COPYFD_RESTORE;
5089 for (i = 0; i < rp->pair_count; i++) {
5090 if (rp->two_fd[i].copy == fd) {
5091 return 1;
5092 }
5093 }
5094 return 0;
5095}
5096
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005097/*
5098 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
5099 * old file descriptors are stashed away so that the redirection can be
5100 * undone by calling popredir. If the REDIR_BACKQ flag is set, then the
5101 * standard output, and the standard error if it becomes a duplicate of
5102 * stdout, is saved in memory.
5103 */
5104/* flags passed to redirect */
5105#define REDIR_PUSH 01 /* save previous values of file descriptors */
5106#define REDIR_SAVEFD2 03 /* set preverrout */
5107static void
5108redirect(union node *redir, int flags)
5109{
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005110 struct redirtab *sv;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005111 int sv_pos;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005112 int i;
5113 int fd;
5114 int newfd;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005115 int copied_fd2 = -1;
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005116
Denis Vlasenko01631112007-12-16 17:20:38 +00005117 g_nullredirs++;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005118 if (!redir) {
5119 return;
5120 }
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005121
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005122 sv = NULL;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005123 sv_pos = 0;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005124 INT_OFF;
5125 if (flags & REDIR_PUSH) {
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005126 union node *tmp = redir;
5127 do {
5128 sv_pos++;
Denis Vlasenko559691a2008-10-05 18:39:31 +00005129#if ENABLE_ASH_BASH_COMPAT
5130 if (redir->nfile.type == NTO2)
5131 sv_pos++;
5132#endif
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005133 tmp = tmp->nfile.next;
5134 } while (tmp);
5135 sv = ckmalloc(sizeof(*sv) + sv_pos * sizeof(sv->two_fd[0]));
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005136 sv->next = redirlist;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005137 sv->pair_count = sv_pos;
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005138 redirlist = sv;
Denis Vlasenko01631112007-12-16 17:20:38 +00005139 sv->nullredirs = g_nullredirs - 1;
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005140 g_nullredirs = 0;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005141 while (sv_pos > 0) {
5142 sv_pos--;
5143 sv->two_fd[sv_pos].orig = sv->two_fd[sv_pos].copy = EMPTY;
5144 }
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005145 }
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005146
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005147 do {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00005148 fd = redir->nfile.fd;
Denis Vlasenko0b769642008-07-24 07:54:57 +00005149 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005150 int right_fd = redir->ndup.dupfd;
5151 /* redirect from/to same file descriptor? */
5152 if (right_fd == fd)
5153 continue;
5154 /* echo >&10 and 10 is a fd opened to the sh script? */
5155 if (is_hidden_fd(sv, right_fd)) {
5156 errno = EBADF; /* as if it is closed */
5157 ash_msg_and_raise_error("%d: %m", right_fd);
5158 }
Denis Vlasenko0b769642008-07-24 07:54:57 +00005159 newfd = -1;
5160 } else {
5161 newfd = openredirect(redir); /* always >= 0 */
5162 if (fd == newfd) {
5163 /* Descriptor wasn't open before redirect.
5164 * Mark it for close in the future */
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005165 if (need_to_remember(sv, fd)) {
Denis Vlasenko5a867312008-07-24 19:46:38 +00005166 goto remember_to_close;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005167 }
Denis Vlasenko0b769642008-07-24 07:54:57 +00005168 continue;
5169 }
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005170 }
Denis Vlasenko559691a2008-10-05 18:39:31 +00005171#if ENABLE_ASH_BASH_COMPAT
5172 redirect_more:
5173#endif
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005174 if (need_to_remember(sv, fd)) {
Denis Vlasenko0b769642008-07-24 07:54:57 +00005175 /* Copy old descriptor */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005176 i = fcntl(fd, F_DUPFD, 10);
Denis Vlasenko5a867312008-07-24 19:46:38 +00005177/* You'd expect copy to be CLOEXECed. Currently these extra "saved" fds
5178 * are closed in popredir() in the child, preventing them from leaking
5179 * into child. (popredir() also cleans up the mess in case of failures)
5180 */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005181 if (i == -1) {
5182 i = errno;
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005183 if (i != EBADF) {
5184 /* Strange error (e.g. "too many files" EMFILE?) */
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005185 if (newfd >= 0)
5186 close(newfd);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005187 errno = i;
5188 ash_msg_and_raise_error("%d: %m", fd);
5189 /* NOTREACHED */
5190 }
Denis Vlasenko5a867312008-07-24 19:46:38 +00005191 /* EBADF: it is not open - good, remember to close it */
5192 remember_to_close:
5193 i = CLOSED;
Denis Vlasenko22f74142008-07-24 22:34:43 +00005194 } else { /* fd is open, save its copy */
5195 /* "exec fd>&-" should not close fds
5196 * which point to script file(s).
5197 * Force them to be restored afterwards */
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00005198 if (is_hidden_fd(sv, fd))
5199 i |= COPYFD_RESTORE;
Denis Vlasenko22f74142008-07-24 22:34:43 +00005200 }
Denis Vlasenko5a867312008-07-24 19:46:38 +00005201 if (fd == 2)
5202 copied_fd2 = i;
5203 sv->two_fd[sv_pos].orig = fd;
5204 sv->two_fd[sv_pos].copy = i;
5205 sv_pos++;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005206 }
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005207 if (newfd < 0) {
5208 /* NTOFD/NFROMFD: copy redir->ndup.dupfd to fd */
Denis Vlasenko22f74142008-07-24 22:34:43 +00005209 if (redir->ndup.dupfd < 0) { /* "fd>&-" */
Denis Vlasenkob9e70dd2009-03-20 01:24:08 +00005210 /* Don't want to trigger debugging */
5211 if (fd != -1)
5212 close(fd);
Denis Vlasenko5a867312008-07-24 19:46:38 +00005213 } else {
5214 copyfd(redir->ndup.dupfd, fd | COPYFD_EXACT);
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005215 }
Denis Vlasenko5a867312008-07-24 19:46:38 +00005216 } else if (fd != newfd) { /* move newfd to fd */
5217 copyfd(newfd, fd | COPYFD_EXACT);
Denis Vlasenko559691a2008-10-05 18:39:31 +00005218#if ENABLE_ASH_BASH_COMPAT
5219 if (!(redir->nfile.type == NTO2 && fd == 2))
5220#endif
5221 close(newfd);
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005222 }
Denis Vlasenko559691a2008-10-05 18:39:31 +00005223#if ENABLE_ASH_BASH_COMPAT
5224 if (redir->nfile.type == NTO2 && fd == 1) {
5225 /* We already redirected it to fd 1, now copy it to 2 */
5226 newfd = 1;
5227 fd = 2;
5228 goto redirect_more;
5229 }
5230#endif
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00005231 } while ((redir = redir->nfile.next) != NULL);
Denis Vlasenko8d924ec2008-07-24 11:34:27 +00005232
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005233 INT_ON;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005234 if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
5235 preverrout_fd = copied_fd2;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005236}
5237
5238/*
5239 * Undo the effects of the last redirection.
5240 */
5241static void
Denis Vlasenko34c73c42008-08-16 11:48:02 +00005242popredir(int drop, int restore)
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005243{
5244 struct redirtab *rp;
5245 int i;
5246
Denis Vlasenko01631112007-12-16 17:20:38 +00005247 if (--g_nullredirs >= 0)
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005248 return;
5249 INT_OFF;
5250 rp = redirlist;
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005251 for (i = 0; i < rp->pair_count; i++) {
5252 int fd = rp->two_fd[i].orig;
Denis Vlasenko22f74142008-07-24 22:34:43 +00005253 int copy = rp->two_fd[i].copy;
5254 if (copy == CLOSED) {
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005255 if (!drop)
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +00005256 close(fd);
Denis Vlasenko7d75a962007-11-22 08:16:57 +00005257 continue;
5258 }
Denis Vlasenko22f74142008-07-24 22:34:43 +00005259 if (copy != EMPTY) {
Denis Vlasenko34c73c42008-08-16 11:48:02 +00005260 if (!drop || (restore && (copy & COPYFD_RESTORE))) {
Denis Vlasenko22f74142008-07-24 22:34:43 +00005261 copy &= ~COPYFD_RESTORE;
Denis Vlasenko5a867312008-07-24 19:46:38 +00005262 /*close(fd);*/
Denis Vlasenko22f74142008-07-24 22:34:43 +00005263 copyfd(copy, fd | COPYFD_EXACT);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005264 }
Denis Vlasenkob9e70dd2009-03-20 01:24:08 +00005265 close(copy & ~COPYFD_RESTORE);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005266 }
5267 }
5268 redirlist = rp->next;
Denis Vlasenko01631112007-12-16 17:20:38 +00005269 g_nullredirs = rp->nullredirs;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005270 free(rp);
5271 INT_ON;
5272}
5273
5274/*
5275 * Undo all redirections. Called on error or interrupt.
5276 */
5277
5278/*
5279 * Discard all saved file descriptors.
5280 */
5281static void
5282clearredir(int drop)
5283{
5284 for (;;) {
Denis Vlasenko01631112007-12-16 17:20:38 +00005285 g_nullredirs = 0;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005286 if (!redirlist)
5287 break;
Denis Vlasenko34c73c42008-08-16 11:48:02 +00005288 popredir(drop, /*restore:*/ 0);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005289 }
5290}
5291
5292static int
5293redirectsafe(union node *redir, int flags)
5294{
5295 int err;
5296 volatile int saveint;
5297 struct jmploc *volatile savehandler = exception_handler;
5298 struct jmploc jmploc;
5299
5300 SAVE_INT(saveint);
Denis Vlasenko5a867312008-07-24 19:46:38 +00005301 /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
5302 err = setjmp(jmploc.loc); // huh?? was = setjmp(jmploc.loc) * 2;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005303 if (!err) {
5304 exception_handler = &jmploc;
5305 redirect(redir, flags);
5306 }
5307 exception_handler = savehandler;
Denis Vlasenko7f88e342009-03-19 03:36:18 +00005308 if (err && exception_type != EXERROR)
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005309 longjmp(exception_handler->loc, 1);
5310 RESTORE_INT(saveint);
5311 return err;
5312}
5313
5314
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005315/* ============ Routines to expand arguments to commands
5316 *
5317 * We have to deal with backquotes, shell variables, and file metacharacters.
5318 */
5319
Mike Frysinger98c52642009-04-02 10:02:37 +00005320#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00005321static arith_t
5322ash_arith(const char *s)
5323{
5324 arith_eval_hooks_t math_hooks;
5325 arith_t result;
5326 int errcode = 0;
5327
5328 math_hooks.lookupvar = lookupvar;
5329 math_hooks.setvar = setvar;
5330 math_hooks.endofname = endofname;
5331
5332 INT_OFF;
5333 result = arith(s, &errcode, &math_hooks);
5334 if (errcode < 0) {
5335 if (errcode == -3)
5336 ash_msg_and_raise_error("exponent less than 0");
5337 if (errcode == -2)
5338 ash_msg_and_raise_error("divide by zero");
5339 if (errcode == -5)
5340 ash_msg_and_raise_error("expression recursion loop detected");
5341 raise_error_syntax(s);
5342 }
5343 INT_ON;
5344
5345 return result;
5346}
Denis Vlasenko448d30e2008-06-27 00:24:11 +00005347#endif
5348
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005349/*
5350 * expandarg flags
5351 */
5352#define EXP_FULL 0x1 /* perform word splitting & file globbing */
5353#define EXP_TILDE 0x2 /* do normal tilde expansion */
5354#define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
5355#define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
5356#define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
5357#define EXP_RECORD 0x20 /* need to record arguments for ifs breakup */
5358#define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
5359#define EXP_WORD 0x80 /* expand word in parameter expansion */
5360#define EXP_QWORD 0x100 /* expand word in quoted parameter expansion */
5361/*
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005362 * rmescape() flags
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005363 */
5364#define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
5365#define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
5366#define RMESCAPE_QUOTED 0x4 /* Remove CTLESC unless in quotes */
5367#define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
5368#define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
5369
5370/*
5371 * Structure specifying which parts of the string should be searched
5372 * for IFS characters.
5373 */
5374struct ifsregion {
5375 struct ifsregion *next; /* next region in list */
5376 int begoff; /* offset of start of region */
5377 int endoff; /* offset of end of region */
5378 int nulonly; /* search for nul bytes only */
5379};
5380
5381struct arglist {
5382 struct strlist *list;
5383 struct strlist **lastp;
5384};
5385
5386/* output of current string */
5387static char *expdest;
5388/* list of back quote expressions */
5389static struct nodelist *argbackq;
5390/* first struct in list of ifs regions */
5391static struct ifsregion ifsfirst;
5392/* last struct in list */
5393static struct ifsregion *ifslastp;
5394/* holds expanded arg list */
5395static struct arglist exparg;
5396
5397/*
5398 * Our own itoa().
5399 */
5400static int
5401cvtnum(arith_t num)
5402{
5403 int len;
5404
5405 expdest = makestrspace(32, expdest);
Mike Frysinger98c52642009-04-02 10:02:37 +00005406 len = fmtstr(expdest, 32, arith_t_fmt, num);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005407 STADJUST(len, expdest);
5408 return len;
5409}
5410
5411static size_t
5412esclen(const char *start, const char *p)
5413{
5414 size_t esc = 0;
5415
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005416 while (p > start && (unsigned char)*--p == CTLESC) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005417 esc++;
5418 }
5419 return esc;
5420}
5421
5422/*
5423 * Remove any CTLESC characters from a string.
5424 */
5425static char *
Denys Vlasenkob6c84342009-08-29 20:23:20 +02005426rmescapes(char *str, int flag)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005427{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00005428 static const char qchars[] ALIGN1 = { CTLESC, CTLQUOTEMARK, '\0' };
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00005429
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005430 char *p, *q, *r;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005431 unsigned inquotes;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005432 unsigned protect_against_glob;
5433 unsigned globbing;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005434
5435 p = strpbrk(str, qchars);
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005436 if (!p)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005437 return str;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005438
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005439 q = p;
5440 r = str;
5441 if (flag & RMESCAPE_ALLOC) {
5442 size_t len = p - str;
5443 size_t fulllen = len + strlen(p) + 1;
5444
5445 if (flag & RMESCAPE_GROW) {
5446 r = makestrspace(fulllen, expdest);
5447 } else if (flag & RMESCAPE_HEAP) {
5448 r = ckmalloc(fulllen);
5449 } else {
5450 r = stalloc(fulllen);
5451 }
5452 q = r;
5453 if (len > 0) {
Denis Vlasenko29eb3592008-05-18 14:06:08 +00005454 q = (char *)memcpy(q, str, len) + len;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005455 }
5456 }
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005457
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005458 inquotes = (flag & RMESCAPE_QUOTED) ^ RMESCAPE_QUOTED;
5459 globbing = flag & RMESCAPE_GLOB;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005460 protect_against_glob = globbing;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005461 while (*p) {
5462 if (*p == CTLQUOTEMARK) {
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005463// TODO: if no RMESCAPE_QUOTED in flags, inquotes never becomes 0
5464// (alternates between RMESCAPE_QUOTED and ~RMESCAPE_QUOTED). Is it ok?
5465// Note: both inquotes and protect_against_glob only affect whether
5466// CTLESC,<ch> gets converted to <ch> or to \<ch>
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005467 inquotes = ~inquotes;
5468 p++;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005469 protect_against_glob = globbing;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005470 continue;
5471 }
5472 if (*p == '\\') {
5473 /* naked back slash */
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005474 protect_against_glob = 0;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005475 goto copy;
5476 }
5477 if (*p == CTLESC) {
5478 p++;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005479 if (protect_against_glob && inquotes && *p != '/') {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005480 *q++ = '\\';
5481 }
5482 }
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005483 protect_against_glob = globbing;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005484 copy:
5485 *q++ = *p++;
5486 }
5487 *q = '\0';
5488 if (flag & RMESCAPE_GROW) {
5489 expdest = r;
5490 STADJUST(q - r + 1, expdest);
5491 }
5492 return r;
5493}
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005494#define pmatch(a, b) !fnmatch((a), (b), 0)
5495
5496/*
5497 * Prepare a pattern for a expmeta (internal glob(3)) call.
5498 *
5499 * Returns an stalloced string.
5500 */
5501static char *
5502preglob(const char *pattern, int quoted, int flag)
5503{
5504 flag |= RMESCAPE_GLOB;
5505 if (quoted) {
5506 flag |= RMESCAPE_QUOTED;
5507 }
Denys Vlasenkob6c84342009-08-29 20:23:20 +02005508 return rmescapes((char *)pattern, flag);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005509}
5510
5511/*
5512 * Put a string on the stack.
5513 */
5514static void
5515memtodest(const char *p, size_t len, int syntax, int quotes)
5516{
5517 char *q = expdest;
5518
Denys Vlasenkob6c84342009-08-29 20:23:20 +02005519 q = makestrspace(quotes ? len * 2 : len, q);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005520
5521 while (len--) {
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00005522 int c = signed_char2int(*p++);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005523 if (!c)
5524 continue;
Denys Vlasenkob6c84342009-08-29 20:23:20 +02005525 if (quotes) {
5526 int n = SIT(c, syntax);
5527 if (n == CCTL || n == CBACK)
5528 USTPUTC(CTLESC, q);
5529 }
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005530 USTPUTC(c, q);
5531 }
5532
5533 expdest = q;
5534}
5535
5536static void
5537strtodest(const char *p, int syntax, int quotes)
5538{
5539 memtodest(p, strlen(p), syntax, quotes);
5540}
5541
5542/*
5543 * Record the fact that we have to scan this region of the
5544 * string for IFS characters.
5545 */
5546static void
5547recordregion(int start, int end, int nulonly)
5548{
5549 struct ifsregion *ifsp;
5550
5551 if (ifslastp == NULL) {
5552 ifsp = &ifsfirst;
5553 } else {
5554 INT_OFF;
Denis Vlasenko597906c2008-02-20 16:38:54 +00005555 ifsp = ckzalloc(sizeof(*ifsp));
5556 /*ifsp->next = NULL; - ckzalloc did it */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005557 ifslastp->next = ifsp;
5558 INT_ON;
5559 }
5560 ifslastp = ifsp;
5561 ifslastp->begoff = start;
5562 ifslastp->endoff = end;
5563 ifslastp->nulonly = nulonly;
5564}
5565
5566static void
5567removerecordregions(int endoff)
5568{
5569 if (ifslastp == NULL)
5570 return;
5571
5572 if (ifsfirst.endoff > endoff) {
5573 while (ifsfirst.next != NULL) {
5574 struct ifsregion *ifsp;
5575 INT_OFF;
5576 ifsp = ifsfirst.next->next;
5577 free(ifsfirst.next);
5578 ifsfirst.next = ifsp;
5579 INT_ON;
5580 }
5581 if (ifsfirst.begoff > endoff)
5582 ifslastp = NULL;
5583 else {
5584 ifslastp = &ifsfirst;
5585 ifsfirst.endoff = endoff;
5586 }
5587 return;
5588 }
5589
5590 ifslastp = &ifsfirst;
5591 while (ifslastp->next && ifslastp->next->begoff < endoff)
5592 ifslastp=ifslastp->next;
5593 while (ifslastp->next != NULL) {
5594 struct ifsregion *ifsp;
5595 INT_OFF;
5596 ifsp = ifslastp->next->next;
5597 free(ifslastp->next);
5598 ifslastp->next = ifsp;
5599 INT_ON;
5600 }
5601 if (ifslastp->endoff > endoff)
5602 ifslastp->endoff = endoff;
5603}
5604
5605static char *
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005606exptilde(char *startp, char *p, int flags)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005607{
5608 char c;
5609 char *name;
5610 struct passwd *pw;
5611 const char *home;
Denys Vlasenko1166d7b2009-09-16 16:20:31 +02005612 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005613 int startloc;
5614
5615 name = p + 1;
5616
5617 while ((c = *++p) != '\0') {
5618 switch (c) {
5619 case CTLESC:
5620 return startp;
5621 case CTLQUOTEMARK:
5622 return startp;
5623 case ':':
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005624 if (flags & EXP_VARTILDE)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005625 goto done;
5626 break;
5627 case '/':
5628 case CTLENDVAR:
5629 goto done;
5630 }
5631 }
5632 done:
5633 *p = '\0';
5634 if (*name == '\0') {
5635 home = lookupvar(homestr);
5636 } else {
5637 pw = getpwnam(name);
5638 if (pw == NULL)
5639 goto lose;
5640 home = pw->pw_dir;
5641 }
5642 if (!home || !*home)
5643 goto lose;
5644 *p = c;
5645 startloc = expdest - (char *)stackblock();
5646 strtodest(home, SQSYNTAX, quotes);
5647 recordregion(startloc, expdest - (char *)stackblock(), 0);
5648 return p;
5649 lose:
5650 *p = c;
5651 return startp;
5652}
5653
5654/*
5655 * Execute a command inside back quotes. If it's a builtin command, we
5656 * want to save its output in a block obtained from malloc. Otherwise
5657 * we fork off a subprocess and get the output of the command via a pipe.
5658 * Should be called with interrupts off.
5659 */
5660struct backcmd { /* result of evalbackcmd */
5661 int fd; /* file descriptor to read from */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005662 int nleft; /* number of chars in buffer */
Denis Vlasenkob07a4962008-06-22 13:16:23 +00005663 char *buf; /* buffer */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005664 struct job *jp; /* job structure for command */
5665};
5666
5667/* These forward decls are needed to use "eval" code for backticks handling: */
Denis Vlasenko448d30e2008-06-27 00:24:11 +00005668static uint8_t back_exitstatus; /* exit status of backquoted command */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005669#define EV_EXIT 01 /* exit after evaluating tree */
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02005670static void evaltree(union node *, int);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005671
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02005672static void FAST_FUNC
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005673evalbackcmd(union node *n, struct backcmd *result)
5674{
5675 int saveherefd;
5676
5677 result->fd = -1;
5678 result->buf = NULL;
5679 result->nleft = 0;
5680 result->jp = NULL;
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00005681 if (n == NULL)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005682 goto out;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005683
5684 saveherefd = herefd;
5685 herefd = -1;
5686
5687 {
5688 int pip[2];
5689 struct job *jp;
5690
5691 if (pipe(pip) < 0)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00005692 ash_msg_and_raise_error("pipe call failed");
Denis Vlasenko68404f12008-03-17 09:00:54 +00005693 jp = makejob(/*n,*/ 1);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005694 if (forkshell(jp, n, FORK_NOJOB) == 0) {
5695 FORCE_INT_ON;
5696 close(pip[0]);
5697 if (pip[1] != 1) {
Denis Vlasenko5a867312008-07-24 19:46:38 +00005698 /*close(1);*/
5699 copyfd(pip[1], 1 | COPYFD_EXACT);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005700 close(pip[1]);
5701 }
5702 eflag = 0;
5703 evaltree(n, EV_EXIT); /* actually evaltreenr... */
5704 /* NOTREACHED */
5705 }
5706 close(pip[1]);
5707 result->fd = pip[0];
5708 result->jp = jp;
5709 }
5710 herefd = saveherefd;
5711 out:
5712 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
5713 result->fd, result->buf, result->nleft, result->jp));
5714}
5715
5716/*
5717 * Expand stuff in backwards quotes.
5718 */
5719static void
5720expbackq(union node *cmd, int quoted, int quotes)
5721{
5722 struct backcmd in;
5723 int i;
5724 char buf[128];
5725 char *p;
5726 char *dest;
5727 int startloc;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00005728 int syntax = quoted ? DQSYNTAX : BASESYNTAX;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005729 struct stackmark smark;
5730
5731 INT_OFF;
5732 setstackmark(&smark);
5733 dest = expdest;
5734 startloc = dest - (char *)stackblock();
5735 grabstackstr(dest);
5736 evalbackcmd(cmd, &in);
5737 popstackmark(&smark);
5738
5739 p = in.buf;
5740 i = in.nleft;
5741 if (i == 0)
5742 goto read;
5743 for (;;) {
5744 memtodest(p, i, syntax, quotes);
5745 read:
5746 if (in.fd < 0)
5747 break;
Denis Vlasenkoe376d452008-02-20 22:23:24 +00005748 i = nonblock_safe_read(in.fd, buf, sizeof(buf));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005749 TRACE(("expbackq: read returns %d\n", i));
5750 if (i <= 0)
5751 break;
5752 p = buf;
5753 }
5754
Denis Vlasenko60818682007-09-28 22:07:23 +00005755 free(in.buf);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005756 if (in.fd >= 0) {
5757 close(in.fd);
5758 back_exitstatus = waitforjob(in.jp);
5759 }
5760 INT_ON;
5761
5762 /* Eat all trailing newlines */
5763 dest = expdest;
5764 for (; dest > (char *)stackblock() && dest[-1] == '\n';)
5765 STUNPUTC(dest);
5766 expdest = dest;
5767
5768 if (quoted == 0)
5769 recordregion(startloc, dest - (char *)stackblock(), 0);
5770 TRACE(("evalbackq: size=%d: \"%.*s\"\n",
5771 (dest - (char *)stackblock()) - startloc,
5772 (dest - (char *)stackblock()) - startloc,
5773 stackblock() + startloc));
5774}
5775
Mike Frysinger98c52642009-04-02 10:02:37 +00005776#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005777/*
5778 * Expand arithmetic expression. Backup to start of expression,
5779 * evaluate, place result in (backed up) result, adjust string position.
5780 */
5781static void
5782expari(int quotes)
5783{
5784 char *p, *start;
5785 int begoff;
5786 int flag;
5787 int len;
5788
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00005789 /* ifsfree(); */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005790
5791 /*
5792 * This routine is slightly over-complicated for
5793 * efficiency. Next we scan backwards looking for the
5794 * start of arithmetic.
5795 */
5796 start = stackblock();
5797 p = expdest - 1;
5798 *p = '\0';
5799 p--;
5800 do {
5801 int esc;
5802
5803 while (*p != CTLARI) {
5804 p--;
5805#if DEBUG
5806 if (p < start) {
5807 ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
5808 }
5809#endif
5810 }
5811
5812 esc = esclen(start, p);
5813 if (!(esc % 2)) {
5814 break;
5815 }
5816
5817 p -= esc + 1;
5818 } while (1);
5819
5820 begoff = p - start;
5821
5822 removerecordregions(begoff);
5823
5824 flag = p[1];
5825
5826 expdest = p;
5827
5828 if (quotes)
Denys Vlasenkob6c84342009-08-29 20:23:20 +02005829 rmescapes(p + 2, 0);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005830
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +00005831 len = cvtnum(ash_arith(p + 2));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005832
5833 if (flag != '"')
5834 recordregion(begoff, begoff + len, 0);
5835}
5836#endif
5837
5838/* argstr needs it */
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005839static char *evalvar(char *p, int flags, struct strlist *var_str_list);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005840
5841/*
5842 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
5843 * characters to allow for further processing. Otherwise treat
5844 * $@ like $* since no splitting will be performed.
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00005845 *
5846 * var_str_list (can be NULL) is a list of "VAR=val" strings which take precedence
5847 * over shell varables. Needed for "A=a B=$A; echo $B" case - we use it
5848 * for correct expansion of "B=$A" word.
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005849 */
5850static void
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005851argstr(char *p, int flags, struct strlist *var_str_list)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005852{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00005853 static const char spclchars[] ALIGN1 = {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005854 '=',
5855 ':',
5856 CTLQUOTEMARK,
5857 CTLENDVAR,
5858 CTLESC,
5859 CTLVAR,
5860 CTLBACKQ,
5861 CTLBACKQ | CTLQUOTE,
Mike Frysinger98c52642009-04-02 10:02:37 +00005862#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005863 CTLENDARI,
5864#endif
5865 0
5866 };
5867 const char *reject = spclchars;
5868 int c;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005869 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR); /* do CTLESC */
5870 int breakall = flags & EXP_WORD;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005871 int inquotes;
5872 size_t length;
5873 int startloc;
5874
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005875 if (!(flags & EXP_VARTILDE)) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005876 reject += 2;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005877 } else if (flags & EXP_VARTILDE2) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005878 reject++;
5879 }
5880 inquotes = 0;
5881 length = 0;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005882 if (flags & EXP_TILDE) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005883 char *q;
5884
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005885 flags &= ~EXP_TILDE;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005886 tilde:
5887 q = p;
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005888 if (*q == CTLESC && (flags & EXP_QWORD))
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005889 q++;
5890 if (*q == '~')
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005891 p = exptilde(p, q, flags);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005892 }
5893 start:
5894 startloc = expdest - (char *)stackblock();
5895 for (;;) {
5896 length += strcspn(p + length, reject);
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005897 c = (unsigned char) p[length];
5898 if (c) {
5899 if (!(c & 0x80)
Mike Frysinger98c52642009-04-02 10:02:37 +00005900#if ENABLE_SH_MATH_SUPPORT
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005901 || c == CTLENDARI
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005902#endif
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005903 ) {
5904 /* c == '=' || c == ':' || c == CTLENDARI */
5905 length++;
5906 }
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005907 }
5908 if (length > 0) {
5909 int newloc;
5910 expdest = stack_nputstr(p, length, expdest);
5911 newloc = expdest - (char *)stackblock();
5912 if (breakall && !inquotes && newloc > startloc) {
5913 recordregion(startloc, newloc, 0);
5914 }
5915 startloc = newloc;
5916 }
5917 p += length + 1;
5918 length = 0;
5919
5920 switch (c) {
5921 case '\0':
5922 goto breakloop;
5923 case '=':
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005924 if (flags & EXP_VARTILDE2) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005925 p--;
5926 continue;
5927 }
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005928 flags |= EXP_VARTILDE2;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005929 reject++;
5930 /* fall through */
5931 case ':':
5932 /*
5933 * sort of a hack - expand tildes in variable
5934 * assignments (after the first '=' and after ':'s).
5935 */
5936 if (*--p == '~') {
5937 goto tilde;
5938 }
5939 continue;
5940 }
5941
5942 switch (c) {
5943 case CTLENDVAR: /* ??? */
5944 goto breakloop;
5945 case CTLQUOTEMARK:
5946 /* "$@" syntax adherence hack */
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005947 if (!inquotes
5948 && memcmp(p, dolatstr, 4) == 0
5949 && ( p[4] == CTLQUOTEMARK
5950 || (p[4] == CTLENDVAR && p[5] == CTLQUOTEMARK)
5951 )
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005952 ) {
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005953 p = evalvar(p + 1, flags, /* var_str_list: */ NULL) + 1;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005954 goto start;
5955 }
5956 inquotes = !inquotes;
5957 addquote:
5958 if (quotes) {
5959 p--;
5960 length++;
5961 startloc++;
5962 }
5963 break;
5964 case CTLESC:
5965 startloc++;
5966 length++;
5967 goto addquote;
5968 case CTLVAR:
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005969 p = evalvar(p, flags, var_str_list);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005970 goto start;
5971 case CTLBACKQ:
Denys Vlasenkob0d63382009-09-16 16:18:32 +02005972 c = '\0';
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005973 case CTLBACKQ|CTLQUOTE:
5974 expbackq(argbackq->n, c, quotes);
5975 argbackq = argbackq->next;
5976 goto start;
Mike Frysinger98c52642009-04-02 10:02:37 +00005977#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005978 case CTLENDARI:
5979 p--;
5980 expari(quotes);
5981 goto start;
5982#endif
5983 }
5984 }
5985 breakloop:
5986 ;
5987}
5988
5989static char *
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00005990scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM, char *str, int quotes,
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005991 int zero)
5992{
Denis Vlasenkoc7131c32008-04-14 01:59:53 +00005993// This commented out code was added by James Simmons <jsimmons@infradead.org>
5994// as part of a larger change when he added support for ${var/a/b}.
5995// However, it broke # and % operators:
5996//
5997//var=ababcdcd
5998// ok bad
5999//echo ${var#ab} abcdcd abcdcd
6000//echo ${var##ab} abcdcd abcdcd
6001//echo ${var#a*b} abcdcd ababcdcd (!)
6002//echo ${var##a*b} cdcd cdcd
6003//echo ${var#?} babcdcd ababcdcd (!)
6004//echo ${var##?} babcdcd babcdcd
6005//echo ${var#*} ababcdcd babcdcd (!)
6006//echo ${var##*}
6007//echo ${var%cd} ababcd ababcd
6008//echo ${var%%cd} ababcd abab (!)
6009//echo ${var%c*d} ababcd ababcd
6010//echo ${var%%c*d} abab ababcdcd (!)
6011//echo ${var%?} ababcdc ababcdc
6012//echo ${var%%?} ababcdc ababcdcd (!)
6013//echo ${var%*} ababcdcd ababcdcd
6014//echo ${var%%*}
6015//
6016// Commenting it back out helped. Remove it completely if it really
6017// is not needed.
6018
6019 char *loc, *loc2; //, *full;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006020 char c;
6021
6022 loc = startp;
6023 loc2 = rmesc;
6024 do {
Denis Vlasenkoc7131c32008-04-14 01:59:53 +00006025 int match; // = strlen(str);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006026 const char *s = loc2;
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006027
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006028 c = *loc2;
6029 if (zero) {
6030 *loc2 = '\0';
6031 s = rmesc;
6032 }
Denis Vlasenkoc7131c32008-04-14 01:59:53 +00006033 match = pmatch(str, s); // this line was deleted
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006034
Denis Vlasenkoc7131c32008-04-14 01:59:53 +00006035// // chop off end if its '*'
6036// full = strrchr(str, '*');
6037// if (full && full != str)
6038// match--;
6039//
6040// // If str starts with '*' replace with s.
6041// if ((*str == '*') && strlen(s) >= match) {
6042// full = xstrdup(s);
6043// strncpy(full+strlen(s)-match+1, str+1, match-1);
6044// } else
6045// full = xstrndup(str, match);
6046// match = strncmp(s, full, strlen(full));
6047// free(full);
6048//
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006049 *loc2 = c;
Denis Vlasenkoc7131c32008-04-14 01:59:53 +00006050 if (match) // if (!match)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006051 return loc;
6052 if (quotes && *loc == CTLESC)
6053 loc++;
6054 loc++;
6055 loc2++;
6056 } while (c);
6057 return 0;
6058}
6059
6060static char *
6061scanright(char *startp, char *rmesc, char *rmescend, char *str, int quotes,
6062 int zero)
6063{
6064 int esc = 0;
6065 char *loc;
6066 char *loc2;
6067
6068 for (loc = str - 1, loc2 = rmescend; loc >= startp; loc2--) {
6069 int match;
6070 char c = *loc2;
6071 const char *s = loc2;
6072 if (zero) {
6073 *loc2 = '\0';
6074 s = rmesc;
6075 }
6076 match = pmatch(str, s);
6077 *loc2 = c;
6078 if (match)
6079 return loc;
6080 loc--;
6081 if (quotes) {
6082 if (--esc < 0) {
6083 esc = esclen(startp, loc);
6084 }
6085 if (esc % 2) {
6086 esc--;
6087 loc--;
6088 }
6089 }
6090 }
6091 return 0;
6092}
6093
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00006094static void varunset(const char *, const char *, const char *, int) NORETURN;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006095static void
6096varunset(const char *end, const char *var, const char *umsg, int varflags)
6097{
6098 const char *msg;
6099 const char *tail;
6100
6101 tail = nullstr;
6102 msg = "parameter not set";
6103 if (umsg) {
6104 if (*end == CTLENDVAR) {
6105 if (varflags & VSNUL)
6106 tail = " or null";
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00006107 } else {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006108 msg = umsg;
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00006109 }
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006110 }
6111 ash_msg_and_raise_error("%.*s: %s%s", end - var - 1, var, msg, tail);
6112}
6113
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006114#if ENABLE_ASH_BASH_COMPAT
6115static char *
6116parse_sub_pattern(char *arg, int inquotes)
6117{
6118 char *idx, *repl = NULL;
6119 unsigned char c;
6120
Denis Vlasenko2659c632008-06-14 06:04:59 +00006121 idx = arg;
6122 while (1) {
6123 c = *arg;
6124 if (!c)
6125 break;
6126 if (c == '/') {
6127 /* Only the first '/' seen is our separator */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006128 if (!repl) {
Denis Vlasenko2659c632008-06-14 06:04:59 +00006129 repl = idx + 1;
6130 c = '\0';
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006131 }
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006132 }
Denis Vlasenko2659c632008-06-14 06:04:59 +00006133 *idx++ = c;
6134 if (!inquotes && c == '\\' && arg[1] == '\\')
6135 arg++; /* skip both \\, not just first one */
6136 arg++;
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006137 }
Denis Vlasenko29038c02008-06-14 06:14:02 +00006138 *idx = c; /* NUL */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006139
6140 return repl;
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006141}
6142#endif /* ENABLE_ASH_BASH_COMPAT */
6143
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006144static const char *
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006145subevalvar(char *p, char *str, int strloc, int subtype,
6146 int startloc, int varflags, int quotes, struct strlist *var_str_list)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006147{
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006148 struct nodelist *saveargbackq = argbackq;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006149 char *startp;
6150 char *loc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006151 char *rmesc, *rmescend;
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00006152 IF_ASH_BASH_COMPAT(char *repl = NULL;)
6153 IF_ASH_BASH_COMPAT(char null = '\0';)
6154 IF_ASH_BASH_COMPAT(int pos, len, orig_len;)
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006155 int saveherefd = herefd;
6156 int amount, workloc, resetloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006157 int zero;
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006158 char *(*scan)(char*, char*, char*, char*, int, int);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006159
6160 herefd = -1;
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006161 argstr(p, (subtype != VSASSIGN && subtype != VSQUESTION) ? EXP_CASE : 0,
6162 var_str_list);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006163 STPUTC('\0', expdest);
6164 herefd = saveherefd;
6165 argbackq = saveargbackq;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00006166 startp = (char *)stackblock() + startloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006167
6168 switch (subtype) {
6169 case VSASSIGN:
6170 setvar(str, startp, 0);
6171 amount = startp - expdest;
6172 STADJUST(amount, expdest);
6173 return startp;
6174
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006175#if ENABLE_ASH_BASH_COMPAT
6176 case VSSUBSTR:
6177 loc = str = stackblock() + strloc;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006178 /* Read POS in ${var:POS:LEN} */
6179 pos = atoi(loc); /* number(loc) errors out on "1:4" */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006180 len = str - startp - 1;
6181
6182 /* *loc != '\0', guaranteed by parser */
6183 if (quotes) {
6184 char *ptr;
6185
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006186 /* Adjust the length by the number of escapes */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006187 for (ptr = startp; ptr < (str - 1); ptr++) {
Denis Vlasenkod6855d12008-09-27 14:03:25 +00006188 if (*ptr == CTLESC) {
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006189 len--;
6190 ptr++;
6191 }
6192 }
6193 }
6194 orig_len = len;
6195
6196 if (*loc++ == ':') {
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006197 /* ${var::LEN} */
6198 len = number(loc);
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006199 } else {
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006200 /* Skip POS in ${var:POS:LEN} */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006201 len = orig_len;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006202 while (*loc && *loc != ':') {
6203 /* TODO?
6204 * bash complains on: var=qwe; echo ${var:1a:123}
6205 if (!isdigit(*loc))
6206 ash_msg_and_raise_error(msg_illnum, str);
6207 */
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006208 loc++;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006209 }
6210 if (*loc++ == ':') {
6211 len = number(loc);
6212 }
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006213 }
6214 if (pos >= orig_len) {
6215 pos = 0;
6216 len = 0;
6217 }
6218 if (len > (orig_len - pos))
6219 len = orig_len - pos;
6220
6221 for (str = startp; pos; str++, pos--) {
6222 if (quotes && *str == CTLESC)
6223 str++;
6224 }
6225 for (loc = startp; len; len--) {
6226 if (quotes && *str == CTLESC)
6227 *loc++ = *str++;
6228 *loc++ = *str++;
6229 }
6230 *loc = '\0';
6231 amount = loc - expdest;
6232 STADJUST(amount, expdest);
6233 return loc;
6234#endif
6235
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006236 case VSQUESTION:
6237 varunset(p, str, startp, varflags);
6238 /* NOTREACHED */
6239 }
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006240 resetloc = expdest - (char *)stackblock();
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006241
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006242 /* We'll comeback here if we grow the stack while handling
6243 * a VSREPLACE or VSREPLACEALL, since our pointers into the
6244 * stack will need rebasing, and we'll need to remove our work
6245 * areas each time
6246 */
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00006247 IF_ASH_BASH_COMPAT(restart:)
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006248
6249 amount = expdest - ((char *)stackblock() + resetloc);
6250 STADJUST(-amount, expdest);
Denis Vlasenko29eb3592008-05-18 14:06:08 +00006251 startp = (char *)stackblock() + startloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006252
6253 rmesc = startp;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00006254 rmescend = (char *)stackblock() + strloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006255 if (quotes) {
Denys Vlasenkob6c84342009-08-29 20:23:20 +02006256 rmesc = rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006257 if (rmesc != startp) {
6258 rmescend = expdest;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00006259 startp = (char *)stackblock() + startloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006260 }
6261 }
6262 rmescend--;
Denis Vlasenko29eb3592008-05-18 14:06:08 +00006263 str = (char *)stackblock() + strloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006264 preglob(str, varflags & VSQUOTE, 0);
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006265 workloc = expdest - (char *)stackblock();
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006266
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006267#if ENABLE_ASH_BASH_COMPAT
6268 if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
6269 char *idx, *end, *restart_detect;
6270
Denis Vlasenkod6855d12008-09-27 14:03:25 +00006271 if (!repl) {
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006272 repl = parse_sub_pattern(str, varflags & VSQUOTE);
6273 if (!repl)
6274 repl = &null;
6275 }
6276
6277 /* If there's no pattern to match, return the expansion unmolested */
6278 if (*str == '\0')
6279 return 0;
6280
6281 len = 0;
6282 idx = startp;
6283 end = str - 1;
6284 while (idx < end) {
6285 loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
6286 if (!loc) {
6287 /* No match, advance */
6288 restart_detect = stackblock();
6289 STPUTC(*idx, expdest);
6290 if (quotes && *idx == CTLESC) {
6291 idx++;
6292 len++;
6293 STPUTC(*idx, expdest);
6294 }
6295 if (stackblock() != restart_detect)
6296 goto restart;
6297 idx++;
6298 len++;
6299 rmesc++;
6300 continue;
6301 }
6302
6303 if (subtype == VSREPLACEALL) {
6304 while (idx < loc) {
6305 if (quotes && *idx == CTLESC)
6306 idx++;
6307 idx++;
6308 rmesc++;
6309 }
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00006310 } else {
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006311 idx = loc;
Denis Vlasenko81c3a1d2008-12-03 11:59:12 +00006312 }
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006313
6314 for (loc = repl; *loc; loc++) {
6315 restart_detect = stackblock();
6316 STPUTC(*loc, expdest);
6317 if (stackblock() != restart_detect)
6318 goto restart;
6319 len++;
6320 }
6321
6322 if (subtype == VSREPLACE) {
6323 while (*idx) {
6324 restart_detect = stackblock();
6325 STPUTC(*idx, expdest);
6326 if (stackblock() != restart_detect)
6327 goto restart;
6328 len++;
6329 idx++;
6330 }
6331 break;
6332 }
6333 }
6334
6335 /* We've put the replaced text into a buffer at workloc, now
6336 * move it to the right place and adjust the stack.
6337 */
6338 startp = stackblock() + startloc;
6339 STPUTC('\0', expdest);
6340 memmove(startp, stackblock() + workloc, len);
6341 startp[len++] = '\0';
6342 amount = expdest - ((char *)stackblock() + startloc + len - 1);
6343 STADJUST(-amount, expdest);
6344 return startp;
6345 }
6346#endif /* ENABLE_ASH_BASH_COMPAT */
6347
6348 subtype -= VSTRIMRIGHT;
6349#if DEBUG
6350 if (subtype < 0 || subtype > 7)
6351 abort();
6352#endif
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006353 /* zero = subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX */
6354 zero = subtype >> 1;
6355 /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
6356 scan = (subtype & 1) ^ zero ? scanleft : scanright;
6357
6358 loc = scan(startp, rmesc, rmescend, str, quotes, zero);
6359 if (loc) {
6360 if (zero) {
6361 memmove(startp, loc, str - loc);
6362 loc = startp + (str - loc) - 1;
6363 }
6364 *loc = '\0';
6365 amount = loc - expdest;
6366 STADJUST(amount, expdest);
6367 }
6368 return loc;
6369}
6370
6371/*
6372 * Add the value of a specialized variable to the stack string.
Denys Vlasenko4d8873f2009-10-04 03:14:41 +02006373 * name parameter (examples):
6374 * ash -c 'echo $1' name:'1='
6375 * ash -c 'echo $qwe' name:'qwe='
6376 * ash -c 'echo $$' name:'$='
6377 * ash -c 'echo ${$}' name:'$='
6378 * ash -c 'echo ${$##q}' name:'$=q'
6379 * ash -c 'echo ${#$}' name:'$='
6380 * note: examples with bad shell syntax:
6381 * ash -c 'echo ${#$1}' name:'$=1'
6382 * ash -c 'echo ${#1#}' name:'1=#'
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006383 */
Denys Vlasenkoadf922e2009-10-08 14:35:37 +02006384static NOINLINE ssize_t
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006385varvalue(char *name, int varflags, int flags, struct strlist *var_str_list)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006386{
6387 int num;
Mike Frysinger98c52642009-04-02 10:02:37 +00006388 const char *p;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006389 int i;
6390 int sep = 0;
6391 int sepq = 0;
6392 ssize_t len = 0;
6393 char **ap;
6394 int syntax;
6395 int quoted = varflags & VSQUOTE;
6396 int subtype = varflags & VSTYPE;
Denys Vlasenko1166d7b2009-09-16 16:20:31 +02006397 int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006398
6399 if (quoted && (flags & EXP_FULL))
6400 sep = 1 << CHAR_BIT;
6401
6402 syntax = quoted ? DQSYNTAX : BASESYNTAX;
6403 switch (*name) {
6404 case '$':
6405 num = rootpid;
6406 goto numvar;
6407 case '?':
6408 num = exitstatus;
6409 goto numvar;
6410 case '#':
6411 num = shellparam.nparam;
6412 goto numvar;
6413 case '!':
6414 num = backgndpid;
6415 if (num == 0)
6416 return -1;
6417 numvar:
6418 len = cvtnum(num);
Denys Vlasenko4d8873f2009-10-04 03:14:41 +02006419 goto check_1char_name;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006420 case '-':
Mike Frysinger98c52642009-04-02 10:02:37 +00006421 expdest = makestrspace(NOPTS, expdest);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006422 for (i = NOPTS - 1; i >= 0; i--) {
6423 if (optlist[i]) {
Mike Frysinger98c52642009-04-02 10:02:37 +00006424 USTPUTC(optletters(i), expdest);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006425 len++;
6426 }
6427 }
Denys Vlasenko4d8873f2009-10-04 03:14:41 +02006428 check_1char_name:
6429#if 0
6430 /* handles cases similar to ${#$1} */
6431 if (name[2] != '\0')
6432 raise_error_syntax("bad substitution");
6433#endif
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006434 break;
6435 case '@':
6436 if (sep)
6437 goto param;
6438 /* fall through */
6439 case '*':
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00006440 sep = ifsset() ? signed_char2int(ifsval()[0]) : ' ';
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006441 if (quotes && (SIT(sep, syntax) == CCTL || SIT(sep, syntax) == CBACK))
6442 sepq = 1;
6443 param:
6444 ap = shellparam.p;
6445 if (!ap)
6446 return -1;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006447 while ((p = *ap++) != NULL) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006448 size_t partlen;
6449
6450 partlen = strlen(p);
6451 len += partlen;
6452
6453 if (!(subtype == VSPLUS || subtype == VSLENGTH))
6454 memtodest(p, partlen, syntax, quotes);
6455
6456 if (*ap && sep) {
6457 char *q;
6458
6459 len++;
6460 if (subtype == VSPLUS || subtype == VSLENGTH) {
6461 continue;
6462 }
6463 q = expdest;
6464 if (sepq)
6465 STPUTC(CTLESC, q);
6466 STPUTC(sep, q);
6467 expdest = q;
6468 }
6469 }
6470 return len;
6471 case '0':
6472 case '1':
6473 case '2':
6474 case '3':
6475 case '4':
6476 case '5':
6477 case '6':
6478 case '7':
6479 case '8':
6480 case '9':
Denys Vlasenkoa00329c2009-08-30 20:05:10 +02006481 num = atoi(name); /* number(name) fails on ${N#str} etc */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006482 if (num < 0 || num > shellparam.nparam)
6483 return -1;
6484 p = num ? shellparam.p[num - 1] : arg0;
6485 goto value;
6486 default:
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006487 /* NB: name has form "VAR=..." */
6488
6489 /* "A=a B=$A" case: var_str_list is a list of "A=a" strings
6490 * which should be considered before we check variables. */
6491 if (var_str_list) {
6492 unsigned name_len = (strchrnul(name, '=') - name) + 1;
6493 p = NULL;
6494 do {
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00006495 char *str, *eq;
6496 str = var_str_list->text;
6497 eq = strchr(str, '=');
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006498 if (!eq) /* stop at first non-assignment */
6499 break;
6500 eq++;
Denis Vlasenko6b06cb82008-05-15 21:30:45 +00006501 if (name_len == (unsigned)(eq - str)
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006502 && strncmp(str, name, name_len) == 0) {
6503 p = eq;
6504 /* goto value; - WRONG! */
6505 /* think "A=1 A=2 B=$A" */
6506 }
6507 var_str_list = var_str_list->next;
6508 } while (var_str_list);
6509 if (p)
6510 goto value;
6511 }
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006512 p = lookupvar(name);
6513 value:
6514 if (!p)
6515 return -1;
6516
6517 len = strlen(p);
6518 if (!(subtype == VSPLUS || subtype == VSLENGTH))
6519 memtodest(p, len, syntax, quotes);
6520 return len;
6521 }
6522
6523 if (subtype == VSPLUS || subtype == VSLENGTH)
6524 STADJUST(-len, expdest);
6525 return len;
6526}
6527
6528/*
6529 * Expand a variable, and return a pointer to the next character in the
6530 * input string.
6531 */
6532static char *
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006533evalvar(char *p, int flags, struct strlist *var_str_list)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006534{
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006535 char varflags;
6536 char subtype;
6537 char quoted;
6538 char easy;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006539 char *var;
6540 int patloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006541 int startloc;
6542 ssize_t varlen;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006543
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006544 varflags = (unsigned char) *p++;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006545 subtype = varflags & VSTYPE;
6546 quoted = varflags & VSQUOTE;
6547 var = p;
6548 easy = (!quoted || (*var == '@' && shellparam.nparam));
6549 startloc = expdest - (char *)stackblock();
6550 p = strchr(p, '=') + 1;
6551
6552 again:
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006553 varlen = varvalue(var, varflags, flags, var_str_list);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006554 if (varflags & VSNUL)
6555 varlen--;
6556
6557 if (subtype == VSPLUS) {
6558 varlen = -1 - varlen;
6559 goto vsplus;
6560 }
6561
6562 if (subtype == VSMINUS) {
6563 vsplus:
6564 if (varlen < 0) {
6565 argstr(
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006566 p, flags | EXP_TILDE |
6567 (quoted ? EXP_QWORD : EXP_WORD),
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006568 var_str_list
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006569 );
6570 goto end;
6571 }
6572 if (easy)
6573 goto record;
6574 goto end;
6575 }
6576
6577 if (subtype == VSASSIGN || subtype == VSQUESTION) {
6578 if (varlen < 0) {
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006579 if (subevalvar(p, var, /* strloc: */ 0,
6580 subtype, startloc, varflags,
6581 /* quotes: */ 0,
6582 var_str_list)
6583 ) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006584 varflags &= ~VSNUL;
6585 /*
6586 * Remove any recorded regions beyond
6587 * start of variable
6588 */
6589 removerecordregions(startloc);
6590 goto again;
6591 }
6592 goto end;
6593 }
6594 if (easy)
6595 goto record;
6596 goto end;
6597 }
6598
6599 if (varlen < 0 && uflag)
6600 varunset(p, var, 0, 0);
6601
6602 if (subtype == VSLENGTH) {
6603 cvtnum(varlen > 0 ? varlen : 0);
6604 goto record;
6605 }
6606
6607 if (subtype == VSNORMAL) {
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006608 if (easy)
6609 goto record;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006610 goto end;
6611 }
6612
6613#if DEBUG
6614 switch (subtype) {
6615 case VSTRIMLEFT:
6616 case VSTRIMLEFTMAX:
6617 case VSTRIMRIGHT:
6618 case VSTRIMRIGHTMAX:
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006619#if ENABLE_ASH_BASH_COMPAT
6620 case VSSUBSTR:
6621 case VSREPLACE:
6622 case VSREPLACEALL:
6623#endif
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006624 break;
6625 default:
6626 abort();
6627 }
6628#endif
6629
6630 if (varlen >= 0) {
6631 /*
6632 * Terminate the string and start recording the pattern
6633 * right after it
6634 */
6635 STPUTC('\0', expdest);
6636 patloc = expdest - (char *)stackblock();
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006637 if (0 == subevalvar(p, /* str: */ NULL, patloc, subtype,
6638 startloc, varflags,
Denys Vlasenko1166d7b2009-09-16 16:20:31 +02006639//TODO: | EXP_REDIR too? All other such places do it too
Denys Vlasenkob0d63382009-09-16 16:18:32 +02006640 /* quotes: */ flags & (EXP_FULL | EXP_CASE),
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006641 var_str_list)
6642 ) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006643 int amount = expdest - (
6644 (char *)stackblock() + patloc - 1
6645 );
6646 STADJUST(-amount, expdest);
6647 }
6648 /* Remove any recorded regions beyond start of variable */
6649 removerecordregions(startloc);
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006650 record:
6651 recordregion(startloc, expdest - (char *)stackblock(), quoted);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006652 }
6653
6654 end:
6655 if (subtype != VSNORMAL) { /* skip to end of alternative */
6656 int nesting = 1;
6657 for (;;) {
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006658 char c = *p++;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006659 if (c == CTLESC)
6660 p++;
6661 else if (c == CTLBACKQ || c == (CTLBACKQ|CTLQUOTE)) {
6662 if (varlen >= 0)
6663 argbackq = argbackq->next;
6664 } else if (c == CTLVAR) {
6665 if ((*p++ & VSTYPE) != VSNORMAL)
6666 nesting++;
6667 } else if (c == CTLENDVAR) {
6668 if (--nesting == 0)
6669 break;
6670 }
6671 }
6672 }
6673 return p;
6674}
6675
6676/*
6677 * Break the argument string into pieces based upon IFS and add the
6678 * strings to the argument list. The regions of the string to be
6679 * searched for IFS characters have been stored by recordregion.
6680 */
6681static void
6682ifsbreakup(char *string, struct arglist *arglist)
6683{
6684 struct ifsregion *ifsp;
6685 struct strlist *sp;
6686 char *start;
6687 char *p;
6688 char *q;
6689 const char *ifs, *realifs;
6690 int ifsspc;
6691 int nulonly;
6692
6693 start = string;
6694 if (ifslastp != NULL) {
6695 ifsspc = 0;
6696 nulonly = 0;
6697 realifs = ifsset() ? ifsval() : defifs;
6698 ifsp = &ifsfirst;
6699 do {
6700 p = string + ifsp->begoff;
6701 nulonly = ifsp->nulonly;
6702 ifs = nulonly ? nullstr : realifs;
6703 ifsspc = 0;
6704 while (p < string + ifsp->endoff) {
6705 q = p;
6706 if (*p == CTLESC)
6707 p++;
6708 if (!strchr(ifs, *p)) {
6709 p++;
6710 continue;
6711 }
6712 if (!nulonly)
6713 ifsspc = (strchr(defifs, *p) != NULL);
6714 /* Ignore IFS whitespace at start */
6715 if (q == start && ifsspc) {
6716 p++;
6717 start = p;
6718 continue;
6719 }
6720 *q = '\0';
Denis Vlasenko597906c2008-02-20 16:38:54 +00006721 sp = stzalloc(sizeof(*sp));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006722 sp->text = start;
6723 *arglist->lastp = sp;
6724 arglist->lastp = &sp->next;
6725 p++;
6726 if (!nulonly) {
6727 for (;;) {
6728 if (p >= string + ifsp->endoff) {
6729 break;
6730 }
6731 q = p;
6732 if (*p == CTLESC)
6733 p++;
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +00006734 if (strchr(ifs, *p) == NULL) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006735 p = q;
6736 break;
Denis Vlasenko597906c2008-02-20 16:38:54 +00006737 }
6738 if (strchr(defifs, *p) == NULL) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006739 if (ifsspc) {
6740 p++;
6741 ifsspc = 0;
6742 } else {
6743 p = q;
6744 break;
6745 }
6746 } else
6747 p++;
6748 }
6749 }
6750 start = p;
6751 } /* while */
6752 ifsp = ifsp->next;
6753 } while (ifsp != NULL);
6754 if (nulonly)
6755 goto add;
6756 }
6757
6758 if (!*start)
6759 return;
6760
6761 add:
Denis Vlasenko597906c2008-02-20 16:38:54 +00006762 sp = stzalloc(sizeof(*sp));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006763 sp->text = start;
6764 *arglist->lastp = sp;
6765 arglist->lastp = &sp->next;
6766}
6767
6768static void
6769ifsfree(void)
6770{
6771 struct ifsregion *p;
6772
6773 INT_OFF;
6774 p = ifsfirst.next;
6775 do {
6776 struct ifsregion *ifsp;
6777 ifsp = p->next;
6778 free(p);
6779 p = ifsp;
6780 } while (p);
6781 ifslastp = NULL;
6782 ifsfirst.next = NULL;
6783 INT_ON;
6784}
6785
6786/*
6787 * Add a file name to the list.
6788 */
6789static void
6790addfname(const char *name)
6791{
6792 struct strlist *sp;
6793
Denis Vlasenko597906c2008-02-20 16:38:54 +00006794 sp = stzalloc(sizeof(*sp));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006795 sp->text = ststrdup(name);
6796 *exparg.lastp = sp;
6797 exparg.lastp = &sp->next;
6798}
6799
6800static char *expdir;
6801
6802/*
6803 * Do metacharacter (i.e. *, ?, [...]) expansion.
6804 */
6805static void
6806expmeta(char *enddir, char *name)
6807{
6808 char *p;
6809 const char *cp;
6810 char *start;
6811 char *endname;
6812 int metaflag;
6813 struct stat statb;
6814 DIR *dirp;
6815 struct dirent *dp;
6816 int atend;
6817 int matchdot;
6818
6819 metaflag = 0;
6820 start = name;
6821 for (p = name; *p; p++) {
6822 if (*p == '*' || *p == '?')
6823 metaflag = 1;
6824 else if (*p == '[') {
6825 char *q = p + 1;
6826 if (*q == '!')
6827 q++;
6828 for (;;) {
6829 if (*q == '\\')
6830 q++;
6831 if (*q == '/' || *q == '\0')
6832 break;
6833 if (*++q == ']') {
6834 metaflag = 1;
6835 break;
6836 }
6837 }
6838 } else if (*p == '\\')
6839 p++;
6840 else if (*p == '/') {
6841 if (metaflag)
6842 goto out;
6843 start = p + 1;
6844 }
6845 }
6846 out:
6847 if (metaflag == 0) { /* we've reached the end of the file name */
6848 if (enddir != expdir)
6849 metaflag++;
6850 p = name;
6851 do {
6852 if (*p == '\\')
6853 p++;
6854 *enddir++ = *p;
6855 } while (*p++);
6856 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
6857 addfname(expdir);
6858 return;
6859 }
6860 endname = p;
6861 if (name < start) {
6862 p = name;
6863 do {
6864 if (*p == '\\')
6865 p++;
6866 *enddir++ = *p++;
6867 } while (p < start);
6868 }
6869 if (enddir == expdir) {
6870 cp = ".";
6871 } else if (enddir == expdir + 1 && *expdir == '/') {
6872 cp = "/";
6873 } else {
6874 cp = expdir;
6875 enddir[-1] = '\0';
6876 }
6877 dirp = opendir(cp);
6878 if (dirp == NULL)
6879 return;
6880 if (enddir != expdir)
6881 enddir[-1] = '/';
6882 if (*endname == 0) {
6883 atend = 1;
6884 } else {
6885 atend = 0;
6886 *endname++ = '\0';
6887 }
6888 matchdot = 0;
6889 p = start;
6890 if (*p == '\\')
6891 p++;
6892 if (*p == '.')
6893 matchdot++;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02006894 while (!pending_int && (dp = readdir(dirp)) != NULL) {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00006895 if (dp->d_name[0] == '.' && !matchdot)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006896 continue;
6897 if (pmatch(start, dp->d_name)) {
6898 if (atend) {
6899 strcpy(enddir, dp->d_name);
6900 addfname(expdir);
6901 } else {
6902 for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
6903 continue;
6904 p[-1] = '/';
6905 expmeta(p, endname);
6906 }
6907 }
6908 }
6909 closedir(dirp);
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00006910 if (!atend)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006911 endname[-1] = '/';
6912}
6913
6914static struct strlist *
6915msort(struct strlist *list, int len)
6916{
6917 struct strlist *p, *q = NULL;
6918 struct strlist **lpp;
6919 int half;
6920 int n;
6921
6922 if (len <= 1)
6923 return list;
6924 half = len >> 1;
6925 p = list;
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +00006926 for (n = half; --n >= 0;) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006927 q = p;
6928 p = p->next;
6929 }
6930 q->next = NULL; /* terminate first half of list */
6931 q = msort(list, half); /* sort first half of list */
6932 p = msort(p, len - half); /* sort second half */
6933 lpp = &list;
6934 for (;;) {
6935#if ENABLE_LOCALE_SUPPORT
6936 if (strcoll(p->text, q->text) < 0)
6937#else
6938 if (strcmp(p->text, q->text) < 0)
6939#endif
6940 {
6941 *lpp = p;
6942 lpp = &p->next;
6943 p = *lpp;
6944 if (p == NULL) {
6945 *lpp = q;
6946 break;
6947 }
6948 } else {
6949 *lpp = q;
6950 lpp = &q->next;
6951 q = *lpp;
6952 if (q == NULL) {
6953 *lpp = p;
6954 break;
6955 }
6956 }
6957 }
6958 return list;
6959}
6960
6961/*
6962 * Sort the results of file name expansion. It calculates the number of
6963 * strings to sort and then calls msort (short for merge sort) to do the
6964 * work.
6965 */
6966static struct strlist *
6967expsort(struct strlist *str)
6968{
6969 int len;
6970 struct strlist *sp;
6971
6972 len = 0;
6973 for (sp = str; sp; sp = sp->next)
6974 len++;
6975 return msort(str, len);
6976}
6977
6978static void
Denis Vlasenko68404f12008-03-17 09:00:54 +00006979expandmeta(struct strlist *str /*, int flag*/)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006980{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00006981 static const char metachars[] ALIGN1 = {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006982 '*', '?', '[', 0
6983 };
6984 /* TODO - EXP_REDIR */
6985
6986 while (str) {
6987 struct strlist **savelastp;
6988 struct strlist *sp;
6989 char *p;
6990
6991 if (fflag)
6992 goto nometa;
6993 if (!strpbrk(str->text, metachars))
6994 goto nometa;
6995 savelastp = exparg.lastp;
6996
6997 INT_OFF;
6998 p = preglob(str->text, 0, RMESCAPE_ALLOC | RMESCAPE_HEAP);
6999 {
7000 int i = strlen(str->text);
7001 expdir = ckmalloc(i < 2048 ? 2048 : i); /* XXX */
7002 }
7003
7004 expmeta(expdir, p);
7005 free(expdir);
7006 if (p != str->text)
7007 free(p);
7008 INT_ON;
7009 if (exparg.lastp == savelastp) {
7010 /*
7011 * no matches
7012 */
7013 nometa:
7014 *exparg.lastp = str;
Denys Vlasenkob6c84342009-08-29 20:23:20 +02007015 rmescapes(str->text, 0);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007016 exparg.lastp = &str->next;
7017 } else {
7018 *exparg.lastp = NULL;
7019 *savelastp = sp = expsort(*savelastp);
7020 while (sp->next != NULL)
7021 sp = sp->next;
7022 exparg.lastp = &sp->next;
7023 }
7024 str = str->next;
7025 }
7026}
7027
7028/*
7029 * Perform variable substitution and command substitution on an argument,
7030 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
7031 * perform splitting and file name expansion. When arglist is NULL, perform
7032 * here document expansion.
7033 */
7034static void
7035expandarg(union node *arg, struct arglist *arglist, int flag)
7036{
7037 struct strlist *sp;
7038 char *p;
7039
7040 argbackq = arg->narg.backquote;
7041 STARTSTACKSTR(expdest);
7042 ifsfirst.next = NULL;
7043 ifslastp = NULL;
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00007044 argstr(arg->narg.text, flag,
7045 /* var_str_list: */ arglist ? arglist->list : NULL);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007046 p = _STPUTC('\0', expdest);
7047 expdest = p - 1;
7048 if (arglist == NULL) {
7049 return; /* here document expanded */
7050 }
7051 p = grabstackstr(p);
7052 exparg.lastp = &exparg.list;
7053 /*
7054 * TODO - EXP_REDIR
7055 */
7056 if (flag & EXP_FULL) {
7057 ifsbreakup(p, &exparg);
7058 *exparg.lastp = NULL;
7059 exparg.lastp = &exparg.list;
Denis Vlasenko68404f12008-03-17 09:00:54 +00007060 expandmeta(exparg.list /*, flag*/);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007061 } else {
7062 if (flag & EXP_REDIR) /*XXX - for now, just remove escapes */
Denys Vlasenkob6c84342009-08-29 20:23:20 +02007063 rmescapes(p, 0);
Denis Vlasenko597906c2008-02-20 16:38:54 +00007064 sp = stzalloc(sizeof(*sp));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007065 sp->text = p;
7066 *exparg.lastp = sp;
7067 exparg.lastp = &sp->next;
7068 }
7069 if (ifsfirst.next)
7070 ifsfree();
7071 *exparg.lastp = NULL;
7072 if (exparg.list) {
7073 *arglist->lastp = exparg.list;
7074 arglist->lastp = exparg.lastp;
7075 }
7076}
7077
7078/*
7079 * Expand shell variables and backquotes inside a here document.
7080 */
7081static void
7082expandhere(union node *arg, int fd)
7083{
7084 herefd = fd;
7085 expandarg(arg, (struct arglist *)NULL, 0);
7086 full_write(fd, stackblock(), expdest - (char *)stackblock());
7087}
7088
7089/*
7090 * Returns true if the pattern matches the string.
7091 */
7092static int
7093patmatch(char *pattern, const char *string)
7094{
7095 return pmatch(preglob(pattern, 0, 0), string);
7096}
7097
7098/*
7099 * See if a pattern matches in a case statement.
7100 */
7101static int
7102casematch(union node *pattern, char *val)
7103{
7104 struct stackmark smark;
7105 int result;
7106
7107 setstackmark(&smark);
7108 argbackq = pattern->narg.backquote;
7109 STARTSTACKSTR(expdest);
7110 ifslastp = NULL;
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00007111 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE,
7112 /* var_str_list: */ NULL);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007113 STACKSTRNUL(expdest);
7114 result = patmatch(stackblock(), val);
7115 popstackmark(&smark);
7116 return result;
7117}
7118
7119
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007120/* ============ find_command */
7121
7122struct builtincmd {
7123 const char *name;
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007124 int (*builtin)(int, char **) FAST_FUNC;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007125 /* unsigned flags; */
7126};
7127#define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
Denis Vlasenkoe26b2782008-02-12 07:40:29 +00007128/* "regular" builtins always take precedence over commands,
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007129 * regardless of PATH=....%builtin... position */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007130#define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007131#define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007132
7133struct cmdentry {
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00007134 smallint cmdtype; /* CMDxxx */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007135 union param {
7136 int index;
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00007137 /* index >= 0 for commands without path (slashes) */
7138 /* (TODO: what exactly does the value mean? PATH position?) */
7139 /* index == -1 for commands with slashes */
7140 /* index == (-2 - applet_no) for NOFORK applets */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007141 const struct builtincmd *cmd;
7142 struct funcnode *func;
7143 } u;
7144};
7145/* values of cmdtype */
7146#define CMDUNKNOWN -1 /* no entry in table for command */
7147#define CMDNORMAL 0 /* command is an executable program */
7148#define CMDFUNCTION 1 /* command is a shell function */
7149#define CMDBUILTIN 2 /* command is a shell builtin */
7150
7151/* action to find_command() */
7152#define DO_ERR 0x01 /* prints errors */
7153#define DO_ABS 0x02 /* checks absolute paths */
7154#define DO_NOFUNC 0x04 /* don't return shell functions, for command */
7155#define DO_ALTPATH 0x08 /* using alternate path */
7156#define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
7157
7158static void find_command(char *, struct cmdentry *, int, const char *);
7159
7160
7161/* ============ Hashing commands */
7162
7163/*
7164 * When commands are first encountered, they are entered in a hash table.
7165 * This ensures that a full path search will not have to be done for them
7166 * on each invocation.
7167 *
7168 * We should investigate converting to a linear search, even though that
7169 * would make the command name "hash" a misnomer.
7170 */
7171
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007172struct tblentry {
7173 struct tblentry *next; /* next entry in hash chain */
7174 union param param; /* definition of builtin function */
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00007175 smallint cmdtype; /* CMDxxx */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007176 char rehash; /* if set, cd done since entry created */
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007177 char cmdname[1]; /* name of command */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007178};
7179
Denis Vlasenko01631112007-12-16 17:20:38 +00007180static struct tblentry **cmdtable;
7181#define INIT_G_cmdtable() do { \
7182 cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
7183} while (0)
7184
7185static int builtinloc = -1; /* index in path of %builtin, or -1 */
7186
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007187
7188static void
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00007189tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) char *cmd, char **argv, char **envp)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007190{
7191 int repeated = 0;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007192
Denis Vlasenko80d14be2007-04-10 23:03:30 +00007193#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007194 if (applet_no >= 0) {
Denis Vlasenkob7304742008-10-20 08:15:51 +00007195 if (APPLET_IS_NOEXEC(applet_no)) {
7196 while (*envp)
7197 putenv(*envp++);
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007198 run_applet_no_and_exit(applet_no, argv);
Denis Vlasenkob7304742008-10-20 08:15:51 +00007199 }
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007200 /* re-exec ourselves with the new arguments */
7201 execve(bb_busybox_exec_path, argv, envp);
7202 /* If they called chroot or otherwise made the binary no longer
7203 * executable, fall through */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007204 }
7205#endif
7206
7207 repeat:
7208#ifdef SYSV
7209 do {
7210 execve(cmd, argv, envp);
7211 } while (errno == EINTR);
7212#else
7213 execve(cmd, argv, envp);
7214#endif
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007215 if (repeated) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007216 free(argv);
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007217 return;
7218 }
7219 if (errno == ENOEXEC) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007220 char **ap;
7221 char **new;
7222
7223 for (ap = argv; *ap; ap++)
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007224 continue;
7225 ap = new = ckmalloc((ap - argv + 2) * sizeof(ap[0]));
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007226 ap[1] = cmd;
Denis Vlasenkoc44ab012007-04-09 03:11:58 +00007227 ap[0] = cmd = (char *)DEFAULT_SHELL;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007228 ap += 2;
7229 argv++;
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007230 while ((*ap++ = *argv++) != NULL)
Denis Vlasenko597906c2008-02-20 16:38:54 +00007231 continue;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007232 argv = new;
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007233 repeated++;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007234 goto repeat;
7235 }
7236}
7237
7238/*
7239 * Exec a program. Never returns. If you change this routine, you may
7240 * have to change the find_command routine as well.
7241 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00007242static void shellexec(char **, const char *, int) NORETURN;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007243static void
7244shellexec(char **argv, const char *path, int idx)
7245{
7246 char *cmdname;
7247 int e;
7248 char **envp;
7249 int exerrno;
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007250#if ENABLE_FEATURE_SH_STANDALONE
7251 int applet_no = -1;
7252#endif
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007253
Denis Vlasenko34c73c42008-08-16 11:48:02 +00007254 clearredir(/*drop:*/ 1);
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007255 envp = listvars(VEXPORT, VUNSET, 0);
7256 if (strchr(argv[0], '/') != NULL
Denis Vlasenko80d14be2007-04-10 23:03:30 +00007257#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko4a9ca132008-04-12 20:07:08 +00007258 || (applet_no = find_applet_by_name(argv[0])) >= 0
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007259#endif
7260 ) {
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00007261 tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) argv[0], argv, envp);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007262 e = errno;
7263 } else {
7264 e = ENOENT;
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02007265 while ((cmdname = path_advance(&path, argv[0])) != NULL) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007266 if (--idx < 0 && pathopt == NULL) {
Denis Vlasenko5e34ff22009-04-21 11:09:40 +00007267 tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007268 if (errno != ENOENT && errno != ENOTDIR)
7269 e = errno;
7270 }
7271 stunalloc(cmdname);
7272 }
7273 }
7274
7275 /* Map to POSIX errors */
7276 switch (e) {
7277 case EACCES:
7278 exerrno = 126;
7279 break;
7280 case ENOENT:
7281 exerrno = 127;
7282 break;
7283 default:
7284 exerrno = 2;
7285 break;
7286 }
7287 exitstatus = exerrno;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02007288 TRACE(("shellexec failed for %s, errno %d, suppress_int %d\n",
7289 argv[0], e, suppress_int));
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007290 ash_msg_and_raise(EXEXEC, "%s: %s", argv[0], errmsg(e, "not found"));
7291 /* NOTREACHED */
7292}
7293
7294static void
7295printentry(struct tblentry *cmdp)
7296{
7297 int idx;
7298 const char *path;
7299 char *name;
7300
7301 idx = cmdp->param.index;
7302 path = pathval();
7303 do {
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02007304 name = path_advance(&path, cmdp->cmdname);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007305 stunalloc(name);
7306 } while (--idx >= 0);
7307 out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
7308}
7309
7310/*
7311 * Clear out command entries. The argument specifies the first entry in
7312 * PATH which has changed.
7313 */
7314static void
7315clearcmdentry(int firstchange)
7316{
7317 struct tblentry **tblp;
7318 struct tblentry **pp;
7319 struct tblentry *cmdp;
7320
7321 INT_OFF;
7322 for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
7323 pp = tblp;
7324 while ((cmdp = *pp) != NULL) {
7325 if ((cmdp->cmdtype == CMDNORMAL &&
7326 cmdp->param.index >= firstchange)
7327 || (cmdp->cmdtype == CMDBUILTIN &&
7328 builtinloc >= firstchange)
7329 ) {
7330 *pp = cmdp->next;
7331 free(cmdp);
7332 } else {
7333 pp = &cmdp->next;
7334 }
7335 }
7336 }
7337 INT_ON;
7338}
7339
7340/*
7341 * Locate a command in the command hash table. If "add" is nonzero,
7342 * add the command to the table if it is not already present. The
7343 * variable "lastcmdentry" is set to point to the address of the link
7344 * pointing to the entry, so that delete_cmd_entry can delete the
7345 * entry.
7346 *
7347 * Interrupts must be off if called with add != 0.
7348 */
7349static struct tblentry **lastcmdentry;
7350
7351static struct tblentry *
7352cmdlookup(const char *name, int add)
7353{
7354 unsigned int hashval;
7355 const char *p;
7356 struct tblentry *cmdp;
7357 struct tblentry **pp;
7358
7359 p = name;
7360 hashval = (unsigned char)*p << 4;
7361 while (*p)
7362 hashval += (unsigned char)*p++;
7363 hashval &= 0x7FFF;
7364 pp = &cmdtable[hashval % CMDTABLESIZE];
7365 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7366 if (strcmp(cmdp->cmdname, name) == 0)
7367 break;
7368 pp = &cmdp->next;
7369 }
7370 if (add && cmdp == NULL) {
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007371 cmdp = *pp = ckzalloc(sizeof(struct tblentry)
7372 + strlen(name)
7373 /* + 1 - already done because
7374 * tblentry::cmdname is char[1] */);
Denis Vlasenko597906c2008-02-20 16:38:54 +00007375 /*cmdp->next = NULL; - ckzalloc did it */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007376 cmdp->cmdtype = CMDUNKNOWN;
7377 strcpy(cmdp->cmdname, name);
7378 }
7379 lastcmdentry = pp;
7380 return cmdp;
7381}
7382
7383/*
7384 * Delete the command entry returned on the last lookup.
7385 */
7386static void
7387delete_cmd_entry(void)
7388{
7389 struct tblentry *cmdp;
7390
7391 INT_OFF;
7392 cmdp = *lastcmdentry;
7393 *lastcmdentry = cmdp->next;
7394 if (cmdp->cmdtype == CMDFUNCTION)
7395 freefunc(cmdp->param.func);
7396 free(cmdp);
7397 INT_ON;
7398}
7399
7400/*
7401 * Add a new command entry, replacing any existing command entry for
7402 * the same name - except special builtins.
7403 */
7404static void
7405addcmdentry(char *name, struct cmdentry *entry)
7406{
7407 struct tblentry *cmdp;
7408
7409 cmdp = cmdlookup(name, 1);
7410 if (cmdp->cmdtype == CMDFUNCTION) {
7411 freefunc(cmdp->param.func);
7412 }
7413 cmdp->cmdtype = entry->cmdtype;
7414 cmdp->param = entry->u;
7415 cmdp->rehash = 0;
7416}
7417
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007418static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00007419hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007420{
7421 struct tblentry **pp;
7422 struct tblentry *cmdp;
7423 int c;
7424 struct cmdentry entry;
7425 char *name;
7426
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007427 if (nextopt("r") != '\0') {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007428 clearcmdentry(0);
7429 return 0;
7430 }
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007431
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007432 if (*argptr == NULL) {
7433 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7434 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7435 if (cmdp->cmdtype == CMDNORMAL)
7436 printentry(cmdp);
7437 }
7438 }
7439 return 0;
7440 }
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007441
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007442 c = 0;
7443 while ((name = *argptr) != NULL) {
7444 cmdp = cmdlookup(name, 0);
7445 if (cmdp != NULL
7446 && (cmdp->cmdtype == CMDNORMAL
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007447 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
7448 ) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007449 delete_cmd_entry();
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007450 }
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007451 find_command(name, &entry, DO_ERR, pathval());
7452 if (entry.cmdtype == CMDUNKNOWN)
7453 c = 1;
7454 argptr++;
7455 }
7456 return c;
7457}
7458
7459/*
7460 * Called when a cd is done. Marks all commands so the next time they
7461 * are executed they will be rehashed.
7462 */
7463static void
7464hashcd(void)
7465{
7466 struct tblentry **pp;
7467 struct tblentry *cmdp;
7468
7469 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7470 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007471 if (cmdp->cmdtype == CMDNORMAL
7472 || (cmdp->cmdtype == CMDBUILTIN
7473 && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
7474 && builtinloc > 0)
7475 ) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007476 cmdp->rehash = 1;
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007477 }
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007478 }
7479 }
7480}
7481
7482/*
7483 * Fix command hash table when PATH changed.
7484 * Called before PATH is changed. The argument is the new value of PATH;
7485 * pathval() still returns the old value at this point.
7486 * Called with interrupts off.
7487 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007488static void FAST_FUNC
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007489changepath(const char *new)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007490{
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007491 const char *old;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007492 int firstchange;
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007493 int idx;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007494 int idx_bltin;
7495
7496 old = pathval();
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007497 firstchange = 9999; /* assume no change */
7498 idx = 0;
7499 idx_bltin = -1;
7500 for (;;) {
7501 if (*old != *new) {
7502 firstchange = idx;
7503 if ((*old == '\0' && *new == ':')
7504 || (*old == ':' && *new == '\0'))
7505 firstchange++;
7506 old = new; /* ignore subsequent differences */
7507 }
7508 if (*new == '\0')
7509 break;
7510 if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
7511 idx_bltin = idx;
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007512 if (*new == ':')
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007513 idx++;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007514 new++, old++;
7515 }
7516 if (builtinloc < 0 && idx_bltin >= 0)
7517 builtinloc = idx_bltin; /* zap builtins */
7518 if (builtinloc >= 0 && idx_bltin < 0)
7519 firstchange = 0;
7520 clearcmdentry(firstchange);
7521 builtinloc = idx_bltin;
7522}
7523
7524#define TEOF 0
7525#define TNL 1
7526#define TREDIR 2
7527#define TWORD 3
7528#define TSEMI 4
7529#define TBACKGND 5
7530#define TAND 6
7531#define TOR 7
7532#define TPIPE 8
7533#define TLP 9
7534#define TRP 10
7535#define TENDCASE 11
7536#define TENDBQUOTE 12
7537#define TNOT 13
7538#define TCASE 14
7539#define TDO 15
7540#define TDONE 16
7541#define TELIF 17
7542#define TELSE 18
7543#define TESAC 19
7544#define TFI 20
7545#define TFOR 21
7546#define TIF 22
7547#define TIN 23
7548#define TTHEN 24
7549#define TUNTIL 25
7550#define TWHILE 26
7551#define TBEGIN 27
7552#define TEND 28
Denis Vlasenkob07a4962008-06-22 13:16:23 +00007553typedef smallint token_id_t;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007554
7555/* first char is indicating which tokens mark the end of a list */
7556static const char *const tokname_array[] = {
7557 "\1end of file",
7558 "\0newline",
7559 "\0redirection",
7560 "\0word",
7561 "\0;",
7562 "\0&",
7563 "\0&&",
7564 "\0||",
7565 "\0|",
7566 "\0(",
7567 "\1)",
7568 "\1;;",
7569 "\1`",
7570#define KWDOFFSET 13
7571 /* the following are keywords */
7572 "\0!",
7573 "\0case",
7574 "\1do",
7575 "\1done",
7576 "\1elif",
7577 "\1else",
7578 "\1esac",
7579 "\1fi",
7580 "\0for",
7581 "\0if",
7582 "\0in",
7583 "\1then",
7584 "\0until",
7585 "\0while",
7586 "\0{",
7587 "\1}",
7588};
7589
7590static const char *
7591tokname(int tok)
7592{
7593 static char buf[16];
7594
Denis Vlasenko240a1cf2007-04-08 16:07:02 +00007595//try this:
7596//if (tok < TSEMI) return tokname_array[tok] + 1;
7597//sprintf(buf, "\"%s\"", tokname_array[tok] + 1);
7598//return buf;
7599
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007600 if (tok >= TSEMI)
7601 buf[0] = '"';
7602 sprintf(buf + (tok >= TSEMI), "%s%c",
7603 tokname_array[tok] + 1, (tok >= TSEMI ? '"' : 0));
7604 return buf;
7605}
7606
7607/* Wrapper around strcmp for qsort/bsearch/... */
7608static int
7609pstrcmp(const void *a, const void *b)
7610{
Denis Vlasenko240a1cf2007-04-08 16:07:02 +00007611 return strcmp((char*) a, (*(char**) b) + 1);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007612}
7613
7614static const char *const *
7615findkwd(const char *s)
7616{
7617 return bsearch(s, tokname_array + KWDOFFSET,
Denis Vlasenko80b8b392007-06-25 10:55:35 +00007618 ARRAY_SIZE(tokname_array) - KWDOFFSET,
7619 sizeof(tokname_array[0]), pstrcmp);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007620}
7621
7622/*
7623 * Locate and print what a word is...
7624 */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007625static int
7626describe_command(char *command, int describe_command_verbose)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007627{
7628 struct cmdentry entry;
7629 struct tblentry *cmdp;
7630#if ENABLE_ASH_ALIAS
7631 const struct alias *ap;
7632#endif
7633 const char *path = pathval();
7634
7635 if (describe_command_verbose) {
7636 out1str(command);
7637 }
7638
7639 /* First look at the keywords */
7640 if (findkwd(command)) {
7641 out1str(describe_command_verbose ? " is a shell keyword" : command);
7642 goto out;
7643 }
7644
7645#if ENABLE_ASH_ALIAS
7646 /* Then look at the aliases */
7647 ap = lookupalias(command, 0);
7648 if (ap != NULL) {
Denis Vlasenko46846e22007-05-20 13:08:31 +00007649 if (!describe_command_verbose) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007650 out1str("alias ");
7651 printalias(ap);
7652 return 0;
7653 }
Denis Vlasenko46846e22007-05-20 13:08:31 +00007654 out1fmt(" is an alias for %s", ap->val);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007655 goto out;
7656 }
7657#endif
7658 /* Then check if it is a tracked alias */
7659 cmdp = cmdlookup(command, 0);
7660 if (cmdp != NULL) {
7661 entry.cmdtype = cmdp->cmdtype;
7662 entry.u = cmdp->param;
7663 } else {
7664 /* Finally use brute force */
7665 find_command(command, &entry, DO_ABS, path);
7666 }
7667
7668 switch (entry.cmdtype) {
7669 case CMDNORMAL: {
7670 int j = entry.u.index;
7671 char *p;
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00007672 if (j < 0) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007673 p = command;
7674 } else {
7675 do {
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02007676 p = path_advance(&path, command);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007677 stunalloc(p);
7678 } while (--j >= 0);
7679 }
7680 if (describe_command_verbose) {
7681 out1fmt(" is%s %s",
7682 (cmdp ? " a tracked alias for" : nullstr), p
7683 );
7684 } else {
7685 out1str(p);
7686 }
7687 break;
7688 }
7689
7690 case CMDFUNCTION:
7691 if (describe_command_verbose) {
7692 out1str(" is a shell function");
7693 } else {
7694 out1str(command);
7695 }
7696 break;
7697
7698 case CMDBUILTIN:
7699 if (describe_command_verbose) {
7700 out1fmt(" is a %sshell builtin",
7701 IS_BUILTIN_SPECIAL(entry.u.cmd) ?
7702 "special " : nullstr
7703 );
7704 } else {
7705 out1str(command);
7706 }
7707 break;
7708
7709 default:
7710 if (describe_command_verbose) {
7711 out1str(": not found\n");
7712 }
7713 return 127;
7714 }
7715 out:
7716 outstr("\n", stdout);
7717 return 0;
7718}
7719
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007720static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00007721typecmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007722{
Denis Vlasenko46846e22007-05-20 13:08:31 +00007723 int i = 1;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007724 int err = 0;
Denis Vlasenko46846e22007-05-20 13:08:31 +00007725 int verbose = 1;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007726
Denis Vlasenko46846e22007-05-20 13:08:31 +00007727 /* type -p ... ? (we don't bother checking for 'p') */
Denis Vlasenko1fc62382007-06-25 22:55:34 +00007728 if (argv[1] && argv[1][0] == '-') {
Denis Vlasenko46846e22007-05-20 13:08:31 +00007729 i++;
7730 verbose = 0;
7731 }
Denis Vlasenko68404f12008-03-17 09:00:54 +00007732 while (argv[i]) {
Denis Vlasenko46846e22007-05-20 13:08:31 +00007733 err |= describe_command(argv[i++], verbose);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007734 }
7735 return err;
7736}
7737
7738#if ENABLE_ASH_CMDCMD
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02007739static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00007740commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007741{
7742 int c;
7743 enum {
7744 VERIFY_BRIEF = 1,
7745 VERIFY_VERBOSE = 2,
7746 } verify = 0;
7747
7748 while ((c = nextopt("pvV")) != '\0')
7749 if (c == 'V')
7750 verify |= VERIFY_VERBOSE;
7751 else if (c == 'v')
7752 verify |= VERIFY_BRIEF;
7753#if DEBUG
7754 else if (c != 'p')
7755 abort();
7756#endif
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00007757 /* Mimic bash: just "command -v" doesn't complain, it's a nop */
7758 if (verify && (*argptr != NULL)) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007759 return describe_command(*argptr, verify - VERIFY_BRIEF);
Denis Vlasenkoe7067e32008-07-11 23:09:34 +00007760 }
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007761
7762 return 0;
7763}
7764#endif
7765
7766
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007767/* ============ eval.c */
Eric Andersencb57d552001-06-28 07:25:16 +00007768
Denis Vlasenko340299a2008-11-21 10:36:36 +00007769static int funcblocksize; /* size of structures in function */
7770static int funcstringsize; /* size of strings in node */
7771static void *funcblock; /* block to allocate function from */
7772static char *funcstring; /* block to allocate strings from */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007773
Eric Andersencb57d552001-06-28 07:25:16 +00007774/* flags in argument to evaltree */
Denis Vlasenko340299a2008-11-21 10:36:36 +00007775#define EV_EXIT 01 /* exit after evaluating tree */
7776#define EV_TESTED 02 /* exit status is checked; ignore -e flag */
Eric Andersenc470f442003-07-28 09:56:35 +00007777#define EV_BACKCMD 04 /* command executing within back quotes */
Eric Andersencb57d552001-06-28 07:25:16 +00007778
Denys Vlasenko0e5e4ea2009-10-11 00:36:20 +02007779static const uint8_t nodesize[N_NUMBER] = {
Denis Vlasenko340299a2008-11-21 10:36:36 +00007780 [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
7781 [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
7782 [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
7783 [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
7784 [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
7785 [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
7786 [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
7787 [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
7788 [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
7789 [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
7790 [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
7791 [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
7792 [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
7793 [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
7794 [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
7795 [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
7796 [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
Denis Vlasenkocc5feab2008-11-22 01:32:40 +00007797#if ENABLE_ASH_BASH_COMPAT
Denis Vlasenko340299a2008-11-21 10:36:36 +00007798 [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
Denis Vlasenkocc5feab2008-11-22 01:32:40 +00007799#endif
Denis Vlasenko340299a2008-11-21 10:36:36 +00007800 [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
7801 [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
7802 [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
7803 [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
7804 [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
7805 [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
7806 [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
7807 [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
7808 [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007809};
7810
7811static void calcsize(union node *n);
7812
7813static void
7814sizenodelist(struct nodelist *lp)
7815{
7816 while (lp) {
7817 funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
7818 calcsize(lp->n);
7819 lp = lp->next;
7820 }
7821}
7822
7823static void
7824calcsize(union node *n)
7825{
7826 if (n == NULL)
7827 return;
7828 funcblocksize += nodesize[n->type];
7829 switch (n->type) {
7830 case NCMD:
7831 calcsize(n->ncmd.redirect);
7832 calcsize(n->ncmd.args);
7833 calcsize(n->ncmd.assign);
7834 break;
7835 case NPIPE:
7836 sizenodelist(n->npipe.cmdlist);
7837 break;
7838 case NREDIR:
7839 case NBACKGND:
7840 case NSUBSHELL:
7841 calcsize(n->nredir.redirect);
7842 calcsize(n->nredir.n);
7843 break;
7844 case NAND:
7845 case NOR:
7846 case NSEMI:
7847 case NWHILE:
7848 case NUNTIL:
7849 calcsize(n->nbinary.ch2);
7850 calcsize(n->nbinary.ch1);
7851 break;
7852 case NIF:
7853 calcsize(n->nif.elsepart);
7854 calcsize(n->nif.ifpart);
7855 calcsize(n->nif.test);
7856 break;
7857 case NFOR:
7858 funcstringsize += strlen(n->nfor.var) + 1;
7859 calcsize(n->nfor.body);
7860 calcsize(n->nfor.args);
7861 break;
7862 case NCASE:
7863 calcsize(n->ncase.cases);
7864 calcsize(n->ncase.expr);
7865 break;
7866 case NCLIST:
7867 calcsize(n->nclist.body);
7868 calcsize(n->nclist.pattern);
7869 calcsize(n->nclist.next);
7870 break;
7871 case NDEFUN:
7872 case NARG:
7873 sizenodelist(n->narg.backquote);
7874 funcstringsize += strlen(n->narg.text) + 1;
7875 calcsize(n->narg.next);
7876 break;
7877 case NTO:
Denis Vlasenko559691a2008-10-05 18:39:31 +00007878#if ENABLE_ASH_BASH_COMPAT
7879 case NTO2:
7880#endif
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007881 case NCLOBBER:
7882 case NFROM:
7883 case NFROMTO:
7884 case NAPPEND:
7885 calcsize(n->nfile.fname);
7886 calcsize(n->nfile.next);
7887 break;
7888 case NTOFD:
7889 case NFROMFD:
7890 calcsize(n->ndup.vname);
7891 calcsize(n->ndup.next);
7892 break;
7893 case NHERE:
7894 case NXHERE:
7895 calcsize(n->nhere.doc);
7896 calcsize(n->nhere.next);
7897 break;
7898 case NNOT:
7899 calcsize(n->nnot.com);
7900 break;
7901 };
7902}
7903
7904static char *
7905nodeckstrdup(char *s)
7906{
7907 char *rtn = funcstring;
7908
7909 strcpy(funcstring, s);
7910 funcstring += strlen(s) + 1;
7911 return rtn;
7912}
7913
7914static union node *copynode(union node *);
7915
7916static struct nodelist *
7917copynodelist(struct nodelist *lp)
7918{
7919 struct nodelist *start;
7920 struct nodelist **lpp;
7921
7922 lpp = &start;
7923 while (lp) {
7924 *lpp = funcblock;
7925 funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
7926 (*lpp)->n = copynode(lp->n);
7927 lp = lp->next;
7928 lpp = &(*lpp)->next;
7929 }
7930 *lpp = NULL;
7931 return start;
7932}
7933
7934static union node *
7935copynode(union node *n)
7936{
7937 union node *new;
7938
7939 if (n == NULL)
7940 return NULL;
7941 new = funcblock;
7942 funcblock = (char *) funcblock + nodesize[n->type];
7943
7944 switch (n->type) {
7945 case NCMD:
7946 new->ncmd.redirect = copynode(n->ncmd.redirect);
7947 new->ncmd.args = copynode(n->ncmd.args);
7948 new->ncmd.assign = copynode(n->ncmd.assign);
7949 break;
7950 case NPIPE:
7951 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00007952 new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007953 break;
7954 case NREDIR:
7955 case NBACKGND:
7956 case NSUBSHELL:
7957 new->nredir.redirect = copynode(n->nredir.redirect);
7958 new->nredir.n = copynode(n->nredir.n);
7959 break;
7960 case NAND:
7961 case NOR:
7962 case NSEMI:
7963 case NWHILE:
7964 case NUNTIL:
7965 new->nbinary.ch2 = copynode(n->nbinary.ch2);
7966 new->nbinary.ch1 = copynode(n->nbinary.ch1);
7967 break;
7968 case NIF:
7969 new->nif.elsepart = copynode(n->nif.elsepart);
7970 new->nif.ifpart = copynode(n->nif.ifpart);
7971 new->nif.test = copynode(n->nif.test);
7972 break;
7973 case NFOR:
7974 new->nfor.var = nodeckstrdup(n->nfor.var);
7975 new->nfor.body = copynode(n->nfor.body);
7976 new->nfor.args = copynode(n->nfor.args);
7977 break;
7978 case NCASE:
7979 new->ncase.cases = copynode(n->ncase.cases);
7980 new->ncase.expr = copynode(n->ncase.expr);
7981 break;
7982 case NCLIST:
7983 new->nclist.body = copynode(n->nclist.body);
7984 new->nclist.pattern = copynode(n->nclist.pattern);
7985 new->nclist.next = copynode(n->nclist.next);
7986 break;
7987 case NDEFUN:
7988 case NARG:
7989 new->narg.backquote = copynodelist(n->narg.backquote);
7990 new->narg.text = nodeckstrdup(n->narg.text);
7991 new->narg.next = copynode(n->narg.next);
7992 break;
7993 case NTO:
Denis Vlasenko559691a2008-10-05 18:39:31 +00007994#if ENABLE_ASH_BASH_COMPAT
7995 case NTO2:
7996#endif
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007997 case NCLOBBER:
7998 case NFROM:
7999 case NFROMTO:
8000 case NAPPEND:
8001 new->nfile.fname = copynode(n->nfile.fname);
8002 new->nfile.fd = n->nfile.fd;
8003 new->nfile.next = copynode(n->nfile.next);
8004 break;
8005 case NTOFD:
8006 case NFROMFD:
8007 new->ndup.vname = copynode(n->ndup.vname);
8008 new->ndup.dupfd = n->ndup.dupfd;
8009 new->ndup.fd = n->ndup.fd;
8010 new->ndup.next = copynode(n->ndup.next);
8011 break;
8012 case NHERE:
8013 case NXHERE:
8014 new->nhere.doc = copynode(n->nhere.doc);
8015 new->nhere.fd = n->nhere.fd;
8016 new->nhere.next = copynode(n->nhere.next);
8017 break;
8018 case NNOT:
8019 new->nnot.com = copynode(n->nnot.com);
8020 break;
8021 };
8022 new->type = n->type;
8023 return new;
8024}
8025
8026/*
8027 * Make a copy of a parse tree.
8028 */
8029static struct funcnode *
8030copyfunc(union node *n)
8031{
8032 struct funcnode *f;
8033 size_t blocksize;
8034
8035 funcblocksize = offsetof(struct funcnode, n);
8036 funcstringsize = 0;
8037 calcsize(n);
8038 blocksize = funcblocksize;
8039 f = ckmalloc(blocksize + funcstringsize);
8040 funcblock = (char *) f + offsetof(struct funcnode, n);
8041 funcstring = (char *) f + blocksize;
8042 copynode(n);
8043 f->count = 0;
8044 return f;
8045}
8046
8047/*
8048 * Define a shell function.
8049 */
8050static void
8051defun(char *name, union node *func)
8052{
8053 struct cmdentry entry;
8054
8055 INT_OFF;
8056 entry.cmdtype = CMDFUNCTION;
8057 entry.u.func = copyfunc(func);
8058 addcmdentry(name, &entry);
8059 INT_ON;
8060}
8061
Denis Vlasenko4b875702009-03-19 13:30:04 +00008062/* Reasons for skipping commands (see comment on breakcmd routine) */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008063#define SKIPBREAK (1 << 0)
8064#define SKIPCONT (1 << 1)
8065#define SKIPFUNC (1 << 2)
8066#define SKIPFILE (1 << 3)
8067#define SKIPEVAL (1 << 4)
Denis Vlasenko4b875702009-03-19 13:30:04 +00008068static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008069static int skipcount; /* number of levels to skip */
8070static int funcnest; /* depth of function calls */
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +00008071static int loopnest; /* current loop nesting level */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008072
Denis Vlasenko4b875702009-03-19 13:30:04 +00008073/* Forward decl way out to parsing code - dotrap needs it */
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008074static int evalstring(char *s, int mask);
8075
Denis Vlasenko4b875702009-03-19 13:30:04 +00008076/* Called to execute a trap.
8077 * Single callsite - at the end of evaltree().
8078 * If we return non-zero, exaltree raises EXEXIT exception.
8079 *
8080 * Perhaps we should avoid entering new trap handlers
8081 * while we are executing a trap handler. [is it a TODO?]
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008082 */
8083static int
8084dotrap(void)
8085{
Denis Vlasenko4b875702009-03-19 13:30:04 +00008086 uint8_t *g;
8087 int sig;
8088 uint8_t savestatus;
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008089
8090 savestatus = exitstatus;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02008091 pending_sig = 0;
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008092 xbarrier();
8093
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008094 TRACE(("dotrap entered\n"));
Denis Vlasenko4b875702009-03-19 13:30:04 +00008095 for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
8096 int want_exexit;
8097 char *t;
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008098
Denis Vlasenko4b875702009-03-19 13:30:04 +00008099 if (*g == 0)
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008100 continue;
Denis Vlasenko4b875702009-03-19 13:30:04 +00008101 t = trap[sig];
8102 /* non-trapped SIGINT is handled separately by raise_interrupt,
8103 * don't upset it by resetting gotsig[SIGINT-1] */
8104 if (sig == SIGINT && !t)
8105 continue;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008106
8107 TRACE(("sig %d is active, will run handler '%s'\n", sig, t));
Denis Vlasenko4b875702009-03-19 13:30:04 +00008108 *g = 0;
8109 if (!t)
8110 continue;
8111 want_exexit = evalstring(t, SKIPEVAL);
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008112 exitstatus = savestatus;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008113 if (want_exexit) {
Denis Vlasenkob21f3792009-03-19 23:09:58 +00008114 TRACE(("dotrap returns %d\n", want_exexit));
Denis Vlasenko4b875702009-03-19 13:30:04 +00008115 return want_exexit;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008116 }
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008117 }
8118
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008119 TRACE(("dotrap returns 0\n"));
Denis Vlasenko991a1da2008-02-10 19:02:53 +00008120 return 0;
Denis Vlasenkofc06f292007-02-23 21:09:35 +00008121}
8122
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00008123/* forward declarations - evaluation is fairly recursive business... */
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008124static void evalloop(union node *, int);
8125static void evalfor(union node *, int);
8126static void evalcase(union node *, int);
8127static void evalsubshell(union node *, int);
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00008128static void expredir(union node *);
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008129static void evalpipe(union node *, int);
8130static void evalcommand(union node *, int);
Eric Andersenc470f442003-07-28 09:56:35 +00008131static int evalbltin(const struct builtincmd *, int, char **);
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008132static void prehash(union node *);
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00008133
Eric Andersen62483552001-07-10 06:09:16 +00008134/*
Eric Andersenc470f442003-07-28 09:56:35 +00008135 * Evaluate a parse tree. The value is left in the global variable
8136 * exitstatus.
Eric Andersen62483552001-07-10 06:09:16 +00008137 */
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008138static void
Eric Andersenc470f442003-07-28 09:56:35 +00008139evaltree(union node *n, int flags)
Eric Andersen62483552001-07-10 06:09:16 +00008140{
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008141 struct jmploc *volatile savehandler = exception_handler;
8142 struct jmploc jmploc;
Eric Andersenc470f442003-07-28 09:56:35 +00008143 int checkexit = 0;
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008144 void (*evalfn)(union node *, int);
Eric Andersenc470f442003-07-28 09:56:35 +00008145 int status;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008146 int int_level;
8147
8148 SAVE_INT(int_level);
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008149
Eric Andersenc470f442003-07-28 09:56:35 +00008150 if (n == NULL) {
8151 TRACE(("evaltree(NULL) called\n"));
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008152 goto out1;
Eric Andersen62483552001-07-10 06:09:16 +00008153 }
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008154 TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008155
8156 exception_handler = &jmploc;
8157 {
8158 int err = setjmp(jmploc.loc);
8159 if (err) {
8160 /* if it was a signal, check for trap handlers */
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008161 if (exception_type == EXSIG) {
Denis Vlasenkob21f3792009-03-19 23:09:58 +00008162 TRACE(("exception %d (EXSIG) in evaltree, err=%d\n",
8163 exception_type, err));
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008164 goto out;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008165 }
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008166 /* continue on the way out */
Denis Vlasenkob21f3792009-03-19 23:09:58 +00008167 TRACE(("exception %d in evaltree, propagating err=%d\n",
8168 exception_type, err));
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008169 exception_handler = savehandler;
8170 longjmp(exception_handler->loc, err);
8171 }
8172 }
8173
Eric Andersenc470f442003-07-28 09:56:35 +00008174 switch (n->type) {
8175 default:
Denis Vlasenkoa7189f02006-11-17 20:29:00 +00008176#if DEBUG
Eric Andersenc470f442003-07-28 09:56:35 +00008177 out1fmt("Node type = %d\n", n->type);
Denys Vlasenko8131eea2009-11-02 14:19:51 +01008178 fflush_all();
Eric Andersenc470f442003-07-28 09:56:35 +00008179 break;
8180#endif
8181 case NNOT:
8182 evaltree(n->nnot.com, EV_TESTED);
8183 status = !exitstatus;
8184 goto setstatus;
8185 case NREDIR:
8186 expredir(n->nredir.redirect);
8187 status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
8188 if (!status) {
8189 evaltree(n->nredir.n, flags & EV_TESTED);
8190 status = exitstatus;
8191 }
Denis Vlasenko34c73c42008-08-16 11:48:02 +00008192 popredir(/*drop:*/ 0, /*restore:*/ 0 /* not sure */);
Eric Andersenc470f442003-07-28 09:56:35 +00008193 goto setstatus;
8194 case NCMD:
8195 evalfn = evalcommand;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008196 checkexit:
Eric Andersenc470f442003-07-28 09:56:35 +00008197 if (eflag && !(flags & EV_TESTED))
8198 checkexit = ~0;
8199 goto calleval;
8200 case NFOR:
8201 evalfn = evalfor;
8202 goto calleval;
8203 case NWHILE:
8204 case NUNTIL:
8205 evalfn = evalloop;
8206 goto calleval;
8207 case NSUBSHELL:
8208 case NBACKGND:
8209 evalfn = evalsubshell;
8210 goto calleval;
8211 case NPIPE:
8212 evalfn = evalpipe;
8213 goto checkexit;
8214 case NCASE:
8215 evalfn = evalcase;
8216 goto calleval;
8217 case NAND:
8218 case NOR:
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008219 case NSEMI: {
8220
Eric Andersenc470f442003-07-28 09:56:35 +00008221#if NAND + 1 != NOR
8222#error NAND + 1 != NOR
8223#endif
8224#if NOR + 1 != NSEMI
8225#error NOR + 1 != NSEMI
8226#endif
Denis Vlasenko87d5fd92008-07-26 13:48:35 +00008227 unsigned is_or = n->type - NAND;
Eric Andersenc470f442003-07-28 09:56:35 +00008228 evaltree(
8229 n->nbinary.ch1,
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008230 (flags | ((is_or >> 1) - 1)) & EV_TESTED
Eric Andersenc470f442003-07-28 09:56:35 +00008231 );
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008232 if (!exitstatus == is_or)
Eric Andersenc470f442003-07-28 09:56:35 +00008233 break;
8234 if (!evalskip) {
8235 n = n->nbinary.ch2;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008236 evaln:
Eric Andersenc470f442003-07-28 09:56:35 +00008237 evalfn = evaltree;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008238 calleval:
Eric Andersenc470f442003-07-28 09:56:35 +00008239 evalfn(n, flags);
8240 break;
8241 }
8242 break;
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008243 }
Eric Andersenc470f442003-07-28 09:56:35 +00008244 case NIF:
8245 evaltree(n->nif.test, EV_TESTED);
8246 if (evalskip)
8247 break;
8248 if (exitstatus == 0) {
8249 n = n->nif.ifpart;
8250 goto evaln;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008251 }
8252 if (n->nif.elsepart) {
Eric Andersenc470f442003-07-28 09:56:35 +00008253 n = n->nif.elsepart;
8254 goto evaln;
8255 }
8256 goto success;
8257 case NDEFUN:
8258 defun(n->narg.text, n->narg.next);
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008259 success:
Eric Andersenc470f442003-07-28 09:56:35 +00008260 status = 0;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008261 setstatus:
Eric Andersenc470f442003-07-28 09:56:35 +00008262 exitstatus = status;
8263 break;
8264 }
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008265
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008266 out:
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +00008267 exception_handler = savehandler;
8268 out1:
8269 if (checkexit & exitstatus)
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00008270 evalskip |= SKIPEVAL;
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02008271 else if (pending_sig && dotrap())
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00008272 goto exexit;
8273
8274 if (flags & EV_EXIT) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008275 exexit:
Denis Vlasenkob012b102007-02-19 22:43:01 +00008276 raise_exception(EXEXIT);
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00008277 }
Denis Vlasenko653d8e72009-03-19 21:59:35 +00008278
8279 RESTORE_INT(int_level);
8280 TRACE(("leaving evaltree (no interrupts)\n"));
Eric Andersen62483552001-07-10 06:09:16 +00008281}
8282
Eric Andersenc470f442003-07-28 09:56:35 +00008283#if !defined(__alpha__) || (defined(__GNUC__) && __GNUC__ >= 3)
8284static
8285#endif
8286void evaltreenr(union node *, int) __attribute__ ((alias("evaltree"),__noreturn__));
8287
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008288static void
Eric Andersenc470f442003-07-28 09:56:35 +00008289evalloop(union node *n, int flags)
Eric Andersencb57d552001-06-28 07:25:16 +00008290{
8291 int status;
8292
8293 loopnest++;
8294 status = 0;
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008295 flags &= EV_TESTED;
Eric Andersencb57d552001-06-28 07:25:16 +00008296 for (;;) {
Eric Andersenc470f442003-07-28 09:56:35 +00008297 int i;
8298
Eric Andersencb57d552001-06-28 07:25:16 +00008299 evaltree(n->nbinary.ch1, EV_TESTED);
8300 if (evalskip) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008301 skipping:
8302 if (evalskip == SKIPCONT && --skipcount <= 0) {
Eric Andersencb57d552001-06-28 07:25:16 +00008303 evalskip = 0;
8304 continue;
8305 }
8306 if (evalskip == SKIPBREAK && --skipcount <= 0)
8307 evalskip = 0;
8308 break;
8309 }
Eric Andersenc470f442003-07-28 09:56:35 +00008310 i = exitstatus;
8311 if (n->type != NWHILE)
8312 i = !i;
8313 if (i != 0)
8314 break;
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008315 evaltree(n->nbinary.ch2, flags);
Eric Andersencb57d552001-06-28 07:25:16 +00008316 status = exitstatus;
8317 if (evalskip)
8318 goto skipping;
8319 }
8320 loopnest--;
8321 exitstatus = status;
8322}
8323
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008324static void
Eric Andersenc470f442003-07-28 09:56:35 +00008325evalfor(union node *n, int flags)
Eric Andersencb57d552001-06-28 07:25:16 +00008326{
8327 struct arglist arglist;
8328 union node *argp;
8329 struct strlist *sp;
8330 struct stackmark smark;
8331
8332 setstackmark(&smark);
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00008333 arglist.list = NULL;
Eric Andersencb57d552001-06-28 07:25:16 +00008334 arglist.lastp = &arglist.list;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008335 for (argp = n->nfor.args; argp; argp = argp->narg.next) {
Eric Andersencb57d552001-06-28 07:25:16 +00008336 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE | EXP_RECORD);
Eric Andersenc470f442003-07-28 09:56:35 +00008337 /* XXX */
Eric Andersencb57d552001-06-28 07:25:16 +00008338 if (evalskip)
8339 goto out;
8340 }
8341 *arglist.lastp = NULL;
8342
8343 exitstatus = 0;
8344 loopnest++;
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008345 flags &= EV_TESTED;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008346 for (sp = arglist.list; sp; sp = sp->next) {
Eric Andersencb57d552001-06-28 07:25:16 +00008347 setvar(n->nfor.var, sp->text, 0);
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008348 evaltree(n->nfor.body, flags);
Eric Andersencb57d552001-06-28 07:25:16 +00008349 if (evalskip) {
8350 if (evalskip == SKIPCONT && --skipcount <= 0) {
8351 evalskip = 0;
8352 continue;
8353 }
8354 if (evalskip == SKIPBREAK && --skipcount <= 0)
8355 evalskip = 0;
8356 break;
8357 }
8358 }
8359 loopnest--;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008360 out:
Eric Andersencb57d552001-06-28 07:25:16 +00008361 popstackmark(&smark);
8362}
8363
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008364static void
Eric Andersenc470f442003-07-28 09:56:35 +00008365evalcase(union node *n, int flags)
Eric Andersencb57d552001-06-28 07:25:16 +00008366{
8367 union node *cp;
8368 union node *patp;
8369 struct arglist arglist;
8370 struct stackmark smark;
8371
8372 setstackmark(&smark);
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00008373 arglist.list = NULL;
Eric Andersencb57d552001-06-28 07:25:16 +00008374 arglist.lastp = &arglist.list;
Eric Andersencb57d552001-06-28 07:25:16 +00008375 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
Eric Andersenc470f442003-07-28 09:56:35 +00008376 exitstatus = 0;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008377 for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
8378 for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
Eric Andersencb57d552001-06-28 07:25:16 +00008379 if (casematch(patp, arglist.list->text)) {
8380 if (evalskip == 0) {
8381 evaltree(cp->nclist.body, flags);
8382 }
8383 goto out;
8384 }
8385 }
8386 }
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008387 out:
Eric Andersencb57d552001-06-28 07:25:16 +00008388 popstackmark(&smark);
8389}
8390
Eric Andersenc470f442003-07-28 09:56:35 +00008391/*
8392 * Kick off a subshell to evaluate a tree.
8393 */
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008394static void
Eric Andersenc470f442003-07-28 09:56:35 +00008395evalsubshell(union node *n, int flags)
8396{
8397 struct job *jp;
8398 int backgnd = (n->type == NBACKGND);
8399 int status;
8400
8401 expredir(n->nredir.redirect);
8402 if (!backgnd && flags & EV_EXIT && !trap[0])
8403 goto nofork;
Denis Vlasenkob012b102007-02-19 22:43:01 +00008404 INT_OFF;
Denis Vlasenko68404f12008-03-17 09:00:54 +00008405 jp = makejob(/*n,*/ 1);
Eric Andersenc470f442003-07-28 09:56:35 +00008406 if (forkshell(jp, n, backgnd) == 0) {
Denis Vlasenkob012b102007-02-19 22:43:01 +00008407 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00008408 flags |= EV_EXIT;
8409 if (backgnd)
8410 flags &=~ EV_TESTED;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00008411 nofork:
Eric Andersenc470f442003-07-28 09:56:35 +00008412 redirect(n->nredir.redirect, 0);
8413 evaltreenr(n->nredir.n, flags);
8414 /* never returns */
8415 }
8416 status = 0;
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00008417 if (!backgnd)
Eric Andersenc470f442003-07-28 09:56:35 +00008418 status = waitforjob(jp);
8419 exitstatus = status;
Denis Vlasenkob012b102007-02-19 22:43:01 +00008420 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00008421}
8422
Eric Andersenc470f442003-07-28 09:56:35 +00008423/*
8424 * Compute the names of the files in a redirection list.
8425 */
Denis Vlasenko99eb8502007-02-23 21:09:49 +00008426static void fixredir(union node *, const char *, int);
Eric Andersenc470f442003-07-28 09:56:35 +00008427static void
8428expredir(union node *n)
8429{
8430 union node *redir;
8431
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008432 for (redir = n; redir; redir = redir->nfile.next) {
Eric Andersenc470f442003-07-28 09:56:35 +00008433 struct arglist fn;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008434
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00008435 fn.list = NULL;
Eric Andersenc470f442003-07-28 09:56:35 +00008436 fn.lastp = &fn.list;
8437 switch (redir->type) {
8438 case NFROMTO:
8439 case NFROM:
8440 case NTO:
Denis Vlasenko559691a2008-10-05 18:39:31 +00008441#if ENABLE_ASH_BASH_COMPAT
8442 case NTO2:
8443#endif
Eric Andersenc470f442003-07-28 09:56:35 +00008444 case NCLOBBER:
8445 case NAPPEND:
8446 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
Denis Vlasenko559691a2008-10-05 18:39:31 +00008447#if ENABLE_ASH_BASH_COMPAT
8448 store_expfname:
8449#endif
Eric Andersenc470f442003-07-28 09:56:35 +00008450 redir->nfile.expfname = fn.list->text;
8451 break;
8452 case NFROMFD:
Denis Vlasenko559691a2008-10-05 18:39:31 +00008453 case NTOFD: /* >& */
Eric Andersenc470f442003-07-28 09:56:35 +00008454 if (redir->ndup.vname) {
8455 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008456 if (fn.list == NULL)
Denis Vlasenkob012b102007-02-19 22:43:01 +00008457 ash_msg_and_raise_error("redir error");
Denis Vlasenko559691a2008-10-05 18:39:31 +00008458#if ENABLE_ASH_BASH_COMPAT
8459//FIXME: we used expandarg with different args!
8460 if (!isdigit_str9(fn.list->text)) {
8461 /* >&file, not >&fd */
8462 if (redir->nfile.fd != 1) /* 123>&file - BAD */
8463 ash_msg_and_raise_error("redir error");
8464 redir->type = NTO2;
8465 goto store_expfname;
8466 }
8467#endif
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008468 fixredir(redir, fn.list->text, 1);
Eric Andersenc470f442003-07-28 09:56:35 +00008469 }
8470 break;
8471 }
8472 }
8473}
8474
Eric Andersencb57d552001-06-28 07:25:16 +00008475/*
Eric Andersencb57d552001-06-28 07:25:16 +00008476 * Evaluate a pipeline. All the processes in the pipeline are children
8477 * of the process creating the pipeline. (This differs from some versions
8478 * of the shell, which make the last process in a pipeline the parent
8479 * of all the rest.)
8480 */
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008481static void
Eric Andersenc470f442003-07-28 09:56:35 +00008482evalpipe(union node *n, int flags)
Eric Andersencb57d552001-06-28 07:25:16 +00008483{
8484 struct job *jp;
8485 struct nodelist *lp;
8486 int pipelen;
8487 int prevfd;
8488 int pip[2];
8489
Eric Andersenc470f442003-07-28 09:56:35 +00008490 TRACE(("evalpipe(0x%lx) called\n", (long)n));
Eric Andersencb57d552001-06-28 07:25:16 +00008491 pipelen = 0;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008492 for (lp = n->npipe.cmdlist; lp; lp = lp->next)
Eric Andersencb57d552001-06-28 07:25:16 +00008493 pipelen++;
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008494 flags |= EV_EXIT;
Denis Vlasenkob012b102007-02-19 22:43:01 +00008495 INT_OFF;
Denis Vlasenko68404f12008-03-17 09:00:54 +00008496 jp = makejob(/*n,*/ pipelen);
Eric Andersencb57d552001-06-28 07:25:16 +00008497 prevfd = -1;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008498 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008499 prehash(lp->n);
Eric Andersencb57d552001-06-28 07:25:16 +00008500 pip[1] = -1;
8501 if (lp->next) {
8502 if (pipe(pip) < 0) {
8503 close(prevfd);
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00008504 ash_msg_and_raise_error("pipe call failed");
Eric Andersencb57d552001-06-28 07:25:16 +00008505 }
8506 }
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00008507 if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
Denis Vlasenkob012b102007-02-19 22:43:01 +00008508 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00008509 if (pip[1] >= 0) {
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008510 close(pip[0]);
Eric Andersencb57d552001-06-28 07:25:16 +00008511 }
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008512 if (prevfd > 0) {
8513 dup2(prevfd, 0);
8514 close(prevfd);
8515 }
8516 if (pip[1] > 1) {
8517 dup2(pip[1], 1);
8518 close(pip[1]);
8519 }
Eric Andersenc470f442003-07-28 09:56:35 +00008520 evaltreenr(lp->n, flags);
8521 /* never returns */
Eric Andersencb57d552001-06-28 07:25:16 +00008522 }
8523 if (prevfd >= 0)
8524 close(prevfd);
8525 prevfd = pip[0];
Denis Vlasenkob9e70dd2009-03-20 01:24:08 +00008526 /* Don't want to trigger debugging */
8527 if (pip[1] != -1)
8528 close(pip[1]);
Eric Andersencb57d552001-06-28 07:25:16 +00008529 }
Denis Vlasenko2dc240c2008-07-24 06:07:50 +00008530 if (n->npipe.pipe_backgnd == 0) {
Eric Andersencb57d552001-06-28 07:25:16 +00008531 exitstatus = waitforjob(jp);
8532 TRACE(("evalpipe: job done exit status %d\n", exitstatus));
Eric Andersencb57d552001-06-28 07:25:16 +00008533 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00008534 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00008535}
8536
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008537/*
8538 * Controls whether the shell is interactive or not.
8539 */
8540static void
8541setinteractive(int on)
8542{
Denis Vlasenkob07a4962008-06-22 13:16:23 +00008543 static smallint is_interactive;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008544
8545 if (++on == is_interactive)
8546 return;
8547 is_interactive = on;
8548 setsignal(SIGINT);
8549 setsignal(SIGQUIT);
8550 setsignal(SIGTERM);
8551#if !ENABLE_FEATURE_SH_EXTRA_QUIET
8552 if (is_interactive > 1) {
8553 /* Looks like they want an interactive shell */
Denis Vlasenkoca525b42007-06-13 12:27:17 +00008554 static smallint did_banner;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008555
Denis Vlasenkoca525b42007-06-13 12:27:17 +00008556 if (!did_banner) {
Denys Vlasenkoc34c0332009-09-29 12:25:30 +02008557 /* note: ash and hush share this string */
8558 out1fmt("\n\n%s %s\n"
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008559 "Enter 'help' for a list of built-in commands."
8560 "\n\n",
Denys Vlasenkoc34c0332009-09-29 12:25:30 +02008561 bb_banner,
8562 "built-in shell (ash)"
8563 );
Denis Vlasenkoca525b42007-06-13 12:27:17 +00008564 did_banner = 1;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008565 }
8566 }
8567#endif
8568}
8569
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008570static void
8571optschanged(void)
8572{
8573#if DEBUG
8574 opentrace();
8575#endif
8576 setinteractive(iflag);
8577 setjobctl(mflag);
Denis Vlasenkob07a4962008-06-22 13:16:23 +00008578#if ENABLE_FEATURE_EDITING_VI
8579 if (viflag)
8580 line_input_state->flags |= VI_MODE;
8581 else
8582 line_input_state->flags &= ~VI_MODE;
8583#else
8584 viflag = 0; /* forcibly keep the option off */
8585#endif
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008586}
8587
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008588static struct localvar *localvars;
8589
8590/*
8591 * Called after a function returns.
8592 * Interrupts must be off.
8593 */
8594static void
8595poplocalvars(void)
8596{
8597 struct localvar *lvp;
8598 struct var *vp;
8599
8600 while ((lvp = localvars) != NULL) {
8601 localvars = lvp->next;
8602 vp = lvp->vp;
Denys Vlasenko883cea42009-07-11 15:31:59 +02008603 TRACE(("poplocalvar %s\n", vp ? vp->text : "-"));
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008604 if (vp == NULL) { /* $- saved */
8605 memcpy(optlist, lvp->text, sizeof(optlist));
8606 free((char*)lvp->text);
8607 optschanged();
8608 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
8609 unsetvar(vp->text);
8610 } else {
8611 if (vp->func)
8612 (*vp->func)(strchrnul(lvp->text, '=') + 1);
8613 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
8614 free((char*)vp->text);
8615 vp->flags = lvp->flags;
8616 vp->text = lvp->text;
8617 }
8618 free(lvp);
8619 }
8620}
8621
8622static int
8623evalfun(struct funcnode *func, int argc, char **argv, int flags)
8624{
8625 volatile struct shparam saveparam;
8626 struct localvar *volatile savelocalvars;
8627 struct jmploc *volatile savehandler;
8628 struct jmploc jmploc;
8629 int e;
8630
8631 saveparam = shellparam;
8632 savelocalvars = localvars;
8633 e = setjmp(jmploc.loc);
8634 if (e) {
8635 goto funcdone;
8636 }
8637 INT_OFF;
8638 savehandler = exception_handler;
8639 exception_handler = &jmploc;
8640 localvars = NULL;
Denis Vlasenko01631112007-12-16 17:20:38 +00008641 shellparam.malloced = 0;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008642 func->count++;
8643 funcnest++;
8644 INT_ON;
8645 shellparam.nparam = argc - 1;
8646 shellparam.p = argv + 1;
8647#if ENABLE_ASH_GETOPTS
8648 shellparam.optind = 1;
8649 shellparam.optoff = -1;
8650#endif
8651 evaltree(&func->n, flags & EV_TESTED);
Denis Vlasenko01631112007-12-16 17:20:38 +00008652 funcdone:
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008653 INT_OFF;
8654 funcnest--;
8655 freefunc(func);
8656 poplocalvars();
8657 localvars = savelocalvars;
8658 freeparam(&shellparam);
8659 shellparam = saveparam;
8660 exception_handler = savehandler;
8661 INT_ON;
8662 evalskip &= ~SKIPFUNC;
8663 return e;
8664}
8665
Denis Vlasenko131ae172007-02-18 13:00:19 +00008666#if ENABLE_ASH_CMDCMD
Denis Vlasenkoaa744452007-02-23 01:04:22 +00008667static char **
8668parse_command_args(char **argv, const char **path)
Eric Andersenc470f442003-07-28 09:56:35 +00008669{
8670 char *cp, c;
8671
8672 for (;;) {
8673 cp = *++argv;
8674 if (!cp)
8675 return 0;
8676 if (*cp++ != '-')
8677 break;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008678 c = *cp++;
8679 if (!c)
Eric Andersenc470f442003-07-28 09:56:35 +00008680 break;
8681 if (c == '-' && !*cp) {
8682 argv++;
8683 break;
8684 }
8685 do {
8686 switch (c) {
8687 case 'p':
Denis Vlasenkof5f75c52007-06-12 22:35:19 +00008688 *path = bb_default_path;
Eric Andersenc470f442003-07-28 09:56:35 +00008689 break;
8690 default:
8691 /* run 'typecmd' for other options */
8692 return 0;
8693 }
Denis Vlasenko9650f362007-02-23 01:04:37 +00008694 c = *cp++;
8695 } while (c);
Eric Andersenc470f442003-07-28 09:56:35 +00008696 }
8697 return argv;
8698}
8699#endif
8700
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008701/*
8702 * Make a variable a local variable. When a variable is made local, it's
8703 * value and flags are saved in a localvar structure. The saved values
8704 * will be restored when the shell function returns. We handle the name
8705 * "-" as a special case.
8706 */
8707static void
8708mklocal(char *name)
8709{
8710 struct localvar *lvp;
8711 struct var **vpp;
8712 struct var *vp;
8713
8714 INT_OFF;
Denis Vlasenko838ffd52008-02-21 04:32:08 +00008715 lvp = ckzalloc(sizeof(struct localvar));
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008716 if (LONE_DASH(name)) {
8717 char *p;
8718 p = ckmalloc(sizeof(optlist));
8719 lvp->text = memcpy(p, optlist, sizeof(optlist));
8720 vp = NULL;
8721 } else {
8722 char *eq;
8723
8724 vpp = hashvar(name);
8725 vp = *findvar(vpp, name);
8726 eq = strchr(name, '=');
8727 if (vp == NULL) {
8728 if (eq)
8729 setvareq(name, VSTRFIXED);
8730 else
8731 setvar(name, NULL, VSTRFIXED);
8732 vp = *vpp; /* the new variable */
8733 lvp->flags = VUNSET;
8734 } else {
8735 lvp->text = vp->text;
8736 lvp->flags = vp->flags;
8737 vp->flags |= VSTRFIXED|VTEXTFIXED;
8738 if (eq)
8739 setvareq(name, 0);
8740 }
8741 }
8742 lvp->vp = vp;
8743 lvp->next = localvars;
8744 localvars = lvp;
8745 INT_ON;
8746}
8747
8748/*
8749 * The "local" command.
8750 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008751static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008752localcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008753{
8754 char *name;
8755
8756 argv = argptr;
8757 while ((name = *argv++) != NULL) {
8758 mklocal(name);
8759 }
8760 return 0;
8761}
8762
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008763static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008764falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008765{
8766 return 1;
8767}
8768
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008769static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008770truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008771{
8772 return 0;
8773}
8774
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008775static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008776execcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008777{
Denis Vlasenko68404f12008-03-17 09:00:54 +00008778 if (argv[1]) {
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008779 iflag = 0; /* exit on error */
8780 mflag = 0;
8781 optschanged();
8782 shellexec(argv + 1, pathval(), 0);
8783 }
8784 return 0;
8785}
8786
8787/*
8788 * The return command.
8789 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008790static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008791returncmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008792{
8793 /*
8794 * If called outside a function, do what ksh does;
8795 * skip the rest of the file.
8796 */
8797 evalskip = funcnest ? SKIPFUNC : SKIPFILE;
8798 return argv[1] ? number(argv[1]) : exitstatus;
8799}
8800
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008801/* Forward declarations for builtintab[] */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008802static int breakcmd(int, char **) FAST_FUNC;
8803static int dotcmd(int, char **) FAST_FUNC;
8804static int evalcmd(int, char **) FAST_FUNC;
8805static int exitcmd(int, char **) FAST_FUNC;
8806static int exportcmd(int, char **) FAST_FUNC;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008807#if ENABLE_ASH_GETOPTS
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008808static int getoptscmd(int, char **) FAST_FUNC;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008809#endif
Denis Vlasenko52764022007-02-24 13:42:56 +00008810#if !ENABLE_FEATURE_SH_EXTRA_QUIET
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008811static int helpcmd(int, char **) FAST_FUNC;
Denis Vlasenko52764022007-02-24 13:42:56 +00008812#endif
Mike Frysinger98c52642009-04-02 10:02:37 +00008813#if ENABLE_SH_MATH_SUPPORT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008814static int letcmd(int, char **) FAST_FUNC;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008815#endif
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008816static int readcmd(int, char **) FAST_FUNC;
8817static int setcmd(int, char **) FAST_FUNC;
8818static int shiftcmd(int, char **) FAST_FUNC;
8819static int timescmd(int, char **) FAST_FUNC;
8820static int trapcmd(int, char **) FAST_FUNC;
8821static int umaskcmd(int, char **) FAST_FUNC;
8822static int unsetcmd(int, char **) FAST_FUNC;
8823static int ulimitcmd(int, char **) FAST_FUNC;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008824
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008825#define BUILTIN_NOSPEC "0"
8826#define BUILTIN_SPECIAL "1"
8827#define BUILTIN_REGULAR "2"
8828#define BUILTIN_SPEC_REG "3"
8829#define BUILTIN_ASSIGN "4"
8830#define BUILTIN_SPEC_ASSG "5"
8831#define BUILTIN_REG_ASSG "6"
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008832#define BUILTIN_SPEC_REG_ASSG "7"
8833
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008834/* Stubs for calling non-FAST_FUNC's */
Denys Vlasenko2634bf32009-06-09 18:40:07 +02008835#if ENABLE_ASH_BUILTIN_ECHO
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008836static int FAST_FUNC echocmd(int argc, char **argv) { return echo_main(argc, argv); }
Denys Vlasenko2634bf32009-06-09 18:40:07 +02008837#endif
8838#if ENABLE_ASH_BUILTIN_PRINTF
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008839static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
Denys Vlasenko2634bf32009-06-09 18:40:07 +02008840#endif
8841#if ENABLE_ASH_BUILTIN_TEST
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008842static int FAST_FUNC testcmd(int argc, char **argv) { return test_main(argc, argv); }
Denys Vlasenko2634bf32009-06-09 18:40:07 +02008843#endif
Denis Vlasenko468aea22008-04-01 14:47:57 +00008844
Denis Vlasenkof7d56652008-03-25 05:51:41 +00008845/* Keep these in proper order since it is searched via bsearch() */
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008846static const struct builtincmd builtintab[] = {
8847 { BUILTIN_SPEC_REG ".", dotcmd },
8848 { BUILTIN_SPEC_REG ":", truecmd },
8849#if ENABLE_ASH_BUILTIN_TEST
Denis Vlasenkocd2663f2008-06-01 22:36:39 +00008850 { BUILTIN_REGULAR "[", testcmd },
Denis Vlasenko80591b02008-03-25 07:49:43 +00008851#if ENABLE_ASH_BASH_COMPAT
Denis Vlasenkocd2663f2008-06-01 22:36:39 +00008852 { BUILTIN_REGULAR "[[", testcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008853#endif
Denis Vlasenko80591b02008-03-25 07:49:43 +00008854#endif
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008855#if ENABLE_ASH_ALIAS
8856 { BUILTIN_REG_ASSG "alias", aliascmd },
8857#endif
8858#if JOBS
8859 { BUILTIN_REGULAR "bg", fg_bgcmd },
8860#endif
8861 { BUILTIN_SPEC_REG "break", breakcmd },
8862 { BUILTIN_REGULAR "cd", cdcmd },
8863 { BUILTIN_NOSPEC "chdir", cdcmd },
8864#if ENABLE_ASH_CMDCMD
8865 { BUILTIN_REGULAR "command", commandcmd },
8866#endif
8867 { BUILTIN_SPEC_REG "continue", breakcmd },
8868#if ENABLE_ASH_BUILTIN_ECHO
8869 { BUILTIN_REGULAR "echo", echocmd },
8870#endif
8871 { BUILTIN_SPEC_REG "eval", evalcmd },
8872 { BUILTIN_SPEC_REG "exec", execcmd },
8873 { BUILTIN_SPEC_REG "exit", exitcmd },
8874 { BUILTIN_SPEC_REG_ASSG "export", exportcmd },
8875 { BUILTIN_REGULAR "false", falsecmd },
8876#if JOBS
8877 { BUILTIN_REGULAR "fg", fg_bgcmd },
8878#endif
8879#if ENABLE_ASH_GETOPTS
8880 { BUILTIN_REGULAR "getopts", getoptscmd },
8881#endif
8882 { BUILTIN_NOSPEC "hash", hashcmd },
8883#if !ENABLE_FEATURE_SH_EXTRA_QUIET
8884 { BUILTIN_NOSPEC "help", helpcmd },
8885#endif
8886#if JOBS
8887 { BUILTIN_REGULAR "jobs", jobscmd },
8888 { BUILTIN_REGULAR "kill", killcmd },
8889#endif
Mike Frysinger98c52642009-04-02 10:02:37 +00008890#if ENABLE_SH_MATH_SUPPORT
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008891 { BUILTIN_NOSPEC "let", letcmd },
8892#endif
8893 { BUILTIN_ASSIGN "local", localcmd },
Denis Vlasenkocd2663f2008-06-01 22:36:39 +00008894#if ENABLE_ASH_BUILTIN_PRINTF
8895 { BUILTIN_REGULAR "printf", printfcmd },
8896#endif
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008897 { BUILTIN_NOSPEC "pwd", pwdcmd },
8898 { BUILTIN_REGULAR "read", readcmd },
8899 { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
8900 { BUILTIN_SPEC_REG "return", returncmd },
8901 { BUILTIN_SPEC_REG "set", setcmd },
8902 { BUILTIN_SPEC_REG "shift", shiftcmd },
8903 { BUILTIN_SPEC_REG "source", dotcmd },
8904#if ENABLE_ASH_BUILTIN_TEST
Denis Vlasenkocd2663f2008-06-01 22:36:39 +00008905 { BUILTIN_REGULAR "test", testcmd },
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008906#endif
8907 { BUILTIN_SPEC_REG "times", timescmd },
8908 { BUILTIN_SPEC_REG "trap", trapcmd },
8909 { BUILTIN_REGULAR "true", truecmd },
8910 { BUILTIN_NOSPEC "type", typecmd },
8911 { BUILTIN_NOSPEC "ulimit", ulimitcmd },
8912 { BUILTIN_REGULAR "umask", umaskcmd },
8913#if ENABLE_ASH_ALIAS
8914 { BUILTIN_REGULAR "unalias", unaliascmd },
8915#endif
8916 { BUILTIN_SPEC_REG "unset", unsetcmd },
8917 { BUILTIN_REGULAR "wait", waitcmd },
8918};
8919
Denis Vlasenko80591b02008-03-25 07:49:43 +00008920/* Should match the above table! */
8921#define COMMANDCMD (builtintab + \
8922 2 + \
8923 1 * ENABLE_ASH_BUILTIN_TEST + \
8924 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
8925 1 * ENABLE_ASH_ALIAS + \
8926 1 * ENABLE_ASH_JOB_CONTROL + \
8927 3)
8928#define EXECCMD (builtintab + \
8929 2 + \
8930 1 * ENABLE_ASH_BUILTIN_TEST + \
8931 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
8932 1 * ENABLE_ASH_ALIAS + \
8933 1 * ENABLE_ASH_JOB_CONTROL + \
8934 3 + \
8935 1 * ENABLE_ASH_CMDCMD + \
8936 1 + \
8937 ENABLE_ASH_BUILTIN_ECHO + \
8938 1)
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008939
8940/*
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008941 * Search the table of builtin commands.
8942 */
8943static struct builtincmd *
8944find_builtin(const char *name)
8945{
8946 struct builtincmd *bp;
8947
8948 bp = bsearch(
Denis Vlasenko80b8b392007-06-25 10:55:35 +00008949 name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008950 pstrcmp
8951 );
8952 return bp;
8953}
8954
8955/*
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008956 * Execute a simple command.
8957 */
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008958static int
8959isassignment(const char *p)
Paul Foxc3850c82005-07-20 18:23:39 +00008960{
8961 const char *q = endofname(p);
8962 if (p == q)
8963 return 0;
8964 return *q == '=';
8965}
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02008966static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00008967bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008968{
8969 /* Preserve exitstatus of a previous possible redirection
8970 * as POSIX mandates */
8971 return back_exitstatus;
8972}
Denys Vlasenko641dd7b2009-06-11 19:30:19 +02008973static void
Eric Andersenc470f442003-07-28 09:56:35 +00008974evalcommand(union node *cmd, int flags)
8975{
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00008976 static const struct builtincmd null_bltin = {
8977 "\0\0", bltincmd /* why three NULs? */
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008978 };
Eric Andersenc470f442003-07-28 09:56:35 +00008979 struct stackmark smark;
8980 union node *argp;
8981 struct arglist arglist;
8982 struct arglist varlist;
8983 char **argv;
8984 int argc;
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00008985 const struct strlist *sp;
Eric Andersenc470f442003-07-28 09:56:35 +00008986 struct cmdentry cmdentry;
8987 struct job *jp;
8988 char *lastarg;
8989 const char *path;
8990 int spclbltin;
Eric Andersenc470f442003-07-28 09:56:35 +00008991 int status;
8992 char **nargv;
Paul Foxc3850c82005-07-20 18:23:39 +00008993 struct builtincmd *bcmd;
Denis Vlasenko34c73c42008-08-16 11:48:02 +00008994 smallint cmd_is_exec;
8995 smallint pseudovarflag = 0;
Eric Andersenc470f442003-07-28 09:56:35 +00008996
8997 /* First expand the arguments. */
8998 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
8999 setstackmark(&smark);
9000 back_exitstatus = 0;
9001
9002 cmdentry.cmdtype = CMDBUILTIN;
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00009003 cmdentry.u.cmd = &null_bltin;
Eric Andersenc470f442003-07-28 09:56:35 +00009004 varlist.lastp = &varlist.list;
9005 *varlist.lastp = NULL;
9006 arglist.lastp = &arglist.list;
9007 *arglist.lastp = NULL;
9008
9009 argc = 0;
Denis Vlasenkob012b102007-02-19 22:43:01 +00009010 if (cmd->ncmd.args) {
Paul Foxc3850c82005-07-20 18:23:39 +00009011 bcmd = find_builtin(cmd->ncmd.args->narg.text);
9012 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
9013 }
9014
Eric Andersenc470f442003-07-28 09:56:35 +00009015 for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
9016 struct strlist **spp;
9017
9018 spp = arglist.lastp;
"Vladimir N. Oleynik"bef14d72005-09-05 13:25:11 +00009019 if (pseudovarflag && isassignment(argp->narg.text))
Paul Foxc3850c82005-07-20 18:23:39 +00009020 expandarg(argp, &arglist, EXP_VARTILDE);
9021 else
9022 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
9023
Eric Andersenc470f442003-07-28 09:56:35 +00009024 for (sp = *spp; sp; sp = sp->next)
9025 argc++;
9026 }
9027
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +00009028 argv = nargv = stalloc(sizeof(char *) * (argc + 1));
Denis Vlasenko2da584f2007-02-19 22:44:05 +00009029 for (sp = arglist.list; sp; sp = sp->next) {
Eric Andersenc470f442003-07-28 09:56:35 +00009030 TRACE(("evalcommand arg: %s\n", sp->text));
9031 *nargv++ = sp->text;
9032 }
9033 *nargv = NULL;
9034
9035 lastarg = NULL;
9036 if (iflag && funcnest == 0 && argc > 0)
9037 lastarg = nargv[-1];
9038
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009039 preverrout_fd = 2;
Eric Andersenc470f442003-07-28 09:56:35 +00009040 expredir(cmd->ncmd.redirect);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009041 status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
Eric Andersenc470f442003-07-28 09:56:35 +00009042
9043 path = vpath.text;
9044 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
9045 struct strlist **spp;
9046 char *p;
9047
9048 spp = varlist.lastp;
9049 expandarg(argp, &varlist, EXP_VARTILDE);
9050
9051 /*
9052 * Modify the command lookup path, if a PATH= assignment
9053 * is present
9054 */
9055 p = (*spp)->text;
9056 if (varequal(p, path))
9057 path = p;
9058 }
9059
9060 /* Print the command if xflag is set. */
9061 if (xflag) {
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009062 int n;
9063 const char *p = " %s";
Eric Andersenc470f442003-07-28 09:56:35 +00009064
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009065 p++;
Denis Vlasenko0de37e12007-10-17 11:08:53 +00009066 fdprintf(preverrout_fd, p, expandstr(ps4val()));
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009067
9068 sp = varlist.list;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +00009069 for (n = 0; n < 2; n++) {
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009070 while (sp) {
Denis Vlasenko0de37e12007-10-17 11:08:53 +00009071 fdprintf(preverrout_fd, p, sp->text);
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009072 sp = sp->next;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +00009073 if (*p == '%') {
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009074 p--;
9075 }
9076 }
9077 sp = arglist.list;
9078 }
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00009079 safe_write(preverrout_fd, "\n", 1);
Eric Andersenc470f442003-07-28 09:56:35 +00009080 }
9081
9082 cmd_is_exec = 0;
9083 spclbltin = -1;
9084
9085 /* Now locate the command. */
9086 if (argc) {
9087 const char *oldpath;
9088 int cmd_flag = DO_ERR;
9089
9090 path += 5;
9091 oldpath = path;
9092 for (;;) {
9093 find_command(argv[0], &cmdentry, cmd_flag, path);
9094 if (cmdentry.cmdtype == CMDUNKNOWN) {
Denys Vlasenko8131eea2009-11-02 14:19:51 +01009095 flush_stdout_stderr();
Denis Vlasenko6514c5e2008-07-24 13:41:37 +00009096 status = 127;
Eric Andersenc470f442003-07-28 09:56:35 +00009097 goto bail;
9098 }
9099
9100 /* implement bltin and command here */
9101 if (cmdentry.cmdtype != CMDBUILTIN)
9102 break;
9103 if (spclbltin < 0)
9104 spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
9105 if (cmdentry.u.cmd == EXECCMD)
Denis Vlasenko34c73c42008-08-16 11:48:02 +00009106 cmd_is_exec = 1;
Denis Vlasenko131ae172007-02-18 13:00:19 +00009107#if ENABLE_ASH_CMDCMD
Eric Andersenc470f442003-07-28 09:56:35 +00009108 if (cmdentry.u.cmd == COMMANDCMD) {
Eric Andersenc470f442003-07-28 09:56:35 +00009109 path = oldpath;
9110 nargv = parse_command_args(argv, &path);
9111 if (!nargv)
9112 break;
9113 argc -= nargv - argv;
9114 argv = nargv;
9115 cmd_flag |= DO_NOFUNC;
9116 } else
9117#endif
9118 break;
9119 }
9120 }
9121
9122 if (status) {
9123 /* We have a redirection error. */
9124 if (spclbltin > 0)
Denis Vlasenkob012b102007-02-19 22:43:01 +00009125 raise_exception(EXERROR);
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009126 bail:
Eric Andersenc470f442003-07-28 09:56:35 +00009127 exitstatus = status;
9128 goto out;
9129 }
9130
9131 /* Execute the command. */
9132 switch (cmdentry.cmdtype) {
9133 default:
Denis Vlasenkobe54d6b2008-10-27 14:25:52 +00009134
Denis Vlasenko9bc80d72008-04-12 20:07:53 +00009135#if ENABLE_FEATURE_SH_NOFORK
Denis Vlasenkobe54d6b2008-10-27 14:25:52 +00009136/* Hmmm... shouldn't it happen somewhere in forkshell() instead?
9137 * Why "fork off a child process if necessary" doesn't apply to NOFORK? */
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00009138 {
9139 /* find_command() encodes applet_no as (-2 - applet_no) */
9140 int applet_no = (- cmdentry.u.index - 2);
Denis Vlasenko9bc80d72008-04-12 20:07:53 +00009141 if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
Denis Vlasenko9bc80d72008-04-12 20:07:53 +00009142 listsetvar(varlist.list, VEXPORT|VSTACK);
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00009143 /* run <applet>_main() */
9144 exitstatus = run_nofork_applet(applet_no, argv);
Denis Vlasenko9bc80d72008-04-12 20:07:53 +00009145 break;
9146 }
Denis Vlasenko7465dbc2008-04-13 02:25:53 +00009147 }
Denis Vlasenko9bc80d72008-04-12 20:07:53 +00009148#endif
Eric Andersenc470f442003-07-28 09:56:35 +00009149 /* Fork off a child process if necessary. */
9150 if (!(flags & EV_EXIT) || trap[0]) {
Denis Vlasenkob012b102007-02-19 22:43:01 +00009151 INT_OFF;
Denis Vlasenko68404f12008-03-17 09:00:54 +00009152 jp = makejob(/*cmd,*/ 1);
Eric Andersenc470f442003-07-28 09:56:35 +00009153 if (forkshell(jp, cmd, FORK_FG) != 0) {
9154 exitstatus = waitforjob(jp);
Denis Vlasenkob012b102007-02-19 22:43:01 +00009155 INT_ON;
Denis Vlasenko653d8e72009-03-19 21:59:35 +00009156 TRACE(("forked child exited with %d\n", exitstatus));
Eric Andersenc470f442003-07-28 09:56:35 +00009157 break;
9158 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00009159 FORCE_INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00009160 }
9161 listsetvar(varlist.list, VEXPORT|VSTACK);
9162 shellexec(argv, path, cmdentry.u.index);
9163 /* NOTREACHED */
9164
9165 case CMDBUILTIN:
9166 cmdenviron = varlist.list;
9167 if (cmdenviron) {
9168 struct strlist *list = cmdenviron;
9169 int i = VNOSET;
9170 if (spclbltin > 0 || argc == 0) {
9171 i = 0;
9172 if (cmd_is_exec && argc > 1)
9173 i = VEXPORT;
9174 }
9175 listsetvar(list, i);
9176 }
Denis Vlasenkobe54d6b2008-10-27 14:25:52 +00009177 /* Tight loop with builtins only:
9178 * "while kill -0 $child; do true; done"
9179 * will never exit even if $child died, unless we do this
9180 * to reap the zombie and make kill detect that it's gone: */
9181 dowait(DOWAIT_NONBLOCK, NULL);
9182
Eric Andersenc470f442003-07-28 09:56:35 +00009183 if (evalbltin(cmdentry.u.cmd, argc, argv)) {
9184 int exit_status;
Denis Vlasenko7f88e342009-03-19 03:36:18 +00009185 int i = exception_type;
Eric Andersenc470f442003-07-28 09:56:35 +00009186 if (i == EXEXIT)
9187 goto raise;
Eric Andersenc470f442003-07-28 09:56:35 +00009188 exit_status = 2;
Eric Andersenc470f442003-07-28 09:56:35 +00009189 if (i == EXINT)
Denis Vlasenko991a1da2008-02-10 19:02:53 +00009190 exit_status = 128 + SIGINT;
Eric Andersenc470f442003-07-28 09:56:35 +00009191 if (i == EXSIG)
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02009192 exit_status = 128 + pending_sig;
Eric Andersenc470f442003-07-28 09:56:35 +00009193 exitstatus = exit_status;
Eric Andersenc470f442003-07-28 09:56:35 +00009194 if (i == EXINT || spclbltin > 0) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009195 raise:
Denis Vlasenko2da584f2007-02-19 22:44:05 +00009196 longjmp(exception_handler->loc, 1);
Eric Andersenc470f442003-07-28 09:56:35 +00009197 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00009198 FORCE_INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00009199 }
9200 break;
9201
9202 case CMDFUNCTION:
9203 listsetvar(varlist.list, 0);
Denis Vlasenkobe54d6b2008-10-27 14:25:52 +00009204 /* See above for the rationale */
9205 dowait(DOWAIT_NONBLOCK, NULL);
Eric Andersenc470f442003-07-28 09:56:35 +00009206 if (evalfun(cmdentry.u.func, argc, argv, flags))
9207 goto raise;
9208 break;
9209 }
9210
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009211 out:
Denis Vlasenko34c73c42008-08-16 11:48:02 +00009212 popredir(/*drop:*/ cmd_is_exec, /*restore:*/ cmd_is_exec);
Denis Vlasenko6514c5e2008-07-24 13:41:37 +00009213 if (lastarg) {
Eric Andersenc470f442003-07-28 09:56:35 +00009214 /* dsl: I think this is intended to be used to support
9215 * '_' in 'vi' command mode during line editing...
9216 * However I implemented that within libedit itself.
9217 */
9218 setvar("_", lastarg, 0);
Denis Vlasenko6514c5e2008-07-24 13:41:37 +00009219 }
Eric Andersenc470f442003-07-28 09:56:35 +00009220 popstackmark(&smark);
9221}
9222
9223static int
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009224evalbltin(const struct builtincmd *cmd, int argc, char **argv)
9225{
Eric Andersenc470f442003-07-28 09:56:35 +00009226 char *volatile savecmdname;
9227 struct jmploc *volatile savehandler;
9228 struct jmploc jmploc;
9229 int i;
9230
9231 savecmdname = commandname;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009232 i = setjmp(jmploc.loc);
9233 if (i)
Eric Andersenc470f442003-07-28 09:56:35 +00009234 goto cmddone;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00009235 savehandler = exception_handler;
9236 exception_handler = &jmploc;
Eric Andersenc470f442003-07-28 09:56:35 +00009237 commandname = argv[0];
9238 argptr = argv + 1;
9239 optptr = NULL; /* initialize nextopt */
9240 exitstatus = (*cmd->builtin)(argc, argv);
Denis Vlasenkob012b102007-02-19 22:43:01 +00009241 flush_stdout_stderr();
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009242 cmddone:
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00009243 exitstatus |= ferror(stdout);
Rob Landleyf296f0b2006-07-06 01:09:21 +00009244 clearerr(stdout);
Eric Andersenc470f442003-07-28 09:56:35 +00009245 commandname = savecmdname;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00009246 exception_handler = savehandler;
Eric Andersenc470f442003-07-28 09:56:35 +00009247
9248 return i;
9249}
9250
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009251static int
9252goodname(const char *p)
Glenn L McGrath16e45d72004-02-04 08:24:39 +00009253{
9254 return !*endofname(p);
9255}
9256
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009257
Glenn L McGrath50812ff2002-08-23 13:14:48 +00009258/*
9259 * Search for a command. This is called before we fork so that the
9260 * location of the command will be available in the parent as well as
Glenn L McGrath16e45d72004-02-04 08:24:39 +00009261 * the child. The check for "goodname" is an overly conservative
9262 * check that the name will not be subject to expansion.
Glenn L McGrath50812ff2002-08-23 13:14:48 +00009263 */
Eric Andersenc470f442003-07-28 09:56:35 +00009264static void
9265prehash(union node *n)
Glenn L McGrath50812ff2002-08-23 13:14:48 +00009266{
9267 struct cmdentry entry;
9268
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +00009269 if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
9270 find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
Glenn L McGrath50812ff2002-08-23 13:14:48 +00009271}
9272
Eric Andersencb57d552001-06-28 07:25:16 +00009273
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00009274/* ============ Builtin commands
9275 *
9276 * Builtin commands whose functions are closely tied to evaluation
9277 * are implemented here.
Eric Andersencb57d552001-06-28 07:25:16 +00009278 */
9279
9280/*
Eric Andersencb57d552001-06-28 07:25:16 +00009281 * Handle break and continue commands. Break, continue, and return are
9282 * all handled by setting the evalskip flag. The evaluation routines
9283 * above all check this flag, and if it is set they start skipping
9284 * commands rather than executing them. The variable skipcount is
9285 * the number of loops to break/continue, or the number of function
9286 * levels to return. (The latter is always 1.) It should probably
9287 * be an error to break out of more loops than exist, but it isn't
9288 * in the standard shell so we don't make it one here.
9289 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009290static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00009291breakcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +00009292{
Denis Vlasenko68404f12008-03-17 09:00:54 +00009293 int n = argv[1] ? number(argv[1]) : 1;
Eric Andersencb57d552001-06-28 07:25:16 +00009294
Aaron Lehmann2aef3a62001-12-31 06:03:12 +00009295 if (n <= 0)
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +02009296 ash_msg_and_raise_error(msg_illnum, argv[1]);
Eric Andersencb57d552001-06-28 07:25:16 +00009297 if (n > loopnest)
9298 n = loopnest;
9299 if (n > 0) {
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00009300 evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
Eric Andersencb57d552001-06-28 07:25:16 +00009301 skipcount = n;
9302 }
9303 return 0;
9304}
9305
Eric Andersenc470f442003-07-28 09:56:35 +00009306
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009307/* ============ input.c
9308 *
Eric Andersen90898442003-08-06 11:20:52 +00009309 * This implements the input routines used by the parser.
Eric Andersencb57d552001-06-28 07:25:16 +00009310 */
Denis Vlasenko99eb8502007-02-23 21:09:49 +00009311
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009312enum {
9313 INPUT_PUSH_FILE = 1,
9314 INPUT_NOFILE_OK = 2,
9315};
Eric Andersencb57d552001-06-28 07:25:16 +00009316
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009317static smallint checkkwd;
Denis Vlasenko99eb8502007-02-23 21:09:49 +00009318/* values of checkkwd variable */
9319#define CHKALIAS 0x1
9320#define CHKKWD 0x2
9321#define CHKNL 0x4
9322
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009323/*
9324 * Push a string back onto the input at this current parsefile level.
9325 * We handle aliases this way.
9326 */
9327#if !ENABLE_ASH_ALIAS
9328#define pushstring(s, ap) pushstring(s)
9329#endif
9330static void
9331pushstring(char *s, struct alias *ap)
9332{
9333 struct strpush *sp;
9334 int len;
9335
9336 len = strlen(s);
9337 INT_OFF;
9338 if (g_parsefile->strpush) {
9339 sp = ckzalloc(sizeof(*sp));
9340 sp->prev = g_parsefile->strpush;
9341 } else {
9342 sp = &(g_parsefile->basestrpush);
9343 }
9344 g_parsefile->strpush = sp;
9345 sp->prev_string = g_parsefile->next_to_pgetc;
9346 sp->prev_left_in_line = g_parsefile->left_in_line;
9347#if ENABLE_ASH_ALIAS
9348 sp->ap = ap;
9349 if (ap) {
9350 ap->flag |= ALIASINUSE;
9351 sp->string = s;
9352 }
9353#endif
9354 g_parsefile->next_to_pgetc = s;
9355 g_parsefile->left_in_line = len;
9356 INT_ON;
9357}
9358
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009359static void
9360popstring(void)
Eric Andersenc470f442003-07-28 09:56:35 +00009361{
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009362 struct strpush *sp = g_parsefile->strpush;
Eric Andersenc470f442003-07-28 09:56:35 +00009363
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009364 INT_OFF;
Denis Vlasenko131ae172007-02-18 13:00:19 +00009365#if ENABLE_ASH_ALIAS
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009366 if (sp->ap) {
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009367 if (g_parsefile->next_to_pgetc[-1] == ' '
9368 || g_parsefile->next_to_pgetc[-1] == '\t'
9369 ) {
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009370 checkkwd |= CHKALIAS;
Glenn L McGrath28939ad2004-07-21 10:20:19 +00009371 }
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009372 if (sp->string != sp->ap->val) {
9373 free(sp->string);
9374 }
9375 sp->ap->flag &= ~ALIASINUSE;
9376 if (sp->ap->flag & ALIASDEAD) {
9377 unalias(sp->ap->name);
9378 }
Glenn L McGrath28939ad2004-07-21 10:20:19 +00009379 }
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009380#endif
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009381 g_parsefile->next_to_pgetc = sp->prev_string;
9382 g_parsefile->left_in_line = sp->prev_left_in_line;
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009383 g_parsefile->strpush = sp->prev;
9384 if (sp != &(g_parsefile->basestrpush))
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009385 free(sp);
9386 INT_ON;
9387}
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009388
Denis Vlasenkoe27dafd2008-11-28 04:01:03 +00009389//FIXME: BASH_COMPAT with "...&" does TWO pungetc():
9390//it peeks whether it is &>, and then pushes back both chars.
9391//This function needs to save last *next_to_pgetc to buf[0]
9392//to make two pungetc() reliable. Currently,
9393// pgetc (out of buf: does preadfd), pgetc, pungetc, pungetc won't work...
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009394static int
9395preadfd(void)
Eric Andersencb57d552001-06-28 07:25:16 +00009396{
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00009397 int nr;
Denis Vlasenko6a0ad252008-07-25 13:34:05 +00009398 char *buf = g_parsefile->buf;
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00009399
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009400 g_parsefile->next_to_pgetc = buf;
Denis Vlasenko38f63192007-01-22 09:03:07 +00009401#if ENABLE_FEATURE_EDITING
Denis Vlasenko85c24712008-03-17 09:04:04 +00009402 retry:
Denis Vlasenko727752d2008-11-28 03:41:47 +00009403 if (!iflag || g_parsefile->fd != STDIN_FILENO)
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009404 nr = nonblock_safe_read(g_parsefile->fd, buf, BUFSIZ - 1);
Eric Andersenc470f442003-07-28 09:56:35 +00009405 else {
Denis Vlasenko38f63192007-01-22 09:03:07 +00009406#if ENABLE_FEATURE_TAB_COMPLETION
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009407 line_input_state->path_lookup = pathval();
Eric Andersen4a79c0e2004-09-08 10:01:07 +00009408#endif
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009409 nr = read_line_input(cmdedit_prompt, buf, BUFSIZ, line_input_state);
9410 if (nr == 0) {
9411 /* Ctrl+C pressed */
9412 if (trap[SIGINT]) {
Glenn L McGrath16e45d72004-02-04 08:24:39 +00009413 buf[0] = '\n';
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009414 buf[1] = '\0';
Glenn L McGrath16e45d72004-02-04 08:24:39 +00009415 raise(SIGINT);
9416 return 1;
9417 }
Eric Andersenc470f442003-07-28 09:56:35 +00009418 goto retry;
9419 }
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00009420 if (nr < 0 && errno == 0) {
Denis Vlasenko9cb220b2007-12-09 10:03:28 +00009421 /* Ctrl+D pressed */
Eric Andersenc470f442003-07-28 09:56:35 +00009422 nr = 0;
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00009423 }
Eric Andersencb57d552001-06-28 07:25:16 +00009424 }
9425#else
Denis Vlasenkocc3f20b2008-06-23 22:31:52 +00009426 nr = nonblock_safe_read(g_parsefile->fd, buf, BUFSIZ - 1);
Eric Andersencb57d552001-06-28 07:25:16 +00009427#endif
9428
Denis Vlasenkoe376d452008-02-20 22:23:24 +00009429#if 0
9430/* nonblock_safe_read() handles this problem */
Eric Andersencb57d552001-06-28 07:25:16 +00009431 if (nr < 0) {
Eric Andersencb57d552001-06-28 07:25:16 +00009432 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
Denis Vlasenkod37f2222007-08-19 13:42:08 +00009433 int flags = fcntl(0, F_GETFL);
Denis Vlasenko9cb220b2007-12-09 10:03:28 +00009434 if (flags >= 0 && (flags & O_NONBLOCK)) {
9435 flags &= ~O_NONBLOCK;
Eric Andersencb57d552001-06-28 07:25:16 +00009436 if (fcntl(0, F_SETFL, flags) >= 0) {
9437 out2str("sh: turning off NDELAY mode\n");
9438 goto retry;
9439 }
9440 }
9441 }
9442 }
Denis Vlasenkoe376d452008-02-20 22:23:24 +00009443#endif
Eric Andersencb57d552001-06-28 07:25:16 +00009444 return nr;
9445}
9446
9447/*
9448 * Refill the input buffer and return the next input character:
9449 *
9450 * 1) If a string was pushed back on the input, pop it;
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009451 * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
9452 * or we are reading from a string so we can't refill the buffer,
9453 * return EOF.
Denys Vlasenko883cea42009-07-11 15:31:59 +02009454 * 3) If there is more stuff in this buffer, use it else call read to fill it.
Eric Andersencb57d552001-06-28 07:25:16 +00009455 * 4) Process input up to the next newline, deleting nul characters.
9456 */
Denis Vlasenko727752d2008-11-28 03:41:47 +00009457//#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
9458#define pgetc_debug(...) ((void)0)
Denis Vlasenko68819d12008-12-15 11:26:36 +00009459/*
9460 * NB: due to SIT(c) internals (syntax_index_table[] vector),
9461 * pgetc() and related functions must return chars SIGN-EXTENDED into ints,
9462 * not zero-extended. Seems fragile to me. Affects only !USE_SIT_FUNCTION case,
9463 * so we can fix it by ditching !USE_SIT_FUNCTION if Unicode requires that.
9464 */
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009465static int
Eric Andersenc470f442003-07-28 09:56:35 +00009466preadbuffer(void)
Eric Andersencb57d552001-06-28 07:25:16 +00009467{
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009468 char *q;
Eric Andersencb57d552001-06-28 07:25:16 +00009469 int more;
Eric Andersencb57d552001-06-28 07:25:16 +00009470
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009471 while (g_parsefile->strpush) {
Denis Vlasenko131ae172007-02-18 13:00:19 +00009472#if ENABLE_ASH_ALIAS
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009473 if (g_parsefile->left_in_line == -1
9474 && g_parsefile->strpush->ap
9475 && g_parsefile->next_to_pgetc[-1] != ' '
9476 && g_parsefile->next_to_pgetc[-1] != '\t'
Denis Vlasenko16898402008-11-25 01:34:52 +00009477 ) {
Denis Vlasenko727752d2008-11-28 03:41:47 +00009478 pgetc_debug("preadbuffer PEOA");
Eric Andersencb57d552001-06-28 07:25:16 +00009479 return PEOA;
9480 }
Eric Andersen2870d962001-07-02 17:27:21 +00009481#endif
Eric Andersencb57d552001-06-28 07:25:16 +00009482 popstring();
Denis Vlasenko727752d2008-11-28 03:41:47 +00009483 /* try "pgetc" now: */
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009484 pgetc_debug("preadbuffer internal pgetc at %d:%p'%s'",
9485 g_parsefile->left_in_line,
9486 g_parsefile->next_to_pgetc,
9487 g_parsefile->next_to_pgetc);
9488 if (--g_parsefile->left_in_line >= 0)
9489 return (unsigned char)(*g_parsefile->next_to_pgetc++);
Eric Andersencb57d552001-06-28 07:25:16 +00009490 }
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009491 /* on both branches above g_parsefile->left_in_line < 0.
Denis Vlasenko727752d2008-11-28 03:41:47 +00009492 * "pgetc" needs refilling.
9493 */
9494
Denis Vlasenkoe27dafd2008-11-28 04:01:03 +00009495 /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009496 * pungetc() may increment it a few times.
Denis Vlasenkoe27dafd2008-11-28 04:01:03 +00009497 * Assuming it won't increment it to less than -90.
Denis Vlasenko727752d2008-11-28 03:41:47 +00009498 */
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009499 if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
Denis Vlasenko727752d2008-11-28 03:41:47 +00009500 pgetc_debug("preadbuffer PEOF1");
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009501 /* even in failure keep left_in_line and next_to_pgetc
9502 * in lock step, for correct multi-layer pungetc.
9503 * left_in_line was decremented before preadbuffer(),
9504 * must inc next_to_pgetc: */
9505 g_parsefile->next_to_pgetc++;
Eric Andersencb57d552001-06-28 07:25:16 +00009506 return PEOF;
Denis Vlasenko727752d2008-11-28 03:41:47 +00009507 }
Eric Andersencb57d552001-06-28 07:25:16 +00009508
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009509 more = g_parsefile->left_in_buffer;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009510 if (more <= 0) {
Denis Vlasenko727752d2008-11-28 03:41:47 +00009511 flush_stdout_stderr();
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009512 again:
9513 more = preadfd();
9514 if (more <= 0) {
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009515 /* don't try reading again */
9516 g_parsefile->left_in_line = -99;
Denis Vlasenko727752d2008-11-28 03:41:47 +00009517 pgetc_debug("preadbuffer PEOF2");
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009518 g_parsefile->next_to_pgetc++;
Eric Andersencb57d552001-06-28 07:25:16 +00009519 return PEOF;
9520 }
9521 }
9522
Denis Vlasenko727752d2008-11-28 03:41:47 +00009523 /* Find out where's the end of line.
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009524 * Set g_parsefile->left_in_line
9525 * and g_parsefile->left_in_buffer acordingly.
Denis Vlasenko727752d2008-11-28 03:41:47 +00009526 * NUL chars are deleted.
9527 */
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009528 q = g_parsefile->next_to_pgetc;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009529 for (;;) {
Denis Vlasenko727752d2008-11-28 03:41:47 +00009530 char c;
Eric Andersencb57d552001-06-28 07:25:16 +00009531
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009532 more--;
Eric Andersenc470f442003-07-28 09:56:35 +00009533
Denis Vlasenko727752d2008-11-28 03:41:47 +00009534 c = *q;
9535 if (c == '\0') {
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009536 memmove(q, q + 1, more);
Denis Vlasenko727752d2008-11-28 03:41:47 +00009537 } else {
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009538 q++;
9539 if (c == '\n') {
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009540 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009541 break;
9542 }
Eric Andersencb57d552001-06-28 07:25:16 +00009543 }
9544
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009545 if (more <= 0) {
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009546 g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
9547 if (g_parsefile->left_in_line < 0)
Eric Andersencb57d552001-06-28 07:25:16 +00009548 goto again;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009549 break;
Eric Andersencb57d552001-06-28 07:25:16 +00009550 }
9551 }
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009552 g_parsefile->left_in_buffer = more;
Eric Andersencb57d552001-06-28 07:25:16 +00009553
Eric Andersencb57d552001-06-28 07:25:16 +00009554 if (vflag) {
Denis Vlasenko727752d2008-11-28 03:41:47 +00009555 char save = *q;
9556 *q = '\0';
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009557 out2str(g_parsefile->next_to_pgetc);
Denis Vlasenko727752d2008-11-28 03:41:47 +00009558 *q = save;
Eric Andersencb57d552001-06-28 07:25:16 +00009559 }
9560
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009561 pgetc_debug("preadbuffer at %d:%p'%s'",
9562 g_parsefile->left_in_line,
9563 g_parsefile->next_to_pgetc,
9564 g_parsefile->next_to_pgetc);
Denis Vlasenko68819d12008-12-15 11:26:36 +00009565 return signed_char2int(*g_parsefile->next_to_pgetc++);
Eric Andersencb57d552001-06-28 07:25:16 +00009566}
9567
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009568#define pgetc_as_macro() \
9569 (--g_parsefile->left_in_line >= 0 \
Denis Vlasenko68819d12008-12-15 11:26:36 +00009570 ? signed_char2int(*g_parsefile->next_to_pgetc++) \
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009571 : preadbuffer() \
9572 )
Denis Vlasenko727752d2008-11-28 03:41:47 +00009573
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009574static int
9575pgetc(void)
9576{
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009577 pgetc_debug("pgetc_fast at %d:%p'%s'",
9578 g_parsefile->left_in_line,
9579 g_parsefile->next_to_pgetc,
9580 g_parsefile->next_to_pgetc);
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009581 return pgetc_as_macro();
9582}
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00009583
9584#if ENABLE_ASH_OPTIMIZE_FOR_SIZE
Denis Vlasenko834dee72008-10-07 09:18:30 +00009585#define pgetc_fast() pgetc()
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009586#else
Denis Vlasenko834dee72008-10-07 09:18:30 +00009587#define pgetc_fast() pgetc_as_macro()
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009588#endif
9589
9590/*
9591 * Same as pgetc(), but ignores PEOA.
9592 */
9593#if ENABLE_ASH_ALIAS
9594static int
9595pgetc2(void)
9596{
9597 int c;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009598 do {
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009599 pgetc_debug("pgetc_fast at %d:%p'%s'",
9600 g_parsefile->left_in_line,
9601 g_parsefile->next_to_pgetc,
9602 g_parsefile->next_to_pgetc);
Denis Vlasenko834dee72008-10-07 09:18:30 +00009603 c = pgetc_fast();
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009604 } while (c == PEOA);
9605 return c;
9606}
9607#else
Denis Vlasenko834dee72008-10-07 09:18:30 +00009608#define pgetc2() pgetc()
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009609#endif
9610
9611/*
9612 * Read a line from the script.
9613 */
9614static char *
9615pfgets(char *line, int len)
9616{
9617 char *p = line;
9618 int nleft = len;
9619 int c;
9620
9621 while (--nleft > 0) {
9622 c = pgetc2();
9623 if (c == PEOF) {
9624 if (p == line)
9625 return NULL;
9626 break;
9627 }
9628 *p++ = c;
9629 if (c == '\n')
9630 break;
9631 }
9632 *p = '\0';
9633 return line;
9634}
9635
Eric Andersenc470f442003-07-28 09:56:35 +00009636/*
9637 * Undo the last call to pgetc. Only one character may be pushed back.
9638 * PEOF may be pushed back.
9639 */
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009640static void
Eric Andersenc470f442003-07-28 09:56:35 +00009641pungetc(void)
9642{
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009643 g_parsefile->left_in_line++;
9644 g_parsefile->next_to_pgetc--;
9645 pgetc_debug("pushed back to %d:%p'%s'",
9646 g_parsefile->left_in_line,
9647 g_parsefile->next_to_pgetc,
9648 g_parsefile->next_to_pgetc);
Eric Andersencb57d552001-06-28 07:25:16 +00009649}
9650
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009651/*
9652 * To handle the "." command, a stack of input files is used. Pushfile
9653 * adds a new entry to the stack and popfile restores the previous level.
9654 */
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009655static void
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009656pushfile(void)
Eric Andersenc470f442003-07-28 09:56:35 +00009657{
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009658 struct parsefile *pf;
9659
Denis Vlasenko597906c2008-02-20 16:38:54 +00009660 pf = ckzalloc(sizeof(*pf));
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009661 pf->prev = g_parsefile;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009662 pf->fd = -1;
Denis Vlasenko597906c2008-02-20 16:38:54 +00009663 /*pf->strpush = NULL; - ckzalloc did it */
9664 /*pf->basestrpush.prev = NULL;*/
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009665 g_parsefile = pf;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009666}
9667
9668static void
9669popfile(void)
9670{
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009671 struct parsefile *pf = g_parsefile;
Eric Andersenc470f442003-07-28 09:56:35 +00009672
Denis Vlasenkob012b102007-02-19 22:43:01 +00009673 INT_OFF;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009674 if (pf->fd >= 0)
9675 close(pf->fd);
Denis Vlasenko60818682007-09-28 22:07:23 +00009676 free(pf->buf);
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009677 while (pf->strpush)
9678 popstring();
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009679 g_parsefile = pf->prev;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009680 free(pf);
Denis Vlasenkob012b102007-02-19 22:43:01 +00009681 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00009682}
9683
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009684/*
9685 * Return to top level.
9686 */
9687static void
9688popallfiles(void)
9689{
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009690 while (g_parsefile != &basepf)
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009691 popfile();
9692}
9693
9694/*
9695 * Close the file(s) that the shell is reading commands from. Called
9696 * after a fork is done.
9697 */
9698static void
9699closescript(void)
9700{
9701 popallfiles();
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009702 if (g_parsefile->fd > 0) {
9703 close(g_parsefile->fd);
9704 g_parsefile->fd = 0;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009705 }
9706}
9707
9708/*
9709 * Like setinputfile, but takes an open file descriptor. Call this with
9710 * interrupts off.
9711 */
9712static void
9713setinputfd(int fd, int push)
9714{
Denis Vlasenko96e1b382007-09-30 23:50:48 +00009715 close_on_exec_on(fd);
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009716 if (push) {
9717 pushfile();
Denis Vlasenko727752d2008-11-28 03:41:47 +00009718 g_parsefile->buf = NULL;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009719 }
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009720 g_parsefile->fd = fd;
9721 if (g_parsefile->buf == NULL)
9722 g_parsefile->buf = ckmalloc(IBUFSIZ);
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009723 g_parsefile->left_in_buffer = 0;
9724 g_parsefile->left_in_line = 0;
9725 g_parsefile->linno = 1;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009726}
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009727
Eric Andersenc470f442003-07-28 09:56:35 +00009728/*
9729 * Set the input to take input from a file. If push is set, push the
9730 * old input onto the stack first.
9731 */
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009732static int
9733setinputfile(const char *fname, int flags)
Eric Andersenc470f442003-07-28 09:56:35 +00009734{
9735 int fd;
9736 int fd2;
9737
Denis Vlasenkob012b102007-02-19 22:43:01 +00009738 INT_OFF;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009739 fd = open(fname, O_RDONLY);
9740 if (fd < 0) {
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009741 if (flags & INPUT_NOFILE_OK)
9742 goto out;
Denis Vlasenko9604e1b2009-03-03 18:47:56 +00009743 ash_msg_and_raise_error("can't open '%s'", fname);
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009744 }
Eric Andersenc470f442003-07-28 09:56:35 +00009745 if (fd < 10) {
9746 fd2 = copyfd(fd, 10);
9747 close(fd);
9748 if (fd2 < 0)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00009749 ash_msg_and_raise_error("out of file descriptors");
Eric Andersenc470f442003-07-28 09:56:35 +00009750 fd = fd2;
9751 }
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009752 setinputfd(fd, flags & INPUT_PUSH_FILE);
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009753 out:
Denis Vlasenkob012b102007-02-19 22:43:01 +00009754 INT_ON;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009755 return fd;
Eric Andersenc470f442003-07-28 09:56:35 +00009756}
9757
Eric Andersencb57d552001-06-28 07:25:16 +00009758/*
9759 * Like setinputfile, but takes input from a string.
9760 */
Eric Andersenc470f442003-07-28 09:56:35 +00009761static void
9762setinputstring(char *string)
Eric Andersen62483552001-07-10 06:09:16 +00009763{
Denis Vlasenkob012b102007-02-19 22:43:01 +00009764 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +00009765 pushfile();
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009766 g_parsefile->next_to_pgetc = string;
9767 g_parsefile->left_in_line = strlen(string);
Denis Vlasenkob07a4962008-06-22 13:16:23 +00009768 g_parsefile->buf = NULL;
Denis Vlasenko41eb3002008-11-28 03:42:31 +00009769 g_parsefile->linno = 1;
Denis Vlasenkob012b102007-02-19 22:43:01 +00009770 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00009771}
9772
9773
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00009774/* ============ mail.c
9775 *
9776 * Routines to check for mail.
Eric Andersencb57d552001-06-28 07:25:16 +00009777 */
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00009778
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00009779#if ENABLE_ASH_MAIL
Eric Andersencb57d552001-06-28 07:25:16 +00009780
Eric Andersencb57d552001-06-28 07:25:16 +00009781#define MAXMBOXES 10
9782
Eric Andersenc470f442003-07-28 09:56:35 +00009783/* times of mailboxes */
9784static time_t mailtime[MAXMBOXES];
9785/* Set if MAIL or MAILPATH is changed. */
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +00009786static smallint mail_var_path_changed;
Eric Andersencb57d552001-06-28 07:25:16 +00009787
Eric Andersencb57d552001-06-28 07:25:16 +00009788/*
Eric Andersenc470f442003-07-28 09:56:35 +00009789 * Print appropriate message(s) if mail has arrived.
9790 * If mail_var_path_changed is set,
9791 * then the value of MAIL has mail_var_path_changed,
9792 * so we just update the values.
Eric Andersencb57d552001-06-28 07:25:16 +00009793 */
Eric Andersenc470f442003-07-28 09:56:35 +00009794static void
9795chkmail(void)
Eric Andersencb57d552001-06-28 07:25:16 +00009796{
Eric Andersencb57d552001-06-28 07:25:16 +00009797 const char *mpath;
9798 char *p;
9799 char *q;
Eric Andersenc470f442003-07-28 09:56:35 +00009800 time_t *mtp;
Eric Andersencb57d552001-06-28 07:25:16 +00009801 struct stackmark smark;
9802 struct stat statb;
9803
Eric Andersencb57d552001-06-28 07:25:16 +00009804 setstackmark(&smark);
Eric Andersenc470f442003-07-28 09:56:35 +00009805 mpath = mpathset() ? mpathval() : mailval();
9806 for (mtp = mailtime; mtp < mailtime + MAXMBOXES; mtp++) {
Denys Vlasenko82a6fb32009-06-14 19:42:12 +02009807 p = path_advance(&mpath, nullstr);
Eric Andersencb57d552001-06-28 07:25:16 +00009808 if (p == NULL)
9809 break;
9810 if (*p == '\0')
9811 continue;
Denis Vlasenkof7d56652008-03-25 05:51:41 +00009812 for (q = p; *q; q++)
9813 continue;
Denis Vlasenkoa7189f02006-11-17 20:29:00 +00009814#if DEBUG
Eric Andersencb57d552001-06-28 07:25:16 +00009815 if (q[-1] != '/')
9816 abort();
9817#endif
Eric Andersenc470f442003-07-28 09:56:35 +00009818 q[-1] = '\0'; /* delete trailing '/' */
9819 if (stat(p, &statb) < 0) {
9820 *mtp = 0;
9821 continue;
Eric Andersencb57d552001-06-28 07:25:16 +00009822 }
Eric Andersenc470f442003-07-28 09:56:35 +00009823 if (!mail_var_path_changed && statb.st_mtime != *mtp) {
9824 fprintf(
9825 stderr, snlfmt,
9826 pathopt ? pathopt : "you have mail"
9827 );
9828 }
9829 *mtp = statb.st_mtime;
Eric Andersencb57d552001-06-28 07:25:16 +00009830 }
Eric Andersenc470f442003-07-28 09:56:35 +00009831 mail_var_path_changed = 0;
Eric Andersencb57d552001-06-28 07:25:16 +00009832 popstackmark(&smark);
9833}
Eric Andersencb57d552001-06-28 07:25:16 +00009834
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009835static void FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00009836changemail(const char *val UNUSED_PARAM)
Eric Andersenc470f442003-07-28 09:56:35 +00009837{
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +00009838 mail_var_path_changed = 1;
Eric Andersenc470f442003-07-28 09:56:35 +00009839}
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00009840
Denis Vlasenko131ae172007-02-18 13:00:19 +00009841#endif /* ASH_MAIL */
Eric Andersenc470f442003-07-28 09:56:35 +00009842
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00009843
9844/* ============ ??? */
9845
Eric Andersencb57d552001-06-28 07:25:16 +00009846/*
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009847 * Set the shell parameters.
Eric Andersencb57d552001-06-28 07:25:16 +00009848 */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009849static void
9850setparam(char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +00009851{
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009852 char **newparam;
9853 char **ap;
9854 int nparam;
Eric Andersencb57d552001-06-28 07:25:16 +00009855
Denis Vlasenkof7d56652008-03-25 05:51:41 +00009856 for (nparam = 0; argv[nparam]; nparam++)
9857 continue;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009858 ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
9859 while (*argv) {
9860 *ap++ = ckstrdup(*argv++);
Eric Andersencb57d552001-06-28 07:25:16 +00009861 }
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009862 *ap = NULL;
9863 freeparam(&shellparam);
Denis Vlasenko01631112007-12-16 17:20:38 +00009864 shellparam.malloced = 1;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009865 shellparam.nparam = nparam;
9866 shellparam.p = newparam;
9867#if ENABLE_ASH_GETOPTS
9868 shellparam.optind = 1;
9869 shellparam.optoff = -1;
9870#endif
Eric Andersencb57d552001-06-28 07:25:16 +00009871}
9872
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00009873/*
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009874 * Process shell options. The global variable argptr contains a pointer
9875 * to the argument list; we advance it past the options.
Denis Vlasenko94e87bc2008-02-14 16:51:58 +00009876 *
9877 * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
9878 * For a non-interactive shell, an error condition encountered
9879 * by a special built-in ... shall cause the shell to write a diagnostic message
9880 * to standard error and exit as shown in the following table:
Denis Vlasenko56244732008-02-17 15:14:04 +00009881 * Error Special Built-In
Denis Vlasenko94e87bc2008-02-14 16:51:58 +00009882 * ...
9883 * Utility syntax error (option or operand error) Shall exit
9884 * ...
9885 * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
9886 * we see that bash does not do that (set "finishes" with error code 1 instead,
9887 * and shell continues), and people rely on this behavior!
9888 * Testcase:
9889 * set -o barfoo 2>/dev/null
9890 * echo $?
9891 *
9892 * Oh well. Let's mimic that.
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00009893 */
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009894static int
Denis Vlasenkodddfaff2008-05-06 15:30:27 +00009895plus_minus_o(char *name, int val)
Eric Andersen62483552001-07-10 06:09:16 +00009896{
9897 int i;
9898
Denis Vlasenkoa624c112007-02-19 22:45:43 +00009899 if (name) {
9900 for (i = 0; i < NOPTS; i++) {
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00009901 if (strcmp(name, optnames(i)) == 0) {
Eric Andersenc470f442003-07-28 09:56:35 +00009902 optlist[i] = val;
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009903 return 0;
Eric Andersen62483552001-07-10 06:09:16 +00009904 }
Denis Vlasenkoa624c112007-02-19 22:45:43 +00009905 }
Denis Vlasenkodddfaff2008-05-06 15:30:27 +00009906 ash_msg("illegal option %co %s", val ? '-' : '+', name);
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009907 return 1;
Eric Andersen62483552001-07-10 06:09:16 +00009908 }
Denis Vlasenko6b06cb82008-05-15 21:30:45 +00009909 for (i = 0; i < NOPTS; i++) {
Denis Vlasenkodddfaff2008-05-06 15:30:27 +00009910 if (val) {
9911 out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
9912 } else {
9913 out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
9914 }
Denis Vlasenko6b06cb82008-05-15 21:30:45 +00009915 }
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009916 return 0;
Eric Andersen62483552001-07-10 06:09:16 +00009917}
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009918static void
9919setoption(int flag, int val)
9920{
9921 int i;
9922
9923 for (i = 0; i < NOPTS; i++) {
9924 if (optletters(i) == flag) {
9925 optlist[i] = val;
9926 return;
9927 }
9928 }
Denis Vlasenkodddfaff2008-05-06 15:30:27 +00009929 ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009930 /* NOTREACHED */
9931}
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009932static int
Eric Andersenc470f442003-07-28 09:56:35 +00009933options(int cmdline)
Eric Andersencb57d552001-06-28 07:25:16 +00009934{
9935 char *p;
9936 int val;
9937 int c;
9938
9939 if (cmdline)
9940 minusc = NULL;
9941 while ((p = *argptr) != NULL) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009942 c = *p++;
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +00009943 if (c != '-' && c != '+')
9944 break;
9945 argptr++;
9946 val = 0; /* val = 0 if c == '+' */
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009947 if (c == '-') {
Eric Andersencb57d552001-06-28 07:25:16 +00009948 val = 1;
Denis Vlasenko9f739442006-12-16 23:49:13 +00009949 if (p[0] == '\0' || LONE_DASH(p)) {
Eric Andersen2870d962001-07-02 17:27:21 +00009950 if (!cmdline) {
9951 /* "-" means turn off -x and -v */
9952 if (p[0] == '\0')
9953 xflag = vflag = 0;
9954 /* "--" means reset params */
9955 else if (*argptr == NULL)
Eric Andersencb57d552001-06-28 07:25:16 +00009956 setparam(argptr);
Eric Andersen2870d962001-07-02 17:27:21 +00009957 }
Eric Andersenc470f442003-07-28 09:56:35 +00009958 break; /* "-" or "--" terminates options */
Eric Andersencb57d552001-06-28 07:25:16 +00009959 }
Eric Andersencb57d552001-06-28 07:25:16 +00009960 }
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +00009961 /* first char was + or - */
Eric Andersencb57d552001-06-28 07:25:16 +00009962 while ((c = *p++) != '\0') {
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +00009963 /* bash 3.2 indeed handles -c CMD and +c CMD the same */
Eric Andersencb57d552001-06-28 07:25:16 +00009964 if (c == 'c' && cmdline) {
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +00009965 minusc = p; /* command is after shell args */
Eric Andersencb57d552001-06-28 07:25:16 +00009966 } else if (c == 'o') {
Denis Vlasenkodddfaff2008-05-06 15:30:27 +00009967 if (plus_minus_o(*argptr, val)) {
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009968 /* it already printed err message */
9969 return 1; /* error */
9970 }
Eric Andersencb57d552001-06-28 07:25:16 +00009971 if (*argptr)
9972 argptr++;
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +00009973 } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
9974 isloginsh = 1;
9975 /* bash does not accept +-login, we also won't */
9976 } else if (cmdline && val && (c == '-')) { /* long options */
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00009977 if (strcmp(p, "login") == 0)
Robert Griebl64f70cc2002-05-14 23:22:06 +00009978 isloginsh = 1;
9979 break;
Eric Andersencb57d552001-06-28 07:25:16 +00009980 } else {
9981 setoption(c, val);
9982 }
9983 }
9984 }
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009985 return 0;
Eric Andersencb57d552001-06-28 07:25:16 +00009986}
9987
Eric Andersencb57d552001-06-28 07:25:16 +00009988/*
Eric Andersencb57d552001-06-28 07:25:16 +00009989 * The shift builtin command.
9990 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +02009991static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +00009992shiftcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +00009993{
9994 int n;
9995 char **ap1, **ap2;
9996
9997 n = 1;
Denis Vlasenko68404f12008-03-17 09:00:54 +00009998 if (argv[1])
Eric Andersencb57d552001-06-28 07:25:16 +00009999 n = number(argv[1]);
10000 if (n > shellparam.nparam)
Denis Vlasenkoc90e1be2008-07-30 15:35:05 +000010001 n = 0; /* bash compat, was = shellparam.nparam; */
Denis Vlasenkob012b102007-02-19 22:43:01 +000010002 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +000010003 shellparam.nparam -= n;
Denis Vlasenko2da584f2007-02-19 22:44:05 +000010004 for (ap1 = shellparam.p; --n >= 0; ap1++) {
Denis Vlasenko01631112007-12-16 17:20:38 +000010005 if (shellparam.malloced)
Denis Vlasenkob012b102007-02-19 22:43:01 +000010006 free(*ap1);
Eric Andersencb57d552001-06-28 07:25:16 +000010007 }
10008 ap2 = shellparam.p;
Denis Vlasenkof7d56652008-03-25 05:51:41 +000010009 while ((*ap2++ = *ap1++) != NULL)
10010 continue;
Denis Vlasenko131ae172007-02-18 13:00:19 +000010011#if ENABLE_ASH_GETOPTS
Eric Andersencb57d552001-06-28 07:25:16 +000010012 shellparam.optind = 1;
10013 shellparam.optoff = -1;
Eric Andersenc470f442003-07-28 09:56:35 +000010014#endif
Denis Vlasenkob012b102007-02-19 22:43:01 +000010015 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +000010016 return 0;
10017}
10018
Eric Andersencb57d552001-06-28 07:25:16 +000010019/*
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010020 * POSIX requires that 'set' (but not export or readonly) output the
10021 * variables in lexicographic order - by the locale's collating order (sigh).
10022 * Maybe we could keep them in an ordered balanced binary tree
10023 * instead of hashed lists.
10024 * For now just roll 'em through qsort for printing...
10025 */
10026static int
10027showvars(const char *sep_prefix, int on, int off)
10028{
10029 const char *sep;
10030 char **ep, **epend;
10031
10032 ep = listvars(on, off, &epend);
10033 qsort(ep, epend - ep, sizeof(char *), vpcmp);
10034
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +000010035 sep = *sep_prefix ? " " : sep_prefix;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010036
10037 for (; ep < epend; ep++) {
10038 const char *p;
10039 const char *q;
10040
10041 p = strchrnul(*ep, '=');
10042 q = nullstr;
10043 if (*p)
10044 q = single_quote(++p);
10045 out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
10046 }
10047 return 0;
10048}
10049
10050/*
Eric Andersencb57d552001-06-28 07:25:16 +000010051 * The set command builtin.
10052 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010053static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000010054setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersencb57d552001-06-28 07:25:16 +000010055{
Denis Vlasenko28bf6712008-02-14 15:01:47 +000010056 int retval;
10057
Denis Vlasenko68404f12008-03-17 09:00:54 +000010058 if (!argv[1])
Eric Andersenc470f442003-07-28 09:56:35 +000010059 return showvars(nullstr, 0, VUNSET);
Denis Vlasenkob012b102007-02-19 22:43:01 +000010060 INT_OFF;
Denis Vlasenko28bf6712008-02-14 15:01:47 +000010061 retval = 1;
10062 if (!options(0)) { /* if no parse error... */
10063 retval = 0;
10064 optschanged();
10065 if (*argptr != NULL) {
10066 setparam(argptr);
10067 }
Eric Andersencb57d552001-06-28 07:25:16 +000010068 }
Denis Vlasenkob012b102007-02-19 22:43:01 +000010069 INT_ON;
Denis Vlasenko28bf6712008-02-14 15:01:47 +000010070 return retval;
Eric Andersencb57d552001-06-28 07:25:16 +000010071}
10072
Denis Vlasenko131ae172007-02-18 13:00:19 +000010073#if ENABLE_ASH_RANDOM_SUPPORT
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010074static void FAST_FUNC
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000010075change_random(const char *value)
Eric Andersenef02f822004-03-11 13:34:24 +000010076{
Denys Vlasenko3ea2e822009-10-09 20:59:04 +020010077 uint32_t t;
10078
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010079 if (value == NULL) {
Eric Andersen16767e22004-03-16 05:14:10 +000010080 /* "get", generate */
Denys Vlasenko3ea2e822009-10-09 20:59:04 +020010081 t = next_random(&random_gen);
Eric Andersen16767e22004-03-16 05:14:10 +000010082 /* set without recursion */
Denis Vlasenko448d30e2008-06-27 00:24:11 +000010083 setvar(vrandom.text, utoa(t), VNOFUNC);
Eric Andersen16767e22004-03-16 05:14:10 +000010084 vrandom.flags &= ~VNOFUNC;
10085 } else {
10086 /* set/reset */
Denys Vlasenko3ea2e822009-10-09 20:59:04 +020010087 t = strtoul(value, NULL, 10);
10088 INIT_RANDOM_T(&random_gen, (t ? t : 1), t);
Eric Andersen16767e22004-03-16 05:14:10 +000010089 }
Eric Andersenef02f822004-03-11 13:34:24 +000010090}
Eric Andersen16767e22004-03-16 05:14:10 +000010091#endif
10092
Denis Vlasenko131ae172007-02-18 13:00:19 +000010093#if ENABLE_ASH_GETOPTS
Eric Andersencb57d552001-06-28 07:25:16 +000010094static int
Eric Andersenc470f442003-07-28 09:56:35 +000010095getopts(char *optstr, char *optvar, char **optfirst, int *param_optind, int *optoff)
Eric Andersencb57d552001-06-28 07:25:16 +000010096{
10097 char *p, *q;
10098 char c = '?';
10099 int done = 0;
10100 int err = 0;
Eric Andersena48b0a32003-10-22 10:56:47 +000010101 char s[12];
10102 char **optnext;
Eric Andersencb57d552001-06-28 07:25:16 +000010103
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010104 if (*param_optind < 1)
Eric Andersena48b0a32003-10-22 10:56:47 +000010105 return 1;
10106 optnext = optfirst + *param_optind - 1;
10107
Denis Vlasenko6b06cb82008-05-15 21:30:45 +000010108 if (*param_optind <= 1 || *optoff < 0 || (int)strlen(optnext[-1]) < *optoff)
Eric Andersencb57d552001-06-28 07:25:16 +000010109 p = NULL;
10110 else
Eric Andersena48b0a32003-10-22 10:56:47 +000010111 p = optnext[-1] + *optoff;
Eric Andersencb57d552001-06-28 07:25:16 +000010112 if (p == NULL || *p == '\0') {
10113 /* Current word is done, advance */
Eric Andersencb57d552001-06-28 07:25:16 +000010114 p = *optnext;
10115 if (p == NULL || *p != '-' || *++p == '\0') {
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010116 atend:
Eric Andersencb57d552001-06-28 07:25:16 +000010117 p = NULL;
10118 done = 1;
10119 goto out;
10120 }
10121 optnext++;
Denis Vlasenko9f739442006-12-16 23:49:13 +000010122 if (LONE_DASH(p)) /* check for "--" */
Eric Andersencb57d552001-06-28 07:25:16 +000010123 goto atend;
10124 }
10125
10126 c = *p++;
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +000010127 for (q = optstr; *q != c;) {
Eric Andersencb57d552001-06-28 07:25:16 +000010128 if (*q == '\0') {
10129 if (optstr[0] == ':') {
10130 s[0] = c;
10131 s[1] = '\0';
10132 err |= setvarsafe("OPTARG", s, 0);
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010133 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000010134 fprintf(stderr, "Illegal option -%c\n", c);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010135 unsetvar("OPTARG");
Eric Andersencb57d552001-06-28 07:25:16 +000010136 }
10137 c = '?';
Eric Andersenc470f442003-07-28 09:56:35 +000010138 goto out;
Eric Andersencb57d552001-06-28 07:25:16 +000010139 }
10140 if (*++q == ':')
10141 q++;
10142 }
10143
10144 if (*++q == ':') {
10145 if (*p == '\0' && (p = *optnext) == NULL) {
10146 if (optstr[0] == ':') {
10147 s[0] = c;
10148 s[1] = '\0';
10149 err |= setvarsafe("OPTARG", s, 0);
10150 c = ':';
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010151 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000010152 fprintf(stderr, "No arg for -%c option\n", c);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010153 unsetvar("OPTARG");
Eric Andersencb57d552001-06-28 07:25:16 +000010154 c = '?';
10155 }
Eric Andersenc470f442003-07-28 09:56:35 +000010156 goto out;
Eric Andersencb57d552001-06-28 07:25:16 +000010157 }
10158
10159 if (p == *optnext)
10160 optnext++;
Eric Andersenc470f442003-07-28 09:56:35 +000010161 err |= setvarsafe("OPTARG", p, 0);
Eric Andersencb57d552001-06-28 07:25:16 +000010162 p = NULL;
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010163 } else
Eric Andersenc470f442003-07-28 09:56:35 +000010164 err |= setvarsafe("OPTARG", nullstr, 0);
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010165 out:
Eric Andersencb57d552001-06-28 07:25:16 +000010166 *optoff = p ? p - *(optnext - 1) : -1;
Eric Andersenc470f442003-07-28 09:56:35 +000010167 *param_optind = optnext - optfirst + 1;
10168 fmtstr(s, sizeof(s), "%d", *param_optind);
Eric Andersencb57d552001-06-28 07:25:16 +000010169 err |= setvarsafe("OPTIND", s, VNOFUNC);
10170 s[0] = c;
10171 s[1] = '\0';
10172 err |= setvarsafe(optvar, s, 0);
10173 if (err) {
Eric Andersenc470f442003-07-28 09:56:35 +000010174 *param_optind = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010175 *optoff = -1;
Denis Vlasenkob012b102007-02-19 22:43:01 +000010176 flush_stdout_stderr();
10177 raise_exception(EXERROR);
Eric Andersencb57d552001-06-28 07:25:16 +000010178 }
10179 return done;
10180}
Eric Andersenc470f442003-07-28 09:56:35 +000010181
10182/*
10183 * The getopts builtin. Shellparam.optnext points to the next argument
10184 * to be processed. Shellparam.optptr points to the next character to
10185 * be processed in the current argument. If shellparam.optnext is NULL,
10186 * then it's the first time getopts has been called.
10187 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020010188static int FAST_FUNC
Eric Andersenc470f442003-07-28 09:56:35 +000010189getoptscmd(int argc, char **argv)
10190{
10191 char **optbase;
10192
10193 if (argc < 3)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +000010194 ash_msg_and_raise_error("usage: getopts optstring var [arg]");
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010195 if (argc == 3) {
Eric Andersenc470f442003-07-28 09:56:35 +000010196 optbase = shellparam.p;
10197 if (shellparam.optind > shellparam.nparam + 1) {
10198 shellparam.optind = 1;
10199 shellparam.optoff = -1;
10200 }
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010201 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000010202 optbase = &argv[3];
10203 if (shellparam.optind > argc - 2) {
10204 shellparam.optind = 1;
10205 shellparam.optoff = -1;
10206 }
10207 }
10208
10209 return getopts(argv[1], argv[2], optbase, &shellparam.optind,
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010210 &shellparam.optoff);
Eric Andersenc470f442003-07-28 09:56:35 +000010211}
Denis Vlasenko131ae172007-02-18 13:00:19 +000010212#endif /* ASH_GETOPTS */
Eric Andersencb57d552001-06-28 07:25:16 +000010213
Eric Andersencb57d552001-06-28 07:25:16 +000010214
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010215/* ============ Shell parser */
Eric Andersencb57d552001-06-28 07:25:16 +000010216
Denis Vlasenkob07a4962008-06-22 13:16:23 +000010217struct heredoc {
10218 struct heredoc *next; /* next here document in list */
10219 union node *here; /* redirection node */
10220 char *eofmark; /* string indicating end of input */
10221 smallint striptabs; /* if set, strip leading tabs */
10222};
10223
10224static smallint tokpushback; /* last token pushed back */
10225static smallint parsebackquote; /* nonzero if we are inside backquotes */
10226static smallint quoteflag; /* set if (part of) last token was quoted */
10227static token_id_t lasttoken; /* last token read (integer id Txxx) */
10228static struct heredoc *heredoclist; /* list of here documents to read */
10229static char *wordtext; /* text of last word returned by readtoken */
10230static struct nodelist *backquotelist;
10231static union node *redirnode;
10232static struct heredoc *heredoc;
Denis Vlasenko99eb8502007-02-23 21:09:49 +000010233
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010234/*
10235 * Called when an unexpected token is read during the parse. The argument
10236 * is the token that is expected, or -1 if more than one type of token can
10237 * occur at this point.
10238 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000010239static void raise_error_unexpected_syntax(int) NORETURN;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010240static void
10241raise_error_unexpected_syntax(int token)
10242{
10243 char msg[64];
10244 int l;
10245
Denis Vlasenko7b2294e2008-11-28 03:50:46 +000010246 l = sprintf(msg, "unexpected %s", tokname(lasttoken));
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010247 if (token >= 0)
10248 sprintf(msg + l, " (expecting %s)", tokname(token));
10249 raise_error_syntax(msg);
10250 /* NOTREACHED */
10251}
Eric Andersencb57d552001-06-28 07:25:16 +000010252
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010253#define EOFMARKLEN 79
Eric Andersencb57d552001-06-28 07:25:16 +000010254
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010255/* parsing is heavily cross-recursive, need these forward decls */
10256static union node *andor(void);
10257static union node *pipeline(void);
10258static union node *parse_command(void);
10259static void parseheredoc(void);
10260static char peektoken(void);
10261static int readtoken(void);
Eric Andersencb57d552001-06-28 07:25:16 +000010262
Eric Andersenc470f442003-07-28 09:56:35 +000010263static union node *
10264list(int nlflag)
Eric Andersencb57d552001-06-28 07:25:16 +000010265{
10266 union node *n1, *n2, *n3;
10267 int tok;
10268
Eric Andersenc470f442003-07-28 09:56:35 +000010269 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10270 if (nlflag == 2 && peektoken())
Eric Andersencb57d552001-06-28 07:25:16 +000010271 return NULL;
10272 n1 = NULL;
10273 for (;;) {
10274 n2 = andor();
10275 tok = readtoken();
10276 if (tok == TBACKGND) {
Eric Andersenc470f442003-07-28 09:56:35 +000010277 if (n2->type == NPIPE) {
Denis Vlasenko2dc240c2008-07-24 06:07:50 +000010278 n2->npipe.pipe_backgnd = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010279 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000010280 if (n2->type != NREDIR) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010281 n3 = stzalloc(sizeof(struct nredir));
Eric Andersenc470f442003-07-28 09:56:35 +000010282 n3->nredir.n = n2;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010283 /*n3->nredir.redirect = NULL; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000010284 n2 = n3;
10285 }
10286 n2->type = NBACKGND;
Eric Andersencb57d552001-06-28 07:25:16 +000010287 }
10288 }
10289 if (n1 == NULL) {
10290 n1 = n2;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010291 } else {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010292 n3 = stzalloc(sizeof(struct nbinary));
Eric Andersencb57d552001-06-28 07:25:16 +000010293 n3->type = NSEMI;
10294 n3->nbinary.ch1 = n1;
10295 n3->nbinary.ch2 = n2;
10296 n1 = n3;
10297 }
10298 switch (tok) {
10299 case TBACKGND:
10300 case TSEMI:
10301 tok = readtoken();
10302 /* fall through */
10303 case TNL:
10304 if (tok == TNL) {
10305 parseheredoc();
Eric Andersenc470f442003-07-28 09:56:35 +000010306 if (nlflag == 1)
Eric Andersencb57d552001-06-28 07:25:16 +000010307 return n1;
10308 } else {
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010309 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010310 }
Eric Andersenc470f442003-07-28 09:56:35 +000010311 checkkwd = CHKNL | CHKKWD | CHKALIAS;
Manuel Novoa III 16815d42001-08-10 19:36:07 +000010312 if (peektoken())
Eric Andersencb57d552001-06-28 07:25:16 +000010313 return n1;
10314 break;
10315 case TEOF:
10316 if (heredoclist)
10317 parseheredoc();
10318 else
Eric Andersenc470f442003-07-28 09:56:35 +000010319 pungetc(); /* push back EOF on input */
Eric Andersencb57d552001-06-28 07:25:16 +000010320 return n1;
10321 default:
Eric Andersenc470f442003-07-28 09:56:35 +000010322 if (nlflag == 1)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010323 raise_error_unexpected_syntax(-1);
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010324 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010325 return n1;
10326 }
10327 }
10328}
10329
Eric Andersenc470f442003-07-28 09:56:35 +000010330static union node *
10331andor(void)
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010332{
Eric Andersencb57d552001-06-28 07:25:16 +000010333 union node *n1, *n2, *n3;
10334 int t;
10335
Eric Andersencb57d552001-06-28 07:25:16 +000010336 n1 = pipeline();
10337 for (;;) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010338 t = readtoken();
10339 if (t == TAND) {
Eric Andersencb57d552001-06-28 07:25:16 +000010340 t = NAND;
10341 } else if (t == TOR) {
10342 t = NOR;
10343 } else {
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010344 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010345 return n1;
10346 }
Eric Andersenc470f442003-07-28 09:56:35 +000010347 checkkwd = CHKNL | CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010348 n2 = pipeline();
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010349 n3 = stzalloc(sizeof(struct nbinary));
Eric Andersencb57d552001-06-28 07:25:16 +000010350 n3->type = t;
10351 n3->nbinary.ch1 = n1;
10352 n3->nbinary.ch2 = n2;
10353 n1 = n3;
10354 }
10355}
10356
Eric Andersenc470f442003-07-28 09:56:35 +000010357static union node *
10358pipeline(void)
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010359{
Eric Andersencb57d552001-06-28 07:25:16 +000010360 union node *n1, *n2, *pipenode;
10361 struct nodelist *lp, *prev;
10362 int negate;
10363
10364 negate = 0;
10365 TRACE(("pipeline: entered\n"));
10366 if (readtoken() == TNOT) {
10367 negate = !negate;
Eric Andersenc470f442003-07-28 09:56:35 +000010368 checkkwd = CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010369 } else
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010370 tokpushback = 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010371 n1 = parse_command();
Eric Andersencb57d552001-06-28 07:25:16 +000010372 if (readtoken() == TPIPE) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010373 pipenode = stzalloc(sizeof(struct npipe));
Eric Andersencb57d552001-06-28 07:25:16 +000010374 pipenode->type = NPIPE;
Denis Vlasenko2dc240c2008-07-24 06:07:50 +000010375 /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010376 lp = stzalloc(sizeof(struct nodelist));
Eric Andersencb57d552001-06-28 07:25:16 +000010377 pipenode->npipe.cmdlist = lp;
10378 lp->n = n1;
10379 do {
10380 prev = lp;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010381 lp = stzalloc(sizeof(struct nodelist));
Eric Andersenc470f442003-07-28 09:56:35 +000010382 checkkwd = CHKNL | CHKKWD | CHKALIAS;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010383 lp->n = parse_command();
Eric Andersencb57d552001-06-28 07:25:16 +000010384 prev->next = lp;
10385 } while (readtoken() == TPIPE);
10386 lp->next = NULL;
10387 n1 = pipenode;
10388 }
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010389 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010390 if (negate) {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010391 n2 = stzalloc(sizeof(struct nnot));
Eric Andersencb57d552001-06-28 07:25:16 +000010392 n2->type = NNOT;
10393 n2->nnot.com = n1;
10394 return n2;
Denis Vlasenko2da584f2007-02-19 22:44:05 +000010395 }
10396 return n1;
Eric Andersencb57d552001-06-28 07:25:16 +000010397}
10398
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010399static union node *
10400makename(void)
10401{
10402 union node *n;
10403
Denis Vlasenko597906c2008-02-20 16:38:54 +000010404 n = stzalloc(sizeof(struct narg));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010405 n->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010406 /*n->narg.next = NULL; - stzalloc did it */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010407 n->narg.text = wordtext;
10408 n->narg.backquote = backquotelist;
10409 return n;
10410}
10411
10412static void
10413fixredir(union node *n, const char *text, int err)
10414{
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000010415 int fd;
10416
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010417 TRACE(("Fix redir %s %d\n", text, err));
10418 if (!err)
10419 n->ndup.vname = NULL;
10420
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000010421 fd = bb_strtou(text, NULL, 10);
10422 if (!errno && fd >= 0)
10423 n->ndup.dupfd = fd;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010424 else if (LONE_DASH(text))
10425 n->ndup.dupfd = -1;
10426 else {
10427 if (err)
Denis Vlasenko559691a2008-10-05 18:39:31 +000010428 raise_error_syntax("bad fd number");
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010429 n->ndup.vname = makename();
10430 }
10431}
10432
10433/*
10434 * Returns true if the text contains nothing to expand (no dollar signs
10435 * or backquotes).
10436 */
10437static int
Denis Vlasenko68819d12008-12-15 11:26:36 +000010438noexpand(const char *text)
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010439{
Denis Vlasenko68819d12008-12-15 11:26:36 +000010440 const char *p;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010441 char c;
10442
10443 p = text;
10444 while ((c = *p++) != '\0') {
10445 if (c == CTLQUOTEMARK)
10446 continue;
10447 if (c == CTLESC)
10448 p++;
Denis Vlasenko68819d12008-12-15 11:26:36 +000010449 else if (SIT((signed char)c, BASESYNTAX) == CCTL)
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010450 return 0;
10451 }
10452 return 1;
10453}
10454
10455static void
10456parsefname(void)
10457{
10458 union node *n = redirnode;
10459
10460 if (readtoken() != TWORD)
10461 raise_error_unexpected_syntax(-1);
10462 if (n->type == NHERE) {
10463 struct heredoc *here = heredoc;
10464 struct heredoc *p;
10465 int i;
10466
10467 if (quoteflag == 0)
10468 n->type = NXHERE;
10469 TRACE(("Here document %d\n", n->type));
10470 if (!noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
Denis Vlasenko559691a2008-10-05 18:39:31 +000010471 raise_error_syntax("illegal eof marker for << redirection");
Denys Vlasenkob6c84342009-08-29 20:23:20 +020010472 rmescapes(wordtext, 0);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010473 here->eofmark = wordtext;
10474 here->next = NULL;
10475 if (heredoclist == NULL)
10476 heredoclist = here;
10477 else {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010478 for (p = heredoclist; p->next; p = p->next)
10479 continue;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010480 p->next = here;
10481 }
10482 } else if (n->type == NTOFD || n->type == NFROMFD) {
10483 fixredir(n, wordtext, 0);
10484 } else {
10485 n->nfile.fname = makename();
10486 }
10487}
Eric Andersencb57d552001-06-28 07:25:16 +000010488
Eric Andersenc470f442003-07-28 09:56:35 +000010489static union node *
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010490simplecmd(void)
10491{
10492 union node *args, **app;
10493 union node *n = NULL;
10494 union node *vars, **vpp;
10495 union node **rpp, *redir;
10496 int savecheckkwd;
Denis Vlasenko80591b02008-03-25 07:49:43 +000010497#if ENABLE_ASH_BASH_COMPAT
10498 smallint double_brackets_flag = 0;
10499#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010500
10501 args = NULL;
10502 app = &args;
10503 vars = NULL;
10504 vpp = &vars;
10505 redir = NULL;
10506 rpp = &redir;
10507
10508 savecheckkwd = CHKALIAS;
10509 for (;;) {
Denis Vlasenko80591b02008-03-25 07:49:43 +000010510 int t;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010511 checkkwd = savecheckkwd;
Denis Vlasenko80591b02008-03-25 07:49:43 +000010512 t = readtoken();
10513 switch (t) {
10514#if ENABLE_ASH_BASH_COMPAT
10515 case TAND: /* "&&" */
10516 case TOR: /* "||" */
10517 if (!double_brackets_flag) {
10518 tokpushback = 1;
10519 goto out;
10520 }
10521 wordtext = (char *) (t == TAND ? "-a" : "-o");
10522#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010523 case TWORD:
Denis Vlasenko597906c2008-02-20 16:38:54 +000010524 n = stzalloc(sizeof(struct narg));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010525 n->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010526 /*n->narg.next = NULL; - stzalloc did it */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010527 n->narg.text = wordtext;
Denis Vlasenko80591b02008-03-25 07:49:43 +000010528#if ENABLE_ASH_BASH_COMPAT
10529 if (strcmp("[[", wordtext) == 0)
10530 double_brackets_flag = 1;
10531 else if (strcmp("]]", wordtext) == 0)
10532 double_brackets_flag = 0;
10533#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010534 n->narg.backquote = backquotelist;
10535 if (savecheckkwd && isassignment(wordtext)) {
10536 *vpp = n;
10537 vpp = &n->narg.next;
10538 } else {
10539 *app = n;
10540 app = &n->narg.next;
10541 savecheckkwd = 0;
10542 }
10543 break;
10544 case TREDIR:
10545 *rpp = n = redirnode;
10546 rpp = &n->nfile.next;
10547 parsefname(); /* read name of redirection file */
10548 break;
10549 case TLP:
10550 if (args && app == &args->narg.next
10551 && !vars && !redir
10552 ) {
10553 struct builtincmd *bcmd;
10554 const char *name;
10555
10556 /* We have a function */
10557 if (readtoken() != TRP)
10558 raise_error_unexpected_syntax(TRP);
10559 name = n->narg.text;
10560 if (!goodname(name)
10561 || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
10562 ) {
Denis Vlasenko559691a2008-10-05 18:39:31 +000010563 raise_error_syntax("bad function name");
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010564 }
10565 n->type = NDEFUN;
10566 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10567 n->narg.next = parse_command();
10568 return n;
10569 }
10570 /* fall through */
10571 default:
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010572 tokpushback = 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010573 goto out;
10574 }
10575 }
10576 out:
10577 *app = NULL;
10578 *vpp = NULL;
10579 *rpp = NULL;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010580 n = stzalloc(sizeof(struct ncmd));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010581 n->type = NCMD;
10582 n->ncmd.args = args;
10583 n->ncmd.assign = vars;
10584 n->ncmd.redirect = redir;
10585 return n;
10586}
10587
10588static union node *
10589parse_command(void)
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010590{
Eric Andersencb57d552001-06-28 07:25:16 +000010591 union node *n1, *n2;
10592 union node *ap, **app;
10593 union node *cp, **cpp;
10594 union node *redir, **rpp;
Eric Andersenc470f442003-07-28 09:56:35 +000010595 union node **rpp2;
Eric Andersencb57d552001-06-28 07:25:16 +000010596 int t;
10597
10598 redir = NULL;
Eric Andersenc470f442003-07-28 09:56:35 +000010599 rpp2 = &redir;
Eric Andersen88cec252001-09-06 17:35:20 +000010600
Eric Andersencb57d552001-06-28 07:25:16 +000010601 switch (readtoken()) {
Eric Andersenc470f442003-07-28 09:56:35 +000010602 default:
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010603 raise_error_unexpected_syntax(-1);
Eric Andersenc470f442003-07-28 09:56:35 +000010604 /* NOTREACHED */
Eric Andersencb57d552001-06-28 07:25:16 +000010605 case TIF:
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010606 n1 = stzalloc(sizeof(struct nif));
Eric Andersencb57d552001-06-28 07:25:16 +000010607 n1->type = NIF;
10608 n1->nif.test = list(0);
10609 if (readtoken() != TTHEN)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010610 raise_error_unexpected_syntax(TTHEN);
Eric Andersencb57d552001-06-28 07:25:16 +000010611 n1->nif.ifpart = list(0);
10612 n2 = n1;
10613 while (readtoken() == TELIF) {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010614 n2->nif.elsepart = stzalloc(sizeof(struct nif));
Eric Andersencb57d552001-06-28 07:25:16 +000010615 n2 = n2->nif.elsepart;
10616 n2->type = NIF;
10617 n2->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 n2->nif.ifpart = list(0);
10621 }
10622 if (lasttoken == TELSE)
10623 n2->nif.elsepart = list(0);
10624 else {
10625 n2->nif.elsepart = NULL;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010626 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010627 }
Eric Andersenc470f442003-07-28 09:56:35 +000010628 t = TFI;
Eric Andersencb57d552001-06-28 07:25:16 +000010629 break;
10630 case TWHILE:
Eric Andersenc470f442003-07-28 09:56:35 +000010631 case TUNTIL: {
Eric Andersencb57d552001-06-28 07:25:16 +000010632 int got;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010633 n1 = stzalloc(sizeof(struct nbinary));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010634 n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
Eric Andersencb57d552001-06-28 07:25:16 +000010635 n1->nbinary.ch1 = list(0);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010636 got = readtoken();
10637 if (got != TDO) {
Denis Vlasenko131ae172007-02-18 13:00:19 +000010638 TRACE(("expecting DO got %s %s\n", tokname(got),
10639 got == TWORD ? wordtext : ""));
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010640 raise_error_unexpected_syntax(TDO);
Eric Andersencb57d552001-06-28 07:25:16 +000010641 }
10642 n1->nbinary.ch2 = list(0);
Eric Andersenc470f442003-07-28 09:56:35 +000010643 t = TDONE;
Eric Andersencb57d552001-06-28 07:25:16 +000010644 break;
10645 }
10646 case TFOR:
Denis Vlasenko2dc240c2008-07-24 06:07:50 +000010647 if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
Denis Vlasenko559691a2008-10-05 18:39:31 +000010648 raise_error_syntax("bad for loop variable");
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010649 n1 = stzalloc(sizeof(struct nfor));
Eric Andersencb57d552001-06-28 07:25:16 +000010650 n1->type = NFOR;
10651 n1->nfor.var = wordtext;
Eric Andersenc470f442003-07-28 09:56:35 +000010652 checkkwd = CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010653 if (readtoken() == TIN) {
10654 app = &ap;
10655 while (readtoken() == TWORD) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010656 n2 = stzalloc(sizeof(struct narg));
Eric Andersencb57d552001-06-28 07:25:16 +000010657 n2->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010658 /*n2->narg.next = NULL; - stzalloc did it */
Eric Andersencb57d552001-06-28 07:25:16 +000010659 n2->narg.text = wordtext;
10660 n2->narg.backquote = backquotelist;
10661 *app = n2;
10662 app = &n2->narg.next;
10663 }
10664 *app = NULL;
10665 n1->nfor.args = ap;
10666 if (lasttoken != TNL && lasttoken != TSEMI)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010667 raise_error_unexpected_syntax(-1);
Eric Andersencb57d552001-06-28 07:25:16 +000010668 } else {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010669 n2 = stzalloc(sizeof(struct narg));
Eric Andersencb57d552001-06-28 07:25:16 +000010670 n2->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010671 /*n2->narg.next = NULL; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000010672 n2->narg.text = (char *)dolatstr;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010673 /*n2->narg.backquote = NULL;*/
Eric Andersencb57d552001-06-28 07:25:16 +000010674 n1->nfor.args = n2;
10675 /*
10676 * Newline or semicolon here is optional (but note
10677 * that the original Bourne shell only allowed NL).
10678 */
10679 if (lasttoken != TNL && lasttoken != TSEMI)
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010680 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010681 }
Eric Andersenc470f442003-07-28 09:56:35 +000010682 checkkwd = CHKNL | CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010683 if (readtoken() != TDO)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010684 raise_error_unexpected_syntax(TDO);
Eric Andersencb57d552001-06-28 07:25:16 +000010685 n1->nfor.body = list(0);
Eric Andersenc470f442003-07-28 09:56:35 +000010686 t = TDONE;
Eric Andersencb57d552001-06-28 07:25:16 +000010687 break;
10688 case TCASE:
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010689 n1 = stzalloc(sizeof(struct ncase));
Eric Andersencb57d552001-06-28 07:25:16 +000010690 n1->type = NCASE;
10691 if (readtoken() != TWORD)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010692 raise_error_unexpected_syntax(TWORD);
Denis Vlasenko597906c2008-02-20 16:38:54 +000010693 n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
Eric Andersencb57d552001-06-28 07:25:16 +000010694 n2->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010695 /*n2->narg.next = NULL; - stzalloc did it */
Eric Andersencb57d552001-06-28 07:25:16 +000010696 n2->narg.text = wordtext;
10697 n2->narg.backquote = backquotelist;
Eric Andersencb57d552001-06-28 07:25:16 +000010698 do {
Eric Andersenc470f442003-07-28 09:56:35 +000010699 checkkwd = CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010700 } while (readtoken() == TNL);
10701 if (lasttoken != TIN)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010702 raise_error_unexpected_syntax(TIN);
Eric Andersencb57d552001-06-28 07:25:16 +000010703 cpp = &n1->ncase.cases;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010704 next_case:
Eric Andersenc470f442003-07-28 09:56:35 +000010705 checkkwd = CHKNL | CHKKWD;
10706 t = readtoken();
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010707 while (t != TESAC) {
Eric Andersencb57d552001-06-28 07:25:16 +000010708 if (lasttoken == TLP)
10709 readtoken();
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010710 *cpp = cp = stzalloc(sizeof(struct nclist));
Eric Andersencb57d552001-06-28 07:25:16 +000010711 cp->type = NCLIST;
10712 app = &cp->nclist.pattern;
10713 for (;;) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010714 *app = ap = stzalloc(sizeof(struct narg));
Eric Andersencb57d552001-06-28 07:25:16 +000010715 ap->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010716 /*ap->narg.next = NULL; - stzalloc did it */
Eric Andersencb57d552001-06-28 07:25:16 +000010717 ap->narg.text = wordtext;
10718 ap->narg.backquote = backquotelist;
Eric Andersenc470f442003-07-28 09:56:35 +000010719 if (readtoken() != TPIPE)
Eric Andersencb57d552001-06-28 07:25:16 +000010720 break;
10721 app = &ap->narg.next;
10722 readtoken();
10723 }
Denis Vlasenko597906c2008-02-20 16:38:54 +000010724 //ap->narg.next = NULL;
Eric Andersencb57d552001-06-28 07:25:16 +000010725 if (lasttoken != TRP)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010726 raise_error_unexpected_syntax(TRP);
Eric Andersenc470f442003-07-28 09:56:35 +000010727 cp->nclist.body = list(2);
Eric Andersencb57d552001-06-28 07:25:16 +000010728
Eric Andersenc470f442003-07-28 09:56:35 +000010729 cpp = &cp->nclist.next;
10730
10731 checkkwd = CHKNL | CHKKWD;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010732 t = readtoken();
10733 if (t != TESAC) {
Eric Andersencb57d552001-06-28 07:25:16 +000010734 if (t != TENDCASE)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010735 raise_error_unexpected_syntax(TENDCASE);
10736 goto next_case;
Eric Andersencb57d552001-06-28 07:25:16 +000010737 }
Eric Andersenc470f442003-07-28 09:56:35 +000010738 }
Eric Andersencb57d552001-06-28 07:25:16 +000010739 *cpp = NULL;
Eric Andersenc470f442003-07-28 09:56:35 +000010740 goto redir;
Eric Andersencb57d552001-06-28 07:25:16 +000010741 case TLP:
Denis Vlasenko597906c2008-02-20 16:38:54 +000010742 n1 = stzalloc(sizeof(struct nredir));
Eric Andersencb57d552001-06-28 07:25:16 +000010743 n1->type = NSUBSHELL;
10744 n1->nredir.n = list(0);
Denis Vlasenko597906c2008-02-20 16:38:54 +000010745 /*n1->nredir.redirect = NULL; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000010746 t = TRP;
Eric Andersencb57d552001-06-28 07:25:16 +000010747 break;
10748 case TBEGIN:
10749 n1 = list(0);
Eric Andersenc470f442003-07-28 09:56:35 +000010750 t = TEND;
Eric Andersencb57d552001-06-28 07:25:16 +000010751 break;
Eric Andersencb57d552001-06-28 07:25:16 +000010752 case TWORD:
Eric Andersenc470f442003-07-28 09:56:35 +000010753 case TREDIR:
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010754 tokpushback = 1;
Eric Andersenc470f442003-07-28 09:56:35 +000010755 return simplecmd();
Eric Andersencb57d552001-06-28 07:25:16 +000010756 }
10757
Eric Andersenc470f442003-07-28 09:56:35 +000010758 if (readtoken() != t)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010759 raise_error_unexpected_syntax(t);
Eric Andersenc470f442003-07-28 09:56:35 +000010760
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010761 redir:
Eric Andersencb57d552001-06-28 07:25:16 +000010762 /* Now check for redirection which may follow command */
Eric Andersenc470f442003-07-28 09:56:35 +000010763 checkkwd = CHKKWD | CHKALIAS;
10764 rpp = rpp2;
Eric Andersencb57d552001-06-28 07:25:16 +000010765 while (readtoken() == TREDIR) {
10766 *rpp = n2 = redirnode;
10767 rpp = &n2->nfile.next;
10768 parsefname();
10769 }
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010770 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010771 *rpp = NULL;
10772 if (redir) {
10773 if (n1->type != NSUBSHELL) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010774 n2 = stzalloc(sizeof(struct nredir));
Eric Andersencb57d552001-06-28 07:25:16 +000010775 n2->type = NREDIR;
10776 n2->nredir.n = n1;
10777 n1 = n2;
10778 }
10779 n1->nredir.redirect = redir;
10780 }
Eric Andersencb57d552001-06-28 07:25:16 +000010781 return n1;
10782}
10783
Denis Vlasenkoef527f52008-06-23 01:52:30 +000010784#if ENABLE_ASH_BASH_COMPAT
10785static int decode_dollar_squote(void)
10786{
10787 static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
10788 int c, cnt;
10789 char *p;
10790 char buf[4];
10791
10792 c = pgetc();
10793 p = strchr(C_escapes, c);
10794 if (p) {
10795 buf[0] = c;
10796 p = buf;
10797 cnt = 3;
10798 if ((unsigned char)(c - '0') <= 7) { /* \ooo */
10799 do {
10800 c = pgetc();
10801 *++p = c;
10802 } while ((unsigned char)(c - '0') <= 7 && --cnt);
10803 pungetc();
10804 } else if (c == 'x') { /* \xHH */
10805 do {
10806 c = pgetc();
10807 *++p = c;
10808 } while (isxdigit(c) && --cnt);
10809 pungetc();
10810 if (cnt == 3) { /* \x but next char is "bad" */
10811 c = 'x';
10812 goto unrecognized;
10813 }
10814 } else { /* simple seq like \\ or \t */
10815 p++;
10816 }
10817 *p = '\0';
10818 p = buf;
10819 c = bb_process_escape_sequence((void*)&p);
10820 } else { /* unrecognized "\z": print both chars unless ' or " */
10821 if (c != '\'' && c != '"') {
10822 unrecognized:
10823 c |= 0x100; /* "please encode \, then me" */
10824 }
10825 }
10826 return c;
10827}
10828#endif
10829
Eric Andersencb57d552001-06-28 07:25:16 +000010830/*
10831 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
10832 * is not NULL, read a here document. In the latter case, eofmark is the
10833 * word which marks the end of the document and striptabs is true if
10834 * leading tabs should be stripped from the document. The argument firstc
10835 * is the first character of the input token or document.
10836 *
10837 * Because C does not have internal subroutines, I have simulated them
10838 * using goto's to implement the subroutine linkage. The following macros
10839 * will run code that appears at the end of readtoken1.
10840 */
Eric Andersen2870d962001-07-02 17:27:21 +000010841#define CHECKEND() {goto checkend; checkend_return:;}
10842#define PARSEREDIR() {goto parseredir; parseredir_return:;}
10843#define PARSESUB() {goto parsesub; parsesub_return:;}
10844#define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
10845#define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
10846#define PARSEARITH() {goto parsearith; parsearith_return:;}
Eric Andersencb57d552001-06-28 07:25:16 +000010847static int
Eric Andersenc470f442003-07-28 09:56:35 +000010848readtoken1(int firstc, int syntax, char *eofmark, int striptabs)
Manuel Novoa III 16815d42001-08-10 19:36:07 +000010849{
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010850 /* NB: syntax parameter fits into smallint */
Eric Andersencb57d552001-06-28 07:25:16 +000010851 int c = firstc;
10852 char *out;
10853 int len;
10854 char line[EOFMARKLEN + 1];
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010855 struct nodelist *bqlist;
10856 smallint quotef;
10857 smallint dblquote;
10858 smallint oldstyle;
10859 smallint prevsyntax; /* syntax before arithmetic */
Denis Vlasenko46a53062007-09-24 18:30:02 +000010860#if ENABLE_ASH_EXPAND_PRMT
10861 smallint pssyntax; /* we are expanding a prompt string */
10862#endif
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010863 int varnest; /* levels of variables expansion */
10864 int arinest; /* levels of arithmetic expansion */
10865 int parenlevel; /* levels of parens in arithmetic */
10866 int dqvarnest; /* levels of variables expansion within double quotes */
10867
Denis Vlasenko5e34ff22009-04-21 11:09:40 +000010868 IF_ASH_BASH_COMPAT(smallint bash_dollar_squote = 0;)
Denis Vlasenkoef527f52008-06-23 01:52:30 +000010869
Eric Andersencb57d552001-06-28 07:25:16 +000010870#if __GNUC__
10871 /* Avoid longjmp clobbering */
10872 (void) &out;
10873 (void) &quotef;
10874 (void) &dblquote;
10875 (void) &varnest;
10876 (void) &arinest;
10877 (void) &parenlevel;
10878 (void) &dqvarnest;
10879 (void) &oldstyle;
10880 (void) &prevsyntax;
10881 (void) &syntax;
10882#endif
Denis Vlasenko41eb3002008-11-28 03:42:31 +000010883 startlinno = g_parsefile->linno;
Eric Andersencb57d552001-06-28 07:25:16 +000010884 bqlist = NULL;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010885 quotef = 0;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010886 oldstyle = 0;
10887 prevsyntax = 0;
Denis Vlasenko46a53062007-09-24 18:30:02 +000010888#if ENABLE_ASH_EXPAND_PRMT
10889 pssyntax = (syntax == PSSYNTAX);
10890 if (pssyntax)
10891 syntax = DQSYNTAX;
10892#endif
10893 dblquote = (syntax == DQSYNTAX);
Eric Andersencb57d552001-06-28 07:25:16 +000010894 varnest = 0;
10895 arinest = 0;
10896 parenlevel = 0;
10897 dqvarnest = 0;
10898
10899 STARTSTACKSTR(out);
Denis Vlasenko176d49d2008-10-06 09:51:47 +000010900 loop:
10901 /* For each line, until end of word */
10902 {
Eric Andersenc470f442003-07-28 09:56:35 +000010903 CHECKEND(); /* set c to PEOF if at end of here document */
10904 for (;;) { /* until end of line or end of word */
10905 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
Denis Vlasenkobf0a2012006-12-26 10:42:51 +000010906 switch (SIT(c, syntax)) {
Eric Andersenc470f442003-07-28 09:56:35 +000010907 case CNL: /* '\n' */
Eric Andersencb57d552001-06-28 07:25:16 +000010908 if (syntax == BASESYNTAX)
Eric Andersenc470f442003-07-28 09:56:35 +000010909 goto endword; /* exit outer loop */
Eric Andersencb57d552001-06-28 07:25:16 +000010910 USTPUTC(c, out);
Denis Vlasenko41eb3002008-11-28 03:42:31 +000010911 g_parsefile->linno++;
Eric Andersencb57d552001-06-28 07:25:16 +000010912 if (doprompt)
10913 setprompt(2);
Eric Andersencb57d552001-06-28 07:25:16 +000010914 c = pgetc();
Eric Andersenc470f442003-07-28 09:56:35 +000010915 goto loop; /* continue outer loop */
Eric Andersencb57d552001-06-28 07:25:16 +000010916 case CWORD:
10917 USTPUTC(c, out);
10918 break;
10919 case CCTL:
Eric Andersenc470f442003-07-28 09:56:35 +000010920 if (eofmark == NULL || dblquote)
Eric Andersencb57d552001-06-28 07:25:16 +000010921 USTPUTC(CTLESC, out);
Denis Vlasenkoef527f52008-06-23 01:52:30 +000010922#if ENABLE_ASH_BASH_COMPAT
10923 if (c == '\\' && bash_dollar_squote) {
10924 c = decode_dollar_squote();
10925 if (c & 0x100) {
10926 USTPUTC('\\', out);
10927 c = (unsigned char)c;
10928 }
10929 }
10930#endif
Eric Andersencb57d552001-06-28 07:25:16 +000010931 USTPUTC(c, out);
10932 break;
Eric Andersenc470f442003-07-28 09:56:35 +000010933 case CBACK: /* backslash */
Eric Andersencb57d552001-06-28 07:25:16 +000010934 c = pgetc2();
10935 if (c == PEOF) {
Eric Andersenc470f442003-07-28 09:56:35 +000010936 USTPUTC(CTLESC, out);
Eric Andersencb57d552001-06-28 07:25:16 +000010937 USTPUTC('\\', out);
10938 pungetc();
10939 } else if (c == '\n') {
10940 if (doprompt)
10941 setprompt(2);
Eric Andersencb57d552001-06-28 07:25:16 +000010942 } else {
Denis Vlasenko46a53062007-09-24 18:30:02 +000010943#if ENABLE_ASH_EXPAND_PRMT
10944 if (c == '$' && pssyntax) {
10945 USTPUTC(CTLESC, out);
10946 USTPUTC('\\', out);
10947 }
10948#endif
Denis Vlasenkoef527f52008-06-23 01:52:30 +000010949 if (dblquote && c != '\\'
10950 && c != '`' && c != '$'
10951 && (c != '"' || eofmark != NULL)
Eric Andersenc470f442003-07-28 09:56:35 +000010952 ) {
10953 USTPUTC(CTLESC, out);
Eric Andersencb57d552001-06-28 07:25:16 +000010954 USTPUTC('\\', out);
Eric Andersenc470f442003-07-28 09:56:35 +000010955 }
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010956 if (SIT(c, SQSYNTAX) == CCTL)
Eric Andersencb57d552001-06-28 07:25:16 +000010957 USTPUTC(CTLESC, out);
Eric Andersencb57d552001-06-28 07:25:16 +000010958 USTPUTC(c, out);
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010959 quotef = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010960 }
10961 break;
10962 case CSQUOTE:
Eric Andersencb57d552001-06-28 07:25:16 +000010963 syntax = SQSYNTAX;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010964 quotemark:
Eric Andersenc470f442003-07-28 09:56:35 +000010965 if (eofmark == NULL) {
10966 USTPUTC(CTLQUOTEMARK, out);
10967 }
Eric Andersencb57d552001-06-28 07:25:16 +000010968 break;
10969 case CDQUOTE:
Eric Andersencb57d552001-06-28 07:25:16 +000010970 syntax = DQSYNTAX;
10971 dblquote = 1;
Eric Andersenc470f442003-07-28 09:56:35 +000010972 goto quotemark;
Eric Andersencb57d552001-06-28 07:25:16 +000010973 case CENDQUOTE:
Denis Vlasenko5e34ff22009-04-21 11:09:40 +000010974 IF_ASH_BASH_COMPAT(bash_dollar_squote = 0;)
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010975 if (eofmark != NULL && arinest == 0
10976 && varnest == 0
10977 ) {
Eric Andersencb57d552001-06-28 07:25:16 +000010978 USTPUTC(c, out);
10979 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000010980 if (dqvarnest == 0) {
Eric Andersencb57d552001-06-28 07:25:16 +000010981 syntax = BASESYNTAX;
10982 dblquote = 0;
10983 }
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010984 quotef = 1;
Eric Andersenc470f442003-07-28 09:56:35 +000010985 goto quotemark;
Eric Andersencb57d552001-06-28 07:25:16 +000010986 }
10987 break;
Eric Andersenc470f442003-07-28 09:56:35 +000010988 case CVAR: /* '$' */
10989 PARSESUB(); /* parse substitution */
Eric Andersencb57d552001-06-28 07:25:16 +000010990 break;
Eric Andersenc470f442003-07-28 09:56:35 +000010991 case CENDVAR: /* '}' */
Eric Andersencb57d552001-06-28 07:25:16 +000010992 if (varnest > 0) {
10993 varnest--;
10994 if (dqvarnest > 0) {
10995 dqvarnest--;
10996 }
10997 USTPUTC(CTLENDVAR, out);
10998 } else {
10999 USTPUTC(c, out);
11000 }
11001 break;
Mike Frysinger98c52642009-04-02 10:02:37 +000011002#if ENABLE_SH_MATH_SUPPORT
Eric Andersenc470f442003-07-28 09:56:35 +000011003 case CLP: /* '(' in arithmetic */
Eric Andersencb57d552001-06-28 07:25:16 +000011004 parenlevel++;
11005 USTPUTC(c, out);
11006 break;
Eric Andersenc470f442003-07-28 09:56:35 +000011007 case CRP: /* ')' in arithmetic */
Eric Andersencb57d552001-06-28 07:25:16 +000011008 if (parenlevel > 0) {
11009 USTPUTC(c, out);
11010 --parenlevel;
11011 } else {
11012 if (pgetc() == ')') {
11013 if (--arinest == 0) {
11014 USTPUTC(CTLENDARI, out);
11015 syntax = prevsyntax;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011016 dblquote = (syntax == DQSYNTAX);
Eric Andersencb57d552001-06-28 07:25:16 +000011017 } else
11018 USTPUTC(')', out);
11019 } else {
11020 /*
11021 * unbalanced parens
11022 * (don't 2nd guess - no error)
11023 */
11024 pungetc();
11025 USTPUTC(')', out);
11026 }
11027 }
11028 break;
11029#endif
Eric Andersenc470f442003-07-28 09:56:35 +000011030 case CBQUOTE: /* '`' */
Eric Andersencb57d552001-06-28 07:25:16 +000011031 PARSEBACKQOLD();
11032 break;
Eric Andersen2870d962001-07-02 17:27:21 +000011033 case CENDFILE:
Eric Andersenc470f442003-07-28 09:56:35 +000011034 goto endword; /* exit outer loop */
Eric Andersencb57d552001-06-28 07:25:16 +000011035 case CIGN:
11036 break;
11037 default:
Denis Vlasenko834dee72008-10-07 09:18:30 +000011038 if (varnest == 0) {
11039#if ENABLE_ASH_BASH_COMPAT
11040 if (c == '&') {
11041 if (pgetc() == '>')
11042 c = 0x100 + '>'; /* flag &> */
11043 pungetc();
11044 }
11045#endif
Eric Andersenc470f442003-07-28 09:56:35 +000011046 goto endword; /* exit outer loop */
Denis Vlasenko834dee72008-10-07 09:18:30 +000011047 }
Denis Vlasenko131ae172007-02-18 13:00:19 +000011048#if ENABLE_ASH_ALIAS
Eric Andersen3102ac42001-07-06 04:26:23 +000011049 if (c != PEOA)
11050#endif
Eric Andersencb57d552001-06-28 07:25:16 +000011051 USTPUTC(c, out);
Eric Andersen3102ac42001-07-06 04:26:23 +000011052
Eric Andersencb57d552001-06-28 07:25:16 +000011053 }
Denis Vlasenko834dee72008-10-07 09:18:30 +000011054 c = pgetc_fast();
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000011055 } /* for (;;) */
Eric Andersencb57d552001-06-28 07:25:16 +000011056 }
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011057 endword:
Mike Frysinger98c52642009-04-02 10:02:37 +000011058#if ENABLE_SH_MATH_SUPPORT
Eric Andersencb57d552001-06-28 07:25:16 +000011059 if (syntax == ARISYNTAX)
Denis Vlasenko559691a2008-10-05 18:39:31 +000011060 raise_error_syntax("missing '))'");
Eric Andersenc470f442003-07-28 09:56:35 +000011061#endif
Denis Vlasenko99eb8502007-02-23 21:09:49 +000011062 if (syntax != BASESYNTAX && !parsebackquote && eofmark == NULL)
Denis Vlasenko559691a2008-10-05 18:39:31 +000011063 raise_error_syntax("unterminated quoted string");
Eric Andersencb57d552001-06-28 07:25:16 +000011064 if (varnest != 0) {
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011065 startlinno = g_parsefile->linno;
Eric Andersenc470f442003-07-28 09:56:35 +000011066 /* { */
Denis Vlasenko559691a2008-10-05 18:39:31 +000011067 raise_error_syntax("missing '}'");
Eric Andersencb57d552001-06-28 07:25:16 +000011068 }
11069 USTPUTC('\0', out);
Eric Andersenc470f442003-07-28 09:56:35 +000011070 len = out - (char *)stackblock();
Eric Andersencb57d552001-06-28 07:25:16 +000011071 out = stackblock();
11072 if (eofmark == NULL) {
Denis Vlasenko5e34ff22009-04-21 11:09:40 +000011073 if ((c == '>' || c == '<' IF_ASH_BASH_COMPAT( || c == 0x100 + '>'))
Denis Vlasenko834dee72008-10-07 09:18:30 +000011074 && quotef == 0
11075 ) {
Denis Vlasenko559691a2008-10-05 18:39:31 +000011076 if (isdigit_str9(out)) {
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000011077 PARSEREDIR(); /* passed as params: out, c */
11078 lasttoken = TREDIR;
11079 return lasttoken;
11080 }
11081 /* else: non-number X seen, interpret it
11082 * as "NNNX>file" = "NNNX >file" */
Eric Andersencb57d552001-06-28 07:25:16 +000011083 }
Denis Vlasenkoef527f52008-06-23 01:52:30 +000011084 pungetc();
Eric Andersencb57d552001-06-28 07:25:16 +000011085 }
11086 quoteflag = quotef;
11087 backquotelist = bqlist;
11088 grabstackblock(len);
11089 wordtext = out;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011090 lasttoken = TWORD;
11091 return lasttoken;
Eric Andersencb57d552001-06-28 07:25:16 +000011092/* end of readtoken routine */
11093
Eric Andersencb57d552001-06-28 07:25:16 +000011094/*
11095 * Check to see whether we are at the end of the here document. When this
11096 * is called, c is set to the first character of the next input line. If
11097 * we are at the end of the here document, this routine sets the c to PEOF.
11098 */
Eric Andersenc470f442003-07-28 09:56:35 +000011099checkend: {
11100 if (eofmark) {
Denis Vlasenko131ae172007-02-18 13:00:19 +000011101#if ENABLE_ASH_ALIAS
Eric Andersenc470f442003-07-28 09:56:35 +000011102 if (c == PEOA) {
11103 c = pgetc2();
11104 }
11105#endif
11106 if (striptabs) {
11107 while (c == '\t') {
Eric Andersencb57d552001-06-28 07:25:16 +000011108 c = pgetc2();
11109 }
Eric Andersenc470f442003-07-28 09:56:35 +000011110 }
11111 if (c == *eofmark) {
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011112 if (pfgets(line, sizeof(line)) != NULL) {
Eric Andersenc470f442003-07-28 09:56:35 +000011113 char *p, *q;
Eric Andersencb57d552001-06-28 07:25:16 +000011114
Eric Andersenc470f442003-07-28 09:56:35 +000011115 p = line;
Denis Vlasenkof7d56652008-03-25 05:51:41 +000011116 for (q = eofmark + 1; *q && *p == *q; p++, q++)
11117 continue;
Eric Andersenc470f442003-07-28 09:56:35 +000011118 if (*p == '\n' && *q == '\0') {
11119 c = PEOF;
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011120 g_parsefile->linno++;
Eric Andersenc470f442003-07-28 09:56:35 +000011121 needprompt = doprompt;
11122 } else {
11123 pushstring(line, NULL);
Eric Andersencb57d552001-06-28 07:25:16 +000011124 }
11125 }
11126 }
11127 }
Eric Andersenc470f442003-07-28 09:56:35 +000011128 goto checkend_return;
11129}
Eric Andersencb57d552001-06-28 07:25:16 +000011130
Eric Andersencb57d552001-06-28 07:25:16 +000011131/*
11132 * Parse a redirection operator. The variable "out" points to a string
11133 * specifying the fd to be redirected. The variable "c" contains the
11134 * first character of the redirection operator.
11135 */
Eric Andersenc470f442003-07-28 09:56:35 +000011136parseredir: {
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000011137 /* out is already checked to be a valid number or "" */
11138 int fd = (*out == '\0' ? -1 : atoi(out));
Eric Andersenc470f442003-07-28 09:56:35 +000011139 union node *np;
Eric Andersencb57d552001-06-28 07:25:16 +000011140
Denis Vlasenko597906c2008-02-20 16:38:54 +000011141 np = stzalloc(sizeof(struct nfile));
Eric Andersenc470f442003-07-28 09:56:35 +000011142 if (c == '>') {
11143 np->nfile.fd = 1;
11144 c = pgetc();
11145 if (c == '>')
11146 np->type = NAPPEND;
11147 else if (c == '|')
11148 np->type = NCLOBBER;
11149 else if (c == '&')
11150 np->type = NTOFD;
Denis Vlasenko559691a2008-10-05 18:39:31 +000011151 /* it also can be NTO2 (>&file), but we can't figure it out yet */
Eric Andersenc470f442003-07-28 09:56:35 +000011152 else {
11153 np->type = NTO;
11154 pungetc();
Eric Andersencb57d552001-06-28 07:25:16 +000011155 }
Denis Vlasenko834dee72008-10-07 09:18:30 +000011156 }
11157#if ENABLE_ASH_BASH_COMPAT
11158 else if (c == 0x100 + '>') { /* this flags &> redirection */
11159 np->nfile.fd = 1;
11160 pgetc(); /* this is '>', no need to check */
11161 np->type = NTO2;
11162 }
11163#endif
11164 else { /* c == '<' */
Denis Vlasenko597906c2008-02-20 16:38:54 +000011165 /*np->nfile.fd = 0; - stzalloc did it */
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011166 c = pgetc();
11167 switch (c) {
Eric Andersenc470f442003-07-28 09:56:35 +000011168 case '<':
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011169 if (sizeof(struct nfile) != sizeof(struct nhere)) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000011170 np = stzalloc(sizeof(struct nhere));
11171 /*np->nfile.fd = 0; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000011172 }
11173 np->type = NHERE;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000011174 heredoc = stzalloc(sizeof(struct heredoc));
Eric Andersenc470f442003-07-28 09:56:35 +000011175 heredoc->here = np;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011176 c = pgetc();
11177 if (c == '-') {
Eric Andersenc470f442003-07-28 09:56:35 +000011178 heredoc->striptabs = 1;
11179 } else {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000011180 /*heredoc->striptabs = 0; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000011181 pungetc();
11182 }
11183 break;
11184
11185 case '&':
11186 np->type = NFROMFD;
11187 break;
11188
11189 case '>':
11190 np->type = NFROMTO;
11191 break;
11192
11193 default:
11194 np->type = NFROM;
11195 pungetc();
11196 break;
11197 }
Eric Andersencb57d552001-06-28 07:25:16 +000011198 }
Denis Vlasenko6fbb43b2008-07-24 19:44:41 +000011199 if (fd >= 0)
11200 np->nfile.fd = fd;
Eric Andersenc470f442003-07-28 09:56:35 +000011201 redirnode = np;
11202 goto parseredir_return;
11203}
Eric Andersencb57d552001-06-28 07:25:16 +000011204
Eric Andersencb57d552001-06-28 07:25:16 +000011205/*
11206 * Parse a substitution. At this point, we have read the dollar sign
11207 * and nothing else.
11208 */
Denis Vlasenkocc571512007-02-23 21:10:35 +000011209
11210/* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
11211 * (assuming ascii char codes, as the original implementation did) */
11212#define is_special(c) \
Denis Vlasenkoef527f52008-06-23 01:52:30 +000011213 (((unsigned)(c) - 33 < 32) \
11214 && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
Eric Andersenc470f442003-07-28 09:56:35 +000011215parsesub: {
11216 int subtype;
11217 int typeloc;
11218 int flags;
11219 char *p;
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011220 static const char types[] ALIGN1 = "}-+?=";
Eric Andersencb57d552001-06-28 07:25:16 +000011221
Eric Andersenc470f442003-07-28 09:56:35 +000011222 c = pgetc();
Denis Vlasenkoef527f52008-06-23 01:52:30 +000011223 if (c <= PEOA_OR_PEOF
11224 || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
Eric Andersenc470f442003-07-28 09:56:35 +000011225 ) {
Denis Vlasenkoef527f52008-06-23 01:52:30 +000011226#if ENABLE_ASH_BASH_COMPAT
11227 if (c == '\'')
11228 bash_dollar_squote = 1;
11229 else
11230#endif
11231 USTPUTC('$', out);
Eric Andersenc470f442003-07-28 09:56:35 +000011232 pungetc();
11233 } else if (c == '(') { /* $(command) or $((arith)) */
11234 if (pgetc() == '(') {
Mike Frysinger98c52642009-04-02 10:02:37 +000011235#if ENABLE_SH_MATH_SUPPORT
Eric Andersenc470f442003-07-28 09:56:35 +000011236 PARSEARITH();
11237#else
Mike Frysinger98a6f562008-06-09 09:38:45 +000011238 raise_error_syntax("you disabled math support for $((arith)) syntax");
Eric Andersenc470f442003-07-28 09:56:35 +000011239#endif
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000011240 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000011241 pungetc();
11242 PARSEBACKQNEW();
11243 }
11244 } else {
11245 USTPUTC(CTLVAR, out);
11246 typeloc = out - (char *)stackblock();
11247 USTPUTC(VSNORMAL, out);
11248 subtype = VSNORMAL;
11249 if (c == '{') {
11250 c = pgetc();
11251 if (c == '#') {
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011252 c = pgetc();
11253 if (c == '}')
Eric Andersenc470f442003-07-28 09:56:35 +000011254 c = '#';
11255 else
11256 subtype = VSLENGTH;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011257 } else
Eric Andersenc470f442003-07-28 09:56:35 +000011258 subtype = 0;
11259 }
11260 if (c > PEOA_OR_PEOF && is_name(c)) {
11261 do {
11262 STPUTC(c, out);
Eric Andersencb57d552001-06-28 07:25:16 +000011263 c = pgetc();
Eric Andersenc470f442003-07-28 09:56:35 +000011264 } while (c > PEOA_OR_PEOF && is_in_name(c));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011265 } else if (isdigit(c)) {
Eric Andersenc470f442003-07-28 09:56:35 +000011266 do {
11267 STPUTC(c, out);
11268 c = pgetc();
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011269 } while (isdigit(c));
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011270 } else if (is_special(c)) {
Eric Andersenc470f442003-07-28 09:56:35 +000011271 USTPUTC(c, out);
11272 c = pgetc();
Denis Vlasenko559691a2008-10-05 18:39:31 +000011273 } else {
11274 badsub:
11275 raise_error_syntax("bad substitution");
11276 }
Cristian Ionescu-Idbohrn301f5ec2009-10-05 02:07:23 +020011277 if (c != '}' && subtype == VSLENGTH)
11278 goto badsub;
Eric Andersencb57d552001-06-28 07:25:16 +000011279
Eric Andersenc470f442003-07-28 09:56:35 +000011280 STPUTC('=', out);
11281 flags = 0;
11282 if (subtype == 0) {
11283 switch (c) {
11284 case ':':
Eric Andersenc470f442003-07-28 09:56:35 +000011285 c = pgetc();
Denis Vlasenko92e13c22008-03-25 01:17:40 +000011286#if ENABLE_ASH_BASH_COMPAT
11287 if (c == ':' || c == '$' || isdigit(c)) {
11288 pungetc();
11289 subtype = VSSUBSTR;
11290 break;
11291 }
11292#endif
11293 flags = VSNUL;
Eric Andersenc470f442003-07-28 09:56:35 +000011294 /*FALLTHROUGH*/
11295 default:
11296 p = strchr(types, c);
11297 if (p == NULL)
11298 goto badsub;
11299 subtype = p - types + VSNORMAL;
11300 break;
11301 case '%':
Denis Vlasenko92e13c22008-03-25 01:17:40 +000011302 case '#': {
11303 int cc = c;
11304 subtype = c == '#' ? VSTRIMLEFT : VSTRIMRIGHT;
11305 c = pgetc();
11306 if (c == cc)
11307 subtype++;
11308 else
11309 pungetc();
11310 break;
11311 }
11312#if ENABLE_ASH_BASH_COMPAT
11313 case '/':
11314 subtype = VSREPLACE;
11315 c = pgetc();
11316 if (c == '/')
11317 subtype++; /* VSREPLACEALL */
11318 else
11319 pungetc();
11320 break;
11321#endif
Eric Andersencb57d552001-06-28 07:25:16 +000011322 }
Eric Andersenc470f442003-07-28 09:56:35 +000011323 } else {
11324 pungetc();
11325 }
11326 if (dblquote || arinest)
11327 flags |= VSQUOTE;
11328 *((char *)stackblock() + typeloc) = subtype | flags;
11329 if (subtype != VSNORMAL) {
11330 varnest++;
11331 if (dblquote || arinest) {
11332 dqvarnest++;
Eric Andersencb57d552001-06-28 07:25:16 +000011333 }
11334 }
11335 }
Eric Andersenc470f442003-07-28 09:56:35 +000011336 goto parsesub_return;
11337}
Eric Andersencb57d552001-06-28 07:25:16 +000011338
Eric Andersencb57d552001-06-28 07:25:16 +000011339/*
11340 * Called to parse command substitutions. Newstyle is set if the command
11341 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
11342 * list of commands (passed by reference), and savelen is the number of
11343 * characters on the top of the stack which must be preserved.
11344 */
Eric Andersenc470f442003-07-28 09:56:35 +000011345parsebackq: {
11346 struct nodelist **nlpp;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011347 smallint savepbq;
Eric Andersenc470f442003-07-28 09:56:35 +000011348 union node *n;
11349 char *volatile str;
11350 struct jmploc jmploc;
11351 struct jmploc *volatile savehandler;
11352 size_t savelen;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011353 smallint saveprompt = 0;
11354
Eric Andersencb57d552001-06-28 07:25:16 +000011355#ifdef __GNUC__
Eric Andersenc470f442003-07-28 09:56:35 +000011356 (void) &saveprompt;
Eric Andersencb57d552001-06-28 07:25:16 +000011357#endif
Eric Andersenc470f442003-07-28 09:56:35 +000011358 savepbq = parsebackquote;
11359 if (setjmp(jmploc.loc)) {
Denis Vlasenko60818682007-09-28 22:07:23 +000011360 free(str);
Eric Andersenc470f442003-07-28 09:56:35 +000011361 parsebackquote = 0;
Denis Vlasenko2da584f2007-02-19 22:44:05 +000011362 exception_handler = savehandler;
11363 longjmp(exception_handler->loc, 1);
Eric Andersenc470f442003-07-28 09:56:35 +000011364 }
Denis Vlasenkob012b102007-02-19 22:43:01 +000011365 INT_OFF;
Eric Andersenc470f442003-07-28 09:56:35 +000011366 str = NULL;
11367 savelen = out - (char *)stackblock();
11368 if (savelen > 0) {
11369 str = ckmalloc(savelen);
11370 memcpy(str, stackblock(), savelen);
11371 }
Denis Vlasenko2da584f2007-02-19 22:44:05 +000011372 savehandler = exception_handler;
11373 exception_handler = &jmploc;
Denis Vlasenkob012b102007-02-19 22:43:01 +000011374 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +000011375 if (oldstyle) {
11376 /* We must read until the closing backquote, giving special
11377 treatment to some slashes, and then push the string and
11378 reread it as input, interpreting it normally. */
11379 char *pout;
11380 int pc;
11381 size_t psavelen;
11382 char *pstr;
11383
11384
11385 STARTSTACKSTR(pout);
11386 for (;;) {
11387 if (needprompt) {
11388 setprompt(2);
Eric Andersenc470f442003-07-28 09:56:35 +000011389 }
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011390 pc = pgetc();
11391 switch (pc) {
Eric Andersenc470f442003-07-28 09:56:35 +000011392 case '`':
11393 goto done;
11394
11395 case '\\':
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011396 pc = pgetc();
11397 if (pc == '\n') {
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011398 g_parsefile->linno++;
Eric Andersenc470f442003-07-28 09:56:35 +000011399 if (doprompt)
11400 setprompt(2);
11401 /*
11402 * If eating a newline, avoid putting
11403 * the newline into the new character
11404 * stream (via the STPUTC after the
11405 * switch).
11406 */
11407 continue;
11408 }
11409 if (pc != '\\' && pc != '`' && pc != '$'
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011410 && (!dblquote || pc != '"'))
Eric Andersenc470f442003-07-28 09:56:35 +000011411 STPUTC('\\', pout);
11412 if (pc > PEOA_OR_PEOF) {
11413 break;
11414 }
11415 /* fall through */
11416
11417 case PEOF:
Denis Vlasenko131ae172007-02-18 13:00:19 +000011418#if ENABLE_ASH_ALIAS
Eric Andersenc470f442003-07-28 09:56:35 +000011419 case PEOA:
11420#endif
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011421 startlinno = g_parsefile->linno;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000011422 raise_error_syntax("EOF in backquote substitution");
Eric Andersenc470f442003-07-28 09:56:35 +000011423
11424 case '\n':
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011425 g_parsefile->linno++;
Eric Andersenc470f442003-07-28 09:56:35 +000011426 needprompt = doprompt;
11427 break;
11428
11429 default:
11430 break;
11431 }
11432 STPUTC(pc, pout);
11433 }
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011434 done:
Eric Andersenc470f442003-07-28 09:56:35 +000011435 STPUTC('\0', pout);
11436 psavelen = pout - (char *)stackblock();
11437 if (psavelen > 0) {
11438 pstr = grabstackstr(pout);
11439 setinputstring(pstr);
11440 }
11441 }
11442 nlpp = &bqlist;
11443 while (*nlpp)
11444 nlpp = &(*nlpp)->next;
Denis Vlasenko597906c2008-02-20 16:38:54 +000011445 *nlpp = stzalloc(sizeof(**nlpp));
11446 /* (*nlpp)->next = NULL; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000011447 parsebackquote = oldstyle;
11448
11449 if (oldstyle) {
11450 saveprompt = doprompt;
11451 doprompt = 0;
Eric Andersencb57d552001-06-28 07:25:16 +000011452 }
11453
Eric Andersenc470f442003-07-28 09:56:35 +000011454 n = list(2);
11455
11456 if (oldstyle)
11457 doprompt = saveprompt;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011458 else if (readtoken() != TRP)
11459 raise_error_unexpected_syntax(TRP);
Eric Andersenc470f442003-07-28 09:56:35 +000011460
11461 (*nlpp)->n = n;
11462 if (oldstyle) {
11463 /*
11464 * Start reading from old file again, ignoring any pushed back
11465 * tokens left from the backquote parsing
11466 */
11467 popfile();
11468 tokpushback = 0;
11469 }
11470 while (stackblocksize() <= savelen)
11471 growstackblock();
11472 STARTSTACKSTR(out);
11473 if (str) {
11474 memcpy(out, str, savelen);
11475 STADJUST(savelen, out);
Denis Vlasenkob012b102007-02-19 22:43:01 +000011476 INT_OFF;
11477 free(str);
Eric Andersenc470f442003-07-28 09:56:35 +000011478 str = NULL;
Denis Vlasenkob012b102007-02-19 22:43:01 +000011479 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +000011480 }
11481 parsebackquote = savepbq;
Denis Vlasenko2da584f2007-02-19 22:44:05 +000011482 exception_handler = savehandler;
Eric Andersenc470f442003-07-28 09:56:35 +000011483 if (arinest || dblquote)
11484 USTPUTC(CTLBACKQ | CTLQUOTE, out);
11485 else
11486 USTPUTC(CTLBACKQ, out);
11487 if (oldstyle)
11488 goto parsebackq_oldreturn;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000011489 goto parsebackq_newreturn;
Eric Andersenc470f442003-07-28 09:56:35 +000011490}
11491
Mike Frysinger98c52642009-04-02 10:02:37 +000011492#if ENABLE_SH_MATH_SUPPORT
Eric Andersencb57d552001-06-28 07:25:16 +000011493/*
11494 * Parse an arithmetic expansion (indicate start of one and set state)
11495 */
Eric Andersenc470f442003-07-28 09:56:35 +000011496parsearith: {
Eric Andersenc470f442003-07-28 09:56:35 +000011497 if (++arinest == 1) {
11498 prevsyntax = syntax;
11499 syntax = ARISYNTAX;
11500 USTPUTC(CTLARI, out);
11501 if (dblquote)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000011502 USTPUTC('"', out);
Eric Andersenc470f442003-07-28 09:56:35 +000011503 else
Denis Vlasenkoa624c112007-02-19 22:45:43 +000011504 USTPUTC(' ', out);
Eric Andersenc470f442003-07-28 09:56:35 +000011505 } else {
11506 /*
11507 * we collapse embedded arithmetic expansion to
11508 * parenthesis, which should be equivalent
11509 */
11510 USTPUTC('(', out);
Eric Andersencb57d552001-06-28 07:25:16 +000011511 }
Eric Andersenc470f442003-07-28 09:56:35 +000011512 goto parsearith_return;
11513}
11514#endif
Eric Andersencb57d552001-06-28 07:25:16 +000011515
Eric Andersenc470f442003-07-28 09:56:35 +000011516} /* end of readtoken */
11517
Eric Andersencb57d552001-06-28 07:25:16 +000011518/*
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011519 * Read the next input token.
11520 * If the token is a word, we set backquotelist to the list of cmds in
11521 * backquotes. We set quoteflag to true if any part of the word was
11522 * quoted.
11523 * If the token is TREDIR, then we set redirnode to a structure containing
11524 * the redirection.
11525 * In all cases, the variable startlinno is set to the number of the line
11526 * on which the token starts.
11527 *
11528 * [Change comment: here documents and internal procedures]
11529 * [Readtoken shouldn't have any arguments. Perhaps we should make the
11530 * word parsing code into a separate routine. In this case, readtoken
11531 * doesn't need to have any internal procedures, but parseword does.
11532 * We could also make parseoperator in essence the main routine, and
11533 * have parseword (readtoken1?) handle both words and redirection.]
Eric Andersencb57d552001-06-28 07:25:16 +000011534 */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011535#define NEW_xxreadtoken
11536#ifdef NEW_xxreadtoken
11537/* singles must be first! */
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011538static const char xxreadtoken_chars[7] ALIGN1 = {
Denis Vlasenko834dee72008-10-07 09:18:30 +000011539 '\n', '(', ')', /* singles */
11540 '&', '|', ';', /* doubles */
11541 0
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011542};
Eric Andersencb57d552001-06-28 07:25:16 +000011543
Denis Vlasenko834dee72008-10-07 09:18:30 +000011544#define xxreadtoken_singles 3
11545#define xxreadtoken_doubles 3
11546
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011547static const char xxreadtoken_tokens[] ALIGN1 = {
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011548 TNL, TLP, TRP, /* only single occurrence allowed */
11549 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
11550 TEOF, /* corresponds to trailing nul */
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011551 TAND, TOR, TENDCASE /* if double occurrence */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011552};
11553
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011554static int
11555xxreadtoken(void)
11556{
11557 int c;
11558
11559 if (tokpushback) {
11560 tokpushback = 0;
11561 return lasttoken;
Eric Andersencb57d552001-06-28 07:25:16 +000011562 }
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011563 if (needprompt) {
11564 setprompt(2);
11565 }
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011566 startlinno = g_parsefile->linno;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011567 for (;;) { /* until token or start of word found */
Denis Vlasenko834dee72008-10-07 09:18:30 +000011568 c = pgetc_fast();
Denis Vlasenko5e34ff22009-04-21 11:09:40 +000011569 if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011570 continue;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011571
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011572 if (c == '#') {
11573 while ((c = pgetc()) != '\n' && c != PEOF)
11574 continue;
11575 pungetc();
11576 } else if (c == '\\') {
11577 if (pgetc() != '\n') {
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011578 pungetc();
Denis Vlasenko834dee72008-10-07 09:18:30 +000011579 break; /* return readtoken1(...) */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011580 }
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011581 startlinno = ++g_parsefile->linno;
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011582 if (doprompt)
11583 setprompt(2);
11584 } else {
11585 const char *p;
11586
11587 p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
11588 if (c != PEOF) {
11589 if (c == '\n') {
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011590 g_parsefile->linno++;
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011591 needprompt = doprompt;
11592 }
11593
11594 p = strchr(xxreadtoken_chars, c);
Denis Vlasenko834dee72008-10-07 09:18:30 +000011595 if (p == NULL)
11596 break; /* return readtoken1(...) */
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011597
Denis Vlasenko834dee72008-10-07 09:18:30 +000011598 if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
11599 int cc = pgetc();
11600 if (cc == c) { /* double occurrence? */
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011601 p += xxreadtoken_doubles + 1;
11602 } else {
11603 pungetc();
Denis Vlasenko834dee72008-10-07 09:18:30 +000011604#if ENABLE_ASH_BASH_COMPAT
11605 if (c == '&' && cc == '>') /* &> */
11606 break; /* return readtoken1(...) */
11607#endif
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011608 }
11609 }
11610 }
11611 lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
11612 return lasttoken;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011613 }
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011614 } /* for (;;) */
Denis Vlasenko834dee72008-10-07 09:18:30 +000011615
11616 return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011617}
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011618#else /* old xxreadtoken */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011619#define RETURN(token) return lasttoken = token
11620static int
11621xxreadtoken(void)
11622{
11623 int c;
11624
11625 if (tokpushback) {
11626 tokpushback = 0;
11627 return lasttoken;
11628 }
11629 if (needprompt) {
11630 setprompt(2);
11631 }
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011632 startlinno = g_parsefile->linno;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011633 for (;;) { /* until token or start of word found */
Denis Vlasenko834dee72008-10-07 09:18:30 +000011634 c = pgetc_fast();
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011635 switch (c) {
11636 case ' ': case '\t':
11637#if ENABLE_ASH_ALIAS
11638 case PEOA:
11639#endif
11640 continue;
11641 case '#':
Denis Vlasenkof7d56652008-03-25 05:51:41 +000011642 while ((c = pgetc()) != '\n' && c != PEOF)
11643 continue;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011644 pungetc();
11645 continue;
11646 case '\\':
11647 if (pgetc() == '\n') {
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011648 startlinno = ++g_parsefile->linno;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011649 if (doprompt)
11650 setprompt(2);
11651 continue;
11652 }
11653 pungetc();
11654 goto breakloop;
11655 case '\n':
Denis Vlasenko41eb3002008-11-28 03:42:31 +000011656 g_parsefile->linno++;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011657 needprompt = doprompt;
11658 RETURN(TNL);
11659 case PEOF:
11660 RETURN(TEOF);
11661 case '&':
11662 if (pgetc() == '&')
11663 RETURN(TAND);
11664 pungetc();
11665 RETURN(TBACKGND);
11666 case '|':
11667 if (pgetc() == '|')
11668 RETURN(TOR);
11669 pungetc();
11670 RETURN(TPIPE);
11671 case ';':
11672 if (pgetc() == ';')
11673 RETURN(TENDCASE);
11674 pungetc();
11675 RETURN(TSEMI);
11676 case '(':
11677 RETURN(TLP);
11678 case ')':
11679 RETURN(TRP);
11680 default:
11681 goto breakloop;
11682 }
11683 }
11684 breakloop:
11685 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
11686#undef RETURN
11687}
Denis Vlasenko176d49d2008-10-06 09:51:47 +000011688#endif /* old xxreadtoken */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011689
11690static int
11691readtoken(void)
11692{
11693 int t;
11694#if DEBUG
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011695 smallint alreadyseen = tokpushback;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011696#endif
11697
11698#if ENABLE_ASH_ALIAS
11699 top:
11700#endif
11701
11702 t = xxreadtoken();
11703
11704 /*
11705 * eat newlines
11706 */
11707 if (checkkwd & CHKNL) {
11708 while (t == TNL) {
11709 parseheredoc();
11710 t = xxreadtoken();
11711 }
11712 }
11713
11714 if (t != TWORD || quoteflag) {
11715 goto out;
11716 }
11717
11718 /*
11719 * check for keywords
11720 */
11721 if (checkkwd & CHKKWD) {
11722 const char *const *pp;
11723
11724 pp = findkwd(wordtext);
11725 if (pp) {
11726 lasttoken = t = pp - tokname_array;
11727 TRACE(("keyword %s recognized\n", tokname(t)));
11728 goto out;
11729 }
11730 }
11731
11732 if (checkkwd & CHKALIAS) {
11733#if ENABLE_ASH_ALIAS
11734 struct alias *ap;
11735 ap = lookupalias(wordtext, 1);
11736 if (ap != NULL) {
11737 if (*ap->val) {
11738 pushstring(ap->val, ap);
11739 }
11740 goto top;
11741 }
11742#endif
11743 }
11744 out:
11745 checkkwd = 0;
11746#if DEBUG
11747 if (!alreadyseen)
11748 TRACE(("token %s %s\n", tokname(t), t == TWORD ? wordtext : ""));
11749 else
11750 TRACE(("reread token %s %s\n", tokname(t), t == TWORD ? wordtext : ""));
11751#endif
11752 return t;
Eric Andersencb57d552001-06-28 07:25:16 +000011753}
11754
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011755static char
11756peektoken(void)
11757{
11758 int t;
11759
11760 t = readtoken();
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011761 tokpushback = 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011762 return tokname_array[t][0];
11763}
Eric Andersencb57d552001-06-28 07:25:16 +000011764
11765/*
Denys Vlasenko86e83ec2009-07-23 22:07:07 +020011766 * Read and parse a command. Returns NODE_EOF on end of file.
11767 * (NULL is a valid parse tree indicating a blank line.)
Eric Andersencb57d552001-06-28 07:25:16 +000011768 */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011769static union node *
11770parsecmd(int interact)
Eric Andersen90898442003-08-06 11:20:52 +000011771{
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011772 int t;
Eric Andersencb57d552001-06-28 07:25:16 +000011773
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011774 tokpushback = 0;
11775 doprompt = interact;
11776 if (doprompt)
11777 setprompt(doprompt);
11778 needprompt = 0;
11779 t = readtoken();
11780 if (t == TEOF)
Denys Vlasenko86e83ec2009-07-23 22:07:07 +020011781 return NODE_EOF;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011782 if (t == TNL)
11783 return NULL;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011784 tokpushback = 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011785 return list(1);
11786}
11787
11788/*
11789 * Input any here documents.
11790 */
11791static void
11792parseheredoc(void)
11793{
11794 struct heredoc *here;
11795 union node *n;
11796
11797 here = heredoclist;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000011798 heredoclist = NULL;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011799
11800 while (here) {
11801 if (needprompt) {
11802 setprompt(2);
11803 }
11804 readtoken1(pgetc(), here->here->type == NHERE? SQSYNTAX : DQSYNTAX,
11805 here->eofmark, here->striptabs);
Denis Vlasenko597906c2008-02-20 16:38:54 +000011806 n = stzalloc(sizeof(struct narg));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011807 n->narg.type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000011808 /*n->narg.next = NULL; - stzalloc did it */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011809 n->narg.text = wordtext;
11810 n->narg.backquote = backquotelist;
11811 here->here->nhere.doc = n;
11812 here = here->next;
Eric Andersencb57d552001-06-28 07:25:16 +000011813 }
Eric Andersencb57d552001-06-28 07:25:16 +000011814}
11815
11816
11817/*
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +000011818 * called by editline -- any expansions to the prompt should be added here.
Eric Andersencb57d552001-06-28 07:25:16 +000011819 */
Denis Vlasenko131ae172007-02-18 13:00:19 +000011820#if ENABLE_ASH_EXPAND_PRMT
"Vladimir N. Oleynik"bef14d72005-09-05 13:25:11 +000011821static const char *
11822expandstr(const char *ps)
11823{
11824 union node n;
11825
Denis Vlasenko5c2b8142009-03-19 01:59:59 +000011826 /* XXX Fix (char *) cast. It _is_ a bug. ps is variable's value,
11827 * and token processing _can_ alter it (delete NULs etc). */
"Vladimir N. Oleynik"bef14d72005-09-05 13:25:11 +000011828 setinputstring((char *)ps);
Denis Vlasenko46a53062007-09-24 18:30:02 +000011829 readtoken1(pgetc(), PSSYNTAX, nullstr, 0);
"Vladimir N. Oleynik"bef14d72005-09-05 13:25:11 +000011830 popfile();
11831
11832 n.narg.type = NARG;
11833 n.narg.next = NULL;
11834 n.narg.text = wordtext;
11835 n.narg.backquote = backquotelist;
11836
11837 expandarg(&n, NULL, 0);
11838 return stackblock();
11839}
11840#endif
11841
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011842/*
11843 * Execute a command or commands contained in a string.
11844 */
11845static int
11846evalstring(char *s, int mask)
Eric Andersenc470f442003-07-28 09:56:35 +000011847{
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011848 union node *n;
11849 struct stackmark smark;
11850 int skip;
11851
11852 setinputstring(s);
11853 setstackmark(&smark);
11854
11855 skip = 0;
Denys Vlasenko86e83ec2009-07-23 22:07:07 +020011856 while ((n = parsecmd(0)) != NODE_EOF) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011857 evaltree(n, 0);
11858 popstackmark(&smark);
11859 skip = evalskip;
11860 if (skip)
11861 break;
11862 }
11863 popfile();
11864
11865 skip &= mask;
11866 evalskip = skip;
11867 return skip;
Eric Andersenc470f442003-07-28 09:56:35 +000011868}
11869
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011870/*
11871 * The eval command.
11872 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020011873static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000011874evalcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011875{
11876 char *p;
11877 char *concat;
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011878
Denis Vlasenko68404f12008-03-17 09:00:54 +000011879 if (argv[1]) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011880 p = argv[1];
Denis Vlasenko68404f12008-03-17 09:00:54 +000011881 argv += 2;
11882 if (argv[0]) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011883 STARTSTACKSTR(concat);
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011884 for (;;) {
11885 concat = stack_putstr(p, concat);
Denis Vlasenko68404f12008-03-17 09:00:54 +000011886 p = *argv++;
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011887 if (p == NULL)
11888 break;
11889 STPUTC(' ', concat);
11890 }
11891 STPUTC('\0', concat);
11892 p = grabstackstr(concat);
11893 }
11894 evalstring(p, ~SKIPEVAL);
11895
11896 }
11897 return exitstatus;
11898}
11899
11900/*
11901 * Read and execute commands. "Top" is nonzero for the top level command
11902 * loop; it turns on prompting if the shell is interactive.
11903 */
11904static int
11905cmdloop(int top)
11906{
11907 union node *n;
11908 struct stackmark smark;
11909 int inter;
11910 int numeof = 0;
11911
11912 TRACE(("cmdloop(%d) called\n", top));
11913 for (;;) {
11914 int skip;
11915
11916 setstackmark(&smark);
11917#if JOBS
Denis Vlasenkob07a4962008-06-22 13:16:23 +000011918 if (doing_jobctl)
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011919 showjobs(stderr, SHOW_CHANGED);
11920#endif
11921 inter = 0;
11922 if (iflag && top) {
11923 inter++;
11924#if ENABLE_ASH_MAIL
11925 chkmail();
11926#endif
11927 }
11928 n = parsecmd(inter);
Denys Vlasenko7cee00e2009-07-24 01:08:03 +020011929#if DEBUG
11930 if (DEBUG > 2 && debug && (n != NODE_EOF))
Denys Vlasenko883cea42009-07-11 15:31:59 +020011931 showtree(n);
Denis Vlasenko135cecb2009-04-12 00:00:57 +000011932#endif
Denys Vlasenko86e83ec2009-07-23 22:07:07 +020011933 if (n == NODE_EOF) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011934 if (!top || numeof >= 50)
11935 break;
11936 if (!stoppedjobs()) {
11937 if (!Iflag)
11938 break;
11939 out2str("\nUse \"exit\" to leave shell.\n");
11940 }
11941 numeof++;
11942 } else if (nflag == 0) {
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +000011943 /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
11944 job_warning >>= 1;
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011945 numeof = 0;
11946 evaltree(n, 0);
11947 }
11948 popstackmark(&smark);
11949 skip = evalskip;
11950
11951 if (skip) {
11952 evalskip = 0;
11953 return skip & SKIPEVAL;
11954 }
11955 }
11956 return 0;
11957}
11958
Denis Vlasenko0dec6de2007-02-23 21:10:47 +000011959/*
11960 * Take commands from a file. To be compatible we should do a path
11961 * search for the file, which is necessary to find sub-commands.
11962 */
11963static char *
11964find_dot_file(char *name)
11965{
11966 char *fullname;
11967 const char *path = pathval();
11968 struct stat statb;
11969
11970 /* don't try this for absolute or relative paths */
11971 if (strchr(name, '/'))
11972 return name;
11973
Denis Vlasenko8ad78e12009-02-15 12:40:30 +000011974 /* IIRC standards do not say whether . is to be searched.
11975 * And it is even smaller this way, making it unconditional for now:
11976 */
11977 if (1) { /* ENABLE_ASH_BASH_COMPAT */
11978 fullname = name;
11979 goto try_cur_dir;
11980 }
11981
Denys Vlasenko82a6fb32009-06-14 19:42:12 +020011982 while ((fullname = path_advance(&path, name)) != NULL) {
Denis Vlasenko8ad78e12009-02-15 12:40:30 +000011983 try_cur_dir:
Denis Vlasenko0dec6de2007-02-23 21:10:47 +000011984 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
11985 /*
11986 * Don't bother freeing here, since it will
11987 * be freed by the caller.
11988 */
11989 return fullname;
11990 }
Denys Vlasenko82a6fb32009-06-14 19:42:12 +020011991 if (fullname != name)
11992 stunalloc(fullname);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +000011993 }
11994
11995 /* not found in the PATH */
11996 ash_msg_and_raise_error("%s: not found", name);
11997 /* NOTREACHED */
11998}
11999
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012000static int FAST_FUNC
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012001dotcmd(int argc, char **argv)
12002{
12003 struct strlist *sp;
12004 volatile struct shparam saveparam;
12005 int status = 0;
12006
12007 for (sp = cmdenviron; sp; sp = sp->next)
Denis Vlasenko4222ae42007-02-25 02:37:49 +000012008 setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012009
Denis Vlasenko68404f12008-03-17 09:00:54 +000012010 if (argv[1]) { /* That's what SVR2 does */
12011 char *fullname = find_dot_file(argv[1]);
12012 argv += 2;
12013 argc -= 2;
12014 if (argc) { /* argc > 0, argv[0] != NULL */
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012015 saveparam = shellparam;
Denis Vlasenko01631112007-12-16 17:20:38 +000012016 shellparam.malloced = 0;
Denis Vlasenko68404f12008-03-17 09:00:54 +000012017 shellparam.nparam = argc;
12018 shellparam.p = argv;
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012019 };
12020
12021 setinputfile(fullname, INPUT_PUSH_FILE);
12022 commandname = fullname;
12023 cmdloop(0);
12024 popfile();
12025
Denis Vlasenko68404f12008-03-17 09:00:54 +000012026 if (argc) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012027 freeparam(&shellparam);
12028 shellparam = saveparam;
12029 };
12030 status = exitstatus;
12031 }
12032 return status;
12033}
12034
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012035static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012036exitcmd(int argc UNUSED_PARAM, char **argv)
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012037{
12038 if (stoppedjobs())
12039 return 0;
Denis Vlasenko68404f12008-03-17 09:00:54 +000012040 if (argv[1])
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012041 exitstatus = number(argv[1]);
12042 raise_exception(EXEXIT);
12043 /* NOTREACHED */
12044}
12045
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012046/*
12047 * Read a file containing shell functions.
12048 */
12049static void
12050readcmdfile(char *name)
12051{
12052 setinputfile(name, INPUT_PUSH_FILE);
12053 cmdloop(0);
12054 popfile();
12055}
12056
12057
Denis Vlasenkocc571512007-02-23 21:10:35 +000012058/* ============ find_command inplementation */
12059
12060/*
12061 * Resolve a command name. If you change this routine, you may have to
12062 * change the shellexec routine as well.
12063 */
12064static void
12065find_command(char *name, struct cmdentry *entry, int act, const char *path)
12066{
12067 struct tblentry *cmdp;
12068 int idx;
12069 int prev;
12070 char *fullname;
12071 struct stat statb;
12072 int e;
12073 int updatetbl;
12074 struct builtincmd *bcmd;
12075
12076 /* If name contains a slash, don't use PATH or hash table */
12077 if (strchr(name, '/') != NULL) {
12078 entry->u.index = -1;
12079 if (act & DO_ABS) {
12080 while (stat(name, &statb) < 0) {
12081#ifdef SYSV
12082 if (errno == EINTR)
12083 continue;
12084#endif
12085 entry->cmdtype = CMDUNKNOWN;
12086 return;
12087 }
12088 }
12089 entry->cmdtype = CMDNORMAL;
12090 return;
12091 }
12092
Denis Vlasenkof20de5b2007-04-29 23:42:54 +000012093/* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
Denis Vlasenkocc571512007-02-23 21:10:35 +000012094
12095 updatetbl = (path == pathval());
12096 if (!updatetbl) {
12097 act |= DO_ALTPATH;
12098 if (strstr(path, "%builtin") != NULL)
12099 act |= DO_ALTBLTIN;
12100 }
12101
12102 /* If name is in the table, check answer will be ok */
12103 cmdp = cmdlookup(name, 0);
12104 if (cmdp != NULL) {
12105 int bit;
12106
12107 switch (cmdp->cmdtype) {
12108 default:
12109#if DEBUG
12110 abort();
12111#endif
12112 case CMDNORMAL:
12113 bit = DO_ALTPATH;
12114 break;
12115 case CMDFUNCTION:
12116 bit = DO_NOFUNC;
12117 break;
12118 case CMDBUILTIN:
12119 bit = DO_ALTBLTIN;
12120 break;
12121 }
12122 if (act & bit) {
12123 updatetbl = 0;
12124 cmdp = NULL;
12125 } else if (cmdp->rehash == 0)
12126 /* if not invalidated by cd, we're done */
12127 goto success;
12128 }
12129
12130 /* If %builtin not in path, check for builtin next */
12131 bcmd = find_builtin(name);
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +000012132 if (bcmd) {
12133 if (IS_BUILTIN_REGULAR(bcmd))
12134 goto builtin_success;
12135 if (act & DO_ALTPATH) {
12136 if (!(act & DO_ALTBLTIN))
12137 goto builtin_success;
12138 } else if (builtinloc <= 0) {
12139 goto builtin_success;
Denis Vlasenko8e858e22007-03-07 09:35:43 +000012140 }
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +000012141 }
Denis Vlasenkocc571512007-02-23 21:10:35 +000012142
Denis Vlasenkof20de5b2007-04-29 23:42:54 +000012143#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko7465dbc2008-04-13 02:25:53 +000012144 {
12145 int applet_no = find_applet_by_name(name);
12146 if (applet_no >= 0) {
12147 entry->cmdtype = CMDNORMAL;
12148 entry->u.index = -2 - applet_no;
12149 return;
12150 }
Denis Vlasenkof20de5b2007-04-29 23:42:54 +000012151 }
12152#endif
12153
Denis Vlasenkocc571512007-02-23 21:10:35 +000012154 /* We have to search path. */
12155 prev = -1; /* where to start */
12156 if (cmdp && cmdp->rehash) { /* doing a rehash */
12157 if (cmdp->cmdtype == CMDBUILTIN)
12158 prev = builtinloc;
12159 else
12160 prev = cmdp->param.index;
12161 }
12162
12163 e = ENOENT;
12164 idx = -1;
12165 loop:
Denys Vlasenko82a6fb32009-06-14 19:42:12 +020012166 while ((fullname = path_advance(&path, name)) != NULL) {
Denis Vlasenkocc571512007-02-23 21:10:35 +000012167 stunalloc(fullname);
Denis Vlasenkodee82b62007-07-29 14:05:27 +000012168 /* NB: code below will still use fullname
12169 * despite it being "unallocated" */
Denis Vlasenkocc571512007-02-23 21:10:35 +000012170 idx++;
12171 if (pathopt) {
12172 if (prefix(pathopt, "builtin")) {
12173 if (bcmd)
12174 goto builtin_success;
12175 continue;
Denis Vlasenko4a9ca132008-04-12 20:07:08 +000012176 }
12177 if ((act & DO_NOFUNC)
12178 || !prefix(pathopt, "func")
12179 ) { /* ignore unimplemented options */
Denis Vlasenkocc571512007-02-23 21:10:35 +000012180 continue;
12181 }
12182 }
12183 /* if rehash, don't redo absolute path names */
12184 if (fullname[0] == '/' && idx <= prev) {
12185 if (idx < prev)
12186 continue;
12187 TRACE(("searchexec \"%s\": no change\n", name));
12188 goto success;
12189 }
12190 while (stat(fullname, &statb) < 0) {
12191#ifdef SYSV
12192 if (errno == EINTR)
12193 continue;
12194#endif
12195 if (errno != ENOENT && errno != ENOTDIR)
12196 e = errno;
12197 goto loop;
12198 }
12199 e = EACCES; /* if we fail, this will be the error */
12200 if (!S_ISREG(statb.st_mode))
12201 continue;
12202 if (pathopt) { /* this is a %func directory */
12203 stalloc(strlen(fullname) + 1);
Denis Vlasenkodee82b62007-07-29 14:05:27 +000012204 /* NB: stalloc will return space pointed by fullname
12205 * (because we don't have any intervening allocations
12206 * between stunalloc above and this stalloc) */
Denis Vlasenkocc571512007-02-23 21:10:35 +000012207 readcmdfile(fullname);
12208 cmdp = cmdlookup(name, 0);
12209 if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
12210 ash_msg_and_raise_error("%s not defined in %s", name, fullname);
12211 stunalloc(fullname);
12212 goto success;
12213 }
12214 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
12215 if (!updatetbl) {
12216 entry->cmdtype = CMDNORMAL;
12217 entry->u.index = idx;
12218 return;
12219 }
12220 INT_OFF;
12221 cmdp = cmdlookup(name, 1);
12222 cmdp->cmdtype = CMDNORMAL;
12223 cmdp->param.index = idx;
12224 INT_ON;
12225 goto success;
12226 }
12227
12228 /* We failed. If there was an entry for this command, delete it */
12229 if (cmdp && updatetbl)
12230 delete_cmd_entry();
12231 if (act & DO_ERR)
12232 ash_msg("%s: %s", name, errmsg(e, "not found"));
12233 entry->cmdtype = CMDUNKNOWN;
12234 return;
12235
12236 builtin_success:
12237 if (!updatetbl) {
12238 entry->cmdtype = CMDBUILTIN;
12239 entry->u.cmd = bcmd;
12240 return;
12241 }
12242 INT_OFF;
12243 cmdp = cmdlookup(name, 1);
12244 cmdp->cmdtype = CMDBUILTIN;
12245 cmdp->param.cmd = bcmd;
12246 INT_ON;
12247 success:
12248 cmdp->rehash = 0;
12249 entry->cmdtype = cmdp->cmdtype;
12250 entry->u = cmdp->param;
12251}
12252
12253
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012254/* ============ trap.c */
Eric Andersenc470f442003-07-28 09:56:35 +000012255
Eric Andersencb57d552001-06-28 07:25:16 +000012256/*
Eric Andersencb57d552001-06-28 07:25:16 +000012257 * The trap builtin.
12258 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012259static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012260trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersencb57d552001-06-28 07:25:16 +000012261{
12262 char *action;
12263 char **ap;
12264 int signo;
12265
Eric Andersenc470f442003-07-28 09:56:35 +000012266 nextopt(nullstr);
12267 ap = argptr;
12268 if (!*ap) {
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012269 for (signo = 0; signo < NSIG; signo++) {
Denys Vlasenko21d87d42009-09-25 00:06:51 +020012270 char *tr = trap_ptr[signo];
12271 if (tr) {
Denys Vlasenkoe74aaf92009-09-27 02:05:45 +020012272 /* note: bash adds "SIG", but only if invoked
12273 * as "bash". If called as "sh", or if set -o posix,
12274 * then it prints short signal names.
12275 * We are printing short names: */
12276 out1fmt("trap -- %s %s\n",
Denys Vlasenko21d87d42009-09-25 00:06:51 +020012277 single_quote(tr),
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +000012278 get_signame(signo));
Denys Vlasenko726e1a02009-09-25 02:58:20 +020012279 /* trap_ptr != trap only if we are in special-cased `trap` code.
12280 * In this case, we will exit very soon, no need to free(). */
Denys Vlasenkoe74aaf92009-09-27 02:05:45 +020012281 /* if (trap_ptr != trap && tp[0]) */
Denys Vlasenko726e1a02009-09-25 02:58:20 +020012282 /* free(tr); */
Eric Andersencb57d552001-06-28 07:25:16 +000012283 }
12284 }
Denys Vlasenko726e1a02009-09-25 02:58:20 +020012285 /*
Denys Vlasenko21d87d42009-09-25 00:06:51 +020012286 if (trap_ptr != trap) {
12287 free(trap_ptr);
12288 trap_ptr = trap;
12289 }
Denys Vlasenko726e1a02009-09-25 02:58:20 +020012290 */
Eric Andersencb57d552001-06-28 07:25:16 +000012291 return 0;
12292 }
Denys Vlasenko21d87d42009-09-25 00:06:51 +020012293
Denis Vlasenko4e19a9c2008-07-26 13:45:57 +000012294 action = NULL;
12295 if (ap[1])
Eric Andersencb57d552001-06-28 07:25:16 +000012296 action = *ap++;
12297 while (*ap) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +000012298 signo = get_signum(*ap);
12299 if (signo < 0)
Denis Vlasenkob012b102007-02-19 22:43:01 +000012300 ash_msg_and_raise_error("%s: bad trap", *ap);
12301 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +000012302 if (action) {
Denis Vlasenko9f739442006-12-16 23:49:13 +000012303 if (LONE_DASH(action))
Eric Andersencb57d552001-06-28 07:25:16 +000012304 action = NULL;
12305 else
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012306 action = ckstrdup(action);
Eric Andersencb57d552001-06-28 07:25:16 +000012307 }
Denis Vlasenko60818682007-09-28 22:07:23 +000012308 free(trap[signo]);
Eric Andersencb57d552001-06-28 07:25:16 +000012309 trap[signo] = action;
12310 if (signo != 0)
12311 setsignal(signo);
Denis Vlasenkob012b102007-02-19 22:43:01 +000012312 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +000012313 ap++;
12314 }
12315 return 0;
12316}
12317
Eric Andersenc470f442003-07-28 09:56:35 +000012318
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012319/* ============ Builtins */
Eric Andersenc470f442003-07-28 09:56:35 +000012320
Denis Vlasenko8e1c7152007-01-22 07:21:38 +000012321#if !ENABLE_FEATURE_SH_EXTRA_QUIET
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012322/*
12323 * Lists available builtins
12324 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012325static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012326helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersenc470f442003-07-28 09:56:35 +000012327{
Denis Vlasenko6b06cb82008-05-15 21:30:45 +000012328 unsigned col;
12329 unsigned i;
Eric Andersenc470f442003-07-28 09:56:35 +000012330
Denys Vlasenkod6b05eb2009-06-06 20:59:55 +020012331 out1fmt(
Denis Vlasenko34d4d892009-04-04 20:24:37 +000012332 "Built-in commands:\n"
12333 "------------------\n");
Denis Vlasenkob71c6682007-07-21 15:08:09 +000012334 for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
Eric Andersenc470f442003-07-28 09:56:35 +000012335 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
Denis Vlasenko52764022007-02-24 13:42:56 +000012336 builtintab[i].name + 1);
Eric Andersenc470f442003-07-28 09:56:35 +000012337 if (col > 60) {
12338 out1fmt("\n");
12339 col = 0;
12340 }
12341 }
Denis Vlasenko80d14be2007-04-10 23:03:30 +000012342#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko1aa7e472007-11-28 06:49:03 +000012343 {
12344 const char *a = applet_names;
12345 while (*a) {
12346 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
12347 if (col > 60) {
12348 out1fmt("\n");
12349 col = 0;
12350 }
12351 a += strlen(a) + 1;
Eric Andersenc470f442003-07-28 09:56:35 +000012352 }
12353 }
12354#endif
12355 out1fmt("\n\n");
12356 return EXIT_SUCCESS;
12357}
Denis Vlasenko131ae172007-02-18 13:00:19 +000012358#endif /* FEATURE_SH_EXTRA_QUIET */
Eric Andersenc470f442003-07-28 09:56:35 +000012359
Eric Andersencb57d552001-06-28 07:25:16 +000012360/*
Eric Andersencb57d552001-06-28 07:25:16 +000012361 * The export and readonly commands.
12362 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012363static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012364exportcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +000012365{
12366 struct var *vp;
12367 char *name;
12368 const char *p;
Eric Andersenc470f442003-07-28 09:56:35 +000012369 char **aptr;
Denis Vlasenkob7304742008-10-20 08:15:51 +000012370 int flag = argv[0][0] == 'r' ? VREADONLY : VEXPORT;
Eric Andersencb57d552001-06-28 07:25:16 +000012371
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012372 if (nextopt("p") != 'p') {
12373 aptr = argptr;
12374 name = *aptr;
12375 if (name) {
12376 do {
12377 p = strchr(name, '=');
12378 if (p != NULL) {
12379 p++;
12380 } else {
12381 vp = *findvar(hashvar(name), name);
12382 if (vp) {
12383 vp->flags |= flag;
12384 continue;
12385 }
Eric Andersencb57d552001-06-28 07:25:16 +000012386 }
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012387 setvar(name, p, flag);
12388 } while ((name = *++aptr) != NULL);
12389 return 0;
12390 }
Eric Andersencb57d552001-06-28 07:25:16 +000012391 }
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012392 showvars(argv[0], flag, 0);
Eric Andersencb57d552001-06-28 07:25:16 +000012393 return 0;
12394}
12395
Eric Andersencb57d552001-06-28 07:25:16 +000012396/*
Denis Vlasenko5651bfc2007-02-23 21:08:58 +000012397 * Delete a function if it exists.
Eric Andersencb57d552001-06-28 07:25:16 +000012398 */
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012399static void
Denis Vlasenko5651bfc2007-02-23 21:08:58 +000012400unsetfunc(const char *name)
Aaron Lehmannb6ecbdc2001-12-06 03:37:38 +000012401{
Denis Vlasenko5651bfc2007-02-23 21:08:58 +000012402 struct tblentry *cmdp;
Eric Andersencb57d552001-06-28 07:25:16 +000012403
Denis Vlasenko5651bfc2007-02-23 21:08:58 +000012404 cmdp = cmdlookup(name, 0);
12405 if (cmdp!= NULL && cmdp->cmdtype == CMDFUNCTION)
12406 delete_cmd_entry();
Eric Andersenc470f442003-07-28 09:56:35 +000012407}
12408
Eric Andersencb57d552001-06-28 07:25:16 +000012409/*
Eric Andersencb57d552001-06-28 07:25:16 +000012410 * The unset builtin command. We unset the function before we unset the
12411 * variable to allow a function to be unset when there is a readonly variable
12412 * with the same name.
12413 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012414static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012415unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersencb57d552001-06-28 07:25:16 +000012416{
12417 char **ap;
12418 int i;
Eric Andersenc470f442003-07-28 09:56:35 +000012419 int flag = 0;
Eric Andersencb57d552001-06-28 07:25:16 +000012420 int ret = 0;
12421
12422 while ((i = nextopt("vf")) != '\0') {
Eric Andersenc470f442003-07-28 09:56:35 +000012423 flag = i;
Eric Andersencb57d552001-06-28 07:25:16 +000012424 }
Eric Andersencb57d552001-06-28 07:25:16 +000012425
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012426 for (ap = argptr; *ap; ap++) {
Eric Andersenc470f442003-07-28 09:56:35 +000012427 if (flag != 'f') {
12428 i = unsetvar(*ap);
12429 ret |= i;
12430 if (!(i & 2))
12431 continue;
12432 }
12433 if (flag != 'v')
Eric Andersencb57d552001-06-28 07:25:16 +000012434 unsetfunc(*ap);
Eric Andersencb57d552001-06-28 07:25:16 +000012435 }
Eric Andersenc470f442003-07-28 09:56:35 +000012436 return ret & 1;
Eric Andersencb57d552001-06-28 07:25:16 +000012437}
12438
12439
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +000012440/* setmode.c */
Eric Andersencb57d552001-06-28 07:25:16 +000012441
Eric Andersenc470f442003-07-28 09:56:35 +000012442#include <sys/times.h>
12443
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000012444static const unsigned char timescmd_str[] ALIGN1 = {
Manuel Novoa III 4456f252003-08-13 17:48:47 +000012445 ' ', offsetof(struct tms, tms_utime),
12446 '\n', offsetof(struct tms, tms_stime),
12447 ' ', offsetof(struct tms, tms_cutime),
12448 '\n', offsetof(struct tms, tms_cstime),
12449 0
12450};
Eric Andersencb57d552001-06-28 07:25:16 +000012451
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012452static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012453timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Manuel Novoa III 4456f252003-08-13 17:48:47 +000012454{
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012455 long clk_tck, s, t;
Manuel Novoa III 4456f252003-08-13 17:48:47 +000012456 const unsigned char *p;
12457 struct tms buf;
12458
12459 clk_tck = sysconf(_SC_CLK_TCK);
Eric Andersencb57d552001-06-28 07:25:16 +000012460 times(&buf);
Manuel Novoa III 4456f252003-08-13 17:48:47 +000012461
12462 p = timescmd_str;
12463 do {
12464 t = *(clock_t *)(((char *) &buf) + p[1]);
12465 s = t / clk_tck;
12466 out1fmt("%ldm%ld.%.3lds%c",
12467 s/60, s%60,
12468 ((t - s * clk_tck) * 1000) / clk_tck,
12469 p[0]);
12470 } while (*(p += 2));
12471
Eric Andersencb57d552001-06-28 07:25:16 +000012472 return 0;
12473}
12474
Mike Frysinger98c52642009-04-02 10:02:37 +000012475#if ENABLE_SH_MATH_SUPPORT
Eric Andersenc470f442003-07-28 09:56:35 +000012476/*
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +000012477 * The let builtin. partial stolen from GNU Bash, the Bourne Again SHell.
12478 * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
Eric Andersen90898442003-08-06 11:20:52 +000012479 *
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +000012480 * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
Eric Andersenc470f442003-07-28 09:56:35 +000012481 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012482static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012483letcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersenc470f442003-07-28 09:56:35 +000012484{
Denis Vlasenko68404f12008-03-17 09:00:54 +000012485 arith_t i;
Eric Andersenc470f442003-07-28 09:56:35 +000012486
Denis Vlasenko68404f12008-03-17 09:00:54 +000012487 argv++;
12488 if (!*argv)
Denis Vlasenkob012b102007-02-19 22:43:01 +000012489 ash_msg_and_raise_error("expression expected");
Denis Vlasenko68404f12008-03-17 09:00:54 +000012490 do {
Denis Vlasenkob29eb6e2009-04-02 13:46:27 +000012491 i = ash_arith(*argv);
Denis Vlasenko68404f12008-03-17 09:00:54 +000012492 } while (*++argv);
Eric Andersenc470f442003-07-28 09:56:35 +000012493
Denis Vlasenkod9e15f22006-11-27 16:49:55 +000012494 return !i;
Eric Andersenc470f442003-07-28 09:56:35 +000012495}
Mike Frysinger98c52642009-04-02 10:02:37 +000012496#endif /* SH_MATH_SUPPORT */
Eric Andersenc470f442003-07-28 09:56:35 +000012497
Eric Andersenc470f442003-07-28 09:56:35 +000012498
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012499/* ============ miscbltin.c
12500 *
Eric Andersenaff114c2004-04-14 17:51:38 +000012501 * Miscellaneous builtins.
Eric Andersenc470f442003-07-28 09:56:35 +000012502 */
12503
12504#undef rflag
12505
Denis Vlasenko83e5d6f2006-12-18 21:49:06 +000012506#if defined(__GLIBC__) && __GLIBC__ == 2 && __GLIBC_MINOR__ < 1
Eric Andersenc470f442003-07-28 09:56:35 +000012507typedef enum __rlimit_resource rlim_t;
12508#endif
Eric Andersen74bcd162001-07-30 21:41:37 +000012509
Eric Andersenc470f442003-07-28 09:56:35 +000012510/*
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012511 * The read builtin. Options:
12512 * -r Do not interpret '\' specially
12513 * -s Turn off echo (tty only)
12514 * -n NCHARS Read NCHARS max
12515 * -p PROMPT Display PROMPT on stderr (if input is from tty)
12516 * -t SECONDS Timeout after SECONDS (tty or pipe only)
12517 * -u FD Read from given FD instead of fd 0
Eric Andersenc470f442003-07-28 09:56:35 +000012518 * This uses unbuffered input, which may be avoidable in some cases.
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012519 * TODO: bash also has:
12520 * -a ARRAY Read into array[0],[1],etc
12521 * -d DELIM End on DELIM char, not newline
12522 * -e Use line editing (tty only)
Eric Andersenc470f442003-07-28 09:56:35 +000012523 */
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012524static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012525readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersenc470f442003-07-28 09:56:35 +000012526{
Denis Vlasenko9cd4c762008-06-18 19:22:19 +000012527 static const char *const arg_REPLY[] = { "REPLY", NULL };
12528
Eric Andersenc470f442003-07-28 09:56:35 +000012529 char **ap;
12530 int backslash;
12531 char c;
12532 int rflag;
12533 char *prompt;
12534 const char *ifs;
12535 char *p;
12536 int startword;
12537 int status;
12538 int i;
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012539 int fd = 0;
Denis Vlasenko131ae172007-02-18 13:00:19 +000012540#if ENABLE_ASH_READ_NCHARS
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012541 int nchars = 0; /* if != 0, -n is in effect */
Paul Fox02eb9342005-09-07 16:56:02 +000012542 int silent = 0;
12543 struct termios tty, old_tty;
12544#endif
Denis Vlasenko131ae172007-02-18 13:00:19 +000012545#if ENABLE_ASH_READ_TIMEOUT
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012546 unsigned end_ms = 0;
12547 unsigned timeout = 0;
Paul Fox02eb9342005-09-07 16:56:02 +000012548#endif
Eric Andersenc470f442003-07-28 09:56:35 +000012549
12550 rflag = 0;
12551 prompt = NULL;
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012552 while ((i = nextopt("p:u:r"
Denis Vlasenko5e34ff22009-04-21 11:09:40 +000012553 IF_ASH_READ_TIMEOUT("t:")
12554 IF_ASH_READ_NCHARS("n:s")
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012555 )) != '\0') {
Denis Vlasenkobf0a2012006-12-26 10:42:51 +000012556 switch (i) {
Paul Fox02eb9342005-09-07 16:56:02 +000012557 case 'p':
Eric Andersenc470f442003-07-28 09:56:35 +000012558 prompt = optionarg;
Paul Fox02eb9342005-09-07 16:56:02 +000012559 break;
Denis Vlasenko131ae172007-02-18 13:00:19 +000012560#if ENABLE_ASH_READ_NCHARS
Paul Fox02eb9342005-09-07 16:56:02 +000012561 case 'n':
Denis Vlasenko037576d2007-10-20 18:30:38 +000012562 nchars = bb_strtou(optionarg, NULL, 10);
12563 if (nchars < 0 || errno)
Denis Vlasenkob012b102007-02-19 22:43:01 +000012564 ash_msg_and_raise_error("invalid count");
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012565 /* nchars == 0: off (bash 3.2 does this too) */
Paul Fox02eb9342005-09-07 16:56:02 +000012566 break;
12567 case 's':
12568 silent = 1;
12569 break;
Ned Ludd2123b7c2005-02-09 21:07:23 +000012570#endif
Denis Vlasenko131ae172007-02-18 13:00:19 +000012571#if ENABLE_ASH_READ_TIMEOUT
Paul Fox02eb9342005-09-07 16:56:02 +000012572 case 't':
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012573 timeout = bb_strtou(optionarg, NULL, 10);
12574 if (errno || timeout > UINT_MAX / 2048)
12575 ash_msg_and_raise_error("invalid timeout");
12576 timeout *= 1000;
12577#if 0 /* even bash have no -t N.NNN support */
Denis Vlasenko037576d2007-10-20 18:30:38 +000012578 ts.tv_sec = bb_strtou(optionarg, &p, 10);
Paul Fox02eb9342005-09-07 16:56:02 +000012579 ts.tv_usec = 0;
Denis Vlasenko037576d2007-10-20 18:30:38 +000012580 /* EINVAL means number is ok, but not terminated by NUL */
12581 if (*p == '.' && errno == EINVAL) {
Paul Fox02eb9342005-09-07 16:56:02 +000012582 char *p2;
12583 if (*++p) {
12584 int scale;
Denis Vlasenko037576d2007-10-20 18:30:38 +000012585 ts.tv_usec = bb_strtou(p, &p2, 10);
12586 if (errno)
Denis Vlasenkob012b102007-02-19 22:43:01 +000012587 ash_msg_and_raise_error("invalid timeout");
Paul Fox02eb9342005-09-07 16:56:02 +000012588 scale = p2 - p;
12589 /* normalize to usec */
12590 if (scale > 6)
Denis Vlasenkob012b102007-02-19 22:43:01 +000012591 ash_msg_and_raise_error("invalid timeout");
Paul Fox02eb9342005-09-07 16:56:02 +000012592 while (scale++ < 6)
12593 ts.tv_usec *= 10;
12594 }
Denis Vlasenko037576d2007-10-20 18:30:38 +000012595 } else if (ts.tv_sec < 0 || errno) {
Denis Vlasenkob012b102007-02-19 22:43:01 +000012596 ash_msg_and_raise_error("invalid timeout");
Paul Fox02eb9342005-09-07 16:56:02 +000012597 }
Denis Vlasenko037576d2007-10-20 18:30:38 +000012598 if (!(ts.tv_sec | ts.tv_usec)) { /* both are 0? */
Denis Vlasenkob012b102007-02-19 22:43:01 +000012599 ash_msg_and_raise_error("invalid timeout");
Denis Vlasenko037576d2007-10-20 18:30:38 +000012600 }
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012601#endif /* if 0 */
Paul Fox02eb9342005-09-07 16:56:02 +000012602 break;
12603#endif
12604 case 'r':
12605 rflag = 1;
12606 break;
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012607 case 'u':
12608 fd = bb_strtou(optionarg, NULL, 10);
12609 if (fd < 0 || errno)
12610 ash_msg_and_raise_error("invalid file descriptor");
12611 break;
Paul Fox02eb9342005-09-07 16:56:02 +000012612 default:
12613 break;
12614 }
Eric Andersenc470f442003-07-28 09:56:35 +000012615 }
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012616 if (prompt && isatty(fd)) {
Eric Andersenc470f442003-07-28 09:56:35 +000012617 out2str(prompt);
Eric Andersenc470f442003-07-28 09:56:35 +000012618 }
Denis Vlasenko5cedb752007-02-18 19:56:41 +000012619 ap = argptr;
12620 if (*ap == NULL)
Denis Vlasenko9cd4c762008-06-18 19:22:19 +000012621 ap = (char**)arg_REPLY;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000012622 ifs = bltinlookup("IFS");
12623 if (ifs == NULL)
Eric Andersenc470f442003-07-28 09:56:35 +000012624 ifs = defifs;
Denis Vlasenko131ae172007-02-18 13:00:19 +000012625#if ENABLE_ASH_READ_NCHARS
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012626 tcgetattr(fd, &tty);
12627 old_tty = tty;
12628 if (nchars || silent) {
12629 if (nchars) {
12630 tty.c_lflag &= ~ICANON;
12631 tty.c_cc[VMIN] = nchars < 256 ? nchars : 255;
Paul Fox02eb9342005-09-07 16:56:02 +000012632 }
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012633 if (silent) {
12634 tty.c_lflag &= ~(ECHO | ECHOK | ECHONL);
12635 }
12636 /* if tcgetattr failed, tcsetattr will fail too.
12637 * Ignoring, it's harmless. */
12638 tcsetattr(fd, TCSANOW, &tty);
Paul Fox02eb9342005-09-07 16:56:02 +000012639 }
12640#endif
Paul Fox02eb9342005-09-07 16:56:02 +000012641
Eric Andersenc470f442003-07-28 09:56:35 +000012642 status = 0;
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012643 startword = 2;
Eric Andersenc470f442003-07-28 09:56:35 +000012644 backslash = 0;
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012645#if ENABLE_ASH_READ_TIMEOUT
12646 if (timeout) /* NB: ensuring end_ms is nonzero */
12647 end_ms = ((unsigned)(monotonic_us() / 1000) + timeout) | 1;
12648#endif
Eric Andersenc470f442003-07-28 09:56:35 +000012649 STARTSTACKSTR(p);
Denis Vlasenko037576d2007-10-20 18:30:38 +000012650 do {
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012651 const char *is_ifs;
12652
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012653#if ENABLE_ASH_READ_TIMEOUT
12654 if (end_ms) {
12655 struct pollfd pfd[1];
12656 pfd[0].fd = fd;
12657 pfd[0].events = POLLIN;
12658 timeout = end_ms - (unsigned)(monotonic_us() / 1000);
12659 if ((int)timeout <= 0 /* already late? */
12660 || safe_poll(pfd, 1, timeout) != 1 /* no? wait... */
12661 ) { /* timed out! */
12662#if ENABLE_ASH_READ_NCHARS
12663 tcsetattr(fd, TCSANOW, &old_tty);
12664#endif
12665 return 1;
12666 }
12667 }
12668#endif
12669 if (nonblock_safe_read(fd, &c, 1) != 1) {
Eric Andersenc470f442003-07-28 09:56:35 +000012670 status = 1;
12671 break;
12672 }
12673 if (c == '\0')
12674 continue;
12675 if (backslash) {
12676 backslash = 0;
12677 if (c != '\n')
12678 goto put;
12679 continue;
12680 }
12681 if (!rflag && c == '\\') {
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012682 backslash = 1;
Eric Andersenc470f442003-07-28 09:56:35 +000012683 continue;
12684 }
12685 if (c == '\n')
12686 break;
Denis Vlasenkof6fbd622009-03-31 19:36:58 +000012687 /* $IFS splitting */
Denis Vlasenko551ffdc2009-04-01 19:48:05 +000012688/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_05 */
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012689 is_ifs = strchr(ifs, c);
12690 if (startword && is_ifs) {
12691 if (isspace(c))
12692 continue;
Denis Vlasenkof6fbd622009-03-31 19:36:58 +000012693 /* it is a non-space ifs char */
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012694 startword--;
12695 if (startword == 1) /* first one? */
Denis Vlasenkof6fbd622009-03-31 19:36:58 +000012696 continue; /* yes, it is not next word yet */
Eric Andersenc470f442003-07-28 09:56:35 +000012697 }
12698 startword = 0;
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012699 if (ap[1] != NULL && is_ifs) {
12700 const char *beg;
Eric Andersenc470f442003-07-28 09:56:35 +000012701 STACKSTRNUL(p);
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012702 beg = stackblock();
12703 setvar(*ap, beg, 0);
Eric Andersenc470f442003-07-28 09:56:35 +000012704 ap++;
Denis Vlasenkof6fbd622009-03-31 19:36:58 +000012705 /* can we skip one non-space ifs char? (2: yes) */
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012706 startword = isspace(c) ? 2 : 1;
Eric Andersenc470f442003-07-28 09:56:35 +000012707 STARTSTACKSTR(p);
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012708 continue;
Eric Andersenc470f442003-07-28 09:56:35 +000012709 }
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012710 put:
12711 STPUTC(c, p);
Eric Andersenc470f442003-07-28 09:56:35 +000012712 }
Denis Vlasenko037576d2007-10-20 18:30:38 +000012713/* end of do {} while: */
Denis Vlasenko131ae172007-02-18 13:00:19 +000012714#if ENABLE_ASH_READ_NCHARS
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012715 while (--nchars);
Denis Vlasenko037576d2007-10-20 18:30:38 +000012716#else
12717 while (1);
12718#endif
12719
12720#if ENABLE_ASH_READ_NCHARS
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012721 tcsetattr(fd, TCSANOW, &old_tty);
Paul Fox02eb9342005-09-07 16:56:02 +000012722#endif
12723
Eric Andersenc470f442003-07-28 09:56:35 +000012724 STACKSTRNUL(p);
Denis Vlasenko46aeab92009-03-31 19:18:17 +000012725 /* Remove trailing space ifs chars */
12726 while ((char *)stackblock() <= --p && isspace(*p) && strchr(ifs, *p) != NULL)
Eric Andersenc470f442003-07-28 09:56:35 +000012727 *p = '\0';
12728 setvar(*ap, stackblock(), 0);
12729 while (*++ap != NULL)
12730 setvar(*ap, nullstr, 0);
12731 return status;
12732}
12733
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012734static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012735umaskcmd(int argc UNUSED_PARAM, char **argv)
Eric Andersenc470f442003-07-28 09:56:35 +000012736{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000012737 static const char permuser[3] ALIGN1 = "ugo";
12738 static const char permmode[3] ALIGN1 = "rwx";
12739 static const short permmask[] ALIGN2 = {
Eric Andersenc470f442003-07-28 09:56:35 +000012740 S_IRUSR, S_IWUSR, S_IXUSR,
12741 S_IRGRP, S_IWGRP, S_IXGRP,
12742 S_IROTH, S_IWOTH, S_IXOTH
12743 };
12744
Denis Vlasenkoeb858492009-04-18 02:06:54 +000012745 /* TODO: use bb_parse_mode() instead */
12746
Eric Andersenc470f442003-07-28 09:56:35 +000012747 char *ap;
12748 mode_t mask;
12749 int i;
12750 int symbolic_mode = 0;
12751
12752 while (nextopt("S") != '\0') {
12753 symbolic_mode = 1;
12754 }
12755
Denis Vlasenkob012b102007-02-19 22:43:01 +000012756 INT_OFF;
Eric Andersenc470f442003-07-28 09:56:35 +000012757 mask = umask(0);
12758 umask(mask);
Denis Vlasenkob012b102007-02-19 22:43:01 +000012759 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +000012760
Denis Vlasenko5cedb752007-02-18 19:56:41 +000012761 ap = *argptr;
12762 if (ap == NULL) {
Eric Andersenc470f442003-07-28 09:56:35 +000012763 if (symbolic_mode) {
12764 char buf[18];
12765 char *p = buf;
12766
12767 for (i = 0; i < 3; i++) {
12768 int j;
12769
12770 *p++ = permuser[i];
12771 *p++ = '=';
12772 for (j = 0; j < 3; j++) {
12773 if ((mask & permmask[3 * i + j]) == 0) {
12774 *p++ = permmode[j];
12775 }
12776 }
12777 *p++ = ',';
12778 }
12779 *--p = 0;
12780 puts(buf);
12781 } else {
12782 out1fmt("%.4o\n", mask);
12783 }
12784 } else {
Denis Vlasenkoaa744452007-02-23 01:04:22 +000012785 if (isdigit((unsigned char) *ap)) {
Eric Andersenc470f442003-07-28 09:56:35 +000012786 mask = 0;
12787 do {
12788 if (*ap >= '8' || *ap < '0')
Denys Vlasenkoecc2a2e2009-08-29 22:53:41 +020012789 ash_msg_and_raise_error(msg_illnum, argv[1]);
Eric Andersenc470f442003-07-28 09:56:35 +000012790 mask = (mask << 3) + (*ap - '0');
12791 } while (*++ap != '\0');
12792 umask(mask);
12793 } else {
12794 mask = ~mask & 0777;
12795 if (!bb_parse_mode(ap, &mask)) {
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +000012796 ash_msg_and_raise_error("illegal mode: %s", ap);
Eric Andersenc470f442003-07-28 09:56:35 +000012797 }
12798 umask(~mask & 0777);
12799 }
12800 }
12801 return 0;
12802}
12803
12804/*
12805 * ulimit builtin
12806 *
12807 * This code, originally by Doug Gwyn, Doug Kingston, Eric Gisin, and
12808 * Michael Rendell was ripped from pdksh 5.0.8 and hacked for use with
12809 * ash by J.T. Conklin.
12810 *
12811 * Public domain.
12812 */
Eric Andersenc470f442003-07-28 09:56:35 +000012813struct limits {
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012814 uint8_t cmd; /* RLIMIT_xxx fit into it */
12815 uint8_t factor_shift; /* shift by to get rlim_{cur,max} values */
Eric Andersenc470f442003-07-28 09:56:35 +000012816 char option;
12817};
12818
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012819static const struct limits limits_tbl[] = {
Eric Andersenc470f442003-07-28 09:56:35 +000012820#ifdef RLIMIT_CPU
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012821 { RLIMIT_CPU, 0, 't' },
Eric Andersenc470f442003-07-28 09:56:35 +000012822#endif
12823#ifdef RLIMIT_FSIZE
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012824 { RLIMIT_FSIZE, 9, 'f' },
Eric Andersenc470f442003-07-28 09:56:35 +000012825#endif
12826#ifdef RLIMIT_DATA
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012827 { RLIMIT_DATA, 10, 'd' },
Eric Andersenc470f442003-07-28 09:56:35 +000012828#endif
12829#ifdef RLIMIT_STACK
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012830 { RLIMIT_STACK, 10, 's' },
Eric Andersenc470f442003-07-28 09:56:35 +000012831#endif
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012832#ifdef RLIMIT_CORE
12833 { RLIMIT_CORE, 9, 'c' },
Eric Andersenc470f442003-07-28 09:56:35 +000012834#endif
12835#ifdef RLIMIT_RSS
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012836 { RLIMIT_RSS, 10, 'm' },
Eric Andersenc470f442003-07-28 09:56:35 +000012837#endif
12838#ifdef RLIMIT_MEMLOCK
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012839 { RLIMIT_MEMLOCK, 10, 'l' },
Eric Andersenc470f442003-07-28 09:56:35 +000012840#endif
12841#ifdef RLIMIT_NPROC
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012842 { RLIMIT_NPROC, 0, 'p' },
Eric Andersenc470f442003-07-28 09:56:35 +000012843#endif
12844#ifdef RLIMIT_NOFILE
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012845 { RLIMIT_NOFILE, 0, 'n' },
Eric Andersenc470f442003-07-28 09:56:35 +000012846#endif
Glenn L McGrath76620622004-01-13 10:19:37 +000012847#ifdef RLIMIT_AS
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012848 { RLIMIT_AS, 10, 'v' },
Eric Andersenc470f442003-07-28 09:56:35 +000012849#endif
Glenn L McGrath76620622004-01-13 10:19:37 +000012850#ifdef RLIMIT_LOCKS
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012851 { RLIMIT_LOCKS, 0, 'w' },
Eric Andersenc470f442003-07-28 09:56:35 +000012852#endif
Eric Andersenc470f442003-07-28 09:56:35 +000012853};
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012854static const char limits_name[] =
12855#ifdef RLIMIT_CPU
12856 "time(seconds)" "\0"
12857#endif
12858#ifdef RLIMIT_FSIZE
12859 "file(blocks)" "\0"
12860#endif
12861#ifdef RLIMIT_DATA
12862 "data(kb)" "\0"
12863#endif
12864#ifdef RLIMIT_STACK
12865 "stack(kb)" "\0"
12866#endif
12867#ifdef RLIMIT_CORE
12868 "coredump(blocks)" "\0"
12869#endif
12870#ifdef RLIMIT_RSS
12871 "memory(kb)" "\0"
12872#endif
12873#ifdef RLIMIT_MEMLOCK
12874 "locked memory(kb)" "\0"
12875#endif
12876#ifdef RLIMIT_NPROC
12877 "process" "\0"
12878#endif
12879#ifdef RLIMIT_NOFILE
12880 "nofiles" "\0"
12881#endif
12882#ifdef RLIMIT_AS
12883 "vmemory(kb)" "\0"
12884#endif
12885#ifdef RLIMIT_LOCKS
12886 "locks" "\0"
12887#endif
12888;
Eric Andersenc470f442003-07-28 09:56:35 +000012889
Glenn L McGrath76620622004-01-13 10:19:37 +000012890enum limtype { SOFT = 0x1, HARD = 0x2 };
12891
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012892static void
12893printlim(enum limtype how, const struct rlimit *limit,
Glenn L McGrath76620622004-01-13 10:19:37 +000012894 const struct limits *l)
12895{
12896 rlim_t val;
12897
12898 val = limit->rlim_max;
12899 if (how & SOFT)
12900 val = limit->rlim_cur;
12901
12902 if (val == RLIM_INFINITY)
12903 out1fmt("unlimited\n");
12904 else {
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012905 val >>= l->factor_shift;
Glenn L McGrath76620622004-01-13 10:19:37 +000012906 out1fmt("%lld\n", (long long) val);
12907 }
12908}
12909
Denys Vlasenkod5f1b1b2009-06-05 12:06:05 +020012910static int FAST_FUNC
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000012911ulimitcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
Eric Andersenc470f442003-07-28 09:56:35 +000012912{
Denys Vlasenko76622db2009-10-04 01:14:19 +020012913 rlim_t val;
Glenn L McGrath76620622004-01-13 10:19:37 +000012914 enum limtype how = SOFT | HARD;
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012915 const struct limits *l;
12916 int set, all = 0;
12917 int optc, what;
12918 struct rlimit limit;
Eric Andersenc470f442003-07-28 09:56:35 +000012919
12920 what = 'f';
Glenn L McGrath16e45d72004-02-04 08:24:39 +000012921 while ((optc = nextopt("HSa"
12922#ifdef RLIMIT_CPU
12923 "t"
12924#endif
12925#ifdef RLIMIT_FSIZE
12926 "f"
12927#endif
12928#ifdef RLIMIT_DATA
12929 "d"
12930#endif
12931#ifdef RLIMIT_STACK
12932 "s"
12933#endif
12934#ifdef RLIMIT_CORE
12935 "c"
12936#endif
12937#ifdef RLIMIT_RSS
12938 "m"
12939#endif
12940#ifdef RLIMIT_MEMLOCK
12941 "l"
12942#endif
12943#ifdef RLIMIT_NPROC
12944 "p"
12945#endif
12946#ifdef RLIMIT_NOFILE
12947 "n"
12948#endif
12949#ifdef RLIMIT_AS
12950 "v"
12951#endif
12952#ifdef RLIMIT_LOCKS
12953 "w"
12954#endif
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000012955 )) != '\0')
Eric Andersenc470f442003-07-28 09:56:35 +000012956 switch (optc) {
12957 case 'H':
12958 how = HARD;
12959 break;
12960 case 'S':
12961 how = SOFT;
12962 break;
12963 case 'a':
12964 all = 1;
12965 break;
12966 default:
12967 what = optc;
12968 }
12969
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012970 for (l = limits_tbl; l->option != what; l++)
12971 continue;
Eric Andersenc470f442003-07-28 09:56:35 +000012972
12973 set = *argptr ? 1 : 0;
Denys Vlasenko76622db2009-10-04 01:14:19 +020012974 val = 0;
Eric Andersenc470f442003-07-28 09:56:35 +000012975 if (set) {
12976 char *p = *argptr;
12977
12978 if (all || argptr[1])
Denis Vlasenkob012b102007-02-19 22:43:01 +000012979 ash_msg_and_raise_error("too many arguments");
Eric Andersen81fe1232003-07-29 06:38:40 +000012980 if (strncmp(p, "unlimited\n", 9) == 0)
Eric Andersenc470f442003-07-28 09:56:35 +000012981 val = RLIM_INFINITY;
12982 else {
Denys Vlasenko76622db2009-10-04 01:14:19 +020012983 if (sizeof(val) == sizeof(int))
12984 val = bb_strtou(p, NULL, 10);
12985 else if (sizeof(val) == sizeof(long))
12986 val = bb_strtoul(p, NULL, 10);
12987 else
12988 val = bb_strtoull(p, NULL, 10);
12989 if (errno)
Denis Vlasenkob012b102007-02-19 22:43:01 +000012990 ash_msg_and_raise_error("bad number");
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012991 val <<= l->factor_shift;
Eric Andersenc470f442003-07-28 09:56:35 +000012992 }
12993 }
12994 if (all) {
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012995 const char *lname = limits_name;
12996 for (l = limits_tbl; l != &limits_tbl[ARRAY_SIZE(limits_tbl)]; l++) {
Eric Andersenc470f442003-07-28 09:56:35 +000012997 getrlimit(l->cmd, &limit);
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012998 out1fmt("%-20s ", lname);
12999 lname += strlen(lname) + 1;
Glenn L McGrath76620622004-01-13 10:19:37 +000013000 printlim(how, &limit, l);
Eric Andersenc470f442003-07-28 09:56:35 +000013001 }
13002 return 0;
13003 }
13004
13005 getrlimit(l->cmd, &limit);
13006 if (set) {
13007 if (how & HARD)
13008 limit.rlim_max = val;
13009 if (how & SOFT)
13010 limit.rlim_cur = val;
13011 if (setrlimit(l->cmd, &limit) < 0)
Denis Vlasenkob012b102007-02-19 22:43:01 +000013012 ash_msg_and_raise_error("error setting limit (%m)");
Eric Andersenc470f442003-07-28 09:56:35 +000013013 } else {
Glenn L McGrath76620622004-01-13 10:19:37 +000013014 printlim(how, &limit, l);
Eric Andersenc470f442003-07-28 09:56:35 +000013015 }
13016 return 0;
13017}
13018
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000013019/* ============ main() and helpers */
13020
13021/*
13022 * Called to exit the shell.
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013023 */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000013024static void exitshell(void) NORETURN;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000013025static void
13026exitshell(void)
13027{
13028 struct jmploc loc;
13029 char *p;
13030 int status;
13031
13032 status = exitstatus;
13033 TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
13034 if (setjmp(loc.loc)) {
Denis Vlasenko7f88e342009-03-19 03:36:18 +000013035 if (exception_type == EXEXIT)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000013036/* dash bug: it just does _exit(exitstatus) here
13037 * but we have to do setjobctl(0) first!
13038 * (bug is still not fixed in dash-0.5.3 - if you run dash
13039 * under Midnight Commander, on exit from dash MC is backgrounded) */
13040 status = exitstatus;
13041 goto out;
13042 }
13043 exception_handler = &loc;
13044 p = trap[0];
13045 if (p) {
13046 trap[0] = NULL;
13047 evalstring(p, 0);
Denys Vlasenko0800e3a2009-09-24 03:09:26 +020013048 free(p);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000013049 }
13050 flush_stdout_stderr();
13051 out:
13052 setjobctl(0);
13053 _exit(status);
13054 /* NOTREACHED */
13055}
13056
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000013057static void
13058init(void)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013059{
13060 /* from input.c: */
Denis Vlasenko41eb3002008-11-28 03:42:31 +000013061 basepf.next_to_pgetc = basepf.buf = basebuf;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013062
13063 /* from trap.c: */
13064 signal(SIGCHLD, SIG_DFL);
13065
13066 /* from var.c: */
13067 {
13068 char **envp;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013069 const char *p;
13070 struct stat st1, st2;
13071
13072 initvar();
13073 for (envp = environ; envp && *envp; envp++) {
13074 if (strchr(*envp, '=')) {
13075 setvareq(*envp, VEXPORT|VTEXTFIXED);
13076 }
13077 }
13078
Denys Vlasenko7bb346f2009-10-06 22:09:50 +020013079 setvar("PPID", utoa(getppid()), 0);
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013080
13081 p = lookupvar("PWD");
13082 if (p)
13083 if (*p != '/' || stat(p, &st1) || stat(".", &st2)
13084 || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino)
13085 p = '\0';
13086 setpwd(p, 0);
13087 }
13088}
13089
13090/*
13091 * Process the shell command line arguments.
13092 */
13093static void
Denis Vlasenko68404f12008-03-17 09:00:54 +000013094procargs(char **argv)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013095{
13096 int i;
13097 const char *xminusc;
13098 char **xargv;
13099
13100 xargv = argv;
13101 arg0 = xargv[0];
Denis Vlasenko68404f12008-03-17 09:00:54 +000013102 /* if (xargv[0]) - mmm, this is always true! */
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013103 xargv++;
13104 for (i = 0; i < NOPTS; i++)
13105 optlist[i] = 2;
13106 argptr = xargv;
Denis Vlasenko28bf6712008-02-14 15:01:47 +000013107 if (options(1)) {
13108 /* it already printed err message */
13109 raise_exception(EXERROR);
13110 }
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013111 xargv = argptr;
13112 xminusc = minusc;
13113 if (*xargv == NULL) {
13114 if (xminusc)
13115 ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
13116 sflag = 1;
13117 }
13118 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
13119 iflag = 1;
13120 if (mflag == 2)
13121 mflag = iflag;
13122 for (i = 0; i < NOPTS; i++)
13123 if (optlist[i] == 2)
13124 optlist[i] = 0;
13125#if DEBUG == 2
13126 debug = 1;
13127#endif
13128 /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
13129 if (xminusc) {
13130 minusc = *xargv++;
13131 if (*xargv)
13132 goto setarg0;
13133 } else if (!sflag) {
13134 setinputfile(*xargv, 0);
13135 setarg0:
13136 arg0 = *xargv++;
13137 commandname = arg0;
13138 }
13139
13140 shellparam.p = xargv;
13141#if ENABLE_ASH_GETOPTS
13142 shellparam.optind = 1;
13143 shellparam.optoff = -1;
13144#endif
Denis Vlasenko01631112007-12-16 17:20:38 +000013145 /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013146 while (*xargv) {
13147 shellparam.nparam++;
13148 xargv++;
13149 }
13150 optschanged();
13151}
13152
13153/*
13154 * Read /etc/profile or .profile.
13155 */
13156static void
13157read_profile(const char *name)
13158{
13159 int skip;
13160
13161 if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
13162 return;
13163 skip = cmdloop(0);
13164 popfile();
13165 if (skip)
13166 exitshell();
13167}
13168
Denis Vlasenko0c032a42007-02-23 01:03:40 +000013169/*
13170 * This routine is called when an error or an interrupt occurs in an
13171 * interactive shell and control is returned to the main command loop.
13172 */
13173static void
13174reset(void)
13175{
13176 /* from eval.c: */
13177 evalskip = 0;
13178 loopnest = 0;
13179 /* from input.c: */
Denis Vlasenko41eb3002008-11-28 03:42:31 +000013180 g_parsefile->left_in_buffer = 0;
13181 g_parsefile->left_in_line = 0; /* clear input buffer */
Denis Vlasenko0c032a42007-02-23 01:03:40 +000013182 popallfiles();
13183 /* from parser.c: */
13184 tokpushback = 0;
13185 checkkwd = 0;
13186 /* from redir.c: */
Denis Vlasenko34c73c42008-08-16 11:48:02 +000013187 clearredir(/*drop:*/ 0);
Denis Vlasenko0c032a42007-02-23 01:03:40 +000013188}
13189
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013190#if PROFILE
13191static short profile_buf[16384];
13192extern int etext();
13193#endif
13194
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000013195/*
13196 * Main routine. We initialize things, parse the arguments, execute
13197 * profiles if we're a login shell, and then call cmdloop to execute
13198 * commands. The setjmp call sets up the location to jump to when an
13199 * exception occurs. When an exception occurs the variable "state"
13200 * is used to figure out how far we had gotten.
13201 */
Denis Vlasenko9b49a5e2007-10-11 10:05:36 +000013202int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +000013203int ash_main(int argc UNUSED_PARAM, char **argv)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013204{
Mike Frysinger98c52642009-04-02 10:02:37 +000013205 const char *shinit;
Denis Vlasenko4e12b1a2008-12-23 23:36:47 +000013206 volatile smallint state;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013207 struct jmploc jmploc;
13208 struct stackmark smark;
13209
Denis Vlasenko01631112007-12-16 17:20:38 +000013210 /* Initialize global data */
13211 INIT_G_misc();
13212 INIT_G_memstack();
13213 INIT_G_var();
Denis Vlasenkoee87ebf2007-12-21 22:18:16 +000013214#if ENABLE_ASH_ALIAS
Denis Vlasenko01631112007-12-16 17:20:38 +000013215 INIT_G_alias();
Denis Vlasenkoee87ebf2007-12-21 22:18:16 +000013216#endif
Denis Vlasenko01631112007-12-16 17:20:38 +000013217 INIT_G_cmdtable();
13218
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013219#if PROFILE
13220 monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
13221#endif
13222
13223#if ENABLE_FEATURE_EDITING
13224 line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
13225#endif
13226 state = 0;
13227 if (setjmp(jmploc.loc)) {
Denis Vlasenko7f88e342009-03-19 03:36:18 +000013228 smallint e;
Denis Vlasenko4e12b1a2008-12-23 23:36:47 +000013229 smallint s;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013230
13231 reset();
13232
Denis Vlasenko7f88e342009-03-19 03:36:18 +000013233 e = exception_type;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013234 if (e == EXERROR)
13235 exitstatus = 2;
13236 s = state;
13237 if (e == EXEXIT || s == 0 || iflag == 0 || shlvl)
13238 exitshell();
Denis Vlasenko7f88e342009-03-19 03:36:18 +000013239 if (e == EXINT)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013240 outcslow('\n', stderr);
Denis Vlasenko7f88e342009-03-19 03:36:18 +000013241
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013242 popstackmark(&smark);
13243 FORCE_INT_ON; /* enable interrupts */
13244 if (s == 1)
13245 goto state1;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000013246 if (s == 2)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013247 goto state2;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000013248 if (s == 3)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013249 goto state3;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000013250 goto state4;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013251 }
13252 exception_handler = &jmploc;
13253#if DEBUG
13254 opentrace();
Denis Vlasenko653d8e72009-03-19 21:59:35 +000013255 TRACE(("Shell args: "));
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000013256 trace_puts_args(argv);
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013257#endif
13258 rootpid = getpid();
13259
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013260 init();
13261 setstackmark(&smark);
Denis Vlasenko68404f12008-03-17 09:00:54 +000013262 procargs(argv);
13263
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013264#if ENABLE_FEATURE_EDITING_SAVEHISTORY
13265 if (iflag) {
13266 const char *hp = lookupvar("HISTFILE");
13267
13268 if (hp == NULL) {
13269 hp = lookupvar("HOME");
13270 if (hp != NULL) {
13271 char *defhp = concat_path_file(hp, ".ash_history");
13272 setvar("HISTFILE", defhp, 0);
13273 free(defhp);
13274 }
13275 }
13276 }
13277#endif
Denis Vlasenko4e12b1a2008-12-23 23:36:47 +000013278 if (/* argv[0] && */ argv[0][0] == '-')
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013279 isloginsh = 1;
13280 if (isloginsh) {
13281 state = 1;
13282 read_profile("/etc/profile");
13283 state1:
13284 state = 2;
13285 read_profile(".profile");
13286 }
13287 state2:
13288 state = 3;
13289 if (
13290#ifndef linux
Denis Vlasenko0c032a42007-02-23 01:03:40 +000013291 getuid() == geteuid() && getgid() == getegid() &&
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013292#endif
Denis Vlasenko0c032a42007-02-23 01:03:40 +000013293 iflag
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013294 ) {
13295 shinit = lookupvar("ENV");
13296 if (shinit != NULL && *shinit != '\0') {
13297 read_profile(shinit);
13298 }
13299 }
13300 state3:
13301 state = 4;
Denis Vlasenko5c2b8142009-03-19 01:59:59 +000013302 if (minusc) {
13303 /* evalstring pushes parsefile stack.
13304 * Ensure we don't falsely claim that 0 (stdin)
Denis Vlasenko5368ad52009-03-20 10:20:08 +000013305 * is one of stacked source fds.
13306 * Testcase: ash -c 'exec 1>&0' must not complain. */
Denis Vlasenko5c2b8142009-03-19 01:59:59 +000013307 if (!sflag)
13308 g_parsefile->fd = -1;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013309 evalstring(minusc, 0);
Denis Vlasenko5c2b8142009-03-19 01:59:59 +000013310 }
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013311
13312 if (sflag || minusc == NULL) {
Denys Vlasenkodb9c57e2009-09-27 02:48:53 +020013313#if MAX_HISTORY > 0 && ENABLE_FEATURE_EDITING_SAVEHISTORY
Denis Vlasenko2f5d0cd2008-06-23 13:24:19 +000013314 if (iflag) {
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013315 const char *hp = lookupvar("HISTFILE");
Denis Vlasenko5c2b8142009-03-19 01:59:59 +000013316 if (hp)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013317 line_input_state->hist_file = hp;
13318 }
13319#endif
13320 state4: /* XXX ??? - why isn't this before the "if" statement */
13321 cmdloop(1);
13322 }
13323#if PROFILE
13324 monitor(0);
13325#endif
13326#ifdef GPROF
13327 {
13328 extern void _mcleanup(void);
13329 _mcleanup();
13330 }
13331#endif
13332 exitshell();
13333 /* NOTREACHED */
13334}
13335
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013336
Eric Andersendf82f612001-06-28 07:46:40 +000013337/*-
13338 * Copyright (c) 1989, 1991, 1993, 1994
Eric Andersen2870d962001-07-02 17:27:21 +000013339 * The Regents of the University of California. All rights reserved.
Eric Andersendf82f612001-06-28 07:46:40 +000013340 *
13341 * This code is derived from software contributed to Berkeley by
13342 * Kenneth Almquist.
13343 *
13344 * Redistribution and use in source and binary forms, with or without
13345 * modification, are permitted provided that the following conditions
13346 * are met:
13347 * 1. Redistributions of source code must retain the above copyright
13348 * notice, this list of conditions and the following disclaimer.
13349 * 2. Redistributions in binary form must reproduce the above copyright
13350 * notice, this list of conditions and the following disclaimer in the
13351 * documentation and/or other materials provided with the distribution.
"Vladimir N. Oleynik"ddc280e2005-12-15 12:01:49 +000013352 * 3. Neither the name of the University nor the names of its contributors
Eric Andersendf82f612001-06-28 07:46:40 +000013353 * may be used to endorse or promote products derived from this software
13354 * without specific prior written permission.
13355 *
13356 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
13357 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
13358 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
13359 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
13360 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
13361 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
13362 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
13363 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
13364 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
13365 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
13366 * SUCH DAMAGE.
13367 */