blob: 65f94f682c4aff357c353ac2f7e43b0ab2e713ea [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 *
11 *
Eric Andersencb57d552001-06-28 07:25:16 +000012 * This code is derived from software contributed to Berkeley by
13 * Kenneth Almquist.
14 *
Bernhard Reutner-Fischer86f5c992006-01-22 22:55:11 +000015 * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
Eric Andersendf82f612001-06-28 07:46:40 +000016 *
Eric Andersen81fe1232003-07-29 06:38:40 +000017 * Original BSD copyright notice is retained at the end of this file.
Eric Andersencb57d552001-06-28 07:25:16 +000018 */
19
Eric Andersenc470f442003-07-28 09:56:35 +000020/*
Eric Andersen90898442003-08-06 11:20:52 +000021 * rewrite arith.y to micro stack based cryptic algorithm by
22 * Copyright (c) 2001 Aaron Lehmann <aaronl@vitelus.com>
23 *
Eric Andersenef02f822004-03-11 13:34:24 +000024 * Modified by Paul Mundt <lethal@linux-sh.org> (c) 2004 to support
25 * dynamic variables.
Eric Andersen16767e22004-03-16 05:14:10 +000026 *
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +000027 * Modified by Vladimir Oleynik <dzo@simtreas.ru> (c) 2001-2005 to be
Eric Andersen16767e22004-03-16 05:14:10 +000028 * used in busybox and size optimizations,
29 * rewrote arith (see notes to this), added locale support,
30 * rewrote dynamic variables.
31 *
Eric Andersen90898442003-08-06 11:20:52 +000032 */
33
Eric Andersen90898442003-08-06 11:20:52 +000034/*
Eric Andersenc470f442003-07-28 09:56:35 +000035 * The follow should be set to reflect the type of system you have:
36 * JOBS -> 1 if you have Berkeley job control, 0 otherwise.
37 * define SYSV if you are running under System V.
38 * define DEBUG=1 to compile in debugging ('set -o debug' to turn on)
39 * define DEBUG=2 to compile in and turn on debugging.
40 *
41 * When debugging is on, debugging info will be written to ./trace and
42 * a quit signal will generate a core dump.
43 */
Denis Vlasenkoa7189f02006-11-17 20:29:00 +000044#define DEBUG 0
Eric Andersenc470f442003-07-28 09:56:35 +000045#define PROFILE 0
Denis Vlasenko0e6f6612008-02-15 15:02:15 +000046
47#define IFS_BROKEN
48
49#define JOBS ENABLE_ASH_JOB_CONTROL
Eric Andersenc470f442003-07-28 09:56:35 +000050
Denis Vlasenkob012b102007-02-19 22:43:01 +000051#if DEBUG
Denis Vlasenkoe26b2782008-02-12 07:40:29 +000052#ifndef _GNU_SOURCE
Denis Vlasenkob012b102007-02-19 22:43:01 +000053#define _GNU_SOURCE
54#endif
Denis Vlasenkoe26b2782008-02-12 07:40:29 +000055#endif
Denis Vlasenko0e6f6612008-02-15 15:02:15 +000056
Denis Vlasenko1aa7e472007-11-28 06:49:03 +000057#include "busybox.h" /* for applet_names */
Denis Vlasenkob012b102007-02-19 22:43:01 +000058#include <paths.h>
59#include <setjmp.h>
60#include <fnmatch.h>
Denis Vlasenko131ae172007-02-18 13:00:19 +000061#if JOBS || ENABLE_ASH_READ_NCHARS
Eric Andersencb57d552001-06-28 07:25:16 +000062#include <termios.h>
Eric Andersencb57d552001-06-28 07:25:16 +000063#endif
64
Denis Vlasenkob012b102007-02-19 22:43:01 +000065#if defined(__uClinux__)
66#error "Do not even bother, ash will not run on uClinux"
67#endif
68
Denis Vlasenkob012b102007-02-19 22:43:01 +000069
Denis Vlasenko01631112007-12-16 17:20:38 +000070/* ============ Hash table sizes. Configurable. */
71
72#define VTABSIZE 39
73#define ATABSIZE 39
74#define CMDTABLESIZE 31 /* should be prime */
75
76
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +000077/* ============ Misc helpers */
78
79#define xbarrier() do { __asm__ __volatile__ ("": : :"memory"); } while (0)
80
81/* C99 say: "char" declaration may be signed or unsigned default */
82#define signed_char2int(sc) ((int)((signed char)sc))
83
84
Denis Vlasenkob012b102007-02-19 22:43:01 +000085/* ============ Shell options */
86
87static const char *const optletters_optnames[] = {
88 "e" "errexit",
89 "f" "noglob",
90 "I" "ignoreeof",
91 "i" "interactive",
92 "m" "monitor",
93 "n" "noexec",
94 "s" "stdin",
95 "x" "xtrace",
96 "v" "verbose",
97 "C" "noclobber",
98 "a" "allexport",
99 "b" "notify",
100 "u" "nounset",
Denis Vlasenko6ca409e2007-08-12 20:58:27 +0000101 "\0" "vi"
Denis Vlasenkob012b102007-02-19 22:43:01 +0000102#if DEBUG
Denis Vlasenko6ca409e2007-08-12 20:58:27 +0000103 ,"\0" "nolog"
104 ,"\0" "debug"
Denis Vlasenkob012b102007-02-19 22:43:01 +0000105#endif
106};
107
108#define optletters(n) optletters_optnames[(n)][0]
109#define optnames(n) (&optletters_optnames[(n)][1])
110
Denis Vlasenko80b8b392007-06-25 10:55:35 +0000111enum { NOPTS = ARRAY_SIZE(optletters_optnames) };
Denis Vlasenkob012b102007-02-19 22:43:01 +0000112
Denis Vlasenko6ca409e2007-08-12 20:58:27 +0000113static char optlist[NOPTS] ALIGN1;
Denis Vlasenkob012b102007-02-19 22:43:01 +0000114
115#define eflag optlist[0]
116#define fflag optlist[1]
117#define Iflag optlist[2]
118#define iflag optlist[3]
119#define mflag optlist[4]
120#define nflag optlist[5]
121#define sflag optlist[6]
122#define xflag optlist[7]
123#define vflag optlist[8]
124#define Cflag optlist[9]
125#define aflag optlist[10]
126#define bflag optlist[11]
127#define uflag optlist[12]
128#define viflag optlist[13]
129#if DEBUG
130#define nolog optlist[14]
131#define debug optlist[15]
132#endif
Eric Andersenc470f442003-07-28 09:56:35 +0000133
134
Denis Vlasenkob012b102007-02-19 22:43:01 +0000135/* ============ Misc data */
Eric Andersenc470f442003-07-28 09:56:35 +0000136
Denis Vlasenko6ca409e2007-08-12 20:58:27 +0000137static const char homestr[] ALIGN1 = "HOME";
138static const char snlfmt[] ALIGN1 = "%s\n";
139static const char illnum[] ALIGN1 = "Illegal number: %s";
Denis Vlasenkoaa744452007-02-23 01:04:22 +0000140
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +0000141/*
Eric Andersenc470f442003-07-28 09:56:35 +0000142 * We enclose jmp_buf in a structure so that we can declare pointers to
143 * jump locations. The global variable handler contains the location to
144 * jump to when an exception occurs, and the global variable exception
Eric Andersenaff114c2004-04-14 17:51:38 +0000145 * contains a code identifying the exception. To implement nested
Eric Andersenc470f442003-07-28 09:56:35 +0000146 * exception handlers, the user should save the value of handler on entry
147 * to an inner scope, set handler to point to a jmploc structure for the
148 * inner scope, and restore handler on exit from the scope.
149 */
Eric Andersenc470f442003-07-28 09:56:35 +0000150struct jmploc {
151 jmp_buf loc;
152};
Denis Vlasenko01631112007-12-16 17:20:38 +0000153
154struct globals_misc {
155 /* pid of main shell */
156 int rootpid;
157 /* shell level: 0 for the main shell, 1 for its children, and so on */
158 int shlvl;
159#define rootshell (!shlvl)
160 char *minusc; /* argument to -c option */
161
162 char *curdir; // = nullstr; /* current working directory */
163 char *physdir; // = nullstr; /* physical working directory */
164
165 char *arg0; /* value of $0 */
166
167 struct jmploc *exception_handler;
Denis Vlasenko991a1da2008-02-10 19:02:53 +0000168
169// disabled by vda: cannot understand how it was supposed to work -
170// cannot fix bugs. That's why you have to explain your non-trivial designs!
171// /* do we generate EXSIG events */
172// int exsig; /* counter */
173 volatile int suppressint; /* counter */
174 volatile /*sig_atomic_t*/ smallint intpending; /* 1 = got SIGINT */
175 /* last pending signal */
176 volatile /*sig_atomic_t*/ smallint pendingsig;
177 smallint exception; /* kind of exception (0..5) */
Denis Vlasenko01631112007-12-16 17:20:38 +0000178 /* exceptions */
Eric Andersenc470f442003-07-28 09:56:35 +0000179#define EXINT 0 /* SIGINT received */
180#define EXERROR 1 /* a generic error */
181#define EXSHELLPROC 2 /* execute a shell procedure */
182#define EXEXEC 3 /* command execution failed */
183#define EXEXIT 4 /* exit the shell */
184#define EXSIG 5 /* trapped signal in wait(1) */
Eric Andersen2870d962001-07-02 17:27:21 +0000185
Denis Vlasenko01631112007-12-16 17:20:38 +0000186 /* trap handler commands */
187 char *trap[NSIG];
188 smallint isloginsh;
189 char nullstr[1]; /* zero length string */
190 /*
191 * Sigmode records the current value of the signal handlers for the various
192 * modes. A value of zero means that the current handler is not known.
193 * S_HARD_IGN indicates that the signal was ignored on entry to the shell,
194 */
195 char sigmode[NSIG - 1];
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +0000196#define S_DFL 1 /* default signal handling (SIG_DFL) */
197#define S_CATCH 2 /* signal is caught */
198#define S_IGN 3 /* signal is ignored (SIG_IGN) */
199#define S_HARD_IGN 4 /* signal is ignored permenantly */
200#define S_RESET 5 /* temporary - to reset a hard ignored sig */
201
Denis Vlasenko01631112007-12-16 17:20:38 +0000202 /* indicates specified signal received */
203 char gotsig[NSIG - 1];
204};
205/* Make it reside in writable memory, yet make compiler understand that it is not going to change. */
206static struct globals_misc *const ptr_to_globals_misc __attribute__ ((section (".data")));
207#define G_misc (*ptr_to_globals_misc)
208#define rootpid (G_misc.rootpid )
209#define shlvl (G_misc.shlvl )
210#define minusc (G_misc.minusc )
211#define curdir (G_misc.curdir )
212#define physdir (G_misc.physdir )
213#define arg0 (G_misc.arg0 )
214#define exception_handler (G_misc.exception_handler)
215#define exception (G_misc.exception )
216#define suppressint (G_misc.suppressint )
217#define intpending (G_misc.intpending )
Denis Vlasenko991a1da2008-02-10 19:02:53 +0000218//#define exsig (G_misc.exsig )
Denis Vlasenko01631112007-12-16 17:20:38 +0000219#define pendingsig (G_misc.pendingsig )
220#define trap (G_misc.trap )
221#define isloginsh (G_misc.isloginsh)
222#define nullstr (G_misc.nullstr )
223#define sigmode (G_misc.sigmode )
224#define gotsig (G_misc.gotsig )
225#define INIT_G_misc() do { \
226 (*(struct globals_misc**)&ptr_to_globals_misc) = xzalloc(sizeof(G_misc)); \
227 curdir = nullstr; \
228 physdir = nullstr; \
229} while (0)
230
231
232/* ============ Interrupts / exceptions */
233
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +0000234/*
Eric Andersen2870d962001-07-02 17:27:21 +0000235 * These macros allow the user to suspend the handling of interrupt signals
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +0000236 * over a period of time. This is similar to SIGHOLD or to sigblock, but
Eric Andersen2870d962001-07-02 17:27:21 +0000237 * much more efficient and portable. (But hacking the kernel is so much
238 * more fun than worrying about efficiency and portability. :-))
239 */
Denis Vlasenkob012b102007-02-19 22:43:01 +0000240#define INT_OFF \
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +0000241 do { \
Eric Andersenc470f442003-07-28 09:56:35 +0000242 suppressint++; \
Glenn L McGrath2f325a02004-08-06 01:49:04 +0000243 xbarrier(); \
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +0000244 } while (0)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000245
246/*
247 * Called to raise an exception. Since C doesn't include exceptions, we
248 * just do a longjmp to the exception handler. The type of exception is
249 * stored in the global variable "exception".
250 */
251static void raise_exception(int) ATTRIBUTE_NORETURN;
252static void
253raise_exception(int e)
254{
255#if DEBUG
Denis Vlasenko2da584f2007-02-19 22:44:05 +0000256 if (exception_handler == NULL)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000257 abort();
258#endif
259 INT_OFF;
260 exception = e;
Denis Vlasenko2da584f2007-02-19 22:44:05 +0000261 longjmp(exception_handler->loc, 1);
Denis Vlasenkob012b102007-02-19 22:43:01 +0000262}
263
264/*
265 * Called from trap.c when a SIGINT is received. (If the user specifies
266 * that SIGINT is to be trapped or ignored using the trap builtin, then
267 * this routine is not called.) Suppressint is nonzero when interrupts
268 * are held using the INT_OFF macro. (The test for iflag is just
269 * defensive programming.)
270 */
271static void raise_interrupt(void) ATTRIBUTE_NORETURN;
272static void
273raise_interrupt(void)
274{
275 int i;
Denis Vlasenko7c139b42007-03-21 20:17:27 +0000276 sigset_t mask;
Denis Vlasenkob012b102007-02-19 22:43:01 +0000277
278 intpending = 0;
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +0000279 /* Signal is not automatically unmasked after it is raised,
280 * do it ourself - unmask all signals */
Denis Vlasenko7c139b42007-03-21 20:17:27 +0000281 sigemptyset(&mask);
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +0000282 sigprocmask(SIG_SETMASK, &mask, NULL);
Denis Vlasenko7c139b42007-03-21 20:17:27 +0000283 /* pendingsig = 0; - now done in onsig() */
284
Denis Vlasenkob012b102007-02-19 22:43:01 +0000285 i = EXSIG;
286 if (gotsig[SIGINT - 1] && !trap[SIGINT]) {
287 if (!(rootshell && iflag)) {
Denis Vlasenko991a1da2008-02-10 19:02:53 +0000288 /* Kill ourself with SIGINT */
Denis Vlasenkob012b102007-02-19 22:43:01 +0000289 signal(SIGINT, SIG_DFL);
290 raise(SIGINT);
291 }
292 i = EXINT;
293 }
294 raise_exception(i);
295 /* NOTREACHED */
296}
297
298#if ENABLE_ASH_OPTIMIZE_FOR_SIZE
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000299static void
300int_on(void)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000301{
302 if (--suppressint == 0 && intpending) {
303 raise_interrupt();
304 }
305}
306#define INT_ON int_on()
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000307static void
308force_int_on(void)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000309{
310 suppressint = 0;
311 if (intpending)
312 raise_interrupt();
313}
314#define FORCE_INT_ON force_int_on()
315#else
316#define INT_ON \
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +0000317 do { \
Denis Vlasenkob012b102007-02-19 22:43:01 +0000318 xbarrier(); \
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +0000319 if (--suppressint == 0 && intpending) \
320 raise_interrupt(); \
321 } while (0)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000322#define FORCE_INT_ON \
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +0000323 do { \
Denis Vlasenkob012b102007-02-19 22:43:01 +0000324 xbarrier(); \
325 suppressint = 0; \
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +0000326 if (intpending) \
327 raise_interrupt(); \
328 } while (0)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000329#endif /* ASH_OPTIMIZE_FOR_SIZE */
330
331#define SAVE_INT(v) ((v) = suppressint)
332
333#define RESTORE_INT(v) \
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +0000334 do { \
Glenn L McGrath2f325a02004-08-06 01:49:04 +0000335 xbarrier(); \
Denis Vlasenko5cedb752007-02-18 19:56:41 +0000336 suppressint = (v); \
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +0000337 if (suppressint == 0 && intpending) \
338 raise_interrupt(); \
339 } while (0)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000340
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +0000341/*
342 * Ignore a signal. Only one usage site - in forkchild()
343 */
344static void
345ignoresig(int signo)
346{
347 if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
348 signal(signo, SIG_IGN);
349 }
350 sigmode[signo - 1] = S_HARD_IGN;
351}
352
353/*
354 * Signal handler. Only one usage site - in setsignal()
355 */
356static void
357onsig(int signo)
358{
359 gotsig[signo - 1] = 1;
Denis Vlasenko7c139b42007-03-21 20:17:27 +0000360 pendingsig = signo;
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +0000361
Denis Vlasenko991a1da2008-02-10 19:02:53 +0000362 if ( /* exsig || */ (signo == SIGINT && !trap[SIGINT])) {
Denis Vlasenko7c139b42007-03-21 20:17:27 +0000363 if (!suppressint) {
364 pendingsig = 0;
Denis Vlasenko991a1da2008-02-10 19:02:53 +0000365 raise_interrupt(); /* does not return */
Denis Vlasenko7c139b42007-03-21 20:17:27 +0000366 }
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +0000367 intpending = 1;
368 }
369}
370
Glenn L McGrath9fef17d2002-08-22 18:41:20 +0000371
Denis Vlasenkobc54cff2007-02-23 01:05:52 +0000372/* ============ Stdout/stderr output */
Eric Andersenc470f442003-07-28 09:56:35 +0000373
Eric Andersenc470f442003-07-28 09:56:35 +0000374static void
Denis Vlasenkob012b102007-02-19 22:43:01 +0000375outstr(const char *p, FILE *file)
Denis Vlasenkoe5570da2007-02-19 22:41:55 +0000376{
Denis Vlasenkob012b102007-02-19 22:43:01 +0000377 INT_OFF;
378 fputs(p, file);
379 INT_ON;
380}
381
382static void
383flush_stdout_stderr(void)
384{
385 INT_OFF;
386 fflush(stdout);
387 fflush(stderr);
388 INT_ON;
389}
390
391static void
392flush_stderr(void)
393{
394 INT_OFF;
395 fflush(stderr);
396 INT_ON;
397}
398
399static void
400outcslow(int c, FILE *dest)
401{
402 INT_OFF;
403 putc(c, dest);
404 fflush(dest);
405 INT_ON;
406}
407
408static int out1fmt(const char *, ...) __attribute__((__format__(__printf__,1,2)));
409static int
410out1fmt(const char *fmt, ...)
411{
412 va_list ap;
413 int r;
414
415 INT_OFF;
416 va_start(ap, fmt);
417 r = vprintf(fmt, ap);
418 va_end(ap);
419 INT_ON;
420 return r;
421}
422
423static int fmtstr(char *, size_t, const char *, ...) __attribute__((__format__(__printf__,3,4)));
424static int
425fmtstr(char *outbuf, size_t length, const char *fmt, ...)
426{
427 va_list ap;
428 int ret;
429
430 va_start(ap, fmt);
431 INT_OFF;
432 ret = vsnprintf(outbuf, length, fmt, ap);
433 va_end(ap);
434 INT_ON;
435 return ret;
436}
437
438static void
439out1str(const char *p)
440{
441 outstr(p, stdout);
442}
443
444static void
445out2str(const char *p)
446{
447 outstr(p, stderr);
448 flush_stderr();
449}
450
451
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +0000452/* ============ Parser structures */
Denis Vlasenko4d2183b2007-02-23 01:05:38 +0000453
Denis Vlasenko5651bfc2007-02-23 21:08:58 +0000454/* control characters in argument strings */
455#define CTLESC '\201' /* escape next character */
456#define CTLVAR '\202' /* variable defn */
457#define CTLENDVAR '\203'
458#define CTLBACKQ '\204'
459#define CTLQUOTE 01 /* ored with CTLBACKQ code if in quotes */
460/* CTLBACKQ | CTLQUOTE == '\205' */
461#define CTLARI '\206' /* arithmetic expression */
462#define CTLENDARI '\207'
463#define CTLQUOTEMARK '\210'
464
465/* variable substitution byte (follows CTLVAR) */
466#define VSTYPE 0x0f /* type of variable substitution */
467#define VSNUL 0x10 /* colon--treat the empty string as unset */
468#define VSQUOTE 0x80 /* inside double quotes--suppress splitting */
469
470/* values of VSTYPE field */
471#define VSNORMAL 0x1 /* normal variable: $var or ${var} */
472#define VSMINUS 0x2 /* ${var-text} */
473#define VSPLUS 0x3 /* ${var+text} */
474#define VSQUESTION 0x4 /* ${var?message} */
475#define VSASSIGN 0x5 /* ${var=text} */
476#define VSTRIMRIGHT 0x6 /* ${var%pattern} */
477#define VSTRIMRIGHTMAX 0x7 /* ${var%%pattern} */
478#define VSTRIMLEFT 0x8 /* ${var#pattern} */
479#define VSTRIMLEFTMAX 0x9 /* ${var##pattern} */
480#define VSLENGTH 0xa /* ${#var} */
481
Denis Vlasenko6ca409e2007-08-12 20:58:27 +0000482static const char dolatstr[] ALIGN1 = {
483 CTLVAR, VSNORMAL|VSQUOTE, '@', '=', '\0'
484};
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +0000485
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000486#define NCMD 0
487#define NPIPE 1
488#define NREDIR 2
489#define NBACKGND 3
490#define NSUBSHELL 4
491#define NAND 5
492#define NOR 6
493#define NSEMI 7
494#define NIF 8
495#define NWHILE 9
496#define NUNTIL 10
497#define NFOR 11
498#define NCASE 12
499#define NCLIST 13
500#define NDEFUN 14
501#define NARG 15
502#define NTO 16
503#define NCLOBBER 17
504#define NFROM 18
505#define NFROMTO 19
506#define NAPPEND 20
507#define NTOFD 21
508#define NFROMFD 22
509#define NHERE 23
510#define NXHERE 24
511#define NNOT 25
512
513union node;
514
515struct ncmd {
516 int type;
517 union node *assign;
518 union node *args;
519 union node *redirect;
520};
521
522struct npipe {
523 int type;
524 int backgnd;
525 struct nodelist *cmdlist;
526};
527
528struct nredir {
529 int type;
530 union node *n;
531 union node *redirect;
532};
533
534struct nbinary {
535 int type;
536 union node *ch1;
537 union node *ch2;
538};
539
540struct nif {
541 int type;
542 union node *test;
543 union node *ifpart;
544 union node *elsepart;
545};
546
547struct nfor {
548 int type;
549 union node *args;
550 union node *body;
551 char *var;
552};
553
554struct ncase {
555 int type;
556 union node *expr;
557 union node *cases;
558};
559
560struct nclist {
561 int type;
562 union node *next;
563 union node *pattern;
564 union node *body;
565};
566
567struct narg {
568 int type;
569 union node *next;
570 char *text;
571 struct nodelist *backquote;
572};
573
574struct nfile {
575 int type;
576 union node *next;
577 int fd;
578 union node *fname;
579 char *expfname;
580};
581
582struct ndup {
583 int type;
584 union node *next;
585 int fd;
586 int dupfd;
587 union node *vname;
588};
589
590struct nhere {
591 int type;
592 union node *next;
593 int fd;
594 union node *doc;
595};
596
597struct nnot {
598 int type;
599 union node *com;
600};
601
602union node {
603 int type;
604 struct ncmd ncmd;
605 struct npipe npipe;
606 struct nredir nredir;
607 struct nbinary nbinary;
608 struct nif nif;
609 struct nfor nfor;
610 struct ncase ncase;
611 struct nclist nclist;
612 struct narg narg;
613 struct nfile nfile;
614 struct ndup ndup;
615 struct nhere nhere;
616 struct nnot nnot;
617};
618
619struct nodelist {
620 struct nodelist *next;
621 union node *n;
622};
623
624struct funcnode {
625 int count;
626 union node n;
627};
628
Denis Vlasenko5651bfc2007-02-23 21:08:58 +0000629/*
630 * Free a parse tree.
631 */
632static void
633freefunc(struct funcnode *f)
634{
635 if (f && --f->count < 0)
636 free(f);
637}
638
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000639
640/* ============ Debugging output */
641
642#if DEBUG
643
644static FILE *tracefile;
645
646static void
647trace_printf(const char *fmt, ...)
648{
649 va_list va;
650
651 if (debug != 1)
652 return;
653 va_start(va, fmt);
654 vfprintf(tracefile, fmt, va);
655 va_end(va);
656}
657
658static void
659trace_vprintf(const char *fmt, va_list va)
660{
661 if (debug != 1)
662 return;
663 vfprintf(tracefile, fmt, va);
664}
665
666static void
667trace_puts(const char *s)
668{
669 if (debug != 1)
670 return;
671 fputs(s, tracefile);
672}
673
674static void
675trace_puts_quoted(char *s)
676{
677 char *p;
678 char c;
679
680 if (debug != 1)
681 return;
682 putc('"', tracefile);
683 for (p = s; *p; p++) {
684 switch (*p) {
685 case '\n': c = 'n'; goto backslash;
686 case '\t': c = 't'; goto backslash;
687 case '\r': c = 'r'; goto backslash;
688 case '"': c = '"'; goto backslash;
689 case '\\': c = '\\'; goto backslash;
690 case CTLESC: c = 'e'; goto backslash;
691 case CTLVAR: c = 'v'; goto backslash;
692 case CTLVAR+CTLQUOTE: c = 'V'; goto backslash;
693 case CTLBACKQ: c = 'q'; goto backslash;
694 case CTLBACKQ+CTLQUOTE: c = 'Q'; goto backslash;
695 backslash:
696 putc('\\', tracefile);
697 putc(c, tracefile);
698 break;
699 default:
700 if (*p >= ' ' && *p <= '~')
701 putc(*p, tracefile);
702 else {
703 putc('\\', tracefile);
704 putc(*p >> 6 & 03, tracefile);
705 putc(*p >> 3 & 07, tracefile);
706 putc(*p & 07, tracefile);
707 }
708 break;
709 }
710 }
711 putc('"', tracefile);
712}
713
714static void
715trace_puts_args(char **ap)
716{
717 if (debug != 1)
718 return;
719 if (!*ap)
720 return;
721 while (1) {
722 trace_puts_quoted(*ap);
723 if (!*++ap) {
724 putc('\n', tracefile);
725 break;
726 }
727 putc(' ', tracefile);
728 }
729}
730
731static void
732opentrace(void)
733{
734 char s[100];
735#ifdef O_APPEND
736 int flags;
737#endif
738
739 if (debug != 1) {
740 if (tracefile)
741 fflush(tracefile);
742 /* leave open because libedit might be using it */
743 return;
744 }
745 strcpy(s, "./trace");
746 if (tracefile) {
747 if (!freopen(s, "a", tracefile)) {
748 fprintf(stderr, "Can't re-open %s\n", s);
749 debug = 0;
750 return;
751 }
752 } else {
753 tracefile = fopen(s, "a");
754 if (tracefile == NULL) {
755 fprintf(stderr, "Can't open %s\n", s);
756 debug = 0;
757 return;
758 }
759 }
760#ifdef O_APPEND
Denis Vlasenkod37f2222007-08-19 13:42:08 +0000761 flags = fcntl(fileno(tracefile), F_GETFL);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000762 if (flags >= 0)
763 fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
764#endif
765 setlinebuf(tracefile);
766 fputs("\nTracing started.\n", tracefile);
767}
768
769static void
770indent(int amount, char *pfx, FILE *fp)
771{
772 int i;
773
774 for (i = 0; i < amount; i++) {
775 if (pfx && i == amount - 1)
776 fputs(pfx, fp);
777 putc('\t', fp);
778 }
779}
780
781/* little circular references here... */
782static void shtree(union node *n, int ind, char *pfx, FILE *fp);
783
784static void
785sharg(union node *arg, FILE *fp)
786{
787 char *p;
788 struct nodelist *bqlist;
789 int subtype;
790
791 if (arg->type != NARG) {
792 out1fmt("<node type %d>\n", arg->type);
793 abort();
794 }
795 bqlist = arg->narg.backquote;
796 for (p = arg->narg.text; *p; p++) {
797 switch (*p) {
798 case CTLESC:
799 putc(*++p, fp);
800 break;
801 case CTLVAR:
802 putc('$', fp);
803 putc('{', fp);
804 subtype = *++p;
805 if (subtype == VSLENGTH)
806 putc('#', fp);
807
808 while (*p != '=')
809 putc(*p++, fp);
810
811 if (subtype & VSNUL)
812 putc(':', fp);
813
814 switch (subtype & VSTYPE) {
815 case VSNORMAL:
816 putc('}', fp);
817 break;
818 case VSMINUS:
819 putc('-', fp);
820 break;
821 case VSPLUS:
822 putc('+', fp);
823 break;
824 case VSQUESTION:
825 putc('?', fp);
826 break;
827 case VSASSIGN:
828 putc('=', fp);
829 break;
830 case VSTRIMLEFT:
831 putc('#', fp);
832 break;
833 case VSTRIMLEFTMAX:
834 putc('#', fp);
835 putc('#', fp);
836 break;
837 case VSTRIMRIGHT:
838 putc('%', fp);
839 break;
840 case VSTRIMRIGHTMAX:
841 putc('%', fp);
842 putc('%', fp);
843 break;
844 case VSLENGTH:
845 break;
846 default:
847 out1fmt("<subtype %d>", subtype);
848 }
849 break;
850 case CTLENDVAR:
851 putc('}', fp);
852 break;
853 case CTLBACKQ:
854 case CTLBACKQ|CTLQUOTE:
855 putc('$', fp);
856 putc('(', fp);
857 shtree(bqlist->n, -1, NULL, fp);
858 putc(')', fp);
859 break;
860 default:
861 putc(*p, fp);
862 break;
863 }
864 }
865}
866
867static void
868shcmd(union node *cmd, FILE *fp)
869{
870 union node *np;
871 int first;
872 const char *s;
873 int dftfd;
874
875 first = 1;
876 for (np = cmd->ncmd.args; np; np = np->narg.next) {
Denis Vlasenko40ba9982007-07-14 00:48:29 +0000877 if (!first)
878 putc(' ', fp);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000879 sharg(np, fp);
880 first = 0;
881 }
882 for (np = cmd->ncmd.redirect; np; np = np->nfile.next) {
Denis Vlasenko40ba9982007-07-14 00:48:29 +0000883 if (!first)
884 putc(' ', fp);
885 dftfd = 0;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000886 switch (np->nfile.type) {
Denis Vlasenko40ba9982007-07-14 00:48:29 +0000887 case NTO: s = ">>"+1; dftfd = 1; break;
888 case NCLOBBER: s = ">|"; dftfd = 1; break;
889 case NAPPEND: s = ">>"; dftfd = 1; break;
890 case NTOFD: s = ">&"; dftfd = 1; break;
891 case NFROM: s = "<"; break;
892 case NFROMFD: s = "<&"; break;
893 case NFROMTO: s = "<>"; break;
894 default: s = "*error*"; break;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000895 }
896 if (np->nfile.fd != dftfd)
897 fprintf(fp, "%d", np->nfile.fd);
898 fputs(s, fp);
899 if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
900 fprintf(fp, "%d", np->ndup.dupfd);
901 } else {
902 sharg(np->nfile.fname, fp);
903 }
904 first = 0;
905 }
906}
907
908static void
909shtree(union node *n, int ind, char *pfx, FILE *fp)
910{
911 struct nodelist *lp;
912 const char *s;
913
914 if (n == NULL)
915 return;
916
917 indent(ind, pfx, fp);
918 switch (n->type) {
919 case NSEMI:
920 s = "; ";
921 goto binop;
922 case NAND:
923 s = " && ";
924 goto binop;
925 case NOR:
926 s = " || ";
927 binop:
928 shtree(n->nbinary.ch1, ind, NULL, fp);
929 /* if (ind < 0) */
930 fputs(s, fp);
931 shtree(n->nbinary.ch2, ind, NULL, fp);
932 break;
933 case NCMD:
934 shcmd(n, fp);
935 if (ind >= 0)
936 putc('\n', fp);
937 break;
938 case NPIPE:
939 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
940 shcmd(lp->n, fp);
941 if (lp->next)
942 fputs(" | ", fp);
943 }
944 if (n->npipe.backgnd)
945 fputs(" &", fp);
946 if (ind >= 0)
947 putc('\n', fp);
948 break;
949 default:
950 fprintf(fp, "<node type %d>", n->type);
951 if (ind >= 0)
952 putc('\n', fp);
953 break;
954 }
955}
956
957static void
958showtree(union node *n)
959{
960 trace_puts("showtree called\n");
961 shtree(n, 1, NULL, stdout);
962}
963
964#define TRACE(param) trace_printf param
965#define TRACEV(param) trace_vprintf param
966
967#else
968
969#define TRACE(param)
970#define TRACEV(param)
971
972#endif /* DEBUG */
973
974
Denis Vlasenko5651bfc2007-02-23 21:08:58 +0000975/* ============ Parser data */
976
977/*
Denis Vlasenkob012b102007-02-19 22:43:01 +0000978 * ash_vmsg() needs parsefile->fd, hence parsefile definition is moved up.
979 */
Denis Vlasenkoaa744452007-02-23 01:04:22 +0000980struct strlist {
981 struct strlist *next;
982 char *text;
983};
984
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000985#if ENABLE_ASH_ALIAS
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000986struct alias;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000987#endif
988
Denis Vlasenkob012b102007-02-19 22:43:01 +0000989struct strpush {
990 struct strpush *prev; /* preceding string on stack */
991 char *prevstring;
992 int prevnleft;
993#if ENABLE_ASH_ALIAS
994 struct alias *ap; /* if push was associated with an alias */
995#endif
996 char *string; /* remember the string since it may change */
997};
998
999struct parsefile {
1000 struct parsefile *prev; /* preceding file on stack */
1001 int linno; /* current line */
1002 int fd; /* file descriptor (or -1 if string) */
1003 int nleft; /* number of chars left in this line */
1004 int lleft; /* number of chars left in this buffer */
1005 char *nextc; /* next char in buffer */
1006 char *buf; /* input buffer */
1007 struct strpush *strpush; /* for pushing strings at this level */
1008 struct strpush basestrpush; /* so pushing one is fast */
1009};
1010
1011static struct parsefile basepf; /* top level input file */
1012static struct parsefile *parsefile = &basepf; /* current input file */
1013static int startlinno; /* line # where last token started */
1014static char *commandname; /* currently executing command */
1015static struct strlist *cmdenviron; /* environment for builtin command */
1016static int exitstatus; /* exit status of last command */
Denis Vlasenkob012b102007-02-19 22:43:01 +00001017
1018
1019/* ============ Message printing */
1020
1021static void
1022ash_vmsg(const char *msg, va_list ap)
1023{
1024 fprintf(stderr, "%s: ", arg0);
1025 if (commandname) {
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00001026 if (strcmp(arg0, commandname))
1027 fprintf(stderr, "%s: ", commandname);
1028 if (!iflag || parsefile->fd)
1029 fprintf(stderr, "line %d: ", startlinno);
Eric Andersenc470f442003-07-28 09:56:35 +00001030 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00001031 vfprintf(stderr, msg, ap);
1032 outcslow('\n', stderr);
Eric Andersenc470f442003-07-28 09:56:35 +00001033}
Denis Vlasenkob012b102007-02-19 22:43:01 +00001034
1035/*
1036 * Exverror is called to raise the error exception. If the second argument
1037 * is not NULL then error prints an error message using printf style
1038 * formatting. It then raises the error exception.
1039 */
1040static void ash_vmsg_and_raise(int, const char *, va_list) ATTRIBUTE_NORETURN;
1041static void
1042ash_vmsg_and_raise(int cond, const char *msg, va_list ap)
Eric Andersenc470f442003-07-28 09:56:35 +00001043{
Denis Vlasenkob012b102007-02-19 22:43:01 +00001044#if DEBUG
1045 if (msg) {
1046 TRACE(("ash_vmsg_and_raise(%d, \"", cond));
1047 TRACEV((msg, ap));
1048 TRACE(("\") pid=%d\n", getpid()));
1049 } else
1050 TRACE(("ash_vmsg_and_raise(%d, NULL) pid=%d\n", cond, getpid()));
1051 if (msg)
1052#endif
1053 ash_vmsg(msg, ap);
1054
1055 flush_stdout_stderr();
1056 raise_exception(cond);
1057 /* NOTREACHED */
Eric Andersenc470f442003-07-28 09:56:35 +00001058}
Denis Vlasenkob012b102007-02-19 22:43:01 +00001059
1060static void ash_msg_and_raise_error(const char *, ...) ATTRIBUTE_NORETURN;
1061static void
1062ash_msg_and_raise_error(const char *msg, ...)
1063{
1064 va_list ap;
1065
1066 va_start(ap, msg);
1067 ash_vmsg_and_raise(EXERROR, msg, ap);
1068 /* NOTREACHED */
1069 va_end(ap);
1070}
1071
1072static void ash_msg_and_raise(int, const char *, ...) ATTRIBUTE_NORETURN;
1073static void
1074ash_msg_and_raise(int cond, const char *msg, ...)
1075{
1076 va_list ap;
1077
1078 va_start(ap, msg);
1079 ash_vmsg_and_raise(cond, msg, ap);
1080 /* NOTREACHED */
1081 va_end(ap);
1082}
1083
1084/*
1085 * error/warning routines for external builtins
1086 */
1087static void
1088ash_msg(const char *fmt, ...)
1089{
1090 va_list ap;
1091
1092 va_start(ap, fmt);
1093 ash_vmsg(fmt, ap);
1094 va_end(ap);
1095}
1096
1097/*
1098 * Return a string describing an error. The returned string may be a
1099 * pointer to a static buffer that will be overwritten on the next call.
1100 * Action describes the operation that got the error.
1101 */
1102static const char *
1103errmsg(int e, const char *em)
1104{
1105 if (e == ENOENT || e == ENOTDIR) {
1106 return em;
1107 }
1108 return strerror(e);
1109}
1110
1111
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001112/* ============ Memory allocation */
1113
1114/*
1115 * It appears that grabstackstr() will barf with such alignments
1116 * because stalloc() will return a string allocated in a new stackblock.
1117 */
1118#define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
1119enum {
1120 /* Most machines require the value returned from malloc to be aligned
1121 * in some way. The following macro will get this right
1122 * on many machines. */
1123 SHELL_SIZE = sizeof(union {int i; char *cp; double d; }) - 1,
1124 /* Minimum size of a block */
Denis Vlasenko01631112007-12-16 17:20:38 +00001125 MINSIZE = SHELL_ALIGN(504),
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001126};
1127
1128struct stack_block {
1129 struct stack_block *prev;
1130 char space[MINSIZE];
1131};
1132
1133struct stackmark {
1134 struct stack_block *stackp;
1135 char *stacknxt;
1136 size_t stacknleft;
1137 struct stackmark *marknext;
1138};
1139
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001140
Denis Vlasenko01631112007-12-16 17:20:38 +00001141struct globals_memstack {
1142 struct stack_block *g_stackp; // = &stackbase;
1143 struct stackmark *markp;
1144 char *g_stacknxt; // = stackbase.space;
1145 char *sstrend; // = stackbase.space + MINSIZE;
1146 size_t g_stacknleft; // = MINSIZE;
1147 int herefd; // = -1;
1148 struct stack_block stackbase;
1149};
1150/* Make it reside in writable memory, yet make compiler understand that it is not going to change. */
1151static struct globals_memstack *const ptr_to_globals_memstack __attribute__ ((section (".data")));
1152#define G_memstack (*ptr_to_globals_memstack)
1153#define g_stackp (G_memstack.g_stackp )
1154#define markp (G_memstack.markp )
1155#define g_stacknxt (G_memstack.g_stacknxt )
1156#define sstrend (G_memstack.sstrend )
1157#define g_stacknleft (G_memstack.g_stacknleft)
1158#define herefd (G_memstack.herefd )
1159#define stackbase (G_memstack.stackbase )
1160#define INIT_G_memstack() do { \
1161 (*(struct globals_memstack**)&ptr_to_globals_memstack) = xzalloc(sizeof(G_memstack)); \
1162 g_stackp = &stackbase; \
1163 g_stacknxt = stackbase.space; \
1164 g_stacknleft = MINSIZE; \
1165 sstrend = stackbase.space + MINSIZE; \
1166 herefd = -1; \
1167} while (0)
1168
1169#define stackblock() ((void *)g_stacknxt)
1170#define stackblocksize() g_stacknleft
1171
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001172
1173static void *
1174ckrealloc(void * p, size_t nbytes)
1175{
1176 p = realloc(p, nbytes);
1177 if (!p)
1178 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1179 return p;
1180}
1181
1182static void *
1183ckmalloc(size_t nbytes)
1184{
1185 return ckrealloc(NULL, nbytes);
1186}
1187
Denis Vlasenko597906c2008-02-20 16:38:54 +00001188static void *
1189ckzalloc(size_t nbytes)
1190{
1191 return memset(ckmalloc(nbytes), 0, nbytes);
1192}
1193
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001194/*
1195 * Make a copy of a string in safe storage.
1196 */
1197static char *
1198ckstrdup(const char *s)
1199{
1200 char *p = strdup(s);
1201 if (!p)
1202 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1203 return p;
1204}
1205
1206/*
1207 * Parse trees for commands are allocated in lifo order, so we use a stack
1208 * to make this more efficient, and also to avoid all sorts of exception
1209 * handling code to handle interrupts in the middle of a parse.
1210 *
1211 * The size 504 was chosen because the Ultrix malloc handles that size
1212 * well.
1213 */
1214static void *
1215stalloc(size_t nbytes)
1216{
1217 char *p;
1218 size_t aligned;
1219
1220 aligned = SHELL_ALIGN(nbytes);
Denis Vlasenko01631112007-12-16 17:20:38 +00001221 if (aligned > g_stacknleft) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001222 size_t len;
1223 size_t blocksize;
1224 struct stack_block *sp;
1225
1226 blocksize = aligned;
1227 if (blocksize < MINSIZE)
1228 blocksize = MINSIZE;
1229 len = sizeof(struct stack_block) - MINSIZE + blocksize;
1230 if (len < blocksize)
1231 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1232 INT_OFF;
1233 sp = ckmalloc(len);
Denis Vlasenko01631112007-12-16 17:20:38 +00001234 sp->prev = g_stackp;
1235 g_stacknxt = sp->space;
1236 g_stacknleft = blocksize;
1237 sstrend = g_stacknxt + blocksize;
1238 g_stackp = sp;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001239 INT_ON;
1240 }
Denis Vlasenko01631112007-12-16 17:20:38 +00001241 p = g_stacknxt;
1242 g_stacknxt += aligned;
1243 g_stacknleft -= aligned;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001244 return p;
1245}
1246
Denis Vlasenko597906c2008-02-20 16:38:54 +00001247static void *
1248stzalloc(size_t nbytes)
1249{
1250 return memset(stalloc(nbytes), 0, nbytes);
1251}
1252
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001253static void
1254stunalloc(void *p)
1255{
1256#if DEBUG
Denis Vlasenko01631112007-12-16 17:20:38 +00001257 if (!p || (g_stacknxt < (char *)p) || ((char *)p < g_stackp->space)) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001258 write(2, "stunalloc\n", 10);
1259 abort();
1260 }
1261#endif
Denis Vlasenko01631112007-12-16 17:20:38 +00001262 g_stacknleft += g_stacknxt - (char *)p;
1263 g_stacknxt = p;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001264}
1265
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001266/*
1267 * Like strdup but works with the ash stack.
1268 */
1269static char *
1270ststrdup(const char *p)
1271{
1272 size_t len = strlen(p) + 1;
1273 return memcpy(stalloc(len), p, len);
1274}
1275
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001276static void
1277setstackmark(struct stackmark *mark)
1278{
Denis Vlasenko01631112007-12-16 17:20:38 +00001279 mark->stackp = g_stackp;
1280 mark->stacknxt = g_stacknxt;
1281 mark->stacknleft = g_stacknleft;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001282 mark->marknext = markp;
1283 markp = mark;
1284}
1285
1286static void
1287popstackmark(struct stackmark *mark)
1288{
1289 struct stack_block *sp;
1290
Denis Vlasenko93ebd4f2007-03-13 20:55:36 +00001291 if (!mark->stackp)
1292 return;
1293
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001294 INT_OFF;
1295 markp = mark->marknext;
Denis Vlasenko01631112007-12-16 17:20:38 +00001296 while (g_stackp != mark->stackp) {
1297 sp = g_stackp;
1298 g_stackp = sp->prev;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001299 free(sp);
1300 }
Denis Vlasenko01631112007-12-16 17:20:38 +00001301 g_stacknxt = mark->stacknxt;
1302 g_stacknleft = mark->stacknleft;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001303 sstrend = mark->stacknxt + mark->stacknleft;
1304 INT_ON;
1305}
1306
1307/*
1308 * When the parser reads in a string, it wants to stick the string on the
1309 * stack and only adjust the stack pointer when it knows how big the
1310 * string is. Stackblock (defined in stack.h) returns a pointer to a block
1311 * of space on top of the stack and stackblocklen returns the length of
1312 * this block. Growstackblock will grow this space by at least one byte,
1313 * possibly moving it (like realloc). Grabstackblock actually allocates the
1314 * part of the block that has been used.
1315 */
1316static void
1317growstackblock(void)
1318{
1319 size_t newlen;
1320
Denis Vlasenko01631112007-12-16 17:20:38 +00001321 newlen = g_stacknleft * 2;
1322 if (newlen < g_stacknleft)
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001323 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1324 if (newlen < 128)
1325 newlen += 128;
1326
Denis Vlasenko01631112007-12-16 17:20:38 +00001327 if (g_stacknxt == g_stackp->space && g_stackp != &stackbase) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001328 struct stack_block *oldstackp;
1329 struct stackmark *xmark;
1330 struct stack_block *sp;
1331 struct stack_block *prevstackp;
1332 size_t grosslen;
1333
1334 INT_OFF;
Denis Vlasenko01631112007-12-16 17:20:38 +00001335 oldstackp = g_stackp;
1336 sp = g_stackp;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001337 prevstackp = sp->prev;
1338 grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
1339 sp = ckrealloc(sp, grosslen);
1340 sp->prev = prevstackp;
Denis Vlasenko01631112007-12-16 17:20:38 +00001341 g_stackp = sp;
1342 g_stacknxt = sp->space;
1343 g_stacknleft = newlen;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001344 sstrend = sp->space + newlen;
1345
1346 /*
1347 * Stack marks pointing to the start of the old block
1348 * must be relocated to point to the new block
1349 */
1350 xmark = markp;
1351 while (xmark != NULL && xmark->stackp == oldstackp) {
Denis Vlasenko01631112007-12-16 17:20:38 +00001352 xmark->stackp = g_stackp;
1353 xmark->stacknxt = g_stacknxt;
1354 xmark->stacknleft = g_stacknleft;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001355 xmark = xmark->marknext;
1356 }
1357 INT_ON;
1358 } else {
Denis Vlasenko01631112007-12-16 17:20:38 +00001359 char *oldspace = g_stacknxt;
1360 int oldlen = g_stacknleft;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001361 char *p = stalloc(newlen);
1362
1363 /* free the space we just allocated */
Denis Vlasenko01631112007-12-16 17:20:38 +00001364 g_stacknxt = memcpy(p, oldspace, oldlen);
1365 g_stacknleft += newlen;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001366 }
1367}
1368
1369static void
1370grabstackblock(size_t len)
1371{
1372 len = SHELL_ALIGN(len);
Denis Vlasenko01631112007-12-16 17:20:38 +00001373 g_stacknxt += len;
1374 g_stacknleft -= len;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001375}
1376
1377/*
1378 * The following routines are somewhat easier to use than the above.
1379 * The user declares a variable of type STACKSTR, which may be declared
1380 * to be a register. The macro STARTSTACKSTR initializes things. Then
1381 * the user uses the macro STPUTC to add characters to the string. In
1382 * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
1383 * grown as necessary. When the user is done, she can just leave the
1384 * string there and refer to it using stackblock(). Or she can allocate
1385 * the space for it using grabstackstr(). If it is necessary to allow
1386 * someone else to use the stack temporarily and then continue to grow
1387 * the string, the user should use grabstack to allocate the space, and
1388 * then call ungrabstr(p) to return to the previous mode of operation.
1389 *
1390 * USTPUTC is like STPUTC except that it doesn't check for overflow.
1391 * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
1392 * is space for at least one character.
1393 */
1394static void *
1395growstackstr(void)
1396{
1397 size_t len = stackblocksize();
1398 if (herefd >= 0 && len >= 1024) {
1399 full_write(herefd, stackblock(), len);
1400 return stackblock();
1401 }
1402 growstackblock();
1403 return stackblock() + len;
1404}
1405
1406/*
1407 * Called from CHECKSTRSPACE.
1408 */
1409static char *
1410makestrspace(size_t newlen, char *p)
1411{
Denis Vlasenko01631112007-12-16 17:20:38 +00001412 size_t len = p - g_stacknxt;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001413 size_t size = stackblocksize();
1414
1415 for (;;) {
1416 size_t nleft;
1417
1418 size = stackblocksize();
1419 nleft = size - len;
1420 if (nleft >= newlen)
1421 break;
1422 growstackblock();
1423 }
1424 return stackblock() + len;
1425}
1426
1427static char *
1428stack_nputstr(const char *s, size_t n, char *p)
1429{
1430 p = makestrspace(n, p);
1431 p = memcpy(p, s, n) + n;
1432 return p;
1433}
1434
1435static char *
1436stack_putstr(const char *s, char *p)
1437{
1438 return stack_nputstr(s, strlen(s), p);
1439}
1440
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001441static char *
1442_STPUTC(int c, char *p)
1443{
1444 if (p == sstrend)
1445 p = growstackstr();
1446 *p++ = c;
1447 return p;
1448}
1449
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00001450#define STARTSTACKSTR(p) ((p) = stackblock())
1451#define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001452#define CHECKSTRSPACE(n, p) \
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00001453 do { \
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001454 char *q = (p); \
1455 size_t l = (n); \
1456 size_t m = sstrend - q; \
1457 if (l > m) \
1458 (p) = makestrspace(l, q); \
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00001459 } while (0)
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001460#define USTPUTC(c, p) (*p++ = (c))
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00001461#define STACKSTRNUL(p) \
1462 do { \
1463 if ((p) == sstrend) \
1464 p = growstackstr(); \
1465 *p = '\0'; \
1466 } while (0)
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001467#define STUNPUTC(p) (--p)
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00001468#define STTOPC(p) (p[-1])
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001469#define STADJUST(amount, p) (p += (amount))
1470
1471#define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
1472#define ungrabstackstr(s, p) stunalloc((s))
1473#define stackstrend() ((void *)sstrend)
1474
1475
1476/* ============ String helpers */
1477
1478/*
1479 * prefix -- see if pfx is a prefix of string.
1480 */
1481static char *
1482prefix(const char *string, const char *pfx)
1483{
1484 while (*pfx) {
1485 if (*pfx++ != *string++)
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00001486 return NULL;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001487 }
1488 return (char *) string;
1489}
1490
1491/*
1492 * Check for a valid number. This should be elsewhere.
1493 */
1494static int
1495is_number(const char *p)
1496{
1497 do {
1498 if (!isdigit(*p))
1499 return 0;
1500 } while (*++p != '\0');
1501 return 1;
1502}
1503
1504/*
1505 * Convert a string of digits to an integer, printing an error message on
1506 * failure.
1507 */
1508static int
1509number(const char *s)
1510{
1511 if (!is_number(s))
1512 ash_msg_and_raise_error(illnum, s);
1513 return atoi(s);
1514}
1515
1516/*
1517 * Produce a possibly single quoted string suitable as input to the shell.
1518 * The return string is allocated on the stack.
1519 */
1520static char *
1521single_quote(const char *s)
1522{
1523 char *p;
1524
1525 STARTSTACKSTR(p);
1526
1527 do {
1528 char *q;
1529 size_t len;
1530
1531 len = strchrnul(s, '\'') - s;
1532
1533 q = p = makestrspace(len + 3, p);
1534
1535 *q++ = '\'';
1536 q = memcpy(q, s, len) + len;
1537 *q++ = '\'';
1538 s += len;
1539
1540 STADJUST(q - p, p);
1541
1542 len = strspn(s, "'");
1543 if (!len)
1544 break;
1545
1546 q = p = makestrspace(len + 3, p);
1547
1548 *q++ = '"';
1549 q = memcpy(q, s, len) + len;
1550 *q++ = '"';
1551 s += len;
1552
1553 STADJUST(q - p, p);
1554 } while (*s);
1555
1556 USTPUTC(0, p);
1557
1558 return stackblock();
1559}
1560
1561
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00001562/* ============ nextopt */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001563
1564static char **argptr; /* argument list for builtin commands */
1565static char *optionarg; /* set by nextopt (like getopt) */
1566static char *optptr; /* used by nextopt */
1567
1568/*
1569 * XXX - should get rid of. have all builtins use getopt(3). the
1570 * library getopt must have the BSD extension static variable "optreset"
1571 * otherwise it can't be used within the shell safely.
1572 *
1573 * Standard option processing (a la getopt) for builtin routines. The
1574 * only argument that is passed to nextopt is the option string; the
1575 * other arguments are unnecessary. It return the character, or '\0' on
1576 * end of input.
1577 */
1578static int
1579nextopt(const char *optstring)
1580{
1581 char *p;
1582 const char *q;
1583 char c;
1584
1585 p = optptr;
1586 if (p == NULL || *p == '\0') {
1587 p = *argptr;
1588 if (p == NULL || *p != '-' || *++p == '\0')
1589 return '\0';
1590 argptr++;
1591 if (LONE_DASH(p)) /* check for "--" */
1592 return '\0';
1593 }
1594 c = *p++;
1595 for (q = optstring; *q != c; ) {
1596 if (*q == '\0')
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00001597 ash_msg_and_raise_error("illegal option -%c", c);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001598 if (*++q == ':')
1599 q++;
1600 }
1601 if (*++q == ':') {
1602 if (*p == '\0' && (p = *argptr++) == NULL)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00001603 ash_msg_and_raise_error("no arg for -%c option", c);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001604 optionarg = p;
1605 p = NULL;
1606 }
1607 optptr = p;
1608 return c;
1609}
1610
1611
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00001612/* ============ Math support definitions */
1613
1614#if ENABLE_ASH_MATH_SUPPORT_64
1615typedef int64_t arith_t;
1616#define arith_t_type long long
1617#else
1618typedef long arith_t;
1619#define arith_t_type long
1620#endif
1621
1622#if ENABLE_ASH_MATH_SUPPORT
1623static arith_t dash_arith(const char *);
1624static arith_t arith(const char *expr, int *perrcode);
1625#endif
1626
1627#if ENABLE_ASH_RANDOM_SUPPORT
1628static unsigned long rseed;
1629#ifndef DYNAMIC_VAR
1630#define DYNAMIC_VAR
1631#endif
1632#endif
1633
1634
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00001635/* ============ Shell variables */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001636
Denis Vlasenko01631112007-12-16 17:20:38 +00001637/*
1638 * The parsefile structure pointed to by the global variable parsefile
1639 * contains information about the current file being read.
1640 */
1641struct redirtab {
1642 struct redirtab *next;
1643 int renamed[10];
1644 int nullredirs;
1645};
1646
1647struct shparam {
1648 int nparam; /* # of positional parameters (without $0) */
1649#if ENABLE_ASH_GETOPTS
1650 int optind; /* next parameter to be processed by getopts */
1651 int optoff; /* used by getopts */
1652#endif
1653 unsigned char malloced; /* if parameter list dynamically allocated */
1654 char **p; /* parameter list */
1655};
1656
1657/*
1658 * Free the list of positional parameters.
1659 */
1660static void
1661freeparam(volatile struct shparam *param)
1662{
1663 char **ap;
1664
1665 if (param->malloced) {
1666 for (ap = param->p; *ap; ap++)
1667 free(*ap);
1668 free(param->p);
1669 }
1670}
1671
1672#if ENABLE_ASH_GETOPTS
1673static void getoptsreset(const char *value);
1674#endif
1675
1676struct var {
1677 struct var *next; /* next entry in hash list */
1678 int flags; /* flags are defined above */
1679 const char *text; /* name=value */
1680 void (*func)(const char *); /* function to be called when */
1681 /* the variable gets set/unset */
1682};
1683
1684struct localvar {
1685 struct localvar *next; /* next local variable in list */
1686 struct var *vp; /* the variable that was made local */
1687 int flags; /* saved flags */
1688 const char *text; /* saved text */
1689};
1690
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001691/* flags */
1692#define VEXPORT 0x01 /* variable is exported */
1693#define VREADONLY 0x02 /* variable cannot be modified */
1694#define VSTRFIXED 0x04 /* variable struct is statically allocated */
1695#define VTEXTFIXED 0x08 /* text is statically allocated */
1696#define VSTACK 0x10 /* text is allocated on the stack */
1697#define VUNSET 0x20 /* the variable is not set */
1698#define VNOFUNC 0x40 /* don't call the callback function */
1699#define VNOSET 0x80 /* do not set variable - just readonly test */
1700#define VNOSAVE 0x100 /* when text is on the heap before setvareq */
1701#ifdef DYNAMIC_VAR
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00001702# define VDYNAMIC 0x200 /* dynamic variable */
1703#else
1704# define VDYNAMIC 0
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001705#endif
1706
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001707#ifdef IFS_BROKEN
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00001708static const char defifsvar[] ALIGN1 = "IFS= \t\n";
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001709#define defifs (defifsvar + 4)
1710#else
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00001711static const char defifs[] ALIGN1 = " \t\n";
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001712#endif
1713
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00001714
Denis Vlasenko01631112007-12-16 17:20:38 +00001715/* Need to be before varinit_data[] */
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00001716#if ENABLE_LOCALE_SUPPORT
Denis Vlasenkoa8915072007-02-23 21:10:06 +00001717static void
1718change_lc_all(const char *value)
1719{
1720 if (value && *value != '\0')
1721 setlocale(LC_ALL, value);
1722}
1723static void
1724change_lc_ctype(const char *value)
1725{
1726 if (value && *value != '\0')
1727 setlocale(LC_CTYPE, value);
1728}
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00001729#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001730#if ENABLE_ASH_MAIL
1731static void chkmail(void);
1732static void changemail(const char *);
1733#endif
1734static void changepath(const char *);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001735#if ENABLE_ASH_RANDOM_SUPPORT
1736static void change_random(const char *);
1737#endif
1738
Denis Vlasenko01631112007-12-16 17:20:38 +00001739static const struct {
1740 int flags;
1741 const char *text;
1742 void (*func)(const char *);
1743} varinit_data[] = {
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001744#ifdef IFS_BROKEN
Denis Vlasenko01631112007-12-16 17:20:38 +00001745 { VSTRFIXED|VTEXTFIXED , defifsvar , NULL },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001746#else
Denis Vlasenko01631112007-12-16 17:20:38 +00001747 { VSTRFIXED|VTEXTFIXED|VUNSET, "IFS\0" , NULL },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001748#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001749#if ENABLE_ASH_MAIL
Denis Vlasenko01631112007-12-16 17:20:38 +00001750 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL\0" , changemail },
1751 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH\0", changemail },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001752#endif
Denis Vlasenko01631112007-12-16 17:20:38 +00001753 { VSTRFIXED|VTEXTFIXED , bb_PATH_root_path, changepath },
1754 { VSTRFIXED|VTEXTFIXED , "PS1=$ " , NULL },
1755 { VSTRFIXED|VTEXTFIXED , "PS2=> " , NULL },
1756 { VSTRFIXED|VTEXTFIXED , "PS4=+ " , NULL },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001757#if ENABLE_ASH_GETOPTS
Denis Vlasenko01631112007-12-16 17:20:38 +00001758 { VSTRFIXED|VTEXTFIXED , "OPTIND=1" , getoptsreset },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001759#endif
1760#if ENABLE_ASH_RANDOM_SUPPORT
Denis Vlasenko01631112007-12-16 17:20:38 +00001761 { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM\0", change_random },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001762#endif
1763#if ENABLE_LOCALE_SUPPORT
Denis Vlasenko01631112007-12-16 17:20:38 +00001764 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL\0" , change_lc_all },
1765 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE\0", change_lc_ctype },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001766#endif
1767#if ENABLE_FEATURE_EDITING_SAVEHISTORY
Denis Vlasenko01631112007-12-16 17:20:38 +00001768 { VSTRFIXED|VTEXTFIXED|VUNSET, "HISTFILE\0", NULL },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001769#endif
1770};
1771
Denis Vlasenko01631112007-12-16 17:20:38 +00001772
1773struct globals_var {
1774 struct shparam shellparam; /* $@ current positional parameters */
1775 struct redirtab *redirlist;
1776 int g_nullredirs;
1777 int preverrout_fd; /* save fd2 before print debug if xflag is set. */
1778 struct var *vartab[VTABSIZE];
1779 struct var varinit[ARRAY_SIZE(varinit_data)];
1780};
1781/* Make it reside in writable memory, yet make compiler understand that it is not going to change. */
1782static struct globals_var *const ptr_to_globals_var __attribute__ ((section (".data")));
1783#define G_var (*ptr_to_globals_var)
1784#define shellparam (G_var.shellparam )
1785#define redirlist (G_var.redirlist )
1786#define g_nullredirs (G_var.g_nullredirs )
1787#define preverrout_fd (G_var.preverrout_fd)
1788#define vartab (G_var.vartab )
1789#define varinit (G_var.varinit )
1790#define INIT_G_var() do { \
1791 int i; \
1792 (*(struct globals_var**)&ptr_to_globals_var) = xzalloc(sizeof(G_var)); \
1793 for (i = 0; i < ARRAY_SIZE(varinit_data); i++) { \
1794 varinit[i].flags = varinit_data[i].flags; \
1795 varinit[i].text = varinit_data[i].text; \
1796 varinit[i].func = varinit_data[i].func; \
1797 } \
1798} while (0)
1799
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001800#define vifs varinit[0]
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001801#if ENABLE_ASH_MAIL
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001802# define vmail (&vifs)[1]
1803# define vmpath (&vmail)[1]
1804# define vpath (&vmpath)[1]
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001805#else
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001806# define vpath (&vifs)[1]
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001807#endif
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001808#define vps1 (&vpath)[1]
1809#define vps2 (&vps1)[1]
1810#define vps4 (&vps2)[1]
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001811#if ENABLE_ASH_GETOPTS
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001812# define voptind (&vps4)[1]
1813# if ENABLE_ASH_RANDOM_SUPPORT
1814# define vrandom (&voptind)[1]
1815# endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001816#else
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001817# if ENABLE_ASH_RANDOM_SUPPORT
1818# define vrandom (&vps4)[1]
1819# endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001820#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001821
1822/*
1823 * The following macros access the values of the above variables.
1824 * They have to skip over the name. They return the null string
1825 * for unset variables.
1826 */
1827#define ifsval() (vifs.text + 4)
1828#define ifsset() ((vifs.flags & VUNSET) == 0)
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001829#if ENABLE_ASH_MAIL
1830# define mailval() (vmail.text + 5)
1831# define mpathval() (vmpath.text + 9)
1832# define mpathset() ((vmpath.flags & VUNSET) == 0)
1833#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001834#define pathval() (vpath.text + 5)
1835#define ps1val() (vps1.text + 4)
1836#define ps2val() (vps2.text + 4)
1837#define ps4val() (vps4.text + 4)
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001838#if ENABLE_ASH_GETOPTS
1839# define optindval() (voptind.text + 7)
1840#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001841
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001842
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001843#define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
1844#define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
1845
Denis Vlasenko01631112007-12-16 17:20:38 +00001846#if ENABLE_ASH_GETOPTS
1847static void
1848getoptsreset(const char *value)
1849{
1850 shellparam.optind = number(value);
1851 shellparam.optoff = -1;
1852}
1853#endif
1854
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001855/*
1856 * Return of a legal variable name (a letter or underscore followed by zero or
1857 * more letters, underscores, and digits).
1858 */
1859static char *
1860endofname(const char *name)
1861{
1862 char *p;
1863
1864 p = (char *) name;
1865 if (!is_name(*p))
1866 return p;
1867 while (*++p) {
1868 if (!is_in_name(*p))
1869 break;
1870 }
1871 return p;
1872}
1873
1874/*
1875 * Compares two strings up to the first = or '\0'. The first
1876 * string must be terminated by '='; the second may be terminated by
1877 * either '=' or '\0'.
1878 */
1879static int
1880varcmp(const char *p, const char *q)
1881{
1882 int c, d;
1883
1884 while ((c = *p) == (d = *q)) {
1885 if (!c || c == '=')
1886 goto out;
1887 p++;
1888 q++;
1889 }
1890 if (c == '=')
Denis Vlasenko9650f362007-02-23 01:04:37 +00001891 c = '\0';
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001892 if (d == '=')
Denis Vlasenko9650f362007-02-23 01:04:37 +00001893 d = '\0';
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001894 out:
1895 return c - d;
1896}
1897
1898static int
1899varequal(const char *a, const char *b)
1900{
1901 return !varcmp(a, b);
1902}
1903
1904/*
1905 * Find the appropriate entry in the hash table from the name.
1906 */
1907static struct var **
1908hashvar(const char *p)
1909{
1910 unsigned hashval;
1911
1912 hashval = ((unsigned char) *p) << 4;
1913 while (*p && *p != '=')
1914 hashval += (unsigned char) *p++;
1915 return &vartab[hashval % VTABSIZE];
1916}
1917
1918static int
1919vpcmp(const void *a, const void *b)
1920{
1921 return varcmp(*(const char **)a, *(const char **)b);
1922}
1923
1924/*
1925 * This routine initializes the builtin variables.
1926 */
1927static void
1928initvar(void)
1929{
1930 struct var *vp;
1931 struct var *end;
1932 struct var **vpp;
1933
1934 /*
1935 * PS1 depends on uid
1936 */
1937#if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
1938 vps1.text = "PS1=\\w \\$ ";
1939#else
1940 if (!geteuid())
1941 vps1.text = "PS1=# ";
1942#endif
1943 vp = varinit;
Denis Vlasenko80b8b392007-06-25 10:55:35 +00001944 end = vp + ARRAY_SIZE(varinit);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001945 do {
1946 vpp = hashvar(vp->text);
1947 vp->next = *vpp;
1948 *vpp = vp;
1949 } while (++vp < end);
1950}
1951
1952static struct var **
1953findvar(struct var **vpp, const char *name)
1954{
1955 for (; *vpp; vpp = &(*vpp)->next) {
1956 if (varequal((*vpp)->text, name)) {
1957 break;
1958 }
1959 }
1960 return vpp;
1961}
1962
1963/*
1964 * Find the value of a variable. Returns NULL if not set.
1965 */
1966static char *
1967lookupvar(const char *name)
1968{
1969 struct var *v;
1970
1971 v = *findvar(hashvar(name), name);
1972 if (v) {
1973#ifdef DYNAMIC_VAR
1974 /*
1975 * Dynamic variables are implemented roughly the same way they are
1976 * in bash. Namely, they're "special" so long as they aren't unset.
1977 * As soon as they're unset, they're no longer dynamic, and dynamic
1978 * lookup will no longer happen at that point. -- PFM.
1979 */
1980 if ((v->flags & VDYNAMIC))
1981 (*v->func)(NULL);
1982#endif
1983 if (!(v->flags & VUNSET))
1984 return strchrnul(v->text, '=') + 1;
1985 }
1986 return NULL;
1987}
1988
1989/*
1990 * Search the environment of a builtin command.
1991 */
1992static char *
1993bltinlookup(const char *name)
1994{
1995 struct strlist *sp;
1996
1997 for (sp = cmdenviron; sp; sp = sp->next) {
1998 if (varequal(sp->text, name))
1999 return strchrnul(sp->text, '=') + 1;
2000 }
2001 return lookupvar(name);
2002}
2003
2004/*
2005 * Same as setvar except that the variable and value are passed in
2006 * the first argument as name=value. Since the first argument will
2007 * be actually stored in the table, it should not be a string that
2008 * will go away.
2009 * Called with interrupts off.
2010 */
2011static void
2012setvareq(char *s, int flags)
2013{
2014 struct var *vp, **vpp;
2015
2016 vpp = hashvar(s);
2017 flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
2018 vp = *findvar(vpp, s);
2019 if (vp) {
2020 if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
2021 const char *n;
2022
2023 if (flags & VNOSAVE)
2024 free(s);
2025 n = vp->text;
2026 ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
2027 }
2028
2029 if (flags & VNOSET)
2030 return;
2031
2032 if (vp->func && (flags & VNOFUNC) == 0)
2033 (*vp->func)(strchrnul(s, '=') + 1);
2034
2035 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
2036 free((char*)vp->text);
2037
2038 flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
2039 } else {
2040 if (flags & VNOSET)
2041 return;
2042 /* not found */
Denis Vlasenko597906c2008-02-20 16:38:54 +00002043 vp = ckzalloc(sizeof(*vp));
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002044 vp->next = *vpp;
Denis Vlasenko597906c2008-02-20 16:38:54 +00002045 /*vp->func = NULL; - ckzalloc did it */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002046 *vpp = vp;
2047 }
2048 if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
2049 s = ckstrdup(s);
2050 vp->text = s;
2051 vp->flags = flags;
2052}
2053
2054/*
2055 * Set the value of a variable. The flags argument is ored with the
2056 * flags of the variable. If val is NULL, the variable is unset.
2057 */
2058static void
2059setvar(const char *name, const char *val, int flags)
2060{
2061 char *p, *q;
2062 size_t namelen;
2063 char *nameeq;
2064 size_t vallen;
2065
2066 q = endofname(name);
2067 p = strchrnul(q, '=');
2068 namelen = p - name;
2069 if (!namelen || p != q)
2070 ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
2071 vallen = 0;
2072 if (val == NULL) {
2073 flags |= VUNSET;
2074 } else {
2075 vallen = strlen(val);
2076 }
2077 INT_OFF;
2078 nameeq = ckmalloc(namelen + vallen + 2);
2079 p = memcpy(nameeq, name, namelen) + namelen;
2080 if (val) {
2081 *p++ = '=';
2082 p = memcpy(p, val, vallen) + vallen;
2083 }
2084 *p = '\0';
2085 setvareq(nameeq, flags | VNOSAVE);
2086 INT_ON;
2087}
2088
2089#if ENABLE_ASH_GETOPTS
2090/*
2091 * Safe version of setvar, returns 1 on success 0 on failure.
2092 */
2093static int
2094setvarsafe(const char *name, const char *val, int flags)
2095{
2096 int err;
2097 volatile int saveint;
2098 struct jmploc *volatile savehandler = exception_handler;
2099 struct jmploc jmploc;
2100
2101 SAVE_INT(saveint);
2102 if (setjmp(jmploc.loc))
2103 err = 1;
2104 else {
2105 exception_handler = &jmploc;
2106 setvar(name, val, flags);
2107 err = 0;
2108 }
2109 exception_handler = savehandler;
2110 RESTORE_INT(saveint);
2111 return err;
2112}
2113#endif
2114
2115/*
2116 * Unset the specified variable.
2117 */
2118static int
2119unsetvar(const char *s)
2120{
2121 struct var **vpp;
2122 struct var *vp;
2123 int retval;
2124
2125 vpp = findvar(hashvar(s), s);
2126 vp = *vpp;
2127 retval = 2;
2128 if (vp) {
2129 int flags = vp->flags;
2130
2131 retval = 1;
2132 if (flags & VREADONLY)
2133 goto out;
2134#ifdef DYNAMIC_VAR
2135 vp->flags &= ~VDYNAMIC;
2136#endif
2137 if (flags & VUNSET)
2138 goto ok;
2139 if ((flags & VSTRFIXED) == 0) {
2140 INT_OFF;
2141 if ((flags & (VTEXTFIXED|VSTACK)) == 0)
2142 free((char*)vp->text);
2143 *vpp = vp->next;
2144 free(vp);
2145 INT_ON;
2146 } else {
2147 setvar(s, 0, 0);
2148 vp->flags &= ~VEXPORT;
2149 }
2150 ok:
2151 retval = 0;
2152 }
2153 out:
2154 return retval;
2155}
2156
2157/*
2158 * Process a linked list of variable assignments.
2159 */
2160static void
2161listsetvar(struct strlist *list_set_var, int flags)
2162{
2163 struct strlist *lp = list_set_var;
2164
2165 if (!lp)
2166 return;
2167 INT_OFF;
2168 do {
2169 setvareq(lp->text, flags);
Denis Vlasenko9650f362007-02-23 01:04:37 +00002170 lp = lp->next;
2171 } while (lp);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002172 INT_ON;
2173}
2174
2175/*
2176 * Generate a list of variables satisfying the given conditions.
2177 */
2178static char **
2179listvars(int on, int off, char ***end)
2180{
2181 struct var **vpp;
2182 struct var *vp;
2183 char **ep;
2184 int mask;
2185
2186 STARTSTACKSTR(ep);
2187 vpp = vartab;
2188 mask = on | off;
2189 do {
2190 for (vp = *vpp; vp; vp = vp->next) {
2191 if ((vp->flags & mask) == on) {
2192 if (ep == stackstrend())
2193 ep = growstackstr();
2194 *ep++ = (char *) vp->text;
2195 }
2196 }
2197 } while (++vpp < vartab + VTABSIZE);
2198 if (ep == stackstrend())
2199 ep = growstackstr();
2200 if (end)
2201 *end = ep;
2202 *ep++ = NULL;
2203 return grabstackstr(ep);
2204}
2205
2206
2207/* ============ Path search helper
2208 *
2209 * The variable path (passed by reference) should be set to the start
2210 * of the path before the first call; padvance will update
2211 * this value as it proceeds. Successive calls to padvance will return
2212 * the possible path expansions in sequence. If an option (indicated by
2213 * a percent sign) appears in the path entry then the global variable
2214 * pathopt will be set to point to it; otherwise pathopt will be set to
2215 * NULL.
2216 */
2217static const char *pathopt; /* set by padvance */
2218
2219static char *
2220padvance(const char **path, const char *name)
2221{
2222 const char *p;
2223 char *q;
2224 const char *start;
2225 size_t len;
2226
2227 if (*path == NULL)
2228 return NULL;
2229 start = *path;
2230 for (p = start; *p && *p != ':' && *p != '%'; p++);
2231 len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
2232 while (stackblocksize() < len)
2233 growstackblock();
2234 q = stackblock();
2235 if (p != start) {
2236 memcpy(q, start, p - start);
2237 q += p - start;
2238 *q++ = '/';
2239 }
2240 strcpy(q, name);
2241 pathopt = NULL;
2242 if (*p == '%') {
2243 pathopt = ++p;
2244 while (*p && *p != ':') p++;
2245 }
2246 if (*p == ':')
2247 *path = p + 1;
2248 else
2249 *path = NULL;
2250 return stalloc(len);
2251}
2252
2253
2254/* ============ Prompt */
2255
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +00002256static smallint doprompt; /* if set, prompt the user */
2257static smallint needprompt; /* true if interactive and at start of line */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002258
2259#if ENABLE_FEATURE_EDITING
2260static line_input_t *line_input_state;
2261static const char *cmdedit_prompt;
2262static void
2263putprompt(const char *s)
2264{
2265 if (ENABLE_ASH_EXPAND_PRMT) {
2266 free((char*)cmdedit_prompt);
Denis Vlasenko4222ae42007-02-25 02:37:49 +00002267 cmdedit_prompt = ckstrdup(s);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002268 return;
2269 }
2270 cmdedit_prompt = s;
2271}
2272#else
2273static void
2274putprompt(const char *s)
2275{
2276 out2str(s);
2277}
2278#endif
2279
2280#if ENABLE_ASH_EXPAND_PRMT
2281/* expandstr() needs parsing machinery, so it is far away ahead... */
2282static const char *expandstr(const char *ps);
2283#else
2284#define expandstr(s) s
2285#endif
2286
2287static void
2288setprompt(int whichprompt)
2289{
2290 const char *prompt;
2291#if ENABLE_ASH_EXPAND_PRMT
2292 struct stackmark smark;
2293#endif
2294
2295 needprompt = 0;
2296
2297 switch (whichprompt) {
2298 case 1:
2299 prompt = ps1val();
2300 break;
2301 case 2:
2302 prompt = ps2val();
2303 break;
2304 default: /* 0 */
2305 prompt = nullstr;
2306 }
2307#if ENABLE_ASH_EXPAND_PRMT
2308 setstackmark(&smark);
2309 stalloc(stackblocksize());
2310#endif
2311 putprompt(expandstr(prompt));
2312#if ENABLE_ASH_EXPAND_PRMT
2313 popstackmark(&smark);
2314#endif
2315}
2316
2317
2318/* ============ The cd and pwd commands */
2319
2320#define CD_PHYSICAL 1
2321#define CD_PRINT 2
2322
2323static int docd(const char *, int);
2324
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002325static int
2326cdopt(void)
2327{
2328 int flags = 0;
2329 int i, j;
2330
2331 j = 'L';
2332 while ((i = nextopt("LP"))) {
2333 if (i != j) {
2334 flags ^= CD_PHYSICAL;
2335 j = i;
2336 }
2337 }
2338
2339 return flags;
2340}
2341
2342/*
2343 * Update curdir (the name of the current directory) in response to a
2344 * cd command.
2345 */
2346static const char *
2347updatepwd(const char *dir)
2348{
2349 char *new;
2350 char *p;
2351 char *cdcomppath;
2352 const char *lim;
2353
2354 cdcomppath = ststrdup(dir);
2355 STARTSTACKSTR(new);
2356 if (*dir != '/') {
2357 if (curdir == nullstr)
2358 return 0;
2359 new = stack_putstr(curdir, new);
2360 }
2361 new = makestrspace(strlen(dir) + 2, new);
2362 lim = stackblock() + 1;
2363 if (*dir != '/') {
2364 if (new[-1] != '/')
2365 USTPUTC('/', new);
2366 if (new > lim && *lim == '/')
2367 lim++;
2368 } else {
2369 USTPUTC('/', new);
2370 cdcomppath++;
2371 if (dir[1] == '/' && dir[2] != '/') {
2372 USTPUTC('/', new);
2373 cdcomppath++;
2374 lim++;
2375 }
2376 }
2377 p = strtok(cdcomppath, "/");
2378 while (p) {
2379 switch (*p) {
2380 case '.':
2381 if (p[1] == '.' && p[2] == '\0') {
2382 while (new > lim) {
2383 STUNPUTC(new);
2384 if (new[-1] == '/')
2385 break;
2386 }
2387 break;
Denis Vlasenko16abcd92007-04-13 23:59:52 +00002388 }
2389 if (p[1] == '\0')
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002390 break;
2391 /* fall through */
2392 default:
2393 new = stack_putstr(p, new);
2394 USTPUTC('/', new);
2395 }
2396 p = strtok(0, "/");
2397 }
2398 if (new > lim)
2399 STUNPUTC(new);
2400 *new = 0;
2401 return stackblock();
2402}
2403
2404/*
2405 * Find out what the current directory is. If we already know the current
2406 * directory, this routine returns immediately.
2407 */
2408static char *
2409getpwd(void)
2410{
Denis Vlasenko01631112007-12-16 17:20:38 +00002411 char *dir = getcwd(NULL, 0); /* huh, using glibc extension? */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002412 return dir ? dir : nullstr;
2413}
2414
2415static void
2416setpwd(const char *val, int setold)
2417{
2418 char *oldcur, *dir;
2419
2420 oldcur = dir = curdir;
2421
2422 if (setold) {
2423 setvar("OLDPWD", oldcur, VEXPORT);
2424 }
2425 INT_OFF;
2426 if (physdir != nullstr) {
2427 if (physdir != oldcur)
2428 free(physdir);
2429 physdir = nullstr;
2430 }
2431 if (oldcur == val || !val) {
2432 char *s = getpwd();
2433 physdir = s;
2434 if (!val)
2435 dir = s;
2436 } else
2437 dir = ckstrdup(val);
2438 if (oldcur != dir && oldcur != nullstr) {
2439 free(oldcur);
2440 }
2441 curdir = dir;
2442 INT_ON;
2443 setvar("PWD", dir, VEXPORT);
2444}
2445
2446static void hashcd(void);
2447
2448/*
2449 * Actually do the chdir. We also call hashcd to let the routines in exec.c
2450 * know that the current directory has changed.
2451 */
2452static int
2453docd(const char *dest, int flags)
2454{
2455 const char *dir = 0;
2456 int err;
2457
2458 TRACE(("docd(\"%s\", %d) called\n", dest, flags));
2459
2460 INT_OFF;
2461 if (!(flags & CD_PHYSICAL)) {
2462 dir = updatepwd(dest);
2463 if (dir)
2464 dest = dir;
2465 }
2466 err = chdir(dest);
2467 if (err)
2468 goto out;
2469 setpwd(dir, 1);
2470 hashcd();
2471 out:
2472 INT_ON;
2473 return err;
2474}
2475
2476static int
2477cdcmd(int argc, char **argv)
2478{
2479 const char *dest;
2480 const char *path;
2481 const char *p;
2482 char c;
2483 struct stat statb;
2484 int flags;
2485
2486 flags = cdopt();
2487 dest = *argptr;
2488 if (!dest)
2489 dest = bltinlookup(homestr);
2490 else if (LONE_DASH(dest)) {
2491 dest = bltinlookup("OLDPWD");
2492 flags |= CD_PRINT;
2493 }
2494 if (!dest)
2495 dest = nullstr;
2496 if (*dest == '/')
2497 goto step7;
2498 if (*dest == '.') {
2499 c = dest[1];
2500 dotdot:
2501 switch (c) {
2502 case '\0':
2503 case '/':
2504 goto step6;
2505 case '.':
2506 c = dest[2];
2507 if (c != '.')
2508 goto dotdot;
2509 }
2510 }
2511 if (!*dest)
2512 dest = ".";
2513 path = bltinlookup("CDPATH");
2514 if (!path) {
2515 step6:
2516 step7:
2517 p = dest;
2518 goto docd;
2519 }
2520 do {
2521 c = *path;
2522 p = padvance(&path, dest);
2523 if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
2524 if (c && c != ':')
2525 flags |= CD_PRINT;
2526 docd:
2527 if (!docd(p, flags))
2528 goto out;
2529 break;
2530 }
2531 } while (path);
2532 ash_msg_and_raise_error("can't cd to %s", dest);
2533 /* NOTREACHED */
2534 out:
2535 if (flags & CD_PRINT)
2536 out1fmt(snlfmt, curdir);
2537 return 0;
2538}
2539
2540static int
2541pwdcmd(int argc, char **argv)
2542{
2543 int flags;
2544 const char *dir = curdir;
2545
2546 flags = cdopt();
2547 if (flags) {
2548 if (physdir == nullstr)
2549 setpwd(dir, 0);
2550 dir = physdir;
2551 }
2552 out1fmt(snlfmt, dir);
2553 return 0;
2554}
2555
Denis Vlasenko0c032a42007-02-23 01:03:40 +00002556
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00002557/* ============ ... */
Eric Andersenc470f442003-07-28 09:56:35 +00002558
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +00002559#define IBUFSIZ COMMON_BUFSIZE
"Vladimir N. Oleynik"6f347ef2005-10-15 10:23:55 +00002560#define basebuf bb_common_bufsiz1 /* buffer for top level input file */
Eric Andersenc470f442003-07-28 09:56:35 +00002561
Eric Andersenc470f442003-07-28 09:56:35 +00002562/* Syntax classes */
2563#define CWORD 0 /* character is nothing special */
2564#define CNL 1 /* newline character */
2565#define CBACK 2 /* a backslash character */
2566#define CSQUOTE 3 /* single quote */
2567#define CDQUOTE 4 /* double quote */
2568#define CENDQUOTE 5 /* a terminating quote */
2569#define CBQUOTE 6 /* backwards single quote */
2570#define CVAR 7 /* a dollar sign */
2571#define CENDVAR 8 /* a '}' character */
2572#define CLP 9 /* a left paren in arithmetic */
2573#define CRP 10 /* a right paren in arithmetic */
2574#define CENDFILE 11 /* end of file */
2575#define CCTL 12 /* like CWORD, except it must be escaped */
2576#define CSPCL 13 /* these terminate a word */
2577#define CIGN 14 /* character should be ignored */
2578
Denis Vlasenko131ae172007-02-18 13:00:19 +00002579#if ENABLE_ASH_ALIAS
Eric Andersenc470f442003-07-28 09:56:35 +00002580#define SYNBASE 130
2581#define PEOF -130
2582#define PEOA -129
2583#define PEOA_OR_PEOF PEOA
2584#else
2585#define SYNBASE 129
2586#define PEOF -129
2587#define PEOA_OR_PEOF PEOF
2588#endif
2589
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00002590/* number syntax index */
2591#define BASESYNTAX 0 /* not in quotes */
2592#define DQSYNTAX 1 /* in double quotes */
2593#define SQSYNTAX 2 /* in single quotes */
2594#define ARISYNTAX 3 /* in arithmetic */
Denis Vlasenko46a53062007-09-24 18:30:02 +00002595#define PSSYNTAX 4 /* prompt */
Eric Andersenc470f442003-07-28 09:56:35 +00002596
Denis Vlasenko131ae172007-02-18 13:00:19 +00002597#if ENABLE_ASH_OPTIMIZE_FOR_SIZE
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002598#define USE_SIT_FUNCTION
2599#endif
2600
Denis Vlasenko131ae172007-02-18 13:00:19 +00002601#if ENABLE_ASH_MATH_SUPPORT
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002602static const char S_I_T[][4] = {
Denis Vlasenko131ae172007-02-18 13:00:19 +00002603#if ENABLE_ASH_ALIAS
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00002604 { CSPCL, CIGN, CIGN, CIGN }, /* 0, PEOA */
Eric Andersenc470f442003-07-28 09:56:35 +00002605#endif
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00002606 { CSPCL, CWORD, CWORD, CWORD }, /* 1, ' ' */
2607 { CNL, CNL, CNL, CNL }, /* 2, \n */
2608 { CWORD, CCTL, CCTL, CWORD }, /* 3, !*-/:=?[]~ */
2609 { CDQUOTE, CENDQUOTE, CWORD, CWORD }, /* 4, '"' */
2610 { CVAR, CVAR, CWORD, CVAR }, /* 5, $ */
2611 { CSQUOTE, CWORD, CENDQUOTE, CWORD }, /* 6, "'" */
2612 { CSPCL, CWORD, CWORD, CLP }, /* 7, ( */
2613 { CSPCL, CWORD, CWORD, CRP }, /* 8, ) */
2614 { CBACK, CBACK, CCTL, CBACK }, /* 9, \ */
2615 { CBQUOTE, CBQUOTE, CWORD, CBQUOTE }, /* 10, ` */
2616 { CENDVAR, CENDVAR, CWORD, CENDVAR }, /* 11, } */
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002617#ifndef USE_SIT_FUNCTION
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00002618 { CENDFILE, CENDFILE, CENDFILE, CENDFILE }, /* 12, PEOF */
2619 { CWORD, CWORD, CWORD, CWORD }, /* 13, 0-9A-Za-z */
2620 { CCTL, CCTL, CCTL, CCTL } /* 14, CTLESC ... */
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002621#endif
Eric Andersen2870d962001-07-02 17:27:21 +00002622};
Eric Andersenc470f442003-07-28 09:56:35 +00002623#else
2624static const char S_I_T[][3] = {
Denis Vlasenko131ae172007-02-18 13:00:19 +00002625#if ENABLE_ASH_ALIAS
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00002626 { CSPCL, CIGN, CIGN }, /* 0, PEOA */
Eric Andersenc470f442003-07-28 09:56:35 +00002627#endif
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00002628 { CSPCL, CWORD, CWORD }, /* 1, ' ' */
2629 { CNL, CNL, CNL }, /* 2, \n */
2630 { CWORD, CCTL, CCTL }, /* 3, !*-/:=?[]~ */
2631 { CDQUOTE, CENDQUOTE, CWORD }, /* 4, '"' */
2632 { CVAR, CVAR, CWORD }, /* 5, $ */
2633 { CSQUOTE, CWORD, CENDQUOTE }, /* 6, "'" */
2634 { CSPCL, CWORD, CWORD }, /* 7, ( */
2635 { CSPCL, CWORD, CWORD }, /* 8, ) */
2636 { CBACK, CBACK, CCTL }, /* 9, \ */
2637 { CBQUOTE, CBQUOTE, CWORD }, /* 10, ` */
2638 { CENDVAR, CENDVAR, CWORD }, /* 11, } */
Eric Andersenc470f442003-07-28 09:56:35 +00002639#ifndef USE_SIT_FUNCTION
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00002640 { CENDFILE, CENDFILE, CENDFILE }, /* 12, PEOF */
2641 { CWORD, CWORD, CWORD }, /* 13, 0-9A-Za-z */
2642 { CCTL, CCTL, CCTL } /* 14, CTLESC ... */
Eric Andersenc470f442003-07-28 09:56:35 +00002643#endif
2644};
Denis Vlasenko131ae172007-02-18 13:00:19 +00002645#endif /* ASH_MATH_SUPPORT */
Eric Andersen2870d962001-07-02 17:27:21 +00002646
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002647#ifdef USE_SIT_FUNCTION
2648
Denis Vlasenko0c032a42007-02-23 01:03:40 +00002649static int
2650SIT(int c, int syntax)
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002651{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00002652 static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-/:;<=>?[\\]`|}~";
Denis Vlasenko131ae172007-02-18 13:00:19 +00002653#if ENABLE_ASH_ALIAS
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00002654 static const char syntax_index_table[] ALIGN1 = {
Eric Andersenc470f442003-07-28 09:56:35 +00002655 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
2656 7, 8, 3, 3, 3, 3, 1, 1, /* "()*-/:;<" */
2657 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
2658 11, 3 /* "}~" */
2659 };
2660#else
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00002661 static const char syntax_index_table[] ALIGN1 = {
Eric Andersenc470f442003-07-28 09:56:35 +00002662 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
2663 6, 7, 2, 2, 2, 2, 0, 0, /* "()*-/:;<" */
2664 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
2665 10, 2 /* "}~" */
2666 };
2667#endif
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002668 const char *s;
2669 int indx;
2670
Eric Andersenc470f442003-07-28 09:56:35 +00002671 if (c == PEOF) /* 2^8+2 */
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002672 return CENDFILE;
Denis Vlasenko131ae172007-02-18 13:00:19 +00002673#if ENABLE_ASH_ALIAS
Eric Andersenc470f442003-07-28 09:56:35 +00002674 if (c == PEOA) /* 2^8+1 */
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002675 indx = 0;
Eric Andersenc470f442003-07-28 09:56:35 +00002676 else
2677#endif
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00002678#define U_C(c) ((unsigned char)(c))
2679
2680 if ((unsigned char)c >= (unsigned char)(CTLESC)
2681 && (unsigned char)c <= (unsigned char)(CTLQUOTEMARK)
2682 ) {
Denis Vlasenko2da584f2007-02-19 22:44:05 +00002683 return CCTL;
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00002684 } else {
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002685 s = strchr(spec_symbls, c);
Denis Vlasenko2da584f2007-02-19 22:44:05 +00002686 if (s == NULL || *s == '\0')
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002687 return CWORD;
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00002688 indx = syntax_index_table[(s - spec_symbls)];
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002689 }
2690 return S_I_T[indx][syntax];
2691}
2692
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00002693#else /* !USE_SIT_FUNCTION */
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002694
Denis Vlasenko131ae172007-02-18 13:00:19 +00002695#if ENABLE_ASH_ALIAS
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00002696#define CSPCL_CIGN_CIGN_CIGN 0
2697#define CSPCL_CWORD_CWORD_CWORD 1
2698#define CNL_CNL_CNL_CNL 2
2699#define CWORD_CCTL_CCTL_CWORD 3
2700#define CDQUOTE_CENDQUOTE_CWORD_CWORD 4
2701#define CVAR_CVAR_CWORD_CVAR 5
2702#define CSQUOTE_CWORD_CENDQUOTE_CWORD 6
2703#define CSPCL_CWORD_CWORD_CLP 7
2704#define CSPCL_CWORD_CWORD_CRP 8
2705#define CBACK_CBACK_CCTL_CBACK 9
2706#define CBQUOTE_CBQUOTE_CWORD_CBQUOTE 10
2707#define CENDVAR_CENDVAR_CWORD_CENDVAR 11
2708#define CENDFILE_CENDFILE_CENDFILE_CENDFILE 12
2709#define CWORD_CWORD_CWORD_CWORD 13
2710#define CCTL_CCTL_CCTL_CCTL 14
Eric Andersenc470f442003-07-28 09:56:35 +00002711#else
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00002712#define CSPCL_CWORD_CWORD_CWORD 0
2713#define CNL_CNL_CNL_CNL 1
2714#define CWORD_CCTL_CCTL_CWORD 2
2715#define CDQUOTE_CENDQUOTE_CWORD_CWORD 3
2716#define CVAR_CVAR_CWORD_CVAR 4
2717#define CSQUOTE_CWORD_CENDQUOTE_CWORD 5
2718#define CSPCL_CWORD_CWORD_CLP 6
2719#define CSPCL_CWORD_CWORD_CRP 7
2720#define CBACK_CBACK_CCTL_CBACK 8
2721#define CBQUOTE_CBQUOTE_CWORD_CBQUOTE 9
2722#define CENDVAR_CENDVAR_CWORD_CENDVAR 10
2723#define CENDFILE_CENDFILE_CENDFILE_CENDFILE 11
2724#define CWORD_CWORD_CWORD_CWORD 12
2725#define CCTL_CCTL_CCTL_CCTL 13
Eric Andersenc470f442003-07-28 09:56:35 +00002726#endif
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002727
2728static const char syntax_index_table[258] = {
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00002729 /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
Eric Andersenc470f442003-07-28 09:56:35 +00002730 /* 0 PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
Denis Vlasenko131ae172007-02-18 13:00:19 +00002731#if ENABLE_ASH_ALIAS
Eric Andersenc470f442003-07-28 09:56:35 +00002732 /* 1 PEOA */ CSPCL_CIGN_CIGN_CIGN,
2733#endif
2734 /* 2 -128 0x80 */ CWORD_CWORD_CWORD_CWORD,
2735 /* 3 -127 CTLESC */ CCTL_CCTL_CCTL_CCTL,
2736 /* 4 -126 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
2737 /* 5 -125 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
2738 /* 6 -124 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
2739 /* 7 -123 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
2740 /* 8 -122 CTLARI */ CCTL_CCTL_CCTL_CCTL,
2741 /* 9 -121 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
2742 /* 10 -120 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00002743 /* 11 -119 */ CWORD_CWORD_CWORD_CWORD,
2744 /* 12 -118 */ CWORD_CWORD_CWORD_CWORD,
2745 /* 13 -117 */ CWORD_CWORD_CWORD_CWORD,
2746 /* 14 -116 */ CWORD_CWORD_CWORD_CWORD,
2747 /* 15 -115 */ CWORD_CWORD_CWORD_CWORD,
2748 /* 16 -114 */ CWORD_CWORD_CWORD_CWORD,
2749 /* 17 -113 */ CWORD_CWORD_CWORD_CWORD,
2750 /* 18 -112 */ CWORD_CWORD_CWORD_CWORD,
2751 /* 19 -111 */ CWORD_CWORD_CWORD_CWORD,
2752 /* 20 -110 */ CWORD_CWORD_CWORD_CWORD,
2753 /* 21 -109 */ CWORD_CWORD_CWORD_CWORD,
2754 /* 22 -108 */ CWORD_CWORD_CWORD_CWORD,
2755 /* 23 -107 */ CWORD_CWORD_CWORD_CWORD,
2756 /* 24 -106 */ CWORD_CWORD_CWORD_CWORD,
2757 /* 25 -105 */ CWORD_CWORD_CWORD_CWORD,
2758 /* 26 -104 */ CWORD_CWORD_CWORD_CWORD,
2759 /* 27 -103 */ CWORD_CWORD_CWORD_CWORD,
2760 /* 28 -102 */ CWORD_CWORD_CWORD_CWORD,
2761 /* 29 -101 */ CWORD_CWORD_CWORD_CWORD,
2762 /* 30 -100 */ CWORD_CWORD_CWORD_CWORD,
2763 /* 31 -99 */ CWORD_CWORD_CWORD_CWORD,
2764 /* 32 -98 */ CWORD_CWORD_CWORD_CWORD,
2765 /* 33 -97 */ CWORD_CWORD_CWORD_CWORD,
2766 /* 34 -96 */ CWORD_CWORD_CWORD_CWORD,
2767 /* 35 -95 */ CWORD_CWORD_CWORD_CWORD,
2768 /* 36 -94 */ CWORD_CWORD_CWORD_CWORD,
2769 /* 37 -93 */ CWORD_CWORD_CWORD_CWORD,
2770 /* 38 -92 */ CWORD_CWORD_CWORD_CWORD,
2771 /* 39 -91 */ CWORD_CWORD_CWORD_CWORD,
2772 /* 40 -90 */ CWORD_CWORD_CWORD_CWORD,
2773 /* 41 -89 */ CWORD_CWORD_CWORD_CWORD,
2774 /* 42 -88 */ CWORD_CWORD_CWORD_CWORD,
2775 /* 43 -87 */ CWORD_CWORD_CWORD_CWORD,
2776 /* 44 -86 */ CWORD_CWORD_CWORD_CWORD,
2777 /* 45 -85 */ CWORD_CWORD_CWORD_CWORD,
2778 /* 46 -84 */ CWORD_CWORD_CWORD_CWORD,
2779 /* 47 -83 */ CWORD_CWORD_CWORD_CWORD,
2780 /* 48 -82 */ CWORD_CWORD_CWORD_CWORD,
2781 /* 49 -81 */ CWORD_CWORD_CWORD_CWORD,
2782 /* 50 -80 */ CWORD_CWORD_CWORD_CWORD,
2783 /* 51 -79 */ CWORD_CWORD_CWORD_CWORD,
2784 /* 52 -78 */ CWORD_CWORD_CWORD_CWORD,
2785 /* 53 -77 */ CWORD_CWORD_CWORD_CWORD,
2786 /* 54 -76 */ CWORD_CWORD_CWORD_CWORD,
2787 /* 55 -75 */ CWORD_CWORD_CWORD_CWORD,
2788 /* 56 -74 */ CWORD_CWORD_CWORD_CWORD,
2789 /* 57 -73 */ CWORD_CWORD_CWORD_CWORD,
2790 /* 58 -72 */ CWORD_CWORD_CWORD_CWORD,
2791 /* 59 -71 */ CWORD_CWORD_CWORD_CWORD,
2792 /* 60 -70 */ CWORD_CWORD_CWORD_CWORD,
2793 /* 61 -69 */ CWORD_CWORD_CWORD_CWORD,
2794 /* 62 -68 */ CWORD_CWORD_CWORD_CWORD,
2795 /* 63 -67 */ CWORD_CWORD_CWORD_CWORD,
2796 /* 64 -66 */ CWORD_CWORD_CWORD_CWORD,
2797 /* 65 -65 */ CWORD_CWORD_CWORD_CWORD,
2798 /* 66 -64 */ CWORD_CWORD_CWORD_CWORD,
2799 /* 67 -63 */ CWORD_CWORD_CWORD_CWORD,
2800 /* 68 -62 */ CWORD_CWORD_CWORD_CWORD,
2801 /* 69 -61 */ CWORD_CWORD_CWORD_CWORD,
2802 /* 70 -60 */ CWORD_CWORD_CWORD_CWORD,
2803 /* 71 -59 */ CWORD_CWORD_CWORD_CWORD,
2804 /* 72 -58 */ CWORD_CWORD_CWORD_CWORD,
2805 /* 73 -57 */ CWORD_CWORD_CWORD_CWORD,
2806 /* 74 -56 */ CWORD_CWORD_CWORD_CWORD,
2807 /* 75 -55 */ CWORD_CWORD_CWORD_CWORD,
2808 /* 76 -54 */ CWORD_CWORD_CWORD_CWORD,
2809 /* 77 -53 */ CWORD_CWORD_CWORD_CWORD,
2810 /* 78 -52 */ CWORD_CWORD_CWORD_CWORD,
2811 /* 79 -51 */ CWORD_CWORD_CWORD_CWORD,
2812 /* 80 -50 */ CWORD_CWORD_CWORD_CWORD,
2813 /* 81 -49 */ CWORD_CWORD_CWORD_CWORD,
2814 /* 82 -48 */ CWORD_CWORD_CWORD_CWORD,
2815 /* 83 -47 */ CWORD_CWORD_CWORD_CWORD,
2816 /* 84 -46 */ CWORD_CWORD_CWORD_CWORD,
2817 /* 85 -45 */ CWORD_CWORD_CWORD_CWORD,
2818 /* 86 -44 */ CWORD_CWORD_CWORD_CWORD,
2819 /* 87 -43 */ CWORD_CWORD_CWORD_CWORD,
2820 /* 88 -42 */ CWORD_CWORD_CWORD_CWORD,
2821 /* 89 -41 */ CWORD_CWORD_CWORD_CWORD,
2822 /* 90 -40 */ CWORD_CWORD_CWORD_CWORD,
2823 /* 91 -39 */ CWORD_CWORD_CWORD_CWORD,
2824 /* 92 -38 */ CWORD_CWORD_CWORD_CWORD,
2825 /* 93 -37 */ CWORD_CWORD_CWORD_CWORD,
2826 /* 94 -36 */ CWORD_CWORD_CWORD_CWORD,
2827 /* 95 -35 */ CWORD_CWORD_CWORD_CWORD,
2828 /* 96 -34 */ CWORD_CWORD_CWORD_CWORD,
2829 /* 97 -33 */ CWORD_CWORD_CWORD_CWORD,
2830 /* 98 -32 */ CWORD_CWORD_CWORD_CWORD,
2831 /* 99 -31 */ CWORD_CWORD_CWORD_CWORD,
2832 /* 100 -30 */ CWORD_CWORD_CWORD_CWORD,
2833 /* 101 -29 */ CWORD_CWORD_CWORD_CWORD,
2834 /* 102 -28 */ CWORD_CWORD_CWORD_CWORD,
2835 /* 103 -27 */ CWORD_CWORD_CWORD_CWORD,
2836 /* 104 -26 */ CWORD_CWORD_CWORD_CWORD,
2837 /* 105 -25 */ CWORD_CWORD_CWORD_CWORD,
2838 /* 106 -24 */ CWORD_CWORD_CWORD_CWORD,
2839 /* 107 -23 */ CWORD_CWORD_CWORD_CWORD,
2840 /* 108 -22 */ CWORD_CWORD_CWORD_CWORD,
2841 /* 109 -21 */ CWORD_CWORD_CWORD_CWORD,
2842 /* 110 -20 */ CWORD_CWORD_CWORD_CWORD,
2843 /* 111 -19 */ CWORD_CWORD_CWORD_CWORD,
2844 /* 112 -18 */ CWORD_CWORD_CWORD_CWORD,
2845 /* 113 -17 */ CWORD_CWORD_CWORD_CWORD,
2846 /* 114 -16 */ CWORD_CWORD_CWORD_CWORD,
2847 /* 115 -15 */ CWORD_CWORD_CWORD_CWORD,
2848 /* 116 -14 */ CWORD_CWORD_CWORD_CWORD,
2849 /* 117 -13 */ CWORD_CWORD_CWORD_CWORD,
2850 /* 118 -12 */ CWORD_CWORD_CWORD_CWORD,
2851 /* 119 -11 */ CWORD_CWORD_CWORD_CWORD,
2852 /* 120 -10 */ CWORD_CWORD_CWORD_CWORD,
2853 /* 121 -9 */ CWORD_CWORD_CWORD_CWORD,
2854 /* 122 -8 */ CWORD_CWORD_CWORD_CWORD,
2855 /* 123 -7 */ CWORD_CWORD_CWORD_CWORD,
2856 /* 124 -6 */ CWORD_CWORD_CWORD_CWORD,
2857 /* 125 -5 */ CWORD_CWORD_CWORD_CWORD,
2858 /* 126 -4 */ CWORD_CWORD_CWORD_CWORD,
2859 /* 127 -3 */ CWORD_CWORD_CWORD_CWORD,
2860 /* 128 -2 */ CWORD_CWORD_CWORD_CWORD,
2861 /* 129 -1 */ CWORD_CWORD_CWORD_CWORD,
2862 /* 130 0 */ CWORD_CWORD_CWORD_CWORD,
2863 /* 131 1 */ CWORD_CWORD_CWORD_CWORD,
2864 /* 132 2 */ CWORD_CWORD_CWORD_CWORD,
2865 /* 133 3 */ CWORD_CWORD_CWORD_CWORD,
2866 /* 134 4 */ CWORD_CWORD_CWORD_CWORD,
2867 /* 135 5 */ CWORD_CWORD_CWORD_CWORD,
2868 /* 136 6 */ CWORD_CWORD_CWORD_CWORD,
2869 /* 137 7 */ CWORD_CWORD_CWORD_CWORD,
2870 /* 138 8 */ CWORD_CWORD_CWORD_CWORD,
2871 /* 139 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
2872 /* 140 10 "\n" */ CNL_CNL_CNL_CNL,
2873 /* 141 11 */ CWORD_CWORD_CWORD_CWORD,
2874 /* 142 12 */ CWORD_CWORD_CWORD_CWORD,
2875 /* 143 13 */ CWORD_CWORD_CWORD_CWORD,
2876 /* 144 14 */ CWORD_CWORD_CWORD_CWORD,
2877 /* 145 15 */ CWORD_CWORD_CWORD_CWORD,
2878 /* 146 16 */ CWORD_CWORD_CWORD_CWORD,
2879 /* 147 17 */ CWORD_CWORD_CWORD_CWORD,
2880 /* 148 18 */ CWORD_CWORD_CWORD_CWORD,
2881 /* 149 19 */ CWORD_CWORD_CWORD_CWORD,
2882 /* 150 20 */ CWORD_CWORD_CWORD_CWORD,
2883 /* 151 21 */ CWORD_CWORD_CWORD_CWORD,
2884 /* 152 22 */ CWORD_CWORD_CWORD_CWORD,
2885 /* 153 23 */ CWORD_CWORD_CWORD_CWORD,
2886 /* 154 24 */ CWORD_CWORD_CWORD_CWORD,
2887 /* 155 25 */ CWORD_CWORD_CWORD_CWORD,
2888 /* 156 26 */ CWORD_CWORD_CWORD_CWORD,
2889 /* 157 27 */ CWORD_CWORD_CWORD_CWORD,
2890 /* 158 28 */ CWORD_CWORD_CWORD_CWORD,
2891 /* 159 29 */ CWORD_CWORD_CWORD_CWORD,
2892 /* 160 30 */ CWORD_CWORD_CWORD_CWORD,
2893 /* 161 31 */ CWORD_CWORD_CWORD_CWORD,
2894 /* 162 32 " " */ CSPCL_CWORD_CWORD_CWORD,
2895 /* 163 33 "!" */ CWORD_CCTL_CCTL_CWORD,
Eric Andersenc470f442003-07-28 09:56:35 +00002896 /* 164 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00002897 /* 165 35 "#" */ CWORD_CWORD_CWORD_CWORD,
2898 /* 166 36 "$" */ CVAR_CVAR_CWORD_CVAR,
2899 /* 167 37 "%" */ CWORD_CWORD_CWORD_CWORD,
2900 /* 168 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
Eric Andersenc470f442003-07-28 09:56:35 +00002901 /* 169 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00002902 /* 170 40 "(" */ CSPCL_CWORD_CWORD_CLP,
2903 /* 171 41 ")" */ CSPCL_CWORD_CWORD_CRP,
2904 /* 172 42 "*" */ CWORD_CCTL_CCTL_CWORD,
2905 /* 173 43 "+" */ CWORD_CWORD_CWORD_CWORD,
2906 /* 174 44 "," */ CWORD_CWORD_CWORD_CWORD,
2907 /* 175 45 "-" */ CWORD_CCTL_CCTL_CWORD,
2908 /* 176 46 "." */ CWORD_CWORD_CWORD_CWORD,
2909 /* 177 47 "/" */ CWORD_CCTL_CCTL_CWORD,
2910 /* 178 48 "0" */ CWORD_CWORD_CWORD_CWORD,
2911 /* 179 49 "1" */ CWORD_CWORD_CWORD_CWORD,
2912 /* 180 50 "2" */ CWORD_CWORD_CWORD_CWORD,
2913 /* 181 51 "3" */ CWORD_CWORD_CWORD_CWORD,
2914 /* 182 52 "4" */ CWORD_CWORD_CWORD_CWORD,
2915 /* 183 53 "5" */ CWORD_CWORD_CWORD_CWORD,
2916 /* 184 54 "6" */ CWORD_CWORD_CWORD_CWORD,
2917 /* 185 55 "7" */ CWORD_CWORD_CWORD_CWORD,
2918 /* 186 56 "8" */ CWORD_CWORD_CWORD_CWORD,
2919 /* 187 57 "9" */ CWORD_CWORD_CWORD_CWORD,
2920 /* 188 58 ":" */ CWORD_CCTL_CCTL_CWORD,
2921 /* 189 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
2922 /* 190 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
2923 /* 191 61 "=" */ CWORD_CCTL_CCTL_CWORD,
2924 /* 192 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
2925 /* 193 63 "?" */ CWORD_CCTL_CCTL_CWORD,
2926 /* 194 64 "@" */ CWORD_CWORD_CWORD_CWORD,
2927 /* 195 65 "A" */ CWORD_CWORD_CWORD_CWORD,
2928 /* 196 66 "B" */ CWORD_CWORD_CWORD_CWORD,
2929 /* 197 67 "C" */ CWORD_CWORD_CWORD_CWORD,
2930 /* 198 68 "D" */ CWORD_CWORD_CWORD_CWORD,
2931 /* 199 69 "E" */ CWORD_CWORD_CWORD_CWORD,
2932 /* 200 70 "F" */ CWORD_CWORD_CWORD_CWORD,
2933 /* 201 71 "G" */ CWORD_CWORD_CWORD_CWORD,
2934 /* 202 72 "H" */ CWORD_CWORD_CWORD_CWORD,
2935 /* 203 73 "I" */ CWORD_CWORD_CWORD_CWORD,
2936 /* 204 74 "J" */ CWORD_CWORD_CWORD_CWORD,
2937 /* 205 75 "K" */ CWORD_CWORD_CWORD_CWORD,
2938 /* 206 76 "L" */ CWORD_CWORD_CWORD_CWORD,
2939 /* 207 77 "M" */ CWORD_CWORD_CWORD_CWORD,
2940 /* 208 78 "N" */ CWORD_CWORD_CWORD_CWORD,
2941 /* 209 79 "O" */ CWORD_CWORD_CWORD_CWORD,
2942 /* 210 80 "P" */ CWORD_CWORD_CWORD_CWORD,
2943 /* 211 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
2944 /* 212 82 "R" */ CWORD_CWORD_CWORD_CWORD,
2945 /* 213 83 "S" */ CWORD_CWORD_CWORD_CWORD,
2946 /* 214 84 "T" */ CWORD_CWORD_CWORD_CWORD,
2947 /* 215 85 "U" */ CWORD_CWORD_CWORD_CWORD,
2948 /* 216 86 "V" */ CWORD_CWORD_CWORD_CWORD,
2949 /* 217 87 "W" */ CWORD_CWORD_CWORD_CWORD,
2950 /* 218 88 "X" */ CWORD_CWORD_CWORD_CWORD,
2951 /* 219 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
2952 /* 220 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
2953 /* 221 91 "[" */ CWORD_CCTL_CCTL_CWORD,
2954 /* 222 92 "\" */ CBACK_CBACK_CCTL_CBACK,
2955 /* 223 93 "]" */ CWORD_CCTL_CCTL_CWORD,
2956 /* 224 94 "^" */ CWORD_CWORD_CWORD_CWORD,
2957 /* 225 95 "_" */ CWORD_CWORD_CWORD_CWORD,
2958 /* 226 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
2959 /* 227 97 "a" */ CWORD_CWORD_CWORD_CWORD,
2960 /* 228 98 "b" */ CWORD_CWORD_CWORD_CWORD,
2961 /* 229 99 "c" */ CWORD_CWORD_CWORD_CWORD,
2962 /* 230 100 "d" */ CWORD_CWORD_CWORD_CWORD,
2963 /* 231 101 "e" */ CWORD_CWORD_CWORD_CWORD,
2964 /* 232 102 "f" */ CWORD_CWORD_CWORD_CWORD,
2965 /* 233 103 "g" */ CWORD_CWORD_CWORD_CWORD,
2966 /* 234 104 "h" */ CWORD_CWORD_CWORD_CWORD,
2967 /* 235 105 "i" */ CWORD_CWORD_CWORD_CWORD,
2968 /* 236 106 "j" */ CWORD_CWORD_CWORD_CWORD,
2969 /* 237 107 "k" */ CWORD_CWORD_CWORD_CWORD,
2970 /* 238 108 "l" */ CWORD_CWORD_CWORD_CWORD,
2971 /* 239 109 "m" */ CWORD_CWORD_CWORD_CWORD,
2972 /* 240 110 "n" */ CWORD_CWORD_CWORD_CWORD,
2973 /* 241 111 "o" */ CWORD_CWORD_CWORD_CWORD,
2974 /* 242 112 "p" */ CWORD_CWORD_CWORD_CWORD,
2975 /* 243 113 "q" */ CWORD_CWORD_CWORD_CWORD,
2976 /* 244 114 "r" */ CWORD_CWORD_CWORD_CWORD,
2977 /* 245 115 "s" */ CWORD_CWORD_CWORD_CWORD,
2978 /* 246 116 "t" */ CWORD_CWORD_CWORD_CWORD,
2979 /* 247 117 "u" */ CWORD_CWORD_CWORD_CWORD,
2980 /* 248 118 "v" */ CWORD_CWORD_CWORD_CWORD,
2981 /* 249 119 "w" */ CWORD_CWORD_CWORD_CWORD,
2982 /* 250 120 "x" */ CWORD_CWORD_CWORD_CWORD,
2983 /* 251 121 "y" */ CWORD_CWORD_CWORD_CWORD,
2984 /* 252 122 "z" */ CWORD_CWORD_CWORD_CWORD,
2985 /* 253 123 "{" */ CWORD_CWORD_CWORD_CWORD,
2986 /* 254 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
2987 /* 255 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
2988 /* 256 126 "~" */ CWORD_CCTL_CCTL_CWORD,
2989 /* 257 127 */ CWORD_CWORD_CWORD_CWORD,
Eric Andersen2870d962001-07-02 17:27:21 +00002990};
2991
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00002992#define SIT(c, syntax) (S_I_T[(int)syntax_index_table[((int)c)+SYNBASE]][syntax])
2993
"Vladimir N. Oleynik"fdb871c2006-01-25 11:53:47 +00002994#endif /* USE_SIT_FUNCTION */
Eric Andersenc470f442003-07-28 09:56:35 +00002995
Eric Andersen2870d962001-07-02 17:27:21 +00002996
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00002997/* ============ Alias handling */
Denis Vlasenkofc06f292007-02-23 21:09:35 +00002998
Denis Vlasenko131ae172007-02-18 13:00:19 +00002999#if ENABLE_ASH_ALIAS
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00003000
3001#define ALIASINUSE 1
3002#define ALIASDEAD 2
3003
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00003004struct alias {
3005 struct alias *next;
3006 char *name;
3007 char *val;
3008 int flag;
3009};
3010
Denis Vlasenko01631112007-12-16 17:20:38 +00003011
3012static struct alias **atab; // [ATABSIZE];
3013#define INIT_G_alias() do { \
3014 atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
3015} while (0)
3016
Eric Andersen2870d962001-07-02 17:27:21 +00003017
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00003018static struct alias **
3019__lookupalias(const char *name) {
3020 unsigned int hashval;
3021 struct alias **app;
3022 const char *p;
3023 unsigned int ch;
3024
3025 p = name;
3026
3027 ch = (unsigned char)*p;
3028 hashval = ch << 4;
3029 while (ch) {
3030 hashval += ch;
3031 ch = (unsigned char)*++p;
3032 }
3033 app = &atab[hashval % ATABSIZE];
3034
3035 for (; *app; app = &(*app)->next) {
3036 if (strcmp(name, (*app)->name) == 0) {
3037 break;
3038 }
3039 }
3040
3041 return app;
3042}
3043
3044static struct alias *
3045lookupalias(const char *name, int check)
3046{
3047 struct alias *ap = *__lookupalias(name);
3048
3049 if (check && ap && (ap->flag & ALIASINUSE))
3050 return NULL;
3051 return ap;
3052}
3053
3054static struct alias *
3055freealias(struct alias *ap)
3056{
3057 struct alias *next;
3058
3059 if (ap->flag & ALIASINUSE) {
3060 ap->flag |= ALIASDEAD;
3061 return ap;
3062 }
3063
3064 next = ap->next;
3065 free(ap->name);
3066 free(ap->val);
3067 free(ap);
3068 return next;
3069}
Eric Andersencb57d552001-06-28 07:25:16 +00003070
Eric Andersenc470f442003-07-28 09:56:35 +00003071static void
3072setalias(const char *name, const char *val)
Eric Andersencb57d552001-06-28 07:25:16 +00003073{
3074 struct alias *ap, **app;
3075
3076 app = __lookupalias(name);
3077 ap = *app;
Denis Vlasenkob012b102007-02-19 22:43:01 +00003078 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +00003079 if (ap) {
3080 if (!(ap->flag & ALIASINUSE)) {
Denis Vlasenkob012b102007-02-19 22:43:01 +00003081 free(ap->val);
Eric Andersencb57d552001-06-28 07:25:16 +00003082 }
Denis Vlasenko0c032a42007-02-23 01:03:40 +00003083 ap->val = ckstrdup(val);
Eric Andersencb57d552001-06-28 07:25:16 +00003084 ap->flag &= ~ALIASDEAD;
3085 } else {
3086 /* not found */
Denis Vlasenko597906c2008-02-20 16:38:54 +00003087 ap = ckzalloc(sizeof(struct alias));
Denis Vlasenko0c032a42007-02-23 01:03:40 +00003088 ap->name = ckstrdup(name);
3089 ap->val = ckstrdup(val);
Denis Vlasenko597906c2008-02-20 16:38:54 +00003090 /*ap->flag = 0; - ckzalloc did it */
3091 /*ap->next = NULL;*/
Eric Andersencb57d552001-06-28 07:25:16 +00003092 *app = ap;
3093 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00003094 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00003095}
3096
Eric Andersenc470f442003-07-28 09:56:35 +00003097static int
3098unalias(const char *name)
Eric Andersen2870d962001-07-02 17:27:21 +00003099{
Eric Andersencb57d552001-06-28 07:25:16 +00003100 struct alias **app;
3101
3102 app = __lookupalias(name);
3103
3104 if (*app) {
Denis Vlasenkob012b102007-02-19 22:43:01 +00003105 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +00003106 *app = freealias(*app);
Denis Vlasenkob012b102007-02-19 22:43:01 +00003107 INT_ON;
Denis Vlasenko079f8af2006-11-27 16:49:31 +00003108 return 0;
Eric Andersencb57d552001-06-28 07:25:16 +00003109 }
3110
Denis Vlasenko079f8af2006-11-27 16:49:31 +00003111 return 1;
Eric Andersencb57d552001-06-28 07:25:16 +00003112}
3113
Eric Andersenc470f442003-07-28 09:56:35 +00003114static void
3115rmaliases(void)
Eric Andersen2870d962001-07-02 17:27:21 +00003116{
Eric Andersencb57d552001-06-28 07:25:16 +00003117 struct alias *ap, **app;
3118 int i;
3119
Denis Vlasenkob012b102007-02-19 22:43:01 +00003120 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +00003121 for (i = 0; i < ATABSIZE; i++) {
3122 app = &atab[i];
3123 for (ap = *app; ap; ap = *app) {
3124 *app = freealias(*app);
3125 if (ap == *app) {
3126 app = &ap->next;
3127 }
3128 }
3129 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00003130 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00003131}
3132
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00003133static void
3134printalias(const struct alias *ap)
3135{
3136 out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
3137}
3138
Eric Andersencb57d552001-06-28 07:25:16 +00003139/*
3140 * TODO - sort output
3141 */
Eric Andersenc470f442003-07-28 09:56:35 +00003142static int
3143aliascmd(int argc, char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +00003144{
3145 char *n, *v;
3146 int ret = 0;
3147 struct alias *ap;
3148
3149 if (argc == 1) {
3150 int i;
3151
3152 for (i = 0; i < ATABSIZE; i++)
3153 for (ap = atab[i]; ap; ap = ap->next) {
3154 printalias(ap);
3155 }
Denis Vlasenko079f8af2006-11-27 16:49:31 +00003156 return 0;
Eric Andersencb57d552001-06-28 07:25:16 +00003157 }
3158 while ((n = *++argv) != NULL) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00003159 v = strchr(n+1, '=');
3160 if (v == NULL) { /* n+1: funny ksh stuff */
3161 ap = *__lookupalias(n);
3162 if (ap == NULL) {
Eric Andersenc470f442003-07-28 09:56:35 +00003163 fprintf(stderr, "%s: %s not found\n", "alias", n);
Eric Andersencb57d552001-06-28 07:25:16 +00003164 ret = 1;
3165 } else
3166 printalias(ap);
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00003167 } else {
Eric Andersencb57d552001-06-28 07:25:16 +00003168 *v++ = '\0';
3169 setalias(n, v);
3170 }
3171 }
3172
Denis Vlasenkod9e15f22006-11-27 16:49:55 +00003173 return ret;
Eric Andersencb57d552001-06-28 07:25:16 +00003174}
3175
Eric Andersenc470f442003-07-28 09:56:35 +00003176static int
3177unaliascmd(int argc, char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +00003178{
3179 int i;
3180
3181 while ((i = nextopt("a")) != '\0') {
3182 if (i == 'a') {
3183 rmaliases();
Denis Vlasenko079f8af2006-11-27 16:49:31 +00003184 return 0;
Eric Andersencb57d552001-06-28 07:25:16 +00003185 }
3186 }
3187 for (i = 0; *argptr; argptr++) {
3188 if (unalias(*argptr)) {
Eric Andersenc470f442003-07-28 09:56:35 +00003189 fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
Eric Andersencb57d552001-06-28 07:25:16 +00003190 i = 1;
3191 }
3192 }
3193
Denis Vlasenkod9e15f22006-11-27 16:49:55 +00003194 return i;
Eric Andersencb57d552001-06-28 07:25:16 +00003195}
Denis Vlasenkofc06f292007-02-23 21:09:35 +00003196
Denis Vlasenko131ae172007-02-18 13:00:19 +00003197#endif /* ASH_ALIAS */
Eric Andersencb57d552001-06-28 07:25:16 +00003198
Eric Andersenc470f442003-07-28 09:56:35 +00003199
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003200/* ============ jobs.c */
3201
3202/* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
3203#define FORK_FG 0
3204#define FORK_BG 1
3205#define FORK_NOJOB 2
3206
3207/* mode flags for showjob(s) */
3208#define SHOW_PGID 0x01 /* only show pgid - for jobs -p */
3209#define SHOW_PID 0x04 /* include process pid */
3210#define SHOW_CHANGED 0x08 /* only jobs whose state has changed */
3211
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003212/*
3213 * A job structure contains information about a job. A job is either a
3214 * single process or a set of processes contained in a pipeline. In the
3215 * latter case, pidlist will be non-NULL, and will point to a -1 terminated
3216 * array of pids.
3217 */
3218
3219struct procstat {
3220 pid_t pid; /* process id */
3221 int status; /* last process status from wait() */
3222 char *cmd; /* text of command being run */
3223};
3224
3225struct job {
3226 struct procstat ps0; /* status of process */
3227 struct procstat *ps; /* status or processes when more than one */
3228#if JOBS
3229 int stopstatus; /* status of a stopped job */
3230#endif
3231 uint32_t
3232 nprocs: 16, /* number of processes */
3233 state: 8,
3234#define JOBRUNNING 0 /* at least one proc running */
3235#define JOBSTOPPED 1 /* all procs are stopped */
3236#define JOBDONE 2 /* all procs are completed */
3237#if JOBS
3238 sigint: 1, /* job was killed by SIGINT */
3239 jobctl: 1, /* job running under job control */
3240#endif
3241 waited: 1, /* true if this entry has been waited for */
3242 used: 1, /* true if this entry is in used */
3243 changed: 1; /* true if status has changed */
3244 struct job *prev_job; /* previous job */
3245};
3246
3247static pid_t backgndpid; /* pid of last background process */
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003248static smallint job_warning; /* user was warned about stopped jobs (can be 2, 1 or 0). */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003249
3250static struct job *makejob(union node *, int);
3251static int forkshell(struct job *, union node *, int);
3252static int waitforjob(struct job *);
3253
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003254#if !JOBS
3255enum { jobctl = 0 };
3256#define setjobctl(on) do {} while (0)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003257#else
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003258static smallint jobctl; /* true if doing job control */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003259static void setjobctl(int);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003260#endif
3261
3262/*
3263 * Set the signal handler for the specified signal. The routine figures
3264 * out what it should be set to.
3265 */
3266static void
3267setsignal(int signo)
3268{
3269 int action;
3270 char *t, tsig;
3271 struct sigaction act;
3272
3273 t = trap[signo];
Denis Vlasenko991a1da2008-02-10 19:02:53 +00003274 action = S_IGN;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003275 if (t == NULL)
3276 action = S_DFL;
3277 else if (*t != '\0')
3278 action = S_CATCH;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003279 if (rootshell && action == S_DFL) {
3280 switch (signo) {
3281 case SIGINT:
3282 if (iflag || minusc || sflag == 0)
3283 action = S_CATCH;
3284 break;
3285 case SIGQUIT:
3286#if DEBUG
3287 if (debug)
3288 break;
3289#endif
3290 /* FALLTHROUGH */
3291 case SIGTERM:
3292 if (iflag)
3293 action = S_IGN;
3294 break;
3295#if JOBS
3296 case SIGTSTP:
3297 case SIGTTOU:
3298 if (mflag)
3299 action = S_IGN;
3300 break;
3301#endif
3302 }
3303 }
3304
3305 t = &sigmode[signo - 1];
3306 tsig = *t;
3307 if (tsig == 0) {
3308 /*
3309 * current setting unknown
3310 */
Denis Vlasenko991a1da2008-02-10 19:02:53 +00003311 if (sigaction(signo, NULL, &act) == -1) {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003312 /*
3313 * Pretend it worked; maybe we should give a warning
3314 * here, but other shells don't. We don't alter
3315 * sigmode, so that we retry every time.
3316 */
3317 return;
3318 }
Denis Vlasenko991a1da2008-02-10 19:02:53 +00003319 tsig = S_RESET; /* force to be set */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003320 if (act.sa_handler == SIG_IGN) {
Denis Vlasenko991a1da2008-02-10 19:02:53 +00003321 tsig = S_HARD_IGN;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003322 if (mflag
3323 && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
3324 ) {
3325 tsig = S_IGN; /* don't hard ignore these */
Denis Vlasenko991a1da2008-02-10 19:02:53 +00003326 }
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003327 }
3328 }
3329 if (tsig == S_HARD_IGN || tsig == action)
3330 return;
Denis Vlasenko991a1da2008-02-10 19:02:53 +00003331 act.sa_handler = SIG_DFL;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003332 switch (action) {
3333 case S_CATCH:
3334 act.sa_handler = onsig;
3335 break;
3336 case S_IGN:
3337 act.sa_handler = SIG_IGN;
3338 break;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003339 }
3340 *t = action;
3341 act.sa_flags = 0;
3342 sigfillset(&act.sa_mask);
Denis Vlasenko991a1da2008-02-10 19:02:53 +00003343 sigaction(signo, &act, NULL);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003344}
3345
3346/* mode flags for set_curjob */
3347#define CUR_DELETE 2
3348#define CUR_RUNNING 1
3349#define CUR_STOPPED 0
3350
3351/* mode flags for dowait */
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00003352#define DOWAIT_NONBLOCK WNOHANG
3353#define DOWAIT_BLOCK 0
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003354
3355#if JOBS
3356/* pgrp of shell on invocation */
3357static int initialpgrp;
3358static int ttyfd = -1;
3359#endif
3360/* array of jobs */
3361static struct job *jobtab;
3362/* size of array */
3363static unsigned njobs;
3364/* current job */
3365static struct job *curjob;
3366/* number of presumed living untracked jobs */
3367static int jobless;
3368
3369static void
3370set_curjob(struct job *jp, unsigned mode)
3371{
3372 struct job *jp1;
3373 struct job **jpp, **curp;
3374
3375 /* first remove from list */
3376 jpp = curp = &curjob;
3377 do {
3378 jp1 = *jpp;
3379 if (jp1 == jp)
3380 break;
3381 jpp = &jp1->prev_job;
3382 } while (1);
3383 *jpp = jp1->prev_job;
3384
3385 /* Then re-insert in correct position */
3386 jpp = curp;
3387 switch (mode) {
3388 default:
3389#if DEBUG
3390 abort();
3391#endif
3392 case CUR_DELETE:
3393 /* job being deleted */
3394 break;
3395 case CUR_RUNNING:
3396 /* newly created job or backgrounded job,
3397 put after all stopped jobs. */
3398 do {
3399 jp1 = *jpp;
3400#if JOBS
3401 if (!jp1 || jp1->state != JOBSTOPPED)
3402#endif
3403 break;
3404 jpp = &jp1->prev_job;
3405 } while (1);
3406 /* FALLTHROUGH */
3407#if JOBS
3408 case CUR_STOPPED:
3409#endif
3410 /* newly stopped job - becomes curjob */
3411 jp->prev_job = *jpp;
3412 *jpp = jp;
3413 break;
3414 }
3415}
3416
3417#if JOBS || DEBUG
3418static int
3419jobno(const struct job *jp)
3420{
3421 return jp - jobtab + 1;
3422}
3423#endif
3424
3425/*
3426 * Convert a job name to a job structure.
3427 */
3428static struct job *
3429getjob(const char *name, int getctl)
3430{
3431 struct job *jp;
3432 struct job *found;
3433 const char *err_msg = "No such job: %s";
3434 unsigned num;
3435 int c;
3436 const char *p;
3437 char *(*match)(const char *, const char *);
3438
3439 jp = curjob;
3440 p = name;
3441 if (!p)
3442 goto currentjob;
3443
3444 if (*p != '%')
3445 goto err;
3446
3447 c = *++p;
3448 if (!c)
3449 goto currentjob;
3450
3451 if (!p[1]) {
3452 if (c == '+' || c == '%') {
3453 currentjob:
3454 err_msg = "No current job";
3455 goto check;
3456 }
3457 if (c == '-') {
3458 if (jp)
3459 jp = jp->prev_job;
3460 err_msg = "No previous job";
3461 check:
3462 if (!jp)
3463 goto err;
3464 goto gotit;
3465 }
3466 }
3467
3468 if (is_number(p)) {
3469 num = atoi(p);
3470 if (num < njobs) {
3471 jp = jobtab + num - 1;
3472 if (jp->used)
3473 goto gotit;
3474 goto err;
3475 }
3476 }
3477
3478 match = prefix;
3479 if (*p == '?') {
3480 match = strstr;
3481 p++;
3482 }
3483
3484 found = 0;
3485 while (1) {
3486 if (!jp)
3487 goto err;
3488 if (match(jp->ps[0].cmd, p)) {
3489 if (found)
3490 goto err;
3491 found = jp;
3492 err_msg = "%s: ambiguous";
3493 }
3494 jp = jp->prev_job;
3495 }
3496
3497 gotit:
3498#if JOBS
3499 err_msg = "job %s not created under job control";
3500 if (getctl && jp->jobctl == 0)
3501 goto err;
3502#endif
3503 return jp;
3504 err:
3505 ash_msg_and_raise_error(err_msg, name);
3506}
3507
3508/*
3509 * Mark a job structure as unused.
3510 */
3511static void
3512freejob(struct job *jp)
3513{
3514 struct procstat *ps;
3515 int i;
3516
3517 INT_OFF;
3518 for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
3519 if (ps->cmd != nullstr)
3520 free(ps->cmd);
3521 }
3522 if (jp->ps != &jp->ps0)
3523 free(jp->ps);
3524 jp->used = 0;
3525 set_curjob(jp, CUR_DELETE);
3526 INT_ON;
3527}
3528
3529#if JOBS
3530static void
3531xtcsetpgrp(int fd, pid_t pgrp)
3532{
3533 if (tcsetpgrp(fd, pgrp))
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00003534 ash_msg_and_raise_error("cannot set tty process group (%m)");
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003535}
3536
3537/*
3538 * Turn job control on and off.
3539 *
3540 * Note: This code assumes that the third arg to ioctl is a character
3541 * pointer, which is true on Berkeley systems but not System V. Since
3542 * System V doesn't have job control yet, this isn't a problem now.
3543 *
3544 * Called with interrupts off.
3545 */
3546static void
3547setjobctl(int on)
3548{
3549 int fd;
3550 int pgrp;
3551
3552 if (on == jobctl || rootshell == 0)
3553 return;
3554 if (on) {
3555 int ofd;
3556 ofd = fd = open(_PATH_TTY, O_RDWR);
3557 if (fd < 0) {
3558 /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
3559 * That sometimes helps to acquire controlling tty.
3560 * Obviously, a workaround for bugs when someone
3561 * failed to provide a controlling tty to bash! :) */
Denis Vlasenkoed270a52007-11-26 05:37:07 +00003562 fd = 2;
3563 while (!isatty(fd))
3564 if (--fd < 0)
3565 goto out;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003566 }
3567 fd = fcntl(fd, F_DUPFD, 10);
Denis Vlasenkoed270a52007-11-26 05:37:07 +00003568 if (ofd >= 0)
3569 close(ofd);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003570 if (fd < 0)
3571 goto out;
Denis Vlasenkoed270a52007-11-26 05:37:07 +00003572 /* fd is a tty at this point */
Denis Vlasenko96e1b382007-09-30 23:50:48 +00003573 close_on_exec_on(fd);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003574 do { /* while we are in the background */
3575 pgrp = tcgetpgrp(fd);
3576 if (pgrp < 0) {
3577 out:
3578 ash_msg("can't access tty; job control turned off");
3579 mflag = on = 0;
3580 goto close;
3581 }
3582 if (pgrp == getpgrp())
3583 break;
3584 killpg(0, SIGTTIN);
3585 } while (1);
3586 initialpgrp = pgrp;
3587
3588 setsignal(SIGTSTP);
3589 setsignal(SIGTTOU);
3590 setsignal(SIGTTIN);
3591 pgrp = rootpid;
3592 setpgid(0, pgrp);
3593 xtcsetpgrp(fd, pgrp);
3594 } else {
3595 /* turning job control off */
3596 fd = ttyfd;
3597 pgrp = initialpgrp;
Denis Vlasenko08c8c1d2007-04-28 22:39:02 +00003598 /* was xtcsetpgrp, but this can make exiting ash
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00003599 * loop forever if pty is already deleted */
Denis Vlasenko08c8c1d2007-04-28 22:39:02 +00003600 tcsetpgrp(fd, pgrp);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003601 setpgid(0, pgrp);
3602 setsignal(SIGTSTP);
3603 setsignal(SIGTTOU);
3604 setsignal(SIGTTIN);
3605 close:
Denis Vlasenkoed270a52007-11-26 05:37:07 +00003606 if (fd >= 0)
3607 close(fd);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003608 fd = -1;
3609 }
3610 ttyfd = fd;
3611 jobctl = on;
3612}
3613
3614static int
3615killcmd(int argc, char **argv)
3616{
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003617 if (argv[1] && strcmp(argv[1], "-l") != 0) {
3618 int i = 1;
3619 do {
3620 if (argv[i][0] == '%') {
3621 struct job *jp = getjob(argv[i], 0);
3622 unsigned pid = jp->ps[0].pid;
3623 /* Enough space for ' -NNN<nul>' */
3624 argv[i] = alloca(sizeof(int)*3 + 3);
3625 /* kill_main has matching code to expect
3626 * leading space. Needed to not confuse
3627 * negative pids with "kill -SIGNAL_NO" syntax */
3628 sprintf(argv[i], " -%u", pid);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003629 }
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003630 } while (argv[++i]);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003631 }
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003632 return kill_main(argc, argv);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003633}
3634
3635static void
3636showpipe(struct job *jp, FILE *out)
3637{
3638 struct procstat *sp;
3639 struct procstat *spend;
3640
3641 spend = jp->ps + jp->nprocs;
3642 for (sp = jp->ps + 1; sp < spend; sp++)
3643 fprintf(out, " | %s", sp->cmd);
3644 outcslow('\n', out);
3645 flush_stdout_stderr();
3646}
3647
3648
3649static int
3650restartjob(struct job *jp, int mode)
3651{
3652 struct procstat *ps;
3653 int i;
3654 int status;
3655 pid_t pgid;
3656
3657 INT_OFF;
3658 if (jp->state == JOBDONE)
3659 goto out;
3660 jp->state = JOBRUNNING;
3661 pgid = jp->ps->pid;
3662 if (mode == FORK_FG)
3663 xtcsetpgrp(ttyfd, pgid);
3664 killpg(pgid, SIGCONT);
3665 ps = jp->ps;
3666 i = jp->nprocs;
3667 do {
3668 if (WIFSTOPPED(ps->status)) {
3669 ps->status = -1;
3670 }
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003671 ps++;
3672 } while (--i);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003673 out:
3674 status = (mode == FORK_FG) ? waitforjob(jp) : 0;
3675 INT_ON;
3676 return status;
3677}
3678
3679static int
3680fg_bgcmd(int argc, char **argv)
3681{
3682 struct job *jp;
3683 FILE *out;
3684 int mode;
3685 int retval;
3686
3687 mode = (**argv == 'f') ? FORK_FG : FORK_BG;
3688 nextopt(nullstr);
3689 argv = argptr;
3690 out = stdout;
3691 do {
3692 jp = getjob(*argv, 1);
3693 if (mode == FORK_BG) {
3694 set_curjob(jp, CUR_RUNNING);
3695 fprintf(out, "[%d] ", jobno(jp));
3696 }
3697 outstr(jp->ps->cmd, out);
3698 showpipe(jp, out);
3699 retval = restartjob(jp, mode);
3700 } while (*argv && *++argv);
3701 return retval;
3702}
3703#endif
3704
3705static int
3706sprint_status(char *s, int status, int sigonly)
3707{
3708 int col;
3709 int st;
3710
3711 col = 0;
3712 if (!WIFEXITED(status)) {
3713#if JOBS
3714 if (WIFSTOPPED(status))
3715 st = WSTOPSIG(status);
3716 else
3717#endif
3718 st = WTERMSIG(status);
3719 if (sigonly) {
3720 if (st == SIGINT || st == SIGPIPE)
3721 goto out;
3722#if JOBS
3723 if (WIFSTOPPED(status))
3724 goto out;
3725#endif
3726 }
3727 st &= 0x7f;
3728 col = fmtstr(s, 32, strsignal(st));
3729 if (WCOREDUMP(status)) {
3730 col += fmtstr(s + col, 16, " (core dumped)");
3731 }
3732 } else if (!sigonly) {
3733 st = WEXITSTATUS(status);
3734 if (st)
3735 col = fmtstr(s, 16, "Done(%d)", st);
3736 else
3737 col = fmtstr(s, 16, "Done");
3738 }
3739 out:
3740 return col;
3741}
3742
3743/*
3744 * Do a wait system call. If job control is compiled in, we accept
3745 * stopped processes. If block is zero, we return a value of zero
3746 * rather than blocking.
3747 *
3748 * System V doesn't have a non-blocking wait system call. It does
3749 * have a SIGCLD signal that is sent to a process when one of it's
3750 * children dies. The obvious way to use SIGCLD would be to install
3751 * a handler for SIGCLD which simply bumped a counter when a SIGCLD
3752 * was received, and have waitproc bump another counter when it got
3753 * the status of a process. Waitproc would then know that a wait
3754 * system call would not block if the two counters were different.
3755 * This approach doesn't work because if a process has children that
3756 * have not been waited for, System V will send it a SIGCLD when it
3757 * installs a signal handler for SIGCLD. What this means is that when
3758 * a child exits, the shell will be sent SIGCLD signals continuously
3759 * until is runs out of stack space, unless it does a wait call before
3760 * restoring the signal handler. The code below takes advantage of
3761 * this (mis)feature by installing a signal handler for SIGCLD and
3762 * then checking to see whether it was called. If there are any
3763 * children to be waited for, it will be.
3764 *
3765 * If neither SYSV nor BSD is defined, we don't implement nonblocking
3766 * waits at all. In this case, the user will not be informed when
3767 * a background process until the next time she runs a real program
3768 * (as opposed to running a builtin command or just typing return),
3769 * and the jobs command may give out of date information.
3770 */
3771static int
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00003772waitproc(int wait_flags, int *status)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003773{
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003774#if JOBS
3775 if (jobctl)
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00003776 wait_flags |= WUNTRACED;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003777#endif
Denis Vlasenko991a1da2008-02-10 19:02:53 +00003778 /* NB: _not_ safe_waitpid, we need to detect EINTR */
3779 return waitpid(-1, status, wait_flags);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003780}
3781
3782/*
3783 * Wait for a process to terminate.
3784 */
3785static int
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00003786dowait(int wait_flags, struct job *job)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003787{
3788 int pid;
3789 int status;
3790 struct job *jp;
3791 struct job *thisjob;
3792 int state;
3793
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00003794 TRACE(("dowait(%d) called\n", wait_flags));
3795 pid = waitproc(wait_flags, &status);
3796 TRACE(("wait returns pid=%d, status=%d\n", pid, status));
Denis Vlasenko991a1da2008-02-10 19:02:53 +00003797 if (pid <= 0) {
3798 /* If we were doing blocking wait and (probably) got EINTR,
3799 * check for pending sigs received while waiting.
3800 * (NB: can be moved into callers if needed) */
3801 if (wait_flags == DOWAIT_BLOCK && pendingsig)
3802 raise_exception(EXSIG);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003803 return pid;
Denis Vlasenko991a1da2008-02-10 19:02:53 +00003804 }
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003805 INT_OFF;
3806 thisjob = NULL;
3807 for (jp = curjob; jp; jp = jp->prev_job) {
3808 struct procstat *sp;
3809 struct procstat *spend;
3810 if (jp->state == JOBDONE)
3811 continue;
3812 state = JOBDONE;
3813 spend = jp->ps + jp->nprocs;
3814 sp = jp->ps;
3815 do {
3816 if (sp->pid == pid) {
3817 TRACE(("Job %d: changing status of proc %d "
3818 "from 0x%x to 0x%x\n",
3819 jobno(jp), pid, sp->status, status));
3820 sp->status = status;
3821 thisjob = jp;
3822 }
3823 if (sp->status == -1)
3824 state = JOBRUNNING;
3825#if JOBS
3826 if (state == JOBRUNNING)
3827 continue;
3828 if (WIFSTOPPED(sp->status)) {
3829 jp->stopstatus = sp->status;
3830 state = JOBSTOPPED;
3831 }
3832#endif
3833 } while (++sp < spend);
3834 if (thisjob)
3835 goto gotjob;
3836 }
3837#if JOBS
3838 if (!WIFSTOPPED(status))
3839#endif
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003840 jobless--;
3841 goto out;
3842
3843 gotjob:
3844 if (state != JOBRUNNING) {
3845 thisjob->changed = 1;
3846
3847 if (thisjob->state != state) {
3848 TRACE(("Job %d: changing state from %d to %d\n",
3849 jobno(thisjob), thisjob->state, state));
3850 thisjob->state = state;
3851#if JOBS
3852 if (state == JOBSTOPPED) {
3853 set_curjob(thisjob, CUR_STOPPED);
3854 }
3855#endif
3856 }
3857 }
3858
3859 out:
3860 INT_ON;
3861
3862 if (thisjob && thisjob == job) {
3863 char s[48 + 1];
3864 int len;
3865
3866 len = sprint_status(s, status, 1);
3867 if (len) {
3868 s[len] = '\n';
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00003869 s[len + 1] = '\0';
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003870 out2str(s);
3871 }
3872 }
3873 return pid;
3874}
3875
3876#if JOBS
3877static void
3878showjob(FILE *out, struct job *jp, int mode)
3879{
3880 struct procstat *ps;
3881 struct procstat *psend;
3882 int col;
Denis Vlasenko40ba9982007-07-14 00:48:29 +00003883 int indent_col;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003884 char s[80];
3885
3886 ps = jp->ps;
3887
3888 if (mode & SHOW_PGID) {
3889 /* just output process (group) id of pipeline */
3890 fprintf(out, "%d\n", ps->pid);
3891 return;
3892 }
3893
3894 col = fmtstr(s, 16, "[%d] ", jobno(jp));
Denis Vlasenko40ba9982007-07-14 00:48:29 +00003895 indent_col = col;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003896
3897 if (jp == curjob)
3898 s[col - 2] = '+';
3899 else if (curjob && jp == curjob->prev_job)
3900 s[col - 2] = '-';
3901
3902 if (mode & SHOW_PID)
3903 col += fmtstr(s + col, 16, "%d ", ps->pid);
3904
3905 psend = ps + jp->nprocs;
3906
3907 if (jp->state == JOBRUNNING) {
3908 strcpy(s + col, "Running");
3909 col += sizeof("Running") - 1;
3910 } else {
3911 int status = psend[-1].status;
3912 if (jp->state == JOBSTOPPED)
3913 status = jp->stopstatus;
3914 col += sprint_status(s + col, status, 0);
3915 }
3916
3917 goto start;
3918
3919 do {
3920 /* for each process */
Denis Vlasenko40ba9982007-07-14 00:48:29 +00003921 col = fmtstr(s, 48, " |\n%*c%d ", indent_col, ' ', ps->pid) - 3;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003922 start:
3923 fprintf(out, "%s%*c%s",
3924 s, 33 - col >= 0 ? 33 - col : 0, ' ', ps->cmd
3925 );
3926 if (!(mode & SHOW_PID)) {
3927 showpipe(jp, out);
3928 break;
3929 }
3930 if (++ps == psend) {
3931 outcslow('\n', out);
3932 break;
3933 }
3934 } while (1);
3935
3936 jp->changed = 0;
3937
3938 if (jp->state == JOBDONE) {
3939 TRACE(("showjob: freeing job %d\n", jobno(jp)));
3940 freejob(jp);
3941 }
3942}
3943
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003944/*
3945 * Print a list of jobs. If "change" is nonzero, only print jobs whose
3946 * statuses have changed since the last call to showjobs.
3947 */
3948static void
3949showjobs(FILE *out, int mode)
3950{
3951 struct job *jp;
3952
3953 TRACE(("showjobs(%x) called\n", mode));
3954
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00003955 /* If not even one job changed, there is nothing to do */
3956 while (dowait(DOWAIT_NONBLOCK, NULL) > 0)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003957 continue;
3958
3959 for (jp = curjob; jp; jp = jp->prev_job) {
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003960 if (!(mode & SHOW_CHANGED) || jp->changed) {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003961 showjob(out, jp, mode);
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003962 }
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003963 }
3964}
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003965
3966static int
3967jobscmd(int argc, char **argv)
3968{
3969 int mode, m;
3970
3971 mode = 0;
3972 while ((m = nextopt("lp"))) {
3973 if (m == 'l')
3974 mode = SHOW_PID;
3975 else
3976 mode = SHOW_PGID;
3977 }
3978
3979 argv = argptr;
3980 if (*argv) {
3981 do
3982 showjob(stdout, getjob(*argv,0), mode);
3983 while (*++argv);
3984 } else
3985 showjobs(stdout, mode);
3986
3987 return 0;
3988}
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003989#endif /* JOBS */
3990
3991static int
3992getstatus(struct job *job)
3993{
3994 int status;
3995 int retval;
3996
3997 status = job->ps[job->nprocs - 1].status;
3998 retval = WEXITSTATUS(status);
3999 if (!WIFEXITED(status)) {
4000#if JOBS
4001 retval = WSTOPSIG(status);
4002 if (!WIFSTOPPED(status))
4003#endif
4004 {
4005 /* XXX: limits number of signals */
4006 retval = WTERMSIG(status);
4007#if JOBS
4008 if (retval == SIGINT)
4009 job->sigint = 1;
4010#endif
4011 }
4012 retval += 128;
4013 }
4014 TRACE(("getstatus: job %d, nproc %d, status %x, retval %x\n",
4015 jobno(job), job->nprocs, status, retval));
4016 return retval;
4017}
4018
4019static int
4020waitcmd(int argc, char **argv)
4021{
4022 struct job *job;
4023 int retval;
4024 struct job *jp;
4025
Denis Vlasenko991a1da2008-02-10 19:02:53 +00004026// exsig++;
4027// xbarrier();
4028 if (pendingsig)
4029 raise_exception(EXSIG);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004030
4031 nextopt(nullstr);
4032 retval = 0;
4033
4034 argv = argptr;
4035 if (!*argv) {
4036 /* wait for all jobs */
4037 for (;;) {
4038 jp = curjob;
4039 while (1) {
Denis Vlasenko991a1da2008-02-10 19:02:53 +00004040 if (!jp) /* no running procs */
4041 goto ret;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004042 if (jp->state == JOBRUNNING)
4043 break;
4044 jp->waited = 1;
4045 jp = jp->prev_job;
4046 }
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00004047 dowait(DOWAIT_BLOCK, NULL);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004048 }
4049 }
4050
4051 retval = 127;
4052 do {
4053 if (**argv != '%') {
4054 pid_t pid = number(*argv);
4055 job = curjob;
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00004056 while (1) {
4057 if (!job)
4058 goto repeat;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004059 if (job->ps[job->nprocs - 1].pid == pid)
4060 break;
4061 job = job->prev_job;
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00004062 }
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004063 } else
4064 job = getjob(*argv, 0);
4065 /* loop until process terminated or stopped */
4066 while (job->state == JOBRUNNING)
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00004067 dowait(DOWAIT_BLOCK, NULL);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004068 job->waited = 1;
4069 retval = getstatus(job);
4070 repeat:
4071 ;
4072 } while (*++argv);
4073
Denis Vlasenko991a1da2008-02-10 19:02:53 +00004074 ret:
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004075 return retval;
4076}
4077
4078static struct job *
4079growjobtab(void)
4080{
4081 size_t len;
4082 ptrdiff_t offset;
4083 struct job *jp, *jq;
4084
4085 len = njobs * sizeof(*jp);
4086 jq = jobtab;
4087 jp = ckrealloc(jq, len + 4 * sizeof(*jp));
4088
4089 offset = (char *)jp - (char *)jq;
4090 if (offset) {
4091 /* Relocate pointers */
4092 size_t l = len;
4093
4094 jq = (struct job *)((char *)jq + l);
4095 while (l) {
4096 l -= sizeof(*jp);
4097 jq--;
4098#define joff(p) ((struct job *)((char *)(p) + l))
4099#define jmove(p) (p) = (void *)((char *)(p) + offset)
4100 if (joff(jp)->ps == &jq->ps0)
4101 jmove(joff(jp)->ps);
4102 if (joff(jp)->prev_job)
4103 jmove(joff(jp)->prev_job);
4104 }
4105 if (curjob)
4106 jmove(curjob);
4107#undef joff
4108#undef jmove
4109 }
4110
4111 njobs += 4;
4112 jobtab = jp;
4113 jp = (struct job *)((char *)jp + len);
4114 jq = jp + 3;
4115 do {
4116 jq->used = 0;
4117 } while (--jq >= jp);
4118 return jp;
4119}
4120
4121/*
4122 * Return a new job structure.
4123 * Called with interrupts off.
4124 */
4125static struct job *
4126makejob(union node *node, int nprocs)
4127{
4128 int i;
4129 struct job *jp;
4130
4131 for (i = njobs, jp = jobtab; ; jp++) {
4132 if (--i < 0) {
4133 jp = growjobtab();
4134 break;
4135 }
4136 if (jp->used == 0)
4137 break;
4138 if (jp->state != JOBDONE || !jp->waited)
4139 continue;
4140#if JOBS
4141 if (jobctl)
4142 continue;
4143#endif
4144 freejob(jp);
4145 break;
4146 }
4147 memset(jp, 0, sizeof(*jp));
4148#if JOBS
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00004149 /* jp->jobctl is a bitfield.
4150 * "jp->jobctl |= jobctl" likely to give awful code */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004151 if (jobctl)
4152 jp->jobctl = 1;
4153#endif
4154 jp->prev_job = curjob;
4155 curjob = jp;
4156 jp->used = 1;
4157 jp->ps = &jp->ps0;
4158 if (nprocs > 1) {
4159 jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
4160 }
4161 TRACE(("makejob(0x%lx, %d) returns %%%d\n", (long)node, nprocs,
4162 jobno(jp)));
4163 return jp;
4164}
4165
4166#if JOBS
4167/*
4168 * Return a string identifying a command (to be printed by the
4169 * jobs command).
4170 */
4171static char *cmdnextc;
4172
4173static void
4174cmdputs(const char *s)
4175{
4176 const char *p, *str;
4177 char c, cc[2] = " ";
4178 char *nextc;
4179 int subtype = 0;
4180 int quoted = 0;
4181 static const char vstype[VSTYPE + 1][4] = {
4182 "", "}", "-", "+", "?", "=",
4183 "%", "%%", "#", "##"
4184 };
4185
4186 nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
4187 p = s;
4188 while ((c = *p++) != 0) {
4189 str = 0;
4190 switch (c) {
4191 case CTLESC:
4192 c = *p++;
4193 break;
4194 case CTLVAR:
4195 subtype = *p++;
4196 if ((subtype & VSTYPE) == VSLENGTH)
4197 str = "${#";
4198 else
4199 str = "${";
4200 if (!(subtype & VSQUOTE) == !(quoted & 1))
4201 goto dostr;
4202 quoted ^= 1;
4203 c = '"';
4204 break;
4205 case CTLENDVAR:
4206 str = "\"}" + !(quoted & 1);
4207 quoted >>= 1;
4208 subtype = 0;
4209 goto dostr;
4210 case CTLBACKQ:
4211 str = "$(...)";
4212 goto dostr;
4213 case CTLBACKQ+CTLQUOTE:
4214 str = "\"$(...)\"";
4215 goto dostr;
4216#if ENABLE_ASH_MATH_SUPPORT
4217 case CTLARI:
4218 str = "$((";
4219 goto dostr;
4220 case CTLENDARI:
4221 str = "))";
4222 goto dostr;
4223#endif
4224 case CTLQUOTEMARK:
4225 quoted ^= 1;
4226 c = '"';
4227 break;
4228 case '=':
4229 if (subtype == 0)
4230 break;
4231 if ((subtype & VSTYPE) != VSNORMAL)
4232 quoted <<= 1;
4233 str = vstype[subtype & VSTYPE];
4234 if (subtype & VSNUL)
4235 c = ':';
4236 else
4237 goto checkstr;
4238 break;
4239 case '\'':
4240 case '\\':
4241 case '"':
4242 case '$':
4243 /* These can only happen inside quotes */
4244 cc[0] = c;
4245 str = cc;
4246 c = '\\';
4247 break;
4248 default:
4249 break;
4250 }
4251 USTPUTC(c, nextc);
4252 checkstr:
4253 if (!str)
4254 continue;
4255 dostr:
4256 while ((c = *str++)) {
4257 USTPUTC(c, nextc);
4258 }
4259 }
4260 if (quoted & 1) {
4261 USTPUTC('"', nextc);
4262 }
4263 *nextc = 0;
4264 cmdnextc = nextc;
4265}
4266
4267/* cmdtxt() and cmdlist() call each other */
4268static void cmdtxt(union node *n);
4269
4270static void
4271cmdlist(union node *np, int sep)
4272{
4273 for (; np; np = np->narg.next) {
4274 if (!sep)
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00004275 cmdputs(" ");
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004276 cmdtxt(np);
4277 if (sep && np->narg.next)
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00004278 cmdputs(" ");
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004279 }
4280}
4281
4282static void
4283cmdtxt(union node *n)
4284{
4285 union node *np;
4286 struct nodelist *lp;
4287 const char *p;
4288 char s[2];
4289
4290 if (!n)
4291 return;
4292 switch (n->type) {
4293 default:
4294#if DEBUG
4295 abort();
4296#endif
4297 case NPIPE:
4298 lp = n->npipe.cmdlist;
4299 for (;;) {
4300 cmdtxt(lp->n);
4301 lp = lp->next;
4302 if (!lp)
4303 break;
4304 cmdputs(" | ");
4305 }
4306 break;
4307 case NSEMI:
4308 p = "; ";
4309 goto binop;
4310 case NAND:
4311 p = " && ";
4312 goto binop;
4313 case NOR:
4314 p = " || ";
4315 binop:
4316 cmdtxt(n->nbinary.ch1);
4317 cmdputs(p);
4318 n = n->nbinary.ch2;
4319 goto donode;
4320 case NREDIR:
4321 case NBACKGND:
4322 n = n->nredir.n;
4323 goto donode;
4324 case NNOT:
4325 cmdputs("!");
4326 n = n->nnot.com;
4327 donode:
4328 cmdtxt(n);
4329 break;
4330 case NIF:
4331 cmdputs("if ");
4332 cmdtxt(n->nif.test);
4333 cmdputs("; then ");
4334 n = n->nif.ifpart;
4335 if (n->nif.elsepart) {
4336 cmdtxt(n);
4337 cmdputs("; else ");
4338 n = n->nif.elsepart;
4339 }
4340 p = "; fi";
4341 goto dotail;
4342 case NSUBSHELL:
4343 cmdputs("(");
4344 n = n->nredir.n;
4345 p = ")";
4346 goto dotail;
4347 case NWHILE:
4348 p = "while ";
4349 goto until;
4350 case NUNTIL:
4351 p = "until ";
4352 until:
4353 cmdputs(p);
4354 cmdtxt(n->nbinary.ch1);
4355 n = n->nbinary.ch2;
4356 p = "; done";
4357 dodo:
4358 cmdputs("; do ");
4359 dotail:
4360 cmdtxt(n);
4361 goto dotail2;
4362 case NFOR:
4363 cmdputs("for ");
4364 cmdputs(n->nfor.var);
4365 cmdputs(" in ");
4366 cmdlist(n->nfor.args, 1);
4367 n = n->nfor.body;
4368 p = "; done";
4369 goto dodo;
4370 case NDEFUN:
4371 cmdputs(n->narg.text);
4372 p = "() { ... }";
4373 goto dotail2;
4374 case NCMD:
4375 cmdlist(n->ncmd.args, 1);
4376 cmdlist(n->ncmd.redirect, 0);
4377 break;
4378 case NARG:
4379 p = n->narg.text;
4380 dotail2:
4381 cmdputs(p);
4382 break;
4383 case NHERE:
4384 case NXHERE:
4385 p = "<<...";
4386 goto dotail2;
4387 case NCASE:
4388 cmdputs("case ");
4389 cmdputs(n->ncase.expr->narg.text);
4390 cmdputs(" in ");
4391 for (np = n->ncase.cases; np; np = np->nclist.next) {
4392 cmdtxt(np->nclist.pattern);
4393 cmdputs(") ");
4394 cmdtxt(np->nclist.body);
4395 cmdputs(";; ");
4396 }
4397 p = "esac";
4398 goto dotail2;
4399 case NTO:
4400 p = ">";
4401 goto redir;
4402 case NCLOBBER:
4403 p = ">|";
4404 goto redir;
4405 case NAPPEND:
4406 p = ">>";
4407 goto redir;
4408 case NTOFD:
4409 p = ">&";
4410 goto redir;
4411 case NFROM:
4412 p = "<";
4413 goto redir;
4414 case NFROMFD:
4415 p = "<&";
4416 goto redir;
4417 case NFROMTO:
4418 p = "<>";
4419 redir:
4420 s[0] = n->nfile.fd + '0';
4421 s[1] = '\0';
4422 cmdputs(s);
4423 cmdputs(p);
4424 if (n->type == NTOFD || n->type == NFROMFD) {
4425 s[0] = n->ndup.dupfd + '0';
4426 p = s;
4427 goto dotail2;
4428 }
4429 n = n->nfile.fname;
4430 goto donode;
4431 }
4432}
4433
4434static char *
4435commandtext(union node *n)
4436{
4437 char *name;
4438
4439 STARTSTACKSTR(cmdnextc);
4440 cmdtxt(n);
4441 name = stackblock();
4442 TRACE(("commandtext: name %p, end %p\n\t\"%s\"\n",
4443 name, cmdnextc, cmdnextc));
4444 return ckstrdup(name);
4445}
4446#endif /* JOBS */
4447
4448/*
4449 * Fork off a subshell. If we are doing job control, give the subshell its
4450 * own process group. Jp is a job structure that the job is to be added to.
4451 * N is the command that will be evaluated by the child. Both jp and n may
4452 * be NULL. The mode parameter can be one of the following:
4453 * FORK_FG - Fork off a foreground process.
4454 * FORK_BG - Fork off a background process.
4455 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
4456 * process group even if job control is on.
4457 *
4458 * When job control is turned off, background processes have their standard
4459 * input redirected to /dev/null (except for the second and later processes
4460 * in a pipeline).
4461 *
4462 * Called with interrupts off.
4463 */
4464/*
4465 * Clear traps on a fork.
4466 */
4467static void
4468clear_traps(void)
4469{
4470 char **tp;
4471
4472 for (tp = trap; tp < &trap[NSIG]; tp++) {
Denis Vlasenko991a1da2008-02-10 19:02:53 +00004473 if (*tp && **tp) { /* trap not NULL or "" (SIG_IGN) */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004474 INT_OFF;
4475 free(*tp);
4476 *tp = NULL;
4477 if (tp != &trap[0])
4478 setsignal(tp - trap);
4479 INT_ON;
4480 }
4481 }
4482}
Denis Vlasenkobdc406d2007-07-15 01:13:25 +00004483
4484/* Lives far away from here, needed for forkchild */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004485static void closescript(void);
Denis Vlasenko41770222007-10-07 18:02:52 +00004486
Denis Vlasenkobdc406d2007-07-15 01:13:25 +00004487/* Called after fork(), in child */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004488static void
4489forkchild(struct job *jp, union node *n, int mode)
4490{
4491 int oldlvl;
4492
4493 TRACE(("Child shell %d\n", getpid()));
4494 oldlvl = shlvl;
4495 shlvl++;
4496
4497 closescript();
4498 clear_traps();
4499#if JOBS
4500 /* do job control only in root shell */
4501 jobctl = 0;
4502 if (mode != FORK_NOJOB && jp->jobctl && !oldlvl) {
4503 pid_t pgrp;
4504
4505 if (jp->nprocs == 0)
4506 pgrp = getpid();
4507 else
4508 pgrp = jp->ps[0].pid;
4509 /* This can fail because we are doing it in the parent also */
4510 (void)setpgid(0, pgrp);
4511 if (mode == FORK_FG)
4512 xtcsetpgrp(ttyfd, pgrp);
4513 setsignal(SIGTSTP);
4514 setsignal(SIGTTOU);
4515 } else
4516#endif
4517 if (mode == FORK_BG) {
4518 ignoresig(SIGINT);
4519 ignoresig(SIGQUIT);
4520 if (jp->nprocs == 0) {
4521 close(0);
4522 if (open(bb_dev_null, O_RDONLY) != 0)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00004523 ash_msg_and_raise_error("can't open %s", bb_dev_null);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004524 }
4525 }
4526 if (!oldlvl && iflag) {
4527 setsignal(SIGINT);
4528 setsignal(SIGQUIT);
4529 setsignal(SIGTERM);
4530 }
4531 for (jp = curjob; jp; jp = jp->prev_job)
4532 freejob(jp);
4533 jobless = 0;
4534}
4535
Denis Vlasenkobdc406d2007-07-15 01:13:25 +00004536/* Called after fork(), in parent */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004537static void
4538forkparent(struct job *jp, union node *n, int mode, pid_t pid)
4539{
4540 TRACE(("In parent shell: child = %d\n", pid));
4541 if (!jp) {
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00004542 while (jobless && dowait(DOWAIT_NONBLOCK, NULL) > 0)
4543 continue;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004544 jobless++;
4545 return;
4546 }
4547#if JOBS
4548 if (mode != FORK_NOJOB && jp->jobctl) {
4549 int pgrp;
4550
4551 if (jp->nprocs == 0)
4552 pgrp = pid;
4553 else
4554 pgrp = jp->ps[0].pid;
4555 /* This can fail because we are doing it in the child also */
4556 setpgid(pid, pgrp);
4557 }
4558#endif
4559 if (mode == FORK_BG) {
4560 backgndpid = pid; /* set $! */
4561 set_curjob(jp, CUR_RUNNING);
4562 }
4563 if (jp) {
4564 struct procstat *ps = &jp->ps[jp->nprocs++];
4565 ps->pid = pid;
4566 ps->status = -1;
4567 ps->cmd = nullstr;
4568#if JOBS
4569 if (jobctl && n)
4570 ps->cmd = commandtext(n);
4571#endif
4572 }
4573}
4574
4575static int
4576forkshell(struct job *jp, union node *n, int mode)
4577{
4578 int pid;
4579
4580 TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
4581 pid = fork();
4582 if (pid < 0) {
4583 TRACE(("Fork failed, errno=%d", errno));
4584 if (jp)
4585 freejob(jp);
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00004586 ash_msg_and_raise_error("cannot fork");
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004587 }
4588 if (pid == 0)
4589 forkchild(jp, n, mode);
4590 else
4591 forkparent(jp, n, mode, pid);
4592 return pid;
4593}
4594
4595/*
4596 * Wait for job to finish.
4597 *
4598 * Under job control we have the problem that while a child process is
4599 * running interrupts generated by the user are sent to the child but not
4600 * to the shell. This means that an infinite loop started by an inter-
4601 * active user may be hard to kill. With job control turned off, an
4602 * interactive user may place an interactive program inside a loop. If
4603 * the interactive program catches interrupts, the user doesn't want
4604 * these interrupts to also abort the loop. The approach we take here
4605 * is to have the shell ignore interrupt signals while waiting for a
4606 * foreground process to terminate, and then send itself an interrupt
4607 * signal if the child process was terminated by an interrupt signal.
4608 * Unfortunately, some programs want to do a bit of cleanup and then
4609 * exit on interrupt; unless these processes terminate themselves by
4610 * sending a signal to themselves (instead of calling exit) they will
4611 * confuse this approach.
4612 *
4613 * Called with interrupts off.
4614 */
4615static int
4616waitforjob(struct job *jp)
4617{
4618 int st;
4619
4620 TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
4621 while (jp->state == JOBRUNNING) {
4622 dowait(DOWAIT_BLOCK, jp);
4623 }
4624 st = getstatus(jp);
4625#if JOBS
4626 if (jp->jobctl) {
4627 xtcsetpgrp(ttyfd, rootpid);
4628 /*
4629 * This is truly gross.
4630 * If we're doing job control, then we did a TIOCSPGRP which
4631 * caused us (the shell) to no longer be in the controlling
4632 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
4633 * intuit from the subprocess exit status whether a SIGINT
4634 * occurred, and if so interrupt ourselves. Yuck. - mycroft
4635 */
Denis Vlasenko991a1da2008-02-10 19:02:53 +00004636 if (jp->sigint) /* TODO: do the same with all signals */
4637 raise(SIGINT); /* ... by raise(jp->sig) instead? */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004638 }
4639 if (jp->state == JOBDONE)
4640#endif
4641 freejob(jp);
4642 return st;
4643}
4644
4645/*
4646 * return 1 if there are stopped jobs, otherwise 0
4647 */
4648static int
4649stoppedjobs(void)
4650{
4651 struct job *jp;
4652 int retval;
4653
4654 retval = 0;
4655 if (job_warning)
4656 goto out;
4657 jp = curjob;
4658 if (jp && jp->state == JOBSTOPPED) {
4659 out2str("You have stopped jobs.\n");
4660 job_warning = 2;
4661 retval++;
4662 }
4663 out:
4664 return retval;
4665}
4666
4667
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004668/* ============ redir.c
4669 *
4670 * Code for dealing with input/output redirection.
4671 */
4672
4673#define EMPTY -2 /* marks an unused slot in redirtab */
Denis Vlasenko7d75a962007-11-22 08:16:57 +00004674#define CLOSED -3 /* marks a slot of previously-closed fd */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004675#ifndef PIPE_BUF
4676# define PIPESIZE 4096 /* amount of buffering in a pipe */
4677#else
4678# define PIPESIZE PIPE_BUF
4679#endif
4680
4681/*
4682 * Open a file in noclobber mode.
4683 * The code was copied from bash.
4684 */
4685static int
4686noclobberopen(const char *fname)
4687{
4688 int r, fd;
4689 struct stat finfo, finfo2;
4690
4691 /*
4692 * If the file exists and is a regular file, return an error
4693 * immediately.
4694 */
4695 r = stat(fname, &finfo);
4696 if (r == 0 && S_ISREG(finfo.st_mode)) {
4697 errno = EEXIST;
4698 return -1;
4699 }
4700
4701 /*
4702 * If the file was not present (r != 0), make sure we open it
4703 * exclusively so that if it is created before we open it, our open
4704 * will fail. Make sure that we do not truncate an existing file.
4705 * Note that we don't turn on O_EXCL unless the stat failed -- if the
4706 * file was not a regular file, we leave O_EXCL off.
4707 */
4708 if (r != 0)
4709 return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
4710 fd = open(fname, O_WRONLY|O_CREAT, 0666);
4711
4712 /* If the open failed, return the file descriptor right away. */
4713 if (fd < 0)
4714 return fd;
4715
4716 /*
4717 * OK, the open succeeded, but the file may have been changed from a
4718 * non-regular file to a regular file between the stat and the open.
4719 * We are assuming that the O_EXCL open handles the case where FILENAME
4720 * did not exist and is symlinked to an existing file between the stat
4721 * and open.
4722 */
4723
4724 /*
4725 * If we can open it and fstat the file descriptor, and neither check
4726 * revealed that it was a regular file, and the file has not been
4727 * replaced, return the file descriptor.
4728 */
4729 if (fstat(fd, &finfo2) == 0 && !S_ISREG(finfo2.st_mode)
4730 && finfo.st_dev == finfo2.st_dev && finfo.st_ino == finfo2.st_ino)
4731 return fd;
4732
4733 /* The file has been replaced. badness. */
4734 close(fd);
4735 errno = EEXIST;
4736 return -1;
4737}
4738
4739/*
4740 * Handle here documents. Normally we fork off a process to write the
4741 * data to a pipe. If the document is short, we can stuff the data in
4742 * the pipe without forking.
4743 */
4744/* openhere needs this forward reference */
4745static void expandhere(union node *arg, int fd);
4746static int
4747openhere(union node *redir)
4748{
4749 int pip[2];
4750 size_t len = 0;
4751
4752 if (pipe(pip) < 0)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00004753 ash_msg_and_raise_error("pipe call failed");
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004754 if (redir->type == NHERE) {
4755 len = strlen(redir->nhere.doc->narg.text);
4756 if (len <= PIPESIZE) {
4757 full_write(pip[1], redir->nhere.doc->narg.text, len);
4758 goto out;
4759 }
4760 }
4761 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
4762 close(pip[0]);
4763 signal(SIGINT, SIG_IGN);
4764 signal(SIGQUIT, SIG_IGN);
4765 signal(SIGHUP, SIG_IGN);
4766#ifdef SIGTSTP
4767 signal(SIGTSTP, SIG_IGN);
4768#endif
4769 signal(SIGPIPE, SIG_DFL);
4770 if (redir->type == NHERE)
4771 full_write(pip[1], redir->nhere.doc->narg.text, len);
4772 else
4773 expandhere(redir->nhere.doc, pip[1]);
4774 _exit(0);
4775 }
4776 out:
4777 close(pip[1]);
4778 return pip[0];
4779}
4780
4781static int
4782openredirect(union node *redir)
4783{
4784 char *fname;
4785 int f;
4786
4787 switch (redir->nfile.type) {
4788 case NFROM:
4789 fname = redir->nfile.expfname;
4790 f = open(fname, O_RDONLY);
4791 if (f < 0)
4792 goto eopen;
4793 break;
4794 case NFROMTO:
4795 fname = redir->nfile.expfname;
4796 f = open(fname, O_RDWR|O_CREAT|O_TRUNC, 0666);
4797 if (f < 0)
4798 goto ecreate;
4799 break;
4800 case NTO:
4801 /* Take care of noclobber mode. */
4802 if (Cflag) {
4803 fname = redir->nfile.expfname;
4804 f = noclobberopen(fname);
4805 if (f < 0)
4806 goto ecreate;
4807 break;
4808 }
4809 /* FALLTHROUGH */
4810 case NCLOBBER:
4811 fname = redir->nfile.expfname;
4812 f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
4813 if (f < 0)
4814 goto ecreate;
4815 break;
4816 case NAPPEND:
4817 fname = redir->nfile.expfname;
4818 f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
4819 if (f < 0)
4820 goto ecreate;
4821 break;
4822 default:
4823#if DEBUG
4824 abort();
4825#endif
4826 /* Fall through to eliminate warning. */
4827 case NTOFD:
4828 case NFROMFD:
4829 f = -1;
4830 break;
4831 case NHERE:
4832 case NXHERE:
4833 f = openhere(redir);
4834 break;
4835 }
4836
4837 return f;
4838 ecreate:
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00004839 ash_msg_and_raise_error("cannot create %s: %s", fname, errmsg(errno, "nonexistent directory"));
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004840 eopen:
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00004841 ash_msg_and_raise_error("cannot open %s: %s", fname, errmsg(errno, "no such file"));
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004842}
4843
4844/*
4845 * Copy a file descriptor to be >= to. Returns -1
4846 * if the source file descriptor is closed, EMPTY if there are no unused
4847 * file descriptors left.
4848 */
4849static int
4850copyfd(int from, int to)
4851{
4852 int newfd;
4853
4854 newfd = fcntl(from, F_DUPFD, to);
4855 if (newfd < 0) {
4856 if (errno == EMFILE)
4857 return EMPTY;
4858 ash_msg_and_raise_error("%d: %m", from);
4859 }
4860 return newfd;
4861}
4862
4863static void
4864dupredirect(union node *redir, int f)
4865{
4866 int fd = redir->nfile.fd;
4867
4868 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
4869 if (redir->ndup.dupfd >= 0) { /* if not ">&-" */
4870 copyfd(redir->ndup.dupfd, fd);
4871 }
4872 return;
4873 }
4874
4875 if (f != fd) {
4876 copyfd(f, fd);
4877 close(f);
4878 }
4879}
4880
4881/*
4882 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
4883 * old file descriptors are stashed away so that the redirection can be
4884 * undone by calling popredir. If the REDIR_BACKQ flag is set, then the
4885 * standard output, and the standard error if it becomes a duplicate of
4886 * stdout, is saved in memory.
4887 */
4888/* flags passed to redirect */
4889#define REDIR_PUSH 01 /* save previous values of file descriptors */
4890#define REDIR_SAVEFD2 03 /* set preverrout */
4891static void
4892redirect(union node *redir, int flags)
4893{
4894 union node *n;
4895 struct redirtab *sv;
4896 int i;
4897 int fd;
4898 int newfd;
Denis Vlasenko7d75a962007-11-22 08:16:57 +00004899
Denis Vlasenko01631112007-12-16 17:20:38 +00004900 g_nullredirs++;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004901 if (!redir) {
4902 return;
4903 }
4904 sv = NULL;
4905 INT_OFF;
4906 if (flags & REDIR_PUSH) {
Denis Vlasenko7d75a962007-11-22 08:16:57 +00004907 sv = ckmalloc(sizeof(*sv));
4908 sv->next = redirlist;
4909 redirlist = sv;
Denis Vlasenko01631112007-12-16 17:20:38 +00004910 sv->nullredirs = g_nullredirs - 1;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004911 for (i = 0; i < 10; i++)
Denis Vlasenko7d75a962007-11-22 08:16:57 +00004912 sv->renamed[i] = EMPTY;
Denis Vlasenko01631112007-12-16 17:20:38 +00004913 g_nullredirs = 0;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004914 }
4915 n = redir;
4916 do {
4917 fd = n->nfile.fd;
4918 if ((n->nfile.type == NTOFD || n->nfile.type == NFROMFD)
4919 && n->ndup.dupfd == fd)
4920 continue; /* redirect from/to same file descriptor */
4921
4922 newfd = openredirect(n);
Denis Vlasenko7d75a962007-11-22 08:16:57 +00004923 if (fd == newfd) {
4924 /* Descriptor wasn't open before redirect.
4925 * Mark it for close in the future */
4926 if (sv && sv->renamed[fd] == EMPTY)
4927 sv->renamed[fd] = CLOSED;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004928 continue;
Denis Vlasenko7d75a962007-11-22 08:16:57 +00004929 }
4930 if (sv && sv->renamed[fd] == EMPTY) {
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004931 i = fcntl(fd, F_DUPFD, 10);
4932
4933 if (i == -1) {
4934 i = errno;
4935 if (i != EBADF) {
4936 close(newfd);
4937 errno = i;
4938 ash_msg_and_raise_error("%d: %m", fd);
4939 /* NOTREACHED */
4940 }
4941 } else {
Denis Vlasenko7d75a962007-11-22 08:16:57 +00004942 sv->renamed[fd] = i;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004943 close(fd);
4944 }
4945 } else {
4946 close(fd);
4947 }
4948 dupredirect(n, newfd);
4949 } while ((n = n->nfile.next));
4950 INT_ON;
Denis Vlasenko7d75a962007-11-22 08:16:57 +00004951 if ((flags & REDIR_SAVEFD2) && sv && sv->renamed[2] >= 0)
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004952 preverrout_fd = sv->renamed[2];
4953}
4954
4955/*
4956 * Undo the effects of the last redirection.
4957 */
4958static void
4959popredir(int drop)
4960{
4961 struct redirtab *rp;
4962 int i;
4963
Denis Vlasenko01631112007-12-16 17:20:38 +00004964 if (--g_nullredirs >= 0)
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004965 return;
4966 INT_OFF;
4967 rp = redirlist;
4968 for (i = 0; i < 10; i++) {
Denis Vlasenko7d75a962007-11-22 08:16:57 +00004969 if (rp->renamed[i] == CLOSED) {
4970 if (!drop)
4971 close(i);
4972 continue;
4973 }
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004974 if (rp->renamed[i] != EMPTY) {
4975 if (!drop) {
4976 close(i);
4977 copyfd(rp->renamed[i], i);
4978 }
4979 close(rp->renamed[i]);
4980 }
4981 }
4982 redirlist = rp->next;
Denis Vlasenko01631112007-12-16 17:20:38 +00004983 g_nullredirs = rp->nullredirs;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004984 free(rp);
4985 INT_ON;
4986}
4987
4988/*
4989 * Undo all redirections. Called on error or interrupt.
4990 */
4991
4992/*
4993 * Discard all saved file descriptors.
4994 */
4995static void
4996clearredir(int drop)
4997{
4998 for (;;) {
Denis Vlasenko01631112007-12-16 17:20:38 +00004999 g_nullredirs = 0;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005000 if (!redirlist)
5001 break;
5002 popredir(drop);
5003 }
5004}
5005
5006static int
5007redirectsafe(union node *redir, int flags)
5008{
5009 int err;
5010 volatile int saveint;
5011 struct jmploc *volatile savehandler = exception_handler;
5012 struct jmploc jmploc;
5013
5014 SAVE_INT(saveint);
5015 err = setjmp(jmploc.loc) * 2;
5016 if (!err) {
5017 exception_handler = &jmploc;
5018 redirect(redir, flags);
5019 }
5020 exception_handler = savehandler;
5021 if (err && exception != EXERROR)
5022 longjmp(exception_handler->loc, 1);
5023 RESTORE_INT(saveint);
5024 return err;
5025}
5026
5027
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005028/* ============ Routines to expand arguments to commands
5029 *
5030 * We have to deal with backquotes, shell variables, and file metacharacters.
5031 */
5032
5033/*
5034 * expandarg flags
5035 */
5036#define EXP_FULL 0x1 /* perform word splitting & file globbing */
5037#define EXP_TILDE 0x2 /* do normal tilde expansion */
5038#define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
5039#define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
5040#define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
5041#define EXP_RECORD 0x20 /* need to record arguments for ifs breakup */
5042#define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
5043#define EXP_WORD 0x80 /* expand word in parameter expansion */
5044#define EXP_QWORD 0x100 /* expand word in quoted parameter expansion */
5045/*
5046 * _rmescape() flags
5047 */
5048#define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
5049#define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
5050#define RMESCAPE_QUOTED 0x4 /* Remove CTLESC unless in quotes */
5051#define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
5052#define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
5053
5054/*
5055 * Structure specifying which parts of the string should be searched
5056 * for IFS characters.
5057 */
5058struct ifsregion {
5059 struct ifsregion *next; /* next region in list */
5060 int begoff; /* offset of start of region */
5061 int endoff; /* offset of end of region */
5062 int nulonly; /* search for nul bytes only */
5063};
5064
5065struct arglist {
5066 struct strlist *list;
5067 struct strlist **lastp;
5068};
5069
5070/* output of current string */
5071static char *expdest;
5072/* list of back quote expressions */
5073static struct nodelist *argbackq;
5074/* first struct in list of ifs regions */
5075static struct ifsregion ifsfirst;
5076/* last struct in list */
5077static struct ifsregion *ifslastp;
5078/* holds expanded arg list */
5079static struct arglist exparg;
5080
5081/*
5082 * Our own itoa().
5083 */
5084static int
5085cvtnum(arith_t num)
5086{
5087 int len;
5088
5089 expdest = makestrspace(32, expdest);
5090#if ENABLE_ASH_MATH_SUPPORT_64
5091 len = fmtstr(expdest, 32, "%lld", (long long) num);
5092#else
5093 len = fmtstr(expdest, 32, "%ld", num);
5094#endif
5095 STADJUST(len, expdest);
5096 return len;
5097}
5098
5099static size_t
5100esclen(const char *start, const char *p)
5101{
5102 size_t esc = 0;
5103
5104 while (p > start && *--p == CTLESC) {
5105 esc++;
5106 }
5107 return esc;
5108}
5109
5110/*
5111 * Remove any CTLESC characters from a string.
5112 */
5113static char *
5114_rmescapes(char *str, int flag)
5115{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00005116 static const char qchars[] ALIGN1 = { CTLESC, CTLQUOTEMARK, '\0' };
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00005117
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005118 char *p, *q, *r;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005119 unsigned inquotes;
5120 int notescaped;
5121 int globbing;
5122
5123 p = strpbrk(str, qchars);
5124 if (!p) {
5125 return str;
5126 }
5127 q = p;
5128 r = str;
5129 if (flag & RMESCAPE_ALLOC) {
5130 size_t len = p - str;
5131 size_t fulllen = len + strlen(p) + 1;
5132
5133 if (flag & RMESCAPE_GROW) {
5134 r = makestrspace(fulllen, expdest);
5135 } else if (flag & RMESCAPE_HEAP) {
5136 r = ckmalloc(fulllen);
5137 } else {
5138 r = stalloc(fulllen);
5139 }
5140 q = r;
5141 if (len > 0) {
5142 q = memcpy(q, str, len) + len;
5143 }
5144 }
5145 inquotes = (flag & RMESCAPE_QUOTED) ^ RMESCAPE_QUOTED;
5146 globbing = flag & RMESCAPE_GLOB;
5147 notescaped = globbing;
5148 while (*p) {
5149 if (*p == CTLQUOTEMARK) {
5150 inquotes = ~inquotes;
5151 p++;
5152 notescaped = globbing;
5153 continue;
5154 }
5155 if (*p == '\\') {
5156 /* naked back slash */
5157 notescaped = 0;
5158 goto copy;
5159 }
5160 if (*p == CTLESC) {
5161 p++;
5162 if (notescaped && inquotes && *p != '/') {
5163 *q++ = '\\';
5164 }
5165 }
5166 notescaped = globbing;
5167 copy:
5168 *q++ = *p++;
5169 }
5170 *q = '\0';
5171 if (flag & RMESCAPE_GROW) {
5172 expdest = r;
5173 STADJUST(q - r + 1, expdest);
5174 }
5175 return r;
5176}
5177#define rmescapes(p) _rmescapes((p), 0)
5178
5179#define pmatch(a, b) !fnmatch((a), (b), 0)
5180
5181/*
5182 * Prepare a pattern for a expmeta (internal glob(3)) call.
5183 *
5184 * Returns an stalloced string.
5185 */
5186static char *
5187preglob(const char *pattern, int quoted, int flag)
5188{
5189 flag |= RMESCAPE_GLOB;
5190 if (quoted) {
5191 flag |= RMESCAPE_QUOTED;
5192 }
5193 return _rmescapes((char *)pattern, flag);
5194}
5195
5196/*
5197 * Put a string on the stack.
5198 */
5199static void
5200memtodest(const char *p, size_t len, int syntax, int quotes)
5201{
5202 char *q = expdest;
5203
5204 q = makestrspace(len * 2, q);
5205
5206 while (len--) {
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00005207 int c = signed_char2int(*p++);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005208 if (!c)
5209 continue;
5210 if (quotes && (SIT(c, syntax) == CCTL || SIT(c, syntax) == CBACK))
5211 USTPUTC(CTLESC, q);
5212 USTPUTC(c, q);
5213 }
5214
5215 expdest = q;
5216}
5217
5218static void
5219strtodest(const char *p, int syntax, int quotes)
5220{
5221 memtodest(p, strlen(p), syntax, quotes);
5222}
5223
5224/*
5225 * Record the fact that we have to scan this region of the
5226 * string for IFS characters.
5227 */
5228static void
5229recordregion(int start, int end, int nulonly)
5230{
5231 struct ifsregion *ifsp;
5232
5233 if (ifslastp == NULL) {
5234 ifsp = &ifsfirst;
5235 } else {
5236 INT_OFF;
Denis Vlasenko597906c2008-02-20 16:38:54 +00005237 ifsp = ckzalloc(sizeof(*ifsp));
5238 /*ifsp->next = NULL; - ckzalloc did it */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005239 ifslastp->next = ifsp;
5240 INT_ON;
5241 }
5242 ifslastp = ifsp;
5243 ifslastp->begoff = start;
5244 ifslastp->endoff = end;
5245 ifslastp->nulonly = nulonly;
5246}
5247
5248static void
5249removerecordregions(int endoff)
5250{
5251 if (ifslastp == NULL)
5252 return;
5253
5254 if (ifsfirst.endoff > endoff) {
5255 while (ifsfirst.next != NULL) {
5256 struct ifsregion *ifsp;
5257 INT_OFF;
5258 ifsp = ifsfirst.next->next;
5259 free(ifsfirst.next);
5260 ifsfirst.next = ifsp;
5261 INT_ON;
5262 }
5263 if (ifsfirst.begoff > endoff)
5264 ifslastp = NULL;
5265 else {
5266 ifslastp = &ifsfirst;
5267 ifsfirst.endoff = endoff;
5268 }
5269 return;
5270 }
5271
5272 ifslastp = &ifsfirst;
5273 while (ifslastp->next && ifslastp->next->begoff < endoff)
5274 ifslastp=ifslastp->next;
5275 while (ifslastp->next != NULL) {
5276 struct ifsregion *ifsp;
5277 INT_OFF;
5278 ifsp = ifslastp->next->next;
5279 free(ifslastp->next);
5280 ifslastp->next = ifsp;
5281 INT_ON;
5282 }
5283 if (ifslastp->endoff > endoff)
5284 ifslastp->endoff = endoff;
5285}
5286
5287static char *
5288exptilde(char *startp, char *p, int flag)
5289{
5290 char c;
5291 char *name;
5292 struct passwd *pw;
5293 const char *home;
5294 int quotes = flag & (EXP_FULL | EXP_CASE);
5295 int startloc;
5296
5297 name = p + 1;
5298
5299 while ((c = *++p) != '\0') {
5300 switch (c) {
5301 case CTLESC:
5302 return startp;
5303 case CTLQUOTEMARK:
5304 return startp;
5305 case ':':
5306 if (flag & EXP_VARTILDE)
5307 goto done;
5308 break;
5309 case '/':
5310 case CTLENDVAR:
5311 goto done;
5312 }
5313 }
5314 done:
5315 *p = '\0';
5316 if (*name == '\0') {
5317 home = lookupvar(homestr);
5318 } else {
5319 pw = getpwnam(name);
5320 if (pw == NULL)
5321 goto lose;
5322 home = pw->pw_dir;
5323 }
5324 if (!home || !*home)
5325 goto lose;
5326 *p = c;
5327 startloc = expdest - (char *)stackblock();
5328 strtodest(home, SQSYNTAX, quotes);
5329 recordregion(startloc, expdest - (char *)stackblock(), 0);
5330 return p;
5331 lose:
5332 *p = c;
5333 return startp;
5334}
5335
5336/*
5337 * Execute a command inside back quotes. If it's a builtin command, we
5338 * want to save its output in a block obtained from malloc. Otherwise
5339 * we fork off a subprocess and get the output of the command via a pipe.
5340 * Should be called with interrupts off.
5341 */
5342struct backcmd { /* result of evalbackcmd */
5343 int fd; /* file descriptor to read from */
5344 char *buf; /* buffer */
5345 int nleft; /* number of chars in buffer */
5346 struct job *jp; /* job structure for command */
5347};
5348
5349/* These forward decls are needed to use "eval" code for backticks handling: */
5350static int back_exitstatus; /* exit status of backquoted command */
5351#define EV_EXIT 01 /* exit after evaluating tree */
5352static void evaltree(union node *, int);
5353
5354static void
5355evalbackcmd(union node *n, struct backcmd *result)
5356{
5357 int saveherefd;
5358
5359 result->fd = -1;
5360 result->buf = NULL;
5361 result->nleft = 0;
5362 result->jp = NULL;
5363 if (n == NULL) {
5364 goto out;
5365 }
5366
5367 saveherefd = herefd;
5368 herefd = -1;
5369
5370 {
5371 int pip[2];
5372 struct job *jp;
5373
5374 if (pipe(pip) < 0)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00005375 ash_msg_and_raise_error("pipe call failed");
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005376 jp = makejob(n, 1);
5377 if (forkshell(jp, n, FORK_NOJOB) == 0) {
5378 FORCE_INT_ON;
5379 close(pip[0]);
5380 if (pip[1] != 1) {
5381 close(1);
5382 copyfd(pip[1], 1);
5383 close(pip[1]);
5384 }
5385 eflag = 0;
5386 evaltree(n, EV_EXIT); /* actually evaltreenr... */
5387 /* NOTREACHED */
5388 }
5389 close(pip[1]);
5390 result->fd = pip[0];
5391 result->jp = jp;
5392 }
5393 herefd = saveherefd;
5394 out:
5395 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
5396 result->fd, result->buf, result->nleft, result->jp));
5397}
5398
5399/*
5400 * Expand stuff in backwards quotes.
5401 */
5402static void
5403expbackq(union node *cmd, int quoted, int quotes)
5404{
5405 struct backcmd in;
5406 int i;
5407 char buf[128];
5408 char *p;
5409 char *dest;
5410 int startloc;
5411 int syntax = quoted? DQSYNTAX : BASESYNTAX;
5412 struct stackmark smark;
5413
5414 INT_OFF;
5415 setstackmark(&smark);
5416 dest = expdest;
5417 startloc = dest - (char *)stackblock();
5418 grabstackstr(dest);
5419 evalbackcmd(cmd, &in);
5420 popstackmark(&smark);
5421
5422 p = in.buf;
5423 i = in.nleft;
5424 if (i == 0)
5425 goto read;
5426 for (;;) {
5427 memtodest(p, i, syntax, quotes);
5428 read:
5429 if (in.fd < 0)
5430 break;
5431 i = safe_read(in.fd, buf, sizeof(buf));
5432 TRACE(("expbackq: read returns %d\n", i));
5433 if (i <= 0)
5434 break;
5435 p = buf;
5436 }
5437
Denis Vlasenko60818682007-09-28 22:07:23 +00005438 free(in.buf);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005439 if (in.fd >= 0) {
5440 close(in.fd);
5441 back_exitstatus = waitforjob(in.jp);
5442 }
5443 INT_ON;
5444
5445 /* Eat all trailing newlines */
5446 dest = expdest;
5447 for (; dest > (char *)stackblock() && dest[-1] == '\n';)
5448 STUNPUTC(dest);
5449 expdest = dest;
5450
5451 if (quoted == 0)
5452 recordregion(startloc, dest - (char *)stackblock(), 0);
5453 TRACE(("evalbackq: size=%d: \"%.*s\"\n",
5454 (dest - (char *)stackblock()) - startloc,
5455 (dest - (char *)stackblock()) - startloc,
5456 stackblock() + startloc));
5457}
5458
5459#if ENABLE_ASH_MATH_SUPPORT
5460/*
5461 * Expand arithmetic expression. Backup to start of expression,
5462 * evaluate, place result in (backed up) result, adjust string position.
5463 */
5464static void
5465expari(int quotes)
5466{
5467 char *p, *start;
5468 int begoff;
5469 int flag;
5470 int len;
5471
5472 /* ifsfree(); */
5473
5474 /*
5475 * This routine is slightly over-complicated for
5476 * efficiency. Next we scan backwards looking for the
5477 * start of arithmetic.
5478 */
5479 start = stackblock();
5480 p = expdest - 1;
5481 *p = '\0';
5482 p--;
5483 do {
5484 int esc;
5485
5486 while (*p != CTLARI) {
5487 p--;
5488#if DEBUG
5489 if (p < start) {
5490 ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
5491 }
5492#endif
5493 }
5494
5495 esc = esclen(start, p);
5496 if (!(esc % 2)) {
5497 break;
5498 }
5499
5500 p -= esc + 1;
5501 } while (1);
5502
5503 begoff = p - start;
5504
5505 removerecordregions(begoff);
5506
5507 flag = p[1];
5508
5509 expdest = p;
5510
5511 if (quotes)
5512 rmescapes(p + 2);
5513
5514 len = cvtnum(dash_arith(p + 2));
5515
5516 if (flag != '"')
5517 recordregion(begoff, begoff + len, 0);
5518}
5519#endif
5520
5521/* argstr needs it */
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00005522static char *evalvar(char *p, int flag, struct strlist *var_str_list);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005523
5524/*
5525 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
5526 * characters to allow for further processing. Otherwise treat
5527 * $@ like $* since no splitting will be performed.
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00005528 *
5529 * var_str_list (can be NULL) is a list of "VAR=val" strings which take precedence
5530 * over shell varables. Needed for "A=a B=$A; echo $B" case - we use it
5531 * for correct expansion of "B=$A" word.
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005532 */
5533static void
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00005534argstr(char *p, int flag, struct strlist *var_str_list)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005535{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00005536 static const char spclchars[] ALIGN1 = {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005537 '=',
5538 ':',
5539 CTLQUOTEMARK,
5540 CTLENDVAR,
5541 CTLESC,
5542 CTLVAR,
5543 CTLBACKQ,
5544 CTLBACKQ | CTLQUOTE,
5545#if ENABLE_ASH_MATH_SUPPORT
5546 CTLENDARI,
5547#endif
5548 0
5549 };
5550 const char *reject = spclchars;
5551 int c;
5552 int quotes = flag & (EXP_FULL | EXP_CASE); /* do CTLESC */
5553 int breakall = flag & EXP_WORD;
5554 int inquotes;
5555 size_t length;
5556 int startloc;
5557
5558 if (!(flag & EXP_VARTILDE)) {
5559 reject += 2;
5560 } else if (flag & EXP_VARTILDE2) {
5561 reject++;
5562 }
5563 inquotes = 0;
5564 length = 0;
5565 if (flag & EXP_TILDE) {
5566 char *q;
5567
5568 flag &= ~EXP_TILDE;
5569 tilde:
5570 q = p;
5571 if (*q == CTLESC && (flag & EXP_QWORD))
5572 q++;
5573 if (*q == '~')
5574 p = exptilde(p, q, flag);
5575 }
5576 start:
5577 startloc = expdest - (char *)stackblock();
5578 for (;;) {
5579 length += strcspn(p + length, reject);
5580 c = p[length];
5581 if (c && (!(c & 0x80)
5582#if ENABLE_ASH_MATH_SUPPORT
5583 || c == CTLENDARI
5584#endif
5585 )) {
5586 /* c == '=' || c == ':' || c == CTLENDARI */
5587 length++;
5588 }
5589 if (length > 0) {
5590 int newloc;
5591 expdest = stack_nputstr(p, length, expdest);
5592 newloc = expdest - (char *)stackblock();
5593 if (breakall && !inquotes && newloc > startloc) {
5594 recordregion(startloc, newloc, 0);
5595 }
5596 startloc = newloc;
5597 }
5598 p += length + 1;
5599 length = 0;
5600
5601 switch (c) {
5602 case '\0':
5603 goto breakloop;
5604 case '=':
5605 if (flag & EXP_VARTILDE2) {
5606 p--;
5607 continue;
5608 }
5609 flag |= EXP_VARTILDE2;
5610 reject++;
5611 /* fall through */
5612 case ':':
5613 /*
5614 * sort of a hack - expand tildes in variable
5615 * assignments (after the first '=' and after ':'s).
5616 */
5617 if (*--p == '~') {
5618 goto tilde;
5619 }
5620 continue;
5621 }
5622
5623 switch (c) {
5624 case CTLENDVAR: /* ??? */
5625 goto breakloop;
5626 case CTLQUOTEMARK:
5627 /* "$@" syntax adherence hack */
5628 if (
5629 !inquotes &&
5630 !memcmp(p, dolatstr, 4) &&
5631 (p[4] == CTLQUOTEMARK || (
5632 p[4] == CTLENDVAR &&
5633 p[5] == CTLQUOTEMARK
5634 ))
5635 ) {
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00005636 p = evalvar(p + 1, flag, /* var_str_list: */ NULL) + 1;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005637 goto start;
5638 }
5639 inquotes = !inquotes;
5640 addquote:
5641 if (quotes) {
5642 p--;
5643 length++;
5644 startloc++;
5645 }
5646 break;
5647 case CTLESC:
5648 startloc++;
5649 length++;
5650 goto addquote;
5651 case CTLVAR:
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00005652 p = evalvar(p, flag, var_str_list);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005653 goto start;
5654 case CTLBACKQ:
5655 c = 0;
5656 case CTLBACKQ|CTLQUOTE:
5657 expbackq(argbackq->n, c, quotes);
5658 argbackq = argbackq->next;
5659 goto start;
5660#if ENABLE_ASH_MATH_SUPPORT
5661 case CTLENDARI:
5662 p--;
5663 expari(quotes);
5664 goto start;
5665#endif
5666 }
5667 }
5668 breakloop:
5669 ;
5670}
5671
5672static char *
5673scanleft(char *startp, char *rmesc, char *rmescend, char *str, int quotes,
5674 int zero)
5675{
5676 char *loc;
5677 char *loc2;
5678 char c;
5679
5680 loc = startp;
5681 loc2 = rmesc;
5682 do {
5683 int match;
5684 const char *s = loc2;
5685 c = *loc2;
5686 if (zero) {
5687 *loc2 = '\0';
5688 s = rmesc;
5689 }
5690 match = pmatch(str, s);
5691 *loc2 = c;
5692 if (match)
5693 return loc;
5694 if (quotes && *loc == CTLESC)
5695 loc++;
5696 loc++;
5697 loc2++;
5698 } while (c);
5699 return 0;
5700}
5701
5702static char *
5703scanright(char *startp, char *rmesc, char *rmescend, char *str, int quotes,
5704 int zero)
5705{
5706 int esc = 0;
5707 char *loc;
5708 char *loc2;
5709
5710 for (loc = str - 1, loc2 = rmescend; loc >= startp; loc2--) {
5711 int match;
5712 char c = *loc2;
5713 const char *s = loc2;
5714 if (zero) {
5715 *loc2 = '\0';
5716 s = rmesc;
5717 }
5718 match = pmatch(str, s);
5719 *loc2 = c;
5720 if (match)
5721 return loc;
5722 loc--;
5723 if (quotes) {
5724 if (--esc < 0) {
5725 esc = esclen(startp, loc);
5726 }
5727 if (esc % 2) {
5728 esc--;
5729 loc--;
5730 }
5731 }
5732 }
5733 return 0;
5734}
5735
5736static void varunset(const char *, const char *, const char *, int) ATTRIBUTE_NORETURN;
5737static void
5738varunset(const char *end, const char *var, const char *umsg, int varflags)
5739{
5740 const char *msg;
5741 const char *tail;
5742
5743 tail = nullstr;
5744 msg = "parameter not set";
5745 if (umsg) {
5746 if (*end == CTLENDVAR) {
5747 if (varflags & VSNUL)
5748 tail = " or null";
5749 } else
5750 msg = umsg;
5751 }
5752 ash_msg_and_raise_error("%.*s: %s%s", end - var - 1, var, msg, tail);
5753}
5754
5755static const char *
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00005756subevalvar(char *p, char *str, int strloc, int subtype,
5757 int startloc, int varflags, int quotes, struct strlist *var_str_list)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005758{
5759 char *startp;
5760 char *loc;
5761 int saveherefd = herefd;
5762 struct nodelist *saveargbackq = argbackq;
5763 int amount;
5764 char *rmesc, *rmescend;
5765 int zero;
5766 char *(*scan)(char *, char *, char *, char *, int , int);
5767
5768 herefd = -1;
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00005769 argstr(p, (subtype != VSASSIGN && subtype != VSQUESTION) ? EXP_CASE : 0,
5770 var_str_list);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005771 STPUTC('\0', expdest);
5772 herefd = saveherefd;
5773 argbackq = saveargbackq;
5774 startp = stackblock() + startloc;
5775
5776 switch (subtype) {
5777 case VSASSIGN:
5778 setvar(str, startp, 0);
5779 amount = startp - expdest;
5780 STADJUST(amount, expdest);
5781 return startp;
5782
5783 case VSQUESTION:
5784 varunset(p, str, startp, varflags);
5785 /* NOTREACHED */
5786 }
5787
5788 subtype -= VSTRIMRIGHT;
5789#if DEBUG
5790 if (subtype < 0 || subtype > 3)
5791 abort();
5792#endif
5793
5794 rmesc = startp;
5795 rmescend = stackblock() + strloc;
5796 if (quotes) {
5797 rmesc = _rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
5798 if (rmesc != startp) {
5799 rmescend = expdest;
5800 startp = stackblock() + startloc;
5801 }
5802 }
5803 rmescend--;
5804 str = stackblock() + strloc;
5805 preglob(str, varflags & VSQUOTE, 0);
5806
5807 /* zero = subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX */
5808 zero = subtype >> 1;
5809 /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
5810 scan = (subtype & 1) ^ zero ? scanleft : scanright;
5811
5812 loc = scan(startp, rmesc, rmescend, str, quotes, zero);
5813 if (loc) {
5814 if (zero) {
5815 memmove(startp, loc, str - loc);
5816 loc = startp + (str - loc) - 1;
5817 }
5818 *loc = '\0';
5819 amount = loc - expdest;
5820 STADJUST(amount, expdest);
5821 }
5822 return loc;
5823}
5824
5825/*
5826 * Add the value of a specialized variable to the stack string.
5827 */
5828static ssize_t
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00005829varvalue(char *name, int varflags, int flags, struct strlist *var_str_list)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005830{
5831 int num;
5832 char *p;
5833 int i;
5834 int sep = 0;
5835 int sepq = 0;
5836 ssize_t len = 0;
5837 char **ap;
5838 int syntax;
5839 int quoted = varflags & VSQUOTE;
5840 int subtype = varflags & VSTYPE;
5841 int quotes = flags & (EXP_FULL | EXP_CASE);
5842
5843 if (quoted && (flags & EXP_FULL))
5844 sep = 1 << CHAR_BIT;
5845
5846 syntax = quoted ? DQSYNTAX : BASESYNTAX;
5847 switch (*name) {
5848 case '$':
5849 num = rootpid;
5850 goto numvar;
5851 case '?':
5852 num = exitstatus;
5853 goto numvar;
5854 case '#':
5855 num = shellparam.nparam;
5856 goto numvar;
5857 case '!':
5858 num = backgndpid;
5859 if (num == 0)
5860 return -1;
5861 numvar:
5862 len = cvtnum(num);
5863 break;
5864 case '-':
5865 p = makestrspace(NOPTS, expdest);
5866 for (i = NOPTS - 1; i >= 0; i--) {
5867 if (optlist[i]) {
5868 USTPUTC(optletters(i), p);
5869 len++;
5870 }
5871 }
5872 expdest = p;
5873 break;
5874 case '@':
5875 if (sep)
5876 goto param;
5877 /* fall through */
5878 case '*':
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00005879 sep = ifsset() ? signed_char2int(ifsval()[0]) : ' ';
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005880 if (quotes && (SIT(sep, syntax) == CCTL || SIT(sep, syntax) == CBACK))
5881 sepq = 1;
5882 param:
5883 ap = shellparam.p;
5884 if (!ap)
5885 return -1;
5886 while ((p = *ap++)) {
5887 size_t partlen;
5888
5889 partlen = strlen(p);
5890 len += partlen;
5891
5892 if (!(subtype == VSPLUS || subtype == VSLENGTH))
5893 memtodest(p, partlen, syntax, quotes);
5894
5895 if (*ap && sep) {
5896 char *q;
5897
5898 len++;
5899 if (subtype == VSPLUS || subtype == VSLENGTH) {
5900 continue;
5901 }
5902 q = expdest;
5903 if (sepq)
5904 STPUTC(CTLESC, q);
5905 STPUTC(sep, q);
5906 expdest = q;
5907 }
5908 }
5909 return len;
5910 case '0':
5911 case '1':
5912 case '2':
5913 case '3':
5914 case '4':
5915 case '5':
5916 case '6':
5917 case '7':
5918 case '8':
5919 case '9':
5920 num = atoi(name);
5921 if (num < 0 || num > shellparam.nparam)
5922 return -1;
5923 p = num ? shellparam.p[num - 1] : arg0;
5924 goto value;
5925 default:
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00005926 /* NB: name has form "VAR=..." */
5927
5928 /* "A=a B=$A" case: var_str_list is a list of "A=a" strings
5929 * which should be considered before we check variables. */
5930 if (var_str_list) {
5931 unsigned name_len = (strchrnul(name, '=') - name) + 1;
5932 p = NULL;
5933 do {
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00005934 char *str, *eq;
5935 str = var_str_list->text;
5936 eq = strchr(str, '=');
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00005937 if (!eq) /* stop at first non-assignment */
5938 break;
5939 eq++;
5940 if (name_len == (eq - str)
5941 && strncmp(str, name, name_len) == 0) {
5942 p = eq;
5943 /* goto value; - WRONG! */
5944 /* think "A=1 A=2 B=$A" */
5945 }
5946 var_str_list = var_str_list->next;
5947 } while (var_str_list);
5948 if (p)
5949 goto value;
5950 }
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005951 p = lookupvar(name);
5952 value:
5953 if (!p)
5954 return -1;
5955
5956 len = strlen(p);
5957 if (!(subtype == VSPLUS || subtype == VSLENGTH))
5958 memtodest(p, len, syntax, quotes);
5959 return len;
5960 }
5961
5962 if (subtype == VSPLUS || subtype == VSLENGTH)
5963 STADJUST(-len, expdest);
5964 return len;
5965}
5966
5967/*
5968 * Expand a variable, and return a pointer to the next character in the
5969 * input string.
5970 */
5971static char *
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00005972evalvar(char *p, int flag, struct strlist *var_str_list)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005973{
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00005974 char varflags;
5975 char subtype;
5976 char quoted;
5977 char easy;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005978 char *var;
5979 int patloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005980 int startloc;
5981 ssize_t varlen;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005982
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005983 varflags = *p++;
5984 subtype = varflags & VSTYPE;
5985 quoted = varflags & VSQUOTE;
5986 var = p;
5987 easy = (!quoted || (*var == '@' && shellparam.nparam));
5988 startloc = expdest - (char *)stackblock();
5989 p = strchr(p, '=') + 1;
5990
5991 again:
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00005992 varlen = varvalue(var, varflags, flag, var_str_list);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005993 if (varflags & VSNUL)
5994 varlen--;
5995
5996 if (subtype == VSPLUS) {
5997 varlen = -1 - varlen;
5998 goto vsplus;
5999 }
6000
6001 if (subtype == VSMINUS) {
6002 vsplus:
6003 if (varlen < 0) {
6004 argstr(
6005 p, flag | EXP_TILDE |
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006006 (quoted ? EXP_QWORD : EXP_WORD),
6007 var_str_list
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006008 );
6009 goto end;
6010 }
6011 if (easy)
6012 goto record;
6013 goto end;
6014 }
6015
6016 if (subtype == VSASSIGN || subtype == VSQUESTION) {
6017 if (varlen < 0) {
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006018 if (subevalvar(p, var, /* strloc: */ 0,
6019 subtype, startloc, varflags,
6020 /* quotes: */ 0,
6021 var_str_list)
6022 ) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006023 varflags &= ~VSNUL;
6024 /*
6025 * Remove any recorded regions beyond
6026 * start of variable
6027 */
6028 removerecordregions(startloc);
6029 goto again;
6030 }
6031 goto end;
6032 }
6033 if (easy)
6034 goto record;
6035 goto end;
6036 }
6037
6038 if (varlen < 0 && uflag)
6039 varunset(p, var, 0, 0);
6040
6041 if (subtype == VSLENGTH) {
6042 cvtnum(varlen > 0 ? varlen : 0);
6043 goto record;
6044 }
6045
6046 if (subtype == VSNORMAL) {
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006047 if (easy)
6048 goto record;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006049 goto end;
6050 }
6051
6052#if DEBUG
6053 switch (subtype) {
6054 case VSTRIMLEFT:
6055 case VSTRIMLEFTMAX:
6056 case VSTRIMRIGHT:
6057 case VSTRIMRIGHTMAX:
6058 break;
6059 default:
6060 abort();
6061 }
6062#endif
6063
6064 if (varlen >= 0) {
6065 /*
6066 * Terminate the string and start recording the pattern
6067 * right after it
6068 */
6069 STPUTC('\0', expdest);
6070 patloc = expdest - (char *)stackblock();
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006071 if (0 == subevalvar(p, /* str: */ NULL, patloc, subtype,
6072 startloc, varflags,
6073 /* quotes: */ flag & (EXP_FULL | EXP_CASE),
6074 var_str_list)
6075 ) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006076 int amount = expdest - (
6077 (char *)stackblock() + patloc - 1
6078 );
6079 STADJUST(-amount, expdest);
6080 }
6081 /* Remove any recorded regions beyond start of variable */
6082 removerecordregions(startloc);
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006083 record:
6084 recordregion(startloc, expdest - (char *)stackblock(), quoted);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006085 }
6086
6087 end:
6088 if (subtype != VSNORMAL) { /* skip to end of alternative */
6089 int nesting = 1;
6090 for (;;) {
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006091 char c = *p++;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006092 if (c == CTLESC)
6093 p++;
6094 else if (c == CTLBACKQ || c == (CTLBACKQ|CTLQUOTE)) {
6095 if (varlen >= 0)
6096 argbackq = argbackq->next;
6097 } else if (c == CTLVAR) {
6098 if ((*p++ & VSTYPE) != VSNORMAL)
6099 nesting++;
6100 } else if (c == CTLENDVAR) {
6101 if (--nesting == 0)
6102 break;
6103 }
6104 }
6105 }
6106 return p;
6107}
6108
6109/*
6110 * Break the argument string into pieces based upon IFS and add the
6111 * strings to the argument list. The regions of the string to be
6112 * searched for IFS characters have been stored by recordregion.
6113 */
6114static void
6115ifsbreakup(char *string, struct arglist *arglist)
6116{
6117 struct ifsregion *ifsp;
6118 struct strlist *sp;
6119 char *start;
6120 char *p;
6121 char *q;
6122 const char *ifs, *realifs;
6123 int ifsspc;
6124 int nulonly;
6125
6126 start = string;
6127 if (ifslastp != NULL) {
6128 ifsspc = 0;
6129 nulonly = 0;
6130 realifs = ifsset() ? ifsval() : defifs;
6131 ifsp = &ifsfirst;
6132 do {
6133 p = string + ifsp->begoff;
6134 nulonly = ifsp->nulonly;
6135 ifs = nulonly ? nullstr : realifs;
6136 ifsspc = 0;
6137 while (p < string + ifsp->endoff) {
6138 q = p;
6139 if (*p == CTLESC)
6140 p++;
6141 if (!strchr(ifs, *p)) {
6142 p++;
6143 continue;
6144 }
6145 if (!nulonly)
6146 ifsspc = (strchr(defifs, *p) != NULL);
6147 /* Ignore IFS whitespace at start */
6148 if (q == start && ifsspc) {
6149 p++;
6150 start = p;
6151 continue;
6152 }
6153 *q = '\0';
Denis Vlasenko597906c2008-02-20 16:38:54 +00006154 sp = stzalloc(sizeof(*sp));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006155 sp->text = start;
6156 *arglist->lastp = sp;
6157 arglist->lastp = &sp->next;
6158 p++;
6159 if (!nulonly) {
6160 for (;;) {
6161 if (p >= string + ifsp->endoff) {
6162 break;
6163 }
6164 q = p;
6165 if (*p == CTLESC)
6166 p++;
6167 if (strchr(ifs, *p) == NULL ) {
6168 p = q;
6169 break;
Denis Vlasenko597906c2008-02-20 16:38:54 +00006170 }
6171 if (strchr(defifs, *p) == NULL) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006172 if (ifsspc) {
6173 p++;
6174 ifsspc = 0;
6175 } else {
6176 p = q;
6177 break;
6178 }
6179 } else
6180 p++;
6181 }
6182 }
6183 start = p;
6184 } /* while */
6185 ifsp = ifsp->next;
6186 } while (ifsp != NULL);
6187 if (nulonly)
6188 goto add;
6189 }
6190
6191 if (!*start)
6192 return;
6193
6194 add:
Denis Vlasenko597906c2008-02-20 16:38:54 +00006195 sp = stzalloc(sizeof(*sp));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006196 sp->text = start;
6197 *arglist->lastp = sp;
6198 arglist->lastp = &sp->next;
6199}
6200
6201static void
6202ifsfree(void)
6203{
6204 struct ifsregion *p;
6205
6206 INT_OFF;
6207 p = ifsfirst.next;
6208 do {
6209 struct ifsregion *ifsp;
6210 ifsp = p->next;
6211 free(p);
6212 p = ifsp;
6213 } while (p);
6214 ifslastp = NULL;
6215 ifsfirst.next = NULL;
6216 INT_ON;
6217}
6218
6219/*
6220 * Add a file name to the list.
6221 */
6222static void
6223addfname(const char *name)
6224{
6225 struct strlist *sp;
6226
Denis Vlasenko597906c2008-02-20 16:38:54 +00006227 sp = stzalloc(sizeof(*sp));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006228 sp->text = ststrdup(name);
6229 *exparg.lastp = sp;
6230 exparg.lastp = &sp->next;
6231}
6232
6233static char *expdir;
6234
6235/*
6236 * Do metacharacter (i.e. *, ?, [...]) expansion.
6237 */
6238static void
6239expmeta(char *enddir, char *name)
6240{
6241 char *p;
6242 const char *cp;
6243 char *start;
6244 char *endname;
6245 int metaflag;
6246 struct stat statb;
6247 DIR *dirp;
6248 struct dirent *dp;
6249 int atend;
6250 int matchdot;
6251
6252 metaflag = 0;
6253 start = name;
6254 for (p = name; *p; p++) {
6255 if (*p == '*' || *p == '?')
6256 metaflag = 1;
6257 else if (*p == '[') {
6258 char *q = p + 1;
6259 if (*q == '!')
6260 q++;
6261 for (;;) {
6262 if (*q == '\\')
6263 q++;
6264 if (*q == '/' || *q == '\0')
6265 break;
6266 if (*++q == ']') {
6267 metaflag = 1;
6268 break;
6269 }
6270 }
6271 } else if (*p == '\\')
6272 p++;
6273 else if (*p == '/') {
6274 if (metaflag)
6275 goto out;
6276 start = p + 1;
6277 }
6278 }
6279 out:
6280 if (metaflag == 0) { /* we've reached the end of the file name */
6281 if (enddir != expdir)
6282 metaflag++;
6283 p = name;
6284 do {
6285 if (*p == '\\')
6286 p++;
6287 *enddir++ = *p;
6288 } while (*p++);
6289 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
6290 addfname(expdir);
6291 return;
6292 }
6293 endname = p;
6294 if (name < start) {
6295 p = name;
6296 do {
6297 if (*p == '\\')
6298 p++;
6299 *enddir++ = *p++;
6300 } while (p < start);
6301 }
6302 if (enddir == expdir) {
6303 cp = ".";
6304 } else if (enddir == expdir + 1 && *expdir == '/') {
6305 cp = "/";
6306 } else {
6307 cp = expdir;
6308 enddir[-1] = '\0';
6309 }
6310 dirp = opendir(cp);
6311 if (dirp == NULL)
6312 return;
6313 if (enddir != expdir)
6314 enddir[-1] = '/';
6315 if (*endname == 0) {
6316 atend = 1;
6317 } else {
6318 atend = 0;
6319 *endname++ = '\0';
6320 }
6321 matchdot = 0;
6322 p = start;
6323 if (*p == '\\')
6324 p++;
6325 if (*p == '.')
6326 matchdot++;
Denis Vlasenko991a1da2008-02-10 19:02:53 +00006327 while (!intpending && (dp = readdir(dirp)) != NULL) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006328 if (dp->d_name[0] == '.' && ! matchdot)
6329 continue;
6330 if (pmatch(start, dp->d_name)) {
6331 if (atend) {
6332 strcpy(enddir, dp->d_name);
6333 addfname(expdir);
6334 } else {
6335 for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
6336 continue;
6337 p[-1] = '/';
6338 expmeta(p, endname);
6339 }
6340 }
6341 }
6342 closedir(dirp);
6343 if (! atend)
6344 endname[-1] = '/';
6345}
6346
6347static struct strlist *
6348msort(struct strlist *list, int len)
6349{
6350 struct strlist *p, *q = NULL;
6351 struct strlist **lpp;
6352 int half;
6353 int n;
6354
6355 if (len <= 1)
6356 return list;
6357 half = len >> 1;
6358 p = list;
6359 for (n = half; --n >= 0; ) {
6360 q = p;
6361 p = p->next;
6362 }
6363 q->next = NULL; /* terminate first half of list */
6364 q = msort(list, half); /* sort first half of list */
6365 p = msort(p, len - half); /* sort second half */
6366 lpp = &list;
6367 for (;;) {
6368#if ENABLE_LOCALE_SUPPORT
6369 if (strcoll(p->text, q->text) < 0)
6370#else
6371 if (strcmp(p->text, q->text) < 0)
6372#endif
6373 {
6374 *lpp = p;
6375 lpp = &p->next;
6376 p = *lpp;
6377 if (p == NULL) {
6378 *lpp = q;
6379 break;
6380 }
6381 } else {
6382 *lpp = q;
6383 lpp = &q->next;
6384 q = *lpp;
6385 if (q == NULL) {
6386 *lpp = p;
6387 break;
6388 }
6389 }
6390 }
6391 return list;
6392}
6393
6394/*
6395 * Sort the results of file name expansion. It calculates the number of
6396 * strings to sort and then calls msort (short for merge sort) to do the
6397 * work.
6398 */
6399static struct strlist *
6400expsort(struct strlist *str)
6401{
6402 int len;
6403 struct strlist *sp;
6404
6405 len = 0;
6406 for (sp = str; sp; sp = sp->next)
6407 len++;
6408 return msort(str, len);
6409}
6410
6411static void
6412expandmeta(struct strlist *str, int flag)
6413{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00006414 static const char metachars[] ALIGN1 = {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006415 '*', '?', '[', 0
6416 };
6417 /* TODO - EXP_REDIR */
6418
6419 while (str) {
6420 struct strlist **savelastp;
6421 struct strlist *sp;
6422 char *p;
6423
6424 if (fflag)
6425 goto nometa;
6426 if (!strpbrk(str->text, metachars))
6427 goto nometa;
6428 savelastp = exparg.lastp;
6429
6430 INT_OFF;
6431 p = preglob(str->text, 0, RMESCAPE_ALLOC | RMESCAPE_HEAP);
6432 {
6433 int i = strlen(str->text);
6434 expdir = ckmalloc(i < 2048 ? 2048 : i); /* XXX */
6435 }
6436
6437 expmeta(expdir, p);
6438 free(expdir);
6439 if (p != str->text)
6440 free(p);
6441 INT_ON;
6442 if (exparg.lastp == savelastp) {
6443 /*
6444 * no matches
6445 */
6446 nometa:
6447 *exparg.lastp = str;
6448 rmescapes(str->text);
6449 exparg.lastp = &str->next;
6450 } else {
6451 *exparg.lastp = NULL;
6452 *savelastp = sp = expsort(*savelastp);
6453 while (sp->next != NULL)
6454 sp = sp->next;
6455 exparg.lastp = &sp->next;
6456 }
6457 str = str->next;
6458 }
6459}
6460
6461/*
6462 * Perform variable substitution and command substitution on an argument,
6463 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
6464 * perform splitting and file name expansion. When arglist is NULL, perform
6465 * here document expansion.
6466 */
6467static void
6468expandarg(union node *arg, struct arglist *arglist, int flag)
6469{
6470 struct strlist *sp;
6471 char *p;
6472
6473 argbackq = arg->narg.backquote;
6474 STARTSTACKSTR(expdest);
6475 ifsfirst.next = NULL;
6476 ifslastp = NULL;
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006477 argstr(arg->narg.text, flag,
6478 /* var_str_list: */ arglist ? arglist->list : NULL);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006479 p = _STPUTC('\0', expdest);
6480 expdest = p - 1;
6481 if (arglist == NULL) {
6482 return; /* here document expanded */
6483 }
6484 p = grabstackstr(p);
6485 exparg.lastp = &exparg.list;
6486 /*
6487 * TODO - EXP_REDIR
6488 */
6489 if (flag & EXP_FULL) {
6490 ifsbreakup(p, &exparg);
6491 *exparg.lastp = NULL;
6492 exparg.lastp = &exparg.list;
6493 expandmeta(exparg.list, flag);
6494 } else {
6495 if (flag & EXP_REDIR) /*XXX - for now, just remove escapes */
6496 rmescapes(p);
Denis Vlasenko597906c2008-02-20 16:38:54 +00006497 sp = stzalloc(sizeof(*sp));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006498 sp->text = p;
6499 *exparg.lastp = sp;
6500 exparg.lastp = &sp->next;
6501 }
6502 if (ifsfirst.next)
6503 ifsfree();
6504 *exparg.lastp = NULL;
6505 if (exparg.list) {
6506 *arglist->lastp = exparg.list;
6507 arglist->lastp = exparg.lastp;
6508 }
6509}
6510
6511/*
6512 * Expand shell variables and backquotes inside a here document.
6513 */
6514static void
6515expandhere(union node *arg, int fd)
6516{
6517 herefd = fd;
6518 expandarg(arg, (struct arglist *)NULL, 0);
6519 full_write(fd, stackblock(), expdest - (char *)stackblock());
6520}
6521
6522/*
6523 * Returns true if the pattern matches the string.
6524 */
6525static int
6526patmatch(char *pattern, const char *string)
6527{
6528 return pmatch(preglob(pattern, 0, 0), string);
6529}
6530
6531/*
6532 * See if a pattern matches in a case statement.
6533 */
6534static int
6535casematch(union node *pattern, char *val)
6536{
6537 struct stackmark smark;
6538 int result;
6539
6540 setstackmark(&smark);
6541 argbackq = pattern->narg.backquote;
6542 STARTSTACKSTR(expdest);
6543 ifslastp = NULL;
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006544 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE,
6545 /* var_str_list: */ NULL);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006546 STACKSTRNUL(expdest);
6547 result = patmatch(stackblock(), val);
6548 popstackmark(&smark);
6549 return result;
6550}
6551
6552
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00006553/* ============ find_command */
6554
6555struct builtincmd {
6556 const char *name;
6557 int (*builtin)(int, char **);
6558 /* unsigned flags; */
6559};
6560#define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
Denis Vlasenkoe26b2782008-02-12 07:40:29 +00006561/* "regular" builtins always take precedence over commands,
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00006562 * regardless of PATH=....%builtin... position */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00006563#define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00006564#define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00006565
6566struct cmdentry {
6567 int cmdtype;
6568 union param {
6569 int index;
6570 const struct builtincmd *cmd;
6571 struct funcnode *func;
6572 } u;
6573};
6574/* values of cmdtype */
6575#define CMDUNKNOWN -1 /* no entry in table for command */
6576#define CMDNORMAL 0 /* command is an executable program */
6577#define CMDFUNCTION 1 /* command is a shell function */
6578#define CMDBUILTIN 2 /* command is a shell builtin */
6579
6580/* action to find_command() */
6581#define DO_ERR 0x01 /* prints errors */
6582#define DO_ABS 0x02 /* checks absolute paths */
6583#define DO_NOFUNC 0x04 /* don't return shell functions, for command */
6584#define DO_ALTPATH 0x08 /* using alternate path */
6585#define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
6586
6587static void find_command(char *, struct cmdentry *, int, const char *);
6588
6589
6590/* ============ Hashing commands */
6591
6592/*
6593 * When commands are first encountered, they are entered in a hash table.
6594 * This ensures that a full path search will not have to be done for them
6595 * on each invocation.
6596 *
6597 * We should investigate converting to a linear search, even though that
6598 * would make the command name "hash" a misnomer.
6599 */
6600
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00006601#define ARB 1 /* actual size determined at run time */
6602
6603struct tblentry {
6604 struct tblentry *next; /* next entry in hash chain */
6605 union param param; /* definition of builtin function */
6606 short cmdtype; /* index identifying command */
6607 char rehash; /* if set, cd done since entry created */
6608 char cmdname[ARB]; /* name of command */
6609};
6610
Denis Vlasenko01631112007-12-16 17:20:38 +00006611static struct tblentry **cmdtable;
6612#define INIT_G_cmdtable() do { \
6613 cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
6614} while (0)
6615
6616static int builtinloc = -1; /* index in path of %builtin, or -1 */
6617
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00006618
6619static void
6620tryexec(char *cmd, char **argv, char **envp)
6621{
6622 int repeated = 0;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00006623
Denis Vlasenko80d14be2007-04-10 23:03:30 +00006624#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko29e31dd2007-03-03 23:12:17 +00006625 if (strchr(cmd, '/') == NULL) {
Denis Vlasenko1aa7e472007-11-28 06:49:03 +00006626 int a = find_applet_by_name(cmd);
6627 if (a >= 0) {
6628 if (APPLET_IS_NOEXEC(a))
6629 run_applet_no_and_exit(a, argv);
Denis Vlasenko29e31dd2007-03-03 23:12:17 +00006630 /* re-exec ourselves with the new arguments */
Denis Vlasenkobdbbb7e2007-06-08 15:02:55 +00006631 execve(bb_busybox_exec_path, argv, envp);
Denis Vlasenko29e31dd2007-03-03 23:12:17 +00006632 /* If they called chroot or otherwise made the binary no longer
6633 * executable, fall through */
6634 }
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00006635 }
6636#endif
6637
6638 repeat:
6639#ifdef SYSV
6640 do {
6641 execve(cmd, argv, envp);
6642 } while (errno == EINTR);
6643#else
6644 execve(cmd, argv, envp);
6645#endif
6646 if (repeated++) {
6647 free(argv);
6648 } else if (errno == ENOEXEC) {
6649 char **ap;
6650 char **new;
6651
6652 for (ap = argv; *ap; ap++)
6653 ;
6654 ap = new = ckmalloc((ap - argv + 2) * sizeof(char *));
6655 ap[1] = cmd;
Denis Vlasenkoc44ab012007-04-09 03:11:58 +00006656 ap[0] = cmd = (char *)DEFAULT_SHELL;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00006657 ap += 2;
6658 argv++;
6659 while ((*ap++ = *argv++))
Denis Vlasenko597906c2008-02-20 16:38:54 +00006660 continue;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00006661 argv = new;
6662 goto repeat;
6663 }
6664}
6665
6666/*
6667 * Exec a program. Never returns. If you change this routine, you may
6668 * have to change the find_command routine as well.
6669 */
6670#define environment() listvars(VEXPORT, VUNSET, 0)
6671static void shellexec(char **, const char *, int) ATTRIBUTE_NORETURN;
6672static void
6673shellexec(char **argv, const char *path, int idx)
6674{
6675 char *cmdname;
6676 int e;
6677 char **envp;
6678 int exerrno;
6679
6680 clearredir(1);
6681 envp = environment();
Denis Vlasenko29e31dd2007-03-03 23:12:17 +00006682 if (strchr(argv[0], '/')
Denis Vlasenko80d14be2007-04-10 23:03:30 +00006683#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko1aa7e472007-11-28 06:49:03 +00006684 || find_applet_by_name(argv[0]) >= 0
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00006685#endif
6686 ) {
6687 tryexec(argv[0], argv, envp);
6688 e = errno;
6689 } else {
6690 e = ENOENT;
6691 while ((cmdname = padvance(&path, argv[0])) != NULL) {
6692 if (--idx < 0 && pathopt == NULL) {
6693 tryexec(cmdname, argv, envp);
6694 if (errno != ENOENT && errno != ENOTDIR)
6695 e = errno;
6696 }
6697 stunalloc(cmdname);
6698 }
6699 }
6700
6701 /* Map to POSIX errors */
6702 switch (e) {
6703 case EACCES:
6704 exerrno = 126;
6705 break;
6706 case ENOENT:
6707 exerrno = 127;
6708 break;
6709 default:
6710 exerrno = 2;
6711 break;
6712 }
6713 exitstatus = exerrno;
6714 TRACE(("shellexec failed for %s, errno %d, suppressint %d\n",
6715 argv[0], e, suppressint ));
6716 ash_msg_and_raise(EXEXEC, "%s: %s", argv[0], errmsg(e, "not found"));
6717 /* NOTREACHED */
6718}
6719
6720static void
6721printentry(struct tblentry *cmdp)
6722{
6723 int idx;
6724 const char *path;
6725 char *name;
6726
6727 idx = cmdp->param.index;
6728 path = pathval();
6729 do {
6730 name = padvance(&path, cmdp->cmdname);
6731 stunalloc(name);
6732 } while (--idx >= 0);
6733 out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
6734}
6735
6736/*
6737 * Clear out command entries. The argument specifies the first entry in
6738 * PATH which has changed.
6739 */
6740static void
6741clearcmdentry(int firstchange)
6742{
6743 struct tblentry **tblp;
6744 struct tblentry **pp;
6745 struct tblentry *cmdp;
6746
6747 INT_OFF;
6748 for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
6749 pp = tblp;
6750 while ((cmdp = *pp) != NULL) {
6751 if ((cmdp->cmdtype == CMDNORMAL &&
6752 cmdp->param.index >= firstchange)
6753 || (cmdp->cmdtype == CMDBUILTIN &&
6754 builtinloc >= firstchange)
6755 ) {
6756 *pp = cmdp->next;
6757 free(cmdp);
6758 } else {
6759 pp = &cmdp->next;
6760 }
6761 }
6762 }
6763 INT_ON;
6764}
6765
6766/*
6767 * Locate a command in the command hash table. If "add" is nonzero,
6768 * add the command to the table if it is not already present. The
6769 * variable "lastcmdentry" is set to point to the address of the link
6770 * pointing to the entry, so that delete_cmd_entry can delete the
6771 * entry.
6772 *
6773 * Interrupts must be off if called with add != 0.
6774 */
6775static struct tblentry **lastcmdentry;
6776
6777static struct tblentry *
6778cmdlookup(const char *name, int add)
6779{
6780 unsigned int hashval;
6781 const char *p;
6782 struct tblentry *cmdp;
6783 struct tblentry **pp;
6784
6785 p = name;
6786 hashval = (unsigned char)*p << 4;
6787 while (*p)
6788 hashval += (unsigned char)*p++;
6789 hashval &= 0x7FFF;
6790 pp = &cmdtable[hashval % CMDTABLESIZE];
6791 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
6792 if (strcmp(cmdp->cmdname, name) == 0)
6793 break;
6794 pp = &cmdp->next;
6795 }
6796 if (add && cmdp == NULL) {
Denis Vlasenko597906c2008-02-20 16:38:54 +00006797 cmdp = *pp = ckzalloc(sizeof(struct tblentry) - ARB
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00006798 + strlen(name) + 1);
Denis Vlasenko597906c2008-02-20 16:38:54 +00006799 /*cmdp->next = NULL; - ckzalloc did it */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00006800 cmdp->cmdtype = CMDUNKNOWN;
6801 strcpy(cmdp->cmdname, name);
6802 }
6803 lastcmdentry = pp;
6804 return cmdp;
6805}
6806
6807/*
6808 * Delete the command entry returned on the last lookup.
6809 */
6810static void
6811delete_cmd_entry(void)
6812{
6813 struct tblentry *cmdp;
6814
6815 INT_OFF;
6816 cmdp = *lastcmdentry;
6817 *lastcmdentry = cmdp->next;
6818 if (cmdp->cmdtype == CMDFUNCTION)
6819 freefunc(cmdp->param.func);
6820 free(cmdp);
6821 INT_ON;
6822}
6823
6824/*
6825 * Add a new command entry, replacing any existing command entry for
6826 * the same name - except special builtins.
6827 */
6828static void
6829addcmdentry(char *name, struct cmdentry *entry)
6830{
6831 struct tblentry *cmdp;
6832
6833 cmdp = cmdlookup(name, 1);
6834 if (cmdp->cmdtype == CMDFUNCTION) {
6835 freefunc(cmdp->param.func);
6836 }
6837 cmdp->cmdtype = entry->cmdtype;
6838 cmdp->param = entry->u;
6839 cmdp->rehash = 0;
6840}
6841
6842static int
6843hashcmd(int argc, char **argv)
6844{
6845 struct tblentry **pp;
6846 struct tblentry *cmdp;
6847 int c;
6848 struct cmdentry entry;
6849 char *name;
6850
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00006851 if (nextopt("r") != '\0') {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00006852 clearcmdentry(0);
6853 return 0;
6854 }
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00006855
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00006856 if (*argptr == NULL) {
6857 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
6858 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
6859 if (cmdp->cmdtype == CMDNORMAL)
6860 printentry(cmdp);
6861 }
6862 }
6863 return 0;
6864 }
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00006865
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00006866 c = 0;
6867 while ((name = *argptr) != NULL) {
6868 cmdp = cmdlookup(name, 0);
6869 if (cmdp != NULL
6870 && (cmdp->cmdtype == CMDNORMAL
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00006871 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
6872 ) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00006873 delete_cmd_entry();
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00006874 }
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00006875 find_command(name, &entry, DO_ERR, pathval());
6876 if (entry.cmdtype == CMDUNKNOWN)
6877 c = 1;
6878 argptr++;
6879 }
6880 return c;
6881}
6882
6883/*
6884 * Called when a cd is done. Marks all commands so the next time they
6885 * are executed they will be rehashed.
6886 */
6887static void
6888hashcd(void)
6889{
6890 struct tblentry **pp;
6891 struct tblentry *cmdp;
6892
6893 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
6894 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00006895 if (cmdp->cmdtype == CMDNORMAL
6896 || (cmdp->cmdtype == CMDBUILTIN
6897 && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
6898 && builtinloc > 0)
6899 ) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00006900 cmdp->rehash = 1;
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00006901 }
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00006902 }
6903 }
6904}
6905
6906/*
6907 * Fix command hash table when PATH changed.
6908 * Called before PATH is changed. The argument is the new value of PATH;
6909 * pathval() still returns the old value at this point.
6910 * Called with interrupts off.
6911 */
6912static void
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00006913changepath(const char *new)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00006914{
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00006915 const char *old;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00006916 int firstchange;
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00006917 int idx;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00006918 int idx_bltin;
6919
6920 old = pathval();
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00006921 firstchange = 9999; /* assume no change */
6922 idx = 0;
6923 idx_bltin = -1;
6924 for (;;) {
6925 if (*old != *new) {
6926 firstchange = idx;
6927 if ((*old == '\0' && *new == ':')
6928 || (*old == ':' && *new == '\0'))
6929 firstchange++;
6930 old = new; /* ignore subsequent differences */
6931 }
6932 if (*new == '\0')
6933 break;
6934 if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
6935 idx_bltin = idx;
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00006936 if (*new == ':')
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00006937 idx++;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00006938 new++, old++;
6939 }
6940 if (builtinloc < 0 && idx_bltin >= 0)
6941 builtinloc = idx_bltin; /* zap builtins */
6942 if (builtinloc >= 0 && idx_bltin < 0)
6943 firstchange = 0;
6944 clearcmdentry(firstchange);
6945 builtinloc = idx_bltin;
6946}
6947
6948#define TEOF 0
6949#define TNL 1
6950#define TREDIR 2
6951#define TWORD 3
6952#define TSEMI 4
6953#define TBACKGND 5
6954#define TAND 6
6955#define TOR 7
6956#define TPIPE 8
6957#define TLP 9
6958#define TRP 10
6959#define TENDCASE 11
6960#define TENDBQUOTE 12
6961#define TNOT 13
6962#define TCASE 14
6963#define TDO 15
6964#define TDONE 16
6965#define TELIF 17
6966#define TELSE 18
6967#define TESAC 19
6968#define TFI 20
6969#define TFOR 21
6970#define TIF 22
6971#define TIN 23
6972#define TTHEN 24
6973#define TUNTIL 25
6974#define TWHILE 26
6975#define TBEGIN 27
6976#define TEND 28
6977
6978/* first char is indicating which tokens mark the end of a list */
6979static const char *const tokname_array[] = {
6980 "\1end of file",
6981 "\0newline",
6982 "\0redirection",
6983 "\0word",
6984 "\0;",
6985 "\0&",
6986 "\0&&",
6987 "\0||",
6988 "\0|",
6989 "\0(",
6990 "\1)",
6991 "\1;;",
6992 "\1`",
6993#define KWDOFFSET 13
6994 /* the following are keywords */
6995 "\0!",
6996 "\0case",
6997 "\1do",
6998 "\1done",
6999 "\1elif",
7000 "\1else",
7001 "\1esac",
7002 "\1fi",
7003 "\0for",
7004 "\0if",
7005 "\0in",
7006 "\1then",
7007 "\0until",
7008 "\0while",
7009 "\0{",
7010 "\1}",
7011};
7012
7013static const char *
7014tokname(int tok)
7015{
7016 static char buf[16];
7017
Denis Vlasenko240a1cf2007-04-08 16:07:02 +00007018//try this:
7019//if (tok < TSEMI) return tokname_array[tok] + 1;
7020//sprintf(buf, "\"%s\"", tokname_array[tok] + 1);
7021//return buf;
7022
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007023 if (tok >= TSEMI)
7024 buf[0] = '"';
7025 sprintf(buf + (tok >= TSEMI), "%s%c",
7026 tokname_array[tok] + 1, (tok >= TSEMI ? '"' : 0));
7027 return buf;
7028}
7029
7030/* Wrapper around strcmp for qsort/bsearch/... */
7031static int
7032pstrcmp(const void *a, const void *b)
7033{
Denis Vlasenko240a1cf2007-04-08 16:07:02 +00007034 return strcmp((char*) a, (*(char**) b) + 1);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007035}
7036
7037static const char *const *
7038findkwd(const char *s)
7039{
7040 return bsearch(s, tokname_array + KWDOFFSET,
Denis Vlasenko80b8b392007-06-25 10:55:35 +00007041 ARRAY_SIZE(tokname_array) - KWDOFFSET,
7042 sizeof(tokname_array[0]), pstrcmp);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007043}
7044
7045/*
7046 * Locate and print what a word is...
7047 */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007048static int
7049describe_command(char *command, int describe_command_verbose)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007050{
7051 struct cmdentry entry;
7052 struct tblentry *cmdp;
7053#if ENABLE_ASH_ALIAS
7054 const struct alias *ap;
7055#endif
7056 const char *path = pathval();
7057
7058 if (describe_command_verbose) {
7059 out1str(command);
7060 }
7061
7062 /* First look at the keywords */
7063 if (findkwd(command)) {
7064 out1str(describe_command_verbose ? " is a shell keyword" : command);
7065 goto out;
7066 }
7067
7068#if ENABLE_ASH_ALIAS
7069 /* Then look at the aliases */
7070 ap = lookupalias(command, 0);
7071 if (ap != NULL) {
Denis Vlasenko46846e22007-05-20 13:08:31 +00007072 if (!describe_command_verbose) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007073 out1str("alias ");
7074 printalias(ap);
7075 return 0;
7076 }
Denis Vlasenko46846e22007-05-20 13:08:31 +00007077 out1fmt(" is an alias for %s", ap->val);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007078 goto out;
7079 }
7080#endif
7081 /* Then check if it is a tracked alias */
7082 cmdp = cmdlookup(command, 0);
7083 if (cmdp != NULL) {
7084 entry.cmdtype = cmdp->cmdtype;
7085 entry.u = cmdp->param;
7086 } else {
7087 /* Finally use brute force */
7088 find_command(command, &entry, DO_ABS, path);
7089 }
7090
7091 switch (entry.cmdtype) {
7092 case CMDNORMAL: {
7093 int j = entry.u.index;
7094 char *p;
7095 if (j == -1) {
7096 p = command;
7097 } else {
7098 do {
7099 p = padvance(&path, command);
7100 stunalloc(p);
7101 } while (--j >= 0);
7102 }
7103 if (describe_command_verbose) {
7104 out1fmt(" is%s %s",
7105 (cmdp ? " a tracked alias for" : nullstr), p
7106 );
7107 } else {
7108 out1str(p);
7109 }
7110 break;
7111 }
7112
7113 case CMDFUNCTION:
7114 if (describe_command_verbose) {
7115 out1str(" is a shell function");
7116 } else {
7117 out1str(command);
7118 }
7119 break;
7120
7121 case CMDBUILTIN:
7122 if (describe_command_verbose) {
7123 out1fmt(" is a %sshell builtin",
7124 IS_BUILTIN_SPECIAL(entry.u.cmd) ?
7125 "special " : nullstr
7126 );
7127 } else {
7128 out1str(command);
7129 }
7130 break;
7131
7132 default:
7133 if (describe_command_verbose) {
7134 out1str(": not found\n");
7135 }
7136 return 127;
7137 }
7138 out:
7139 outstr("\n", stdout);
7140 return 0;
7141}
7142
7143static int
7144typecmd(int argc, char **argv)
7145{
Denis Vlasenko46846e22007-05-20 13:08:31 +00007146 int i = 1;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007147 int err = 0;
Denis Vlasenko46846e22007-05-20 13:08:31 +00007148 int verbose = 1;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007149
Denis Vlasenko46846e22007-05-20 13:08:31 +00007150 /* type -p ... ? (we don't bother checking for 'p') */
Denis Vlasenko1fc62382007-06-25 22:55:34 +00007151 if (argv[1] && argv[1][0] == '-') {
Denis Vlasenko46846e22007-05-20 13:08:31 +00007152 i++;
7153 verbose = 0;
7154 }
7155 while (i < argc) {
7156 err |= describe_command(argv[i++], verbose);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007157 }
7158 return err;
7159}
7160
7161#if ENABLE_ASH_CMDCMD
7162static int
7163commandcmd(int argc, char **argv)
7164{
7165 int c;
7166 enum {
7167 VERIFY_BRIEF = 1,
7168 VERIFY_VERBOSE = 2,
7169 } verify = 0;
7170
7171 while ((c = nextopt("pvV")) != '\0')
7172 if (c == 'V')
7173 verify |= VERIFY_VERBOSE;
7174 else if (c == 'v')
7175 verify |= VERIFY_BRIEF;
7176#if DEBUG
7177 else if (c != 'p')
7178 abort();
7179#endif
7180 if (verify)
7181 return describe_command(*argptr, verify - VERIFY_BRIEF);
7182
7183 return 0;
7184}
7185#endif
7186
7187
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007188/* ============ eval.c */
Eric Andersencb57d552001-06-28 07:25:16 +00007189
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007190static int funcblocksize; /* size of structures in function */
7191static int funcstringsize; /* size of strings in node */
7192static void *funcblock; /* block to allocate function from */
7193static char *funcstring; /* block to allocate strings from */
7194
Eric Andersencb57d552001-06-28 07:25:16 +00007195/* flags in argument to evaltree */
Eric Andersenc470f442003-07-28 09:56:35 +00007196#define EV_EXIT 01 /* exit after evaluating tree */
7197#define EV_TESTED 02 /* exit status is checked; ignore -e flag */
7198#define EV_BACKCMD 04 /* command executing within back quotes */
Eric Andersencb57d552001-06-28 07:25:16 +00007199
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007200static const short nodesize[26] = {
7201 SHELL_ALIGN(sizeof(struct ncmd)),
7202 SHELL_ALIGN(sizeof(struct npipe)),
7203 SHELL_ALIGN(sizeof(struct nredir)),
7204 SHELL_ALIGN(sizeof(struct nredir)),
7205 SHELL_ALIGN(sizeof(struct nredir)),
7206 SHELL_ALIGN(sizeof(struct nbinary)),
7207 SHELL_ALIGN(sizeof(struct nbinary)),
7208 SHELL_ALIGN(sizeof(struct nbinary)),
7209 SHELL_ALIGN(sizeof(struct nif)),
7210 SHELL_ALIGN(sizeof(struct nbinary)),
7211 SHELL_ALIGN(sizeof(struct nbinary)),
7212 SHELL_ALIGN(sizeof(struct nfor)),
7213 SHELL_ALIGN(sizeof(struct ncase)),
7214 SHELL_ALIGN(sizeof(struct nclist)),
7215 SHELL_ALIGN(sizeof(struct narg)),
7216 SHELL_ALIGN(sizeof(struct narg)),
7217 SHELL_ALIGN(sizeof(struct nfile)),
7218 SHELL_ALIGN(sizeof(struct nfile)),
7219 SHELL_ALIGN(sizeof(struct nfile)),
7220 SHELL_ALIGN(sizeof(struct nfile)),
7221 SHELL_ALIGN(sizeof(struct nfile)),
7222 SHELL_ALIGN(sizeof(struct ndup)),
7223 SHELL_ALIGN(sizeof(struct ndup)),
7224 SHELL_ALIGN(sizeof(struct nhere)),
7225 SHELL_ALIGN(sizeof(struct nhere)),
7226 SHELL_ALIGN(sizeof(struct nnot)),
7227};
7228
7229static void calcsize(union node *n);
7230
7231static void
7232sizenodelist(struct nodelist *lp)
7233{
7234 while (lp) {
7235 funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
7236 calcsize(lp->n);
7237 lp = lp->next;
7238 }
7239}
7240
7241static void
7242calcsize(union node *n)
7243{
7244 if (n == NULL)
7245 return;
7246 funcblocksize += nodesize[n->type];
7247 switch (n->type) {
7248 case NCMD:
7249 calcsize(n->ncmd.redirect);
7250 calcsize(n->ncmd.args);
7251 calcsize(n->ncmd.assign);
7252 break;
7253 case NPIPE:
7254 sizenodelist(n->npipe.cmdlist);
7255 break;
7256 case NREDIR:
7257 case NBACKGND:
7258 case NSUBSHELL:
7259 calcsize(n->nredir.redirect);
7260 calcsize(n->nredir.n);
7261 break;
7262 case NAND:
7263 case NOR:
7264 case NSEMI:
7265 case NWHILE:
7266 case NUNTIL:
7267 calcsize(n->nbinary.ch2);
7268 calcsize(n->nbinary.ch1);
7269 break;
7270 case NIF:
7271 calcsize(n->nif.elsepart);
7272 calcsize(n->nif.ifpart);
7273 calcsize(n->nif.test);
7274 break;
7275 case NFOR:
7276 funcstringsize += strlen(n->nfor.var) + 1;
7277 calcsize(n->nfor.body);
7278 calcsize(n->nfor.args);
7279 break;
7280 case NCASE:
7281 calcsize(n->ncase.cases);
7282 calcsize(n->ncase.expr);
7283 break;
7284 case NCLIST:
7285 calcsize(n->nclist.body);
7286 calcsize(n->nclist.pattern);
7287 calcsize(n->nclist.next);
7288 break;
7289 case NDEFUN:
7290 case NARG:
7291 sizenodelist(n->narg.backquote);
7292 funcstringsize += strlen(n->narg.text) + 1;
7293 calcsize(n->narg.next);
7294 break;
7295 case NTO:
7296 case NCLOBBER:
7297 case NFROM:
7298 case NFROMTO:
7299 case NAPPEND:
7300 calcsize(n->nfile.fname);
7301 calcsize(n->nfile.next);
7302 break;
7303 case NTOFD:
7304 case NFROMFD:
7305 calcsize(n->ndup.vname);
7306 calcsize(n->ndup.next);
7307 break;
7308 case NHERE:
7309 case NXHERE:
7310 calcsize(n->nhere.doc);
7311 calcsize(n->nhere.next);
7312 break;
7313 case NNOT:
7314 calcsize(n->nnot.com);
7315 break;
7316 };
7317}
7318
7319static char *
7320nodeckstrdup(char *s)
7321{
7322 char *rtn = funcstring;
7323
7324 strcpy(funcstring, s);
7325 funcstring += strlen(s) + 1;
7326 return rtn;
7327}
7328
7329static union node *copynode(union node *);
7330
7331static struct nodelist *
7332copynodelist(struct nodelist *lp)
7333{
7334 struct nodelist *start;
7335 struct nodelist **lpp;
7336
7337 lpp = &start;
7338 while (lp) {
7339 *lpp = funcblock;
7340 funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
7341 (*lpp)->n = copynode(lp->n);
7342 lp = lp->next;
7343 lpp = &(*lpp)->next;
7344 }
7345 *lpp = NULL;
7346 return start;
7347}
7348
7349static union node *
7350copynode(union node *n)
7351{
7352 union node *new;
7353
7354 if (n == NULL)
7355 return NULL;
7356 new = funcblock;
7357 funcblock = (char *) funcblock + nodesize[n->type];
7358
7359 switch (n->type) {
7360 case NCMD:
7361 new->ncmd.redirect = copynode(n->ncmd.redirect);
7362 new->ncmd.args = copynode(n->ncmd.args);
7363 new->ncmd.assign = copynode(n->ncmd.assign);
7364 break;
7365 case NPIPE:
7366 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
7367 new->npipe.backgnd = n->npipe.backgnd;
7368 break;
7369 case NREDIR:
7370 case NBACKGND:
7371 case NSUBSHELL:
7372 new->nredir.redirect = copynode(n->nredir.redirect);
7373 new->nredir.n = copynode(n->nredir.n);
7374 break;
7375 case NAND:
7376 case NOR:
7377 case NSEMI:
7378 case NWHILE:
7379 case NUNTIL:
7380 new->nbinary.ch2 = copynode(n->nbinary.ch2);
7381 new->nbinary.ch1 = copynode(n->nbinary.ch1);
7382 break;
7383 case NIF:
7384 new->nif.elsepart = copynode(n->nif.elsepart);
7385 new->nif.ifpart = copynode(n->nif.ifpart);
7386 new->nif.test = copynode(n->nif.test);
7387 break;
7388 case NFOR:
7389 new->nfor.var = nodeckstrdup(n->nfor.var);
7390 new->nfor.body = copynode(n->nfor.body);
7391 new->nfor.args = copynode(n->nfor.args);
7392 break;
7393 case NCASE:
7394 new->ncase.cases = copynode(n->ncase.cases);
7395 new->ncase.expr = copynode(n->ncase.expr);
7396 break;
7397 case NCLIST:
7398 new->nclist.body = copynode(n->nclist.body);
7399 new->nclist.pattern = copynode(n->nclist.pattern);
7400 new->nclist.next = copynode(n->nclist.next);
7401 break;
7402 case NDEFUN:
7403 case NARG:
7404 new->narg.backquote = copynodelist(n->narg.backquote);
7405 new->narg.text = nodeckstrdup(n->narg.text);
7406 new->narg.next = copynode(n->narg.next);
7407 break;
7408 case NTO:
7409 case NCLOBBER:
7410 case NFROM:
7411 case NFROMTO:
7412 case NAPPEND:
7413 new->nfile.fname = copynode(n->nfile.fname);
7414 new->nfile.fd = n->nfile.fd;
7415 new->nfile.next = copynode(n->nfile.next);
7416 break;
7417 case NTOFD:
7418 case NFROMFD:
7419 new->ndup.vname = copynode(n->ndup.vname);
7420 new->ndup.dupfd = n->ndup.dupfd;
7421 new->ndup.fd = n->ndup.fd;
7422 new->ndup.next = copynode(n->ndup.next);
7423 break;
7424 case NHERE:
7425 case NXHERE:
7426 new->nhere.doc = copynode(n->nhere.doc);
7427 new->nhere.fd = n->nhere.fd;
7428 new->nhere.next = copynode(n->nhere.next);
7429 break;
7430 case NNOT:
7431 new->nnot.com = copynode(n->nnot.com);
7432 break;
7433 };
7434 new->type = n->type;
7435 return new;
7436}
7437
7438/*
7439 * Make a copy of a parse tree.
7440 */
7441static struct funcnode *
7442copyfunc(union node *n)
7443{
7444 struct funcnode *f;
7445 size_t blocksize;
7446
7447 funcblocksize = offsetof(struct funcnode, n);
7448 funcstringsize = 0;
7449 calcsize(n);
7450 blocksize = funcblocksize;
7451 f = ckmalloc(blocksize + funcstringsize);
7452 funcblock = (char *) f + offsetof(struct funcnode, n);
7453 funcstring = (char *) f + blocksize;
7454 copynode(n);
7455 f->count = 0;
7456 return f;
7457}
7458
7459/*
7460 * Define a shell function.
7461 */
7462static void
7463defun(char *name, union node *func)
7464{
7465 struct cmdentry entry;
7466
7467 INT_OFF;
7468 entry.cmdtype = CMDFUNCTION;
7469 entry.u.func = copyfunc(func);
7470 addcmdentry(name, &entry);
7471 INT_ON;
7472}
7473
7474static int evalskip; /* set if we are skipping commands */
7475/* reasons for skipping commands (see comment on breakcmd routine) */
7476#define SKIPBREAK (1 << 0)
7477#define SKIPCONT (1 << 1)
7478#define SKIPFUNC (1 << 2)
7479#define SKIPFILE (1 << 3)
7480#define SKIPEVAL (1 << 4)
7481static int skipcount; /* number of levels to skip */
7482static int funcnest; /* depth of function calls */
7483
Denis Vlasenkofc06f292007-02-23 21:09:35 +00007484/* forward decl way out to parsing code - dotrap needs it */
7485static int evalstring(char *s, int mask);
7486
7487/*
7488 * Called to execute a trap. Perhaps we should avoid entering new trap
7489 * handlers while we are executing a trap handler.
7490 */
7491static int
7492dotrap(void)
7493{
7494 char *p;
7495 char *q;
7496 int i;
7497 int savestatus;
Denis Vlasenko991a1da2008-02-10 19:02:53 +00007498 int skip;
Denis Vlasenkofc06f292007-02-23 21:09:35 +00007499
7500 savestatus = exitstatus;
Denis Vlasenko7c139b42007-03-21 20:17:27 +00007501 pendingsig = 0;
Denis Vlasenkofc06f292007-02-23 21:09:35 +00007502 xbarrier();
7503
7504 for (i = 0, q = gotsig; i < NSIG - 1; i++, q++) {
7505 if (!*q)
7506 continue;
7507 *q = '\0';
7508
7509 p = trap[i + 1];
7510 if (!p)
7511 continue;
7512 skip = evalstring(p, SKIPEVAL);
7513 exitstatus = savestatus;
7514 if (skip)
Denis Vlasenko991a1da2008-02-10 19:02:53 +00007515 return skip;
Denis Vlasenkofc06f292007-02-23 21:09:35 +00007516 }
7517
Denis Vlasenko991a1da2008-02-10 19:02:53 +00007518 return 0;
Denis Vlasenkofc06f292007-02-23 21:09:35 +00007519}
7520
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007521/* forward declarations - evaluation is fairly recursive business... */
Eric Andersenc470f442003-07-28 09:56:35 +00007522static void evalloop(union node *, int);
7523static void evalfor(union node *, int);
7524static void evalcase(union node *, int);
7525static void evalsubshell(union node *, int);
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00007526static void expredir(union node *);
Eric Andersenc470f442003-07-28 09:56:35 +00007527static void evalpipe(union node *, int);
7528static void evalcommand(union node *, int);
7529static int evalbltin(const struct builtincmd *, int, char **);
Glenn L McGrath50812ff2002-08-23 13:14:48 +00007530static void prehash(union node *);
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00007531
Eric Andersen62483552001-07-10 06:09:16 +00007532/*
Eric Andersenc470f442003-07-28 09:56:35 +00007533 * Evaluate a parse tree. The value is left in the global variable
7534 * exitstatus.
Eric Andersen62483552001-07-10 06:09:16 +00007535 */
Eric Andersenc470f442003-07-28 09:56:35 +00007536static void
7537evaltree(union node *n, int flags)
Eric Andersen62483552001-07-10 06:09:16 +00007538{
Eric Andersenc470f442003-07-28 09:56:35 +00007539 int checkexit = 0;
7540 void (*evalfn)(union node *, int);
7541 unsigned isor;
7542 int status;
7543 if (n == NULL) {
7544 TRACE(("evaltree(NULL) called\n"));
7545 goto out;
Eric Andersen62483552001-07-10 06:09:16 +00007546 }
Eric Andersenc470f442003-07-28 09:56:35 +00007547 TRACE(("pid %d, evaltree(%p: %d, %d) called\n",
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +00007548 getpid(), n, n->type, flags));
Eric Andersenc470f442003-07-28 09:56:35 +00007549 switch (n->type) {
7550 default:
Denis Vlasenkoa7189f02006-11-17 20:29:00 +00007551#if DEBUG
Eric Andersenc470f442003-07-28 09:56:35 +00007552 out1fmt("Node type = %d\n", n->type);
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00007553 fflush(stdout);
Eric Andersenc470f442003-07-28 09:56:35 +00007554 break;
7555#endif
7556 case NNOT:
7557 evaltree(n->nnot.com, EV_TESTED);
7558 status = !exitstatus;
7559 goto setstatus;
7560 case NREDIR:
7561 expredir(n->nredir.redirect);
7562 status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
7563 if (!status) {
7564 evaltree(n->nredir.n, flags & EV_TESTED);
7565 status = exitstatus;
7566 }
7567 popredir(0);
7568 goto setstatus;
7569 case NCMD:
7570 evalfn = evalcommand;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00007571 checkexit:
Eric Andersenc470f442003-07-28 09:56:35 +00007572 if (eflag && !(flags & EV_TESTED))
7573 checkexit = ~0;
7574 goto calleval;
7575 case NFOR:
7576 evalfn = evalfor;
7577 goto calleval;
7578 case NWHILE:
7579 case NUNTIL:
7580 evalfn = evalloop;
7581 goto calleval;
7582 case NSUBSHELL:
7583 case NBACKGND:
7584 evalfn = evalsubshell;
7585 goto calleval;
7586 case NPIPE:
7587 evalfn = evalpipe;
7588 goto checkexit;
7589 case NCASE:
7590 evalfn = evalcase;
7591 goto calleval;
7592 case NAND:
7593 case NOR:
7594 case NSEMI:
7595#if NAND + 1 != NOR
7596#error NAND + 1 != NOR
7597#endif
7598#if NOR + 1 != NSEMI
7599#error NOR + 1 != NSEMI
7600#endif
7601 isor = n->type - NAND;
7602 evaltree(
7603 n->nbinary.ch1,
7604 (flags | ((isor >> 1) - 1)) & EV_TESTED
7605 );
7606 if (!exitstatus == isor)
7607 break;
7608 if (!evalskip) {
7609 n = n->nbinary.ch2;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00007610 evaln:
Eric Andersenc470f442003-07-28 09:56:35 +00007611 evalfn = evaltree;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00007612 calleval:
Eric Andersenc470f442003-07-28 09:56:35 +00007613 evalfn(n, flags);
7614 break;
7615 }
7616 break;
7617 case NIF:
7618 evaltree(n->nif.test, EV_TESTED);
7619 if (evalskip)
7620 break;
7621 if (exitstatus == 0) {
7622 n = n->nif.ifpart;
7623 goto evaln;
7624 } else if (n->nif.elsepart) {
7625 n = n->nif.elsepart;
7626 goto evaln;
7627 }
7628 goto success;
7629 case NDEFUN:
7630 defun(n->narg.text, n->narg.next);
Denis Vlasenko5cedb752007-02-18 19:56:41 +00007631 success:
Eric Andersenc470f442003-07-28 09:56:35 +00007632 status = 0;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00007633 setstatus:
Eric Andersenc470f442003-07-28 09:56:35 +00007634 exitstatus = status;
7635 break;
7636 }
Denis Vlasenko5cedb752007-02-18 19:56:41 +00007637 out:
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00007638 if ((checkexit & exitstatus))
7639 evalskip |= SKIPEVAL;
Denis Vlasenko7c139b42007-03-21 20:17:27 +00007640 else if (pendingsig && dotrap())
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00007641 goto exexit;
7642
7643 if (flags & EV_EXIT) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00007644 exexit:
Denis Vlasenkob012b102007-02-19 22:43:01 +00007645 raise_exception(EXEXIT);
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00007646 }
Eric Andersen62483552001-07-10 06:09:16 +00007647}
7648
Eric Andersenc470f442003-07-28 09:56:35 +00007649#if !defined(__alpha__) || (defined(__GNUC__) && __GNUC__ >= 3)
7650static
7651#endif
7652void evaltreenr(union node *, int) __attribute__ ((alias("evaltree"),__noreturn__));
7653
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00007654static int loopnest; /* current loop nesting level */
Eric Andersenc470f442003-07-28 09:56:35 +00007655
7656static void
7657evalloop(union node *n, int flags)
Eric Andersencb57d552001-06-28 07:25:16 +00007658{
7659 int status;
7660
7661 loopnest++;
7662 status = 0;
Glenn L McGrath50812ff2002-08-23 13:14:48 +00007663 flags &= EV_TESTED;
Eric Andersencb57d552001-06-28 07:25:16 +00007664 for (;;) {
Eric Andersenc470f442003-07-28 09:56:35 +00007665 int i;
7666
Eric Andersencb57d552001-06-28 07:25:16 +00007667 evaltree(n->nbinary.ch1, EV_TESTED);
7668 if (evalskip) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00007669 skipping:
7670 if (evalskip == SKIPCONT && --skipcount <= 0) {
Eric Andersencb57d552001-06-28 07:25:16 +00007671 evalskip = 0;
7672 continue;
7673 }
7674 if (evalskip == SKIPBREAK && --skipcount <= 0)
7675 evalskip = 0;
7676 break;
7677 }
Eric Andersenc470f442003-07-28 09:56:35 +00007678 i = exitstatus;
7679 if (n->type != NWHILE)
7680 i = !i;
7681 if (i != 0)
7682 break;
Glenn L McGrath50812ff2002-08-23 13:14:48 +00007683 evaltree(n->nbinary.ch2, flags);
Eric Andersencb57d552001-06-28 07:25:16 +00007684 status = exitstatus;
7685 if (evalskip)
7686 goto skipping;
7687 }
7688 loopnest--;
7689 exitstatus = status;
7690}
7691
Eric Andersenc470f442003-07-28 09:56:35 +00007692static void
7693evalfor(union node *n, int flags)
Eric Andersencb57d552001-06-28 07:25:16 +00007694{
7695 struct arglist arglist;
7696 union node *argp;
7697 struct strlist *sp;
7698 struct stackmark smark;
7699
7700 setstackmark(&smark);
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00007701 arglist.list = NULL;
Eric Andersencb57d552001-06-28 07:25:16 +00007702 arglist.lastp = &arglist.list;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00007703 for (argp = n->nfor.args; argp; argp = argp->narg.next) {
Eric Andersencb57d552001-06-28 07:25:16 +00007704 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE | EXP_RECORD);
Eric Andersenc470f442003-07-28 09:56:35 +00007705 /* XXX */
Eric Andersencb57d552001-06-28 07:25:16 +00007706 if (evalskip)
7707 goto out;
7708 }
7709 *arglist.lastp = NULL;
7710
7711 exitstatus = 0;
7712 loopnest++;
Glenn L McGrath50812ff2002-08-23 13:14:48 +00007713 flags &= EV_TESTED;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00007714 for (sp = arglist.list; sp; sp = sp->next) {
Eric Andersencb57d552001-06-28 07:25:16 +00007715 setvar(n->nfor.var, sp->text, 0);
Glenn L McGrath50812ff2002-08-23 13:14:48 +00007716 evaltree(n->nfor.body, flags);
Eric Andersencb57d552001-06-28 07:25:16 +00007717 if (evalskip) {
7718 if (evalskip == SKIPCONT && --skipcount <= 0) {
7719 evalskip = 0;
7720 continue;
7721 }
7722 if (evalskip == SKIPBREAK && --skipcount <= 0)
7723 evalskip = 0;
7724 break;
7725 }
7726 }
7727 loopnest--;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00007728 out:
Eric Andersencb57d552001-06-28 07:25:16 +00007729 popstackmark(&smark);
7730}
7731
Eric Andersenc470f442003-07-28 09:56:35 +00007732static void
7733evalcase(union node *n, int flags)
Eric Andersencb57d552001-06-28 07:25:16 +00007734{
7735 union node *cp;
7736 union node *patp;
7737 struct arglist arglist;
7738 struct stackmark smark;
7739
7740 setstackmark(&smark);
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00007741 arglist.list = NULL;
Eric Andersencb57d552001-06-28 07:25:16 +00007742 arglist.lastp = &arglist.list;
Eric Andersencb57d552001-06-28 07:25:16 +00007743 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
Eric Andersenc470f442003-07-28 09:56:35 +00007744 exitstatus = 0;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00007745 for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
7746 for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
Eric Andersencb57d552001-06-28 07:25:16 +00007747 if (casematch(patp, arglist.list->text)) {
7748 if (evalskip == 0) {
7749 evaltree(cp->nclist.body, flags);
7750 }
7751 goto out;
7752 }
7753 }
7754 }
Denis Vlasenko5cedb752007-02-18 19:56:41 +00007755 out:
Eric Andersencb57d552001-06-28 07:25:16 +00007756 popstackmark(&smark);
7757}
7758
Eric Andersenc470f442003-07-28 09:56:35 +00007759/*
7760 * Kick off a subshell to evaluate a tree.
7761 */
Eric Andersenc470f442003-07-28 09:56:35 +00007762static void
7763evalsubshell(union node *n, int flags)
7764{
7765 struct job *jp;
7766 int backgnd = (n->type == NBACKGND);
7767 int status;
7768
7769 expredir(n->nredir.redirect);
7770 if (!backgnd && flags & EV_EXIT && !trap[0])
7771 goto nofork;
Denis Vlasenkob012b102007-02-19 22:43:01 +00007772 INT_OFF;
Eric Andersenc470f442003-07-28 09:56:35 +00007773 jp = makejob(n, 1);
7774 if (forkshell(jp, n, backgnd) == 0) {
Denis Vlasenkob012b102007-02-19 22:43:01 +00007775 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00007776 flags |= EV_EXIT;
7777 if (backgnd)
7778 flags &=~ EV_TESTED;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00007779 nofork:
Eric Andersenc470f442003-07-28 09:56:35 +00007780 redirect(n->nredir.redirect, 0);
7781 evaltreenr(n->nredir.n, flags);
7782 /* never returns */
7783 }
7784 status = 0;
7785 if (! backgnd)
7786 status = waitforjob(jp);
7787 exitstatus = status;
Denis Vlasenkob012b102007-02-19 22:43:01 +00007788 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00007789}
7790
Eric Andersenc470f442003-07-28 09:56:35 +00007791/*
7792 * Compute the names of the files in a redirection list.
7793 */
Denis Vlasenko99eb8502007-02-23 21:09:49 +00007794static void fixredir(union node *, const char *, int);
Eric Andersenc470f442003-07-28 09:56:35 +00007795static void
7796expredir(union node *n)
7797{
7798 union node *redir;
7799
Denis Vlasenko2da584f2007-02-19 22:44:05 +00007800 for (redir = n; redir; redir = redir->nfile.next) {
Eric Andersenc470f442003-07-28 09:56:35 +00007801 struct arglist fn;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00007802
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00007803 fn.list = NULL;
Eric Andersenc470f442003-07-28 09:56:35 +00007804 fn.lastp = &fn.list;
7805 switch (redir->type) {
7806 case NFROMTO:
7807 case NFROM:
7808 case NTO:
7809 case NCLOBBER:
7810 case NAPPEND:
7811 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
7812 redir->nfile.expfname = fn.list->text;
7813 break;
7814 case NFROMFD:
7815 case NTOFD:
7816 if (redir->ndup.vname) {
7817 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
Denis Vlasenko2da584f2007-02-19 22:44:05 +00007818 if (fn.list == NULL)
Denis Vlasenkob012b102007-02-19 22:43:01 +00007819 ash_msg_and_raise_error("redir error");
Denis Vlasenko2da584f2007-02-19 22:44:05 +00007820 fixredir(redir, fn.list->text, 1);
Eric Andersenc470f442003-07-28 09:56:35 +00007821 }
7822 break;
7823 }
7824 }
7825}
7826
Eric Andersencb57d552001-06-28 07:25:16 +00007827/*
Eric Andersencb57d552001-06-28 07:25:16 +00007828 * Evaluate a pipeline. All the processes in the pipeline are children
7829 * of the process creating the pipeline. (This differs from some versions
7830 * of the shell, which make the last process in a pipeline the parent
7831 * of all the rest.)
7832 */
Eric Andersenc470f442003-07-28 09:56:35 +00007833static void
7834evalpipe(union node *n, int flags)
Eric Andersencb57d552001-06-28 07:25:16 +00007835{
7836 struct job *jp;
7837 struct nodelist *lp;
7838 int pipelen;
7839 int prevfd;
7840 int pip[2];
7841
Eric Andersenc470f442003-07-28 09:56:35 +00007842 TRACE(("evalpipe(0x%lx) called\n", (long)n));
Eric Andersencb57d552001-06-28 07:25:16 +00007843 pipelen = 0;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00007844 for (lp = n->npipe.cmdlist; lp; lp = lp->next)
Eric Andersencb57d552001-06-28 07:25:16 +00007845 pipelen++;
Glenn L McGrath50812ff2002-08-23 13:14:48 +00007846 flags |= EV_EXIT;
Denis Vlasenkob012b102007-02-19 22:43:01 +00007847 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +00007848 jp = makejob(n, pipelen);
7849 prevfd = -1;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00007850 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
Glenn L McGrath50812ff2002-08-23 13:14:48 +00007851 prehash(lp->n);
Eric Andersencb57d552001-06-28 07:25:16 +00007852 pip[1] = -1;
7853 if (lp->next) {
7854 if (pipe(pip) < 0) {
7855 close(prevfd);
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00007856 ash_msg_and_raise_error("pipe call failed");
Eric Andersencb57d552001-06-28 07:25:16 +00007857 }
7858 }
7859 if (forkshell(jp, lp->n, n->npipe.backgnd) == 0) {
Denis Vlasenkob012b102007-02-19 22:43:01 +00007860 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00007861 if (pip[1] >= 0) {
Glenn L McGrath50812ff2002-08-23 13:14:48 +00007862 close(pip[0]);
Eric Andersencb57d552001-06-28 07:25:16 +00007863 }
Glenn L McGrath50812ff2002-08-23 13:14:48 +00007864 if (prevfd > 0) {
7865 dup2(prevfd, 0);
7866 close(prevfd);
7867 }
7868 if (pip[1] > 1) {
7869 dup2(pip[1], 1);
7870 close(pip[1]);
7871 }
Eric Andersenc470f442003-07-28 09:56:35 +00007872 evaltreenr(lp->n, flags);
7873 /* never returns */
Eric Andersencb57d552001-06-28 07:25:16 +00007874 }
7875 if (prevfd >= 0)
7876 close(prevfd);
7877 prevfd = pip[0];
7878 close(pip[1]);
7879 }
Eric Andersencb57d552001-06-28 07:25:16 +00007880 if (n->npipe.backgnd == 0) {
Eric Andersencb57d552001-06-28 07:25:16 +00007881 exitstatus = waitforjob(jp);
7882 TRACE(("evalpipe: job done exit status %d\n", exitstatus));
Eric Andersencb57d552001-06-28 07:25:16 +00007883 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00007884 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00007885}
7886
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00007887/*
7888 * Controls whether the shell is interactive or not.
7889 */
7890static void
7891setinteractive(int on)
7892{
7893 static int is_interactive;
7894
7895 if (++on == is_interactive)
7896 return;
7897 is_interactive = on;
7898 setsignal(SIGINT);
7899 setsignal(SIGQUIT);
7900 setsignal(SIGTERM);
7901#if !ENABLE_FEATURE_SH_EXTRA_QUIET
7902 if (is_interactive > 1) {
7903 /* Looks like they want an interactive shell */
Denis Vlasenkoca525b42007-06-13 12:27:17 +00007904 static smallint did_banner;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00007905
Denis Vlasenkoca525b42007-06-13 12:27:17 +00007906 if (!did_banner) {
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00007907 out1fmt(
7908 "\n\n"
Denis Vlasenkoca525b42007-06-13 12:27:17 +00007909 "%s built-in shell (ash)\n"
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00007910 "Enter 'help' for a list of built-in commands."
7911 "\n\n",
Denis Vlasenkoca525b42007-06-13 12:27:17 +00007912 bb_banner);
7913 did_banner = 1;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00007914 }
7915 }
7916#endif
7917}
7918
7919#if ENABLE_FEATURE_EDITING_VI
7920#define setvimode(on) do { \
7921 if (on) line_input_state->flags |= VI_MODE; \
7922 else line_input_state->flags &= ~VI_MODE; \
7923} while (0)
7924#else
7925#define setvimode(on) viflag = 0 /* forcibly keep the option off */
7926#endif
7927
7928static void
7929optschanged(void)
7930{
7931#if DEBUG
7932 opentrace();
7933#endif
7934 setinteractive(iflag);
7935 setjobctl(mflag);
7936 setvimode(viflag);
7937}
7938
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007939static struct localvar *localvars;
7940
7941/*
7942 * Called after a function returns.
7943 * Interrupts must be off.
7944 */
7945static void
7946poplocalvars(void)
7947{
7948 struct localvar *lvp;
7949 struct var *vp;
7950
7951 while ((lvp = localvars) != NULL) {
7952 localvars = lvp->next;
7953 vp = lvp->vp;
7954 TRACE(("poplocalvar %s", vp ? vp->text : "-"));
7955 if (vp == NULL) { /* $- saved */
7956 memcpy(optlist, lvp->text, sizeof(optlist));
7957 free((char*)lvp->text);
7958 optschanged();
7959 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
7960 unsetvar(vp->text);
7961 } else {
7962 if (vp->func)
7963 (*vp->func)(strchrnul(lvp->text, '=') + 1);
7964 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
7965 free((char*)vp->text);
7966 vp->flags = lvp->flags;
7967 vp->text = lvp->text;
7968 }
7969 free(lvp);
7970 }
7971}
7972
7973static int
7974evalfun(struct funcnode *func, int argc, char **argv, int flags)
7975{
7976 volatile struct shparam saveparam;
7977 struct localvar *volatile savelocalvars;
7978 struct jmploc *volatile savehandler;
7979 struct jmploc jmploc;
7980 int e;
7981
7982 saveparam = shellparam;
7983 savelocalvars = localvars;
7984 e = setjmp(jmploc.loc);
7985 if (e) {
7986 goto funcdone;
7987 }
7988 INT_OFF;
7989 savehandler = exception_handler;
7990 exception_handler = &jmploc;
7991 localvars = NULL;
Denis Vlasenko01631112007-12-16 17:20:38 +00007992 shellparam.malloced = 0;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007993 func->count++;
7994 funcnest++;
7995 INT_ON;
7996 shellparam.nparam = argc - 1;
7997 shellparam.p = argv + 1;
7998#if ENABLE_ASH_GETOPTS
7999 shellparam.optind = 1;
8000 shellparam.optoff = -1;
8001#endif
8002 evaltree(&func->n, flags & EV_TESTED);
Denis Vlasenko01631112007-12-16 17:20:38 +00008003 funcdone:
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008004 INT_OFF;
8005 funcnest--;
8006 freefunc(func);
8007 poplocalvars();
8008 localvars = savelocalvars;
8009 freeparam(&shellparam);
8010 shellparam = saveparam;
8011 exception_handler = savehandler;
8012 INT_ON;
8013 evalskip &= ~SKIPFUNC;
8014 return e;
8015}
8016
Denis Vlasenko131ae172007-02-18 13:00:19 +00008017#if ENABLE_ASH_CMDCMD
Denis Vlasenkoaa744452007-02-23 01:04:22 +00008018static char **
8019parse_command_args(char **argv, const char **path)
Eric Andersenc470f442003-07-28 09:56:35 +00008020{
8021 char *cp, c;
8022
8023 for (;;) {
8024 cp = *++argv;
8025 if (!cp)
8026 return 0;
8027 if (*cp++ != '-')
8028 break;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008029 c = *cp++;
8030 if (!c)
Eric Andersenc470f442003-07-28 09:56:35 +00008031 break;
8032 if (c == '-' && !*cp) {
8033 argv++;
8034 break;
8035 }
8036 do {
8037 switch (c) {
8038 case 'p':
Denis Vlasenkof5f75c52007-06-12 22:35:19 +00008039 *path = bb_default_path;
Eric Andersenc470f442003-07-28 09:56:35 +00008040 break;
8041 default:
8042 /* run 'typecmd' for other options */
8043 return 0;
8044 }
Denis Vlasenko9650f362007-02-23 01:04:37 +00008045 c = *cp++;
8046 } while (c);
Eric Andersenc470f442003-07-28 09:56:35 +00008047 }
8048 return argv;
8049}
8050#endif
8051
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008052/*
8053 * Make a variable a local variable. When a variable is made local, it's
8054 * value and flags are saved in a localvar structure. The saved values
8055 * will be restored when the shell function returns. We handle the name
8056 * "-" as a special case.
8057 */
8058static void
8059mklocal(char *name)
8060{
8061 struct localvar *lvp;
8062 struct var **vpp;
8063 struct var *vp;
8064
8065 INT_OFF;
8066 lvp = ckmalloc(sizeof(struct localvar));
8067 if (LONE_DASH(name)) {
8068 char *p;
8069 p = ckmalloc(sizeof(optlist));
8070 lvp->text = memcpy(p, optlist, sizeof(optlist));
8071 vp = NULL;
8072 } else {
8073 char *eq;
8074
8075 vpp = hashvar(name);
8076 vp = *findvar(vpp, name);
8077 eq = strchr(name, '=');
8078 if (vp == NULL) {
8079 if (eq)
8080 setvareq(name, VSTRFIXED);
8081 else
8082 setvar(name, NULL, VSTRFIXED);
8083 vp = *vpp; /* the new variable */
8084 lvp->flags = VUNSET;
8085 } else {
8086 lvp->text = vp->text;
8087 lvp->flags = vp->flags;
8088 vp->flags |= VSTRFIXED|VTEXTFIXED;
8089 if (eq)
8090 setvareq(name, 0);
8091 }
8092 }
8093 lvp->vp = vp;
8094 lvp->next = localvars;
8095 localvars = lvp;
8096 INT_ON;
8097}
8098
8099/*
8100 * The "local" command.
8101 */
8102static int
8103localcmd(int argc, char **argv)
8104{
8105 char *name;
8106
8107 argv = argptr;
8108 while ((name = *argv++) != NULL) {
8109 mklocal(name);
8110 }
8111 return 0;
8112}
8113
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008114static int
8115falsecmd(int argc, char **argv)
8116{
8117 return 1;
8118}
8119
8120static int
8121truecmd(int argc, char **argv)
8122{
8123 return 0;
8124}
8125
8126static int
8127execcmd(int argc, char **argv)
8128{
8129 if (argc > 1) {
8130 iflag = 0; /* exit on error */
8131 mflag = 0;
8132 optschanged();
8133 shellexec(argv + 1, pathval(), 0);
8134 }
8135 return 0;
8136}
8137
8138/*
8139 * The return command.
8140 */
8141static int
8142returncmd(int argc, char **argv)
8143{
8144 /*
8145 * If called outside a function, do what ksh does;
8146 * skip the rest of the file.
8147 */
8148 evalskip = funcnest ? SKIPFUNC : SKIPFILE;
8149 return argv[1] ? number(argv[1]) : exitstatus;
8150}
8151
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008152/* Forward declarations for builtintab[] */
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008153static int breakcmd(int, char **);
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008154static int dotcmd(int, char **);
8155static int evalcmd(int, char **);
8156#if ENABLE_ASH_BUILTIN_ECHO
8157static int echocmd(int, char **);
8158#endif
8159#if ENABLE_ASH_BUILTIN_TEST
8160static int testcmd(int, char **);
8161#endif
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008162static int exitcmd(int, char **);
8163static int exportcmd(int, char **);
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008164#if ENABLE_ASH_GETOPTS
8165static int getoptscmd(int, char **);
8166#endif
Denis Vlasenko52764022007-02-24 13:42:56 +00008167#if !ENABLE_FEATURE_SH_EXTRA_QUIET
8168static int helpcmd(int argc, char **argv);
8169#endif
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008170#if ENABLE_ASH_MATH_SUPPORT
8171static int letcmd(int, char **);
8172#endif
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008173static int readcmd(int, char **);
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008174static int setcmd(int, char **);
8175static int shiftcmd(int, char **);
8176static int timescmd(int, char **);
8177static int trapcmd(int, char **);
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008178static int umaskcmd(int, char **);
8179static int unsetcmd(int, char **);
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008180static int ulimitcmd(int, char **);
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008181
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008182#define BUILTIN_NOSPEC "0"
8183#define BUILTIN_SPECIAL "1"
8184#define BUILTIN_REGULAR "2"
8185#define BUILTIN_SPEC_REG "3"
8186#define BUILTIN_ASSIGN "4"
8187#define BUILTIN_SPEC_ASSG "5"
8188#define BUILTIN_REG_ASSG "6"
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008189#define BUILTIN_SPEC_REG_ASSG "7"
8190
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008191/* make sure to keep these in proper order since it is searched via bsearch() */
8192static const struct builtincmd builtintab[] = {
8193 { BUILTIN_SPEC_REG ".", dotcmd },
8194 { BUILTIN_SPEC_REG ":", truecmd },
8195#if ENABLE_ASH_BUILTIN_TEST
8196 { BUILTIN_REGULAR "[", testcmd },
8197 { BUILTIN_REGULAR "[[", testcmd },
8198#endif
8199#if ENABLE_ASH_ALIAS
8200 { BUILTIN_REG_ASSG "alias", aliascmd },
8201#endif
8202#if JOBS
8203 { BUILTIN_REGULAR "bg", fg_bgcmd },
8204#endif
8205 { BUILTIN_SPEC_REG "break", breakcmd },
8206 { BUILTIN_REGULAR "cd", cdcmd },
8207 { BUILTIN_NOSPEC "chdir", cdcmd },
8208#if ENABLE_ASH_CMDCMD
8209 { BUILTIN_REGULAR "command", commandcmd },
8210#endif
8211 { BUILTIN_SPEC_REG "continue", breakcmd },
8212#if ENABLE_ASH_BUILTIN_ECHO
8213 { BUILTIN_REGULAR "echo", echocmd },
8214#endif
8215 { BUILTIN_SPEC_REG "eval", evalcmd },
8216 { BUILTIN_SPEC_REG "exec", execcmd },
8217 { BUILTIN_SPEC_REG "exit", exitcmd },
8218 { BUILTIN_SPEC_REG_ASSG "export", exportcmd },
8219 { BUILTIN_REGULAR "false", falsecmd },
8220#if JOBS
8221 { BUILTIN_REGULAR "fg", fg_bgcmd },
8222#endif
8223#if ENABLE_ASH_GETOPTS
8224 { BUILTIN_REGULAR "getopts", getoptscmd },
8225#endif
8226 { BUILTIN_NOSPEC "hash", hashcmd },
8227#if !ENABLE_FEATURE_SH_EXTRA_QUIET
8228 { BUILTIN_NOSPEC "help", helpcmd },
8229#endif
8230#if JOBS
8231 { BUILTIN_REGULAR "jobs", jobscmd },
8232 { BUILTIN_REGULAR "kill", killcmd },
8233#endif
8234#if ENABLE_ASH_MATH_SUPPORT
8235 { BUILTIN_NOSPEC "let", letcmd },
8236#endif
8237 { BUILTIN_ASSIGN "local", localcmd },
8238 { BUILTIN_NOSPEC "pwd", pwdcmd },
8239 { BUILTIN_REGULAR "read", readcmd },
8240 { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
8241 { BUILTIN_SPEC_REG "return", returncmd },
8242 { BUILTIN_SPEC_REG "set", setcmd },
8243 { BUILTIN_SPEC_REG "shift", shiftcmd },
8244 { BUILTIN_SPEC_REG "source", dotcmd },
8245#if ENABLE_ASH_BUILTIN_TEST
8246 { BUILTIN_REGULAR "test", testcmd },
8247#endif
8248 { BUILTIN_SPEC_REG "times", timescmd },
8249 { BUILTIN_SPEC_REG "trap", trapcmd },
8250 { BUILTIN_REGULAR "true", truecmd },
8251 { BUILTIN_NOSPEC "type", typecmd },
8252 { BUILTIN_NOSPEC "ulimit", ulimitcmd },
8253 { BUILTIN_REGULAR "umask", umaskcmd },
8254#if ENABLE_ASH_ALIAS
8255 { BUILTIN_REGULAR "unalias", unaliascmd },
8256#endif
8257 { BUILTIN_SPEC_REG "unset", unsetcmd },
8258 { BUILTIN_REGULAR "wait", waitcmd },
8259};
8260
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008261
8262#define COMMANDCMD (builtintab + 5 + \
8263 2 * ENABLE_ASH_BUILTIN_TEST + \
8264 ENABLE_ASH_ALIAS + \
8265 ENABLE_ASH_JOB_CONTROL)
8266#define EXECCMD (builtintab + 7 + \
8267 2 * ENABLE_ASH_BUILTIN_TEST + \
8268 ENABLE_ASH_ALIAS + \
8269 ENABLE_ASH_JOB_CONTROL + \
8270 ENABLE_ASH_CMDCMD + \
8271 ENABLE_ASH_BUILTIN_ECHO)
8272
8273/*
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008274 * Search the table of builtin commands.
8275 */
8276static struct builtincmd *
8277find_builtin(const char *name)
8278{
8279 struct builtincmd *bp;
8280
8281 bp = bsearch(
Denis Vlasenko80b8b392007-06-25 10:55:35 +00008282 name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008283 pstrcmp
8284 );
8285 return bp;
8286}
8287
8288/*
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008289 * Execute a simple command.
8290 */
8291static int back_exitstatus; /* exit status of backquoted command */
8292static int
8293isassignment(const char *p)
Paul Foxc3850c82005-07-20 18:23:39 +00008294{
8295 const char *q = endofname(p);
8296 if (p == q)
8297 return 0;
8298 return *q == '=';
8299}
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008300static int
8301bltincmd(int argc, char **argv)
8302{
8303 /* Preserve exitstatus of a previous possible redirection
8304 * as POSIX mandates */
8305 return back_exitstatus;
8306}
Eric Andersenc470f442003-07-28 09:56:35 +00008307static void
8308evalcommand(union node *cmd, int flags)
8309{
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00008310 static const struct builtincmd null_bltin = {
8311 "\0\0", bltincmd /* why three NULs? */
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008312 };
Eric Andersenc470f442003-07-28 09:56:35 +00008313 struct stackmark smark;
8314 union node *argp;
8315 struct arglist arglist;
8316 struct arglist varlist;
8317 char **argv;
8318 int argc;
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00008319 const struct strlist *sp;
Eric Andersenc470f442003-07-28 09:56:35 +00008320 struct cmdentry cmdentry;
8321 struct job *jp;
8322 char *lastarg;
8323 const char *path;
8324 int spclbltin;
8325 int cmd_is_exec;
8326 int status;
8327 char **nargv;
Paul Foxc3850c82005-07-20 18:23:39 +00008328 struct builtincmd *bcmd;
8329 int pseudovarflag = 0;
Eric Andersenc470f442003-07-28 09:56:35 +00008330
8331 /* First expand the arguments. */
8332 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
8333 setstackmark(&smark);
8334 back_exitstatus = 0;
8335
8336 cmdentry.cmdtype = CMDBUILTIN;
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00008337 cmdentry.u.cmd = &null_bltin;
Eric Andersenc470f442003-07-28 09:56:35 +00008338 varlist.lastp = &varlist.list;
8339 *varlist.lastp = NULL;
8340 arglist.lastp = &arglist.list;
8341 *arglist.lastp = NULL;
8342
8343 argc = 0;
Denis Vlasenkob012b102007-02-19 22:43:01 +00008344 if (cmd->ncmd.args) {
Paul Foxc3850c82005-07-20 18:23:39 +00008345 bcmd = find_builtin(cmd->ncmd.args->narg.text);
8346 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
8347 }
8348
Eric Andersenc470f442003-07-28 09:56:35 +00008349 for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
8350 struct strlist **spp;
8351
8352 spp = arglist.lastp;
"Vladimir N. Oleynik"bef14d72005-09-05 13:25:11 +00008353 if (pseudovarflag && isassignment(argp->narg.text))
Paul Foxc3850c82005-07-20 18:23:39 +00008354 expandarg(argp, &arglist, EXP_VARTILDE);
8355 else
8356 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
8357
Eric Andersenc470f442003-07-28 09:56:35 +00008358 for (sp = *spp; sp; sp = sp->next)
8359 argc++;
8360 }
8361
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +00008362 argv = nargv = stalloc(sizeof(char *) * (argc + 1));
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008363 for (sp = arglist.list; sp; sp = sp->next) {
Eric Andersenc470f442003-07-28 09:56:35 +00008364 TRACE(("evalcommand arg: %s\n", sp->text));
8365 *nargv++ = sp->text;
8366 }
8367 *nargv = NULL;
8368
8369 lastarg = NULL;
8370 if (iflag && funcnest == 0 && argc > 0)
8371 lastarg = nargv[-1];
8372
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00008373 preverrout_fd = 2;
Eric Andersenc470f442003-07-28 09:56:35 +00008374 expredir(cmd->ncmd.redirect);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008375 status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
Eric Andersenc470f442003-07-28 09:56:35 +00008376
8377 path = vpath.text;
8378 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
8379 struct strlist **spp;
8380 char *p;
8381
8382 spp = varlist.lastp;
8383 expandarg(argp, &varlist, EXP_VARTILDE);
8384
8385 /*
8386 * Modify the command lookup path, if a PATH= assignment
8387 * is present
8388 */
8389 p = (*spp)->text;
8390 if (varequal(p, path))
8391 path = p;
8392 }
8393
8394 /* Print the command if xflag is set. */
8395 if (xflag) {
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00008396 int n;
8397 const char *p = " %s";
Eric Andersenc470f442003-07-28 09:56:35 +00008398
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00008399 p++;
Denis Vlasenko0de37e12007-10-17 11:08:53 +00008400 fdprintf(preverrout_fd, p, expandstr(ps4val()));
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00008401
8402 sp = varlist.list;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +00008403 for (n = 0; n < 2; n++) {
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00008404 while (sp) {
Denis Vlasenko0de37e12007-10-17 11:08:53 +00008405 fdprintf(preverrout_fd, p, sp->text);
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00008406 sp = sp->next;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +00008407 if (*p == '%') {
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00008408 p--;
8409 }
8410 }
8411 sp = arglist.list;
8412 }
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00008413 safe_write(preverrout_fd, "\n", 1);
Eric Andersenc470f442003-07-28 09:56:35 +00008414 }
8415
8416 cmd_is_exec = 0;
8417 spclbltin = -1;
8418
8419 /* Now locate the command. */
8420 if (argc) {
8421 const char *oldpath;
8422 int cmd_flag = DO_ERR;
8423
8424 path += 5;
8425 oldpath = path;
8426 for (;;) {
8427 find_command(argv[0], &cmdentry, cmd_flag, path);
8428 if (cmdentry.cmdtype == CMDUNKNOWN) {
8429 status = 127;
Denis Vlasenkob012b102007-02-19 22:43:01 +00008430 flush_stderr();
Eric Andersenc470f442003-07-28 09:56:35 +00008431 goto bail;
8432 }
8433
8434 /* implement bltin and command here */
8435 if (cmdentry.cmdtype != CMDBUILTIN)
8436 break;
8437 if (spclbltin < 0)
8438 spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
8439 if (cmdentry.u.cmd == EXECCMD)
8440 cmd_is_exec++;
Denis Vlasenko131ae172007-02-18 13:00:19 +00008441#if ENABLE_ASH_CMDCMD
Eric Andersenc470f442003-07-28 09:56:35 +00008442 if (cmdentry.u.cmd == COMMANDCMD) {
Eric Andersenc470f442003-07-28 09:56:35 +00008443 path = oldpath;
8444 nargv = parse_command_args(argv, &path);
8445 if (!nargv)
8446 break;
8447 argc -= nargv - argv;
8448 argv = nargv;
8449 cmd_flag |= DO_NOFUNC;
8450 } else
8451#endif
8452 break;
8453 }
8454 }
8455
8456 if (status) {
8457 /* We have a redirection error. */
8458 if (spclbltin > 0)
Denis Vlasenkob012b102007-02-19 22:43:01 +00008459 raise_exception(EXERROR);
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008460 bail:
Eric Andersenc470f442003-07-28 09:56:35 +00008461 exitstatus = status;
8462 goto out;
8463 }
8464
8465 /* Execute the command. */
8466 switch (cmdentry.cmdtype) {
8467 default:
8468 /* Fork off a child process if necessary. */
8469 if (!(flags & EV_EXIT) || trap[0]) {
Denis Vlasenkob012b102007-02-19 22:43:01 +00008470 INT_OFF;
Eric Andersenc470f442003-07-28 09:56:35 +00008471 jp = makejob(cmd, 1);
8472 if (forkshell(jp, cmd, FORK_FG) != 0) {
8473 exitstatus = waitforjob(jp);
Denis Vlasenkob012b102007-02-19 22:43:01 +00008474 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00008475 break;
8476 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00008477 FORCE_INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00008478 }
8479 listsetvar(varlist.list, VEXPORT|VSTACK);
8480 shellexec(argv, path, cmdentry.u.index);
8481 /* NOTREACHED */
8482
8483 case CMDBUILTIN:
8484 cmdenviron = varlist.list;
8485 if (cmdenviron) {
8486 struct strlist *list = cmdenviron;
8487 int i = VNOSET;
8488 if (spclbltin > 0 || argc == 0) {
8489 i = 0;
8490 if (cmd_is_exec && argc > 1)
8491 i = VEXPORT;
8492 }
8493 listsetvar(list, i);
8494 }
8495 if (evalbltin(cmdentry.u.cmd, argc, argv)) {
8496 int exit_status;
Denis Vlasenko991a1da2008-02-10 19:02:53 +00008497 int i = exception;
Eric Andersenc470f442003-07-28 09:56:35 +00008498 if (i == EXEXIT)
8499 goto raise;
Eric Andersenc470f442003-07-28 09:56:35 +00008500 exit_status = 2;
Eric Andersenc470f442003-07-28 09:56:35 +00008501 if (i == EXINT)
Denis Vlasenko991a1da2008-02-10 19:02:53 +00008502 exit_status = 128 + SIGINT;
Eric Andersenc470f442003-07-28 09:56:35 +00008503 if (i == EXSIG)
Denis Vlasenko991a1da2008-02-10 19:02:53 +00008504 exit_status = 128 + pendingsig;
Eric Andersenc470f442003-07-28 09:56:35 +00008505 exitstatus = exit_status;
Eric Andersenc470f442003-07-28 09:56:35 +00008506 if (i == EXINT || spclbltin > 0) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008507 raise:
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008508 longjmp(exception_handler->loc, 1);
Eric Andersenc470f442003-07-28 09:56:35 +00008509 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00008510 FORCE_INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00008511 }
8512 break;
8513
8514 case CMDFUNCTION:
8515 listsetvar(varlist.list, 0);
8516 if (evalfun(cmdentry.u.func, argc, argv, flags))
8517 goto raise;
8518 break;
8519 }
8520
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008521 out:
Eric Andersenc470f442003-07-28 09:56:35 +00008522 popredir(cmd_is_exec);
8523 if (lastarg)
8524 /* dsl: I think this is intended to be used to support
8525 * '_' in 'vi' command mode during line editing...
8526 * However I implemented that within libedit itself.
8527 */
8528 setvar("_", lastarg, 0);
8529 popstackmark(&smark);
8530}
8531
8532static int
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008533evalbltin(const struct builtincmd *cmd, int argc, char **argv)
8534{
Eric Andersenc470f442003-07-28 09:56:35 +00008535 char *volatile savecmdname;
8536 struct jmploc *volatile savehandler;
8537 struct jmploc jmploc;
8538 int i;
8539
8540 savecmdname = commandname;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008541 i = setjmp(jmploc.loc);
8542 if (i)
Eric Andersenc470f442003-07-28 09:56:35 +00008543 goto cmddone;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008544 savehandler = exception_handler;
8545 exception_handler = &jmploc;
Eric Andersenc470f442003-07-28 09:56:35 +00008546 commandname = argv[0];
8547 argptr = argv + 1;
8548 optptr = NULL; /* initialize nextopt */
8549 exitstatus = (*cmd->builtin)(argc, argv);
Denis Vlasenkob012b102007-02-19 22:43:01 +00008550 flush_stdout_stderr();
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008551 cmddone:
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00008552 exitstatus |= ferror(stdout);
Rob Landleyf296f0b2006-07-06 01:09:21 +00008553 clearerr(stdout);
Eric Andersenc470f442003-07-28 09:56:35 +00008554 commandname = savecmdname;
Denis Vlasenko991a1da2008-02-10 19:02:53 +00008555// exsig = 0;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008556 exception_handler = savehandler;
Eric Andersenc470f442003-07-28 09:56:35 +00008557
8558 return i;
8559}
8560
Denis Vlasenkoaa744452007-02-23 01:04:22 +00008561static int
8562goodname(const char *p)
Glenn L McGrath16e45d72004-02-04 08:24:39 +00008563{
8564 return !*endofname(p);
8565}
8566
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008567
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008568/*
8569 * Search for a command. This is called before we fork so that the
8570 * location of the command will be available in the parent as well as
Glenn L McGrath16e45d72004-02-04 08:24:39 +00008571 * the child. The check for "goodname" is an overly conservative
8572 * check that the name will not be subject to expansion.
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008573 */
Eric Andersenc470f442003-07-28 09:56:35 +00008574static void
8575prehash(union node *n)
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008576{
8577 struct cmdentry entry;
8578
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +00008579 if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
8580 find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008581}
8582
Eric Andersencb57d552001-06-28 07:25:16 +00008583
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008584/* ============ Builtin commands
8585 *
8586 * Builtin commands whose functions are closely tied to evaluation
8587 * are implemented here.
Eric Andersencb57d552001-06-28 07:25:16 +00008588 */
8589
8590/*
Eric Andersencb57d552001-06-28 07:25:16 +00008591 * Handle break and continue commands. Break, continue, and return are
8592 * all handled by setting the evalskip flag. The evaluation routines
8593 * above all check this flag, and if it is set they start skipping
8594 * commands rather than executing them. The variable skipcount is
8595 * the number of loops to break/continue, or the number of function
8596 * levels to return. (The latter is always 1.) It should probably
8597 * be an error to break out of more loops than exist, but it isn't
8598 * in the standard shell so we don't make it one here.
8599 */
Eric Andersenc470f442003-07-28 09:56:35 +00008600static int
8601breakcmd(int argc, char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +00008602{
8603 int n = argc > 1 ? number(argv[1]) : 1;
8604
Aaron Lehmann2aef3a62001-12-31 06:03:12 +00008605 if (n <= 0)
Denis Vlasenkob012b102007-02-19 22:43:01 +00008606 ash_msg_and_raise_error(illnum, argv[1]);
Eric Andersencb57d552001-06-28 07:25:16 +00008607 if (n > loopnest)
8608 n = loopnest;
8609 if (n > 0) {
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008610 evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
Eric Andersencb57d552001-06-28 07:25:16 +00008611 skipcount = n;
8612 }
8613 return 0;
8614}
8615
Eric Andersenc470f442003-07-28 09:56:35 +00008616
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008617/* ============ input.c
8618 *
Eric Andersen90898442003-08-06 11:20:52 +00008619 * This implements the input routines used by the parser.
Eric Andersencb57d552001-06-28 07:25:16 +00008620 */
Denis Vlasenko99eb8502007-02-23 21:09:49 +00008621
Eric Andersenc470f442003-07-28 09:56:35 +00008622#define EOF_NLEFT -99 /* value of parsenleft when EOF pushed back */
Eric Andersencb57d552001-06-28 07:25:16 +00008623
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008624enum {
8625 INPUT_PUSH_FILE = 1,
8626 INPUT_NOFILE_OK = 2,
8627};
Eric Andersencb57d552001-06-28 07:25:16 +00008628
Denis Vlasenko99eb8502007-02-23 21:09:49 +00008629static int plinno = 1; /* input line number */
8630/* number of characters left in input buffer */
8631static int parsenleft; /* copy of parsefile->nleft */
8632static int parselleft; /* copy of parsefile->lleft */
8633/* next character in input buffer */
8634static char *parsenextc; /* copy of parsefile->nextc */
8635
8636static int checkkwd;
8637/* values of checkkwd variable */
8638#define CHKALIAS 0x1
8639#define CHKKWD 0x2
8640#define CHKNL 0x4
8641
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008642static void
8643popstring(void)
Eric Andersenc470f442003-07-28 09:56:35 +00008644{
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008645 struct strpush *sp = parsefile->strpush;
Eric Andersenc470f442003-07-28 09:56:35 +00008646
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008647 INT_OFF;
Denis Vlasenko131ae172007-02-18 13:00:19 +00008648#if ENABLE_ASH_ALIAS
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008649 if (sp->ap) {
8650 if (parsenextc[-1] == ' ' || parsenextc[-1] == '\t') {
8651 checkkwd |= CHKALIAS;
Glenn L McGrath28939ad2004-07-21 10:20:19 +00008652 }
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008653 if (sp->string != sp->ap->val) {
8654 free(sp->string);
8655 }
8656 sp->ap->flag &= ~ALIASINUSE;
8657 if (sp->ap->flag & ALIASDEAD) {
8658 unalias(sp->ap->name);
8659 }
Glenn L McGrath28939ad2004-07-21 10:20:19 +00008660 }
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00008661#endif
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008662 parsenextc = sp->prevstring;
8663 parsenleft = sp->prevnleft;
8664/*dprintf("*** calling popstring: restoring to '%s'\n", parsenextc);*/
8665 parsefile->strpush = sp->prev;
8666 if (sp != &(parsefile->basestrpush))
8667 free(sp);
8668 INT_ON;
8669}
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00008670
Denis Vlasenkoaa744452007-02-23 01:04:22 +00008671static int
8672preadfd(void)
Eric Andersencb57d552001-06-28 07:25:16 +00008673{
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00008674 int nr;
Eric Andersenc470f442003-07-28 09:56:35 +00008675 char *buf = parsefile->buf;
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00008676 parsenextc = buf;
8677
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008678 retry:
Denis Vlasenko38f63192007-01-22 09:03:07 +00008679#if ENABLE_FEATURE_EDITING
Eric Andersenc470f442003-07-28 09:56:35 +00008680 if (!iflag || parsefile->fd)
8681 nr = safe_read(parsefile->fd, buf, BUFSIZ - 1);
8682 else {
Denis Vlasenko38f63192007-01-22 09:03:07 +00008683#if ENABLE_FEATURE_TAB_COMPLETION
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00008684 line_input_state->path_lookup = pathval();
Eric Andersen4a79c0e2004-09-08 10:01:07 +00008685#endif
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00008686 nr = read_line_input(cmdedit_prompt, buf, BUFSIZ, line_input_state);
8687 if (nr == 0) {
8688 /* Ctrl+C pressed */
8689 if (trap[SIGINT]) {
Glenn L McGrath16e45d72004-02-04 08:24:39 +00008690 buf[0] = '\n';
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00008691 buf[1] = '\0';
Glenn L McGrath16e45d72004-02-04 08:24:39 +00008692 raise(SIGINT);
8693 return 1;
8694 }
Eric Andersenc470f442003-07-28 09:56:35 +00008695 goto retry;
8696 }
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00008697 if (nr < 0 && errno == 0) {
Denis Vlasenko9cb220b2007-12-09 10:03:28 +00008698 /* Ctrl+D pressed */
Eric Andersenc470f442003-07-28 09:56:35 +00008699 nr = 0;
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00008700 }
Eric Andersencb57d552001-06-28 07:25:16 +00008701 }
8702#else
Eric Andersen7467c8d2001-07-12 20:26:32 +00008703 nr = safe_read(parsefile->fd, buf, BUFSIZ - 1);
Eric Andersencb57d552001-06-28 07:25:16 +00008704#endif
8705
8706 if (nr < 0) {
Eric Andersencb57d552001-06-28 07:25:16 +00008707 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
Denis Vlasenkod37f2222007-08-19 13:42:08 +00008708 int flags = fcntl(0, F_GETFL);
Denis Vlasenko9cb220b2007-12-09 10:03:28 +00008709 if (flags >= 0 && (flags & O_NONBLOCK)) {
8710 flags &= ~O_NONBLOCK;
Eric Andersencb57d552001-06-28 07:25:16 +00008711 if (fcntl(0, F_SETFL, flags) >= 0) {
8712 out2str("sh: turning off NDELAY mode\n");
8713 goto retry;
8714 }
8715 }
8716 }
8717 }
8718 return nr;
8719}
8720
8721/*
8722 * Refill the input buffer and return the next input character:
8723 *
8724 * 1) If a string was pushed back on the input, pop it;
8725 * 2) If an EOF was pushed back (parsenleft == EOF_NLEFT) or we are reading
8726 * from a string so we can't refill the buffer, return EOF.
8727 * 3) If the is more stuff in this buffer, use it else call read to fill it.
8728 * 4) Process input up to the next newline, deleting nul characters.
8729 */
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008730static int
Eric Andersenc470f442003-07-28 09:56:35 +00008731preadbuffer(void)
Eric Andersencb57d552001-06-28 07:25:16 +00008732{
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00008733 char *q;
Eric Andersencb57d552001-06-28 07:25:16 +00008734 int more;
8735 char savec;
8736
8737 while (parsefile->strpush) {
Denis Vlasenko131ae172007-02-18 13:00:19 +00008738#if ENABLE_ASH_ALIAS
Eric Andersen2870d962001-07-02 17:27:21 +00008739 if (parsenleft == -1 && parsefile->strpush->ap &&
8740 parsenextc[-1] != ' ' && parsenextc[-1] != '\t') {
Eric Andersencb57d552001-06-28 07:25:16 +00008741 return PEOA;
8742 }
Eric Andersen2870d962001-07-02 17:27:21 +00008743#endif
Eric Andersencb57d552001-06-28 07:25:16 +00008744 popstring();
8745 if (--parsenleft >= 0)
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00008746 return signed_char2int(*parsenextc++);
Eric Andersencb57d552001-06-28 07:25:16 +00008747 }
8748 if (parsenleft == EOF_NLEFT || parsefile->buf == NULL)
8749 return PEOF;
Denis Vlasenkob012b102007-02-19 22:43:01 +00008750 flush_stdout_stderr();
Eric Andersencb57d552001-06-28 07:25:16 +00008751
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00008752 more = parselleft;
8753 if (more <= 0) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008754 again:
8755 more = preadfd();
8756 if (more <= 0) {
Eric Andersencb57d552001-06-28 07:25:16 +00008757 parselleft = parsenleft = EOF_NLEFT;
8758 return PEOF;
8759 }
8760 }
8761
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00008762 q = parsenextc;
Eric Andersencb57d552001-06-28 07:25:16 +00008763
8764 /* delete nul characters */
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00008765 for (;;) {
8766 int c;
Eric Andersencb57d552001-06-28 07:25:16 +00008767
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00008768 more--;
8769 c = *q;
Eric Andersenc470f442003-07-28 09:56:35 +00008770
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00008771 if (!c)
8772 memmove(q, q + 1, more);
8773 else {
8774 q++;
8775 if (c == '\n') {
8776 parsenleft = q - parsenextc - 1;
8777 break;
8778 }
Eric Andersencb57d552001-06-28 07:25:16 +00008779 }
8780
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00008781 if (more <= 0) {
Eric Andersencb57d552001-06-28 07:25:16 +00008782 parsenleft = q - parsenextc - 1;
8783 if (parsenleft < 0)
8784 goto again;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00008785 break;
Eric Andersencb57d552001-06-28 07:25:16 +00008786 }
8787 }
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00008788 parselleft = more;
Eric Andersencb57d552001-06-28 07:25:16 +00008789
8790 savec = *q;
8791 *q = '\0';
8792
8793 if (vflag) {
8794 out2str(parsenextc);
Eric Andersencb57d552001-06-28 07:25:16 +00008795 }
8796
8797 *q = savec;
8798
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00008799 return signed_char2int(*parsenextc++);
Eric Andersencb57d552001-06-28 07:25:16 +00008800}
8801
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00008802#define pgetc_as_macro() (--parsenleft >= 0? signed_char2int(*parsenextc++) : preadbuffer())
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008803static int
8804pgetc(void)
8805{
8806 return pgetc_as_macro();
8807}
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00008808
8809#if ENABLE_ASH_OPTIMIZE_FOR_SIZE
8810#define pgetc_macro() pgetc()
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008811#else
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00008812#define pgetc_macro() pgetc_as_macro()
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008813#endif
8814
8815/*
8816 * Same as pgetc(), but ignores PEOA.
8817 */
8818#if ENABLE_ASH_ALIAS
8819static int
8820pgetc2(void)
8821{
8822 int c;
8823
8824 do {
8825 c = pgetc_macro();
8826 } while (c == PEOA);
8827 return c;
8828}
8829#else
8830static int
8831pgetc2(void)
8832{
8833 return pgetc_macro();
8834}
8835#endif
8836
8837/*
8838 * Read a line from the script.
8839 */
8840static char *
8841pfgets(char *line, int len)
8842{
8843 char *p = line;
8844 int nleft = len;
8845 int c;
8846
8847 while (--nleft > 0) {
8848 c = pgetc2();
8849 if (c == PEOF) {
8850 if (p == line)
8851 return NULL;
8852 break;
8853 }
8854 *p++ = c;
8855 if (c == '\n')
8856 break;
8857 }
8858 *p = '\0';
8859 return line;
8860}
8861
Eric Andersenc470f442003-07-28 09:56:35 +00008862/*
8863 * Undo the last call to pgetc. Only one character may be pushed back.
8864 * PEOF may be pushed back.
8865 */
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008866static void
Eric Andersenc470f442003-07-28 09:56:35 +00008867pungetc(void)
8868{
8869 parsenleft++;
8870 parsenextc--;
8871}
Eric Andersencb57d552001-06-28 07:25:16 +00008872
8873/*
8874 * Push a string back onto the input at this current parsefile level.
8875 * We handle aliases this way.
8876 */
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008877static void
Eric Andersenc470f442003-07-28 09:56:35 +00008878pushstring(char *s, void *ap)
Eric Andersen2870d962001-07-02 17:27:21 +00008879{
Eric Andersencb57d552001-06-28 07:25:16 +00008880 struct strpush *sp;
Eric Andersenc470f442003-07-28 09:56:35 +00008881 size_t len;
Eric Andersencb57d552001-06-28 07:25:16 +00008882
Eric Andersenc470f442003-07-28 09:56:35 +00008883 len = strlen(s);
Denis Vlasenkob012b102007-02-19 22:43:01 +00008884 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +00008885/*dprintf("*** calling pushstring: %s, %d\n", s, len);*/
8886 if (parsefile->strpush) {
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +00008887 sp = ckmalloc(sizeof(struct strpush));
Eric Andersencb57d552001-06-28 07:25:16 +00008888 sp->prev = parsefile->strpush;
8889 parsefile->strpush = sp;
8890 } else
8891 sp = parsefile->strpush = &(parsefile->basestrpush);
8892 sp->prevstring = parsenextc;
8893 sp->prevnleft = parsenleft;
Denis Vlasenko131ae172007-02-18 13:00:19 +00008894#if ENABLE_ASH_ALIAS
Eric Andersenc470f442003-07-28 09:56:35 +00008895 sp->ap = (struct alias *)ap;
Eric Andersencb57d552001-06-28 07:25:16 +00008896 if (ap) {
Eric Andersenc470f442003-07-28 09:56:35 +00008897 ((struct alias *)ap)->flag |= ALIASINUSE;
Eric Andersencb57d552001-06-28 07:25:16 +00008898 sp->string = s;
8899 }
Eric Andersen2870d962001-07-02 17:27:21 +00008900#endif
Eric Andersencb57d552001-06-28 07:25:16 +00008901 parsenextc = s;
8902 parsenleft = len;
Denis Vlasenkob012b102007-02-19 22:43:01 +00008903 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00008904}
8905
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008906/*
8907 * To handle the "." command, a stack of input files is used. Pushfile
8908 * adds a new entry to the stack and popfile restores the previous level.
8909 */
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008910static void
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008911pushfile(void)
Eric Andersenc470f442003-07-28 09:56:35 +00008912{
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008913 struct parsefile *pf;
8914
8915 parsefile->nleft = parsenleft;
8916 parsefile->lleft = parselleft;
8917 parsefile->nextc = parsenextc;
8918 parsefile->linno = plinno;
Denis Vlasenko597906c2008-02-20 16:38:54 +00008919 pf = ckzalloc(sizeof(*pf));
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008920 pf->prev = parsefile;
8921 pf->fd = -1;
Denis Vlasenko597906c2008-02-20 16:38:54 +00008922 /*pf->strpush = NULL; - ckzalloc did it */
8923 /*pf->basestrpush.prev = NULL;*/
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008924 parsefile = pf;
8925}
8926
8927static void
8928popfile(void)
8929{
8930 struct parsefile *pf = parsefile;
Eric Andersenc470f442003-07-28 09:56:35 +00008931
Denis Vlasenkob012b102007-02-19 22:43:01 +00008932 INT_OFF;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008933 if (pf->fd >= 0)
8934 close(pf->fd);
Denis Vlasenko60818682007-09-28 22:07:23 +00008935 free(pf->buf);
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008936 while (pf->strpush)
8937 popstring();
8938 parsefile = pf->prev;
8939 free(pf);
8940 parsenleft = parsefile->nleft;
8941 parselleft = parsefile->lleft;
8942 parsenextc = parsefile->nextc;
8943 plinno = parsefile->linno;
Denis Vlasenkob012b102007-02-19 22:43:01 +00008944 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00008945}
8946
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008947/*
8948 * Return to top level.
8949 */
8950static void
8951popallfiles(void)
8952{
8953 while (parsefile != &basepf)
8954 popfile();
8955}
8956
8957/*
8958 * Close the file(s) that the shell is reading commands from. Called
8959 * after a fork is done.
8960 */
8961static void
8962closescript(void)
8963{
8964 popallfiles();
8965 if (parsefile->fd > 0) {
8966 close(parsefile->fd);
8967 parsefile->fd = 0;
8968 }
8969}
8970
8971/*
8972 * Like setinputfile, but takes an open file descriptor. Call this with
8973 * interrupts off.
8974 */
8975static void
8976setinputfd(int fd, int push)
8977{
Denis Vlasenko96e1b382007-09-30 23:50:48 +00008978 close_on_exec_on(fd);
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008979 if (push) {
8980 pushfile();
8981 parsefile->buf = 0;
8982 }
8983 parsefile->fd = fd;
8984 if (parsefile->buf == NULL)
8985 parsefile->buf = ckmalloc(IBUFSIZ);
8986 parselleft = parsenleft = 0;
8987 plinno = 1;
8988}
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008989
Eric Andersenc470f442003-07-28 09:56:35 +00008990/*
8991 * Set the input to take input from a file. If push is set, push the
8992 * old input onto the stack first.
8993 */
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00008994static int
8995setinputfile(const char *fname, int flags)
Eric Andersenc470f442003-07-28 09:56:35 +00008996{
8997 int fd;
8998 int fd2;
8999
Denis Vlasenkob012b102007-02-19 22:43:01 +00009000 INT_OFF;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009001 fd = open(fname, O_RDONLY);
9002 if (fd < 0) {
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009003 if (flags & INPUT_NOFILE_OK)
9004 goto out;
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00009005 ash_msg_and_raise_error("can't open %s", fname);
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009006 }
Eric Andersenc470f442003-07-28 09:56:35 +00009007 if (fd < 10) {
9008 fd2 = copyfd(fd, 10);
9009 close(fd);
9010 if (fd2 < 0)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00009011 ash_msg_and_raise_error("out of file descriptors");
Eric Andersenc470f442003-07-28 09:56:35 +00009012 fd = fd2;
9013 }
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009014 setinputfd(fd, flags & INPUT_PUSH_FILE);
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009015 out:
Denis Vlasenkob012b102007-02-19 22:43:01 +00009016 INT_ON;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009017 return fd;
Eric Andersenc470f442003-07-28 09:56:35 +00009018}
9019
Eric Andersencb57d552001-06-28 07:25:16 +00009020/*
9021 * Like setinputfile, but takes input from a string.
9022 */
Eric Andersenc470f442003-07-28 09:56:35 +00009023static void
9024setinputstring(char *string)
Eric Andersen62483552001-07-10 06:09:16 +00009025{
Denis Vlasenkob012b102007-02-19 22:43:01 +00009026 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +00009027 pushfile();
9028 parsenextc = string;
9029 parsenleft = strlen(string);
9030 parsefile->buf = NULL;
9031 plinno = 1;
Denis Vlasenkob012b102007-02-19 22:43:01 +00009032 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00009033}
9034
9035
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00009036/* ============ mail.c
9037 *
9038 * Routines to check for mail.
Eric Andersencb57d552001-06-28 07:25:16 +00009039 */
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00009040
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00009041#if ENABLE_ASH_MAIL
Eric Andersencb57d552001-06-28 07:25:16 +00009042
Eric Andersencb57d552001-06-28 07:25:16 +00009043#define MAXMBOXES 10
9044
Eric Andersenc470f442003-07-28 09:56:35 +00009045/* times of mailboxes */
9046static time_t mailtime[MAXMBOXES];
9047/* Set if MAIL or MAILPATH is changed. */
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +00009048static smallint mail_var_path_changed;
Eric Andersencb57d552001-06-28 07:25:16 +00009049
Eric Andersencb57d552001-06-28 07:25:16 +00009050/*
Eric Andersenc470f442003-07-28 09:56:35 +00009051 * Print appropriate message(s) if mail has arrived.
9052 * If mail_var_path_changed is set,
9053 * then the value of MAIL has mail_var_path_changed,
9054 * so we just update the values.
Eric Andersencb57d552001-06-28 07:25:16 +00009055 */
Eric Andersenc470f442003-07-28 09:56:35 +00009056static void
9057chkmail(void)
Eric Andersencb57d552001-06-28 07:25:16 +00009058{
Eric Andersencb57d552001-06-28 07:25:16 +00009059 const char *mpath;
9060 char *p;
9061 char *q;
Eric Andersenc470f442003-07-28 09:56:35 +00009062 time_t *mtp;
Eric Andersencb57d552001-06-28 07:25:16 +00009063 struct stackmark smark;
9064 struct stat statb;
9065
Eric Andersencb57d552001-06-28 07:25:16 +00009066 setstackmark(&smark);
Eric Andersenc470f442003-07-28 09:56:35 +00009067 mpath = mpathset() ? mpathval() : mailval();
9068 for (mtp = mailtime; mtp < mailtime + MAXMBOXES; mtp++) {
Eric Andersencb57d552001-06-28 07:25:16 +00009069 p = padvance(&mpath, nullstr);
9070 if (p == NULL)
9071 break;
9072 if (*p == '\0')
9073 continue;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00009074 for (q = p; *q; q++);
Denis Vlasenkoa7189f02006-11-17 20:29:00 +00009075#if DEBUG
Eric Andersencb57d552001-06-28 07:25:16 +00009076 if (q[-1] != '/')
9077 abort();
9078#endif
Eric Andersenc470f442003-07-28 09:56:35 +00009079 q[-1] = '\0'; /* delete trailing '/' */
9080 if (stat(p, &statb) < 0) {
9081 *mtp = 0;
9082 continue;
Eric Andersencb57d552001-06-28 07:25:16 +00009083 }
Eric Andersenc470f442003-07-28 09:56:35 +00009084 if (!mail_var_path_changed && statb.st_mtime != *mtp) {
9085 fprintf(
9086 stderr, snlfmt,
9087 pathopt ? pathopt : "you have mail"
9088 );
9089 }
9090 *mtp = statb.st_mtime;
Eric Andersencb57d552001-06-28 07:25:16 +00009091 }
Eric Andersenc470f442003-07-28 09:56:35 +00009092 mail_var_path_changed = 0;
Eric Andersencb57d552001-06-28 07:25:16 +00009093 popstackmark(&smark);
9094}
Eric Andersencb57d552001-06-28 07:25:16 +00009095
Eric Andersenc470f442003-07-28 09:56:35 +00009096static void
9097changemail(const char *val)
9098{
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +00009099 mail_var_path_changed = 1;
Eric Andersenc470f442003-07-28 09:56:35 +00009100}
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00009101
Denis Vlasenko131ae172007-02-18 13:00:19 +00009102#endif /* ASH_MAIL */
Eric Andersenc470f442003-07-28 09:56:35 +00009103
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00009104
9105/* ============ ??? */
9106
Eric Andersencb57d552001-06-28 07:25:16 +00009107/*
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009108 * Set the shell parameters.
Eric Andersencb57d552001-06-28 07:25:16 +00009109 */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009110static void
9111setparam(char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +00009112{
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009113 char **newparam;
9114 char **ap;
9115 int nparam;
Eric Andersencb57d552001-06-28 07:25:16 +00009116
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009117 for (nparam = 0; argv[nparam]; nparam++);
9118 ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
9119 while (*argv) {
9120 *ap++ = ckstrdup(*argv++);
Eric Andersencb57d552001-06-28 07:25:16 +00009121 }
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009122 *ap = NULL;
9123 freeparam(&shellparam);
Denis Vlasenko01631112007-12-16 17:20:38 +00009124 shellparam.malloced = 1;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009125 shellparam.nparam = nparam;
9126 shellparam.p = newparam;
9127#if ENABLE_ASH_GETOPTS
9128 shellparam.optind = 1;
9129 shellparam.optoff = -1;
9130#endif
Eric Andersencb57d552001-06-28 07:25:16 +00009131}
9132
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00009133/*
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009134 * Process shell options. The global variable argptr contains a pointer
9135 * to the argument list; we advance it past the options.
Denis Vlasenko94e87bc2008-02-14 16:51:58 +00009136 *
9137 * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
9138 * For a non-interactive shell, an error condition encountered
9139 * by a special built-in ... shall cause the shell to write a diagnostic message
9140 * to standard error and exit as shown in the following table:
Denis Vlasenko56244732008-02-17 15:14:04 +00009141 * Error Special Built-In
Denis Vlasenko94e87bc2008-02-14 16:51:58 +00009142 * ...
9143 * Utility syntax error (option or operand error) Shall exit
9144 * ...
9145 * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
9146 * we see that bash does not do that (set "finishes" with error code 1 instead,
9147 * and shell continues), and people rely on this behavior!
9148 * Testcase:
9149 * set -o barfoo 2>/dev/null
9150 * echo $?
9151 *
9152 * Oh well. Let's mimic that.
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00009153 */
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009154static int
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009155minus_o(char *name, int val)
Eric Andersen62483552001-07-10 06:09:16 +00009156{
9157 int i;
9158
Denis Vlasenkoa624c112007-02-19 22:45:43 +00009159 if (name) {
9160 for (i = 0; i < NOPTS; i++) {
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00009161 if (strcmp(name, optnames(i)) == 0) {
Eric Andersenc470f442003-07-28 09:56:35 +00009162 optlist[i] = val;
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009163 return 0;
Eric Andersen62483552001-07-10 06:09:16 +00009164 }
Denis Vlasenkoa624c112007-02-19 22:45:43 +00009165 }
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009166 ash_msg("illegal option -o %s", name);
9167 return 1;
Eric Andersen62483552001-07-10 06:09:16 +00009168 }
Denis Vlasenkoa624c112007-02-19 22:45:43 +00009169 out1str("Current option settings\n");
9170 for (i = 0; i < NOPTS; i++)
9171 out1fmt("%-16s%s\n", optnames(i),
9172 optlist[i] ? "on" : "off");
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009173 return 0;
Eric Andersen62483552001-07-10 06:09:16 +00009174}
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009175static void
9176setoption(int flag, int val)
9177{
9178 int i;
9179
9180 for (i = 0; i < NOPTS; i++) {
9181 if (optletters(i) == flag) {
9182 optlist[i] = val;
9183 return;
9184 }
9185 }
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00009186 ash_msg_and_raise_error("illegal option -%c", flag);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009187 /* NOTREACHED */
9188}
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009189static int
Eric Andersenc470f442003-07-28 09:56:35 +00009190options(int cmdline)
Eric Andersencb57d552001-06-28 07:25:16 +00009191{
9192 char *p;
9193 int val;
9194 int c;
9195
9196 if (cmdline)
9197 minusc = NULL;
9198 while ((p = *argptr) != NULL) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009199 c = *p++;
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +00009200 if (c != '-' && c != '+')
9201 break;
9202 argptr++;
9203 val = 0; /* val = 0 if c == '+' */
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009204 if (c == '-') {
Eric Andersencb57d552001-06-28 07:25:16 +00009205 val = 1;
Denis Vlasenko9f739442006-12-16 23:49:13 +00009206 if (p[0] == '\0' || LONE_DASH(p)) {
Eric Andersen2870d962001-07-02 17:27:21 +00009207 if (!cmdline) {
9208 /* "-" means turn off -x and -v */
9209 if (p[0] == '\0')
9210 xflag = vflag = 0;
9211 /* "--" means reset params */
9212 else if (*argptr == NULL)
Eric Andersencb57d552001-06-28 07:25:16 +00009213 setparam(argptr);
Eric Andersen2870d962001-07-02 17:27:21 +00009214 }
Eric Andersenc470f442003-07-28 09:56:35 +00009215 break; /* "-" or "--" terminates options */
Eric Andersencb57d552001-06-28 07:25:16 +00009216 }
Eric Andersencb57d552001-06-28 07:25:16 +00009217 }
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +00009218 /* first char was + or - */
Eric Andersencb57d552001-06-28 07:25:16 +00009219 while ((c = *p++) != '\0') {
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +00009220 /* bash 3.2 indeed handles -c CMD and +c CMD the same */
Eric Andersencb57d552001-06-28 07:25:16 +00009221 if (c == 'c' && cmdline) {
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +00009222 minusc = p; /* command is after shell args */
Eric Andersencb57d552001-06-28 07:25:16 +00009223 } else if (c == 'o') {
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009224 if (minus_o(*argptr, val)) {
9225 /* it already printed err message */
9226 return 1; /* error */
9227 }
Eric Andersencb57d552001-06-28 07:25:16 +00009228 if (*argptr)
9229 argptr++;
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +00009230 } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
9231 isloginsh = 1;
9232 /* bash does not accept +-login, we also won't */
9233 } else if (cmdline && val && (c == '-')) { /* long options */
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00009234 if (strcmp(p, "login") == 0)
Robert Griebl64f70cc2002-05-14 23:22:06 +00009235 isloginsh = 1;
9236 break;
Eric Andersencb57d552001-06-28 07:25:16 +00009237 } else {
9238 setoption(c, val);
9239 }
9240 }
9241 }
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009242 return 0;
Eric Andersencb57d552001-06-28 07:25:16 +00009243}
9244
Eric Andersencb57d552001-06-28 07:25:16 +00009245/*
Eric Andersencb57d552001-06-28 07:25:16 +00009246 * The shift builtin command.
9247 */
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009248static int
Eric Andersenc470f442003-07-28 09:56:35 +00009249shiftcmd(int argc, char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +00009250{
9251 int n;
9252 char **ap1, **ap2;
9253
9254 n = 1;
9255 if (argc > 1)
9256 n = number(argv[1]);
9257 if (n > shellparam.nparam)
Denis Vlasenkob012b102007-02-19 22:43:01 +00009258 ash_msg_and_raise_error("can't shift that many");
9259 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +00009260 shellparam.nparam -= n;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00009261 for (ap1 = shellparam.p; --n >= 0; ap1++) {
Denis Vlasenko01631112007-12-16 17:20:38 +00009262 if (shellparam.malloced)
Denis Vlasenkob012b102007-02-19 22:43:01 +00009263 free(*ap1);
Eric Andersencb57d552001-06-28 07:25:16 +00009264 }
9265 ap2 = shellparam.p;
9266 while ((*ap2++ = *ap1++) != NULL);
Denis Vlasenko131ae172007-02-18 13:00:19 +00009267#if ENABLE_ASH_GETOPTS
Eric Andersencb57d552001-06-28 07:25:16 +00009268 shellparam.optind = 1;
9269 shellparam.optoff = -1;
Eric Andersenc470f442003-07-28 09:56:35 +00009270#endif
Denis Vlasenkob012b102007-02-19 22:43:01 +00009271 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00009272 return 0;
9273}
9274
Eric Andersencb57d552001-06-28 07:25:16 +00009275/*
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009276 * POSIX requires that 'set' (but not export or readonly) output the
9277 * variables in lexicographic order - by the locale's collating order (sigh).
9278 * Maybe we could keep them in an ordered balanced binary tree
9279 * instead of hashed lists.
9280 * For now just roll 'em through qsort for printing...
9281 */
9282static int
9283showvars(const char *sep_prefix, int on, int off)
9284{
9285 const char *sep;
9286 char **ep, **epend;
9287
9288 ep = listvars(on, off, &epend);
9289 qsort(ep, epend - ep, sizeof(char *), vpcmp);
9290
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00009291 sep = *sep_prefix ? " " : sep_prefix;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009292
9293 for (; ep < epend; ep++) {
9294 const char *p;
9295 const char *q;
9296
9297 p = strchrnul(*ep, '=');
9298 q = nullstr;
9299 if (*p)
9300 q = single_quote(++p);
9301 out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
9302 }
9303 return 0;
9304}
9305
9306/*
Eric Andersencb57d552001-06-28 07:25:16 +00009307 * The set command builtin.
9308 */
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009309static int
Eric Andersenc470f442003-07-28 09:56:35 +00009310setcmd(int argc, char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +00009311{
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009312 int retval;
9313
Eric Andersencb57d552001-06-28 07:25:16 +00009314 if (argc == 1)
Eric Andersenc470f442003-07-28 09:56:35 +00009315 return showvars(nullstr, 0, VUNSET);
Denis Vlasenkob012b102007-02-19 22:43:01 +00009316 INT_OFF;
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009317 retval = 1;
9318 if (!options(0)) { /* if no parse error... */
9319 retval = 0;
9320 optschanged();
9321 if (*argptr != NULL) {
9322 setparam(argptr);
9323 }
Eric Andersencb57d552001-06-28 07:25:16 +00009324 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00009325 INT_ON;
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009326 return retval;
Eric Andersencb57d552001-06-28 07:25:16 +00009327}
9328
Denis Vlasenko131ae172007-02-18 13:00:19 +00009329#if ENABLE_ASH_RANDOM_SUPPORT
Eric Andersenef02f822004-03-11 13:34:24 +00009330/* Roughly copied from bash.. */
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00009331static void
9332change_random(const char *value)
Eric Andersenef02f822004-03-11 13:34:24 +00009333{
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +00009334 if (value == NULL) {
Eric Andersen16767e22004-03-16 05:14:10 +00009335 /* "get", generate */
9336 char buf[16];
9337
9338 rseed = rseed * 1103515245 + 12345;
9339 sprintf(buf, "%d", (unsigned int)((rseed & 32767)));
9340 /* set without recursion */
9341 setvar(vrandom.text, buf, VNOFUNC);
9342 vrandom.flags &= ~VNOFUNC;
9343 } else {
9344 /* set/reset */
9345 rseed = strtoul(value, (char **)NULL, 10);
9346 }
Eric Andersenef02f822004-03-11 13:34:24 +00009347}
Eric Andersen16767e22004-03-16 05:14:10 +00009348#endif
9349
Denis Vlasenko131ae172007-02-18 13:00:19 +00009350#if ENABLE_ASH_GETOPTS
Eric Andersencb57d552001-06-28 07:25:16 +00009351static int
Eric Andersenc470f442003-07-28 09:56:35 +00009352getopts(char *optstr, char *optvar, char **optfirst, int *param_optind, int *optoff)
Eric Andersencb57d552001-06-28 07:25:16 +00009353{
9354 char *p, *q;
9355 char c = '?';
9356 int done = 0;
9357 int err = 0;
Eric Andersena48b0a32003-10-22 10:56:47 +00009358 char s[12];
9359 char **optnext;
Eric Andersencb57d552001-06-28 07:25:16 +00009360
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +00009361 if (*param_optind < 1)
Eric Andersena48b0a32003-10-22 10:56:47 +00009362 return 1;
9363 optnext = optfirst + *param_optind - 1;
9364
9365 if (*param_optind <= 1 || *optoff < 0 || strlen(optnext[-1]) < *optoff)
Eric Andersencb57d552001-06-28 07:25:16 +00009366 p = NULL;
9367 else
Eric Andersena48b0a32003-10-22 10:56:47 +00009368 p = optnext[-1] + *optoff;
Eric Andersencb57d552001-06-28 07:25:16 +00009369 if (p == NULL || *p == '\0') {
9370 /* Current word is done, advance */
Eric Andersencb57d552001-06-28 07:25:16 +00009371 p = *optnext;
9372 if (p == NULL || *p != '-' || *++p == '\0') {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009373 atend:
Eric Andersencb57d552001-06-28 07:25:16 +00009374 p = NULL;
9375 done = 1;
9376 goto out;
9377 }
9378 optnext++;
Denis Vlasenko9f739442006-12-16 23:49:13 +00009379 if (LONE_DASH(p)) /* check for "--" */
Eric Andersencb57d552001-06-28 07:25:16 +00009380 goto atend;
9381 }
9382
9383 c = *p++;
Eric Andersenc470f442003-07-28 09:56:35 +00009384 for (q = optstr; *q != c; ) {
Eric Andersencb57d552001-06-28 07:25:16 +00009385 if (*q == '\0') {
9386 if (optstr[0] == ':') {
9387 s[0] = c;
9388 s[1] = '\0';
9389 err |= setvarsafe("OPTARG", s, 0);
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00009390 } else {
Eric Andersenc470f442003-07-28 09:56:35 +00009391 fprintf(stderr, "Illegal option -%c\n", c);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009392 unsetvar("OPTARG");
Eric Andersencb57d552001-06-28 07:25:16 +00009393 }
9394 c = '?';
Eric Andersenc470f442003-07-28 09:56:35 +00009395 goto out;
Eric Andersencb57d552001-06-28 07:25:16 +00009396 }
9397 if (*++q == ':')
9398 q++;
9399 }
9400
9401 if (*++q == ':') {
9402 if (*p == '\0' && (p = *optnext) == NULL) {
9403 if (optstr[0] == ':') {
9404 s[0] = c;
9405 s[1] = '\0';
9406 err |= setvarsafe("OPTARG", s, 0);
9407 c = ':';
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00009408 } else {
Eric Andersenc470f442003-07-28 09:56:35 +00009409 fprintf(stderr, "No arg for -%c option\n", c);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009410 unsetvar("OPTARG");
Eric Andersencb57d552001-06-28 07:25:16 +00009411 c = '?';
9412 }
Eric Andersenc470f442003-07-28 09:56:35 +00009413 goto out;
Eric Andersencb57d552001-06-28 07:25:16 +00009414 }
9415
9416 if (p == *optnext)
9417 optnext++;
Eric Andersenc470f442003-07-28 09:56:35 +00009418 err |= setvarsafe("OPTARG", p, 0);
Eric Andersencb57d552001-06-28 07:25:16 +00009419 p = NULL;
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00009420 } else
Eric Andersenc470f442003-07-28 09:56:35 +00009421 err |= setvarsafe("OPTARG", nullstr, 0);
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009422 out:
Eric Andersencb57d552001-06-28 07:25:16 +00009423 *optoff = p ? p - *(optnext - 1) : -1;
Eric Andersenc470f442003-07-28 09:56:35 +00009424 *param_optind = optnext - optfirst + 1;
9425 fmtstr(s, sizeof(s), "%d", *param_optind);
Eric Andersencb57d552001-06-28 07:25:16 +00009426 err |= setvarsafe("OPTIND", s, VNOFUNC);
9427 s[0] = c;
9428 s[1] = '\0';
9429 err |= setvarsafe(optvar, s, 0);
9430 if (err) {
Eric Andersenc470f442003-07-28 09:56:35 +00009431 *param_optind = 1;
Eric Andersencb57d552001-06-28 07:25:16 +00009432 *optoff = -1;
Denis Vlasenkob012b102007-02-19 22:43:01 +00009433 flush_stdout_stderr();
9434 raise_exception(EXERROR);
Eric Andersencb57d552001-06-28 07:25:16 +00009435 }
9436 return done;
9437}
Eric Andersenc470f442003-07-28 09:56:35 +00009438
9439/*
9440 * The getopts builtin. Shellparam.optnext points to the next argument
9441 * to be processed. Shellparam.optptr points to the next character to
9442 * be processed in the current argument. If shellparam.optnext is NULL,
9443 * then it's the first time getopts has been called.
9444 */
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009445static int
Eric Andersenc470f442003-07-28 09:56:35 +00009446getoptscmd(int argc, char **argv)
9447{
9448 char **optbase;
9449
9450 if (argc < 3)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00009451 ash_msg_and_raise_error("usage: getopts optstring var [arg]");
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009452 if (argc == 3) {
Eric Andersenc470f442003-07-28 09:56:35 +00009453 optbase = shellparam.p;
9454 if (shellparam.optind > shellparam.nparam + 1) {
9455 shellparam.optind = 1;
9456 shellparam.optoff = -1;
9457 }
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009458 } else {
Eric Andersenc470f442003-07-28 09:56:35 +00009459 optbase = &argv[3];
9460 if (shellparam.optind > argc - 2) {
9461 shellparam.optind = 1;
9462 shellparam.optoff = -1;
9463 }
9464 }
9465
9466 return getopts(argv[1], argv[2], optbase, &shellparam.optind,
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +00009467 &shellparam.optoff);
Eric Andersenc470f442003-07-28 09:56:35 +00009468}
Denis Vlasenko131ae172007-02-18 13:00:19 +00009469#endif /* ASH_GETOPTS */
Eric Andersencb57d552001-06-28 07:25:16 +00009470
Eric Andersencb57d552001-06-28 07:25:16 +00009471
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009472/* ============ Shell parser */
Eric Andersencb57d552001-06-28 07:25:16 +00009473
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +00009474/*
9475 * NEOF is returned by parsecmd when it encounters an end of file. It
9476 * must be distinct from NULL, so we use the address of a variable that
9477 * happens to be handy.
9478 */
9479static smallint tokpushback; /* last token pushed back */
Denis Vlasenko99eb8502007-02-23 21:09:49 +00009480#define NEOF ((union node *)&tokpushback)
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +00009481static smallint parsebackquote; /* nonzero if we are inside backquotes */
Denis Vlasenko99eb8502007-02-23 21:09:49 +00009482static int lasttoken; /* last token read */
9483static char *wordtext; /* text of last word returned by readtoken */
9484static struct nodelist *backquotelist;
9485static union node *redirnode;
9486static struct heredoc *heredoc;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +00009487static smallint quoteflag; /* set if (part of) last token was quoted */
Denis Vlasenko99eb8502007-02-23 21:09:49 +00009488
Denis Vlasenkoa624c112007-02-19 22:45:43 +00009489static void raise_error_syntax(const char *) ATTRIBUTE_NORETURN;
9490static void
9491raise_error_syntax(const char *msg)
9492{
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00009493 ash_msg_and_raise_error("syntax error: %s", msg);
Denis Vlasenkoa624c112007-02-19 22:45:43 +00009494 /* NOTREACHED */
9495}
9496
9497/*
9498 * Called when an unexpected token is read during the parse. The argument
9499 * is the token that is expected, or -1 if more than one type of token can
9500 * occur at this point.
9501 */
9502static void raise_error_unexpected_syntax(int) ATTRIBUTE_NORETURN;
9503static void
9504raise_error_unexpected_syntax(int token)
9505{
9506 char msg[64];
9507 int l;
9508
9509 l = sprintf(msg, "%s unexpected", tokname(lasttoken));
9510 if (token >= 0)
9511 sprintf(msg + l, " (expecting %s)", tokname(token));
9512 raise_error_syntax(msg);
9513 /* NOTREACHED */
9514}
Eric Andersencb57d552001-06-28 07:25:16 +00009515
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009516#define EOFMARKLEN 79
Eric Andersencb57d552001-06-28 07:25:16 +00009517
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009518struct heredoc {
9519 struct heredoc *next; /* next here document in list */
9520 union node *here; /* redirection node */
9521 char *eofmark; /* string indicating end of input */
9522 int striptabs; /* if set, strip leading tabs */
9523};
Eric Andersencb57d552001-06-28 07:25:16 +00009524
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009525static struct heredoc *heredoclist; /* list of here documents to read */
9526
9527/* parsing is heavily cross-recursive, need these forward decls */
9528static union node *andor(void);
9529static union node *pipeline(void);
9530static union node *parse_command(void);
9531static void parseheredoc(void);
9532static char peektoken(void);
9533static int readtoken(void);
Eric Andersencb57d552001-06-28 07:25:16 +00009534
Eric Andersenc470f442003-07-28 09:56:35 +00009535static union node *
9536list(int nlflag)
Eric Andersencb57d552001-06-28 07:25:16 +00009537{
9538 union node *n1, *n2, *n3;
9539 int tok;
9540
Eric Andersenc470f442003-07-28 09:56:35 +00009541 checkkwd = CHKNL | CHKKWD | CHKALIAS;
9542 if (nlflag == 2 && peektoken())
Eric Andersencb57d552001-06-28 07:25:16 +00009543 return NULL;
9544 n1 = NULL;
9545 for (;;) {
9546 n2 = andor();
9547 tok = readtoken();
9548 if (tok == TBACKGND) {
Eric Andersenc470f442003-07-28 09:56:35 +00009549 if (n2->type == NPIPE) {
9550 n2->npipe.backgnd = 1;
Eric Andersencb57d552001-06-28 07:25:16 +00009551 } else {
Eric Andersenc470f442003-07-28 09:56:35 +00009552 if (n2->type != NREDIR) {
Denis Vlasenko597906c2008-02-20 16:38:54 +00009553 n3 = stzalloc(sizeof(struct nredir));
Eric Andersenc470f442003-07-28 09:56:35 +00009554 n3->nredir.n = n2;
Denis Vlasenko597906c2008-02-20 16:38:54 +00009555 /*n3->nredir.redirect = NULL; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +00009556 n2 = n3;
9557 }
9558 n2->type = NBACKGND;
Eric Andersencb57d552001-06-28 07:25:16 +00009559 }
9560 }
9561 if (n1 == NULL) {
9562 n1 = n2;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009563 } else {
Denis Vlasenkoa624c112007-02-19 22:45:43 +00009564 n3 = stalloc(sizeof(struct nbinary));
Eric Andersencb57d552001-06-28 07:25:16 +00009565 n3->type = NSEMI;
9566 n3->nbinary.ch1 = n1;
9567 n3->nbinary.ch2 = n2;
9568 n1 = n3;
9569 }
9570 switch (tok) {
9571 case TBACKGND:
9572 case TSEMI:
9573 tok = readtoken();
9574 /* fall through */
9575 case TNL:
9576 if (tok == TNL) {
9577 parseheredoc();
Eric Andersenc470f442003-07-28 09:56:35 +00009578 if (nlflag == 1)
Eric Andersencb57d552001-06-28 07:25:16 +00009579 return n1;
9580 } else {
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +00009581 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +00009582 }
Eric Andersenc470f442003-07-28 09:56:35 +00009583 checkkwd = CHKNL | CHKKWD | CHKALIAS;
Manuel Novoa III 16815d42001-08-10 19:36:07 +00009584 if (peektoken())
Eric Andersencb57d552001-06-28 07:25:16 +00009585 return n1;
9586 break;
9587 case TEOF:
9588 if (heredoclist)
9589 parseheredoc();
9590 else
Eric Andersenc470f442003-07-28 09:56:35 +00009591 pungetc(); /* push back EOF on input */
Eric Andersencb57d552001-06-28 07:25:16 +00009592 return n1;
9593 default:
Eric Andersenc470f442003-07-28 09:56:35 +00009594 if (nlflag == 1)
Denis Vlasenkoa624c112007-02-19 22:45:43 +00009595 raise_error_unexpected_syntax(-1);
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +00009596 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +00009597 return n1;
9598 }
9599 }
9600}
9601
Eric Andersenc470f442003-07-28 09:56:35 +00009602static union node *
9603andor(void)
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00009604{
Eric Andersencb57d552001-06-28 07:25:16 +00009605 union node *n1, *n2, *n3;
9606 int t;
9607
Eric Andersencb57d552001-06-28 07:25:16 +00009608 n1 = pipeline();
9609 for (;;) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009610 t = readtoken();
9611 if (t == TAND) {
Eric Andersencb57d552001-06-28 07:25:16 +00009612 t = NAND;
9613 } else if (t == TOR) {
9614 t = NOR;
9615 } else {
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +00009616 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +00009617 return n1;
9618 }
Eric Andersenc470f442003-07-28 09:56:35 +00009619 checkkwd = CHKNL | CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +00009620 n2 = pipeline();
Denis Vlasenkoa624c112007-02-19 22:45:43 +00009621 n3 = stalloc(sizeof(struct nbinary));
Eric Andersencb57d552001-06-28 07:25:16 +00009622 n3->type = t;
9623 n3->nbinary.ch1 = n1;
9624 n3->nbinary.ch2 = n2;
9625 n1 = n3;
9626 }
9627}
9628
Eric Andersenc470f442003-07-28 09:56:35 +00009629static union node *
9630pipeline(void)
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00009631{
Eric Andersencb57d552001-06-28 07:25:16 +00009632 union node *n1, *n2, *pipenode;
9633 struct nodelist *lp, *prev;
9634 int negate;
9635
9636 negate = 0;
9637 TRACE(("pipeline: entered\n"));
9638 if (readtoken() == TNOT) {
9639 negate = !negate;
Eric Andersenc470f442003-07-28 09:56:35 +00009640 checkkwd = CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +00009641 } else
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +00009642 tokpushback = 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009643 n1 = parse_command();
Eric Andersencb57d552001-06-28 07:25:16 +00009644 if (readtoken() == TPIPE) {
Denis Vlasenko597906c2008-02-20 16:38:54 +00009645 pipenode = stzalloc(sizeof(struct npipe));
Eric Andersencb57d552001-06-28 07:25:16 +00009646 pipenode->type = NPIPE;
Denis Vlasenko597906c2008-02-20 16:38:54 +00009647 /*pipenode->npipe.backgnd = 0; - stzalloc did it */
Denis Vlasenkoa624c112007-02-19 22:45:43 +00009648 lp = stalloc(sizeof(struct nodelist));
Eric Andersencb57d552001-06-28 07:25:16 +00009649 pipenode->npipe.cmdlist = lp;
9650 lp->n = n1;
9651 do {
9652 prev = lp;
Denis Vlasenkoa624c112007-02-19 22:45:43 +00009653 lp = stalloc(sizeof(struct nodelist));
Eric Andersenc470f442003-07-28 09:56:35 +00009654 checkkwd = CHKNL | CHKKWD | CHKALIAS;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009655 lp->n = parse_command();
Eric Andersencb57d552001-06-28 07:25:16 +00009656 prev->next = lp;
9657 } while (readtoken() == TPIPE);
9658 lp->next = NULL;
9659 n1 = pipenode;
9660 }
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +00009661 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +00009662 if (negate) {
Denis Vlasenkoa624c112007-02-19 22:45:43 +00009663 n2 = stalloc(sizeof(struct nnot));
Eric Andersencb57d552001-06-28 07:25:16 +00009664 n2->type = NNOT;
9665 n2->nnot.com = n1;
9666 return n2;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00009667 }
9668 return n1;
Eric Andersencb57d552001-06-28 07:25:16 +00009669}
9670
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009671static union node *
9672makename(void)
9673{
9674 union node *n;
9675
Denis Vlasenko597906c2008-02-20 16:38:54 +00009676 n = stzalloc(sizeof(struct narg));
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009677 n->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +00009678 /*n->narg.next = NULL; - stzalloc did it */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009679 n->narg.text = wordtext;
9680 n->narg.backquote = backquotelist;
9681 return n;
9682}
9683
9684static void
9685fixredir(union node *n, const char *text, int err)
9686{
9687 TRACE(("Fix redir %s %d\n", text, err));
9688 if (!err)
9689 n->ndup.vname = NULL;
9690
9691 if (isdigit(text[0]) && text[1] == '\0')
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009692 n->ndup.dupfd = text[0] - '0';
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009693 else if (LONE_DASH(text))
9694 n->ndup.dupfd = -1;
9695 else {
9696 if (err)
9697 raise_error_syntax("Bad fd number");
9698 n->ndup.vname = makename();
9699 }
9700}
9701
9702/*
9703 * Returns true if the text contains nothing to expand (no dollar signs
9704 * or backquotes).
9705 */
9706static int
9707noexpand(char *text)
9708{
9709 char *p;
9710 char c;
9711
9712 p = text;
9713 while ((c = *p++) != '\0') {
9714 if (c == CTLQUOTEMARK)
9715 continue;
9716 if (c == CTLESC)
9717 p++;
9718 else if (SIT(c, BASESYNTAX) == CCTL)
9719 return 0;
9720 }
9721 return 1;
9722}
9723
9724static void
9725parsefname(void)
9726{
9727 union node *n = redirnode;
9728
9729 if (readtoken() != TWORD)
9730 raise_error_unexpected_syntax(-1);
9731 if (n->type == NHERE) {
9732 struct heredoc *here = heredoc;
9733 struct heredoc *p;
9734 int i;
9735
9736 if (quoteflag == 0)
9737 n->type = NXHERE;
9738 TRACE(("Here document %d\n", n->type));
9739 if (!noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
9740 raise_error_syntax("Illegal eof marker for << redirection");
9741 rmescapes(wordtext);
9742 here->eofmark = wordtext;
9743 here->next = NULL;
9744 if (heredoclist == NULL)
9745 heredoclist = here;
9746 else {
9747 for (p = heredoclist; p->next; p = p->next);
9748 p->next = here;
9749 }
9750 } else if (n->type == NTOFD || n->type == NFROMFD) {
9751 fixredir(n, wordtext, 0);
9752 } else {
9753 n->nfile.fname = makename();
9754 }
9755}
Eric Andersencb57d552001-06-28 07:25:16 +00009756
Eric Andersenc470f442003-07-28 09:56:35 +00009757static union node *
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009758simplecmd(void)
9759{
9760 union node *args, **app;
9761 union node *n = NULL;
9762 union node *vars, **vpp;
9763 union node **rpp, *redir;
9764 int savecheckkwd;
9765
9766 args = NULL;
9767 app = &args;
9768 vars = NULL;
9769 vpp = &vars;
9770 redir = NULL;
9771 rpp = &redir;
9772
9773 savecheckkwd = CHKALIAS;
9774 for (;;) {
9775 checkkwd = savecheckkwd;
9776 switch (readtoken()) {
9777 case TWORD:
Denis Vlasenko597906c2008-02-20 16:38:54 +00009778 n = stzalloc(sizeof(struct narg));
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009779 n->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +00009780 /*n->narg.next = NULL; - stzalloc did it */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009781 n->narg.text = wordtext;
9782 n->narg.backquote = backquotelist;
9783 if (savecheckkwd && isassignment(wordtext)) {
9784 *vpp = n;
9785 vpp = &n->narg.next;
9786 } else {
9787 *app = n;
9788 app = &n->narg.next;
9789 savecheckkwd = 0;
9790 }
9791 break;
9792 case TREDIR:
9793 *rpp = n = redirnode;
9794 rpp = &n->nfile.next;
9795 parsefname(); /* read name of redirection file */
9796 break;
9797 case TLP:
9798 if (args && app == &args->narg.next
9799 && !vars && !redir
9800 ) {
9801 struct builtincmd *bcmd;
9802 const char *name;
9803
9804 /* We have a function */
9805 if (readtoken() != TRP)
9806 raise_error_unexpected_syntax(TRP);
9807 name = n->narg.text;
9808 if (!goodname(name)
9809 || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
9810 ) {
9811 raise_error_syntax("Bad function name");
9812 }
9813 n->type = NDEFUN;
9814 checkkwd = CHKNL | CHKKWD | CHKALIAS;
9815 n->narg.next = parse_command();
9816 return n;
9817 }
9818 /* fall through */
9819 default:
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +00009820 tokpushback = 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009821 goto out;
9822 }
9823 }
9824 out:
9825 *app = NULL;
9826 *vpp = NULL;
9827 *rpp = NULL;
9828 n = stalloc(sizeof(struct ncmd));
9829 n->type = NCMD;
9830 n->ncmd.args = args;
9831 n->ncmd.assign = vars;
9832 n->ncmd.redirect = redir;
9833 return n;
9834}
9835
9836static union node *
9837parse_command(void)
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00009838{
Eric Andersencb57d552001-06-28 07:25:16 +00009839 union node *n1, *n2;
9840 union node *ap, **app;
9841 union node *cp, **cpp;
9842 union node *redir, **rpp;
Eric Andersenc470f442003-07-28 09:56:35 +00009843 union node **rpp2;
Eric Andersencb57d552001-06-28 07:25:16 +00009844 int t;
9845
9846 redir = NULL;
Eric Andersenc470f442003-07-28 09:56:35 +00009847 rpp2 = &redir;
Eric Andersen88cec252001-09-06 17:35:20 +00009848
Eric Andersencb57d552001-06-28 07:25:16 +00009849 switch (readtoken()) {
Eric Andersenc470f442003-07-28 09:56:35 +00009850 default:
Denis Vlasenkoa624c112007-02-19 22:45:43 +00009851 raise_error_unexpected_syntax(-1);
Eric Andersenc470f442003-07-28 09:56:35 +00009852 /* NOTREACHED */
Eric Andersencb57d552001-06-28 07:25:16 +00009853 case TIF:
Denis Vlasenkoa624c112007-02-19 22:45:43 +00009854 n1 = stalloc(sizeof(struct nif));
Eric Andersencb57d552001-06-28 07:25:16 +00009855 n1->type = NIF;
9856 n1->nif.test = list(0);
9857 if (readtoken() != TTHEN)
Denis Vlasenkoa624c112007-02-19 22:45:43 +00009858 raise_error_unexpected_syntax(TTHEN);
Eric Andersencb57d552001-06-28 07:25:16 +00009859 n1->nif.ifpart = list(0);
9860 n2 = n1;
9861 while (readtoken() == TELIF) {
Denis Vlasenkoa624c112007-02-19 22:45:43 +00009862 n2->nif.elsepart = stalloc(sizeof(struct nif));
Eric Andersencb57d552001-06-28 07:25:16 +00009863 n2 = n2->nif.elsepart;
9864 n2->type = NIF;
9865 n2->nif.test = list(0);
9866 if (readtoken() != TTHEN)
Denis Vlasenkoa624c112007-02-19 22:45:43 +00009867 raise_error_unexpected_syntax(TTHEN);
Eric Andersencb57d552001-06-28 07:25:16 +00009868 n2->nif.ifpart = list(0);
9869 }
9870 if (lasttoken == TELSE)
9871 n2->nif.elsepart = list(0);
9872 else {
9873 n2->nif.elsepart = NULL;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +00009874 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +00009875 }
Eric Andersenc470f442003-07-28 09:56:35 +00009876 t = TFI;
Eric Andersencb57d552001-06-28 07:25:16 +00009877 break;
9878 case TWHILE:
Eric Andersenc470f442003-07-28 09:56:35 +00009879 case TUNTIL: {
Eric Andersencb57d552001-06-28 07:25:16 +00009880 int got;
Denis Vlasenkoa624c112007-02-19 22:45:43 +00009881 n1 = stalloc(sizeof(struct nbinary));
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009882 n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
Eric Andersencb57d552001-06-28 07:25:16 +00009883 n1->nbinary.ch1 = list(0);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009884 got = readtoken();
9885 if (got != TDO) {
Denis Vlasenko131ae172007-02-18 13:00:19 +00009886 TRACE(("expecting DO got %s %s\n", tokname(got),
9887 got == TWORD ? wordtext : ""));
Denis Vlasenkoa624c112007-02-19 22:45:43 +00009888 raise_error_unexpected_syntax(TDO);
Eric Andersencb57d552001-06-28 07:25:16 +00009889 }
9890 n1->nbinary.ch2 = list(0);
Eric Andersenc470f442003-07-28 09:56:35 +00009891 t = TDONE;
Eric Andersencb57d552001-06-28 07:25:16 +00009892 break;
9893 }
9894 case TFOR:
Eric Andersenc470f442003-07-28 09:56:35 +00009895 if (readtoken() != TWORD || quoteflag || ! goodname(wordtext))
Denis Vlasenkoa624c112007-02-19 22:45:43 +00009896 raise_error_syntax("Bad for loop variable");
9897 n1 = stalloc(sizeof(struct nfor));
Eric Andersencb57d552001-06-28 07:25:16 +00009898 n1->type = NFOR;
9899 n1->nfor.var = wordtext;
Eric Andersenc470f442003-07-28 09:56:35 +00009900 checkkwd = CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +00009901 if (readtoken() == TIN) {
9902 app = &ap;
9903 while (readtoken() == TWORD) {
Denis Vlasenko597906c2008-02-20 16:38:54 +00009904 n2 = stzalloc(sizeof(struct narg));
Eric Andersencb57d552001-06-28 07:25:16 +00009905 n2->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +00009906 /*n2->narg.next = NULL; - stzalloc did it */
Eric Andersencb57d552001-06-28 07:25:16 +00009907 n2->narg.text = wordtext;
9908 n2->narg.backquote = backquotelist;
9909 *app = n2;
9910 app = &n2->narg.next;
9911 }
9912 *app = NULL;
9913 n1->nfor.args = ap;
9914 if (lasttoken != TNL && lasttoken != TSEMI)
Denis Vlasenkoa624c112007-02-19 22:45:43 +00009915 raise_error_unexpected_syntax(-1);
Eric Andersencb57d552001-06-28 07:25:16 +00009916 } else {
Denis Vlasenko597906c2008-02-20 16:38:54 +00009917 n2 = stzalloc(sizeof(struct narg));
Eric Andersencb57d552001-06-28 07:25:16 +00009918 n2->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +00009919 /*n2->narg.next = NULL; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +00009920 n2->narg.text = (char *)dolatstr;
Denis Vlasenko597906c2008-02-20 16:38:54 +00009921 /*n2->narg.backquote = NULL;*/
Eric Andersencb57d552001-06-28 07:25:16 +00009922 n1->nfor.args = n2;
9923 /*
9924 * Newline or semicolon here is optional (but note
9925 * that the original Bourne shell only allowed NL).
9926 */
9927 if (lasttoken != TNL && lasttoken != TSEMI)
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +00009928 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +00009929 }
Eric Andersenc470f442003-07-28 09:56:35 +00009930 checkkwd = CHKNL | CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +00009931 if (readtoken() != TDO)
Denis Vlasenkoa624c112007-02-19 22:45:43 +00009932 raise_error_unexpected_syntax(TDO);
Eric Andersencb57d552001-06-28 07:25:16 +00009933 n1->nfor.body = list(0);
Eric Andersenc470f442003-07-28 09:56:35 +00009934 t = TDONE;
Eric Andersencb57d552001-06-28 07:25:16 +00009935 break;
9936 case TCASE:
Denis Vlasenkoa624c112007-02-19 22:45:43 +00009937 n1 = stalloc(sizeof(struct ncase));
Eric Andersencb57d552001-06-28 07:25:16 +00009938 n1->type = NCASE;
9939 if (readtoken() != TWORD)
Denis Vlasenkoa624c112007-02-19 22:45:43 +00009940 raise_error_unexpected_syntax(TWORD);
Denis Vlasenko597906c2008-02-20 16:38:54 +00009941 n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
Eric Andersencb57d552001-06-28 07:25:16 +00009942 n2->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +00009943 /*n2->narg.next = NULL; - stzalloc did it */
Eric Andersencb57d552001-06-28 07:25:16 +00009944 n2->narg.text = wordtext;
9945 n2->narg.backquote = backquotelist;
Eric Andersencb57d552001-06-28 07:25:16 +00009946 do {
Eric Andersenc470f442003-07-28 09:56:35 +00009947 checkkwd = CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +00009948 } while (readtoken() == TNL);
9949 if (lasttoken != TIN)
Denis Vlasenkoa624c112007-02-19 22:45:43 +00009950 raise_error_unexpected_syntax(TIN);
Eric Andersencb57d552001-06-28 07:25:16 +00009951 cpp = &n1->ncase.cases;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009952 next_case:
Eric Andersenc470f442003-07-28 09:56:35 +00009953 checkkwd = CHKNL | CHKKWD;
9954 t = readtoken();
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +00009955 while (t != TESAC) {
Eric Andersencb57d552001-06-28 07:25:16 +00009956 if (lasttoken == TLP)
9957 readtoken();
Denis Vlasenkoa624c112007-02-19 22:45:43 +00009958 *cpp = cp = stalloc(sizeof(struct nclist));
Eric Andersencb57d552001-06-28 07:25:16 +00009959 cp->type = NCLIST;
9960 app = &cp->nclist.pattern;
9961 for (;;) {
Denis Vlasenko597906c2008-02-20 16:38:54 +00009962 *app = ap = stzalloc(sizeof(struct narg));
Eric Andersencb57d552001-06-28 07:25:16 +00009963 ap->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +00009964 /*ap->narg.next = NULL; - stzalloc did it */
Eric Andersencb57d552001-06-28 07:25:16 +00009965 ap->narg.text = wordtext;
9966 ap->narg.backquote = backquotelist;
Eric Andersenc470f442003-07-28 09:56:35 +00009967 if (readtoken() != TPIPE)
Eric Andersencb57d552001-06-28 07:25:16 +00009968 break;
9969 app = &ap->narg.next;
9970 readtoken();
9971 }
Denis Vlasenko597906c2008-02-20 16:38:54 +00009972 //ap->narg.next = NULL;
Eric Andersencb57d552001-06-28 07:25:16 +00009973 if (lasttoken != TRP)
Denis Vlasenkoa624c112007-02-19 22:45:43 +00009974 raise_error_unexpected_syntax(TRP);
Eric Andersenc470f442003-07-28 09:56:35 +00009975 cp->nclist.body = list(2);
Eric Andersencb57d552001-06-28 07:25:16 +00009976
Eric Andersenc470f442003-07-28 09:56:35 +00009977 cpp = &cp->nclist.next;
9978
9979 checkkwd = CHKNL | CHKKWD;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009980 t = readtoken();
9981 if (t != TESAC) {
Eric Andersencb57d552001-06-28 07:25:16 +00009982 if (t != TENDCASE)
Denis Vlasenkoa624c112007-02-19 22:45:43 +00009983 raise_error_unexpected_syntax(TENDCASE);
9984 goto next_case;
Eric Andersencb57d552001-06-28 07:25:16 +00009985 }
Eric Andersenc470f442003-07-28 09:56:35 +00009986 }
Eric Andersencb57d552001-06-28 07:25:16 +00009987 *cpp = NULL;
Eric Andersenc470f442003-07-28 09:56:35 +00009988 goto redir;
Eric Andersencb57d552001-06-28 07:25:16 +00009989 case TLP:
Denis Vlasenko597906c2008-02-20 16:38:54 +00009990 n1 = stzalloc(sizeof(struct nredir));
Eric Andersencb57d552001-06-28 07:25:16 +00009991 n1->type = NSUBSHELL;
9992 n1->nredir.n = list(0);
Denis Vlasenko597906c2008-02-20 16:38:54 +00009993 /*n1->nredir.redirect = NULL; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +00009994 t = TRP;
Eric Andersencb57d552001-06-28 07:25:16 +00009995 break;
9996 case TBEGIN:
9997 n1 = list(0);
Eric Andersenc470f442003-07-28 09:56:35 +00009998 t = TEND;
Eric Andersencb57d552001-06-28 07:25:16 +00009999 break;
Eric Andersencb57d552001-06-28 07:25:16 +000010000 case TWORD:
Eric Andersenc470f442003-07-28 09:56:35 +000010001 case TREDIR:
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010002 tokpushback = 1;
Eric Andersenc470f442003-07-28 09:56:35 +000010003 return simplecmd();
Eric Andersencb57d552001-06-28 07:25:16 +000010004 }
10005
Eric Andersenc470f442003-07-28 09:56:35 +000010006 if (readtoken() != t)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010007 raise_error_unexpected_syntax(t);
Eric Andersenc470f442003-07-28 09:56:35 +000010008
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010009 redir:
Eric Andersencb57d552001-06-28 07:25:16 +000010010 /* Now check for redirection which may follow command */
Eric Andersenc470f442003-07-28 09:56:35 +000010011 checkkwd = CHKKWD | CHKALIAS;
10012 rpp = rpp2;
Eric Andersencb57d552001-06-28 07:25:16 +000010013 while (readtoken() == TREDIR) {
10014 *rpp = n2 = redirnode;
10015 rpp = &n2->nfile.next;
10016 parsefname();
10017 }
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010018 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010019 *rpp = NULL;
10020 if (redir) {
10021 if (n1->type != NSUBSHELL) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010022 n2 = stzalloc(sizeof(struct nredir));
Eric Andersencb57d552001-06-28 07:25:16 +000010023 n2->type = NREDIR;
10024 n2->nredir.n = n1;
10025 n1 = n2;
10026 }
10027 n1->nredir.redirect = redir;
10028 }
Eric Andersencb57d552001-06-28 07:25:16 +000010029 return n1;
10030}
10031
Eric Andersencb57d552001-06-28 07:25:16 +000010032/*
10033 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
10034 * is not NULL, read a here document. In the latter case, eofmark is the
10035 * word which marks the end of the document and striptabs is true if
10036 * leading tabs should be stripped from the document. The argument firstc
10037 * is the first character of the input token or document.
10038 *
10039 * Because C does not have internal subroutines, I have simulated them
10040 * using goto's to implement the subroutine linkage. The following macros
10041 * will run code that appears at the end of readtoken1.
10042 */
10043
Eric Andersen2870d962001-07-02 17:27:21 +000010044#define CHECKEND() {goto checkend; checkend_return:;}
10045#define PARSEREDIR() {goto parseredir; parseredir_return:;}
10046#define PARSESUB() {goto parsesub; parsesub_return:;}
10047#define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
10048#define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
10049#define PARSEARITH() {goto parsearith; parsearith_return:;}
Eric Andersencb57d552001-06-28 07:25:16 +000010050
10051static int
Eric Andersenc470f442003-07-28 09:56:35 +000010052readtoken1(int firstc, int syntax, char *eofmark, int striptabs)
Manuel Novoa III 16815d42001-08-10 19:36:07 +000010053{
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010054 /* NB: syntax parameter fits into smallint */
Eric Andersencb57d552001-06-28 07:25:16 +000010055 int c = firstc;
10056 char *out;
10057 int len;
10058 char line[EOFMARKLEN + 1];
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010059 struct nodelist *bqlist;
10060 smallint quotef;
10061 smallint dblquote;
10062 smallint oldstyle;
10063 smallint prevsyntax; /* syntax before arithmetic */
Denis Vlasenko46a53062007-09-24 18:30:02 +000010064#if ENABLE_ASH_EXPAND_PRMT
10065 smallint pssyntax; /* we are expanding a prompt string */
10066#endif
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010067 int varnest; /* levels of variables expansion */
10068 int arinest; /* levels of arithmetic expansion */
10069 int parenlevel; /* levels of parens in arithmetic */
10070 int dqvarnest; /* levels of variables expansion within double quotes */
10071
Eric Andersencb57d552001-06-28 07:25:16 +000010072#if __GNUC__
10073 /* Avoid longjmp clobbering */
10074 (void) &out;
10075 (void) &quotef;
10076 (void) &dblquote;
10077 (void) &varnest;
10078 (void) &arinest;
10079 (void) &parenlevel;
10080 (void) &dqvarnest;
10081 (void) &oldstyle;
10082 (void) &prevsyntax;
10083 (void) &syntax;
10084#endif
Eric Andersencb57d552001-06-28 07:25:16 +000010085 startlinno = plinno;
Eric Andersencb57d552001-06-28 07:25:16 +000010086 bqlist = NULL;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010087 quotef = 0;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010088 oldstyle = 0;
10089 prevsyntax = 0;
Denis Vlasenko46a53062007-09-24 18:30:02 +000010090#if ENABLE_ASH_EXPAND_PRMT
10091 pssyntax = (syntax == PSSYNTAX);
10092 if (pssyntax)
10093 syntax = DQSYNTAX;
10094#endif
10095 dblquote = (syntax == DQSYNTAX);
Eric Andersencb57d552001-06-28 07:25:16 +000010096 varnest = 0;
10097 arinest = 0;
10098 parenlevel = 0;
10099 dqvarnest = 0;
10100
10101 STARTSTACKSTR(out);
Eric Andersenc470f442003-07-28 09:56:35 +000010102 loop: { /* for each line, until end of word */
10103 CHECKEND(); /* set c to PEOF if at end of here document */
10104 for (;;) { /* until end of line or end of word */
10105 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
Denis Vlasenkobf0a2012006-12-26 10:42:51 +000010106 switch (SIT(c, syntax)) {
Eric Andersenc470f442003-07-28 09:56:35 +000010107 case CNL: /* '\n' */
Eric Andersencb57d552001-06-28 07:25:16 +000010108 if (syntax == BASESYNTAX)
Eric Andersenc470f442003-07-28 09:56:35 +000010109 goto endword; /* exit outer loop */
Eric Andersencb57d552001-06-28 07:25:16 +000010110 USTPUTC(c, out);
10111 plinno++;
10112 if (doprompt)
10113 setprompt(2);
Eric Andersencb57d552001-06-28 07:25:16 +000010114 c = pgetc();
Eric Andersenc470f442003-07-28 09:56:35 +000010115 goto loop; /* continue outer loop */
Eric Andersencb57d552001-06-28 07:25:16 +000010116 case CWORD:
10117 USTPUTC(c, out);
10118 break;
10119 case CCTL:
Eric Andersenc470f442003-07-28 09:56:35 +000010120 if (eofmark == NULL || dblquote)
Eric Andersencb57d552001-06-28 07:25:16 +000010121 USTPUTC(CTLESC, out);
10122 USTPUTC(c, out);
10123 break;
Eric Andersenc470f442003-07-28 09:56:35 +000010124 case CBACK: /* backslash */
Eric Andersencb57d552001-06-28 07:25:16 +000010125 c = pgetc2();
10126 if (c == PEOF) {
Eric Andersenc470f442003-07-28 09:56:35 +000010127 USTPUTC(CTLESC, out);
Eric Andersencb57d552001-06-28 07:25:16 +000010128 USTPUTC('\\', out);
10129 pungetc();
10130 } else if (c == '\n') {
10131 if (doprompt)
10132 setprompt(2);
Eric Andersencb57d552001-06-28 07:25:16 +000010133 } else {
Denis Vlasenko46a53062007-09-24 18:30:02 +000010134#if ENABLE_ASH_EXPAND_PRMT
10135 if (c == '$' && pssyntax) {
10136 USTPUTC(CTLESC, out);
10137 USTPUTC('\\', out);
10138 }
10139#endif
"Vladimir N. Oleynik"84005af2006-01-25 17:53:04 +000010140 if (dblquote &&
Eric Andersenc470f442003-07-28 09:56:35 +000010141 c != '\\' && c != '`' &&
10142 c != '$' && (
10143 c != '"' ||
"Vladimir N. Oleynik"84005af2006-01-25 17:53:04 +000010144 eofmark != NULL)
Eric Andersenc470f442003-07-28 09:56:35 +000010145 ) {
10146 USTPUTC(CTLESC, out);
Eric Andersencb57d552001-06-28 07:25:16 +000010147 USTPUTC('\\', out);
Eric Andersenc470f442003-07-28 09:56:35 +000010148 }
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010149 if (SIT(c, SQSYNTAX) == CCTL)
Eric Andersencb57d552001-06-28 07:25:16 +000010150 USTPUTC(CTLESC, out);
Eric Andersencb57d552001-06-28 07:25:16 +000010151 USTPUTC(c, out);
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010152 quotef = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010153 }
10154 break;
10155 case CSQUOTE:
Eric Andersencb57d552001-06-28 07:25:16 +000010156 syntax = SQSYNTAX;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010157 quotemark:
Eric Andersenc470f442003-07-28 09:56:35 +000010158 if (eofmark == NULL) {
10159 USTPUTC(CTLQUOTEMARK, out);
10160 }
Eric Andersencb57d552001-06-28 07:25:16 +000010161 break;
10162 case CDQUOTE:
Eric Andersencb57d552001-06-28 07:25:16 +000010163 syntax = DQSYNTAX;
10164 dblquote = 1;
Eric Andersenc470f442003-07-28 09:56:35 +000010165 goto quotemark;
Eric Andersencb57d552001-06-28 07:25:16 +000010166 case CENDQUOTE:
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010167 if (eofmark != NULL && arinest == 0
10168 && varnest == 0
10169 ) {
Eric Andersencb57d552001-06-28 07:25:16 +000010170 USTPUTC(c, out);
10171 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000010172 if (dqvarnest == 0) {
Eric Andersencb57d552001-06-28 07:25:16 +000010173 syntax = BASESYNTAX;
10174 dblquote = 0;
10175 }
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010176 quotef = 1;
Eric Andersenc470f442003-07-28 09:56:35 +000010177 goto quotemark;
Eric Andersencb57d552001-06-28 07:25:16 +000010178 }
10179 break;
Eric Andersenc470f442003-07-28 09:56:35 +000010180 case CVAR: /* '$' */
10181 PARSESUB(); /* parse substitution */
Eric Andersencb57d552001-06-28 07:25:16 +000010182 break;
Eric Andersenc470f442003-07-28 09:56:35 +000010183 case CENDVAR: /* '}' */
Eric Andersencb57d552001-06-28 07:25:16 +000010184 if (varnest > 0) {
10185 varnest--;
10186 if (dqvarnest > 0) {
10187 dqvarnest--;
10188 }
10189 USTPUTC(CTLENDVAR, out);
10190 } else {
10191 USTPUTC(c, out);
10192 }
10193 break;
Denis Vlasenko131ae172007-02-18 13:00:19 +000010194#if ENABLE_ASH_MATH_SUPPORT
Eric Andersenc470f442003-07-28 09:56:35 +000010195 case CLP: /* '(' in arithmetic */
Eric Andersencb57d552001-06-28 07:25:16 +000010196 parenlevel++;
10197 USTPUTC(c, out);
10198 break;
Eric Andersenc470f442003-07-28 09:56:35 +000010199 case CRP: /* ')' in arithmetic */
Eric Andersencb57d552001-06-28 07:25:16 +000010200 if (parenlevel > 0) {
10201 USTPUTC(c, out);
10202 --parenlevel;
10203 } else {
10204 if (pgetc() == ')') {
10205 if (--arinest == 0) {
10206 USTPUTC(CTLENDARI, out);
10207 syntax = prevsyntax;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010208 dblquote = (syntax == DQSYNTAX);
Eric Andersencb57d552001-06-28 07:25:16 +000010209 } else
10210 USTPUTC(')', out);
10211 } else {
10212 /*
10213 * unbalanced parens
10214 * (don't 2nd guess - no error)
10215 */
10216 pungetc();
10217 USTPUTC(')', out);
10218 }
10219 }
10220 break;
10221#endif
Eric Andersenc470f442003-07-28 09:56:35 +000010222 case CBQUOTE: /* '`' */
Eric Andersencb57d552001-06-28 07:25:16 +000010223 PARSEBACKQOLD();
10224 break;
Eric Andersen2870d962001-07-02 17:27:21 +000010225 case CENDFILE:
Eric Andersenc470f442003-07-28 09:56:35 +000010226 goto endword; /* exit outer loop */
Eric Andersencb57d552001-06-28 07:25:16 +000010227 case CIGN:
10228 break;
10229 default:
10230 if (varnest == 0)
Eric Andersenc470f442003-07-28 09:56:35 +000010231 goto endword; /* exit outer loop */
Denis Vlasenko131ae172007-02-18 13:00:19 +000010232#if ENABLE_ASH_ALIAS
Eric Andersen3102ac42001-07-06 04:26:23 +000010233 if (c != PEOA)
10234#endif
Eric Andersencb57d552001-06-28 07:25:16 +000010235 USTPUTC(c, out);
Eric Andersen3102ac42001-07-06 04:26:23 +000010236
Eric Andersencb57d552001-06-28 07:25:16 +000010237 }
10238 c = pgetc_macro();
10239 }
10240 }
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010241 endword:
Denis Vlasenko131ae172007-02-18 13:00:19 +000010242#if ENABLE_ASH_MATH_SUPPORT
Eric Andersencb57d552001-06-28 07:25:16 +000010243 if (syntax == ARISYNTAX)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010244 raise_error_syntax("Missing '))'");
Eric Andersenc470f442003-07-28 09:56:35 +000010245#endif
Denis Vlasenko99eb8502007-02-23 21:09:49 +000010246 if (syntax != BASESYNTAX && !parsebackquote && eofmark == NULL)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010247 raise_error_syntax("Unterminated quoted string");
Eric Andersencb57d552001-06-28 07:25:16 +000010248 if (varnest != 0) {
10249 startlinno = plinno;
Eric Andersenc470f442003-07-28 09:56:35 +000010250 /* { */
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010251 raise_error_syntax("Missing '}'");
Eric Andersencb57d552001-06-28 07:25:16 +000010252 }
10253 USTPUTC('\0', out);
Eric Andersenc470f442003-07-28 09:56:35 +000010254 len = out - (char *)stackblock();
Eric Andersencb57d552001-06-28 07:25:16 +000010255 out = stackblock();
10256 if (eofmark == NULL) {
10257 if ((c == '>' || c == '<')
Eric Andersenc470f442003-07-28 09:56:35 +000010258 && quotef == 0
10259 && len <= 2
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010260 && (*out == '\0' || isdigit(*out))) {
Eric Andersencb57d552001-06-28 07:25:16 +000010261 PARSEREDIR();
10262 return lasttoken = TREDIR;
10263 } else {
10264 pungetc();
10265 }
10266 }
10267 quoteflag = quotef;
10268 backquotelist = bqlist;
10269 grabstackblock(len);
10270 wordtext = out;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010271 lasttoken = TWORD;
10272 return lasttoken;
Eric Andersencb57d552001-06-28 07:25:16 +000010273/* end of readtoken routine */
10274
Eric Andersencb57d552001-06-28 07:25:16 +000010275/*
10276 * Check to see whether we are at the end of the here document. When this
10277 * is called, c is set to the first character of the next input line. If
10278 * we are at the end of the here document, this routine sets the c to PEOF.
10279 */
Eric Andersenc470f442003-07-28 09:56:35 +000010280checkend: {
10281 if (eofmark) {
Denis Vlasenko131ae172007-02-18 13:00:19 +000010282#if ENABLE_ASH_ALIAS
Eric Andersenc470f442003-07-28 09:56:35 +000010283 if (c == PEOA) {
10284 c = pgetc2();
10285 }
10286#endif
10287 if (striptabs) {
10288 while (c == '\t') {
Eric Andersencb57d552001-06-28 07:25:16 +000010289 c = pgetc2();
10290 }
Eric Andersenc470f442003-07-28 09:56:35 +000010291 }
10292 if (c == *eofmark) {
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010293 if (pfgets(line, sizeof(line)) != NULL) {
Eric Andersenc470f442003-07-28 09:56:35 +000010294 char *p, *q;
Eric Andersencb57d552001-06-28 07:25:16 +000010295
Eric Andersenc470f442003-07-28 09:56:35 +000010296 p = line;
Denis Vlasenko2da584f2007-02-19 22:44:05 +000010297 for (q = eofmark + 1; *q && *p == *q; p++, q++);
Eric Andersenc470f442003-07-28 09:56:35 +000010298 if (*p == '\n' && *q == '\0') {
10299 c = PEOF;
10300 plinno++;
10301 needprompt = doprompt;
10302 } else {
10303 pushstring(line, NULL);
Eric Andersencb57d552001-06-28 07:25:16 +000010304 }
10305 }
10306 }
10307 }
Eric Andersenc470f442003-07-28 09:56:35 +000010308 goto checkend_return;
10309}
Eric Andersencb57d552001-06-28 07:25:16 +000010310
Eric Andersencb57d552001-06-28 07:25:16 +000010311/*
10312 * Parse a redirection operator. The variable "out" points to a string
10313 * specifying the fd to be redirected. The variable "c" contains the
10314 * first character of the redirection operator.
10315 */
Eric Andersenc470f442003-07-28 09:56:35 +000010316parseredir: {
10317 char fd = *out;
10318 union node *np;
Eric Andersencb57d552001-06-28 07:25:16 +000010319
Denis Vlasenko597906c2008-02-20 16:38:54 +000010320 np = stzalloc(sizeof(struct nfile));
Eric Andersenc470f442003-07-28 09:56:35 +000010321 if (c == '>') {
10322 np->nfile.fd = 1;
10323 c = pgetc();
10324 if (c == '>')
10325 np->type = NAPPEND;
10326 else if (c == '|')
10327 np->type = NCLOBBER;
10328 else if (c == '&')
10329 np->type = NTOFD;
10330 else {
10331 np->type = NTO;
10332 pungetc();
Eric Andersencb57d552001-06-28 07:25:16 +000010333 }
Eric Andersenc470f442003-07-28 09:56:35 +000010334 } else { /* c == '<' */
Denis Vlasenko597906c2008-02-20 16:38:54 +000010335 /*np->nfile.fd = 0; - stzalloc did it */
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010336 c = pgetc();
10337 switch (c) {
Eric Andersenc470f442003-07-28 09:56:35 +000010338 case '<':
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010339 if (sizeof(struct nfile) != sizeof(struct nhere)) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010340 np = stzalloc(sizeof(struct nhere));
10341 /*np->nfile.fd = 0; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000010342 }
10343 np->type = NHERE;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010344 heredoc = stalloc(sizeof(struct heredoc));
Eric Andersenc470f442003-07-28 09:56:35 +000010345 heredoc->here = np;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010346 c = pgetc();
10347 if (c == '-') {
Eric Andersenc470f442003-07-28 09:56:35 +000010348 heredoc->striptabs = 1;
10349 } else {
10350 heredoc->striptabs = 0;
10351 pungetc();
10352 }
10353 break;
10354
10355 case '&':
10356 np->type = NFROMFD;
10357 break;
10358
10359 case '>':
10360 np->type = NFROMTO;
10361 break;
10362
10363 default:
10364 np->type = NFROM;
10365 pungetc();
10366 break;
10367 }
Eric Andersencb57d552001-06-28 07:25:16 +000010368 }
Eric Andersenc470f442003-07-28 09:56:35 +000010369 if (fd != '\0')
Denis Vlasenko4d2183b2007-02-23 01:05:38 +000010370 np->nfile.fd = fd - '0';
Eric Andersenc470f442003-07-28 09:56:35 +000010371 redirnode = np;
10372 goto parseredir_return;
10373}
Eric Andersencb57d552001-06-28 07:25:16 +000010374
Eric Andersencb57d552001-06-28 07:25:16 +000010375/*
10376 * Parse a substitution. At this point, we have read the dollar sign
10377 * and nothing else.
10378 */
Denis Vlasenkocc571512007-02-23 21:10:35 +000010379
10380/* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
10381 * (assuming ascii char codes, as the original implementation did) */
10382#define is_special(c) \
10383 ((((unsigned int)c) - 33 < 32) \
10384 && ((0xc1ff920dUL >> (((unsigned int)c) - 33)) & 1))
Eric Andersenc470f442003-07-28 09:56:35 +000010385parsesub: {
10386 int subtype;
10387 int typeloc;
10388 int flags;
10389 char *p;
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000010390 static const char types[] ALIGN1 = "}-+?=";
Eric Andersencb57d552001-06-28 07:25:16 +000010391
Eric Andersenc470f442003-07-28 09:56:35 +000010392 c = pgetc();
10393 if (
10394 c <= PEOA_OR_PEOF ||
10395 (c != '(' && c != '{' && !is_name(c) && !is_special(c))
10396 ) {
10397 USTPUTC('$', out);
10398 pungetc();
10399 } else if (c == '(') { /* $(command) or $((arith)) */
10400 if (pgetc() == '(') {
Denis Vlasenko131ae172007-02-18 13:00:19 +000010401#if ENABLE_ASH_MATH_SUPPORT
Eric Andersenc470f442003-07-28 09:56:35 +000010402 PARSEARITH();
10403#else
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010404 raise_error_syntax("We unsupport $((arith))");
Eric Andersenc470f442003-07-28 09:56:35 +000010405#endif
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010406 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000010407 pungetc();
10408 PARSEBACKQNEW();
10409 }
10410 } else {
10411 USTPUTC(CTLVAR, out);
10412 typeloc = out - (char *)stackblock();
10413 USTPUTC(VSNORMAL, out);
10414 subtype = VSNORMAL;
10415 if (c == '{') {
10416 c = pgetc();
10417 if (c == '#') {
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010418 c = pgetc();
10419 if (c == '}')
Eric Andersenc470f442003-07-28 09:56:35 +000010420 c = '#';
10421 else
10422 subtype = VSLENGTH;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010423 } else
Eric Andersenc470f442003-07-28 09:56:35 +000010424 subtype = 0;
10425 }
10426 if (c > PEOA_OR_PEOF && is_name(c)) {
10427 do {
10428 STPUTC(c, out);
Eric Andersencb57d552001-06-28 07:25:16 +000010429 c = pgetc();
Eric Andersenc470f442003-07-28 09:56:35 +000010430 } while (c > PEOA_OR_PEOF && is_in_name(c));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010431 } else if (isdigit(c)) {
Eric Andersenc470f442003-07-28 09:56:35 +000010432 do {
10433 STPUTC(c, out);
10434 c = pgetc();
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010435 } while (isdigit(c));
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010436 } else if (is_special(c)) {
Eric Andersenc470f442003-07-28 09:56:35 +000010437 USTPUTC(c, out);
10438 c = pgetc();
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010439 } else
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010440 badsub: raise_error_syntax("Bad substitution");
Eric Andersencb57d552001-06-28 07:25:16 +000010441
Eric Andersenc470f442003-07-28 09:56:35 +000010442 STPUTC('=', out);
10443 flags = 0;
10444 if (subtype == 0) {
10445 switch (c) {
10446 case ':':
10447 flags = VSNUL;
10448 c = pgetc();
10449 /*FALLTHROUGH*/
10450 default:
10451 p = strchr(types, c);
10452 if (p == NULL)
10453 goto badsub;
10454 subtype = p - types + VSNORMAL;
10455 break;
10456 case '%':
10457 case '#':
Eric Andersencb57d552001-06-28 07:25:16 +000010458 {
10459 int cc = c;
Eric Andersenc470f442003-07-28 09:56:35 +000010460 subtype = c == '#' ? VSTRIMLEFT :
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010461 VSTRIMRIGHT;
Eric Andersencb57d552001-06-28 07:25:16 +000010462 c = pgetc();
10463 if (c == cc)
10464 subtype++;
10465 else
10466 pungetc();
10467 break;
10468 }
10469 }
Eric Andersenc470f442003-07-28 09:56:35 +000010470 } else {
10471 pungetc();
10472 }
10473 if (dblquote || arinest)
10474 flags |= VSQUOTE;
10475 *((char *)stackblock() + typeloc) = subtype | flags;
10476 if (subtype != VSNORMAL) {
10477 varnest++;
10478 if (dblquote || arinest) {
10479 dqvarnest++;
Eric Andersencb57d552001-06-28 07:25:16 +000010480 }
10481 }
10482 }
Eric Andersenc470f442003-07-28 09:56:35 +000010483 goto parsesub_return;
10484}
Eric Andersencb57d552001-06-28 07:25:16 +000010485
Eric Andersencb57d552001-06-28 07:25:16 +000010486/*
10487 * Called to parse command substitutions. Newstyle is set if the command
10488 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
10489 * list of commands (passed by reference), and savelen is the number of
10490 * characters on the top of the stack which must be preserved.
10491 */
Eric Andersenc470f442003-07-28 09:56:35 +000010492parsebackq: {
10493 struct nodelist **nlpp;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010494 smallint savepbq;
Eric Andersenc470f442003-07-28 09:56:35 +000010495 union node *n;
10496 char *volatile str;
10497 struct jmploc jmploc;
10498 struct jmploc *volatile savehandler;
10499 size_t savelen;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010500 smallint saveprompt = 0;
10501
Eric Andersencb57d552001-06-28 07:25:16 +000010502#ifdef __GNUC__
Eric Andersenc470f442003-07-28 09:56:35 +000010503 (void) &saveprompt;
Eric Andersencb57d552001-06-28 07:25:16 +000010504#endif
Eric Andersenc470f442003-07-28 09:56:35 +000010505 savepbq = parsebackquote;
10506 if (setjmp(jmploc.loc)) {
Denis Vlasenko60818682007-09-28 22:07:23 +000010507 free(str);
Eric Andersenc470f442003-07-28 09:56:35 +000010508 parsebackquote = 0;
Denis Vlasenko2da584f2007-02-19 22:44:05 +000010509 exception_handler = savehandler;
10510 longjmp(exception_handler->loc, 1);
Eric Andersenc470f442003-07-28 09:56:35 +000010511 }
Denis Vlasenkob012b102007-02-19 22:43:01 +000010512 INT_OFF;
Eric Andersenc470f442003-07-28 09:56:35 +000010513 str = NULL;
10514 savelen = out - (char *)stackblock();
10515 if (savelen > 0) {
10516 str = ckmalloc(savelen);
10517 memcpy(str, stackblock(), savelen);
10518 }
Denis Vlasenko2da584f2007-02-19 22:44:05 +000010519 savehandler = exception_handler;
10520 exception_handler = &jmploc;
Denis Vlasenkob012b102007-02-19 22:43:01 +000010521 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +000010522 if (oldstyle) {
10523 /* We must read until the closing backquote, giving special
10524 treatment to some slashes, and then push the string and
10525 reread it as input, interpreting it normally. */
10526 char *pout;
10527 int pc;
10528 size_t psavelen;
10529 char *pstr;
10530
10531
10532 STARTSTACKSTR(pout);
10533 for (;;) {
10534 if (needprompt) {
10535 setprompt(2);
Eric Andersenc470f442003-07-28 09:56:35 +000010536 }
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010537 pc = pgetc();
10538 switch (pc) {
Eric Andersenc470f442003-07-28 09:56:35 +000010539 case '`':
10540 goto done;
10541
10542 case '\\':
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010543 pc = pgetc();
10544 if (pc == '\n') {
Eric Andersenc470f442003-07-28 09:56:35 +000010545 plinno++;
10546 if (doprompt)
10547 setprompt(2);
10548 /*
10549 * If eating a newline, avoid putting
10550 * the newline into the new character
10551 * stream (via the STPUTC after the
10552 * switch).
10553 */
10554 continue;
10555 }
10556 if (pc != '\\' && pc != '`' && pc != '$'
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010557 && (!dblquote || pc != '"'))
Eric Andersenc470f442003-07-28 09:56:35 +000010558 STPUTC('\\', pout);
10559 if (pc > PEOA_OR_PEOF) {
10560 break;
10561 }
10562 /* fall through */
10563
10564 case PEOF:
Denis Vlasenko131ae172007-02-18 13:00:19 +000010565#if ENABLE_ASH_ALIAS
Eric Andersenc470f442003-07-28 09:56:35 +000010566 case PEOA:
10567#endif
10568 startlinno = plinno;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010569 raise_error_syntax("EOF in backquote substitution");
Eric Andersenc470f442003-07-28 09:56:35 +000010570
10571 case '\n':
10572 plinno++;
10573 needprompt = doprompt;
10574 break;
10575
10576 default:
10577 break;
10578 }
10579 STPUTC(pc, pout);
10580 }
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010581 done:
Eric Andersenc470f442003-07-28 09:56:35 +000010582 STPUTC('\0', pout);
10583 psavelen = pout - (char *)stackblock();
10584 if (psavelen > 0) {
10585 pstr = grabstackstr(pout);
10586 setinputstring(pstr);
10587 }
10588 }
10589 nlpp = &bqlist;
10590 while (*nlpp)
10591 nlpp = &(*nlpp)->next;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010592 *nlpp = stzalloc(sizeof(**nlpp));
10593 /* (*nlpp)->next = NULL; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000010594 parsebackquote = oldstyle;
10595
10596 if (oldstyle) {
10597 saveprompt = doprompt;
10598 doprompt = 0;
Eric Andersencb57d552001-06-28 07:25:16 +000010599 }
10600
Eric Andersenc470f442003-07-28 09:56:35 +000010601 n = list(2);
10602
10603 if (oldstyle)
10604 doprompt = saveprompt;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010605 else if (readtoken() != TRP)
10606 raise_error_unexpected_syntax(TRP);
Eric Andersenc470f442003-07-28 09:56:35 +000010607
10608 (*nlpp)->n = n;
10609 if (oldstyle) {
10610 /*
10611 * Start reading from old file again, ignoring any pushed back
10612 * tokens left from the backquote parsing
10613 */
10614 popfile();
10615 tokpushback = 0;
10616 }
10617 while (stackblocksize() <= savelen)
10618 growstackblock();
10619 STARTSTACKSTR(out);
10620 if (str) {
10621 memcpy(out, str, savelen);
10622 STADJUST(savelen, out);
Denis Vlasenkob012b102007-02-19 22:43:01 +000010623 INT_OFF;
10624 free(str);
Eric Andersenc470f442003-07-28 09:56:35 +000010625 str = NULL;
Denis Vlasenkob012b102007-02-19 22:43:01 +000010626 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +000010627 }
10628 parsebackquote = savepbq;
Denis Vlasenko2da584f2007-02-19 22:44:05 +000010629 exception_handler = savehandler;
Eric Andersenc470f442003-07-28 09:56:35 +000010630 if (arinest || dblquote)
10631 USTPUTC(CTLBACKQ | CTLQUOTE, out);
10632 else
10633 USTPUTC(CTLBACKQ, out);
10634 if (oldstyle)
10635 goto parsebackq_oldreturn;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010636 goto parsebackq_newreturn;
Eric Andersenc470f442003-07-28 09:56:35 +000010637}
10638
Denis Vlasenko131ae172007-02-18 13:00:19 +000010639#if ENABLE_ASH_MATH_SUPPORT
Eric Andersencb57d552001-06-28 07:25:16 +000010640/*
10641 * Parse an arithmetic expansion (indicate start of one and set state)
10642 */
Eric Andersenc470f442003-07-28 09:56:35 +000010643parsearith: {
Eric Andersenc470f442003-07-28 09:56:35 +000010644 if (++arinest == 1) {
10645 prevsyntax = syntax;
10646 syntax = ARISYNTAX;
10647 USTPUTC(CTLARI, out);
10648 if (dblquote)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010649 USTPUTC('"', out);
Eric Andersenc470f442003-07-28 09:56:35 +000010650 else
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010651 USTPUTC(' ', out);
Eric Andersenc470f442003-07-28 09:56:35 +000010652 } else {
10653 /*
10654 * we collapse embedded arithmetic expansion to
10655 * parenthesis, which should be equivalent
10656 */
10657 USTPUTC('(', out);
Eric Andersencb57d552001-06-28 07:25:16 +000010658 }
Eric Andersenc470f442003-07-28 09:56:35 +000010659 goto parsearith_return;
10660}
10661#endif
Eric Andersencb57d552001-06-28 07:25:16 +000010662
Eric Andersenc470f442003-07-28 09:56:35 +000010663} /* end of readtoken */
10664
Eric Andersencb57d552001-06-28 07:25:16 +000010665/*
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010666 * Read the next input token.
10667 * If the token is a word, we set backquotelist to the list of cmds in
10668 * backquotes. We set quoteflag to true if any part of the word was
10669 * quoted.
10670 * If the token is TREDIR, then we set redirnode to a structure containing
10671 * the redirection.
10672 * In all cases, the variable startlinno is set to the number of the line
10673 * on which the token starts.
10674 *
10675 * [Change comment: here documents and internal procedures]
10676 * [Readtoken shouldn't have any arguments. Perhaps we should make the
10677 * word parsing code into a separate routine. In this case, readtoken
10678 * doesn't need to have any internal procedures, but parseword does.
10679 * We could also make parseoperator in essence the main routine, and
10680 * have parseword (readtoken1?) handle both words and redirection.]
Eric Andersencb57d552001-06-28 07:25:16 +000010681 */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010682#define NEW_xxreadtoken
10683#ifdef NEW_xxreadtoken
10684/* singles must be first! */
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000010685static const char xxreadtoken_chars[7] ALIGN1 = {
10686 '\n', '(', ')', '&', '|', ';', 0
10687};
Eric Andersencb57d552001-06-28 07:25:16 +000010688
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000010689static const char xxreadtoken_tokens[] ALIGN1 = {
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010690 TNL, TLP, TRP, /* only single occurrence allowed */
10691 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
10692 TEOF, /* corresponds to trailing nul */
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000010693 TAND, TOR, TENDCASE /* if double occurrence */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010694};
10695
10696#define xxreadtoken_doubles \
10697 (sizeof(xxreadtoken_tokens) - sizeof(xxreadtoken_chars))
10698#define xxreadtoken_singles \
10699 (sizeof(xxreadtoken_chars) - xxreadtoken_doubles - 1)
10700
10701static int
10702xxreadtoken(void)
10703{
10704 int c;
10705
10706 if (tokpushback) {
10707 tokpushback = 0;
10708 return lasttoken;
Eric Andersencb57d552001-06-28 07:25:16 +000010709 }
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010710 if (needprompt) {
10711 setprompt(2);
10712 }
10713 startlinno = plinno;
10714 for (;;) { /* until token or start of word found */
10715 c = pgetc_macro();
10716
10717 if ((c != ' ') && (c != '\t')
10718#if ENABLE_ASH_ALIAS
10719 && (c != PEOA)
10720#endif
10721 ) {
10722 if (c == '#') {
10723 while ((c = pgetc()) != '\n' && c != PEOF);
10724 pungetc();
10725 } else if (c == '\\') {
10726 if (pgetc() != '\n') {
10727 pungetc();
10728 goto READTOKEN1;
10729 }
10730 startlinno = ++plinno;
10731 if (doprompt)
10732 setprompt(2);
10733 } else {
10734 const char *p
10735 = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
10736
10737 if (c != PEOF) {
10738 if (c == '\n') {
10739 plinno++;
10740 needprompt = doprompt;
10741 }
10742
10743 p = strchr(xxreadtoken_chars, c);
10744 if (p == NULL) {
10745 READTOKEN1:
10746 return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
10747 }
10748
10749 if (p - xxreadtoken_chars >= xxreadtoken_singles) {
10750 if (pgetc() == *p) { /* double occurrence? */
10751 p += xxreadtoken_doubles + 1;
10752 } else {
10753 pungetc();
10754 }
10755 }
10756 }
10757 return lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
10758 }
10759 }
10760 } /* for */
10761}
10762#else
10763#define RETURN(token) return lasttoken = token
10764static int
10765xxreadtoken(void)
10766{
10767 int c;
10768
10769 if (tokpushback) {
10770 tokpushback = 0;
10771 return lasttoken;
10772 }
10773 if (needprompt) {
10774 setprompt(2);
10775 }
10776 startlinno = plinno;
10777 for (;;) { /* until token or start of word found */
10778 c = pgetc_macro();
10779 switch (c) {
10780 case ' ': case '\t':
10781#if ENABLE_ASH_ALIAS
10782 case PEOA:
10783#endif
10784 continue;
10785 case '#':
10786 while ((c = pgetc()) != '\n' && c != PEOF);
10787 pungetc();
10788 continue;
10789 case '\\':
10790 if (pgetc() == '\n') {
10791 startlinno = ++plinno;
10792 if (doprompt)
10793 setprompt(2);
10794 continue;
10795 }
10796 pungetc();
10797 goto breakloop;
10798 case '\n':
10799 plinno++;
10800 needprompt = doprompt;
10801 RETURN(TNL);
10802 case PEOF:
10803 RETURN(TEOF);
10804 case '&':
10805 if (pgetc() == '&')
10806 RETURN(TAND);
10807 pungetc();
10808 RETURN(TBACKGND);
10809 case '|':
10810 if (pgetc() == '|')
10811 RETURN(TOR);
10812 pungetc();
10813 RETURN(TPIPE);
10814 case ';':
10815 if (pgetc() == ';')
10816 RETURN(TENDCASE);
10817 pungetc();
10818 RETURN(TSEMI);
10819 case '(':
10820 RETURN(TLP);
10821 case ')':
10822 RETURN(TRP);
10823 default:
10824 goto breakloop;
10825 }
10826 }
10827 breakloop:
10828 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
10829#undef RETURN
10830}
10831#endif /* NEW_xxreadtoken */
10832
10833static int
10834readtoken(void)
10835{
10836 int t;
10837#if DEBUG
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010838 smallint alreadyseen = tokpushback;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010839#endif
10840
10841#if ENABLE_ASH_ALIAS
10842 top:
10843#endif
10844
10845 t = xxreadtoken();
10846
10847 /*
10848 * eat newlines
10849 */
10850 if (checkkwd & CHKNL) {
10851 while (t == TNL) {
10852 parseheredoc();
10853 t = xxreadtoken();
10854 }
10855 }
10856
10857 if (t != TWORD || quoteflag) {
10858 goto out;
10859 }
10860
10861 /*
10862 * check for keywords
10863 */
10864 if (checkkwd & CHKKWD) {
10865 const char *const *pp;
10866
10867 pp = findkwd(wordtext);
10868 if (pp) {
10869 lasttoken = t = pp - tokname_array;
10870 TRACE(("keyword %s recognized\n", tokname(t)));
10871 goto out;
10872 }
10873 }
10874
10875 if (checkkwd & CHKALIAS) {
10876#if ENABLE_ASH_ALIAS
10877 struct alias *ap;
10878 ap = lookupalias(wordtext, 1);
10879 if (ap != NULL) {
10880 if (*ap->val) {
10881 pushstring(ap->val, ap);
10882 }
10883 goto top;
10884 }
10885#endif
10886 }
10887 out:
10888 checkkwd = 0;
10889#if DEBUG
10890 if (!alreadyseen)
10891 TRACE(("token %s %s\n", tokname(t), t == TWORD ? wordtext : ""));
10892 else
10893 TRACE(("reread token %s %s\n", tokname(t), t == TWORD ? wordtext : ""));
10894#endif
10895 return t;
Eric Andersencb57d552001-06-28 07:25:16 +000010896}
10897
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010898static char
10899peektoken(void)
10900{
10901 int t;
10902
10903 t = readtoken();
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010904 tokpushback = 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010905 return tokname_array[t][0];
10906}
Eric Andersencb57d552001-06-28 07:25:16 +000010907
10908/*
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010909 * Read and parse a command. Returns NEOF on end of file. (NULL is a
10910 * valid parse tree indicating a blank line.)
Eric Andersencb57d552001-06-28 07:25:16 +000010911 */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010912static union node *
10913parsecmd(int interact)
Eric Andersen90898442003-08-06 11:20:52 +000010914{
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010915 int t;
Eric Andersencb57d552001-06-28 07:25:16 +000010916
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010917 tokpushback = 0;
10918 doprompt = interact;
10919 if (doprompt)
10920 setprompt(doprompt);
10921 needprompt = 0;
10922 t = readtoken();
10923 if (t == TEOF)
10924 return NEOF;
10925 if (t == TNL)
10926 return NULL;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010927 tokpushback = 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010928 return list(1);
10929}
10930
10931/*
10932 * Input any here documents.
10933 */
10934static void
10935parseheredoc(void)
10936{
10937 struct heredoc *here;
10938 union node *n;
10939
10940 here = heredoclist;
10941 heredoclist = 0;
10942
10943 while (here) {
10944 if (needprompt) {
10945 setprompt(2);
10946 }
10947 readtoken1(pgetc(), here->here->type == NHERE? SQSYNTAX : DQSYNTAX,
10948 here->eofmark, here->striptabs);
Denis Vlasenko597906c2008-02-20 16:38:54 +000010949 n = stzalloc(sizeof(struct narg));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010950 n->narg.type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010951 /*n->narg.next = NULL; - stzalloc did it */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010952 n->narg.text = wordtext;
10953 n->narg.backquote = backquotelist;
10954 here->here->nhere.doc = n;
10955 here = here->next;
Eric Andersencb57d552001-06-28 07:25:16 +000010956 }
Eric Andersencb57d552001-06-28 07:25:16 +000010957}
10958
10959
10960/*
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +000010961 * called by editline -- any expansions to the prompt should be added here.
Eric Andersencb57d552001-06-28 07:25:16 +000010962 */
Denis Vlasenko131ae172007-02-18 13:00:19 +000010963#if ENABLE_ASH_EXPAND_PRMT
"Vladimir N. Oleynik"bef14d72005-09-05 13:25:11 +000010964static const char *
10965expandstr(const char *ps)
10966{
10967 union node n;
10968
10969 /* XXX Fix (char *) cast. */
10970 setinputstring((char *)ps);
Denis Vlasenko46a53062007-09-24 18:30:02 +000010971 readtoken1(pgetc(), PSSYNTAX, nullstr, 0);
"Vladimir N. Oleynik"bef14d72005-09-05 13:25:11 +000010972 popfile();
10973
10974 n.narg.type = NARG;
10975 n.narg.next = NULL;
10976 n.narg.text = wordtext;
10977 n.narg.backquote = backquotelist;
10978
10979 expandarg(&n, NULL, 0);
10980 return stackblock();
10981}
10982#endif
10983
Denis Vlasenko0c032a42007-02-23 01:03:40 +000010984/*
10985 * Execute a command or commands contained in a string.
10986 */
10987static int
10988evalstring(char *s, int mask)
Eric Andersenc470f442003-07-28 09:56:35 +000010989{
Denis Vlasenko0c032a42007-02-23 01:03:40 +000010990 union node *n;
10991 struct stackmark smark;
10992 int skip;
10993
10994 setinputstring(s);
10995 setstackmark(&smark);
10996
10997 skip = 0;
10998 while ((n = parsecmd(0)) != NEOF) {
10999 evaltree(n, 0);
11000 popstackmark(&smark);
11001 skip = evalskip;
11002 if (skip)
11003 break;
11004 }
11005 popfile();
11006
11007 skip &= mask;
11008 evalskip = skip;
11009 return skip;
Eric Andersenc470f442003-07-28 09:56:35 +000011010}
11011
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011012/*
11013 * The eval command.
11014 */
11015static int
11016evalcmd(int argc, char **argv)
11017{
11018 char *p;
11019 char *concat;
11020 char **ap;
11021
11022 if (argc > 1) {
11023 p = argv[1];
11024 if (argc > 2) {
11025 STARTSTACKSTR(concat);
11026 ap = argv + 2;
11027 for (;;) {
11028 concat = stack_putstr(p, concat);
11029 p = *ap++;
11030 if (p == NULL)
11031 break;
11032 STPUTC(' ', concat);
11033 }
11034 STPUTC('\0', concat);
11035 p = grabstackstr(concat);
11036 }
11037 evalstring(p, ~SKIPEVAL);
11038
11039 }
11040 return exitstatus;
11041}
11042
11043/*
11044 * Read and execute commands. "Top" is nonzero for the top level command
11045 * loop; it turns on prompting if the shell is interactive.
11046 */
11047static int
11048cmdloop(int top)
11049{
11050 union node *n;
11051 struct stackmark smark;
11052 int inter;
11053 int numeof = 0;
11054
11055 TRACE(("cmdloop(%d) called\n", top));
11056 for (;;) {
11057 int skip;
11058
11059 setstackmark(&smark);
11060#if JOBS
11061 if (jobctl)
11062 showjobs(stderr, SHOW_CHANGED);
11063#endif
11064 inter = 0;
11065 if (iflag && top) {
11066 inter++;
11067#if ENABLE_ASH_MAIL
11068 chkmail();
11069#endif
11070 }
11071 n = parsecmd(inter);
11072 /* showtree(n); DEBUG */
11073 if (n == NEOF) {
11074 if (!top || numeof >= 50)
11075 break;
11076 if (!stoppedjobs()) {
11077 if (!Iflag)
11078 break;
11079 out2str("\nUse \"exit\" to leave shell.\n");
11080 }
11081 numeof++;
11082 } else if (nflag == 0) {
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +000011083 /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
11084 job_warning >>= 1;
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011085 numeof = 0;
11086 evaltree(n, 0);
11087 }
11088 popstackmark(&smark);
11089 skip = evalskip;
11090
11091 if (skip) {
11092 evalskip = 0;
11093 return skip & SKIPEVAL;
11094 }
11095 }
11096 return 0;
11097}
11098
Denis Vlasenko0dec6de2007-02-23 21:10:47 +000011099/*
11100 * Take commands from a file. To be compatible we should do a path
11101 * search for the file, which is necessary to find sub-commands.
11102 */
11103static char *
11104find_dot_file(char *name)
11105{
11106 char *fullname;
11107 const char *path = pathval();
11108 struct stat statb;
11109
11110 /* don't try this for absolute or relative paths */
11111 if (strchr(name, '/'))
11112 return name;
11113
11114 while ((fullname = padvance(&path, name)) != NULL) {
11115 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
11116 /*
11117 * Don't bother freeing here, since it will
11118 * be freed by the caller.
11119 */
11120 return fullname;
11121 }
11122 stunalloc(fullname);
11123 }
11124
11125 /* not found in the PATH */
11126 ash_msg_and_raise_error("%s: not found", name);
11127 /* NOTREACHED */
11128}
11129
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011130static int
11131dotcmd(int argc, char **argv)
11132{
11133 struct strlist *sp;
11134 volatile struct shparam saveparam;
11135 int status = 0;
11136
11137 for (sp = cmdenviron; sp; sp = sp->next)
Denis Vlasenko4222ae42007-02-25 02:37:49 +000011138 setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011139
11140 if (argc >= 2) { /* That's what SVR2 does */
11141 char *fullname;
11142
11143 fullname = find_dot_file(argv[1]);
11144
11145 if (argc > 2) {
11146 saveparam = shellparam;
Denis Vlasenko01631112007-12-16 17:20:38 +000011147 shellparam.malloced = 0;
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011148 shellparam.nparam = argc - 2;
11149 shellparam.p = argv + 2;
11150 };
11151
11152 setinputfile(fullname, INPUT_PUSH_FILE);
11153 commandname = fullname;
11154 cmdloop(0);
11155 popfile();
11156
11157 if (argc > 2) {
11158 freeparam(&shellparam);
11159 shellparam = saveparam;
11160 };
11161 status = exitstatus;
11162 }
11163 return status;
11164}
11165
11166static int
11167exitcmd(int argc, char **argv)
11168{
11169 if (stoppedjobs())
11170 return 0;
11171 if (argc > 1)
11172 exitstatus = number(argv[1]);
11173 raise_exception(EXEXIT);
11174 /* NOTREACHED */
11175}
11176
11177#if ENABLE_ASH_BUILTIN_ECHO
11178static int
11179echocmd(int argc, char **argv)
11180{
Denis Vlasenkofe5e23b2007-11-24 02:23:51 +000011181 return echo_main(argc, argv);
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011182}
11183#endif
11184
11185#if ENABLE_ASH_BUILTIN_TEST
11186static int
11187testcmd(int argc, char **argv)
11188{
Denis Vlasenkob304ead2007-06-21 13:35:52 +000011189 return test_main(argc, argv);
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011190}
11191#endif
11192
11193/*
11194 * Read a file containing shell functions.
11195 */
11196static void
11197readcmdfile(char *name)
11198{
11199 setinputfile(name, INPUT_PUSH_FILE);
11200 cmdloop(0);
11201 popfile();
11202}
11203
11204
Denis Vlasenkocc571512007-02-23 21:10:35 +000011205/* ============ find_command inplementation */
11206
11207/*
11208 * Resolve a command name. If you change this routine, you may have to
11209 * change the shellexec routine as well.
11210 */
11211static void
11212find_command(char *name, struct cmdentry *entry, int act, const char *path)
11213{
11214 struct tblentry *cmdp;
11215 int idx;
11216 int prev;
11217 char *fullname;
11218 struct stat statb;
11219 int e;
11220 int updatetbl;
11221 struct builtincmd *bcmd;
11222
11223 /* If name contains a slash, don't use PATH or hash table */
11224 if (strchr(name, '/') != NULL) {
11225 entry->u.index = -1;
11226 if (act & DO_ABS) {
11227 while (stat(name, &statb) < 0) {
11228#ifdef SYSV
11229 if (errno == EINTR)
11230 continue;
11231#endif
11232 entry->cmdtype = CMDUNKNOWN;
11233 return;
11234 }
11235 }
11236 entry->cmdtype = CMDNORMAL;
11237 return;
11238 }
11239
Denis Vlasenkof20de5b2007-04-29 23:42:54 +000011240/* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
Denis Vlasenkocc571512007-02-23 21:10:35 +000011241
11242 updatetbl = (path == pathval());
11243 if (!updatetbl) {
11244 act |= DO_ALTPATH;
11245 if (strstr(path, "%builtin") != NULL)
11246 act |= DO_ALTBLTIN;
11247 }
11248
11249 /* If name is in the table, check answer will be ok */
11250 cmdp = cmdlookup(name, 0);
11251 if (cmdp != NULL) {
11252 int bit;
11253
11254 switch (cmdp->cmdtype) {
11255 default:
11256#if DEBUG
11257 abort();
11258#endif
11259 case CMDNORMAL:
11260 bit = DO_ALTPATH;
11261 break;
11262 case CMDFUNCTION:
11263 bit = DO_NOFUNC;
11264 break;
11265 case CMDBUILTIN:
11266 bit = DO_ALTBLTIN;
11267 break;
11268 }
11269 if (act & bit) {
11270 updatetbl = 0;
11271 cmdp = NULL;
11272 } else if (cmdp->rehash == 0)
11273 /* if not invalidated by cd, we're done */
11274 goto success;
11275 }
11276
11277 /* If %builtin not in path, check for builtin next */
11278 bcmd = find_builtin(name);
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +000011279 if (bcmd) {
11280 if (IS_BUILTIN_REGULAR(bcmd))
11281 goto builtin_success;
11282 if (act & DO_ALTPATH) {
11283 if (!(act & DO_ALTBLTIN))
11284 goto builtin_success;
11285 } else if (builtinloc <= 0) {
11286 goto builtin_success;
Denis Vlasenko8e858e22007-03-07 09:35:43 +000011287 }
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +000011288 }
Denis Vlasenkocc571512007-02-23 21:10:35 +000011289
Denis Vlasenkof20de5b2007-04-29 23:42:54 +000011290#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko1aa7e472007-11-28 06:49:03 +000011291 if (find_applet_by_name(name) >= 0) {
Denis Vlasenkof20de5b2007-04-29 23:42:54 +000011292 entry->cmdtype = CMDNORMAL;
11293 entry->u.index = -1;
11294 return;
11295 }
11296#endif
11297
Denis Vlasenkocc571512007-02-23 21:10:35 +000011298 /* We have to search path. */
11299 prev = -1; /* where to start */
11300 if (cmdp && cmdp->rehash) { /* doing a rehash */
11301 if (cmdp->cmdtype == CMDBUILTIN)
11302 prev = builtinloc;
11303 else
11304 prev = cmdp->param.index;
11305 }
11306
11307 e = ENOENT;
11308 idx = -1;
11309 loop:
11310 while ((fullname = padvance(&path, name)) != NULL) {
11311 stunalloc(fullname);
Denis Vlasenkodee82b62007-07-29 14:05:27 +000011312 /* NB: code below will still use fullname
11313 * despite it being "unallocated" */
Denis Vlasenkocc571512007-02-23 21:10:35 +000011314 idx++;
11315 if (pathopt) {
11316 if (prefix(pathopt, "builtin")) {
11317 if (bcmd)
11318 goto builtin_success;
11319 continue;
Denis Vlasenkodee82b62007-07-29 14:05:27 +000011320 } else if (!(act & DO_NOFUNC)
11321 && prefix(pathopt, "func")) {
Denis Vlasenkocc571512007-02-23 21:10:35 +000011322 /* handled below */
11323 } else {
11324 /* ignore unimplemented options */
11325 continue;
11326 }
11327 }
11328 /* if rehash, don't redo absolute path names */
11329 if (fullname[0] == '/' && idx <= prev) {
11330 if (idx < prev)
11331 continue;
11332 TRACE(("searchexec \"%s\": no change\n", name));
11333 goto success;
11334 }
11335 while (stat(fullname, &statb) < 0) {
11336#ifdef SYSV
11337 if (errno == EINTR)
11338 continue;
11339#endif
11340 if (errno != ENOENT && errno != ENOTDIR)
11341 e = errno;
11342 goto loop;
11343 }
11344 e = EACCES; /* if we fail, this will be the error */
11345 if (!S_ISREG(statb.st_mode))
11346 continue;
11347 if (pathopt) { /* this is a %func directory */
11348 stalloc(strlen(fullname) + 1);
Denis Vlasenkodee82b62007-07-29 14:05:27 +000011349 /* NB: stalloc will return space pointed by fullname
11350 * (because we don't have any intervening allocations
11351 * between stunalloc above and this stalloc) */
Denis Vlasenkocc571512007-02-23 21:10:35 +000011352 readcmdfile(fullname);
11353 cmdp = cmdlookup(name, 0);
11354 if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
11355 ash_msg_and_raise_error("%s not defined in %s", name, fullname);
11356 stunalloc(fullname);
11357 goto success;
11358 }
11359 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
11360 if (!updatetbl) {
11361 entry->cmdtype = CMDNORMAL;
11362 entry->u.index = idx;
11363 return;
11364 }
11365 INT_OFF;
11366 cmdp = cmdlookup(name, 1);
11367 cmdp->cmdtype = CMDNORMAL;
11368 cmdp->param.index = idx;
11369 INT_ON;
11370 goto success;
11371 }
11372
11373 /* We failed. If there was an entry for this command, delete it */
11374 if (cmdp && updatetbl)
11375 delete_cmd_entry();
11376 if (act & DO_ERR)
11377 ash_msg("%s: %s", name, errmsg(e, "not found"));
11378 entry->cmdtype = CMDUNKNOWN;
11379 return;
11380
11381 builtin_success:
11382 if (!updatetbl) {
11383 entry->cmdtype = CMDBUILTIN;
11384 entry->u.cmd = bcmd;
11385 return;
11386 }
11387 INT_OFF;
11388 cmdp = cmdlookup(name, 1);
11389 cmdp->cmdtype = CMDBUILTIN;
11390 cmdp->param.cmd = bcmd;
11391 INT_ON;
11392 success:
11393 cmdp->rehash = 0;
11394 entry->cmdtype = cmdp->cmdtype;
11395 entry->u = cmdp->param;
11396}
11397
11398
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000011399/* ============ trap.c */
Eric Andersenc470f442003-07-28 09:56:35 +000011400
Eric Andersencb57d552001-06-28 07:25:16 +000011401/*
Eric Andersencb57d552001-06-28 07:25:16 +000011402 * The trap builtin.
11403 */
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011404static int
Eric Andersenc470f442003-07-28 09:56:35 +000011405trapcmd(int argc, char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +000011406{
11407 char *action;
11408 char **ap;
11409 int signo;
11410
Eric Andersenc470f442003-07-28 09:56:35 +000011411 nextopt(nullstr);
11412 ap = argptr;
11413 if (!*ap) {
Denis Vlasenko2da584f2007-02-19 22:44:05 +000011414 for (signo = 0; signo < NSIG; signo++) {
Eric Andersencb57d552001-06-28 07:25:16 +000011415 if (trap[signo] != NULL) {
Eric Andersen34506362001-08-02 05:02:46 +000011416 const char *sn;
Eric Andersencb57d552001-06-28 07:25:16 +000011417
Rob Landleyc9c1a412006-07-12 19:17:55 +000011418 sn = get_signame(signo);
Eric Andersenc470f442003-07-28 09:56:35 +000011419 out1fmt("trap -- %s %s\n",
11420 single_quote(trap[signo]), sn);
Eric Andersencb57d552001-06-28 07:25:16 +000011421 }
11422 }
11423 return 0;
11424 }
Eric Andersenc470f442003-07-28 09:56:35 +000011425 if (!ap[1])
Eric Andersencb57d552001-06-28 07:25:16 +000011426 action = NULL;
11427 else
11428 action = *ap++;
11429 while (*ap) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011430 signo = get_signum(*ap);
11431 if (signo < 0)
Denis Vlasenkob012b102007-02-19 22:43:01 +000011432 ash_msg_and_raise_error("%s: bad trap", *ap);
11433 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +000011434 if (action) {
Denis Vlasenko9f739442006-12-16 23:49:13 +000011435 if (LONE_DASH(action))
Eric Andersencb57d552001-06-28 07:25:16 +000011436 action = NULL;
11437 else
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011438 action = ckstrdup(action);
Eric Andersencb57d552001-06-28 07:25:16 +000011439 }
Denis Vlasenko60818682007-09-28 22:07:23 +000011440 free(trap[signo]);
Eric Andersencb57d552001-06-28 07:25:16 +000011441 trap[signo] = action;
11442 if (signo != 0)
11443 setsignal(signo);
Denis Vlasenkob012b102007-02-19 22:43:01 +000011444 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +000011445 ap++;
11446 }
11447 return 0;
11448}
11449
Eric Andersenc470f442003-07-28 09:56:35 +000011450
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000011451/* ============ Builtins */
Eric Andersenc470f442003-07-28 09:56:35 +000011452
Denis Vlasenko8e1c7152007-01-22 07:21:38 +000011453#if !ENABLE_FEATURE_SH_EXTRA_QUIET
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000011454/*
11455 * Lists available builtins
11456 */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011457static int
11458helpcmd(int argc, char **argv)
Eric Andersenc470f442003-07-28 09:56:35 +000011459{
11460 int col, i;
11461
11462 out1fmt("\nBuilt-in commands:\n-------------------\n");
Denis Vlasenkob71c6682007-07-21 15:08:09 +000011463 for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
Eric Andersenc470f442003-07-28 09:56:35 +000011464 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
Denis Vlasenko52764022007-02-24 13:42:56 +000011465 builtintab[i].name + 1);
Eric Andersenc470f442003-07-28 09:56:35 +000011466 if (col > 60) {
11467 out1fmt("\n");
11468 col = 0;
11469 }
11470 }
Denis Vlasenko80d14be2007-04-10 23:03:30 +000011471#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko1aa7e472007-11-28 06:49:03 +000011472 {
11473 const char *a = applet_names;
11474 while (*a) {
11475 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
11476 if (col > 60) {
11477 out1fmt("\n");
11478 col = 0;
11479 }
11480 a += strlen(a) + 1;
Eric Andersenc470f442003-07-28 09:56:35 +000011481 }
11482 }
11483#endif
11484 out1fmt("\n\n");
11485 return EXIT_SUCCESS;
11486}
Denis Vlasenko131ae172007-02-18 13:00:19 +000011487#endif /* FEATURE_SH_EXTRA_QUIET */
Eric Andersenc470f442003-07-28 09:56:35 +000011488
Eric Andersencb57d552001-06-28 07:25:16 +000011489/*
Eric Andersencb57d552001-06-28 07:25:16 +000011490 * The export and readonly commands.
11491 */
Eric Andersenc470f442003-07-28 09:56:35 +000011492static int
11493exportcmd(int argc, char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +000011494{
11495 struct var *vp;
11496 char *name;
11497 const char *p;
Eric Andersenc470f442003-07-28 09:56:35 +000011498 char **aptr;
11499 int flag = argv[0][0] == 'r'? VREADONLY : VEXPORT;
Eric Andersencb57d552001-06-28 07:25:16 +000011500
Denis Vlasenko2da584f2007-02-19 22:44:05 +000011501 if (nextopt("p") != 'p') {
11502 aptr = argptr;
11503 name = *aptr;
11504 if (name) {
11505 do {
11506 p = strchr(name, '=');
11507 if (p != NULL) {
11508 p++;
11509 } else {
11510 vp = *findvar(hashvar(name), name);
11511 if (vp) {
11512 vp->flags |= flag;
11513 continue;
11514 }
Eric Andersencb57d552001-06-28 07:25:16 +000011515 }
Denis Vlasenko2da584f2007-02-19 22:44:05 +000011516 setvar(name, p, flag);
11517 } while ((name = *++aptr) != NULL);
11518 return 0;
11519 }
Eric Andersencb57d552001-06-28 07:25:16 +000011520 }
Denis Vlasenko2da584f2007-02-19 22:44:05 +000011521 showvars(argv[0], flag, 0);
Eric Andersencb57d552001-06-28 07:25:16 +000011522 return 0;
11523}
11524
Eric Andersencb57d552001-06-28 07:25:16 +000011525/*
Denis Vlasenko5651bfc2007-02-23 21:08:58 +000011526 * Delete a function if it exists.
Eric Andersencb57d552001-06-28 07:25:16 +000011527 */
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000011528static void
Denis Vlasenko5651bfc2007-02-23 21:08:58 +000011529unsetfunc(const char *name)
Aaron Lehmannb6ecbdc2001-12-06 03:37:38 +000011530{
Denis Vlasenko5651bfc2007-02-23 21:08:58 +000011531 struct tblentry *cmdp;
Eric Andersencb57d552001-06-28 07:25:16 +000011532
Denis Vlasenko5651bfc2007-02-23 21:08:58 +000011533 cmdp = cmdlookup(name, 0);
11534 if (cmdp!= NULL && cmdp->cmdtype == CMDFUNCTION)
11535 delete_cmd_entry();
Eric Andersenc470f442003-07-28 09:56:35 +000011536}
11537
Eric Andersencb57d552001-06-28 07:25:16 +000011538/*
Eric Andersencb57d552001-06-28 07:25:16 +000011539 * The unset builtin command. We unset the function before we unset the
11540 * variable to allow a function to be unset when there is a readonly variable
11541 * with the same name.
11542 */
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011543static int
Eric Andersenc470f442003-07-28 09:56:35 +000011544unsetcmd(int argc, char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +000011545{
11546 char **ap;
11547 int i;
Eric Andersenc470f442003-07-28 09:56:35 +000011548 int flag = 0;
Eric Andersencb57d552001-06-28 07:25:16 +000011549 int ret = 0;
11550
11551 while ((i = nextopt("vf")) != '\0') {
Eric Andersenc470f442003-07-28 09:56:35 +000011552 flag = i;
Eric Andersencb57d552001-06-28 07:25:16 +000011553 }
Eric Andersencb57d552001-06-28 07:25:16 +000011554
Denis Vlasenko2da584f2007-02-19 22:44:05 +000011555 for (ap = argptr; *ap; ap++) {
Eric Andersenc470f442003-07-28 09:56:35 +000011556 if (flag != 'f') {
11557 i = unsetvar(*ap);
11558 ret |= i;
11559 if (!(i & 2))
11560 continue;
11561 }
11562 if (flag != 'v')
Eric Andersencb57d552001-06-28 07:25:16 +000011563 unsetfunc(*ap);
Eric Andersencb57d552001-06-28 07:25:16 +000011564 }
Eric Andersenc470f442003-07-28 09:56:35 +000011565 return ret & 1;
Eric Andersencb57d552001-06-28 07:25:16 +000011566}
11567
11568
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +000011569/* setmode.c */
Eric Andersencb57d552001-06-28 07:25:16 +000011570
Eric Andersenc470f442003-07-28 09:56:35 +000011571#include <sys/times.h>
11572
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011573static const unsigned char timescmd_str[] ALIGN1 = {
Manuel Novoa III 4456f252003-08-13 17:48:47 +000011574 ' ', offsetof(struct tms, tms_utime),
11575 '\n', offsetof(struct tms, tms_stime),
11576 ' ', offsetof(struct tms, tms_cutime),
11577 '\n', offsetof(struct tms, tms_cstime),
11578 0
11579};
Eric Andersencb57d552001-06-28 07:25:16 +000011580
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000011581static int
11582timescmd(int ac, char **av)
Manuel Novoa III 4456f252003-08-13 17:48:47 +000011583{
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000011584 long clk_tck, s, t;
Manuel Novoa III 4456f252003-08-13 17:48:47 +000011585 const unsigned char *p;
11586 struct tms buf;
11587
11588 clk_tck = sysconf(_SC_CLK_TCK);
Eric Andersencb57d552001-06-28 07:25:16 +000011589 times(&buf);
Manuel Novoa III 4456f252003-08-13 17:48:47 +000011590
11591 p = timescmd_str;
11592 do {
11593 t = *(clock_t *)(((char *) &buf) + p[1]);
11594 s = t / clk_tck;
11595 out1fmt("%ldm%ld.%.3lds%c",
11596 s/60, s%60,
11597 ((t - s * clk_tck) * 1000) / clk_tck,
11598 p[0]);
11599 } while (*(p += 2));
11600
Eric Andersencb57d552001-06-28 07:25:16 +000011601 return 0;
11602}
11603
Denis Vlasenko131ae172007-02-18 13:00:19 +000011604#if ENABLE_ASH_MATH_SUPPORT
Eric Andersened9ecf72004-06-22 08:29:45 +000011605static arith_t
Eric Andersenc470f442003-07-28 09:56:35 +000011606dash_arith(const char *s)
Eric Andersen74bcd162001-07-30 21:41:37 +000011607{
Eric Andersened9ecf72004-06-22 08:29:45 +000011608 arith_t result;
Eric Andersenc470f442003-07-28 09:56:35 +000011609 int errcode = 0;
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000011610
Denis Vlasenkob012b102007-02-19 22:43:01 +000011611 INT_OFF;
Eric Andersenc470f442003-07-28 09:56:35 +000011612 result = arith(s, &errcode);
11613 if (errcode < 0) {
Eric Andersen90898442003-08-06 11:20:52 +000011614 if (errcode == -3)
Denis Vlasenkob012b102007-02-19 22:43:01 +000011615 ash_msg_and_raise_error("exponent less than 0");
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000011616 if (errcode == -2)
Denis Vlasenkob012b102007-02-19 22:43:01 +000011617 ash_msg_and_raise_error("divide by zero");
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000011618 if (errcode == -5)
Denis Vlasenkob012b102007-02-19 22:43:01 +000011619 ash_msg_and_raise_error("expression recursion loop detected");
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000011620 raise_error_syntax(s);
Eric Andersenc470f442003-07-28 09:56:35 +000011621 }
Denis Vlasenkob012b102007-02-19 22:43:01 +000011622 INT_ON;
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000011623
Denis Vlasenkod9e15f22006-11-27 16:49:55 +000011624 return result;
Eric Andersen74bcd162001-07-30 21:41:37 +000011625}
Eric Andersenc470f442003-07-28 09:56:35 +000011626
Eric Andersenc470f442003-07-28 09:56:35 +000011627/*
Eric Andersen90898442003-08-06 11:20:52 +000011628 * The let builtin. partial stolen from GNU Bash, the Bourne Again SHell.
11629 * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
11630 *
11631 * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
Eric Andersenc470f442003-07-28 09:56:35 +000011632 */
11633static int
Eric Andersen90898442003-08-06 11:20:52 +000011634letcmd(int argc, char **argv)
Eric Andersenc470f442003-07-28 09:56:35 +000011635{
Eric Andersenc470f442003-07-28 09:56:35 +000011636 char **ap;
Denis Vlasenkocba9ef52006-10-10 21:00:47 +000011637 arith_t i = 0;
Eric Andersenc470f442003-07-28 09:56:35 +000011638
Eric Andersen90898442003-08-06 11:20:52 +000011639 ap = argv + 1;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000011640 if (!*ap)
Denis Vlasenkob012b102007-02-19 22:43:01 +000011641 ash_msg_and_raise_error("expression expected");
Eric Andersen90898442003-08-06 11:20:52 +000011642 for (ap = argv + 1; *ap; ap++) {
11643 i = dash_arith(*ap);
11644 }
Eric Andersenc470f442003-07-28 09:56:35 +000011645
Denis Vlasenkod9e15f22006-11-27 16:49:55 +000011646 return !i;
Eric Andersenc470f442003-07-28 09:56:35 +000011647}
Denis Vlasenko131ae172007-02-18 13:00:19 +000011648#endif /* ASH_MATH_SUPPORT */
Eric Andersenc470f442003-07-28 09:56:35 +000011649
Eric Andersenc470f442003-07-28 09:56:35 +000011650
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000011651/* ============ miscbltin.c
11652 *
Eric Andersenaff114c2004-04-14 17:51:38 +000011653 * Miscellaneous builtins.
Eric Andersenc470f442003-07-28 09:56:35 +000011654 */
11655
11656#undef rflag
11657
Denis Vlasenko83e5d6f2006-12-18 21:49:06 +000011658#if defined(__GLIBC__) && __GLIBC__ == 2 && __GLIBC_MINOR__ < 1
Eric Andersenc470f442003-07-28 09:56:35 +000011659typedef enum __rlimit_resource rlim_t;
11660#endif
Eric Andersen74bcd162001-07-30 21:41:37 +000011661
Eric Andersenc470f442003-07-28 09:56:35 +000011662/*
11663 * The read builtin. The -e option causes backslashes to escape the
11664 * following character.
11665 *
11666 * This uses unbuffered input, which may be avoidable in some cases.
11667 */
Eric Andersenc470f442003-07-28 09:56:35 +000011668static int
11669readcmd(int argc, char **argv)
11670{
11671 char **ap;
11672 int backslash;
11673 char c;
11674 int rflag;
11675 char *prompt;
11676 const char *ifs;
11677 char *p;
11678 int startword;
11679 int status;
11680 int i;
Denis Vlasenko131ae172007-02-18 13:00:19 +000011681#if ENABLE_ASH_READ_NCHARS
Denis Vlasenko037576d2007-10-20 18:30:38 +000011682 int n_flag = 0;
Paul Fox02eb9342005-09-07 16:56:02 +000011683 int nchars = 0;
11684 int silent = 0;
11685 struct termios tty, old_tty;
11686#endif
Denis Vlasenko131ae172007-02-18 13:00:19 +000011687#if ENABLE_ASH_READ_TIMEOUT
Paul Fox02eb9342005-09-07 16:56:02 +000011688 fd_set set;
11689 struct timeval ts;
11690
11691 ts.tv_sec = ts.tv_usec = 0;
11692#endif
Eric Andersenc470f442003-07-28 09:56:35 +000011693
11694 rflag = 0;
11695 prompt = NULL;
Denis Vlasenko131ae172007-02-18 13:00:19 +000011696#if ENABLE_ASH_READ_NCHARS && ENABLE_ASH_READ_TIMEOUT
Paul Fox02eb9342005-09-07 16:56:02 +000011697 while ((i = nextopt("p:rt:n:s")) != '\0')
Denis Vlasenko131ae172007-02-18 13:00:19 +000011698#elif ENABLE_ASH_READ_NCHARS
Paul Fox02eb9342005-09-07 16:56:02 +000011699 while ((i = nextopt("p:rn:s")) != '\0')
Denis Vlasenko131ae172007-02-18 13:00:19 +000011700#elif ENABLE_ASH_READ_TIMEOUT
Ned Ludd2123b7c2005-02-09 21:07:23 +000011701 while ((i = nextopt("p:rt:")) != '\0')
11702#else
11703 while ((i = nextopt("p:r")) != '\0')
11704#endif
11705 {
Denis Vlasenkobf0a2012006-12-26 10:42:51 +000011706 switch (i) {
Paul Fox02eb9342005-09-07 16:56:02 +000011707 case 'p':
Eric Andersenc470f442003-07-28 09:56:35 +000011708 prompt = optionarg;
Paul Fox02eb9342005-09-07 16:56:02 +000011709 break;
Denis Vlasenko131ae172007-02-18 13:00:19 +000011710#if ENABLE_ASH_READ_NCHARS
Paul Fox02eb9342005-09-07 16:56:02 +000011711 case 'n':
Denis Vlasenko037576d2007-10-20 18:30:38 +000011712 nchars = bb_strtou(optionarg, NULL, 10);
11713 if (nchars < 0 || errno)
Denis Vlasenkob012b102007-02-19 22:43:01 +000011714 ash_msg_and_raise_error("invalid count");
Denis Vlasenko037576d2007-10-20 18:30:38 +000011715 n_flag = nchars; /* just a flag "nchars is nonzero" */
Paul Fox02eb9342005-09-07 16:56:02 +000011716 break;
11717 case 's':
11718 silent = 1;
11719 break;
Ned Ludd2123b7c2005-02-09 21:07:23 +000011720#endif
Denis Vlasenko131ae172007-02-18 13:00:19 +000011721#if ENABLE_ASH_READ_TIMEOUT
Paul Fox02eb9342005-09-07 16:56:02 +000011722 case 't':
Denis Vlasenko037576d2007-10-20 18:30:38 +000011723 ts.tv_sec = bb_strtou(optionarg, &p, 10);
Paul Fox02eb9342005-09-07 16:56:02 +000011724 ts.tv_usec = 0;
Denis Vlasenko037576d2007-10-20 18:30:38 +000011725 /* EINVAL means number is ok, but not terminated by NUL */
11726 if (*p == '.' && errno == EINVAL) {
Paul Fox02eb9342005-09-07 16:56:02 +000011727 char *p2;
11728 if (*++p) {
11729 int scale;
Denis Vlasenko037576d2007-10-20 18:30:38 +000011730 ts.tv_usec = bb_strtou(p, &p2, 10);
11731 if (errno)
Denis Vlasenkob012b102007-02-19 22:43:01 +000011732 ash_msg_and_raise_error("invalid timeout");
Paul Fox02eb9342005-09-07 16:56:02 +000011733 scale = p2 - p;
11734 /* normalize to usec */
11735 if (scale > 6)
Denis Vlasenkob012b102007-02-19 22:43:01 +000011736 ash_msg_and_raise_error("invalid timeout");
Paul Fox02eb9342005-09-07 16:56:02 +000011737 while (scale++ < 6)
11738 ts.tv_usec *= 10;
11739 }
Denis Vlasenko037576d2007-10-20 18:30:38 +000011740 } else if (ts.tv_sec < 0 || errno) {
Denis Vlasenkob012b102007-02-19 22:43:01 +000011741 ash_msg_and_raise_error("invalid timeout");
Paul Fox02eb9342005-09-07 16:56:02 +000011742 }
Denis Vlasenko037576d2007-10-20 18:30:38 +000011743 if (!(ts.tv_sec | ts.tv_usec)) { /* both are 0? */
Denis Vlasenkob012b102007-02-19 22:43:01 +000011744 ash_msg_and_raise_error("invalid timeout");
Denis Vlasenko037576d2007-10-20 18:30:38 +000011745 }
Paul Fox02eb9342005-09-07 16:56:02 +000011746 break;
11747#endif
11748 case 'r':
11749 rflag = 1;
11750 break;
11751 default:
11752 break;
11753 }
Eric Andersenc470f442003-07-28 09:56:35 +000011754 }
11755 if (prompt && isatty(0)) {
11756 out2str(prompt);
Eric Andersenc470f442003-07-28 09:56:35 +000011757 }
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011758 ap = argptr;
11759 if (*ap == NULL)
Denis Vlasenkob012b102007-02-19 22:43:01 +000011760 ash_msg_and_raise_error("arg count");
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011761 ifs = bltinlookup("IFS");
11762 if (ifs == NULL)
Eric Andersenc470f442003-07-28 09:56:35 +000011763 ifs = defifs;
Denis Vlasenko131ae172007-02-18 13:00:19 +000011764#if ENABLE_ASH_READ_NCHARS
Denis Vlasenko037576d2007-10-20 18:30:38 +000011765 if (n_flag || silent) {
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000011766 if (tcgetattr(0, &tty) != 0) {
11767 /* Not a tty */
11768 n_flag = 0;
11769 silent = 0;
11770 } else {
11771 old_tty = tty;
11772 if (n_flag) {
11773 tty.c_lflag &= ~ICANON;
11774 tty.c_cc[VMIN] = nchars < 256 ? nchars : 255;
11775 }
11776 if (silent) {
11777 tty.c_lflag &= ~(ECHO | ECHOK | ECHONL);
11778 }
11779 tcsetattr(0, TCSANOW, &tty);
Paul Fox02eb9342005-09-07 16:56:02 +000011780 }
Paul Fox02eb9342005-09-07 16:56:02 +000011781 }
11782#endif
Denis Vlasenko131ae172007-02-18 13:00:19 +000011783#if ENABLE_ASH_READ_TIMEOUT
Paul Fox02eb9342005-09-07 16:56:02 +000011784 if (ts.tv_sec || ts.tv_usec) {
Denis Vlasenkod67cef22007-06-13 06:47:47 +000011785 FD_ZERO(&set);
11786 FD_SET(0, &set);
Paul Fox02eb9342005-09-07 16:56:02 +000011787
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000011788 /* poll-based wait produces bigger code, using select */
11789 i = select(1, &set, NULL, NULL, &ts);
11790 if (!i) { /* timed out! */
Denis Vlasenko131ae172007-02-18 13:00:19 +000011791#if ENABLE_ASH_READ_NCHARS
Denis Vlasenko037576d2007-10-20 18:30:38 +000011792 if (n_flag)
Paul Fox02eb9342005-09-07 16:56:02 +000011793 tcsetattr(0, TCSANOW, &old_tty);
11794#endif
11795 return 1;
11796 }
11797 }
Ned Ludd2123b7c2005-02-09 21:07:23 +000011798#endif
Eric Andersenc470f442003-07-28 09:56:35 +000011799 status = 0;
11800 startword = 1;
11801 backslash = 0;
11802 STARTSTACKSTR(p);
Denis Vlasenko037576d2007-10-20 18:30:38 +000011803 do {
Eric Andersenc470f442003-07-28 09:56:35 +000011804 if (read(0, &c, 1) != 1) {
11805 status = 1;
11806 break;
11807 }
11808 if (c == '\0')
11809 continue;
11810 if (backslash) {
11811 backslash = 0;
11812 if (c != '\n')
11813 goto put;
11814 continue;
11815 }
11816 if (!rflag && c == '\\') {
11817 backslash++;
11818 continue;
11819 }
11820 if (c == '\n')
11821 break;
11822 if (startword && *ifs == ' ' && strchr(ifs, c)) {
11823 continue;
11824 }
11825 startword = 0;
11826 if (ap[1] != NULL && strchr(ifs, c) != NULL) {
11827 STACKSTRNUL(p);
11828 setvar(*ap, stackblock(), 0);
11829 ap++;
11830 startword = 1;
11831 STARTSTACKSTR(p);
11832 } else {
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011833 put:
Eric Andersenc470f442003-07-28 09:56:35 +000011834 STPUTC(c, p);
11835 }
11836 }
Denis Vlasenko037576d2007-10-20 18:30:38 +000011837/* end of do {} while: */
Denis Vlasenko131ae172007-02-18 13:00:19 +000011838#if ENABLE_ASH_READ_NCHARS
Denis Vlasenko037576d2007-10-20 18:30:38 +000011839 while (!n_flag || --nchars);
11840#else
11841 while (1);
11842#endif
11843
11844#if ENABLE_ASH_READ_NCHARS
11845 if (n_flag || silent)
Paul Fox02eb9342005-09-07 16:56:02 +000011846 tcsetattr(0, TCSANOW, &old_tty);
11847#endif
11848
Eric Andersenc470f442003-07-28 09:56:35 +000011849 STACKSTRNUL(p);
11850 /* Remove trailing blanks */
11851 while ((char *)stackblock() <= --p && strchr(ifs, *p) != NULL)
11852 *p = '\0';
11853 setvar(*ap, stackblock(), 0);
11854 while (*++ap != NULL)
11855 setvar(*ap, nullstr, 0);
11856 return status;
11857}
11858
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000011859static int
11860umaskcmd(int argc, char **argv)
Eric Andersenc470f442003-07-28 09:56:35 +000011861{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011862 static const char permuser[3] ALIGN1 = "ugo";
11863 static const char permmode[3] ALIGN1 = "rwx";
11864 static const short permmask[] ALIGN2 = {
Eric Andersenc470f442003-07-28 09:56:35 +000011865 S_IRUSR, S_IWUSR, S_IXUSR,
11866 S_IRGRP, S_IWGRP, S_IXGRP,
11867 S_IROTH, S_IWOTH, S_IXOTH
11868 };
11869
11870 char *ap;
11871 mode_t mask;
11872 int i;
11873 int symbolic_mode = 0;
11874
11875 while (nextopt("S") != '\0') {
11876 symbolic_mode = 1;
11877 }
11878
Denis Vlasenkob012b102007-02-19 22:43:01 +000011879 INT_OFF;
Eric Andersenc470f442003-07-28 09:56:35 +000011880 mask = umask(0);
11881 umask(mask);
Denis Vlasenkob012b102007-02-19 22:43:01 +000011882 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +000011883
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011884 ap = *argptr;
11885 if (ap == NULL) {
Eric Andersenc470f442003-07-28 09:56:35 +000011886 if (symbolic_mode) {
11887 char buf[18];
11888 char *p = buf;
11889
11890 for (i = 0; i < 3; i++) {
11891 int j;
11892
11893 *p++ = permuser[i];
11894 *p++ = '=';
11895 for (j = 0; j < 3; j++) {
11896 if ((mask & permmask[3 * i + j]) == 0) {
11897 *p++ = permmode[j];
11898 }
11899 }
11900 *p++ = ',';
11901 }
11902 *--p = 0;
11903 puts(buf);
11904 } else {
11905 out1fmt("%.4o\n", mask);
11906 }
11907 } else {
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011908 if (isdigit((unsigned char) *ap)) {
Eric Andersenc470f442003-07-28 09:56:35 +000011909 mask = 0;
11910 do {
11911 if (*ap >= '8' || *ap < '0')
Denis Vlasenkob012b102007-02-19 22:43:01 +000011912 ash_msg_and_raise_error(illnum, argv[1]);
Eric Andersenc470f442003-07-28 09:56:35 +000011913 mask = (mask << 3) + (*ap - '0');
11914 } while (*++ap != '\0');
11915 umask(mask);
11916 } else {
11917 mask = ~mask & 0777;
11918 if (!bb_parse_mode(ap, &mask)) {
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +000011919 ash_msg_and_raise_error("illegal mode: %s", ap);
Eric Andersenc470f442003-07-28 09:56:35 +000011920 }
11921 umask(~mask & 0777);
11922 }
11923 }
11924 return 0;
11925}
11926
11927/*
11928 * ulimit builtin
11929 *
11930 * This code, originally by Doug Gwyn, Doug Kingston, Eric Gisin, and
11931 * Michael Rendell was ripped from pdksh 5.0.8 and hacked for use with
11932 * ash by J.T. Conklin.
11933 *
11934 * Public domain.
11935 */
11936
11937struct limits {
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000011938 uint8_t cmd; /* RLIMIT_xxx fit into it */
11939 uint8_t factor_shift; /* shift by to get rlim_{cur,max} values */
Eric Andersenc470f442003-07-28 09:56:35 +000011940 char option;
11941};
11942
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000011943static const struct limits limits_tbl[] = {
Eric Andersenc470f442003-07-28 09:56:35 +000011944#ifdef RLIMIT_CPU
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000011945 { RLIMIT_CPU, 0, 't' },
Eric Andersenc470f442003-07-28 09:56:35 +000011946#endif
11947#ifdef RLIMIT_FSIZE
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000011948 { RLIMIT_FSIZE, 9, 'f' },
Eric Andersenc470f442003-07-28 09:56:35 +000011949#endif
11950#ifdef RLIMIT_DATA
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000011951 { RLIMIT_DATA, 10, 'd' },
Eric Andersenc470f442003-07-28 09:56:35 +000011952#endif
11953#ifdef RLIMIT_STACK
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000011954 { RLIMIT_STACK, 10, 's' },
Eric Andersenc470f442003-07-28 09:56:35 +000011955#endif
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000011956#ifdef RLIMIT_CORE
11957 { RLIMIT_CORE, 9, 'c' },
Eric Andersenc470f442003-07-28 09:56:35 +000011958#endif
11959#ifdef RLIMIT_RSS
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000011960 { RLIMIT_RSS, 10, 'm' },
Eric Andersenc470f442003-07-28 09:56:35 +000011961#endif
11962#ifdef RLIMIT_MEMLOCK
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000011963 { RLIMIT_MEMLOCK, 10, 'l' },
Eric Andersenc470f442003-07-28 09:56:35 +000011964#endif
11965#ifdef RLIMIT_NPROC
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000011966 { RLIMIT_NPROC, 0, 'p' },
Eric Andersenc470f442003-07-28 09:56:35 +000011967#endif
11968#ifdef RLIMIT_NOFILE
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000011969 { RLIMIT_NOFILE, 0, 'n' },
Eric Andersenc470f442003-07-28 09:56:35 +000011970#endif
Glenn L McGrath76620622004-01-13 10:19:37 +000011971#ifdef RLIMIT_AS
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000011972 { RLIMIT_AS, 10, 'v' },
Eric Andersenc470f442003-07-28 09:56:35 +000011973#endif
Glenn L McGrath76620622004-01-13 10:19:37 +000011974#ifdef RLIMIT_LOCKS
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000011975 { RLIMIT_LOCKS, 0, 'w' },
Eric Andersenc470f442003-07-28 09:56:35 +000011976#endif
Eric Andersenc470f442003-07-28 09:56:35 +000011977};
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000011978static const char limits_name[] =
11979#ifdef RLIMIT_CPU
11980 "time(seconds)" "\0"
11981#endif
11982#ifdef RLIMIT_FSIZE
11983 "file(blocks)" "\0"
11984#endif
11985#ifdef RLIMIT_DATA
11986 "data(kb)" "\0"
11987#endif
11988#ifdef RLIMIT_STACK
11989 "stack(kb)" "\0"
11990#endif
11991#ifdef RLIMIT_CORE
11992 "coredump(blocks)" "\0"
11993#endif
11994#ifdef RLIMIT_RSS
11995 "memory(kb)" "\0"
11996#endif
11997#ifdef RLIMIT_MEMLOCK
11998 "locked memory(kb)" "\0"
11999#endif
12000#ifdef RLIMIT_NPROC
12001 "process" "\0"
12002#endif
12003#ifdef RLIMIT_NOFILE
12004 "nofiles" "\0"
12005#endif
12006#ifdef RLIMIT_AS
12007 "vmemory(kb)" "\0"
12008#endif
12009#ifdef RLIMIT_LOCKS
12010 "locks" "\0"
12011#endif
12012;
Eric Andersenc470f442003-07-28 09:56:35 +000012013
Glenn L McGrath76620622004-01-13 10:19:37 +000012014enum limtype { SOFT = 0x1, HARD = 0x2 };
12015
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012016static void
12017printlim(enum limtype how, const struct rlimit *limit,
Glenn L McGrath76620622004-01-13 10:19:37 +000012018 const struct limits *l)
12019{
12020 rlim_t val;
12021
12022 val = limit->rlim_max;
12023 if (how & SOFT)
12024 val = limit->rlim_cur;
12025
12026 if (val == RLIM_INFINITY)
12027 out1fmt("unlimited\n");
12028 else {
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012029 val >>= l->factor_shift;
Glenn L McGrath76620622004-01-13 10:19:37 +000012030 out1fmt("%lld\n", (long long) val);
12031 }
12032}
12033
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012034static int
Eric Andersenc470f442003-07-28 09:56:35 +000012035ulimitcmd(int argc, char **argv)
12036{
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012037 int c;
Eric Andersenc470f442003-07-28 09:56:35 +000012038 rlim_t val = 0;
Glenn L McGrath76620622004-01-13 10:19:37 +000012039 enum limtype how = SOFT | HARD;
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012040 const struct limits *l;
12041 int set, all = 0;
12042 int optc, what;
12043 struct rlimit limit;
Eric Andersenc470f442003-07-28 09:56:35 +000012044
12045 what = 'f';
Glenn L McGrath16e45d72004-02-04 08:24:39 +000012046 while ((optc = nextopt("HSa"
12047#ifdef RLIMIT_CPU
12048 "t"
12049#endif
12050#ifdef RLIMIT_FSIZE
12051 "f"
12052#endif
12053#ifdef RLIMIT_DATA
12054 "d"
12055#endif
12056#ifdef RLIMIT_STACK
12057 "s"
12058#endif
12059#ifdef RLIMIT_CORE
12060 "c"
12061#endif
12062#ifdef RLIMIT_RSS
12063 "m"
12064#endif
12065#ifdef RLIMIT_MEMLOCK
12066 "l"
12067#endif
12068#ifdef RLIMIT_NPROC
12069 "p"
12070#endif
12071#ifdef RLIMIT_NOFILE
12072 "n"
12073#endif
12074#ifdef RLIMIT_AS
12075 "v"
12076#endif
12077#ifdef RLIMIT_LOCKS
12078 "w"
12079#endif
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000012080 )) != '\0')
Eric Andersenc470f442003-07-28 09:56:35 +000012081 switch (optc) {
12082 case 'H':
12083 how = HARD;
12084 break;
12085 case 'S':
12086 how = SOFT;
12087 break;
12088 case 'a':
12089 all = 1;
12090 break;
12091 default:
12092 what = optc;
12093 }
12094
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012095 for (l = limits_tbl; l->option != what; l++)
12096 continue;
Eric Andersenc470f442003-07-28 09:56:35 +000012097
12098 set = *argptr ? 1 : 0;
12099 if (set) {
12100 char *p = *argptr;
12101
12102 if (all || argptr[1])
Denis Vlasenkob012b102007-02-19 22:43:01 +000012103 ash_msg_and_raise_error("too many arguments");
Eric Andersen81fe1232003-07-29 06:38:40 +000012104 if (strncmp(p, "unlimited\n", 9) == 0)
Eric Andersenc470f442003-07-28 09:56:35 +000012105 val = RLIM_INFINITY;
12106 else {
12107 val = (rlim_t) 0;
12108
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000012109 while ((c = *p++) >= '0' && c <= '9') {
Eric Andersenc470f442003-07-28 09:56:35 +000012110 val = (val * 10) + (long)(c - '0');
12111 if (val < (rlim_t) 0)
12112 break;
12113 }
12114 if (c)
Denis Vlasenkob012b102007-02-19 22:43:01 +000012115 ash_msg_and_raise_error("bad number");
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012116 val <<= l->factor_shift;
Eric Andersenc470f442003-07-28 09:56:35 +000012117 }
12118 }
12119 if (all) {
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012120 const char *lname = limits_name;
12121 for (l = limits_tbl; l != &limits_tbl[ARRAY_SIZE(limits_tbl)]; l++) {
Eric Andersenc470f442003-07-28 09:56:35 +000012122 getrlimit(l->cmd, &limit);
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012123 out1fmt("%-20s ", lname);
12124 lname += strlen(lname) + 1;
Glenn L McGrath76620622004-01-13 10:19:37 +000012125 printlim(how, &limit, l);
Eric Andersenc470f442003-07-28 09:56:35 +000012126 }
12127 return 0;
12128 }
12129
12130 getrlimit(l->cmd, &limit);
12131 if (set) {
12132 if (how & HARD)
12133 limit.rlim_max = val;
12134 if (how & SOFT)
12135 limit.rlim_cur = val;
12136 if (setrlimit(l->cmd, &limit) < 0)
Denis Vlasenkob012b102007-02-19 22:43:01 +000012137 ash_msg_and_raise_error("error setting limit (%m)");
Eric Andersenc470f442003-07-28 09:56:35 +000012138 } else {
Glenn L McGrath76620622004-01-13 10:19:37 +000012139 printlim(how, &limit, l);
Eric Andersenc470f442003-07-28 09:56:35 +000012140 }
12141 return 0;
12142}
12143
Eric Andersen90898442003-08-06 11:20:52 +000012144
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012145/* ============ Math support */
12146
Denis Vlasenko131ae172007-02-18 13:00:19 +000012147#if ENABLE_ASH_MATH_SUPPORT
Eric Andersen90898442003-08-06 11:20:52 +000012148
12149/* Copyright (c) 2001 Aaron Lehmann <aaronl@vitelus.com>
12150
12151 Permission is hereby granted, free of charge, to any person obtaining
12152 a copy of this software and associated documentation files (the
12153 "Software"), to deal in the Software without restriction, including
12154 without limitation the rights to use, copy, modify, merge, publish,
12155 distribute, sublicense, and/or sell copies of the Software, and to
12156 permit persons to whom the Software is furnished to do so, subject to
12157 the following conditions:
12158
12159 The above copyright notice and this permission notice shall be
12160 included in all copies or substantial portions of the Software.
12161
12162 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
12163 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
12164 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
12165 IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
12166 CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
12167 TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
12168 SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
12169*/
12170
12171/* This is my infix parser/evaluator. It is optimized for size, intended
12172 * as a replacement for yacc-based parsers. However, it may well be faster
Eric Andersenaff114c2004-04-14 17:51:38 +000012173 * than a comparable parser written in yacc. The supported operators are
Eric Andersen90898442003-08-06 11:20:52 +000012174 * listed in #defines below. Parens, order of operations, and error handling
Eric Andersenaff114c2004-04-14 17:51:38 +000012175 * are supported. This code is thread safe. The exact expression format should
Eric Andersen90898442003-08-06 11:20:52 +000012176 * be that which POSIX specifies for shells. */
12177
12178/* The code uses a simple two-stack algorithm. See
12179 * http://www.onthenet.com.au/~grahamis/int2008/week02/lect02.html
Eric Andersenaff114c2004-04-14 17:51:38 +000012180 * for a detailed explanation of the infix-to-postfix algorithm on which
Eric Andersen90898442003-08-06 11:20:52 +000012181 * this is based (this code differs in that it applies operators immediately
12182 * to the stack instead of adding them to a queue to end up with an
12183 * expression). */
12184
12185/* To use the routine, call it with an expression string and error return
12186 * pointer */
12187
12188/*
12189 * Aug 24, 2001 Manuel Novoa III
12190 *
12191 * Reduced the generated code size by about 30% (i386) and fixed several bugs.
12192 *
12193 * 1) In arith_apply():
12194 * a) Cached values of *numptr and &(numptr[-1]).
12195 * b) Removed redundant test for zero denominator.
12196 *
12197 * 2) In arith():
12198 * a) Eliminated redundant code for processing operator tokens by moving
12199 * to a table-based implementation. Also folded handling of parens
12200 * into the table.
12201 * b) Combined all 3 loops which called arith_apply to reduce generated
12202 * code size at the cost of speed.
12203 *
12204 * 3) The following expressions were treated as valid by the original code:
12205 * 1() , 0! , 1 ( *3 ) .
12206 * These bugs have been fixed by internally enclosing the expression in
12207 * parens and then checking that all binary ops and right parens are
12208 * preceded by a valid expression (NUM_TOKEN).
12209 *
Eric Andersenaff114c2004-04-14 17:51:38 +000012210 * Note: It may be desirable to replace Aaron's test for whitespace with
Eric Andersen90898442003-08-06 11:20:52 +000012211 * ctype's isspace() if it is used by another busybox applet or if additional
12212 * whitespace chars should be considered. Look below the "#include"s for a
12213 * precompiler test.
12214 */
12215
12216/*
12217 * Aug 26, 2001 Manuel Novoa III
12218 *
12219 * Return 0 for null expressions. Pointed out by Vladimir Oleynik.
12220 *
12221 * Merge in Aaron's comments previously posted to the busybox list,
12222 * modified slightly to take account of my changes to the code.
12223 *
12224 */
12225
12226/*
12227 * (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
12228 *
12229 * - allow access to variable,
12230 * used recursive find value indirection (c=2*2; a="c"; $((a+=2)) produce 6)
12231 * - realize assign syntax (VAR=expr, +=, *= etc)
12232 * - realize exponentiation (** operator)
12233 * - realize comma separated - expr, expr
12234 * - realise ++expr --expr expr++ expr--
12235 * - realise expr ? expr : expr (but, second expr calculate always)
Eric Andersenaff114c2004-04-14 17:51:38 +000012236 * - allow hexadecimal and octal numbers
Eric Andersen90898442003-08-06 11:20:52 +000012237 * - was restored loses XOR operator
12238 * - remove one goto label, added three ;-)
12239 * - protect $((num num)) as true zero expr (Manuel`s error)
12240 * - always use special isspace(), see comment from bash ;-)
12241 */
12242
Eric Andersen90898442003-08-06 11:20:52 +000012243#define arith_isspace(arithval) \
12244 (arithval == ' ' || arithval == '\n' || arithval == '\t')
12245
Eric Andersen90898442003-08-06 11:20:52 +000012246typedef unsigned char operator;
12247
12248/* An operator's token id is a bit of a bitfield. The lower 5 bits are the
Eric Andersenaff114c2004-04-14 17:51:38 +000012249 * precedence, and 3 high bits are an ID unique across operators of that
Eric Andersen90898442003-08-06 11:20:52 +000012250 * precedence. The ID portion is so that multiple operators can have the
12251 * same precedence, ensuring that the leftmost one is evaluated first.
12252 * Consider * and /. */
12253
12254#define tok_decl(prec,id) (((id)<<5)|(prec))
12255#define PREC(op) ((op) & 0x1F)
12256
12257#define TOK_LPAREN tok_decl(0,0)
12258
12259#define TOK_COMMA tok_decl(1,0)
12260
12261#define TOK_ASSIGN tok_decl(2,0)
12262#define TOK_AND_ASSIGN tok_decl(2,1)
12263#define TOK_OR_ASSIGN tok_decl(2,2)
12264#define TOK_XOR_ASSIGN tok_decl(2,3)
12265#define TOK_PLUS_ASSIGN tok_decl(2,4)
12266#define TOK_MINUS_ASSIGN tok_decl(2,5)
12267#define TOK_LSHIFT_ASSIGN tok_decl(2,6)
12268#define TOK_RSHIFT_ASSIGN tok_decl(2,7)
12269
12270#define TOK_MUL_ASSIGN tok_decl(3,0)
12271#define TOK_DIV_ASSIGN tok_decl(3,1)
12272#define TOK_REM_ASSIGN tok_decl(3,2)
12273
12274/* all assign is right associativity and precedence eq, but (7+3)<<5 > 256 */
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000012275#define convert_prec_is_assing(prec) do { if (prec == 3) prec = 2; } while (0)
Eric Andersen90898442003-08-06 11:20:52 +000012276
12277/* conditional is right associativity too */
12278#define TOK_CONDITIONAL tok_decl(4,0)
12279#define TOK_CONDITIONAL_SEP tok_decl(4,1)
12280
12281#define TOK_OR tok_decl(5,0)
12282
12283#define TOK_AND tok_decl(6,0)
12284
12285#define TOK_BOR tok_decl(7,0)
12286
12287#define TOK_BXOR tok_decl(8,0)
12288
12289#define TOK_BAND tok_decl(9,0)
12290
12291#define TOK_EQ tok_decl(10,0)
12292#define TOK_NE tok_decl(10,1)
12293
12294#define TOK_LT tok_decl(11,0)
12295#define TOK_GT tok_decl(11,1)
12296#define TOK_GE tok_decl(11,2)
12297#define TOK_LE tok_decl(11,3)
12298
12299#define TOK_LSHIFT tok_decl(12,0)
12300#define TOK_RSHIFT tok_decl(12,1)
12301
12302#define TOK_ADD tok_decl(13,0)
12303#define TOK_SUB tok_decl(13,1)
12304
12305#define TOK_MUL tok_decl(14,0)
12306#define TOK_DIV tok_decl(14,1)
12307#define TOK_REM tok_decl(14,2)
12308
12309/* exponent is right associativity */
12310#define TOK_EXPONENT tok_decl(15,1)
12311
12312/* For now unary operators. */
12313#define UNARYPREC 16
12314#define TOK_BNOT tok_decl(UNARYPREC,0)
12315#define TOK_NOT tok_decl(UNARYPREC,1)
12316
12317#define TOK_UMINUS tok_decl(UNARYPREC+1,0)
12318#define TOK_UPLUS tok_decl(UNARYPREC+1,1)
12319
12320#define PREC_PRE (UNARYPREC+2)
12321
12322#define TOK_PRE_INC tok_decl(PREC_PRE, 0)
12323#define TOK_PRE_DEC tok_decl(PREC_PRE, 1)
12324
12325#define PREC_POST (UNARYPREC+3)
12326
12327#define TOK_POST_INC tok_decl(PREC_POST, 0)
12328#define TOK_POST_DEC tok_decl(PREC_POST, 1)
12329
12330#define SPEC_PREC (UNARYPREC+4)
12331
12332#define TOK_NUM tok_decl(SPEC_PREC, 0)
12333#define TOK_RPAREN tok_decl(SPEC_PREC, 1)
12334
12335#define NUMPTR (*numstackptr)
12336
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012337static int
12338tok_have_assign(operator op)
Eric Andersen90898442003-08-06 11:20:52 +000012339{
12340 operator prec = PREC(op);
12341
12342 convert_prec_is_assing(prec);
12343 return (prec == PREC(TOK_ASSIGN) ||
12344 prec == PREC_PRE || prec == PREC_POST);
12345}
12346
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012347static int
12348is_right_associativity(operator prec)
Eric Andersen90898442003-08-06 11:20:52 +000012349{
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000012350 return (prec == PREC(TOK_ASSIGN) || prec == PREC(TOK_EXPONENT)
12351 || prec == PREC(TOK_CONDITIONAL));
Eric Andersen90898442003-08-06 11:20:52 +000012352}
12353
Eric Andersen90898442003-08-06 11:20:52 +000012354typedef struct ARITCH_VAR_NUM {
Eric Andersened9ecf72004-06-22 08:29:45 +000012355 arith_t val;
12356 arith_t contidional_second_val;
Eric Andersen90898442003-08-06 11:20:52 +000012357 char contidional_second_val_initialized;
12358 char *var; /* if NULL then is regular number,
Eric Andersenaff114c2004-04-14 17:51:38 +000012359 else is variable name */
Eric Andersen90898442003-08-06 11:20:52 +000012360} v_n_t;
12361
Eric Andersen90898442003-08-06 11:20:52 +000012362typedef struct CHK_VAR_RECURSIVE_LOOPED {
12363 const char *var;
12364 struct CHK_VAR_RECURSIVE_LOOPED *next;
12365} chk_var_recursive_looped_t;
12366
12367static chk_var_recursive_looped_t *prev_chk_var_recursive;
12368
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012369static int
12370arith_lookup_val(v_n_t *t)
Eric Andersen90898442003-08-06 11:20:52 +000012371{
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000012372 if (t->var) {
12373 const char * p = lookupvar(t->var);
Eric Andersen90898442003-08-06 11:20:52 +000012374
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000012375 if (p) {
12376 int errcode;
Eric Andersen90898442003-08-06 11:20:52 +000012377
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000012378 /* recursive try as expression */
12379 chk_var_recursive_looped_t *cur;
12380 chk_var_recursive_looped_t cur_save;
Eric Andersen90898442003-08-06 11:20:52 +000012381
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000012382 for (cur = prev_chk_var_recursive; cur; cur = cur->next) {
12383 if (strcmp(cur->var, t->var) == 0) {
12384 /* expression recursion loop detected */
12385 return -5;
12386 }
12387 }
12388 /* save current lookuped var name */
12389 cur = prev_chk_var_recursive;
12390 cur_save.var = t->var;
12391 cur_save.next = cur;
12392 prev_chk_var_recursive = &cur_save;
12393
12394 t->val = arith (p, &errcode);
12395 /* restore previous ptr after recursiving */
12396 prev_chk_var_recursive = cur;
12397 return errcode;
Eric Andersen90898442003-08-06 11:20:52 +000012398 }
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000012399 /* allow undefined var as 0 */
12400 t->val = 0;
Eric Andersen90898442003-08-06 11:20:52 +000012401 }
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000012402 return 0;
Eric Andersen90898442003-08-06 11:20:52 +000012403}
12404
12405/* "applying" a token means performing it on the top elements on the integer
12406 * stack. For a unary operator it will only change the top element, but a
12407 * binary operator will pop two arguments and push a result */
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012408static int
12409arith_apply(operator op, v_n_t *numstack, v_n_t **numstackptr)
Eric Andersen90898442003-08-06 11:20:52 +000012410{
Eric Andersen90898442003-08-06 11:20:52 +000012411 v_n_t *numptr_m1;
Eric Andersenfac312d2004-06-22 20:09:40 +000012412 arith_t numptr_val, rez;
Eric Andersen90898442003-08-06 11:20:52 +000012413 int ret_arith_lookup_val;
12414
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000012415 /* There is no operator that can work without arguments */
12416 if (NUMPTR == numstack) goto err;
Eric Andersen90898442003-08-06 11:20:52 +000012417 numptr_m1 = NUMPTR - 1;
12418
12419 /* check operand is var with noninteger value */
12420 ret_arith_lookup_val = arith_lookup_val(numptr_m1);
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000012421 if (ret_arith_lookup_val)
Eric Andersen90898442003-08-06 11:20:52 +000012422 return ret_arith_lookup_val;
12423
12424 rez = numptr_m1->val;
12425 if (op == TOK_UMINUS)
12426 rez *= -1;
12427 else if (op == TOK_NOT)
12428 rez = !rez;
12429 else if (op == TOK_BNOT)
12430 rez = ~rez;
12431 else if (op == TOK_POST_INC || op == TOK_PRE_INC)
12432 rez++;
12433 else if (op == TOK_POST_DEC || op == TOK_PRE_DEC)
12434 rez--;
12435 else if (op != TOK_UPLUS) {
12436 /* Binary operators */
12437
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000012438 /* check and binary operators need two arguments */
12439 if (numptr_m1 == numstack) goto err;
Eric Andersen90898442003-08-06 11:20:52 +000012440
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000012441 /* ... and they pop one */
12442 --NUMPTR;
12443 numptr_val = rez;
12444 if (op == TOK_CONDITIONAL) {
12445 if (! numptr_m1->contidional_second_val_initialized) {
12446 /* protect $((expr1 ? expr2)) without ": expr" */
12447 goto err;
12448 }
12449 rez = numptr_m1->contidional_second_val;
12450 } else if (numptr_m1->contidional_second_val_initialized) {
12451 /* protect $((expr1 : expr2)) without "expr ? " */
12452 goto err;
Eric Andersen90898442003-08-06 11:20:52 +000012453 }
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000012454 numptr_m1 = NUMPTR - 1;
12455 if (op != TOK_ASSIGN) {
12456 /* check operand is var with noninteger value for not '=' */
12457 ret_arith_lookup_val = arith_lookup_val(numptr_m1);
12458 if (ret_arith_lookup_val)
12459 return ret_arith_lookup_val;
12460 }
12461 if (op == TOK_CONDITIONAL) {
12462 numptr_m1->contidional_second_val = rez;
12463 }
12464 rez = numptr_m1->val;
12465 if (op == TOK_BOR || op == TOK_OR_ASSIGN)
Eric Andersen90898442003-08-06 11:20:52 +000012466 rez |= numptr_val;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000012467 else if (op == TOK_OR)
Eric Andersen90898442003-08-06 11:20:52 +000012468 rez = numptr_val || rez;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000012469 else if (op == TOK_BAND || op == TOK_AND_ASSIGN)
Eric Andersen90898442003-08-06 11:20:52 +000012470 rez &= numptr_val;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000012471 else if (op == TOK_BXOR || op == TOK_XOR_ASSIGN)
Eric Andersen90898442003-08-06 11:20:52 +000012472 rez ^= numptr_val;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000012473 else if (op == TOK_AND)
Eric Andersen90898442003-08-06 11:20:52 +000012474 rez = rez && numptr_val;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000012475 else if (op == TOK_EQ)
Eric Andersen90898442003-08-06 11:20:52 +000012476 rez = (rez == numptr_val);
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000012477 else if (op == TOK_NE)
Eric Andersen90898442003-08-06 11:20:52 +000012478 rez = (rez != numptr_val);
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000012479 else if (op == TOK_GE)
Eric Andersen90898442003-08-06 11:20:52 +000012480 rez = (rez >= numptr_val);
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000012481 else if (op == TOK_RSHIFT || op == TOK_RSHIFT_ASSIGN)
Eric Andersen90898442003-08-06 11:20:52 +000012482 rez >>= numptr_val;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000012483 else if (op == TOK_LSHIFT || op == TOK_LSHIFT_ASSIGN)
Eric Andersen90898442003-08-06 11:20:52 +000012484 rez <<= numptr_val;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000012485 else if (op == TOK_GT)
Eric Andersen90898442003-08-06 11:20:52 +000012486 rez = (rez > numptr_val);
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000012487 else if (op == TOK_LT)
Eric Andersen90898442003-08-06 11:20:52 +000012488 rez = (rez < numptr_val);
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000012489 else if (op == TOK_LE)
Eric Andersen90898442003-08-06 11:20:52 +000012490 rez = (rez <= numptr_val);
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000012491 else if (op == TOK_MUL || op == TOK_MUL_ASSIGN)
Eric Andersen90898442003-08-06 11:20:52 +000012492 rez *= numptr_val;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000012493 else if (op == TOK_ADD || op == TOK_PLUS_ASSIGN)
Eric Andersen90898442003-08-06 11:20:52 +000012494 rez += numptr_val;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000012495 else if (op == TOK_SUB || op == TOK_MINUS_ASSIGN)
Eric Andersen90898442003-08-06 11:20:52 +000012496 rez -= numptr_val;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000012497 else if (op == TOK_ASSIGN || op == TOK_COMMA)
Eric Andersen90898442003-08-06 11:20:52 +000012498 rez = numptr_val;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000012499 else if (op == TOK_CONDITIONAL_SEP) {
Eric Andersen90898442003-08-06 11:20:52 +000012500 if (numptr_m1 == numstack) {
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000012501 /* protect $((expr : expr)) without "expr ? " */
12502 goto err;
Eric Andersen90898442003-08-06 11:20:52 +000012503 }
12504 numptr_m1->contidional_second_val_initialized = op;
12505 numptr_m1->contidional_second_val = numptr_val;
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012506 } else if (op == TOK_CONDITIONAL) {
Eric Andersen90898442003-08-06 11:20:52 +000012507 rez = rez ?
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000012508 numptr_val : numptr_m1->contidional_second_val;
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012509 } else if (op == TOK_EXPONENT) {
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000012510 if (numptr_val < 0)
Eric Andersen90898442003-08-06 11:20:52 +000012511 return -3; /* exponent less than 0 */
12512 else {
Eric Andersenad63cb22004-10-08 09:43:34 +000012513 arith_t c = 1;
Eric Andersen90898442003-08-06 11:20:52 +000012514
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000012515 if (numptr_val)
12516 while (numptr_val--)
Eric Andersen90898442003-08-06 11:20:52 +000012517 c *= rez;
12518 rez = c;
12519 }
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012520 } else if (numptr_val==0) /* zero divisor check */
Eric Andersen90898442003-08-06 11:20:52 +000012521 return -2;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000012522 else if (op == TOK_DIV || op == TOK_DIV_ASSIGN)
Eric Andersen90898442003-08-06 11:20:52 +000012523 rez /= numptr_val;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000012524 else if (op == TOK_REM || op == TOK_REM_ASSIGN)
Eric Andersen90898442003-08-06 11:20:52 +000012525 rez %= numptr_val;
12526 }
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000012527 if (tok_have_assign(op)) {
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012528 char buf[sizeof(arith_t_type)*3 + 2];
Eric Andersen90898442003-08-06 11:20:52 +000012529
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000012530 if (numptr_m1->var == NULL) {
Eric Andersen90898442003-08-06 11:20:52 +000012531 /* Hmm, 1=2 ? */
12532 goto err;
12533 }
12534 /* save to shell variable */
Denis Vlasenko131ae172007-02-18 13:00:19 +000012535#if ENABLE_ASH_MATH_SUPPORT_64
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012536 snprintf(buf, sizeof(buf), "%lld", (arith_t_type) rez);
"Vladimir N. Oleynik"bef14d72005-09-05 13:25:11 +000012537#else
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012538 snprintf(buf, sizeof(buf), "%ld", (arith_t_type) rez);
"Vladimir N. Oleynik"bef14d72005-09-05 13:25:11 +000012539#endif
Eric Andersen90898442003-08-06 11:20:52 +000012540 setvar(numptr_m1->var, buf, 0);
12541 /* after saving, make previous value for v++ or v-- */
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000012542 if (op == TOK_POST_INC)
Eric Andersen90898442003-08-06 11:20:52 +000012543 rez--;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000012544 else if (op == TOK_POST_DEC)
Eric Andersen90898442003-08-06 11:20:52 +000012545 rez++;
12546 }
12547 numptr_m1->val = rez;
12548 /* protect geting var value, is number now */
12549 numptr_m1->var = NULL;
12550 return 0;
Denis Vlasenko079f8af2006-11-27 16:49:31 +000012551 err:
12552 return -1;
Eric Andersen90898442003-08-06 11:20:52 +000012553}
12554
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012555/* longest must be first */
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000012556static const char op_tokens[] ALIGN1 = {
Eric Andersen90898442003-08-06 11:20:52 +000012557 '<','<','=',0, TOK_LSHIFT_ASSIGN,
12558 '>','>','=',0, TOK_RSHIFT_ASSIGN,
12559 '<','<', 0, TOK_LSHIFT,
12560 '>','>', 0, TOK_RSHIFT,
12561 '|','|', 0, TOK_OR,
12562 '&','&', 0, TOK_AND,
12563 '!','=', 0, TOK_NE,
12564 '<','=', 0, TOK_LE,
12565 '>','=', 0, TOK_GE,
12566 '=','=', 0, TOK_EQ,
12567 '|','=', 0, TOK_OR_ASSIGN,
12568 '&','=', 0, TOK_AND_ASSIGN,
12569 '*','=', 0, TOK_MUL_ASSIGN,
12570 '/','=', 0, TOK_DIV_ASSIGN,
12571 '%','=', 0, TOK_REM_ASSIGN,
12572 '+','=', 0, TOK_PLUS_ASSIGN,
12573 '-','=', 0, TOK_MINUS_ASSIGN,
12574 '-','-', 0, TOK_POST_DEC,
12575 '^','=', 0, TOK_XOR_ASSIGN,
12576 '+','+', 0, TOK_POST_INC,
12577 '*','*', 0, TOK_EXPONENT,
12578 '!', 0, TOK_NOT,
12579 '<', 0, TOK_LT,
12580 '>', 0, TOK_GT,
12581 '=', 0, TOK_ASSIGN,
12582 '|', 0, TOK_BOR,
12583 '&', 0, TOK_BAND,
12584 '*', 0, TOK_MUL,
12585 '/', 0, TOK_DIV,
12586 '%', 0, TOK_REM,
12587 '+', 0, TOK_ADD,
12588 '-', 0, TOK_SUB,
12589 '^', 0, TOK_BXOR,
12590 /* uniq */
12591 '~', 0, TOK_BNOT,
12592 ',', 0, TOK_COMMA,
12593 '?', 0, TOK_CONDITIONAL,
12594 ':', 0, TOK_CONDITIONAL_SEP,
12595 ')', 0, TOK_RPAREN,
12596 '(', 0, TOK_LPAREN,
12597 0
12598};
12599/* ptr to ")" */
12600#define endexpression &op_tokens[sizeof(op_tokens)-7]
12601
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012602static arith_t
12603arith(const char *expr, int *perrcode)
Eric Andersen90898442003-08-06 11:20:52 +000012604{
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000012605 char arithval; /* Current character under analysis */
12606 operator lasttok, op;
12607 operator prec;
Eric Andersen90898442003-08-06 11:20:52 +000012608
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000012609 const char *p = endexpression;
12610 int errcode;
Eric Andersen90898442003-08-06 11:20:52 +000012611
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000012612 size_t datasizes = strlen(expr) + 2;
Eric Andersen90898442003-08-06 11:20:52 +000012613
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000012614 /* Stack of integers */
12615 /* The proof that there can be no more than strlen(startbuf)/2+1 integers
12616 * in any given correct or incorrect expression is left as an exercise to
12617 * the reader. */
12618 v_n_t *numstack = alloca(((datasizes)/2)*sizeof(v_n_t)),
12619 *numstackptr = numstack;
12620 /* Stack of operator tokens */
12621 operator *stack = alloca((datasizes) * sizeof(operator)),
12622 *stackptr = stack;
Eric Andersen90898442003-08-06 11:20:52 +000012623
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000012624 *stackptr++ = lasttok = TOK_LPAREN; /* start off with a left paren */
12625 *perrcode = errcode = 0;
Eric Andersen90898442003-08-06 11:20:52 +000012626
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000012627 while (1) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +000012628 arithval = *expr;
12629 if (arithval == 0) {
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000012630 if (p == endexpression) {
12631 /* Null expression. */
12632 return 0;
12633 }
12634
12635 /* This is only reached after all tokens have been extracted from the
12636 * input stream. If there are still tokens on the operator stack, they
12637 * are to be applied in order. At the end, there should be a final
12638 * result on the integer stack */
12639
12640 if (expr != endexpression + 1) {
12641 /* If we haven't done so already, */
12642 /* append a closing right paren */
12643 expr = endexpression;
12644 /* and let the loop process it. */
12645 continue;
12646 }
12647 /* At this point, we're done with the expression. */
12648 if (numstackptr != numstack+1) {
12649 /* ... but if there isn't, it's bad */
12650 err:
12651 return (*perrcode = -1);
12652 }
12653 if (numstack->var) {
12654 /* expression is $((var)) only, lookup now */
12655 errcode = arith_lookup_val(numstack);
12656 }
12657 ret:
12658 *perrcode = errcode;
12659 return numstack->val;
Eric Andersen90898442003-08-06 11:20:52 +000012660 }
12661
Eric Andersen90898442003-08-06 11:20:52 +000012662 /* Continue processing the expression. */
12663 if (arith_isspace(arithval)) {
12664 /* Skip whitespace */
12665 goto prologue;
12666 }
Denis Vlasenko5cedb752007-02-18 19:56:41 +000012667 p = endofname(expr);
12668 if (p != expr) {
Eric Andersenad63cb22004-10-08 09:43:34 +000012669 size_t var_name_size = (p-expr) + 1; /* trailing zero */
Eric Andersen90898442003-08-06 11:20:52 +000012670
12671 numstackptr->var = alloca(var_name_size);
12672 safe_strncpy(numstackptr->var, expr, var_name_size);
12673 expr = p;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000012674 num:
Eric Andersen90898442003-08-06 11:20:52 +000012675 numstackptr->contidional_second_val_initialized = 0;
12676 numstackptr++;
12677 lasttok = TOK_NUM;
12678 continue;
Denis Vlasenko2da584f2007-02-19 22:44:05 +000012679 }
Denis Vlasenkoaa744452007-02-23 01:04:22 +000012680 if (isdigit(arithval)) {
Eric Andersen90898442003-08-06 11:20:52 +000012681 numstackptr->var = NULL;
Denis Vlasenko131ae172007-02-18 13:00:19 +000012682#if ENABLE_ASH_MATH_SUPPORT_64
Eric Andersenad63cb22004-10-08 09:43:34 +000012683 numstackptr->val = strtoll(expr, (char **) &expr, 0);
"Vladimir N. Oleynik"bef14d72005-09-05 13:25:11 +000012684#else
12685 numstackptr->val = strtol(expr, (char **) &expr, 0);
12686#endif
Eric Andersen90898442003-08-06 11:20:52 +000012687 goto num;
12688 }
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000012689 for (p = op_tokens; ; p++) {
Eric Andersen90898442003-08-06 11:20:52 +000012690 const char *o;
12691
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000012692 if (*p == 0) {
Eric Andersen90898442003-08-06 11:20:52 +000012693 /* strange operator not found */
12694 goto err;
12695 }
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000012696 for (o = expr; *p && *o == *p; p++)
Eric Andersen90898442003-08-06 11:20:52 +000012697 o++;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000012698 if (! *p) {
Eric Andersen90898442003-08-06 11:20:52 +000012699 /* found */
12700 expr = o - 1;
12701 break;
12702 }
12703 /* skip tail uncompared token */
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000012704 while (*p)
Eric Andersen90898442003-08-06 11:20:52 +000012705 p++;
12706 /* skip zero delim */
12707 p++;
12708 }
12709 op = p[1];
12710
12711 /* post grammar: a++ reduce to num */
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000012712 if (lasttok == TOK_POST_INC || lasttok == TOK_POST_DEC)
12713 lasttok = TOK_NUM;
Eric Andersen90898442003-08-06 11:20:52 +000012714
12715 /* Plus and minus are binary (not unary) _only_ if the last
12716 * token was as number, or a right paren (which pretends to be
12717 * a number, since it evaluates to one). Think about it.
12718 * It makes sense. */
12719 if (lasttok != TOK_NUM) {
Denis Vlasenkobf0a2012006-12-26 10:42:51 +000012720 switch (op) {
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000012721 case TOK_ADD:
12722 op = TOK_UPLUS;
12723 break;
12724 case TOK_SUB:
12725 op = TOK_UMINUS;
12726 break;
12727 case TOK_POST_INC:
12728 op = TOK_PRE_INC;
12729 break;
12730 case TOK_POST_DEC:
12731 op = TOK_PRE_DEC;
12732 break;
Eric Andersen90898442003-08-06 11:20:52 +000012733 }
12734 }
12735 /* We don't want a unary operator to cause recursive descent on the
12736 * stack, because there can be many in a row and it could cause an
12737 * operator to be evaluated before its argument is pushed onto the
12738 * integer stack. */
12739 /* But for binary operators, "apply" everything on the operator
12740 * stack until we find an operator with a lesser priority than the
12741 * one we have just extracted. */
12742 /* Left paren is given the lowest priority so it will never be
12743 * "applied" in this way.
12744 * if associativity is right and priority eq, applied also skip
12745 */
12746 prec = PREC(op);
12747 if ((prec > 0 && prec < UNARYPREC) || prec == SPEC_PREC) {
12748 /* not left paren or unary */
12749 if (lasttok != TOK_NUM) {
12750 /* binary op must be preceded by a num */
12751 goto err;
12752 }
12753 while (stackptr != stack) {
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000012754 if (op == TOK_RPAREN) {
12755 /* The algorithm employed here is simple: while we don't
12756 * hit an open paren nor the bottom of the stack, pop
12757 * tokens and apply them */
12758 if (stackptr[-1] == TOK_LPAREN) {
12759 --stackptr;
12760 /* Any operator directly after a */
12761 lasttok = TOK_NUM;
12762 /* close paren should consider itself binary */
12763 goto prologue;
12764 }
12765 } else {
12766 operator prev_prec = PREC(stackptr[-1]);
Eric Andersen90898442003-08-06 11:20:52 +000012767
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000012768 convert_prec_is_assing(prec);
12769 convert_prec_is_assing(prev_prec);
12770 if (prev_prec < prec)
12771 break;
12772 /* check right assoc */
12773 if (prev_prec == prec && is_right_associativity(prec))
12774 break;
12775 }
12776 errcode = arith_apply(*--stackptr, numstack, &numstackptr);
12777 if (errcode) goto ret;
Eric Andersen90898442003-08-06 11:20:52 +000012778 }
12779 if (op == TOK_RPAREN) {
12780 goto err;
12781 }
12782 }
12783
12784 /* Push this operator to the stack and remember it. */
12785 *stackptr++ = lasttok = op;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000012786 prologue:
Eric Andersen90898442003-08-06 11:20:52 +000012787 ++expr;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000012788 } /* while */
Eric Andersen90898442003-08-06 11:20:52 +000012789}
Denis Vlasenko131ae172007-02-18 13:00:19 +000012790#endif /* ASH_MATH_SUPPORT */
Eric Andersen90898442003-08-06 11:20:52 +000012791
12792
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012793/* ============ main() and helpers */
12794
12795/*
12796 * Called to exit the shell.
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012797 */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012798static void exitshell(void) ATTRIBUTE_NORETURN;
12799static void
12800exitshell(void)
12801{
12802 struct jmploc loc;
12803 char *p;
12804 int status;
12805
12806 status = exitstatus;
12807 TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
12808 if (setjmp(loc.loc)) {
12809 if (exception == EXEXIT)
12810/* dash bug: it just does _exit(exitstatus) here
12811 * but we have to do setjobctl(0) first!
12812 * (bug is still not fixed in dash-0.5.3 - if you run dash
12813 * under Midnight Commander, on exit from dash MC is backgrounded) */
12814 status = exitstatus;
12815 goto out;
12816 }
12817 exception_handler = &loc;
12818 p = trap[0];
12819 if (p) {
12820 trap[0] = NULL;
12821 evalstring(p, 0);
12822 }
12823 flush_stdout_stderr();
12824 out:
12825 setjobctl(0);
12826 _exit(status);
12827 /* NOTREACHED */
12828}
12829
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012830static void
12831init(void)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012832{
12833 /* from input.c: */
12834 basepf.nextc = basepf.buf = basebuf;
12835
12836 /* from trap.c: */
12837 signal(SIGCHLD, SIG_DFL);
12838
12839 /* from var.c: */
12840 {
12841 char **envp;
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012842 char ppid[sizeof(int)*3 + 1];
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012843 const char *p;
12844 struct stat st1, st2;
12845
12846 initvar();
12847 for (envp = environ; envp && *envp; envp++) {
12848 if (strchr(*envp, '=')) {
12849 setvareq(*envp, VEXPORT|VTEXTFIXED);
12850 }
12851 }
12852
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012853 snprintf(ppid, sizeof(ppid), "%u", (unsigned) getppid());
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012854 setvar("PPID", ppid, 0);
12855
12856 p = lookupvar("PWD");
12857 if (p)
12858 if (*p != '/' || stat(p, &st1) || stat(".", &st2)
12859 || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino)
12860 p = '\0';
12861 setpwd(p, 0);
12862 }
12863}
12864
12865/*
12866 * Process the shell command line arguments.
12867 */
12868static void
12869procargs(int argc, char **argv)
12870{
12871 int i;
12872 const char *xminusc;
12873 char **xargv;
12874
12875 xargv = argv;
12876 arg0 = xargv[0];
12877 if (argc > 0)
12878 xargv++;
12879 for (i = 0; i < NOPTS; i++)
12880 optlist[i] = 2;
12881 argptr = xargv;
Denis Vlasenko28bf6712008-02-14 15:01:47 +000012882 if (options(1)) {
12883 /* it already printed err message */
12884 raise_exception(EXERROR);
12885 }
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012886 xargv = argptr;
12887 xminusc = minusc;
12888 if (*xargv == NULL) {
12889 if (xminusc)
12890 ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
12891 sflag = 1;
12892 }
12893 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
12894 iflag = 1;
12895 if (mflag == 2)
12896 mflag = iflag;
12897 for (i = 0; i < NOPTS; i++)
12898 if (optlist[i] == 2)
12899 optlist[i] = 0;
12900#if DEBUG == 2
12901 debug = 1;
12902#endif
12903 /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
12904 if (xminusc) {
12905 minusc = *xargv++;
12906 if (*xargv)
12907 goto setarg0;
12908 } else if (!sflag) {
12909 setinputfile(*xargv, 0);
12910 setarg0:
12911 arg0 = *xargv++;
12912 commandname = arg0;
12913 }
12914
12915 shellparam.p = xargv;
12916#if ENABLE_ASH_GETOPTS
12917 shellparam.optind = 1;
12918 shellparam.optoff = -1;
12919#endif
Denis Vlasenko01631112007-12-16 17:20:38 +000012920 /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012921 while (*xargv) {
12922 shellparam.nparam++;
12923 xargv++;
12924 }
12925 optschanged();
12926}
12927
12928/*
12929 * Read /etc/profile or .profile.
12930 */
12931static void
12932read_profile(const char *name)
12933{
12934 int skip;
12935
12936 if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
12937 return;
12938 skip = cmdloop(0);
12939 popfile();
12940 if (skip)
12941 exitshell();
12942}
12943
Denis Vlasenko0c032a42007-02-23 01:03:40 +000012944/*
12945 * This routine is called when an error or an interrupt occurs in an
12946 * interactive shell and control is returned to the main command loop.
12947 */
12948static void
12949reset(void)
12950{
12951 /* from eval.c: */
12952 evalskip = 0;
12953 loopnest = 0;
12954 /* from input.c: */
12955 parselleft = parsenleft = 0; /* clear input buffer */
12956 popallfiles();
12957 /* from parser.c: */
12958 tokpushback = 0;
12959 checkkwd = 0;
12960 /* from redir.c: */
12961 clearredir(0);
12962}
12963
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012964#if PROFILE
12965static short profile_buf[16384];
12966extern int etext();
12967#endif
12968
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012969/*
12970 * Main routine. We initialize things, parse the arguments, execute
12971 * profiles if we're a login shell, and then call cmdloop to execute
12972 * commands. The setjmp call sets up the location to jump to when an
12973 * exception occurs. When an exception occurs the variable "state"
12974 * is used to figure out how far we had gotten.
12975 */
Denis Vlasenko9b49a5e2007-10-11 10:05:36 +000012976int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012977int ash_main(int argc, char **argv)
12978{
12979 char *shinit;
12980 volatile int state;
12981 struct jmploc jmploc;
12982 struct stackmark smark;
12983
Denis Vlasenko01631112007-12-16 17:20:38 +000012984 /* Initialize global data */
12985 INIT_G_misc();
12986 INIT_G_memstack();
12987 INIT_G_var();
Denis Vlasenkoee87ebf2007-12-21 22:18:16 +000012988#if ENABLE_ASH_ALIAS
Denis Vlasenko01631112007-12-16 17:20:38 +000012989 INIT_G_alias();
Denis Vlasenkoee87ebf2007-12-21 22:18:16 +000012990#endif
Denis Vlasenko01631112007-12-16 17:20:38 +000012991 INIT_G_cmdtable();
12992
Denis Vlasenkoa624c112007-02-19 22:45:43 +000012993#if PROFILE
12994 monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
12995#endif
12996
12997#if ENABLE_FEATURE_EDITING
12998 line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
12999#endif
13000 state = 0;
13001 if (setjmp(jmploc.loc)) {
13002 int e;
13003 int s;
13004
13005 reset();
13006
13007 e = exception;
13008 if (e == EXERROR)
13009 exitstatus = 2;
13010 s = state;
13011 if (e == EXEXIT || s == 0 || iflag == 0 || shlvl)
13012 exitshell();
13013
13014 if (e == EXINT) {
13015 outcslow('\n', stderr);
13016 }
13017 popstackmark(&smark);
13018 FORCE_INT_ON; /* enable interrupts */
13019 if (s == 1)
13020 goto state1;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000013021 if (s == 2)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013022 goto state2;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000013023 if (s == 3)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013024 goto state3;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000013025 goto state4;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013026 }
13027 exception_handler = &jmploc;
13028#if DEBUG
13029 opentrace();
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000013030 trace_puts("Shell args: ");
13031 trace_puts_args(argv);
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013032#endif
13033 rootpid = getpid();
13034
13035#if ENABLE_ASH_RANDOM_SUPPORT
13036 rseed = rootpid + time(NULL);
13037#endif
13038 init();
13039 setstackmark(&smark);
13040 procargs(argc, argv);
13041#if ENABLE_FEATURE_EDITING_SAVEHISTORY
13042 if (iflag) {
13043 const char *hp = lookupvar("HISTFILE");
13044
13045 if (hp == NULL) {
13046 hp = lookupvar("HOME");
13047 if (hp != NULL) {
13048 char *defhp = concat_path_file(hp, ".ash_history");
13049 setvar("HISTFILE", defhp, 0);
13050 free(defhp);
13051 }
13052 }
13053 }
13054#endif
13055 if (argv[0] && argv[0][0] == '-')
13056 isloginsh = 1;
13057 if (isloginsh) {
13058 state = 1;
13059 read_profile("/etc/profile");
13060 state1:
13061 state = 2;
13062 read_profile(".profile");
13063 }
13064 state2:
13065 state = 3;
13066 if (
13067#ifndef linux
Denis Vlasenko0c032a42007-02-23 01:03:40 +000013068 getuid() == geteuid() && getgid() == getegid() &&
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013069#endif
Denis Vlasenko0c032a42007-02-23 01:03:40 +000013070 iflag
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013071 ) {
13072 shinit = lookupvar("ENV");
13073 if (shinit != NULL && *shinit != '\0') {
13074 read_profile(shinit);
13075 }
13076 }
13077 state3:
13078 state = 4;
13079 if (minusc)
13080 evalstring(minusc, 0);
13081
13082 if (sflag || minusc == NULL) {
13083#if ENABLE_FEATURE_EDITING_SAVEHISTORY
13084 if ( iflag ) {
13085 const char *hp = lookupvar("HISTFILE");
13086
13087 if (hp != NULL)
13088 line_input_state->hist_file = hp;
13089 }
13090#endif
13091 state4: /* XXX ??? - why isn't this before the "if" statement */
13092 cmdloop(1);
13093 }
13094#if PROFILE
13095 monitor(0);
13096#endif
13097#ifdef GPROF
13098 {
13099 extern void _mcleanup(void);
13100 _mcleanup();
13101 }
13102#endif
13103 exitshell();
13104 /* NOTREACHED */
13105}
13106
Denis Vlasenkoa7189f02006-11-17 20:29:00 +000013107#if DEBUG
Denis Vlasenko8f8f2682006-10-03 21:00:43 +000013108const char *applet_name = "debug stuff usage";
Eric Andersenc470f442003-07-28 09:56:35 +000013109int main(int argc, char **argv)
13110{
13111 return ash_main(argc, argv);
13112}
13113#endif
Eric Andersen74bcd162001-07-30 21:41:37 +000013114
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013115
Eric Andersendf82f612001-06-28 07:46:40 +000013116/*-
13117 * Copyright (c) 1989, 1991, 1993, 1994
Eric Andersen2870d962001-07-02 17:27:21 +000013118 * The Regents of the University of California. All rights reserved.
Eric Andersendf82f612001-06-28 07:46:40 +000013119 *
13120 * This code is derived from software contributed to Berkeley by
13121 * Kenneth Almquist.
13122 *
13123 * Redistribution and use in source and binary forms, with or without
13124 * modification, are permitted provided that the following conditions
13125 * are met:
13126 * 1. Redistributions of source code must retain the above copyright
13127 * notice, this list of conditions and the following disclaimer.
13128 * 2. Redistributions in binary form must reproduce the above copyright
13129 * notice, this list of conditions and the following disclaimer in the
13130 * documentation and/or other materials provided with the distribution.
"Vladimir N. Oleynik"ddc280e2005-12-15 12:01:49 +000013131 * 3. Neither the name of the University nor the names of its contributors
Eric Andersendf82f612001-06-28 07:46:40 +000013132 * may be used to endorse or promote products derived from this software
13133 * without specific prior written permission.
13134 *
13135 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
13136 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
13137 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
13138 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
13139 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
13140 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
13141 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
13142 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
13143 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
13144 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
13145 * SUCH DAMAGE.
13146 */