blob: 3651929c229caed0455f2c19e44b571f25bb1304 [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};
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000205extern struct globals_misc *const ash_ptr_to_globals_misc;
206#define G_misc (*ash_ptr_to_globals_misc)
Denis Vlasenko01631112007-12-16 17:20:38 +0000207#define rootpid (G_misc.rootpid )
208#define shlvl (G_misc.shlvl )
209#define minusc (G_misc.minusc )
210#define curdir (G_misc.curdir )
211#define physdir (G_misc.physdir )
212#define arg0 (G_misc.arg0 )
213#define exception_handler (G_misc.exception_handler)
214#define exception (G_misc.exception )
215#define suppressint (G_misc.suppressint )
216#define intpending (G_misc.intpending )
Denis Vlasenko991a1da2008-02-10 19:02:53 +0000217//#define exsig (G_misc.exsig )
Denis Vlasenko01631112007-12-16 17:20:38 +0000218#define pendingsig (G_misc.pendingsig )
219#define trap (G_misc.trap )
220#define isloginsh (G_misc.isloginsh)
221#define nullstr (G_misc.nullstr )
222#define sigmode (G_misc.sigmode )
223#define gotsig (G_misc.gotsig )
224#define INIT_G_misc() do { \
Denis Vlasenko574f2f42008-02-27 18:41:59 +0000225 (*(struct globals_misc**)&ash_ptr_to_globals_misc) = xzalloc(sizeof(G_misc)); \
226 barrier(); \
Denis Vlasenko01631112007-12-16 17:20:38 +0000227 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;
276
277 intpending = 0;
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +0000278 /* Signal is not automatically unmasked after it is raised,
279 * do it ourself - unmask all signals */
Denis Vlasenko3f165fa2008-03-17 08:29:08 +0000280 sigprocmask_allsigs(SIG_UNBLOCK);
Denis Vlasenko7c139b42007-03-21 20:17:27 +0000281 /* pendingsig = 0; - now done in onsig() */
282
Denis Vlasenkob012b102007-02-19 22:43:01 +0000283 i = EXSIG;
284 if (gotsig[SIGINT - 1] && !trap[SIGINT]) {
285 if (!(rootshell && iflag)) {
Denis Vlasenko991a1da2008-02-10 19:02:53 +0000286 /* Kill ourself with SIGINT */
Denis Vlasenkob012b102007-02-19 22:43:01 +0000287 signal(SIGINT, SIG_DFL);
288 raise(SIGINT);
289 }
290 i = EXINT;
291 }
292 raise_exception(i);
293 /* NOTREACHED */
294}
295
296#if ENABLE_ASH_OPTIMIZE_FOR_SIZE
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000297static void
298int_on(void)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000299{
300 if (--suppressint == 0 && intpending) {
301 raise_interrupt();
302 }
303}
304#define INT_ON int_on()
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000305static void
306force_int_on(void)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000307{
308 suppressint = 0;
309 if (intpending)
310 raise_interrupt();
311}
312#define FORCE_INT_ON force_int_on()
313#else
314#define INT_ON \
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +0000315 do { \
Denis Vlasenkob012b102007-02-19 22:43:01 +0000316 xbarrier(); \
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +0000317 if (--suppressint == 0 && intpending) \
318 raise_interrupt(); \
319 } while (0)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000320#define FORCE_INT_ON \
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +0000321 do { \
Denis Vlasenkob012b102007-02-19 22:43:01 +0000322 xbarrier(); \
323 suppressint = 0; \
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +0000324 if (intpending) \
325 raise_interrupt(); \
326 } while (0)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000327#endif /* ASH_OPTIMIZE_FOR_SIZE */
328
329#define SAVE_INT(v) ((v) = suppressint)
330
331#define RESTORE_INT(v) \
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +0000332 do { \
Glenn L McGrath2f325a02004-08-06 01:49:04 +0000333 xbarrier(); \
Denis Vlasenko5cedb752007-02-18 19:56:41 +0000334 suppressint = (v); \
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +0000335 if (suppressint == 0 && intpending) \
336 raise_interrupt(); \
337 } while (0)
Denis Vlasenkob012b102007-02-19 22:43:01 +0000338
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +0000339/*
340 * Ignore a signal. Only one usage site - in forkchild()
341 */
342static void
343ignoresig(int signo)
344{
345 if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
346 signal(signo, SIG_IGN);
347 }
348 sigmode[signo - 1] = S_HARD_IGN;
349}
350
351/*
352 * Signal handler. Only one usage site - in setsignal()
353 */
354static void
355onsig(int signo)
356{
357 gotsig[signo - 1] = 1;
Denis Vlasenko7c139b42007-03-21 20:17:27 +0000358 pendingsig = signo;
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +0000359
Denis Vlasenko991a1da2008-02-10 19:02:53 +0000360 if ( /* exsig || */ (signo == SIGINT && !trap[SIGINT])) {
Denis Vlasenko7c139b42007-03-21 20:17:27 +0000361 if (!suppressint) {
362 pendingsig = 0;
Denis Vlasenko991a1da2008-02-10 19:02:53 +0000363 raise_interrupt(); /* does not return */
Denis Vlasenko7c139b42007-03-21 20:17:27 +0000364 }
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +0000365 intpending = 1;
366 }
367}
368
Glenn L McGrath9fef17d2002-08-22 18:41:20 +0000369
Denis Vlasenkobc54cff2007-02-23 01:05:52 +0000370/* ============ Stdout/stderr output */
Eric Andersenc470f442003-07-28 09:56:35 +0000371
Eric Andersenc470f442003-07-28 09:56:35 +0000372static void
Denis Vlasenkob012b102007-02-19 22:43:01 +0000373outstr(const char *p, FILE *file)
Denis Vlasenkoe5570da2007-02-19 22:41:55 +0000374{
Denis Vlasenkob012b102007-02-19 22:43:01 +0000375 INT_OFF;
376 fputs(p, file);
377 INT_ON;
378}
379
380static void
381flush_stdout_stderr(void)
382{
383 INT_OFF;
384 fflush(stdout);
385 fflush(stderr);
386 INT_ON;
387}
388
389static void
390flush_stderr(void)
391{
392 INT_OFF;
393 fflush(stderr);
394 INT_ON;
395}
396
397static void
398outcslow(int c, FILE *dest)
399{
400 INT_OFF;
401 putc(c, dest);
402 fflush(dest);
403 INT_ON;
404}
405
406static int out1fmt(const char *, ...) __attribute__((__format__(__printf__,1,2)));
407static int
408out1fmt(const char *fmt, ...)
409{
410 va_list ap;
411 int r;
412
413 INT_OFF;
414 va_start(ap, fmt);
415 r = vprintf(fmt, ap);
416 va_end(ap);
417 INT_ON;
418 return r;
419}
420
421static int fmtstr(char *, size_t, const char *, ...) __attribute__((__format__(__printf__,3,4)));
422static int
423fmtstr(char *outbuf, size_t length, const char *fmt, ...)
424{
425 va_list ap;
426 int ret;
427
428 va_start(ap, fmt);
429 INT_OFF;
430 ret = vsnprintf(outbuf, length, fmt, ap);
431 va_end(ap);
432 INT_ON;
433 return ret;
434}
435
436static void
437out1str(const char *p)
438{
439 outstr(p, stdout);
440}
441
442static void
443out2str(const char *p)
444{
445 outstr(p, stderr);
446 flush_stderr();
447}
448
449
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +0000450/* ============ Parser structures */
Denis Vlasenko4d2183b2007-02-23 01:05:38 +0000451
Denis Vlasenko5651bfc2007-02-23 21:08:58 +0000452/* control characters in argument strings */
453#define CTLESC '\201' /* escape next character */
454#define CTLVAR '\202' /* variable defn */
455#define CTLENDVAR '\203'
456#define CTLBACKQ '\204'
457#define CTLQUOTE 01 /* ored with CTLBACKQ code if in quotes */
458/* CTLBACKQ | CTLQUOTE == '\205' */
459#define CTLARI '\206' /* arithmetic expression */
460#define CTLENDARI '\207'
461#define CTLQUOTEMARK '\210'
462
463/* variable substitution byte (follows CTLVAR) */
464#define VSTYPE 0x0f /* type of variable substitution */
465#define VSNUL 0x10 /* colon--treat the empty string as unset */
466#define VSQUOTE 0x80 /* inside double quotes--suppress splitting */
467
468/* values of VSTYPE field */
Denis Vlasenko92e13c22008-03-25 01:17:40 +0000469#define VSNORMAL 0x1 /* normal variable: $var or ${var} */
470#define VSMINUS 0x2 /* ${var-text} */
471#define VSPLUS 0x3 /* ${var+text} */
472#define VSQUESTION 0x4 /* ${var?message} */
473#define VSASSIGN 0x5 /* ${var=text} */
474#define VSTRIMRIGHT 0x6 /* ${var%pattern} */
475#define VSTRIMRIGHTMAX 0x7 /* ${var%%pattern} */
476#define VSTRIMLEFT 0x8 /* ${var#pattern} */
477#define VSTRIMLEFTMAX 0x9 /* ${var##pattern} */
478#define VSLENGTH 0xa /* ${#var} */
479#if ENABLE_ASH_BASH_COMPAT
480#define VSSUBSTR 0xc /* ${var:position:length} */
481#define VSREPLACE 0xd /* ${var/pattern/replacement} */
482#define VSREPLACEALL 0xe /* ${var//pattern/replacement} */
483#endif
Denis Vlasenko5651bfc2007-02-23 21:08:58 +0000484
Denis Vlasenko6ca409e2007-08-12 20:58:27 +0000485static const char dolatstr[] ALIGN1 = {
486 CTLVAR, VSNORMAL|VSQUOTE, '@', '=', '\0'
487};
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +0000488
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000489#define NCMD 0
490#define NPIPE 1
491#define NREDIR 2
492#define NBACKGND 3
493#define NSUBSHELL 4
494#define NAND 5
495#define NOR 6
496#define NSEMI 7
497#define NIF 8
498#define NWHILE 9
499#define NUNTIL 10
500#define NFOR 11
501#define NCASE 12
502#define NCLIST 13
503#define NDEFUN 14
504#define NARG 15
505#define NTO 16
506#define NCLOBBER 17
507#define NFROM 18
508#define NFROMTO 19
509#define NAPPEND 20
510#define NTOFD 21
511#define NFROMFD 22
512#define NHERE 23
513#define NXHERE 24
514#define NNOT 25
515
516union node;
517
518struct ncmd {
519 int type;
520 union node *assign;
521 union node *args;
522 union node *redirect;
523};
524
525struct npipe {
526 int type;
527 int backgnd;
528 struct nodelist *cmdlist;
529};
530
531struct nredir {
532 int type;
533 union node *n;
534 union node *redirect;
535};
536
537struct nbinary {
538 int type;
539 union node *ch1;
540 union node *ch2;
541};
542
543struct nif {
544 int type;
545 union node *test;
546 union node *ifpart;
547 union node *elsepart;
548};
549
550struct nfor {
551 int type;
552 union node *args;
553 union node *body;
554 char *var;
555};
556
557struct ncase {
558 int type;
559 union node *expr;
560 union node *cases;
561};
562
563struct nclist {
564 int type;
565 union node *next;
566 union node *pattern;
567 union node *body;
568};
569
570struct narg {
571 int type;
572 union node *next;
573 char *text;
574 struct nodelist *backquote;
575};
576
577struct nfile {
578 int type;
579 union node *next;
580 int fd;
581 union node *fname;
582 char *expfname;
583};
584
585struct ndup {
586 int type;
587 union node *next;
588 int fd;
589 int dupfd;
590 union node *vname;
591};
592
593struct nhere {
594 int type;
595 union node *next;
596 int fd;
597 union node *doc;
598};
599
600struct nnot {
601 int type;
602 union node *com;
603};
604
605union node {
606 int type;
607 struct ncmd ncmd;
608 struct npipe npipe;
609 struct nredir nredir;
610 struct nbinary nbinary;
611 struct nif nif;
612 struct nfor nfor;
613 struct ncase ncase;
614 struct nclist nclist;
615 struct narg narg;
616 struct nfile nfile;
617 struct ndup ndup;
618 struct nhere nhere;
619 struct nnot nnot;
620};
621
622struct nodelist {
623 struct nodelist *next;
624 union node *n;
625};
626
627struct funcnode {
628 int count;
629 union node n;
630};
631
Denis Vlasenko5651bfc2007-02-23 21:08:58 +0000632/*
633 * Free a parse tree.
634 */
635static void
636freefunc(struct funcnode *f)
637{
638 if (f && --f->count < 0)
639 free(f);
640}
641
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000642
643/* ============ Debugging output */
644
645#if DEBUG
646
647static FILE *tracefile;
648
649static void
650trace_printf(const char *fmt, ...)
651{
652 va_list va;
653
654 if (debug != 1)
655 return;
656 va_start(va, fmt);
657 vfprintf(tracefile, fmt, va);
658 va_end(va);
659}
660
661static void
662trace_vprintf(const char *fmt, va_list va)
663{
664 if (debug != 1)
665 return;
666 vfprintf(tracefile, fmt, va);
667}
668
669static void
670trace_puts(const char *s)
671{
672 if (debug != 1)
673 return;
674 fputs(s, tracefile);
675}
676
677static void
678trace_puts_quoted(char *s)
679{
680 char *p;
681 char c;
682
683 if (debug != 1)
684 return;
685 putc('"', tracefile);
686 for (p = s; *p; p++) {
687 switch (*p) {
688 case '\n': c = 'n'; goto backslash;
689 case '\t': c = 't'; goto backslash;
690 case '\r': c = 'r'; goto backslash;
691 case '"': c = '"'; goto backslash;
692 case '\\': c = '\\'; goto backslash;
693 case CTLESC: c = 'e'; goto backslash;
694 case CTLVAR: c = 'v'; goto backslash;
695 case CTLVAR+CTLQUOTE: c = 'V'; goto backslash;
696 case CTLBACKQ: c = 'q'; goto backslash;
697 case CTLBACKQ+CTLQUOTE: c = 'Q'; goto backslash;
698 backslash:
699 putc('\\', tracefile);
700 putc(c, tracefile);
701 break;
702 default:
703 if (*p >= ' ' && *p <= '~')
704 putc(*p, tracefile);
705 else {
706 putc('\\', tracefile);
707 putc(*p >> 6 & 03, tracefile);
708 putc(*p >> 3 & 07, tracefile);
709 putc(*p & 07, tracefile);
710 }
711 break;
712 }
713 }
714 putc('"', tracefile);
715}
716
717static void
718trace_puts_args(char **ap)
719{
720 if (debug != 1)
721 return;
722 if (!*ap)
723 return;
724 while (1) {
725 trace_puts_quoted(*ap);
726 if (!*++ap) {
727 putc('\n', tracefile);
728 break;
729 }
730 putc(' ', tracefile);
731 }
732}
733
734static void
735opentrace(void)
736{
737 char s[100];
738#ifdef O_APPEND
739 int flags;
740#endif
741
742 if (debug != 1) {
743 if (tracefile)
744 fflush(tracefile);
745 /* leave open because libedit might be using it */
746 return;
747 }
748 strcpy(s, "./trace");
749 if (tracefile) {
750 if (!freopen(s, "a", tracefile)) {
751 fprintf(stderr, "Can't re-open %s\n", s);
752 debug = 0;
753 return;
754 }
755 } else {
756 tracefile = fopen(s, "a");
757 if (tracefile == NULL) {
758 fprintf(stderr, "Can't open %s\n", s);
759 debug = 0;
760 return;
761 }
762 }
763#ifdef O_APPEND
Denis Vlasenkod37f2222007-08-19 13:42:08 +0000764 flags = fcntl(fileno(tracefile), F_GETFL);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000765 if (flags >= 0)
766 fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
767#endif
768 setlinebuf(tracefile);
769 fputs("\nTracing started.\n", tracefile);
770}
771
772static void
773indent(int amount, char *pfx, FILE *fp)
774{
775 int i;
776
777 for (i = 0; i < amount; i++) {
778 if (pfx && i == amount - 1)
779 fputs(pfx, fp);
780 putc('\t', fp);
781 }
782}
783
784/* little circular references here... */
785static void shtree(union node *n, int ind, char *pfx, FILE *fp);
786
787static void
788sharg(union node *arg, FILE *fp)
789{
790 char *p;
791 struct nodelist *bqlist;
792 int subtype;
793
794 if (arg->type != NARG) {
795 out1fmt("<node type %d>\n", arg->type);
796 abort();
797 }
798 bqlist = arg->narg.backquote;
799 for (p = arg->narg.text; *p; p++) {
800 switch (*p) {
801 case CTLESC:
802 putc(*++p, fp);
803 break;
804 case CTLVAR:
805 putc('$', fp);
806 putc('{', fp);
807 subtype = *++p;
808 if (subtype == VSLENGTH)
809 putc('#', fp);
810
811 while (*p != '=')
812 putc(*p++, fp);
813
814 if (subtype & VSNUL)
815 putc(':', fp);
816
817 switch (subtype & VSTYPE) {
818 case VSNORMAL:
819 putc('}', fp);
820 break;
821 case VSMINUS:
822 putc('-', fp);
823 break;
824 case VSPLUS:
825 putc('+', fp);
826 break;
827 case VSQUESTION:
828 putc('?', fp);
829 break;
830 case VSASSIGN:
831 putc('=', fp);
832 break;
833 case VSTRIMLEFT:
834 putc('#', fp);
835 break;
836 case VSTRIMLEFTMAX:
837 putc('#', fp);
838 putc('#', fp);
839 break;
840 case VSTRIMRIGHT:
841 putc('%', fp);
842 break;
843 case VSTRIMRIGHTMAX:
844 putc('%', fp);
845 putc('%', fp);
846 break;
847 case VSLENGTH:
848 break;
849 default:
850 out1fmt("<subtype %d>", subtype);
851 }
852 break;
853 case CTLENDVAR:
854 putc('}', fp);
855 break;
856 case CTLBACKQ:
857 case CTLBACKQ|CTLQUOTE:
858 putc('$', fp);
859 putc('(', fp);
860 shtree(bqlist->n, -1, NULL, fp);
861 putc(')', fp);
862 break;
863 default:
864 putc(*p, fp);
865 break;
866 }
867 }
868}
869
870static void
871shcmd(union node *cmd, FILE *fp)
872{
873 union node *np;
874 int first;
875 const char *s;
876 int dftfd;
877
878 first = 1;
879 for (np = cmd->ncmd.args; np; np = np->narg.next) {
Denis Vlasenko40ba9982007-07-14 00:48:29 +0000880 if (!first)
881 putc(' ', fp);
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000882 sharg(np, fp);
883 first = 0;
884 }
885 for (np = cmd->ncmd.redirect; np; np = np->nfile.next) {
Denis Vlasenko40ba9982007-07-14 00:48:29 +0000886 if (!first)
887 putc(' ', fp);
888 dftfd = 0;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000889 switch (np->nfile.type) {
Denis Vlasenko40ba9982007-07-14 00:48:29 +0000890 case NTO: s = ">>"+1; dftfd = 1; break;
891 case NCLOBBER: s = ">|"; dftfd = 1; break;
892 case NAPPEND: s = ">>"; dftfd = 1; break;
893 case NTOFD: s = ">&"; dftfd = 1; break;
894 case NFROM: s = "<"; break;
895 case NFROMFD: s = "<&"; break;
896 case NFROMTO: s = "<>"; break;
897 default: s = "*error*"; break;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000898 }
899 if (np->nfile.fd != dftfd)
900 fprintf(fp, "%d", np->nfile.fd);
901 fputs(s, fp);
902 if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
903 fprintf(fp, "%d", np->ndup.dupfd);
904 } else {
905 sharg(np->nfile.fname, fp);
906 }
907 first = 0;
908 }
909}
910
911static void
912shtree(union node *n, int ind, char *pfx, FILE *fp)
913{
914 struct nodelist *lp;
915 const char *s;
916
917 if (n == NULL)
918 return;
919
920 indent(ind, pfx, fp);
921 switch (n->type) {
922 case NSEMI:
923 s = "; ";
924 goto binop;
925 case NAND:
926 s = " && ";
927 goto binop;
928 case NOR:
929 s = " || ";
930 binop:
931 shtree(n->nbinary.ch1, ind, NULL, fp);
932 /* if (ind < 0) */
933 fputs(s, fp);
934 shtree(n->nbinary.ch2, ind, NULL, fp);
935 break;
936 case NCMD:
937 shcmd(n, fp);
938 if (ind >= 0)
939 putc('\n', fp);
940 break;
941 case NPIPE:
942 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
943 shcmd(lp->n, fp);
944 if (lp->next)
945 fputs(" | ", fp);
946 }
947 if (n->npipe.backgnd)
948 fputs(" &", fp);
949 if (ind >= 0)
950 putc('\n', fp);
951 break;
952 default:
953 fprintf(fp, "<node type %d>", n->type);
954 if (ind >= 0)
955 putc('\n', fp);
956 break;
957 }
958}
959
960static void
961showtree(union node *n)
962{
963 trace_puts("showtree called\n");
964 shtree(n, 1, NULL, stdout);
965}
966
967#define TRACE(param) trace_printf param
968#define TRACEV(param) trace_vprintf param
969
970#else
971
972#define TRACE(param)
973#define TRACEV(param)
974
975#endif /* DEBUG */
976
977
Denis Vlasenko5651bfc2007-02-23 21:08:58 +0000978/* ============ Parser data */
979
980/*
Denis Vlasenkob012b102007-02-19 22:43:01 +0000981 * ash_vmsg() needs parsefile->fd, hence parsefile definition is moved up.
982 */
Denis Vlasenkoaa744452007-02-23 01:04:22 +0000983struct strlist {
984 struct strlist *next;
985 char *text;
986};
987
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000988#if ENABLE_ASH_ALIAS
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000989struct alias;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +0000990#endif
991
Denis Vlasenkob012b102007-02-19 22:43:01 +0000992struct strpush {
993 struct strpush *prev; /* preceding string on stack */
994 char *prevstring;
995 int prevnleft;
996#if ENABLE_ASH_ALIAS
997 struct alias *ap; /* if push was associated with an alias */
998#endif
999 char *string; /* remember the string since it may change */
1000};
1001
1002struct parsefile {
1003 struct parsefile *prev; /* preceding file on stack */
1004 int linno; /* current line */
1005 int fd; /* file descriptor (or -1 if string) */
1006 int nleft; /* number of chars left in this line */
1007 int lleft; /* number of chars left in this buffer */
1008 char *nextc; /* next char in buffer */
1009 char *buf; /* input buffer */
1010 struct strpush *strpush; /* for pushing strings at this level */
1011 struct strpush basestrpush; /* so pushing one is fast */
1012};
1013
1014static struct parsefile basepf; /* top level input file */
1015static struct parsefile *parsefile = &basepf; /* current input file */
1016static int startlinno; /* line # where last token started */
1017static char *commandname; /* currently executing command */
1018static struct strlist *cmdenviron; /* environment for builtin command */
1019static int exitstatus; /* exit status of last command */
Denis Vlasenkob012b102007-02-19 22:43:01 +00001020
1021
1022/* ============ Message printing */
1023
1024static void
1025ash_vmsg(const char *msg, va_list ap)
1026{
1027 fprintf(stderr, "%s: ", arg0);
1028 if (commandname) {
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00001029 if (strcmp(arg0, commandname))
1030 fprintf(stderr, "%s: ", commandname);
1031 if (!iflag || parsefile->fd)
1032 fprintf(stderr, "line %d: ", startlinno);
Eric Andersenc470f442003-07-28 09:56:35 +00001033 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00001034 vfprintf(stderr, msg, ap);
1035 outcslow('\n', stderr);
Eric Andersenc470f442003-07-28 09:56:35 +00001036}
Denis Vlasenkob012b102007-02-19 22:43:01 +00001037
1038/*
1039 * Exverror is called to raise the error exception. If the second argument
1040 * is not NULL then error prints an error message using printf style
1041 * formatting. It then raises the error exception.
1042 */
1043static void ash_vmsg_and_raise(int, const char *, va_list) ATTRIBUTE_NORETURN;
1044static void
1045ash_vmsg_and_raise(int cond, const char *msg, va_list ap)
Eric Andersenc470f442003-07-28 09:56:35 +00001046{
Denis Vlasenkob012b102007-02-19 22:43:01 +00001047#if DEBUG
1048 if (msg) {
1049 TRACE(("ash_vmsg_and_raise(%d, \"", cond));
1050 TRACEV((msg, ap));
1051 TRACE(("\") pid=%d\n", getpid()));
1052 } else
1053 TRACE(("ash_vmsg_and_raise(%d, NULL) pid=%d\n", cond, getpid()));
1054 if (msg)
1055#endif
1056 ash_vmsg(msg, ap);
1057
1058 flush_stdout_stderr();
1059 raise_exception(cond);
1060 /* NOTREACHED */
Eric Andersenc470f442003-07-28 09:56:35 +00001061}
Denis Vlasenkob012b102007-02-19 22:43:01 +00001062
1063static void ash_msg_and_raise_error(const char *, ...) ATTRIBUTE_NORETURN;
1064static void
1065ash_msg_and_raise_error(const char *msg, ...)
1066{
1067 va_list ap;
1068
1069 va_start(ap, msg);
1070 ash_vmsg_and_raise(EXERROR, msg, ap);
1071 /* NOTREACHED */
1072 va_end(ap);
1073}
1074
1075static void ash_msg_and_raise(int, const char *, ...) ATTRIBUTE_NORETURN;
1076static void
1077ash_msg_and_raise(int cond, const char *msg, ...)
1078{
1079 va_list ap;
1080
1081 va_start(ap, msg);
1082 ash_vmsg_and_raise(cond, msg, ap);
1083 /* NOTREACHED */
1084 va_end(ap);
1085}
1086
1087/*
1088 * error/warning routines for external builtins
1089 */
1090static void
1091ash_msg(const char *fmt, ...)
1092{
1093 va_list ap;
1094
1095 va_start(ap, fmt);
1096 ash_vmsg(fmt, ap);
1097 va_end(ap);
1098}
1099
1100/*
1101 * Return a string describing an error. The returned string may be a
1102 * pointer to a static buffer that will be overwritten on the next call.
1103 * Action describes the operation that got the error.
1104 */
1105static const char *
1106errmsg(int e, const char *em)
1107{
1108 if (e == ENOENT || e == ENOTDIR) {
1109 return em;
1110 }
1111 return strerror(e);
1112}
1113
1114
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001115/* ============ Memory allocation */
1116
1117/*
1118 * It appears that grabstackstr() will barf with such alignments
1119 * because stalloc() will return a string allocated in a new stackblock.
1120 */
1121#define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
1122enum {
1123 /* Most machines require the value returned from malloc to be aligned
1124 * in some way. The following macro will get this right
1125 * on many machines. */
1126 SHELL_SIZE = sizeof(union {int i; char *cp; double d; }) - 1,
1127 /* Minimum size of a block */
Denis Vlasenko01631112007-12-16 17:20:38 +00001128 MINSIZE = SHELL_ALIGN(504),
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001129};
1130
1131struct stack_block {
1132 struct stack_block *prev;
1133 char space[MINSIZE];
1134};
1135
1136struct stackmark {
1137 struct stack_block *stackp;
1138 char *stacknxt;
1139 size_t stacknleft;
1140 struct stackmark *marknext;
1141};
1142
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001143
Denis Vlasenko01631112007-12-16 17:20:38 +00001144struct globals_memstack {
1145 struct stack_block *g_stackp; // = &stackbase;
1146 struct stackmark *markp;
1147 char *g_stacknxt; // = stackbase.space;
1148 char *sstrend; // = stackbase.space + MINSIZE;
1149 size_t g_stacknleft; // = MINSIZE;
1150 int herefd; // = -1;
1151 struct stack_block stackbase;
1152};
Denis Vlasenko574f2f42008-02-27 18:41:59 +00001153extern struct globals_memstack *const ash_ptr_to_globals_memstack;
1154#define G_memstack (*ash_ptr_to_globals_memstack)
Denis Vlasenko01631112007-12-16 17:20:38 +00001155#define g_stackp (G_memstack.g_stackp )
1156#define markp (G_memstack.markp )
1157#define g_stacknxt (G_memstack.g_stacknxt )
1158#define sstrend (G_memstack.sstrend )
1159#define g_stacknleft (G_memstack.g_stacknleft)
1160#define herefd (G_memstack.herefd )
1161#define stackbase (G_memstack.stackbase )
1162#define INIT_G_memstack() do { \
Denis Vlasenko574f2f42008-02-27 18:41:59 +00001163 (*(struct globals_memstack**)&ash_ptr_to_globals_memstack) = xzalloc(sizeof(G_memstack)); \
1164 barrier(); \
Denis Vlasenko01631112007-12-16 17:20:38 +00001165 g_stackp = &stackbase; \
1166 g_stacknxt = stackbase.space; \
1167 g_stacknleft = MINSIZE; \
1168 sstrend = stackbase.space + MINSIZE; \
1169 herefd = -1; \
1170} while (0)
1171
1172#define stackblock() ((void *)g_stacknxt)
1173#define stackblocksize() g_stacknleft
1174
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001175
1176static void *
1177ckrealloc(void * p, size_t nbytes)
1178{
1179 p = realloc(p, nbytes);
1180 if (!p)
1181 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1182 return p;
1183}
1184
1185static void *
1186ckmalloc(size_t nbytes)
1187{
1188 return ckrealloc(NULL, nbytes);
1189}
1190
Denis Vlasenko597906c2008-02-20 16:38:54 +00001191static void *
1192ckzalloc(size_t nbytes)
1193{
1194 return memset(ckmalloc(nbytes), 0, nbytes);
1195}
1196
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001197/*
1198 * Make a copy of a string in safe storage.
1199 */
1200static char *
1201ckstrdup(const char *s)
1202{
1203 char *p = strdup(s);
1204 if (!p)
1205 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1206 return p;
1207}
1208
1209/*
1210 * Parse trees for commands are allocated in lifo order, so we use a stack
1211 * to make this more efficient, and also to avoid all sorts of exception
1212 * handling code to handle interrupts in the middle of a parse.
1213 *
1214 * The size 504 was chosen because the Ultrix malloc handles that size
1215 * well.
1216 */
1217static void *
1218stalloc(size_t nbytes)
1219{
1220 char *p;
1221 size_t aligned;
1222
1223 aligned = SHELL_ALIGN(nbytes);
Denis Vlasenko01631112007-12-16 17:20:38 +00001224 if (aligned > g_stacknleft) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001225 size_t len;
1226 size_t blocksize;
1227 struct stack_block *sp;
1228
1229 blocksize = aligned;
1230 if (blocksize < MINSIZE)
1231 blocksize = MINSIZE;
1232 len = sizeof(struct stack_block) - MINSIZE + blocksize;
1233 if (len < blocksize)
1234 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1235 INT_OFF;
1236 sp = ckmalloc(len);
Denis Vlasenko01631112007-12-16 17:20:38 +00001237 sp->prev = g_stackp;
1238 g_stacknxt = sp->space;
1239 g_stacknleft = blocksize;
1240 sstrend = g_stacknxt + blocksize;
1241 g_stackp = sp;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001242 INT_ON;
1243 }
Denis Vlasenko01631112007-12-16 17:20:38 +00001244 p = g_stacknxt;
1245 g_stacknxt += aligned;
1246 g_stacknleft -= aligned;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001247 return p;
1248}
1249
Denis Vlasenko597906c2008-02-20 16:38:54 +00001250static void *
1251stzalloc(size_t nbytes)
1252{
1253 return memset(stalloc(nbytes), 0, nbytes);
1254}
1255
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001256static void
1257stunalloc(void *p)
1258{
1259#if DEBUG
Denis Vlasenko01631112007-12-16 17:20:38 +00001260 if (!p || (g_stacknxt < (char *)p) || ((char *)p < g_stackp->space)) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001261 write(2, "stunalloc\n", 10);
1262 abort();
1263 }
1264#endif
Denis Vlasenko01631112007-12-16 17:20:38 +00001265 g_stacknleft += g_stacknxt - (char *)p;
1266 g_stacknxt = p;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001267}
1268
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001269/*
1270 * Like strdup but works with the ash stack.
1271 */
1272static char *
1273ststrdup(const char *p)
1274{
1275 size_t len = strlen(p) + 1;
1276 return memcpy(stalloc(len), p, len);
1277}
1278
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001279static void
1280setstackmark(struct stackmark *mark)
1281{
Denis Vlasenko01631112007-12-16 17:20:38 +00001282 mark->stackp = g_stackp;
1283 mark->stacknxt = g_stacknxt;
1284 mark->stacknleft = g_stacknleft;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001285 mark->marknext = markp;
1286 markp = mark;
1287}
1288
1289static void
1290popstackmark(struct stackmark *mark)
1291{
1292 struct stack_block *sp;
1293
Denis Vlasenko93ebd4f2007-03-13 20:55:36 +00001294 if (!mark->stackp)
1295 return;
1296
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001297 INT_OFF;
1298 markp = mark->marknext;
Denis Vlasenko01631112007-12-16 17:20:38 +00001299 while (g_stackp != mark->stackp) {
1300 sp = g_stackp;
1301 g_stackp = sp->prev;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001302 free(sp);
1303 }
Denis Vlasenko01631112007-12-16 17:20:38 +00001304 g_stacknxt = mark->stacknxt;
1305 g_stacknleft = mark->stacknleft;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001306 sstrend = mark->stacknxt + mark->stacknleft;
1307 INT_ON;
1308}
1309
1310/*
1311 * When the parser reads in a string, it wants to stick the string on the
1312 * stack and only adjust the stack pointer when it knows how big the
1313 * string is. Stackblock (defined in stack.h) returns a pointer to a block
1314 * of space on top of the stack and stackblocklen returns the length of
1315 * this block. Growstackblock will grow this space by at least one byte,
1316 * possibly moving it (like realloc). Grabstackblock actually allocates the
1317 * part of the block that has been used.
1318 */
1319static void
1320growstackblock(void)
1321{
1322 size_t newlen;
1323
Denis Vlasenko01631112007-12-16 17:20:38 +00001324 newlen = g_stacknleft * 2;
1325 if (newlen < g_stacknleft)
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001326 ash_msg_and_raise_error(bb_msg_memory_exhausted);
1327 if (newlen < 128)
1328 newlen += 128;
1329
Denis Vlasenko01631112007-12-16 17:20:38 +00001330 if (g_stacknxt == g_stackp->space && g_stackp != &stackbase) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001331 struct stack_block *oldstackp;
1332 struct stackmark *xmark;
1333 struct stack_block *sp;
1334 struct stack_block *prevstackp;
1335 size_t grosslen;
1336
1337 INT_OFF;
Denis Vlasenko01631112007-12-16 17:20:38 +00001338 oldstackp = g_stackp;
1339 sp = g_stackp;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001340 prevstackp = sp->prev;
1341 grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
1342 sp = ckrealloc(sp, grosslen);
1343 sp->prev = prevstackp;
Denis Vlasenko01631112007-12-16 17:20:38 +00001344 g_stackp = sp;
1345 g_stacknxt = sp->space;
1346 g_stacknleft = newlen;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001347 sstrend = sp->space + newlen;
1348
1349 /*
1350 * Stack marks pointing to the start of the old block
1351 * must be relocated to point to the new block
1352 */
1353 xmark = markp;
1354 while (xmark != NULL && xmark->stackp == oldstackp) {
Denis Vlasenko01631112007-12-16 17:20:38 +00001355 xmark->stackp = g_stackp;
1356 xmark->stacknxt = g_stacknxt;
1357 xmark->stacknleft = g_stacknleft;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001358 xmark = xmark->marknext;
1359 }
1360 INT_ON;
1361 } else {
Denis Vlasenko01631112007-12-16 17:20:38 +00001362 char *oldspace = g_stacknxt;
1363 int oldlen = g_stacknleft;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001364 char *p = stalloc(newlen);
1365
1366 /* free the space we just allocated */
Denis Vlasenko01631112007-12-16 17:20:38 +00001367 g_stacknxt = memcpy(p, oldspace, oldlen);
1368 g_stacknleft += newlen;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001369 }
1370}
1371
1372static void
1373grabstackblock(size_t len)
1374{
1375 len = SHELL_ALIGN(len);
Denis Vlasenko01631112007-12-16 17:20:38 +00001376 g_stacknxt += len;
1377 g_stacknleft -= len;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001378}
1379
1380/*
1381 * The following routines are somewhat easier to use than the above.
1382 * The user declares a variable of type STACKSTR, which may be declared
1383 * to be a register. The macro STARTSTACKSTR initializes things. Then
1384 * the user uses the macro STPUTC to add characters to the string. In
1385 * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
1386 * grown as necessary. When the user is done, she can just leave the
1387 * string there and refer to it using stackblock(). Or she can allocate
1388 * the space for it using grabstackstr(). If it is necessary to allow
1389 * someone else to use the stack temporarily and then continue to grow
1390 * the string, the user should use grabstack to allocate the space, and
1391 * then call ungrabstr(p) to return to the previous mode of operation.
1392 *
1393 * USTPUTC is like STPUTC except that it doesn't check for overflow.
1394 * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
1395 * is space for at least one character.
1396 */
1397static void *
1398growstackstr(void)
1399{
1400 size_t len = stackblocksize();
1401 if (herefd >= 0 && len >= 1024) {
1402 full_write(herefd, stackblock(), len);
1403 return stackblock();
1404 }
1405 growstackblock();
1406 return stackblock() + len;
1407}
1408
1409/*
1410 * Called from CHECKSTRSPACE.
1411 */
1412static char *
1413makestrspace(size_t newlen, char *p)
1414{
Denis Vlasenko01631112007-12-16 17:20:38 +00001415 size_t len = p - g_stacknxt;
Denis Vlasenko0c032a42007-02-23 01:03:40 +00001416 size_t size = stackblocksize();
1417
1418 for (;;) {
1419 size_t nleft;
1420
1421 size = stackblocksize();
1422 nleft = size - len;
1423 if (nleft >= newlen)
1424 break;
1425 growstackblock();
1426 }
1427 return stackblock() + len;
1428}
1429
1430static char *
1431stack_nputstr(const char *s, size_t n, char *p)
1432{
1433 p = makestrspace(n, p);
1434 p = memcpy(p, s, n) + n;
1435 return p;
1436}
1437
1438static char *
1439stack_putstr(const char *s, char *p)
1440{
1441 return stack_nputstr(s, strlen(s), p);
1442}
1443
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001444static char *
1445_STPUTC(int c, char *p)
1446{
1447 if (p == sstrend)
1448 p = growstackstr();
1449 *p++ = c;
1450 return p;
1451}
1452
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00001453#define STARTSTACKSTR(p) ((p) = stackblock())
1454#define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001455#define CHECKSTRSPACE(n, p) \
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00001456 do { \
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001457 char *q = (p); \
1458 size_t l = (n); \
1459 size_t m = sstrend - q; \
1460 if (l > m) \
1461 (p) = makestrspace(l, q); \
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00001462 } while (0)
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001463#define USTPUTC(c, p) (*p++ = (c))
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00001464#define STACKSTRNUL(p) \
1465 do { \
1466 if ((p) == sstrend) \
1467 p = growstackstr(); \
1468 *p = '\0'; \
1469 } while (0)
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001470#define STUNPUTC(p) (--p)
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00001471#define STTOPC(p) (p[-1])
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001472#define STADJUST(amount, p) (p += (amount))
1473
1474#define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
1475#define ungrabstackstr(s, p) stunalloc((s))
1476#define stackstrend() ((void *)sstrend)
1477
1478
1479/* ============ String helpers */
1480
1481/*
1482 * prefix -- see if pfx is a prefix of string.
1483 */
1484static char *
1485prefix(const char *string, const char *pfx)
1486{
1487 while (*pfx) {
1488 if (*pfx++ != *string++)
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00001489 return NULL;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001490 }
1491 return (char *) string;
1492}
1493
1494/*
1495 * Check for a valid number. This should be elsewhere.
1496 */
1497static int
1498is_number(const char *p)
1499{
1500 do {
1501 if (!isdigit(*p))
1502 return 0;
1503 } while (*++p != '\0');
1504 return 1;
1505}
1506
1507/*
1508 * Convert a string of digits to an integer, printing an error message on
1509 * failure.
1510 */
1511static int
1512number(const char *s)
1513{
1514 if (!is_number(s))
1515 ash_msg_and_raise_error(illnum, s);
1516 return atoi(s);
1517}
1518
1519/*
1520 * Produce a possibly single quoted string suitable as input to the shell.
1521 * The return string is allocated on the stack.
1522 */
1523static char *
1524single_quote(const char *s)
1525{
1526 char *p;
1527
1528 STARTSTACKSTR(p);
1529
1530 do {
1531 char *q;
1532 size_t len;
1533
1534 len = strchrnul(s, '\'') - s;
1535
1536 q = p = makestrspace(len + 3, p);
1537
1538 *q++ = '\'';
1539 q = memcpy(q, s, len) + len;
1540 *q++ = '\'';
1541 s += len;
1542
1543 STADJUST(q - p, p);
1544
1545 len = strspn(s, "'");
1546 if (!len)
1547 break;
1548
1549 q = p = makestrspace(len + 3, p);
1550
1551 *q++ = '"';
1552 q = memcpy(q, s, len) + len;
1553 *q++ = '"';
1554 s += len;
1555
1556 STADJUST(q - p, p);
1557 } while (*s);
1558
1559 USTPUTC(0, p);
1560
1561 return stackblock();
1562}
1563
1564
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00001565/* ============ nextopt */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001566
1567static char **argptr; /* argument list for builtin commands */
1568static char *optionarg; /* set by nextopt (like getopt) */
1569static char *optptr; /* used by nextopt */
1570
1571/*
1572 * XXX - should get rid of. have all builtins use getopt(3). the
1573 * library getopt must have the BSD extension static variable "optreset"
1574 * otherwise it can't be used within the shell safely.
1575 *
1576 * Standard option processing (a la getopt) for builtin routines. The
1577 * only argument that is passed to nextopt is the option string; the
1578 * other arguments are unnecessary. It return the character, or '\0' on
1579 * end of input.
1580 */
1581static int
1582nextopt(const char *optstring)
1583{
1584 char *p;
1585 const char *q;
1586 char c;
1587
1588 p = optptr;
1589 if (p == NULL || *p == '\0') {
1590 p = *argptr;
1591 if (p == NULL || *p != '-' || *++p == '\0')
1592 return '\0';
1593 argptr++;
1594 if (LONE_DASH(p)) /* check for "--" */
1595 return '\0';
1596 }
1597 c = *p++;
1598 for (q = optstring; *q != c; ) {
1599 if (*q == '\0')
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00001600 ash_msg_and_raise_error("illegal option -%c", c);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001601 if (*++q == ':')
1602 q++;
1603 }
1604 if (*++q == ':') {
1605 if (*p == '\0' && (p = *argptr++) == NULL)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00001606 ash_msg_and_raise_error("no arg for -%c option", c);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001607 optionarg = p;
1608 p = NULL;
1609 }
1610 optptr = p;
1611 return c;
1612}
1613
1614
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00001615/* ============ Math support definitions */
1616
1617#if ENABLE_ASH_MATH_SUPPORT_64
1618typedef int64_t arith_t;
1619#define arith_t_type long long
1620#else
1621typedef long arith_t;
1622#define arith_t_type long
1623#endif
1624
1625#if ENABLE_ASH_MATH_SUPPORT
1626static arith_t dash_arith(const char *);
1627static arith_t arith(const char *expr, int *perrcode);
1628#endif
1629
1630#if ENABLE_ASH_RANDOM_SUPPORT
1631static unsigned long rseed;
1632#ifndef DYNAMIC_VAR
1633#define DYNAMIC_VAR
1634#endif
1635#endif
1636
1637
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00001638/* ============ Shell variables */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001639
Denis Vlasenko01631112007-12-16 17:20:38 +00001640/*
1641 * The parsefile structure pointed to by the global variable parsefile
1642 * contains information about the current file being read.
1643 */
1644struct redirtab {
1645 struct redirtab *next;
1646 int renamed[10];
1647 int nullredirs;
1648};
1649
1650struct shparam {
1651 int nparam; /* # of positional parameters (without $0) */
1652#if ENABLE_ASH_GETOPTS
1653 int optind; /* next parameter to be processed by getopts */
1654 int optoff; /* used by getopts */
1655#endif
1656 unsigned char malloced; /* if parameter list dynamically allocated */
1657 char **p; /* parameter list */
1658};
1659
1660/*
1661 * Free the list of positional parameters.
1662 */
1663static void
1664freeparam(volatile struct shparam *param)
1665{
1666 char **ap;
1667
1668 if (param->malloced) {
1669 for (ap = param->p; *ap; ap++)
1670 free(*ap);
1671 free(param->p);
1672 }
1673}
1674
1675#if ENABLE_ASH_GETOPTS
1676static void getoptsreset(const char *value);
1677#endif
1678
1679struct var {
1680 struct var *next; /* next entry in hash list */
1681 int flags; /* flags are defined above */
1682 const char *text; /* name=value */
1683 void (*func)(const char *); /* function to be called when */
1684 /* the variable gets set/unset */
1685};
1686
1687struct localvar {
1688 struct localvar *next; /* next local variable in list */
1689 struct var *vp; /* the variable that was made local */
1690 int flags; /* saved flags */
1691 const char *text; /* saved text */
1692};
1693
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001694/* flags */
1695#define VEXPORT 0x01 /* variable is exported */
1696#define VREADONLY 0x02 /* variable cannot be modified */
1697#define VSTRFIXED 0x04 /* variable struct is statically allocated */
1698#define VTEXTFIXED 0x08 /* text is statically allocated */
1699#define VSTACK 0x10 /* text is allocated on the stack */
1700#define VUNSET 0x20 /* the variable is not set */
1701#define VNOFUNC 0x40 /* don't call the callback function */
1702#define VNOSET 0x80 /* do not set variable - just readonly test */
1703#define VNOSAVE 0x100 /* when text is on the heap before setvareq */
1704#ifdef DYNAMIC_VAR
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00001705# define VDYNAMIC 0x200 /* dynamic variable */
1706#else
1707# define VDYNAMIC 0
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001708#endif
1709
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001710#ifdef IFS_BROKEN
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00001711static const char defifsvar[] ALIGN1 = "IFS= \t\n";
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001712#define defifs (defifsvar + 4)
1713#else
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00001714static const char defifs[] ALIGN1 = " \t\n";
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001715#endif
1716
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00001717
Denis Vlasenko01631112007-12-16 17:20:38 +00001718/* Need to be before varinit_data[] */
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00001719#if ENABLE_LOCALE_SUPPORT
Denis Vlasenkoa8915072007-02-23 21:10:06 +00001720static void
1721change_lc_all(const char *value)
1722{
1723 if (value && *value != '\0')
1724 setlocale(LC_ALL, value);
1725}
1726static void
1727change_lc_ctype(const char *value)
1728{
1729 if (value && *value != '\0')
1730 setlocale(LC_CTYPE, value);
1731}
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00001732#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001733#if ENABLE_ASH_MAIL
1734static void chkmail(void);
1735static void changemail(const char *);
1736#endif
1737static void changepath(const char *);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001738#if ENABLE_ASH_RANDOM_SUPPORT
1739static void change_random(const char *);
1740#endif
1741
Denis Vlasenko01631112007-12-16 17:20:38 +00001742static const struct {
1743 int flags;
1744 const char *text;
1745 void (*func)(const char *);
1746} varinit_data[] = {
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001747#ifdef IFS_BROKEN
Denis Vlasenko01631112007-12-16 17:20:38 +00001748 { VSTRFIXED|VTEXTFIXED , defifsvar , NULL },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001749#else
Denis Vlasenko01631112007-12-16 17:20:38 +00001750 { VSTRFIXED|VTEXTFIXED|VUNSET, "IFS\0" , NULL },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001751#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001752#if ENABLE_ASH_MAIL
Denis Vlasenko01631112007-12-16 17:20:38 +00001753 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL\0" , changemail },
1754 { VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH\0", changemail },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001755#endif
Denis Vlasenko01631112007-12-16 17:20:38 +00001756 { VSTRFIXED|VTEXTFIXED , bb_PATH_root_path, changepath },
1757 { VSTRFIXED|VTEXTFIXED , "PS1=$ " , NULL },
1758 { VSTRFIXED|VTEXTFIXED , "PS2=> " , NULL },
1759 { VSTRFIXED|VTEXTFIXED , "PS4=+ " , NULL },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001760#if ENABLE_ASH_GETOPTS
Denis Vlasenko01631112007-12-16 17:20:38 +00001761 { VSTRFIXED|VTEXTFIXED , "OPTIND=1" , getoptsreset },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001762#endif
1763#if ENABLE_ASH_RANDOM_SUPPORT
Denis Vlasenko01631112007-12-16 17:20:38 +00001764 { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM\0", change_random },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001765#endif
1766#if ENABLE_LOCALE_SUPPORT
Denis Vlasenko01631112007-12-16 17:20:38 +00001767 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL\0" , change_lc_all },
1768 { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE\0", change_lc_ctype },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001769#endif
1770#if ENABLE_FEATURE_EDITING_SAVEHISTORY
Denis Vlasenko01631112007-12-16 17:20:38 +00001771 { VSTRFIXED|VTEXTFIXED|VUNSET, "HISTFILE\0", NULL },
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001772#endif
1773};
1774
Denis Vlasenko01631112007-12-16 17:20:38 +00001775
1776struct globals_var {
1777 struct shparam shellparam; /* $@ current positional parameters */
1778 struct redirtab *redirlist;
1779 int g_nullredirs;
1780 int preverrout_fd; /* save fd2 before print debug if xflag is set. */
1781 struct var *vartab[VTABSIZE];
1782 struct var varinit[ARRAY_SIZE(varinit_data)];
1783};
Denis Vlasenko574f2f42008-02-27 18:41:59 +00001784extern struct globals_var *const ash_ptr_to_globals_var;
1785#define G_var (*ash_ptr_to_globals_var)
Denis Vlasenko01631112007-12-16 17:20:38 +00001786#define shellparam (G_var.shellparam )
1787#define redirlist (G_var.redirlist )
1788#define g_nullredirs (G_var.g_nullredirs )
1789#define preverrout_fd (G_var.preverrout_fd)
1790#define vartab (G_var.vartab )
1791#define varinit (G_var.varinit )
1792#define INIT_G_var() do { \
1793 int i; \
Denis Vlasenko574f2f42008-02-27 18:41:59 +00001794 (*(struct globals_var**)&ash_ptr_to_globals_var) = xzalloc(sizeof(G_var)); \
1795 barrier(); \
Denis Vlasenko01631112007-12-16 17:20:38 +00001796 for (i = 0; i < ARRAY_SIZE(varinit_data); i++) { \
1797 varinit[i].flags = varinit_data[i].flags; \
1798 varinit[i].text = varinit_data[i].text; \
1799 varinit[i].func = varinit_data[i].func; \
1800 } \
1801} while (0)
1802
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001803#define vifs varinit[0]
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001804#if ENABLE_ASH_MAIL
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001805# define vmail (&vifs)[1]
1806# define vmpath (&vmail)[1]
1807# define vpath (&vmpath)[1]
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001808#else
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001809# define vpath (&vifs)[1]
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001810#endif
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001811#define vps1 (&vpath)[1]
1812#define vps2 (&vps1)[1]
1813#define vps4 (&vps2)[1]
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001814#if ENABLE_ASH_GETOPTS
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001815# define voptind (&vps4)[1]
1816# if ENABLE_ASH_RANDOM_SUPPORT
1817# define vrandom (&voptind)[1]
1818# endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001819#else
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001820# if ENABLE_ASH_RANDOM_SUPPORT
1821# define vrandom (&vps4)[1]
1822# endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001823#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001824
1825/*
1826 * The following macros access the values of the above variables.
1827 * They have to skip over the name. They return the null string
1828 * for unset variables.
1829 */
1830#define ifsval() (vifs.text + 4)
1831#define ifsset() ((vifs.flags & VUNSET) == 0)
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001832#if ENABLE_ASH_MAIL
1833# define mailval() (vmail.text + 5)
1834# define mpathval() (vmpath.text + 9)
1835# define mpathset() ((vmpath.flags & VUNSET) == 0)
1836#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001837#define pathval() (vpath.text + 5)
1838#define ps1val() (vps1.text + 4)
1839#define ps2val() (vps2.text + 4)
1840#define ps4val() (vps4.text + 4)
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00001841#if ENABLE_ASH_GETOPTS
1842# define optindval() (voptind.text + 7)
1843#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001844
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001845
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001846#define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
1847#define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
1848
Denis Vlasenko01631112007-12-16 17:20:38 +00001849#if ENABLE_ASH_GETOPTS
1850static void
1851getoptsreset(const char *value)
1852{
1853 shellparam.optind = number(value);
1854 shellparam.optoff = -1;
1855}
1856#endif
1857
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001858/*
1859 * Return of a legal variable name (a letter or underscore followed by zero or
1860 * more letters, underscores, and digits).
1861 */
1862static char *
1863endofname(const char *name)
1864{
1865 char *p;
1866
1867 p = (char *) name;
1868 if (!is_name(*p))
1869 return p;
1870 while (*++p) {
1871 if (!is_in_name(*p))
1872 break;
1873 }
1874 return p;
1875}
1876
1877/*
1878 * Compares two strings up to the first = or '\0'. The first
1879 * string must be terminated by '='; the second may be terminated by
1880 * either '=' or '\0'.
1881 */
1882static int
1883varcmp(const char *p, const char *q)
1884{
1885 int c, d;
1886
1887 while ((c = *p) == (d = *q)) {
1888 if (!c || c == '=')
1889 goto out;
1890 p++;
1891 q++;
1892 }
1893 if (c == '=')
Denis Vlasenko9650f362007-02-23 01:04:37 +00001894 c = '\0';
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001895 if (d == '=')
Denis Vlasenko9650f362007-02-23 01:04:37 +00001896 d = '\0';
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001897 out:
1898 return c - d;
1899}
1900
1901static int
1902varequal(const char *a, const char *b)
1903{
1904 return !varcmp(a, b);
1905}
1906
1907/*
1908 * Find the appropriate entry in the hash table from the name.
1909 */
1910static struct var **
1911hashvar(const char *p)
1912{
1913 unsigned hashval;
1914
1915 hashval = ((unsigned char) *p) << 4;
1916 while (*p && *p != '=')
1917 hashval += (unsigned char) *p++;
1918 return &vartab[hashval % VTABSIZE];
1919}
1920
1921static int
1922vpcmp(const void *a, const void *b)
1923{
1924 return varcmp(*(const char **)a, *(const char **)b);
1925}
1926
1927/*
1928 * This routine initializes the builtin variables.
1929 */
1930static void
1931initvar(void)
1932{
1933 struct var *vp;
1934 struct var *end;
1935 struct var **vpp;
1936
1937 /*
1938 * PS1 depends on uid
1939 */
1940#if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
1941 vps1.text = "PS1=\\w \\$ ";
1942#else
1943 if (!geteuid())
1944 vps1.text = "PS1=# ";
1945#endif
1946 vp = varinit;
Denis Vlasenko80b8b392007-06-25 10:55:35 +00001947 end = vp + ARRAY_SIZE(varinit);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00001948 do {
1949 vpp = hashvar(vp->text);
1950 vp->next = *vpp;
1951 *vpp = vp;
1952 } while (++vp < end);
1953}
1954
1955static struct var **
1956findvar(struct var **vpp, const char *name)
1957{
1958 for (; *vpp; vpp = &(*vpp)->next) {
1959 if (varequal((*vpp)->text, name)) {
1960 break;
1961 }
1962 }
1963 return vpp;
1964}
1965
1966/*
1967 * Find the value of a variable. Returns NULL if not set.
1968 */
1969static char *
1970lookupvar(const char *name)
1971{
1972 struct var *v;
1973
1974 v = *findvar(hashvar(name), name);
1975 if (v) {
1976#ifdef DYNAMIC_VAR
1977 /*
1978 * Dynamic variables are implemented roughly the same way they are
1979 * in bash. Namely, they're "special" so long as they aren't unset.
1980 * As soon as they're unset, they're no longer dynamic, and dynamic
1981 * lookup will no longer happen at that point. -- PFM.
1982 */
1983 if ((v->flags & VDYNAMIC))
1984 (*v->func)(NULL);
1985#endif
1986 if (!(v->flags & VUNSET))
1987 return strchrnul(v->text, '=') + 1;
1988 }
1989 return NULL;
1990}
1991
1992/*
1993 * Search the environment of a builtin command.
1994 */
1995static char *
1996bltinlookup(const char *name)
1997{
1998 struct strlist *sp;
1999
2000 for (sp = cmdenviron; sp; sp = sp->next) {
2001 if (varequal(sp->text, name))
2002 return strchrnul(sp->text, '=') + 1;
2003 }
2004 return lookupvar(name);
2005}
2006
2007/*
2008 * Same as setvar except that the variable and value are passed in
2009 * the first argument as name=value. Since the first argument will
2010 * be actually stored in the table, it should not be a string that
2011 * will go away.
2012 * Called with interrupts off.
2013 */
2014static void
2015setvareq(char *s, int flags)
2016{
2017 struct var *vp, **vpp;
2018
2019 vpp = hashvar(s);
2020 flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
2021 vp = *findvar(vpp, s);
2022 if (vp) {
2023 if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
2024 const char *n;
2025
2026 if (flags & VNOSAVE)
2027 free(s);
2028 n = vp->text;
2029 ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
2030 }
2031
2032 if (flags & VNOSET)
2033 return;
2034
2035 if (vp->func && (flags & VNOFUNC) == 0)
2036 (*vp->func)(strchrnul(s, '=') + 1);
2037
2038 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
2039 free((char*)vp->text);
2040
2041 flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
2042 } else {
2043 if (flags & VNOSET)
2044 return;
2045 /* not found */
Denis Vlasenko597906c2008-02-20 16:38:54 +00002046 vp = ckzalloc(sizeof(*vp));
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002047 vp->next = *vpp;
Denis Vlasenko597906c2008-02-20 16:38:54 +00002048 /*vp->func = NULL; - ckzalloc did it */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002049 *vpp = vp;
2050 }
2051 if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
2052 s = ckstrdup(s);
2053 vp->text = s;
2054 vp->flags = flags;
2055}
2056
2057/*
2058 * Set the value of a variable. The flags argument is ored with the
2059 * flags of the variable. If val is NULL, the variable is unset.
2060 */
2061static void
2062setvar(const char *name, const char *val, int flags)
2063{
2064 char *p, *q;
2065 size_t namelen;
2066 char *nameeq;
2067 size_t vallen;
2068
2069 q = endofname(name);
2070 p = strchrnul(q, '=');
2071 namelen = p - name;
2072 if (!namelen || p != q)
2073 ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
2074 vallen = 0;
2075 if (val == NULL) {
2076 flags |= VUNSET;
2077 } else {
2078 vallen = strlen(val);
2079 }
2080 INT_OFF;
2081 nameeq = ckmalloc(namelen + vallen + 2);
2082 p = memcpy(nameeq, name, namelen) + namelen;
2083 if (val) {
2084 *p++ = '=';
2085 p = memcpy(p, val, vallen) + vallen;
2086 }
2087 *p = '\0';
2088 setvareq(nameeq, flags | VNOSAVE);
2089 INT_ON;
2090}
2091
2092#if ENABLE_ASH_GETOPTS
2093/*
2094 * Safe version of setvar, returns 1 on success 0 on failure.
2095 */
2096static int
2097setvarsafe(const char *name, const char *val, int flags)
2098{
2099 int err;
2100 volatile int saveint;
2101 struct jmploc *volatile savehandler = exception_handler;
2102 struct jmploc jmploc;
2103
2104 SAVE_INT(saveint);
2105 if (setjmp(jmploc.loc))
2106 err = 1;
2107 else {
2108 exception_handler = &jmploc;
2109 setvar(name, val, flags);
2110 err = 0;
2111 }
2112 exception_handler = savehandler;
2113 RESTORE_INT(saveint);
2114 return err;
2115}
2116#endif
2117
2118/*
2119 * Unset the specified variable.
2120 */
2121static int
2122unsetvar(const char *s)
2123{
2124 struct var **vpp;
2125 struct var *vp;
2126 int retval;
2127
2128 vpp = findvar(hashvar(s), s);
2129 vp = *vpp;
2130 retval = 2;
2131 if (vp) {
2132 int flags = vp->flags;
2133
2134 retval = 1;
2135 if (flags & VREADONLY)
2136 goto out;
2137#ifdef DYNAMIC_VAR
2138 vp->flags &= ~VDYNAMIC;
2139#endif
2140 if (flags & VUNSET)
2141 goto ok;
2142 if ((flags & VSTRFIXED) == 0) {
2143 INT_OFF;
2144 if ((flags & (VTEXTFIXED|VSTACK)) == 0)
2145 free((char*)vp->text);
2146 *vpp = vp->next;
2147 free(vp);
2148 INT_ON;
2149 } else {
2150 setvar(s, 0, 0);
2151 vp->flags &= ~VEXPORT;
2152 }
2153 ok:
2154 retval = 0;
2155 }
2156 out:
2157 return retval;
2158}
2159
2160/*
2161 * Process a linked list of variable assignments.
2162 */
2163static void
2164listsetvar(struct strlist *list_set_var, int flags)
2165{
2166 struct strlist *lp = list_set_var;
2167
2168 if (!lp)
2169 return;
2170 INT_OFF;
2171 do {
2172 setvareq(lp->text, flags);
Denis Vlasenko9650f362007-02-23 01:04:37 +00002173 lp = lp->next;
2174 } while (lp);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002175 INT_ON;
2176}
2177
2178/*
2179 * Generate a list of variables satisfying the given conditions.
2180 */
2181static char **
2182listvars(int on, int off, char ***end)
2183{
2184 struct var **vpp;
2185 struct var *vp;
2186 char **ep;
2187 int mask;
2188
2189 STARTSTACKSTR(ep);
2190 vpp = vartab;
2191 mask = on | off;
2192 do {
2193 for (vp = *vpp; vp; vp = vp->next) {
2194 if ((vp->flags & mask) == on) {
2195 if (ep == stackstrend())
2196 ep = growstackstr();
2197 *ep++ = (char *) vp->text;
2198 }
2199 }
2200 } while (++vpp < vartab + VTABSIZE);
2201 if (ep == stackstrend())
2202 ep = growstackstr();
2203 if (end)
2204 *end = ep;
2205 *ep++ = NULL;
2206 return grabstackstr(ep);
2207}
2208
2209
2210/* ============ Path search helper
2211 *
2212 * The variable path (passed by reference) should be set to the start
2213 * of the path before the first call; padvance will update
2214 * this value as it proceeds. Successive calls to padvance will return
2215 * the possible path expansions in sequence. If an option (indicated by
2216 * a percent sign) appears in the path entry then the global variable
2217 * pathopt will be set to point to it; otherwise pathopt will be set to
2218 * NULL.
2219 */
2220static const char *pathopt; /* set by padvance */
2221
2222static char *
2223padvance(const char **path, const char *name)
2224{
2225 const char *p;
2226 char *q;
2227 const char *start;
2228 size_t len;
2229
2230 if (*path == NULL)
2231 return NULL;
2232 start = *path;
Denis Vlasenkof7d56652008-03-25 05:51:41 +00002233 for (p = start; *p && *p != ':' && *p != '%'; p++)
2234 continue;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002235 len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
2236 while (stackblocksize() < len)
2237 growstackblock();
2238 q = stackblock();
2239 if (p != start) {
2240 memcpy(q, start, p - start);
2241 q += p - start;
2242 *q++ = '/';
2243 }
2244 strcpy(q, name);
2245 pathopt = NULL;
2246 if (*p == '%') {
2247 pathopt = ++p;
Denis Vlasenkof7d56652008-03-25 05:51:41 +00002248 while (*p && *p != ':')
2249 p++;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002250 }
2251 if (*p == ':')
2252 *path = p + 1;
2253 else
2254 *path = NULL;
2255 return stalloc(len);
2256}
2257
2258
2259/* ============ Prompt */
2260
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +00002261static smallint doprompt; /* if set, prompt the user */
2262static smallint needprompt; /* true if interactive and at start of line */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002263
2264#if ENABLE_FEATURE_EDITING
2265static line_input_t *line_input_state;
2266static const char *cmdedit_prompt;
2267static void
2268putprompt(const char *s)
2269{
2270 if (ENABLE_ASH_EXPAND_PRMT) {
2271 free((char*)cmdedit_prompt);
Denis Vlasenko4222ae42007-02-25 02:37:49 +00002272 cmdedit_prompt = ckstrdup(s);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002273 return;
2274 }
2275 cmdedit_prompt = s;
2276}
2277#else
2278static void
2279putprompt(const char *s)
2280{
2281 out2str(s);
2282}
2283#endif
2284
2285#if ENABLE_ASH_EXPAND_PRMT
2286/* expandstr() needs parsing machinery, so it is far away ahead... */
2287static const char *expandstr(const char *ps);
2288#else
2289#define expandstr(s) s
2290#endif
2291
2292static void
2293setprompt(int whichprompt)
2294{
2295 const char *prompt;
2296#if ENABLE_ASH_EXPAND_PRMT
2297 struct stackmark smark;
2298#endif
2299
2300 needprompt = 0;
2301
2302 switch (whichprompt) {
2303 case 1:
2304 prompt = ps1val();
2305 break;
2306 case 2:
2307 prompt = ps2val();
2308 break;
2309 default: /* 0 */
2310 prompt = nullstr;
2311 }
2312#if ENABLE_ASH_EXPAND_PRMT
2313 setstackmark(&smark);
2314 stalloc(stackblocksize());
2315#endif
2316 putprompt(expandstr(prompt));
2317#if ENABLE_ASH_EXPAND_PRMT
2318 popstackmark(&smark);
2319#endif
2320}
2321
2322
2323/* ============ The cd and pwd commands */
2324
2325#define CD_PHYSICAL 1
2326#define CD_PRINT 2
2327
2328static int docd(const char *, int);
2329
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002330static int
2331cdopt(void)
2332{
2333 int flags = 0;
2334 int i, j;
2335
2336 j = 'L';
2337 while ((i = nextopt("LP"))) {
2338 if (i != j) {
2339 flags ^= CD_PHYSICAL;
2340 j = i;
2341 }
2342 }
2343
2344 return flags;
2345}
2346
2347/*
2348 * Update curdir (the name of the current directory) in response to a
2349 * cd command.
2350 */
2351static const char *
2352updatepwd(const char *dir)
2353{
2354 char *new;
2355 char *p;
2356 char *cdcomppath;
2357 const char *lim;
2358
2359 cdcomppath = ststrdup(dir);
2360 STARTSTACKSTR(new);
2361 if (*dir != '/') {
2362 if (curdir == nullstr)
2363 return 0;
2364 new = stack_putstr(curdir, new);
2365 }
2366 new = makestrspace(strlen(dir) + 2, new);
2367 lim = stackblock() + 1;
2368 if (*dir != '/') {
2369 if (new[-1] != '/')
2370 USTPUTC('/', new);
2371 if (new > lim && *lim == '/')
2372 lim++;
2373 } else {
2374 USTPUTC('/', new);
2375 cdcomppath++;
2376 if (dir[1] == '/' && dir[2] != '/') {
2377 USTPUTC('/', new);
2378 cdcomppath++;
2379 lim++;
2380 }
2381 }
2382 p = strtok(cdcomppath, "/");
2383 while (p) {
2384 switch (*p) {
2385 case '.':
2386 if (p[1] == '.' && p[2] == '\0') {
2387 while (new > lim) {
2388 STUNPUTC(new);
2389 if (new[-1] == '/')
2390 break;
2391 }
2392 break;
Denis Vlasenko16abcd92007-04-13 23:59:52 +00002393 }
2394 if (p[1] == '\0')
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002395 break;
2396 /* fall through */
2397 default:
2398 new = stack_putstr(p, new);
2399 USTPUTC('/', new);
2400 }
2401 p = strtok(0, "/");
2402 }
2403 if (new > lim)
2404 STUNPUTC(new);
2405 *new = 0;
2406 return stackblock();
2407}
2408
2409/*
2410 * Find out what the current directory is. If we already know the current
2411 * directory, this routine returns immediately.
2412 */
2413static char *
2414getpwd(void)
2415{
Denis Vlasenko01631112007-12-16 17:20:38 +00002416 char *dir = getcwd(NULL, 0); /* huh, using glibc extension? */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002417 return dir ? dir : nullstr;
2418}
2419
2420static void
2421setpwd(const char *val, int setold)
2422{
2423 char *oldcur, *dir;
2424
2425 oldcur = dir = curdir;
2426
2427 if (setold) {
2428 setvar("OLDPWD", oldcur, VEXPORT);
2429 }
2430 INT_OFF;
2431 if (physdir != nullstr) {
2432 if (physdir != oldcur)
2433 free(physdir);
2434 physdir = nullstr;
2435 }
2436 if (oldcur == val || !val) {
2437 char *s = getpwd();
2438 physdir = s;
2439 if (!val)
2440 dir = s;
2441 } else
2442 dir = ckstrdup(val);
2443 if (oldcur != dir && oldcur != nullstr) {
2444 free(oldcur);
2445 }
2446 curdir = dir;
2447 INT_ON;
2448 setvar("PWD", dir, VEXPORT);
2449}
2450
2451static void hashcd(void);
2452
2453/*
2454 * Actually do the chdir. We also call hashcd to let the routines in exec.c
2455 * know that the current directory has changed.
2456 */
2457static int
2458docd(const char *dest, int flags)
2459{
2460 const char *dir = 0;
2461 int err;
2462
2463 TRACE(("docd(\"%s\", %d) called\n", dest, flags));
2464
2465 INT_OFF;
2466 if (!(flags & CD_PHYSICAL)) {
2467 dir = updatepwd(dest);
2468 if (dir)
2469 dest = dir;
2470 }
2471 err = chdir(dest);
2472 if (err)
2473 goto out;
2474 setpwd(dir, 1);
2475 hashcd();
2476 out:
2477 INT_ON;
2478 return err;
2479}
2480
2481static int
Denis Vlasenko68404f12008-03-17 09:00:54 +00002482cdcmd(int argc ATTRIBUTE_UNUSED, char **argv ATTRIBUTE_UNUSED)
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002483{
2484 const char *dest;
2485 const char *path;
2486 const char *p;
2487 char c;
2488 struct stat statb;
2489 int flags;
2490
2491 flags = cdopt();
2492 dest = *argptr;
2493 if (!dest)
2494 dest = bltinlookup(homestr);
2495 else if (LONE_DASH(dest)) {
2496 dest = bltinlookup("OLDPWD");
2497 flags |= CD_PRINT;
2498 }
2499 if (!dest)
2500 dest = nullstr;
2501 if (*dest == '/')
2502 goto step7;
2503 if (*dest == '.') {
2504 c = dest[1];
2505 dotdot:
2506 switch (c) {
2507 case '\0':
2508 case '/':
2509 goto step6;
2510 case '.':
2511 c = dest[2];
2512 if (c != '.')
2513 goto dotdot;
2514 }
2515 }
2516 if (!*dest)
2517 dest = ".";
2518 path = bltinlookup("CDPATH");
2519 if (!path) {
2520 step6:
2521 step7:
2522 p = dest;
2523 goto docd;
2524 }
2525 do {
2526 c = *path;
2527 p = padvance(&path, dest);
2528 if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
2529 if (c && c != ':')
2530 flags |= CD_PRINT;
2531 docd:
2532 if (!docd(p, flags))
2533 goto out;
2534 break;
2535 }
2536 } while (path);
2537 ash_msg_and_raise_error("can't cd to %s", dest);
2538 /* NOTREACHED */
2539 out:
2540 if (flags & CD_PRINT)
2541 out1fmt(snlfmt, curdir);
2542 return 0;
2543}
2544
2545static int
Denis Vlasenko68404f12008-03-17 09:00:54 +00002546pwdcmd(int argc ATTRIBUTE_UNUSED, char **argv ATTRIBUTE_UNUSED)
Denis Vlasenkoaa744452007-02-23 01:04:22 +00002547{
2548 int flags;
2549 const char *dir = curdir;
2550
2551 flags = cdopt();
2552 if (flags) {
2553 if (physdir == nullstr)
2554 setpwd(dir, 0);
2555 dir = physdir;
2556 }
2557 out1fmt(snlfmt, dir);
2558 return 0;
2559}
2560
Denis Vlasenko0c032a42007-02-23 01:03:40 +00002561
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00002562/* ============ ... */
Eric Andersenc470f442003-07-28 09:56:35 +00002563
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +00002564#define IBUFSIZ COMMON_BUFSIZE
"Vladimir N. Oleynik"6f347ef2005-10-15 10:23:55 +00002565#define basebuf bb_common_bufsiz1 /* buffer for top level input file */
Eric Andersenc470f442003-07-28 09:56:35 +00002566
Eric Andersenc470f442003-07-28 09:56:35 +00002567/* Syntax classes */
2568#define CWORD 0 /* character is nothing special */
2569#define CNL 1 /* newline character */
2570#define CBACK 2 /* a backslash character */
2571#define CSQUOTE 3 /* single quote */
2572#define CDQUOTE 4 /* double quote */
2573#define CENDQUOTE 5 /* a terminating quote */
2574#define CBQUOTE 6 /* backwards single quote */
2575#define CVAR 7 /* a dollar sign */
2576#define CENDVAR 8 /* a '}' character */
2577#define CLP 9 /* a left paren in arithmetic */
2578#define CRP 10 /* a right paren in arithmetic */
2579#define CENDFILE 11 /* end of file */
2580#define CCTL 12 /* like CWORD, except it must be escaped */
2581#define CSPCL 13 /* these terminate a word */
2582#define CIGN 14 /* character should be ignored */
2583
Denis Vlasenko131ae172007-02-18 13:00:19 +00002584#if ENABLE_ASH_ALIAS
Eric Andersenc470f442003-07-28 09:56:35 +00002585#define SYNBASE 130
2586#define PEOF -130
2587#define PEOA -129
2588#define PEOA_OR_PEOF PEOA
2589#else
2590#define SYNBASE 129
2591#define PEOF -129
2592#define PEOA_OR_PEOF PEOF
2593#endif
2594
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00002595/* number syntax index */
2596#define BASESYNTAX 0 /* not in quotes */
2597#define DQSYNTAX 1 /* in double quotes */
2598#define SQSYNTAX 2 /* in single quotes */
2599#define ARISYNTAX 3 /* in arithmetic */
Denis Vlasenko46a53062007-09-24 18:30:02 +00002600#define PSSYNTAX 4 /* prompt */
Eric Andersenc470f442003-07-28 09:56:35 +00002601
Denis Vlasenko131ae172007-02-18 13:00:19 +00002602#if ENABLE_ASH_OPTIMIZE_FOR_SIZE
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002603#define USE_SIT_FUNCTION
2604#endif
2605
Denis Vlasenko131ae172007-02-18 13:00:19 +00002606#if ENABLE_ASH_MATH_SUPPORT
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002607static const char S_I_T[][4] = {
Denis Vlasenko131ae172007-02-18 13:00:19 +00002608#if ENABLE_ASH_ALIAS
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00002609 { CSPCL, CIGN, CIGN, CIGN }, /* 0, PEOA */
Eric Andersenc470f442003-07-28 09:56:35 +00002610#endif
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00002611 { CSPCL, CWORD, CWORD, CWORD }, /* 1, ' ' */
2612 { CNL, CNL, CNL, CNL }, /* 2, \n */
2613 { CWORD, CCTL, CCTL, CWORD }, /* 3, !*-/:=?[]~ */
2614 { CDQUOTE, CENDQUOTE, CWORD, CWORD }, /* 4, '"' */
2615 { CVAR, CVAR, CWORD, CVAR }, /* 5, $ */
2616 { CSQUOTE, CWORD, CENDQUOTE, CWORD }, /* 6, "'" */
2617 { CSPCL, CWORD, CWORD, CLP }, /* 7, ( */
2618 { CSPCL, CWORD, CWORD, CRP }, /* 8, ) */
2619 { CBACK, CBACK, CCTL, CBACK }, /* 9, \ */
2620 { CBQUOTE, CBQUOTE, CWORD, CBQUOTE }, /* 10, ` */
2621 { CENDVAR, CENDVAR, CWORD, CENDVAR }, /* 11, } */
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002622#ifndef USE_SIT_FUNCTION
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00002623 { CENDFILE, CENDFILE, CENDFILE, CENDFILE }, /* 12, PEOF */
2624 { CWORD, CWORD, CWORD, CWORD }, /* 13, 0-9A-Za-z */
2625 { CCTL, CCTL, CCTL, CCTL } /* 14, CTLESC ... */
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002626#endif
Eric Andersen2870d962001-07-02 17:27:21 +00002627};
Eric Andersenc470f442003-07-28 09:56:35 +00002628#else
2629static const char S_I_T[][3] = {
Denis Vlasenko131ae172007-02-18 13:00:19 +00002630#if ENABLE_ASH_ALIAS
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00002631 { CSPCL, CIGN, CIGN }, /* 0, PEOA */
Eric Andersenc470f442003-07-28 09:56:35 +00002632#endif
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00002633 { CSPCL, CWORD, CWORD }, /* 1, ' ' */
2634 { CNL, CNL, CNL }, /* 2, \n */
2635 { CWORD, CCTL, CCTL }, /* 3, !*-/:=?[]~ */
2636 { CDQUOTE, CENDQUOTE, CWORD }, /* 4, '"' */
2637 { CVAR, CVAR, CWORD }, /* 5, $ */
2638 { CSQUOTE, CWORD, CENDQUOTE }, /* 6, "'" */
2639 { CSPCL, CWORD, CWORD }, /* 7, ( */
2640 { CSPCL, CWORD, CWORD }, /* 8, ) */
2641 { CBACK, CBACK, CCTL }, /* 9, \ */
2642 { CBQUOTE, CBQUOTE, CWORD }, /* 10, ` */
2643 { CENDVAR, CENDVAR, CWORD }, /* 11, } */
Eric Andersenc470f442003-07-28 09:56:35 +00002644#ifndef USE_SIT_FUNCTION
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00002645 { CENDFILE, CENDFILE, CENDFILE }, /* 12, PEOF */
2646 { CWORD, CWORD, CWORD }, /* 13, 0-9A-Za-z */
2647 { CCTL, CCTL, CCTL } /* 14, CTLESC ... */
Eric Andersenc470f442003-07-28 09:56:35 +00002648#endif
2649};
Denis Vlasenko131ae172007-02-18 13:00:19 +00002650#endif /* ASH_MATH_SUPPORT */
Eric Andersen2870d962001-07-02 17:27:21 +00002651
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002652#ifdef USE_SIT_FUNCTION
2653
Denis Vlasenko0c032a42007-02-23 01:03:40 +00002654static int
2655SIT(int c, int syntax)
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002656{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00002657 static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-/:;<=>?[\\]`|}~";
Denis Vlasenko131ae172007-02-18 13:00:19 +00002658#if ENABLE_ASH_ALIAS
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00002659 static const char syntax_index_table[] ALIGN1 = {
Eric Andersenc470f442003-07-28 09:56:35 +00002660 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
2661 7, 8, 3, 3, 3, 3, 1, 1, /* "()*-/:;<" */
2662 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
2663 11, 3 /* "}~" */
2664 };
2665#else
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00002666 static const char syntax_index_table[] ALIGN1 = {
Eric Andersenc470f442003-07-28 09:56:35 +00002667 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
2668 6, 7, 2, 2, 2, 2, 0, 0, /* "()*-/:;<" */
2669 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
2670 10, 2 /* "}~" */
2671 };
2672#endif
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002673 const char *s;
2674 int indx;
2675
Eric Andersenc470f442003-07-28 09:56:35 +00002676 if (c == PEOF) /* 2^8+2 */
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002677 return CENDFILE;
Denis Vlasenko131ae172007-02-18 13:00:19 +00002678#if ENABLE_ASH_ALIAS
Eric Andersenc470f442003-07-28 09:56:35 +00002679 if (c == PEOA) /* 2^8+1 */
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002680 indx = 0;
Eric Andersenc470f442003-07-28 09:56:35 +00002681 else
2682#endif
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00002683#define U_C(c) ((unsigned char)(c))
2684
2685 if ((unsigned char)c >= (unsigned char)(CTLESC)
2686 && (unsigned char)c <= (unsigned char)(CTLQUOTEMARK)
2687 ) {
Denis Vlasenko2da584f2007-02-19 22:44:05 +00002688 return CCTL;
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00002689 } else {
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002690 s = strchr(spec_symbls, c);
Denis Vlasenko2da584f2007-02-19 22:44:05 +00002691 if (s == NULL || *s == '\0')
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002692 return CWORD;
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00002693 indx = syntax_index_table[(s - spec_symbls)];
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002694 }
2695 return S_I_T[indx][syntax];
2696}
2697
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00002698#else /* !USE_SIT_FUNCTION */
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002699
Denis Vlasenko131ae172007-02-18 13:00:19 +00002700#if ENABLE_ASH_ALIAS
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00002701#define CSPCL_CIGN_CIGN_CIGN 0
2702#define CSPCL_CWORD_CWORD_CWORD 1
2703#define CNL_CNL_CNL_CNL 2
2704#define CWORD_CCTL_CCTL_CWORD 3
2705#define CDQUOTE_CENDQUOTE_CWORD_CWORD 4
2706#define CVAR_CVAR_CWORD_CVAR 5
2707#define CSQUOTE_CWORD_CENDQUOTE_CWORD 6
2708#define CSPCL_CWORD_CWORD_CLP 7
2709#define CSPCL_CWORD_CWORD_CRP 8
2710#define CBACK_CBACK_CCTL_CBACK 9
2711#define CBQUOTE_CBQUOTE_CWORD_CBQUOTE 10
2712#define CENDVAR_CENDVAR_CWORD_CENDVAR 11
2713#define CENDFILE_CENDFILE_CENDFILE_CENDFILE 12
2714#define CWORD_CWORD_CWORD_CWORD 13
2715#define CCTL_CCTL_CCTL_CCTL 14
Eric Andersenc470f442003-07-28 09:56:35 +00002716#else
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00002717#define CSPCL_CWORD_CWORD_CWORD 0
2718#define CNL_CNL_CNL_CNL 1
2719#define CWORD_CCTL_CCTL_CWORD 2
2720#define CDQUOTE_CENDQUOTE_CWORD_CWORD 3
2721#define CVAR_CVAR_CWORD_CVAR 4
2722#define CSQUOTE_CWORD_CENDQUOTE_CWORD 5
2723#define CSPCL_CWORD_CWORD_CLP 6
2724#define CSPCL_CWORD_CWORD_CRP 7
2725#define CBACK_CBACK_CCTL_CBACK 8
2726#define CBQUOTE_CBQUOTE_CWORD_CBQUOTE 9
2727#define CENDVAR_CENDVAR_CWORD_CENDVAR 10
2728#define CENDFILE_CENDFILE_CENDFILE_CENDFILE 11
2729#define CWORD_CWORD_CWORD_CWORD 12
2730#define CCTL_CCTL_CCTL_CCTL 13
Eric Andersenc470f442003-07-28 09:56:35 +00002731#endif
Manuel Novoa III 16815d42001-08-10 19:36:07 +00002732
2733static const char syntax_index_table[258] = {
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00002734 /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
Eric Andersenc470f442003-07-28 09:56:35 +00002735 /* 0 PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
Denis Vlasenko131ae172007-02-18 13:00:19 +00002736#if ENABLE_ASH_ALIAS
Eric Andersenc470f442003-07-28 09:56:35 +00002737 /* 1 PEOA */ CSPCL_CIGN_CIGN_CIGN,
2738#endif
2739 /* 2 -128 0x80 */ CWORD_CWORD_CWORD_CWORD,
2740 /* 3 -127 CTLESC */ CCTL_CCTL_CCTL_CCTL,
2741 /* 4 -126 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
2742 /* 5 -125 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
2743 /* 6 -124 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
2744 /* 7 -123 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
2745 /* 8 -122 CTLARI */ CCTL_CCTL_CCTL_CCTL,
2746 /* 9 -121 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
2747 /* 10 -120 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00002748 /* 11 -119 */ CWORD_CWORD_CWORD_CWORD,
2749 /* 12 -118 */ CWORD_CWORD_CWORD_CWORD,
2750 /* 13 -117 */ CWORD_CWORD_CWORD_CWORD,
2751 /* 14 -116 */ CWORD_CWORD_CWORD_CWORD,
2752 /* 15 -115 */ CWORD_CWORD_CWORD_CWORD,
2753 /* 16 -114 */ CWORD_CWORD_CWORD_CWORD,
2754 /* 17 -113 */ CWORD_CWORD_CWORD_CWORD,
2755 /* 18 -112 */ CWORD_CWORD_CWORD_CWORD,
2756 /* 19 -111 */ CWORD_CWORD_CWORD_CWORD,
2757 /* 20 -110 */ CWORD_CWORD_CWORD_CWORD,
2758 /* 21 -109 */ CWORD_CWORD_CWORD_CWORD,
2759 /* 22 -108 */ CWORD_CWORD_CWORD_CWORD,
2760 /* 23 -107 */ CWORD_CWORD_CWORD_CWORD,
2761 /* 24 -106 */ CWORD_CWORD_CWORD_CWORD,
2762 /* 25 -105 */ CWORD_CWORD_CWORD_CWORD,
2763 /* 26 -104 */ CWORD_CWORD_CWORD_CWORD,
2764 /* 27 -103 */ CWORD_CWORD_CWORD_CWORD,
2765 /* 28 -102 */ CWORD_CWORD_CWORD_CWORD,
2766 /* 29 -101 */ CWORD_CWORD_CWORD_CWORD,
2767 /* 30 -100 */ CWORD_CWORD_CWORD_CWORD,
2768 /* 31 -99 */ CWORD_CWORD_CWORD_CWORD,
2769 /* 32 -98 */ CWORD_CWORD_CWORD_CWORD,
2770 /* 33 -97 */ CWORD_CWORD_CWORD_CWORD,
2771 /* 34 -96 */ CWORD_CWORD_CWORD_CWORD,
2772 /* 35 -95 */ CWORD_CWORD_CWORD_CWORD,
2773 /* 36 -94 */ CWORD_CWORD_CWORD_CWORD,
2774 /* 37 -93 */ CWORD_CWORD_CWORD_CWORD,
2775 /* 38 -92 */ CWORD_CWORD_CWORD_CWORD,
2776 /* 39 -91 */ CWORD_CWORD_CWORD_CWORD,
2777 /* 40 -90 */ CWORD_CWORD_CWORD_CWORD,
2778 /* 41 -89 */ CWORD_CWORD_CWORD_CWORD,
2779 /* 42 -88 */ CWORD_CWORD_CWORD_CWORD,
2780 /* 43 -87 */ CWORD_CWORD_CWORD_CWORD,
2781 /* 44 -86 */ CWORD_CWORD_CWORD_CWORD,
2782 /* 45 -85 */ CWORD_CWORD_CWORD_CWORD,
2783 /* 46 -84 */ CWORD_CWORD_CWORD_CWORD,
2784 /* 47 -83 */ CWORD_CWORD_CWORD_CWORD,
2785 /* 48 -82 */ CWORD_CWORD_CWORD_CWORD,
2786 /* 49 -81 */ CWORD_CWORD_CWORD_CWORD,
2787 /* 50 -80 */ CWORD_CWORD_CWORD_CWORD,
2788 /* 51 -79 */ CWORD_CWORD_CWORD_CWORD,
2789 /* 52 -78 */ CWORD_CWORD_CWORD_CWORD,
2790 /* 53 -77 */ CWORD_CWORD_CWORD_CWORD,
2791 /* 54 -76 */ CWORD_CWORD_CWORD_CWORD,
2792 /* 55 -75 */ CWORD_CWORD_CWORD_CWORD,
2793 /* 56 -74 */ CWORD_CWORD_CWORD_CWORD,
2794 /* 57 -73 */ CWORD_CWORD_CWORD_CWORD,
2795 /* 58 -72 */ CWORD_CWORD_CWORD_CWORD,
2796 /* 59 -71 */ CWORD_CWORD_CWORD_CWORD,
2797 /* 60 -70 */ CWORD_CWORD_CWORD_CWORD,
2798 /* 61 -69 */ CWORD_CWORD_CWORD_CWORD,
2799 /* 62 -68 */ CWORD_CWORD_CWORD_CWORD,
2800 /* 63 -67 */ CWORD_CWORD_CWORD_CWORD,
2801 /* 64 -66 */ CWORD_CWORD_CWORD_CWORD,
2802 /* 65 -65 */ CWORD_CWORD_CWORD_CWORD,
2803 /* 66 -64 */ CWORD_CWORD_CWORD_CWORD,
2804 /* 67 -63 */ CWORD_CWORD_CWORD_CWORD,
2805 /* 68 -62 */ CWORD_CWORD_CWORD_CWORD,
2806 /* 69 -61 */ CWORD_CWORD_CWORD_CWORD,
2807 /* 70 -60 */ CWORD_CWORD_CWORD_CWORD,
2808 /* 71 -59 */ CWORD_CWORD_CWORD_CWORD,
2809 /* 72 -58 */ CWORD_CWORD_CWORD_CWORD,
2810 /* 73 -57 */ CWORD_CWORD_CWORD_CWORD,
2811 /* 74 -56 */ CWORD_CWORD_CWORD_CWORD,
2812 /* 75 -55 */ CWORD_CWORD_CWORD_CWORD,
2813 /* 76 -54 */ CWORD_CWORD_CWORD_CWORD,
2814 /* 77 -53 */ CWORD_CWORD_CWORD_CWORD,
2815 /* 78 -52 */ CWORD_CWORD_CWORD_CWORD,
2816 /* 79 -51 */ CWORD_CWORD_CWORD_CWORD,
2817 /* 80 -50 */ CWORD_CWORD_CWORD_CWORD,
2818 /* 81 -49 */ CWORD_CWORD_CWORD_CWORD,
2819 /* 82 -48 */ CWORD_CWORD_CWORD_CWORD,
2820 /* 83 -47 */ CWORD_CWORD_CWORD_CWORD,
2821 /* 84 -46 */ CWORD_CWORD_CWORD_CWORD,
2822 /* 85 -45 */ CWORD_CWORD_CWORD_CWORD,
2823 /* 86 -44 */ CWORD_CWORD_CWORD_CWORD,
2824 /* 87 -43 */ CWORD_CWORD_CWORD_CWORD,
2825 /* 88 -42 */ CWORD_CWORD_CWORD_CWORD,
2826 /* 89 -41 */ CWORD_CWORD_CWORD_CWORD,
2827 /* 90 -40 */ CWORD_CWORD_CWORD_CWORD,
2828 /* 91 -39 */ CWORD_CWORD_CWORD_CWORD,
2829 /* 92 -38 */ CWORD_CWORD_CWORD_CWORD,
2830 /* 93 -37 */ CWORD_CWORD_CWORD_CWORD,
2831 /* 94 -36 */ CWORD_CWORD_CWORD_CWORD,
2832 /* 95 -35 */ CWORD_CWORD_CWORD_CWORD,
2833 /* 96 -34 */ CWORD_CWORD_CWORD_CWORD,
2834 /* 97 -33 */ CWORD_CWORD_CWORD_CWORD,
2835 /* 98 -32 */ CWORD_CWORD_CWORD_CWORD,
2836 /* 99 -31 */ CWORD_CWORD_CWORD_CWORD,
2837 /* 100 -30 */ CWORD_CWORD_CWORD_CWORD,
2838 /* 101 -29 */ CWORD_CWORD_CWORD_CWORD,
2839 /* 102 -28 */ CWORD_CWORD_CWORD_CWORD,
2840 /* 103 -27 */ CWORD_CWORD_CWORD_CWORD,
2841 /* 104 -26 */ CWORD_CWORD_CWORD_CWORD,
2842 /* 105 -25 */ CWORD_CWORD_CWORD_CWORD,
2843 /* 106 -24 */ CWORD_CWORD_CWORD_CWORD,
2844 /* 107 -23 */ CWORD_CWORD_CWORD_CWORD,
2845 /* 108 -22 */ CWORD_CWORD_CWORD_CWORD,
2846 /* 109 -21 */ CWORD_CWORD_CWORD_CWORD,
2847 /* 110 -20 */ CWORD_CWORD_CWORD_CWORD,
2848 /* 111 -19 */ CWORD_CWORD_CWORD_CWORD,
2849 /* 112 -18 */ CWORD_CWORD_CWORD_CWORD,
2850 /* 113 -17 */ CWORD_CWORD_CWORD_CWORD,
2851 /* 114 -16 */ CWORD_CWORD_CWORD_CWORD,
2852 /* 115 -15 */ CWORD_CWORD_CWORD_CWORD,
2853 /* 116 -14 */ CWORD_CWORD_CWORD_CWORD,
2854 /* 117 -13 */ CWORD_CWORD_CWORD_CWORD,
2855 /* 118 -12 */ CWORD_CWORD_CWORD_CWORD,
2856 /* 119 -11 */ CWORD_CWORD_CWORD_CWORD,
2857 /* 120 -10 */ CWORD_CWORD_CWORD_CWORD,
2858 /* 121 -9 */ CWORD_CWORD_CWORD_CWORD,
2859 /* 122 -8 */ CWORD_CWORD_CWORD_CWORD,
2860 /* 123 -7 */ CWORD_CWORD_CWORD_CWORD,
2861 /* 124 -6 */ CWORD_CWORD_CWORD_CWORD,
2862 /* 125 -5 */ CWORD_CWORD_CWORD_CWORD,
2863 /* 126 -4 */ CWORD_CWORD_CWORD_CWORD,
2864 /* 127 -3 */ CWORD_CWORD_CWORD_CWORD,
2865 /* 128 -2 */ CWORD_CWORD_CWORD_CWORD,
2866 /* 129 -1 */ CWORD_CWORD_CWORD_CWORD,
2867 /* 130 0 */ CWORD_CWORD_CWORD_CWORD,
2868 /* 131 1 */ CWORD_CWORD_CWORD_CWORD,
2869 /* 132 2 */ CWORD_CWORD_CWORD_CWORD,
2870 /* 133 3 */ CWORD_CWORD_CWORD_CWORD,
2871 /* 134 4 */ CWORD_CWORD_CWORD_CWORD,
2872 /* 135 5 */ CWORD_CWORD_CWORD_CWORD,
2873 /* 136 6 */ CWORD_CWORD_CWORD_CWORD,
2874 /* 137 7 */ CWORD_CWORD_CWORD_CWORD,
2875 /* 138 8 */ CWORD_CWORD_CWORD_CWORD,
2876 /* 139 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
2877 /* 140 10 "\n" */ CNL_CNL_CNL_CNL,
2878 /* 141 11 */ CWORD_CWORD_CWORD_CWORD,
2879 /* 142 12 */ CWORD_CWORD_CWORD_CWORD,
2880 /* 143 13 */ CWORD_CWORD_CWORD_CWORD,
2881 /* 144 14 */ CWORD_CWORD_CWORD_CWORD,
2882 /* 145 15 */ CWORD_CWORD_CWORD_CWORD,
2883 /* 146 16 */ CWORD_CWORD_CWORD_CWORD,
2884 /* 147 17 */ CWORD_CWORD_CWORD_CWORD,
2885 /* 148 18 */ CWORD_CWORD_CWORD_CWORD,
2886 /* 149 19 */ CWORD_CWORD_CWORD_CWORD,
2887 /* 150 20 */ CWORD_CWORD_CWORD_CWORD,
2888 /* 151 21 */ CWORD_CWORD_CWORD_CWORD,
2889 /* 152 22 */ CWORD_CWORD_CWORD_CWORD,
2890 /* 153 23 */ CWORD_CWORD_CWORD_CWORD,
2891 /* 154 24 */ CWORD_CWORD_CWORD_CWORD,
2892 /* 155 25 */ CWORD_CWORD_CWORD_CWORD,
2893 /* 156 26 */ CWORD_CWORD_CWORD_CWORD,
2894 /* 157 27 */ CWORD_CWORD_CWORD_CWORD,
2895 /* 158 28 */ CWORD_CWORD_CWORD_CWORD,
2896 /* 159 29 */ CWORD_CWORD_CWORD_CWORD,
2897 /* 160 30 */ CWORD_CWORD_CWORD_CWORD,
2898 /* 161 31 */ CWORD_CWORD_CWORD_CWORD,
2899 /* 162 32 " " */ CSPCL_CWORD_CWORD_CWORD,
2900 /* 163 33 "!" */ CWORD_CCTL_CCTL_CWORD,
Eric Andersenc470f442003-07-28 09:56:35 +00002901 /* 164 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00002902 /* 165 35 "#" */ CWORD_CWORD_CWORD_CWORD,
2903 /* 166 36 "$" */ CVAR_CVAR_CWORD_CVAR,
2904 /* 167 37 "%" */ CWORD_CWORD_CWORD_CWORD,
2905 /* 168 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
Eric Andersenc470f442003-07-28 09:56:35 +00002906 /* 169 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00002907 /* 170 40 "(" */ CSPCL_CWORD_CWORD_CLP,
2908 /* 171 41 ")" */ CSPCL_CWORD_CWORD_CRP,
2909 /* 172 42 "*" */ CWORD_CCTL_CCTL_CWORD,
2910 /* 173 43 "+" */ CWORD_CWORD_CWORD_CWORD,
2911 /* 174 44 "," */ CWORD_CWORD_CWORD_CWORD,
2912 /* 175 45 "-" */ CWORD_CCTL_CCTL_CWORD,
2913 /* 176 46 "." */ CWORD_CWORD_CWORD_CWORD,
2914 /* 177 47 "/" */ CWORD_CCTL_CCTL_CWORD,
2915 /* 178 48 "0" */ CWORD_CWORD_CWORD_CWORD,
2916 /* 179 49 "1" */ CWORD_CWORD_CWORD_CWORD,
2917 /* 180 50 "2" */ CWORD_CWORD_CWORD_CWORD,
2918 /* 181 51 "3" */ CWORD_CWORD_CWORD_CWORD,
2919 /* 182 52 "4" */ CWORD_CWORD_CWORD_CWORD,
2920 /* 183 53 "5" */ CWORD_CWORD_CWORD_CWORD,
2921 /* 184 54 "6" */ CWORD_CWORD_CWORD_CWORD,
2922 /* 185 55 "7" */ CWORD_CWORD_CWORD_CWORD,
2923 /* 186 56 "8" */ CWORD_CWORD_CWORD_CWORD,
2924 /* 187 57 "9" */ CWORD_CWORD_CWORD_CWORD,
2925 /* 188 58 ":" */ CWORD_CCTL_CCTL_CWORD,
2926 /* 189 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
2927 /* 190 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
2928 /* 191 61 "=" */ CWORD_CCTL_CCTL_CWORD,
2929 /* 192 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
2930 /* 193 63 "?" */ CWORD_CCTL_CCTL_CWORD,
2931 /* 194 64 "@" */ CWORD_CWORD_CWORD_CWORD,
2932 /* 195 65 "A" */ CWORD_CWORD_CWORD_CWORD,
2933 /* 196 66 "B" */ CWORD_CWORD_CWORD_CWORD,
2934 /* 197 67 "C" */ CWORD_CWORD_CWORD_CWORD,
2935 /* 198 68 "D" */ CWORD_CWORD_CWORD_CWORD,
2936 /* 199 69 "E" */ CWORD_CWORD_CWORD_CWORD,
2937 /* 200 70 "F" */ CWORD_CWORD_CWORD_CWORD,
2938 /* 201 71 "G" */ CWORD_CWORD_CWORD_CWORD,
2939 /* 202 72 "H" */ CWORD_CWORD_CWORD_CWORD,
2940 /* 203 73 "I" */ CWORD_CWORD_CWORD_CWORD,
2941 /* 204 74 "J" */ CWORD_CWORD_CWORD_CWORD,
2942 /* 205 75 "K" */ CWORD_CWORD_CWORD_CWORD,
2943 /* 206 76 "L" */ CWORD_CWORD_CWORD_CWORD,
2944 /* 207 77 "M" */ CWORD_CWORD_CWORD_CWORD,
2945 /* 208 78 "N" */ CWORD_CWORD_CWORD_CWORD,
2946 /* 209 79 "O" */ CWORD_CWORD_CWORD_CWORD,
2947 /* 210 80 "P" */ CWORD_CWORD_CWORD_CWORD,
2948 /* 211 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
2949 /* 212 82 "R" */ CWORD_CWORD_CWORD_CWORD,
2950 /* 213 83 "S" */ CWORD_CWORD_CWORD_CWORD,
2951 /* 214 84 "T" */ CWORD_CWORD_CWORD_CWORD,
2952 /* 215 85 "U" */ CWORD_CWORD_CWORD_CWORD,
2953 /* 216 86 "V" */ CWORD_CWORD_CWORD_CWORD,
2954 /* 217 87 "W" */ CWORD_CWORD_CWORD_CWORD,
2955 /* 218 88 "X" */ CWORD_CWORD_CWORD_CWORD,
2956 /* 219 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
2957 /* 220 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
2958 /* 221 91 "[" */ CWORD_CCTL_CCTL_CWORD,
2959 /* 222 92 "\" */ CBACK_CBACK_CCTL_CBACK,
2960 /* 223 93 "]" */ CWORD_CCTL_CCTL_CWORD,
2961 /* 224 94 "^" */ CWORD_CWORD_CWORD_CWORD,
2962 /* 225 95 "_" */ CWORD_CWORD_CWORD_CWORD,
2963 /* 226 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
2964 /* 227 97 "a" */ CWORD_CWORD_CWORD_CWORD,
2965 /* 228 98 "b" */ CWORD_CWORD_CWORD_CWORD,
2966 /* 229 99 "c" */ CWORD_CWORD_CWORD_CWORD,
2967 /* 230 100 "d" */ CWORD_CWORD_CWORD_CWORD,
2968 /* 231 101 "e" */ CWORD_CWORD_CWORD_CWORD,
2969 /* 232 102 "f" */ CWORD_CWORD_CWORD_CWORD,
2970 /* 233 103 "g" */ CWORD_CWORD_CWORD_CWORD,
2971 /* 234 104 "h" */ CWORD_CWORD_CWORD_CWORD,
2972 /* 235 105 "i" */ CWORD_CWORD_CWORD_CWORD,
2973 /* 236 106 "j" */ CWORD_CWORD_CWORD_CWORD,
2974 /* 237 107 "k" */ CWORD_CWORD_CWORD_CWORD,
2975 /* 238 108 "l" */ CWORD_CWORD_CWORD_CWORD,
2976 /* 239 109 "m" */ CWORD_CWORD_CWORD_CWORD,
2977 /* 240 110 "n" */ CWORD_CWORD_CWORD_CWORD,
2978 /* 241 111 "o" */ CWORD_CWORD_CWORD_CWORD,
2979 /* 242 112 "p" */ CWORD_CWORD_CWORD_CWORD,
2980 /* 243 113 "q" */ CWORD_CWORD_CWORD_CWORD,
2981 /* 244 114 "r" */ CWORD_CWORD_CWORD_CWORD,
2982 /* 245 115 "s" */ CWORD_CWORD_CWORD_CWORD,
2983 /* 246 116 "t" */ CWORD_CWORD_CWORD_CWORD,
2984 /* 247 117 "u" */ CWORD_CWORD_CWORD_CWORD,
2985 /* 248 118 "v" */ CWORD_CWORD_CWORD_CWORD,
2986 /* 249 119 "w" */ CWORD_CWORD_CWORD_CWORD,
2987 /* 250 120 "x" */ CWORD_CWORD_CWORD_CWORD,
2988 /* 251 121 "y" */ CWORD_CWORD_CWORD_CWORD,
2989 /* 252 122 "z" */ CWORD_CWORD_CWORD_CWORD,
2990 /* 253 123 "{" */ CWORD_CWORD_CWORD_CWORD,
2991 /* 254 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
2992 /* 255 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
2993 /* 256 126 "~" */ CWORD_CCTL_CCTL_CWORD,
2994 /* 257 127 */ CWORD_CWORD_CWORD_CWORD,
Eric Andersen2870d962001-07-02 17:27:21 +00002995};
2996
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00002997#define SIT(c, syntax) (S_I_T[(int)syntax_index_table[((int)c)+SYNBASE]][syntax])
2998
"Vladimir N. Oleynik"fdb871c2006-01-25 11:53:47 +00002999#endif /* USE_SIT_FUNCTION */
Eric Andersenc470f442003-07-28 09:56:35 +00003000
Eric Andersen2870d962001-07-02 17:27:21 +00003001
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00003002/* ============ Alias handling */
Denis Vlasenkofc06f292007-02-23 21:09:35 +00003003
Denis Vlasenko131ae172007-02-18 13:00:19 +00003004#if ENABLE_ASH_ALIAS
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00003005
3006#define ALIASINUSE 1
3007#define ALIASDEAD 2
3008
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00003009struct alias {
3010 struct alias *next;
3011 char *name;
3012 char *val;
3013 int flag;
3014};
3015
Denis Vlasenko01631112007-12-16 17:20:38 +00003016
3017static struct alias **atab; // [ATABSIZE];
3018#define INIT_G_alias() do { \
3019 atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
3020} while (0)
3021
Eric Andersen2870d962001-07-02 17:27:21 +00003022
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00003023static struct alias **
3024__lookupalias(const char *name) {
3025 unsigned int hashval;
3026 struct alias **app;
3027 const char *p;
3028 unsigned int ch;
3029
3030 p = name;
3031
3032 ch = (unsigned char)*p;
3033 hashval = ch << 4;
3034 while (ch) {
3035 hashval += ch;
3036 ch = (unsigned char)*++p;
3037 }
3038 app = &atab[hashval % ATABSIZE];
3039
3040 for (; *app; app = &(*app)->next) {
3041 if (strcmp(name, (*app)->name) == 0) {
3042 break;
3043 }
3044 }
3045
3046 return app;
3047}
3048
3049static struct alias *
3050lookupalias(const char *name, int check)
3051{
3052 struct alias *ap = *__lookupalias(name);
3053
3054 if (check && ap && (ap->flag & ALIASINUSE))
3055 return NULL;
3056 return ap;
3057}
3058
3059static struct alias *
3060freealias(struct alias *ap)
3061{
3062 struct alias *next;
3063
3064 if (ap->flag & ALIASINUSE) {
3065 ap->flag |= ALIASDEAD;
3066 return ap;
3067 }
3068
3069 next = ap->next;
3070 free(ap->name);
3071 free(ap->val);
3072 free(ap);
3073 return next;
3074}
Eric Andersencb57d552001-06-28 07:25:16 +00003075
Eric Andersenc470f442003-07-28 09:56:35 +00003076static void
3077setalias(const char *name, const char *val)
Eric Andersencb57d552001-06-28 07:25:16 +00003078{
3079 struct alias *ap, **app;
3080
3081 app = __lookupalias(name);
3082 ap = *app;
Denis Vlasenkob012b102007-02-19 22:43:01 +00003083 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +00003084 if (ap) {
3085 if (!(ap->flag & ALIASINUSE)) {
Denis Vlasenkob012b102007-02-19 22:43:01 +00003086 free(ap->val);
Eric Andersencb57d552001-06-28 07:25:16 +00003087 }
Denis Vlasenko0c032a42007-02-23 01:03:40 +00003088 ap->val = ckstrdup(val);
Eric Andersencb57d552001-06-28 07:25:16 +00003089 ap->flag &= ~ALIASDEAD;
3090 } else {
3091 /* not found */
Denis Vlasenko597906c2008-02-20 16:38:54 +00003092 ap = ckzalloc(sizeof(struct alias));
Denis Vlasenko0c032a42007-02-23 01:03:40 +00003093 ap->name = ckstrdup(name);
3094 ap->val = ckstrdup(val);
Denis Vlasenko597906c2008-02-20 16:38:54 +00003095 /*ap->flag = 0; - ckzalloc did it */
3096 /*ap->next = NULL;*/
Eric Andersencb57d552001-06-28 07:25:16 +00003097 *app = ap;
3098 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00003099 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00003100}
3101
Eric Andersenc470f442003-07-28 09:56:35 +00003102static int
3103unalias(const char *name)
Eric Andersen2870d962001-07-02 17:27:21 +00003104{
Eric Andersencb57d552001-06-28 07:25:16 +00003105 struct alias **app;
3106
3107 app = __lookupalias(name);
3108
3109 if (*app) {
Denis Vlasenkob012b102007-02-19 22:43:01 +00003110 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +00003111 *app = freealias(*app);
Denis Vlasenkob012b102007-02-19 22:43:01 +00003112 INT_ON;
Denis Vlasenko079f8af2006-11-27 16:49:31 +00003113 return 0;
Eric Andersencb57d552001-06-28 07:25:16 +00003114 }
3115
Denis Vlasenko079f8af2006-11-27 16:49:31 +00003116 return 1;
Eric Andersencb57d552001-06-28 07:25:16 +00003117}
3118
Eric Andersenc470f442003-07-28 09:56:35 +00003119static void
3120rmaliases(void)
Eric Andersen2870d962001-07-02 17:27:21 +00003121{
Eric Andersencb57d552001-06-28 07:25:16 +00003122 struct alias *ap, **app;
3123 int i;
3124
Denis Vlasenkob012b102007-02-19 22:43:01 +00003125 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +00003126 for (i = 0; i < ATABSIZE; i++) {
3127 app = &atab[i];
3128 for (ap = *app; ap; ap = *app) {
3129 *app = freealias(*app);
3130 if (ap == *app) {
3131 app = &ap->next;
3132 }
3133 }
3134 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00003135 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00003136}
3137
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00003138static void
3139printalias(const struct alias *ap)
3140{
3141 out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
3142}
3143
Eric Andersencb57d552001-06-28 07:25:16 +00003144/*
3145 * TODO - sort output
3146 */
Eric Andersenc470f442003-07-28 09:56:35 +00003147static int
Denis Vlasenko68404f12008-03-17 09:00:54 +00003148aliascmd(int argc ATTRIBUTE_UNUSED, char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +00003149{
3150 char *n, *v;
3151 int ret = 0;
3152 struct alias *ap;
3153
Denis Vlasenko68404f12008-03-17 09:00:54 +00003154 if (!argv[1]) {
Eric Andersencb57d552001-06-28 07:25:16 +00003155 int i;
3156
Denis Vlasenko68404f12008-03-17 09:00:54 +00003157 for (i = 0; i < ATABSIZE; i++) {
Eric Andersencb57d552001-06-28 07:25:16 +00003158 for (ap = atab[i]; ap; ap = ap->next) {
3159 printalias(ap);
3160 }
Denis Vlasenko68404f12008-03-17 09:00:54 +00003161 }
Denis Vlasenko079f8af2006-11-27 16:49:31 +00003162 return 0;
Eric Andersencb57d552001-06-28 07:25:16 +00003163 }
3164 while ((n = *++argv) != NULL) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00003165 v = strchr(n+1, '=');
3166 if (v == NULL) { /* n+1: funny ksh stuff */
3167 ap = *__lookupalias(n);
3168 if (ap == NULL) {
Eric Andersenc470f442003-07-28 09:56:35 +00003169 fprintf(stderr, "%s: %s not found\n", "alias", n);
Eric Andersencb57d552001-06-28 07:25:16 +00003170 ret = 1;
3171 } else
3172 printalias(ap);
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00003173 } else {
Eric Andersencb57d552001-06-28 07:25:16 +00003174 *v++ = '\0';
3175 setalias(n, v);
3176 }
3177 }
3178
Denis Vlasenkod9e15f22006-11-27 16:49:55 +00003179 return ret;
Eric Andersencb57d552001-06-28 07:25:16 +00003180}
3181
Eric Andersenc470f442003-07-28 09:56:35 +00003182static int
Denis Vlasenko68404f12008-03-17 09:00:54 +00003183unaliascmd(int argc ATTRIBUTE_UNUSED, char **argv ATTRIBUTE_UNUSED)
Eric Andersencb57d552001-06-28 07:25:16 +00003184{
3185 int i;
3186
3187 while ((i = nextopt("a")) != '\0') {
3188 if (i == 'a') {
3189 rmaliases();
Denis Vlasenko079f8af2006-11-27 16:49:31 +00003190 return 0;
Eric Andersencb57d552001-06-28 07:25:16 +00003191 }
3192 }
3193 for (i = 0; *argptr; argptr++) {
3194 if (unalias(*argptr)) {
Eric Andersenc470f442003-07-28 09:56:35 +00003195 fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
Eric Andersencb57d552001-06-28 07:25:16 +00003196 i = 1;
3197 }
3198 }
3199
Denis Vlasenkod9e15f22006-11-27 16:49:55 +00003200 return i;
Eric Andersencb57d552001-06-28 07:25:16 +00003201}
Denis Vlasenkofc06f292007-02-23 21:09:35 +00003202
Denis Vlasenko131ae172007-02-18 13:00:19 +00003203#endif /* ASH_ALIAS */
Eric Andersencb57d552001-06-28 07:25:16 +00003204
Eric Andersenc470f442003-07-28 09:56:35 +00003205
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003206/* ============ jobs.c */
3207
3208/* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
3209#define FORK_FG 0
3210#define FORK_BG 1
3211#define FORK_NOJOB 2
3212
3213/* mode flags for showjob(s) */
3214#define SHOW_PGID 0x01 /* only show pgid - for jobs -p */
3215#define SHOW_PID 0x04 /* include process pid */
3216#define SHOW_CHANGED 0x08 /* only jobs whose state has changed */
3217
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003218/*
3219 * A job structure contains information about a job. A job is either a
3220 * single process or a set of processes contained in a pipeline. In the
3221 * latter case, pidlist will be non-NULL, and will point to a -1 terminated
3222 * array of pids.
3223 */
3224
3225struct procstat {
3226 pid_t pid; /* process id */
3227 int status; /* last process status from wait() */
3228 char *cmd; /* text of command being run */
3229};
3230
3231struct job {
3232 struct procstat ps0; /* status of process */
3233 struct procstat *ps; /* status or processes when more than one */
3234#if JOBS
3235 int stopstatus; /* status of a stopped job */
3236#endif
3237 uint32_t
3238 nprocs: 16, /* number of processes */
3239 state: 8,
3240#define JOBRUNNING 0 /* at least one proc running */
3241#define JOBSTOPPED 1 /* all procs are stopped */
3242#define JOBDONE 2 /* all procs are completed */
3243#if JOBS
3244 sigint: 1, /* job was killed by SIGINT */
3245 jobctl: 1, /* job running under job control */
3246#endif
3247 waited: 1, /* true if this entry has been waited for */
3248 used: 1, /* true if this entry is in used */
3249 changed: 1; /* true if status has changed */
3250 struct job *prev_job; /* previous job */
3251};
3252
3253static pid_t backgndpid; /* pid of last background process */
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003254static smallint job_warning; /* user was warned about stopped jobs (can be 2, 1 or 0). */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003255
Denis Vlasenko68404f12008-03-17 09:00:54 +00003256static struct job *makejob(/*union node *,*/ int);
Denis Vlasenko85c24712008-03-17 09:04:04 +00003257#if !JOBS
3258#define forkshell(job, node, mode) forkshell(job, mode)
3259#endif
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003260static int forkshell(struct job *, union node *, int);
3261static int waitforjob(struct job *);
3262
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003263#if !JOBS
3264enum { jobctl = 0 };
3265#define setjobctl(on) do {} while (0)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003266#else
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003267static smallint jobctl; /* true if doing job control */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003268static void setjobctl(int);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003269#endif
3270
3271/*
3272 * Set the signal handler for the specified signal. The routine figures
3273 * out what it should be set to.
3274 */
3275static void
3276setsignal(int signo)
3277{
3278 int action;
3279 char *t, tsig;
3280 struct sigaction act;
3281
3282 t = trap[signo];
Denis Vlasenko991a1da2008-02-10 19:02:53 +00003283 action = S_IGN;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003284 if (t == NULL)
3285 action = S_DFL;
3286 else if (*t != '\0')
3287 action = S_CATCH;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003288 if (rootshell && action == S_DFL) {
3289 switch (signo) {
3290 case SIGINT:
3291 if (iflag || minusc || sflag == 0)
3292 action = S_CATCH;
3293 break;
3294 case SIGQUIT:
3295#if DEBUG
3296 if (debug)
3297 break;
3298#endif
3299 /* FALLTHROUGH */
3300 case SIGTERM:
3301 if (iflag)
3302 action = S_IGN;
3303 break;
3304#if JOBS
3305 case SIGTSTP:
3306 case SIGTTOU:
3307 if (mflag)
3308 action = S_IGN;
3309 break;
3310#endif
3311 }
3312 }
3313
3314 t = &sigmode[signo - 1];
3315 tsig = *t;
3316 if (tsig == 0) {
3317 /*
3318 * current setting unknown
3319 */
Denis Vlasenko991a1da2008-02-10 19:02:53 +00003320 if (sigaction(signo, NULL, &act) == -1) {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003321 /*
3322 * Pretend it worked; maybe we should give a warning
3323 * here, but other shells don't. We don't alter
3324 * sigmode, so that we retry every time.
3325 */
3326 return;
3327 }
Denis Vlasenko991a1da2008-02-10 19:02:53 +00003328 tsig = S_RESET; /* force to be set */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003329 if (act.sa_handler == SIG_IGN) {
Denis Vlasenko991a1da2008-02-10 19:02:53 +00003330 tsig = S_HARD_IGN;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003331 if (mflag
3332 && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
3333 ) {
3334 tsig = S_IGN; /* don't hard ignore these */
Denis Vlasenko991a1da2008-02-10 19:02:53 +00003335 }
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003336 }
3337 }
3338 if (tsig == S_HARD_IGN || tsig == action)
3339 return;
Denis Vlasenko991a1da2008-02-10 19:02:53 +00003340 act.sa_handler = SIG_DFL;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003341 switch (action) {
3342 case S_CATCH:
3343 act.sa_handler = onsig;
3344 break;
3345 case S_IGN:
3346 act.sa_handler = SIG_IGN;
3347 break;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003348 }
3349 *t = action;
3350 act.sa_flags = 0;
3351 sigfillset(&act.sa_mask);
Denis Vlasenko8e2cfec2008-03-12 23:19:35 +00003352 sigaction_set(signo, &act);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003353}
3354
3355/* mode flags for set_curjob */
3356#define CUR_DELETE 2
3357#define CUR_RUNNING 1
3358#define CUR_STOPPED 0
3359
3360/* mode flags for dowait */
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00003361#define DOWAIT_NONBLOCK WNOHANG
3362#define DOWAIT_BLOCK 0
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003363
3364#if JOBS
3365/* pgrp of shell on invocation */
3366static int initialpgrp;
3367static int ttyfd = -1;
3368#endif
3369/* array of jobs */
3370static struct job *jobtab;
3371/* size of array */
3372static unsigned njobs;
3373/* current job */
3374static struct job *curjob;
3375/* number of presumed living untracked jobs */
3376static int jobless;
3377
3378static void
3379set_curjob(struct job *jp, unsigned mode)
3380{
3381 struct job *jp1;
3382 struct job **jpp, **curp;
3383
3384 /* first remove from list */
3385 jpp = curp = &curjob;
3386 do {
3387 jp1 = *jpp;
3388 if (jp1 == jp)
3389 break;
3390 jpp = &jp1->prev_job;
3391 } while (1);
3392 *jpp = jp1->prev_job;
3393
3394 /* Then re-insert in correct position */
3395 jpp = curp;
3396 switch (mode) {
3397 default:
3398#if DEBUG
3399 abort();
3400#endif
3401 case CUR_DELETE:
3402 /* job being deleted */
3403 break;
3404 case CUR_RUNNING:
3405 /* newly created job or backgrounded job,
3406 put after all stopped jobs. */
3407 do {
3408 jp1 = *jpp;
3409#if JOBS
3410 if (!jp1 || jp1->state != JOBSTOPPED)
3411#endif
3412 break;
3413 jpp = &jp1->prev_job;
3414 } while (1);
3415 /* FALLTHROUGH */
3416#if JOBS
3417 case CUR_STOPPED:
3418#endif
3419 /* newly stopped job - becomes curjob */
3420 jp->prev_job = *jpp;
3421 *jpp = jp;
3422 break;
3423 }
3424}
3425
3426#if JOBS || DEBUG
3427static int
3428jobno(const struct job *jp)
3429{
3430 return jp - jobtab + 1;
3431}
3432#endif
3433
3434/*
3435 * Convert a job name to a job structure.
3436 */
Denis Vlasenko85c24712008-03-17 09:04:04 +00003437#if !JOBS
3438#define getjob(name, getctl) getjob(name)
3439#endif
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003440static struct job *
3441getjob(const char *name, int getctl)
3442{
3443 struct job *jp;
3444 struct job *found;
3445 const char *err_msg = "No such job: %s";
3446 unsigned num;
3447 int c;
3448 const char *p;
3449 char *(*match)(const char *, const char *);
3450
3451 jp = curjob;
3452 p = name;
3453 if (!p)
3454 goto currentjob;
3455
3456 if (*p != '%')
3457 goto err;
3458
3459 c = *++p;
3460 if (!c)
3461 goto currentjob;
3462
3463 if (!p[1]) {
3464 if (c == '+' || c == '%') {
3465 currentjob:
3466 err_msg = "No current job";
3467 goto check;
3468 }
3469 if (c == '-') {
3470 if (jp)
3471 jp = jp->prev_job;
3472 err_msg = "No previous job";
3473 check:
3474 if (!jp)
3475 goto err;
3476 goto gotit;
3477 }
3478 }
3479
3480 if (is_number(p)) {
Denis Vlasenko92e13c22008-03-25 01:17:40 +00003481// TODO: number() instead? It does error checking...
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003482 num = atoi(p);
3483 if (num < njobs) {
3484 jp = jobtab + num - 1;
3485 if (jp->used)
3486 goto gotit;
3487 goto err;
3488 }
3489 }
3490
3491 match = prefix;
3492 if (*p == '?') {
3493 match = strstr;
3494 p++;
3495 }
3496
3497 found = 0;
3498 while (1) {
3499 if (!jp)
3500 goto err;
3501 if (match(jp->ps[0].cmd, p)) {
3502 if (found)
3503 goto err;
3504 found = jp;
3505 err_msg = "%s: ambiguous";
3506 }
3507 jp = jp->prev_job;
3508 }
3509
3510 gotit:
3511#if JOBS
3512 err_msg = "job %s not created under job control";
3513 if (getctl && jp->jobctl == 0)
3514 goto err;
3515#endif
3516 return jp;
3517 err:
3518 ash_msg_and_raise_error(err_msg, name);
3519}
3520
3521/*
3522 * Mark a job structure as unused.
3523 */
3524static void
3525freejob(struct job *jp)
3526{
3527 struct procstat *ps;
3528 int i;
3529
3530 INT_OFF;
3531 for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
3532 if (ps->cmd != nullstr)
3533 free(ps->cmd);
3534 }
3535 if (jp->ps != &jp->ps0)
3536 free(jp->ps);
3537 jp->used = 0;
3538 set_curjob(jp, CUR_DELETE);
3539 INT_ON;
3540}
3541
3542#if JOBS
3543static void
3544xtcsetpgrp(int fd, pid_t pgrp)
3545{
3546 if (tcsetpgrp(fd, pgrp))
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00003547 ash_msg_and_raise_error("cannot set tty process group (%m)");
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003548}
3549
3550/*
3551 * Turn job control on and off.
3552 *
3553 * Note: This code assumes that the third arg to ioctl is a character
3554 * pointer, which is true on Berkeley systems but not System V. Since
3555 * System V doesn't have job control yet, this isn't a problem now.
3556 *
3557 * Called with interrupts off.
3558 */
3559static void
3560setjobctl(int on)
3561{
3562 int fd;
3563 int pgrp;
3564
3565 if (on == jobctl || rootshell == 0)
3566 return;
3567 if (on) {
3568 int ofd;
3569 ofd = fd = open(_PATH_TTY, O_RDWR);
3570 if (fd < 0) {
3571 /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
3572 * That sometimes helps to acquire controlling tty.
3573 * Obviously, a workaround for bugs when someone
3574 * failed to provide a controlling tty to bash! :) */
Denis Vlasenkoed270a52007-11-26 05:37:07 +00003575 fd = 2;
3576 while (!isatty(fd))
3577 if (--fd < 0)
3578 goto out;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003579 }
3580 fd = fcntl(fd, F_DUPFD, 10);
Denis Vlasenkoed270a52007-11-26 05:37:07 +00003581 if (ofd >= 0)
3582 close(ofd);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003583 if (fd < 0)
3584 goto out;
Denis Vlasenkoed270a52007-11-26 05:37:07 +00003585 /* fd is a tty at this point */
Denis Vlasenko96e1b382007-09-30 23:50:48 +00003586 close_on_exec_on(fd);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003587 do { /* while we are in the background */
3588 pgrp = tcgetpgrp(fd);
3589 if (pgrp < 0) {
3590 out:
3591 ash_msg("can't access tty; job control turned off");
3592 mflag = on = 0;
3593 goto close;
3594 }
3595 if (pgrp == getpgrp())
3596 break;
3597 killpg(0, SIGTTIN);
3598 } while (1);
3599 initialpgrp = pgrp;
3600
3601 setsignal(SIGTSTP);
3602 setsignal(SIGTTOU);
3603 setsignal(SIGTTIN);
3604 pgrp = rootpid;
3605 setpgid(0, pgrp);
3606 xtcsetpgrp(fd, pgrp);
3607 } else {
3608 /* turning job control off */
3609 fd = ttyfd;
3610 pgrp = initialpgrp;
Denis Vlasenko08c8c1d2007-04-28 22:39:02 +00003611 /* was xtcsetpgrp, but this can make exiting ash
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00003612 * loop forever if pty is already deleted */
Denis Vlasenko08c8c1d2007-04-28 22:39:02 +00003613 tcsetpgrp(fd, pgrp);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003614 setpgid(0, pgrp);
3615 setsignal(SIGTSTP);
3616 setsignal(SIGTTOU);
3617 setsignal(SIGTTIN);
3618 close:
Denis Vlasenkoed270a52007-11-26 05:37:07 +00003619 if (fd >= 0)
3620 close(fd);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003621 fd = -1;
3622 }
3623 ttyfd = fd;
3624 jobctl = on;
3625}
3626
3627static int
3628killcmd(int argc, char **argv)
3629{
Denis Vlasenko68404f12008-03-17 09:00:54 +00003630 int i = 1;
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003631 if (argv[1] && strcmp(argv[1], "-l") != 0) {
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003632 do {
3633 if (argv[i][0] == '%') {
3634 struct job *jp = getjob(argv[i], 0);
3635 unsigned pid = jp->ps[0].pid;
3636 /* Enough space for ' -NNN<nul>' */
3637 argv[i] = alloca(sizeof(int)*3 + 3);
3638 /* kill_main has matching code to expect
3639 * leading space. Needed to not confuse
3640 * negative pids with "kill -SIGNAL_NO" syntax */
3641 sprintf(argv[i], " -%u", pid);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003642 }
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003643 } while (argv[++i]);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003644 }
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003645 return kill_main(argc, argv);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003646}
3647
3648static void
3649showpipe(struct job *jp, FILE *out)
3650{
3651 struct procstat *sp;
3652 struct procstat *spend;
3653
3654 spend = jp->ps + jp->nprocs;
3655 for (sp = jp->ps + 1; sp < spend; sp++)
3656 fprintf(out, " | %s", sp->cmd);
3657 outcslow('\n', out);
3658 flush_stdout_stderr();
3659}
3660
3661
3662static int
3663restartjob(struct job *jp, int mode)
3664{
3665 struct procstat *ps;
3666 int i;
3667 int status;
3668 pid_t pgid;
3669
3670 INT_OFF;
3671 if (jp->state == JOBDONE)
3672 goto out;
3673 jp->state = JOBRUNNING;
3674 pgid = jp->ps->pid;
3675 if (mode == FORK_FG)
3676 xtcsetpgrp(ttyfd, pgid);
3677 killpg(pgid, SIGCONT);
3678 ps = jp->ps;
3679 i = jp->nprocs;
3680 do {
3681 if (WIFSTOPPED(ps->status)) {
3682 ps->status = -1;
3683 }
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00003684 ps++;
3685 } while (--i);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003686 out:
3687 status = (mode == FORK_FG) ? waitforjob(jp) : 0;
3688 INT_ON;
3689 return status;
3690}
3691
3692static int
Denis Vlasenko68404f12008-03-17 09:00:54 +00003693fg_bgcmd(int argc ATTRIBUTE_UNUSED, char **argv)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003694{
3695 struct job *jp;
3696 FILE *out;
3697 int mode;
3698 int retval;
3699
3700 mode = (**argv == 'f') ? FORK_FG : FORK_BG;
3701 nextopt(nullstr);
3702 argv = argptr;
3703 out = stdout;
3704 do {
3705 jp = getjob(*argv, 1);
3706 if (mode == FORK_BG) {
3707 set_curjob(jp, CUR_RUNNING);
3708 fprintf(out, "[%d] ", jobno(jp));
3709 }
3710 outstr(jp->ps->cmd, out);
3711 showpipe(jp, out);
3712 retval = restartjob(jp, mode);
3713 } while (*argv && *++argv);
3714 return retval;
3715}
3716#endif
3717
3718static int
3719sprint_status(char *s, int status, int sigonly)
3720{
3721 int col;
3722 int st;
3723
3724 col = 0;
3725 if (!WIFEXITED(status)) {
3726#if JOBS
3727 if (WIFSTOPPED(status))
3728 st = WSTOPSIG(status);
3729 else
3730#endif
3731 st = WTERMSIG(status);
3732 if (sigonly) {
3733 if (st == SIGINT || st == SIGPIPE)
3734 goto out;
3735#if JOBS
3736 if (WIFSTOPPED(status))
3737 goto out;
3738#endif
3739 }
3740 st &= 0x7f;
3741 col = fmtstr(s, 32, strsignal(st));
3742 if (WCOREDUMP(status)) {
3743 col += fmtstr(s + col, 16, " (core dumped)");
3744 }
3745 } else if (!sigonly) {
3746 st = WEXITSTATUS(status);
3747 if (st)
3748 col = fmtstr(s, 16, "Done(%d)", st);
3749 else
3750 col = fmtstr(s, 16, "Done");
3751 }
3752 out:
3753 return col;
3754}
3755
3756/*
3757 * Do a wait system call. If job control is compiled in, we accept
3758 * stopped processes. If block is zero, we return a value of zero
3759 * rather than blocking.
3760 *
3761 * System V doesn't have a non-blocking wait system call. It does
3762 * have a SIGCLD signal that is sent to a process when one of it's
3763 * children dies. The obvious way to use SIGCLD would be to install
3764 * a handler for SIGCLD which simply bumped a counter when a SIGCLD
3765 * was received, and have waitproc bump another counter when it got
3766 * the status of a process. Waitproc would then know that a wait
3767 * system call would not block if the two counters were different.
3768 * This approach doesn't work because if a process has children that
3769 * have not been waited for, System V will send it a SIGCLD when it
3770 * installs a signal handler for SIGCLD. What this means is that when
3771 * a child exits, the shell will be sent SIGCLD signals continuously
3772 * until is runs out of stack space, unless it does a wait call before
3773 * restoring the signal handler. The code below takes advantage of
3774 * this (mis)feature by installing a signal handler for SIGCLD and
3775 * then checking to see whether it was called. If there are any
3776 * children to be waited for, it will be.
3777 *
3778 * If neither SYSV nor BSD is defined, we don't implement nonblocking
3779 * waits at all. In this case, the user will not be informed when
3780 * a background process until the next time she runs a real program
3781 * (as opposed to running a builtin command or just typing return),
3782 * and the jobs command may give out of date information.
3783 */
3784static int
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00003785waitproc(int wait_flags, int *status)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003786{
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003787#if JOBS
3788 if (jobctl)
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00003789 wait_flags |= WUNTRACED;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003790#endif
Denis Vlasenko991a1da2008-02-10 19:02:53 +00003791 /* NB: _not_ safe_waitpid, we need to detect EINTR */
3792 return waitpid(-1, status, wait_flags);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003793}
3794
3795/*
3796 * Wait for a process to terminate.
3797 */
3798static int
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00003799dowait(int wait_flags, struct job *job)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003800{
3801 int pid;
3802 int status;
3803 struct job *jp;
3804 struct job *thisjob;
3805 int state;
3806
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00003807 TRACE(("dowait(%d) called\n", wait_flags));
3808 pid = waitproc(wait_flags, &status);
3809 TRACE(("wait returns pid=%d, status=%d\n", pid, status));
Denis Vlasenko991a1da2008-02-10 19:02:53 +00003810 if (pid <= 0) {
3811 /* If we were doing blocking wait and (probably) got EINTR,
3812 * check for pending sigs received while waiting.
3813 * (NB: can be moved into callers if needed) */
3814 if (wait_flags == DOWAIT_BLOCK && pendingsig)
3815 raise_exception(EXSIG);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003816 return pid;
Denis Vlasenko991a1da2008-02-10 19:02:53 +00003817 }
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003818 INT_OFF;
3819 thisjob = NULL;
3820 for (jp = curjob; jp; jp = jp->prev_job) {
3821 struct procstat *sp;
3822 struct procstat *spend;
3823 if (jp->state == JOBDONE)
3824 continue;
3825 state = JOBDONE;
3826 spend = jp->ps + jp->nprocs;
3827 sp = jp->ps;
3828 do {
3829 if (sp->pid == pid) {
3830 TRACE(("Job %d: changing status of proc %d "
3831 "from 0x%x to 0x%x\n",
3832 jobno(jp), pid, sp->status, status));
3833 sp->status = status;
3834 thisjob = jp;
3835 }
3836 if (sp->status == -1)
3837 state = JOBRUNNING;
3838#if JOBS
3839 if (state == JOBRUNNING)
3840 continue;
3841 if (WIFSTOPPED(sp->status)) {
3842 jp->stopstatus = sp->status;
3843 state = JOBSTOPPED;
3844 }
3845#endif
3846 } while (++sp < spend);
3847 if (thisjob)
3848 goto gotjob;
3849 }
3850#if JOBS
3851 if (!WIFSTOPPED(status))
3852#endif
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003853 jobless--;
3854 goto out;
3855
3856 gotjob:
3857 if (state != JOBRUNNING) {
3858 thisjob->changed = 1;
3859
3860 if (thisjob->state != state) {
3861 TRACE(("Job %d: changing state from %d to %d\n",
3862 jobno(thisjob), thisjob->state, state));
3863 thisjob->state = state;
3864#if JOBS
3865 if (state == JOBSTOPPED) {
3866 set_curjob(thisjob, CUR_STOPPED);
3867 }
3868#endif
3869 }
3870 }
3871
3872 out:
3873 INT_ON;
3874
3875 if (thisjob && thisjob == job) {
3876 char s[48 + 1];
3877 int len;
3878
3879 len = sprint_status(s, status, 1);
3880 if (len) {
3881 s[len] = '\n';
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00003882 s[len + 1] = '\0';
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003883 out2str(s);
3884 }
3885 }
3886 return pid;
3887}
3888
3889#if JOBS
3890static void
3891showjob(FILE *out, struct job *jp, int mode)
3892{
3893 struct procstat *ps;
3894 struct procstat *psend;
3895 int col;
Denis Vlasenko40ba9982007-07-14 00:48:29 +00003896 int indent_col;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003897 char s[80];
3898
3899 ps = jp->ps;
3900
3901 if (mode & SHOW_PGID) {
3902 /* just output process (group) id of pipeline */
3903 fprintf(out, "%d\n", ps->pid);
3904 return;
3905 }
3906
3907 col = fmtstr(s, 16, "[%d] ", jobno(jp));
Denis Vlasenko40ba9982007-07-14 00:48:29 +00003908 indent_col = col;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003909
3910 if (jp == curjob)
3911 s[col - 2] = '+';
3912 else if (curjob && jp == curjob->prev_job)
3913 s[col - 2] = '-';
3914
3915 if (mode & SHOW_PID)
3916 col += fmtstr(s + col, 16, "%d ", ps->pid);
3917
3918 psend = ps + jp->nprocs;
3919
3920 if (jp->state == JOBRUNNING) {
3921 strcpy(s + col, "Running");
3922 col += sizeof("Running") - 1;
3923 } else {
3924 int status = psend[-1].status;
3925 if (jp->state == JOBSTOPPED)
3926 status = jp->stopstatus;
3927 col += sprint_status(s + col, status, 0);
3928 }
3929
3930 goto start;
3931
3932 do {
3933 /* for each process */
Denis Vlasenko40ba9982007-07-14 00:48:29 +00003934 col = fmtstr(s, 48, " |\n%*c%d ", indent_col, ' ', ps->pid) - 3;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003935 start:
3936 fprintf(out, "%s%*c%s",
3937 s, 33 - col >= 0 ? 33 - col : 0, ' ', ps->cmd
3938 );
3939 if (!(mode & SHOW_PID)) {
3940 showpipe(jp, out);
3941 break;
3942 }
3943 if (++ps == psend) {
3944 outcslow('\n', out);
3945 break;
3946 }
3947 } while (1);
3948
3949 jp->changed = 0;
3950
3951 if (jp->state == JOBDONE) {
3952 TRACE(("showjob: freeing job %d\n", jobno(jp)));
3953 freejob(jp);
3954 }
3955}
3956
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003957/*
3958 * Print a list of jobs. If "change" is nonzero, only print jobs whose
3959 * statuses have changed since the last call to showjobs.
3960 */
3961static void
3962showjobs(FILE *out, int mode)
3963{
3964 struct job *jp;
3965
3966 TRACE(("showjobs(%x) called\n", mode));
3967
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00003968 /* If not even one job changed, there is nothing to do */
3969 while (dowait(DOWAIT_NONBLOCK, NULL) > 0)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003970 continue;
3971
3972 for (jp = curjob; jp; jp = jp->prev_job) {
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003973 if (!(mode & SHOW_CHANGED) || jp->changed) {
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003974 showjob(out, jp, mode);
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003975 }
Denis Vlasenkoa8915072007-02-23 21:10:06 +00003976 }
3977}
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003978
3979static int
Denis Vlasenko68404f12008-03-17 09:00:54 +00003980jobscmd(int argc ATTRIBUTE_UNUSED, char **argv)
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00003981{
3982 int mode, m;
3983
3984 mode = 0;
3985 while ((m = nextopt("lp"))) {
3986 if (m == 'l')
3987 mode = SHOW_PID;
3988 else
3989 mode = SHOW_PGID;
3990 }
3991
3992 argv = argptr;
3993 if (*argv) {
3994 do
3995 showjob(stdout, getjob(*argv,0), mode);
3996 while (*++argv);
3997 } else
3998 showjobs(stdout, mode);
3999
4000 return 0;
4001}
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004002#endif /* JOBS */
4003
4004static int
4005getstatus(struct job *job)
4006{
4007 int status;
4008 int retval;
4009
4010 status = job->ps[job->nprocs - 1].status;
4011 retval = WEXITSTATUS(status);
4012 if (!WIFEXITED(status)) {
4013#if JOBS
4014 retval = WSTOPSIG(status);
4015 if (!WIFSTOPPED(status))
4016#endif
4017 {
4018 /* XXX: limits number of signals */
4019 retval = WTERMSIG(status);
4020#if JOBS
4021 if (retval == SIGINT)
4022 job->sigint = 1;
4023#endif
4024 }
4025 retval += 128;
4026 }
4027 TRACE(("getstatus: job %d, nproc %d, status %x, retval %x\n",
4028 jobno(job), job->nprocs, status, retval));
4029 return retval;
4030}
4031
4032static int
Denis Vlasenko68404f12008-03-17 09:00:54 +00004033waitcmd(int argc ATTRIBUTE_UNUSED, char **argv)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004034{
4035 struct job *job;
4036 int retval;
4037 struct job *jp;
4038
Denis Vlasenko991a1da2008-02-10 19:02:53 +00004039// exsig++;
4040// xbarrier();
4041 if (pendingsig)
4042 raise_exception(EXSIG);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004043
4044 nextopt(nullstr);
4045 retval = 0;
4046
4047 argv = argptr;
4048 if (!*argv) {
4049 /* wait for all jobs */
4050 for (;;) {
4051 jp = curjob;
4052 while (1) {
Denis Vlasenko991a1da2008-02-10 19:02:53 +00004053 if (!jp) /* no running procs */
4054 goto ret;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004055 if (jp->state == JOBRUNNING)
4056 break;
4057 jp->waited = 1;
4058 jp = jp->prev_job;
4059 }
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00004060 dowait(DOWAIT_BLOCK, NULL);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004061 }
4062 }
4063
4064 retval = 127;
4065 do {
4066 if (**argv != '%') {
4067 pid_t pid = number(*argv);
4068 job = curjob;
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00004069 while (1) {
4070 if (!job)
4071 goto repeat;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004072 if (job->ps[job->nprocs - 1].pid == pid)
4073 break;
4074 job = job->prev_job;
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00004075 }
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004076 } else
4077 job = getjob(*argv, 0);
4078 /* loop until process terminated or stopped */
4079 while (job->state == JOBRUNNING)
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00004080 dowait(DOWAIT_BLOCK, NULL);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004081 job->waited = 1;
4082 retval = getstatus(job);
4083 repeat:
4084 ;
4085 } while (*++argv);
4086
Denis Vlasenko991a1da2008-02-10 19:02:53 +00004087 ret:
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004088 return retval;
4089}
4090
4091static struct job *
4092growjobtab(void)
4093{
4094 size_t len;
4095 ptrdiff_t offset;
4096 struct job *jp, *jq;
4097
4098 len = njobs * sizeof(*jp);
4099 jq = jobtab;
4100 jp = ckrealloc(jq, len + 4 * sizeof(*jp));
4101
4102 offset = (char *)jp - (char *)jq;
4103 if (offset) {
4104 /* Relocate pointers */
4105 size_t l = len;
4106
4107 jq = (struct job *)((char *)jq + l);
4108 while (l) {
4109 l -= sizeof(*jp);
4110 jq--;
4111#define joff(p) ((struct job *)((char *)(p) + l))
4112#define jmove(p) (p) = (void *)((char *)(p) + offset)
4113 if (joff(jp)->ps == &jq->ps0)
4114 jmove(joff(jp)->ps);
4115 if (joff(jp)->prev_job)
4116 jmove(joff(jp)->prev_job);
4117 }
4118 if (curjob)
4119 jmove(curjob);
4120#undef joff
4121#undef jmove
4122 }
4123
4124 njobs += 4;
4125 jobtab = jp;
4126 jp = (struct job *)((char *)jp + len);
4127 jq = jp + 3;
4128 do {
4129 jq->used = 0;
4130 } while (--jq >= jp);
4131 return jp;
4132}
4133
4134/*
4135 * Return a new job structure.
4136 * Called with interrupts off.
4137 */
4138static struct job *
Denis Vlasenko68404f12008-03-17 09:00:54 +00004139makejob(/*union node *node,*/ int nprocs)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004140{
4141 int i;
4142 struct job *jp;
4143
4144 for (i = njobs, jp = jobtab; ; jp++) {
4145 if (--i < 0) {
4146 jp = growjobtab();
4147 break;
4148 }
4149 if (jp->used == 0)
4150 break;
4151 if (jp->state != JOBDONE || !jp->waited)
4152 continue;
4153#if JOBS
4154 if (jobctl)
4155 continue;
4156#endif
4157 freejob(jp);
4158 break;
4159 }
4160 memset(jp, 0, sizeof(*jp));
4161#if JOBS
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +00004162 /* jp->jobctl is a bitfield.
4163 * "jp->jobctl |= jobctl" likely to give awful code */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004164 if (jobctl)
4165 jp->jobctl = 1;
4166#endif
4167 jp->prev_job = curjob;
4168 curjob = jp;
4169 jp->used = 1;
4170 jp->ps = &jp->ps0;
4171 if (nprocs > 1) {
4172 jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
4173 }
Denis Vlasenko68404f12008-03-17 09:00:54 +00004174 TRACE(("makejob(%d) returns %%%d\n", nprocs,
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004175 jobno(jp)));
4176 return jp;
4177}
4178
4179#if JOBS
4180/*
4181 * Return a string identifying a command (to be printed by the
4182 * jobs command).
4183 */
4184static char *cmdnextc;
4185
4186static void
4187cmdputs(const char *s)
4188{
Denis Vlasenko92e13c22008-03-25 01:17:40 +00004189 static const char vstype[VSTYPE + 1][3] = {
4190 "", "}", "-", "+", "?", "=",
4191 "%", "%%", "#", "##"
4192 USE_ASH_BASH_COMPAT(, ":", "/", "//")
4193 };
4194
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004195 const char *p, *str;
4196 char c, cc[2] = " ";
4197 char *nextc;
4198 int subtype = 0;
4199 int quoted = 0;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004200
4201 nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
4202 p = s;
4203 while ((c = *p++) != 0) {
4204 str = 0;
4205 switch (c) {
4206 case CTLESC:
4207 c = *p++;
4208 break;
4209 case CTLVAR:
4210 subtype = *p++;
4211 if ((subtype & VSTYPE) == VSLENGTH)
4212 str = "${#";
4213 else
4214 str = "${";
4215 if (!(subtype & VSQUOTE) == !(quoted & 1))
4216 goto dostr;
4217 quoted ^= 1;
4218 c = '"';
4219 break;
4220 case CTLENDVAR:
4221 str = "\"}" + !(quoted & 1);
4222 quoted >>= 1;
4223 subtype = 0;
4224 goto dostr;
4225 case CTLBACKQ:
4226 str = "$(...)";
4227 goto dostr;
4228 case CTLBACKQ+CTLQUOTE:
4229 str = "\"$(...)\"";
4230 goto dostr;
4231#if ENABLE_ASH_MATH_SUPPORT
4232 case CTLARI:
4233 str = "$((";
4234 goto dostr;
4235 case CTLENDARI:
4236 str = "))";
4237 goto dostr;
4238#endif
4239 case CTLQUOTEMARK:
4240 quoted ^= 1;
4241 c = '"';
4242 break;
4243 case '=':
4244 if (subtype == 0)
4245 break;
4246 if ((subtype & VSTYPE) != VSNORMAL)
4247 quoted <<= 1;
4248 str = vstype[subtype & VSTYPE];
4249 if (subtype & VSNUL)
4250 c = ':';
4251 else
4252 goto checkstr;
4253 break;
4254 case '\'':
4255 case '\\':
4256 case '"':
4257 case '$':
4258 /* These can only happen inside quotes */
4259 cc[0] = c;
4260 str = cc;
4261 c = '\\';
4262 break;
4263 default:
4264 break;
4265 }
4266 USTPUTC(c, nextc);
4267 checkstr:
4268 if (!str)
4269 continue;
4270 dostr:
4271 while ((c = *str++)) {
4272 USTPUTC(c, nextc);
4273 }
4274 }
4275 if (quoted & 1) {
4276 USTPUTC('"', nextc);
4277 }
4278 *nextc = 0;
4279 cmdnextc = nextc;
4280}
4281
4282/* cmdtxt() and cmdlist() call each other */
4283static void cmdtxt(union node *n);
4284
4285static void
4286cmdlist(union node *np, int sep)
4287{
4288 for (; np; np = np->narg.next) {
4289 if (!sep)
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00004290 cmdputs(" ");
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004291 cmdtxt(np);
4292 if (sep && np->narg.next)
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00004293 cmdputs(" ");
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004294 }
4295}
4296
4297static void
4298cmdtxt(union node *n)
4299{
4300 union node *np;
4301 struct nodelist *lp;
4302 const char *p;
4303 char s[2];
4304
4305 if (!n)
4306 return;
4307 switch (n->type) {
4308 default:
4309#if DEBUG
4310 abort();
4311#endif
4312 case NPIPE:
4313 lp = n->npipe.cmdlist;
4314 for (;;) {
4315 cmdtxt(lp->n);
4316 lp = lp->next;
4317 if (!lp)
4318 break;
4319 cmdputs(" | ");
4320 }
4321 break;
4322 case NSEMI:
4323 p = "; ";
4324 goto binop;
4325 case NAND:
4326 p = " && ";
4327 goto binop;
4328 case NOR:
4329 p = " || ";
4330 binop:
4331 cmdtxt(n->nbinary.ch1);
4332 cmdputs(p);
4333 n = n->nbinary.ch2;
4334 goto donode;
4335 case NREDIR:
4336 case NBACKGND:
4337 n = n->nredir.n;
4338 goto donode;
4339 case NNOT:
4340 cmdputs("!");
4341 n = n->nnot.com;
4342 donode:
4343 cmdtxt(n);
4344 break;
4345 case NIF:
4346 cmdputs("if ");
4347 cmdtxt(n->nif.test);
4348 cmdputs("; then ");
4349 n = n->nif.ifpart;
4350 if (n->nif.elsepart) {
4351 cmdtxt(n);
4352 cmdputs("; else ");
4353 n = n->nif.elsepart;
4354 }
4355 p = "; fi";
4356 goto dotail;
4357 case NSUBSHELL:
4358 cmdputs("(");
4359 n = n->nredir.n;
4360 p = ")";
4361 goto dotail;
4362 case NWHILE:
4363 p = "while ";
4364 goto until;
4365 case NUNTIL:
4366 p = "until ";
4367 until:
4368 cmdputs(p);
4369 cmdtxt(n->nbinary.ch1);
4370 n = n->nbinary.ch2;
4371 p = "; done";
4372 dodo:
4373 cmdputs("; do ");
4374 dotail:
4375 cmdtxt(n);
4376 goto dotail2;
4377 case NFOR:
4378 cmdputs("for ");
4379 cmdputs(n->nfor.var);
4380 cmdputs(" in ");
4381 cmdlist(n->nfor.args, 1);
4382 n = n->nfor.body;
4383 p = "; done";
4384 goto dodo;
4385 case NDEFUN:
4386 cmdputs(n->narg.text);
4387 p = "() { ... }";
4388 goto dotail2;
4389 case NCMD:
4390 cmdlist(n->ncmd.args, 1);
4391 cmdlist(n->ncmd.redirect, 0);
4392 break;
4393 case NARG:
4394 p = n->narg.text;
4395 dotail2:
4396 cmdputs(p);
4397 break;
4398 case NHERE:
4399 case NXHERE:
4400 p = "<<...";
4401 goto dotail2;
4402 case NCASE:
4403 cmdputs("case ");
4404 cmdputs(n->ncase.expr->narg.text);
4405 cmdputs(" in ");
4406 for (np = n->ncase.cases; np; np = np->nclist.next) {
4407 cmdtxt(np->nclist.pattern);
4408 cmdputs(") ");
4409 cmdtxt(np->nclist.body);
4410 cmdputs(";; ");
4411 }
4412 p = "esac";
4413 goto dotail2;
4414 case NTO:
4415 p = ">";
4416 goto redir;
4417 case NCLOBBER:
4418 p = ">|";
4419 goto redir;
4420 case NAPPEND:
4421 p = ">>";
4422 goto redir;
4423 case NTOFD:
4424 p = ">&";
4425 goto redir;
4426 case NFROM:
4427 p = "<";
4428 goto redir;
4429 case NFROMFD:
4430 p = "<&";
4431 goto redir;
4432 case NFROMTO:
4433 p = "<>";
4434 redir:
4435 s[0] = n->nfile.fd + '0';
4436 s[1] = '\0';
4437 cmdputs(s);
4438 cmdputs(p);
4439 if (n->type == NTOFD || n->type == NFROMFD) {
4440 s[0] = n->ndup.dupfd + '0';
4441 p = s;
4442 goto dotail2;
4443 }
4444 n = n->nfile.fname;
4445 goto donode;
4446 }
4447}
4448
4449static char *
4450commandtext(union node *n)
4451{
4452 char *name;
4453
4454 STARTSTACKSTR(cmdnextc);
4455 cmdtxt(n);
4456 name = stackblock();
4457 TRACE(("commandtext: name %p, end %p\n\t\"%s\"\n",
4458 name, cmdnextc, cmdnextc));
4459 return ckstrdup(name);
4460}
4461#endif /* JOBS */
4462
4463/*
4464 * Fork off a subshell. If we are doing job control, give the subshell its
4465 * own process group. Jp is a job structure that the job is to be added to.
4466 * N is the command that will be evaluated by the child. Both jp and n may
4467 * be NULL. The mode parameter can be one of the following:
4468 * FORK_FG - Fork off a foreground process.
4469 * FORK_BG - Fork off a background process.
4470 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
4471 * process group even if job control is on.
4472 *
4473 * When job control is turned off, background processes have their standard
4474 * input redirected to /dev/null (except for the second and later processes
4475 * in a pipeline).
4476 *
4477 * Called with interrupts off.
4478 */
4479/*
4480 * Clear traps on a fork.
4481 */
4482static void
4483clear_traps(void)
4484{
4485 char **tp;
4486
4487 for (tp = trap; tp < &trap[NSIG]; tp++) {
Denis Vlasenko991a1da2008-02-10 19:02:53 +00004488 if (*tp && **tp) { /* trap not NULL or "" (SIG_IGN) */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004489 INT_OFF;
4490 free(*tp);
4491 *tp = NULL;
4492 if (tp != &trap[0])
4493 setsignal(tp - trap);
4494 INT_ON;
4495 }
4496 }
4497}
Denis Vlasenkobdc406d2007-07-15 01:13:25 +00004498
4499/* Lives far away from here, needed for forkchild */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004500static void closescript(void);
Denis Vlasenko41770222007-10-07 18:02:52 +00004501
Denis Vlasenkobdc406d2007-07-15 01:13:25 +00004502/* Called after fork(), in child */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004503static void
Denis Vlasenko68404f12008-03-17 09:00:54 +00004504forkchild(struct job *jp, /*union node *n,*/ int mode)
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004505{
4506 int oldlvl;
4507
4508 TRACE(("Child shell %d\n", getpid()));
4509 oldlvl = shlvl;
4510 shlvl++;
4511
4512 closescript();
4513 clear_traps();
4514#if JOBS
4515 /* do job control only in root shell */
4516 jobctl = 0;
4517 if (mode != FORK_NOJOB && jp->jobctl && !oldlvl) {
4518 pid_t pgrp;
4519
4520 if (jp->nprocs == 0)
4521 pgrp = getpid();
4522 else
4523 pgrp = jp->ps[0].pid;
4524 /* This can fail because we are doing it in the parent also */
4525 (void)setpgid(0, pgrp);
4526 if (mode == FORK_FG)
4527 xtcsetpgrp(ttyfd, pgrp);
4528 setsignal(SIGTSTP);
4529 setsignal(SIGTTOU);
4530 } else
4531#endif
4532 if (mode == FORK_BG) {
4533 ignoresig(SIGINT);
4534 ignoresig(SIGQUIT);
4535 if (jp->nprocs == 0) {
4536 close(0);
4537 if (open(bb_dev_null, O_RDONLY) != 0)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00004538 ash_msg_and_raise_error("can't open %s", bb_dev_null);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004539 }
4540 }
4541 if (!oldlvl && iflag) {
4542 setsignal(SIGINT);
4543 setsignal(SIGQUIT);
4544 setsignal(SIGTERM);
4545 }
4546 for (jp = curjob; jp; jp = jp->prev_job)
4547 freejob(jp);
4548 jobless = 0;
4549}
4550
Denis Vlasenkobdc406d2007-07-15 01:13:25 +00004551/* Called after fork(), in parent */
Denis Vlasenko85c24712008-03-17 09:04:04 +00004552#if !JOBS
4553#define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
4554#endif
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004555static void
4556forkparent(struct job *jp, union node *n, int mode, pid_t pid)
4557{
4558 TRACE(("In parent shell: child = %d\n", pid));
4559 if (!jp) {
Denis Vlasenko36fc3cd2008-01-29 09:23:49 +00004560 while (jobless && dowait(DOWAIT_NONBLOCK, NULL) > 0)
4561 continue;
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004562 jobless++;
4563 return;
4564 }
4565#if JOBS
4566 if (mode != FORK_NOJOB && jp->jobctl) {
4567 int pgrp;
4568
4569 if (jp->nprocs == 0)
4570 pgrp = pid;
4571 else
4572 pgrp = jp->ps[0].pid;
4573 /* This can fail because we are doing it in the child also */
4574 setpgid(pid, pgrp);
4575 }
4576#endif
4577 if (mode == FORK_BG) {
4578 backgndpid = pid; /* set $! */
4579 set_curjob(jp, CUR_RUNNING);
4580 }
4581 if (jp) {
4582 struct procstat *ps = &jp->ps[jp->nprocs++];
4583 ps->pid = pid;
4584 ps->status = -1;
4585 ps->cmd = nullstr;
4586#if JOBS
4587 if (jobctl && n)
4588 ps->cmd = commandtext(n);
4589#endif
4590 }
4591}
4592
4593static int
4594forkshell(struct job *jp, union node *n, int mode)
4595{
4596 int pid;
4597
4598 TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
4599 pid = fork();
4600 if (pid < 0) {
4601 TRACE(("Fork failed, errno=%d", errno));
4602 if (jp)
4603 freejob(jp);
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00004604 ash_msg_and_raise_error("cannot fork");
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004605 }
4606 if (pid == 0)
Denis Vlasenko68404f12008-03-17 09:00:54 +00004607 forkchild(jp, /*n,*/ mode);
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004608 else
4609 forkparent(jp, n, mode, pid);
4610 return pid;
4611}
4612
4613/*
4614 * Wait for job to finish.
4615 *
4616 * Under job control we have the problem that while a child process is
4617 * running interrupts generated by the user are sent to the child but not
4618 * to the shell. This means that an infinite loop started by an inter-
4619 * active user may be hard to kill. With job control turned off, an
4620 * interactive user may place an interactive program inside a loop. If
4621 * the interactive program catches interrupts, the user doesn't want
4622 * these interrupts to also abort the loop. The approach we take here
4623 * is to have the shell ignore interrupt signals while waiting for a
4624 * foreground process to terminate, and then send itself an interrupt
4625 * signal if the child process was terminated by an interrupt signal.
4626 * Unfortunately, some programs want to do a bit of cleanup and then
4627 * exit on interrupt; unless these processes terminate themselves by
4628 * sending a signal to themselves (instead of calling exit) they will
4629 * confuse this approach.
4630 *
4631 * Called with interrupts off.
4632 */
4633static int
4634waitforjob(struct job *jp)
4635{
4636 int st;
4637
4638 TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
4639 while (jp->state == JOBRUNNING) {
4640 dowait(DOWAIT_BLOCK, jp);
4641 }
4642 st = getstatus(jp);
4643#if JOBS
4644 if (jp->jobctl) {
4645 xtcsetpgrp(ttyfd, rootpid);
4646 /*
4647 * This is truly gross.
4648 * If we're doing job control, then we did a TIOCSPGRP which
4649 * caused us (the shell) to no longer be in the controlling
4650 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
4651 * intuit from the subprocess exit status whether a SIGINT
4652 * occurred, and if so interrupt ourselves. Yuck. - mycroft
4653 */
Denis Vlasenko991a1da2008-02-10 19:02:53 +00004654 if (jp->sigint) /* TODO: do the same with all signals */
4655 raise(SIGINT); /* ... by raise(jp->sig) instead? */
Denis Vlasenkoa8915072007-02-23 21:10:06 +00004656 }
4657 if (jp->state == JOBDONE)
4658#endif
4659 freejob(jp);
4660 return st;
4661}
4662
4663/*
4664 * return 1 if there are stopped jobs, otherwise 0
4665 */
4666static int
4667stoppedjobs(void)
4668{
4669 struct job *jp;
4670 int retval;
4671
4672 retval = 0;
4673 if (job_warning)
4674 goto out;
4675 jp = curjob;
4676 if (jp && jp->state == JOBSTOPPED) {
4677 out2str("You have stopped jobs.\n");
4678 job_warning = 2;
4679 retval++;
4680 }
4681 out:
4682 return retval;
4683}
4684
4685
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004686/* ============ redir.c
4687 *
4688 * Code for dealing with input/output redirection.
4689 */
4690
4691#define EMPTY -2 /* marks an unused slot in redirtab */
Denis Vlasenko7d75a962007-11-22 08:16:57 +00004692#define CLOSED -3 /* marks a slot of previously-closed fd */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004693#ifndef PIPE_BUF
4694# define PIPESIZE 4096 /* amount of buffering in a pipe */
4695#else
4696# define PIPESIZE PIPE_BUF
4697#endif
4698
4699/*
4700 * Open a file in noclobber mode.
4701 * The code was copied from bash.
4702 */
4703static int
4704noclobberopen(const char *fname)
4705{
4706 int r, fd;
4707 struct stat finfo, finfo2;
4708
4709 /*
4710 * If the file exists and is a regular file, return an error
4711 * immediately.
4712 */
4713 r = stat(fname, &finfo);
4714 if (r == 0 && S_ISREG(finfo.st_mode)) {
4715 errno = EEXIST;
4716 return -1;
4717 }
4718
4719 /*
4720 * If the file was not present (r != 0), make sure we open it
4721 * exclusively so that if it is created before we open it, our open
4722 * will fail. Make sure that we do not truncate an existing file.
4723 * Note that we don't turn on O_EXCL unless the stat failed -- if the
4724 * file was not a regular file, we leave O_EXCL off.
4725 */
4726 if (r != 0)
4727 return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
4728 fd = open(fname, O_WRONLY|O_CREAT, 0666);
4729
4730 /* If the open failed, return the file descriptor right away. */
4731 if (fd < 0)
4732 return fd;
4733
4734 /*
4735 * OK, the open succeeded, but the file may have been changed from a
4736 * non-regular file to a regular file between the stat and the open.
4737 * We are assuming that the O_EXCL open handles the case where FILENAME
4738 * did not exist and is symlinked to an existing file between the stat
4739 * and open.
4740 */
4741
4742 /*
4743 * If we can open it and fstat the file descriptor, and neither check
4744 * revealed that it was a regular file, and the file has not been
4745 * replaced, return the file descriptor.
4746 */
4747 if (fstat(fd, &finfo2) == 0 && !S_ISREG(finfo2.st_mode)
4748 && finfo.st_dev == finfo2.st_dev && finfo.st_ino == finfo2.st_ino)
4749 return fd;
4750
4751 /* The file has been replaced. badness. */
4752 close(fd);
4753 errno = EEXIST;
4754 return -1;
4755}
4756
4757/*
4758 * Handle here documents. Normally we fork off a process to write the
4759 * data to a pipe. If the document is short, we can stuff the data in
4760 * the pipe without forking.
4761 */
4762/* openhere needs this forward reference */
4763static void expandhere(union node *arg, int fd);
4764static int
4765openhere(union node *redir)
4766{
4767 int pip[2];
4768 size_t len = 0;
4769
4770 if (pipe(pip) < 0)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00004771 ash_msg_and_raise_error("pipe call failed");
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004772 if (redir->type == NHERE) {
4773 len = strlen(redir->nhere.doc->narg.text);
4774 if (len <= PIPESIZE) {
4775 full_write(pip[1], redir->nhere.doc->narg.text, len);
4776 goto out;
4777 }
4778 }
4779 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
4780 close(pip[0]);
4781 signal(SIGINT, SIG_IGN);
4782 signal(SIGQUIT, SIG_IGN);
4783 signal(SIGHUP, SIG_IGN);
4784#ifdef SIGTSTP
4785 signal(SIGTSTP, SIG_IGN);
4786#endif
4787 signal(SIGPIPE, SIG_DFL);
4788 if (redir->type == NHERE)
4789 full_write(pip[1], redir->nhere.doc->narg.text, len);
4790 else
4791 expandhere(redir->nhere.doc, pip[1]);
4792 _exit(0);
4793 }
4794 out:
4795 close(pip[1]);
4796 return pip[0];
4797}
4798
4799static int
4800openredirect(union node *redir)
4801{
4802 char *fname;
4803 int f;
4804
4805 switch (redir->nfile.type) {
4806 case NFROM:
4807 fname = redir->nfile.expfname;
4808 f = open(fname, O_RDONLY);
4809 if (f < 0)
4810 goto eopen;
4811 break;
4812 case NFROMTO:
4813 fname = redir->nfile.expfname;
4814 f = open(fname, O_RDWR|O_CREAT|O_TRUNC, 0666);
4815 if (f < 0)
4816 goto ecreate;
4817 break;
4818 case NTO:
4819 /* Take care of noclobber mode. */
4820 if (Cflag) {
4821 fname = redir->nfile.expfname;
4822 f = noclobberopen(fname);
4823 if (f < 0)
4824 goto ecreate;
4825 break;
4826 }
4827 /* FALLTHROUGH */
4828 case NCLOBBER:
4829 fname = redir->nfile.expfname;
4830 f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
4831 if (f < 0)
4832 goto ecreate;
4833 break;
4834 case NAPPEND:
4835 fname = redir->nfile.expfname;
4836 f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
4837 if (f < 0)
4838 goto ecreate;
4839 break;
4840 default:
4841#if DEBUG
4842 abort();
4843#endif
4844 /* Fall through to eliminate warning. */
4845 case NTOFD:
4846 case NFROMFD:
4847 f = -1;
4848 break;
4849 case NHERE:
4850 case NXHERE:
4851 f = openhere(redir);
4852 break;
4853 }
4854
4855 return f;
4856 ecreate:
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00004857 ash_msg_and_raise_error("cannot create %s: %s", fname, errmsg(errno, "nonexistent directory"));
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004858 eopen:
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00004859 ash_msg_and_raise_error("cannot open %s: %s", fname, errmsg(errno, "no such file"));
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004860}
4861
4862/*
4863 * Copy a file descriptor to be >= to. Returns -1
4864 * if the source file descriptor is closed, EMPTY if there are no unused
4865 * file descriptors left.
4866 */
4867static int
4868copyfd(int from, int to)
4869{
4870 int newfd;
4871
4872 newfd = fcntl(from, F_DUPFD, to);
4873 if (newfd < 0) {
4874 if (errno == EMFILE)
4875 return EMPTY;
4876 ash_msg_and_raise_error("%d: %m", from);
4877 }
4878 return newfd;
4879}
4880
4881static void
4882dupredirect(union node *redir, int f)
4883{
4884 int fd = redir->nfile.fd;
4885
4886 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
4887 if (redir->ndup.dupfd >= 0) { /* if not ">&-" */
4888 copyfd(redir->ndup.dupfd, fd);
4889 }
4890 return;
4891 }
4892
4893 if (f != fd) {
4894 copyfd(f, fd);
4895 close(f);
4896 }
4897}
4898
4899/*
4900 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
4901 * old file descriptors are stashed away so that the redirection can be
4902 * undone by calling popredir. If the REDIR_BACKQ flag is set, then the
4903 * standard output, and the standard error if it becomes a duplicate of
4904 * stdout, is saved in memory.
4905 */
4906/* flags passed to redirect */
4907#define REDIR_PUSH 01 /* save previous values of file descriptors */
4908#define REDIR_SAVEFD2 03 /* set preverrout */
4909static void
4910redirect(union node *redir, int flags)
4911{
4912 union node *n;
4913 struct redirtab *sv;
4914 int i;
4915 int fd;
4916 int newfd;
Denis Vlasenko7d75a962007-11-22 08:16:57 +00004917
Denis Vlasenko01631112007-12-16 17:20:38 +00004918 g_nullredirs++;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004919 if (!redir) {
4920 return;
4921 }
4922 sv = NULL;
4923 INT_OFF;
4924 if (flags & REDIR_PUSH) {
Denis Vlasenko7d75a962007-11-22 08:16:57 +00004925 sv = ckmalloc(sizeof(*sv));
4926 sv->next = redirlist;
4927 redirlist = sv;
Denis Vlasenko01631112007-12-16 17:20:38 +00004928 sv->nullredirs = g_nullredirs - 1;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004929 for (i = 0; i < 10; i++)
Denis Vlasenko7d75a962007-11-22 08:16:57 +00004930 sv->renamed[i] = EMPTY;
Denis Vlasenko01631112007-12-16 17:20:38 +00004931 g_nullredirs = 0;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004932 }
4933 n = redir;
4934 do {
4935 fd = n->nfile.fd;
4936 if ((n->nfile.type == NTOFD || n->nfile.type == NFROMFD)
4937 && n->ndup.dupfd == fd)
4938 continue; /* redirect from/to same file descriptor */
4939
4940 newfd = openredirect(n);
Denis Vlasenko7d75a962007-11-22 08:16:57 +00004941 if (fd == newfd) {
4942 /* Descriptor wasn't open before redirect.
4943 * Mark it for close in the future */
4944 if (sv && sv->renamed[fd] == EMPTY)
4945 sv->renamed[fd] = CLOSED;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004946 continue;
Denis Vlasenko7d75a962007-11-22 08:16:57 +00004947 }
4948 if (sv && sv->renamed[fd] == EMPTY) {
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004949 i = fcntl(fd, F_DUPFD, 10);
4950
4951 if (i == -1) {
4952 i = errno;
4953 if (i != EBADF) {
4954 close(newfd);
4955 errno = i;
4956 ash_msg_and_raise_error("%d: %m", fd);
4957 /* NOTREACHED */
4958 }
4959 } else {
Denis Vlasenko7d75a962007-11-22 08:16:57 +00004960 sv->renamed[fd] = i;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004961 close(fd);
4962 }
4963 } else {
4964 close(fd);
4965 }
4966 dupredirect(n, newfd);
4967 } while ((n = n->nfile.next));
4968 INT_ON;
Denis Vlasenko7d75a962007-11-22 08:16:57 +00004969 if ((flags & REDIR_SAVEFD2) && sv && sv->renamed[2] >= 0)
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004970 preverrout_fd = sv->renamed[2];
4971}
4972
4973/*
4974 * Undo the effects of the last redirection.
4975 */
4976static void
4977popredir(int drop)
4978{
4979 struct redirtab *rp;
4980 int i;
4981
Denis Vlasenko01631112007-12-16 17:20:38 +00004982 if (--g_nullredirs >= 0)
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004983 return;
4984 INT_OFF;
4985 rp = redirlist;
4986 for (i = 0; i < 10; i++) {
Denis Vlasenko7d75a962007-11-22 08:16:57 +00004987 if (rp->renamed[i] == CLOSED) {
4988 if (!drop)
4989 close(i);
4990 continue;
4991 }
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00004992 if (rp->renamed[i] != EMPTY) {
4993 if (!drop) {
4994 close(i);
4995 copyfd(rp->renamed[i], i);
4996 }
4997 close(rp->renamed[i]);
4998 }
4999 }
5000 redirlist = rp->next;
Denis Vlasenko01631112007-12-16 17:20:38 +00005001 g_nullredirs = rp->nullredirs;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005002 free(rp);
5003 INT_ON;
5004}
5005
5006/*
5007 * Undo all redirections. Called on error or interrupt.
5008 */
5009
5010/*
5011 * Discard all saved file descriptors.
5012 */
5013static void
5014clearredir(int drop)
5015{
5016 for (;;) {
Denis Vlasenko01631112007-12-16 17:20:38 +00005017 g_nullredirs = 0;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00005018 if (!redirlist)
5019 break;
5020 popredir(drop);
5021 }
5022}
5023
5024static int
5025redirectsafe(union node *redir, int flags)
5026{
5027 int err;
5028 volatile int saveint;
5029 struct jmploc *volatile savehandler = exception_handler;
5030 struct jmploc jmploc;
5031
5032 SAVE_INT(saveint);
5033 err = setjmp(jmploc.loc) * 2;
5034 if (!err) {
5035 exception_handler = &jmploc;
5036 redirect(redir, flags);
5037 }
5038 exception_handler = savehandler;
5039 if (err && exception != EXERROR)
5040 longjmp(exception_handler->loc, 1);
5041 RESTORE_INT(saveint);
5042 return err;
5043}
5044
5045
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005046/* ============ Routines to expand arguments to commands
5047 *
5048 * We have to deal with backquotes, shell variables, and file metacharacters.
5049 */
5050
5051/*
5052 * expandarg flags
5053 */
5054#define EXP_FULL 0x1 /* perform word splitting & file globbing */
5055#define EXP_TILDE 0x2 /* do normal tilde expansion */
5056#define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
5057#define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
5058#define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
5059#define EXP_RECORD 0x20 /* need to record arguments for ifs breakup */
5060#define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
5061#define EXP_WORD 0x80 /* expand word in parameter expansion */
5062#define EXP_QWORD 0x100 /* expand word in quoted parameter expansion */
5063/*
5064 * _rmescape() flags
5065 */
5066#define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
5067#define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
5068#define RMESCAPE_QUOTED 0x4 /* Remove CTLESC unless in quotes */
5069#define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
5070#define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
5071
5072/*
5073 * Structure specifying which parts of the string should be searched
5074 * for IFS characters.
5075 */
5076struct ifsregion {
5077 struct ifsregion *next; /* next region in list */
5078 int begoff; /* offset of start of region */
5079 int endoff; /* offset of end of region */
5080 int nulonly; /* search for nul bytes only */
5081};
5082
5083struct arglist {
5084 struct strlist *list;
5085 struct strlist **lastp;
5086};
5087
5088/* output of current string */
5089static char *expdest;
5090/* list of back quote expressions */
5091static struct nodelist *argbackq;
5092/* first struct in list of ifs regions */
5093static struct ifsregion ifsfirst;
5094/* last struct in list */
5095static struct ifsregion *ifslastp;
5096/* holds expanded arg list */
5097static struct arglist exparg;
5098
5099/*
5100 * Our own itoa().
5101 */
5102static int
5103cvtnum(arith_t num)
5104{
5105 int len;
5106
5107 expdest = makestrspace(32, expdest);
5108#if ENABLE_ASH_MATH_SUPPORT_64
5109 len = fmtstr(expdest, 32, "%lld", (long long) num);
5110#else
5111 len = fmtstr(expdest, 32, "%ld", num);
5112#endif
5113 STADJUST(len, expdest);
5114 return len;
5115}
5116
5117static size_t
5118esclen(const char *start, const char *p)
5119{
5120 size_t esc = 0;
5121
5122 while (p > start && *--p == CTLESC) {
5123 esc++;
5124 }
5125 return esc;
5126}
5127
5128/*
5129 * Remove any CTLESC characters from a string.
5130 */
5131static char *
5132_rmescapes(char *str, int flag)
5133{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00005134 static const char qchars[] ALIGN1 = { CTLESC, CTLQUOTEMARK, '\0' };
Denis Vlasenkof20de5b2007-04-29 23:42:54 +00005135
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005136 char *p, *q, *r;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005137 unsigned inquotes;
5138 int notescaped;
5139 int globbing;
5140
5141 p = strpbrk(str, qchars);
5142 if (!p) {
5143 return str;
5144 }
5145 q = p;
5146 r = str;
5147 if (flag & RMESCAPE_ALLOC) {
5148 size_t len = p - str;
5149 size_t fulllen = len + strlen(p) + 1;
5150
5151 if (flag & RMESCAPE_GROW) {
5152 r = makestrspace(fulllen, expdest);
5153 } else if (flag & RMESCAPE_HEAP) {
5154 r = ckmalloc(fulllen);
5155 } else {
5156 r = stalloc(fulllen);
5157 }
5158 q = r;
5159 if (len > 0) {
5160 q = memcpy(q, str, len) + len;
5161 }
5162 }
5163 inquotes = (flag & RMESCAPE_QUOTED) ^ RMESCAPE_QUOTED;
5164 globbing = flag & RMESCAPE_GLOB;
5165 notescaped = globbing;
5166 while (*p) {
5167 if (*p == CTLQUOTEMARK) {
5168 inquotes = ~inquotes;
5169 p++;
5170 notescaped = globbing;
5171 continue;
5172 }
5173 if (*p == '\\') {
5174 /* naked back slash */
5175 notescaped = 0;
5176 goto copy;
5177 }
5178 if (*p == CTLESC) {
5179 p++;
5180 if (notescaped && inquotes && *p != '/') {
5181 *q++ = '\\';
5182 }
5183 }
5184 notescaped = globbing;
5185 copy:
5186 *q++ = *p++;
5187 }
5188 *q = '\0';
5189 if (flag & RMESCAPE_GROW) {
5190 expdest = r;
5191 STADJUST(q - r + 1, expdest);
5192 }
5193 return r;
5194}
5195#define rmescapes(p) _rmescapes((p), 0)
5196
5197#define pmatch(a, b) !fnmatch((a), (b), 0)
5198
5199/*
5200 * Prepare a pattern for a expmeta (internal glob(3)) call.
5201 *
5202 * Returns an stalloced string.
5203 */
5204static char *
5205preglob(const char *pattern, int quoted, int flag)
5206{
5207 flag |= RMESCAPE_GLOB;
5208 if (quoted) {
5209 flag |= RMESCAPE_QUOTED;
5210 }
5211 return _rmescapes((char *)pattern, flag);
5212}
5213
5214/*
5215 * Put a string on the stack.
5216 */
5217static void
5218memtodest(const char *p, size_t len, int syntax, int quotes)
5219{
5220 char *q = expdest;
5221
5222 q = makestrspace(len * 2, q);
5223
5224 while (len--) {
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00005225 int c = signed_char2int(*p++);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005226 if (!c)
5227 continue;
5228 if (quotes && (SIT(c, syntax) == CCTL || SIT(c, syntax) == CBACK))
5229 USTPUTC(CTLESC, q);
5230 USTPUTC(c, q);
5231 }
5232
5233 expdest = q;
5234}
5235
5236static void
5237strtodest(const char *p, int syntax, int quotes)
5238{
5239 memtodest(p, strlen(p), syntax, quotes);
5240}
5241
5242/*
5243 * Record the fact that we have to scan this region of the
5244 * string for IFS characters.
5245 */
5246static void
5247recordregion(int start, int end, int nulonly)
5248{
5249 struct ifsregion *ifsp;
5250
5251 if (ifslastp == NULL) {
5252 ifsp = &ifsfirst;
5253 } else {
5254 INT_OFF;
Denis Vlasenko597906c2008-02-20 16:38:54 +00005255 ifsp = ckzalloc(sizeof(*ifsp));
5256 /*ifsp->next = NULL; - ckzalloc did it */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005257 ifslastp->next = ifsp;
5258 INT_ON;
5259 }
5260 ifslastp = ifsp;
5261 ifslastp->begoff = start;
5262 ifslastp->endoff = end;
5263 ifslastp->nulonly = nulonly;
5264}
5265
5266static void
5267removerecordregions(int endoff)
5268{
5269 if (ifslastp == NULL)
5270 return;
5271
5272 if (ifsfirst.endoff > endoff) {
5273 while (ifsfirst.next != NULL) {
5274 struct ifsregion *ifsp;
5275 INT_OFF;
5276 ifsp = ifsfirst.next->next;
5277 free(ifsfirst.next);
5278 ifsfirst.next = ifsp;
5279 INT_ON;
5280 }
5281 if (ifsfirst.begoff > endoff)
5282 ifslastp = NULL;
5283 else {
5284 ifslastp = &ifsfirst;
5285 ifsfirst.endoff = endoff;
5286 }
5287 return;
5288 }
5289
5290 ifslastp = &ifsfirst;
5291 while (ifslastp->next && ifslastp->next->begoff < endoff)
5292 ifslastp=ifslastp->next;
5293 while (ifslastp->next != NULL) {
5294 struct ifsregion *ifsp;
5295 INT_OFF;
5296 ifsp = ifslastp->next->next;
5297 free(ifslastp->next);
5298 ifslastp->next = ifsp;
5299 INT_ON;
5300 }
5301 if (ifslastp->endoff > endoff)
5302 ifslastp->endoff = endoff;
5303}
5304
5305static char *
5306exptilde(char *startp, char *p, int flag)
5307{
5308 char c;
5309 char *name;
5310 struct passwd *pw;
5311 const char *home;
5312 int quotes = flag & (EXP_FULL | EXP_CASE);
5313 int startloc;
5314
5315 name = p + 1;
5316
5317 while ((c = *++p) != '\0') {
5318 switch (c) {
5319 case CTLESC:
5320 return startp;
5321 case CTLQUOTEMARK:
5322 return startp;
5323 case ':':
5324 if (flag & EXP_VARTILDE)
5325 goto done;
5326 break;
5327 case '/':
5328 case CTLENDVAR:
5329 goto done;
5330 }
5331 }
5332 done:
5333 *p = '\0';
5334 if (*name == '\0') {
5335 home = lookupvar(homestr);
5336 } else {
5337 pw = getpwnam(name);
5338 if (pw == NULL)
5339 goto lose;
5340 home = pw->pw_dir;
5341 }
5342 if (!home || !*home)
5343 goto lose;
5344 *p = c;
5345 startloc = expdest - (char *)stackblock();
5346 strtodest(home, SQSYNTAX, quotes);
5347 recordregion(startloc, expdest - (char *)stackblock(), 0);
5348 return p;
5349 lose:
5350 *p = c;
5351 return startp;
5352}
5353
5354/*
5355 * Execute a command inside back quotes. If it's a builtin command, we
5356 * want to save its output in a block obtained from malloc. Otherwise
5357 * we fork off a subprocess and get the output of the command via a pipe.
5358 * Should be called with interrupts off.
5359 */
5360struct backcmd { /* result of evalbackcmd */
5361 int fd; /* file descriptor to read from */
5362 char *buf; /* buffer */
5363 int nleft; /* number of chars in buffer */
5364 struct job *jp; /* job structure for command */
5365};
5366
5367/* These forward decls are needed to use "eval" code for backticks handling: */
5368static int back_exitstatus; /* exit status of backquoted command */
5369#define EV_EXIT 01 /* exit after evaluating tree */
5370static void evaltree(union node *, int);
5371
5372static void
5373evalbackcmd(union node *n, struct backcmd *result)
5374{
5375 int saveherefd;
5376
5377 result->fd = -1;
5378 result->buf = NULL;
5379 result->nleft = 0;
5380 result->jp = NULL;
5381 if (n == NULL) {
5382 goto out;
5383 }
5384
5385 saveherefd = herefd;
5386 herefd = -1;
5387
5388 {
5389 int pip[2];
5390 struct job *jp;
5391
5392 if (pipe(pip) < 0)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00005393 ash_msg_and_raise_error("pipe call failed");
Denis Vlasenko68404f12008-03-17 09:00:54 +00005394 jp = makejob(/*n,*/ 1);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005395 if (forkshell(jp, n, FORK_NOJOB) == 0) {
5396 FORCE_INT_ON;
5397 close(pip[0]);
5398 if (pip[1] != 1) {
5399 close(1);
5400 copyfd(pip[1], 1);
5401 close(pip[1]);
5402 }
5403 eflag = 0;
5404 evaltree(n, EV_EXIT); /* actually evaltreenr... */
5405 /* NOTREACHED */
5406 }
5407 close(pip[1]);
5408 result->fd = pip[0];
5409 result->jp = jp;
5410 }
5411 herefd = saveherefd;
5412 out:
5413 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
5414 result->fd, result->buf, result->nleft, result->jp));
5415}
5416
5417/*
5418 * Expand stuff in backwards quotes.
5419 */
5420static void
5421expbackq(union node *cmd, int quoted, int quotes)
5422{
5423 struct backcmd in;
5424 int i;
5425 char buf[128];
5426 char *p;
5427 char *dest;
5428 int startloc;
5429 int syntax = quoted? DQSYNTAX : BASESYNTAX;
5430 struct stackmark smark;
5431
5432 INT_OFF;
5433 setstackmark(&smark);
5434 dest = expdest;
5435 startloc = dest - (char *)stackblock();
5436 grabstackstr(dest);
5437 evalbackcmd(cmd, &in);
5438 popstackmark(&smark);
5439
5440 p = in.buf;
5441 i = in.nleft;
5442 if (i == 0)
5443 goto read;
5444 for (;;) {
5445 memtodest(p, i, syntax, quotes);
5446 read:
5447 if (in.fd < 0)
5448 break;
Denis Vlasenkoe376d452008-02-20 22:23:24 +00005449 i = nonblock_safe_read(in.fd, buf, sizeof(buf));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005450 TRACE(("expbackq: read returns %d\n", i));
5451 if (i <= 0)
5452 break;
5453 p = buf;
5454 }
5455
Denis Vlasenko60818682007-09-28 22:07:23 +00005456 free(in.buf);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005457 if (in.fd >= 0) {
5458 close(in.fd);
5459 back_exitstatus = waitforjob(in.jp);
5460 }
5461 INT_ON;
5462
5463 /* Eat all trailing newlines */
5464 dest = expdest;
5465 for (; dest > (char *)stackblock() && dest[-1] == '\n';)
5466 STUNPUTC(dest);
5467 expdest = dest;
5468
5469 if (quoted == 0)
5470 recordregion(startloc, dest - (char *)stackblock(), 0);
5471 TRACE(("evalbackq: size=%d: \"%.*s\"\n",
5472 (dest - (char *)stackblock()) - startloc,
5473 (dest - (char *)stackblock()) - startloc,
5474 stackblock() + startloc));
5475}
5476
5477#if ENABLE_ASH_MATH_SUPPORT
5478/*
5479 * Expand arithmetic expression. Backup to start of expression,
5480 * evaluate, place result in (backed up) result, adjust string position.
5481 */
5482static void
5483expari(int quotes)
5484{
5485 char *p, *start;
5486 int begoff;
5487 int flag;
5488 int len;
5489
5490 /* ifsfree(); */
5491
5492 /*
5493 * This routine is slightly over-complicated for
5494 * efficiency. Next we scan backwards looking for the
5495 * start of arithmetic.
5496 */
5497 start = stackblock();
5498 p = expdest - 1;
5499 *p = '\0';
5500 p--;
5501 do {
5502 int esc;
5503
5504 while (*p != CTLARI) {
5505 p--;
5506#if DEBUG
5507 if (p < start) {
5508 ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
5509 }
5510#endif
5511 }
5512
5513 esc = esclen(start, p);
5514 if (!(esc % 2)) {
5515 break;
5516 }
5517
5518 p -= esc + 1;
5519 } while (1);
5520
5521 begoff = p - start;
5522
5523 removerecordregions(begoff);
5524
5525 flag = p[1];
5526
5527 expdest = p;
5528
5529 if (quotes)
5530 rmescapes(p + 2);
5531
5532 len = cvtnum(dash_arith(p + 2));
5533
5534 if (flag != '"')
5535 recordregion(begoff, begoff + len, 0);
5536}
5537#endif
5538
5539/* argstr needs it */
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00005540static char *evalvar(char *p, int flag, struct strlist *var_str_list);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005541
5542/*
5543 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
5544 * characters to allow for further processing. Otherwise treat
5545 * $@ like $* since no splitting will be performed.
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00005546 *
5547 * var_str_list (can be NULL) is a list of "VAR=val" strings which take precedence
5548 * over shell varables. Needed for "A=a B=$A; echo $B" case - we use it
5549 * for correct expansion of "B=$A" word.
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005550 */
5551static void
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00005552argstr(char *p, int flag, struct strlist *var_str_list)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005553{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00005554 static const char spclchars[] ALIGN1 = {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005555 '=',
5556 ':',
5557 CTLQUOTEMARK,
5558 CTLENDVAR,
5559 CTLESC,
5560 CTLVAR,
5561 CTLBACKQ,
5562 CTLBACKQ | CTLQUOTE,
5563#if ENABLE_ASH_MATH_SUPPORT
5564 CTLENDARI,
5565#endif
5566 0
5567 };
5568 const char *reject = spclchars;
5569 int c;
5570 int quotes = flag & (EXP_FULL | EXP_CASE); /* do CTLESC */
5571 int breakall = flag & EXP_WORD;
5572 int inquotes;
5573 size_t length;
5574 int startloc;
5575
5576 if (!(flag & EXP_VARTILDE)) {
5577 reject += 2;
5578 } else if (flag & EXP_VARTILDE2) {
5579 reject++;
5580 }
5581 inquotes = 0;
5582 length = 0;
5583 if (flag & EXP_TILDE) {
5584 char *q;
5585
5586 flag &= ~EXP_TILDE;
5587 tilde:
5588 q = p;
5589 if (*q == CTLESC && (flag & EXP_QWORD))
5590 q++;
5591 if (*q == '~')
5592 p = exptilde(p, q, flag);
5593 }
5594 start:
5595 startloc = expdest - (char *)stackblock();
5596 for (;;) {
5597 length += strcspn(p + length, reject);
5598 c = p[length];
5599 if (c && (!(c & 0x80)
5600#if ENABLE_ASH_MATH_SUPPORT
5601 || c == CTLENDARI
5602#endif
5603 )) {
5604 /* c == '=' || c == ':' || c == CTLENDARI */
5605 length++;
5606 }
5607 if (length > 0) {
5608 int newloc;
5609 expdest = stack_nputstr(p, length, expdest);
5610 newloc = expdest - (char *)stackblock();
5611 if (breakall && !inquotes && newloc > startloc) {
5612 recordregion(startloc, newloc, 0);
5613 }
5614 startloc = newloc;
5615 }
5616 p += length + 1;
5617 length = 0;
5618
5619 switch (c) {
5620 case '\0':
5621 goto breakloop;
5622 case '=':
5623 if (flag & EXP_VARTILDE2) {
5624 p--;
5625 continue;
5626 }
5627 flag |= EXP_VARTILDE2;
5628 reject++;
5629 /* fall through */
5630 case ':':
5631 /*
5632 * sort of a hack - expand tildes in variable
5633 * assignments (after the first '=' and after ':'s).
5634 */
5635 if (*--p == '~') {
5636 goto tilde;
5637 }
5638 continue;
5639 }
5640
5641 switch (c) {
5642 case CTLENDVAR: /* ??? */
5643 goto breakloop;
5644 case CTLQUOTEMARK:
5645 /* "$@" syntax adherence hack */
5646 if (
5647 !inquotes &&
5648 !memcmp(p, dolatstr, 4) &&
5649 (p[4] == CTLQUOTEMARK || (
5650 p[4] == CTLENDVAR &&
5651 p[5] == CTLQUOTEMARK
5652 ))
5653 ) {
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00005654 p = evalvar(p + 1, flag, /* var_str_list: */ NULL) + 1;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005655 goto start;
5656 }
5657 inquotes = !inquotes;
5658 addquote:
5659 if (quotes) {
5660 p--;
5661 length++;
5662 startloc++;
5663 }
5664 break;
5665 case CTLESC:
5666 startloc++;
5667 length++;
5668 goto addquote;
5669 case CTLVAR:
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00005670 p = evalvar(p, flag, var_str_list);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005671 goto start;
5672 case CTLBACKQ:
5673 c = 0;
5674 case CTLBACKQ|CTLQUOTE:
5675 expbackq(argbackq->n, c, quotes);
5676 argbackq = argbackq->next;
5677 goto start;
5678#if ENABLE_ASH_MATH_SUPPORT
5679 case CTLENDARI:
5680 p--;
5681 expari(quotes);
5682 goto start;
5683#endif
5684 }
5685 }
5686 breakloop:
5687 ;
5688}
5689
5690static char *
Denis Vlasenko68404f12008-03-17 09:00:54 +00005691scanleft(char *startp, char *rmesc, char *rmescend ATTRIBUTE_UNUSED, char *str, int quotes,
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005692 int zero)
5693{
Denis Vlasenko92e13c22008-03-25 01:17:40 +00005694 char *loc, *loc2, *full;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005695 char c;
5696
5697 loc = startp;
5698 loc2 = rmesc;
5699 do {
Denis Vlasenko92e13c22008-03-25 01:17:40 +00005700 int match = strlen(str);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005701 const char *s = loc2;
Denis Vlasenko92e13c22008-03-25 01:17:40 +00005702
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005703 c = *loc2;
5704 if (zero) {
5705 *loc2 = '\0';
5706 s = rmesc;
5707 }
Denis Vlasenko92e13c22008-03-25 01:17:40 +00005708
5709 // chop off end if its '*'
5710 full = strrchr(str, '*');
5711 if (full && full != str)
5712 match--;
5713
5714 // If str starts with '*' replace with s.
5715 if ((*str == '*') && strlen(s) >= match) {
5716 full = xstrdup(s);
5717 strncpy(full+strlen(s)-match+1, str+1, match-1);
5718 } else
5719 full = xstrndup(str, match);
5720 match = strncmp(s, full, strlen(full));
5721 free(full);
5722
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005723 *loc2 = c;
Denis Vlasenko92e13c22008-03-25 01:17:40 +00005724 if (!match)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005725 return loc;
5726 if (quotes && *loc == CTLESC)
5727 loc++;
5728 loc++;
5729 loc2++;
5730 } while (c);
5731 return 0;
5732}
5733
5734static char *
5735scanright(char *startp, char *rmesc, char *rmescend, char *str, int quotes,
5736 int zero)
5737{
5738 int esc = 0;
5739 char *loc;
5740 char *loc2;
5741
5742 for (loc = str - 1, loc2 = rmescend; loc >= startp; loc2--) {
5743 int match;
5744 char c = *loc2;
5745 const char *s = loc2;
5746 if (zero) {
5747 *loc2 = '\0';
5748 s = rmesc;
5749 }
5750 match = pmatch(str, s);
5751 *loc2 = c;
5752 if (match)
5753 return loc;
5754 loc--;
5755 if (quotes) {
5756 if (--esc < 0) {
5757 esc = esclen(startp, loc);
5758 }
5759 if (esc % 2) {
5760 esc--;
5761 loc--;
5762 }
5763 }
5764 }
5765 return 0;
5766}
5767
5768static void varunset(const char *, const char *, const char *, int) ATTRIBUTE_NORETURN;
5769static void
5770varunset(const char *end, const char *var, const char *umsg, int varflags)
5771{
5772 const char *msg;
5773 const char *tail;
5774
5775 tail = nullstr;
5776 msg = "parameter not set";
5777 if (umsg) {
5778 if (*end == CTLENDVAR) {
5779 if (varflags & VSNUL)
5780 tail = " or null";
5781 } else
5782 msg = umsg;
5783 }
5784 ash_msg_and_raise_error("%.*s: %s%s", end - var - 1, var, msg, tail);
5785}
5786
Denis Vlasenko92e13c22008-03-25 01:17:40 +00005787#if ENABLE_ASH_BASH_COMPAT
5788static char *
5789parse_sub_pattern(char *arg, int inquotes)
5790{
5791 char *idx, *repl = NULL;
5792 unsigned char c;
5793
5794 for (idx = arg; *arg; arg++) {
5795 if (*arg == '/') {
5796 /* Only the first '/' seen is our seperator */
5797 if (!repl) {
5798 *idx++ = '\0';
5799 repl = idx;
5800 } else
5801 *idx++ = *arg;
5802 } else if (*arg != '\\') {
5803 *idx++ = *arg;
5804 } else {
5805 if (inquotes)
5806 arg++;
5807 else {
5808 if (*(arg + 1) != '\\')
5809 goto single_backslash;
5810 arg += 2;
5811 }
5812
5813 switch (*arg) {
5814 case 'n': c = '\n'; break;
5815 case 'r': c = '\r'; break;
5816 case 't': c = '\t'; break;
5817 case 'v': c = '\v'; break;
5818 case 'f': c = '\f'; break;
5819 case 'b': c = '\b'; break;
5820 case 'a': c = '\a'; break;
5821 case '\\':
5822 if (*(arg + 1) != '\\' && !inquotes)
5823 goto single_backslash;
5824 arg++;
5825 /* FALLTHROUGH */
5826 case '\0':
5827 /* Trailing backslash, just stuff one in the buffer
5828 * and backup arg so the loop will exit.
5829 */
5830 c = '\\';
5831 if (!*arg)
5832 arg--;
5833 break;
5834 default:
5835 c = *arg;
5836 if (isdigit(c)) {
5837 /* It's an octal number, parse it. */
5838 int i;
5839 c = 0;
5840
5841 for (i = 0; *arg && i < 3; arg++, i++) {
5842 if (*arg >= '8' || *arg < '0')
5843 ash_msg_and_raise_error("Invalid octal char in pattern");
5844// TODO: number() instead? It does error checking...
5845 c = (c << 3) + atoi(arg);
5846 }
5847 /* back off one (so outer loop can do it) */
5848 arg--;
5849 }
5850 }
5851 *idx++ = c;
5852 }
5853 }
5854 *idx = *arg;
5855
5856 return repl;
5857
5858 single_backslash:
5859 ash_msg_and_raise_error("single backslash unexpected");
5860 /* NOTREACHED */
5861}
5862#endif /* ENABLE_ASH_BASH_COMPAT */
5863
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005864static const char *
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00005865subevalvar(char *p, char *str, int strloc, int subtype,
5866 int startloc, int varflags, int quotes, struct strlist *var_str_list)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005867{
Denis Vlasenko92e13c22008-03-25 01:17:40 +00005868 struct nodelist *saveargbackq = argbackq;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005869 char *startp;
5870 char *loc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005871 char *rmesc, *rmescend;
Denis Vlasenko92e13c22008-03-25 01:17:40 +00005872 USE_ASH_BASH_COMPAT(char *repl = NULL;)
5873 USE_ASH_BASH_COMPAT(char null = '\0';)
5874 USE_ASH_BASH_COMPAT(int pos, len, orig_len;)
5875 int saveherefd = herefd;
5876 int amount, workloc, resetloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005877 int zero;
Denis Vlasenko92e13c22008-03-25 01:17:40 +00005878 char *(*scan)(char*, char*, char*, char*, int, int);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005879
5880 herefd = -1;
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00005881 argstr(p, (subtype != VSASSIGN && subtype != VSQUESTION) ? EXP_CASE : 0,
5882 var_str_list);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005883 STPUTC('\0', expdest);
5884 herefd = saveherefd;
5885 argbackq = saveargbackq;
5886 startp = stackblock() + startloc;
5887
5888 switch (subtype) {
5889 case VSASSIGN:
5890 setvar(str, startp, 0);
5891 amount = startp - expdest;
5892 STADJUST(amount, expdest);
5893 return startp;
5894
Denis Vlasenko92e13c22008-03-25 01:17:40 +00005895#if ENABLE_ASH_BASH_COMPAT
5896 case VSSUBSTR:
5897 loc = str = stackblock() + strloc;
5898// TODO: number() instead? It does error checking...
5899 pos = atoi(loc);
5900 len = str - startp - 1;
5901
5902 /* *loc != '\0', guaranteed by parser */
5903 if (quotes) {
5904 char *ptr;
5905
5906 /* We must adjust the length by the number of escapes we find. */
5907 for (ptr = startp; ptr < (str - 1); ptr++) {
5908 if(*ptr == CTLESC) {
5909 len--;
5910 ptr++;
5911 }
5912 }
5913 }
5914 orig_len = len;
5915
5916 if (*loc++ == ':') {
5917// TODO: number() instead? It does error checking...
5918 len = atoi(loc);
5919 } else {
5920 len = orig_len;
5921 while (*loc && *loc != ':')
5922 loc++;
5923 if (*loc++ == ':')
5924// TODO: number() instead? It does error checking...
5925 len = atoi(loc);
5926 }
5927 if (pos >= orig_len) {
5928 pos = 0;
5929 len = 0;
5930 }
5931 if (len > (orig_len - pos))
5932 len = orig_len - pos;
5933
5934 for (str = startp; pos; str++, pos--) {
5935 if (quotes && *str == CTLESC)
5936 str++;
5937 }
5938 for (loc = startp; len; len--) {
5939 if (quotes && *str == CTLESC)
5940 *loc++ = *str++;
5941 *loc++ = *str++;
5942 }
5943 *loc = '\0';
5944 amount = loc - expdest;
5945 STADJUST(amount, expdest);
5946 return loc;
5947#endif
5948
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005949 case VSQUESTION:
5950 varunset(p, str, startp, varflags);
5951 /* NOTREACHED */
5952 }
Denis Vlasenko92e13c22008-03-25 01:17:40 +00005953 resetloc = expdest - (char *)stackblock();
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005954
Denis Vlasenko92e13c22008-03-25 01:17:40 +00005955 /* We'll comeback here if we grow the stack while handling
5956 * a VSREPLACE or VSREPLACEALL, since our pointers into the
5957 * stack will need rebasing, and we'll need to remove our work
5958 * areas each time
5959 */
5960 USE_ASH_BASH_COMPAT(restart:)
5961
5962 amount = expdest - ((char *)stackblock() + resetloc);
5963 STADJUST(-amount, expdest);
5964 startp = stackblock() + startloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005965
5966 rmesc = startp;
5967 rmescend = stackblock() + strloc;
5968 if (quotes) {
5969 rmesc = _rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
5970 if (rmesc != startp) {
5971 rmescend = expdest;
5972 startp = stackblock() + startloc;
5973 }
5974 }
5975 rmescend--;
5976 str = stackblock() + strloc;
5977 preglob(str, varflags & VSQUOTE, 0);
Denis Vlasenko92e13c22008-03-25 01:17:40 +00005978 workloc = expdest - (char *)stackblock();
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00005979
Denis Vlasenko92e13c22008-03-25 01:17:40 +00005980#if ENABLE_ASH_BASH_COMPAT
5981 if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
5982 char *idx, *end, *restart_detect;
5983
5984 if(!repl) {
5985 repl = parse_sub_pattern(str, varflags & VSQUOTE);
5986 if (!repl)
5987 repl = &null;
5988 }
5989
5990 /* If there's no pattern to match, return the expansion unmolested */
5991 if (*str == '\0')
5992 return 0;
5993
5994 len = 0;
5995 idx = startp;
5996 end = str - 1;
5997 while (idx < end) {
5998 loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
5999 if (!loc) {
6000 /* No match, advance */
6001 restart_detect = stackblock();
6002 STPUTC(*idx, expdest);
6003 if (quotes && *idx == CTLESC) {
6004 idx++;
6005 len++;
6006 STPUTC(*idx, expdest);
6007 }
6008 if (stackblock() != restart_detect)
6009 goto restart;
6010 idx++;
6011 len++;
6012 rmesc++;
6013 continue;
6014 }
6015
6016 if (subtype == VSREPLACEALL) {
6017 while (idx < loc) {
6018 if (quotes && *idx == CTLESC)
6019 idx++;
6020 idx++;
6021 rmesc++;
6022 }
6023 } else
6024 idx = loc;
6025
6026 for (loc = repl; *loc; loc++) {
6027 restart_detect = stackblock();
6028 STPUTC(*loc, expdest);
6029 if (stackblock() != restart_detect)
6030 goto restart;
6031 len++;
6032 }
6033
6034 if (subtype == VSREPLACE) {
6035 while (*idx) {
6036 restart_detect = stackblock();
6037 STPUTC(*idx, expdest);
6038 if (stackblock() != restart_detect)
6039 goto restart;
6040 len++;
6041 idx++;
6042 }
6043 break;
6044 }
6045 }
6046
6047 /* We've put the replaced text into a buffer at workloc, now
6048 * move it to the right place and adjust the stack.
6049 */
6050 startp = stackblock() + startloc;
6051 STPUTC('\0', expdest);
6052 memmove(startp, stackblock() + workloc, len);
6053 startp[len++] = '\0';
6054 amount = expdest - ((char *)stackblock() + startloc + len - 1);
6055 STADJUST(-amount, expdest);
6056 return startp;
6057 }
6058#endif /* ENABLE_ASH_BASH_COMPAT */
6059
6060 subtype -= VSTRIMRIGHT;
6061#if DEBUG
6062 if (subtype < 0 || subtype > 7)
6063 abort();
6064#endif
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006065 /* zero = subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX */
6066 zero = subtype >> 1;
6067 /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
6068 scan = (subtype & 1) ^ zero ? scanleft : scanright;
6069
6070 loc = scan(startp, rmesc, rmescend, str, quotes, zero);
6071 if (loc) {
6072 if (zero) {
6073 memmove(startp, loc, str - loc);
6074 loc = startp + (str - loc) - 1;
6075 }
6076 *loc = '\0';
6077 amount = loc - expdest;
6078 STADJUST(amount, expdest);
6079 }
6080 return loc;
6081}
6082
6083/*
6084 * Add the value of a specialized variable to the stack string.
6085 */
6086static ssize_t
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006087varvalue(char *name, int varflags, int flags, struct strlist *var_str_list)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006088{
6089 int num;
6090 char *p;
6091 int i;
6092 int sep = 0;
6093 int sepq = 0;
6094 ssize_t len = 0;
6095 char **ap;
6096 int syntax;
6097 int quoted = varflags & VSQUOTE;
6098 int subtype = varflags & VSTYPE;
6099 int quotes = flags & (EXP_FULL | EXP_CASE);
6100
6101 if (quoted && (flags & EXP_FULL))
6102 sep = 1 << CHAR_BIT;
6103
6104 syntax = quoted ? DQSYNTAX : BASESYNTAX;
6105 switch (*name) {
6106 case '$':
6107 num = rootpid;
6108 goto numvar;
6109 case '?':
6110 num = exitstatus;
6111 goto numvar;
6112 case '#':
6113 num = shellparam.nparam;
6114 goto numvar;
6115 case '!':
6116 num = backgndpid;
6117 if (num == 0)
6118 return -1;
6119 numvar:
6120 len = cvtnum(num);
6121 break;
6122 case '-':
6123 p = makestrspace(NOPTS, expdest);
6124 for (i = NOPTS - 1; i >= 0; i--) {
6125 if (optlist[i]) {
6126 USTPUTC(optletters(i), p);
6127 len++;
6128 }
6129 }
6130 expdest = p;
6131 break;
6132 case '@':
6133 if (sep)
6134 goto param;
6135 /* fall through */
6136 case '*':
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00006137 sep = ifsset() ? signed_char2int(ifsval()[0]) : ' ';
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006138 if (quotes && (SIT(sep, syntax) == CCTL || SIT(sep, syntax) == CBACK))
6139 sepq = 1;
6140 param:
6141 ap = shellparam.p;
6142 if (!ap)
6143 return -1;
6144 while ((p = *ap++)) {
6145 size_t partlen;
6146
6147 partlen = strlen(p);
6148 len += partlen;
6149
6150 if (!(subtype == VSPLUS || subtype == VSLENGTH))
6151 memtodest(p, partlen, syntax, quotes);
6152
6153 if (*ap && sep) {
6154 char *q;
6155
6156 len++;
6157 if (subtype == VSPLUS || subtype == VSLENGTH) {
6158 continue;
6159 }
6160 q = expdest;
6161 if (sepq)
6162 STPUTC(CTLESC, q);
6163 STPUTC(sep, q);
6164 expdest = q;
6165 }
6166 }
6167 return len;
6168 case '0':
6169 case '1':
6170 case '2':
6171 case '3':
6172 case '4':
6173 case '5':
6174 case '6':
6175 case '7':
6176 case '8':
6177 case '9':
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006178// TODO: number() instead? It does error checking...
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006179 num = atoi(name);
6180 if (num < 0 || num > shellparam.nparam)
6181 return -1;
6182 p = num ? shellparam.p[num - 1] : arg0;
6183 goto value;
6184 default:
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006185 /* NB: name has form "VAR=..." */
6186
6187 /* "A=a B=$A" case: var_str_list is a list of "A=a" strings
6188 * which should be considered before we check variables. */
6189 if (var_str_list) {
6190 unsigned name_len = (strchrnul(name, '=') - name) + 1;
6191 p = NULL;
6192 do {
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00006193 char *str, *eq;
6194 str = var_str_list->text;
6195 eq = strchr(str, '=');
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006196 if (!eq) /* stop at first non-assignment */
6197 break;
6198 eq++;
6199 if (name_len == (eq - str)
6200 && strncmp(str, name, name_len) == 0) {
6201 p = eq;
6202 /* goto value; - WRONG! */
6203 /* think "A=1 A=2 B=$A" */
6204 }
6205 var_str_list = var_str_list->next;
6206 } while (var_str_list);
6207 if (p)
6208 goto value;
6209 }
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006210 p = lookupvar(name);
6211 value:
6212 if (!p)
6213 return -1;
6214
6215 len = strlen(p);
6216 if (!(subtype == VSPLUS || subtype == VSLENGTH))
6217 memtodest(p, len, syntax, quotes);
6218 return len;
6219 }
6220
6221 if (subtype == VSPLUS || subtype == VSLENGTH)
6222 STADJUST(-len, expdest);
6223 return len;
6224}
6225
6226/*
6227 * Expand a variable, and return a pointer to the next character in the
6228 * input string.
6229 */
6230static char *
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006231evalvar(char *p, int flag, struct strlist *var_str_list)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006232{
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006233 char varflags;
6234 char subtype;
6235 char quoted;
6236 char easy;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006237 char *var;
6238 int patloc;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006239 int startloc;
6240 ssize_t varlen;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006241
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006242 varflags = *p++;
6243 subtype = varflags & VSTYPE;
6244 quoted = varflags & VSQUOTE;
6245 var = p;
6246 easy = (!quoted || (*var == '@' && shellparam.nparam));
6247 startloc = expdest - (char *)stackblock();
6248 p = strchr(p, '=') + 1;
6249
6250 again:
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006251 varlen = varvalue(var, varflags, flag, var_str_list);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006252 if (varflags & VSNUL)
6253 varlen--;
6254
6255 if (subtype == VSPLUS) {
6256 varlen = -1 - varlen;
6257 goto vsplus;
6258 }
6259
6260 if (subtype == VSMINUS) {
6261 vsplus:
6262 if (varlen < 0) {
6263 argstr(
6264 p, flag | EXP_TILDE |
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006265 (quoted ? EXP_QWORD : EXP_WORD),
6266 var_str_list
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006267 );
6268 goto end;
6269 }
6270 if (easy)
6271 goto record;
6272 goto end;
6273 }
6274
6275 if (subtype == VSASSIGN || subtype == VSQUESTION) {
6276 if (varlen < 0) {
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006277 if (subevalvar(p, var, /* strloc: */ 0,
6278 subtype, startloc, varflags,
6279 /* quotes: */ 0,
6280 var_str_list)
6281 ) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006282 varflags &= ~VSNUL;
6283 /*
6284 * Remove any recorded regions beyond
6285 * start of variable
6286 */
6287 removerecordregions(startloc);
6288 goto again;
6289 }
6290 goto end;
6291 }
6292 if (easy)
6293 goto record;
6294 goto end;
6295 }
6296
6297 if (varlen < 0 && uflag)
6298 varunset(p, var, 0, 0);
6299
6300 if (subtype == VSLENGTH) {
6301 cvtnum(varlen > 0 ? varlen : 0);
6302 goto record;
6303 }
6304
6305 if (subtype == VSNORMAL) {
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006306 if (easy)
6307 goto record;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006308 goto end;
6309 }
6310
6311#if DEBUG
6312 switch (subtype) {
6313 case VSTRIMLEFT:
6314 case VSTRIMLEFTMAX:
6315 case VSTRIMRIGHT:
6316 case VSTRIMRIGHTMAX:
Denis Vlasenko92e13c22008-03-25 01:17:40 +00006317#if ENABLE_ASH_BASH_COMPAT
6318 case VSSUBSTR:
6319 case VSREPLACE:
6320 case VSREPLACEALL:
6321#endif
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006322 break;
6323 default:
6324 abort();
6325 }
6326#endif
6327
6328 if (varlen >= 0) {
6329 /*
6330 * Terminate the string and start recording the pattern
6331 * right after it
6332 */
6333 STPUTC('\0', expdest);
6334 patloc = expdest - (char *)stackblock();
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006335 if (0 == subevalvar(p, /* str: */ NULL, patloc, subtype,
6336 startloc, varflags,
6337 /* quotes: */ flag & (EXP_FULL | EXP_CASE),
6338 var_str_list)
6339 ) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006340 int amount = expdest - (
6341 (char *)stackblock() + patloc - 1
6342 );
6343 STADJUST(-amount, expdest);
6344 }
6345 /* Remove any recorded regions beyond start of variable */
6346 removerecordregions(startloc);
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006347 record:
6348 recordregion(startloc, expdest - (char *)stackblock(), quoted);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006349 }
6350
6351 end:
6352 if (subtype != VSNORMAL) { /* skip to end of alternative */
6353 int nesting = 1;
6354 for (;;) {
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006355 char c = *p++;
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006356 if (c == CTLESC)
6357 p++;
6358 else if (c == CTLBACKQ || c == (CTLBACKQ|CTLQUOTE)) {
6359 if (varlen >= 0)
6360 argbackq = argbackq->next;
6361 } else if (c == CTLVAR) {
6362 if ((*p++ & VSTYPE) != VSNORMAL)
6363 nesting++;
6364 } else if (c == CTLENDVAR) {
6365 if (--nesting == 0)
6366 break;
6367 }
6368 }
6369 }
6370 return p;
6371}
6372
6373/*
6374 * Break the argument string into pieces based upon IFS and add the
6375 * strings to the argument list. The regions of the string to be
6376 * searched for IFS characters have been stored by recordregion.
6377 */
6378static void
6379ifsbreakup(char *string, struct arglist *arglist)
6380{
6381 struct ifsregion *ifsp;
6382 struct strlist *sp;
6383 char *start;
6384 char *p;
6385 char *q;
6386 const char *ifs, *realifs;
6387 int ifsspc;
6388 int nulonly;
6389
6390 start = string;
6391 if (ifslastp != NULL) {
6392 ifsspc = 0;
6393 nulonly = 0;
6394 realifs = ifsset() ? ifsval() : defifs;
6395 ifsp = &ifsfirst;
6396 do {
6397 p = string + ifsp->begoff;
6398 nulonly = ifsp->nulonly;
6399 ifs = nulonly ? nullstr : realifs;
6400 ifsspc = 0;
6401 while (p < string + ifsp->endoff) {
6402 q = p;
6403 if (*p == CTLESC)
6404 p++;
6405 if (!strchr(ifs, *p)) {
6406 p++;
6407 continue;
6408 }
6409 if (!nulonly)
6410 ifsspc = (strchr(defifs, *p) != NULL);
6411 /* Ignore IFS whitespace at start */
6412 if (q == start && ifsspc) {
6413 p++;
6414 start = p;
6415 continue;
6416 }
6417 *q = '\0';
Denis Vlasenko597906c2008-02-20 16:38:54 +00006418 sp = stzalloc(sizeof(*sp));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006419 sp->text = start;
6420 *arglist->lastp = sp;
6421 arglist->lastp = &sp->next;
6422 p++;
6423 if (!nulonly) {
6424 for (;;) {
6425 if (p >= string + ifsp->endoff) {
6426 break;
6427 }
6428 q = p;
6429 if (*p == CTLESC)
6430 p++;
6431 if (strchr(ifs, *p) == NULL ) {
6432 p = q;
6433 break;
Denis Vlasenko597906c2008-02-20 16:38:54 +00006434 }
6435 if (strchr(defifs, *p) == NULL) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006436 if (ifsspc) {
6437 p++;
6438 ifsspc = 0;
6439 } else {
6440 p = q;
6441 break;
6442 }
6443 } else
6444 p++;
6445 }
6446 }
6447 start = p;
6448 } /* while */
6449 ifsp = ifsp->next;
6450 } while (ifsp != NULL);
6451 if (nulonly)
6452 goto add;
6453 }
6454
6455 if (!*start)
6456 return;
6457
6458 add:
Denis Vlasenko597906c2008-02-20 16:38:54 +00006459 sp = stzalloc(sizeof(*sp));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006460 sp->text = start;
6461 *arglist->lastp = sp;
6462 arglist->lastp = &sp->next;
6463}
6464
6465static void
6466ifsfree(void)
6467{
6468 struct ifsregion *p;
6469
6470 INT_OFF;
6471 p = ifsfirst.next;
6472 do {
6473 struct ifsregion *ifsp;
6474 ifsp = p->next;
6475 free(p);
6476 p = ifsp;
6477 } while (p);
6478 ifslastp = NULL;
6479 ifsfirst.next = NULL;
6480 INT_ON;
6481}
6482
6483/*
6484 * Add a file name to the list.
6485 */
6486static void
6487addfname(const char *name)
6488{
6489 struct strlist *sp;
6490
Denis Vlasenko597906c2008-02-20 16:38:54 +00006491 sp = stzalloc(sizeof(*sp));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006492 sp->text = ststrdup(name);
6493 *exparg.lastp = sp;
6494 exparg.lastp = &sp->next;
6495}
6496
6497static char *expdir;
6498
6499/*
6500 * Do metacharacter (i.e. *, ?, [...]) expansion.
6501 */
6502static void
6503expmeta(char *enddir, char *name)
6504{
6505 char *p;
6506 const char *cp;
6507 char *start;
6508 char *endname;
6509 int metaflag;
6510 struct stat statb;
6511 DIR *dirp;
6512 struct dirent *dp;
6513 int atend;
6514 int matchdot;
6515
6516 metaflag = 0;
6517 start = name;
6518 for (p = name; *p; p++) {
6519 if (*p == '*' || *p == '?')
6520 metaflag = 1;
6521 else if (*p == '[') {
6522 char *q = p + 1;
6523 if (*q == '!')
6524 q++;
6525 for (;;) {
6526 if (*q == '\\')
6527 q++;
6528 if (*q == '/' || *q == '\0')
6529 break;
6530 if (*++q == ']') {
6531 metaflag = 1;
6532 break;
6533 }
6534 }
6535 } else if (*p == '\\')
6536 p++;
6537 else if (*p == '/') {
6538 if (metaflag)
6539 goto out;
6540 start = p + 1;
6541 }
6542 }
6543 out:
6544 if (metaflag == 0) { /* we've reached the end of the file name */
6545 if (enddir != expdir)
6546 metaflag++;
6547 p = name;
6548 do {
6549 if (*p == '\\')
6550 p++;
6551 *enddir++ = *p;
6552 } while (*p++);
6553 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
6554 addfname(expdir);
6555 return;
6556 }
6557 endname = p;
6558 if (name < start) {
6559 p = name;
6560 do {
6561 if (*p == '\\')
6562 p++;
6563 *enddir++ = *p++;
6564 } while (p < start);
6565 }
6566 if (enddir == expdir) {
6567 cp = ".";
6568 } else if (enddir == expdir + 1 && *expdir == '/') {
6569 cp = "/";
6570 } else {
6571 cp = expdir;
6572 enddir[-1] = '\0';
6573 }
6574 dirp = opendir(cp);
6575 if (dirp == NULL)
6576 return;
6577 if (enddir != expdir)
6578 enddir[-1] = '/';
6579 if (*endname == 0) {
6580 atend = 1;
6581 } else {
6582 atend = 0;
6583 *endname++ = '\0';
6584 }
6585 matchdot = 0;
6586 p = start;
6587 if (*p == '\\')
6588 p++;
6589 if (*p == '.')
6590 matchdot++;
Denis Vlasenko991a1da2008-02-10 19:02:53 +00006591 while (!intpending && (dp = readdir(dirp)) != NULL) {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006592 if (dp->d_name[0] == '.' && ! matchdot)
6593 continue;
6594 if (pmatch(start, dp->d_name)) {
6595 if (atend) {
6596 strcpy(enddir, dp->d_name);
6597 addfname(expdir);
6598 } else {
6599 for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
6600 continue;
6601 p[-1] = '/';
6602 expmeta(p, endname);
6603 }
6604 }
6605 }
6606 closedir(dirp);
6607 if (! atend)
6608 endname[-1] = '/';
6609}
6610
6611static struct strlist *
6612msort(struct strlist *list, int len)
6613{
6614 struct strlist *p, *q = NULL;
6615 struct strlist **lpp;
6616 int half;
6617 int n;
6618
6619 if (len <= 1)
6620 return list;
6621 half = len >> 1;
6622 p = list;
6623 for (n = half; --n >= 0; ) {
6624 q = p;
6625 p = p->next;
6626 }
6627 q->next = NULL; /* terminate first half of list */
6628 q = msort(list, half); /* sort first half of list */
6629 p = msort(p, len - half); /* sort second half */
6630 lpp = &list;
6631 for (;;) {
6632#if ENABLE_LOCALE_SUPPORT
6633 if (strcoll(p->text, q->text) < 0)
6634#else
6635 if (strcmp(p->text, q->text) < 0)
6636#endif
6637 {
6638 *lpp = p;
6639 lpp = &p->next;
6640 p = *lpp;
6641 if (p == NULL) {
6642 *lpp = q;
6643 break;
6644 }
6645 } else {
6646 *lpp = q;
6647 lpp = &q->next;
6648 q = *lpp;
6649 if (q == NULL) {
6650 *lpp = p;
6651 break;
6652 }
6653 }
6654 }
6655 return list;
6656}
6657
6658/*
6659 * Sort the results of file name expansion. It calculates the number of
6660 * strings to sort and then calls msort (short for merge sort) to do the
6661 * work.
6662 */
6663static struct strlist *
6664expsort(struct strlist *str)
6665{
6666 int len;
6667 struct strlist *sp;
6668
6669 len = 0;
6670 for (sp = str; sp; sp = sp->next)
6671 len++;
6672 return msort(str, len);
6673}
6674
6675static void
Denis Vlasenko68404f12008-03-17 09:00:54 +00006676expandmeta(struct strlist *str /*, int flag*/)
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006677{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +00006678 static const char metachars[] ALIGN1 = {
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006679 '*', '?', '[', 0
6680 };
6681 /* TODO - EXP_REDIR */
6682
6683 while (str) {
6684 struct strlist **savelastp;
6685 struct strlist *sp;
6686 char *p;
6687
6688 if (fflag)
6689 goto nometa;
6690 if (!strpbrk(str->text, metachars))
6691 goto nometa;
6692 savelastp = exparg.lastp;
6693
6694 INT_OFF;
6695 p = preglob(str->text, 0, RMESCAPE_ALLOC | RMESCAPE_HEAP);
6696 {
6697 int i = strlen(str->text);
6698 expdir = ckmalloc(i < 2048 ? 2048 : i); /* XXX */
6699 }
6700
6701 expmeta(expdir, p);
6702 free(expdir);
6703 if (p != str->text)
6704 free(p);
6705 INT_ON;
6706 if (exparg.lastp == savelastp) {
6707 /*
6708 * no matches
6709 */
6710 nometa:
6711 *exparg.lastp = str;
6712 rmescapes(str->text);
6713 exparg.lastp = &str->next;
6714 } else {
6715 *exparg.lastp = NULL;
6716 *savelastp = sp = expsort(*savelastp);
6717 while (sp->next != NULL)
6718 sp = sp->next;
6719 exparg.lastp = &sp->next;
6720 }
6721 str = str->next;
6722 }
6723}
6724
6725/*
6726 * Perform variable substitution and command substitution on an argument,
6727 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
6728 * perform splitting and file name expansion. When arglist is NULL, perform
6729 * here document expansion.
6730 */
6731static void
6732expandarg(union node *arg, struct arglist *arglist, int flag)
6733{
6734 struct strlist *sp;
6735 char *p;
6736
6737 argbackq = arg->narg.backquote;
6738 STARTSTACKSTR(expdest);
6739 ifsfirst.next = NULL;
6740 ifslastp = NULL;
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006741 argstr(arg->narg.text, flag,
6742 /* var_str_list: */ arglist ? arglist->list : NULL);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006743 p = _STPUTC('\0', expdest);
6744 expdest = p - 1;
6745 if (arglist == NULL) {
6746 return; /* here document expanded */
6747 }
6748 p = grabstackstr(p);
6749 exparg.lastp = &exparg.list;
6750 /*
6751 * TODO - EXP_REDIR
6752 */
6753 if (flag & EXP_FULL) {
6754 ifsbreakup(p, &exparg);
6755 *exparg.lastp = NULL;
6756 exparg.lastp = &exparg.list;
Denis Vlasenko68404f12008-03-17 09:00:54 +00006757 expandmeta(exparg.list /*, flag*/);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006758 } else {
6759 if (flag & EXP_REDIR) /*XXX - for now, just remove escapes */
6760 rmescapes(p);
Denis Vlasenko597906c2008-02-20 16:38:54 +00006761 sp = stzalloc(sizeof(*sp));
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006762 sp->text = p;
6763 *exparg.lastp = sp;
6764 exparg.lastp = &sp->next;
6765 }
6766 if (ifsfirst.next)
6767 ifsfree();
6768 *exparg.lastp = NULL;
6769 if (exparg.list) {
6770 *arglist->lastp = exparg.list;
6771 arglist->lastp = exparg.lastp;
6772 }
6773}
6774
6775/*
6776 * Expand shell variables and backquotes inside a here document.
6777 */
6778static void
6779expandhere(union node *arg, int fd)
6780{
6781 herefd = fd;
6782 expandarg(arg, (struct arglist *)NULL, 0);
6783 full_write(fd, stackblock(), expdest - (char *)stackblock());
6784}
6785
6786/*
6787 * Returns true if the pattern matches the string.
6788 */
6789static int
6790patmatch(char *pattern, const char *string)
6791{
6792 return pmatch(preglob(pattern, 0, 0), string);
6793}
6794
6795/*
6796 * See if a pattern matches in a case statement.
6797 */
6798static int
6799casematch(union node *pattern, char *val)
6800{
6801 struct stackmark smark;
6802 int result;
6803
6804 setstackmark(&smark);
6805 argbackq = pattern->narg.backquote;
6806 STARTSTACKSTR(expdest);
6807 ifslastp = NULL;
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00006808 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE,
6809 /* var_str_list: */ NULL);
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00006810 STACKSTRNUL(expdest);
6811 result = patmatch(stackblock(), val);
6812 popstackmark(&smark);
6813 return result;
6814}
6815
6816
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00006817/* ============ find_command */
6818
6819struct builtincmd {
6820 const char *name;
6821 int (*builtin)(int, char **);
6822 /* unsigned flags; */
6823};
6824#define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
Denis Vlasenkoe26b2782008-02-12 07:40:29 +00006825/* "regular" builtins always take precedence over commands,
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00006826 * regardless of PATH=....%builtin... position */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00006827#define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00006828#define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00006829
6830struct cmdentry {
6831 int cmdtype;
6832 union param {
6833 int index;
6834 const struct builtincmd *cmd;
6835 struct funcnode *func;
6836 } u;
6837};
6838/* values of cmdtype */
6839#define CMDUNKNOWN -1 /* no entry in table for command */
6840#define CMDNORMAL 0 /* command is an executable program */
6841#define CMDFUNCTION 1 /* command is a shell function */
6842#define CMDBUILTIN 2 /* command is a shell builtin */
6843
6844/* action to find_command() */
6845#define DO_ERR 0x01 /* prints errors */
6846#define DO_ABS 0x02 /* checks absolute paths */
6847#define DO_NOFUNC 0x04 /* don't return shell functions, for command */
6848#define DO_ALTPATH 0x08 /* using alternate path */
6849#define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
6850
6851static void find_command(char *, struct cmdentry *, int, const char *);
6852
6853
6854/* ============ Hashing commands */
6855
6856/*
6857 * When commands are first encountered, they are entered in a hash table.
6858 * This ensures that a full path search will not have to be done for them
6859 * on each invocation.
6860 *
6861 * We should investigate converting to a linear search, even though that
6862 * would make the command name "hash" a misnomer.
6863 */
6864
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00006865#define ARB 1 /* actual size determined at run time */
6866
6867struct tblentry {
6868 struct tblentry *next; /* next entry in hash chain */
6869 union param param; /* definition of builtin function */
6870 short cmdtype; /* index identifying command */
6871 char rehash; /* if set, cd done since entry created */
6872 char cmdname[ARB]; /* name of command */
6873};
6874
Denis Vlasenko01631112007-12-16 17:20:38 +00006875static struct tblentry **cmdtable;
6876#define INIT_G_cmdtable() do { \
6877 cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
6878} while (0)
6879
6880static int builtinloc = -1; /* index in path of %builtin, or -1 */
6881
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00006882
6883static void
6884tryexec(char *cmd, char **argv, char **envp)
6885{
6886 int repeated = 0;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00006887
Denis Vlasenko80d14be2007-04-10 23:03:30 +00006888#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko29e31dd2007-03-03 23:12:17 +00006889 if (strchr(cmd, '/') == NULL) {
Denis Vlasenko1aa7e472007-11-28 06:49:03 +00006890 int a = find_applet_by_name(cmd);
6891 if (a >= 0) {
6892 if (APPLET_IS_NOEXEC(a))
6893 run_applet_no_and_exit(a, argv);
Denis Vlasenko29e31dd2007-03-03 23:12:17 +00006894 /* re-exec ourselves with the new arguments */
Denis Vlasenkobdbbb7e2007-06-08 15:02:55 +00006895 execve(bb_busybox_exec_path, argv, envp);
Denis Vlasenko29e31dd2007-03-03 23:12:17 +00006896 /* If they called chroot or otherwise made the binary no longer
6897 * executable, fall through */
6898 }
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00006899 }
6900#endif
6901
6902 repeat:
6903#ifdef SYSV
6904 do {
6905 execve(cmd, argv, envp);
6906 } while (errno == EINTR);
6907#else
6908 execve(cmd, argv, envp);
6909#endif
6910 if (repeated++) {
6911 free(argv);
6912 } else if (errno == ENOEXEC) {
6913 char **ap;
6914 char **new;
6915
6916 for (ap = argv; *ap; ap++)
6917 ;
6918 ap = new = ckmalloc((ap - argv + 2) * sizeof(char *));
6919 ap[1] = cmd;
Denis Vlasenkoc44ab012007-04-09 03:11:58 +00006920 ap[0] = cmd = (char *)DEFAULT_SHELL;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00006921 ap += 2;
6922 argv++;
6923 while ((*ap++ = *argv++))
Denis Vlasenko597906c2008-02-20 16:38:54 +00006924 continue;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00006925 argv = new;
6926 goto repeat;
6927 }
6928}
6929
6930/*
6931 * Exec a program. Never returns. If you change this routine, you may
6932 * have to change the find_command routine as well.
6933 */
6934#define environment() listvars(VEXPORT, VUNSET, 0)
6935static void shellexec(char **, const char *, int) ATTRIBUTE_NORETURN;
6936static void
6937shellexec(char **argv, const char *path, int idx)
6938{
6939 char *cmdname;
6940 int e;
6941 char **envp;
6942 int exerrno;
6943
6944 clearredir(1);
6945 envp = environment();
Denis Vlasenko29e31dd2007-03-03 23:12:17 +00006946 if (strchr(argv[0], '/')
Denis Vlasenko80d14be2007-04-10 23:03:30 +00006947#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko1aa7e472007-11-28 06:49:03 +00006948 || find_applet_by_name(argv[0]) >= 0
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00006949#endif
6950 ) {
6951 tryexec(argv[0], argv, envp);
6952 e = errno;
6953 } else {
6954 e = ENOENT;
6955 while ((cmdname = padvance(&path, argv[0])) != NULL) {
6956 if (--idx < 0 && pathopt == NULL) {
6957 tryexec(cmdname, argv, envp);
6958 if (errno != ENOENT && errno != ENOTDIR)
6959 e = errno;
6960 }
6961 stunalloc(cmdname);
6962 }
6963 }
6964
6965 /* Map to POSIX errors */
6966 switch (e) {
6967 case EACCES:
6968 exerrno = 126;
6969 break;
6970 case ENOENT:
6971 exerrno = 127;
6972 break;
6973 default:
6974 exerrno = 2;
6975 break;
6976 }
6977 exitstatus = exerrno;
6978 TRACE(("shellexec failed for %s, errno %d, suppressint %d\n",
6979 argv[0], e, suppressint ));
6980 ash_msg_and_raise(EXEXEC, "%s: %s", argv[0], errmsg(e, "not found"));
6981 /* NOTREACHED */
6982}
6983
6984static void
6985printentry(struct tblentry *cmdp)
6986{
6987 int idx;
6988 const char *path;
6989 char *name;
6990
6991 idx = cmdp->param.index;
6992 path = pathval();
6993 do {
6994 name = padvance(&path, cmdp->cmdname);
6995 stunalloc(name);
6996 } while (--idx >= 0);
6997 out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
6998}
6999
7000/*
7001 * Clear out command entries. The argument specifies the first entry in
7002 * PATH which has changed.
7003 */
7004static void
7005clearcmdentry(int firstchange)
7006{
7007 struct tblentry **tblp;
7008 struct tblentry **pp;
7009 struct tblentry *cmdp;
7010
7011 INT_OFF;
7012 for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
7013 pp = tblp;
7014 while ((cmdp = *pp) != NULL) {
7015 if ((cmdp->cmdtype == CMDNORMAL &&
7016 cmdp->param.index >= firstchange)
7017 || (cmdp->cmdtype == CMDBUILTIN &&
7018 builtinloc >= firstchange)
7019 ) {
7020 *pp = cmdp->next;
7021 free(cmdp);
7022 } else {
7023 pp = &cmdp->next;
7024 }
7025 }
7026 }
7027 INT_ON;
7028}
7029
7030/*
7031 * Locate a command in the command hash table. If "add" is nonzero,
7032 * add the command to the table if it is not already present. The
7033 * variable "lastcmdentry" is set to point to the address of the link
7034 * pointing to the entry, so that delete_cmd_entry can delete the
7035 * entry.
7036 *
7037 * Interrupts must be off if called with add != 0.
7038 */
7039static struct tblentry **lastcmdentry;
7040
7041static struct tblentry *
7042cmdlookup(const char *name, int add)
7043{
7044 unsigned int hashval;
7045 const char *p;
7046 struct tblentry *cmdp;
7047 struct tblentry **pp;
7048
7049 p = name;
7050 hashval = (unsigned char)*p << 4;
7051 while (*p)
7052 hashval += (unsigned char)*p++;
7053 hashval &= 0x7FFF;
7054 pp = &cmdtable[hashval % CMDTABLESIZE];
7055 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7056 if (strcmp(cmdp->cmdname, name) == 0)
7057 break;
7058 pp = &cmdp->next;
7059 }
7060 if (add && cmdp == NULL) {
Denis Vlasenko597906c2008-02-20 16:38:54 +00007061 cmdp = *pp = ckzalloc(sizeof(struct tblentry) - ARB
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007062 + strlen(name) + 1);
Denis Vlasenko597906c2008-02-20 16:38:54 +00007063 /*cmdp->next = NULL; - ckzalloc did it */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007064 cmdp->cmdtype = CMDUNKNOWN;
7065 strcpy(cmdp->cmdname, name);
7066 }
7067 lastcmdentry = pp;
7068 return cmdp;
7069}
7070
7071/*
7072 * Delete the command entry returned on the last lookup.
7073 */
7074static void
7075delete_cmd_entry(void)
7076{
7077 struct tblentry *cmdp;
7078
7079 INT_OFF;
7080 cmdp = *lastcmdentry;
7081 *lastcmdentry = cmdp->next;
7082 if (cmdp->cmdtype == CMDFUNCTION)
7083 freefunc(cmdp->param.func);
7084 free(cmdp);
7085 INT_ON;
7086}
7087
7088/*
7089 * Add a new command entry, replacing any existing command entry for
7090 * the same name - except special builtins.
7091 */
7092static void
7093addcmdentry(char *name, struct cmdentry *entry)
7094{
7095 struct tblentry *cmdp;
7096
7097 cmdp = cmdlookup(name, 1);
7098 if (cmdp->cmdtype == CMDFUNCTION) {
7099 freefunc(cmdp->param.func);
7100 }
7101 cmdp->cmdtype = entry->cmdtype;
7102 cmdp->param = entry->u;
7103 cmdp->rehash = 0;
7104}
7105
7106static int
Denis Vlasenko68404f12008-03-17 09:00:54 +00007107hashcmd(int argc ATTRIBUTE_UNUSED, char **argv ATTRIBUTE_UNUSED)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007108{
7109 struct tblentry **pp;
7110 struct tblentry *cmdp;
7111 int c;
7112 struct cmdentry entry;
7113 char *name;
7114
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007115 if (nextopt("r") != '\0') {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007116 clearcmdentry(0);
7117 return 0;
7118 }
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007119
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007120 if (*argptr == NULL) {
7121 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7122 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
7123 if (cmdp->cmdtype == CMDNORMAL)
7124 printentry(cmdp);
7125 }
7126 }
7127 return 0;
7128 }
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007129
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007130 c = 0;
7131 while ((name = *argptr) != NULL) {
7132 cmdp = cmdlookup(name, 0);
7133 if (cmdp != NULL
7134 && (cmdp->cmdtype == CMDNORMAL
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007135 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
7136 ) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007137 delete_cmd_entry();
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007138 }
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007139 find_command(name, &entry, DO_ERR, pathval());
7140 if (entry.cmdtype == CMDUNKNOWN)
7141 c = 1;
7142 argptr++;
7143 }
7144 return c;
7145}
7146
7147/*
7148 * Called when a cd is done. Marks all commands so the next time they
7149 * are executed they will be rehashed.
7150 */
7151static void
7152hashcd(void)
7153{
7154 struct tblentry **pp;
7155 struct tblentry *cmdp;
7156
7157 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
7158 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007159 if (cmdp->cmdtype == CMDNORMAL
7160 || (cmdp->cmdtype == CMDBUILTIN
7161 && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
7162 && builtinloc > 0)
7163 ) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007164 cmdp->rehash = 1;
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007165 }
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007166 }
7167 }
7168}
7169
7170/*
7171 * Fix command hash table when PATH changed.
7172 * Called before PATH is changed. The argument is the new value of PATH;
7173 * pathval() still returns the old value at this point.
7174 * Called with interrupts off.
7175 */
7176static void
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007177changepath(const char *new)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007178{
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007179 const char *old;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007180 int firstchange;
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007181 int idx;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007182 int idx_bltin;
7183
7184 old = pathval();
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007185 firstchange = 9999; /* assume no change */
7186 idx = 0;
7187 idx_bltin = -1;
7188 for (;;) {
7189 if (*old != *new) {
7190 firstchange = idx;
7191 if ((*old == '\0' && *new == ':')
7192 || (*old == ':' && *new == '\0'))
7193 firstchange++;
7194 old = new; /* ignore subsequent differences */
7195 }
7196 if (*new == '\0')
7197 break;
7198 if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
7199 idx_bltin = idx;
Denis Vlasenko5c3d2b32008-02-03 22:01:08 +00007200 if (*new == ':')
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007201 idx++;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007202 new++, old++;
7203 }
7204 if (builtinloc < 0 && idx_bltin >= 0)
7205 builtinloc = idx_bltin; /* zap builtins */
7206 if (builtinloc >= 0 && idx_bltin < 0)
7207 firstchange = 0;
7208 clearcmdentry(firstchange);
7209 builtinloc = idx_bltin;
7210}
7211
7212#define TEOF 0
7213#define TNL 1
7214#define TREDIR 2
7215#define TWORD 3
7216#define TSEMI 4
7217#define TBACKGND 5
7218#define TAND 6
7219#define TOR 7
7220#define TPIPE 8
7221#define TLP 9
7222#define TRP 10
7223#define TENDCASE 11
7224#define TENDBQUOTE 12
7225#define TNOT 13
7226#define TCASE 14
7227#define TDO 15
7228#define TDONE 16
7229#define TELIF 17
7230#define TELSE 18
7231#define TESAC 19
7232#define TFI 20
7233#define TFOR 21
7234#define TIF 22
7235#define TIN 23
7236#define TTHEN 24
7237#define TUNTIL 25
7238#define TWHILE 26
7239#define TBEGIN 27
7240#define TEND 28
7241
7242/* first char is indicating which tokens mark the end of a list */
7243static const char *const tokname_array[] = {
7244 "\1end of file",
7245 "\0newline",
7246 "\0redirection",
7247 "\0word",
7248 "\0;",
7249 "\0&",
7250 "\0&&",
7251 "\0||",
7252 "\0|",
7253 "\0(",
7254 "\1)",
7255 "\1;;",
7256 "\1`",
7257#define KWDOFFSET 13
7258 /* the following are keywords */
7259 "\0!",
7260 "\0case",
7261 "\1do",
7262 "\1done",
7263 "\1elif",
7264 "\1else",
7265 "\1esac",
7266 "\1fi",
7267 "\0for",
7268 "\0if",
7269 "\0in",
7270 "\1then",
7271 "\0until",
7272 "\0while",
7273 "\0{",
7274 "\1}",
7275};
7276
7277static const char *
7278tokname(int tok)
7279{
7280 static char buf[16];
7281
Denis Vlasenko240a1cf2007-04-08 16:07:02 +00007282//try this:
7283//if (tok < TSEMI) return tokname_array[tok] + 1;
7284//sprintf(buf, "\"%s\"", tokname_array[tok] + 1);
7285//return buf;
7286
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007287 if (tok >= TSEMI)
7288 buf[0] = '"';
7289 sprintf(buf + (tok >= TSEMI), "%s%c",
7290 tokname_array[tok] + 1, (tok >= TSEMI ? '"' : 0));
7291 return buf;
7292}
7293
7294/* Wrapper around strcmp for qsort/bsearch/... */
7295static int
7296pstrcmp(const void *a, const void *b)
7297{
Denis Vlasenko240a1cf2007-04-08 16:07:02 +00007298 return strcmp((char*) a, (*(char**) b) + 1);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007299}
7300
7301static const char *const *
7302findkwd(const char *s)
7303{
7304 return bsearch(s, tokname_array + KWDOFFSET,
Denis Vlasenko80b8b392007-06-25 10:55:35 +00007305 ARRAY_SIZE(tokname_array) - KWDOFFSET,
7306 sizeof(tokname_array[0]), pstrcmp);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007307}
7308
7309/*
7310 * Locate and print what a word is...
7311 */
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007312static int
7313describe_command(char *command, int describe_command_verbose)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007314{
7315 struct cmdentry entry;
7316 struct tblentry *cmdp;
7317#if ENABLE_ASH_ALIAS
7318 const struct alias *ap;
7319#endif
7320 const char *path = pathval();
7321
7322 if (describe_command_verbose) {
7323 out1str(command);
7324 }
7325
7326 /* First look at the keywords */
7327 if (findkwd(command)) {
7328 out1str(describe_command_verbose ? " is a shell keyword" : command);
7329 goto out;
7330 }
7331
7332#if ENABLE_ASH_ALIAS
7333 /* Then look at the aliases */
7334 ap = lookupalias(command, 0);
7335 if (ap != NULL) {
Denis Vlasenko46846e22007-05-20 13:08:31 +00007336 if (!describe_command_verbose) {
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007337 out1str("alias ");
7338 printalias(ap);
7339 return 0;
7340 }
Denis Vlasenko46846e22007-05-20 13:08:31 +00007341 out1fmt(" is an alias for %s", ap->val);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007342 goto out;
7343 }
7344#endif
7345 /* Then check if it is a tracked alias */
7346 cmdp = cmdlookup(command, 0);
7347 if (cmdp != NULL) {
7348 entry.cmdtype = cmdp->cmdtype;
7349 entry.u = cmdp->param;
7350 } else {
7351 /* Finally use brute force */
7352 find_command(command, &entry, DO_ABS, path);
7353 }
7354
7355 switch (entry.cmdtype) {
7356 case CMDNORMAL: {
7357 int j = entry.u.index;
7358 char *p;
7359 if (j == -1) {
7360 p = command;
7361 } else {
7362 do {
7363 p = padvance(&path, command);
7364 stunalloc(p);
7365 } while (--j >= 0);
7366 }
7367 if (describe_command_verbose) {
7368 out1fmt(" is%s %s",
7369 (cmdp ? " a tracked alias for" : nullstr), p
7370 );
7371 } else {
7372 out1str(p);
7373 }
7374 break;
7375 }
7376
7377 case CMDFUNCTION:
7378 if (describe_command_verbose) {
7379 out1str(" is a shell function");
7380 } else {
7381 out1str(command);
7382 }
7383 break;
7384
7385 case CMDBUILTIN:
7386 if (describe_command_verbose) {
7387 out1fmt(" is a %sshell builtin",
7388 IS_BUILTIN_SPECIAL(entry.u.cmd) ?
7389 "special " : nullstr
7390 );
7391 } else {
7392 out1str(command);
7393 }
7394 break;
7395
7396 default:
7397 if (describe_command_verbose) {
7398 out1str(": not found\n");
7399 }
7400 return 127;
7401 }
7402 out:
7403 outstr("\n", stdout);
7404 return 0;
7405}
7406
7407static int
Denis Vlasenko68404f12008-03-17 09:00:54 +00007408typecmd(int argc ATTRIBUTE_UNUSED, char **argv)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007409{
Denis Vlasenko46846e22007-05-20 13:08:31 +00007410 int i = 1;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007411 int err = 0;
Denis Vlasenko46846e22007-05-20 13:08:31 +00007412 int verbose = 1;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007413
Denis Vlasenko46846e22007-05-20 13:08:31 +00007414 /* type -p ... ? (we don't bother checking for 'p') */
Denis Vlasenko1fc62382007-06-25 22:55:34 +00007415 if (argv[1] && argv[1][0] == '-') {
Denis Vlasenko46846e22007-05-20 13:08:31 +00007416 i++;
7417 verbose = 0;
7418 }
Denis Vlasenko68404f12008-03-17 09:00:54 +00007419 while (argv[i]) {
Denis Vlasenko46846e22007-05-20 13:08:31 +00007420 err |= describe_command(argv[i++], verbose);
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007421 }
7422 return err;
7423}
7424
7425#if ENABLE_ASH_CMDCMD
7426static int
Denis Vlasenko68404f12008-03-17 09:00:54 +00007427commandcmd(int argc ATTRIBUTE_UNUSED, char **argv ATTRIBUTE_UNUSED)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007428{
7429 int c;
7430 enum {
7431 VERIFY_BRIEF = 1,
7432 VERIFY_VERBOSE = 2,
7433 } verify = 0;
7434
7435 while ((c = nextopt("pvV")) != '\0')
7436 if (c == 'V')
7437 verify |= VERIFY_VERBOSE;
7438 else if (c == 'v')
7439 verify |= VERIFY_BRIEF;
7440#if DEBUG
7441 else if (c != 'p')
7442 abort();
7443#endif
7444 if (verify)
7445 return describe_command(*argptr, verify - VERIFY_BRIEF);
7446
7447 return 0;
7448}
7449#endif
7450
7451
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007452/* ============ eval.c */
Eric Andersencb57d552001-06-28 07:25:16 +00007453
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007454static int funcblocksize; /* size of structures in function */
7455static int funcstringsize; /* size of strings in node */
7456static void *funcblock; /* block to allocate function from */
7457static char *funcstring; /* block to allocate strings from */
7458
Eric Andersencb57d552001-06-28 07:25:16 +00007459/* flags in argument to evaltree */
Eric Andersenc470f442003-07-28 09:56:35 +00007460#define EV_EXIT 01 /* exit after evaluating tree */
7461#define EV_TESTED 02 /* exit status is checked; ignore -e flag */
7462#define EV_BACKCMD 04 /* command executing within back quotes */
Eric Andersencb57d552001-06-28 07:25:16 +00007463
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00007464static const short nodesize[26] = {
7465 SHELL_ALIGN(sizeof(struct ncmd)),
7466 SHELL_ALIGN(sizeof(struct npipe)),
7467 SHELL_ALIGN(sizeof(struct nredir)),
7468 SHELL_ALIGN(sizeof(struct nredir)),
7469 SHELL_ALIGN(sizeof(struct nredir)),
7470 SHELL_ALIGN(sizeof(struct nbinary)),
7471 SHELL_ALIGN(sizeof(struct nbinary)),
7472 SHELL_ALIGN(sizeof(struct nbinary)),
7473 SHELL_ALIGN(sizeof(struct nif)),
7474 SHELL_ALIGN(sizeof(struct nbinary)),
7475 SHELL_ALIGN(sizeof(struct nbinary)),
7476 SHELL_ALIGN(sizeof(struct nfor)),
7477 SHELL_ALIGN(sizeof(struct ncase)),
7478 SHELL_ALIGN(sizeof(struct nclist)),
7479 SHELL_ALIGN(sizeof(struct narg)),
7480 SHELL_ALIGN(sizeof(struct narg)),
7481 SHELL_ALIGN(sizeof(struct nfile)),
7482 SHELL_ALIGN(sizeof(struct nfile)),
7483 SHELL_ALIGN(sizeof(struct nfile)),
7484 SHELL_ALIGN(sizeof(struct nfile)),
7485 SHELL_ALIGN(sizeof(struct nfile)),
7486 SHELL_ALIGN(sizeof(struct ndup)),
7487 SHELL_ALIGN(sizeof(struct ndup)),
7488 SHELL_ALIGN(sizeof(struct nhere)),
7489 SHELL_ALIGN(sizeof(struct nhere)),
7490 SHELL_ALIGN(sizeof(struct nnot)),
7491};
7492
7493static void calcsize(union node *n);
7494
7495static void
7496sizenodelist(struct nodelist *lp)
7497{
7498 while (lp) {
7499 funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
7500 calcsize(lp->n);
7501 lp = lp->next;
7502 }
7503}
7504
7505static void
7506calcsize(union node *n)
7507{
7508 if (n == NULL)
7509 return;
7510 funcblocksize += nodesize[n->type];
7511 switch (n->type) {
7512 case NCMD:
7513 calcsize(n->ncmd.redirect);
7514 calcsize(n->ncmd.args);
7515 calcsize(n->ncmd.assign);
7516 break;
7517 case NPIPE:
7518 sizenodelist(n->npipe.cmdlist);
7519 break;
7520 case NREDIR:
7521 case NBACKGND:
7522 case NSUBSHELL:
7523 calcsize(n->nredir.redirect);
7524 calcsize(n->nredir.n);
7525 break;
7526 case NAND:
7527 case NOR:
7528 case NSEMI:
7529 case NWHILE:
7530 case NUNTIL:
7531 calcsize(n->nbinary.ch2);
7532 calcsize(n->nbinary.ch1);
7533 break;
7534 case NIF:
7535 calcsize(n->nif.elsepart);
7536 calcsize(n->nif.ifpart);
7537 calcsize(n->nif.test);
7538 break;
7539 case NFOR:
7540 funcstringsize += strlen(n->nfor.var) + 1;
7541 calcsize(n->nfor.body);
7542 calcsize(n->nfor.args);
7543 break;
7544 case NCASE:
7545 calcsize(n->ncase.cases);
7546 calcsize(n->ncase.expr);
7547 break;
7548 case NCLIST:
7549 calcsize(n->nclist.body);
7550 calcsize(n->nclist.pattern);
7551 calcsize(n->nclist.next);
7552 break;
7553 case NDEFUN:
7554 case NARG:
7555 sizenodelist(n->narg.backquote);
7556 funcstringsize += strlen(n->narg.text) + 1;
7557 calcsize(n->narg.next);
7558 break;
7559 case NTO:
7560 case NCLOBBER:
7561 case NFROM:
7562 case NFROMTO:
7563 case NAPPEND:
7564 calcsize(n->nfile.fname);
7565 calcsize(n->nfile.next);
7566 break;
7567 case NTOFD:
7568 case NFROMFD:
7569 calcsize(n->ndup.vname);
7570 calcsize(n->ndup.next);
7571 break;
7572 case NHERE:
7573 case NXHERE:
7574 calcsize(n->nhere.doc);
7575 calcsize(n->nhere.next);
7576 break;
7577 case NNOT:
7578 calcsize(n->nnot.com);
7579 break;
7580 };
7581}
7582
7583static char *
7584nodeckstrdup(char *s)
7585{
7586 char *rtn = funcstring;
7587
7588 strcpy(funcstring, s);
7589 funcstring += strlen(s) + 1;
7590 return rtn;
7591}
7592
7593static union node *copynode(union node *);
7594
7595static struct nodelist *
7596copynodelist(struct nodelist *lp)
7597{
7598 struct nodelist *start;
7599 struct nodelist **lpp;
7600
7601 lpp = &start;
7602 while (lp) {
7603 *lpp = funcblock;
7604 funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
7605 (*lpp)->n = copynode(lp->n);
7606 lp = lp->next;
7607 lpp = &(*lpp)->next;
7608 }
7609 *lpp = NULL;
7610 return start;
7611}
7612
7613static union node *
7614copynode(union node *n)
7615{
7616 union node *new;
7617
7618 if (n == NULL)
7619 return NULL;
7620 new = funcblock;
7621 funcblock = (char *) funcblock + nodesize[n->type];
7622
7623 switch (n->type) {
7624 case NCMD:
7625 new->ncmd.redirect = copynode(n->ncmd.redirect);
7626 new->ncmd.args = copynode(n->ncmd.args);
7627 new->ncmd.assign = copynode(n->ncmd.assign);
7628 break;
7629 case NPIPE:
7630 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
7631 new->npipe.backgnd = n->npipe.backgnd;
7632 break;
7633 case NREDIR:
7634 case NBACKGND:
7635 case NSUBSHELL:
7636 new->nredir.redirect = copynode(n->nredir.redirect);
7637 new->nredir.n = copynode(n->nredir.n);
7638 break;
7639 case NAND:
7640 case NOR:
7641 case NSEMI:
7642 case NWHILE:
7643 case NUNTIL:
7644 new->nbinary.ch2 = copynode(n->nbinary.ch2);
7645 new->nbinary.ch1 = copynode(n->nbinary.ch1);
7646 break;
7647 case NIF:
7648 new->nif.elsepart = copynode(n->nif.elsepart);
7649 new->nif.ifpart = copynode(n->nif.ifpart);
7650 new->nif.test = copynode(n->nif.test);
7651 break;
7652 case NFOR:
7653 new->nfor.var = nodeckstrdup(n->nfor.var);
7654 new->nfor.body = copynode(n->nfor.body);
7655 new->nfor.args = copynode(n->nfor.args);
7656 break;
7657 case NCASE:
7658 new->ncase.cases = copynode(n->ncase.cases);
7659 new->ncase.expr = copynode(n->ncase.expr);
7660 break;
7661 case NCLIST:
7662 new->nclist.body = copynode(n->nclist.body);
7663 new->nclist.pattern = copynode(n->nclist.pattern);
7664 new->nclist.next = copynode(n->nclist.next);
7665 break;
7666 case NDEFUN:
7667 case NARG:
7668 new->narg.backquote = copynodelist(n->narg.backquote);
7669 new->narg.text = nodeckstrdup(n->narg.text);
7670 new->narg.next = copynode(n->narg.next);
7671 break;
7672 case NTO:
7673 case NCLOBBER:
7674 case NFROM:
7675 case NFROMTO:
7676 case NAPPEND:
7677 new->nfile.fname = copynode(n->nfile.fname);
7678 new->nfile.fd = n->nfile.fd;
7679 new->nfile.next = copynode(n->nfile.next);
7680 break;
7681 case NTOFD:
7682 case NFROMFD:
7683 new->ndup.vname = copynode(n->ndup.vname);
7684 new->ndup.dupfd = n->ndup.dupfd;
7685 new->ndup.fd = n->ndup.fd;
7686 new->ndup.next = copynode(n->ndup.next);
7687 break;
7688 case NHERE:
7689 case NXHERE:
7690 new->nhere.doc = copynode(n->nhere.doc);
7691 new->nhere.fd = n->nhere.fd;
7692 new->nhere.next = copynode(n->nhere.next);
7693 break;
7694 case NNOT:
7695 new->nnot.com = copynode(n->nnot.com);
7696 break;
7697 };
7698 new->type = n->type;
7699 return new;
7700}
7701
7702/*
7703 * Make a copy of a parse tree.
7704 */
7705static struct funcnode *
7706copyfunc(union node *n)
7707{
7708 struct funcnode *f;
7709 size_t blocksize;
7710
7711 funcblocksize = offsetof(struct funcnode, n);
7712 funcstringsize = 0;
7713 calcsize(n);
7714 blocksize = funcblocksize;
7715 f = ckmalloc(blocksize + funcstringsize);
7716 funcblock = (char *) f + offsetof(struct funcnode, n);
7717 funcstring = (char *) f + blocksize;
7718 copynode(n);
7719 f->count = 0;
7720 return f;
7721}
7722
7723/*
7724 * Define a shell function.
7725 */
7726static void
7727defun(char *name, union node *func)
7728{
7729 struct cmdentry entry;
7730
7731 INT_OFF;
7732 entry.cmdtype = CMDFUNCTION;
7733 entry.u.func = copyfunc(func);
7734 addcmdentry(name, &entry);
7735 INT_ON;
7736}
7737
7738static int evalskip; /* set if we are skipping commands */
7739/* reasons for skipping commands (see comment on breakcmd routine) */
7740#define SKIPBREAK (1 << 0)
7741#define SKIPCONT (1 << 1)
7742#define SKIPFUNC (1 << 2)
7743#define SKIPFILE (1 << 3)
7744#define SKIPEVAL (1 << 4)
7745static int skipcount; /* number of levels to skip */
7746static int funcnest; /* depth of function calls */
7747
Denis Vlasenkofc06f292007-02-23 21:09:35 +00007748/* forward decl way out to parsing code - dotrap needs it */
7749static int evalstring(char *s, int mask);
7750
7751/*
7752 * Called to execute a trap. Perhaps we should avoid entering new trap
7753 * handlers while we are executing a trap handler.
7754 */
7755static int
7756dotrap(void)
7757{
7758 char *p;
7759 char *q;
7760 int i;
7761 int savestatus;
Denis Vlasenko991a1da2008-02-10 19:02:53 +00007762 int skip;
Denis Vlasenkofc06f292007-02-23 21:09:35 +00007763
7764 savestatus = exitstatus;
Denis Vlasenko7c139b42007-03-21 20:17:27 +00007765 pendingsig = 0;
Denis Vlasenkofc06f292007-02-23 21:09:35 +00007766 xbarrier();
7767
7768 for (i = 0, q = gotsig; i < NSIG - 1; i++, q++) {
7769 if (!*q)
7770 continue;
7771 *q = '\0';
7772
7773 p = trap[i + 1];
7774 if (!p)
7775 continue;
7776 skip = evalstring(p, SKIPEVAL);
7777 exitstatus = savestatus;
7778 if (skip)
Denis Vlasenko991a1da2008-02-10 19:02:53 +00007779 return skip;
Denis Vlasenkofc06f292007-02-23 21:09:35 +00007780 }
7781
Denis Vlasenko991a1da2008-02-10 19:02:53 +00007782 return 0;
Denis Vlasenkofc06f292007-02-23 21:09:35 +00007783}
7784
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00007785/* forward declarations - evaluation is fairly recursive business... */
Eric Andersenc470f442003-07-28 09:56:35 +00007786static void evalloop(union node *, int);
7787static void evalfor(union node *, int);
7788static void evalcase(union node *, int);
7789static void evalsubshell(union node *, int);
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00007790static void expredir(union node *);
Eric Andersenc470f442003-07-28 09:56:35 +00007791static void evalpipe(union node *, int);
7792static void evalcommand(union node *, int);
7793static int evalbltin(const struct builtincmd *, int, char **);
Glenn L McGrath50812ff2002-08-23 13:14:48 +00007794static void prehash(union node *);
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00007795
Eric Andersen62483552001-07-10 06:09:16 +00007796/*
Eric Andersenc470f442003-07-28 09:56:35 +00007797 * Evaluate a parse tree. The value is left in the global variable
7798 * exitstatus.
Eric Andersen62483552001-07-10 06:09:16 +00007799 */
Eric Andersenc470f442003-07-28 09:56:35 +00007800static void
7801evaltree(union node *n, int flags)
Eric Andersen62483552001-07-10 06:09:16 +00007802{
Eric Andersenc470f442003-07-28 09:56:35 +00007803 int checkexit = 0;
7804 void (*evalfn)(union node *, int);
7805 unsigned isor;
7806 int status;
7807 if (n == NULL) {
7808 TRACE(("evaltree(NULL) called\n"));
7809 goto out;
Eric Andersen62483552001-07-10 06:09:16 +00007810 }
Eric Andersenc470f442003-07-28 09:56:35 +00007811 TRACE(("pid %d, evaltree(%p: %d, %d) called\n",
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +00007812 getpid(), n, n->type, flags));
Eric Andersenc470f442003-07-28 09:56:35 +00007813 switch (n->type) {
7814 default:
Denis Vlasenkoa7189f02006-11-17 20:29:00 +00007815#if DEBUG
Eric Andersenc470f442003-07-28 09:56:35 +00007816 out1fmt("Node type = %d\n", n->type);
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00007817 fflush(stdout);
Eric Andersenc470f442003-07-28 09:56:35 +00007818 break;
7819#endif
7820 case NNOT:
7821 evaltree(n->nnot.com, EV_TESTED);
7822 status = !exitstatus;
7823 goto setstatus;
7824 case NREDIR:
7825 expredir(n->nredir.redirect);
7826 status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
7827 if (!status) {
7828 evaltree(n->nredir.n, flags & EV_TESTED);
7829 status = exitstatus;
7830 }
7831 popredir(0);
7832 goto setstatus;
7833 case NCMD:
7834 evalfn = evalcommand;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00007835 checkexit:
Eric Andersenc470f442003-07-28 09:56:35 +00007836 if (eflag && !(flags & EV_TESTED))
7837 checkexit = ~0;
7838 goto calleval;
7839 case NFOR:
7840 evalfn = evalfor;
7841 goto calleval;
7842 case NWHILE:
7843 case NUNTIL:
7844 evalfn = evalloop;
7845 goto calleval;
7846 case NSUBSHELL:
7847 case NBACKGND:
7848 evalfn = evalsubshell;
7849 goto calleval;
7850 case NPIPE:
7851 evalfn = evalpipe;
7852 goto checkexit;
7853 case NCASE:
7854 evalfn = evalcase;
7855 goto calleval;
7856 case NAND:
7857 case NOR:
7858 case NSEMI:
7859#if NAND + 1 != NOR
7860#error NAND + 1 != NOR
7861#endif
7862#if NOR + 1 != NSEMI
7863#error NOR + 1 != NSEMI
7864#endif
7865 isor = n->type - NAND;
7866 evaltree(
7867 n->nbinary.ch1,
7868 (flags | ((isor >> 1) - 1)) & EV_TESTED
7869 );
7870 if (!exitstatus == isor)
7871 break;
7872 if (!evalskip) {
7873 n = n->nbinary.ch2;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00007874 evaln:
Eric Andersenc470f442003-07-28 09:56:35 +00007875 evalfn = evaltree;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00007876 calleval:
Eric Andersenc470f442003-07-28 09:56:35 +00007877 evalfn(n, flags);
7878 break;
7879 }
7880 break;
7881 case NIF:
7882 evaltree(n->nif.test, EV_TESTED);
7883 if (evalskip)
7884 break;
7885 if (exitstatus == 0) {
7886 n = n->nif.ifpart;
7887 goto evaln;
7888 } else if (n->nif.elsepart) {
7889 n = n->nif.elsepart;
7890 goto evaln;
7891 }
7892 goto success;
7893 case NDEFUN:
7894 defun(n->narg.text, n->narg.next);
Denis Vlasenko5cedb752007-02-18 19:56:41 +00007895 success:
Eric Andersenc470f442003-07-28 09:56:35 +00007896 status = 0;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00007897 setstatus:
Eric Andersenc470f442003-07-28 09:56:35 +00007898 exitstatus = status;
7899 break;
7900 }
Denis Vlasenko5cedb752007-02-18 19:56:41 +00007901 out:
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00007902 if ((checkexit & exitstatus))
7903 evalskip |= SKIPEVAL;
Denis Vlasenko7c139b42007-03-21 20:17:27 +00007904 else if (pendingsig && dotrap())
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00007905 goto exexit;
7906
7907 if (flags & EV_EXIT) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00007908 exexit:
Denis Vlasenkob012b102007-02-19 22:43:01 +00007909 raise_exception(EXEXIT);
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00007910 }
Eric Andersen62483552001-07-10 06:09:16 +00007911}
7912
Eric Andersenc470f442003-07-28 09:56:35 +00007913#if !defined(__alpha__) || (defined(__GNUC__) && __GNUC__ >= 3)
7914static
7915#endif
7916void evaltreenr(union node *, int) __attribute__ ((alias("evaltree"),__noreturn__));
7917
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00007918static int loopnest; /* current loop nesting level */
Eric Andersenc470f442003-07-28 09:56:35 +00007919
7920static void
7921evalloop(union node *n, int flags)
Eric Andersencb57d552001-06-28 07:25:16 +00007922{
7923 int status;
7924
7925 loopnest++;
7926 status = 0;
Glenn L McGrath50812ff2002-08-23 13:14:48 +00007927 flags &= EV_TESTED;
Eric Andersencb57d552001-06-28 07:25:16 +00007928 for (;;) {
Eric Andersenc470f442003-07-28 09:56:35 +00007929 int i;
7930
Eric Andersencb57d552001-06-28 07:25:16 +00007931 evaltree(n->nbinary.ch1, EV_TESTED);
7932 if (evalskip) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00007933 skipping:
7934 if (evalskip == SKIPCONT && --skipcount <= 0) {
Eric Andersencb57d552001-06-28 07:25:16 +00007935 evalskip = 0;
7936 continue;
7937 }
7938 if (evalskip == SKIPBREAK && --skipcount <= 0)
7939 evalskip = 0;
7940 break;
7941 }
Eric Andersenc470f442003-07-28 09:56:35 +00007942 i = exitstatus;
7943 if (n->type != NWHILE)
7944 i = !i;
7945 if (i != 0)
7946 break;
Glenn L McGrath50812ff2002-08-23 13:14:48 +00007947 evaltree(n->nbinary.ch2, flags);
Eric Andersencb57d552001-06-28 07:25:16 +00007948 status = exitstatus;
7949 if (evalskip)
7950 goto skipping;
7951 }
7952 loopnest--;
7953 exitstatus = status;
7954}
7955
Eric Andersenc470f442003-07-28 09:56:35 +00007956static void
7957evalfor(union node *n, int flags)
Eric Andersencb57d552001-06-28 07:25:16 +00007958{
7959 struct arglist arglist;
7960 union node *argp;
7961 struct strlist *sp;
7962 struct stackmark smark;
7963
7964 setstackmark(&smark);
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00007965 arglist.list = NULL;
Eric Andersencb57d552001-06-28 07:25:16 +00007966 arglist.lastp = &arglist.list;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00007967 for (argp = n->nfor.args; argp; argp = argp->narg.next) {
Eric Andersencb57d552001-06-28 07:25:16 +00007968 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE | EXP_RECORD);
Eric Andersenc470f442003-07-28 09:56:35 +00007969 /* XXX */
Eric Andersencb57d552001-06-28 07:25:16 +00007970 if (evalskip)
7971 goto out;
7972 }
7973 *arglist.lastp = NULL;
7974
7975 exitstatus = 0;
7976 loopnest++;
Glenn L McGrath50812ff2002-08-23 13:14:48 +00007977 flags &= EV_TESTED;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00007978 for (sp = arglist.list; sp; sp = sp->next) {
Eric Andersencb57d552001-06-28 07:25:16 +00007979 setvar(n->nfor.var, sp->text, 0);
Glenn L McGrath50812ff2002-08-23 13:14:48 +00007980 evaltree(n->nfor.body, flags);
Eric Andersencb57d552001-06-28 07:25:16 +00007981 if (evalskip) {
7982 if (evalskip == SKIPCONT && --skipcount <= 0) {
7983 evalskip = 0;
7984 continue;
7985 }
7986 if (evalskip == SKIPBREAK && --skipcount <= 0)
7987 evalskip = 0;
7988 break;
7989 }
7990 }
7991 loopnest--;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00007992 out:
Eric Andersencb57d552001-06-28 07:25:16 +00007993 popstackmark(&smark);
7994}
7995
Eric Andersenc470f442003-07-28 09:56:35 +00007996static void
7997evalcase(union node *n, int flags)
Eric Andersencb57d552001-06-28 07:25:16 +00007998{
7999 union node *cp;
8000 union node *patp;
8001 struct arglist arglist;
8002 struct stackmark smark;
8003
8004 setstackmark(&smark);
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00008005 arglist.list = NULL;
Eric Andersencb57d552001-06-28 07:25:16 +00008006 arglist.lastp = &arglist.list;
Eric Andersencb57d552001-06-28 07:25:16 +00008007 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
Eric Andersenc470f442003-07-28 09:56:35 +00008008 exitstatus = 0;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008009 for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
8010 for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
Eric Andersencb57d552001-06-28 07:25:16 +00008011 if (casematch(patp, arglist.list->text)) {
8012 if (evalskip == 0) {
8013 evaltree(cp->nclist.body, flags);
8014 }
8015 goto out;
8016 }
8017 }
8018 }
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008019 out:
Eric Andersencb57d552001-06-28 07:25:16 +00008020 popstackmark(&smark);
8021}
8022
Eric Andersenc470f442003-07-28 09:56:35 +00008023/*
8024 * Kick off a subshell to evaluate a tree.
8025 */
Eric Andersenc470f442003-07-28 09:56:35 +00008026static void
8027evalsubshell(union node *n, int flags)
8028{
8029 struct job *jp;
8030 int backgnd = (n->type == NBACKGND);
8031 int status;
8032
8033 expredir(n->nredir.redirect);
8034 if (!backgnd && flags & EV_EXIT && !trap[0])
8035 goto nofork;
Denis Vlasenkob012b102007-02-19 22:43:01 +00008036 INT_OFF;
Denis Vlasenko68404f12008-03-17 09:00:54 +00008037 jp = makejob(/*n,*/ 1);
Eric Andersenc470f442003-07-28 09:56:35 +00008038 if (forkshell(jp, n, backgnd) == 0) {
Denis Vlasenkob012b102007-02-19 22:43:01 +00008039 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00008040 flags |= EV_EXIT;
8041 if (backgnd)
8042 flags &=~ EV_TESTED;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00008043 nofork:
Eric Andersenc470f442003-07-28 09:56:35 +00008044 redirect(n->nredir.redirect, 0);
8045 evaltreenr(n->nredir.n, flags);
8046 /* never returns */
8047 }
8048 status = 0;
8049 if (! backgnd)
8050 status = waitforjob(jp);
8051 exitstatus = status;
Denis Vlasenkob012b102007-02-19 22:43:01 +00008052 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00008053}
8054
Eric Andersenc470f442003-07-28 09:56:35 +00008055/*
8056 * Compute the names of the files in a redirection list.
8057 */
Denis Vlasenko99eb8502007-02-23 21:09:49 +00008058static void fixredir(union node *, const char *, int);
Eric Andersenc470f442003-07-28 09:56:35 +00008059static void
8060expredir(union node *n)
8061{
8062 union node *redir;
8063
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008064 for (redir = n; redir; redir = redir->nfile.next) {
Eric Andersenc470f442003-07-28 09:56:35 +00008065 struct arglist fn;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008066
Denis Vlasenkoc12d51e2008-02-19 23:31:05 +00008067 fn.list = NULL;
Eric Andersenc470f442003-07-28 09:56:35 +00008068 fn.lastp = &fn.list;
8069 switch (redir->type) {
8070 case NFROMTO:
8071 case NFROM:
8072 case NTO:
8073 case NCLOBBER:
8074 case NAPPEND:
8075 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
8076 redir->nfile.expfname = fn.list->text;
8077 break;
8078 case NFROMFD:
8079 case NTOFD:
8080 if (redir->ndup.vname) {
8081 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008082 if (fn.list == NULL)
Denis Vlasenkob012b102007-02-19 22:43:01 +00008083 ash_msg_and_raise_error("redir error");
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008084 fixredir(redir, fn.list->text, 1);
Eric Andersenc470f442003-07-28 09:56:35 +00008085 }
8086 break;
8087 }
8088 }
8089}
8090
Eric Andersencb57d552001-06-28 07:25:16 +00008091/*
Eric Andersencb57d552001-06-28 07:25:16 +00008092 * Evaluate a pipeline. All the processes in the pipeline are children
8093 * of the process creating the pipeline. (This differs from some versions
8094 * of the shell, which make the last process in a pipeline the parent
8095 * of all the rest.)
8096 */
Eric Andersenc470f442003-07-28 09:56:35 +00008097static void
8098evalpipe(union node *n, int flags)
Eric Andersencb57d552001-06-28 07:25:16 +00008099{
8100 struct job *jp;
8101 struct nodelist *lp;
8102 int pipelen;
8103 int prevfd;
8104 int pip[2];
8105
Eric Andersenc470f442003-07-28 09:56:35 +00008106 TRACE(("evalpipe(0x%lx) called\n", (long)n));
Eric Andersencb57d552001-06-28 07:25:16 +00008107 pipelen = 0;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008108 for (lp = n->npipe.cmdlist; lp; lp = lp->next)
Eric Andersencb57d552001-06-28 07:25:16 +00008109 pipelen++;
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008110 flags |= EV_EXIT;
Denis Vlasenkob012b102007-02-19 22:43:01 +00008111 INT_OFF;
Denis Vlasenko68404f12008-03-17 09:00:54 +00008112 jp = makejob(/*n,*/ pipelen);
Eric Andersencb57d552001-06-28 07:25:16 +00008113 prevfd = -1;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008114 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008115 prehash(lp->n);
Eric Andersencb57d552001-06-28 07:25:16 +00008116 pip[1] = -1;
8117 if (lp->next) {
8118 if (pipe(pip) < 0) {
8119 close(prevfd);
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00008120 ash_msg_and_raise_error("pipe call failed");
Eric Andersencb57d552001-06-28 07:25:16 +00008121 }
8122 }
8123 if (forkshell(jp, lp->n, n->npipe.backgnd) == 0) {
Denis Vlasenkob012b102007-02-19 22:43:01 +00008124 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00008125 if (pip[1] >= 0) {
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008126 close(pip[0]);
Eric Andersencb57d552001-06-28 07:25:16 +00008127 }
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008128 if (prevfd > 0) {
8129 dup2(prevfd, 0);
8130 close(prevfd);
8131 }
8132 if (pip[1] > 1) {
8133 dup2(pip[1], 1);
8134 close(pip[1]);
8135 }
Eric Andersenc470f442003-07-28 09:56:35 +00008136 evaltreenr(lp->n, flags);
8137 /* never returns */
Eric Andersencb57d552001-06-28 07:25:16 +00008138 }
8139 if (prevfd >= 0)
8140 close(prevfd);
8141 prevfd = pip[0];
8142 close(pip[1]);
8143 }
Eric Andersencb57d552001-06-28 07:25:16 +00008144 if (n->npipe.backgnd == 0) {
Eric Andersencb57d552001-06-28 07:25:16 +00008145 exitstatus = waitforjob(jp);
8146 TRACE(("evalpipe: job done exit status %d\n", exitstatus));
Eric Andersencb57d552001-06-28 07:25:16 +00008147 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00008148 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00008149}
8150
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008151/*
8152 * Controls whether the shell is interactive or not.
8153 */
8154static void
8155setinteractive(int on)
8156{
8157 static int is_interactive;
8158
8159 if (++on == is_interactive)
8160 return;
8161 is_interactive = on;
8162 setsignal(SIGINT);
8163 setsignal(SIGQUIT);
8164 setsignal(SIGTERM);
8165#if !ENABLE_FEATURE_SH_EXTRA_QUIET
8166 if (is_interactive > 1) {
8167 /* Looks like they want an interactive shell */
Denis Vlasenkoca525b42007-06-13 12:27:17 +00008168 static smallint did_banner;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008169
Denis Vlasenkoca525b42007-06-13 12:27:17 +00008170 if (!did_banner) {
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008171 out1fmt(
8172 "\n\n"
Denis Vlasenkoca525b42007-06-13 12:27:17 +00008173 "%s built-in shell (ash)\n"
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008174 "Enter 'help' for a list of built-in commands."
8175 "\n\n",
Denis Vlasenkoca525b42007-06-13 12:27:17 +00008176 bb_banner);
8177 did_banner = 1;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008178 }
8179 }
8180#endif
8181}
8182
8183#if ENABLE_FEATURE_EDITING_VI
8184#define setvimode(on) do { \
8185 if (on) line_input_state->flags |= VI_MODE; \
8186 else line_input_state->flags &= ~VI_MODE; \
8187} while (0)
8188#else
8189#define setvimode(on) viflag = 0 /* forcibly keep the option off */
8190#endif
8191
8192static void
8193optschanged(void)
8194{
8195#if DEBUG
8196 opentrace();
8197#endif
8198 setinteractive(iflag);
8199 setjobctl(mflag);
8200 setvimode(viflag);
8201}
8202
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008203static struct localvar *localvars;
8204
8205/*
8206 * Called after a function returns.
8207 * Interrupts must be off.
8208 */
8209static void
8210poplocalvars(void)
8211{
8212 struct localvar *lvp;
8213 struct var *vp;
8214
8215 while ((lvp = localvars) != NULL) {
8216 localvars = lvp->next;
8217 vp = lvp->vp;
8218 TRACE(("poplocalvar %s", vp ? vp->text : "-"));
8219 if (vp == NULL) { /* $- saved */
8220 memcpy(optlist, lvp->text, sizeof(optlist));
8221 free((char*)lvp->text);
8222 optschanged();
8223 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
8224 unsetvar(vp->text);
8225 } else {
8226 if (vp->func)
8227 (*vp->func)(strchrnul(lvp->text, '=') + 1);
8228 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
8229 free((char*)vp->text);
8230 vp->flags = lvp->flags;
8231 vp->text = lvp->text;
8232 }
8233 free(lvp);
8234 }
8235}
8236
8237static int
8238evalfun(struct funcnode *func, int argc, char **argv, int flags)
8239{
8240 volatile struct shparam saveparam;
8241 struct localvar *volatile savelocalvars;
8242 struct jmploc *volatile savehandler;
8243 struct jmploc jmploc;
8244 int e;
8245
8246 saveparam = shellparam;
8247 savelocalvars = localvars;
8248 e = setjmp(jmploc.loc);
8249 if (e) {
8250 goto funcdone;
8251 }
8252 INT_OFF;
8253 savehandler = exception_handler;
8254 exception_handler = &jmploc;
8255 localvars = NULL;
Denis Vlasenko01631112007-12-16 17:20:38 +00008256 shellparam.malloced = 0;
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008257 func->count++;
8258 funcnest++;
8259 INT_ON;
8260 shellparam.nparam = argc - 1;
8261 shellparam.p = argv + 1;
8262#if ENABLE_ASH_GETOPTS
8263 shellparam.optind = 1;
8264 shellparam.optoff = -1;
8265#endif
8266 evaltree(&func->n, flags & EV_TESTED);
Denis Vlasenko01631112007-12-16 17:20:38 +00008267 funcdone:
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008268 INT_OFF;
8269 funcnest--;
8270 freefunc(func);
8271 poplocalvars();
8272 localvars = savelocalvars;
8273 freeparam(&shellparam);
8274 shellparam = saveparam;
8275 exception_handler = savehandler;
8276 INT_ON;
8277 evalskip &= ~SKIPFUNC;
8278 return e;
8279}
8280
Denis Vlasenko131ae172007-02-18 13:00:19 +00008281#if ENABLE_ASH_CMDCMD
Denis Vlasenkoaa744452007-02-23 01:04:22 +00008282static char **
8283parse_command_args(char **argv, const char **path)
Eric Andersenc470f442003-07-28 09:56:35 +00008284{
8285 char *cp, c;
8286
8287 for (;;) {
8288 cp = *++argv;
8289 if (!cp)
8290 return 0;
8291 if (*cp++ != '-')
8292 break;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008293 c = *cp++;
8294 if (!c)
Eric Andersenc470f442003-07-28 09:56:35 +00008295 break;
8296 if (c == '-' && !*cp) {
8297 argv++;
8298 break;
8299 }
8300 do {
8301 switch (c) {
8302 case 'p':
Denis Vlasenkof5f75c52007-06-12 22:35:19 +00008303 *path = bb_default_path;
Eric Andersenc470f442003-07-28 09:56:35 +00008304 break;
8305 default:
8306 /* run 'typecmd' for other options */
8307 return 0;
8308 }
Denis Vlasenko9650f362007-02-23 01:04:37 +00008309 c = *cp++;
8310 } while (c);
Eric Andersenc470f442003-07-28 09:56:35 +00008311 }
8312 return argv;
8313}
8314#endif
8315
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008316/*
8317 * Make a variable a local variable. When a variable is made local, it's
8318 * value and flags are saved in a localvar structure. The saved values
8319 * will be restored when the shell function returns. We handle the name
8320 * "-" as a special case.
8321 */
8322static void
8323mklocal(char *name)
8324{
8325 struct localvar *lvp;
8326 struct var **vpp;
8327 struct var *vp;
8328
8329 INT_OFF;
Denis Vlasenko838ffd52008-02-21 04:32:08 +00008330 lvp = ckzalloc(sizeof(struct localvar));
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008331 if (LONE_DASH(name)) {
8332 char *p;
8333 p = ckmalloc(sizeof(optlist));
8334 lvp->text = memcpy(p, optlist, sizeof(optlist));
8335 vp = NULL;
8336 } else {
8337 char *eq;
8338
8339 vpp = hashvar(name);
8340 vp = *findvar(vpp, name);
8341 eq = strchr(name, '=');
8342 if (vp == NULL) {
8343 if (eq)
8344 setvareq(name, VSTRFIXED);
8345 else
8346 setvar(name, NULL, VSTRFIXED);
8347 vp = *vpp; /* the new variable */
8348 lvp->flags = VUNSET;
8349 } else {
8350 lvp->text = vp->text;
8351 lvp->flags = vp->flags;
8352 vp->flags |= VSTRFIXED|VTEXTFIXED;
8353 if (eq)
8354 setvareq(name, 0);
8355 }
8356 }
8357 lvp->vp = vp;
8358 lvp->next = localvars;
8359 localvars = lvp;
8360 INT_ON;
8361}
8362
8363/*
8364 * The "local" command.
8365 */
8366static int
Denis Vlasenko68404f12008-03-17 09:00:54 +00008367localcmd(int argc ATTRIBUTE_UNUSED, char **argv)
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008368{
8369 char *name;
8370
8371 argv = argptr;
8372 while ((name = *argv++) != NULL) {
8373 mklocal(name);
8374 }
8375 return 0;
8376}
8377
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008378static int
Denis Vlasenko68404f12008-03-17 09:00:54 +00008379falsecmd(int argc ATTRIBUTE_UNUSED, char **argv ATTRIBUTE_UNUSED)
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008380{
8381 return 1;
8382}
8383
8384static int
Denis Vlasenko68404f12008-03-17 09:00:54 +00008385truecmd(int argc ATTRIBUTE_UNUSED, char **argv ATTRIBUTE_UNUSED)
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008386{
8387 return 0;
8388}
8389
8390static int
Denis Vlasenko68404f12008-03-17 09:00:54 +00008391execcmd(int argc ATTRIBUTE_UNUSED, char **argv)
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008392{
Denis Vlasenko68404f12008-03-17 09:00:54 +00008393 if (argv[1]) {
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008394 iflag = 0; /* exit on error */
8395 mflag = 0;
8396 optschanged();
8397 shellexec(argv + 1, pathval(), 0);
8398 }
8399 return 0;
8400}
8401
8402/*
8403 * The return command.
8404 */
8405static int
Denis Vlasenko68404f12008-03-17 09:00:54 +00008406returncmd(int argc ATTRIBUTE_UNUSED, char **argv)
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008407{
8408 /*
8409 * If called outside a function, do what ksh does;
8410 * skip the rest of the file.
8411 */
8412 evalskip = funcnest ? SKIPFUNC : SKIPFILE;
8413 return argv[1] ? number(argv[1]) : exitstatus;
8414}
8415
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008416/* Forward declarations for builtintab[] */
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008417static int breakcmd(int, char **);
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008418static int dotcmd(int, char **);
8419static int evalcmd(int, char **);
8420#if ENABLE_ASH_BUILTIN_ECHO
8421static int echocmd(int, char **);
8422#endif
8423#if ENABLE_ASH_BUILTIN_TEST
8424static int testcmd(int, char **);
8425#endif
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008426static int exitcmd(int, char **);
8427static int exportcmd(int, char **);
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008428#if ENABLE_ASH_GETOPTS
8429static int getoptscmd(int, char **);
8430#endif
Denis Vlasenko52764022007-02-24 13:42:56 +00008431#if !ENABLE_FEATURE_SH_EXTRA_QUIET
Denis Vlasenkof7d56652008-03-25 05:51:41 +00008432static int helpcmd(int, char **);
Denis Vlasenko52764022007-02-24 13:42:56 +00008433#endif
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008434#if ENABLE_ASH_MATH_SUPPORT
8435static int letcmd(int, char **);
8436#endif
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008437static int readcmd(int, char **);
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008438static int setcmd(int, char **);
8439static int shiftcmd(int, char **);
8440static int timescmd(int, char **);
8441static int trapcmd(int, char **);
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008442static int umaskcmd(int, char **);
8443static int unsetcmd(int, char **);
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008444static int ulimitcmd(int, char **);
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008445
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008446#define BUILTIN_NOSPEC "0"
8447#define BUILTIN_SPECIAL "1"
8448#define BUILTIN_REGULAR "2"
8449#define BUILTIN_SPEC_REG "3"
8450#define BUILTIN_ASSIGN "4"
8451#define BUILTIN_SPEC_ASSG "5"
8452#define BUILTIN_REG_ASSG "6"
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008453#define BUILTIN_SPEC_REG_ASSG "7"
8454
Denis Vlasenkof7d56652008-03-25 05:51:41 +00008455/* We do not handle [[ expr ]] bashism bash-compatibly,
8456 * we make it a synonym of [ expr ].
8457 * Basically, word splitting and pathname expansion should NOT be performed
8458 * Examples:
8459 * no word splitting: a="a b"; [[ $a = "a b" ]]; echo $? should print "0"
8460 * no pathname expansion: [[ /bin/m* = "/bin/m*" ]]; echo $? should print "0"
8461 * Additional operators:
8462 * || and && should work as -o and -a
8463 * =~ regexp match
8464 * Apart from the above, [[ expr ]] should work as [ expr ]
8465 */
8466
8467/* Keep these in proper order since it is searched via bsearch() */
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008468static const struct builtincmd builtintab[] = {
8469 { BUILTIN_SPEC_REG ".", dotcmd },
8470 { BUILTIN_SPEC_REG ":", truecmd },
8471#if ENABLE_ASH_BUILTIN_TEST
8472 { BUILTIN_REGULAR "[", testcmd },
Denis Vlasenko80591b02008-03-25 07:49:43 +00008473#if ENABLE_ASH_BASH_COMPAT
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008474 { BUILTIN_REGULAR "[[", testcmd },
8475#endif
Denis Vlasenko80591b02008-03-25 07:49:43 +00008476#endif
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008477#if ENABLE_ASH_ALIAS
8478 { BUILTIN_REG_ASSG "alias", aliascmd },
8479#endif
8480#if JOBS
8481 { BUILTIN_REGULAR "bg", fg_bgcmd },
8482#endif
8483 { BUILTIN_SPEC_REG "break", breakcmd },
8484 { BUILTIN_REGULAR "cd", cdcmd },
8485 { BUILTIN_NOSPEC "chdir", cdcmd },
8486#if ENABLE_ASH_CMDCMD
8487 { BUILTIN_REGULAR "command", commandcmd },
8488#endif
8489 { BUILTIN_SPEC_REG "continue", breakcmd },
8490#if ENABLE_ASH_BUILTIN_ECHO
8491 { BUILTIN_REGULAR "echo", echocmd },
8492#endif
8493 { BUILTIN_SPEC_REG "eval", evalcmd },
8494 { BUILTIN_SPEC_REG "exec", execcmd },
8495 { BUILTIN_SPEC_REG "exit", exitcmd },
8496 { BUILTIN_SPEC_REG_ASSG "export", exportcmd },
8497 { BUILTIN_REGULAR "false", falsecmd },
8498#if JOBS
8499 { BUILTIN_REGULAR "fg", fg_bgcmd },
8500#endif
8501#if ENABLE_ASH_GETOPTS
8502 { BUILTIN_REGULAR "getopts", getoptscmd },
8503#endif
8504 { BUILTIN_NOSPEC "hash", hashcmd },
8505#if !ENABLE_FEATURE_SH_EXTRA_QUIET
8506 { BUILTIN_NOSPEC "help", helpcmd },
8507#endif
8508#if JOBS
8509 { BUILTIN_REGULAR "jobs", jobscmd },
8510 { BUILTIN_REGULAR "kill", killcmd },
8511#endif
8512#if ENABLE_ASH_MATH_SUPPORT
8513 { BUILTIN_NOSPEC "let", letcmd },
8514#endif
8515 { BUILTIN_ASSIGN "local", localcmd },
8516 { BUILTIN_NOSPEC "pwd", pwdcmd },
8517 { BUILTIN_REGULAR "read", readcmd },
8518 { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
8519 { BUILTIN_SPEC_REG "return", returncmd },
8520 { BUILTIN_SPEC_REG "set", setcmd },
8521 { BUILTIN_SPEC_REG "shift", shiftcmd },
8522 { BUILTIN_SPEC_REG "source", dotcmd },
8523#if ENABLE_ASH_BUILTIN_TEST
8524 { BUILTIN_REGULAR "test", testcmd },
8525#endif
8526 { BUILTIN_SPEC_REG "times", timescmd },
8527 { BUILTIN_SPEC_REG "trap", trapcmd },
8528 { BUILTIN_REGULAR "true", truecmd },
8529 { BUILTIN_NOSPEC "type", typecmd },
8530 { BUILTIN_NOSPEC "ulimit", ulimitcmd },
8531 { BUILTIN_REGULAR "umask", umaskcmd },
8532#if ENABLE_ASH_ALIAS
8533 { BUILTIN_REGULAR "unalias", unaliascmd },
8534#endif
8535 { BUILTIN_SPEC_REG "unset", unsetcmd },
8536 { BUILTIN_REGULAR "wait", waitcmd },
8537};
8538
Denis Vlasenko80591b02008-03-25 07:49:43 +00008539/* Should match the above table! */
8540#define COMMANDCMD (builtintab + \
8541 2 + \
8542 1 * ENABLE_ASH_BUILTIN_TEST + \
8543 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
8544 1 * ENABLE_ASH_ALIAS + \
8545 1 * ENABLE_ASH_JOB_CONTROL + \
8546 3)
8547#define EXECCMD (builtintab + \
8548 2 + \
8549 1 * ENABLE_ASH_BUILTIN_TEST + \
8550 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
8551 1 * ENABLE_ASH_ALIAS + \
8552 1 * ENABLE_ASH_JOB_CONTROL + \
8553 3 + \
8554 1 * ENABLE_ASH_CMDCMD + \
8555 1 + \
8556 ENABLE_ASH_BUILTIN_ECHO + \
8557 1)
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008558
8559/*
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008560 * Search the table of builtin commands.
8561 */
8562static struct builtincmd *
8563find_builtin(const char *name)
8564{
8565 struct builtincmd *bp;
8566
8567 bp = bsearch(
Denis Vlasenko80b8b392007-06-25 10:55:35 +00008568 name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
Denis Vlasenko5651bfc2007-02-23 21:08:58 +00008569 pstrcmp
8570 );
8571 return bp;
8572}
8573
8574/*
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008575 * Execute a simple command.
8576 */
8577static int back_exitstatus; /* exit status of backquoted command */
8578static int
8579isassignment(const char *p)
Paul Foxc3850c82005-07-20 18:23:39 +00008580{
8581 const char *q = endofname(p);
8582 if (p == q)
8583 return 0;
8584 return *q == '=';
8585}
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008586static int
Denis Vlasenko68404f12008-03-17 09:00:54 +00008587bltincmd(int argc ATTRIBUTE_UNUSED, char **argv ATTRIBUTE_UNUSED)
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008588{
8589 /* Preserve exitstatus of a previous possible redirection
8590 * as POSIX mandates */
8591 return back_exitstatus;
8592}
Eric Andersenc470f442003-07-28 09:56:35 +00008593static void
8594evalcommand(union node *cmd, int flags)
8595{
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00008596 static const struct builtincmd null_bltin = {
8597 "\0\0", bltincmd /* why three NULs? */
Denis Vlasenko4fe15f32007-02-23 01:05:26 +00008598 };
Eric Andersenc470f442003-07-28 09:56:35 +00008599 struct stackmark smark;
8600 union node *argp;
8601 struct arglist arglist;
8602 struct arglist varlist;
8603 char **argv;
8604 int argc;
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00008605 const struct strlist *sp;
Eric Andersenc470f442003-07-28 09:56:35 +00008606 struct cmdentry cmdentry;
8607 struct job *jp;
8608 char *lastarg;
8609 const char *path;
8610 int spclbltin;
8611 int cmd_is_exec;
8612 int status;
8613 char **nargv;
Paul Foxc3850c82005-07-20 18:23:39 +00008614 struct builtincmd *bcmd;
8615 int pseudovarflag = 0;
Eric Andersenc470f442003-07-28 09:56:35 +00008616
8617 /* First expand the arguments. */
8618 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
8619 setstackmark(&smark);
8620 back_exitstatus = 0;
8621
8622 cmdentry.cmdtype = CMDBUILTIN;
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00008623 cmdentry.u.cmd = &null_bltin;
Eric Andersenc470f442003-07-28 09:56:35 +00008624 varlist.lastp = &varlist.list;
8625 *varlist.lastp = NULL;
8626 arglist.lastp = &arglist.list;
8627 *arglist.lastp = NULL;
8628
8629 argc = 0;
Denis Vlasenkob012b102007-02-19 22:43:01 +00008630 if (cmd->ncmd.args) {
Paul Foxc3850c82005-07-20 18:23:39 +00008631 bcmd = find_builtin(cmd->ncmd.args->narg.text);
8632 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
8633 }
8634
Eric Andersenc470f442003-07-28 09:56:35 +00008635 for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
8636 struct strlist **spp;
8637
8638 spp = arglist.lastp;
"Vladimir N. Oleynik"bef14d72005-09-05 13:25:11 +00008639 if (pseudovarflag && isassignment(argp->narg.text))
Paul Foxc3850c82005-07-20 18:23:39 +00008640 expandarg(argp, &arglist, EXP_VARTILDE);
8641 else
8642 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
8643
Eric Andersenc470f442003-07-28 09:56:35 +00008644 for (sp = *spp; sp; sp = sp->next)
8645 argc++;
8646 }
8647
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +00008648 argv = nargv = stalloc(sizeof(char *) * (argc + 1));
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008649 for (sp = arglist.list; sp; sp = sp->next) {
Eric Andersenc470f442003-07-28 09:56:35 +00008650 TRACE(("evalcommand arg: %s\n", sp->text));
8651 *nargv++ = sp->text;
8652 }
8653 *nargv = NULL;
8654
8655 lastarg = NULL;
8656 if (iflag && funcnest == 0 && argc > 0)
8657 lastarg = nargv[-1];
8658
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00008659 preverrout_fd = 2;
Eric Andersenc470f442003-07-28 09:56:35 +00008660 expredir(cmd->ncmd.redirect);
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00008661 status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
Eric Andersenc470f442003-07-28 09:56:35 +00008662
8663 path = vpath.text;
8664 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
8665 struct strlist **spp;
8666 char *p;
8667
8668 spp = varlist.lastp;
8669 expandarg(argp, &varlist, EXP_VARTILDE);
8670
8671 /*
8672 * Modify the command lookup path, if a PATH= assignment
8673 * is present
8674 */
8675 p = (*spp)->text;
8676 if (varequal(p, path))
8677 path = p;
8678 }
8679
8680 /* Print the command if xflag is set. */
8681 if (xflag) {
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00008682 int n;
8683 const char *p = " %s";
Eric Andersenc470f442003-07-28 09:56:35 +00008684
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00008685 p++;
Denis Vlasenko0de37e12007-10-17 11:08:53 +00008686 fdprintf(preverrout_fd, p, expandstr(ps4val()));
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00008687
8688 sp = varlist.list;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +00008689 for (n = 0; n < 2; n++) {
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00008690 while (sp) {
Denis Vlasenko0de37e12007-10-17 11:08:53 +00008691 fdprintf(preverrout_fd, p, sp->text);
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00008692 sp = sp->next;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +00008693 if (*p == '%') {
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00008694 p--;
8695 }
8696 }
8697 sp = arglist.list;
8698 }
Denis Vlasenko0e6f6612008-02-15 15:02:15 +00008699 safe_write(preverrout_fd, "\n", 1);
Eric Andersenc470f442003-07-28 09:56:35 +00008700 }
8701
8702 cmd_is_exec = 0;
8703 spclbltin = -1;
8704
8705 /* Now locate the command. */
8706 if (argc) {
8707 const char *oldpath;
8708 int cmd_flag = DO_ERR;
8709
8710 path += 5;
8711 oldpath = path;
8712 for (;;) {
8713 find_command(argv[0], &cmdentry, cmd_flag, path);
8714 if (cmdentry.cmdtype == CMDUNKNOWN) {
8715 status = 127;
Denis Vlasenkob012b102007-02-19 22:43:01 +00008716 flush_stderr();
Eric Andersenc470f442003-07-28 09:56:35 +00008717 goto bail;
8718 }
8719
8720 /* implement bltin and command here */
8721 if (cmdentry.cmdtype != CMDBUILTIN)
8722 break;
8723 if (spclbltin < 0)
8724 spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
8725 if (cmdentry.u.cmd == EXECCMD)
8726 cmd_is_exec++;
Denis Vlasenko131ae172007-02-18 13:00:19 +00008727#if ENABLE_ASH_CMDCMD
Eric Andersenc470f442003-07-28 09:56:35 +00008728 if (cmdentry.u.cmd == COMMANDCMD) {
Eric Andersenc470f442003-07-28 09:56:35 +00008729 path = oldpath;
8730 nargv = parse_command_args(argv, &path);
8731 if (!nargv)
8732 break;
8733 argc -= nargv - argv;
8734 argv = nargv;
8735 cmd_flag |= DO_NOFUNC;
8736 } else
8737#endif
8738 break;
8739 }
8740 }
8741
8742 if (status) {
8743 /* We have a redirection error. */
8744 if (spclbltin > 0)
Denis Vlasenkob012b102007-02-19 22:43:01 +00008745 raise_exception(EXERROR);
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008746 bail:
Eric Andersenc470f442003-07-28 09:56:35 +00008747 exitstatus = status;
8748 goto out;
8749 }
8750
8751 /* Execute the command. */
8752 switch (cmdentry.cmdtype) {
8753 default:
8754 /* Fork off a child process if necessary. */
8755 if (!(flags & EV_EXIT) || trap[0]) {
Denis Vlasenkob012b102007-02-19 22:43:01 +00008756 INT_OFF;
Denis Vlasenko68404f12008-03-17 09:00:54 +00008757 jp = makejob(/*cmd,*/ 1);
Eric Andersenc470f442003-07-28 09:56:35 +00008758 if (forkshell(jp, cmd, FORK_FG) != 0) {
8759 exitstatus = waitforjob(jp);
Denis Vlasenkob012b102007-02-19 22:43:01 +00008760 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00008761 break;
8762 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00008763 FORCE_INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00008764 }
8765 listsetvar(varlist.list, VEXPORT|VSTACK);
8766 shellexec(argv, path, cmdentry.u.index);
8767 /* NOTREACHED */
8768
8769 case CMDBUILTIN:
8770 cmdenviron = varlist.list;
8771 if (cmdenviron) {
8772 struct strlist *list = cmdenviron;
8773 int i = VNOSET;
8774 if (spclbltin > 0 || argc == 0) {
8775 i = 0;
8776 if (cmd_is_exec && argc > 1)
8777 i = VEXPORT;
8778 }
8779 listsetvar(list, i);
8780 }
8781 if (evalbltin(cmdentry.u.cmd, argc, argv)) {
8782 int exit_status;
Denis Vlasenko991a1da2008-02-10 19:02:53 +00008783 int i = exception;
Eric Andersenc470f442003-07-28 09:56:35 +00008784 if (i == EXEXIT)
8785 goto raise;
Eric Andersenc470f442003-07-28 09:56:35 +00008786 exit_status = 2;
Eric Andersenc470f442003-07-28 09:56:35 +00008787 if (i == EXINT)
Denis Vlasenko991a1da2008-02-10 19:02:53 +00008788 exit_status = 128 + SIGINT;
Eric Andersenc470f442003-07-28 09:56:35 +00008789 if (i == EXSIG)
Denis Vlasenko991a1da2008-02-10 19:02:53 +00008790 exit_status = 128 + pendingsig;
Eric Andersenc470f442003-07-28 09:56:35 +00008791 exitstatus = exit_status;
Eric Andersenc470f442003-07-28 09:56:35 +00008792 if (i == EXINT || spclbltin > 0) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008793 raise:
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008794 longjmp(exception_handler->loc, 1);
Eric Andersenc470f442003-07-28 09:56:35 +00008795 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00008796 FORCE_INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00008797 }
8798 break;
8799
8800 case CMDFUNCTION:
8801 listsetvar(varlist.list, 0);
8802 if (evalfun(cmdentry.u.func, argc, argv, flags))
8803 goto raise;
8804 break;
8805 }
8806
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008807 out:
Eric Andersenc470f442003-07-28 09:56:35 +00008808 popredir(cmd_is_exec);
8809 if (lastarg)
8810 /* dsl: I think this is intended to be used to support
8811 * '_' in 'vi' command mode during line editing...
8812 * However I implemented that within libedit itself.
8813 */
8814 setvar("_", lastarg, 0);
8815 popstackmark(&smark);
8816}
8817
8818static int
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008819evalbltin(const struct builtincmd *cmd, int argc, char **argv)
8820{
Eric Andersenc470f442003-07-28 09:56:35 +00008821 char *volatile savecmdname;
8822 struct jmploc *volatile savehandler;
8823 struct jmploc jmploc;
8824 int i;
8825
8826 savecmdname = commandname;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008827 i = setjmp(jmploc.loc);
8828 if (i)
Eric Andersenc470f442003-07-28 09:56:35 +00008829 goto cmddone;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008830 savehandler = exception_handler;
8831 exception_handler = &jmploc;
Eric Andersenc470f442003-07-28 09:56:35 +00008832 commandname = argv[0];
8833 argptr = argv + 1;
8834 optptr = NULL; /* initialize nextopt */
8835 exitstatus = (*cmd->builtin)(argc, argv);
Denis Vlasenkob012b102007-02-19 22:43:01 +00008836 flush_stdout_stderr();
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008837 cmddone:
Glenn L McGrath7b8765c2003-08-29 07:29:30 +00008838 exitstatus |= ferror(stdout);
Rob Landleyf296f0b2006-07-06 01:09:21 +00008839 clearerr(stdout);
Eric Andersenc470f442003-07-28 09:56:35 +00008840 commandname = savecmdname;
Denis Vlasenko991a1da2008-02-10 19:02:53 +00008841// exsig = 0;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00008842 exception_handler = savehandler;
Eric Andersenc470f442003-07-28 09:56:35 +00008843
8844 return i;
8845}
8846
Denis Vlasenkoaa744452007-02-23 01:04:22 +00008847static int
8848goodname(const char *p)
Glenn L McGrath16e45d72004-02-04 08:24:39 +00008849{
8850 return !*endofname(p);
8851}
8852
Denis Vlasenko5cedb752007-02-18 19:56:41 +00008853
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008854/*
8855 * Search for a command. This is called before we fork so that the
8856 * location of the command will be available in the parent as well as
Glenn L McGrath16e45d72004-02-04 08:24:39 +00008857 * the child. The check for "goodname" is an overly conservative
8858 * check that the name will not be subject to expansion.
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008859 */
Eric Andersenc470f442003-07-28 09:56:35 +00008860static void
8861prehash(union node *n)
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008862{
8863 struct cmdentry entry;
8864
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +00008865 if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
8866 find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
Glenn L McGrath50812ff2002-08-23 13:14:48 +00008867}
8868
Eric Andersencb57d552001-06-28 07:25:16 +00008869
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008870/* ============ Builtin commands
8871 *
8872 * Builtin commands whose functions are closely tied to evaluation
8873 * are implemented here.
Eric Andersencb57d552001-06-28 07:25:16 +00008874 */
8875
8876/*
Eric Andersencb57d552001-06-28 07:25:16 +00008877 * Handle break and continue commands. Break, continue, and return are
8878 * all handled by setting the evalskip flag. The evaluation routines
8879 * above all check this flag, and if it is set they start skipping
8880 * commands rather than executing them. The variable skipcount is
8881 * the number of loops to break/continue, or the number of function
8882 * levels to return. (The latter is always 1.) It should probably
8883 * be an error to break out of more loops than exist, but it isn't
8884 * in the standard shell so we don't make it one here.
8885 */
Eric Andersenc470f442003-07-28 09:56:35 +00008886static int
Denis Vlasenko68404f12008-03-17 09:00:54 +00008887breakcmd(int argc ATTRIBUTE_UNUSED, char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +00008888{
Denis Vlasenko68404f12008-03-17 09:00:54 +00008889 int n = argv[1] ? number(argv[1]) : 1;
Eric Andersencb57d552001-06-28 07:25:16 +00008890
Aaron Lehmann2aef3a62001-12-31 06:03:12 +00008891 if (n <= 0)
Denis Vlasenkob012b102007-02-19 22:43:01 +00008892 ash_msg_and_raise_error(illnum, argv[1]);
Eric Andersencb57d552001-06-28 07:25:16 +00008893 if (n > loopnest)
8894 n = loopnest;
8895 if (n > 0) {
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +00008896 evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
Eric Andersencb57d552001-06-28 07:25:16 +00008897 skipcount = n;
8898 }
8899 return 0;
8900}
8901
Eric Andersenc470f442003-07-28 09:56:35 +00008902
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008903/* ============ input.c
8904 *
Eric Andersen90898442003-08-06 11:20:52 +00008905 * This implements the input routines used by the parser.
Eric Andersencb57d552001-06-28 07:25:16 +00008906 */
Denis Vlasenko99eb8502007-02-23 21:09:49 +00008907
Eric Andersenc470f442003-07-28 09:56:35 +00008908#define EOF_NLEFT -99 /* value of parsenleft when EOF pushed back */
Eric Andersencb57d552001-06-28 07:25:16 +00008909
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008910enum {
8911 INPUT_PUSH_FILE = 1,
8912 INPUT_NOFILE_OK = 2,
8913};
Eric Andersencb57d552001-06-28 07:25:16 +00008914
Denis Vlasenko99eb8502007-02-23 21:09:49 +00008915static int plinno = 1; /* input line number */
8916/* number of characters left in input buffer */
8917static int parsenleft; /* copy of parsefile->nleft */
8918static int parselleft; /* copy of parsefile->lleft */
8919/* next character in input buffer */
8920static char *parsenextc; /* copy of parsefile->nextc */
8921
8922static int checkkwd;
8923/* values of checkkwd variable */
8924#define CHKALIAS 0x1
8925#define CHKKWD 0x2
8926#define CHKNL 0x4
8927
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008928static void
8929popstring(void)
Eric Andersenc470f442003-07-28 09:56:35 +00008930{
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008931 struct strpush *sp = parsefile->strpush;
Eric Andersenc470f442003-07-28 09:56:35 +00008932
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008933 INT_OFF;
Denis Vlasenko131ae172007-02-18 13:00:19 +00008934#if ENABLE_ASH_ALIAS
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008935 if (sp->ap) {
8936 if (parsenextc[-1] == ' ' || parsenextc[-1] == '\t') {
8937 checkkwd |= CHKALIAS;
Glenn L McGrath28939ad2004-07-21 10:20:19 +00008938 }
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008939 if (sp->string != sp->ap->val) {
8940 free(sp->string);
8941 }
8942 sp->ap->flag &= ~ALIASINUSE;
8943 if (sp->ap->flag & ALIASDEAD) {
8944 unalias(sp->ap->name);
8945 }
Glenn L McGrath28939ad2004-07-21 10:20:19 +00008946 }
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00008947#endif
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00008948 parsenextc = sp->prevstring;
8949 parsenleft = sp->prevnleft;
8950/*dprintf("*** calling popstring: restoring to '%s'\n", parsenextc);*/
8951 parsefile->strpush = sp->prev;
8952 if (sp != &(parsefile->basestrpush))
8953 free(sp);
8954 INT_ON;
8955}
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00008956
Denis Vlasenkoaa744452007-02-23 01:04:22 +00008957static int
8958preadfd(void)
Eric Andersencb57d552001-06-28 07:25:16 +00008959{
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00008960 int nr;
Eric Andersenc470f442003-07-28 09:56:35 +00008961 char *buf = parsefile->buf;
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00008962 parsenextc = buf;
8963
Denis Vlasenko38f63192007-01-22 09:03:07 +00008964#if ENABLE_FEATURE_EDITING
Denis Vlasenko85c24712008-03-17 09:04:04 +00008965 retry:
Eric Andersenc470f442003-07-28 09:56:35 +00008966 if (!iflag || parsefile->fd)
Denis Vlasenkoe376d452008-02-20 22:23:24 +00008967 nr = nonblock_safe_read(parsefile->fd, buf, BUFSIZ - 1);
Eric Andersenc470f442003-07-28 09:56:35 +00008968 else {
Denis Vlasenko38f63192007-01-22 09:03:07 +00008969#if ENABLE_FEATURE_TAB_COMPLETION
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00008970 line_input_state->path_lookup = pathval();
Eric Andersen4a79c0e2004-09-08 10:01:07 +00008971#endif
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00008972 nr = read_line_input(cmdedit_prompt, buf, BUFSIZ, line_input_state);
8973 if (nr == 0) {
8974 /* Ctrl+C pressed */
8975 if (trap[SIGINT]) {
Glenn L McGrath16e45d72004-02-04 08:24:39 +00008976 buf[0] = '\n';
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00008977 buf[1] = '\0';
Glenn L McGrath16e45d72004-02-04 08:24:39 +00008978 raise(SIGINT);
8979 return 1;
8980 }
Eric Andersenc470f442003-07-28 09:56:35 +00008981 goto retry;
8982 }
Denis Vlasenko8e1c7152007-01-22 07:21:38 +00008983 if (nr < 0 && errno == 0) {
Denis Vlasenko9cb220b2007-12-09 10:03:28 +00008984 /* Ctrl+D pressed */
Eric Andersenc470f442003-07-28 09:56:35 +00008985 nr = 0;
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00008986 }
Eric Andersencb57d552001-06-28 07:25:16 +00008987 }
8988#else
Denis Vlasenkoe376d452008-02-20 22:23:24 +00008989 nr = nonblock_safe_read(parsefile->fd, buf, BUFSIZ - 1);
Eric Andersencb57d552001-06-28 07:25:16 +00008990#endif
8991
Denis Vlasenkoe376d452008-02-20 22:23:24 +00008992#if 0
8993/* nonblock_safe_read() handles this problem */
Eric Andersencb57d552001-06-28 07:25:16 +00008994 if (nr < 0) {
Eric Andersencb57d552001-06-28 07:25:16 +00008995 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
Denis Vlasenkod37f2222007-08-19 13:42:08 +00008996 int flags = fcntl(0, F_GETFL);
Denis Vlasenko9cb220b2007-12-09 10:03:28 +00008997 if (flags >= 0 && (flags & O_NONBLOCK)) {
8998 flags &= ~O_NONBLOCK;
Eric Andersencb57d552001-06-28 07:25:16 +00008999 if (fcntl(0, F_SETFL, flags) >= 0) {
9000 out2str("sh: turning off NDELAY mode\n");
9001 goto retry;
9002 }
9003 }
9004 }
9005 }
Denis Vlasenkoe376d452008-02-20 22:23:24 +00009006#endif
Eric Andersencb57d552001-06-28 07:25:16 +00009007 return nr;
9008}
9009
9010/*
9011 * Refill the input buffer and return the next input character:
9012 *
9013 * 1) If a string was pushed back on the input, pop it;
9014 * 2) If an EOF was pushed back (parsenleft == EOF_NLEFT) or we are reading
9015 * from a string so we can't refill the buffer, return EOF.
9016 * 3) If the is more stuff in this buffer, use it else call read to fill it.
9017 * 4) Process input up to the next newline, deleting nul characters.
9018 */
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009019static int
Eric Andersenc470f442003-07-28 09:56:35 +00009020preadbuffer(void)
Eric Andersencb57d552001-06-28 07:25:16 +00009021{
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009022 char *q;
Eric Andersencb57d552001-06-28 07:25:16 +00009023 int more;
9024 char savec;
9025
9026 while (parsefile->strpush) {
Denis Vlasenko131ae172007-02-18 13:00:19 +00009027#if ENABLE_ASH_ALIAS
Eric Andersen2870d962001-07-02 17:27:21 +00009028 if (parsenleft == -1 && parsefile->strpush->ap &&
9029 parsenextc[-1] != ' ' && parsenextc[-1] != '\t') {
Eric Andersencb57d552001-06-28 07:25:16 +00009030 return PEOA;
9031 }
Eric Andersen2870d962001-07-02 17:27:21 +00009032#endif
Eric Andersencb57d552001-06-28 07:25:16 +00009033 popstring();
9034 if (--parsenleft >= 0)
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00009035 return signed_char2int(*parsenextc++);
Eric Andersencb57d552001-06-28 07:25:16 +00009036 }
9037 if (parsenleft == EOF_NLEFT || parsefile->buf == NULL)
9038 return PEOF;
Denis Vlasenkob012b102007-02-19 22:43:01 +00009039 flush_stdout_stderr();
Eric Andersencb57d552001-06-28 07:25:16 +00009040
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009041 more = parselleft;
9042 if (more <= 0) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009043 again:
9044 more = preadfd();
9045 if (more <= 0) {
Eric Andersencb57d552001-06-28 07:25:16 +00009046 parselleft = parsenleft = EOF_NLEFT;
9047 return PEOF;
9048 }
9049 }
9050
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009051 q = parsenextc;
Eric Andersencb57d552001-06-28 07:25:16 +00009052
9053 /* delete nul characters */
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009054 for (;;) {
9055 int c;
Eric Andersencb57d552001-06-28 07:25:16 +00009056
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009057 more--;
9058 c = *q;
Eric Andersenc470f442003-07-28 09:56:35 +00009059
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009060 if (!c)
9061 memmove(q, q + 1, more);
9062 else {
9063 q++;
9064 if (c == '\n') {
9065 parsenleft = q - parsenextc - 1;
9066 break;
9067 }
Eric Andersencb57d552001-06-28 07:25:16 +00009068 }
9069
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009070 if (more <= 0) {
Eric Andersencb57d552001-06-28 07:25:16 +00009071 parsenleft = q - parsenextc - 1;
9072 if (parsenleft < 0)
9073 goto again;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009074 break;
Eric Andersencb57d552001-06-28 07:25:16 +00009075 }
9076 }
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009077 parselleft = more;
Eric Andersencb57d552001-06-28 07:25:16 +00009078
9079 savec = *q;
9080 *q = '\0';
9081
9082 if (vflag) {
9083 out2str(parsenextc);
Eric Andersencb57d552001-06-28 07:25:16 +00009084 }
9085
9086 *q = savec;
9087
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00009088 return signed_char2int(*parsenextc++);
Eric Andersencb57d552001-06-28 07:25:16 +00009089}
9090
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00009091#define pgetc_as_macro() (--parsenleft >= 0? signed_char2int(*parsenextc++) : preadbuffer())
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009092static int
9093pgetc(void)
9094{
9095 return pgetc_as_macro();
9096}
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00009097
9098#if ENABLE_ASH_OPTIMIZE_FOR_SIZE
9099#define pgetc_macro() pgetc()
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009100#else
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00009101#define pgetc_macro() pgetc_as_macro()
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009102#endif
9103
9104/*
9105 * Same as pgetc(), but ignores PEOA.
9106 */
9107#if ENABLE_ASH_ALIAS
9108static int
9109pgetc2(void)
9110{
9111 int c;
9112
9113 do {
9114 c = pgetc_macro();
9115 } while (c == PEOA);
9116 return c;
9117}
9118#else
9119static int
9120pgetc2(void)
9121{
9122 return pgetc_macro();
9123}
9124#endif
9125
9126/*
9127 * Read a line from the script.
9128 */
9129static char *
9130pfgets(char *line, int len)
9131{
9132 char *p = line;
9133 int nleft = len;
9134 int c;
9135
9136 while (--nleft > 0) {
9137 c = pgetc2();
9138 if (c == PEOF) {
9139 if (p == line)
9140 return NULL;
9141 break;
9142 }
9143 *p++ = c;
9144 if (c == '\n')
9145 break;
9146 }
9147 *p = '\0';
9148 return line;
9149}
9150
Eric Andersenc470f442003-07-28 09:56:35 +00009151/*
9152 * Undo the last call to pgetc. Only one character may be pushed back.
9153 * PEOF may be pushed back.
9154 */
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009155static void
Eric Andersenc470f442003-07-28 09:56:35 +00009156pungetc(void)
9157{
9158 parsenleft++;
9159 parsenextc--;
9160}
Eric Andersencb57d552001-06-28 07:25:16 +00009161
9162/*
9163 * Push a string back onto the input at this current parsefile level.
9164 * We handle aliases this way.
9165 */
Denis Vlasenko85c24712008-03-17 09:04:04 +00009166#if !ENABLE_ASH_ALIAS
9167#define pushstring(s, ap) pushstring(s)
9168#endif
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009169static void
Denis Vlasenko85c24712008-03-17 09:04:04 +00009170pushstring(char *s, struct alias *ap)
Eric Andersen2870d962001-07-02 17:27:21 +00009171{
Eric Andersencb57d552001-06-28 07:25:16 +00009172 struct strpush *sp;
Eric Andersenc470f442003-07-28 09:56:35 +00009173 size_t len;
Eric Andersencb57d552001-06-28 07:25:16 +00009174
Eric Andersenc470f442003-07-28 09:56:35 +00009175 len = strlen(s);
Denis Vlasenkob012b102007-02-19 22:43:01 +00009176 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +00009177/*dprintf("*** calling pushstring: %s, %d\n", s, len);*/
9178 if (parsefile->strpush) {
Denis Vlasenko6aa74fc2008-02-21 04:35:14 +00009179 sp = ckzalloc(sizeof(struct strpush));
Eric Andersencb57d552001-06-28 07:25:16 +00009180 sp->prev = parsefile->strpush;
9181 parsefile->strpush = sp;
9182 } else
9183 sp = parsefile->strpush = &(parsefile->basestrpush);
9184 sp->prevstring = parsenextc;
9185 sp->prevnleft = parsenleft;
Denis Vlasenko131ae172007-02-18 13:00:19 +00009186#if ENABLE_ASH_ALIAS
Denis Vlasenko85c24712008-03-17 09:04:04 +00009187 sp->ap = ap;
Eric Andersencb57d552001-06-28 07:25:16 +00009188 if (ap) {
Denis Vlasenko85c24712008-03-17 09:04:04 +00009189 ap->flag |= ALIASINUSE;
Eric Andersencb57d552001-06-28 07:25:16 +00009190 sp->string = s;
9191 }
Eric Andersen2870d962001-07-02 17:27:21 +00009192#endif
Eric Andersencb57d552001-06-28 07:25:16 +00009193 parsenextc = s;
9194 parsenleft = len;
Denis Vlasenkob012b102007-02-19 22:43:01 +00009195 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00009196}
9197
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009198/*
9199 * To handle the "." command, a stack of input files is used. Pushfile
9200 * adds a new entry to the stack and popfile restores the previous level.
9201 */
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009202static void
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009203pushfile(void)
Eric Andersenc470f442003-07-28 09:56:35 +00009204{
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009205 struct parsefile *pf;
9206
9207 parsefile->nleft = parsenleft;
9208 parsefile->lleft = parselleft;
9209 parsefile->nextc = parsenextc;
9210 parsefile->linno = plinno;
Denis Vlasenko597906c2008-02-20 16:38:54 +00009211 pf = ckzalloc(sizeof(*pf));
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009212 pf->prev = parsefile;
9213 pf->fd = -1;
Denis Vlasenko597906c2008-02-20 16:38:54 +00009214 /*pf->strpush = NULL; - ckzalloc did it */
9215 /*pf->basestrpush.prev = NULL;*/
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009216 parsefile = pf;
9217}
9218
9219static void
9220popfile(void)
9221{
9222 struct parsefile *pf = parsefile;
Eric Andersenc470f442003-07-28 09:56:35 +00009223
Denis Vlasenkob012b102007-02-19 22:43:01 +00009224 INT_OFF;
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009225 if (pf->fd >= 0)
9226 close(pf->fd);
Denis Vlasenko60818682007-09-28 22:07:23 +00009227 free(pf->buf);
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009228 while (pf->strpush)
9229 popstring();
9230 parsefile = pf->prev;
9231 free(pf);
9232 parsenleft = parsefile->nleft;
9233 parselleft = parsefile->lleft;
9234 parsenextc = parsefile->nextc;
9235 plinno = parsefile->linno;
Denis Vlasenkob012b102007-02-19 22:43:01 +00009236 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +00009237}
9238
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009239/*
9240 * Return to top level.
9241 */
9242static void
9243popallfiles(void)
9244{
9245 while (parsefile != &basepf)
9246 popfile();
9247}
9248
9249/*
9250 * Close the file(s) that the shell is reading commands from. Called
9251 * after a fork is done.
9252 */
9253static void
9254closescript(void)
9255{
9256 popallfiles();
9257 if (parsefile->fd > 0) {
9258 close(parsefile->fd);
9259 parsefile->fd = 0;
9260 }
9261}
9262
9263/*
9264 * Like setinputfile, but takes an open file descriptor. Call this with
9265 * interrupts off.
9266 */
9267static void
9268setinputfd(int fd, int push)
9269{
Denis Vlasenko96e1b382007-09-30 23:50:48 +00009270 close_on_exec_on(fd);
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009271 if (push) {
9272 pushfile();
9273 parsefile->buf = 0;
9274 }
9275 parsefile->fd = fd;
9276 if (parsefile->buf == NULL)
9277 parsefile->buf = ckmalloc(IBUFSIZ);
9278 parselleft = parsenleft = 0;
9279 plinno = 1;
9280}
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009281
Eric Andersenc470f442003-07-28 09:56:35 +00009282/*
9283 * Set the input to take input from a file. If push is set, push the
9284 * old input onto the stack first.
9285 */
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009286static int
9287setinputfile(const char *fname, int flags)
Eric Andersenc470f442003-07-28 09:56:35 +00009288{
9289 int fd;
9290 int fd2;
9291
Denis Vlasenkob012b102007-02-19 22:43:01 +00009292 INT_OFF;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009293 fd = open(fname, O_RDONLY);
9294 if (fd < 0) {
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009295 if (flags & INPUT_NOFILE_OK)
9296 goto out;
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00009297 ash_msg_and_raise_error("can't open %s", fname);
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009298 }
Eric Andersenc470f442003-07-28 09:56:35 +00009299 if (fd < 10) {
9300 fd2 = copyfd(fd, 10);
9301 close(fd);
9302 if (fd2 < 0)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00009303 ash_msg_and_raise_error("out of file descriptors");
Eric Andersenc470f442003-07-28 09:56:35 +00009304 fd = fd2;
9305 }
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009306 setinputfd(fd, flags & INPUT_PUSH_FILE);
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009307 out:
Denis Vlasenkob012b102007-02-19 22:43:01 +00009308 INT_ON;
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +00009309 return fd;
Eric Andersenc470f442003-07-28 09:56:35 +00009310}
9311
Eric Andersencb57d552001-06-28 07:25:16 +00009312/*
9313 * Like setinputfile, but takes input from a string.
9314 */
Eric Andersenc470f442003-07-28 09:56:35 +00009315static void
9316setinputstring(char *string)
Eric Andersen62483552001-07-10 06:09:16 +00009317{
Denis Vlasenkob012b102007-02-19 22:43:01 +00009318 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +00009319 pushfile();
9320 parsenextc = string;
9321 parsenleft = strlen(string);
9322 parsefile->buf = NULL;
9323 plinno = 1;
Denis Vlasenkob012b102007-02-19 22:43:01 +00009324 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00009325}
9326
9327
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00009328/* ============ mail.c
9329 *
9330 * Routines to check for mail.
Eric Andersencb57d552001-06-28 07:25:16 +00009331 */
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00009332
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00009333#if ENABLE_ASH_MAIL
Eric Andersencb57d552001-06-28 07:25:16 +00009334
Eric Andersencb57d552001-06-28 07:25:16 +00009335#define MAXMBOXES 10
9336
Eric Andersenc470f442003-07-28 09:56:35 +00009337/* times of mailboxes */
9338static time_t mailtime[MAXMBOXES];
9339/* Set if MAIL or MAILPATH is changed. */
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +00009340static smallint mail_var_path_changed;
Eric Andersencb57d552001-06-28 07:25:16 +00009341
Eric Andersencb57d552001-06-28 07:25:16 +00009342/*
Eric Andersenc470f442003-07-28 09:56:35 +00009343 * Print appropriate message(s) if mail has arrived.
9344 * If mail_var_path_changed is set,
9345 * then the value of MAIL has mail_var_path_changed,
9346 * so we just update the values.
Eric Andersencb57d552001-06-28 07:25:16 +00009347 */
Eric Andersenc470f442003-07-28 09:56:35 +00009348static void
9349chkmail(void)
Eric Andersencb57d552001-06-28 07:25:16 +00009350{
Eric Andersencb57d552001-06-28 07:25:16 +00009351 const char *mpath;
9352 char *p;
9353 char *q;
Eric Andersenc470f442003-07-28 09:56:35 +00009354 time_t *mtp;
Eric Andersencb57d552001-06-28 07:25:16 +00009355 struct stackmark smark;
9356 struct stat statb;
9357
Eric Andersencb57d552001-06-28 07:25:16 +00009358 setstackmark(&smark);
Eric Andersenc470f442003-07-28 09:56:35 +00009359 mpath = mpathset() ? mpathval() : mailval();
9360 for (mtp = mailtime; mtp < mailtime + MAXMBOXES; mtp++) {
Eric Andersencb57d552001-06-28 07:25:16 +00009361 p = padvance(&mpath, nullstr);
9362 if (p == NULL)
9363 break;
9364 if (*p == '\0')
9365 continue;
Denis Vlasenkof7d56652008-03-25 05:51:41 +00009366 for (q = p; *q; q++)
9367 continue;
Denis Vlasenkoa7189f02006-11-17 20:29:00 +00009368#if DEBUG
Eric Andersencb57d552001-06-28 07:25:16 +00009369 if (q[-1] != '/')
9370 abort();
9371#endif
Eric Andersenc470f442003-07-28 09:56:35 +00009372 q[-1] = '\0'; /* delete trailing '/' */
9373 if (stat(p, &statb) < 0) {
9374 *mtp = 0;
9375 continue;
Eric Andersencb57d552001-06-28 07:25:16 +00009376 }
Eric Andersenc470f442003-07-28 09:56:35 +00009377 if (!mail_var_path_changed && statb.st_mtime != *mtp) {
9378 fprintf(
9379 stderr, snlfmt,
9380 pathopt ? pathopt : "you have mail"
9381 );
9382 }
9383 *mtp = statb.st_mtime;
Eric Andersencb57d552001-06-28 07:25:16 +00009384 }
Eric Andersenc470f442003-07-28 09:56:35 +00009385 mail_var_path_changed = 0;
Eric Andersencb57d552001-06-28 07:25:16 +00009386 popstackmark(&smark);
9387}
Eric Andersencb57d552001-06-28 07:25:16 +00009388
Eric Andersenc470f442003-07-28 09:56:35 +00009389static void
Denis Vlasenko68404f12008-03-17 09:00:54 +00009390changemail(const char *val ATTRIBUTE_UNUSED)
Eric Andersenc470f442003-07-28 09:56:35 +00009391{
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +00009392 mail_var_path_changed = 1;
Eric Andersenc470f442003-07-28 09:56:35 +00009393}
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00009394
Denis Vlasenko131ae172007-02-18 13:00:19 +00009395#endif /* ASH_MAIL */
Eric Andersenc470f442003-07-28 09:56:35 +00009396
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00009397
9398/* ============ ??? */
9399
Eric Andersencb57d552001-06-28 07:25:16 +00009400/*
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009401 * Set the shell parameters.
Eric Andersencb57d552001-06-28 07:25:16 +00009402 */
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009403static void
9404setparam(char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +00009405{
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009406 char **newparam;
9407 char **ap;
9408 int nparam;
Eric Andersencb57d552001-06-28 07:25:16 +00009409
Denis Vlasenkof7d56652008-03-25 05:51:41 +00009410 for (nparam = 0; argv[nparam]; nparam++)
9411 continue;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009412 ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
9413 while (*argv) {
9414 *ap++ = ckstrdup(*argv++);
Eric Andersencb57d552001-06-28 07:25:16 +00009415 }
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009416 *ap = NULL;
9417 freeparam(&shellparam);
Denis Vlasenko01631112007-12-16 17:20:38 +00009418 shellparam.malloced = 1;
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009419 shellparam.nparam = nparam;
9420 shellparam.p = newparam;
9421#if ENABLE_ASH_GETOPTS
9422 shellparam.optind = 1;
9423 shellparam.optoff = -1;
9424#endif
Eric Andersencb57d552001-06-28 07:25:16 +00009425}
9426
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00009427/*
Denis Vlasenko0dec6de2007-02-23 21:10:47 +00009428 * Process shell options. The global variable argptr contains a pointer
9429 * to the argument list; we advance it past the options.
Denis Vlasenko94e87bc2008-02-14 16:51:58 +00009430 *
9431 * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
9432 * For a non-interactive shell, an error condition encountered
9433 * by a special built-in ... shall cause the shell to write a diagnostic message
9434 * to standard error and exit as shown in the following table:
Denis Vlasenko56244732008-02-17 15:14:04 +00009435 * Error Special Built-In
Denis Vlasenko94e87bc2008-02-14 16:51:58 +00009436 * ...
9437 * Utility syntax error (option or operand error) Shall exit
9438 * ...
9439 * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
9440 * we see that bash does not do that (set "finishes" with error code 1 instead,
9441 * and shell continues), and people rely on this behavior!
9442 * Testcase:
9443 * set -o barfoo 2>/dev/null
9444 * echo $?
9445 *
9446 * Oh well. Let's mimic that.
Denis Vlasenkobc54cff2007-02-23 01:05:52 +00009447 */
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009448static int
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009449minus_o(char *name, int val)
Eric Andersen62483552001-07-10 06:09:16 +00009450{
9451 int i;
9452
Denis Vlasenkoa624c112007-02-19 22:45:43 +00009453 if (name) {
9454 for (i = 0; i < NOPTS; i++) {
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00009455 if (strcmp(name, optnames(i)) == 0) {
Eric Andersenc470f442003-07-28 09:56:35 +00009456 optlist[i] = val;
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009457 return 0;
Eric Andersen62483552001-07-10 06:09:16 +00009458 }
Denis Vlasenkoa624c112007-02-19 22:45:43 +00009459 }
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009460 ash_msg("illegal option -o %s", name);
9461 return 1;
Eric Andersen62483552001-07-10 06:09:16 +00009462 }
Denis Vlasenkoa624c112007-02-19 22:45:43 +00009463 out1str("Current option settings\n");
9464 for (i = 0; i < NOPTS; i++)
9465 out1fmt("%-16s%s\n", optnames(i),
9466 optlist[i] ? "on" : "off");
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009467 return 0;
Eric Andersen62483552001-07-10 06:09:16 +00009468}
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009469static void
9470setoption(int flag, int val)
9471{
9472 int i;
9473
9474 for (i = 0; i < NOPTS; i++) {
9475 if (optletters(i) == flag) {
9476 optlist[i] = val;
9477 return;
9478 }
9479 }
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00009480 ash_msg_and_raise_error("illegal option -%c", flag);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009481 /* NOTREACHED */
9482}
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009483static int
Eric Andersenc470f442003-07-28 09:56:35 +00009484options(int cmdline)
Eric Andersencb57d552001-06-28 07:25:16 +00009485{
9486 char *p;
9487 int val;
9488 int c;
9489
9490 if (cmdline)
9491 minusc = NULL;
9492 while ((p = *argptr) != NULL) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009493 c = *p++;
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +00009494 if (c != '-' && c != '+')
9495 break;
9496 argptr++;
9497 val = 0; /* val = 0 if c == '+' */
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009498 if (c == '-') {
Eric Andersencb57d552001-06-28 07:25:16 +00009499 val = 1;
Denis Vlasenko9f739442006-12-16 23:49:13 +00009500 if (p[0] == '\0' || LONE_DASH(p)) {
Eric Andersen2870d962001-07-02 17:27:21 +00009501 if (!cmdline) {
9502 /* "-" means turn off -x and -v */
9503 if (p[0] == '\0')
9504 xflag = vflag = 0;
9505 /* "--" means reset params */
9506 else if (*argptr == NULL)
Eric Andersencb57d552001-06-28 07:25:16 +00009507 setparam(argptr);
Eric Andersen2870d962001-07-02 17:27:21 +00009508 }
Eric Andersenc470f442003-07-28 09:56:35 +00009509 break; /* "-" or "--" terminates options */
Eric Andersencb57d552001-06-28 07:25:16 +00009510 }
Eric Andersencb57d552001-06-28 07:25:16 +00009511 }
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +00009512 /* first char was + or - */
Eric Andersencb57d552001-06-28 07:25:16 +00009513 while ((c = *p++) != '\0') {
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +00009514 /* bash 3.2 indeed handles -c CMD and +c CMD the same */
Eric Andersencb57d552001-06-28 07:25:16 +00009515 if (c == 'c' && cmdline) {
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +00009516 minusc = p; /* command is after shell args */
Eric Andersencb57d552001-06-28 07:25:16 +00009517 } else if (c == 'o') {
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009518 if (minus_o(*argptr, val)) {
9519 /* it already printed err message */
9520 return 1; /* error */
9521 }
Eric Andersencb57d552001-06-28 07:25:16 +00009522 if (*argptr)
9523 argptr++;
Denis Vlasenko8fdc4b72007-07-14 11:33:10 +00009524 } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
9525 isloginsh = 1;
9526 /* bash does not accept +-login, we also won't */
9527 } else if (cmdline && val && (c == '-')) { /* long options */
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00009528 if (strcmp(p, "login") == 0)
Robert Griebl64f70cc2002-05-14 23:22:06 +00009529 isloginsh = 1;
9530 break;
Eric Andersencb57d552001-06-28 07:25:16 +00009531 } else {
9532 setoption(c, val);
9533 }
9534 }
9535 }
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009536 return 0;
Eric Andersencb57d552001-06-28 07:25:16 +00009537}
9538
Eric Andersencb57d552001-06-28 07:25:16 +00009539/*
Eric Andersencb57d552001-06-28 07:25:16 +00009540 * The shift builtin command.
9541 */
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009542static int
Denis Vlasenko68404f12008-03-17 09:00:54 +00009543shiftcmd(int argc ATTRIBUTE_UNUSED, char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +00009544{
9545 int n;
9546 char **ap1, **ap2;
9547
9548 n = 1;
Denis Vlasenko68404f12008-03-17 09:00:54 +00009549 if (argv[1])
Eric Andersencb57d552001-06-28 07:25:16 +00009550 n = number(argv[1]);
9551 if (n > shellparam.nparam)
Denis Vlasenkob012b102007-02-19 22:43:01 +00009552 ash_msg_and_raise_error("can't shift that many");
9553 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +00009554 shellparam.nparam -= n;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00009555 for (ap1 = shellparam.p; --n >= 0; ap1++) {
Denis Vlasenko01631112007-12-16 17:20:38 +00009556 if (shellparam.malloced)
Denis Vlasenkob012b102007-02-19 22:43:01 +00009557 free(*ap1);
Eric Andersencb57d552001-06-28 07:25:16 +00009558 }
9559 ap2 = shellparam.p;
Denis Vlasenkof7d56652008-03-25 05:51:41 +00009560 while ((*ap2++ = *ap1++) != NULL)
9561 continue;
Denis Vlasenko131ae172007-02-18 13:00:19 +00009562#if ENABLE_ASH_GETOPTS
Eric Andersencb57d552001-06-28 07:25:16 +00009563 shellparam.optind = 1;
9564 shellparam.optoff = -1;
Eric Andersenc470f442003-07-28 09:56:35 +00009565#endif
Denis Vlasenkob012b102007-02-19 22:43:01 +00009566 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +00009567 return 0;
9568}
9569
Eric Andersencb57d552001-06-28 07:25:16 +00009570/*
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009571 * POSIX requires that 'set' (but not export or readonly) output the
9572 * variables in lexicographic order - by the locale's collating order (sigh).
9573 * Maybe we could keep them in an ordered balanced binary tree
9574 * instead of hashed lists.
9575 * For now just roll 'em through qsort for printing...
9576 */
9577static int
9578showvars(const char *sep_prefix, int on, int off)
9579{
9580 const char *sep;
9581 char **ep, **epend;
9582
9583 ep = listvars(on, off, &epend);
9584 qsort(ep, epend - ep, sizeof(char *), vpcmp);
9585
Denis Vlasenko2de3d9f2007-02-23 21:10:23 +00009586 sep = *sep_prefix ? " " : sep_prefix;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009587
9588 for (; ep < epend; ep++) {
9589 const char *p;
9590 const char *q;
9591
9592 p = strchrnul(*ep, '=');
9593 q = nullstr;
9594 if (*p)
9595 q = single_quote(++p);
9596 out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
9597 }
9598 return 0;
9599}
9600
9601/*
Eric Andersencb57d552001-06-28 07:25:16 +00009602 * The set command builtin.
9603 */
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009604static int
Denis Vlasenko68404f12008-03-17 09:00:54 +00009605setcmd(int argc ATTRIBUTE_UNUSED, char **argv ATTRIBUTE_UNUSED)
Eric Andersencb57d552001-06-28 07:25:16 +00009606{
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009607 int retval;
9608
Denis Vlasenko68404f12008-03-17 09:00:54 +00009609 if (!argv[1])
Eric Andersenc470f442003-07-28 09:56:35 +00009610 return showvars(nullstr, 0, VUNSET);
Denis Vlasenkob012b102007-02-19 22:43:01 +00009611 INT_OFF;
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009612 retval = 1;
9613 if (!options(0)) { /* if no parse error... */
9614 retval = 0;
9615 optschanged();
9616 if (*argptr != NULL) {
9617 setparam(argptr);
9618 }
Eric Andersencb57d552001-06-28 07:25:16 +00009619 }
Denis Vlasenkob012b102007-02-19 22:43:01 +00009620 INT_ON;
Denis Vlasenko28bf6712008-02-14 15:01:47 +00009621 return retval;
Eric Andersencb57d552001-06-28 07:25:16 +00009622}
9623
Denis Vlasenko131ae172007-02-18 13:00:19 +00009624#if ENABLE_ASH_RANDOM_SUPPORT
Eric Andersenef02f822004-03-11 13:34:24 +00009625/* Roughly copied from bash.. */
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +00009626static void
9627change_random(const char *value)
Eric Andersenef02f822004-03-11 13:34:24 +00009628{
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +00009629 if (value == NULL) {
Eric Andersen16767e22004-03-16 05:14:10 +00009630 /* "get", generate */
9631 char buf[16];
9632
9633 rseed = rseed * 1103515245 + 12345;
9634 sprintf(buf, "%d", (unsigned int)((rseed & 32767)));
9635 /* set without recursion */
9636 setvar(vrandom.text, buf, VNOFUNC);
9637 vrandom.flags &= ~VNOFUNC;
9638 } else {
9639 /* set/reset */
9640 rseed = strtoul(value, (char **)NULL, 10);
9641 }
Eric Andersenef02f822004-03-11 13:34:24 +00009642}
Eric Andersen16767e22004-03-16 05:14:10 +00009643#endif
9644
Denis Vlasenko131ae172007-02-18 13:00:19 +00009645#if ENABLE_ASH_GETOPTS
Eric Andersencb57d552001-06-28 07:25:16 +00009646static int
Eric Andersenc470f442003-07-28 09:56:35 +00009647getopts(char *optstr, char *optvar, char **optfirst, int *param_optind, int *optoff)
Eric Andersencb57d552001-06-28 07:25:16 +00009648{
9649 char *p, *q;
9650 char c = '?';
9651 int done = 0;
9652 int err = 0;
Eric Andersena48b0a32003-10-22 10:56:47 +00009653 char s[12];
9654 char **optnext;
Eric Andersencb57d552001-06-28 07:25:16 +00009655
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +00009656 if (*param_optind < 1)
Eric Andersena48b0a32003-10-22 10:56:47 +00009657 return 1;
9658 optnext = optfirst + *param_optind - 1;
9659
9660 if (*param_optind <= 1 || *optoff < 0 || strlen(optnext[-1]) < *optoff)
Eric Andersencb57d552001-06-28 07:25:16 +00009661 p = NULL;
9662 else
Eric Andersena48b0a32003-10-22 10:56:47 +00009663 p = optnext[-1] + *optoff;
Eric Andersencb57d552001-06-28 07:25:16 +00009664 if (p == NULL || *p == '\0') {
9665 /* Current word is done, advance */
Eric Andersencb57d552001-06-28 07:25:16 +00009666 p = *optnext;
9667 if (p == NULL || *p != '-' || *++p == '\0') {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009668 atend:
Eric Andersencb57d552001-06-28 07:25:16 +00009669 p = NULL;
9670 done = 1;
9671 goto out;
9672 }
9673 optnext++;
Denis Vlasenko9f739442006-12-16 23:49:13 +00009674 if (LONE_DASH(p)) /* check for "--" */
Eric Andersencb57d552001-06-28 07:25:16 +00009675 goto atend;
9676 }
9677
9678 c = *p++;
Eric Andersenc470f442003-07-28 09:56:35 +00009679 for (q = optstr; *q != c; ) {
Eric Andersencb57d552001-06-28 07:25:16 +00009680 if (*q == '\0') {
9681 if (optstr[0] == ':') {
9682 s[0] = c;
9683 s[1] = '\0';
9684 err |= setvarsafe("OPTARG", s, 0);
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00009685 } else {
Eric Andersenc470f442003-07-28 09:56:35 +00009686 fprintf(stderr, "Illegal option -%c\n", c);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009687 unsetvar("OPTARG");
Eric Andersencb57d552001-06-28 07:25:16 +00009688 }
9689 c = '?';
Eric Andersenc470f442003-07-28 09:56:35 +00009690 goto out;
Eric Andersencb57d552001-06-28 07:25:16 +00009691 }
9692 if (*++q == ':')
9693 q++;
9694 }
9695
9696 if (*++q == ':') {
9697 if (*p == '\0' && (p = *optnext) == NULL) {
9698 if (optstr[0] == ':') {
9699 s[0] = c;
9700 s[1] = '\0';
9701 err |= setvarsafe("OPTARG", s, 0);
9702 c = ':';
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00009703 } else {
Eric Andersenc470f442003-07-28 09:56:35 +00009704 fprintf(stderr, "No arg for -%c option\n", c);
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009705 unsetvar("OPTARG");
Eric Andersencb57d552001-06-28 07:25:16 +00009706 c = '?';
9707 }
Eric Andersenc470f442003-07-28 09:56:35 +00009708 goto out;
Eric Andersencb57d552001-06-28 07:25:16 +00009709 }
9710
9711 if (p == *optnext)
9712 optnext++;
Eric Andersenc470f442003-07-28 09:56:35 +00009713 err |= setvarsafe("OPTARG", p, 0);
Eric Andersencb57d552001-06-28 07:25:16 +00009714 p = NULL;
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00009715 } else
Eric Andersenc470f442003-07-28 09:56:35 +00009716 err |= setvarsafe("OPTARG", nullstr, 0);
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009717 out:
Eric Andersencb57d552001-06-28 07:25:16 +00009718 *optoff = p ? p - *(optnext - 1) : -1;
Eric Andersenc470f442003-07-28 09:56:35 +00009719 *param_optind = optnext - optfirst + 1;
9720 fmtstr(s, sizeof(s), "%d", *param_optind);
Eric Andersencb57d552001-06-28 07:25:16 +00009721 err |= setvarsafe("OPTIND", s, VNOFUNC);
9722 s[0] = c;
9723 s[1] = '\0';
9724 err |= setvarsafe(optvar, s, 0);
9725 if (err) {
Eric Andersenc470f442003-07-28 09:56:35 +00009726 *param_optind = 1;
Eric Andersencb57d552001-06-28 07:25:16 +00009727 *optoff = -1;
Denis Vlasenkob012b102007-02-19 22:43:01 +00009728 flush_stdout_stderr();
9729 raise_exception(EXERROR);
Eric Andersencb57d552001-06-28 07:25:16 +00009730 }
9731 return done;
9732}
Eric Andersenc470f442003-07-28 09:56:35 +00009733
9734/*
9735 * The getopts builtin. Shellparam.optnext points to the next argument
9736 * to be processed. Shellparam.optptr points to the next character to
9737 * be processed in the current argument. If shellparam.optnext is NULL,
9738 * then it's the first time getopts has been called.
9739 */
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009740static int
Eric Andersenc470f442003-07-28 09:56:35 +00009741getoptscmd(int argc, char **argv)
9742{
9743 char **optbase;
9744
9745 if (argc < 3)
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00009746 ash_msg_and_raise_error("usage: getopts optstring var [arg]");
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009747 if (argc == 3) {
Eric Andersenc470f442003-07-28 09:56:35 +00009748 optbase = shellparam.p;
9749 if (shellparam.optind > shellparam.nparam + 1) {
9750 shellparam.optind = 1;
9751 shellparam.optoff = -1;
9752 }
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009753 } else {
Eric Andersenc470f442003-07-28 09:56:35 +00009754 optbase = &argv[3];
9755 if (shellparam.optind > argc - 2) {
9756 shellparam.optind = 1;
9757 shellparam.optoff = -1;
9758 }
9759 }
9760
9761 return getopts(argv[1], argv[2], optbase, &shellparam.optind,
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +00009762 &shellparam.optoff);
Eric Andersenc470f442003-07-28 09:56:35 +00009763}
Denis Vlasenko131ae172007-02-18 13:00:19 +00009764#endif /* ASH_GETOPTS */
Eric Andersencb57d552001-06-28 07:25:16 +00009765
Eric Andersencb57d552001-06-28 07:25:16 +00009766
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009767/* ============ Shell parser */
Eric Andersencb57d552001-06-28 07:25:16 +00009768
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +00009769/*
9770 * NEOF is returned by parsecmd when it encounters an end of file. It
9771 * must be distinct from NULL, so we use the address of a variable that
9772 * happens to be handy.
9773 */
9774static smallint tokpushback; /* last token pushed back */
Denis Vlasenko99eb8502007-02-23 21:09:49 +00009775#define NEOF ((union node *)&tokpushback)
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +00009776static smallint parsebackquote; /* nonzero if we are inside backquotes */
Denis Vlasenko99eb8502007-02-23 21:09:49 +00009777static int lasttoken; /* last token read */
9778static char *wordtext; /* text of last word returned by readtoken */
9779static struct nodelist *backquotelist;
9780static union node *redirnode;
9781static struct heredoc *heredoc;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +00009782static smallint quoteflag; /* set if (part of) last token was quoted */
Denis Vlasenko99eb8502007-02-23 21:09:49 +00009783
Denis Vlasenkoa624c112007-02-19 22:45:43 +00009784static void raise_error_syntax(const char *) ATTRIBUTE_NORETURN;
9785static void
9786raise_error_syntax(const char *msg)
9787{
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +00009788 ash_msg_and_raise_error("syntax error: %s", msg);
Denis Vlasenkoa624c112007-02-19 22:45:43 +00009789 /* NOTREACHED */
9790}
9791
9792/*
9793 * Called when an unexpected token is read during the parse. The argument
9794 * is the token that is expected, or -1 if more than one type of token can
9795 * occur at this point.
9796 */
9797static void raise_error_unexpected_syntax(int) ATTRIBUTE_NORETURN;
9798static void
9799raise_error_unexpected_syntax(int token)
9800{
9801 char msg[64];
9802 int l;
9803
9804 l = sprintf(msg, "%s unexpected", tokname(lasttoken));
9805 if (token >= 0)
9806 sprintf(msg + l, " (expecting %s)", tokname(token));
9807 raise_error_syntax(msg);
9808 /* NOTREACHED */
9809}
Eric Andersencb57d552001-06-28 07:25:16 +00009810
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009811#define EOFMARKLEN 79
Eric Andersencb57d552001-06-28 07:25:16 +00009812
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009813struct heredoc {
9814 struct heredoc *next; /* next here document in list */
Denis Vlasenko838ffd52008-02-21 04:32:08 +00009815 union node *here; /* redirection node */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009816 char *eofmark; /* string indicating end of input */
9817 int striptabs; /* if set, strip leading tabs */
9818};
Eric Andersencb57d552001-06-28 07:25:16 +00009819
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009820static struct heredoc *heredoclist; /* list of here documents to read */
9821
9822/* parsing is heavily cross-recursive, need these forward decls */
9823static union node *andor(void);
9824static union node *pipeline(void);
9825static union node *parse_command(void);
9826static void parseheredoc(void);
9827static char peektoken(void);
9828static int readtoken(void);
Eric Andersencb57d552001-06-28 07:25:16 +00009829
Eric Andersenc470f442003-07-28 09:56:35 +00009830static union node *
9831list(int nlflag)
Eric Andersencb57d552001-06-28 07:25:16 +00009832{
9833 union node *n1, *n2, *n3;
9834 int tok;
9835
Eric Andersenc470f442003-07-28 09:56:35 +00009836 checkkwd = CHKNL | CHKKWD | CHKALIAS;
9837 if (nlflag == 2 && peektoken())
Eric Andersencb57d552001-06-28 07:25:16 +00009838 return NULL;
9839 n1 = NULL;
9840 for (;;) {
9841 n2 = andor();
9842 tok = readtoken();
9843 if (tok == TBACKGND) {
Eric Andersenc470f442003-07-28 09:56:35 +00009844 if (n2->type == NPIPE) {
9845 n2->npipe.backgnd = 1;
Eric Andersencb57d552001-06-28 07:25:16 +00009846 } else {
Eric Andersenc470f442003-07-28 09:56:35 +00009847 if (n2->type != NREDIR) {
Denis Vlasenko597906c2008-02-20 16:38:54 +00009848 n3 = stzalloc(sizeof(struct nredir));
Eric Andersenc470f442003-07-28 09:56:35 +00009849 n3->nredir.n = n2;
Denis Vlasenko597906c2008-02-20 16:38:54 +00009850 /*n3->nredir.redirect = NULL; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +00009851 n2 = n3;
9852 }
9853 n2->type = NBACKGND;
Eric Andersencb57d552001-06-28 07:25:16 +00009854 }
9855 }
9856 if (n1 == NULL) {
9857 n1 = n2;
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009858 } else {
Denis Vlasenko838ffd52008-02-21 04:32:08 +00009859 n3 = stzalloc(sizeof(struct nbinary));
Eric Andersencb57d552001-06-28 07:25:16 +00009860 n3->type = NSEMI;
9861 n3->nbinary.ch1 = n1;
9862 n3->nbinary.ch2 = n2;
9863 n1 = n3;
9864 }
9865 switch (tok) {
9866 case TBACKGND:
9867 case TSEMI:
9868 tok = readtoken();
9869 /* fall through */
9870 case TNL:
9871 if (tok == TNL) {
9872 parseheredoc();
Eric Andersenc470f442003-07-28 09:56:35 +00009873 if (nlflag == 1)
Eric Andersencb57d552001-06-28 07:25:16 +00009874 return n1;
9875 } else {
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +00009876 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +00009877 }
Eric Andersenc470f442003-07-28 09:56:35 +00009878 checkkwd = CHKNL | CHKKWD | CHKALIAS;
Manuel Novoa III 16815d42001-08-10 19:36:07 +00009879 if (peektoken())
Eric Andersencb57d552001-06-28 07:25:16 +00009880 return n1;
9881 break;
9882 case TEOF:
9883 if (heredoclist)
9884 parseheredoc();
9885 else
Eric Andersenc470f442003-07-28 09:56:35 +00009886 pungetc(); /* push back EOF on input */
Eric Andersencb57d552001-06-28 07:25:16 +00009887 return n1;
9888 default:
Eric Andersenc470f442003-07-28 09:56:35 +00009889 if (nlflag == 1)
Denis Vlasenkoa624c112007-02-19 22:45:43 +00009890 raise_error_unexpected_syntax(-1);
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +00009891 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +00009892 return n1;
9893 }
9894 }
9895}
9896
Eric Andersenc470f442003-07-28 09:56:35 +00009897static union node *
9898andor(void)
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00009899{
Eric Andersencb57d552001-06-28 07:25:16 +00009900 union node *n1, *n2, *n3;
9901 int t;
9902
Eric Andersencb57d552001-06-28 07:25:16 +00009903 n1 = pipeline();
9904 for (;;) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +00009905 t = readtoken();
9906 if (t == TAND) {
Eric Andersencb57d552001-06-28 07:25:16 +00009907 t = NAND;
9908 } else if (t == TOR) {
9909 t = NOR;
9910 } else {
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +00009911 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +00009912 return n1;
9913 }
Eric Andersenc470f442003-07-28 09:56:35 +00009914 checkkwd = CHKNL | CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +00009915 n2 = pipeline();
Denis Vlasenko838ffd52008-02-21 04:32:08 +00009916 n3 = stzalloc(sizeof(struct nbinary));
Eric Andersencb57d552001-06-28 07:25:16 +00009917 n3->type = t;
9918 n3->nbinary.ch1 = n1;
9919 n3->nbinary.ch2 = n2;
9920 n1 = n3;
9921 }
9922}
9923
Eric Andersenc470f442003-07-28 09:56:35 +00009924static union node *
9925pipeline(void)
Glenn L McGrath9fef17d2002-08-22 18:41:20 +00009926{
Eric Andersencb57d552001-06-28 07:25:16 +00009927 union node *n1, *n2, *pipenode;
9928 struct nodelist *lp, *prev;
9929 int negate;
9930
9931 negate = 0;
9932 TRACE(("pipeline: entered\n"));
9933 if (readtoken() == TNOT) {
9934 negate = !negate;
Eric Andersenc470f442003-07-28 09:56:35 +00009935 checkkwd = CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +00009936 } else
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +00009937 tokpushback = 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009938 n1 = parse_command();
Eric Andersencb57d552001-06-28 07:25:16 +00009939 if (readtoken() == TPIPE) {
Denis Vlasenko597906c2008-02-20 16:38:54 +00009940 pipenode = stzalloc(sizeof(struct npipe));
Eric Andersencb57d552001-06-28 07:25:16 +00009941 pipenode->type = NPIPE;
Denis Vlasenko597906c2008-02-20 16:38:54 +00009942 /*pipenode->npipe.backgnd = 0; - stzalloc did it */
Denis Vlasenko838ffd52008-02-21 04:32:08 +00009943 lp = stzalloc(sizeof(struct nodelist));
Eric Andersencb57d552001-06-28 07:25:16 +00009944 pipenode->npipe.cmdlist = lp;
9945 lp->n = n1;
9946 do {
9947 prev = lp;
Denis Vlasenko838ffd52008-02-21 04:32:08 +00009948 lp = stzalloc(sizeof(struct nodelist));
Eric Andersenc470f442003-07-28 09:56:35 +00009949 checkkwd = CHKNL | CHKKWD | CHKALIAS;
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009950 lp->n = parse_command();
Eric Andersencb57d552001-06-28 07:25:16 +00009951 prev->next = lp;
9952 } while (readtoken() == TPIPE);
9953 lp->next = NULL;
9954 n1 = pipenode;
9955 }
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +00009956 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +00009957 if (negate) {
Denis Vlasenko838ffd52008-02-21 04:32:08 +00009958 n2 = stzalloc(sizeof(struct nnot));
Eric Andersencb57d552001-06-28 07:25:16 +00009959 n2->type = NNOT;
9960 n2->nnot.com = n1;
9961 return n2;
Denis Vlasenko2da584f2007-02-19 22:44:05 +00009962 }
9963 return n1;
Eric Andersencb57d552001-06-28 07:25:16 +00009964}
9965
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009966static union node *
9967makename(void)
9968{
9969 union node *n;
9970
Denis Vlasenko597906c2008-02-20 16:38:54 +00009971 n = stzalloc(sizeof(struct narg));
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009972 n->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +00009973 /*n->narg.next = NULL; - stzalloc did it */
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009974 n->narg.text = wordtext;
9975 n->narg.backquote = backquotelist;
9976 return n;
9977}
9978
9979static void
9980fixredir(union node *n, const char *text, int err)
9981{
9982 TRACE(("Fix redir %s %d\n", text, err));
9983 if (!err)
9984 n->ndup.vname = NULL;
9985
9986 if (isdigit(text[0]) && text[1] == '\0')
Denis Vlasenko4d2183b2007-02-23 01:05:38 +00009987 n->ndup.dupfd = text[0] - '0';
Denis Vlasenkoaa744452007-02-23 01:04:22 +00009988 else if (LONE_DASH(text))
9989 n->ndup.dupfd = -1;
9990 else {
9991 if (err)
9992 raise_error_syntax("Bad fd number");
9993 n->ndup.vname = makename();
9994 }
9995}
9996
9997/*
9998 * Returns true if the text contains nothing to expand (no dollar signs
9999 * or backquotes).
10000 */
10001static int
10002noexpand(char *text)
10003{
10004 char *p;
10005 char c;
10006
10007 p = text;
10008 while ((c = *p++) != '\0') {
10009 if (c == CTLQUOTEMARK)
10010 continue;
10011 if (c == CTLESC)
10012 p++;
10013 else if (SIT(c, BASESYNTAX) == CCTL)
10014 return 0;
10015 }
10016 return 1;
10017}
10018
10019static void
10020parsefname(void)
10021{
10022 union node *n = redirnode;
10023
10024 if (readtoken() != TWORD)
10025 raise_error_unexpected_syntax(-1);
10026 if (n->type == NHERE) {
10027 struct heredoc *here = heredoc;
10028 struct heredoc *p;
10029 int i;
10030
10031 if (quoteflag == 0)
10032 n->type = NXHERE;
10033 TRACE(("Here document %d\n", n->type));
10034 if (!noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
10035 raise_error_syntax("Illegal eof marker for << redirection");
10036 rmescapes(wordtext);
10037 here->eofmark = wordtext;
10038 here->next = NULL;
10039 if (heredoclist == NULL)
10040 heredoclist = here;
10041 else {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010042 for (p = heredoclist; p->next; p = p->next)
10043 continue;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010044 p->next = here;
10045 }
10046 } else if (n->type == NTOFD || n->type == NFROMFD) {
10047 fixredir(n, wordtext, 0);
10048 } else {
10049 n->nfile.fname = makename();
10050 }
10051}
Eric Andersencb57d552001-06-28 07:25:16 +000010052
Eric Andersenc470f442003-07-28 09:56:35 +000010053static union node *
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010054simplecmd(void)
10055{
10056 union node *args, **app;
10057 union node *n = NULL;
10058 union node *vars, **vpp;
10059 union node **rpp, *redir;
10060 int savecheckkwd;
Denis Vlasenko80591b02008-03-25 07:49:43 +000010061#if ENABLE_ASH_BASH_COMPAT
10062 smallint double_brackets_flag = 0;
10063#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010064
10065 args = NULL;
10066 app = &args;
10067 vars = NULL;
10068 vpp = &vars;
10069 redir = NULL;
10070 rpp = &redir;
10071
10072 savecheckkwd = CHKALIAS;
10073 for (;;) {
Denis Vlasenko80591b02008-03-25 07:49:43 +000010074 int t;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010075 checkkwd = savecheckkwd;
Denis Vlasenko80591b02008-03-25 07:49:43 +000010076 t = readtoken();
10077 switch (t) {
10078#if ENABLE_ASH_BASH_COMPAT
10079 case TAND: /* "&&" */
10080 case TOR: /* "||" */
10081 if (!double_brackets_flag) {
10082 tokpushback = 1;
10083 goto out;
10084 }
10085 wordtext = (char *) (t == TAND ? "-a" : "-o");
10086#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010087 case TWORD:
Denis Vlasenko597906c2008-02-20 16:38:54 +000010088 n = stzalloc(sizeof(struct narg));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010089 n->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010090 /*n->narg.next = NULL; - stzalloc did it */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010091 n->narg.text = wordtext;
Denis Vlasenko80591b02008-03-25 07:49:43 +000010092#if ENABLE_ASH_BASH_COMPAT
10093 if (strcmp("[[", wordtext) == 0)
10094 double_brackets_flag = 1;
10095 else if (strcmp("]]", wordtext) == 0)
10096 double_brackets_flag = 0;
10097#endif
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010098 n->narg.backquote = backquotelist;
10099 if (savecheckkwd && isassignment(wordtext)) {
10100 *vpp = n;
10101 vpp = &n->narg.next;
10102 } else {
10103 *app = n;
10104 app = &n->narg.next;
10105 savecheckkwd = 0;
10106 }
10107 break;
10108 case TREDIR:
10109 *rpp = n = redirnode;
10110 rpp = &n->nfile.next;
10111 parsefname(); /* read name of redirection file */
10112 break;
10113 case TLP:
10114 if (args && app == &args->narg.next
10115 && !vars && !redir
10116 ) {
10117 struct builtincmd *bcmd;
10118 const char *name;
10119
10120 /* We have a function */
10121 if (readtoken() != TRP)
10122 raise_error_unexpected_syntax(TRP);
10123 name = n->narg.text;
10124 if (!goodname(name)
10125 || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
10126 ) {
10127 raise_error_syntax("Bad function name");
10128 }
10129 n->type = NDEFUN;
10130 checkkwd = CHKNL | CHKKWD | CHKALIAS;
10131 n->narg.next = parse_command();
10132 return n;
10133 }
10134 /* fall through */
10135 default:
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010136 tokpushback = 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010137 goto out;
10138 }
10139 }
10140 out:
10141 *app = NULL;
10142 *vpp = NULL;
10143 *rpp = NULL;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010144 n = stzalloc(sizeof(struct ncmd));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010145 n->type = NCMD;
10146 n->ncmd.args = args;
10147 n->ncmd.assign = vars;
10148 n->ncmd.redirect = redir;
10149 return n;
10150}
10151
10152static union node *
10153parse_command(void)
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010154{
Eric Andersencb57d552001-06-28 07:25:16 +000010155 union node *n1, *n2;
10156 union node *ap, **app;
10157 union node *cp, **cpp;
10158 union node *redir, **rpp;
Eric Andersenc470f442003-07-28 09:56:35 +000010159 union node **rpp2;
Eric Andersencb57d552001-06-28 07:25:16 +000010160 int t;
10161
10162 redir = NULL;
Eric Andersenc470f442003-07-28 09:56:35 +000010163 rpp2 = &redir;
Eric Andersen88cec252001-09-06 17:35:20 +000010164
Eric Andersencb57d552001-06-28 07:25:16 +000010165 switch (readtoken()) {
Eric Andersenc470f442003-07-28 09:56:35 +000010166 default:
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010167 raise_error_unexpected_syntax(-1);
Eric Andersenc470f442003-07-28 09:56:35 +000010168 /* NOTREACHED */
Eric Andersencb57d552001-06-28 07:25:16 +000010169 case TIF:
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010170 n1 = stzalloc(sizeof(struct nif));
Eric Andersencb57d552001-06-28 07:25:16 +000010171 n1->type = NIF;
10172 n1->nif.test = list(0);
10173 if (readtoken() != TTHEN)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010174 raise_error_unexpected_syntax(TTHEN);
Eric Andersencb57d552001-06-28 07:25:16 +000010175 n1->nif.ifpart = list(0);
10176 n2 = n1;
10177 while (readtoken() == TELIF) {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010178 n2->nif.elsepart = stzalloc(sizeof(struct nif));
Eric Andersencb57d552001-06-28 07:25:16 +000010179 n2 = n2->nif.elsepart;
10180 n2->type = NIF;
10181 n2->nif.test = list(0);
10182 if (readtoken() != TTHEN)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010183 raise_error_unexpected_syntax(TTHEN);
Eric Andersencb57d552001-06-28 07:25:16 +000010184 n2->nif.ifpart = list(0);
10185 }
10186 if (lasttoken == TELSE)
10187 n2->nif.elsepart = list(0);
10188 else {
10189 n2->nif.elsepart = NULL;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010190 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010191 }
Eric Andersenc470f442003-07-28 09:56:35 +000010192 t = TFI;
Eric Andersencb57d552001-06-28 07:25:16 +000010193 break;
10194 case TWHILE:
Eric Andersenc470f442003-07-28 09:56:35 +000010195 case TUNTIL: {
Eric Andersencb57d552001-06-28 07:25:16 +000010196 int got;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010197 n1 = stzalloc(sizeof(struct nbinary));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010198 n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
Eric Andersencb57d552001-06-28 07:25:16 +000010199 n1->nbinary.ch1 = list(0);
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010200 got = readtoken();
10201 if (got != TDO) {
Denis Vlasenko131ae172007-02-18 13:00:19 +000010202 TRACE(("expecting DO got %s %s\n", tokname(got),
10203 got == TWORD ? wordtext : ""));
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010204 raise_error_unexpected_syntax(TDO);
Eric Andersencb57d552001-06-28 07:25:16 +000010205 }
10206 n1->nbinary.ch2 = list(0);
Eric Andersenc470f442003-07-28 09:56:35 +000010207 t = TDONE;
Eric Andersencb57d552001-06-28 07:25:16 +000010208 break;
10209 }
10210 case TFOR:
Eric Andersenc470f442003-07-28 09:56:35 +000010211 if (readtoken() != TWORD || quoteflag || ! goodname(wordtext))
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010212 raise_error_syntax("Bad for loop variable");
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010213 n1 = stzalloc(sizeof(struct nfor));
Eric Andersencb57d552001-06-28 07:25:16 +000010214 n1->type = NFOR;
10215 n1->nfor.var = wordtext;
Eric Andersenc470f442003-07-28 09:56:35 +000010216 checkkwd = CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010217 if (readtoken() == TIN) {
10218 app = &ap;
10219 while (readtoken() == TWORD) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010220 n2 = stzalloc(sizeof(struct narg));
Eric Andersencb57d552001-06-28 07:25:16 +000010221 n2->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010222 /*n2->narg.next = NULL; - stzalloc did it */
Eric Andersencb57d552001-06-28 07:25:16 +000010223 n2->narg.text = wordtext;
10224 n2->narg.backquote = backquotelist;
10225 *app = n2;
10226 app = &n2->narg.next;
10227 }
10228 *app = NULL;
10229 n1->nfor.args = ap;
10230 if (lasttoken != TNL && lasttoken != TSEMI)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010231 raise_error_unexpected_syntax(-1);
Eric Andersencb57d552001-06-28 07:25:16 +000010232 } else {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010233 n2 = stzalloc(sizeof(struct narg));
Eric Andersencb57d552001-06-28 07:25:16 +000010234 n2->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010235 /*n2->narg.next = NULL; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000010236 n2->narg.text = (char *)dolatstr;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010237 /*n2->narg.backquote = NULL;*/
Eric Andersencb57d552001-06-28 07:25:16 +000010238 n1->nfor.args = n2;
10239 /*
10240 * Newline or semicolon here is optional (but note
10241 * that the original Bourne shell only allowed NL).
10242 */
10243 if (lasttoken != TNL && lasttoken != TSEMI)
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010244 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010245 }
Eric Andersenc470f442003-07-28 09:56:35 +000010246 checkkwd = CHKNL | CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010247 if (readtoken() != TDO)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010248 raise_error_unexpected_syntax(TDO);
Eric Andersencb57d552001-06-28 07:25:16 +000010249 n1->nfor.body = list(0);
Eric Andersenc470f442003-07-28 09:56:35 +000010250 t = TDONE;
Eric Andersencb57d552001-06-28 07:25:16 +000010251 break;
10252 case TCASE:
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010253 n1 = stzalloc(sizeof(struct ncase));
Eric Andersencb57d552001-06-28 07:25:16 +000010254 n1->type = NCASE;
10255 if (readtoken() != TWORD)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010256 raise_error_unexpected_syntax(TWORD);
Denis Vlasenko597906c2008-02-20 16:38:54 +000010257 n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
Eric Andersencb57d552001-06-28 07:25:16 +000010258 n2->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010259 /*n2->narg.next = NULL; - stzalloc did it */
Eric Andersencb57d552001-06-28 07:25:16 +000010260 n2->narg.text = wordtext;
10261 n2->narg.backquote = backquotelist;
Eric Andersencb57d552001-06-28 07:25:16 +000010262 do {
Eric Andersenc470f442003-07-28 09:56:35 +000010263 checkkwd = CHKKWD | CHKALIAS;
Eric Andersencb57d552001-06-28 07:25:16 +000010264 } while (readtoken() == TNL);
10265 if (lasttoken != TIN)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010266 raise_error_unexpected_syntax(TIN);
Eric Andersencb57d552001-06-28 07:25:16 +000010267 cpp = &n1->ncase.cases;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010268 next_case:
Eric Andersenc470f442003-07-28 09:56:35 +000010269 checkkwd = CHKNL | CHKKWD;
10270 t = readtoken();
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010271 while (t != TESAC) {
Eric Andersencb57d552001-06-28 07:25:16 +000010272 if (lasttoken == TLP)
10273 readtoken();
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010274 *cpp = cp = stzalloc(sizeof(struct nclist));
Eric Andersencb57d552001-06-28 07:25:16 +000010275 cp->type = NCLIST;
10276 app = &cp->nclist.pattern;
10277 for (;;) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010278 *app = ap = stzalloc(sizeof(struct narg));
Eric Andersencb57d552001-06-28 07:25:16 +000010279 ap->type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010280 /*ap->narg.next = NULL; - stzalloc did it */
Eric Andersencb57d552001-06-28 07:25:16 +000010281 ap->narg.text = wordtext;
10282 ap->narg.backquote = backquotelist;
Eric Andersenc470f442003-07-28 09:56:35 +000010283 if (readtoken() != TPIPE)
Eric Andersencb57d552001-06-28 07:25:16 +000010284 break;
10285 app = &ap->narg.next;
10286 readtoken();
10287 }
Denis Vlasenko597906c2008-02-20 16:38:54 +000010288 //ap->narg.next = NULL;
Eric Andersencb57d552001-06-28 07:25:16 +000010289 if (lasttoken != TRP)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010290 raise_error_unexpected_syntax(TRP);
Eric Andersenc470f442003-07-28 09:56:35 +000010291 cp->nclist.body = list(2);
Eric Andersencb57d552001-06-28 07:25:16 +000010292
Eric Andersenc470f442003-07-28 09:56:35 +000010293 cpp = &cp->nclist.next;
10294
10295 checkkwd = CHKNL | CHKKWD;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010296 t = readtoken();
10297 if (t != TESAC) {
Eric Andersencb57d552001-06-28 07:25:16 +000010298 if (t != TENDCASE)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010299 raise_error_unexpected_syntax(TENDCASE);
10300 goto next_case;
Eric Andersencb57d552001-06-28 07:25:16 +000010301 }
Eric Andersenc470f442003-07-28 09:56:35 +000010302 }
Eric Andersencb57d552001-06-28 07:25:16 +000010303 *cpp = NULL;
Eric Andersenc470f442003-07-28 09:56:35 +000010304 goto redir;
Eric Andersencb57d552001-06-28 07:25:16 +000010305 case TLP:
Denis Vlasenko597906c2008-02-20 16:38:54 +000010306 n1 = stzalloc(sizeof(struct nredir));
Eric Andersencb57d552001-06-28 07:25:16 +000010307 n1->type = NSUBSHELL;
10308 n1->nredir.n = list(0);
Denis Vlasenko597906c2008-02-20 16:38:54 +000010309 /*n1->nredir.redirect = NULL; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000010310 t = TRP;
Eric Andersencb57d552001-06-28 07:25:16 +000010311 break;
10312 case TBEGIN:
10313 n1 = list(0);
Eric Andersenc470f442003-07-28 09:56:35 +000010314 t = TEND;
Eric Andersencb57d552001-06-28 07:25:16 +000010315 break;
Eric Andersencb57d552001-06-28 07:25:16 +000010316 case TWORD:
Eric Andersenc470f442003-07-28 09:56:35 +000010317 case TREDIR:
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010318 tokpushback = 1;
Eric Andersenc470f442003-07-28 09:56:35 +000010319 return simplecmd();
Eric Andersencb57d552001-06-28 07:25:16 +000010320 }
10321
Eric Andersenc470f442003-07-28 09:56:35 +000010322 if (readtoken() != t)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010323 raise_error_unexpected_syntax(t);
Eric Andersenc470f442003-07-28 09:56:35 +000010324
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010325 redir:
Eric Andersencb57d552001-06-28 07:25:16 +000010326 /* Now check for redirection which may follow command */
Eric Andersenc470f442003-07-28 09:56:35 +000010327 checkkwd = CHKKWD | CHKALIAS;
10328 rpp = rpp2;
Eric Andersencb57d552001-06-28 07:25:16 +000010329 while (readtoken() == TREDIR) {
10330 *rpp = n2 = redirnode;
10331 rpp = &n2->nfile.next;
10332 parsefname();
10333 }
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010334 tokpushback = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010335 *rpp = NULL;
10336 if (redir) {
10337 if (n1->type != NSUBSHELL) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010338 n2 = stzalloc(sizeof(struct nredir));
Eric Andersencb57d552001-06-28 07:25:16 +000010339 n2->type = NREDIR;
10340 n2->nredir.n = n1;
10341 n1 = n2;
10342 }
10343 n1->nredir.redirect = redir;
10344 }
Eric Andersencb57d552001-06-28 07:25:16 +000010345 return n1;
10346}
10347
Eric Andersencb57d552001-06-28 07:25:16 +000010348/*
10349 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
10350 * is not NULL, read a here document. In the latter case, eofmark is the
10351 * word which marks the end of the document and striptabs is true if
10352 * leading tabs should be stripped from the document. The argument firstc
10353 * is the first character of the input token or document.
10354 *
10355 * Because C does not have internal subroutines, I have simulated them
10356 * using goto's to implement the subroutine linkage. The following macros
10357 * will run code that appears at the end of readtoken1.
10358 */
10359
Eric Andersen2870d962001-07-02 17:27:21 +000010360#define CHECKEND() {goto checkend; checkend_return:;}
10361#define PARSEREDIR() {goto parseredir; parseredir_return:;}
10362#define PARSESUB() {goto parsesub; parsesub_return:;}
10363#define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
10364#define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
10365#define PARSEARITH() {goto parsearith; parsearith_return:;}
Eric Andersencb57d552001-06-28 07:25:16 +000010366
10367static int
Eric Andersenc470f442003-07-28 09:56:35 +000010368readtoken1(int firstc, int syntax, char *eofmark, int striptabs)
Manuel Novoa III 16815d42001-08-10 19:36:07 +000010369{
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010370 /* NB: syntax parameter fits into smallint */
Eric Andersencb57d552001-06-28 07:25:16 +000010371 int c = firstc;
10372 char *out;
10373 int len;
10374 char line[EOFMARKLEN + 1];
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010375 struct nodelist *bqlist;
10376 smallint quotef;
10377 smallint dblquote;
10378 smallint oldstyle;
10379 smallint prevsyntax; /* syntax before arithmetic */
Denis Vlasenko46a53062007-09-24 18:30:02 +000010380#if ENABLE_ASH_EXPAND_PRMT
10381 smallint pssyntax; /* we are expanding a prompt string */
10382#endif
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010383 int varnest; /* levels of variables expansion */
10384 int arinest; /* levels of arithmetic expansion */
10385 int parenlevel; /* levels of parens in arithmetic */
10386 int dqvarnest; /* levels of variables expansion within double quotes */
10387
Eric Andersencb57d552001-06-28 07:25:16 +000010388#if __GNUC__
10389 /* Avoid longjmp clobbering */
10390 (void) &out;
10391 (void) &quotef;
10392 (void) &dblquote;
10393 (void) &varnest;
10394 (void) &arinest;
10395 (void) &parenlevel;
10396 (void) &dqvarnest;
10397 (void) &oldstyle;
10398 (void) &prevsyntax;
10399 (void) &syntax;
10400#endif
Eric Andersencb57d552001-06-28 07:25:16 +000010401 startlinno = plinno;
Eric Andersencb57d552001-06-28 07:25:16 +000010402 bqlist = NULL;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010403 quotef = 0;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010404 oldstyle = 0;
10405 prevsyntax = 0;
Denis Vlasenko46a53062007-09-24 18:30:02 +000010406#if ENABLE_ASH_EXPAND_PRMT
10407 pssyntax = (syntax == PSSYNTAX);
10408 if (pssyntax)
10409 syntax = DQSYNTAX;
10410#endif
10411 dblquote = (syntax == DQSYNTAX);
Eric Andersencb57d552001-06-28 07:25:16 +000010412 varnest = 0;
10413 arinest = 0;
10414 parenlevel = 0;
10415 dqvarnest = 0;
10416
10417 STARTSTACKSTR(out);
Eric Andersenc470f442003-07-28 09:56:35 +000010418 loop: { /* for each line, until end of word */
10419 CHECKEND(); /* set c to PEOF if at end of here document */
10420 for (;;) { /* until end of line or end of word */
10421 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
Denis Vlasenkobf0a2012006-12-26 10:42:51 +000010422 switch (SIT(c, syntax)) {
Eric Andersenc470f442003-07-28 09:56:35 +000010423 case CNL: /* '\n' */
Eric Andersencb57d552001-06-28 07:25:16 +000010424 if (syntax == BASESYNTAX)
Eric Andersenc470f442003-07-28 09:56:35 +000010425 goto endword; /* exit outer loop */
Eric Andersencb57d552001-06-28 07:25:16 +000010426 USTPUTC(c, out);
10427 plinno++;
10428 if (doprompt)
10429 setprompt(2);
Eric Andersencb57d552001-06-28 07:25:16 +000010430 c = pgetc();
Eric Andersenc470f442003-07-28 09:56:35 +000010431 goto loop; /* continue outer loop */
Eric Andersencb57d552001-06-28 07:25:16 +000010432 case CWORD:
10433 USTPUTC(c, out);
10434 break;
10435 case CCTL:
Eric Andersenc470f442003-07-28 09:56:35 +000010436 if (eofmark == NULL || dblquote)
Eric Andersencb57d552001-06-28 07:25:16 +000010437 USTPUTC(CTLESC, out);
10438 USTPUTC(c, out);
10439 break;
Eric Andersenc470f442003-07-28 09:56:35 +000010440 case CBACK: /* backslash */
Eric Andersencb57d552001-06-28 07:25:16 +000010441 c = pgetc2();
10442 if (c == PEOF) {
Eric Andersenc470f442003-07-28 09:56:35 +000010443 USTPUTC(CTLESC, out);
Eric Andersencb57d552001-06-28 07:25:16 +000010444 USTPUTC('\\', out);
10445 pungetc();
10446 } else if (c == '\n') {
10447 if (doprompt)
10448 setprompt(2);
Eric Andersencb57d552001-06-28 07:25:16 +000010449 } else {
Denis Vlasenko46a53062007-09-24 18:30:02 +000010450#if ENABLE_ASH_EXPAND_PRMT
10451 if (c == '$' && pssyntax) {
10452 USTPUTC(CTLESC, out);
10453 USTPUTC('\\', out);
10454 }
10455#endif
"Vladimir N. Oleynik"84005af2006-01-25 17:53:04 +000010456 if (dblquote &&
Eric Andersenc470f442003-07-28 09:56:35 +000010457 c != '\\' && c != '`' &&
10458 c != '$' && (
10459 c != '"' ||
"Vladimir N. Oleynik"84005af2006-01-25 17:53:04 +000010460 eofmark != NULL)
Eric Andersenc470f442003-07-28 09:56:35 +000010461 ) {
10462 USTPUTC(CTLESC, out);
Eric Andersencb57d552001-06-28 07:25:16 +000010463 USTPUTC('\\', out);
Eric Andersenc470f442003-07-28 09:56:35 +000010464 }
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010465 if (SIT(c, SQSYNTAX) == CCTL)
Eric Andersencb57d552001-06-28 07:25:16 +000010466 USTPUTC(CTLESC, out);
Eric Andersencb57d552001-06-28 07:25:16 +000010467 USTPUTC(c, out);
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010468 quotef = 1;
Eric Andersencb57d552001-06-28 07:25:16 +000010469 }
10470 break;
10471 case CSQUOTE:
Eric Andersencb57d552001-06-28 07:25:16 +000010472 syntax = SQSYNTAX;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010473 quotemark:
Eric Andersenc470f442003-07-28 09:56:35 +000010474 if (eofmark == NULL) {
10475 USTPUTC(CTLQUOTEMARK, out);
10476 }
Eric Andersencb57d552001-06-28 07:25:16 +000010477 break;
10478 case CDQUOTE:
Eric Andersencb57d552001-06-28 07:25:16 +000010479 syntax = DQSYNTAX;
10480 dblquote = 1;
Eric Andersenc470f442003-07-28 09:56:35 +000010481 goto quotemark;
Eric Andersencb57d552001-06-28 07:25:16 +000010482 case CENDQUOTE:
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010483 if (eofmark != NULL && arinest == 0
10484 && varnest == 0
10485 ) {
Eric Andersencb57d552001-06-28 07:25:16 +000010486 USTPUTC(c, out);
10487 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000010488 if (dqvarnest == 0) {
Eric Andersencb57d552001-06-28 07:25:16 +000010489 syntax = BASESYNTAX;
10490 dblquote = 0;
10491 }
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010492 quotef = 1;
Eric Andersenc470f442003-07-28 09:56:35 +000010493 goto quotemark;
Eric Andersencb57d552001-06-28 07:25:16 +000010494 }
10495 break;
Eric Andersenc470f442003-07-28 09:56:35 +000010496 case CVAR: /* '$' */
10497 PARSESUB(); /* parse substitution */
Eric Andersencb57d552001-06-28 07:25:16 +000010498 break;
Eric Andersenc470f442003-07-28 09:56:35 +000010499 case CENDVAR: /* '}' */
Eric Andersencb57d552001-06-28 07:25:16 +000010500 if (varnest > 0) {
10501 varnest--;
10502 if (dqvarnest > 0) {
10503 dqvarnest--;
10504 }
10505 USTPUTC(CTLENDVAR, out);
10506 } else {
10507 USTPUTC(c, out);
10508 }
10509 break;
Denis Vlasenko131ae172007-02-18 13:00:19 +000010510#if ENABLE_ASH_MATH_SUPPORT
Eric Andersenc470f442003-07-28 09:56:35 +000010511 case CLP: /* '(' in arithmetic */
Eric Andersencb57d552001-06-28 07:25:16 +000010512 parenlevel++;
10513 USTPUTC(c, out);
10514 break;
Eric Andersenc470f442003-07-28 09:56:35 +000010515 case CRP: /* ')' in arithmetic */
Eric Andersencb57d552001-06-28 07:25:16 +000010516 if (parenlevel > 0) {
10517 USTPUTC(c, out);
10518 --parenlevel;
10519 } else {
10520 if (pgetc() == ')') {
10521 if (--arinest == 0) {
10522 USTPUTC(CTLENDARI, out);
10523 syntax = prevsyntax;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010524 dblquote = (syntax == DQSYNTAX);
Eric Andersencb57d552001-06-28 07:25:16 +000010525 } else
10526 USTPUTC(')', out);
10527 } else {
10528 /*
10529 * unbalanced parens
10530 * (don't 2nd guess - no error)
10531 */
10532 pungetc();
10533 USTPUTC(')', out);
10534 }
10535 }
10536 break;
10537#endif
Eric Andersenc470f442003-07-28 09:56:35 +000010538 case CBQUOTE: /* '`' */
Eric Andersencb57d552001-06-28 07:25:16 +000010539 PARSEBACKQOLD();
10540 break;
Eric Andersen2870d962001-07-02 17:27:21 +000010541 case CENDFILE:
Eric Andersenc470f442003-07-28 09:56:35 +000010542 goto endword; /* exit outer loop */
Eric Andersencb57d552001-06-28 07:25:16 +000010543 case CIGN:
10544 break;
10545 default:
10546 if (varnest == 0)
Eric Andersenc470f442003-07-28 09:56:35 +000010547 goto endword; /* exit outer loop */
Denis Vlasenko131ae172007-02-18 13:00:19 +000010548#if ENABLE_ASH_ALIAS
Eric Andersen3102ac42001-07-06 04:26:23 +000010549 if (c != PEOA)
10550#endif
Eric Andersencb57d552001-06-28 07:25:16 +000010551 USTPUTC(c, out);
Eric Andersen3102ac42001-07-06 04:26:23 +000010552
Eric Andersencb57d552001-06-28 07:25:16 +000010553 }
10554 c = pgetc_macro();
10555 }
10556 }
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010557 endword:
Denis Vlasenko131ae172007-02-18 13:00:19 +000010558#if ENABLE_ASH_MATH_SUPPORT
Eric Andersencb57d552001-06-28 07:25:16 +000010559 if (syntax == ARISYNTAX)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010560 raise_error_syntax("Missing '))'");
Eric Andersenc470f442003-07-28 09:56:35 +000010561#endif
Denis Vlasenko99eb8502007-02-23 21:09:49 +000010562 if (syntax != BASESYNTAX && !parsebackquote && eofmark == NULL)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010563 raise_error_syntax("Unterminated quoted string");
Eric Andersencb57d552001-06-28 07:25:16 +000010564 if (varnest != 0) {
10565 startlinno = plinno;
Eric Andersenc470f442003-07-28 09:56:35 +000010566 /* { */
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010567 raise_error_syntax("Missing '}'");
Eric Andersencb57d552001-06-28 07:25:16 +000010568 }
10569 USTPUTC('\0', out);
Eric Andersenc470f442003-07-28 09:56:35 +000010570 len = out - (char *)stackblock();
Eric Andersencb57d552001-06-28 07:25:16 +000010571 out = stackblock();
10572 if (eofmark == NULL) {
10573 if ((c == '>' || c == '<')
Eric Andersenc470f442003-07-28 09:56:35 +000010574 && quotef == 0
10575 && len <= 2
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010576 && (*out == '\0' || isdigit(*out))) {
Eric Andersencb57d552001-06-28 07:25:16 +000010577 PARSEREDIR();
10578 return lasttoken = TREDIR;
10579 } else {
10580 pungetc();
10581 }
10582 }
10583 quoteflag = quotef;
10584 backquotelist = bqlist;
10585 grabstackblock(len);
10586 wordtext = out;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010587 lasttoken = TWORD;
10588 return lasttoken;
Eric Andersencb57d552001-06-28 07:25:16 +000010589/* end of readtoken routine */
10590
Eric Andersencb57d552001-06-28 07:25:16 +000010591/*
10592 * Check to see whether we are at the end of the here document. When this
10593 * is called, c is set to the first character of the next input line. If
10594 * we are at the end of the here document, this routine sets the c to PEOF.
10595 */
Eric Andersenc470f442003-07-28 09:56:35 +000010596checkend: {
10597 if (eofmark) {
Denis Vlasenko131ae172007-02-18 13:00:19 +000010598#if ENABLE_ASH_ALIAS
Eric Andersenc470f442003-07-28 09:56:35 +000010599 if (c == PEOA) {
10600 c = pgetc2();
10601 }
10602#endif
10603 if (striptabs) {
10604 while (c == '\t') {
Eric Andersencb57d552001-06-28 07:25:16 +000010605 c = pgetc2();
10606 }
Eric Andersenc470f442003-07-28 09:56:35 +000010607 }
10608 if (c == *eofmark) {
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010609 if (pfgets(line, sizeof(line)) != NULL) {
Eric Andersenc470f442003-07-28 09:56:35 +000010610 char *p, *q;
Eric Andersencb57d552001-06-28 07:25:16 +000010611
Eric Andersenc470f442003-07-28 09:56:35 +000010612 p = line;
Denis Vlasenkof7d56652008-03-25 05:51:41 +000010613 for (q = eofmark + 1; *q && *p == *q; p++, q++)
10614 continue;
Eric Andersenc470f442003-07-28 09:56:35 +000010615 if (*p == '\n' && *q == '\0') {
10616 c = PEOF;
10617 plinno++;
10618 needprompt = doprompt;
10619 } else {
10620 pushstring(line, NULL);
Eric Andersencb57d552001-06-28 07:25:16 +000010621 }
10622 }
10623 }
10624 }
Eric Andersenc470f442003-07-28 09:56:35 +000010625 goto checkend_return;
10626}
Eric Andersencb57d552001-06-28 07:25:16 +000010627
Eric Andersencb57d552001-06-28 07:25:16 +000010628/*
10629 * Parse a redirection operator. The variable "out" points to a string
10630 * specifying the fd to be redirected. The variable "c" contains the
10631 * first character of the redirection operator.
10632 */
Eric Andersenc470f442003-07-28 09:56:35 +000010633parseredir: {
10634 char fd = *out;
10635 union node *np;
Eric Andersencb57d552001-06-28 07:25:16 +000010636
Denis Vlasenko597906c2008-02-20 16:38:54 +000010637 np = stzalloc(sizeof(struct nfile));
Eric Andersenc470f442003-07-28 09:56:35 +000010638 if (c == '>') {
10639 np->nfile.fd = 1;
10640 c = pgetc();
10641 if (c == '>')
10642 np->type = NAPPEND;
10643 else if (c == '|')
10644 np->type = NCLOBBER;
10645 else if (c == '&')
10646 np->type = NTOFD;
10647 else {
10648 np->type = NTO;
10649 pungetc();
Eric Andersencb57d552001-06-28 07:25:16 +000010650 }
Eric Andersenc470f442003-07-28 09:56:35 +000010651 } else { /* c == '<' */
Denis Vlasenko597906c2008-02-20 16:38:54 +000010652 /*np->nfile.fd = 0; - stzalloc did it */
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010653 c = pgetc();
10654 switch (c) {
Eric Andersenc470f442003-07-28 09:56:35 +000010655 case '<':
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010656 if (sizeof(struct nfile) != sizeof(struct nhere)) {
Denis Vlasenko597906c2008-02-20 16:38:54 +000010657 np = stzalloc(sizeof(struct nhere));
10658 /*np->nfile.fd = 0; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000010659 }
10660 np->type = NHERE;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010661 heredoc = stzalloc(sizeof(struct heredoc));
Eric Andersenc470f442003-07-28 09:56:35 +000010662 heredoc->here = np;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010663 c = pgetc();
10664 if (c == '-') {
Eric Andersenc470f442003-07-28 09:56:35 +000010665 heredoc->striptabs = 1;
10666 } else {
Denis Vlasenko838ffd52008-02-21 04:32:08 +000010667 /*heredoc->striptabs = 0; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000010668 pungetc();
10669 }
10670 break;
10671
10672 case '&':
10673 np->type = NFROMFD;
10674 break;
10675
10676 case '>':
10677 np->type = NFROMTO;
10678 break;
10679
10680 default:
10681 np->type = NFROM;
10682 pungetc();
10683 break;
10684 }
Eric Andersencb57d552001-06-28 07:25:16 +000010685 }
Eric Andersenc470f442003-07-28 09:56:35 +000010686 if (fd != '\0')
Denis Vlasenko4d2183b2007-02-23 01:05:38 +000010687 np->nfile.fd = fd - '0';
Eric Andersenc470f442003-07-28 09:56:35 +000010688 redirnode = np;
10689 goto parseredir_return;
10690}
Eric Andersencb57d552001-06-28 07:25:16 +000010691
Eric Andersencb57d552001-06-28 07:25:16 +000010692/*
10693 * Parse a substitution. At this point, we have read the dollar sign
10694 * and nothing else.
10695 */
Denis Vlasenkocc571512007-02-23 21:10:35 +000010696
10697/* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
10698 * (assuming ascii char codes, as the original implementation did) */
10699#define is_special(c) \
10700 ((((unsigned int)c) - 33 < 32) \
10701 && ((0xc1ff920dUL >> (((unsigned int)c) - 33)) & 1))
Eric Andersenc470f442003-07-28 09:56:35 +000010702parsesub: {
10703 int subtype;
10704 int typeloc;
10705 int flags;
10706 char *p;
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000010707 static const char types[] ALIGN1 = "}-+?=";
Eric Andersencb57d552001-06-28 07:25:16 +000010708
Eric Andersenc470f442003-07-28 09:56:35 +000010709 c = pgetc();
10710 if (
10711 c <= PEOA_OR_PEOF ||
10712 (c != '(' && c != '{' && !is_name(c) && !is_special(c))
10713 ) {
10714 USTPUTC('$', out);
10715 pungetc();
10716 } else if (c == '(') { /* $(command) or $((arith)) */
10717 if (pgetc() == '(') {
Denis Vlasenko131ae172007-02-18 13:00:19 +000010718#if ENABLE_ASH_MATH_SUPPORT
Eric Andersenc470f442003-07-28 09:56:35 +000010719 PARSEARITH();
10720#else
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010721 raise_error_syntax("We unsupport $((arith))");
Eric Andersenc470f442003-07-28 09:56:35 +000010722#endif
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000010723 } else {
Eric Andersenc470f442003-07-28 09:56:35 +000010724 pungetc();
10725 PARSEBACKQNEW();
10726 }
10727 } else {
10728 USTPUTC(CTLVAR, out);
10729 typeloc = out - (char *)stackblock();
10730 USTPUTC(VSNORMAL, out);
10731 subtype = VSNORMAL;
10732 if (c == '{') {
10733 c = pgetc();
10734 if (c == '#') {
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010735 c = pgetc();
10736 if (c == '}')
Eric Andersenc470f442003-07-28 09:56:35 +000010737 c = '#';
10738 else
10739 subtype = VSLENGTH;
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010740 } else
Eric Andersenc470f442003-07-28 09:56:35 +000010741 subtype = 0;
10742 }
10743 if (c > PEOA_OR_PEOF && is_name(c)) {
10744 do {
10745 STPUTC(c, out);
Eric Andersencb57d552001-06-28 07:25:16 +000010746 c = pgetc();
Eric Andersenc470f442003-07-28 09:56:35 +000010747 } while (c > PEOA_OR_PEOF && is_in_name(c));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010748 } else if (isdigit(c)) {
Eric Andersenc470f442003-07-28 09:56:35 +000010749 do {
10750 STPUTC(c, out);
10751 c = pgetc();
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010752 } while (isdigit(c));
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010753 } else if (is_special(c)) {
Eric Andersenc470f442003-07-28 09:56:35 +000010754 USTPUTC(c, out);
10755 c = pgetc();
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010756 } else
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010757 badsub: raise_error_syntax("Bad substitution");
Eric Andersencb57d552001-06-28 07:25:16 +000010758
Eric Andersenc470f442003-07-28 09:56:35 +000010759 STPUTC('=', out);
10760 flags = 0;
10761 if (subtype == 0) {
10762 switch (c) {
10763 case ':':
Eric Andersenc470f442003-07-28 09:56:35 +000010764 c = pgetc();
Denis Vlasenko92e13c22008-03-25 01:17:40 +000010765#if ENABLE_ASH_BASH_COMPAT
10766 if (c == ':' || c == '$' || isdigit(c)) {
10767 pungetc();
10768 subtype = VSSUBSTR;
10769 break;
10770 }
10771#endif
10772 flags = VSNUL;
Eric Andersenc470f442003-07-28 09:56:35 +000010773 /*FALLTHROUGH*/
10774 default:
10775 p = strchr(types, c);
10776 if (p == NULL)
10777 goto badsub;
10778 subtype = p - types + VSNORMAL;
10779 break;
10780 case '%':
Denis Vlasenko92e13c22008-03-25 01:17:40 +000010781 case '#': {
10782 int cc = c;
10783 subtype = c == '#' ? VSTRIMLEFT : VSTRIMRIGHT;
10784 c = pgetc();
10785 if (c == cc)
10786 subtype++;
10787 else
10788 pungetc();
10789 break;
10790 }
10791#if ENABLE_ASH_BASH_COMPAT
10792 case '/':
10793 subtype = VSREPLACE;
10794 c = pgetc();
10795 if (c == '/')
10796 subtype++; /* VSREPLACEALL */
10797 else
10798 pungetc();
10799 break;
10800#endif
Eric Andersencb57d552001-06-28 07:25:16 +000010801 }
Eric Andersenc470f442003-07-28 09:56:35 +000010802 } else {
10803 pungetc();
10804 }
10805 if (dblquote || arinest)
10806 flags |= VSQUOTE;
10807 *((char *)stackblock() + typeloc) = subtype | flags;
10808 if (subtype != VSNORMAL) {
10809 varnest++;
10810 if (dblquote || arinest) {
10811 dqvarnest++;
Eric Andersencb57d552001-06-28 07:25:16 +000010812 }
10813 }
10814 }
Eric Andersenc470f442003-07-28 09:56:35 +000010815 goto parsesub_return;
10816}
Eric Andersencb57d552001-06-28 07:25:16 +000010817
Eric Andersencb57d552001-06-28 07:25:16 +000010818/*
10819 * Called to parse command substitutions. Newstyle is set if the command
10820 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
10821 * list of commands (passed by reference), and savelen is the number of
10822 * characters on the top of the stack which must be preserved.
10823 */
Eric Andersenc470f442003-07-28 09:56:35 +000010824parsebackq: {
10825 struct nodelist **nlpp;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010826 smallint savepbq;
Eric Andersenc470f442003-07-28 09:56:35 +000010827 union node *n;
10828 char *volatile str;
10829 struct jmploc jmploc;
10830 struct jmploc *volatile savehandler;
10831 size_t savelen;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000010832 smallint saveprompt = 0;
10833
Eric Andersencb57d552001-06-28 07:25:16 +000010834#ifdef __GNUC__
Eric Andersenc470f442003-07-28 09:56:35 +000010835 (void) &saveprompt;
Eric Andersencb57d552001-06-28 07:25:16 +000010836#endif
Eric Andersenc470f442003-07-28 09:56:35 +000010837 savepbq = parsebackquote;
10838 if (setjmp(jmploc.loc)) {
Denis Vlasenko60818682007-09-28 22:07:23 +000010839 free(str);
Eric Andersenc470f442003-07-28 09:56:35 +000010840 parsebackquote = 0;
Denis Vlasenko2da584f2007-02-19 22:44:05 +000010841 exception_handler = savehandler;
10842 longjmp(exception_handler->loc, 1);
Eric Andersenc470f442003-07-28 09:56:35 +000010843 }
Denis Vlasenkob012b102007-02-19 22:43:01 +000010844 INT_OFF;
Eric Andersenc470f442003-07-28 09:56:35 +000010845 str = NULL;
10846 savelen = out - (char *)stackblock();
10847 if (savelen > 0) {
10848 str = ckmalloc(savelen);
10849 memcpy(str, stackblock(), savelen);
10850 }
Denis Vlasenko2da584f2007-02-19 22:44:05 +000010851 savehandler = exception_handler;
10852 exception_handler = &jmploc;
Denis Vlasenkob012b102007-02-19 22:43:01 +000010853 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +000010854 if (oldstyle) {
10855 /* We must read until the closing backquote, giving special
10856 treatment to some slashes, and then push the string and
10857 reread it as input, interpreting it normally. */
10858 char *pout;
10859 int pc;
10860 size_t psavelen;
10861 char *pstr;
10862
10863
10864 STARTSTACKSTR(pout);
10865 for (;;) {
10866 if (needprompt) {
10867 setprompt(2);
Eric Andersenc470f442003-07-28 09:56:35 +000010868 }
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010869 pc = pgetc();
10870 switch (pc) {
Eric Andersenc470f442003-07-28 09:56:35 +000010871 case '`':
10872 goto done;
10873
10874 case '\\':
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010875 pc = pgetc();
10876 if (pc == '\n') {
Eric Andersenc470f442003-07-28 09:56:35 +000010877 plinno++;
10878 if (doprompt)
10879 setprompt(2);
10880 /*
10881 * If eating a newline, avoid putting
10882 * the newline into the new character
10883 * stream (via the STPUTC after the
10884 * switch).
10885 */
10886 continue;
10887 }
10888 if (pc != '\\' && pc != '`' && pc != '$'
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000010889 && (!dblquote || pc != '"'))
Eric Andersenc470f442003-07-28 09:56:35 +000010890 STPUTC('\\', pout);
10891 if (pc > PEOA_OR_PEOF) {
10892 break;
10893 }
10894 /* fall through */
10895
10896 case PEOF:
Denis Vlasenko131ae172007-02-18 13:00:19 +000010897#if ENABLE_ASH_ALIAS
Eric Andersenc470f442003-07-28 09:56:35 +000010898 case PEOA:
10899#endif
10900 startlinno = plinno;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010901 raise_error_syntax("EOF in backquote substitution");
Eric Andersenc470f442003-07-28 09:56:35 +000010902
10903 case '\n':
10904 plinno++;
10905 needprompt = doprompt;
10906 break;
10907
10908 default:
10909 break;
10910 }
10911 STPUTC(pc, pout);
10912 }
Denis Vlasenko5cedb752007-02-18 19:56:41 +000010913 done:
Eric Andersenc470f442003-07-28 09:56:35 +000010914 STPUTC('\0', pout);
10915 psavelen = pout - (char *)stackblock();
10916 if (psavelen > 0) {
10917 pstr = grabstackstr(pout);
10918 setinputstring(pstr);
10919 }
10920 }
10921 nlpp = &bqlist;
10922 while (*nlpp)
10923 nlpp = &(*nlpp)->next;
Denis Vlasenko597906c2008-02-20 16:38:54 +000010924 *nlpp = stzalloc(sizeof(**nlpp));
10925 /* (*nlpp)->next = NULL; - stzalloc did it */
Eric Andersenc470f442003-07-28 09:56:35 +000010926 parsebackquote = oldstyle;
10927
10928 if (oldstyle) {
10929 saveprompt = doprompt;
10930 doprompt = 0;
Eric Andersencb57d552001-06-28 07:25:16 +000010931 }
10932
Eric Andersenc470f442003-07-28 09:56:35 +000010933 n = list(2);
10934
10935 if (oldstyle)
10936 doprompt = saveprompt;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010937 else if (readtoken() != TRP)
10938 raise_error_unexpected_syntax(TRP);
Eric Andersenc470f442003-07-28 09:56:35 +000010939
10940 (*nlpp)->n = n;
10941 if (oldstyle) {
10942 /*
10943 * Start reading from old file again, ignoring any pushed back
10944 * tokens left from the backquote parsing
10945 */
10946 popfile();
10947 tokpushback = 0;
10948 }
10949 while (stackblocksize() <= savelen)
10950 growstackblock();
10951 STARTSTACKSTR(out);
10952 if (str) {
10953 memcpy(out, str, savelen);
10954 STADJUST(savelen, out);
Denis Vlasenkob012b102007-02-19 22:43:01 +000010955 INT_OFF;
10956 free(str);
Eric Andersenc470f442003-07-28 09:56:35 +000010957 str = NULL;
Denis Vlasenkob012b102007-02-19 22:43:01 +000010958 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +000010959 }
10960 parsebackquote = savepbq;
Denis Vlasenko2da584f2007-02-19 22:44:05 +000010961 exception_handler = savehandler;
Eric Andersenc470f442003-07-28 09:56:35 +000010962 if (arinest || dblquote)
10963 USTPUTC(CTLBACKQ | CTLQUOTE, out);
10964 else
10965 USTPUTC(CTLBACKQ, out);
10966 if (oldstyle)
10967 goto parsebackq_oldreturn;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010968 goto parsebackq_newreturn;
Eric Andersenc470f442003-07-28 09:56:35 +000010969}
10970
Denis Vlasenko131ae172007-02-18 13:00:19 +000010971#if ENABLE_ASH_MATH_SUPPORT
Eric Andersencb57d552001-06-28 07:25:16 +000010972/*
10973 * Parse an arithmetic expansion (indicate start of one and set state)
10974 */
Eric Andersenc470f442003-07-28 09:56:35 +000010975parsearith: {
Eric Andersenc470f442003-07-28 09:56:35 +000010976 if (++arinest == 1) {
10977 prevsyntax = syntax;
10978 syntax = ARISYNTAX;
10979 USTPUTC(CTLARI, out);
10980 if (dblquote)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010981 USTPUTC('"', out);
Eric Andersenc470f442003-07-28 09:56:35 +000010982 else
Denis Vlasenkoa624c112007-02-19 22:45:43 +000010983 USTPUTC(' ', out);
Eric Andersenc470f442003-07-28 09:56:35 +000010984 } else {
10985 /*
10986 * we collapse embedded arithmetic expansion to
10987 * parenthesis, which should be equivalent
10988 */
10989 USTPUTC('(', out);
Eric Andersencb57d552001-06-28 07:25:16 +000010990 }
Eric Andersenc470f442003-07-28 09:56:35 +000010991 goto parsearith_return;
10992}
10993#endif
Eric Andersencb57d552001-06-28 07:25:16 +000010994
Eric Andersenc470f442003-07-28 09:56:35 +000010995} /* end of readtoken */
10996
Eric Andersencb57d552001-06-28 07:25:16 +000010997/*
Denis Vlasenkoaa744452007-02-23 01:04:22 +000010998 * Read the next input token.
10999 * If the token is a word, we set backquotelist to the list of cmds in
11000 * backquotes. We set quoteflag to true if any part of the word was
11001 * quoted.
11002 * If the token is TREDIR, then we set redirnode to a structure containing
11003 * the redirection.
11004 * In all cases, the variable startlinno is set to the number of the line
11005 * on which the token starts.
11006 *
11007 * [Change comment: here documents and internal procedures]
11008 * [Readtoken shouldn't have any arguments. Perhaps we should make the
11009 * word parsing code into a separate routine. In this case, readtoken
11010 * doesn't need to have any internal procedures, but parseword does.
11011 * We could also make parseoperator in essence the main routine, and
11012 * have parseword (readtoken1?) handle both words and redirection.]
Eric Andersencb57d552001-06-28 07:25:16 +000011013 */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011014#define NEW_xxreadtoken
11015#ifdef NEW_xxreadtoken
11016/* singles must be first! */
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011017static const char xxreadtoken_chars[7] ALIGN1 = {
11018 '\n', '(', ')', '&', '|', ';', 0
11019};
Eric Andersencb57d552001-06-28 07:25:16 +000011020
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011021static const char xxreadtoken_tokens[] ALIGN1 = {
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011022 TNL, TLP, TRP, /* only single occurrence allowed */
11023 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
11024 TEOF, /* corresponds to trailing nul */
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011025 TAND, TOR, TENDCASE /* if double occurrence */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011026};
11027
11028#define xxreadtoken_doubles \
11029 (sizeof(xxreadtoken_tokens) - sizeof(xxreadtoken_chars))
11030#define xxreadtoken_singles \
11031 (sizeof(xxreadtoken_chars) - xxreadtoken_doubles - 1)
11032
11033static int
11034xxreadtoken(void)
11035{
11036 int c;
11037
11038 if (tokpushback) {
11039 tokpushback = 0;
11040 return lasttoken;
Eric Andersencb57d552001-06-28 07:25:16 +000011041 }
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011042 if (needprompt) {
11043 setprompt(2);
11044 }
11045 startlinno = plinno;
11046 for (;;) { /* until token or start of word found */
11047 c = pgetc_macro();
11048
11049 if ((c != ' ') && (c != '\t')
11050#if ENABLE_ASH_ALIAS
11051 && (c != PEOA)
11052#endif
11053 ) {
11054 if (c == '#') {
Denis Vlasenkof7d56652008-03-25 05:51:41 +000011055 while ((c = pgetc()) != '\n' && c != PEOF)
11056 continue;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011057 pungetc();
11058 } else if (c == '\\') {
11059 if (pgetc() != '\n') {
11060 pungetc();
11061 goto READTOKEN1;
11062 }
11063 startlinno = ++plinno;
11064 if (doprompt)
11065 setprompt(2);
11066 } else {
11067 const char *p
11068 = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
11069
11070 if (c != PEOF) {
11071 if (c == '\n') {
11072 plinno++;
11073 needprompt = doprompt;
11074 }
11075
11076 p = strchr(xxreadtoken_chars, c);
11077 if (p == NULL) {
11078 READTOKEN1:
11079 return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
11080 }
11081
11082 if (p - xxreadtoken_chars >= xxreadtoken_singles) {
11083 if (pgetc() == *p) { /* double occurrence? */
11084 p += xxreadtoken_doubles + 1;
11085 } else {
11086 pungetc();
11087 }
11088 }
11089 }
11090 return lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
11091 }
11092 }
11093 } /* for */
11094}
11095#else
11096#define RETURN(token) return lasttoken = token
11097static int
11098xxreadtoken(void)
11099{
11100 int c;
11101
11102 if (tokpushback) {
11103 tokpushback = 0;
11104 return lasttoken;
11105 }
11106 if (needprompt) {
11107 setprompt(2);
11108 }
11109 startlinno = plinno;
11110 for (;;) { /* until token or start of word found */
11111 c = pgetc_macro();
11112 switch (c) {
11113 case ' ': case '\t':
11114#if ENABLE_ASH_ALIAS
11115 case PEOA:
11116#endif
11117 continue;
11118 case '#':
Denis Vlasenkof7d56652008-03-25 05:51:41 +000011119 while ((c = pgetc()) != '\n' && c != PEOF)
11120 continue;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011121 pungetc();
11122 continue;
11123 case '\\':
11124 if (pgetc() == '\n') {
11125 startlinno = ++plinno;
11126 if (doprompt)
11127 setprompt(2);
11128 continue;
11129 }
11130 pungetc();
11131 goto breakloop;
11132 case '\n':
11133 plinno++;
11134 needprompt = doprompt;
11135 RETURN(TNL);
11136 case PEOF:
11137 RETURN(TEOF);
11138 case '&':
11139 if (pgetc() == '&')
11140 RETURN(TAND);
11141 pungetc();
11142 RETURN(TBACKGND);
11143 case '|':
11144 if (pgetc() == '|')
11145 RETURN(TOR);
11146 pungetc();
11147 RETURN(TPIPE);
11148 case ';':
11149 if (pgetc() == ';')
11150 RETURN(TENDCASE);
11151 pungetc();
11152 RETURN(TSEMI);
11153 case '(':
11154 RETURN(TLP);
11155 case ')':
11156 RETURN(TRP);
11157 default:
11158 goto breakloop;
11159 }
11160 }
11161 breakloop:
11162 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
11163#undef RETURN
11164}
11165#endif /* NEW_xxreadtoken */
11166
11167static int
11168readtoken(void)
11169{
11170 int t;
11171#if DEBUG
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011172 smallint alreadyseen = tokpushback;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011173#endif
11174
11175#if ENABLE_ASH_ALIAS
11176 top:
11177#endif
11178
11179 t = xxreadtoken();
11180
11181 /*
11182 * eat newlines
11183 */
11184 if (checkkwd & CHKNL) {
11185 while (t == TNL) {
11186 parseheredoc();
11187 t = xxreadtoken();
11188 }
11189 }
11190
11191 if (t != TWORD || quoteflag) {
11192 goto out;
11193 }
11194
11195 /*
11196 * check for keywords
11197 */
11198 if (checkkwd & CHKKWD) {
11199 const char *const *pp;
11200
11201 pp = findkwd(wordtext);
11202 if (pp) {
11203 lasttoken = t = pp - tokname_array;
11204 TRACE(("keyword %s recognized\n", tokname(t)));
11205 goto out;
11206 }
11207 }
11208
11209 if (checkkwd & CHKALIAS) {
11210#if ENABLE_ASH_ALIAS
11211 struct alias *ap;
11212 ap = lookupalias(wordtext, 1);
11213 if (ap != NULL) {
11214 if (*ap->val) {
11215 pushstring(ap->val, ap);
11216 }
11217 goto top;
11218 }
11219#endif
11220 }
11221 out:
11222 checkkwd = 0;
11223#if DEBUG
11224 if (!alreadyseen)
11225 TRACE(("token %s %s\n", tokname(t), t == TWORD ? wordtext : ""));
11226 else
11227 TRACE(("reread token %s %s\n", tokname(t), t == TWORD ? wordtext : ""));
11228#endif
11229 return t;
Eric Andersencb57d552001-06-28 07:25:16 +000011230}
11231
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011232static char
11233peektoken(void)
11234{
11235 int t;
11236
11237 t = readtoken();
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011238 tokpushback = 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011239 return tokname_array[t][0];
11240}
Eric Andersencb57d552001-06-28 07:25:16 +000011241
11242/*
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011243 * Read and parse a command. Returns NEOF on end of file. (NULL is a
11244 * valid parse tree indicating a blank line.)
Eric Andersencb57d552001-06-28 07:25:16 +000011245 */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011246static union node *
11247parsecmd(int interact)
Eric Andersen90898442003-08-06 11:20:52 +000011248{
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011249 int t;
Eric Andersencb57d552001-06-28 07:25:16 +000011250
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011251 tokpushback = 0;
11252 doprompt = interact;
11253 if (doprompt)
11254 setprompt(doprompt);
11255 needprompt = 0;
11256 t = readtoken();
11257 if (t == TEOF)
11258 return NEOF;
11259 if (t == TNL)
11260 return NULL;
Denis Vlasenkobcceb0c2007-09-21 18:06:20 +000011261 tokpushback = 1;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011262 return list(1);
11263}
11264
11265/*
11266 * Input any here documents.
11267 */
11268static void
11269parseheredoc(void)
11270{
11271 struct heredoc *here;
11272 union node *n;
11273
11274 here = heredoclist;
Denis Vlasenko838ffd52008-02-21 04:32:08 +000011275 heredoclist = NULL;
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011276
11277 while (here) {
11278 if (needprompt) {
11279 setprompt(2);
11280 }
11281 readtoken1(pgetc(), here->here->type == NHERE? SQSYNTAX : DQSYNTAX,
11282 here->eofmark, here->striptabs);
Denis Vlasenko597906c2008-02-20 16:38:54 +000011283 n = stzalloc(sizeof(struct narg));
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011284 n->narg.type = NARG;
Denis Vlasenko597906c2008-02-20 16:38:54 +000011285 /*n->narg.next = NULL; - stzalloc did it */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011286 n->narg.text = wordtext;
11287 n->narg.backquote = backquotelist;
11288 here->here->nhere.doc = n;
11289 here = here->next;
Eric Andersencb57d552001-06-28 07:25:16 +000011290 }
Eric Andersencb57d552001-06-28 07:25:16 +000011291}
11292
11293
11294/*
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +000011295 * called by editline -- any expansions to the prompt should be added here.
Eric Andersencb57d552001-06-28 07:25:16 +000011296 */
Denis Vlasenko131ae172007-02-18 13:00:19 +000011297#if ENABLE_ASH_EXPAND_PRMT
"Vladimir N. Oleynik"bef14d72005-09-05 13:25:11 +000011298static const char *
11299expandstr(const char *ps)
11300{
11301 union node n;
11302
11303 /* XXX Fix (char *) cast. */
11304 setinputstring((char *)ps);
Denis Vlasenko46a53062007-09-24 18:30:02 +000011305 readtoken1(pgetc(), PSSYNTAX, nullstr, 0);
"Vladimir N. Oleynik"bef14d72005-09-05 13:25:11 +000011306 popfile();
11307
11308 n.narg.type = NARG;
11309 n.narg.next = NULL;
11310 n.narg.text = wordtext;
11311 n.narg.backquote = backquotelist;
11312
11313 expandarg(&n, NULL, 0);
11314 return stackblock();
11315}
11316#endif
11317
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011318/*
11319 * Execute a command or commands contained in a string.
11320 */
11321static int
11322evalstring(char *s, int mask)
Eric Andersenc470f442003-07-28 09:56:35 +000011323{
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011324 union node *n;
11325 struct stackmark smark;
11326 int skip;
11327
11328 setinputstring(s);
11329 setstackmark(&smark);
11330
11331 skip = 0;
11332 while ((n = parsecmd(0)) != NEOF) {
11333 evaltree(n, 0);
11334 popstackmark(&smark);
11335 skip = evalskip;
11336 if (skip)
11337 break;
11338 }
11339 popfile();
11340
11341 skip &= mask;
11342 evalskip = skip;
11343 return skip;
Eric Andersenc470f442003-07-28 09:56:35 +000011344}
11345
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011346/*
11347 * The eval command.
11348 */
11349static int
Denis Vlasenko68404f12008-03-17 09:00:54 +000011350evalcmd(int argc ATTRIBUTE_UNUSED, char **argv)
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011351{
11352 char *p;
11353 char *concat;
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011354
Denis Vlasenko68404f12008-03-17 09:00:54 +000011355 if (argv[1]) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011356 p = argv[1];
Denis Vlasenko68404f12008-03-17 09:00:54 +000011357 argv += 2;
11358 if (argv[0]) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011359 STARTSTACKSTR(concat);
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011360 for (;;) {
11361 concat = stack_putstr(p, concat);
Denis Vlasenko68404f12008-03-17 09:00:54 +000011362 p = *argv++;
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011363 if (p == NULL)
11364 break;
11365 STPUTC(' ', concat);
11366 }
11367 STPUTC('\0', concat);
11368 p = grabstackstr(concat);
11369 }
11370 evalstring(p, ~SKIPEVAL);
11371
11372 }
11373 return exitstatus;
11374}
11375
11376/*
11377 * Read and execute commands. "Top" is nonzero for the top level command
11378 * loop; it turns on prompting if the shell is interactive.
11379 */
11380static int
11381cmdloop(int top)
11382{
11383 union node *n;
11384 struct stackmark smark;
11385 int inter;
11386 int numeof = 0;
11387
11388 TRACE(("cmdloop(%d) called\n", top));
11389 for (;;) {
11390 int skip;
11391
11392 setstackmark(&smark);
11393#if JOBS
11394 if (jobctl)
11395 showjobs(stderr, SHOW_CHANGED);
11396#endif
11397 inter = 0;
11398 if (iflag && top) {
11399 inter++;
11400#if ENABLE_ASH_MAIL
11401 chkmail();
11402#endif
11403 }
11404 n = parsecmd(inter);
11405 /* showtree(n); DEBUG */
11406 if (n == NEOF) {
11407 if (!top || numeof >= 50)
11408 break;
11409 if (!stoppedjobs()) {
11410 if (!Iflag)
11411 break;
11412 out2str("\nUse \"exit\" to leave shell.\n");
11413 }
11414 numeof++;
11415 } else if (nflag == 0) {
Denis Vlasenkofcfaf2e2007-07-14 18:45:37 +000011416 /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
11417 job_warning >>= 1;
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011418 numeof = 0;
11419 evaltree(n, 0);
11420 }
11421 popstackmark(&smark);
11422 skip = evalskip;
11423
11424 if (skip) {
11425 evalskip = 0;
11426 return skip & SKIPEVAL;
11427 }
11428 }
11429 return 0;
11430}
11431
Denis Vlasenko0dec6de2007-02-23 21:10:47 +000011432/*
11433 * Take commands from a file. To be compatible we should do a path
11434 * search for the file, which is necessary to find sub-commands.
11435 */
11436static char *
11437find_dot_file(char *name)
11438{
11439 char *fullname;
11440 const char *path = pathval();
11441 struct stat statb;
11442
11443 /* don't try this for absolute or relative paths */
11444 if (strchr(name, '/'))
11445 return name;
11446
11447 while ((fullname = padvance(&path, name)) != NULL) {
11448 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
11449 /*
11450 * Don't bother freeing here, since it will
11451 * be freed by the caller.
11452 */
11453 return fullname;
11454 }
11455 stunalloc(fullname);
11456 }
11457
11458 /* not found in the PATH */
11459 ash_msg_and_raise_error("%s: not found", name);
11460 /* NOTREACHED */
11461}
11462
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011463static int
11464dotcmd(int argc, char **argv)
11465{
11466 struct strlist *sp;
11467 volatile struct shparam saveparam;
11468 int status = 0;
11469
11470 for (sp = cmdenviron; sp; sp = sp->next)
Denis Vlasenko4222ae42007-02-25 02:37:49 +000011471 setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011472
Denis Vlasenko68404f12008-03-17 09:00:54 +000011473 if (argv[1]) { /* That's what SVR2 does */
11474 char *fullname = find_dot_file(argv[1]);
11475 argv += 2;
11476 argc -= 2;
11477 if (argc) { /* argc > 0, argv[0] != NULL */
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011478 saveparam = shellparam;
Denis Vlasenko01631112007-12-16 17:20:38 +000011479 shellparam.malloced = 0;
Denis Vlasenko68404f12008-03-17 09:00:54 +000011480 shellparam.nparam = argc;
11481 shellparam.p = argv;
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011482 };
11483
11484 setinputfile(fullname, INPUT_PUSH_FILE);
11485 commandname = fullname;
11486 cmdloop(0);
11487 popfile();
11488
Denis Vlasenko68404f12008-03-17 09:00:54 +000011489 if (argc) {
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011490 freeparam(&shellparam);
11491 shellparam = saveparam;
11492 };
11493 status = exitstatus;
11494 }
11495 return status;
11496}
11497
11498static int
Denis Vlasenko68404f12008-03-17 09:00:54 +000011499exitcmd(int argc ATTRIBUTE_UNUSED, char **argv)
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011500{
11501 if (stoppedjobs())
11502 return 0;
Denis Vlasenko68404f12008-03-17 09:00:54 +000011503 if (argv[1])
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011504 exitstatus = number(argv[1]);
11505 raise_exception(EXEXIT);
11506 /* NOTREACHED */
11507}
11508
11509#if ENABLE_ASH_BUILTIN_ECHO
11510static int
11511echocmd(int argc, char **argv)
11512{
Denis Vlasenkofe5e23b2007-11-24 02:23:51 +000011513 return echo_main(argc, argv);
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011514}
11515#endif
11516
11517#if ENABLE_ASH_BUILTIN_TEST
11518static int
11519testcmd(int argc, char **argv)
11520{
Denis Vlasenkob304ead2007-06-21 13:35:52 +000011521 return test_main(argc, argv);
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011522}
11523#endif
11524
11525/*
11526 * Read a file containing shell functions.
11527 */
11528static void
11529readcmdfile(char *name)
11530{
11531 setinputfile(name, INPUT_PUSH_FILE);
11532 cmdloop(0);
11533 popfile();
11534}
11535
11536
Denis Vlasenkocc571512007-02-23 21:10:35 +000011537/* ============ find_command inplementation */
11538
11539/*
11540 * Resolve a command name. If you change this routine, you may have to
11541 * change the shellexec routine as well.
11542 */
11543static void
11544find_command(char *name, struct cmdentry *entry, int act, const char *path)
11545{
11546 struct tblentry *cmdp;
11547 int idx;
11548 int prev;
11549 char *fullname;
11550 struct stat statb;
11551 int e;
11552 int updatetbl;
11553 struct builtincmd *bcmd;
11554
11555 /* If name contains a slash, don't use PATH or hash table */
11556 if (strchr(name, '/') != NULL) {
11557 entry->u.index = -1;
11558 if (act & DO_ABS) {
11559 while (stat(name, &statb) < 0) {
11560#ifdef SYSV
11561 if (errno == EINTR)
11562 continue;
11563#endif
11564 entry->cmdtype = CMDUNKNOWN;
11565 return;
11566 }
11567 }
11568 entry->cmdtype = CMDNORMAL;
11569 return;
11570 }
11571
Denis Vlasenkof20de5b2007-04-29 23:42:54 +000011572/* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
Denis Vlasenkocc571512007-02-23 21:10:35 +000011573
11574 updatetbl = (path == pathval());
11575 if (!updatetbl) {
11576 act |= DO_ALTPATH;
11577 if (strstr(path, "%builtin") != NULL)
11578 act |= DO_ALTBLTIN;
11579 }
11580
11581 /* If name is in the table, check answer will be ok */
11582 cmdp = cmdlookup(name, 0);
11583 if (cmdp != NULL) {
11584 int bit;
11585
11586 switch (cmdp->cmdtype) {
11587 default:
11588#if DEBUG
11589 abort();
11590#endif
11591 case CMDNORMAL:
11592 bit = DO_ALTPATH;
11593 break;
11594 case CMDFUNCTION:
11595 bit = DO_NOFUNC;
11596 break;
11597 case CMDBUILTIN:
11598 bit = DO_ALTBLTIN;
11599 break;
11600 }
11601 if (act & bit) {
11602 updatetbl = 0;
11603 cmdp = NULL;
11604 } else if (cmdp->rehash == 0)
11605 /* if not invalidated by cd, we're done */
11606 goto success;
11607 }
11608
11609 /* If %builtin not in path, check for builtin next */
11610 bcmd = find_builtin(name);
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +000011611 if (bcmd) {
11612 if (IS_BUILTIN_REGULAR(bcmd))
11613 goto builtin_success;
11614 if (act & DO_ALTPATH) {
11615 if (!(act & DO_ALTBLTIN))
11616 goto builtin_success;
11617 } else if (builtinloc <= 0) {
11618 goto builtin_success;
Denis Vlasenko8e858e22007-03-07 09:35:43 +000011619 }
Denis Vlasenkof98dc4d2007-02-23 21:11:02 +000011620 }
Denis Vlasenkocc571512007-02-23 21:10:35 +000011621
Denis Vlasenkof20de5b2007-04-29 23:42:54 +000011622#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko1aa7e472007-11-28 06:49:03 +000011623 if (find_applet_by_name(name) >= 0) {
Denis Vlasenkof20de5b2007-04-29 23:42:54 +000011624 entry->cmdtype = CMDNORMAL;
11625 entry->u.index = -1;
11626 return;
11627 }
11628#endif
11629
Denis Vlasenkocc571512007-02-23 21:10:35 +000011630 /* We have to search path. */
11631 prev = -1; /* where to start */
11632 if (cmdp && cmdp->rehash) { /* doing a rehash */
11633 if (cmdp->cmdtype == CMDBUILTIN)
11634 prev = builtinloc;
11635 else
11636 prev = cmdp->param.index;
11637 }
11638
11639 e = ENOENT;
11640 idx = -1;
11641 loop:
11642 while ((fullname = padvance(&path, name)) != NULL) {
11643 stunalloc(fullname);
Denis Vlasenkodee82b62007-07-29 14:05:27 +000011644 /* NB: code below will still use fullname
11645 * despite it being "unallocated" */
Denis Vlasenkocc571512007-02-23 21:10:35 +000011646 idx++;
11647 if (pathopt) {
11648 if (prefix(pathopt, "builtin")) {
11649 if (bcmd)
11650 goto builtin_success;
11651 continue;
Denis Vlasenkodee82b62007-07-29 14:05:27 +000011652 } else if (!(act & DO_NOFUNC)
11653 && prefix(pathopt, "func")) {
Denis Vlasenkocc571512007-02-23 21:10:35 +000011654 /* handled below */
11655 } else {
11656 /* ignore unimplemented options */
11657 continue;
11658 }
11659 }
11660 /* if rehash, don't redo absolute path names */
11661 if (fullname[0] == '/' && idx <= prev) {
11662 if (idx < prev)
11663 continue;
11664 TRACE(("searchexec \"%s\": no change\n", name));
11665 goto success;
11666 }
11667 while (stat(fullname, &statb) < 0) {
11668#ifdef SYSV
11669 if (errno == EINTR)
11670 continue;
11671#endif
11672 if (errno != ENOENT && errno != ENOTDIR)
11673 e = errno;
11674 goto loop;
11675 }
11676 e = EACCES; /* if we fail, this will be the error */
11677 if (!S_ISREG(statb.st_mode))
11678 continue;
11679 if (pathopt) { /* this is a %func directory */
11680 stalloc(strlen(fullname) + 1);
Denis Vlasenkodee82b62007-07-29 14:05:27 +000011681 /* NB: stalloc will return space pointed by fullname
11682 * (because we don't have any intervening allocations
11683 * between stunalloc above and this stalloc) */
Denis Vlasenkocc571512007-02-23 21:10:35 +000011684 readcmdfile(fullname);
11685 cmdp = cmdlookup(name, 0);
11686 if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
11687 ash_msg_and_raise_error("%s not defined in %s", name, fullname);
11688 stunalloc(fullname);
11689 goto success;
11690 }
11691 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
11692 if (!updatetbl) {
11693 entry->cmdtype = CMDNORMAL;
11694 entry->u.index = idx;
11695 return;
11696 }
11697 INT_OFF;
11698 cmdp = cmdlookup(name, 1);
11699 cmdp->cmdtype = CMDNORMAL;
11700 cmdp->param.index = idx;
11701 INT_ON;
11702 goto success;
11703 }
11704
11705 /* We failed. If there was an entry for this command, delete it */
11706 if (cmdp && updatetbl)
11707 delete_cmd_entry();
11708 if (act & DO_ERR)
11709 ash_msg("%s: %s", name, errmsg(e, "not found"));
11710 entry->cmdtype = CMDUNKNOWN;
11711 return;
11712
11713 builtin_success:
11714 if (!updatetbl) {
11715 entry->cmdtype = CMDBUILTIN;
11716 entry->u.cmd = bcmd;
11717 return;
11718 }
11719 INT_OFF;
11720 cmdp = cmdlookup(name, 1);
11721 cmdp->cmdtype = CMDBUILTIN;
11722 cmdp->param.cmd = bcmd;
11723 INT_ON;
11724 success:
11725 cmdp->rehash = 0;
11726 entry->cmdtype = cmdp->cmdtype;
11727 entry->u = cmdp->param;
11728}
11729
11730
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000011731/* ============ trap.c */
Eric Andersenc470f442003-07-28 09:56:35 +000011732
Eric Andersencb57d552001-06-28 07:25:16 +000011733/*
Eric Andersencb57d552001-06-28 07:25:16 +000011734 * The trap builtin.
11735 */
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011736static int
Denis Vlasenko68404f12008-03-17 09:00:54 +000011737trapcmd(int argc ATTRIBUTE_UNUSED, char **argv ATTRIBUTE_UNUSED)
Eric Andersencb57d552001-06-28 07:25:16 +000011738{
11739 char *action;
11740 char **ap;
11741 int signo;
11742
Eric Andersenc470f442003-07-28 09:56:35 +000011743 nextopt(nullstr);
11744 ap = argptr;
11745 if (!*ap) {
Denis Vlasenko2da584f2007-02-19 22:44:05 +000011746 for (signo = 0; signo < NSIG; signo++) {
Eric Andersencb57d552001-06-28 07:25:16 +000011747 if (trap[signo] != NULL) {
Eric Andersen34506362001-08-02 05:02:46 +000011748 const char *sn;
Eric Andersencb57d552001-06-28 07:25:16 +000011749
Rob Landleyc9c1a412006-07-12 19:17:55 +000011750 sn = get_signame(signo);
Eric Andersenc470f442003-07-28 09:56:35 +000011751 out1fmt("trap -- %s %s\n",
11752 single_quote(trap[signo]), sn);
Eric Andersencb57d552001-06-28 07:25:16 +000011753 }
11754 }
11755 return 0;
11756 }
Eric Andersenc470f442003-07-28 09:56:35 +000011757 if (!ap[1])
Eric Andersencb57d552001-06-28 07:25:16 +000011758 action = NULL;
11759 else
11760 action = *ap++;
11761 while (*ap) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011762 signo = get_signum(*ap);
11763 if (signo < 0)
Denis Vlasenkob012b102007-02-19 22:43:01 +000011764 ash_msg_and_raise_error("%s: bad trap", *ap);
11765 INT_OFF;
Eric Andersencb57d552001-06-28 07:25:16 +000011766 if (action) {
Denis Vlasenko9f739442006-12-16 23:49:13 +000011767 if (LONE_DASH(action))
Eric Andersencb57d552001-06-28 07:25:16 +000011768 action = NULL;
11769 else
Denis Vlasenko0c032a42007-02-23 01:03:40 +000011770 action = ckstrdup(action);
Eric Andersencb57d552001-06-28 07:25:16 +000011771 }
Denis Vlasenko60818682007-09-28 22:07:23 +000011772 free(trap[signo]);
Eric Andersencb57d552001-06-28 07:25:16 +000011773 trap[signo] = action;
11774 if (signo != 0)
11775 setsignal(signo);
Denis Vlasenkob012b102007-02-19 22:43:01 +000011776 INT_ON;
Eric Andersencb57d552001-06-28 07:25:16 +000011777 ap++;
11778 }
11779 return 0;
11780}
11781
Eric Andersenc470f442003-07-28 09:56:35 +000011782
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000011783/* ============ Builtins */
Eric Andersenc470f442003-07-28 09:56:35 +000011784
Denis Vlasenko8e1c7152007-01-22 07:21:38 +000011785#if !ENABLE_FEATURE_SH_EXTRA_QUIET
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000011786/*
11787 * Lists available builtins
11788 */
Denis Vlasenkoaa744452007-02-23 01:04:22 +000011789static int
Denis Vlasenko68404f12008-03-17 09:00:54 +000011790helpcmd(int argc ATTRIBUTE_UNUSED, char **argv ATTRIBUTE_UNUSED)
Eric Andersenc470f442003-07-28 09:56:35 +000011791{
11792 int col, i;
11793
11794 out1fmt("\nBuilt-in commands:\n-------------------\n");
Denis Vlasenkob71c6682007-07-21 15:08:09 +000011795 for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
Eric Andersenc470f442003-07-28 09:56:35 +000011796 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
Denis Vlasenko52764022007-02-24 13:42:56 +000011797 builtintab[i].name + 1);
Eric Andersenc470f442003-07-28 09:56:35 +000011798 if (col > 60) {
11799 out1fmt("\n");
11800 col = 0;
11801 }
11802 }
Denis Vlasenko80d14be2007-04-10 23:03:30 +000011803#if ENABLE_FEATURE_SH_STANDALONE
Denis Vlasenko1aa7e472007-11-28 06:49:03 +000011804 {
11805 const char *a = applet_names;
11806 while (*a) {
11807 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
11808 if (col > 60) {
11809 out1fmt("\n");
11810 col = 0;
11811 }
11812 a += strlen(a) + 1;
Eric Andersenc470f442003-07-28 09:56:35 +000011813 }
11814 }
11815#endif
11816 out1fmt("\n\n");
11817 return EXIT_SUCCESS;
11818}
Denis Vlasenko131ae172007-02-18 13:00:19 +000011819#endif /* FEATURE_SH_EXTRA_QUIET */
Eric Andersenc470f442003-07-28 09:56:35 +000011820
Eric Andersencb57d552001-06-28 07:25:16 +000011821/*
Eric Andersencb57d552001-06-28 07:25:16 +000011822 * The export and readonly commands.
11823 */
Eric Andersenc470f442003-07-28 09:56:35 +000011824static int
Denis Vlasenko68404f12008-03-17 09:00:54 +000011825exportcmd(int argc ATTRIBUTE_UNUSED, char **argv)
Eric Andersencb57d552001-06-28 07:25:16 +000011826{
11827 struct var *vp;
11828 char *name;
11829 const char *p;
Eric Andersenc470f442003-07-28 09:56:35 +000011830 char **aptr;
11831 int flag = argv[0][0] == 'r'? VREADONLY : VEXPORT;
Eric Andersencb57d552001-06-28 07:25:16 +000011832
Denis Vlasenko2da584f2007-02-19 22:44:05 +000011833 if (nextopt("p") != 'p') {
11834 aptr = argptr;
11835 name = *aptr;
11836 if (name) {
11837 do {
11838 p = strchr(name, '=');
11839 if (p != NULL) {
11840 p++;
11841 } else {
11842 vp = *findvar(hashvar(name), name);
11843 if (vp) {
11844 vp->flags |= flag;
11845 continue;
11846 }
Eric Andersencb57d552001-06-28 07:25:16 +000011847 }
Denis Vlasenko2da584f2007-02-19 22:44:05 +000011848 setvar(name, p, flag);
11849 } while ((name = *++aptr) != NULL);
11850 return 0;
11851 }
Eric Andersencb57d552001-06-28 07:25:16 +000011852 }
Denis Vlasenko2da584f2007-02-19 22:44:05 +000011853 showvars(argv[0], flag, 0);
Eric Andersencb57d552001-06-28 07:25:16 +000011854 return 0;
11855}
11856
Eric Andersencb57d552001-06-28 07:25:16 +000011857/*
Denis Vlasenko5651bfc2007-02-23 21:08:58 +000011858 * Delete a function if it exists.
Eric Andersencb57d552001-06-28 07:25:16 +000011859 */
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000011860static void
Denis Vlasenko5651bfc2007-02-23 21:08:58 +000011861unsetfunc(const char *name)
Aaron Lehmannb6ecbdc2001-12-06 03:37:38 +000011862{
Denis Vlasenko5651bfc2007-02-23 21:08:58 +000011863 struct tblentry *cmdp;
Eric Andersencb57d552001-06-28 07:25:16 +000011864
Denis Vlasenko5651bfc2007-02-23 21:08:58 +000011865 cmdp = cmdlookup(name, 0);
11866 if (cmdp!= NULL && cmdp->cmdtype == CMDFUNCTION)
11867 delete_cmd_entry();
Eric Andersenc470f442003-07-28 09:56:35 +000011868}
11869
Eric Andersencb57d552001-06-28 07:25:16 +000011870/*
Eric Andersencb57d552001-06-28 07:25:16 +000011871 * The unset builtin command. We unset the function before we unset the
11872 * variable to allow a function to be unset when there is a readonly variable
11873 * with the same name.
11874 */
Denis Vlasenko5cedb752007-02-18 19:56:41 +000011875static int
Denis Vlasenko68404f12008-03-17 09:00:54 +000011876unsetcmd(int argc ATTRIBUTE_UNUSED, char **argv ATTRIBUTE_UNUSED)
Eric Andersencb57d552001-06-28 07:25:16 +000011877{
11878 char **ap;
11879 int i;
Eric Andersenc470f442003-07-28 09:56:35 +000011880 int flag = 0;
Eric Andersencb57d552001-06-28 07:25:16 +000011881 int ret = 0;
11882
11883 while ((i = nextopt("vf")) != '\0') {
Eric Andersenc470f442003-07-28 09:56:35 +000011884 flag = i;
Eric Andersencb57d552001-06-28 07:25:16 +000011885 }
Eric Andersencb57d552001-06-28 07:25:16 +000011886
Denis Vlasenko2da584f2007-02-19 22:44:05 +000011887 for (ap = argptr; *ap; ap++) {
Eric Andersenc470f442003-07-28 09:56:35 +000011888 if (flag != 'f') {
11889 i = unsetvar(*ap);
11890 ret |= i;
11891 if (!(i & 2))
11892 continue;
11893 }
11894 if (flag != 'v')
Eric Andersencb57d552001-06-28 07:25:16 +000011895 unsetfunc(*ap);
Eric Andersencb57d552001-06-28 07:25:16 +000011896 }
Eric Andersenc470f442003-07-28 09:56:35 +000011897 return ret & 1;
Eric Andersencb57d552001-06-28 07:25:16 +000011898}
11899
11900
"Vladimir N. Oleynik"fb29b462006-01-15 14:21:01 +000011901/* setmode.c */
Eric Andersencb57d552001-06-28 07:25:16 +000011902
Eric Andersenc470f442003-07-28 09:56:35 +000011903#include <sys/times.h>
11904
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000011905static const unsigned char timescmd_str[] ALIGN1 = {
Manuel Novoa III 4456f252003-08-13 17:48:47 +000011906 ' ', offsetof(struct tms, tms_utime),
11907 '\n', offsetof(struct tms, tms_stime),
11908 ' ', offsetof(struct tms, tms_cutime),
11909 '\n', offsetof(struct tms, tms_cstime),
11910 0
11911};
Eric Andersencb57d552001-06-28 07:25:16 +000011912
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000011913static int
Denis Vlasenko68404f12008-03-17 09:00:54 +000011914timescmd(int argc ATTRIBUTE_UNUSED, char **argv ATTRIBUTE_UNUSED)
Manuel Novoa III 4456f252003-08-13 17:48:47 +000011915{
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000011916 long clk_tck, s, t;
Manuel Novoa III 4456f252003-08-13 17:48:47 +000011917 const unsigned char *p;
11918 struct tms buf;
11919
11920 clk_tck = sysconf(_SC_CLK_TCK);
Eric Andersencb57d552001-06-28 07:25:16 +000011921 times(&buf);
Manuel Novoa III 4456f252003-08-13 17:48:47 +000011922
11923 p = timescmd_str;
11924 do {
11925 t = *(clock_t *)(((char *) &buf) + p[1]);
11926 s = t / clk_tck;
11927 out1fmt("%ldm%ld.%.3lds%c",
11928 s/60, s%60,
11929 ((t - s * clk_tck) * 1000) / clk_tck,
11930 p[0]);
11931 } while (*(p += 2));
11932
Eric Andersencb57d552001-06-28 07:25:16 +000011933 return 0;
11934}
11935
Denis Vlasenko131ae172007-02-18 13:00:19 +000011936#if ENABLE_ASH_MATH_SUPPORT
Eric Andersened9ecf72004-06-22 08:29:45 +000011937static arith_t
Eric Andersenc470f442003-07-28 09:56:35 +000011938dash_arith(const char *s)
Eric Andersen74bcd162001-07-30 21:41:37 +000011939{
Eric Andersened9ecf72004-06-22 08:29:45 +000011940 arith_t result;
Eric Andersenc470f442003-07-28 09:56:35 +000011941 int errcode = 0;
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000011942
Denis Vlasenkob012b102007-02-19 22:43:01 +000011943 INT_OFF;
Eric Andersenc470f442003-07-28 09:56:35 +000011944 result = arith(s, &errcode);
11945 if (errcode < 0) {
Eric Andersen90898442003-08-06 11:20:52 +000011946 if (errcode == -3)
Denis Vlasenkob012b102007-02-19 22:43:01 +000011947 ash_msg_and_raise_error("exponent less than 0");
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000011948 if (errcode == -2)
Denis Vlasenkob012b102007-02-19 22:43:01 +000011949 ash_msg_and_raise_error("divide by zero");
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000011950 if (errcode == -5)
Denis Vlasenkob012b102007-02-19 22:43:01 +000011951 ash_msg_and_raise_error("expression recursion loop detected");
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000011952 raise_error_syntax(s);
Eric Andersenc470f442003-07-28 09:56:35 +000011953 }
Denis Vlasenkob012b102007-02-19 22:43:01 +000011954 INT_ON;
Glenn L McGrath9fef17d2002-08-22 18:41:20 +000011955
Denis Vlasenkod9e15f22006-11-27 16:49:55 +000011956 return result;
Eric Andersen74bcd162001-07-30 21:41:37 +000011957}
Eric Andersenc470f442003-07-28 09:56:35 +000011958
Eric Andersenc470f442003-07-28 09:56:35 +000011959/*
Eric Andersen90898442003-08-06 11:20:52 +000011960 * The let builtin. partial stolen from GNU Bash, the Bourne Again SHell.
11961 * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
11962 *
11963 * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
Eric Andersenc470f442003-07-28 09:56:35 +000011964 */
11965static int
Denis Vlasenko68404f12008-03-17 09:00:54 +000011966letcmd(int argc ATTRIBUTE_UNUSED, char **argv)
Eric Andersenc470f442003-07-28 09:56:35 +000011967{
Denis Vlasenko68404f12008-03-17 09:00:54 +000011968 arith_t i;
Eric Andersenc470f442003-07-28 09:56:35 +000011969
Denis Vlasenko68404f12008-03-17 09:00:54 +000011970 argv++;
11971 if (!*argv)
Denis Vlasenkob012b102007-02-19 22:43:01 +000011972 ash_msg_and_raise_error("expression expected");
Denis Vlasenko68404f12008-03-17 09:00:54 +000011973 do {
11974 i = dash_arith(*argv);
11975 } while (*++argv);
Eric Andersenc470f442003-07-28 09:56:35 +000011976
Denis Vlasenkod9e15f22006-11-27 16:49:55 +000011977 return !i;
Eric Andersenc470f442003-07-28 09:56:35 +000011978}
Denis Vlasenko131ae172007-02-18 13:00:19 +000011979#endif /* ASH_MATH_SUPPORT */
Eric Andersenc470f442003-07-28 09:56:35 +000011980
Eric Andersenc470f442003-07-28 09:56:35 +000011981
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000011982/* ============ miscbltin.c
11983 *
Eric Andersenaff114c2004-04-14 17:51:38 +000011984 * Miscellaneous builtins.
Eric Andersenc470f442003-07-28 09:56:35 +000011985 */
11986
11987#undef rflag
11988
Denis Vlasenko83e5d6f2006-12-18 21:49:06 +000011989#if defined(__GLIBC__) && __GLIBC__ == 2 && __GLIBC_MINOR__ < 1
Eric Andersenc470f442003-07-28 09:56:35 +000011990typedef enum __rlimit_resource rlim_t;
11991#endif
Eric Andersen74bcd162001-07-30 21:41:37 +000011992
Eric Andersenc470f442003-07-28 09:56:35 +000011993/*
Denis Vlasenko59f351c2008-03-25 00:07:12 +000011994 * The read builtin. Options:
11995 * -r Do not interpret '\' specially
11996 * -s Turn off echo (tty only)
11997 * -n NCHARS Read NCHARS max
11998 * -p PROMPT Display PROMPT on stderr (if input is from tty)
11999 * -t SECONDS Timeout after SECONDS (tty or pipe only)
12000 * -u FD Read from given FD instead of fd 0
Eric Andersenc470f442003-07-28 09:56:35 +000012001 * This uses unbuffered input, which may be avoidable in some cases.
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012002 * TODO: bash also has:
12003 * -a ARRAY Read into array[0],[1],etc
12004 * -d DELIM End on DELIM char, not newline
12005 * -e Use line editing (tty only)
Eric Andersenc470f442003-07-28 09:56:35 +000012006 */
Eric Andersenc470f442003-07-28 09:56:35 +000012007static int
Denis Vlasenko68404f12008-03-17 09:00:54 +000012008readcmd(int argc ATTRIBUTE_UNUSED, char **argv ATTRIBUTE_UNUSED)
Eric Andersenc470f442003-07-28 09:56:35 +000012009{
12010 char **ap;
12011 int backslash;
12012 char c;
12013 int rflag;
12014 char *prompt;
12015 const char *ifs;
12016 char *p;
12017 int startword;
12018 int status;
12019 int i;
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012020 int fd = 0;
Denis Vlasenko131ae172007-02-18 13:00:19 +000012021#if ENABLE_ASH_READ_NCHARS
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012022 int nchars = 0; /* if != 0, -n is in effect */
Paul Fox02eb9342005-09-07 16:56:02 +000012023 int silent = 0;
12024 struct termios tty, old_tty;
12025#endif
Denis Vlasenko131ae172007-02-18 13:00:19 +000012026#if ENABLE_ASH_READ_TIMEOUT
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012027 unsigned end_ms = 0;
12028 unsigned timeout = 0;
Paul Fox02eb9342005-09-07 16:56:02 +000012029#endif
Eric Andersenc470f442003-07-28 09:56:35 +000012030
12031 rflag = 0;
12032 prompt = NULL;
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012033 while ((i = nextopt("p:u:r"
12034 USE_ASH_READ_TIMEOUT("t:")
12035 USE_ASH_READ_NCHARS("n:s")
12036 )) != '\0') {
Denis Vlasenkobf0a2012006-12-26 10:42:51 +000012037 switch (i) {
Paul Fox02eb9342005-09-07 16:56:02 +000012038 case 'p':
Eric Andersenc470f442003-07-28 09:56:35 +000012039 prompt = optionarg;
Paul Fox02eb9342005-09-07 16:56:02 +000012040 break;
Denis Vlasenko131ae172007-02-18 13:00:19 +000012041#if ENABLE_ASH_READ_NCHARS
Paul Fox02eb9342005-09-07 16:56:02 +000012042 case 'n':
Denis Vlasenko037576d2007-10-20 18:30:38 +000012043 nchars = bb_strtou(optionarg, NULL, 10);
12044 if (nchars < 0 || errno)
Denis Vlasenkob012b102007-02-19 22:43:01 +000012045 ash_msg_and_raise_error("invalid count");
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012046 /* nchars == 0: off (bash 3.2 does this too) */
Paul Fox02eb9342005-09-07 16:56:02 +000012047 break;
12048 case 's':
12049 silent = 1;
12050 break;
Ned Ludd2123b7c2005-02-09 21:07:23 +000012051#endif
Denis Vlasenko131ae172007-02-18 13:00:19 +000012052#if ENABLE_ASH_READ_TIMEOUT
Paul Fox02eb9342005-09-07 16:56:02 +000012053 case 't':
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012054 timeout = bb_strtou(optionarg, NULL, 10);
12055 if (errno || timeout > UINT_MAX / 2048)
12056 ash_msg_and_raise_error("invalid timeout");
12057 timeout *= 1000;
12058#if 0 /* even bash have no -t N.NNN support */
Denis Vlasenko037576d2007-10-20 18:30:38 +000012059 ts.tv_sec = bb_strtou(optionarg, &p, 10);
Paul Fox02eb9342005-09-07 16:56:02 +000012060 ts.tv_usec = 0;
Denis Vlasenko037576d2007-10-20 18:30:38 +000012061 /* EINVAL means number is ok, but not terminated by NUL */
12062 if (*p == '.' && errno == EINVAL) {
Paul Fox02eb9342005-09-07 16:56:02 +000012063 char *p2;
12064 if (*++p) {
12065 int scale;
Denis Vlasenko037576d2007-10-20 18:30:38 +000012066 ts.tv_usec = bb_strtou(p, &p2, 10);
12067 if (errno)
Denis Vlasenkob012b102007-02-19 22:43:01 +000012068 ash_msg_and_raise_error("invalid timeout");
Paul Fox02eb9342005-09-07 16:56:02 +000012069 scale = p2 - p;
12070 /* normalize to usec */
12071 if (scale > 6)
Denis Vlasenkob012b102007-02-19 22:43:01 +000012072 ash_msg_and_raise_error("invalid timeout");
Paul Fox02eb9342005-09-07 16:56:02 +000012073 while (scale++ < 6)
12074 ts.tv_usec *= 10;
12075 }
Denis Vlasenko037576d2007-10-20 18:30:38 +000012076 } else if (ts.tv_sec < 0 || errno) {
Denis Vlasenkob012b102007-02-19 22:43:01 +000012077 ash_msg_and_raise_error("invalid timeout");
Paul Fox02eb9342005-09-07 16:56:02 +000012078 }
Denis Vlasenko037576d2007-10-20 18:30:38 +000012079 if (!(ts.tv_sec | ts.tv_usec)) { /* both are 0? */
Denis Vlasenkob012b102007-02-19 22:43:01 +000012080 ash_msg_and_raise_error("invalid timeout");
Denis Vlasenko037576d2007-10-20 18:30:38 +000012081 }
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012082#endif /* if 0 */
Paul Fox02eb9342005-09-07 16:56:02 +000012083 break;
12084#endif
12085 case 'r':
12086 rflag = 1;
12087 break;
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012088 case 'u':
12089 fd = bb_strtou(optionarg, NULL, 10);
12090 if (fd < 0 || errno)
12091 ash_msg_and_raise_error("invalid file descriptor");
12092 break;
Paul Fox02eb9342005-09-07 16:56:02 +000012093 default:
12094 break;
12095 }
Eric Andersenc470f442003-07-28 09:56:35 +000012096 }
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012097 if (prompt && isatty(fd)) {
Eric Andersenc470f442003-07-28 09:56:35 +000012098 out2str(prompt);
Eric Andersenc470f442003-07-28 09:56:35 +000012099 }
Denis Vlasenko5cedb752007-02-18 19:56:41 +000012100 ap = argptr;
12101 if (*ap == NULL)
Denis Vlasenkob012b102007-02-19 22:43:01 +000012102 ash_msg_and_raise_error("arg count");
Denis Vlasenko5cedb752007-02-18 19:56:41 +000012103 ifs = bltinlookup("IFS");
12104 if (ifs == NULL)
Eric Andersenc470f442003-07-28 09:56:35 +000012105 ifs = defifs;
Denis Vlasenko131ae172007-02-18 13:00:19 +000012106#if ENABLE_ASH_READ_NCHARS
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012107 tcgetattr(fd, &tty);
12108 old_tty = tty;
12109 if (nchars || silent) {
12110 if (nchars) {
12111 tty.c_lflag &= ~ICANON;
12112 tty.c_cc[VMIN] = nchars < 256 ? nchars : 255;
Paul Fox02eb9342005-09-07 16:56:02 +000012113 }
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012114 if (silent) {
12115 tty.c_lflag &= ~(ECHO | ECHOK | ECHONL);
12116 }
12117 /* if tcgetattr failed, tcsetattr will fail too.
12118 * Ignoring, it's harmless. */
12119 tcsetattr(fd, TCSANOW, &tty);
Paul Fox02eb9342005-09-07 16:56:02 +000012120 }
12121#endif
Paul Fox02eb9342005-09-07 16:56:02 +000012122
Eric Andersenc470f442003-07-28 09:56:35 +000012123 status = 0;
12124 startword = 1;
12125 backslash = 0;
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012126#if ENABLE_ASH_READ_TIMEOUT
12127 if (timeout) /* NB: ensuring end_ms is nonzero */
12128 end_ms = ((unsigned)(monotonic_us() / 1000) + timeout) | 1;
12129#endif
Eric Andersenc470f442003-07-28 09:56:35 +000012130 STARTSTACKSTR(p);
Denis Vlasenko037576d2007-10-20 18:30:38 +000012131 do {
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012132#if ENABLE_ASH_READ_TIMEOUT
12133 if (end_ms) {
12134 struct pollfd pfd[1];
12135 pfd[0].fd = fd;
12136 pfd[0].events = POLLIN;
12137 timeout = end_ms - (unsigned)(monotonic_us() / 1000);
12138 if ((int)timeout <= 0 /* already late? */
12139 || safe_poll(pfd, 1, timeout) != 1 /* no? wait... */
12140 ) { /* timed out! */
12141#if ENABLE_ASH_READ_NCHARS
12142 tcsetattr(fd, TCSANOW, &old_tty);
12143#endif
12144 return 1;
12145 }
12146 }
12147#endif
12148 if (nonblock_safe_read(fd, &c, 1) != 1) {
Eric Andersenc470f442003-07-28 09:56:35 +000012149 status = 1;
12150 break;
12151 }
12152 if (c == '\0')
12153 continue;
12154 if (backslash) {
12155 backslash = 0;
12156 if (c != '\n')
12157 goto put;
12158 continue;
12159 }
12160 if (!rflag && c == '\\') {
12161 backslash++;
12162 continue;
12163 }
12164 if (c == '\n')
12165 break;
12166 if (startword && *ifs == ' ' && strchr(ifs, c)) {
12167 continue;
12168 }
12169 startword = 0;
12170 if (ap[1] != NULL && strchr(ifs, c) != NULL) {
12171 STACKSTRNUL(p);
12172 setvar(*ap, stackblock(), 0);
12173 ap++;
12174 startword = 1;
12175 STARTSTACKSTR(p);
12176 } else {
Denis Vlasenko5cedb752007-02-18 19:56:41 +000012177 put:
Eric Andersenc470f442003-07-28 09:56:35 +000012178 STPUTC(c, p);
12179 }
12180 }
Denis Vlasenko037576d2007-10-20 18:30:38 +000012181/* end of do {} while: */
Denis Vlasenko131ae172007-02-18 13:00:19 +000012182#if ENABLE_ASH_READ_NCHARS
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012183 while (--nchars);
Denis Vlasenko037576d2007-10-20 18:30:38 +000012184#else
12185 while (1);
12186#endif
12187
12188#if ENABLE_ASH_READ_NCHARS
Denis Vlasenko59f351c2008-03-25 00:07:12 +000012189 tcsetattr(fd, TCSANOW, &old_tty);
Paul Fox02eb9342005-09-07 16:56:02 +000012190#endif
12191
Eric Andersenc470f442003-07-28 09:56:35 +000012192 STACKSTRNUL(p);
12193 /* Remove trailing blanks */
12194 while ((char *)stackblock() <= --p && strchr(ifs, *p) != NULL)
12195 *p = '\0';
12196 setvar(*ap, stackblock(), 0);
12197 while (*++ap != NULL)
12198 setvar(*ap, nullstr, 0);
12199 return status;
12200}
12201
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012202static int
Denis Vlasenko68404f12008-03-17 09:00:54 +000012203umaskcmd(int argc ATTRIBUTE_UNUSED, char **argv)
Eric Andersenc470f442003-07-28 09:56:35 +000012204{
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000012205 static const char permuser[3] ALIGN1 = "ugo";
12206 static const char permmode[3] ALIGN1 = "rwx";
12207 static const short permmask[] ALIGN2 = {
Eric Andersenc470f442003-07-28 09:56:35 +000012208 S_IRUSR, S_IWUSR, S_IXUSR,
12209 S_IRGRP, S_IWGRP, S_IXGRP,
12210 S_IROTH, S_IWOTH, S_IXOTH
12211 };
12212
12213 char *ap;
12214 mode_t mask;
12215 int i;
12216 int symbolic_mode = 0;
12217
12218 while (nextopt("S") != '\0') {
12219 symbolic_mode = 1;
12220 }
12221
Denis Vlasenkob012b102007-02-19 22:43:01 +000012222 INT_OFF;
Eric Andersenc470f442003-07-28 09:56:35 +000012223 mask = umask(0);
12224 umask(mask);
Denis Vlasenkob012b102007-02-19 22:43:01 +000012225 INT_ON;
Eric Andersenc470f442003-07-28 09:56:35 +000012226
Denis Vlasenko5cedb752007-02-18 19:56:41 +000012227 ap = *argptr;
12228 if (ap == NULL) {
Eric Andersenc470f442003-07-28 09:56:35 +000012229 if (symbolic_mode) {
12230 char buf[18];
12231 char *p = buf;
12232
12233 for (i = 0; i < 3; i++) {
12234 int j;
12235
12236 *p++ = permuser[i];
12237 *p++ = '=';
12238 for (j = 0; j < 3; j++) {
12239 if ((mask & permmask[3 * i + j]) == 0) {
12240 *p++ = permmode[j];
12241 }
12242 }
12243 *p++ = ',';
12244 }
12245 *--p = 0;
12246 puts(buf);
12247 } else {
12248 out1fmt("%.4o\n", mask);
12249 }
12250 } else {
Denis Vlasenkoaa744452007-02-23 01:04:22 +000012251 if (isdigit((unsigned char) *ap)) {
Eric Andersenc470f442003-07-28 09:56:35 +000012252 mask = 0;
12253 do {
12254 if (*ap >= '8' || *ap < '0')
Denis Vlasenkob012b102007-02-19 22:43:01 +000012255 ash_msg_and_raise_error(illnum, argv[1]);
Eric Andersenc470f442003-07-28 09:56:35 +000012256 mask = (mask << 3) + (*ap - '0');
12257 } while (*++ap != '\0');
12258 umask(mask);
12259 } else {
12260 mask = ~mask & 0777;
12261 if (!bb_parse_mode(ap, &mask)) {
Denis Vlasenko3af3e5b2007-03-05 00:24:52 +000012262 ash_msg_and_raise_error("illegal mode: %s", ap);
Eric Andersenc470f442003-07-28 09:56:35 +000012263 }
12264 umask(~mask & 0777);
12265 }
12266 }
12267 return 0;
12268}
12269
12270/*
12271 * ulimit builtin
12272 *
12273 * This code, originally by Doug Gwyn, Doug Kingston, Eric Gisin, and
12274 * Michael Rendell was ripped from pdksh 5.0.8 and hacked for use with
12275 * ash by J.T. Conklin.
12276 *
12277 * Public domain.
12278 */
12279
12280struct limits {
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012281 uint8_t cmd; /* RLIMIT_xxx fit into it */
12282 uint8_t factor_shift; /* shift by to get rlim_{cur,max} values */
Eric Andersenc470f442003-07-28 09:56:35 +000012283 char option;
12284};
12285
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012286static const struct limits limits_tbl[] = {
Eric Andersenc470f442003-07-28 09:56:35 +000012287#ifdef RLIMIT_CPU
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012288 { RLIMIT_CPU, 0, 't' },
Eric Andersenc470f442003-07-28 09:56:35 +000012289#endif
12290#ifdef RLIMIT_FSIZE
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012291 { RLIMIT_FSIZE, 9, 'f' },
Eric Andersenc470f442003-07-28 09:56:35 +000012292#endif
12293#ifdef RLIMIT_DATA
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012294 { RLIMIT_DATA, 10, 'd' },
Eric Andersenc470f442003-07-28 09:56:35 +000012295#endif
12296#ifdef RLIMIT_STACK
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012297 { RLIMIT_STACK, 10, 's' },
Eric Andersenc470f442003-07-28 09:56:35 +000012298#endif
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012299#ifdef RLIMIT_CORE
12300 { RLIMIT_CORE, 9, 'c' },
Eric Andersenc470f442003-07-28 09:56:35 +000012301#endif
12302#ifdef RLIMIT_RSS
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012303 { RLIMIT_RSS, 10, 'm' },
Eric Andersenc470f442003-07-28 09:56:35 +000012304#endif
12305#ifdef RLIMIT_MEMLOCK
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012306 { RLIMIT_MEMLOCK, 10, 'l' },
Eric Andersenc470f442003-07-28 09:56:35 +000012307#endif
12308#ifdef RLIMIT_NPROC
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012309 { RLIMIT_NPROC, 0, 'p' },
Eric Andersenc470f442003-07-28 09:56:35 +000012310#endif
12311#ifdef RLIMIT_NOFILE
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012312 { RLIMIT_NOFILE, 0, 'n' },
Eric Andersenc470f442003-07-28 09:56:35 +000012313#endif
Glenn L McGrath76620622004-01-13 10:19:37 +000012314#ifdef RLIMIT_AS
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012315 { RLIMIT_AS, 10, 'v' },
Eric Andersenc470f442003-07-28 09:56:35 +000012316#endif
Glenn L McGrath76620622004-01-13 10:19:37 +000012317#ifdef RLIMIT_LOCKS
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012318 { RLIMIT_LOCKS, 0, 'w' },
Eric Andersenc470f442003-07-28 09:56:35 +000012319#endif
Eric Andersenc470f442003-07-28 09:56:35 +000012320};
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012321static const char limits_name[] =
12322#ifdef RLIMIT_CPU
12323 "time(seconds)" "\0"
12324#endif
12325#ifdef RLIMIT_FSIZE
12326 "file(blocks)" "\0"
12327#endif
12328#ifdef RLIMIT_DATA
12329 "data(kb)" "\0"
12330#endif
12331#ifdef RLIMIT_STACK
12332 "stack(kb)" "\0"
12333#endif
12334#ifdef RLIMIT_CORE
12335 "coredump(blocks)" "\0"
12336#endif
12337#ifdef RLIMIT_RSS
12338 "memory(kb)" "\0"
12339#endif
12340#ifdef RLIMIT_MEMLOCK
12341 "locked memory(kb)" "\0"
12342#endif
12343#ifdef RLIMIT_NPROC
12344 "process" "\0"
12345#endif
12346#ifdef RLIMIT_NOFILE
12347 "nofiles" "\0"
12348#endif
12349#ifdef RLIMIT_AS
12350 "vmemory(kb)" "\0"
12351#endif
12352#ifdef RLIMIT_LOCKS
12353 "locks" "\0"
12354#endif
12355;
Eric Andersenc470f442003-07-28 09:56:35 +000012356
Glenn L McGrath76620622004-01-13 10:19:37 +000012357enum limtype { SOFT = 0x1, HARD = 0x2 };
12358
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012359static void
12360printlim(enum limtype how, const struct rlimit *limit,
Glenn L McGrath76620622004-01-13 10:19:37 +000012361 const struct limits *l)
12362{
12363 rlim_t val;
12364
12365 val = limit->rlim_max;
12366 if (how & SOFT)
12367 val = limit->rlim_cur;
12368
12369 if (val == RLIM_INFINITY)
12370 out1fmt("unlimited\n");
12371 else {
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012372 val >>= l->factor_shift;
Glenn L McGrath76620622004-01-13 10:19:37 +000012373 out1fmt("%lld\n", (long long) val);
12374 }
12375}
12376
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012377static int
Denis Vlasenko68404f12008-03-17 09:00:54 +000012378ulimitcmd(int argc ATTRIBUTE_UNUSED, char **argv ATTRIBUTE_UNUSED)
Eric Andersenc470f442003-07-28 09:56:35 +000012379{
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012380 int c;
Eric Andersenc470f442003-07-28 09:56:35 +000012381 rlim_t val = 0;
Glenn L McGrath76620622004-01-13 10:19:37 +000012382 enum limtype how = SOFT | HARD;
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012383 const struct limits *l;
12384 int set, all = 0;
12385 int optc, what;
12386 struct rlimit limit;
Eric Andersenc470f442003-07-28 09:56:35 +000012387
12388 what = 'f';
Glenn L McGrath16e45d72004-02-04 08:24:39 +000012389 while ((optc = nextopt("HSa"
12390#ifdef RLIMIT_CPU
12391 "t"
12392#endif
12393#ifdef RLIMIT_FSIZE
12394 "f"
12395#endif
12396#ifdef RLIMIT_DATA
12397 "d"
12398#endif
12399#ifdef RLIMIT_STACK
12400 "s"
12401#endif
12402#ifdef RLIMIT_CORE
12403 "c"
12404#endif
12405#ifdef RLIMIT_RSS
12406 "m"
12407#endif
12408#ifdef RLIMIT_MEMLOCK
12409 "l"
12410#endif
12411#ifdef RLIMIT_NPROC
12412 "p"
12413#endif
12414#ifdef RLIMIT_NOFILE
12415 "n"
12416#endif
12417#ifdef RLIMIT_AS
12418 "v"
12419#endif
12420#ifdef RLIMIT_LOCKS
12421 "w"
12422#endif
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000012423 )) != '\0')
Eric Andersenc470f442003-07-28 09:56:35 +000012424 switch (optc) {
12425 case 'H':
12426 how = HARD;
12427 break;
12428 case 'S':
12429 how = SOFT;
12430 break;
12431 case 'a':
12432 all = 1;
12433 break;
12434 default:
12435 what = optc;
12436 }
12437
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012438 for (l = limits_tbl; l->option != what; l++)
12439 continue;
Eric Andersenc470f442003-07-28 09:56:35 +000012440
12441 set = *argptr ? 1 : 0;
12442 if (set) {
12443 char *p = *argptr;
12444
12445 if (all || argptr[1])
Denis Vlasenkob012b102007-02-19 22:43:01 +000012446 ash_msg_and_raise_error("too many arguments");
Eric Andersen81fe1232003-07-29 06:38:40 +000012447 if (strncmp(p, "unlimited\n", 9) == 0)
Eric Andersenc470f442003-07-28 09:56:35 +000012448 val = RLIM_INFINITY;
12449 else {
12450 val = (rlim_t) 0;
12451
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000012452 while ((c = *p++) >= '0' && c <= '9') {
Eric Andersenc470f442003-07-28 09:56:35 +000012453 val = (val * 10) + (long)(c - '0');
12454 if (val < (rlim_t) 0)
12455 break;
12456 }
12457 if (c)
Denis Vlasenkob012b102007-02-19 22:43:01 +000012458 ash_msg_and_raise_error("bad number");
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012459 val <<= l->factor_shift;
Eric Andersenc470f442003-07-28 09:56:35 +000012460 }
12461 }
12462 if (all) {
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012463 const char *lname = limits_name;
12464 for (l = limits_tbl; l != &limits_tbl[ARRAY_SIZE(limits_tbl)]; l++) {
Eric Andersenc470f442003-07-28 09:56:35 +000012465 getrlimit(l->cmd, &limit);
Denis Vlasenkoa59f4352007-10-29 19:17:29 +000012466 out1fmt("%-20s ", lname);
12467 lname += strlen(lname) + 1;
Glenn L McGrath76620622004-01-13 10:19:37 +000012468 printlim(how, &limit, l);
Eric Andersenc470f442003-07-28 09:56:35 +000012469 }
12470 return 0;
12471 }
12472
12473 getrlimit(l->cmd, &limit);
12474 if (set) {
12475 if (how & HARD)
12476 limit.rlim_max = val;
12477 if (how & SOFT)
12478 limit.rlim_cur = val;
12479 if (setrlimit(l->cmd, &limit) < 0)
Denis Vlasenkob012b102007-02-19 22:43:01 +000012480 ash_msg_and_raise_error("error setting limit (%m)");
Eric Andersenc470f442003-07-28 09:56:35 +000012481 } else {
Glenn L McGrath76620622004-01-13 10:19:37 +000012482 printlim(how, &limit, l);
Eric Andersenc470f442003-07-28 09:56:35 +000012483 }
12484 return 0;
12485}
12486
Eric Andersen90898442003-08-06 11:20:52 +000012487
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000012488/* ============ Math support */
12489
Denis Vlasenko131ae172007-02-18 13:00:19 +000012490#if ENABLE_ASH_MATH_SUPPORT
Eric Andersen90898442003-08-06 11:20:52 +000012491
12492/* Copyright (c) 2001 Aaron Lehmann <aaronl@vitelus.com>
12493
12494 Permission is hereby granted, free of charge, to any person obtaining
12495 a copy of this software and associated documentation files (the
12496 "Software"), to deal in the Software without restriction, including
12497 without limitation the rights to use, copy, modify, merge, publish,
12498 distribute, sublicense, and/or sell copies of the Software, and to
12499 permit persons to whom the Software is furnished to do so, subject to
12500 the following conditions:
12501
12502 The above copyright notice and this permission notice shall be
12503 included in all copies or substantial portions of the Software.
12504
12505 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
12506 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
12507 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
12508 IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
12509 CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
12510 TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
12511 SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
12512*/
12513
12514/* This is my infix parser/evaluator. It is optimized for size, intended
12515 * as a replacement for yacc-based parsers. However, it may well be faster
Eric Andersenaff114c2004-04-14 17:51:38 +000012516 * than a comparable parser written in yacc. The supported operators are
Eric Andersen90898442003-08-06 11:20:52 +000012517 * listed in #defines below. Parens, order of operations, and error handling
Eric Andersenaff114c2004-04-14 17:51:38 +000012518 * are supported. This code is thread safe. The exact expression format should
Eric Andersen90898442003-08-06 11:20:52 +000012519 * be that which POSIX specifies for shells. */
12520
12521/* The code uses a simple two-stack algorithm. See
12522 * http://www.onthenet.com.au/~grahamis/int2008/week02/lect02.html
Eric Andersenaff114c2004-04-14 17:51:38 +000012523 * for a detailed explanation of the infix-to-postfix algorithm on which
Eric Andersen90898442003-08-06 11:20:52 +000012524 * this is based (this code differs in that it applies operators immediately
12525 * to the stack instead of adding them to a queue to end up with an
12526 * expression). */
12527
12528/* To use the routine, call it with an expression string and error return
12529 * pointer */
12530
12531/*
12532 * Aug 24, 2001 Manuel Novoa III
12533 *
12534 * Reduced the generated code size by about 30% (i386) and fixed several bugs.
12535 *
12536 * 1) In arith_apply():
12537 * a) Cached values of *numptr and &(numptr[-1]).
12538 * b) Removed redundant test for zero denominator.
12539 *
12540 * 2) In arith():
12541 * a) Eliminated redundant code for processing operator tokens by moving
12542 * to a table-based implementation. Also folded handling of parens
12543 * into the table.
12544 * b) Combined all 3 loops which called arith_apply to reduce generated
12545 * code size at the cost of speed.
12546 *
12547 * 3) The following expressions were treated as valid by the original code:
12548 * 1() , 0! , 1 ( *3 ) .
12549 * These bugs have been fixed by internally enclosing the expression in
12550 * parens and then checking that all binary ops and right parens are
12551 * preceded by a valid expression (NUM_TOKEN).
12552 *
Eric Andersenaff114c2004-04-14 17:51:38 +000012553 * Note: It may be desirable to replace Aaron's test for whitespace with
Eric Andersen90898442003-08-06 11:20:52 +000012554 * ctype's isspace() if it is used by another busybox applet or if additional
12555 * whitespace chars should be considered. Look below the "#include"s for a
12556 * precompiler test.
12557 */
12558
12559/*
12560 * Aug 26, 2001 Manuel Novoa III
12561 *
12562 * Return 0 for null expressions. Pointed out by Vladimir Oleynik.
12563 *
12564 * Merge in Aaron's comments previously posted to the busybox list,
12565 * modified slightly to take account of my changes to the code.
12566 *
12567 */
12568
12569/*
12570 * (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
12571 *
12572 * - allow access to variable,
12573 * used recursive find value indirection (c=2*2; a="c"; $((a+=2)) produce 6)
12574 * - realize assign syntax (VAR=expr, +=, *= etc)
12575 * - realize exponentiation (** operator)
12576 * - realize comma separated - expr, expr
12577 * - realise ++expr --expr expr++ expr--
12578 * - realise expr ? expr : expr (but, second expr calculate always)
Eric Andersenaff114c2004-04-14 17:51:38 +000012579 * - allow hexadecimal and octal numbers
Eric Andersen90898442003-08-06 11:20:52 +000012580 * - was restored loses XOR operator
12581 * - remove one goto label, added three ;-)
12582 * - protect $((num num)) as true zero expr (Manuel`s error)
12583 * - always use special isspace(), see comment from bash ;-)
12584 */
12585
Eric Andersen90898442003-08-06 11:20:52 +000012586#define arith_isspace(arithval) \
12587 (arithval == ' ' || arithval == '\n' || arithval == '\t')
12588
Eric Andersen90898442003-08-06 11:20:52 +000012589typedef unsigned char operator;
12590
12591/* An operator's token id is a bit of a bitfield. The lower 5 bits are the
Eric Andersenaff114c2004-04-14 17:51:38 +000012592 * precedence, and 3 high bits are an ID unique across operators of that
Eric Andersen90898442003-08-06 11:20:52 +000012593 * precedence. The ID portion is so that multiple operators can have the
12594 * same precedence, ensuring that the leftmost one is evaluated first.
12595 * Consider * and /. */
12596
12597#define tok_decl(prec,id) (((id)<<5)|(prec))
12598#define PREC(op) ((op) & 0x1F)
12599
12600#define TOK_LPAREN tok_decl(0,0)
12601
12602#define TOK_COMMA tok_decl(1,0)
12603
12604#define TOK_ASSIGN tok_decl(2,0)
12605#define TOK_AND_ASSIGN tok_decl(2,1)
12606#define TOK_OR_ASSIGN tok_decl(2,2)
12607#define TOK_XOR_ASSIGN tok_decl(2,3)
12608#define TOK_PLUS_ASSIGN tok_decl(2,4)
12609#define TOK_MINUS_ASSIGN tok_decl(2,5)
12610#define TOK_LSHIFT_ASSIGN tok_decl(2,6)
12611#define TOK_RSHIFT_ASSIGN tok_decl(2,7)
12612
12613#define TOK_MUL_ASSIGN tok_decl(3,0)
12614#define TOK_DIV_ASSIGN tok_decl(3,1)
12615#define TOK_REM_ASSIGN tok_decl(3,2)
12616
12617/* all assign is right associativity and precedence eq, but (7+3)<<5 > 256 */
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000012618#define convert_prec_is_assing(prec) do { if (prec == 3) prec = 2; } while (0)
Eric Andersen90898442003-08-06 11:20:52 +000012619
12620/* conditional is right associativity too */
12621#define TOK_CONDITIONAL tok_decl(4,0)
12622#define TOK_CONDITIONAL_SEP tok_decl(4,1)
12623
12624#define TOK_OR tok_decl(5,0)
12625
12626#define TOK_AND tok_decl(6,0)
12627
12628#define TOK_BOR tok_decl(7,0)
12629
12630#define TOK_BXOR tok_decl(8,0)
12631
12632#define TOK_BAND tok_decl(9,0)
12633
12634#define TOK_EQ tok_decl(10,0)
12635#define TOK_NE tok_decl(10,1)
12636
12637#define TOK_LT tok_decl(11,0)
12638#define TOK_GT tok_decl(11,1)
12639#define TOK_GE tok_decl(11,2)
12640#define TOK_LE tok_decl(11,3)
12641
12642#define TOK_LSHIFT tok_decl(12,0)
12643#define TOK_RSHIFT tok_decl(12,1)
12644
12645#define TOK_ADD tok_decl(13,0)
12646#define TOK_SUB tok_decl(13,1)
12647
12648#define TOK_MUL tok_decl(14,0)
12649#define TOK_DIV tok_decl(14,1)
12650#define TOK_REM tok_decl(14,2)
12651
12652/* exponent is right associativity */
12653#define TOK_EXPONENT tok_decl(15,1)
12654
12655/* For now unary operators. */
12656#define UNARYPREC 16
12657#define TOK_BNOT tok_decl(UNARYPREC,0)
12658#define TOK_NOT tok_decl(UNARYPREC,1)
12659
12660#define TOK_UMINUS tok_decl(UNARYPREC+1,0)
12661#define TOK_UPLUS tok_decl(UNARYPREC+1,1)
12662
12663#define PREC_PRE (UNARYPREC+2)
12664
12665#define TOK_PRE_INC tok_decl(PREC_PRE, 0)
12666#define TOK_PRE_DEC tok_decl(PREC_PRE, 1)
12667
12668#define PREC_POST (UNARYPREC+3)
12669
12670#define TOK_POST_INC tok_decl(PREC_POST, 0)
12671#define TOK_POST_DEC tok_decl(PREC_POST, 1)
12672
12673#define SPEC_PREC (UNARYPREC+4)
12674
12675#define TOK_NUM tok_decl(SPEC_PREC, 0)
12676#define TOK_RPAREN tok_decl(SPEC_PREC, 1)
12677
12678#define NUMPTR (*numstackptr)
12679
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012680static int
12681tok_have_assign(operator op)
Eric Andersen90898442003-08-06 11:20:52 +000012682{
12683 operator prec = PREC(op);
12684
12685 convert_prec_is_assing(prec);
12686 return (prec == PREC(TOK_ASSIGN) ||
12687 prec == PREC_PRE || prec == PREC_POST);
12688}
12689
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012690static int
12691is_right_associativity(operator prec)
Eric Andersen90898442003-08-06 11:20:52 +000012692{
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000012693 return (prec == PREC(TOK_ASSIGN) || prec == PREC(TOK_EXPONENT)
12694 || prec == PREC(TOK_CONDITIONAL));
Eric Andersen90898442003-08-06 11:20:52 +000012695}
12696
Eric Andersen90898442003-08-06 11:20:52 +000012697typedef struct ARITCH_VAR_NUM {
Eric Andersened9ecf72004-06-22 08:29:45 +000012698 arith_t val;
12699 arith_t contidional_second_val;
Eric Andersen90898442003-08-06 11:20:52 +000012700 char contidional_second_val_initialized;
12701 char *var; /* if NULL then is regular number,
Eric Andersenaff114c2004-04-14 17:51:38 +000012702 else is variable name */
Eric Andersen90898442003-08-06 11:20:52 +000012703} v_n_t;
12704
Eric Andersen90898442003-08-06 11:20:52 +000012705typedef struct CHK_VAR_RECURSIVE_LOOPED {
12706 const char *var;
12707 struct CHK_VAR_RECURSIVE_LOOPED *next;
12708} chk_var_recursive_looped_t;
12709
12710static chk_var_recursive_looped_t *prev_chk_var_recursive;
12711
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012712static int
12713arith_lookup_val(v_n_t *t)
Eric Andersen90898442003-08-06 11:20:52 +000012714{
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000012715 if (t->var) {
12716 const char * p = lookupvar(t->var);
Eric Andersen90898442003-08-06 11:20:52 +000012717
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000012718 if (p) {
12719 int errcode;
Eric Andersen90898442003-08-06 11:20:52 +000012720
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000012721 /* recursive try as expression */
12722 chk_var_recursive_looped_t *cur;
12723 chk_var_recursive_looped_t cur_save;
Eric Andersen90898442003-08-06 11:20:52 +000012724
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000012725 for (cur = prev_chk_var_recursive; cur; cur = cur->next) {
12726 if (strcmp(cur->var, t->var) == 0) {
12727 /* expression recursion loop detected */
12728 return -5;
12729 }
12730 }
12731 /* save current lookuped var name */
12732 cur = prev_chk_var_recursive;
12733 cur_save.var = t->var;
12734 cur_save.next = cur;
12735 prev_chk_var_recursive = &cur_save;
12736
12737 t->val = arith (p, &errcode);
12738 /* restore previous ptr after recursiving */
12739 prev_chk_var_recursive = cur;
12740 return errcode;
Eric Andersen90898442003-08-06 11:20:52 +000012741 }
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000012742 /* allow undefined var as 0 */
12743 t->val = 0;
Eric Andersen90898442003-08-06 11:20:52 +000012744 }
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000012745 return 0;
Eric Andersen90898442003-08-06 11:20:52 +000012746}
12747
12748/* "applying" a token means performing it on the top elements on the integer
12749 * stack. For a unary operator it will only change the top element, but a
12750 * binary operator will pop two arguments and push a result */
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012751static int
12752arith_apply(operator op, v_n_t *numstack, v_n_t **numstackptr)
Eric Andersen90898442003-08-06 11:20:52 +000012753{
Eric Andersen90898442003-08-06 11:20:52 +000012754 v_n_t *numptr_m1;
Eric Andersenfac312d2004-06-22 20:09:40 +000012755 arith_t numptr_val, rez;
Eric Andersen90898442003-08-06 11:20:52 +000012756 int ret_arith_lookup_val;
12757
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000012758 /* There is no operator that can work without arguments */
12759 if (NUMPTR == numstack) goto err;
Eric Andersen90898442003-08-06 11:20:52 +000012760 numptr_m1 = NUMPTR - 1;
12761
12762 /* check operand is var with noninteger value */
12763 ret_arith_lookup_val = arith_lookup_val(numptr_m1);
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000012764 if (ret_arith_lookup_val)
Eric Andersen90898442003-08-06 11:20:52 +000012765 return ret_arith_lookup_val;
12766
12767 rez = numptr_m1->val;
12768 if (op == TOK_UMINUS)
12769 rez *= -1;
12770 else if (op == TOK_NOT)
12771 rez = !rez;
12772 else if (op == TOK_BNOT)
12773 rez = ~rez;
12774 else if (op == TOK_POST_INC || op == TOK_PRE_INC)
12775 rez++;
12776 else if (op == TOK_POST_DEC || op == TOK_PRE_DEC)
12777 rez--;
12778 else if (op != TOK_UPLUS) {
12779 /* Binary operators */
12780
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000012781 /* check and binary operators need two arguments */
12782 if (numptr_m1 == numstack) goto err;
Eric Andersen90898442003-08-06 11:20:52 +000012783
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000012784 /* ... and they pop one */
12785 --NUMPTR;
12786 numptr_val = rez;
12787 if (op == TOK_CONDITIONAL) {
12788 if (! numptr_m1->contidional_second_val_initialized) {
12789 /* protect $((expr1 ? expr2)) without ": expr" */
12790 goto err;
12791 }
12792 rez = numptr_m1->contidional_second_val;
12793 } else if (numptr_m1->contidional_second_val_initialized) {
12794 /* protect $((expr1 : expr2)) without "expr ? " */
12795 goto err;
Eric Andersen90898442003-08-06 11:20:52 +000012796 }
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000012797 numptr_m1 = NUMPTR - 1;
12798 if (op != TOK_ASSIGN) {
12799 /* check operand is var with noninteger value for not '=' */
12800 ret_arith_lookup_val = arith_lookup_val(numptr_m1);
12801 if (ret_arith_lookup_val)
12802 return ret_arith_lookup_val;
12803 }
12804 if (op == TOK_CONDITIONAL) {
12805 numptr_m1->contidional_second_val = rez;
12806 }
12807 rez = numptr_m1->val;
12808 if (op == TOK_BOR || op == TOK_OR_ASSIGN)
Eric Andersen90898442003-08-06 11:20:52 +000012809 rez |= numptr_val;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000012810 else if (op == TOK_OR)
Eric Andersen90898442003-08-06 11:20:52 +000012811 rez = numptr_val || rez;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000012812 else if (op == TOK_BAND || op == TOK_AND_ASSIGN)
Eric Andersen90898442003-08-06 11:20:52 +000012813 rez &= numptr_val;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000012814 else if (op == TOK_BXOR || op == TOK_XOR_ASSIGN)
Eric Andersen90898442003-08-06 11:20:52 +000012815 rez ^= numptr_val;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000012816 else if (op == TOK_AND)
Eric Andersen90898442003-08-06 11:20:52 +000012817 rez = rez && numptr_val;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000012818 else if (op == TOK_EQ)
Eric Andersen90898442003-08-06 11:20:52 +000012819 rez = (rez == numptr_val);
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000012820 else if (op == TOK_NE)
Eric Andersen90898442003-08-06 11:20:52 +000012821 rez = (rez != numptr_val);
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000012822 else if (op == TOK_GE)
Eric Andersen90898442003-08-06 11:20:52 +000012823 rez = (rez >= numptr_val);
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000012824 else if (op == TOK_RSHIFT || op == TOK_RSHIFT_ASSIGN)
Eric Andersen90898442003-08-06 11:20:52 +000012825 rez >>= numptr_val;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000012826 else if (op == TOK_LSHIFT || op == TOK_LSHIFT_ASSIGN)
Eric Andersen90898442003-08-06 11:20:52 +000012827 rez <<= numptr_val;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000012828 else if (op == TOK_GT)
Eric Andersen90898442003-08-06 11:20:52 +000012829 rez = (rez > numptr_val);
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000012830 else if (op == TOK_LT)
Eric Andersen90898442003-08-06 11:20:52 +000012831 rez = (rez < numptr_val);
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000012832 else if (op == TOK_LE)
Eric Andersen90898442003-08-06 11:20:52 +000012833 rez = (rez <= numptr_val);
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000012834 else if (op == TOK_MUL || op == TOK_MUL_ASSIGN)
Eric Andersen90898442003-08-06 11:20:52 +000012835 rez *= numptr_val;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000012836 else if (op == TOK_ADD || op == TOK_PLUS_ASSIGN)
Eric Andersen90898442003-08-06 11:20:52 +000012837 rez += numptr_val;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000012838 else if (op == TOK_SUB || op == TOK_MINUS_ASSIGN)
Eric Andersen90898442003-08-06 11:20:52 +000012839 rez -= numptr_val;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000012840 else if (op == TOK_ASSIGN || op == TOK_COMMA)
Eric Andersen90898442003-08-06 11:20:52 +000012841 rez = numptr_val;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000012842 else if (op == TOK_CONDITIONAL_SEP) {
Eric Andersen90898442003-08-06 11:20:52 +000012843 if (numptr_m1 == numstack) {
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000012844 /* protect $((expr : expr)) without "expr ? " */
12845 goto err;
Eric Andersen90898442003-08-06 11:20:52 +000012846 }
12847 numptr_m1->contidional_second_val_initialized = op;
12848 numptr_m1->contidional_second_val = numptr_val;
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012849 } else if (op == TOK_CONDITIONAL) {
Eric Andersen90898442003-08-06 11:20:52 +000012850 rez = rez ?
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000012851 numptr_val : numptr_m1->contidional_second_val;
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012852 } else if (op == TOK_EXPONENT) {
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000012853 if (numptr_val < 0)
Eric Andersen90898442003-08-06 11:20:52 +000012854 return -3; /* exponent less than 0 */
12855 else {
Eric Andersenad63cb22004-10-08 09:43:34 +000012856 arith_t c = 1;
Eric Andersen90898442003-08-06 11:20:52 +000012857
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000012858 if (numptr_val)
12859 while (numptr_val--)
Eric Andersen90898442003-08-06 11:20:52 +000012860 c *= rez;
12861 rez = c;
12862 }
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012863 } else if (numptr_val==0) /* zero divisor check */
Eric Andersen90898442003-08-06 11:20:52 +000012864 return -2;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000012865 else if (op == TOK_DIV || op == TOK_DIV_ASSIGN)
Eric Andersen90898442003-08-06 11:20:52 +000012866 rez /= numptr_val;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000012867 else if (op == TOK_REM || op == TOK_REM_ASSIGN)
Eric Andersen90898442003-08-06 11:20:52 +000012868 rez %= numptr_val;
12869 }
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000012870 if (tok_have_assign(op)) {
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012871 char buf[sizeof(arith_t_type)*3 + 2];
Eric Andersen90898442003-08-06 11:20:52 +000012872
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000012873 if (numptr_m1->var == NULL) {
Eric Andersen90898442003-08-06 11:20:52 +000012874 /* Hmm, 1=2 ? */
12875 goto err;
12876 }
12877 /* save to shell variable */
Denis Vlasenko131ae172007-02-18 13:00:19 +000012878#if ENABLE_ASH_MATH_SUPPORT_64
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012879 snprintf(buf, sizeof(buf), "%lld", (arith_t_type) rez);
"Vladimir N. Oleynik"bef14d72005-09-05 13:25:11 +000012880#else
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012881 snprintf(buf, sizeof(buf), "%ld", (arith_t_type) rez);
"Vladimir N. Oleynik"bef14d72005-09-05 13:25:11 +000012882#endif
Eric Andersen90898442003-08-06 11:20:52 +000012883 setvar(numptr_m1->var, buf, 0);
12884 /* after saving, make previous value for v++ or v-- */
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000012885 if (op == TOK_POST_INC)
Eric Andersen90898442003-08-06 11:20:52 +000012886 rez--;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000012887 else if (op == TOK_POST_DEC)
Eric Andersen90898442003-08-06 11:20:52 +000012888 rez++;
12889 }
12890 numptr_m1->val = rez;
12891 /* protect geting var value, is number now */
12892 numptr_m1->var = NULL;
12893 return 0;
Denis Vlasenko079f8af2006-11-27 16:49:31 +000012894 err:
12895 return -1;
Eric Andersen90898442003-08-06 11:20:52 +000012896}
12897
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012898/* longest must be first */
Denis Vlasenko6ca409e2007-08-12 20:58:27 +000012899static const char op_tokens[] ALIGN1 = {
Eric Andersen90898442003-08-06 11:20:52 +000012900 '<','<','=',0, TOK_LSHIFT_ASSIGN,
12901 '>','>','=',0, TOK_RSHIFT_ASSIGN,
12902 '<','<', 0, TOK_LSHIFT,
12903 '>','>', 0, TOK_RSHIFT,
12904 '|','|', 0, TOK_OR,
12905 '&','&', 0, TOK_AND,
12906 '!','=', 0, TOK_NE,
12907 '<','=', 0, TOK_LE,
12908 '>','=', 0, TOK_GE,
12909 '=','=', 0, TOK_EQ,
12910 '|','=', 0, TOK_OR_ASSIGN,
12911 '&','=', 0, TOK_AND_ASSIGN,
12912 '*','=', 0, TOK_MUL_ASSIGN,
12913 '/','=', 0, TOK_DIV_ASSIGN,
12914 '%','=', 0, TOK_REM_ASSIGN,
12915 '+','=', 0, TOK_PLUS_ASSIGN,
12916 '-','=', 0, TOK_MINUS_ASSIGN,
12917 '-','-', 0, TOK_POST_DEC,
12918 '^','=', 0, TOK_XOR_ASSIGN,
12919 '+','+', 0, TOK_POST_INC,
12920 '*','*', 0, TOK_EXPONENT,
12921 '!', 0, TOK_NOT,
12922 '<', 0, TOK_LT,
12923 '>', 0, TOK_GT,
12924 '=', 0, TOK_ASSIGN,
12925 '|', 0, TOK_BOR,
12926 '&', 0, TOK_BAND,
12927 '*', 0, TOK_MUL,
12928 '/', 0, TOK_DIV,
12929 '%', 0, TOK_REM,
12930 '+', 0, TOK_ADD,
12931 '-', 0, TOK_SUB,
12932 '^', 0, TOK_BXOR,
12933 /* uniq */
12934 '~', 0, TOK_BNOT,
12935 ',', 0, TOK_COMMA,
12936 '?', 0, TOK_CONDITIONAL,
12937 ':', 0, TOK_CONDITIONAL_SEP,
12938 ')', 0, TOK_RPAREN,
12939 '(', 0, TOK_LPAREN,
12940 0
12941};
12942/* ptr to ")" */
Denis Vlasenko92e13c22008-03-25 01:17:40 +000012943#define endexpression (&op_tokens[sizeof(op_tokens)-7])
Eric Andersen90898442003-08-06 11:20:52 +000012944
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000012945static arith_t
12946arith(const char *expr, int *perrcode)
Eric Andersen90898442003-08-06 11:20:52 +000012947{
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000012948 char arithval; /* Current character under analysis */
12949 operator lasttok, op;
12950 operator prec;
Eric Andersen90898442003-08-06 11:20:52 +000012951
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000012952 const char *p = endexpression;
12953 int errcode;
Eric Andersen90898442003-08-06 11:20:52 +000012954
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000012955 size_t datasizes = strlen(expr) + 2;
Eric Andersen90898442003-08-06 11:20:52 +000012956
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000012957 /* Stack of integers */
12958 /* The proof that there can be no more than strlen(startbuf)/2+1 integers
12959 * in any given correct or incorrect expression is left as an exercise to
12960 * the reader. */
12961 v_n_t *numstack = alloca(((datasizes)/2)*sizeof(v_n_t)),
12962 *numstackptr = numstack;
12963 /* Stack of operator tokens */
12964 operator *stack = alloca((datasizes) * sizeof(operator)),
12965 *stackptr = stack;
Eric Andersen90898442003-08-06 11:20:52 +000012966
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000012967 *stackptr++ = lasttok = TOK_LPAREN; /* start off with a left paren */
12968 *perrcode = errcode = 0;
Eric Andersen90898442003-08-06 11:20:52 +000012969
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000012970 while (1) {
Denis Vlasenko5cedb752007-02-18 19:56:41 +000012971 arithval = *expr;
12972 if (arithval == 0) {
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000012973 if (p == endexpression) {
12974 /* Null expression. */
12975 return 0;
12976 }
12977
12978 /* This is only reached after all tokens have been extracted from the
12979 * input stream. If there are still tokens on the operator stack, they
12980 * are to be applied in order. At the end, there should be a final
12981 * result on the integer stack */
12982
12983 if (expr != endexpression + 1) {
12984 /* If we haven't done so already, */
12985 /* append a closing right paren */
12986 expr = endexpression;
12987 /* and let the loop process it. */
12988 continue;
12989 }
12990 /* At this point, we're done with the expression. */
12991 if (numstackptr != numstack+1) {
12992 /* ... but if there isn't, it's bad */
12993 err:
12994 return (*perrcode = -1);
12995 }
12996 if (numstack->var) {
12997 /* expression is $((var)) only, lookup now */
12998 errcode = arith_lookup_val(numstack);
12999 }
13000 ret:
13001 *perrcode = errcode;
13002 return numstack->val;
Eric Andersen90898442003-08-06 11:20:52 +000013003 }
13004
Eric Andersen90898442003-08-06 11:20:52 +000013005 /* Continue processing the expression. */
13006 if (arith_isspace(arithval)) {
13007 /* Skip whitespace */
13008 goto prologue;
13009 }
Denis Vlasenko5cedb752007-02-18 19:56:41 +000013010 p = endofname(expr);
13011 if (p != expr) {
Eric Andersenad63cb22004-10-08 09:43:34 +000013012 size_t var_name_size = (p-expr) + 1; /* trailing zero */
Eric Andersen90898442003-08-06 11:20:52 +000013013
13014 numstackptr->var = alloca(var_name_size);
13015 safe_strncpy(numstackptr->var, expr, var_name_size);
13016 expr = p;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000013017 num:
Eric Andersen90898442003-08-06 11:20:52 +000013018 numstackptr->contidional_second_val_initialized = 0;
13019 numstackptr++;
13020 lasttok = TOK_NUM;
13021 continue;
Denis Vlasenko2da584f2007-02-19 22:44:05 +000013022 }
Denis Vlasenkoaa744452007-02-23 01:04:22 +000013023 if (isdigit(arithval)) {
Eric Andersen90898442003-08-06 11:20:52 +000013024 numstackptr->var = NULL;
Denis Vlasenko131ae172007-02-18 13:00:19 +000013025#if ENABLE_ASH_MATH_SUPPORT_64
Eric Andersenad63cb22004-10-08 09:43:34 +000013026 numstackptr->val = strtoll(expr, (char **) &expr, 0);
"Vladimir N. Oleynik"bef14d72005-09-05 13:25:11 +000013027#else
13028 numstackptr->val = strtol(expr, (char **) &expr, 0);
13029#endif
Eric Andersen90898442003-08-06 11:20:52 +000013030 goto num;
13031 }
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000013032 for (p = op_tokens; ; p++) {
Eric Andersen90898442003-08-06 11:20:52 +000013033 const char *o;
13034
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000013035 if (*p == 0) {
Eric Andersen90898442003-08-06 11:20:52 +000013036 /* strange operator not found */
13037 goto err;
13038 }
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000013039 for (o = expr; *p && *o == *p; p++)
Eric Andersen90898442003-08-06 11:20:52 +000013040 o++;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000013041 if (! *p) {
Eric Andersen90898442003-08-06 11:20:52 +000013042 /* found */
13043 expr = o - 1;
13044 break;
13045 }
13046 /* skip tail uncompared token */
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000013047 while (*p)
Eric Andersen90898442003-08-06 11:20:52 +000013048 p++;
13049 /* skip zero delim */
13050 p++;
13051 }
13052 op = p[1];
13053
13054 /* post grammar: a++ reduce to num */
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000013055 if (lasttok == TOK_POST_INC || lasttok == TOK_POST_DEC)
13056 lasttok = TOK_NUM;
Eric Andersen90898442003-08-06 11:20:52 +000013057
13058 /* Plus and minus are binary (not unary) _only_ if the last
13059 * token was as number, or a right paren (which pretends to be
13060 * a number, since it evaluates to one). Think about it.
13061 * It makes sense. */
13062 if (lasttok != TOK_NUM) {
Denis Vlasenkobf0a2012006-12-26 10:42:51 +000013063 switch (op) {
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000013064 case TOK_ADD:
13065 op = TOK_UPLUS;
13066 break;
13067 case TOK_SUB:
13068 op = TOK_UMINUS;
13069 break;
13070 case TOK_POST_INC:
13071 op = TOK_PRE_INC;
13072 break;
13073 case TOK_POST_DEC:
13074 op = TOK_PRE_DEC;
13075 break;
Eric Andersen90898442003-08-06 11:20:52 +000013076 }
13077 }
13078 /* We don't want a unary operator to cause recursive descent on the
13079 * stack, because there can be many in a row and it could cause an
13080 * operator to be evaluated before its argument is pushed onto the
13081 * integer stack. */
13082 /* But for binary operators, "apply" everything on the operator
13083 * stack until we find an operator with a lesser priority than the
13084 * one we have just extracted. */
13085 /* Left paren is given the lowest priority so it will never be
13086 * "applied" in this way.
13087 * if associativity is right and priority eq, applied also skip
13088 */
13089 prec = PREC(op);
13090 if ((prec > 0 && prec < UNARYPREC) || prec == SPEC_PREC) {
13091 /* not left paren or unary */
13092 if (lasttok != TOK_NUM) {
13093 /* binary op must be preceded by a num */
13094 goto err;
13095 }
13096 while (stackptr != stack) {
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000013097 if (op == TOK_RPAREN) {
13098 /* The algorithm employed here is simple: while we don't
13099 * hit an open paren nor the bottom of the stack, pop
13100 * tokens and apply them */
13101 if (stackptr[-1] == TOK_LPAREN) {
13102 --stackptr;
13103 /* Any operator directly after a */
13104 lasttok = TOK_NUM;
13105 /* close paren should consider itself binary */
13106 goto prologue;
13107 }
13108 } else {
13109 operator prev_prec = PREC(stackptr[-1]);
Eric Andersen90898442003-08-06 11:20:52 +000013110
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000013111 convert_prec_is_assing(prec);
13112 convert_prec_is_assing(prev_prec);
13113 if (prev_prec < prec)
13114 break;
13115 /* check right assoc */
13116 if (prev_prec == prec && is_right_associativity(prec))
13117 break;
13118 }
13119 errcode = arith_apply(*--stackptr, numstack, &numstackptr);
13120 if (errcode) goto ret;
Eric Andersen90898442003-08-06 11:20:52 +000013121 }
13122 if (op == TOK_RPAREN) {
13123 goto err;
13124 }
13125 }
13126
13127 /* Push this operator to the stack and remember it. */
13128 *stackptr++ = lasttok = op;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000013129 prologue:
Eric Andersen90898442003-08-06 11:20:52 +000013130 ++expr;
Denis Vlasenkoa0f82e92007-02-18 12:35:30 +000013131 } /* while */
Eric Andersen90898442003-08-06 11:20:52 +000013132}
Denis Vlasenko131ae172007-02-18 13:00:19 +000013133#endif /* ASH_MATH_SUPPORT */
Eric Andersen90898442003-08-06 11:20:52 +000013134
13135
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000013136/* ============ main() and helpers */
13137
13138/*
13139 * Called to exit the shell.
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013140 */
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000013141static void exitshell(void) ATTRIBUTE_NORETURN;
13142static void
13143exitshell(void)
13144{
13145 struct jmploc loc;
13146 char *p;
13147 int status;
13148
13149 status = exitstatus;
13150 TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
13151 if (setjmp(loc.loc)) {
13152 if (exception == EXEXIT)
13153/* dash bug: it just does _exit(exitstatus) here
13154 * but we have to do setjobctl(0) first!
13155 * (bug is still not fixed in dash-0.5.3 - if you run dash
13156 * under Midnight Commander, on exit from dash MC is backgrounded) */
13157 status = exitstatus;
13158 goto out;
13159 }
13160 exception_handler = &loc;
13161 p = trap[0];
13162 if (p) {
13163 trap[0] = NULL;
13164 evalstring(p, 0);
13165 }
13166 flush_stdout_stderr();
13167 out:
13168 setjobctl(0);
13169 _exit(status);
13170 /* NOTREACHED */
13171}
13172
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000013173static void
13174init(void)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013175{
13176 /* from input.c: */
13177 basepf.nextc = basepf.buf = basebuf;
13178
13179 /* from trap.c: */
13180 signal(SIGCHLD, SIG_DFL);
13181
13182 /* from var.c: */
13183 {
13184 char **envp;
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000013185 char ppid[sizeof(int)*3 + 1];
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013186 const char *p;
13187 struct stat st1, st2;
13188
13189 initvar();
13190 for (envp = environ; envp && *envp; envp++) {
13191 if (strchr(*envp, '=')) {
13192 setvareq(*envp, VEXPORT|VTEXTFIXED);
13193 }
13194 }
13195
Denis Vlasenko5c67e3e2007-02-23 01:05:03 +000013196 snprintf(ppid, sizeof(ppid), "%u", (unsigned) getppid());
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013197 setvar("PPID", ppid, 0);
13198
13199 p = lookupvar("PWD");
13200 if (p)
13201 if (*p != '/' || stat(p, &st1) || stat(".", &st2)
13202 || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino)
13203 p = '\0';
13204 setpwd(p, 0);
13205 }
13206}
13207
13208/*
13209 * Process the shell command line arguments.
13210 */
13211static void
Denis Vlasenko68404f12008-03-17 09:00:54 +000013212procargs(char **argv)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013213{
13214 int i;
13215 const char *xminusc;
13216 char **xargv;
13217
13218 xargv = argv;
13219 arg0 = xargv[0];
Denis Vlasenko68404f12008-03-17 09:00:54 +000013220 /* if (xargv[0]) - mmm, this is always true! */
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013221 xargv++;
13222 for (i = 0; i < NOPTS; i++)
13223 optlist[i] = 2;
13224 argptr = xargv;
Denis Vlasenko28bf6712008-02-14 15:01:47 +000013225 if (options(1)) {
13226 /* it already printed err message */
13227 raise_exception(EXERROR);
13228 }
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013229 xargv = argptr;
13230 xminusc = minusc;
13231 if (*xargv == NULL) {
13232 if (xminusc)
13233 ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
13234 sflag = 1;
13235 }
13236 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
13237 iflag = 1;
13238 if (mflag == 2)
13239 mflag = iflag;
13240 for (i = 0; i < NOPTS; i++)
13241 if (optlist[i] == 2)
13242 optlist[i] = 0;
13243#if DEBUG == 2
13244 debug = 1;
13245#endif
13246 /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
13247 if (xminusc) {
13248 minusc = *xargv++;
13249 if (*xargv)
13250 goto setarg0;
13251 } else if (!sflag) {
13252 setinputfile(*xargv, 0);
13253 setarg0:
13254 arg0 = *xargv++;
13255 commandname = arg0;
13256 }
13257
13258 shellparam.p = xargv;
13259#if ENABLE_ASH_GETOPTS
13260 shellparam.optind = 1;
13261 shellparam.optoff = -1;
13262#endif
Denis Vlasenko01631112007-12-16 17:20:38 +000013263 /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013264 while (*xargv) {
13265 shellparam.nparam++;
13266 xargv++;
13267 }
13268 optschanged();
13269}
13270
13271/*
13272 * Read /etc/profile or .profile.
13273 */
13274static void
13275read_profile(const char *name)
13276{
13277 int skip;
13278
13279 if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
13280 return;
13281 skip = cmdloop(0);
13282 popfile();
13283 if (skip)
13284 exitshell();
13285}
13286
Denis Vlasenko0c032a42007-02-23 01:03:40 +000013287/*
13288 * This routine is called when an error or an interrupt occurs in an
13289 * interactive shell and control is returned to the main command loop.
13290 */
13291static void
13292reset(void)
13293{
13294 /* from eval.c: */
13295 evalskip = 0;
13296 loopnest = 0;
13297 /* from input.c: */
13298 parselleft = parsenleft = 0; /* clear input buffer */
13299 popallfiles();
13300 /* from parser.c: */
13301 tokpushback = 0;
13302 checkkwd = 0;
13303 /* from redir.c: */
13304 clearredir(0);
13305}
13306
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013307#if PROFILE
13308static short profile_buf[16384];
13309extern int etext();
13310#endif
13311
Denis Vlasenkobc54cff2007-02-23 01:05:52 +000013312/*
13313 * Main routine. We initialize things, parse the arguments, execute
13314 * profiles if we're a login shell, and then call cmdloop to execute
13315 * commands. The setjmp call sets up the location to jump to when an
13316 * exception occurs. When an exception occurs the variable "state"
13317 * is used to figure out how far we had gotten.
13318 */
Denis Vlasenko9b49a5e2007-10-11 10:05:36 +000013319int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Denis Vlasenko68404f12008-03-17 09:00:54 +000013320int ash_main(int argc ATTRIBUTE_UNUSED, char **argv)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013321{
13322 char *shinit;
13323 volatile int state;
13324 struct jmploc jmploc;
13325 struct stackmark smark;
13326
Denis Vlasenko01631112007-12-16 17:20:38 +000013327 /* Initialize global data */
13328 INIT_G_misc();
13329 INIT_G_memstack();
13330 INIT_G_var();
Denis Vlasenkoee87ebf2007-12-21 22:18:16 +000013331#if ENABLE_ASH_ALIAS
Denis Vlasenko01631112007-12-16 17:20:38 +000013332 INIT_G_alias();
Denis Vlasenkoee87ebf2007-12-21 22:18:16 +000013333#endif
Denis Vlasenko01631112007-12-16 17:20:38 +000013334 INIT_G_cmdtable();
13335
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013336#if PROFILE
13337 monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
13338#endif
13339
13340#if ENABLE_FEATURE_EDITING
13341 line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
13342#endif
13343 state = 0;
13344 if (setjmp(jmploc.loc)) {
13345 int e;
13346 int s;
13347
13348 reset();
13349
13350 e = exception;
13351 if (e == EXERROR)
13352 exitstatus = 2;
13353 s = state;
13354 if (e == EXEXIT || s == 0 || iflag == 0 || shlvl)
13355 exitshell();
13356
13357 if (e == EXINT) {
13358 outcslow('\n', stderr);
13359 }
13360 popstackmark(&smark);
13361 FORCE_INT_ON; /* enable interrupts */
13362 if (s == 1)
13363 goto state1;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000013364 if (s == 2)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013365 goto state2;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000013366 if (s == 3)
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013367 goto state3;
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000013368 goto state4;
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013369 }
13370 exception_handler = &jmploc;
13371#if DEBUG
13372 opentrace();
Denis Vlasenkofe1f00a2007-02-23 01:04:50 +000013373 trace_puts("Shell args: ");
13374 trace_puts_args(argv);
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013375#endif
13376 rootpid = getpid();
13377
13378#if ENABLE_ASH_RANDOM_SUPPORT
13379 rseed = rootpid + time(NULL);
13380#endif
13381 init();
13382 setstackmark(&smark);
Denis Vlasenko68404f12008-03-17 09:00:54 +000013383 procargs(argv);
13384
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013385#if ENABLE_FEATURE_EDITING_SAVEHISTORY
13386 if (iflag) {
13387 const char *hp = lookupvar("HISTFILE");
13388
13389 if (hp == NULL) {
13390 hp = lookupvar("HOME");
13391 if (hp != NULL) {
13392 char *defhp = concat_path_file(hp, ".ash_history");
13393 setvar("HISTFILE", defhp, 0);
13394 free(defhp);
13395 }
13396 }
13397 }
13398#endif
13399 if (argv[0] && argv[0][0] == '-')
13400 isloginsh = 1;
13401 if (isloginsh) {
13402 state = 1;
13403 read_profile("/etc/profile");
13404 state1:
13405 state = 2;
13406 read_profile(".profile");
13407 }
13408 state2:
13409 state = 3;
13410 if (
13411#ifndef linux
Denis Vlasenko0c032a42007-02-23 01:03:40 +000013412 getuid() == geteuid() && getgid() == getegid() &&
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013413#endif
Denis Vlasenko0c032a42007-02-23 01:03:40 +000013414 iflag
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013415 ) {
13416 shinit = lookupvar("ENV");
13417 if (shinit != NULL && *shinit != '\0') {
13418 read_profile(shinit);
13419 }
13420 }
13421 state3:
13422 state = 4;
13423 if (minusc)
13424 evalstring(minusc, 0);
13425
13426 if (sflag || minusc == NULL) {
13427#if ENABLE_FEATURE_EDITING_SAVEHISTORY
13428 if ( iflag ) {
13429 const char *hp = lookupvar("HISTFILE");
13430
13431 if (hp != NULL)
13432 line_input_state->hist_file = hp;
13433 }
13434#endif
13435 state4: /* XXX ??? - why isn't this before the "if" statement */
13436 cmdloop(1);
13437 }
13438#if PROFILE
13439 monitor(0);
13440#endif
13441#ifdef GPROF
13442 {
13443 extern void _mcleanup(void);
13444 _mcleanup();
13445 }
13446#endif
13447 exitshell();
13448 /* NOTREACHED */
13449}
13450
Denis Vlasenkoa7189f02006-11-17 20:29:00 +000013451#if DEBUG
Denis Vlasenko8f8f2682006-10-03 21:00:43 +000013452const char *applet_name = "debug stuff usage";
Eric Andersenc470f442003-07-28 09:56:35 +000013453int main(int argc, char **argv)
13454{
13455 return ash_main(argc, argv);
13456}
13457#endif
Eric Andersen74bcd162001-07-30 21:41:37 +000013458
Denis Vlasenkoa624c112007-02-19 22:45:43 +000013459
Eric Andersendf82f612001-06-28 07:46:40 +000013460/*-
13461 * Copyright (c) 1989, 1991, 1993, 1994
Eric Andersen2870d962001-07-02 17:27:21 +000013462 * The Regents of the University of California. All rights reserved.
Eric Andersendf82f612001-06-28 07:46:40 +000013463 *
13464 * This code is derived from software contributed to Berkeley by
13465 * Kenneth Almquist.
13466 *
13467 * Redistribution and use in source and binary forms, with or without
13468 * modification, are permitted provided that the following conditions
13469 * are met:
13470 * 1. Redistributions of source code must retain the above copyright
13471 * notice, this list of conditions and the following disclaimer.
13472 * 2. Redistributions in binary form must reproduce the above copyright
13473 * notice, this list of conditions and the following disclaimer in the
13474 * documentation and/or other materials provided with the distribution.
"Vladimir N. Oleynik"ddc280e2005-12-15 12:01:49 +000013475 * 3. Neither the name of the University nor the names of its contributors
Eric Andersendf82f612001-06-28 07:46:40 +000013476 * may be used to endorse or promote products derived from this software
13477 * without specific prior written permission.
13478 *
13479 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
13480 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
13481 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
13482 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
13483 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
13484 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
13485 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
13486 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
13487 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
13488 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
13489 * SUCH DAMAGE.
13490 */